diff --git a/cloud/apps/billing/src/plans.ts b/cloud/apps/billing/src/plans.ts index 969e14cb847..75507f01f65 100644 --- a/cloud/apps/billing/src/plans.ts +++ b/cloud/apps/billing/src/plans.ts @@ -64,8 +64,8 @@ export type PlanCatalog = { team: TeamPlan; enterprise: EnterpriseOffer } export const DEFAULT_PLANS: PlanCatalog = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, includedHoursPerSeat: 60, @@ -138,7 +138,8 @@ export function publicOffers(catalog: PlanCatalog) { concurrentSandboxesPerSeat: team.concurrentSandboxesPerSeat, idleSleepMinutes: team.idleSleepMinutes, overageCentsPerHour: team.overageCentsPerHour, - defaultSpendCapCents: team.defaultSpendCapCents + defaultSpendCapCents: team.defaultSpendCapCents, + maxSpendCapCents: team.maxSpendCapCents }, enterprise: catalog.enterprise } diff --git a/cloud/apps/billing/test/billing-config.test.ts b/cloud/apps/billing/test/billing-config.test.ts index 762173fb759..7fffd02109d 100644 --- a/cloud/apps/billing/test/billing-config.test.ts +++ b/cloud/apps/billing/test/billing-config.test.ts @@ -24,7 +24,7 @@ describe('config: tax and plan catalog', () => { it('takes Team numbers and labels and the Enterprise contact from BILLING_PLANS', async () => { const h = await createHarness({ BILLING_PLANS: JSON.stringify({ - team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45/seat/mo', defaultSpendCapCents: 5000 }, + team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45 per seat per month', defaultSpendCapCents: 5000 }, enterprise: { contactUrl: 'https://example.test/sales' } }) }) @@ -33,8 +33,8 @@ describe('config: tax and plan catalog', () => { expect(entitlement.body.offers).toEqual({ team: { label: 'Team', - monthlyPriceLabel: '$45/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$45 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, largeMachineWeight: 1, @@ -42,7 +42,8 @@ describe('config: tax and plan catalog', () => { concurrentSandboxesPerSeat: 3, idleSleepMinutes: 15, overageCentsPerHour: 100, - defaultSpendCapCents: 5000 + defaultSpendCapCents: 5000, + maxSpendCapCents: 500_000 }, enterprise: { label: 'Enterprise', priceLabel: 'Custom', contactUrl: 'https://example.test/sales' } }) diff --git a/cloud/apps/billing/test/billing-flow.test.ts b/cloud/apps/billing/test/billing-flow.test.ts index 61605eb041e..baeb58d52bb 100644 --- a/cloud/apps/billing/test/billing-flow.test.ts +++ b/cloud/apps/billing/test/billing-flow.test.ts @@ -221,7 +221,7 @@ describe('entitlements, overage and usage', () => { canManageBilling: true, period: { start: PERIOD_START * 1000, end: PERIOD_END * 1000 } }) - expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50/seat/mo', annualPriceLabel: '$480/seat/yr' }) + expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50 per seat per month', annualPriceLabel: '$480 per seat, billed yearly' }) expect(entitlement.body.offers.enterprise).toMatchObject({ label: 'Enterprise', priceLabel: 'Custom' }) for (let i = 0; i < 4; i++) { diff --git a/cloud/apps/sandbox-control/image/golden-image.test.ts b/cloud/apps/sandbox-control/image/golden-image.test.ts index 8c251997304..f0eefb452e5 100644 --- a/cloud/apps/sandbox-control/image/golden-image.test.ts +++ b/cloud/apps/sandbox-control/image/golden-image.test.ts @@ -160,6 +160,15 @@ describe('Worker-embedded image scripts', () => { const generated = readFileSync(fileURLToPath(new URL('./vm-scripts.generated.ts', import.meta.url).href), 'utf8') expect(generated).toBe(renderVmScriptsModule()) }) + + it('installs every VM script and makes zsh read the session env hook once', () => { + const provision = readFileSync(fileURLToPath(new URL('./provision-golden.sh', import.meta.url).href), 'utf8') + const loop = provision.match(/^for name in (.+); do$/m)?.[1].split(' ') ?? [] + expect(new Set(loop)).toEqual(new Set(VM_SCRIPTS)) + expect(provision).toContain( + "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" + ) + }) }) describe('agents the image ships', () => { diff --git a/cloud/apps/sandbox-control/image/golden-image.ts b/cloud/apps/sandbox-control/image/golden-image.ts index a91def68aa2..94e2f51c1a2 100644 --- a/cloud/apps/sandbox-control/image/golden-image.ts +++ b/cloud/apps/sandbox-control/image/golden-image.ts @@ -9,6 +9,7 @@ export const VM_SCRIPTS = [ 'orca-sandbox-drain', 'orca-sandbox-env', 'orca-session-env.sh', + 'orca-env', 'orca-egress-probe', 'orca-image-wipe', 'orca-share-proxy', @@ -20,6 +21,8 @@ export const VM_SCRIPTS = [ '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', diff --git a/cloud/apps/sandbox-control/image/provision-golden.sh b/cloud/apps/sandbox-control/image/provision-golden.sh index 949a36d4de4..2a3469f9204 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -209,7 +209,7 @@ if [ -n "${NOVNC_VERSION:-}" ]; then fi log 'Orca entry points' -for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe 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-git-as orca-git-identity orcad-boot git; do +for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe 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 var="ORCA_VM_SCRIPT_${name//[-.]/_}" printf '%s' "${!var}" | base64 -d >"$ORCA_HOME/bin/$name" chmod 0755 "$ORCA_HOME/bin/$name" @@ -238,6 +238,14 @@ if [ -f /etc/bash.bashrc ]; then grep -q zz-orca-session-env /etc/bash.bashrc || 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 fi +if [ -f /etc/bash.bashrc ]; then + # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers + # shells that were already open). + sudo install -d -m 0755 /etc/zsh + sudo touch /etc/zsh/zshenv + grep -q zz-orca-session-env /etc/zsh/zshenv || + 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 +fi sudo chown -R root:root "$ORCA_HOME" log 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)' diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index bc0c2ae96f4..595c90ddf9f 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -2,8 +2,8 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} -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-egress-probe orca-image-wipe 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-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\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)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(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=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\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) gemini_key=1 ;;\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 both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$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 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 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# ---- 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 if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= \"gemini-api-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' || 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-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-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-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 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-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)}\"\ndir=\"/dev/shm/orca-env-$(id -u)\"\nif [ \"$(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=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\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 both managed blocks\n awk '/^# >>> orca-cloud managed/{skip=1} !skip{print} /^# <<< orca-cloud managed/{skip=0}' \"$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 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 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# ---- 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' || 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 | CLAUDE_CODE_OAUTH_TOKEN) return 0 ;;\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-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_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" diff --git a/cloud/apps/sandbox-control/image/vm/orca-env b/cloud/apps/sandbox-control/image/vm/orca-env new file mode 100755 index 00000000000..32f08c4c013 --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-env @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets +# saved after the shell started): eval "$(orca-env)" or, in fish: orca-env --fish | source +# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and +# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone. +# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal. +set -euo pipefail +fish='' +case "${1-}" in + '') ;; + --fish) fish=1 ;; + -h | --help) + printf 'usage: eval "$(orca-env)" (fish: orca-env --fish | source)\n' + exit 0 + ;; + *) + printf 'orca-env: unknown option %s\n' "$1" >&2 + exit 2 + ;; +esac +# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names. +file="${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}" +set -f # names are split below, never globbed +# Not written yet (or not a cloud VM): nothing to change, like the shell hook. +[ -r "$file" ] || exit 0 + +# 'it'\''s' for POSIX shells; fish single quotes escape only \ and '. +quote() { + local v="$1" + if [ -n "$fish" ]; then + v="${v//\\/\\\\}" + v="${v//\'/\\\'}" + printf "'%s'" "$v" + else + printf "'%s'" "${v//\'/\'\\\'\'}" + fi +} + +# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test +# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes. +skip_name() { + case "$1" in + '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;; + LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;; + PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \ + BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \ + NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \ + CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \ + PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \ + GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \ + GH_TOKEN | GITHUB_TOKEN | CLAUDE_CODE_OAUTH_TOKEN) return 0 ;; + esac + return 1 +} + +names=' ' +while IFS= read -r line || [ -n "$line" ]; do + name="${line%%=*}" + skip_name "$name" && continue + # $(...) drops trailing newlines; the x keeps them. + value="$(printf '%s' "${line#*=}" | base64 -d 2>/dev/null; printf x)" + value="${value%x}" + if [ -n "$fish" ]; then + printf 'set -gx %s %s\n' "$name" "$(quote "$value")" + else + printf 'export %s=%s\n' "$name" "$(quote "$value")" + fi + names="$names$name " +done <"$file" +for name in ${ORCA_SESSION_ENV_NAMES-}; do + skip_name "$name" && continue + case "$names" in *" $name "*) continue ;; esac + if [ -n "$fish" ]; then + printf 'set -e %s\n' "$name" + else + printf 'unset %s\n' "$name" + fi +done +names="${names# }" +names="${names% }" +if [ -n "$fish" ]; then + printf 'set -gx ORCA_SESSION_ENV_NAMES %s\n' "$(quote "$names")" +else + printf 'export ORCA_SESSION_ENV_NAMES=%s\n' "$(quote "$names")" +fi diff --git a/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs new file mode 100644 index 00000000000..a039671a4e9 --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-read-snapshot.cjs @@ -0,0 +1,409 @@ +#!/usr/bin/env node +// Gathers what a sleeping workspace should still show (recent chats per agent session, agent +// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals +// it to the reader keys the control plane passed, so only ciphertext leaves the VM. +// Run by orca-sandbox-read-snapshot right before the drain. Env: +// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex> +// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover +// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there) +// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}. +// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app): +// body = AES-256-GCM(dek, nonce, JSON, AAD "orca-cloud-read-v1::") +// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, "orca-cloud-read-wrap-v1"), +// nonce_i, dek, AAD "orca-cloud-read-wrap-v1:::") +'use strict' +const crypto = require('node:crypto') +const fs = require('node:fs') +const net = require('node:net') +const path = require('node:path') + +const INFO = 'orca-cloud-read-v1' +const WRAP_INFO = 'orca-cloud-read-wrap-v1' +const PROJECT = '/vercel/sandbox/project' +const LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 } +/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */ +const MAX_PLAIN_BYTES = 150_000 +const CALL_TIMEOUT_MS = 5_000 +const TOTAL_BUDGET_MS = 20_000 + +function b64(bytes) { + return Buffer.from(bytes).toString('base64') +} + +function x25519PublicKey(raw) { + return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' }) +} + +function gcmSeal(key, nonce, plain, aad) { + const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce) + cipher.setAAD(Buffer.from(aad)) + return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()]) +} + +/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */ +function seal(payload, recipients, workspaceId, snapshotId) { + const scope = `${workspaceId}:${snapshotId}` + const dek = crypto.randomBytes(32) + const nonce = crypto.randomBytes(12) + const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`) + const sealedTo = [] + for (const recipient of recipients) { + const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64') + if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) { + continue + } + let shared + const eph = crypto.generateKeyPairSync('x25519') + try { + shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) }) + } catch { + continue + } + if (shared.every((byte) => byte === 0)) { + continue + } + const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url') + const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32)) + const wrapNonce = crypto.randomBytes(12) + const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`) + sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) }) + } + dek.fill(0) + return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo } +} + +// --- gathering ------------------------------------------------------------------------------- + +/** One request per connection, like the CLI. A streaming method resolves on its first frame. */ +function rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) { + return new Promise((resolve) => { + const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe')) + if (!transport) { + resolve(null) + return + } + const socket = net.createConnection(transport.endpoint) + const id = crypto.randomUUID() + let buffer = '' + let done = false + const finish = (value) => { + if (!done) { + done = true + clearTimeout(timer) + socket.destroy() + resolve(value) + } + } + const timer = setTimeout(() => finish(null), timeoutMs) + socket.setEncoding('utf8') + socket.on('error', () => finish(null)) + socket.on('close', () => finish(null)) + socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\n`)) + socket.on('data', (chunk) => { + buffer += chunk + let newline + while ((newline = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newline) + buffer = buffer.slice(newline + 1) + let frame + try { + frame = JSON.parse(line) + } catch { + continue + } + if (!frame || frame.id !== id) { + continue + } + finish(frame.ok === true ? frame.result : null) + return + } + }) + }) +} + +const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) +const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null) +const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null) + +function messagesOf(history) { + const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : [] + const out = [] + for (const item of items) { + const body = isObj(item) && isObj(item.body) ? item.body : null + if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) { + continue + } + const role = body.role + if (role !== 'user' && role !== 'assistant' && role !== 'system') { + continue + } + const text = body.blocks + .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string') + .map((b) => b.text) + .join('\n') + .trim() + if (text) { + out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 }) + } + } + return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true } +} + +function gitOf(status, log) { + if (!isObj(status) && !isObj(log)) { + return null + } + const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : [] + let added = 0 + let removed = 0 + let counted = false + const changes = entries.slice(0, LIMITS.changes).map((e) => { + const a = num(e.added) + const r = num(e.removed) + if (a !== null || r !== null) { + counted = true + } + return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r } + }) + for (const e of entries) { + added += num(e.added) || 0 + removed += num(e.removed) || 0 + } + const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : [] + return { + branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\/heads\//, '') : null, + head: isObj(status) ? str(status.head, 64) : null, + changes, + changeCount: entries.length, + added: counted ? added : null, + removed: counted ? removed : null, + commits: items.slice(0, LIMITS.commits).map((c) => ({ + id: String(c.id).slice(0, 64), + subject: String(c.subject ?? '').slice(0, 300), + author: str(c.author, 120), + at: num(c.timestamp) + })) + } +} + +function prOf(linked) { + if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) { + return null + } + return { + number: linked.number, + title: String(linked.title ?? '').slice(0, 300), + state: str(linked.state, 20) || 'open', + url: linked.url.slice(0, 500), + checksStatus: str(linked.checksStatus, 20), + checksSummary: str(linked.checksSummary, 200) + } +} + +const STATUSES = new Set(['working', 'attention', 'idle']) +const PANE_PREFIX = 'structured-agent-session-' + +/** + * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name + * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and + * worktree.ps lists only agents that are live right now, so this is the complete list. + */ +function storedSessions(dataDir) { + let db + try { + const { DatabaseSync } = require('node:sqlite') + db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true }) + const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id)) + const out = [] + for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) { + let record + try { + record = JSON.parse(row.record_json) + } catch { + continue + } + const last = isObj(record.lastTurn) ? record.lastTurn : {} + out.push({ + sessionId: row.session_id, + agent: str(record.provider, 40), + title: str(record.conversationName, 200) || str(last.prompt, 200), + status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown', + turnOutcome: str(last.outcome, 40), + updatedAt: num(record.updatedAt), + open: open.has(row.session_id), + lastPrompt: str(last.prompt, LIMITS.messageChars), + lastReply: str(last.reply, LIMITS.messageChars), + lastAt: num(last.at) + }) + } + return out + } catch { + return [] + } finally { + try { + db && db.close() + } catch {} + } +} + +/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */ +function liveAgents(worktrees) { + const out = new Map() + for (const w of worktrees) { + for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) { + const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : '' + if (!tab.startsWith(PANE_PREFIX)) { + continue + } + const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state + out.set(tab.slice(PANE_PREFIX.length), { + agent: str(a.agentType, 40), + title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200), + status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle', + updatedAt: num(a.updatedAt) + }) + } + } + return out +} + +/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */ +async function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) { + const timeLeft = () => deadline - Date.now() + const ps = await call('worktree.ps', { limit: 20 }) + const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : [] + const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null + const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}` + const [status, log] = await Promise.all([ + call('git.status', { worktree: selector, includeLineStats: true }), + call('git.history', { worktree: selector, limit: LIMITS.commits }) + ]) + const live = liveAgents(worktrees) + const byId = new Map() + for (const s of listSessions()) { + byId.set(s.sessionId, s) + } + for (const [sessionId, a] of live) { + byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) }) + } + // Open chats first, then newest activity. + const picked = [...byId.values()] + .filter((s) => typeof s.sessionId === 'string') + .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0)) + .slice(0, LIMITS.sessions) + const sessions = [] + for (const s of picked) { + const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null + let { messages, hasOlder } = messagesOf(history) + if (messages.length === 0) { + // No readable history (or out of time): the stored last turn still says what happened. + const at = s.lastAt || s.updatedAt || 0 + messages = [ + ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []), + ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : []) + ] + hasOlder = hasOlder || messages.length > 0 + } + sessions.push({ + sessionId: s.sessionId.slice(0, 200), + agent: s.agent || null, + title: s.title || null, + status: STATUSES.has(s.status) ? s.status : 'unknown', + turnOutcome: s.turnOutcome || null, + updatedAt: num(s.updatedAt), + messages: messages.slice(-LIMITS.messagesPerSession), + truncated: hasOlder || messages.length > LIMITS.messagesPerSession + }) + } + return { + v: 1, + workspaceId, + snapshotId, + capturedAt: now, + reason, + git: gitOf(status, log), + pr: prOf(project && project.linkedPR), + sessions + } +} + +/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */ +function fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) { + const size = () => Buffer.byteLength(JSON.stringify(payload)) + let guard = 0 + while (size() > maxBytes && guard++ < 10_000) { + const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null) + if (longest && longest.messages.length > 4) { + longest.messages.shift() + longest.truncated = true + continue + } + const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500) + if (longText) { + longText.text = `${longText.text.slice(0, 500)}…` + continue + } + if (payload.git && payload.git.changes.length > 20) { + payload.git.changes = payload.git.changes.slice(0, 20) + continue + } + if (payload.sessions.length > 1) { + payload.sessions.pop() + continue + } + payload.sessions = [] + break + } + return payload +} + +async function main() { + const started = Date.now() + const env = process.env + const snapshotId = env.ORCA_READ_SNAPSHOT_ID || '' + const workspaceId = env.ORCA_READ_WORKSPACE_ID || '' + if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) { + process.stderr.write('bad ids\n') + process.exit(2) + } + let recipients + try { + recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]') + } catch { + recipients = null + } + if (!Array.isArray(recipients) || recipients.length === 0) { + process.stderr.write('no recipients\n') + process.exit(2) + } + const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data') + let metadata + try { + metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8')) + } catch { + metadata = null + } + if (!metadata || !metadata.authToken) { + process.stderr.write('orcad not running\n') + process.exit(3) + } + const deadline = started + TOTAL_BUDGET_MS + const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now()))) + const payload = fitToBudget( + await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) }) + ) + const out = seal(payload, recipients, workspaceId, snapshotId) + // Timing only: counts and sizes would describe the plaintext to the control plane's logs. + out.stats = { collectMs: Date.now() - started } + process.stdout.write(`${JSON.stringify(out)}\n`) +} + +module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents } + +if (require.main === module) { + // A fixed message: an error text could carry workspace content into the control plane's logs. + main().catch(() => { + process.stderr.write('read snapshot failed\n') + process.exit(1) + }) +} diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-env b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env index 149f6379ebe..3385bc365bb 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-env +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-env @@ -44,7 +44,8 @@ while IFS= read -r line; do OPENAI_MODEL) openai_model="$(printf '%s' "$b64" | base64 -d)" ;; ANTHROPIC_MODEL) anthropic_model="$(printf '%s' "$b64" | base64 -d)" ;; AI_GATEWAY_API_KEY) gateway_key=1 ;; - GEMINI_API_KEY) gemini_key=1 ;; + GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key="${gemini_key:-gemini-api-key}" ;; + GOOGLE_GENAI_USE_VERTEXAI) case "$(printf '%s' "$b64" | base64 -d)" in true | 1) gemini_key=vertex-ai ;; esac ;; # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars. ANTHROPIC_API_KEY) anthropic_key_tail="$(printf '%s' "$b64" | base64 -d | tail -c 20)" ;; esac @@ -160,7 +161,9 @@ if (isObject(g)) { general.disableAutoUpdate ??= true general.disableUpdateNag ??= true section(g, "privacy").usageStatisticsEnabled ??= false - if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= "gemini-api-key" + // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs + // refuse to start without a method ("Invalid auth method selected"). + if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= process.env.ORCA_GEMINI_KEY if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g) } diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot b/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot new file mode 100755 index 00000000000..697d142463d --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-read-snapshot @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the +# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see +# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read). +set -euo pipefail +umask 077 +ORCA_HOME=/opt/orca +export ORCA_USER_DATA_PATH="${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}" +node="$(find "$ORCA_HOME/runtime/runtimes" -type f -name node | head -n 1)" +[ -n "$node" ] || { echo 'node not found' >&2; exit 1; } +exec timeout 35 "$node" "$ORCA_HOME/bin/orca-read-snapshot.cjs" diff --git a/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql b/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql new file mode 100644 index 00000000000..ab388527cb9 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0039_read_snapshots.sql @@ -0,0 +1,45 @@ +-- Read a sleeping workspace without waking it (gap 5). Every device keeps one X25519 "reader key"; +-- only the public half is stored here. At each drain the VM seals a compact snapshot (chats, agent +-- status, git, PR) to the reader keys allowed to open the workspace; this database keeps only that +-- ciphertext and one wrapped content key per reader key, never plaintext. +CREATE TABLE IF NOT EXISTS reader_keys ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + dev INTEGER NOT NULL DEFAULT 0, + public_key TEXT NOT NULL, + device_kind TEXT NOT NULL, + device_label TEXT NOT NULL, + -- A phone's key dies with its device session (unpair, revoke, member removal). + device_session_id TEXT, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + revoked_at INTEGER, + revoked_by TEXT +); +CREATE UNIQUE INDEX IF NOT EXISTS reader_keys_live ON reader_keys (account_id, user_id, public_key) WHERE revoked_at IS NULL; +CREATE INDEX IF NOT EXISTS reader_keys_account ON reader_keys (account_id, revoked_at); +CREATE INDEX IF NOT EXISTS reader_keys_device_session ON reader_keys (device_session_id); + +-- One snapshot per workspace, replaced at every drain. +CREATE TABLE IF NOT EXISTS read_snapshots ( + sandbox_id TEXT PRIMARY KEY, + snapshot_id TEXT NOT NULL, + stored_at INTEGER NOT NULL, + bytes INTEGER NOT NULL, + nonce TEXT NOT NULL, + ciphertext TEXT NOT NULL +); + +-- The snapshot's content key wrapped to one reader key. Deleting a row is how access is pruned +-- (member removed, workspace made private, key revoked) without waking the VM. +CREATE TABLE IF NOT EXISTS read_snapshot_keys ( + sandbox_id TEXT NOT NULL, + key_id TEXT NOT NULL, + snapshot_id TEXT NOT NULL, + ephemeral_public_key TEXT NOT NULL, + nonce TEXT NOT NULL, + wrapped_key TEXT NOT NULL, + PRIMARY KEY (sandbox_id, key_id) +); +CREATE INDEX IF NOT EXISTS read_snapshot_keys_key ON read_snapshot_keys (key_id); diff --git a/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql b/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql new file mode 100644 index 00000000000..7ac41691c4b --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0041_agent_sources.sql @@ -0,0 +1,13 @@ +-- Per-person agent Source (agent-sources contract §2): "Your sign-in" or "API key", as a default +-- (scope 'default'), a per-workspace override (scope = sandbox id), or the one-time sign-in offer answer +-- (scope 'offer', source 'accepted'|'declined'). Rows for a sandbox go with it. +CREATE TABLE agent_sources ( + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + scope TEXT NOT NULL, + agent TEXT NOT NULL CHECK (agent IN ('claude', 'codex')), + source TEXT NOT NULL CHECK (source IN ('sign-in', 'key', 'accepted', 'declined')), + updated_at INTEGER NOT NULL, + PRIMARY KEY (user_id, scope, agent) +); +CREATE INDEX agent_sources_scope ON agent_sources (scope); diff --git a/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql b/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql new file mode 100644 index 00000000000..ffb834b73c9 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0042_session_cpu.sql @@ -0,0 +1,20 @@ +-- U22: each session's measured CPU, for internal fair-use review only. Customers keep flat +-- sandbox hours: nothing here feeds usage_outbox, billing or any customer-facing route. +-- One row per provider session (idempotent); active_cpu_ms stays NULL until Vercel reports it +-- after the VM stops, and a cron sweep retries the ones still missing. Additive. +CREATE TABLE session_cpu ( + session_id TEXT PRIMARY KEY, + sandbox_id TEXT NOT NULL, + account_id TEXT NOT NULL, + user_id TEXT, + vcpus INTEGER NOT NULL, + memory_mb INTEGER, + active_cpu_ms INTEGER, + wall_ms INTEGER NOT NULL, + started_at INTEGER, + ended_at INTEGER NOT NULL, + fetched_at INTEGER, + attempts INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX session_cpu_account_ended ON session_cpu (account_id, ended_at); +CREATE INDEX session_cpu_pending ON session_cpu (ended_at) WHERE active_cpu_ms IS NULL; diff --git a/cloud/apps/sandbox-control/src/agent-credential-names.ts b/cloud/apps/sandbox-control/src/agent-credential-names.ts new file mode 100644 index 00000000000..84d14a32e10 --- /dev/null +++ b/cloud/apps/sandbox-control/src/agent-credential-names.ts @@ -0,0 +1,20 @@ +// Worker mirror of src/shared/agent-credentials/agent-credential-names.ts (agent-sources contract §1); +// test/agent-credential-names.test.ts fails if the two lists drift. +export type CredentialAgent = 'claude' | 'codex' +export const AGENT_CREDENTIAL_NAMES: Record = { + claude: [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'ANTHROPIC_BASE_URL', + 'ANTHROPIC_MODEL', + 'ANTHROPIC_SMALL_FAST_MODEL', + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX', + 'AWS_BEARER_TOKEN_BEDROCK', + 'ANTHROPIC_VERTEX_PROJECT_ID', + 'CLOUD_ML_REGION' + ], + codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'] +} + +export const CREDENTIAL_AGENTS: readonly CredentialAgent[] = ['claude', 'codex'] diff --git a/cloud/apps/sandbox-control/src/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts new file mode 100644 index 00000000000..312b66bf722 --- /dev/null +++ b/cloud/apps/sandbox-control/src/agent-sources.ts @@ -0,0 +1,183 @@ +// Agent Source per person (agent-sources contract §2): "Your sign-in" or "API key", per agent, as a +// default plus an optional per-workspace override, and the one-time "Use my sign-in" offer answer (D8). +// GET /v1/agent-sources[?workspaceId=] +// PUT /v1/agent-sources {agent, source: 'sign-in'|'key'|null, workspaceId?} +// PUT /v1/agent-sources/offer {agent, answer: 'accepted'|'declined'} +// A sandbox applies its OWNER's effective source: with 'sign-in', that agent's credential names are left +// out of the session env (and so out of egress routes, the allowlist and gateway derivation), letting +// the agent's own login inside the sandbox win. Variables are never touched. +import { z } from 'zod' +import { AGENT_CREDENTIAL_NAMES, CREDENTIAL_AGENTS, type CredentialAgent } from './agent-credential-names' +import type { SandboxCaller } from './auth' +import { memberNamesFor } from './member-names' +import { effectiveSecrets } from './secrets' +import { getSandbox, type SandboxRow } from './store' + +export type AgentSource = 'sign-in' | 'key' +type OfferAnswer = 'unanswered' | 'accepted' | 'declined' +const DEFAULT_SCOPE = 'default' +const OFFER_SCOPE = 'offer' + +type SourceRow = { scope: string; agent: CredentialAgent; source: string } + +const AgentSchema = z.enum(['claude', 'codex']) +export const PutSourceSchema = z + .object({ + agent: AgentSchema, + source: z.enum(['sign-in', 'key']).nullable(), + workspaceId: z.string().min(1).max(128).optional() + }) + .strict() +export const PutOfferSchema = z.object({ agent: AgentSchema, answer: z.enum(['accepted', 'declined']) }).strict() + +export class AgentSourceError extends Error { + constructor( + readonly status: 400 | 403 | 404, + readonly code: string, + readonly reason?: string + ) { + super(reason ? `${code}:${reason}` : code) + } +} + +async function rowsFor(db: D1Database, userId: string, scopes: string[]): Promise { + const { results } = await db + .prepare(`SELECT scope, agent, source FROM agent_sources WHERE user_id = ? AND scope IN (${scopes.map(() => '?').join(', ')})`) + .bind(userId, ...scopes) + .all() + return results +} + +function byAgent(rows: SourceRow[], scope: string): Record { + const out = { claude: null, codex: null } as Record + for (const row of rows) { + if (row.scope === scope && (row.source === 'sign-in' || row.source === 'key')) { + out[row.agent] = row.source + } + } + return out +} + +/** Agents whose owner chose "Your sign-in" for this sandbox (override first, then default). */ +export async function signInAgentsFor(db: D1Database, row: Pick): Promise> { + const rows = await rowsFor(db, row.user_id, [row.id, DEFAULT_SCOPE]) + const workspace = byAgent(rows, row.id) + const defaults = byAgent(rows, DEFAULT_SCOPE) + return new Set(CREDENTIAL_AGENTS.filter((agent) => (workspace[agent] ?? defaults[agent]) === 'sign-in')) +} + +/** Drops the credential names of agents on "Your sign-in" (after preset derivation, so derived ones go too). */ +export function withoutSignInCredentials>(env: T, signIn: ReadonlySet): T { + if (signIn.size === 0) { + return env + } + const next: Record = { ...env } + for (const agent of signIn) { + for (const name of AGENT_CREDENTIAL_NAMES[agent]) { + delete next[name] + } + } + return next as T +} + +/** Some agent key the caller's sessions would get covers this agent (the gateway key covers both). */ +function coveredByKey(names: ReadonlySet): Record { + const gateway = names.has('AI_GATEWAY_API_KEY') + return { + claude: gateway || ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'AWS_BEARER_TOKEN_BEDROCK', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'].some((n) => names.has(n)), + codex: gateway || names.has('OPENAI_API_KEY') + } +} + +async function ownedWorkspace(db: D1Database, caller: SandboxCaller, workspaceId: string): Promise { + const row = await getSandbox(db, workspaceId) + if (!row || row.account_id !== caller.accountId || row.status === 'destroyed') { + throw new AgentSourceError(404, 'not_found') + } + return row +} + +export async function agentSourcesView(db: D1Database, caller: SandboxCaller, workspaceId: string | null) { + const row = workspaceId ? await ownedWorkspace(db, caller, workspaceId) : null + // The sandbox applies its owner's choice (shared sandboxes, v1): show the owner's, not the caller's. + const subject = row ? row.user_id : caller.userId + const rows = await rowsFor(db, subject, [DEFAULT_SCOPE, OFFER_SCOPE, ...(row ? [row.id] : [])]) + const defaults = byAgent(rows, DEFAULT_SCOPE) + const workspace = row ? byAgent(rows, row.id) : null + const effective = await effectiveSecrets(db, caller, row?.repo_url ?? null) + const covered = coveredByKey(new Set(effective.map((secret) => secret.name))) + const offerRows = rows.filter((r) => r.scope === OFFER_SCOPE) + const signInOffer = Object.fromEntries( + CREDENTIAL_AGENTS.map((agent) => [ + agent, + (offerRows.find((r) => r.agent === agent)?.source as OfferAnswer | undefined) ?? 'unanswered' + ]) + ) as Record + const resolved = Object.fromEntries( + CREDENTIAL_AGENTS.map((agent) => { + const chosen = workspace?.[agent] ?? null + if (chosen) { + return [agent, { source: chosen, origin: 'workspace' }] + } + if (defaults[agent]) { + return [agent, { source: defaults[agent], origin: 'default' }] + } + return [agent, { source: covered[agent] ? 'key' : null, origin: 'implicit' }] + }) + ) + let owner: { userId: string; displayName: string | null; isCaller: boolean } | null = null + if (row) { + const names = await memberNamesFor(db, caller.accountId, [row.user_id]) + owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId } + } + return { defaults, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner } +} + +async function upsert(db: D1Database, caller: SandboxCaller, scope: string, agent: CredentialAgent, source: string | null, now: number) { + if (source === null) { + await db.prepare('DELETE FROM agent_sources WHERE user_id = ? AND scope = ? AND agent = ?').bind(caller.userId, scope, agent).run() + return + } + await db + .prepare( + `INSERT INTO agent_sources (user_id, account_id, scope, agent, source, updated_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (user_id, scope, agent) DO UPDATE SET source = excluded.source, account_id = excluded.account_id, updated_at = excluded.updated_at` + ) + .bind(caller.userId, caller.accountId, scope, agent, source, now) + .run() +} + +/** Returns the sandbox whose session env must refresh (a running one whose owner's source changed), if any. */ +export async function putAgentSource(db: D1Database, caller: SandboxCaller, body: z.infer, now: number) { + let row: SandboxRow | null = null + if (body.workspaceId) { + row = await ownedWorkspace(db, caller, body.workspaceId) + if (row.user_id !== caller.userId) { + throw new AgentSourceError(403, 'forbidden', 'owner_only') + } + } + // D9: accepted while the sandbox is still starting; its first boot reads the row. + await upsert(db, caller, row ? row.id : DEFAULT_SCOPE, body.agent, body.source, now) + return row +} + +export async function putOfferAnswer(db: D1Database, caller: SandboxCaller, body: z.infer, now: number) { + await upsert(db, caller, OFFER_SCOPE, body.agent, body.answer, now) +} + +/** Running sandboxes of this person that a default change affects (no workspace override for that agent). */ +export async function runningSandboxesForDefault(db: D1Database, userId: string, agent: CredentialAgent): Promise { + const { results } = await db + .prepare( + `SELECT s.* FROM sandboxes s WHERE s.user_id = ? AND s.status = 'running' + AND NOT EXISTS (SELECT 1 FROM agent_sources a WHERE a.user_id = s.user_id AND a.scope = s.id AND a.agent = ?) + LIMIT 200` + ) + .bind(userId, agent) + .all() + return results +} + +export async function deleteAgentSourcesForSandbox(db: D1Database, sandboxId: string): Promise { + await db.prepare('DELETE FROM agent_sources WHERE scope = ?').bind(sandboxId).run() +} diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 1939442d0da..bb270fbc52e 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -32,6 +32,7 @@ // Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts) // Public share links (src/share-gateway.ts): /s//*, plus the root-path cookie fallback // Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy +import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots' import { refreshStaleEnvironments } from './environment-golden-refresh' import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' @@ -89,12 +90,21 @@ import { GuardrailError, consumeCreateToken, guardrailsFromEnv } from './guardra import { handleOperator, isOperator } from './operator' import { DEFAULT_RETENTION, type RetentionConfig } from './retention' import { reconcile } from './reconcile' -import { egressSecretHosts, secretPlaceholder } from './secret-egress' +import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress' import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' +import { + AgentSourceError, + PutOfferSchema, + PutSourceSchema, + agentSourcesView, + putAgentSource, + putOfferAnswer, + runningSandboxesForDefault +} from './agent-sources' import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts' import { cachedProviderEnv } from './session-env' -import { credentialTargets } from './provider-env' +import { credentialTargets, type CredentialTarget } from './provider-env' import type { Keyring } from './secrets-crypto' import { ProviderError, type SandboxProviderApi } from './sandbox-provider' import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands' @@ -150,12 +160,14 @@ import { isOrgAdmin, listWorkspaces, patchWorkspace, + assertCanManageWorkspace, reportPresence, requireVisible, resolveLink, workspaceViews } from './workspaces' import { rememberCallerName } from './member-names' +import { sweepSessionCpu } from './session-cpu' import type { SandboxCaller } from './auth' const MAX_JSON_BYTES = 16 * 1024 @@ -251,17 +263,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => : null } }) - return async (row, host) => { - if (host === 'github.com') { - return members.routes(row, host) - } - if (host === 'api.github.com') { - return [ - // Members first: a member placeholder must never fall through to the app's token. - ...(await members.routes(row, host)), - { header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) } - ] - } + const secretRoutes = (row: SandboxRow, host: string): ProxiedRoute[] => { const entries = egressSecretHosts(row).filter((candidate) => candidate.host === host) const keyring = keyringFor(env) if (entries.length === 0 || !keyring) { @@ -270,7 +272,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => return entries.flatMap((entry) => Object.entries(entry.headers).map(([header, format]): ProxiedRoute => ({ header, - placeholders: [format(secretPlaceholder(row, entry.secret))], + placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)), label: entry.secret, ...(entry.paths ? { pathAllowed: requestMatches(entry.paths) } : {}), ...(entry.keepResponseFields ? { keepResponseFields: entry.keepResponseFields } : {}), @@ -287,13 +289,34 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => })) ) } + return async (row, host) => { + if (host === 'github.com') { + return members.routes(row, host) + } + if (host === 'api.github.com') { + return [ + // Members first: a member placeholder must never fall through to the app's token. + ...(await members.routes(row, host)), + { header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) }, + // A user's own GitHub token for Copilot CLI (COPILOT_GITHUB_TOKEN), on its own placeholder. + ...secretRoutes(row, host) + ] + } + return secretRoutes(row, host) + } } -/** Exact method and path (the query string is ignored). */ -function requestMatches(allowed: readonly { method: string; path: string }[]): (method: string, path: string) => boolean { +/** Method and path (the query string is ignored); a prefix entry matches below a normalized path only. */ +function requestMatches(allowed: NonNullable): (method: string, path: string) => boolean { return (method, path) => { - const pathname = path.split('?')[0] - return allowed.some((entry) => entry.method === method.toUpperCase() && entry.path === pathname) + const pathname = path.split('?')[0] ?? '' + // A prefix grant never stretches across encoded or dot segments into another API. + const plain = /^(\/[A-Za-z0-9._~-]+)+\/?$/.test(pathname) && !/(^|\/)\.\.?(\/|$)/.test(pathname) + return allowed.some( + (entry) => + entry.method === method.toUpperCase() && + (entry.prefix ? plain && pathname.startsWith(entry.path) : entry.path === pathname) + ) } } @@ -890,6 +913,14 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) const state = await createConnectState(env.SANDBOX_DB, connect.stateSecret, { accountId: `dev:${sub}`, userId: sub }, (deps.now ?? Date.now)()) return Response.redirect(authorizeUrl(connect, url.origin, state), 302) } + if (url.pathname === '/v1/reader-keys' || url.pathname.startsWith('/v1/reader-keys/')) { + const now = (deps.now ?? Date.now)() + const caller = await authenticateDesktop(env, request, now) + if (!caller) { + return fail('unauthorized', 401) + } + return await handleReaderKeysRoute(request, url, { db: env.SANDBOX_DB, caller, now, readJson: () => readJson(request) }) + } if (url.pathname === '/v1/device-sessions' || url.pathname.startsWith('/v1/device-sessions/')) { const now = (deps.now ?? Date.now)() const caller = await authenticateDesktop(env, request, now) @@ -905,6 +936,10 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) onRevoked: deps.onDeviceSessionRevoked ?? (async (deviceSessionId) => { + // Its reader key: independent of the grant cleanup below, so neither failure blocks the other. + await revokeDeviceSessionReaderKeys(env.SANDBOX_DB, deviceSessionId, now).catch((error: unknown) => + console.log(JSON.stringify({ event: 'device_reader_key_revoke_failed', id: deviceSessionId, error: String(error).slice(0, 120) })) + ) const life = await lifecycleDeps(env, deps) if (life) { await revokeGrantsForDeviceSession(life, deviceSessionId) @@ -1048,6 +1083,16 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) } return response } + if (url.pathname === '/v1/agent-sources' || url.pathname === '/v1/agent-sources/offer') { + const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) + if (!caller) { + return fail('unauthorized', 401) + } + if (caller.deviceSessionId) { + return fail('forbidden', 403, 'device_session') + } + return await agentSourcesRoute(request, url, env, deps, caller) + } if (isEnvironmentRoute(url.pathname)) { const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) if (!caller) { @@ -1337,7 +1382,7 @@ 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) } - const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) + 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) } @@ -1348,6 +1393,16 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, if (route === 'GET ') { return json({ workspace: await view() }) } + if (route === 'GET read-snapshot') { + try { + return json(await getReadSnapshot(db, caller, row, url.searchParams.get('keyId'), now)) + } catch (error) { + if (error instanceof ReadSnapshotRouteError) { + return fail(error.code, error.status) + } + throw error + } + } if (route === 'POST sent') { // The caller's own client: "I just sent a message here" (opens their git-as-sender window). if (!canOpen(caller, row)) { @@ -1374,15 +1429,37 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, return fail('invalid_request', 400) } const { archived, ...rest } = body.data - // Archive/unarchive are lifecycle changes, not labels: the sandbox really stops (snapshot kept - // with a TTL) or comes back asleep. Permissions are checked by patchWorkspace first. - let patched = await patchWorkspace(db, caller, row, archived === undefined ? body.data : { ...rest, archived }, now) - if (archived === true && (patched.row.status === 'running' || patched.row.status === 'suspended')) { - const stopped = await archiveSandbox(life, patched.row, {}, workspaceConfig(env, deps)) - patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, stopped.id)) ?? patched.row } - } else if (archived === false && patched.row.status === 'archived') { - const restored = await restoreArchivedToSleeping(life, patched.row) - patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, restored.id)) ?? patched.row } + // Archive/unarchive are lifecycle changes, not labels. The lifecycle runs FIRST and is what + // sets archived_at, so a failed or refused archive never labels a running sandbox archived. + let archivedNow = false + if (archived !== undefined) { + assertCanManageWorkspace(caller, row) + if (archived && row.archived_at === null) { + if (row.status !== 'running' && row.status !== 'suspended') { + // Starting, waking or going to sleep: nothing changes; the client asks to try again. + return fail('conflict', 409, `sandbox_${row.status}`) + } + await archiveSandbox(life, row, {}, workspaceConfig(env, deps)) + archivedNow = true + } else if (!archived && row.status === 'archived') { + await restoreArchivedToSleeping(life, row) + } else if (!archived && row.archived_at !== null) { + // A label-only archive from before archive stopped the sandbox: clear the label. + await patchWorkspace(db, caller, row, { archived: false }, now) + } + } + const current = (await getSandbox(env.SANDBOX_DB, row.id)) ?? row + let patched: Awaited> = + Object.keys(rest).length > 0 + ? await patchWorkspace(db, caller, current, rest, now) + : { row: current, revoke: 'none' } + if (archivedNow && patched.revoke === 'none') { + // Archiving disconnects teammates' devices, as before. + patched = { ...patched, revoke: 'non_owner' } + } + if (patched.revoke !== 'none') { + // Readers lose the sleeping copy at once, before (and regardless of) the VM-side revokes. + await pruneReadSnapshotToOwner(db, patched.row) } const revoked = patched.revoke === 'none' ? null : await revokeForAccessChange(life, patched.row, patched.revoke, caller.userId) @@ -1555,6 +1632,11 @@ export default { // Counts only; no ids, tokens or pairing material. const summary = await reconcile(life) console.log(JSON.stringify({ event: 'reconcile', ...summary })) + // Internal fair-use review (U22): retry sessions whose CPU the stop couldn't read yet. + const cpu = await sweepSessionCpu(life.db, life.provider, life.now()) + if (cpu.checked > 0) { + console.log(JSON.stringify({ event: 'session_cpu_sweep', ...cpu })) + } const retried = await retryPendingMessages(life).catch(() => -1) if (retried !== 0) { console.log(JSON.stringify({ event: 'message_retry', retried })) @@ -1636,3 +1718,54 @@ export class EnvironmentBuildRunner implements DurableObject { await this.state.storage.setAlarm(Date.now() + next) } } + +async function agentSourcesRoute(request: Request, url: URL, env: Env, deps: Deps, caller: SandboxCaller): Promise { + const db = env.SANDBOX_DB + const now = (deps.now ?? Date.now)() + // Labels for the owner block on teammates' views; a failure here must never fail the request. + await rememberCallerName(db, caller, now).catch(() => undefined) + const noStore = (body: unknown) => Response.json(body, { headers: { 'cache-control': 'no-store' } }) + try { + if (request.method === 'GET' && url.pathname === '/v1/agent-sources') { + return noStore(await agentSourcesView(db, caller, url.searchParams.get('workspaceId'))) + } + if (request.method === 'PUT' && url.pathname === '/v1/agent-sources/offer') { + const body = PutOfferSchema.safeParse(await readJson(request)) + if (!body.success) { + return fail('invalid_request', 400) + } + await putOfferAnswer(db, caller, body.data, now) + return noStore(await agentSourcesView(db, caller, null)) + } + if (request.method === 'PUT' && url.pathname === '/v1/agent-sources') { + const body = PutSourceSchema.safeParse(await readJson(request)) + if (!body.success) { + return fail('invalid_request', 400) + } + const row = await putAgentSource(db, caller, body.data, now) + // A running sandbox picks the change up in new shells within seconds (same path as a secret edit). + const targets = row ? (row.status === 'running' ? [row] : []) : await runningSandboxesForDefault(db, caller.userId, body.data.agent) + if (targets.length > 0) { + const work = lifecycleDeps(env, deps).then(async (life) => { + if (life) { + for (const target of targets) { + await refreshSandboxEnv(life, target).catch(() => false) + } + } + }) + if (deps.waitUntil) { + deps.waitUntil(work.catch(() => undefined)) + } else { + await work + } + } + return noStore(await agentSourcesView(db, caller, body.data.workspaceId ?? null)) + } + return fail('not_found', 404) + } catch (error) { + if (error instanceof AgentSourceError) { + return fail(error.code, error.status, error.reason) + } + throw error + } +} diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index bd24826d129..1ca025f0b61 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -1,5 +1,6 @@ // Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease, // a forced stop before the provider's 24h cap, usage metering and write-ahead rows. +import { deleteAgentSourcesForSandbox } from './agent-sources' import type { EntitlementClient, MachineSize } from './entitlements' import { parseGitHubRepo, type GitHubAppMinter } from './github-app' import { @@ -17,9 +18,10 @@ import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' import { connectedMembers, memberGitConfigs } from './member-git' import type { RetentionConfig } from './retention' import type { ProviderSandboxState, SandboxProviderApi } from './sandbox-provider' -import { egressSecretHosts, secretPlaceholder } from './secret-egress' +import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress' import { egressAllowHosts, sessionSecretEnv, type SessionSecrets } from './session-env' import type { Keyring } from './secrets-crypto' +import { captureReadSnapshot, deleteReadSnapshot } from './read-snapshots' import { ORCAD_PORT, SHARE_PROXY_PORT, drainOrcad, runningOrcad, startOrcad, type OrcadReady, type StartInputs } from './sandbox-vm-commands' import { WORKSPACE_PRELUDE_SCRIPT } from '../image/vm-scripts.generated' import { resolveEnvironmentBoot, type BootSource } from './environments' @@ -41,6 +43,7 @@ import { type SandboxRow, type SessionFields } from './store' +import { recordSessionEnd } from './session-cpu' import { flushUsage, queueUsage } from './usage' import { SANDBOX_VCPUS } from './machine-size' import { isRegionalFailure } from './regions' @@ -232,11 +235,11 @@ export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: st // Model API keys swapped at egress (phase 2); each host also ends in the 403 deny rule, except a // host whose client sends its own short-lived token on later calls (Cursor). ...egressSecretHosts(row).flatMap((entry) => - Object.entries(entry.headers).map( - ([header, format]): CredentialRoute => ({ + Object.keys(entry.headers).map( + (header): CredentialRoute => ({ host: entry.host, header, - placeholders: [format(secretPlaceholder(row, entry.secret))], + placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)), via: 'forward', forwardURL: proxyUrl, ...(entry.allowUnclaimed ? { allowUnclaimed: true } : {}) @@ -659,23 +662,34 @@ export async function failAndRelease(deps: LifecycleDeps, row: SandboxRow): Prom export async function stopForSuspend( deps: LifecycleDeps, row: SandboxRow, - options: { drainSeconds?: number } = {} + options: { drainSeconds?: number; reason?: 'sleep' | 'rollover'; captureRead?: boolean } = {} ): Promise { if (row.session_id) { + // While orcad still serves: what a sleeping workspace shows to readers (sealed on the VM). + // Skipped for Restart (orcad isn't answering) and Archive (an archived workspace isn't readable). + if (options.captureRead !== false) { + await captureReadSnapshot(deps, row, options.reason ?? 'sleep').catch(() => undefined) + } await drainOrcad(deps.provider, row.session_id, options.drainSeconds) const stopped = await deps.provider.stopSession(row.session_id) if (stopped.snapshotId) { await recordSnapshots(deps.db, row.id, [stopped.snapshotId], deps.now()) } + await queueUsage(deps.db, row, deps.now()) + // Internal CPU review (U22): never throws, never touches the meter. + await recordSessionEnd(deps.db, row, deps.now(), stopped.usage, deps.now()) + } else { + await queueUsage(deps.db, row, deps.now()) } - await queueUsage(deps.db, row, deps.now()) await deps.hooks?.afterStop?.(row).catch(() => undefined) return claim(deps, row, { status: 'suspended', ...NO_SESSION }) } /** The provider ended the session on its own (lease lapsed): bill up to when it stopped. */ export async function markProviderStopped(deps: LifecycleDeps, row: SandboxRow): Promise { - await queueUsage(deps.db, row, Math.min(deps.now(), row.lease_expires_at ?? deps.now())) + const endedAt = Math.min(deps.now(), row.lease_expires_at ?? deps.now()) + await queueUsage(deps.db, row, endedAt) + await recordSessionEnd(deps.db, row, endedAt, null, deps.now()) await deps.hooks?.afterStop?.(row).catch(() => undefined) return claim(deps, row, { status: 'suspended', ...NO_SESSION }) } @@ -778,7 +792,7 @@ export async function rolloverSandbox(deps: LifecycleDeps, row: SandboxRow): Pro throw new GuardrailError('maintenance') } const suspending = await claim(deps, row, { status: 'suspending' }) - const stopped = await stopForSuspend(deps, suspending) + const stopped = await stopForSuspend(deps, suspending, { reason: 'rollover' }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) return wake(deps, await claim(deps, stopped, { status: 'resuming' })) } @@ -802,6 +816,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom } let destroying = row.status === 'destroying' ? row : await claim(deps, row, { status: 'destroying' }) const settled = await queueUsage(deps.db, destroying, deps.now()) + // A live session ends with the delete (no-op once suspended: the row has no session then). + await recordSessionEnd(deps.db, destroying, deps.now(), null, deps.now()) if (settled !== destroying.usage_settled_at) { destroying = await claim(deps, destroying, { usage_settled_at: settled }) } @@ -825,6 +841,10 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom await markSnapshotsDeleted(deps.db, row.id, deps.now()) // Archive metadata (repo state, file tree) goes with the workspace. await deps.db.prepare('DELETE FROM sandbox_archives WHERE sandbox_id = ?').bind(row.id).run() + // So does its sealed read snapshot. + await deleteReadSnapshot(deps.db, row.id) + // And its per-workspace agent Source overrides. + await deleteAgentSourcesForSandbox(deps.db, row.id) const destroyed = await claim(deps, destroying, { status: 'destroyed', ...NO_SESSION, diff --git a/cloud/apps/sandbox-control/src/member-removal.ts b/cloud/apps/sandbox-control/src/member-removal.ts index 2e878195057..d63234aa1ff 100644 --- a/cloud/apps/sandbox-control/src/member-removal.ts +++ b/cloud/apps/sandbox-control/src/member-removal.ts @@ -6,6 +6,7 @@ import { revokeMemberDeviceSessions } from './device-sessions' import { revokeGrantsForMember } from './grants' import type { LifecycleDeps } from './lifecycle' import { memberChangeTime, recordMemberChange } from './member-changes' +import { revokeMemberReaderKeys } from './read-snapshots' import { disableMemberRoutines } from './routines/runs' export type MemberRemoval = { @@ -14,6 +15,7 @@ export type MemberRemoval = { grantsRevoked: number grantsQueued: number routinesDisabled: number + readerKeysRevoked: number } export async function removeMember( @@ -37,6 +39,8 @@ export async function removeMember( ]) // Their phones sign as them; then every workspace device they were granted (phones' included). 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) 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) @@ -45,7 +49,8 @@ export async function removeMember( devicesRevoked, grantsRevoked: grants.revoked, grantsQueued: grants.queued, - routinesDisabled: routines.disabled + routinesDisabled: routines.disabled, + readerKeysRevoked } await audit(life.db, { accountId, type: 'system', id: 'auth', userId }, { action: 'member.removed', detail: { ...result, runsCancelled: routines.cancelled } }, now) return result diff --git a/cloud/apps/sandbox-control/src/network-policy.ts b/cloud/apps/sandbox-control/src/network-policy.ts index 024cebdeaaa..19bb7f5f967 100644 --- a/cloud/apps/sandbox-control/src/network-policy.ts +++ b/cloud/apps/sandbox-control/src/network-policy.ts @@ -80,6 +80,8 @@ export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [ 'accounts.google.com', // Vercel AI Gateway: Anthropic/OpenAI-compatible endpoint teams point agents at (ANTHROPIC_BASE_URL). 'ai-gateway.vercel.sh', + // Vertex AI express mode (GOOGLE_API_KEY with GOOGLE_GENAI_USE_VERTEXAI=true). + 'aiplatform.googleapis.com', // Gemini CLI signed in with Google: Code Assist API and the account lookup after OAuth. 'cloudcode-pa.googleapis.com', 'www.googleapis.com', diff --git a/cloud/apps/sandbox-control/src/operator.ts b/cloud/apps/sandbox-control/src/operator.ts index 1dfe2de47a7..a709679b12a 100644 --- a/cloud/apps/sandbox-control/src/operator.ts +++ b/cloud/apps/sandbox-control/src/operator.ts @@ -7,6 +7,8 @@ // DELETE /v1/internal/github/bindings {installationId, accountId?} // POST /v1/internal/members/role-changed {accountId, userId, role} re-cap their keys and MCP grants (auth calls this) // POST /v1/internal/members/removed {accountId, userId} revoke a departed member's keys, phones and workspace grants, disable their routines (auth calls this) +// GET /v1/internal/fair-use?days=30 per-account CPU utilisation + fair-use flag (U22; internal only, never billed) +// POST /v1/internal/session-cpu/sweep fetch CPU for recently stopped sessions now (the cron does this every 5 min) import { z } from 'zod' import { audit } from './api/audit' import { syncMemberRole } from './api/member-role-sync' @@ -18,6 +20,7 @@ import { guardrails, type LifecycleDeps } from './lifecycle' import { drainAll, housekeeping } from './retention' import { memberChangeTime, recordMemberChange } from './member-changes' import { removeMember } from './member-removal' +import { fairUseReport, FAIR_USE_WINDOW_DAYS, sweepSessionCpu } from './session-cpu' import { listByStatus } from './store' const KillSwitchBody = z.object({ enabled: z.boolean(), drain: z.boolean().optional() }).strict() @@ -141,6 +144,15 @@ export async function handleOperator( const removal = await removeMember(life, body.data.accountId, body.data.userId, now, body.data.changedAt) return Response.json({ revoked: removal.keysRevoked, ...removal }) } + case 'GET /v1/internal/fair-use': { + const days = Number(new URL(request.url).searchParams.get('days') ?? FAIR_USE_WINDOW_DAYS) + if (!Number.isInteger(days) || days < 1 || days > 90) { + return Response.json({ error: 'invalid_request' }, { status: 400 }) + } + return Response.json(await fairUseReport(life.db, now, days), { headers: { 'cache-control': 'no-store' } }) + } + case 'POST /v1/internal/session-cpu/sweep': + return Response.json({ sweep: await sweepSessionCpu(life.db, life.provider, now) }) default: return null } diff --git a/cloud/apps/sandbox-control/src/provider-env.ts b/cloud/apps/sandbox-control/src/provider-env.ts index df75f6d64e0..2c766282f92 100644 --- a/cloud/apps/sandbox-control/src/provider-env.ts +++ b/cloud/apps/sandbox-control/src/provider-env.ts @@ -8,6 +8,14 @@ const AI_GATEWAY_OPENAI_BASE_URL = `https://${AI_GATEWAY_HOST}/v1` export const GEMINI_HOST = 'generativelanguage.googleapis.com' export const CURSOR_API_HOST = 'api2.cursor.sh' +export const VERTEX_HOST = 'aiplatform.googleapis.com' +/** Copilot's API, per plan; which one a token uses comes from GitHub at sign-in. */ +export const COPILOT_API_HOSTS = [ + 'api.githubcopilot.com', + 'api.individual.githubcopilot.com', + 'api.business.githubcopilot.com', + 'api.enterprise.githubcopilot.com' +] as const export const BASE_URL_NAMES: ReadonlySet = new Set(['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'COPILOT_PROVIDER_BASE_URL']) const HOST = /^([a-z0-9-]+\.)+[a-z]{2,63}$/ @@ -81,8 +89,8 @@ export type CredentialTarget = { } & CredentialPolicy export type CredentialPolicy = { - /** Only these requests may carry the key (exact method, path up to an optional query). Absent: any. */ - paths?: readonly { method: string; path: string }[] + /** Only these requests may carry the key (method, then the path up to its query: exact, or a prefix). Absent: any. */ + paths?: readonly { method: string; path: string; prefix?: true }[] /** * The host stays reachable without the placeholder. Cursor trades the key for a short-lived access * token and sends that on every later call, so a 403 for unclaimed requests would break it. @@ -93,6 +101,8 @@ export type CredentialPolicy = { * headers that set state either); anything else is refused. */ keepResponseFields?: readonly string[] + /** More ways the client may send the key in a header (gh-style `token `). */ + altHeaderFormats?: Record string)[]> } const bearer = (value: string) => `Bearer ${value}` @@ -102,11 +112,15 @@ const raw = (value: string) => value export type ValueScopes = Readonly> type CredentialSpec = CredentialPolicy & { + /** Hosts (of the default ones) that stay open without the placeholder. */ + allowUnclaimedHosts?: readonly string[] + /** Per-host request limits, over `paths`. */ + pathsByHost?: Readonly>> secret: string /** Env var that may point this key at a custom host (honoured only from the key's own scope). */ baseUrl?: string - /** Host without a base URL; null: the key is only routed together with its base URL. */ - defaultHost: string | null + /** Hosts without a base URL (a base URL replaces them); empty: only routed with its base URL. */ + defaultHosts: readonly string[] headers: Record string> } @@ -120,23 +134,23 @@ const CREDENTIALS: readonly CredentialSpec[] = [ { secret: 'ANTHROPIC_API_KEY', baseUrl: 'ANTHROPIC_BASE_URL', - defaultHost: 'api.anthropic.com', + defaultHosts: ['api.anthropic.com'], headers: { 'x-api-key': raw, authorization: bearer } }, { secret: 'ANTHROPIC_AUTH_TOKEN', baseUrl: 'ANTHROPIC_BASE_URL', - defaultHost: 'api.anthropic.com', + defaultHosts: ['api.anthropic.com'], headers: { authorization: bearer, 'x-api-key': raw } }, // AI SDK clients (OpenCode's `vercel/...` models) read the gateway key directly. - { secret: 'AI_GATEWAY_API_KEY', defaultHost: AI_GATEWAY_HOST, headers: { authorization: bearer, 'x-api-key': raw } }, - { secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHost: 'api.openai.com', headers: { authorization: bearer } }, - { secret: 'GEMINI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } }, - { secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } }, + { secret: 'AI_GATEWAY_API_KEY', defaultHosts: [AI_GATEWAY_HOST], headers: { authorization: bearer, 'x-api-key': raw } }, + { secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHosts: ['api.openai.com'], headers: { authorization: bearer } }, + { secret: 'GEMINI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } }, + { secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } }, { secret: 'CURSOR_API_KEY', - defaultHost: CURSOR_API_HOST, + defaultHosts: [CURSOR_API_HOST], headers: { authorization: bearer }, paths: [{ method: 'POST', path: '/auth/exchange_user_api_key' }], allowUnclaimed: true, @@ -144,16 +158,37 @@ const CREDENTIALS: readonly CredentialSpec[] = [ // and exchanges the key again when it expires; with one it would persist a long-lived credential. keepResponseFields: ['accessToken'] }, + // Gemini CLI and the Google GenAI SDK read GOOGLE_API_KEY for the Gemini API and for Vertex AI + // express mode (GOOGLE_GENAI_USE_VERTEXAI=true). + { secret: 'GOOGLE_API_KEY', defaultHosts: [GEMINI_HOST, VERTEX_HOST], headers: { 'x-goog-api-key': raw } }, + { + // A user's own GitHub token for Copilot CLI (fine-grained PAT with Copilot Requests). Copilot + // checks it on api.github.com, then calls its API with it. The Copilot hosts stay open without + // the placeholder: a session token Copilot gets back is sent there too. + secret: 'COPILOT_GITHUB_TOKEN', + defaultHosts: ['api.github.com', ...COPILOT_API_HOSTS], + headers: { authorization: bearer }, + altHeaderFormats: { authorization: [(value: string) => `token ${value}`] }, + allowUnclaimedHosts: [...COPILOT_API_HOSTS], + // On GitHub's API the user's token checks Copilot access and nothing else: the rest of the API + // (repos, gists, ...) stays out of reach of whatever runs in the workspace. + pathsByHost: { + 'api.github.com': [ + { method: 'GET', path: '/user' }, + { method: 'GET', path: '/copilot_internal/', prefix: true } + ] + } + }, { secret: 'COPILOT_PROVIDER_API_KEY', baseUrl: 'COPILOT_PROVIDER_BASE_URL', - defaultHost: null, + defaultHosts: [], headers: { authorization: bearer, 'api-key': raw } }, { secret: 'COPILOT_PROVIDER_BEARER_TOKEN', baseUrl: 'COPILOT_PROVIDER_BASE_URL', - defaultHost: null, + defaultHosts: [], headers: { authorization: bearer } } ] @@ -167,7 +202,7 @@ export function credentialShape(secret: string): Omit if (!spec) { return null } - const { baseUrl: _baseUrl, defaultHost: _defaultHost, ...shape } = spec + const { baseUrl: _baseUrl, defaultHosts: _defaultHosts, allowUnclaimedHosts: _openHosts, pathsByHost: _paths, ...shape } = spec return shape } @@ -175,25 +210,43 @@ export function credentialShape(secret: string): Omit * A base URL only redirects a credential from the same scope: a member's personal base URL must * never route the org's shared key to a host the member picked (the proxy would hand it over). */ -function hostFor(env: Record, spec: CredentialSpec, scopes?: ValueScopes): string | null { +function hostsFor(env: Record, spec: CredentialSpec, scopes?: ValueScopes): readonly string[] { const base = spec.baseUrl ? env[spec.baseUrl] : undefined if (!base || !spec.baseUrl) { - return spec.defaultHost + return spec.defaultHosts } if (scopes && scopes[spec.baseUrl] !== scopes[spec.secret]) { - return spec.defaultHost + return spec.defaultHosts } - return baseUrlHost(base) + const host = baseUrlHost(base) + return host ? [host] : [] } -/** Where each model credential in `env` is used, so the egress proxy can swap it in on that host only. */ +/** How a credential is sent and policed on one of its hosts. */ +export function credentialTarget(secret: string, host: string): CredentialTarget | null { + const spec = CREDENTIALS.find((candidate) => candidate.secret === secret) + const shape = credentialShape(secret) + if (!spec || !shape) { + return null + } + const { allowUnclaimed: _open, ...rest } = shape + const open = spec.allowUnclaimed || spec.allowUnclaimedHosts?.includes(host) + const paths = spec.pathsByHost?.[host] ?? spec.paths + return { ...rest, ...(open ? { allowUnclaimed: true as const } : {}), ...(paths ? { paths } : {}), host } +} + +/** Where each model credential in `env` is used, so the egress proxy can swap it in on those hosts only. */ export function credentialTargets(env: Record, scopes?: ValueScopes): CredentialTarget[] { const targets: CredentialTarget[] = [] for (const spec of CREDENTIALS) { - const host = env[spec.secret] ? hostFor(env, spec, scopes) : null - const shape = host ? credentialShape(spec.secret) : null - if (host && shape) { - targets.push({ ...shape, host }) + if (!env[spec.secret]) { + continue + } + for (const host of hostsFor(env, spec, scopes)) { + const target = credentialTarget(spec.secret, host) + if (target) { + targets.push(target) + } } } return targets diff --git a/cloud/apps/sandbox-control/src/read-snapshots.ts b/cloud/apps/sandbox-control/src/read-snapshots.ts new file mode 100644 index 00000000000..c11b9959af9 --- /dev/null +++ b/cloud/apps/sandbox-control/src/read-snapshots.ts @@ -0,0 +1,459 @@ +// Read a sleeping workspace without waking it (gap 5), end-to-end encrypted: +// PUT /v1/reader-keys {publicKeyB64, deviceLabel, deviceKind} register this device's X25519 key +// GET /v1/reader-keys the caller's live keys +// DELETE /v1/reader-keys/:id +// GET /v1/team/workspaces/:id/read-snapshot?keyId=rk_… the body + only that key's wrapped key +// At every drain the control plane asks the VM (image/vm/orca-sandbox-read-snapshot) to seal a +// compact snapshot to the reader keys allowed to open the workspace, and stores the ciphertext. +// D1, backups and logs hold only ciphertext and never a reader secret. Trust model: like W4 grants, +// the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to +// add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning +// (removal, private, revoke) deletes wrapped keys at once, without the VM. +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { ensureEntryPoints } from './golden-images' +import type { LifecycleDeps } from './lifecycle' +import type { SandboxRow } from './store' +import { WorkspaceError, canOpen, isOwner } from './workspaces' + +export const READ_SNAPSHOT_COMMAND = '/opt/orca/bin/orca-sandbox-read-snapshot' +const READ_SNAPSHOT_TIMEOUT_MS = 40_000 +/** Above this the VM trims the payload; anything bigger here is refused (D1 rows stay small). */ +export const MAX_READ_SNAPSHOT_BYTES = 220_000 +/** A sleeping workspace is sealed to at most this many devices (newest first). */ +export const MAX_READ_RECIPIENTS = 64 +const MAX_KEYS_PER_USER = 12 + +const B64_32 = z + .string() + .regex(/^[A-Za-z0-9+/]{43}=$/) + .refine((value) => atob(value).length === 32, 'expected 32 bytes') +const B64_NONCE = z.string().regex(/^[A-Za-z0-9+/]{16}$/) +const KEY_ID = /^rk_[0-9a-f]{24}$/ +const SNAPSHOT_ID = /^rsn_[0-9a-f]{24}$/ + +export const ReaderKeyRequestSchema = z + .object({ + publicKeyB64: B64_32, + deviceLabel: z.string().trim().min(1).max(80).regex(/^[^\u0000-\u001f]+$/), + deviceKind: z.enum(['desktop', 'mobile']) + }) + .strict() + +export type ReaderKeyRow = { + id: string + user_id: string + account_id: string + dev: number + public_key: string + device_kind: string + device_label: string + device_session_id: string | null + created_at: number + last_seen_at: number + revoked_at: number | null + revoked_by: string | null +} + +export class ReadSnapshotRouteError extends Error { + constructor( + readonly code: 'not_found' | 'no_snapshot' | 'not_sealed_for_key' | 'invalid_request', + readonly status: number + ) { + super(code) + } +} + +function randomHexId(prefix: string): string { + const bytes = crypto.getRandomValues(new Uint8Array(12)) + return `${prefix}_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}` +} + +function readerKeyView(row: ReaderKeyRow) { + return { + id: row.id, + deviceKind: row.device_kind, + deviceLabel: row.device_label, + createdAt: row.created_at, + lastSeenAt: row.last_seen_at + } +} + +/** Idempotent per (caller, public key): the same id comes back and lastSeenAt moves. */ +export async function registerReaderKey( + db: D1Database, + caller: SandboxCaller, + body: z.infer, + now: number +): Promise { + const live = await db + .prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND public_key = ? AND revoked_at IS NULL') + .bind(caller.accountId, caller.userId, body.publicKeyB64) + .first() + if (live) { + // A phone's key must stay bound to the session that registered it; another session (or a + // desktop token) presenting the same public key is refused rather than rebinding it. + if ((live.device_session_id ?? null) !== (caller.deviceSessionId ?? null)) { + throw new ReadSnapshotRouteError('invalid_request', 409) + } + await db + .prepare('UPDATE reader_keys SET last_seen_at = ?, device_label = ? WHERE id = ?') + .bind(now, body.deviceLabel, live.id) + .run() + return { ...live, last_seen_at: now, device_label: body.deviceLabel } + } + const row: ReaderKeyRow = { + id: randomHexId('rk'), + user_id: caller.userId, + account_id: caller.accountId, + dev: caller.dev ? 1 : 0, + public_key: body.publicKeyB64, + // A phone token is a phone, whatever it claims. + device_kind: caller.deviceSessionId ? 'mobile' : body.deviceKind, + device_label: body.deviceLabel, + device_session_id: caller.deviceSessionId ?? null, + created_at: now, + last_seen_at: now, + revoked_at: null, + revoked_by: null + } + const inserted = await db + .prepare( + `INSERT INTO reader_keys (id, user_id, account_id, dev, public_key, device_kind, device_label, device_session_id, created_at, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING` + ) + .bind(row.id, row.user_id, row.account_id, row.dev, row.public_key, row.device_kind, row.device_label, row.device_session_id, now, now) + .run() + if (inserted.meta.changes === 0) { + // A concurrent PUT of the same key won the race: answer with its row. + return registerReaderKey(db, caller, body, now) + } + // Bounded per member: the least recently seen keys beyond the cap are retired. + const { results: stale } = await db + .prepare( + `SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL + ORDER BY last_seen_at DESC, created_at DESC LIMIT -1 OFFSET ?` + ) + .bind(caller.accountId, caller.userId, MAX_KEYS_PER_USER) + .all<{ id: string }>() + if (stale.length > 0) { + await revokeReaderKeys(db, stale.map((s) => s.id), 'system:key_limit', now) + } + return row +} + +/** Revokes the keys and deletes every wrapped snapshot key they had (no VM involved). */ +export async function revokeReaderKeys(db: D1Database, ids: readonly string[], by: string, now: number): Promise { + let revoked = 0 + for (let i = 0; i < ids.length; i += 50) { + const chunk = ids.slice(i, i + 50) + const marks = chunk.map(() => '?').join(',') + const [update] = await db.batch([ + db.prepare(`UPDATE reader_keys SET revoked_at = ?, revoked_by = ? WHERE id IN (${marks}) AND revoked_at IS NULL`).bind(now, by, ...chunk), + db.prepare(`DELETE FROM read_snapshot_keys WHERE key_id IN (${marks})`).bind(...chunk) + ]) + revoked += update?.meta.changes ?? 0 + } + return revoked +} + +async function revokeWhere(db: D1Database, where: string, binds: (string | number)[], by: string, now: number): Promise { + const { results } = await db + .prepare(`SELECT id FROM reader_keys WHERE ${where} AND revoked_at IS NULL`) + .bind(...binds) + .all<{ id: string }>() + return revokeReaderKeys(db, results.map((r) => r.id), by, now) +} + +/** A member left the account: none of their devices may read any of its workspaces again. */ +export function revokeMemberReaderKeys(db: D1Database, accountId: string, userId: string, now: number): Promise { + return revokeWhere(db, 'account_id = ? AND user_id = ?', [accountId, userId], 'system:member_removed', now) +} + +/** A phone was unpaired or revoked: its reader key goes with it. */ +export function revokeDeviceSessionReaderKeys(db: D1Database, deviceSessionId: string, now: number): Promise { + return revokeWhere(db, 'device_session_id = ?', [deviceSessionId], 'system:device_revoked', now) +} + +/** + * Visibility or owner changed: drop every wrapped key of this workspace whose holder is not its + * (new) owner. Team members get back in at the next drain if it becomes team-visible again. + */ +export async function pruneReadSnapshotToOwner(db: D1Database, row: SandboxRow): Promise { + const result = await db + .prepare( + `DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id NOT IN + (SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL)` + ) + .bind(row.id, row.account_id, row.user_id) + .run() + return result.meta.changes +} + +export async function deleteReadSnapshot(db: D1Database, sandboxId: string): Promise { + await db.batch([ + db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(sandboxId), + db.prepare('DELETE FROM read_snapshots WHERE sandbox_id = ?').bind(sandboxId) + ]) +} + +/** The live keys allowed to open this workspace right now (owner; every member when team-visible). */ +export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number): Promise<{ id: string; public_key: string }[]> { + if (row.archived_at !== null) { + return [] + } + const team = row.visibility === 'team' + const { results } = await db + .prepare( + `SELECT k.id, k.public_key FROM reader_keys k + LEFT JOIN device_sessions d ON d.id = k.device_session_id + WHERE k.account_id = ? AND k.revoked_at IS NULL ${team ? '' : 'AND k.user_id = ?'} + -- A phone key counts only while its device session is live (not revoked, not expired). + AND (k.device_session_id IS NULL OR (d.revoked_at IS NULL AND d.expires_at > ?)) + ORDER BY (k.user_id = ?) DESC, k.last_seen_at DESC LIMIT ?` + ) + .bind(...(team ? [row.account_id] : [row.account_id, row.user_id]), now, row.user_id, MAX_READ_RECIPIENTS) + .all<{ id: string; public_key: string }>() + return results +} + +const VmOutputSchema = z + .object({ + v: z.literal(1), + snapshotId: z.string().regex(SNAPSHOT_ID), + workspaceId: z.string(), + nonceB64: B64_NONCE, + ciphertextB64: z.string().regex(/^[A-Za-z0-9+/]+=*$/).max(MAX_READ_SNAPSHOT_BYTES), + recipients: z + .array( + z + .object({ + keyId: z.string().regex(KEY_ID), + ephemeralPublicKeyB64: B64_32, + nonceB64: B64_NONCE, + wrappedKeyB64: z.string().regex(/^[A-Za-z0-9+/]{64}$/) + }) + .strict() + ) + .max(MAX_READ_RECIPIENTS), + // Timing only: nothing about the plaintext's shape is logged here. + stats: z.object({ collectMs: z.number().int().min(0).max(600_000) }).strict().optional() + }) + .strict() + +type CaptureOutcome = + | { captured: true; snapshotId: string; recipients: number; bytes: number; stats?: { collectMs: number } } + | { captured: false; reason: string } +export type CaptureResult = CaptureOutcome & { ms: number } + +/** + * Best effort, before orcad drains: the VM gathers and seals the snapshot (it never leaves the VM + * in plaintext); this stores the ciphertext and replaces the previous one. A failure keeps the old + * snapshot and never blocks the sleep. + */ +export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, reason: string): Promise { + const started = deps.now() + const done = (r: CaptureOutcome): CaptureResult => { + const result: CaptureResult = { ...r, ms: deps.now() - started } + console.log(JSON.stringify({ event: 'read_snapshot', sandboxId: row.id, reason, ...result })) + return result + } + if (!row.session_id) { + return done({ captured: false, reason: 'no_session' }) + } + const keys = await readerKeysFor(deps.db, row, deps.now()) + if (keys.length === 0) { + return done({ captured: false, reason: 'no_reader_keys' }) + } + const snapshotId = randomHexId('rsn') + const sessionId = row.session_id + let stdout: string + try { + // VMs booted from an older image get the current entry points (this script) first. + await ensureEntryPoints(deps, sessionId).catch(() => undefined) + const result = await deps.provider.runCommand(sessionId, { + command: READ_SNAPSHOT_COMMAND, + env: { + ORCA_READ_SNAPSHOT_ID: snapshotId, + ORCA_READ_WORKSPACE_ID: row.id, + ORCA_READ_REASON: reason, + ORCA_READ_RECIPIENTS: JSON.stringify(keys.map((k) => ({ keyId: k.id, publicKeyB64: k.public_key }))) + }, + timeoutMs: READ_SNAPSHOT_TIMEOUT_MS + }) + if (result.exitCode !== 0) { + return done({ captured: false, reason: `exit_${result.exitCode}:${result.stderr.trim().slice(0, 120)}` }) + } + stdout = result.stdout + } catch (error) { + return done({ captured: false, reason: `run_failed:${String(error).slice(0, 120)}` }) + } + let parsed: z.infer + try { + const line = stdout.trim().split('\n').pop() ?? '' + const out = VmOutputSchema.safeParse(JSON.parse(line)) + if (!out.success) { + return done({ captured: false, reason: 'bad_output' }) + } + parsed = out.data + } catch { + return done({ captured: false, reason: 'bad_output' }) + } + const asked = new Set(keys.map((k) => k.id)) + if (parsed.snapshotId !== snapshotId || parsed.workspaceId !== row.id || parsed.recipients.some((r) => !asked.has(r.keyId))) { + return done({ captured: false, reason: 'mismatched_output' }) + } + const now = deps.now() + const statements = [ + deps.db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(row.id), + deps.db + .prepare( + `INSERT INTO read_snapshots (sandbox_id, snapshot_id, stored_at, bytes, nonce, ciphertext) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(sandbox_id) DO UPDATE SET snapshot_id = excluded.snapshot_id, stored_at = excluded.stored_at, + bytes = excluded.bytes, nonce = excluded.nonce, ciphertext = excluded.ciphertext` + ) + .bind(row.id, snapshotId, now, parsed.ciphertextB64.length, parsed.nonceB64, parsed.ciphertextB64), + ...parsed.recipients.map((r) => + deps.db + .prepare( + 'INSERT INTO read_snapshot_keys (sandbox_id, key_id, snapshot_id, ephemeral_public_key, nonce, wrapped_key) VALUES (?, ?, ?, ?, ?, ?)' + ) + .bind(row.id, r.keyId, snapshotId, r.ephemeralPublicKeyB64, r.nonceB64, r.wrappedKeyB64) + ), + // A key revoked (or a member removed) while the VM was sealing must not slip back in. + deps.db + .prepare( + `DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id IN (SELECT id FROM reader_keys WHERE revoked_at IS NOT NULL)` + ) + .bind(row.id) + ] + await deps.db.batch(statements) + // The workspace may have been made private while sealing: re-apply the current rule. + const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first() + if (current && current.visibility !== 'team') { + await pruneReadSnapshotToOwner(deps.db, current) + } + return done({ + captured: true, + snapshotId, + recipients: parsed.recipients.length, + bytes: parsed.ciphertextB64.length, + ...(parsed.stats ? { stats: parsed.stats } : {}) + }) +} + +/** For workspace views: when each workspace's snapshot was stored (only rows the caller can open). */ +export async function readSnapshotTimes(db: D1Database, ids: readonly string[]): Promise> { + const out = new Map() + for (let i = 0; i < ids.length; i += 90) { + const chunk = ids.slice(i, i + 90) + if (chunk.length === 0) { + continue + } + const { results } = await db + .prepare(`SELECT sandbox_id, stored_at FROM read_snapshots WHERE sandbox_id IN (${chunk.map(() => '?').join(',')})`) + .bind(...chunk) + .all<{ sandbox_id: string; stored_at: number }>() + for (const r of results) { + out.set(r.sandbox_id, r.stored_at) + } + } + return out +} + +export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) { + // Belt and braces over canOpen: a private workspace's snapshot opens only for its owner. + if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) { + throw new WorkspaceError('not_found') + } + if (!keyId || !KEY_ID.test(keyId)) { + throw new ReadSnapshotRouteError('invalid_request', 400) + } + // The key must be the caller's own, live one: nobody fetches another member's wrapped key. + const key = await db + .prepare('SELECT * FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL') + .bind(keyId, caller.accountId, caller.userId) + .first() + // A phone reads only with its own key (least privilege; desktop tokens have no device session). + if (!key || (caller.deviceSessionId && key.device_session_id !== caller.deviceSessionId)) { + throw new ReadSnapshotRouteError('invalid_request', 400) + } + const snapshot = await db + .prepare('SELECT * FROM read_snapshots WHERE sandbox_id = ?') + .bind(row.id) + .first<{ snapshot_id: string; stored_at: number; nonce: string; ciphertext: string }>() + if (!snapshot) { + throw new ReadSnapshotRouteError('no_snapshot', 404) + } + const wrapped = await db + .prepare('SELECT * FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id = ? AND snapshot_id = ?') + .bind(row.id, keyId, snapshot.snapshot_id) + .first<{ ephemeral_public_key: string; nonce: string; wrapped_key: string }>() + if (!wrapped) { + throw new ReadSnapshotRouteError('not_sealed_for_key', 404) + } + if (now - key.last_seen_at > 60 * 60_000) { + await db.prepare('UPDATE reader_keys SET last_seen_at = ? WHERE id = ?').bind(now, key.id).run() + } + return { + snapshot: { + v: 1 as const, + snapshotId: snapshot.snapshot_id, + workspaceId: row.id, + storedAt: snapshot.stored_at, + nonceB64: snapshot.nonce, + ciphertextB64: snapshot.ciphertext, + recipient: { + keyId, + ephemeralPublicKeyB64: wrapped.ephemeral_public_key, + nonceB64: wrapped.nonce, + wrappedKeyB64: wrapped.wrapped_key + } + } + } +} + + +export type ReaderKeysRouteDeps = { db: D1Database; caller: SandboxCaller; now: number; readJson: () => Promise } + +export async function handleReaderKeysRoute(request: Request, url: URL, deps: ReaderKeysRouteDeps): Promise { + const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { 'cache-control': 'no-store' } }) + const match = /^\/v1\/reader-keys(?:\/(rk_[0-9a-f]{24}))?$/.exec(url.pathname) + if (!match) { + return json({ error: 'not_found' }, 404) + } + const [, id] = match + try { + if (!id && request.method === 'PUT') { + const body = ReaderKeyRequestSchema.safeParse(await deps.readJson()) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return json({ readerKey: readerKeyView(await registerReaderKey(deps.db, deps.caller, body.data, deps.now)) }) + } + if (!id && request.method === 'GET') { + const { results } = await deps.db + .prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL ORDER BY last_seen_at DESC') + .bind(deps.caller.accountId, deps.caller.userId) + .all() + return json({ readerKeys: results.map(readerKeyView) }) + } + if (id && request.method === 'DELETE') { + const owned = await deps.db + .prepare('SELECT id FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL') + .bind(id, deps.caller.accountId, deps.caller.userId) + .first<{ id: string }>() + if (!owned) { + return json({ error: 'not_found' }, 404) + } + await revokeReaderKeys(deps.db, [id], deps.caller.userId, deps.now) + return json({ ok: true }) + } + return json({ error: 'not_found' }, 404) + } catch (error) { + if (error instanceof ReadSnapshotRouteError) { + return json({ error: error.code }, error.status) + } + throw error + } +} diff --git a/cloud/apps/sandbox-control/src/routines/runs.ts b/cloud/apps/sandbox-control/src/routines/runs.ts index 534eaaec818..4af4ed04593 100644 --- a/cloud/apps/sandbox-control/src/routines/runs.ts +++ b/cloud/apps/sandbox-control/src/routines/runs.ts @@ -114,6 +114,23 @@ function detailOf(run: RunRow): RunDetail { } } +/** Untrusted context in a prompt, in UTF-8 bytes; the whole prompt stays far below one argv entry's 128 KiB. */ +export const MAX_CONTEXT_BYTES = 48 * 1024 + +function truncateUtf8(text: string, maxBytes: number): string { + let bytes = 0 + let end = 0 + for (const char of text) { + const size = new TextEncoder().encode(char).length + if (bytes + size > maxBytes) { + break + } + bytes += size + end += char.length + } + return text.slice(0, end) +} + /** The agent's full prompt: the routine's prompt, what happens to its output, and fenced untrusted context. */ export function composePrompt(routine: Pick, detail: RunDetail): string { const parts = [routine.prompt.trim()] @@ -128,6 +145,14 @@ export function composePrompt(routine: Pick MAX_CONTEXT_BYTES) { + context = JSON.stringify(detail.context) + } + if (new TextEncoder().encode(context).length > MAX_CONTEXT_BYTES) { + context = `${truncateUtf8(context, MAX_CONTEXT_BYTES)}\n[truncated]` + } // A payload cannot close the fence early. context = context.replaceAll('', '<\\/untrusted_context>') parts.push( diff --git a/cloud/apps/sandbox-control/src/routines/vm-runner.ts b/cloud/apps/sandbox-control/src/routines/vm-runner.ts index 6354ba9d63d..aaf9f5c93a9 100644 --- a/cloud/apps/sandbox-control/src/routines/vm-runner.ts +++ b/cloud/apps/sandbox-control/src/routines/vm-runner.ts @@ -95,9 +95,43 @@ codex) --output-last-message "$D/last.txt" - >"$D/agent.out" 2>"$D/agent.err" <"$D/prompt.txt" || code=$? summary="$(head -c 6000 "$D/last.txt" 2>/dev/null || true)" ;; +opencode) + # "--" ends the flags, so a prompt starting with "-" stays the message. + timeout --kill-after=20 "$limit" opencode run --auto --format json -- "$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" + ;; +gemini) + # --prompt=TEXT, not "-p TEXT": a prompt starting with "-" would read as a flag. + timeout --kill-after=20 "$limit" gemini --yolo --output-format json --prompt="$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" + if [ "$code" = 0 ] && [ -n "$(jq -r '.error // empty' "$D/agent.out" 2>/dev/null)" ]; then code=1; fi + ;; +cursor) + timeout --kill-after=20 "$limit" cursor-agent --print --force --trust --output-format json -- "$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" /dev/null | head -c 6000)" + ;; +copilot) + # --silent: only the agent's response, no tool output or stats. + timeout --kill-after=20 "$limit" copilot --allow-all --silent --prompt="$(cat "$D/prompt.txt")" \ + >"$D/agent.out" 2>"$D/agent.err" /dev/null || true)" + ;; *) code=2; note=unknown_agent; finish ;; esac [ -n "$summary" ] || summary="$(tail -c 2000 "$D/agent.out" 2>/dev/null || true)" +# The summary can be posted publicly (comment / PR body): no session secret value leaves in it, even +# one an agent printed (AWS keys and plain env secrets are real values in this VM). +summary="$(ORCA_SUMMARY="$summary" node -e ' +let s = process.env.ORCA_SUMMARY || "" +for (const name of (process.env.ORCA_SESSION_ENV_NAMES || "").split(/\s+/)) { + const value = process.env[name] + if (value && value.length >= 8) s = s.split(value).join("[redacted]") +} +process.stdout.write(s)' 2>/dev/null)" || summary="" echo "routine: agent exit $code" if [ "$code" = 0 ] && [ "$post" = pr ] && [ -n "$start_sha" ]; then git add -A >/dev/null 2>&1 || true diff --git a/cloud/apps/sandbox-control/src/sandbox-provider.ts b/cloud/apps/sandbox-control/src/sandbox-provider.ts index 8d31727ab3a..9f9852141d6 100644 --- a/cloud/apps/sandbox-control/src/sandbox-provider.ts +++ b/cloud/apps/sandbox-control/src/sandbox-provider.ts @@ -27,6 +27,18 @@ export type ProviderSession = { timeoutMs: number } +/** A session's measured usage (internal fair-use review only; never metered or sent to billing). */ +export type ProviderSessionUsage = { + sessionId: string + status: ProviderSessionStatus + /** Vercel reports this only once the VM has stopped. */ + activeCpuMs: number | null + durationMs: number | null + vcpus: number | null + memoryMb: number | null + stoppedAt: number | null +} + export type ProviderRoute = { port: number; url: string } export type ProviderSandboxState = { @@ -87,7 +99,9 @@ export type SandboxProviderApi = { createSandbox(params: CreateSandboxParams): Promise /** `resume: true` boots a stopped persistent sandbox from its latest snapshot. Null when absent. */ getSandbox(name: string, options: { resume: boolean }): Promise - stopSession(sessionId: string): Promise<{ snapshotId: string | null }> + stopSession(sessionId: string): Promise<{ snapshotId: string | null; usage?: ProviderSessionUsage | null }> + /** A session's usage, stopped or not. Null when the provider no longer knows it. Optional: CPU review is best-effort. */ + getSessionUsage?(sessionId: string): Promise extendTimeout(sessionId: string, durationMs: number): Promise updateNetworkPolicy(sessionId: string, policy: NetworkPolicy): Promise /** Sets the full exposed-port list on the sandbox (live on a running session); returns its routes. */ diff --git a/cloud/apps/sandbox-control/src/secret-egress.ts b/cloud/apps/sandbox-control/src/secret-egress.ts index de81ea5dc87..19a9553b8b0 100644 --- a/cloud/apps/sandbox-control/src/secret-egress.ts +++ b/cloud/apps/sandbox-control/src/secret-egress.ts @@ -5,7 +5,7 @@ // Codex) hang under Vercel transform rules, so these hosts always take the forwardURL path through // /v1/egress/proxy, the same path api.github.com uses. Placeholders are not secrets: the proxy // authenticates the sandbox by Vercel's OIDC token, the placeholder only marks which header to swap. -import { SWAPPED_CREDENTIALS, credentialShape, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env' +import { SWAPPED_CREDENTIALS, credentialTarget, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env' import type { SandboxRow } from './store' export type SecretEgressHost = CredentialTarget @@ -24,21 +24,28 @@ export function encodeEgressSecretHosts(targets: readonly CredentialTarget[]): s /** Credential routes recorded on the row for this session. */ export function egressSecretHosts(row: Pick): SecretEgressHost[] { - const recorded: Record = {} + const recorded = new Map>() for (const entry of (row.egress_secret_hosts ?? '').split(',').filter(Boolean)) { const at = entry.indexOf('@') const [secret, host] = at === -1 ? [LEGACY_HOSTS[entry], entry] : [entry.slice(0, at), entry.slice(at + 1)] if (secret && host) { - recorded[secret] = host + recorded.set(secret, (recorded.get(secret) ?? new Set()).add(host)) } } // Header shapes and policies come from the code, never from the row. The base URL value is only - // used to pick the default-vs-custom host, and the recorded host is what was allowlisted at boot. - return SWAPPED_CREDENTIALS.flatMap((secret) => { - const host = recorded[secret] - const shape = host ? credentialShape(secret) : null - return host && shape ? [{ ...shape, host }] : [] - }) + // used to pick the default-vs-custom host, and the recorded hosts are what was allowlisted at boot. + return SWAPPED_CREDENTIALS.flatMap((secret) => + [...(recorded.get(secret) ?? [])].flatMap((host) => { + const target = credentialTarget(secret, host) + return target ? [target] : [] + }) + ) +} + +/** Every header value the VM may send a credential's placeholder in. */ +export function placeholderValues(target: CredentialTarget, header: string, placeholder: string): string[] { + const format = target.headers[header] + return format ? [format(placeholder), ...(target.altHeaderFormats?.[header] ?? []).map((alt) => alt(placeholder))] : [] } /** diff --git a/cloud/apps/sandbox-control/src/session-cpu.ts b/cloud/apps/sandbox-control/src/session-cpu.ts new file mode 100644 index 00000000000..4bae566095f --- /dev/null +++ b/cloud/apps/sandbox-control/src/session-cpu.ts @@ -0,0 +1,175 @@ +// U22: internal-only CPU tracking. Customers keep flat sandbox hours; this records each session's +// measured active CPU (Vercel reports it after the VM stops) so operators can spot fair-use outliers. +// Never touches usage_outbox, billing or a customer route, and never blocks a stop: every entry +// point swallows its own failures, and the cron sweep fills in what the stop couldn't read. +import { SANDBOX_VCPUS } from './machine-size' +import type { ProviderSessionUsage, SandboxProviderApi } from './sandbox-provider' +import type { SandboxRow } from './store' + +export const FAIR_USE_WINDOW_DAYS = 30 +/** Average active CPU over vCPU-time above this flags an account for review. */ +export const FAIR_USE_THRESHOLD = 0.6 +/** Sessions older than this without CPU are given up on (the provider may have forgotten them). */ +const SWEEP_WINDOW_MS = 7 * 24 * 60 * 60_000 +const SWEEP_MAX_ATTEMPTS = 12 +const SWEEP_BATCH = 25 + +/** + * Records a session that just ended; idempotent per session id. `usage` is whatever the stop + * answered (often no CPU yet). Never throws. + */ +export async function recordSessionEnd( + db: D1Database, + row: SandboxRow, + endedAt: number, + usage: ProviderSessionUsage | null | undefined, + now: number +): Promise { + try { + if (!row.session_id) { + return + } + const vcpus = positive(usage?.vcpus) ?? SANDBOX_VCPUS + const startedAt = row.session_started_at + const wallMs = positive(usage?.durationMs) ?? (startedAt !== null ? Math.max(0, endedAt - startedAt) : 0) + await db + .prepare( + `INSERT OR IGNORE INTO session_cpu + (session_id, sandbox_id, account_id, user_id, vcpus, memory_mb, wall_ms, started_at, ended_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .bind(row.session_id, row.id, row.account_id, row.user_id ?? null, vcpus, positive(usage?.memoryMb), wallMs, startedAt, endedAt) + .run() + if (usage) { + await applyUsage(db, row.session_id, usage, now) + } + } catch { + // Internal review data only: a D1 or shape problem must never fail the stop. + } +} + +/** Fills CPU on a pending row; first answer wins (re-fetching never rewrites a recorded value). */ +async function applyUsage(db: D1Database, sessionId: string, usage: ProviderSessionUsage, now: number): Promise { + if (usage.activeCpuMs === null || !Number.isFinite(usage.activeCpuMs) || usage.activeCpuMs < 0) { + return false + } + const result = await db + .prepare( + `UPDATE session_cpu SET active_cpu_ms = ?, fetched_at = ?, + wall_ms = COALESCE(?, wall_ms), vcpus = COALESCE(?, vcpus), memory_mb = COALESCE(?, memory_mb) + WHERE session_id = ? AND active_cpu_ms IS NULL` + ) + .bind( + Math.round(usage.activeCpuMs), + now, + positive(usage.durationMs), + positive(usage.vcpus), + positive(usage.memoryMb), + sessionId + ) + .run() + return (result.meta?.changes ?? 0) > 0 +} + +export type SessionCpuSweep = { checked: number; recorded: number; failed: number } + +/** Cron: asks the provider again for recent sessions still missing CPU. Never throws. */ +export async function sweepSessionCpu( + db: D1Database, + provider: Pick, + now: number +): Promise { + const summary: SessionCpuSweep = { checked: 0, recorded: 0, failed: 0 } + if (!provider.getSessionUsage) { + return summary + } + let pending: { session_id: string }[] + try { + pending = ( + await db + .prepare( + `SELECT session_id FROM session_cpu + WHERE active_cpu_ms IS NULL AND ended_at >= ? AND attempts < ? + ORDER BY ended_at DESC LIMIT ?` + ) + .bind(now - SWEEP_WINDOW_MS, SWEEP_MAX_ATTEMPTS, SWEEP_BATCH) + .all<{ session_id: string }>() + ).results + } catch { + return summary + } + for (const { session_id } of pending) { + summary.checked++ + try { + const usage = await provider.getSessionUsage(session_id) + if (usage && (await applyUsage(db, session_id, usage, now))) { + summary.recorded++ + continue + } + } catch { + summary.failed++ + } + await db + .prepare('UPDATE session_cpu SET attempts = attempts + 1 WHERE session_id = ?') + .bind(session_id) + .run() + .catch(() => undefined) + } + return summary +} + +export type FairUseAccount = { + accountId: string + sessions: number + activeCpuMs: number + vcpuMs: number + /** sum(active_cpu_ms) / sum(wall_ms × vcpus), 0..1 (null when there is no measured time). */ + cpuUtilization: number | null + fairUseFlag: boolean +} + +export type FairUseReport = { + windowDays: number + since: number + threshold: number + /** Ended sessions in the window still waiting for the provider's CPU figure (excluded from the math). */ + pendingSessions: number + accounts: FairUseAccount[] +} + +/** Operator-only. Per account over the window; highest utilisation first. */ +export async function fairUseReport(db: D1Database, now: number, windowDays = FAIR_USE_WINDOW_DAYS): Promise { + const since = now - windowDays * 24 * 60 * 60_000 + const { results } = await db + .prepare( + `SELECT account_id, COUNT(*) AS sessions, SUM(active_cpu_ms) AS active_cpu_ms, SUM(wall_ms * vcpus) AS vcpu_ms + FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NOT NULL + GROUP BY account_id` + ) + .bind(since) + .all<{ account_id: string; sessions: number; active_cpu_ms: number; vcpu_ms: number }>() + const pending = await db + .prepare('SELECT COUNT(*) AS n FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NULL') + .bind(since) + .first<{ n: number }>() + const accounts = results + .map((row): FairUseAccount => { + const vcpuMs = Number(row.vcpu_ms) || 0 + const activeCpuMs = Number(row.active_cpu_ms) || 0 + const ratio = vcpuMs > 0 ? activeCpuMs / vcpuMs : null + return { + accountId: row.account_id, + sessions: Number(row.sessions), + activeCpuMs, + vcpuMs, + cpuUtilization: ratio === null ? null : Math.round(ratio * 10_000) / 10_000, + fairUseFlag: ratio !== null && ratio > FAIR_USE_THRESHOLD + } + }) + .sort((a, b) => (b.cpuUtilization ?? -1) - (a.cpuUtilization ?? -1)) + return { windowDays, since, threshold: FAIR_USE_THRESHOLD, pendingSessions: Number(pending?.n ?? 0), accounts } +} + +function positive(value: number | null | undefined): number | null { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null +} diff --git a/cloud/apps/sandbox-control/src/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index 52e3446f882..f0aaca727a9 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -2,6 +2,7 @@ // presets filled in, and with egress placeholders on, model keys swapped for placeholders. The same // answer drives the egress allowlist and the proxy's credential routes, at boot and on refresh. import type { LifecycleDeps } from './lifecycle' +import { signInAgentsFor, withoutSignInCredentials } from './agent-sources' import { deriveProviderEnv, deriveProviderScopes, providerHosts } from './provider-env' import { applySecretPlaceholders, encodeEgressSecretHosts } from './secret-egress' import { resolveSandboxSecrets } from './secrets' @@ -26,8 +27,11 @@ export async function resolvedProviderEnv( keyring: Keyring, row: Pick ): Promise { - const { env: stored, scopes } = await resolveSandboxSecrets(db, keyring, row) - const env = deriveProviderEnv(stored) + const [{ env: stored, scopes }, signIn] = await Promise.all([ + resolveSandboxSecrets(db, keyring, row), + signInAgentsFor(db, row) + ]) + const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn) return { env, scopes: deriveProviderScopes(stored, env, scopes) } } @@ -70,7 +74,9 @@ export async function sessionSecretEnv( return EMPTY } const { env: stored, scopes: storedScopes, skipped } = await resolveSandboxSecrets(deps.db, deps.secrets.keyring, row) - const env = deriveProviderEnv(stored) + // Agents on "Your sign-in" (owner's choice): their credentials never reach this session. + const signIn = await signInAgentsFor(deps.db, row) + const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn) const scopes = deriveProviderScopes(stored, env, storedScopes) const egressAllowHosts = providerHosts(env).join(',') || null // Counts only. diff --git a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts index e8715bcac9b..088c66da934 100644 --- a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts +++ b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts @@ -8,6 +8,7 @@ import { type CommandResult, type ProviderSandboxState, type ProviderSession, + type ProviderSessionUsage, type SandboxProviderApi } from './sandbox-provider' @@ -26,7 +27,13 @@ const Session = z.looseObject({ id: z.string(), status: Status, startedAt: z.number().optional(), - timeout: z.number() + timeout: z.number(), + // Usage fields (SDK 3.9.1). activeCpuDurationMs only appears once the VM has stopped. + vcpus: z.number().optional(), + memory: z.number().optional(), + duration: z.number().optional(), + stoppedAt: z.number().optional(), + activeCpuDurationMs: z.number().optional() }) const Sandbox = z.looseObject({ name: z.string(), @@ -104,6 +111,15 @@ export function createVercelSandboxApi( startedAt: session.startedAt ?? null, timeoutMs: session.timeout }) + const toUsage = (session: z.infer): ProviderSessionUsage => ({ + sessionId: session.id, + status: session.status, + activeCpuMs: session.activeCpuDurationMs ?? null, + durationMs: session.duration ?? null, + vcpus: session.vcpus ?? null, + memoryMb: session.memory ?? null, + stoppedAt: session.stoppedAt ?? null + }) const toState = (body: z.infer): ProviderSandboxState => ({ sandbox: { name: body.sandbox.name, @@ -163,8 +179,22 @@ export function createVercelSandboxApi( async stopSession(sessionId) { const response = await request('POST', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}/stop`) - const body = await json(z.looseObject({ snapshot: Snapshot.optional() }), response) - return { snapshotId: body.snapshot?.id ?? null } + const body = await json(z.looseObject({ snapshot: Snapshot.optional(), session: z.unknown().optional() }), response) + // Usage is internal-only and best-effort: a session shape we can't read never fails the stop. + const session = Session.safeParse(body.session) + return { snapshotId: body.snapshot?.id ?? null, usage: session.success ? toUsage(session.data) : null } + }, + + async getSessionUsage(sessionId) { + try { + const response = await request('GET', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}`) + return toUsage((await json(z.looseObject({ session: Session }), response)).session) + } catch (error) { + if (error instanceof ProviderError && error.status === 404) { + return null + } + throw error + } }, async extendTimeout(sessionId, durationMs) { diff --git a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts index 4bd1b62fa96..e16b826a85c 100644 --- a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts +++ b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts @@ -233,7 +233,7 @@ export async function restartSandbox(deps: LifecycleDeps, row: SandboxRow): Prom throw new LifecycleError('conflict', `sandbox_${current.status}`) } const suspending = await claim(deps, current, { status: 'suspending' }) - const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS }) + const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS, captureRead: false }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) return wake(deps, await claim(deps, stopped, { status: 'resuming' })) } @@ -300,7 +300,7 @@ export async function archiveSandbox( let stopped = row if (row.status === 'running') { // Short drain: the desktop's Sleep normally ran first; a long drain would outlive the caller. - stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS }) + stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS, captureRead: false }) await flushUsage(deps.db, deps.entitlements, deps.now(), row.id) } const ttl = config.archiveTtlMs ?? DEFAULT_ARCHIVE_TTL_MS diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 8052b6075b0..f29d0c52e5c 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -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 { readSnapshotTimes } from './read-snapshots' import { sandboxView } from './wire' import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' @@ -68,6 +69,13 @@ function canManage(caller: SandboxCaller, row: SandboxRow): boolean { return row.account_id === caller.accountId && (row.user_id === caller.userId || isOrgAdmin(caller)) } +/** Owner or a team admin; anyone else gets forbidden (or not_found when they can't see it). */ +export function assertCanManageWorkspace(caller: SandboxCaller, row: SandboxRow): void { + if (!canManage(caller, row)) { + throw new WorkspaceError(canSee(caller, row) ? 'forbidden' : 'not_found', 'owner_or_admin_only') + } +} + /** A row the caller may address by id; anything else is indistinguishable from a missing one. */ export async function requireVisible(db: D1Database, caller: SandboxCaller, id: string): Promise { const row = await getSandbox(db, id) @@ -162,10 +170,11 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted] = await Promise.all([ + const [presence, compute, granted, readAt] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), - activeGrantUsers(db, ids, caller.userId) + activeGrantUsers(db, ids, caller.userId), + readSnapshotTimes(db, ids) ]) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( @@ -199,7 +208,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows access, presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })), // Display names (token `name` claim) for the ids above; the roster wins where it has one. - memberNames + 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 } }) } @@ -281,6 +292,9 @@ export async function patchWorkspace( } else if (!canManage(caller, row)) { throw new WorkspaceError(canSee(caller, row) ? 'forbidden' : 'not_found', 'owner_or_admin_only') } + if (patch.archived === true) { + throw new WorkspaceError('invalid_request', 'archive_via_lifecycle') + } if (patch.visibility === 'team' && !row.account_id.includes('org:')) { // A personal account has no team to share with. throw new WorkspaceError('invalid_request', 'personal_account') @@ -299,7 +313,9 @@ export async function patchWorkspace( ...(patch.branch !== undefined ? { repo_branch: patch.branch } : {}), ...(patch.visibility !== undefined ? { visibility: patch.visibility } : {}), ...(patch.section !== undefined ? { section: patch.section } : {}), - ...(patch.archived !== undefined ? { archived_at: patch.archived ? (row.archived_at ?? now) : null } : {}), + // Archiving is a lifecycle change (archiveSandbox stops the VM, then sets archived_at); this edit + // can only clear a label left by an older label-only archive. + ...(patch.archived === false ? { archived_at: null } : {}), ...(patch.ownerUserId !== undefined ? { user_id: patch.ownerUserId } : {}), ...(patch.tokenUsdMicros !== undefined ? { token_usd_micros: patch.tokenUsdMicros } : {}) }) diff --git a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts index 801615fec1f..9eb50a5b13a 100644 --- a/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts +++ b/cloud/apps/sandbox-control/test/agent-credentials-more.test.ts @@ -4,7 +4,9 @@ import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { compileNetworkPolicy } from '../src/network-policy' -import { credentialTargets } from '../src/provider-env' +import { SWAPPED_CREDENTIALS, credentialTargets } from '../src/provider-env' +import { AGENT_KEY_NAMES } from '../src/secrets' +import { CLOUD_SWAPPED_CREDENTIALS, cloudSecretStoredOnVm } from '../../../../src/shared/cloud-secrets/cloud-secret-rules' import { egressSecretHosts, encodeEgressSecretHosts } from '../src/secret-egress' import { ENV_COMMAND } from '../src/sandbox-vm-commands' import { createHarness } from './harness' @@ -59,6 +61,22 @@ describe('credential routes for Gemini, Cursor and Copilot BYOK', () => { expect(credentialTargets(env, { COPILOT_PROVIDER_BASE_URL: 'user:mia', COPILOT_PROVIDER_API_KEY: 'org:acme' })).toEqual([]) }) + it('routes GOOGLE_API_KEY to the Gemini API and Vertex AI, and COPILOT_GITHUB_TOKEN to GitHub and the Copilot API', () => { + const targets = credentialTargets({ GOOGLE_API_KEY: GEMINI_KEY, COPILOT_GITHUB_TOKEN: COPILOT_KEY }) + expect(targets.map((t) => `${t.secret}@${t.host}${t.allowUnclaimed ? ' open' : ''}`)).toEqual([ + 'GOOGLE_API_KEY@generativelanguage.googleapis.com', + 'GOOGLE_API_KEY@aiplatform.googleapis.com', + 'COPILOT_GITHUB_TOKEN@api.github.com', + 'COPILOT_GITHUB_TOKEN@api.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.individual.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.business.githubcopilot.com open', + 'COPILOT_GITHUB_TOKEN@api.enterprise.githubcopilot.com open' + ]) + // Several hosts per credential survive the row encoding. + const row = { egress_secret_hosts: encodeEgressSecretHosts(targets) } + expect(egressSecretHosts(row).map((t) => `${t.secret}@${t.host}`)).toEqual(targets.map((t) => `${t.secret}@${t.host}`)) + }) + it('round-trips through the row with the policy taken from code, never from the row', () => { const row = { egress_secret_hosts: encodeEgressSecretHosts(credentialTargets({ CURSOR_API_KEY: CURSOR_KEY, GEMINI_API_KEY: GEMINI_KEY })) @@ -174,6 +192,38 @@ describe('egress swap on a sandbox with the new keys', () => { expect(logs.some((line) => line.includes('"event":"egress_swap"') && line.includes('"credential":"GEMINI_API_KEY"'))).toBe(true) }) + it('Copilot token: swapped on api.github.com next to the workspace token, in Bearer or gh-style token form', async () => { + const { h, id, send, upstream } = await setup() + const mia = await h.token('mia', undefined, 'sandbox') + expect((await h.call('PUT', '/v1/secrets/personal/COPILOT_GITHUB_TOKEN', { body: { value: COPILOT_KEY }, bearer: mia })).status).toBe(200) + const ph = `orca-ph-copilot-github-token-${id}` + const policy = [...h.vercel.boxes.values()][0]!.policy + const values = policy.allow['api.github.com']!.flatMap((rule) => ('match' in rule && rule.match?.headers ? [rule.match.headers[0]!.value.exact] : [])) + expect(values).toEqual(expect.arrayContaining([`Bearer ${ph}`, `token ${ph}`, `Bearer orca-ph-${id}`])) + expect(policy.allow['api.github.com']!.at(-1)).toEqual(DENY) + expect(policy.allow['api.individual.githubcopilot.com']!.some((rule) => 'response' in rule)).toBe(false) + for (const header of [`Bearer ${ph}`, `token ${ph}`]) { + expect((await send('api.github.com', 'GET', '/copilot_internal/user', { authorization: header })).status).toBe(200) + expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${COPILOT_KEY}`) + } + expect((await send('api.github.com', 'GET', '/user', { authorization: `Bearer ${ph}` })).status).toBe(200) + // The rest of GitHub's API is out of reach of the user's token, however the path is dressed up. + const sent = upstream.length + for (const [method, path] of [ + ['GET', '/user/repos'], + ['POST', '/copilot_internal/user'], + ['GET', '/copilot_internal/../user/repos'], + ['GET', '/copilot_internal/%2e%2e/user/repos'], + ['GET', '/copilot_internal//../gists'], + ['DELETE', '/repos/acme/app'] + ]) { + expect(await send('api.github.com', method!, path!, { authorization: `Bearer ${ph}` }), path).toEqual({ status: 403, body: 'path_not_allowed' }) + } + expect(upstream).toHaveLength(sent) + expect((await send('api.individual.githubcopilot.com', 'POST', '/chat/completions', { authorization: `Bearer ${ph}` })).status).toBe(200) + expect(upstream.at(-1)!.url).toBe('https://api.individual.githubcopilot.com/chat/completions') + }) + it('Cursor: only the key exchange carries the key, and the refresh token never reaches the VM', async () => { const { id, send, upstream, setReply } = await setup() setReply(() => new Response(JSON.stringify({ accessToken: 'at-short', refreshToken: 'rt-long-lived' }), { status: 200, headers: { 'content-type': 'application/json', 'content-length': '60' } })) @@ -224,3 +274,19 @@ describe('egress swap on a sandbox with the new keys', () => { expect(JSON.stringify(env)).not.toContain(COPILOT_KEY) }) }) + +describe('every agent credential is either swapped or marked "stored on workspace"', () => { + it('leaves no agent key reaching the VM raw without the warning', () => { + const settings = /(_MODEL|_BASE_URL|_REGION|_PROJECT|_PROJECT_ID)$|^CLAUDE_CODE_USE_/ + for (const name of AGENT_KEY_NAMES) { + if (settings.test(name)) { + continue + } + const swapped = SWAPPED_CREDENTIALS.includes(name) + expect(swapped !== cloudSecretStoredOnVm(name), `${name}: swapped=${swapped}`).toBe(true) + } + expect(SWAPPED_CREDENTIALS.includes('COPILOT_GITHUB_TOKEN')).toBe(true) + // The desktop's mirror (what it offers to save from this computer) matches the proxy exactly. + expect([...CLOUD_SWAPPED_CREDENTIALS].sort()).toEqual([...SWAPPED_CREDENTIALS].sort()) + }) +}) diff --git a/cloud/apps/sandbox-control/test/agent-sources.test.ts b/cloud/apps/sandbox-control/test/agent-sources.test.ts new file mode 100644 index 00000000000..390738d0dd7 --- /dev/null +++ b/cloud/apps/sandbox-control/test/agent-sources.test.ts @@ -0,0 +1,138 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { AGENT_CREDENTIAL_NAMES } from '../src/agent-credential-names' +import { ENV_COMMAND, START_COMMAND } from '../src/sandbox-vm-commands' +import { createHarness } from './harness' + +const KEK = Buffer.alloc(32, 7).toString('base64') +const PROXY_URL = 'https://sandbox.test/v1/egress/proxy' +const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa' +const GATEWAY_KEY = 'vck_fake-gateway-key-0000-aaaa-bbbb' + +let logs: string[] = [] +beforeEach(() => { + logs = [] + for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) { + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')) + }) + } +}) +afterEach(() => { + for (const value of [TEAM_KEY, GATEWAY_KEY]) { + expect(logs.join('\n')).not.toContain(value) + } + vi.restoreAllMocks() +}) + +function decode(encoded: string | undefined): Record { + return Object.fromEntries( + (encoded ?? '') + .split('\n') + .filter(Boolean) + .map((line) => { + const at = line.indexOf('=') + return [line.slice(0, at), Buffer.from(line.slice(at + 1), 'base64').toString('utf8')] + }) + ) +} + +async function setup(overrides: Record = {}) { + const h = await createHarness({ SECRETS_KEK: KEK, ...overrides }) + const as = (sub: string, org?: string, role?: string, name?: string) => + h.token(sub, org, 'sandbox', { ...(role ? { orgRole: role } : {}), ...(name ? { name } : {}) }) + const put = (scope: string, name: string, value: string, bearer: string) => + h.call('PUT', `/v1/secrets/${scope}/${name}`, { body: { value }, bearer }) + const lastEnv = (command: string) => decode(h.vercel.commands.filter((c) => c.command === command).at(-1)?.env.ORCA_SECRET_ENV) + return { h, as, put, lastEnv } +} + +describe('per-agent credential names', () => { + it('the Worker mirror matches the shared module verbatim', () => { + const shared = readFileSync(fileURLToPath(new URL('../../../../src/shared/agent-credentials/agent-credential-names.ts', import.meta.url).href), 'utf8') + for (const [agent, names] of Object.entries(AGENT_CREDENTIAL_NAMES)) { + const block = new RegExp(`${agent}: \\[([^\\]]*)\\]`).exec(shared)?.[1] ?? '' + expect(block.match(/'[A-Z0-9_]+'/g)?.map((n) => n.slice(1, -1))).toEqual([...names]) + } + }) +}) + +describe('/v1/agent-sources', () => { + it('implicit default follows key coverage, explicit choices win, and the offer is per person', async () => { + const { h, as, put } = await setup() + const ada = await as('ada', 'acme', 'admin') + const mia = await as('mia', 'acme', 'member') + let view = await h.call('GET', '/v1/agent-sources', { bearer: mia }) + expect(view.body.effective).toEqual({ claude: { source: null, origin: 'implicit' }, codex: { source: null, origin: 'implicit' } }) + expect(view.body.signInOffer).toEqual({ claude: 'unanswered', codex: 'unanswered' }) + await put('org', 'ANTHROPIC_API_KEY', TEAM_KEY, ada) + view = await h.call('GET', '/v1/agent-sources', { bearer: mia }) + expect(view.body.coveredByKey).toEqual({ claude: true, codex: false }) + expect(view.body.effective.claude).toEqual({ source: 'key', origin: 'implicit' }) + view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in' } }) + expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'default' }) + view = await h.call('PUT', '/v1/agent-sources/offer', { bearer: mia, body: { agent: 'claude', answer: 'declined' } }) + expect(view.body.signInOffer.claude).toBe('declined') + // Ada's answers are hers alone. + expect((await h.call('GET', '/v1/agent-sources', { bearer: ada })).body.signInOffer.claude).toBe('unanswered') + expect((await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'gemini', source: 'key' } })).status).toBe(400) + }) + + it('"Your sign-in" keeps that agent\'s credentials (incl. gateway-derived) out of the session, live, and only that agent\'s', async () => { + const { h, as, put, lastEnv } = await setup({ SECRETS_EGRESS_PLACEHOLDERS: 'on', EGRESS_PROXY_URL: PROXY_URL }) + const ada = await as('ada', 'acme', 'admin') + const mia = await as('mia', 'acme', 'member', 'Mia Chen') + await put('org', 'AI_GATEWAY_API_KEY', GATEWAY_KEY, ada) + await put('personal', 'APP_MODE', 'dev', mia) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + expect(Object.keys(lastEnv(START_COMMAND))).toEqual(expect.arrayContaining(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY'])) + const view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } }) + expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'workspace' }) + expect(view.body.owner).toEqual({ userId: 'mia', displayName: 'Mia Chen', isCaller: true }) + const env = lastEnv(ENV_COMMAND) + for (const name of AGENT_CREDENTIAL_NAMES.claude) { + expect(env[name]).toBeUndefined() + } + expect(env.OPENAI_API_KEY).toMatch(/^orca-ph-openai-api-key-/) + expect(env.APP_MODE).toBe('dev') + const row = await h.env.SANDBOX_DB.prepare('SELECT egress_secret_hosts FROM sandboxes WHERE id = ?').bind(id).first<{ egress_secret_hosts: string }>() + expect(row!.egress_secret_hosts).not.toContain('ANTHROPIC') + // Back to the key: it returns in new shells. + await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: null, workspaceId: id } }) + expect(lastEnv(ENV_COMMAND).ANTHROPIC_AUTH_TOKEN).toMatch(/^orca-ph-anthropic-auth-token-/) + }) + + it('a default applies to running sandboxes without an override; only the owner sets a workspace source', async () => { + const { h, as, put, lastEnv } = await setup() + const ada = await as('ada', 'acme', 'admin', 'Ada Lovelace') + const mia = await as('mia', 'acme', 'member') + await put('org', 'OPENAI_API_KEY', 'sk-proj-team-fake-1234-zzzz', ada) + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ada', machineSize: 'standard' }, bearer: ada }) + const id: string = created.body.sandbox.id + await h.call('PUT', '/v1/agent-sources', { bearer: ada, body: { agent: 'codex', source: 'sign-in' } }) + expect(lastEnv(ENV_COMMAND).OPENAI_API_KEY).toBeUndefined() + const forbidden = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'codex', source: 'key', workspaceId: id } }) + expect(forbidden.status).toBe(403) + expect(forbidden.body.reason).toBe('owner_only') + const teammate = await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: mia }) + expect(teammate.body.owner).toEqual({ userId: 'ada', displayName: 'Ada Lovelace', isCaller: false }) + expect(teammate.body.effective.codex).toEqual({ source: 'sign-in', origin: 'default' }) + expect((await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: await as('zed', 'other', 'admin') })).status).toBe(404) + }) + + it('a workspace source set while the sandbox is still starting applies at its first boot (D9)', async () => { + const { h, as, put, lastEnv } = await setup() + const mia = await as('mia') + await put('personal', 'ANTHROPIC_API_KEY', TEAM_KEY, mia) + const id = 'sbx_creating_fake' + await h.env.SANDBOX_DB.prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region, generation, created_at, updated_at) + VALUES (?, 'user:mia', 'mia', 'ws-c', 'vercel', 'orca-test-x', 'creating', 'standard', 'iad1', 0, 1, 1)` + ).bind(id).run() + const put1 = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } }) + expect(put1.status).toBe(200) + expect(put1.body.effective.claude.source).toBe('sign-in') + }) +}) diff --git a/cloud/apps/sandbox-control/test/api.test.ts b/cloud/apps/sandbox-control/test/api.test.ts index 0f830cbfc0d..2644d27d9a1 100644 --- a/cloud/apps/sandbox-control/test/api.test.ts +++ b/cloud/apps/sandbox-control/test/api.test.ts @@ -191,7 +191,7 @@ describe('member removal', () => { const { secret } = (await h.call('POST', '/v1/api-keys', { bearer: member, body: { name: 'bob ci', scopes: ['workspaces:read'] } })).body expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(200) const removed = await h.call('POST', '/v1/internal/members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) - expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0 }) + expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 }) expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(401) }) }) diff --git a/cloud/apps/sandbox-control/test/fake-vercel.ts b/cloud/apps/sandbox-control/test/fake-vercel.ts index abf4af00964..0162e3ed33f 100644 --- a/cloud/apps/sandbox-control/test/fake-vercel.ts +++ b/cloud/apps/sandbox-control/test/fake-vercel.ts @@ -83,6 +83,10 @@ export type FakeVercel = SandboxProviderApi & GoldenImageProviderApi & { snapshotExpirations: Map /** Simulates the provider ending a session at its timeout. */ expire(name: string): void + /** activeCpuDurationMs per session, as GET session reports it once stopped (stop answers without it). */ + sessionCpu: Map + /** GET session fails (provider outage) when set. */ + failSessionUsage: boolean } export function createFakeVercel(now: () => number): FakeVercel { @@ -122,6 +126,8 @@ export function createFakeVercel(now: () => number): FakeVercel { const buildCommands = new Map() const fake: FakeVercel = { + sessionCpu: new Map(), + failSessionUsage: false, boxes, snapshots, commands, @@ -222,7 +228,19 @@ export function createFakeVercel(now: () => number): FakeVercel { }, async stopSession(sessionId) { const box = bySession(sessionId) - return { snapshotId: box.status === 'running' ? stop(box) : null } + const startedAt = box.startedAt + const snapshotId = box.status === 'running' ? stop(box) : null + return { + snapshotId, + usage: { sessionId, status: 'stopped', activeCpuMs: null, durationMs: now() - startedAt, vcpus: box.params.vcpus, memoryMb: box.params.vcpus * 2048, stoppedAt: now() } + } + }, + async getSessionUsage(sessionId) { + if (fake.failSessionUsage) { + throw new ProviderError(503, null) + } + const cpu = fake.sessionCpu.get(sessionId) + return cpu === undefined ? null : { sessionId, status: 'stopped', activeCpuMs: cpu, durationMs: null, vcpus: null, memoryMb: null, stoppedAt: null } }, async extendTimeout(sessionId, durationMs) { const box = bySession(sessionId) diff --git a/cloud/apps/sandbox-control/test/orca-env.test.ts b/cloud/apps/sandbox-control/test/orca-env.test.ts new file mode 100644 index 00000000000..74f5e3d5f48 --- /dev/null +++ b/cloud/apps/sandbox-control/test/orca-env.test.ts @@ -0,0 +1,147 @@ +// orca-env (image/vm/orca-env): prints lines that bring a running shell up to date with the session +// env file. Values must survive quoting exactly (quotes, newlines, $, backslashes) in POSIX shells +// and fish, and names that were removed must be unset. +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const ORCA_ENV = fileURLToPath(new URL('../image/vm/orca-env', import.meta.url).href) + +const TRICKY: Record = { + SINGLE: "it's a 'quoted' value", + DOUBLE: 'say "hi" and \\"escaped\\"', + DOLLAR: '$HOME $(touch /tmp/orca-env-pwned) `id` ${PATH}', + NEWLINES: 'line one\nline two\n\n', + BACKSLASH: 'C:\\path\\to\\ \\n not-a-newline \\', + SEMI: 'a; echo pwned; b && c | d', + EMPTY: '' +} + +let dir = '' +let envFile = '' + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-env-')) + envFile = join(dir, 'session.env') +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function writeSessionEnv(values: Record, extraLines: string[] = []): void { + const lines = Object.entries(values).map(([name, value]) => `${name}=${Buffer.from(value).toString('base64')}`) + writeFileSync(envFile, [...lines, ...extraLines].join('\n') + '\n') +} + +function orcaEnv(args: string[], names = ''): string { + const result = spawnSync('bash', [ORCA_ENV, ...args], { + encoding: 'utf8', + env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: envFile, ORCA_SESSION_ENV_NAMES: names } + }) + expect(result.stderr).toBe('') + expect(result.status).toBe(0) + return result.stdout +} + +/** Runs `script` in `shell` and returns the env it ends with, read back as JSON through node. */ +function envAfter(shell: string, args: string[], script: string, initial: Record = {}) { + const dump = `"${process.execPath}" -e 'process.stdout.write(JSON.stringify(process.env))'` + const result = spawnSync(shell, ['-c', `${script}\n${dump}`], { + encoding: 'utf8', + env: { + PATH: process.env.PATH, + // A throwaway HOME keeps this machine's rc files out of it. + HOME: dir, + ORCA_SESSION_ENV_FILE: envFile, + ORCA_ENV_BIN: ORCA_ENV, + ...initial + } + }) + expect(result.stderr, shell).toBe('') + return JSON.parse(result.stdout) as Record +} + +function hasShell(shell: string): boolean { + return !spawnSync(shell, ['-c', 'true']).error +} + +describe('orca-env', () => { + it('exports every session name with its exact value in bash, sh and zsh', () => { + writeSessionEnv(TRICKY) + for (const shell of ['bash', 'sh', 'zsh'].filter(hasShell)) { + const env = envAfter(shell, [], 'eval "$(bash "$ORCA_ENV_BIN")"') + for (const [name, value] of Object.entries(TRICKY)) { + expect(env[name], `${shell} ${name}`).toBe(value) + } + expect(env.ORCA_SESSION_ENV_NAMES).toBe(Object.keys(TRICKY).join(' ')) + } + }) + + it('exports the exact values in fish', () => { + if (!hasShell('fish')) { + return + } + writeSessionEnv(TRICKY) + const env = envAfter('fish', ['--fish'], 'bash $ORCA_ENV_BIN --fish | source') + for (const [name, value] of Object.entries(TRICKY)) { + expect(env[name], name).toBe(value) + } + }) + + it('unsets names the session env no longer has, in POSIX shells and fish', () => { + writeSessionEnv({ KEPT: 'new' }) + const initial = { KEPT: 'old', GONE: 'stale', MINE: 'untouched', ORCA_SESSION_ENV_NAMES: 'KEPT GONE' } + expect(orcaEnv([], 'KEPT GONE')).toContain('unset GONE\n') + expect(orcaEnv(['--fish'], 'KEPT GONE')).toContain('set -e GONE\n') + const shells: [string, string][] = [['bash', 'eval "$(bash "$ORCA_ENV_BIN")"']] + if (hasShell('fish')) { + shells.push(['fish', 'bash $ORCA_ENV_BIN --fish | source']) + } + for (const [shell, script] of shells) { + const env = envAfter(shell, [], script, initial) + expect(env.KEPT, shell).toBe('new') + expect(env.GONE, shell).toBeUndefined() + expect(env.MINE, shell).toBe('untouched') + expect(env.ORCA_SESSION_ENV_NAMES, shell).toBe('KEPT') + } + }) + + it('skips names the shell hook skips and globs nothing', () => { + writeSessionEnv({ GOOD: 'x' }, ['PATH=L3RtcA==', 'ORCA_X=eA==', 'LD_PRELOAD=eA==', 'lower=eA==', 'not a line']) + const out = orcaEnv([], '* ORCA_TOKEN') + expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n") + }) + + it("never sets or unsets the control plane's reserved names and prefixes (kept in sync with secrets.ts)", () => { + const source = readFileSync(fileURLToPath(new URL('../src/secrets.ts', import.meta.url).href), 'utf8') + const quoted = (text: string | undefined): string[] => [...(text ?? '').matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]) + const names = quoted(source.match(/const RESERVED_NAMES[^=]*= new Set\(\[([\s\S]*?)\]\)/)?.[1]) + const prefixes = quoted(source.match(/const RESERVED_PREFIXES = \[([^\]]*)\]/)?.[1]) + expect(names.length).toBeGreaterThan(30) + expect(prefixes.length).toBeGreaterThan(3) + const blocked = [...names, ...prefixes.map((prefix) => `${prefix}X`)] + writeSessionEnv({ GOOD: 'x', ...Object.fromEntries(blocked.map((name) => [name, 'evil'])) }) + const out = orcaEnv([], blocked.join(' ')) + expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n") + }) + + it('prints nothing before the session env exists and never writes a file', () => { + const result = spawnSync('bash', [ORCA_ENV], { + encoding: 'utf8', + cwd: dir, + env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: join(dir, 'missing'), ORCA_SESSION_ENV_NAMES: 'A B' } + }) + expect(result.status).toBe(0) + expect(result.stdout).toBe('') + expect(spawnSync('ls', ['-A', dir], { encoding: 'utf8' }).stdout).toBe('') + }) + + it('rejects unknown options', () => { + const result = spawnSync('bash', [ORCA_ENV, '--zsh'], { encoding: 'utf8' }) + expect(result.status).toBe(2) + }) +}) diff --git a/cloud/apps/sandbox-control/test/read-snapshots.test.ts b/cloud/apps/sandbox-control/test/read-snapshots.test.ts new file mode 100644 index 00000000000..81eaff2e970 --- /dev/null +++ b/cloud/apps/sandbox-control/test/read-snapshots.test.ts @@ -0,0 +1,323 @@ +import { mkdtempSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import { SignJWT, exportJWK, generateKeyPair } from 'jose' +import { describe, expect, it, vi } from 'vitest' +import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from '../../../../src/main/cloud-workspaces/sealed-grant-node' +import { openReadSnapshot, type ReadSnapshot } from '../../../../src/shared/cloud-workspaces/read-snapshot' +import type { RunCommandParams } from '../src/sandbox-provider' +import { MAX_READ_RECIPIENTS, READ_SNAPSHOT_COMMAND } from '../src/read-snapshots' +import { createHarness } from './harness' + +// The real VM collector + sealer (image/vm/orca-read-snapshot.cjs), fed a fake orcad. +const require = createRequire(import.meta.url) +const vm = require('../image/vm/orca-read-snapshot.cjs') as { + seal: (payload: unknown, recipients: unknown[], workspaceId: string, snapshotId: string) => Record + gather: (call: (method: string, params: unknown) => Promise, opts: Record) => Promise> + fitToBudget: (payload: T, maxBytes?: number) => T + storedSessions: (dataDir: string) => Record[] +} + +const SECRET_LINE = 'the deploy key is in 1password, not in the repo' + +function fakeOrcad(method: string, params?: unknown): unknown { + switch (method) { + case 'worktree.ps': + return { + worktrees: [ + { + path: '/vercel/sandbox/project', + // Live right now: its status wins over the stored one. + agents: [{ paneKey: 'structured-agent-session-chat-2:leaf-1', agentType: 'codex', state: 'working', conversationName: 'Add tests', updatedAt: 1 }], + linkedPR: { number: 42, title: 'Fix login', state: 'open', url: 'https://github.com/acme/app/pull/42', checksStatus: 'success', checksSummary: '3/3 passed' } + } + ] + } + case 'git.status': + return { branch: 'refs/heads/fix/login', head: 'abc1234', entries: [{ path: 'src/login.ts', status: 'modified', area: 'unstaged', added: 12, removed: 3 }] } + case 'git.history': + return { items: [{ id: 'abc1234', subject: 'Fix the login redirect', author: 'Alice', timestamp: 1 }] } + case 'agentSession.history': + // chat-2 has no readable history yet: its stored last turn stands in. + if ((params as { sessionId?: string })?.sessionId === 'chat-2') { + return null + } + return { + page: { + hasOlder: false, + items: [ + { itemId: 'i1', observedAt: 1, body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Why does login loop?' }] } }, + { itemId: 'i2', observedAt: 2, body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: SECRET_LINE }] } }, + { itemId: 'i3', observedAt: 3, body: { kind: 'tool', blocks: [] } } + ] + } + } + default: + return null + } +} + +/** What orca-sandbox-read-snapshot does on a VM, minus the socket: gather from orcad, then seal. */ +async function runVmSealer(params: RunCommandParams): Promise { + const env = params.env ?? {} + const payload = vm.fitToBudget( + await vm.gather(async (method, params) => fakeOrcad(method, params), { + workspaceId: env.ORCA_READ_WORKSPACE_ID, + snapshotId: env.ORCA_READ_SNAPSHOT_ID, + reason: env.ORCA_READ_REASON, + now: 1_800_000_000_000, + deadline: Date.now() + 10_000, + // What orcad's session store holds (agent-session-journal.db on the VM). + listSessions: () => [ + { sessionId: 'chat-1', agent: 'claude', title: 'Fix login', status: 'idle', turnOutcome: 'success', updatedAt: 2, open: true }, + { sessionId: 'chat-2', agent: 'codex', title: 'Add tests', status: 'idle', updatedAt: 1, open: true, lastPrompt: 'Add tests', lastReply: null, lastAt: 1 } + ] + }) + ) + const out = vm.seal(payload, JSON.parse(env.ORCA_READ_RECIPIENTS ?? '[]'), env.ORCA_READ_WORKSPACE_ID!, env.ORCA_READ_SNAPSHOT_ID!) + return `${JSON.stringify(out)}\n` +} + +async function setup() { + vi.spyOn(console, 'log').mockImplementation((line: string) => { if (process.env.DBG && String(line).includes('read_snapshot')) process.stderr.write(line + '\n') }) + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40) }) + // The fake's runCommand awaits whatever the handler returns, so the real (async) sealer can run. + let vmUp = true + h.vercel.commandHandler = ((params: RunCommandParams) => { + if (params.command !== READ_SNAPSHOT_COMMAND) { + return undefined + } + return vmUp + ? runVmSealer(params).then((stdout) => ({ exitCode: 0, stdout, stderr: '' })) + : { exitCode: 3, stdout: '', stderr: 'orcad not running' } + }) as never + type Who = { sub: string; org: string; role: 'owner' | 'admin' | 'member' } + const as = (sub: string, role: Who['role'] = 'member', org = 'acme'): Who => ({ sub, org, role }) + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', { org_role: who.role }), body }) + const alice = as('alice') + const bob = as('bob') + const created = await req(alice, 'POST', '/v1/sandboxes', { + workspaceId: 'ws-1', + machineSize: 'standard', + title: 'Fix login', + repo: { url: 'https://github.com/acme/app', ref: 'fix/login' } + }) + expect(created.status).toBe(200) + const id = created.body.sandbox.id as string + const register = async (who: Who, kind: 'desktop' | 'mobile' = 'desktop', bearer?: string) => { + const key = generateGrantRecipientKey() + const res = bearer + ? await h.call('PUT', '/v1/reader-keys', { bearer, body: { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind } }) + : await req(who, 'PUT', '/v1/reader-keys', { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind }) + expect(res.status).toBe(200) + return { ...key, id: res.body.readerKey.id as string } + } + /** Sleep the workspace (the drain seals first). `orcadDown`: the VM script finds no orcad. */ + const sleep = async (who: Who = alice, orcadDown = false) => { + vmUp = !orcadDown + return req(who, 'POST', `/v1/sandboxes/${id}/suspend`) + } + const read = (who: Who, keyId: string, bearer?: string) => + bearer + ? h.call('GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`, { bearer }) + : req(who, 'GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`) + const open = async (body: { snapshot: never }, secretKey: Uint8Array): Promise => + openReadSnapshot(body.snapshot, id, secretKey, nodeSealedGrantPrimitives) + return { h, req, as, alice, bob, id, register, sleep, read, open } +} + +describe('read snapshots of sleeping workspaces (E2EE)', () => { + it('seals at sleep to the owner devices; the control plane stores only ciphertext; the VM stays asleep', async () => { + const t = await setup() + const laptop = await t.register(t.alice) + const phone = await t.register(t.alice, 'mobile') + expect((await t.sleep()).status).toBe(200) + const row = t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string } + expect(row.status).toBe('suspended') + + const before = t.h.vercel.commands.length + for (const key of [laptop, phone]) { + const res = await t.read(t.alice, key.id) + expect(res.status).toBe(200) + const snap = await t.open(res.body, key.secretKey) + expect(snap.sessions.map((s) => [s.agent, s.title, s.status])).toEqual([ + ['claude', 'Fix login', 'idle'], + ['codex', 'Add tests', 'working'] + ]) + expect(snap.sessions[0]!.messages.map((m) => m.text)).toEqual(['Why does login loop?', SECRET_LINE]) + expect(snap.git).toMatchObject({ branch: 'fix/login', changeCount: 1, added: 12, removed: 3 }) + expect(snap.pr).toMatchObject({ number: 42, url: 'https://github.com/acme/app/pull/42', checksStatus: 'success' }) + // Only this device's wrapped key is handed out. + expect(res.body.snapshot.recipient.keyId).toBe(key.id) + } + // Reading never touched the VM. + expect(t.h.vercel.commands.length).toBe(before) + expect((t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string }).status).toBe('suspended') + // Nothing readable at rest. + const dump = JSON.stringify([ + t.h.raw.prepare('SELECT * FROM read_snapshots').all(), + t.h.raw.prepare('SELECT * FROM read_snapshot_keys').all() + ]) + expect(dump).not.toContain('1password') + expect(dump).not.toContain('login loop') + // The list says when, for "As of" without fetching the blob. + const list = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine') + expect(list.body.workspaces[0].readSnapshotAt).toBe(t.h.now()) + }) + + it('opens for teammates only on team workspaces; private stays owner-only; bad keys and other people’s keys are refused', async () => { + const t = await setup() + const own = await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + // Private: Bob can't see it at all, and was never a recipient. + expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_found' }) + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + await t.sleep() + const res = await t.read(t.bob, bobs.id) + expect(res.status).toBe(200) + expect((await t.open(res.body, bobs.secretKey)).sessions).toHaveLength(2) + // Bob can't fetch Alice's wrapped key, nor open his blob with another key. + expect((await t.read(t.bob, own.id)).status).toBe(400) + await expect(t.open(res.body, own.secretKey)).rejects.toThrow('decrypt_failed') + // Another org's member sees nothing. + const mallory = t.as('mallory', 'member', 'evil') + const mk = await t.register(mallory) + expect((await t.read(mallory, mk.id)).status).toBe(404) + }) + + it('making it private prunes teammates at once, without the VM', async () => { + const t = await setup() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + const own = await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + expect((await t.read(t.bob, bobs.id)).status).toBe(200) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'private' }) + expect((await t.read(t.bob, bobs.id)).status).toBe(404) + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys').all()).toEqual([{ key_id: own.id }]) + // Even back to team: Bob's wrapped key is gone until the next sleep re-seals. + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_sealed_for_key' }) + }) + + it('a removed member can no longer read, and their wrapped keys are deleted', async () => { + const t = await setup() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + await t.register(t.alice) + const bobs = await t.register(t.bob) + await t.sleep() + expect((await t.read(t.bob, bobs.id)).status).toBe(200) + const removed = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) + expect(removed.body.readerKeysRevoked).toBe(1) + // A token minted after removal (stale org claim) still gets nothing: key revoked, wrapped key gone. + t.h.advance(1000) + const again = await t.read(t.bob, bobs.id) + expect(again.status).not.toBe(200) + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([]) + // Next sleep is not sealed to him either. + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + await t.sleep() + expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([]) + }) + + it('a device added after the last sleep gets not_sealed_for_key; no snapshot yet is no_snapshot', async () => { + const t = await setup() + const first = await t.register(t.alice) + expect((await t.read(t.alice, first.id)).body).toEqual({ error: 'no_snapshot' }) + await t.sleep() + const later = await t.register(t.alice) + expect((await t.read(t.alice, later.id)).body).toEqual({ error: 'not_sealed_for_key' }) + expect((await t.read(t.alice, 'rk_nope')).status).toBe(400) + }) + + it('registration is idempotent, per member capped, and a key revoke drops its wrapped key', async () => { + const t = await setup() + const key = generateGrantRecipientKey() + const body = { publicKeyB64: key.publicKeyB64, deviceLabel: 'Mac', deviceKind: 'desktop' } + const a = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + const b = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + expect(a.body.readerKey.id).toBe(b.body.readerKey.id) + expect((await t.req(t.alice, 'PUT', '/v1/reader-keys', { ...body, publicKeyB64: 'AAAA' })).status).toBe(400) + await t.sleep() + expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(200) + expect((await t.req(t.bob, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).status).toBe(404) + expect((await t.req(t.alice, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).body).toEqual({ ok: true }) + expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(400) + // Re-registering a revoked key yields a new id (never resurrected), with nothing sealed to it. + const c = await t.req(t.alice, 'PUT', '/v1/reader-keys', body) + expect(c.body.readerKey.id).not.toBe(a.body.readerKey.id) + for (let i = 0; i < 14; i++) { + await t.register(t.alice) + } + expect((await t.req(t.alice, 'GET', '/v1/reader-keys')).body.readerKeys).toHaveLength(12) + }) + + it('a phone key dies with its device session', async () => { + const t = await setup() + const { privateKey, publicKey } = await generateKeyPair('Ed25519', { extractable: true }) + const publicKeyB64 = Buffer.from((await exportJWK(publicKey)).x!, 'base64url').toString('base64') + const enrolled = await t.h.call('POST', '/v1/device-sessions', { + body: { label: 'iPhone', platform: 'ios', publicKeyB64 }, + bearer: await t.h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + }) + const sessionId = enrolled.body.deviceSession.id as string + const phoneToken = async () => { + const iat = Math.floor(t.h.now() / 1000) + return new SignJWT({}).setProtectedHeader({ alg: 'EdDSA', kid: sessionId }).setIssuer('orca-device').setSubject(sessionId) + .setAudience('orca-sandbox').setIssuedAt(iat).setExpirationTime(iat + 120).sign(privateKey) + } + const key = await t.register(t.alice, 'mobile', await phoneToken()) + await t.sleep() + const res = await t.read(t.alice, key.id, await phoneToken()) + expect(res.status).toBe(200) + expect((await t.open(res.body, key.secretKey)).sessions[0]!.messages[1]!.text).toBe(SECRET_LINE) + await t.h.call('DELETE', `/v1/device-sessions/${sessionId}`, { bearer: await t.h.token('alice', 'acme') }) + expect(t.h.raw.prepare('SELECT revoked_by FROM reader_keys WHERE id = ?').get(key.id)).toEqual({ revoked_by: 'system:device_revoked' }) + expect(t.h.raw.prepare('SELECT * FROM read_snapshot_keys WHERE key_id = ?').all(key.id)).toEqual([]) + }) + + it('a failed capture keeps the previous snapshot and never blocks the sleep', async () => { + const t = await setup() + const key = await t.register(t.alice) + await t.sleep() + const first = (await t.read(t.alice, key.id)).body.snapshot.snapshotId + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`) + // The VM script finds no orcad (exit 3). + expect((await t.sleep(t.alice, true)).status).toBe(200) + expect((await t.read(t.alice, key.id)).body.snapshot.snapshotId).toBe(first) + }) + + it('the VM sealer bounds what it seals and caps recipients', () => { + const big = { + v: 1, + sessions: Array.from({ length: 3 }, (_, i) => ({ sessionId: `s${i}`, messages: Array.from({ length: 60 }, (_, j) => ({ itemId: `${j}`, role: 'user', text: 'x'.repeat(4000), at: j })) })), + git: { changes: [] } + } + const fitted = vm.fitToBudget(big, 150_000) + expect(Buffer.byteLength(JSON.stringify(fitted))).toBeLessThanOrEqual(150_000) + expect(MAX_READ_RECIPIENTS).toBe(64) + // A malformed recipient is skipped, not fatal. + const out = vm.seal({ v: 1 }, [{ keyId: 'rk_bad', publicKeyB64: 'x' }, { keyId: 'rk_000000000000000000000000', publicKeyB64: generateGrantRecipientKey().publicKeyB64 }], 'sbx_0', 'rsn_0') as { recipients: unknown[] } + expect(out.recipients).toHaveLength(1) + }) + + it('lists chats from orcad’s session store (read-only), open tabs and last turns included', () => { + const dir = mkdtempSync(join(tmpdir(), 'orcad-')) + const db = new DatabaseSync(join(dir, 'agent-session-journal.db')) + db.exec('CREATE TABLE agent_session_records (session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL); CREATE TABLE agent_session_tabs (tab_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, position INTEGER NOT NULL)') + const record = { provider: 'claude', conversationName: 'Gap5 live check', updatedAt: 5, lastTurn: { state: 'settled', outcome: 'success', prompt: 'What is this repo?', reply: 'Hello World!', at: 4 } } + db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('claude_1', JSON.stringify(record)) + db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('broken', '{not json') + db.prepare('INSERT INTO agent_session_tabs VALUES (?, ?, 0)').run('structured-agent-session-claude_1', 'claude_1') + db.close() + expect(vm.storedSessions(dir)).toEqual([ + expect.objectContaining({ sessionId: 'claude_1', agent: 'claude', title: 'Gap5 live check', status: 'idle', turnOutcome: 'success', open: true, lastPrompt: 'What is this repo?', lastReply: 'Hello World!' }) + ]) + expect(vm.storedSessions(join(dir, 'missing'))).toEqual([]) + }) +}) diff --git a/cloud/apps/sandbox-control/test/routines.test.ts b/cloud/apps/sandbox-control/test/routines.test.ts index 82f3c51c1d8..7fa4f9eb95d 100644 --- a/cloud/apps/sandbox-control/test/routines.test.ts +++ b/cloud/apps/sandbox-control/test/routines.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { ORCA_CLOUD_IMAGE_AGENTS } from '../../../../src/shared/hosted-sandbox/orca-cloud-image-agents' import type { GitHubAppMinter } from '../src/github-app' import type { RunCommandParams } from '../src/sandbox-provider' import { redactLog } from '../src/routines/vm-runner' @@ -199,6 +200,26 @@ describe('routine runs (state machine on the fake provider)', () => { ]) }) + it('runs every agent the image ships, headless, and refuses any other', async () => { + const h = await harness() + for (const agent of ORCA_CLOUD_IMAGE_AGENTS) { + const created = await h.create({ name: `r-${agent}`, agent }) + expect(created.status, agent).toBe(201) + expect(created.body.routine.agent).toBe(agent) + const run = (await h.call('POST', `/v1/routines/${created.body.routine.id}/run`)).body.run + await h.tick() + const start = h.runnerCalls.find((c) => c.mode === 'start' && c.args.includes(run.id))! + expect(start.args[5]).toBe(agent) + // The worker has a headless command for it (an unknown agent ends as unknown_agent). + expect(start.args.at(-1)).toMatch(new RegExp(`^${agent}\\)$`, 'm')) + h.runs.set(run.id, h.done()) + await h.tick() + } + expect((await h.create({ agent: 'aider' })).body.reason).toMatch(/^agent/) + const routine = (await h.create({ name: 'patch-me' })).body.routine + expect((await h.call('PATCH', `/v1/routines/${routine.id}`, { body: { agent: 'gemini' } })).body.routine.agent).toBe('gemini') + }) + it('pr mode: falls back to opening the PR from the control plane when gh did not report one', async () => { const h = await harness() const routine = (await h.create({ postResults: 'pr' })).body.routine diff --git a/cloud/apps/sandbox-control/test/session-cpu.test.ts b/cloud/apps/sandbox-control/test/session-cpu.test.ts new file mode 100644 index 00000000000..9288d5dfaaf --- /dev/null +++ b/cloud/apps/sandbox-control/test/session-cpu.test.ts @@ -0,0 +1,201 @@ +// U22: internal-only per-session CPU, fair-use report, and its operator gate. +import { describe, expect, it } from 'vitest' +import { FAIR_USE_THRESHOLD, fairUseReport, recordSessionEnd, sweepSessionCpu } from '../src/session-cpu' +import type { SandboxRow } from '../src/store' +import { createVercelSandboxApi } from '../src/vercel-sandbox-api' +import { createFakeD1 } from './d1-fake' +import { createHarness } from './harness' + +const OPERATOR = 'o'.repeat(40) +const MIN = 60_000 +const create = { workspaceId: 'ws-1', machineSize: 'standard' } + +async function operator(h: Awaited>, method: string, path: string) { + const response = await h.send( + new Request(`https://sandbox.test${path}`, { method, headers: { authorization: `Bearer ${OPERATOR}` } }) + ) + return { status: response.status, body: (await response.json()) as any } +} + +function client(answer: (url: URL, method: string) => Response) { + return createVercelSandboxApi({ + token: 'vercel_test_token', + teamId: 'team_orca', + projectId: 'prj_orca', + fetch: async (input, init) => answer(new URL(String(input)), init?.method ?? 'GET') + }) +} + +const stoppedSession = { + id: 'sess_1', + status: 'stopped', + startedAt: 1000, + timeout: 1_800_000, + memory: 16384, + vcpus: 8, + region: 'iad1', + duration: 600_000, + stoppedAt: 601_000, + activeCpuDurationMs: 123_456 +} + +describe('Vercel session usage mapping', () => { + it('maps activeCpuDurationMs, duration, vcpus and memory from GET session', async () => { + let seen: URL | null = null + const api = client((url) => ((seen = url), Response.json({ session: stoppedSession, routes: [] }))) + expect(await api.getSessionUsage!('sess_1')).toEqual({ + sessionId: 'sess_1', + status: 'stopped', + activeCpuMs: 123_456, + durationMs: 600_000, + vcpus: 8, + memoryMb: 16384, + stoppedAt: 601_000 + }) + expect(seen!.pathname).toBe('/api/v2/sandboxes/sessions/sess_1') + }) + + it('a running session has no CPU yet; a forgotten one is null', async () => { + const running = client(() => Response.json({ session: { id: 's', status: 'running', timeout: 1, vcpus: 8 } })) + expect(await running.getSessionUsage!('s')).toMatchObject({ activeCpuMs: null, vcpus: 8, durationMs: null }) + const gone = client(() => Response.json({ error: { code: 'not_found' } }, { status: 404 })) + expect(await gone.getSessionUsage!('s')).toBeNull() + }) + + it('reads usage off the stop response, and an unreadable session never fails the stop', async () => { + const withSession = client(() => Response.json({ session: stoppedSession, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } })) + expect(await withSession.stopSession('sess_1')).toMatchObject({ snapshotId: 'snap_1', usage: { activeCpuMs: 123_456 } }) + const odd = client(() => Response.json({ session: { id: 7 }, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } })) + expect(await odd.stopSession('sess_1')).toEqual({ snapshotId: 'snap_1', usage: null }) + }) +}) + +function row(overrides: Partial = {}): SandboxRow { + return { + id: 'sbx_1', + account_id: 'user:alice', + user_id: 'alice', + session_id: 'sess_1', + session_started_at: 1_000, + ...overrides + } as SandboxRow +} + +describe('session CPU storage', () => { + it('is idempotent per session and the first recorded CPU wins', async () => { + const { db, raw } = createFakeD1() + await recordSessionEnd(db, row(), 61_000, null, 61_000) + await recordSessionEnd(db, row(), 99_000, null, 99_000) + const usage = { sessionId: 'sess_1', status: 'stopped' as const, activeCpuMs: 30_000, durationMs: 60_000, vcpus: 8, memoryMb: 16384, stoppedAt: 61_000 } + await recordSessionEnd(db, row(), 99_000, usage, 100_000) + await recordSessionEnd(db, row(), 99_000, { ...usage, activeCpuMs: 1 }, 200_000) + const rows = raw.prepare('SELECT * FROM session_cpu').all() as any[] + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ session_id: 'sess_1', sandbox_id: 'sbx_1', account_id: 'user:alice', user_id: 'alice', ended_at: 61_000, active_cpu_ms: 30_000, wall_ms: 60_000, vcpus: 8, memory_mb: 16384, fetched_at: 100_000 }) + }) + + it('never throws, even when D1 does', async () => { + const broken = { prepare: () => { throw new Error('d1 down') } } as unknown as D1Database + await expect(recordSessionEnd(broken, row(), 1, null, 1)).resolves.toBeUndefined() + expect(await sweepSessionCpu(broken, { getSessionUsage: async () => null }, 1)).toEqual({ checked: 0, recorded: 0, failed: 0 }) + }) +}) + +describe('session CPU through the lifecycle', () => { + it('suspend records the session (wall time, vCPUs) without touching the meter; the sweep fills CPU later', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + const sessionId = [...h.vercel.boxes.values()][0]!.sessionId + h.advance(10 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + + const [recorded] = h.raw.prepare('SELECT * FROM session_cpu').all() as any[] + expect(recorded).toMatchObject({ session_id: sessionId, sandbox_id: body.sandbox.id, account_id: 'user:alice', vcpus: 8, wall_ms: 10 * MIN, active_cpu_ms: null }) + // Billing sees exactly the flat-hours segment, with no CPU anywhere in it. + expect(h.billing.usage).toHaveLength(1) + expect(Object.keys(h.billing.usage[0]!).sort()).toEqual(['accountId', 'endedAt', 'machineSize', 'sandboxId', 'startedAt', 'usageId', 'userId']) + + h.vercel.sessionCpu.set(sessionId, 4 * 8 * MIN) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body).toEqual({ sweep: { checked: 1, recorded: 1, failed: 0 } }) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep.checked).toBe(0) + const report = await operator(h, 'GET', '/v1/internal/fair-use') + expect(report.body.accounts).toEqual([ + { accountId: 'user:alice', sessions: 1, activeCpuMs: 32 * MIN, vcpuMs: 80 * MIN, cpuUtilization: 0.4, fairUseFlag: false } + ]) + }) + + it('a failing CPU fetch never blocks suspend or usage reporting; the sweep backs off', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + h.vercel.failSessionUsage = true + // Even a D1 table missing entirely must not fail the stop. + h.raw.exec('ALTER TABLE session_cpu RENAME TO session_cpu_hidden') + h.advance(5 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + expect(h.billing.usage).toHaveLength(1) + h.raw.exec('ALTER TABLE session_cpu_hidden RENAME TO session_cpu') + + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/resume`)).status).toBe(200) + h.advance(5 * MIN) + expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200) + expect(h.billing.usage).toHaveLength(2) + expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep).toEqual({ checked: 1, recorded: 0, failed: 1 }) + expect((h.raw.prepare('SELECT attempts FROM session_cpu').get() as any).attempts).toBe(1) + }) + + it('a session the provider ended on its own is recorded too', async () => { + const h = await createHarness() + const { body } = await h.call('POST', '/v1/sandboxes', { body: create }) + const box = [...h.vercel.boxes.values()][0]! + h.advance(31 * MIN) + h.vercel.expire(box.params.name) + await h.reconcile() + expect(h.raw.prepare('SELECT sandbox_id, wall_ms FROM session_cpu').all()).toEqual([{ sandbox_id: body.sandbox.id, wall_ms: 30 * MIN }]) + }) +}) + +describe('fair-use report', () => { + async function seed(db: D1Database, account: string, session: string, wallMs: number, vcpus: number, cpuMs: number | null, endedAt: number) { + await recordSessionEnd(db, row({ id: `sbx_${session}`, account_id: account, session_id: session, session_started_at: endedAt - wallMs }), endedAt, null, endedAt) + if (cpuMs !== null) { + await recordSessionEnd(db, row({ session_id: session }), endedAt, { sessionId: session, status: 'stopped', activeCpuMs: cpuMs, durationMs: wallMs, vcpus, memoryMb: null, stoppedAt: endedAt }, endedAt) + } + } + + it('averages active CPU over wall × vCPUs per account and flags only above 60%', async () => { + const { db } = createFakeD1() + const now = 100 * 24 * 60 * MIN + const hour = 60 * MIN + await seed(db, 'org:heavy', 'h1', hour, 8, 6 * hour, now - hour) // 75% + await seed(db, 'org:heavy', 'h2', hour, 8, 4 * hour, now - 2 * hour) // 50% → combined 62.5% + await seed(db, 'org:edge', 'e1', hour, 8, 4.8 * hour, now - hour) // exactly 60%: not over + await seed(db, 'user:light', 'l1', 2 * hour, 4, 0.8 * hour, now - hour) // 10% + await seed(db, 'user:light', 'old', hour, 8, 8 * hour, now - 31 * 24 * hour) // outside the window + await seed(db, 'user:light', 'pending', hour, 8, null, now - hour) // no CPU yet: excluded + const report = await fairUseReport(db, now) + expect(report).toMatchObject({ windowDays: 30, threshold: FAIR_USE_THRESHOLD, pendingSessions: 1 }) + expect(report.accounts.map((a) => [a.accountId, a.sessions, a.cpuUtilization, a.fairUseFlag])).toEqual([ + ['org:heavy', 2, 0.625, true], + ['org:edge', 1, 0.6, false], + ['user:light', 1, 0.1, false] + ]) + expect(report.accounts[0]).toMatchObject({ activeCpuMs: 10 * hour, vcpuMs: 16 * hour }) + }) +}) + +describe('fair-use auth gate', () => { + it('refuses customer tokens, wrong tokens and an unset operator token; accepts the operator', async () => { + const h = await createHarness({ OPERATOR_TOKEN: OPERATOR }) + expect((await h.call('GET', '/v1/internal/fair-use')).status).toBe(404) + expect((await h.call('GET', '/v1/internal/fair-use', { bearer: 'x'.repeat(40) })).status).toBe(404) + expect((await h.call('POST', '/v1/internal/session-cpu/sweep')).status).toBe(404) + expect((await operator(h, 'GET', '/v1/internal/fair-use')).body).toMatchObject({ windowDays: 30, accounts: [] }) + expect((await operator(h, 'GET', '/v1/internal/fair-use?days=0')).status).toBe(400) + + const closed = await createHarness() + const response = await closed.send( + new Request('https://sandbox.test/v1/internal/fair-use', { headers: { authorization: `Bearer ${OPERATOR}` } }) + ) + expect(response.status).toBe(404) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 1dfeb05f7f9..7b090930f83 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -101,6 +101,52 @@ describe('workspace registry', () => { expect(t.h.vercel.snapshotExpirations.get(name)).toBe(104 * 24 * 60 * MIN) }) + it('refuses to archive a sandbox that is starting or mid-transition, and leaves the row unchanged', async () => { + const t = await team() + for (const status of ['creating', 'suspending']) { + t.h.raw.prepare(`UPDATE sandboxes SET status = ? WHERE id = ?`).run(status, t.id) + const busy = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(busy).toMatchObject({ status: 409, body: { reason: `sandbox_${status}` } }) + } + t.h.raw.prepare(`UPDATE sandboxes SET status = 'resuming' WHERE id = ?`).run(t.id) + const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(res).toMatchObject({ status: 409, body: { error: 'conflict', reason: 'sandbox_resuming' } }) + expect(t.h.raw.prepare('SELECT status, archived_at FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ + status: 'resuming', + archived_at: null + }) + }) + + it('archives an asleep sandbox without waking it', async () => { + const t = await team() + await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/suspend`) + const { START_COMMAND } = await import('../src/sandbox-vm-commands') + const starts = t.h.vercel.commands.filter((c) => c.command === START_COMMAND).length + const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(res.status).toBe(200) + expect(t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ status: 'archived' }) + expect(t.h.vercel.commands.filter((c) => c.command === START_COMMAND)).toHaveLength(starts) + expect(t.h.vercel.boxes.get(`orca-test-${t.id}`)!.status).toBe('stopped') + }) + + it('never labels a running sandbox archived when the archive itself fails', async () => { + const t = await team() + const { ProviderError } = await import('../src/sandbox-provider') + t.h.vercel.stopSession = async () => { + throw new ProviderError(500, 'internal_error') + } + const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true }) + expect(res.status).toBeGreaterThanOrEqual(500) + expect((t.h.raw.prepare('SELECT archived_at FROM sandboxes WHERE id = ?').get(t.id) as { archived_at: number | null }).archived_at).toBeNull() + }) + + it('only the owner or a team admin can archive', async () => { + const t = await team() + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })).status).toBe(403) + expect(t.h.vercel.boxes.get(`orca-test-${t.id}`)!.status).toBe('running') + }) + it('reports cost from metered compute at the billing rate, plus reported token spend', async () => { const t = await team() t.h.advance(90 * MIN) @@ -253,7 +299,7 @@ describe('workspace grants (E2EE pairing through the control plane)', () => { await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' }) await t.req(t.bob, 'POST', `/v1/team/workspaces/${t.id}/grants`, { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }) const res = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } }) - expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0 }) + expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 }) }) }) diff --git a/cloud/apps/sandbox-control/wrangler.dev.jsonc b/cloud/apps/sandbox-control/wrangler.dev.jsonc index f6d711e61e1..5ed1f29ddd6 100644 --- a/cloud/apps/sandbox-control/wrangler.dev.jsonc +++ b/cloud/apps/sandbox-control/wrangler.dev.jsonc @@ -11,6 +11,8 @@ "main": "src/index.ts", "compatibility_date": "2026-11-01", "workers_dev": true, + // Preview aliases (wrangler versions upload --preview-alias) must stay reachable for pre-merge VM tests. + "preview_urls": true, "d1_databases": [ { "binding": "SANDBOX_DB", diff --git a/mobile/src/cloud/CloudReadSnapshotSection.tsx b/mobile/src/cloud/CloudReadSnapshotSection.tsx new file mode 100644 index 00000000000..afad96d971c --- /dev/null +++ b/mobile/src/cloud/CloudReadSnapshotSection.tsx @@ -0,0 +1,309 @@ +import { ExternalLink } from 'lucide-react-native' +import { useEffect, useRef, useState } from 'react' +import { Animated, Easing, Linking, Pressable, Text, View } from 'react-native' +import type { + ReadSnapshot, + ReadSnapshotGit, + ReadSnapshotPr +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { Translate } from '../i18n/mobile-i18n' +import { getUiIntlLocale } from '../i18n/ui-intl-locale' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useReducedMotionEnabled } from '../platform/use-reduced-motion' +import { colors } from '../theme/mobile-theme' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { formatTimeAgo } from '../worktree/agent-row-display' +import { CloudErrorBanner } from './CloudErrorBanner' +import { CloudStatusDot } from './CloudStatusDot' +import { CloudReadSnapshotSessions } from './CloudReadSnapshotSessions' +import { CloudReadSnapshotRollbackError, type CloudReadSnapshotResult } from './cloud-read-snapshot' +import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles' +import { cloudStatusLabel } from './cloud-workspace-display' +import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles' + +const GIT_PATHS_SHOWN = 5 + +export function formatReadSnapshotAbsolute(at: number): string { + try { + return new Intl.DateTimeFormat(getUiIntlLocale(), { + dateStyle: 'medium', + timeStyle: 'short' + }).format(at) + } catch { + return new Date(at).toLocaleString() + } +} + +/** "As of 5m ago" (relative); the absolute time is the long-press / screen-reader form. */ +export function formatReadSnapshotAsOf(at: number, now: number, t: Translate): string { + return now - at < 60_000 + ? t('cloud.snapshot.asOfJustNow', 'As of just now') + : t('cloud.snapshot.asOf', 'As of {{ago}} ago', { ago: formatTimeAgo(at, now) }) +} + +/** + * The asleep workspace's read-only "Latest from this workspace": what its PR, agents and git looked + * like when it went to sleep, opened on this phone. Never wakes the sandbox. + */ +export function CloudReadSnapshotSection(props: { + result: CloudReadSnapshotResult | undefined + /** When the result was fetched: the clock "As of" counts from (no impure clock read in render). */ + fetchedAt: number + loading: boolean + /** Wake was tapped: the header says Waking (the copy stays readable until it is open). */ + waking: boolean + onRetry: () => void +}) { + useMobileColorScheme() + const t = useMobileTranslation() + const { result } = props + // Gone or not openable: the screen itself says so; this area has nothing to add. + if (!props.loading && result?.state === 'not_found') { + return null + } + return ( + + + + {t('cloud.snapshot.heading', 'Latest from this workspace')} + + + + + {cloudStatusLabel(props.waking ? 'waking' : 'sleeping', t)} + + + + {props.loading || !result ? ( + + ) : result.state === 'ready' ? ( + + ) : result.state === 'no_snapshot' ? ( + + ) : result.state === 'not_sealed_for_key' ? ( + + ) : result.state === 'error' && result.error instanceof CloudReadSnapshotRollbackError ? ( + // Trying again cannot help: the newer copy only comes back from the workspace itself. + + ) : ( + + )} + + ) +} + +function Notice({ text }: { text: string }) { + return ( + + {text} + + ) +} + +function SnapshotSkeleton() { + const t = useMobileTranslation() + const reducedMotion = useReducedMotionEnabled() !== false + const pulse = useRef(new Animated.Value(1)).current + useEffect(() => { + if (reducedMotion) { + pulse.setValue(1) + return + } + const loop = Animated.loop( + Animated.sequence([ + Animated.timing(pulse, { + toValue: 0.45, + duration: 800, + easing: Easing.inOut(Easing.quad), + useNativeDriver: true + }), + Animated.timing(pulse, { + toValue: 1, + duration: 800, + easing: Easing.inOut(Easing.quad), + useNativeDriver: true + }) + ]) + ) + loop.start() + return () => loop.stop() + }, [reducedMotion, pulse]) + return ( + + + + + + ) +} + +function SnapshotBody({ snapshot, now }: { snapshot: ReadSnapshot; now: number }) { + const t = useMobileTranslation() + const [absolute, setAbsolute] = useState(false) + const exact = formatReadSnapshotAbsolute(snapshot.capturedAt) + const empty = !snapshot.pr && !snapshot.git && snapshot.sessions.length === 0 + return ( + + setAbsolute((value) => !value)} + style={styles.asOfButton} + > + + {absolute + ? t('cloud.snapshot.asOfExact', 'As of {{time}}', { time: exact }) + : formatReadSnapshotAsOf(snapshot.capturedAt, Math.max(now, snapshot.capturedAt), t)} + + + + {snapshot.pr ? : null} + + {snapshot.git ? : null} + {empty ? ( + + ) : null} + + + ) +} + +function prStateLabel(pr: ReadSnapshotPr, t: Translate): string { + switch (pr.state.toLowerCase()) { + case 'merged': + return t('cloud.snapshot.pr.merged', 'Merged') + case 'closed': + return t('cloud.snapshot.pr.closed', 'Closed') + case 'draft': + return t('cloud.snapshot.pr.draft', 'Draft') + default: + return t('cloud.snapshot.pr.open', 'Open') + } +} + +function prChecksLabel(pr: ReadSnapshotPr, t: Translate): string | null { + switch (pr.checksStatus?.toLowerCase()) { + case 'success': + case 'passed': + case 'passing': + return t('cloud.snapshot.checks.passing', 'Checks passing') + case 'failure': + case 'failed': + case 'failing': + return t('cloud.snapshot.checks.failing', 'Checks failing') + case 'pending': + case 'running': + return t('cloud.snapshot.checks.pending', 'Checks running') + // No status, or one this build doesn't name: the VM's own summary line, if any. + case undefined: + default: + return pr.checksSummary + } +} + +function PrCard({ pr }: { pr: ReadSnapshotPr }) { + const t = useMobileTranslation() + const failing = /fail/i.test(pr.checksStatus ?? '') + const meta = [prStateLabel(pr, t), prChecksLabel(pr, t)].filter(Boolean).join(' · ') + const title = t('cloud.snapshot.pr.title', '#{{number}} {{title}}', { + number: pr.number, + title: pr.title + }) + return ( + + void Linking.openURL(pr.url).catch(() => undefined)} + style={({ pressed }) => [styles.row, pressed && screen.pressed]} + > + + + {title} + + + {meta} + + + + + + ) +} + +function GitCard({ git }: { git: ReadSnapshotGit }) { + const t = useMobileTranslation() + const count = git.changeCount + const files = + count === 1 + ? t('cloud.snapshot.git.files_one', '{{count}} changed file', { count }) + : t('cloud.snapshot.git.files_other', '{{count}} changed files', { count }) + const more = count - Math.min(git.changes.length, GIT_PATHS_SHOWN) + return ( + + + {git.branch ? ( + + {git.branch} + + ) : null} + + + {count === 0 ? t('cloud.snapshot.git.clean', 'No uncommitted changes') : files} + + {git.added !== null ? ( + +{git.added} + ) : null} + {git.removed !== null ? ( + −{git.removed} + ) : null} + + {git.changes.slice(0, GIT_PATHS_SHOWN).map((change) => ( + + {change.path} + + ))} + {more > 0 ? ( + + {more === 1 + ? t('cloud.snapshot.git.more_one', 'and {{count}} more', { count: more }) + : t('cloud.snapshot.git.more_other', 'and {{count}} more', { count: more })} + + ) : null} + + + ) +} diff --git a/mobile/src/cloud/CloudReadSnapshotSessions.tsx b/mobile/src/cloud/CloudReadSnapshotSessions.tsx new file mode 100644 index 00000000000..0a06527b3e7 --- /dev/null +++ b/mobile/src/cloud/CloudReadSnapshotSessions.tsx @@ -0,0 +1,152 @@ +import { ChevronDown, ChevronRight } from 'lucide-react-native' +import { useState } from 'react' +import { Pressable, Text, View } from 'react-native' +import type { + ReadSnapshotMessage, + ReadSnapshotSession +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { Translate } from '../i18n/mobile-i18n' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { MobileNativeChatMarkdown } from '../session/native-chat/MobileNativeChatMarkdown' +import { colors } from '../theme/mobile-theme' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { cloudAgentLabel } from './CloudAgentPicker' +import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles' +import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles' + +export function readSnapshotSessionStatus( + session: Pick, + t: Translate +): string | null { + switch (session.status) { + case 'working': + return t('cloud.snapshot.status.working', 'Working') + case 'attention': + return t('cloud.snapshot.status.attention', 'Needs you') + case 'idle': + return session.turnOutcome + ? t('cloud.snapshot.status.done', 'Done') + : t('cloud.snapshot.status.idle', 'Idle') + case 'unknown': + return null + } +} + +/** The product name ("Claude Code", "Codex") from the app's one agent-name table, never the raw id. */ +function agentName(agent: string | null, t: Translate): string { + const trimmed = agent?.trim() + return trimmed ? cloudAgentLabel(trimmed) : t('cloud.snapshot.agentFallback', 'Agent') +} + +/** Agents as they were when the workspace went to sleep; each opens to the tail of its chat. */ +export function CloudReadSnapshotSessions({ sessions }: { sessions: ReadSnapshotSession[] }) { + useMobileColorScheme() + const t = useMobileTranslation() + const [open, setOpen] = useState>(new Set()) + if (sessions.length === 0) { + return null + } + const toggle = (id: string) => + setOpen((current) => { + const next = new Set(current) + if (!next.delete(id)) { + next.add(id) + } + return next + }) + return ( + + {sessions.map((session, index) => { + const expanded = open.has(session.sessionId) + const name = agentName(session.agent, t) + const status = readSnapshotSessionStatus(session, t) + const title = session.title?.trim() || name + const meta = [title === name ? null : name, status].filter(Boolean).join(' · ') + const Chevron = expanded ? ChevronDown : ChevronRight + return ( + 0 ? styles.rowDivider : undefined}> + toggle(session.sessionId)} + style={({ pressed }) => [styles.row, pressed && screen.pressed]} + > + + + {title} + + {meta ? ( + + {meta} + + ) : null} + + + + {expanded ? : null} + + ) + })} + + ) +} + +function Transcript({ session, agent }: { session: ReadSnapshotSession; agent: string }) { + const t = useMobileTranslation() + return ( + + {session.truncated ? ( + + {t('cloud.snapshot.truncated', 'Earlier messages aren’t in this copy.')} + + ) : null} + {session.messages.length === 0 ? ( + + {t('cloud.snapshot.noMessages', 'No messages in this chat yet.')} + + ) : ( + session.messages.map((message) => ( + + )) + )} + + ) +} + +function Bubble({ message, agent }: { message: ReadSnapshotMessage; agent: string }) { + const t = useMobileTranslation() + if (message.role === 'user') { + return ( + + {t('cloud.snapshot.role.you', 'You')} + + {message.text} + + + ) + } + if (message.role === 'system') { + return ( + + {t('cloud.snapshot.role.system', 'System')} + + {message.text} + + + ) + } + return ( + + {agent} + + + ) +} diff --git a/mobile/src/cloud/CloudStatusCard.tsx b/mobile/src/cloud/CloudStatusCard.tsx index bcd3adbc34d..4917bd9db42 100644 --- a/mobile/src/cloud/CloudStatusCard.tsx +++ b/mobile/src/cloud/CloudStatusCard.tsx @@ -27,21 +27,21 @@ function spendLine( if (!awake) { return t( 'cloud.usage.asleep', - '{{hours}} sandbox hours so far · no sandbox hours while asleep', + '{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.', { count: value, hours: label, - defaultValue_one: '{{hours}} sandbox hour so far · no sandbox hours while asleep' + defaultValue_one: '{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.' } ) } return t( 'cloud.usage.running', - '{{hours}} sandbox hours so far · uses sandbox hours while running', + '{{hours}} sandbox hours so far. Uses sandbox hours while running.', { count: value, hours: label, - defaultValue_one: '{{hours}} sandbox hour so far · uses sandbox hours while running' + defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.' } ) } diff --git a/mobile/src/cloud/CloudWorkspaceScreen.tsx b/mobile/src/cloud/CloudWorkspaceScreen.tsx index 2e20db20e21..45f0b157920 100644 --- a/mobile/src/cloud/CloudWorkspaceScreen.tsx +++ b/mobile/src/cloud/CloudWorkspaceScreen.tsx @@ -20,6 +20,7 @@ import { CloudAgentStartedCard } from './CloudAgentStartedCard' import { CloudErrorBanner } from './CloudErrorBanner' import { CloudPromptComposer } from './CloudPromptComposer' import { CloudPromptQueueSection } from './CloudPromptQueueSection' +import { CloudReadSnapshotSection } from './CloudReadSnapshotSection' import { CloudStatusCard } from './CloudStatusCard' import { CloudWorkspaceActions } from './CloudWorkspaceActions' import { archiveCloudWorkspace, sleepCloudWorkspace } from './cloud-control-plane-client' @@ -41,7 +42,8 @@ import { cloudScrollBottomPadding, cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles' -import { useCloudWorkspaceRun } from './use-cloud-workspace-run' +import { useCloudReadSnapshot } from './use-cloud-read-snapshot' +import { useCloudWorkspaceRun, type CloudWorkspaceRun } from './use-cloud-workspace-run' import { useCloudEnrollment, useCloudWorkspace, @@ -65,12 +67,19 @@ export function CloudWorkspaceScreen({ const enrollment = useCloudEnrollment() const { workspace, isPending, isFetching, refetch } = useCloudWorkspace(enrollment, sandboxId) const live = useCloudWorkspaceLiveStatus(sandboxId, workspace?.status === 'running') + // Asleep: read its last sealed snapshot instead of waking it. Nothing here ever wakes it. + const asleep = workspace?.status === 'sleeping' + const snapshot = useCloudReadSnapshot(sandboxId, asleep, workspace?.readSnapshotAt ?? null) const invalidate = useInvalidateCloudWorkspaces() const { run, active, start, fail, clearError, openSession } = useCloudWorkspaceRun( sandboxId, workspace ) const [queue, setQueue] = useState([]) + // The run as it was when wake was tapped: until the run moves on (start() first reads the + // keychain), the button already reads Waking rather than keeping "Wake to continue". + const [wakeTappedAt, setWakeTappedAt] = useState(null) + const wakePending = wakeTappedAt !== null && wakeTappedAt === run const [busyAction, setBusyAction] = useState<'sleep' | 'archive' | null>(null) useEffect(() => { @@ -184,8 +193,17 @@ export function CloudWorkspaceScreen({ workspace.status === 'creating' || workspace.status === 'stopping' || workspace.status === 'archived' - const primaryLabel = - run.kind === 'launched' + const waking = + wakePending || + run.kind === 'attaching' || + run.kind === 'delivering' || + workspace.status === 'waking' + // Asleep, or waking from it: the read-only copy stays readable (header says Waking) until it opens. + const showSnapshot = asleep || (waking && !awake && snapshot.data !== undefined) + const busy = active || wakePending + const primaryLabel = wakePending + ? phaseLabel('waking', t) + : run.kind === 'launched' ? t('cloud.action.openSession', 'Open session') : run.kind === 'attaching' ? phaseLabel(run.phase, t) @@ -197,8 +215,10 @@ export function CloudWorkspaceScreen({ ? t('cloud.status.archived', 'Archived') : awake ? t('cloud.action.open', 'Open workspace') - : t('cloud.action.wakeOpen', 'Wake and open workspace') - const primaryDisabled = active || unavailable + : asleep + ? t('cloud.action.wakeToContinue', 'Wake to continue') + : t('cloud.action.wakeOpen', 'Wake and open workspace') + const primaryDisabled = busy || unavailable return ( @@ -234,6 +254,17 @@ export function CloudWorkspaceScreen({ onRetry={run.retry ? () => void start(run.retry ?? 'open') : null} /> ) : null} + {showSnapshot ? ( + void snapshot.refetch()} + /> + ) : null} @@ -284,18 +315,25 @@ export function CloudWorkspaceScreen({ (run.kind === 'launched' ? openSession('chat') : void start('open'))} + onPress={() => { + if (run.kind === 'launched') { + openSession('chat') + return + } + setWakeTappedAt(run) + void start('open').finally(() => setWakeTappedAt(null)) + }} style={({ pressed }) => [ styles.primary, - primaryDisabled && !active && styles.primaryDisabled, + primaryDisabled && !busy && styles.primaryDisabled, pressed && styles.pressed ]} > - {active ? : null} + {busy ? : null} {primaryLabel} diff --git a/mobile/src/cloud/cloud-control-plane-client.ts b/mobile/src/cloud/cloud-control-plane-client.ts index 985ee349b69..29086df890d 100644 --- a/mobile/src/cloud/cloud-control-plane-client.ts +++ b/mobile/src/cloud/cloud-control-plane-client.ts @@ -42,6 +42,8 @@ export type CloudWorkspace = { /** Awake time so far, from the team registry; the plan meters hours, not per-workspace dollars. */ sandboxMs: number | null createdByUserId: string | null + /** When the last sleeping read snapshot was stored (ms); null when none or unknown. */ + readSnapshotAt: number | null } const SANDBOX_STATUS: Record = { creating: 'creating', @@ -93,7 +95,8 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace { createdAt: row.createdAt, lastActivityAt: row.lastActivityAt, sandboxMs: row.cost.computeMs, - createdByUserId: row.createdBy + createdByUserId: row.createdBy, + readSnapshotAt: row.readSnapshotAt ?? null } } @@ -108,7 +111,8 @@ function fromSandbox(row: z.infer): CloudWorkspace { createdAt: row.createdAt, lastActivityAt: null, sandboxMs: null, - createdByUserId: null + createdByUserId: null, + readSnapshotAt: null } } // Lists archived rows as `archived` rather than folding them into `suspended` (W2 lifecycle). diff --git a/mobile/src/cloud/cloud-control-plane-request.ts b/mobile/src/cloud/cloud-control-plane-request.ts index b8f552dc4d1..e7c8ec34351 100644 --- a/mobile/src/cloud/cloud-control-plane-request.ts +++ b/mobile/src/cloud/cloud-control-plane-request.ts @@ -23,7 +23,7 @@ const ErrorBodySchema = z.object({ error: z.string(), reason: z.string().optiona export async function cloudRequest( plane: CloudControlPlane, - method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, schema: z.ZodType, init: { diff --git a/mobile/src/cloud/cloud-device-identity.ts b/mobile/src/cloud/cloud-device-identity.ts index 820d32fe430..239d50d67f2 100644 --- a/mobile/src/cloud/cloud-device-identity.ts +++ b/mobile/src/cloud/cloud-device-identity.ts @@ -3,6 +3,7 @@ import nacl from 'tweetnacl' import { z } from 'zod' import { randomBytes } from '../transport/encryption/e2ee' import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec' +import { clearCloudReaderKey } from './cloud-reader-key' // This phone's own Orca Cloud key and enrollment. Kept off iCloud Keychain and backups, like pairing // credentials, so a restored phone has to be enrolled again rather than inheriting access. @@ -91,6 +92,8 @@ export async function saveCloudEnrollment(enrollment: CloudEnrollment): Promise< export async function clearCloudEnrollment(): Promise { const seed = randomBytes(32) await write(seed, null) + // The reader key goes with the session: snapshots sealed to it stay unreadable here. + await clearCloudReaderKey().catch(() => undefined) cached = Promise.resolve(fromSeed(seed, null)) listeners.forEach((listener) => listener()) } diff --git a/mobile/src/cloud/cloud-entitlement-copy.ts b/mobile/src/cloud/cloud-entitlement-copy.ts index b62e90662e8..c015fbd7165 100644 --- a/mobile/src/cloud/cloud-entitlement-copy.ts +++ b/mobile/src/cloud/cloud-entitlement-copy.ts @@ -1,3 +1,7 @@ +import { + classifyEntitlementDenial, + type OrcaEntitlementDenialKind +} from '../../../src/shared/orca-billing' import type { Translate } from '../i18n/mobile-i18n' import { readCloudRole, @@ -13,25 +17,20 @@ import { CloudRequestError, type CloudControlPlane } from './cloud-control-plane type Denial = 'hours' | 'cap' | 'payment' | 'plan' | 'teamLimit' | 'memberLimit' | 'other' +// The shared classifier names the category; the phone keeps its own wording per category. +const DENIALS: Record = { + plan: 'plan', + hours: 'hours', + spendCap: 'cap', + payment: 'payment', + teamLimit: 'teamLimit', + memberLimit: 'memberLimit', + machineSize: 'other', + other: 'other' +} + function denialOf(reason: string | undefined): Denial { - switch (reason) { - case 'included_hours_exhausted': - return 'hours' - case 'overage_cap_reached': - return 'cap' - case 'payment_past_due': - case 'payment_grace_expired': - return 'payment' - case 'no_subscription': - case 'subscription_inactive': - return 'plan' - case 'concurrency_limit': - return 'teamLimit' - case 'member_concurrency_limit': - return 'memberLimit' - default: - return 'other' - } + return DENIALS[classifyEntitlementDenial(reason)] } export function isEntitlementDenied(error: unknown): error is CloudRequestError { diff --git a/mobile/src/cloud/cloud-read-snapshot-styles.ts b/mobile/src/cloud/cloud-read-snapshot-styles.ts new file mode 100644 index 00000000000..922b3cdfb2e --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot-styles.ts @@ -0,0 +1,106 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' + +// The asleep workspace's read-only "Latest from this workspace" area; scheme-aware like every cloud card. +export const readSnapshotStyles = themedStyleSheet(() => ({ + headingRow: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm }, + headingText: { flex: 1 }, + headingState: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + marginBottom: spacing.sm, + paddingHorizontal: spacing.xs + }, + headingStateText: { fontSize: 13, color: colors.textSecondary }, + asOf: { + fontSize: 13, + lineHeight: 18, + color: colors.textMuted, + marginBottom: spacing.sm, + paddingHorizontal: spacing.xs + }, + asOfButton: { alignSelf: 'flex-start', minHeight: 32, justifyContent: 'center' }, + stack: { gap: spacing.sm }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + minHeight: 52 + }, + rowDivider: { + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + rowText: { flex: 1, gap: 2 }, + rowTitle: { fontSize: 15, lineHeight: 20, color: colors.textPrimary }, + rowMeta: { fontSize: 13, lineHeight: 18, color: colors.textSecondary }, + rowMetaAttention: { color: colors.statusAmber }, + mono: { + fontFamily: typography.monoFamily, + fontSize: 12, + lineHeight: 17, + color: colors.textSecondary + }, + added: { color: colors.gitDecorationAdded }, + removed: { color: colors.gitDecorationDeleted }, + gitBody: { paddingHorizontal: spacing.lg, paddingVertical: spacing.md, gap: 6 }, + gitHeadline: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm, flexWrap: 'wrap' }, + transcript: { + paddingHorizontal: spacing.md, + paddingBottom: spacing.md, + gap: spacing.sm + }, + truncatedNote: { + fontSize: 12, + color: colors.textMuted, + textAlign: 'center', + paddingVertical: spacing.xs + }, + roleLabel: { fontSize: 11, fontWeight: '600', color: colors.textMuted, marginBottom: 2 }, + bubbleUser: { + alignSelf: 'flex-end', + maxWidth: '88%', + backgroundColor: colors.chatUserSurface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.chatUserBorder, + borderRadius: radii.surface, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm + }, + bubbleAssistant: { + alignSelf: 'stretch', + paddingHorizontal: spacing.xs, + paddingVertical: 2 + }, + bubbleSystem: { + alignSelf: 'stretch', + paddingHorizontal: spacing.sm, + paddingVertical: spacing.xs, + borderRadius: radii.control, + backgroundColor: colors.bgRaised + }, + userText: { fontSize: 15, lineHeight: 21, color: colors.textPrimary }, + systemText: { fontSize: 13, lineHeight: 18, color: colors.textSecondary }, + notice: { + backgroundColor: colors.bgPanel, + borderRadius: radii.surface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md + }, + noticeText: { fontSize: typography.bodySize, lineHeight: 20, color: colors.textSecondary }, + skeletonCard: { + backgroundColor: colors.bgPanel, + borderRadius: radii.surface, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + padding: spacing.lg, + gap: spacing.md + }, + skeletonBar: { height: 10, borderRadius: 5, backgroundColor: colors.bgRaised } +})) diff --git a/mobile/src/cloud/cloud-read-snapshot.test.ts b/mobile/src/cloud/cloud-read-snapshot.test.ts new file mode 100644 index 00000000000..473775cc9f6 --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot.test.ts @@ -0,0 +1,331 @@ +import { + createCipheriv, + createPublicKey, + diffieHellman, + generateKeyPairSync, + hkdfSync, + randomBytes +} from 'node:crypto' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { store } = vi.hoisted(() => ({ store: new Map() })) +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', + getItemAsync: async (key: string) => store.get(key) ?? null, + setItemAsync: async (key: string, value: string) => void store.set(key, value), + deleteItemAsync: async (key: string) => void store.delete(key) +})) +vi.mock('./cloud-device-identity', () => ({ + loadCloudDeviceIdentity: async () => ({ + publicKeyB64: 'x', + secretKey: new Uint8Array(64), + enrollment: { + controlPlaneUrl: 'https://cloud.test', + deviceSessionId: 'ds_1', + label: 'Neil’s iPhone', + enrolledAt: 1 + } + }) +})) + +import type { SealedReadSnapshot } from '../../../src/shared/cloud-workspaces/read-snapshot' +import type { CloudControlPlane } from './cloud-control-plane-request' +import { + CLOUD_READER_KEY_REFRESH_MS, + ensureCloudReaderKey, + readCloudWorkspaceSnapshot, + resetCloudReadSnapshotPins +} from './cloud-read-snapshot' +import { loadCloudReaderKey } from './cloud-reader-key' + +// Seals exactly as the header of src/shared/cloud-workspaces/read-snapshot.ts says the VM does. +function sealLikeVm(args: { + readerPublicKeyB64: string + keyId: string + workspaceId: string + snapshotId: string + payload: unknown +}): SealedReadSnapshot { + const dek = randomBytes(32) + const nonce = randomBytes(12) + const body = createCipheriv('aes-256-gcm', dek, nonce) + body.setAAD(Buffer.from(`orca-cloud-read-v1:${args.workspaceId}:${args.snapshotId}`)) + const ciphertext = Buffer.concat([ + body.update(JSON.stringify(args.payload), 'utf8'), + body.final(), + body.getAuthTag() + ]) + const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64') + const eph = generateKeyPairSync('x25519') + const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x!, 'base64url') + const shared = diffieHellman({ + privateKey: eph.privateKey, + publicKey: createPublicKey({ + key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') }, + format: 'jwk' + }) + }) + const kek = Buffer.from( + hkdfSync('sha256', shared, Buffer.concat([ephRaw, readerPublic]), 'orca-cloud-read-wrap-v1', 32) + ) + const wrapNonce = randomBytes(12) + const wrap = createCipheriv('aes-256-gcm', kek, wrapNonce) + wrap.setAAD( + Buffer.from(`orca-cloud-read-wrap-v1:${args.workspaceId}:${args.snapshotId}:${args.keyId}`) + ) + const wrapped = Buffer.concat([wrap.update(dek), wrap.final(), wrap.getAuthTag()]) + return { + v: 1, + snapshotId: args.snapshotId, + workspaceId: args.workspaceId, + storedAt: 2, + nonceB64: nonce.toString('base64'), + ciphertextB64: ciphertext.toString('base64'), + recipient: { + keyId: args.keyId, + ephemeralPublicKeyB64: ephRaw.toString('base64'), + nonceB64: wrapNonce.toString('base64'), + wrappedKeyB64: wrapped.toString('base64') + } + } +} + +const PAYLOAD = { + v: 1, + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + capturedAt: 1_700_000_000_000, + reason: 'sleep', + pr: { + number: 42, + title: 'Fix login', + state: 'open', + url: 'https://github.com/o/r/pull/42', + checksStatus: 'success', + checksSummary: null + }, + git: { branch: 'fix-login', changes: [{ path: 'a.ts', added: 3, removed: 1 }], changeCount: 1 }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Login bug', + status: 'idle', + turnOutcome: 'completed', + messages: [ + { itemId: 'm1', role: 'user', text: 'fix it', at: 1 }, + { itemId: 'm2', role: 'assistant', text: '**Done**', at: 2 } + ] + } + ] +} + +type Call = { method: string; url: string; body: unknown } + +function fakePlane(handle: (call: Call) => { status: number; body: unknown }): { + plane: CloudControlPlane + calls: Call[] +} { + const calls: Call[] = [] + const fakeFetch: typeof fetch = async (input, init) => { + const call = { + method: init?.method ?? 'GET', + url: String(input), + body: init?.body ? JSON.parse(String(init.body)) : undefined + } + calls.push(call) + const reply = handle(call) + return new Response(JSON.stringify(reply.body), { status: reply.status }) + } + const plane: CloudControlPlane = { + baseUrl: 'https://cloud.test', + token: () => 'tok', + fetch: fakeFetch + } + return { plane, calls } +} + +const registered = (id = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa') => ({ + status: 200, + body: { + readerKey: { id, deviceKind: 'mobile', deviceLabel: 'x', createdAt: 1, lastSeenAt: 1 } + } +}) + +beforeEach(() => { + store.clear() + resetCloudReadSnapshotPins() +}) + +describe('ensureCloudReaderKey', () => { + it('registers once as a mobile key, then only again after 6 h or when forced', async () => { + let clock = 1_000 + const now = () => clock + const { plane, calls } = fakePlane(() => registered()) + const first = await ensureCloudReaderKey(plane, { now }) + const key = await loadCloudReaderKey('ds_1') + expect(first?.keyId).toBe('rk_aaaaaaaaaaaaaaaaaaaaaaaa') + expect(calls).toHaveLength(1) + expect(calls[0]).toMatchObject({ + method: 'PUT', + url: 'https://cloud.test/v1/reader-keys', + body: { publicKeyB64: key.publicKeyB64, deviceLabel: 'Neil’s iPhone', deviceKind: 'mobile' } + }) + await ensureCloudReaderKey(plane, { now }) + expect(calls).toHaveLength(1) + clock += CLOUD_READER_KEY_REFRESH_MS + await ensureCloudReaderKey(plane, { now }) + expect(calls).toHaveLength(2) + await ensureCloudReaderKey(plane, { now, force: true }) + expect(calls).toHaveLength(3) + }) +}) + +describe('readCloudWorkspaceSnapshot', () => { + it('opens a snapshot the VM sealed to this phone (node:crypto seal, Hermes primitives open)', async () => { + const key = await loadCloudReaderKey('ds_1') + const keyId = 'rk_bbbbbbbbbbbbbbbbbbbbbbbb' + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId, + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + payload: PAYLOAD + }) + const { plane, calls } = fakePlane((call) => + call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(calls[1]?.url).toBe( + `https://cloud.test/v1/team/workspaces/sbx_1/read-snapshot?keyId=${keyId}` + ) + expect(calls.some((call) => /wake/.test(call.url))).toBe(false) + expect(result.state).toBe('ready') + if (result.state !== 'ready') { + return + } + expect(result.snapshot.capturedAt).toBe(PAYLOAD.capturedAt) + expect(result.snapshot.pr?.number).toBe(42) + expect(result.snapshot.git?.branch).toBe('fix-login') + expect(result.snapshot.sessions[0]?.messages.map((m) => m.role)).toEqual(['user', 'assistant']) + }) + + it('refuses a snapshot sealed for another workspace', async () => { + const key = await loadCloudReaderKey('ds_1') + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId: 'rk_111111111111111111111111', + workspaceId: 'sbx_other', + snapshotId: 'snap_1', + payload: { ...PAYLOAD, workspaceId: 'sbx_other' } + }) + const { plane } = fakePlane((call) => + call.method === 'PUT' + ? registered('rk_111111111111111111111111') + : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result.state).toBe('error') + }) + + it('fails closed when the wrapped key is for another key id', async () => { + const key = await loadCloudReaderKey('ds_1') + const sealed = sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId: 'rk_111111111111111111111111', + workspaceId: 'sbx_1', + snapshotId: 'snap_1', + payload: PAYLOAD + }) + sealed.recipient.keyId = 'rk_222222222222222222222222' + const { plane } = fakePlane((call) => + call.method === 'PUT' + ? registered('rk_222222222222222222222222') + : { status: 200, body: { snapshot: sealed } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result).toMatchObject({ state: 'error', error: { code: 'decrypt_failed' } }) + }) + + it.each(['no_snapshot', 'not_sealed_for_key', 'not_found'] as const)( + 'maps 404 %s to its state', + async (code) => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 404, body: { error: code } } + ) + await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({ state: code }) + } + ) + + it('does not renew the key on not_sealed_for_key', async () => { + const { plane, calls } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 404, body: { error: 'not_sealed_for_key' } } + ) + await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET']) + }) + + it('refuses a snapshot older than one already shown for the workspace (rollback pin)', async () => { + const key = await loadCloudReaderKey('ds_1') + const keyId = `rk_${'c'.repeat(24)}` + const seal = (snapshotId: string, capturedAt: number) => + sealLikeVm({ + readerPublicKeyB64: key.publicKeyB64, + keyId, + workspaceId: 'sbx_pin', + snapshotId, + payload: { ...PAYLOAD, workspaceId: 'sbx_pin', snapshotId, capturedAt } + }) + let next = seal('snap_new', 2_000) + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: next } } + ) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_old', 1_000) + expect(await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).toMatchObject({ + state: 'error', + error: { name: 'CloudReadSnapshotRollbackError', capturedAt: 1_000, newestShownAt: 2_000 } + }) + next = seal('snap_same', 2_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_newer', 3_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready') + next = seal('snap_same', 2_000) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('error') + }) + + it('re-registers once on invalid_request and asks again', async () => { + let gets = 0 + const { plane, calls } = fakePlane((call) => { + if (call.method === 'PUT') { + return registered( + gets === 0 ? 'rk_000000000000000000000000' : 'rk_ffffffffffffffffffffffff' + ) + } + gets += 1 + return gets === 1 + ? { status: 400, body: { error: 'invalid_request' } } + : { status: 404, body: { error: 'no_snapshot' } } + }) + await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({ + state: 'no_snapshot' + }) + expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET', 'PUT', 'GET']) + expect(calls[3]?.url).toContain('keyId=rk_ffffffffffffffffffffffff') + }) + + it('returns a 401 as an error carrying the status, for the caller to forget the session', async () => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 401, body: { error: 'unauthorized' } } + ) + const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1') + expect(result).toMatchObject({ state: 'error', error: { status: 401 } }) + }) + + it('returns a malformed reply as an error', async () => { + const { plane } = fakePlane((call) => + call.method === 'PUT' ? registered() : { status: 200, body: { snapshot: { v: 2 } } } + ) + expect((await readCloudWorkspaceSnapshot(plane, 'sbx_1')).state).toBe('error') + }) +}) diff --git a/mobile/src/cloud/cloud-read-snapshot.ts b/mobile/src/cloud/cloud-read-snapshot.ts new file mode 100644 index 00000000000..cc64e4e9b19 --- /dev/null +++ b/mobile/src/cloud/cloud-read-snapshot.ts @@ -0,0 +1,190 @@ +import { + CloudReadSnapshotResponseSchema, + CloudReaderKeyResponseSchema +} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire' +import { + openReadSnapshot, + type ReadSnapshot, + type SealedReadSnapshot +} from '../../../src/shared/cloud-workspaces/read-snapshot' +import { + CloudRequestError, + cloudRequest, + type CloudControlPlane +} from './cloud-control-plane-request' +import { loadCloudDeviceIdentity } from './cloud-device-identity' +import { loadCloudReaderKey, saveCloudReaderKeyRegistration } from './cloud-reader-key' +import { CLOUD_SEALED_PRIMITIVES } from './cloud-sealed-grant' + +// Reads a sleeping workspace's sealed snapshot without waking it. The control plane relays only +// ciphertext plus this phone's own wrapped key; the reader key's secret opens it on the phone. + +/** Re-register at most this often; the control plane bumps lastSeenAt on each. */ +export const CLOUD_READER_KEY_REFRESH_MS = 6 * 60 * 60 * 1000 + +export type CloudReadSnapshotResult = + | { state: 'ready'; snapshot: ReadSnapshot } + /** Nothing captured yet: it is captured each time the workspace goes to sleep. */ + | { state: 'no_snapshot' } + /** A snapshot exists, but this phone's key was added (or renewed) after it last slept. */ + | { state: 'not_sealed_for_key' } + /** Gone, or this phone may no longer open it. */ + | { state: 'not_found' } + /** Anything else; a 401 here means the session was revoked (see forgetRevokedCloudSession). */ + | { state: 'error'; error: unknown } + +const inflight = new Map>() + +/** + * This phone's reader key, registered with the control plane (PUT /v1/reader-keys) when it never + * was, when the last registration is over 6 h old, or when `force` is set. Null before enrollment. + */ +export async function ensureCloudReaderKey( + plane: CloudControlPlane, + options: { force?: boolean; now?: () => number } = {} +): Promise<{ keyId: string; secretKey: Uint8Array } | null> { + const enrollment = (await loadCloudDeviceIdentity()).enrollment + if (!enrollment) { + return null + } + const now = options.now ?? Date.now + const sessionId = enrollment.deviceSessionId + const running = inflight.get(sessionId) + if (running) { + return running + } + const task = (async () => { + const key = await loadCloudReaderKey(sessionId) + const registered = key.registration + if ( + !options.force && + registered && + now() - registered.registeredAt < CLOUD_READER_KEY_REFRESH_MS + ) { + return { keyId: registered.keyId, secretKey: key.secretKey } + } + const reply = await cloudRequest( + plane, + 'PUT', + '/v1/reader-keys', + CloudReaderKeyResponseSchema, + { + body: { + publicKeyB64: key.publicKeyB64, + deviceLabel: enrollment.label.trim().slice(0, 80) || 'Orca mobile', + deviceKind: 'mobile' + }, + timeoutMs: 15_000 + } + ) + const keyId = reply.readerKey.id + await saveCloudReaderKeyRegistration(key, { keyId, registeredAt: now() }) + return { keyId, secretKey: key.secretKey } + })() + inflight.set(sessionId, task) + try { + return await task + } finally { + inflight.delete(sessionId) + } +} + +async function fetchSealed( + plane: CloudControlPlane, + sandboxId: string, + keyId: string, + signal?: AbortSignal +): Promise { + const reply = await cloudRequest( + plane, + 'GET', + `/v1/team/workspaces/${encodeURIComponent(sandboxId)}/read-snapshot?keyId=${encodeURIComponent(keyId)}`, + CloudReadSnapshotResponseSchema, + { signal, timeoutMs: 20_000 } + ) + return reply.snapshot +} + +/** A snapshot older than one this phone already showed for the workspace: a rollback, refused. */ +export class CloudReadSnapshotRollbackError extends Error { + constructor( + readonly capturedAt: number, + readonly newestShownAt: number + ) { + super('read_snapshot_rollback') + this.name = 'CloudReadSnapshotRollbackError' + } +} + +// Per workspace, the newest capturedAt opened this app session. The control plane relays the +// ciphertext, so it could replay an older (validly sealed) snapshot; this pins it forward. +const newestShown = new Map() + +/** Test seam: forget the per-workspace rollback pins. */ +export function resetCloudReadSnapshotPins(): void { + newestShown.clear() +} + +type MissingState = 'no_snapshot' | 'not_sealed_for_key' | 'not_found' + +const isMissingState = (code: string): code is MissingState => + code === 'no_snapshot' || code === 'not_sealed_for_key' || code === 'not_found' + +function missingState(error: unknown): MissingState | null { + return error instanceof CloudRequestError && error.status === 404 && isMissingState(error.code) + ? error.code + : null +} + +/** The sleeping workspace's last snapshot, opened on this phone; never wakes the sandbox. */ +export async function readCloudWorkspaceSnapshot( + plane: CloudControlPlane, + sandboxId: string, + options: { signal?: AbortSignal; now?: () => number } = {} +): Promise { + const { signal, now } = options + try { + let reader = await ensureCloudReaderKey(plane, { now }) + if (!reader) { + return { state: 'error', error: new CloudRequestError('not_enrolled', 0) } + } + let sealed: SealedReadSnapshot + try { + sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal) + } catch (error) { + if ( + !(error instanceof CloudRequestError) || + error.status !== 400 || + error.code !== 'invalid_request' + ) { + throw error + } + // A key id the control plane no longer takes: register again and ask once more. + reader = await ensureCloudReaderKey(plane, { force: true, now }) + if (!reader) { + throw error + } + sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal) + } + // The AAD binds exactly the sandbox row id this phone asked for. + const snapshot = await openReadSnapshot( + sealed, + sandboxId, + reader.secretKey, + CLOUD_SEALED_PRIMITIVES + ) + const pinned = newestShown.get(sandboxId) + if (pinned !== undefined && snapshot.capturedAt < pinned) { + return { + state: 'error', + error: new CloudReadSnapshotRollbackError(snapshot.capturedAt, pinned) + } + } + newestShown.set(sandboxId, snapshot.capturedAt) + return { state: 'ready', snapshot } + } catch (error) { + // not_sealed_for_key only means the snapshot predates this key: nothing to renew here. + const missing = missingState(error) + return missing ? { state: missing } : { state: 'error', error } + } +} diff --git a/mobile/src/cloud/cloud-reader-key.test.ts b/mobile/src/cloud/cloud-reader-key.test.ts new file mode 100644 index 00000000000..803381a097e --- /dev/null +++ b/mobile/src/cloud/cloud-reader-key.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { store, options } = vi.hoisted(() => { + const options: unknown[] = [] + return { store: new Map(), options } +}) +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', + getItemAsync: vi.fn(async (key: string, opts: unknown) => { + options.push(opts) + return store.get(key) ?? null + }), + setItemAsync: vi.fn(async (key: string, value: string, opts: unknown) => { + options.push(opts) + store.set(key, value) + }), + deleteItemAsync: vi.fn(async (key: string) => { + store.delete(key) + }) +})) + +import nacl from 'tweetnacl' +import { + clearCloudReaderKey, + loadCloudReaderKey, + saveCloudReaderKeyRegistration +} from './cloud-reader-key' + +const STORE_KEY = 'orca.cloud-reader.v1' + +beforeEach(() => { + store.clear() + options.length = 0 +}) + +describe('cloud reader key store', () => { + it('generates one X25519 key lazily, this device only, and keeps it', async () => { + const [a, b] = await Promise.all([loadCloudReaderKey('ds_1'), loadCloudReaderKey('ds_1')]) + expect(a.publicKeyB64).toBe(b.publicKeyB64) + expect(a.secretKey).toHaveLength(32) + expect(a.registration).toBeNull() + expect(Buffer.from(nacl.scalarMult.base(a.secretKey)).toString('base64')).toBe(a.publicKeyB64) + expect(options).toContainEqual({ keychainAccessible: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY' }) + expect(options.every((o) => JSON.stringify(o).includes('WHEN_UNLOCKED_THIS_DEVICE_ONLY'))).toBe( + true + ) + expect((await loadCloudReaderKey('ds_1')).publicKeyB64).toBe(a.publicKeyB64) + }) + + it('records the registration for the same key only', async () => { + const key = await loadCloudReaderKey('ds_1') + await saveCloudReaderKeyRegistration(key, { keyId: 'rk_1', registeredAt: 5 }) + expect((await loadCloudReaderKey('ds_1')).registration).toEqual({ + keyId: 'rk_1', + registeredAt: 5 + }) + await saveCloudReaderKeyRegistration( + { deviceSessionId: 'ds_1', publicKeyB64: 'other' }, + { keyId: 'rk_2', registeredAt: 6 } + ) + expect((await loadCloudReaderKey('ds_1')).registration?.keyId).toBe('rk_1') + }) + + it('mints a new key for a new device session', async () => { + const first = await loadCloudReaderKey('ds_1') + await saveCloudReaderKeyRegistration(first, { keyId: 'rk_1', registeredAt: 5 }) + const second = await loadCloudReaderKey('ds_2') + expect(second.publicKeyB64).not.toBe(first.publicKeyB64) + expect(second.registration).toBeNull() + }) + + it('replaces an unreadable item and drops the key on clear', async () => { + store.set(STORE_KEY, '{not json') + const key = await loadCloudReaderKey('ds_1') + expect(key.secretKey).toHaveLength(32) + await clearCloudReaderKey() + expect(store.has(STORE_KEY)).toBe(false) + expect((await loadCloudReaderKey('ds_1')).publicKeyB64).not.toBe(key.publicKeyB64) + }) +}) diff --git a/mobile/src/cloud/cloud-reader-key.ts b/mobile/src/cloud/cloud-reader-key.ts new file mode 100644 index 00000000000..4e951001dff --- /dev/null +++ b/mobile/src/cloud/cloud-reader-key.ts @@ -0,0 +1,104 @@ +import * as SecureStore from 'expo-secure-store' +import nacl from 'tweetnacl' +import { z } from 'zod' +import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec' + +// This phone's long-lived X25519 "reader key": sleeping workspaces seal their read-only snapshot to +// its public half. The secret never leaves this keychain item (off iCloud Keychain and backups), and +// it is bound to one device session, so a new enrollment never inherits an old session's key. +const STORE_KEY = 'orca.cloud-reader.v1' +const OPTIONS: SecureStore.SecureStoreOptions = { + keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY +} + +const RegistrationSchema = z.object({ keyId: z.string().min(1), registeredAt: z.number() }) +const StoredSchema = z.object({ + deviceSessionId: z.string().min(1), + secretKeyB64: z.string(), + registration: RegistrationSchema.nullable() +}) + +export type CloudReaderKeyRegistration = z.infer + +export type CloudReaderKey = { + deviceSessionId: string + publicKeyB64: string + secretKey: Uint8Array + /** The control plane's id for this key (`rk_…`), once registered. */ + registration: CloudReaderKeyRegistration | null +} + +type Stored = z.infer + +// Every read-modify-write runs in order, so two callers never mint two keys. +let queue: Promise = Promise.resolve() +function serial(task: () => Promise): Promise { + const next = queue.then(task, task) + queue = next.catch(() => undefined) + return next +} + +async function readStored(): Promise { + const raw = await SecureStore.getItemAsync(STORE_KEY, OPTIONS) + if (!raw) { + return null + } + try { + const parsed = StoredSchema.safeParse(JSON.parse(raw)) + return parsed.success && decodeBase64Bytes(parsed.data.secretKeyB64).length === 32 + ? parsed.data + : null + } catch { + return null + } +} + +function toKey(stored: Stored): CloudReaderKey { + const secretKey = decodeBase64Bytes(stored.secretKeyB64) + return { + deviceSessionId: stored.deviceSessionId, + publicKeyB64: encodeBase64Bytes(nacl.scalarMult.base(new Uint8Array(secretKey))), + secretKey, + registration: stored.registration + } +} + +/** This session's reader key, generated on first use (only once the phone is enrolled). */ +export function loadCloudReaderKey(deviceSessionId: string): Promise { + return serial(async () => { + const stored = await readStored() + if (stored && stored.deviceSessionId === deviceSessionId) { + return toKey(stored) + } + const pair = nacl.box.keyPair() + const fresh: Stored = { + deviceSessionId, + secretKeyB64: encodeBase64Bytes(new Uint8Array(pair.secretKey)), + registration: null + } + await SecureStore.setItemAsync(STORE_KEY, JSON.stringify(fresh), OPTIONS) + return toKey(fresh) + }) +} + +/** Records the control plane's id, unless the key was replaced or dropped meanwhile. */ +export function saveCloudReaderKeyRegistration( + key: Pick, + registration: CloudReaderKeyRegistration | null +): Promise { + return serial(async () => { + const stored = await readStored() + if (!stored || stored.deviceSessionId !== key.deviceSessionId) { + return + } + if (toKey(stored).publicKeyB64 !== key.publicKeyB64) { + return + } + await SecureStore.setItemAsync(STORE_KEY, JSON.stringify({ ...stored, registration }), OPTIONS) + }) +} + +/** Drops the key with the cloud session: nothing this phone could read outlives its access. */ +export function clearCloudReaderKey(): Promise { + return serial(() => SecureStore.deleteItemAsync(STORE_KEY, OPTIONS)) +} diff --git a/mobile/src/cloud/cloud-sealed-grant.ts b/mobile/src/cloud/cloud-sealed-grant.ts index 6cbf032cbce..eba15132cb7 100644 --- a/mobile/src/cloud/cloud-sealed-grant.ts +++ b/mobile/src/cloud/cloud-sealed-grant.ts @@ -9,8 +9,8 @@ import { type SealedGrantPrimitives } from '../../../src/shared/cloud-workspaces/sealed-grant' -// Hermes has no WebCrypto, so the shared opener runs on pure-JS primitives here. -const PRIMITIVES: SealedGrantPrimitives = { +// Hermes has no WebCrypto, so the shared openers (grants, read snapshots) run on pure-JS primitives. +export const CLOUD_SEALED_PRIMITIVES: SealedGrantPrimitives = { x25519: (secretKey, publicKey) => nacl.scalarMult(new Uint8Array(secretKey), new Uint8Array(publicKey)), x25519PublicKey: (secretKey) => nacl.scalarMult.base(new Uint8Array(secretKey)), @@ -29,5 +29,5 @@ export function openCloudSealedGrant( grantId: string, recipientSecretKey: Uint8Array ): Promise { - return openSealedGrant(sealed, grantId, recipientSecretKey, PRIMITIVES, 'mobile') + return openSealedGrant(sealed, grantId, recipientSecretKey, CLOUD_SEALED_PRIMITIVES, 'mobile') } diff --git a/mobile/src/cloud/cloud-workspace-copy.ts b/mobile/src/cloud/cloud-workspace-copy.ts index 76388468114..7e637d15d41 100644 --- a/mobile/src/cloud/cloud-workspace-copy.ts +++ b/mobile/src/cloud/cloud-workspace-copy.ts @@ -37,7 +37,9 @@ export function attachErrorMessage( 'cloud.error.pairing', 'The workspace is running, but this phone couldn’t connect to it. Your files are safe.' ) - default: + case 'not_found': + return t('cloud.workspace.missing', 'This workspace is gone or you no longer have access.') + case 'failed': return t( 'cloud.error.failed', 'The workspace couldn’t start. Try again, or open it on your desktop.' @@ -128,6 +130,9 @@ export function cloudPromptErrorMessage(code: string | undefined, t: Translate): return t('cloud.prompt.errorNotConnected', 'This phone couldn’t reach the workspace') case 'cloud_agent_unknown': return t('cloud.prompt.errorAgent', 'That agent isn’t installed in this workspace') + // An older queue entry may carry no code: it failed to launch all the same. + case undefined: + case 'launch_failed': default: return t('cloud.prompt.errorLaunch', 'The agent didn’t start') } diff --git a/mobile/src/cloud/use-cloud-read-snapshot.ts b/mobile/src/cloud/use-cloud-read-snapshot.ts new file mode 100644 index 00000000000..11c74d23cf1 --- /dev/null +++ b/mobile/src/cloud/use-cloud-read-snapshot.ts @@ -0,0 +1,38 @@ +import { useQuery } from '@tanstack/react-query' +import { readCloudWorkspaceSnapshot, type CloudReadSnapshotResult } from './cloud-read-snapshot' +import { + forgetRevokedCloudSession, + loadCloudControlPlane, + useCloudHostRemoval +} from './cloud-session' + +/** + * The sleeping workspace's read-only snapshot, fetched only while it is asleep and never waking it. + * Keyed by `readSnapshotAt`, so a newer sleep refetches; kept in memory only (never persisted). + */ +export function useCloudReadSnapshot( + sandboxId: string, + asleep: boolean, + readSnapshotAt: number | null +) { + const removal = useCloudHostRemoval() + return useQuery({ + queryKey: ['orca-cloud', 'read-snapshot', sandboxId, readSnapshotAt], + enabled: asleep, + queryFn: async ({ signal }) => { + const plane = await loadCloudControlPlane() + if (!plane) { + return { state: 'error', error: new Error('not_enrolled') } + } + const result = await readCloudWorkspaceSnapshot(plane, sandboxId, { signal }) + if (result.state === 'error') { + await forgetRevokedCloudSession(result.error, removal) + } + return result + }, + // A snapshot only changes when the workspace sleeps again, which changes the key above. + staleTime: 5 * 60_000, + gcTime: 60_000, + retry: false + }) +} diff --git a/mobile/src/cloud/use-cloud-workspaces.ts b/mobile/src/cloud/use-cloud-workspaces.ts index 3ef74125e1f..d918f99b568 100644 --- a/mobile/src/cloud/use-cloud-workspaces.ts +++ b/mobile/src/cloud/use-cloud-workspaces.ts @@ -13,6 +13,7 @@ import { type CloudEnrollment } from './cloud-device-identity' import { pruneCloudHostsMissingFrom } from './cloud-host-pruning' +import { ensureCloudReaderKey } from './cloud-read-snapshot' import { cloudHostRemover, forgetRevokedCloudSession, @@ -75,6 +76,8 @@ export function useCloudWorkspaces(enrollment: CloudEnrollment | null | undefine try { const startedAt = Date.now() const list = await listCloudWorkspaces(plane, signal) + // Keeps this phone's reader key registered (at most every 6 h) so the next sleep seals to it. + void ensureCloudReaderKey(plane).catch(() => undefined) if (list.complete) { // A linked workspace the list lacks is checked by id; one the registry says is gone // (destroyed, or no longer shared) stops being retried. diff --git a/mobile/src/home/MobileHomeCloudSection.tsx b/mobile/src/home/MobileHomeCloudSection.tsx index 025049effbb..ff4aa8d6679 100644 --- a/mobile/src/home/MobileHomeCloudSection.tsx +++ b/mobile/src/home/MobileHomeCloudSection.tsx @@ -2,6 +2,7 @@ import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native' import { Fragment, useState } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' import { CloudStatusDot } from '../cloud/CloudStatusDot' +import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection' import type { CloudWorkspace } from '../cloud/cloud-control-plane-client' import { CloudEnrollmentError, enrollCloudDevice } from '../cloud/cloud-device-enrollment' import type { CloudEnrollment } from '../cloud/cloud-device-identity' @@ -154,10 +155,17 @@ function CloudWorkspaceRow({ ago: formatTimeAgo(workspace.createdAt, reference) }) // "Created just now · just now" says one thing twice: the activity time adds nothing yet. + // Asleep with a saved read-only copy: say how fresh that copy is; it opens without waking. const when = - createdLine && lastActive - workspace.createdAt < 60_000 - ? null - : formatTimeAgo(lastActive, reference) + workspace.status === 'sleeping' && workspace.readSnapshotAt + ? formatReadSnapshotAsOf( + workspace.readSnapshotAt, + Math.max(reference, workspace.readSnapshotAt), + t + ) + : createdLine && lastActive - workspace.createdAt < 60_000 + ? null + : formatTimeAgo(lastActive, reference) const line = [status, detail, when].filter(Boolean).join(' · ') return ( (await import('./handlers/cloud-env.js')).CLOUD_ENV_HANDLERS }, + { + name: 'secret', + keys: ['secret request'], + load: async () => (await import('./handlers/secret.js')).SECRET_HANDLERS + }, { name: 'speech', keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'], diff --git a/src/cli/handlers/secret.test.ts b/src/cli/handlers/secret.test.ts new file mode 100644 index 00000000000..e7196f317df --- /dev/null +++ b/src/cli/handlers/secret.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from 'vitest' +import { RuntimeClientError } from '../runtime/types' +import { parseSecretRequestWait, runSecretRequest, type SecretRequestCliInput } from './secret' + +const HINT = + 'STRIPE_KEY is set for new shells in this workspace. To use it in this shell: eval "$(orca-env)" (fish: orca-env --fish | source).' + +function harness(answers: { request: unknown; statuses?: string[] }) { + const clock = { now: 0 } + const calls: { method: string; params: unknown }[] = [] + const printed: string[] = [] + const statuses = [...(answers.statuses ?? [])] + return { + calls, + printed, + deps: { + call: async (method: string, params: unknown): Promise => { + calls.push({ method, params }) + if (method === 'secrets.request') { + if (answers.request instanceof Error) { + throw answers.request + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned reply for this method. + return answers.request as T + } + const status = statuses.shift() ?? 'pending' + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned requestStatus reply. + return { requestId: 'sr_abcdefgh', name: 'STRIPE_KEY', status, expiresAt: 0 } as T + }, + sleep: async (ms: number) => { + clock.now += ms + }, + now: () => clock.now, + print: (line: string) => printed.push(line) + } + } +} + +const base: SecretRequestCliInput = { + name: 'STRIPE_KEY', + reason: 'Run the checkout tests', + waitSec: null, + json: false, + worktreeId: 'wt-1' +} + +describe('orca secret request', () => { + it('names no terminal or agent: orcad derives them from verified launch evidence', async () => { + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await runSecretRequest({ ...base, scope: 'repo' }, h.deps) + expect(h.calls[0]).toEqual({ + method: 'secrets.request', + params: { + name: 'STRIPE_KEY', + reason: 'Run the checkout tests', + scope: 'repo', + worktreeId: 'wt-1' + } + }) + }) + + it('without --wait, reports the pending request and exits 0', async () => { + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await expect(runSecretRequest(base, h.deps)).resolves.toBe(0) + expect(h.printed).toEqual([ + 'Asked the person for STRIPE_KEY (sr_abcdefgh). Add --wait to wait for the answer.' + ]) + }) + + it('with --wait, polls until provided and prints the D4 reload hint exactly', async () => { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: ['pending', 'pending', 'provided'] + }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0) + expect(h.printed).toEqual([HINT]) + expect(h.calls.filter((c) => c.method === 'secrets.requestStatus')).toHaveLength(3) + }) + + it('prints JSON with the hint when provided', async () => { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: ['provided'] + }) + await runSecretRequest({ ...base, waitSec: 60, json: true }, h.deps) + expect(JSON.parse(h.printed[0])).toEqual({ + requestId: 'sr_abcdefgh', + name: 'STRIPE_KEY', + status: 'provided', + hint: HINT + }) + }) + + it('exits 1 when declined, expired, or the wait runs out', async () => { + for (const [status, line] of [ + ['declined', 'The person declined to provide STRIPE_KEY.'], + ['expired', 'The request for STRIPE_KEY expired before anyone answered it.'] + ]) { + const h = harness({ + request: { requestId: 'sr_abcdefgh', status: 'pending' }, + statuses: [status] + }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(1) + expect(h.printed).toEqual([line]) + } + const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } }) + await expect(runSecretRequest({ ...base, waitSec: 5 }, h.deps)).resolves.toBe(1) + expect(h.printed[0]).toBe( + 'Still waiting for STRIPE_KEY (sr_abcdefgh). Run the same command again to keep waiting.' + ) + }) + + it('reports already-set without polling', async () => { + const h = harness({ request: { requestId: null, status: 'already-set' } }) + await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0) + expect(h.calls).toHaveLength(1) + expect(h.printed[0]).toContain('STRIPE_KEY is already set in this workspace.') + }) + + it('explains refusals in words', async () => { + const h = harness({ + request: new RuntimeClientError('runtime_error', 'use_sign_in_or_cloud_secrets') + }) + await expect(runSecretRequest({ ...base, name: 'ANTHROPIC_API_KEY' }, h.deps)).rejects.toThrow( + "ANTHROPIC_API_KEY is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested." + ) + }) + + it('parses --wait', () => { + expect(parseSecretRequestWait(undefined)).toBeNull() + expect(parseSecretRequestWait(true)).toBe(900) + expect(parseSecretRequestWait('30')).toBe(30) + expect(parseSecretRequestWait('99999')).toBe(3600) + expect(() => parseSecretRequestWait('soon')).toThrow('--wait takes a number of seconds') + expect(() => parseSecretRequestWait('0')).toThrow() + }) +}) diff --git a/src/cli/handlers/secret.ts b/src/cli/handlers/secret.ts new file mode 100644 index 00000000000..ba89eb2e672 --- /dev/null +++ b/src/cli/handlers/secret.ts @@ -0,0 +1,200 @@ +import type { CommandHandler } from '../dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' +import { + SECRET_REQUEST_ERRORS, + SECRET_REQUEST_REASON_MAX, + SECRETS_REQUEST_METHOD, + SECRETS_REQUEST_STATUS_METHOD, + secretReloadHint, + type SecretRequestScope, + type SecretRequestStatus, + type SecretsRequestParams, + type SecretsRequestResult, + type SecretsRequestStatusResult +} from '../../shared/secret-request-contract' + +const DEFAULT_WAIT_SEC = 900 +const MAX_WAIT_SEC = 3600 +const POLL_MS = 2000 + +export type SecretRequestOutcome = SecretRequestStatus | 'already-set' + +export type SecretRequestCliDeps = { + call: (method: string, params: unknown) => Promise + sleep: (ms: number) => Promise + now: () => number + print: (line: string) => void +} + +export type SecretRequestCliInput = { + name: string + reason: string + scope?: SecretRequestScope + waitSec: number | null + json: boolean + worktreeId?: string +} + +/** Returns the exit code. */ +export async function runSecretRequest( + input: SecretRequestCliInput, + deps: SecretRequestCliDeps +): Promise { + const params: SecretsRequestParams = { + name: input.name, + reason: input.reason, + ...(input.scope ? { scope: input.scope } : {}), + // The calling terminal (and so the agent) travels as launch evidence that orcad verifies. + ...(input.worktreeId ? { worktreeId: input.worktreeId } : {}) + } + let created: SecretsRequestResult + try { + created = await deps.call(SECRETS_REQUEST_METHOD, params) + } catch (error) { + throw explainRequestError(error, input.name) + } + if (created.status === 'already-set') { + return finish(input, deps, { requestId: null, status: 'already-set' }) + } + const requestId = created.requestId + if (input.waitSec === null) { + return finish(input, deps, { requestId, status: 'pending' }) + } + const deadline = deps.now() + input.waitSec * 1000 + for (;;) { + const current = await deps.call(SECRETS_REQUEST_STATUS_METHOD, { + requestId + }) + if (current.status !== 'pending' || deps.now() >= deadline) { + return finish(input, deps, { requestId, status: current.status, waited: true }) + } + await deps.sleep(Math.min(POLL_MS, Math.max(0, deadline - deps.now()))) + } +} + +function finish( + input: SecretRequestCliInput, + deps: SecretRequestCliDeps, + result: { requestId: string | null; status: SecretRequestOutcome; waited?: boolean } +): number { + const answered = result.status === 'provided' || result.status === 'already-set' + const exitCode = answered || (result.status === 'pending' && !result.waited) ? 0 : 1 + if (input.json) { + deps.print( + JSON.stringify( + { + requestId: result.requestId, + name: input.name, + status: result.status, + ...(result.status === 'provided' || result.status === 'already-set' + ? { hint: secretReloadHint(input.name) } + : {}) + }, + null, + 2 + ) + ) + return exitCode + } + deps.print(formatSecretRequestOutcome(input.name, result.requestId, result.status, result.waited)) + return exitCode +} + +export function formatSecretRequestOutcome( + name: string, + requestId: string | null, + status: SecretRequestOutcome, + waited = false +): string { + switch (status) { + case 'provided': + return secretReloadHint(name) + case 'already-set': + return `${name} is already set in this workspace. If this shell doesn't have it yet: eval "$(orca-env)" (fish: orca-env --fish | source).` + case 'declined': + return `The person declined to provide ${name}.` + case 'expired': + return `The request for ${name} expired before anyone answered it.` + case 'pending': + return waited + ? `Still waiting for ${name} (${requestId}). Run the same command again to keep waiting.` + : `Asked the person for ${name} (${requestId}). Add --wait to wait for the answer.` + } +} + +const ERROR_MESSAGES: Record string> = { + [SECRET_REQUEST_ERRORS.invalidName]: (name) => + `${name} is not a valid secret name: use A-Z, 0-9 and _, not starting with a digit.`, + [SECRET_REQUEST_ERRORS.reservedName]: (name) => + `${name} is reserved: Orca or the system manages it, so it can't be a secret.`, + [SECRET_REQUEST_ERRORS.subscriptionTokenRefused]: () => + 'CLAUDE_CODE_OAUTH_TOKEN is never stored. Ask the person to sign Claude in instead.', + [SECRET_REQUEST_ERRORS.agentCredential]: (name) => + `${name} is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested.`, + [SECRET_REQUEST_ERRORS.tooManyPending]: () => + 'This workspace already has 3 secret requests waiting. Wait for one to be answered.', + [SECRET_REQUEST_ERRORS.rateLimited]: () => + 'This workspace asked for 10 secrets in the last hour. Try again later.', + [SECRET_REQUEST_ERRORS.unavailable]: () => + 'Secret requests work only inside an Orca Cloud workspace.' +} + +function explainRequestError(error: unknown, name: string): unknown { + if (!(error instanceof RuntimeClientError)) { + return error + } + const explain = ERROR_MESSAGES[error.message] + return explain ? new RuntimeClientError(error.message, explain(name)) : error +} + +export function parseSecretRequestWait(value: string | boolean | undefined): number | null { + if (value === undefined) { + return null + } + if (value === true) { + return DEFAULT_WAIT_SEC + } + const seconds = Number(value) + if (typeof value !== 'string' || !/^\d+$/.test(value) || seconds < 1) { + throw new RuntimeClientError('invalid_argument', '--wait takes a number of seconds') + } + return Math.min(seconds, MAX_WAIT_SEC) +} + +function parseScope(value: string | undefined): SecretRequestScope | undefined { + if (value === undefined || value === 'personal' || value === 'repo') { + return value + } + throw new RuntimeClientError('invalid_argument', '--scope is personal or repo') +} + +export const SECRET_HANDLERS: Record = { + 'secret request': async ({ flags, client, json }) => { + const name = getRequiredStringFlag(flags, 'name') + const reason = getRequiredStringFlag(flags, 'reason').trim() + if (reason.length === 0 || reason.length > SECRET_REQUEST_REASON_MAX) { + throw new RuntimeClientError( + 'invalid_argument', + `--reason must be 1-${SECRET_REQUEST_REASON_MAX} characters` + ) + } + process.exitCode = await runSecretRequest( + { + name, + reason, + scope: parseScope(getOptionalStringFlag(flags, 'scope')), + waitSec: parseSecretRequestWait(flags.get('wait')), + json, + worktreeId: process.env.ORCA_WORKTREE_ID || undefined + }, + { + call: async (method: string, params: unknown) => + (await client.call(method, params)).result, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + now: Date.now, + print: (line) => console.log(line) + } + ) + } +} diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index b28fd7feb1c..bbcbaea79e3 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -93,6 +93,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' cloud messages List or show messages sent to a cloud workspace', ' cloud sessions List agent sessions in a cloud workspace', ' cloud projects list List Orca Cloud projects', + ' secret request Ask the person for a secret this workspace needs', '', 'Automations:', ' automations list List scheduled Orca automations', diff --git a/src/cli/runtime/orchestration-compatibility-envelope.ts b/src/cli/runtime/orchestration-compatibility-envelope.ts index be78e8dee2f..84fbd908309 100644 --- a/src/cli/runtime/orchestration-compatibility-envelope.ts +++ b/src/cli/runtime/orchestration-compatibility-envelope.ts @@ -28,6 +28,8 @@ export function createAgentLaunchCallerEvidence( } const AGENT_LAUNCH_METHODS: ReadonlySet = new Set(['agent.launch', 'agent.launchReplay']) +/** Methods where orcad names the calling terminal (and its agent) from the shell's launch evidence. */ +const TERMINAL_CALLER_METHODS: ReadonlySet = new Set(['secrets.request']) /** The caller evidence one request carries, read from this process's environment once. */ export class OrchestrationRequestEvidence { @@ -58,6 +60,11 @@ export class OrchestrationRequestEvidence { compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId } } + if (TERMINAL_CALLER_METHODS.has(method)) { + // Terminal evidence only: it identifies a caller on this host, never on a remote server. + const shell = this.remoteRead.orchestrationCompatibilityEvidence + return request.remote || !shell ? {} : { orchestrationCompatibilityEvidence: shell } + } return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller ? { orchestrationCompatibilityEvidence: this.agentLaunchCaller } : {} diff --git a/src/cli/runtime/orchestration-request-evidence.test.ts b/src/cli/runtime/orchestration-request-evidence.test.ts index aceef390bc2..9d5d3407068 100644 --- a/src/cli/runtime/orchestration-request-evidence.test.ts +++ b/src/cli/runtime/orchestration-request-evidence.test.ts @@ -26,3 +26,40 @@ describe('caller evidence on requests to another server', () => { ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) }) }) + +describe('terminal evidence on secret requests', () => { + const SHELL = { + ...CHAT, + ORCA_TERMINAL_HANDLE: 'term_1', + ORCA_PANE_KEY: 'tab:leaf', + ORCA_AGENT_LAUNCH_TOKEN: 'tok' + } + + it('sends the shell evidence (never the chat id) to this host so orcad can verify the caller', () => { + const evidence = new OrchestrationRequestEvidence(SHELL) + expect( + evidence.envelopeFor('secrets.request', { + remote: false, + mutation: false, + requestId: undefined + }) + ).toEqual({ + orchestrationCompatibilityEvidence: { + terminalHandle: 'term_1', + paneKey: 'tab:leaf', + launchToken: 'tok' + } + }) + }) + + it('sends nothing to another server', () => { + const evidence = new OrchestrationRequestEvidence(SHELL) + expect( + evidence.envelopeFor('secrets.request', { + remote: true, + mutation: false, + requestId: undefined + }) + ).toEqual({}) + }) +}) diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index dfeb0239e7f..89714b6524c 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -26,6 +26,7 @@ import { VM_COMMAND_SPECS } from './vm' import { VM_ENV_COMMAND_SPECS } from './vm-env' import { CLOUD_ENV_COMMAND_SPECS } from './cloud-env' import { CLOUD_SSH_COMMAND_SPECS } from './cloud-ssh' +import { SECRET_COMMAND_SPECS } from './secret' import { SKILL_COMMAND_SPECS } from './skills' import { ARTIFACT_COMMAND_SPECS } from './artifacts' import { SEARCH_COMMAND_SPECS } from './search' @@ -66,6 +67,7 @@ export const COMMAND_SPECS: CommandSpec[] = [ ...VM_ENV_COMMAND_SPECS, ...CLOUD_ENV_COMMAND_SPECS, ...CLOUD_SSH_COMMAND_SPECS, + ...SECRET_COMMAND_SPECS, ...EMULATOR_COMMAND_SPECS, ...SKILL_COMMAND_SPECS, ...SEARCH_COMMAND_SPECS, diff --git a/src/cli/specs/secret.ts b/src/cli/specs/secret.ts new file mode 100644 index 00000000000..da2b904c9b0 --- /dev/null +++ b/src/cli/specs/secret.ts @@ -0,0 +1,26 @@ +import type { CommandSpec } from '../args' +import { LOCAL_COMMAND_FLAGS } from '../args' + +export const SECRET_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['secret', 'request'], + summary: 'Ask the person to provide a secret for this workspace', + usage: + 'orca secret request --reason "" [--scope personal|repo] [--wait ] [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS, 'name', 'reason', 'scope', 'wait'], + positionalArgs: ['name'], + notes: [ + 'Orca shows the person a card with NAME and your reason; they type the value. The value never passes through you or this command.', + 'Once provided, NAME is set for new shells in this workspace. In the current shell run eval "$(orca-env)" (fish: orca-env --fish | source).', + '--reason (at most 200 characters) is shown to the person as your words. Say what the secret unblocks.', + '--scope is a hint: the person chooses where it is saved.', + '--wait waits for an answer (default without a number: 900). Running the same request again while it is pending waits on it rather than asking twice.', + "Agent keys (ANTHROPIC_*, OPENAI_* and similar) cannot be requested: they come from the person's sign-in or Orca Cloud secrets.", + 'Exits 1 when the request is declined, expires, or --wait ends without an answer.' + ], + examples: [ + 'orca secret request STRIPE_TEST_KEY --reason "Run the checkout integration tests" --wait 600', + 'orca secret request SENTRY_DSN --reason "Upload source maps in the release script" --json' + ] + } +] diff --git a/src/main/billing/billing-client.test.ts b/src/main/billing/billing-client.test.ts index 1bf5c759c24..14d52ed8520 100644 --- a/src/main/billing/billing-client.test.ts +++ b/src/main/billing/billing-client.test.ts @@ -132,8 +132,8 @@ describe('billing client', () => { const offers = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, idleSleepMinutes: 15, diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index ff8d113bf25..c53653a6bc7 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -111,7 +111,8 @@ const OffersSchema = z concurrentSandboxesPerSeat: z.number().int().nonnegative(), idleSleepMinutes: z.number().int().positive(), overageCentsPerHour: z.number().int().positive(), - defaultSpendCapCents: z.number().int().nonnegative() + defaultSpendCapCents: z.number().int().nonnegative(), + maxSpendCapCents: z.number().int().positive().nullable().catch(null) }), enterprise: z.object({ label: z.string().max(40), diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 56033281053..502a3502990 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -14,6 +14,16 @@ import { withCloudBuildDefaults } from '../cloud-build-defaults' import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' import { HOSTED_SANDBOX_DRIVER_ID } from '../hosted-sandbox/hosted-sandbox-driver' import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install' +import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' +import { + cloudSecretNameError, + cloudSecretSwapped, + cloudSecretValueError +} from '../../shared/cloud-secrets/cloud-secret-rules' +import { + desktopKeyValueForCloud, + setCloudDesktopKeysUserDataPath +} from '../hosted-sandbox/cloud-desktop-keys' import { cloudSecretsFailureCode, createCloudSecretsClient, @@ -45,6 +55,10 @@ const BatchRequest = z ) const EffectiveRequest = z.object({ repo: Repo.optional() }) const RefreshRequest = z.object({ runtimeEnvironmentId: z.string().min(1).max(256) }) +const SaveDesktopKeyRequest = z.object({ + agent: z.string().refine(isTuiAgent), + envName: Name +}) const CHANNELS = [ 'cloudSecrets:status', @@ -53,7 +67,8 @@ const CHANNELS = [ 'cloudSecrets:remove', 'cloudSecrets:batch', 'cloudSecrets:effective', - 'cloudSecrets:refreshEnv' + 'cloudSecrets:refreshEnv', + 'cloudSecrets:saveDesktopKey' ] as const async function attempt( @@ -85,6 +100,7 @@ function sandboxIdFor(userDataPath: string, runtimeEnvironmentId: string): strin } export function registerCloudSecretsHandlers(userDataPath: string): void { + setCloudDesktopKeysUserDataPath(userDataPath) // Packaged integration builds read no shell env; their control-plane URL is baked in. const config = getHostedSandboxConfig( userDataPath, @@ -137,6 +153,32 @@ export function registerCloudSecretsHandlers(userDataPath: string): void { const request = EffectiveRequest.safeParse(raw ?? {}) return request.success ? attempt(client, (c) => c.effective(request.data.repo)) : invalid }) + // One desktop-sealed key, unsealed here and sent once to the user's personal Cloud secrets; the + // renderer names it (agent + variable) and never sees the value. Each call is one explicit click. + ipcMain.handle('cloudSecrets:saveDesktopKey', async (_event, raw: unknown) => { + const request = SaveDesktopKeyRequest.safeParse(raw) + if (!request.success || !isTuiAgent(request.data.agent)) { + return invalid + } + const { agent, envName } = request.data + const nameError = cloudSecretNameError(envName) + if (nameError) { + return { ok: false, error: nameError } + } + // Only keys the workspace gets as a stand-in: anything else would sit there in full. + if (!cloudSecretSwapped(envName)) { + return { ok: false, error: 'not_swappable' } + } + const value = await desktopKeyValueForCloud(agent, envName) + if (!value) { + return { ok: false, error: 'not_found' } + } + const valueError = cloudSecretValueError(envName, value) + if (valueError) { + return { ok: false, error: valueError } + } + return attempt(client, (c) => c.put({ scope: 'personal' }, envName, value)) + }) ipcMain.handle('cloudSecrets:refreshEnv', (_event, raw: unknown) => { const request = RefreshRequest.safeParse(raw) if (!request.success) { diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts new file mode 100644 index 00000000000..682443282d7 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it, vi } from 'vitest' +import { CloudWorkspacesError, type ReadSnapshotFetch } from './cloud-workspaces-client' +import { + createReadSnapshotReader, + READER_KEY_REFRESH_MS, + type ReaderKeyAccess +} from './cloud-read-snapshot-reader' +import { generateGrantRecipientKey } from './sealed-grant-node' +import { sealReadSnapshotForTest } from './read-snapshot-sealer.test-fixture' + +const SBX = 'sbx_0123456789abcdef01234567' +const KEY_A = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa' +const KEY_B = 'rk_bbbbbbbbbbbbbbbbbbbbbbbb' + +const payload = { + v: 1, + workspaceId: SBX, + snapshotId: 'snap_1', + capturedAt: 1_700_000_000_000, + reason: 'sleep', + git: { + branch: 'main', + head: 'abc1234', + changes: [{ path: 'src/a.ts', status: 'modified', area: 'unstaged', added: 3, removed: 1 }], + changeCount: 1, + added: 3, + removed: 1, + commits: [{ id: 'abc1234', subject: 'Fix', author: 'Ada', at: 1 }] + }, + pr: { + number: 42, + title: 'Fix it', + state: 'open', + url: 'https://github.com/acme/web/pull/42', + checksStatus: 'success', + checksSummary: '3/3 passed' + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Fix the bug', + status: 'idle', + turnOutcome: 'done', + updatedAt: 2, + messages: [{ itemId: 'm1', role: 'assistant', text: 'Done.', at: 2 }], + truncated: false + } + ] +} + +function setup(options: { identity?: string | null; keychain?: boolean } = {}) { + const key = generateGrantRecipientKey() + let identity: string | null = options.identity === undefined ? 'me' : options.identity + const readerKey: ReaderKeyAccess = { + identity: () => identity, + load: async () => + options.keychain === false + ? { ok: false, reason: 'keychain_unavailable', message: 'no keychain' } + : { ok: true, key }, + peek: async () => (options.keychain === false ? null : key) + } + let now = 10_000 + const ids = [KEY_A] + const registerReaderKey = vi.fn(async () => ({ + id: ids[0]!, + deviceKind: 'desktop' as const, + deviceLabel: 'test', + createdAt: 1, + lastSeenAt: 1 + })) + let capturedAt = payload.capturedAt + const getReadSnapshot = vi.fn(async (_id: string, keyId: string): Promise => ({ + kind: 'sealed', + sealed: sealReadSnapshotForTest({ + payload: { ...payload, capturedAt }, + workspaceId: SBX, + snapshotId: 'snap_1', + readerPublicKeyB64: key.publicKeyB64, + keyId, + storedAt: 5 + }) + })) + const deleteReaderKey = vi.fn(async (_keyId: string, _timeoutMs?: number) => {}) + const reader = createReadSnapshotReader({ + client: { registerReaderKey, getReadSnapshot, deleteReaderKey }, + readerKey, + deviceLabel: () => 'test-mac', + now: () => now + }) + return { + reader, + key, + ids, + registerReaderKey, + getReadSnapshot, + deleteReaderKey, + setCapturedAt: (at: number) => { + capturedAt = at + }, + tick: (ms: number) => { + now += ms + }, + setIdentity: (next: string | null) => { + identity = next + } + } +} + +describe('createReadSnapshotReader', () => { + it('registers the key, then opens a snapshot sealed to it (independent sealer roundtrip)', async () => { + const t = setup() + const result = await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledWith({ + publicKeyB64: t.key.publicKeyB64, + deviceLabel: 'test-mac', + deviceKind: 'desktop' + }) + expect(t.getReadSnapshot).toHaveBeenCalledWith(SBX, KEY_A) + expect(result.state).toBe('ready') + if (result.state !== 'ready') { + return + } + expect(result.storedAt).toBe(5) + expect(result.snapshot.capturedAt).toBe(payload.capturedAt) + expect(result.snapshot.pr?.number).toBe(42) + expect(result.snapshot.git?.changes[0]).toMatchObject({ path: 'src/a.ts', added: 3 }) + expect(result.snapshot.sessions[0]).toMatchObject({ agent: 'claude', status: 'idle' }) + }) + + it('reuses the registration for 6 h, then refreshes it', async () => { + const t = setup() + await t.reader.register() + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + t.tick(READER_KEY_REFRESH_MS) + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + }) + + it('shares one registration between concurrent callers', async () => { + const t = setup() + await Promise.all([t.reader.register(), t.reader.read(SBX), t.reader.read(SBX)]) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('registers again after an account switch', async () => { + const t = setup() + await t.reader.read(SBX) + t.setIdentity('someone-else') + await t.reader.read(SBX) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + }) + + it.each(['no_snapshot', 'not_found'] as const)('reports %s as a state', async (kind) => { + const t = setup() + t.getReadSnapshot.mockResolvedValueOnce({ kind }) + expect(await t.reader.read(SBX)).toEqual({ state: kind }) + }) + + it('reports not_sealed_for_key when the snapshot predates a freshly registered key', async () => { + const t = setup() + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) + expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('never re-registers on not_sealed_for_key (the snapshot just predates the key)', async () => { + const t = setup() + await t.reader.register() + t.ids[0] = KEY_B + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' }) + expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + expect(t.getReadSnapshot).toHaveBeenCalledTimes(1) + }) + + it('re-registers at most once on invalid_request', async () => { + const t = setup() + await t.reader.register() + t.getReadSnapshot + .mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + .mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'invalid_request' }) + expect(t.registerReaderKey).toHaveBeenCalledTimes(2) + expect(t.getReadSnapshot).toHaveBeenCalledTimes(2) + }) + + it('refuses a snapshot older than one already shown (rollback pin), per workspace and account', async () => { + const t = setup() + t.setCapturedAt(2_000) + expect((await t.reader.read(SBX)).state).toBe('ready') + // The same snapshot again is fine; a newer one moves the pin. + expect((await t.reader.read(SBX)).state).toBe('ready') + t.setCapturedAt(3_000) + expect((await t.reader.read(SBX)).state).toBe('ready') + t.setCapturedAt(2_500) + expect(await t.reader.read(SBX)).toEqual({ state: 'stale' }) + // Another account on this computer has its own pin. + t.setIdentity('someone-else') + expect((await t.reader.read(SBX)).state).toBe('ready') + }) + + it('revokes the registered key server-side on sign-out', async () => { + const t = setup() + await t.reader.register() + await t.reader.revoke(1_000) + expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + }) + + it('learns the key id before revoking when this run never registered', async () => { + const t = setup() + await t.reader.revoke(1_000) + expect(t.registerReaderKey).toHaveBeenCalledTimes(1) + expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000) + }) + + it('revokes nothing without a key or when signed out', async () => { + await setup({ keychain: false }).reader.revoke(1_000) + const signedOut = setup({ identity: null }) + await signedOut.reader.revoke(1_000) + expect(signedOut.deleteReaderKey).not.toHaveBeenCalled() + expect(signedOut.registerReaderKey).not.toHaveBeenCalled() + }) + + it('re-registers on invalid_request for a remembered key id', async () => { + const t = setup() + await t.reader.register() + t.ids[0] = KEY_B + t.getReadSnapshot.mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request')) + expect((await t.reader.read(SBX)).state).toBe('ready') + expect(t.getReadSnapshot).toHaveBeenLastCalledWith(SBX, KEY_B) + }) + + it('is off with a clear reason without an OS keychain', async () => { + const t = setup({ keychain: false }) + expect(await t.reader.read(SBX)).toEqual({ + state: 'unavailable', + reason: 'keychain_unavailable', + message: 'no keychain' + }) + expect(t.registerReaderKey).not.toHaveBeenCalled() + }) + + it('refuses when signed out', async () => { + const t = setup({ identity: null }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'unauthorized' }) + }) + + it('turns a snapshot sealed to another key into snapshot_unreadable', async () => { + const t = setup() + const other = generateGrantRecipientKey() + t.getReadSnapshot.mockResolvedValueOnce({ + kind: 'sealed', + sealed: sealReadSnapshotForTest({ + payload, + workspaceId: SBX, + snapshotId: 'snap_1', + readerPublicKeyB64: other.publicKeyB64, + keyId: KEY_A + }) + }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ + code: 'snapshot_unreadable', + reason: 'decrypt_failed' + }) + }) + + it('refuses a snapshot of another workspace', async () => { + const t = setup() + const sealed = sealReadSnapshotForTest({ + payload: { ...payload, workspaceId: 'sbx_ffffffffffffffffffffffff' }, + workspaceId: 'sbx_ffffffffffffffffffffffff', + snapshotId: 'snap_1', + readerPublicKeyB64: t.key.publicKeyB64, + keyId: KEY_A + }) + t.getReadSnapshot.mockResolvedValueOnce({ kind: 'sealed', sealed }) + await expect(t.reader.read(SBX)).rejects.toMatchObject({ reason: 'wrong_workspace' }) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts new file mode 100644 index 00000000000..01d2cebcc70 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-read-snapshot-reader.ts @@ -0,0 +1,194 @@ +// Reads a sleeping Orca Cloud workspace from the sealed snapshot it left on the control plane, +// without waking the VM. This device's reader key is registered with the control plane (on start, +// after a sign-in or account switch, and at most every 6 h after); the VM seals each snapshot to +// the reader keys registered when it went to sleep. +import { hostname } from 'node:os' +import { openReadSnapshot, ReadSnapshotError } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' +import { CloudWorkspacesError, type CloudWorkspacesClient } from './cloud-workspaces-client' +import type { CloudReaderKey, ReaderKeyLoad } from './cloud-reader-key-store' +import { nodeSealedGrantPrimitives } from './sealed-grant-node' + +export const READER_KEY_REFRESH_MS = 6 * 60 * 60_000 + +export type ReaderKeyAccess = { + /** Who is asking (profile, user, account); null when signed out. Registrations are per identity. */ + identity: () => string | null + /** This profile's key (created on first use), or why there can be none. */ + load: () => Promise + /** The key only if one already exists (sign-out must not create one just to delete it). */ + peek?: () => Promise +} + +type Registration = { identity: string; publicKeyB64: string; keyId: string; at: number } +type Ready = { key: CloudReaderKey; keyId: string; fresh: boolean; identity: string } +type Unavailable = { unavailable: Extract } + +export function createReadSnapshotReader(deps: { + client: Pick + readerKey: ReaderKeyAccess + deviceLabel?: () => string + now?: () => number +}) { + const now = deps.now ?? Date.now + let registration: Registration | null = null + let inflight: { tag: string; promise: Promise } | null = null + // Highest payload capturedAt opened per (profile/user/account, workspace). Memory only: a + // restart forgets it, but within a run a replayed older snapshot is refused. + const newestShown = new Map() + + async function ensure(force = false): Promise { + const identity = deps.readerKey.identity() + if (!identity) { + throw new CloudWorkspacesError(401, 'unauthorized') + } + const loaded = await deps.readerKey.load() + if (!loaded.ok) { + return { unavailable: loaded } + } + const { key } = loaded + const known = registration + if ( + !force && + known && + known.identity === identity && + known.publicKeyB64 === key.publicKeyB64 && + now() - known.at < READER_KEY_REFRESH_MS + ) { + return { key, keyId: known.keyId, fresh: false, identity } + } + // Concurrent reads (and the start-up registration) share one PUT per identity and key. + const tag = `${identity}\0${key.publicKeyB64}` + let shared = !force && inflight?.tag === tag ? inflight : null + if (!shared) { + const promise = deps.client + .registerReaderKey({ + publicKeyB64: key.publicKeyB64, + deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop', + deviceKind: 'desktop' + }) + .then((readerKey) => { + const next = { + identity, + publicKeyB64: key.publicKeyB64, + keyId: readerKey.id, + at: now() + } + // A sign-out or account switch while this was in flight must not adopt the old id. + if (deps.readerKey.identity() === identity) { + registration = next + } + return next + }) + const entry = { tag, promise } + shared = entry + inflight = entry + void promise + .catch(() => undefined) + .finally(() => { + if (inflight === entry) { + inflight = null + } + }) + } + const done = await shared.promise + return { key, keyId: done.keyId, fresh: true, identity } + } + + async function fetchWith(sandboxId: string, ready: Ready) { + try { + return await deps.client.getReadSnapshot(sandboxId, ready.keyId) + } catch (error) { + // A remembered id the server no longer accepts: register again (a revoked key gets a new id). + if ( + !ready.fresh && + error instanceof CloudWorkspacesError && + error.status === 400 && + error.code === 'invalid_request' + ) { + const again = await ensure(true) + if ('unavailable' in again) { + throw error + } + return { ready: again, fetched: await deps.client.getReadSnapshot(sandboxId, again.keyId) } + } + throw error + } + } + + return { + /** Best effort: make sure the control plane knows this device's key before workspaces sleep. */ + async register(): Promise { + await ensure().catch(() => undefined) + }, + + /** + * Sign-out: revoke this device's key server-side so no later sleep seals to it. Learns the id + * (idempotent PUT) when this run never registered. Throws on failure; callers bound and ignore. + */ + async revoke(timeoutMs: number): Promise { + const identity = deps.readerKey.identity() + const key = (await deps.readerKey.peek?.()) ?? null + if (!identity || !key) { + return + } + const known = registration + const keyId = + known && known.identity === identity && known.publicKeyB64 === key.publicKeyB64 + ? known.keyId + : ( + await deps.client.registerReaderKey({ + publicKeyB64: key.publicKeyB64, + deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop', + deviceKind: 'desktop' + }) + ).id + registration = null + await deps.client.deleteReaderKey(keyId, timeoutMs) + }, + + async read(sandboxId: string): Promise { + const first = await ensure() + if ('unavailable' in first) { + return { + state: 'unavailable', + reason: first.unavailable.reason, + message: first.unavailable.message + } + } + let ready = first + const answer = await fetchWith(sandboxId, ready) + const fetched = 'ready' in answer ? answer.fetched : answer + if ('ready' in answer) { + ready = answer.ready + } + // not_sealed_for_key only means the snapshot predates this key: report it, never re-register. + if (fetched.kind !== 'sealed') { + return { state: fetched.kind } + } + try { + const snapshot = await openReadSnapshot( + fetched.sealed, + sandboxId, + ready.key.secretKey, + nodeSealedGrantPrimitives + ) + // Rollback pin: never show a copy older than one already shown for this workspace here. + const pinKey = `${first.identity}\0${sandboxId}` + const pinned = newestShown.get(pinKey) + if (pinned !== undefined && snapshot.capturedAt < pinned) { + return { state: 'stale' } + } + newestShown.set(pinKey, snapshot.capturedAt) + return { state: 'ready', snapshot, storedAt: fetched.sealed.storedAt } + } catch (error) { + if (error instanceof ReadSnapshotError) { + throw new CloudWorkspacesError(0, 'snapshot_unreadable', error.code) + } + throw error + } + } + } +} + +export type ReadSnapshotReader = ReturnType diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.test.ts b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts new file mode 100644 index 00000000000..7fd62418f64 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-reader-key-store.test.ts @@ -0,0 +1,161 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { getPath: () => tmpdir() }, + safeStorage: { + isEncryptionAvailable: () => false, + encryptString: () => Buffer.alloc(0), + decryptString: () => '' + } +})) + +import { + createCloudReaderKeyStore, + revokeCloudReaderKeyBestEffort, + setCloudReaderKeyRevoker, + type ReaderKeyCodec +} from './cloud-reader-key-store' +import { x25519PublicKeyOf } from './sealed-grant-node' +import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' + +// Reversible stand-in for the OS keychain: the file must never hold the raw secret. +const codec: ReaderKeyCodec = { + encrypt: (plain) => Buffer.from(`sealed:${Buffer.from(plain).toString('hex')}`), + decrypt: (sealed) => { + const text = sealed.toString() + if (!text.startsWith('sealed:')) { + throw new Error('bad seal') + } + return Buffer.from(text.slice(7), 'hex').toString() + } +} + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'reader-key-')) +}) +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +const storeWith = (next: () => ReaderKeyCodec | null = () => codec) => + createCloudReaderKeyStore({ + pathFor: (profileId) => join(dir, profileId, 'key.enc'), + codec: next, + now: () => 1_700_000_000_000 + }) + +describe('createCloudReaderKeyStore', async () => { + it('creates one key per profile lazily and keeps it sealed on disk', async () => { + const store = storeWith() + const first = await store.load('p1') + expect(first.ok).toBe(true) + if (!first.ok) { + return + } + expect(first.key.secretKey).toHaveLength(32) + const derived = x25519PublicKeyOf(first.key.secretKey) + expect(first.key.publicKeyB64).toBe(bytesToBase64(derived)) + const file = readFileSync(join(dir, 'p1', 'key.enc'), 'utf8') + expect(file).not.toContain(bytesToBase64(first.key.secretKey)) + expect(JSON.parse(file)).toMatchObject({ version: 1, format: 'electron-safe-storage-v1' }) + + const second = await store.load('p2') + expect(second.ok && second.key.publicKeyB64).not.toBe(first.key.publicKeyB64) + }) + + it('reads the same key back after a restart', async () => { + const first = await storeWith().load('p1') + const again = await storeWith().load('p1') + expect(first.ok && again.ok).toBe(true) + if (first.ok && again.ok) { + expect(again.key.publicKeyB64).toBe(first.key.publicKeyB64) + expect(base64ToBytes(bytesToBase64(again.key.secretKey))).toEqual(first.key.secretKey) + } + }) + + it('is off with a reason when the OS keychain is missing, and writes nothing', async () => { + const store = storeWith(() => null) + expect(await store.load('p1')).toMatchObject({ ok: false, reason: 'keychain_unavailable' }) + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + }) + + it('replaces a key the keychain can no longer open', async () => { + const first = await storeWith().load('p1') + writeFileSync( + join(dir, 'p1', 'key.enc'), + JSON.stringify({ version: 1, format: 'electron-safe-storage-v1', ciphertext: 'AAAA' }) + ) + const replaced = await storeWith().load('p1') + expect(replaced.ok).toBe(true) + expect(first.ok && replaced.ok && replaced.key.publicKeyB64 !== first.key.publicKeyB64).toBe( + true + ) + }) + + it('clear drops the key from memory and disk (sign-out)', async () => { + const store = storeWith() + const first = await store.load('p1') + await store.clear('p1') + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + const next = await store.load('p1') + expect(first.ok && next.ok && next.key.publicKeyB64 !== first.key.publicKeyB64).toBe(true) + }) +}) + +describe('revokeCloudReaderKeyBestEffort', async () => { + afterEach(() => setCloudReaderKeyRevoker(null)) + + it('runs the registered revoker with the timeout', async () => { + const revoke = vi.fn(async (_timeoutMs: number) => {}) + setCloudReaderKeyRevoker(revoke) + await revokeCloudReaderKeyBestEffort(500) + expect(revoke).toHaveBeenCalledWith(500) + }) + + it('never blocks sign-out: a hung or failing revoke resolves within the timeout', async () => { + vi.useFakeTimers() + try { + setCloudReaderKeyRevoker(() => new Promise(() => {})) + let settled = false + const done = revokeCloudReaderKeyBestEffort(30).then(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(29) + expect(settled).toBe(false) + await vi.advanceTimersByTimeAsync(1) + await done + expect(settled).toBe(true) + } finally { + vi.useRealTimers() + } + setCloudReaderKeyRevoker(async () => { + throw new Error('offline') + }) + await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined() + setCloudReaderKeyRevoker(null) + await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined() + }) +}) + +describe('peek', async () => { + it('returns the existing key and never creates one', async () => { + const store = storeWith() + expect(await store.peek('p1')).toBeNull() + expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false) + const loaded = await store.load('p1') + const fresh = await storeWith().peek('p1') + expect(loaded.ok && fresh?.publicKeyB64 === loaded.key.publicKeyB64).toBe(true) + }) +}) + +describe('concurrent first loads', () => { + it('mint a single key', async () => { + const store = storeWith() + const [a, b] = await Promise.all([store.load('p1'), store.load('p1')]) + expect(a.ok && b.ok && a.key.publicKeyB64 === b.key.publicKeyB64).toBe(true) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-reader-key-store.ts b/src/main/cloud-workspaces/cloud-reader-key-store.ts new file mode 100644 index 00000000000..3f570aa9156 --- /dev/null +++ b/src/main/cloud-workspaces/cloud-reader-key-store.ts @@ -0,0 +1,234 @@ +// This device's long-lived X25519 "reader key", one per Orca profile. A sleeping Orca Cloud +// workspace seals its read snapshot to every registered reader key allowed to open it; the secret +// half never leaves this machine. It is sealed by the OS keychain (safeStorage at level 'os'); with +// no real keychain the feature is off rather than keeping a long-lived secret in the clear. +import { readFile, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { assessSecretProtection } from '../host/electron-secret-store' +import { guardedSafeStorage } from '../host/safe-storage-availability' +import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant' +import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths' +import { generateGrantRecipientKey, x25519PublicKeyOf } from './sealed-grant-node' + +export const READER_KEY_FILE_NAME = 'cloud-reader-key.json.enc' + +export type ReaderKeyCodec = { + encrypt: (plain: string) => Buffer + decrypt: (sealed: Buffer) => string +} + +export type CloudReaderKey = { + /** 32-byte X25519 secret. Callers must not keep or zero it; the store owns the buffer. */ + secretKey: Uint8Array + publicKeyB64: string +} + +export type ReaderKeyLoad = + | { ok: true; key: CloudReaderKey } + | { ok: false; reason: 'keychain_unavailable' | 'storage_failed'; message: string } + +type PersistedReaderKey = { + version: 1 + format: 'electron-safe-storage-v1' + createdAt: number + ciphertext: string +} + +const KEYCHAIN_MESSAGE = + 'Reading sleeping workspaces needs the OS keychain to protect this device’s key.' + +/** The OS keychain, or null when it is missing or only obfuscates (Linux basic_text). */ +export function osReaderKeyCodec(): ReaderKeyCodec | null { + try { + if (!guardedSafeStorage.isEncryptionAvailable() || assessSecretProtection().level !== 'os') { + return null + } + } catch { + return null + } + return { + encrypt: (plain) => guardedSafeStorage.encryptString(plain), + decrypt: (sealed) => guardedSafeStorage.decryptString(sealed) + } +} + +export function getCloudReaderKeyPath(profileId: string, userDataPath: string): string { + return join(getOrcaProfileDirectory(profileId, userDataPath), READER_KEY_FILE_NAME) +} + +export function createCloudReaderKeyStore(deps: { + pathFor: (profileId: string) => string + codec: () => ReaderKeyCodec | null + now?: () => number +}) { + const cache = new Map() + // One load per key file at a time, so two first reads can never mint two keys. + const loading = new Map>() + + /** The sealed key on disk, or null when there is none or this keychain cannot open it. */ + async function readExisting(path: string, codec: ReaderKeyCodec): Promise { + let text: string + try { + text = await readFile(path, 'utf8') + } catch { + return null + } + try { + const parsed: unknown = JSON.parse(text) + if ( + !isRecord(parsed) || + parsed.version !== 1 || + parsed.format !== 'electron-safe-storage-v1' || + typeof parsed.ciphertext !== 'string' + ) { + return null + } + const secretKey = base64ToBytes(codec.decrypt(Buffer.from(parsed.ciphertext, 'base64'))) + if (secretKey.length !== 32) { + return null + } + return { secretKey, publicKeyB64: bytesToBase64(x25519PublicKeyOf(secretKey)) } + } catch { + return null + } + } + + async function loadUncached(path: string, codec: ReaderKeyCodec): Promise { + const existing = await readExisting(path, codec) + if (existing) { + cache.set(path, existing) + return { ok: true, key: existing } + } + // A new key only means snapshots taken before it are not readable here until the next sleep. + const fresh = generateGrantRecipientKey() + try { + const persisted: PersistedReaderKey = { + version: 1, + format: 'electron-safe-storage-v1', + createdAt: (deps.now ?? Date.now)(), + ciphertext: codec.encrypt(bytesToBase64(fresh.secretKey)).toString('base64') + } + // Once per profile; the shared writer applies owner-only permissions (and Windows ACLs). + writeSecureJsonFile(path, persisted) + } catch (error) { + fresh.secretKey.fill(0) + return { + ok: false, + reason: 'storage_failed', + message: `Could not save this device’s reader key: ${String(error).slice(0, 120)}` + } + } + const key = { secretKey: fresh.secretKey, publicKeyB64: fresh.publicKeyB64 } + cache.set(path, key) + return { ok: true, key } + } + + return { + /** The profile's existing key, if any; never creates one. */ + async peek(profileId: string): Promise { + const codec = deps.codec() + const path = deps.pathFor(profileId) + const cached = cache.get(path) + if (cached || !codec) { + return cached ?? null + } + const existing = await readExisting(path, codec) + if (existing) { + cache.set(path, existing) + } + return existing + }, + /** The profile's key, created on first use. A key the keychain can no longer open is replaced. */ + async load(profileId: string): Promise { + const codec = deps.codec() + if (!codec) { + return { ok: false, reason: 'keychain_unavailable', message: KEYCHAIN_MESSAGE } + } + const path = deps.pathFor(profileId) + const cached = cache.get(path) + if (cached) { + return { ok: true, key: cached } + } + let pending = loading.get(path) + if (!pending) { + pending = loadUncached(path, codec).finally(() => loading.delete(path)) + loading.set(path, pending) + } + return pending + }, + /** Sign-out: the next account on this profile gets a new key (never one an old account knew). */ + async clear(profileId: string): Promise { + const path = deps.pathFor(profileId) + // A first load still in flight would otherwise write its key back after this. + await loading.get(path) + cache.get(path)?.secretKey.fill(0) + cache.delete(path) + await rm(path, { force: true }) + } + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export type CloudReaderKeyStore = ReturnType + +let defaultStore: { userDataPath: string; store: CloudReaderKeyStore } | null = null + +/** The process-wide store for this user data directory (the OS keychain codec). */ +export function getCloudReaderKeyStore(userDataPath: string): CloudReaderKeyStore { + if (defaultStore?.userDataPath !== userDataPath) { + defaultStore = { + userDataPath, + store: createCloudReaderKeyStore({ + pathFor: (profileId) => getCloudReaderKeyPath(profileId, userDataPath), + codec: osReaderKeyCodec + }) + } + } + return defaultStore.store +} + +// Sign-out revokes the key server-side through the cloud workspaces service (it owns the client +// and the registration id). A seam so profile code never loads that service. +let revoker: ((timeoutMs: number) => Promise) | null = null + +export function setCloudReaderKeyRevoker(next: typeof revoker): void { + revoker = next +} + +export const READER_KEY_REVOKE_TIMEOUT_MS = 2_500 + +/** Best effort and bounded: resolves within `timeoutMs` whatever the network does. */ +export async function revokeCloudReaderKeyBestEffort( + timeoutMs = READER_KEY_REVOKE_TIMEOUT_MS +): Promise { + const run = revoker + if (!run) { + return + } + let timer: ReturnType | undefined + try { + await Promise.race([ + Promise.resolve() + .then(() => run(timeoutMs)) + .catch(() => undefined), + new Promise((resolve) => { + timer = setTimeout(resolve, timeoutMs) + }) + ]) + } finally { + clearTimeout(timer) + } +} + +/** Sign-out / profile reset hook: drop the profile's reader key (memory and disk). */ +export async function clearCloudReaderKey(profileId: string, userDataPath: string): Promise { + try { + await getCloudReaderKeyStore(userDataPath).clear(profileId) + } catch (error) { + console.error(`[orca-cloud] clearing the reader key failed: ${String(error)}`) + } +} diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts new file mode 100644 index 00000000000..a858d51898f --- /dev/null +++ b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it, vi } from 'vitest' +import { CloudWorkspaceSchema } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +import { createCloudWorkspacesClient } from './cloud-workspaces-client' + +const SBX = 'sbx_0123456789abcdef01234567' +const KEY = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa' + +function clientAnswering(status: number, body: unknown) { + const fetch = vi.fn( + async () => new Response(JSON.stringify(body), { status }) + ) + const client = createCloudWorkspacesClient({ + baseUrl: 'https://cp.example.test', + getAccessToken: async () => 'tok', + fetch + }) + return { client, fetch } +} + +const sealed = { + v: 1, + snapshotId: 'snap_1', + workspaceId: SBX, + storedAt: 5, + nonceB64: 'AAAAAAAAAAAAAAAA', + ciphertextB64: 'AAAA', + recipient: { + keyId: KEY, + ephemeralPublicKeyB64: 'AAAA', + nonceB64: 'AAAA', + wrappedKeyB64: 'AAAA' + } +} + +describe('cloud workspaces client: read snapshots', () => { + it('PUTs the reader key and returns its id', async () => { + const { client, fetch } = clientAnswering(200, { + readerKey: { id: KEY, deviceKind: 'desktop', deviceLabel: 'mac', createdAt: 1, lastSeenAt: 2 } + }) + const key = await client.registerReaderKey({ + publicKeyB64: 'pub', + deviceLabel: 'mac', + deviceKind: 'desktop' + }) + expect(key.id).toBe(KEY) + const [url, init] = fetch.mock.calls[0]! + expect(String(url)).toBe('https://cp.example.test/v1/reader-keys') + expect(init?.method).toBe('PUT') + expect(JSON.parse(String(init?.body))).toEqual({ + publicKeyB64: 'pub', + deviceLabel: 'mac', + deviceKind: 'desktop' + }) + }) + + it('DELETEs a reader key by id', async () => { + const { client, fetch } = clientAnswering(200, { ok: true }) + await client.deleteReaderKey(KEY, 2_000) + const [url, init] = fetch.mock.calls[0]! + expect(String(url)).toBe(`https://cp.example.test/v1/reader-keys/${KEY}`) + expect(init?.method).toBe('DELETE') + }) + + it('GETs the sealed snapshot for this key', async () => { + const { client, fetch } = clientAnswering(200, { snapshot: sealed }) + expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: 'sealed', sealed }) + expect(String(fetch.mock.calls[0]![0])).toBe( + `https://cp.example.test/v1/team/workspaces/${SBX}/read-snapshot?keyId=${KEY}` + ) + }) + + it.each(['not_found', 'no_snapshot', 'not_sealed_for_key'] as const)( + 'maps 404 %s to a typed result', + async (code) => { + const { client } = clientAnswering(404, { error: code }) + expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: code }) + } + ) + + it('keeps other failures as errors', async () => { + await expect( + clientAnswering(404, { error: 'something_else' }).client.getReadSnapshot(SBX, KEY) + ).rejects.toMatchObject({ status: 404, code: 'something_else' }) + await expect( + clientAnswering(400, { error: 'invalid_request' }).client.getReadSnapshot(SBX, KEY) + ).rejects.toMatchObject({ status: 400, code: 'invalid_request' }) + }) +}) + +describe('CloudWorkspaceSchema.readSnapshotAt', () => { + const base = { + id: SBX, + workspaceId: 'w', + status: 'suspended', + machineSize: 'standard', + region: 'iad1', + createdAt: 1, + title: null, + repo: null, + visibility: 'team', + section: null, + archivedAt: null, + createdBy: 'u', + ownerUserId: 'u', + lastActivityAt: 1, + lastActivityBy: null, + cost: { + computeMs: 0, + rateUsdMicrosPerHour: 0, + computeUsdMicros: 0, + tokenUsdMicros: null, + totalUsdMicros: 0 + }, + access: 'can_open', + presence: [] + } + it('is optional for older control planes and nullable', () => { + expect(CloudWorkspaceSchema.parse(base).readSnapshotAt).toBeUndefined() + expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: null }).readSnapshotAt).toBeNull() + expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: 9 }).readSnapshotAt).toBe(9) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index 71453f65bd5..94f16ecfdd1 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -2,7 +2,10 @@ // hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential. import { z } from 'zod' import { errorMessage } from '../../shared/error-message' +import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' import { + CloudReadSnapshotResponseSchema, + CloudReaderKeyResponseSchema, CloudWorkspaceGrantIssuedSchema, CloudWorkspaceGrantListSchema, CloudWorkspaceLinkResponseSchema, @@ -38,6 +41,15 @@ const CONTROL_TIMEOUT_MS = 20_000 // Opening a sleeping teammate workspace includes a VM boot. const GRANT_TIMEOUT_MS = 120_000 const MAX_RESPONSE_BYTES = 512 * 1024 +// A read snapshot carries chat tails (bounded by READ_SNAPSHOT_LIMITS), base64 over AES-GCM. +const MAX_READ_SNAPSHOT_BYTES = 16 * 1024 * 1024 + +/** The read-snapshot 404s are states, not failures: each has its own copy. */ +const READ_SNAPSHOT_MISSES = ['not_found', 'no_snapshot', 'not_sealed_for_key'] as const +export type ReadSnapshotMiss = (typeof READ_SNAPSHOT_MISSES)[number] +export type ReadSnapshotFetch = + | { kind: 'sealed'; sealed: SealedReadSnapshot } + | { kind: ReadSnapshotMiss } export function createCloudWorkspacesClient(options: CloudWorkspacesClientOptions) { const doFetch = options.fetch ?? fetch @@ -48,7 +60,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption path: string, schema: z.ZodType, body?: unknown, - timeoutMs = CONTROL_TIMEOUT_MS + timeoutMs = CONTROL_TIMEOUT_MS, + maxBytes = MAX_RESPONSE_BYTES ): Promise { const signal = AbortSignal.timeout(timeoutMs) let token: string @@ -80,7 +93,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption ) } const text = await response.text() - if (text.length > MAX_RESPONSE_BYTES) { + if (text.length > maxBytes) { throw new CloudWorkspacesError(response.status, 'invalid_response') } let payload: unknown = null @@ -177,6 +190,46 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption } return call('GET', `/v1/team/links/resolve?${params}`, CloudWorkspaceLinkResponseSchema) }, + /** Idempotent per (user, account, public key): the same id comes back, lastSeenAt bumped. */ + async registerReaderKey(body: { + publicKeyB64: string + deviceLabel: string + deviceKind: 'desktop' | 'mobile' + }) { + return (await call('PUT', '/v1/reader-keys', CloudReaderKeyResponseSchema, body)).readerKey + }, + /** Server-side revoke: wrapped keys for it are pruned and it is never resurrected. */ + async deleteReaderKey(keyId: string, timeoutMs = CONTROL_TIMEOUT_MS): Promise { + await call( + 'DELETE', + `/v1/reader-keys/${encodeURIComponent(keyId)}`, + NoteSentSchema.passthrough(), + undefined, + timeoutMs + ) + }, + async getReadSnapshot(id: string, keyId: string): Promise { + try { + const { snapshot } = await call( + 'GET', + `${ws(id)}/read-snapshot?${new URLSearchParams({ keyId })}`, + CloudReadSnapshotResponseSchema, + undefined, + CONTROL_TIMEOUT_MS, + MAX_READ_SNAPSHOT_BYTES + ) + return { kind: 'sealed', sealed: snapshot } + } catch (error) { + const miss = + error instanceof CloudWorkspacesError && error.status === 404 + ? READ_SNAPSHOT_MISSES.find((code) => code === error.code) + : undefined + if (miss) { + return { kind: miss } + } + throw error + } + }, getOrgPrompts(): Promise { return call('GET', '/v1/team/prompts', OrgPromptsSchema) }, diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index 6a3340a1c22..564fed8a6a4 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -18,6 +18,7 @@ import { type CloudWorkspacesClient } from './cloud-workspaces-client' import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from './sealed-grant-node' +import { createReadSnapshotReader, type ReaderKeyAccess } from './cloud-read-snapshot-reader' const PRESENCE_BEAT_MS = 20_000 /** Renew a teammate-opened workspace's lease well before the control plane's 30 min lease lapses. */ @@ -52,6 +53,8 @@ export function createCloudWorkspacesService(deps: { config: HostedSandboxConfig clientId: string fetch?: typeof fetch + /** This profile's reader key (sleeping-workspace snapshots); absent: reading them is off. */ + readerKey?: ReaderKeyAccess }) { const client: CloudWorkspacesClient = createCloudWorkspacesClient({ baseUrl: deps.config.controlPlaneUrl, @@ -69,6 +72,11 @@ export function createCloudWorkspacesService(deps: { let heartbeat: ReturnType | null = null let leaseSandboxId: string | null = null let leaseRenewedAt = 0 + const reader = deps.readerKey + ? createReadSnapshotReader({ client, readerKey: deps.readerKey }) + : null + // Register the key up front: a workspace seals its snapshot to the keys known when it sleeps. + void reader?.register() function localWorkspaces(): LocalCloudWorkspace[] { const out: LocalCloudWorkspace[] = [] @@ -126,7 +134,23 @@ export function createCloudWorkspacesService(deps: { return { available: true as const, - list: (query: CloudWorkspaceListQuery) => wrap(() => client.list(query)), + list: (query: CloudWorkspaceListQuery) => + wrap(async () => { + const workspaces = await client.list(query) + // Cheap when already registered; catches a sign-in or account switch since the last list. + void reader?.register() + return workspaces + }), + /** 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. */ + readSnapshot: (id: string) => + wrap(async () => { + if (!reader) { + throw new CloudWorkspacesError(0, 'not_configured') + } + return reader.read(id) + }), get: (id: string) => wrap(() => client.get(id)), patch: (id: string, patch: CloudWorkspacePatch) => wrap(async () => (await client.patch(id, patch)).workspace), diff --git a/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts b/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts new file mode 100644 index 00000000000..ed147061bcc --- /dev/null +++ b/src/main/cloud-workspaces/read-snapshot-sealer.test-fixture.ts @@ -0,0 +1,78 @@ +// Test-only sealer: the VM's construction (see read-snapshot.ts header) with node:crypto, so the +// desktop opener is checked against an independent implementation rather than itself. +import { + createCipheriv, + createPublicKey, + diffieHellman, + generateKeyPairSync, + hkdfSync, + randomBytes +} from 'node:crypto' +import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' + +const b64 = (bytes: Uint8Array): string => Buffer.from(bytes).toString('base64') + +function gcm(key: Uint8Array, nonce: Uint8Array, plain: Uint8Array, aad: string): Buffer { + const cipher = createCipheriv('aes-256-gcm', key, nonce) + cipher.setAAD(Buffer.from(aad, 'utf8')) + return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()]) +} + +export function sealReadSnapshotForTest(args: { + payload: unknown + workspaceId: string + snapshotId: string + readerPublicKeyB64: string + keyId: string + storedAt?: number +}): SealedReadSnapshot { + const { workspaceId, snapshotId, keyId } = args + const dek = randomBytes(32) + const nonce = randomBytes(12) + const body = gcm( + dek, + nonce, + Buffer.from(JSON.stringify(args.payload), 'utf8'), + `orca-cloud-read-v1:${workspaceId}:${snapshotId}` + ) + const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64') + const ephemeral = generateKeyPairSync('x25519') + const ephemeralPublic = Buffer.from(ephemeral.publicKey.export({ format: 'jwk' }).x!, 'base64url') + const shared = diffieHellman({ + privateKey: ephemeral.privateKey, + publicKey: createPublicKey({ + key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') }, + format: 'jwk' + }) + }) + const kek = Buffer.from( + hkdfSync( + 'sha256', + shared, + Buffer.concat([ephemeralPublic, readerPublic]), + Buffer.from('orca-cloud-read-wrap-v1', 'utf8'), + 32 + ) + ) + const wrapNonce = randomBytes(12) + const wrapped = gcm( + kek, + wrapNonce, + dek, + `orca-cloud-read-wrap-v1:${workspaceId}:${snapshotId}:${keyId}` + ) + return { + v: 1, + snapshotId, + workspaceId, + storedAt: args.storedAt ?? 1_000, + nonceB64: b64(nonce), + ciphertextB64: b64(body), + recipient: { + keyId, + ephemeralPublicKeyB64: b64(ephemeralPublic), + nonceB64: b64(wrapNonce), + wrappedKeyB64: b64(wrapped) + } + } +} diff --git a/src/main/cloud-workspaces/sealed-grant-node.ts b/src/main/cloud-workspaces/sealed-grant-node.ts index d615d396ed7..b7eb5590dc5 100644 --- a/src/main/cloud-workspaces/sealed-grant-node.ts +++ b/src/main/cloud-workspaces/sealed-grant-node.ts @@ -21,7 +21,8 @@ function privateKeyFor(secret: Uint8Array, publicKey: Uint8Array) { }) } -function publicKeyOf(secret: Uint8Array): Uint8Array { +/** X25519 public key for a 32-byte secret (synchronous, unlike the primitives' contract). */ +export function x25519PublicKeyOf(secret: Uint8Array): Uint8Array { // Node derives the public half when only `d` is given via PKCS#8; JWK import needs `x`, so go through DER. const pkcs8 = Buffer.concat([ Buffer.from('302e020100300506032b656e04220420', 'hex'), @@ -33,10 +34,10 @@ function publicKeyOf(secret: Uint8Array): Uint8Array { } export const nodeSealedGrantPrimitives: SealedGrantPrimitives = { - x25519PublicKey: publicKeyOf, + x25519PublicKey: x25519PublicKeyOf, x25519(secret, peer) { const shared = diffieHellman({ - privateKey: privateKeyFor(secret, publicKeyOf(secret)), + privateKey: privateKeyFor(secret, x25519PublicKeyOf(secret)), publicKey: createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: b64url(peer) }, format: 'jwk' diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.test.ts b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts new file mode 100644 index 00000000000..39de8220bcd --- /dev/null +++ b/src/main/hosted-sandbox/cloud-desktop-keys.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const runtimes: { runtimeEnvironmentId: string; recipe?: { provider?: string } }[] = [] +const environments = new Map() +let launchEnv: Record = {} +const launchCalls: unknown[][] = [] + +vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ + listEphemeralVmRuntimes: () => runtimes +})) +vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ + resolveEnvironment: (_userData: string, id: string) => { + const environment = environments.get(id) + if (!environment) { + throw new Error('unknown environment') + } + return environment + } +})) +vi.mock('../agent-api-keys/agent-api-key-launch-env', () => ({ + resolveAgentApiKeyLaunchEnv: async (...args: unknown[]) => { + launchCalls.push(args) + return launchEnv + }, + withAgentApiKeyLaunchEnv: async (env: Record | undefined, ...args: unknown[]) => { + launchCalls.push(args) + return { ...env, ...launchEnv } + } +})) +const sshTargets = new Map< + string, + { host: string; label: string; configHost?: string; proxyCommand?: string } +>() +vi.mock('../ssh/targets/ssh-target-registry', () => ({ + getSshTargetRegistryStore: () => ({ getTarget: (id: string) => sshTargets.get(id) }) +})) + +const { desktopKeyValueForCloud, isOrcaCloudRuntimeEnvironment } = + await import('./cloud-desktop-keys') + +beforeEach(() => { + runtimes.length = 0 + environments.clear() + launchEnv = {} + launchCalls.length = 0 + sshTargets.clear() +}) + +describe('isOrcaCloudRuntimeEnvironment', () => { + it('is true for an Orca Cloud runtime and false for another VM recipe or a paired machine', () => { + runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } }) + runtimes.push({ runtimeEnvironmentId: 'env-own-vm', recipe: { provider: 'my-recipes' } }) + environments.set('env-mac', { + source: 'manual', + endpoints: [{ endpoint: 'wss://192.168.1.4:6768' }] + }) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-cloud')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-own-vm')).toBe(false) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-mac')).toBe(false) + }) + + it('fails closed: a VM with no provider record, or a host on a Vercel Sandbox route, counts as Orca Cloud', () => { + runtimes.push({ runtimeEnvironmentId: 'env-unknown-recipe' }) + environments.set('env-vm', { source: 'ephemeral-vm', endpoints: [{ endpoint: 'wss://x' }] }) + environments.set('env-paired-cloud', { + source: 'manual', + endpoints: [{ endpoint: 'wss://sb-abc123.vercel.run' }] + }) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-unknown-recipe')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-vm')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-paired-cloud')).toBe(true) + expect(isOrcaCloudRuntimeEnvironment('/u', 'env-missing')).toBe(false) + }) +}) + +describe('desktopKeyValueForCloud', () => { + it('reads only keys set for every host, for one agent and one variable', async () => { + launchEnv = { GEMINI_API_KEY: 'AIzaSy-real', OTHER: 'x' } + expect(await desktopKeyValueForCloud('gemini', 'GEMINI_API_KEY')).toBe('AIzaSy-real') + expect(await desktopKeyValueForCloud('gemini', 'CURSOR_API_KEY')).toBeNull() + expect(launchCalls[0]).toEqual(['gemini', 'runtime:orca-cloud']) + }) +}) + +describe('withHostAgentApiKeyEnv', () => { + it('adds no desktop keys to a launch on an Orca Cloud VM', async () => { + runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } }) + launchEnv = { GEMINI_API_KEY: 'AIzaSy-real' } + const params = { agent: 'gemini', kind: 'explicit' } + const { setCloudDesktopKeysUserDataPath, withHostAgentApiKeyEnv } = + await import('./cloud-desktop-keys') + setCloudDesktopKeysUserDataPath('/u') + const readStatus = vi.fn() + expect( + await withHostAgentApiKeyEnv('env-cloud', 'terminal.createAgentSession', params, readStatus) + ).toBe(params) + expect(launchCalls).toEqual([]) + expect(readStatus).not.toHaveBeenCalled() + }) +}) + +describe('withHostAgentApiKeyLaunchEnv (SSH)', () => { + it('sends no desktop keys over SSH into an Orca Cloud workspace, and does elsewhere', async () => { + const { withHostAgentApiKeyLaunchEnv } = await import('./cloud-desktop-keys') + launchEnv = { CURSOR_API_KEY: 'key_real' } + sshTargets.set('t-cloud', { + host: 'orca-api-7f3a', + label: 'orca-api-7f3a', + configHost: 'orca-api-7f3a' + }) + sshTargets.set('t-proxy', { + host: 'box', + label: 'box', + proxyCommand: '/Applications/Orca.app/bin/orca ssh-proxy env-1' + }) + sshTargets.set('t-devbox', { host: 'devbox.lan', label: 'devbox' }) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-cloud')).toEqual({ A: '1' }) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-proxy')).toEqual({ A: '1' }) + expect(launchCalls).toEqual([]) + expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-devbox')).toEqual({ + A: '1', + CURSOR_API_KEY: 'key_real' + }) + expect(await withHostAgentApiKeyLaunchEnv(undefined, 'cursor', null)).toEqual({ + CURSOR_API_KEY: 'key_real' + }) + }) +}) diff --git a/src/main/hosted-sandbox/cloud-desktop-keys.ts b/src/main/hosted-sandbox/cloud-desktop-keys.ts new file mode 100644 index 00000000000..f036d072020 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-desktop-keys.ts @@ -0,0 +1,126 @@ +// Desktop-sealed agent API keys (Settings → Agent API Keys) and Orca Cloud workspaces. On any other +// host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key, +// so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key +// per click), and the VM then gets a placeholder the egress proxy swaps. +import { + resolveAgentApiKeyLaunchEnv, + withAgentApiKeyLaunchEnv +} from '../agent-api-keys/agent-api-key-launch-env' +import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call' +import { isCloudSshAlias } from '../cloud-ssh/cloud-ssh-config' +import { getSshTargetRegistryStore } from '../ssh/targets/ssh-target-registry' +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' +import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { getConnectionExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' +import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' + +// Set once the desktop starts (registerCloudSecretsHandlers); this module stays free of Electron +// because launch assembly that the headless runtime also loads imports it. +let desktopUserDataPath: string | null = null +export function setCloudDesktopKeysUserDataPath(path: string): void { + desktopUserDataPath = path +} + +/** Orca Cloud sandboxes answer on Vercel Sandbox routes. */ +const ORCA_CLOUD_ENDPOINT_HOST = /\.vercel\.run$/i + +function endpointHost(endpoint: string): string | null { + try { + return new URL(endpoint).hostname + } catch { + return null + } +} + +/** + * Whether `environmentId` is an Orca Cloud VM. Fails closed: a VM-provisioned host this desktop has no + * provider record for, or any host on a Vercel Sandbox route, counts as Orca Cloud. + */ +export function isOrcaCloudRuntimeEnvironment( + userDataPath: string, + environmentId: string +): boolean { + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (record) => record.runtimeEnvironmentId === environmentId + ) + if (runtime) { + return runtime.recipe?.provider === 'orca-cloud' || runtime.recipe?.provider === undefined + } + let environment: ReturnType | null = null + try { + environment = resolveEnvironment(userDataPath, environmentId) + } catch { + return false + } + if (environment.source === 'ephemeral-vm') { + return true + } + return (environment.endpoints ?? []).some((endpoint) => { + const host = endpointHost(endpoint.endpoint) + return host !== null && ORCA_CLOUD_ENDPOINT_HOST.test(host) + }) +} + +/** A host id no host-scoped key names, so only keys set for every host match (the ones a new VM would get). */ +const ANY_CLOUD_HOST = toRuntimeExecutionHostId('orca-cloud') + +/** The sealed value of the desktop key `envName` for `agent`, unsealed for one cloud write. */ +export async function desktopKeyValueForCloud( + agent: TuiAgent, + envName: string +): Promise { + const env = await resolveAgentApiKeyLaunchEnv(agent, ANY_CLOUD_HOST) + return env[envName] ?? null +} + +/** + * A runtime call's params with this computer's Agent API Keys for the agent it starts, except on an + * Orca Cloud VM: there they would sit in plaintext, so the user saves them as Cloud secrets instead + * (the VM then only sees egress placeholders). + */ +export async function withHostAgentApiKeyEnv( + environmentId: string, + method: string, + params: unknown, + readStatus: Parameters[3] +): Promise { + // Without the desktop's records nothing can be ruled out, so no keys go anywhere. + if ( + desktopUserDataPath === null || + isOrcaCloudRuntimeEnvironment(desktopUserDataPath, environmentId) + ) { + return params + } + return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus) +} + +/** + * An SSH target that reaches an Orca Cloud workspace (`orca ssh` writes `orca-*` aliases that proxy + * through the Orca CLI; OpenSSH config Includes can surface them as targets). + */ +export function isOrcaCloudSshConnection(connectionId: string | null | undefined): boolean { + if (!connectionId) { + return false + } + const target = getSshTargetRegistryStore()?.getTarget(connectionId) + if (!target) { + return false + } + return ( + [target.configHost, target.host, target.label].some( + (value) => value !== undefined && isCloudSshAlias(value) + ) || /\bssh-proxy\b/.test(target.proxyCommand ?? '') + ) +} + +/** A local or SSH launch env with this computer's Agent API Keys, except over SSH into an Orca Cloud workspace. */ +export async function withHostAgentApiKeyLaunchEnv( + env: Record | undefined, + agent: TuiAgent | undefined, + connectionId: string | null | undefined +): Promise | undefined> { + if (isOrcaCloudSshConnection(connectionId)) { + return env + } + return withAgentApiKeyLaunchEnv(env, agent, getConnectionExecutionHostId(connectionId)) +} diff --git a/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts new file mode 100644 index 00000000000..aca5e7aff79 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-cloud-read.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest' +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import { createCloudReadMemo } from './cloud-offline-cloud-read' + +const snap: ReadSnapshot = { + v: 1, + workspaceId: 'sbx', + snapshotId: 'snap', + capturedAt: 1, + reason: 'sleep', + git: null, + pr: null, + sessions: [] +} + +describe('createCloudReadMemo', () => { + it('reads once per workspace while fresh, again after forget', async () => { + const read = vi.fn(async () => snap) + const memo = createCloudReadMemo(read) + expect(await memo.get('w')).toBe(snap) + expect(await memo.get('w')).toBe(snap) + expect(read).toHaveBeenCalledTimes(1) + memo.forget('w') + await memo.get('w') + expect(read).toHaveBeenCalledTimes(2) + }) + + it('never throws and never waits past its budget; a late answer serves the next call', async () => { + let resolve: (value: ReadSnapshot) => void = () => {} + const read = vi.fn(() => new Promise((r) => (resolve = r))) + const memo = createCloudReadMemo(read, { waitMs: 10 }) + expect(await memo.get('w')).toBeNull() + resolve(snap) + expect(await memo.get('w')).toBe(snap) + expect(read).toHaveBeenCalledTimes(1) + const failing = createCloudReadMemo(async () => { + throw new Error('offline') + }) + expect(await failing.get('w')).toBeNull() + }) + + it('is a no-op without a reader', async () => { + expect(await createCloudReadMemo(undefined).get('w')).toBeNull() + }) +}) diff --git a/src/main/hosted-sandbox/cloud-offline-cloud-read.ts b/src/main/hosted-sandbox/cloud-offline-cloud-read.ts new file mode 100644 index 00000000000..317090592c3 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-cloud-read.ts @@ -0,0 +1,82 @@ +// The asleep view's reads of a workspace's sealed sleep snapshot (Orca Cloud), memoized: the +// snapshot only changes when the workspace wakes and sleeps again, and the view polls. +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' +import type { CloudOfflineCache } from './cloud-offline-cache' +import { buildOfflineSnapshot } from './cloud-offline-snapshot' +import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge' + +/** The workspace's sealed sleep snapshot opened on this device, or null (none, unreadable). */ +export type CloudSnapshotReader = (workspaceId: string) => Promise + +const TTL_MS = 2 * 60_000 +const FAILED_TTL_MS = 30_000 +/** The asleep view never waits long on the network; a slow read lands on the next poll. */ +const WAIT_MS = 3_000 + +type Entry = { at: number; ttl: number; promise: Promise } + +export function createCloudReadMemo( + read: CloudSnapshotReader | undefined, + options: { waitMs?: number; now?: () => number } = {} +) { + const now = options.now ?? Date.now + const entries = new Map() + const memo = { + /** Resolves null (never throws) when there is none, it failed, or it is not back in time. */ + async get(workspaceId: string): Promise { + if (!read) { + return null + } + let entry = entries.get(workspaceId) + if (!entry || now() - entry.at >= entry.ttl) { + const fresh: Entry = { + at: now(), + ttl: TTL_MS, + promise: read(workspaceId).catch(() => null) + } + void fresh.promise.then((value) => { + if (value === null) { + fresh.ttl = FAILED_TTL_MS + } + }) + entries.set(workspaceId, fresh) + entry = fresh + } + let timer: ReturnType | undefined + const late = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), options.waitMs ?? WAIT_MS) + }) + try { + return await Promise.race([entry.promise, late]) + } finally { + clearTimeout(timer) + } + }, + /** Awake again: the next sleep leaves a new snapshot. */ + forget(workspaceId: string): void { + entries.delete(workspaceId) + }, + clear(): void { + entries.clear() + }, + /** + * The asleep view: this computer's cached copy, with newer sections from the workspace's own + * sleep snapshot while it is asleep. Any cloud failure leaves the cached copy as it was. + */ + async snapshot( + cache: CloudOfflineCache, + info: { environmentId: string; asleep: boolean }, + workspaceId: string + ): Promise { + const local = await buildOfflineSnapshot(cache, info.environmentId, workspaceId, info.asleep) + if (!info.asleep) { + memo.forget(workspaceId) + return local + } + const remote = await memo.get(workspaceId) + return remote ? mergeCloudReadSnapshot(local, remote) : local + } + } + return memo +} diff --git a/src/main/hosted-sandbox/cloud-offline-service.ts b/src/main/hosted-sandbox/cloud-offline-service.ts index 89ee90f9d63..0323ff36a6b 100644 --- a/src/main/hosted-sandbox/cloud-offline-service.ts +++ b/src/main/hosted-sandbox/cloud-offline-service.ts @@ -29,12 +29,8 @@ import { import { createOwedWorkBeat } from './cloud-offline-beat' import { setCloudOfflineReset } from './cloud-offline-reset' import { safeStorageCodec, setCloudOfflineObserver } from './cloud-offline-seam' -import { - archiveCheckoutsFromCache, - buildOfflineSnapshot, - stringParam, - terminalHandlesOf -} from './cloud-offline-snapshot' +import { archiveCheckoutsFromCache, stringParam, terminalHandlesOf } from './cloud-offline-snapshot' +import { createCloudReadMemo, type CloudSnapshotReader } from './cloud-offline-cloud-read' import { getHostedWorkspaceService, setArchiveCheckoutsProvider } from './hosted-workspace-service' type CloudRuntimeInfo = { @@ -71,6 +67,11 @@ export function installCloudOfflineService(deps: { windows: () => readonly BrowserWindow[] /** The control plane says the workspace is archived (nothing wakes or sends to it). */ isArchived: (workspaceId: string) => Promise + /** + * The workspace's own sealed sleep snapshot, opened on this device (never wakes it). Null when + * there is none or it cannot be read; the view then shows this computer's copy alone. + */ + readCloudSnapshot?: CloudSnapshotReader codec?: OfflineCacheCodec | null log?: (line: string) => void }): CloudOfflineService { @@ -122,6 +123,8 @@ export function installCloudOfflineService(deps: { memo = null } + const cloudReads = createCloudReadMemo(deps.readCloudSnapshot) + const broadcast = (channel: string, payload: unknown): void => { for (const window of deps.windows()) { if (!window.isDestroyed()) { @@ -252,6 +255,7 @@ export function installCloudOfflineService(deps: { } }) setCloudOfflineReset(() => { + cloudReads.clear() void cache.clear() queue.clear() }) @@ -274,9 +278,7 @@ export function installCloudOfflineService(deps: { async (_event, args: { workspaceId: string }): Promise => { invalidate() const info = runtimes().byWorkspace.get(args.workspaceId) - return info - ? await buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep) - : null + return info ? await cloudReads.snapshot(cache, info, args.workspaceId) : null } ) ipcMain.handle( diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts new file mode 100644 index 00000000000..2ff941b247e --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest' +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' +import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge' + +const local: CloudOfflineSnapshot = { + workspaceId: 'w', + asleep: true, + capturedAt: 1_000, + git: { + branch: 'old', + head: 'aaa', + changes: [{ path: 'a.ts', status: 'modified', area: 'unstaged' }], + changeCount: 1, + commits: [], + at: 1_000 + }, + terminals: [{ handle: 'h', title: null, lines: ['x'], at: 1_000 }], + chats: [ + { sessionId: 's1', at: 1_000, messages: [{ itemId: 'a', role: 'user', text: 'hi', at: 1 }] }, + { sessionId: 's9', at: 900, messages: [{ itemId: 'z', role: 'user', text: 'kept', at: 1 }] } + ], + source: 'device' +} + +function remote(capturedAt: number): ReadSnapshot { + return { + v: 1, + workspaceId: 'sbx', + snapshotId: 'snap', + capturedAt, + reason: 'sleep', + git: { + branch: 'new', + head: 'bbb', + changes: [{ path: 'b.ts', status: 'added', area: 'untracked', added: 5, removed: 0 }], + changeCount: 1, + added: 5, + removed: 0, + commits: [] + }, + pr: { + number: 7, + title: 'PR', + state: 'open', + url: 'https://github.com/a/b/pull/7', + checksStatus: 'success', + checksSummary: null + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'T', + status: 'idle', + turnOutcome: 'done', + updatedAt: null, + messages: [{ itemId: 'b', role: 'assistant', text: 'newer', at: 2 }], + truncated: false + }, + { + sessionId: 's2', + agent: 'codex', + title: null, + status: 'working', + turnOutcome: null, + updatedAt: null, + messages: [{ itemId: 'c', role: 'user', text: 'only in cloud', at: 2 }], + truncated: false + } + ] + } +} + +describe('mergeCloudReadSnapshot', () => { + it('takes newer cloud sections, keeps terminals and chats the snapshot lacks', () => { + const merged = mergeCloudReadSnapshot(local, remote(2_000)) + expect(merged.git).toMatchObject({ branch: 'new', at: 2_000, added: 5 }) + expect(merged.git?.changes[0]).toMatchObject({ path: 'b.ts', added: 5 }) + expect(merged.terminals).toEqual(local.terminals) + expect(merged.chats.map((chat) => chat.sessionId)).toEqual(['s1', 's2', 's9']) + expect(merged.chats[0]).toMatchObject({ agent: 'claude', title: 'T' }) + expect(merged.chats[0]!.messages[0]!.text).toBe('newer') + expect(merged.pr?.number).toBe(7) + expect(merged.capturedAt).toBe(2_000) + expect(merged.source).toBe('mixed') + }) + + it('keeps the local copy where it is newer, but adds what only the cloud has', () => { + const merged = mergeCloudReadSnapshot(local, remote(500)) + expect(merged.git?.branch).toBe('old') + expect(merged.chats.find((chat) => chat.sessionId === 's1')!.messages[0]!.text).toBe('hi') + expect(merged.chats.some((chat) => chat.sessionId === 's2')).toBe(true) + expect(merged.pr?.number).toBe(7) + expect(merged.capturedAt).toBe(1_000) + }) + + it('fills an empty local cache entirely from the cloud', () => { + const empty: CloudOfflineSnapshot = { + workspaceId: 'w', + asleep: true, + capturedAt: null, + git: null, + terminals: [], + chats: [] + } + const merged = mergeCloudReadSnapshot(empty, remote(2_000)) + expect(merged.capturedAt).toBe(2_000) + expect(merged.source).toBe('cloud') + expect(merged.git?.branch).toBe('new') + expect(merged.chats).toHaveLength(2) + }) +}) diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts new file mode 100644 index 00000000000..88979adebe4 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-snapshot-merge.ts @@ -0,0 +1,62 @@ +// Folds a sleeping workspace's sealed read snapshot (Orca Cloud) into this computer's cached copy. +import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot' +import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' + +const MAX_CHANGES = 300 + +/** + * Folds the workspace's own sealed sleep snapshot into this computer's cached copy: each section + * (git, each chat) comes from whichever is newer, so the view is never older than either. The cache + * keeps terminals (the snapshot has none); the PR only exists in the snapshot. + */ +export function mergeCloudReadSnapshot( + local: CloudOfflineSnapshot, + remote: ReadSnapshot +): CloudOfflineSnapshot { + const at = remote.capturedAt + let fromCloud = false + let git = local.git + if (remote.git && (!local.git || at > local.git.at)) { + fromCloud = true + git = { + branch: remote.git.branch, + head: remote.git.head, + changes: remote.git.changes.slice(0, MAX_CHANGES).map((change) => ({ ...change })), + changeCount: remote.git.changeCount, + commits: remote.git.commits.map((commit) => ({ ...commit })), + at, + added: remote.git.added, + removed: remote.git.removed + } + } + const chats = new Map(local.chats.map((chat) => [chat.sessionId, chat])) + for (const session of remote.sessions) { + const known = chats.get(session.sessionId) + // A session the snapshot saw with no messages adds nothing a cached transcript lacks. + if (session.messages.length === 0 && known) { + continue + } + if (!known || at > known.at) { + fromCloud = true + chats.set(session.sessionId, { + sessionId: session.sessionId, + at, + messages: session.messages.map((message) => ({ ...message })), + agent: session.agent, + title: session.title + }) + } + } + const pr = remote.pr ? { ...remote.pr } : (local.pr ?? null) + fromCloud ||= pr !== null && local.pr == null + const hadLocal = local.capturedAt !== null + const times = [local.capturedAt ?? 0, fromCloud ? at : 0].filter((time) => time > 0) + return { + ...local, + capturedAt: times.length > 0 ? Math.max(...times) : null, + git, + chats: [...chats.values()].sort((a, b) => b.at - a.at), + pr, + source: !fromCloud ? (local.source ?? 'device') : hadLocal ? 'mixed' : 'cloud' + } +} diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot.ts b/src/main/hosted-sandbox/cloud-offline-snapshot.ts index 27233aa83a8..2965d500959 100644 --- a/src/main/hosted-sandbox/cloud-offline-snapshot.ts +++ b/src/main/hosted-sandbox/cloud-offline-snapshot.ts @@ -227,7 +227,8 @@ export async function buildOfflineSnapshot( capturedAt: times.length > 0 ? Math.max(...times) : null, git, terminals, - chats + chats, + source: 'device' } } diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 923ca2a52c2..70cb592cd3d 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -21,6 +21,7 @@ import { createHostedSandboxDeviceEnroller } from './hosted-sandbox-device-enrol import { registerOrcaCloudDeviceEnroller } from '../runtime/rpc/methods/orca-cloud/orca-cloud-device-enrollment' import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' import { registerCloudRemoteDesktopHandlers } from '../ipc/cloud-remote-desktop' +import { readCloudWorkspaceSnapshot } from '../ipc/cloud-workspaces' import { ORCA_CLOUD_RECIPE, createHostedSandboxRecipeClient, @@ -157,6 +158,11 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo return found ? (await client.workspaceStatus(found.sandboxId)).status.state === 'archived' : false + }, + readCloudSnapshot: async (workspaceId) => { + const found = findCloudRuntime(userDataPath, workspaceId) + const read = found ? await readCloudWorkspaceSnapshot(found.sandboxId) : null + return read?.state === 'ready' ? read.snapshot : null } }) setCloudOfflineService(offline) diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 01df642c556..67fc4eb7201 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -11,6 +11,13 @@ import { createCloudWorkspacesService, type CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service' +import { + getCloudReaderKeyStore, + setCloudReaderKeyRevoker +} from '../cloud-workspaces/cloud-reader-key-store' +import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/) const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/) @@ -60,8 +67,11 @@ function getService(): Promise { service = createCloudWorkspacesService({ userDataPath, config, - clientId: await clientIdFor(userDataPath) + clientId: await clientIdFor(userDataPath), + readerKey: profileReaderKey(userDataPath) }) + const started = service + setCloudReaderKeyRevoker((timeoutMs) => started.revokeReaderKey(timeoutMs)) return service })() servicePromise = starting @@ -74,6 +84,38 @@ function getService(): Promise { return starting } +/** The active Orca profile's reader key; registrations follow its signed-in user and account. */ +function profileReaderKey(userDataPath: string): ReaderKeyAccess { + return { + identity: () => { + const active = ensureActiveOrcaProfile(userDataPath) + const cloud = active.profile.cloud + return cloud + ? JSON.stringify([active.profile.id, cloud.userId ?? null, cloud.activeOrgId ?? null]) + : null + }, + load: () => + getCloudReaderKeyStore(userDataPath).load(ensureActiveOrcaProfile(userDataPath).profile.id), + peek: () => + getCloudReaderKeyStore(userDataPath).peek(ensureActiveOrcaProfile(userDataPath).profile.id) + } +} + +/** + * The owner's asleep view merges this in (main process). Null when it cannot be read (no control + * plane, keychain, network); the view then keeps showing this computer's own copy. + */ +export async function readCloudWorkspaceSnapshot( + sandboxId: string +): Promise { + if (!Id.safeParse(sandboxId).success) { + return null + } + const s = await getService().catch(() => null) + const result = await s?.readSnapshot(sandboxId) + return result?.ok ? result.value : null +} + /** Stable per-install id for presence rows (one row per device, not per window). */ async function clientIdFor(userDataPath: string): Promise { const file = join(userDataPath, 'cloud-workspaces-client-id') @@ -187,6 +229,11 @@ export function registerCloudWorkspacesHandlers(): void { const s = await getService() return !s ? NOT_CONFIGURED : parsed.success ? s.openGrant(parsed.data.id) : INVALID }) + handle('cloudWorkspaces:readSnapshot', async (args) => { + const parsed = z.object({ id: Id }).safeParse(args) + const s = await getService() + return !s ? NOT_CONFIGURED : parsed.success ? s.readSnapshot(parsed.data.id) : INVALID + }) handle('cloudWorkspaces:listGrants', async (args) => { const parsed = z.object({ id: Id }).safeParse(args) const s = await getService() diff --git a/src/main/ipc/pty/spawn-options-assembly.ts b/src/main/ipc/pty/spawn-options-assembly.ts index ef3279a6f77..e0dcc651271 100644 --- a/src/main/ipc/pty/spawn-options-assembly.ts +++ b/src/main/ipc/pty/spawn-options-assembly.ts @@ -1,6 +1,5 @@ import { withClaudeAgentViewPlugin } from '../../../shared/claude-agent-view-launch' -import { getConnectionExecutionHostId } from '../../../shared/execution-host' -import { withAgentApiKeyLaunchEnv } from '../../agent-api-keys/agent-api-key-launch-env' +import { withHostAgentApiKeyLaunchEnv } from '../../hosted-sandbox/cloud-desktop-keys' import { resolveStartupShell } from '../../../shared/agent-launch/startup/tui-agent-startup-shell' import { resolveLocalWindowsAgentStartupShell } from '../../../shared/windows-terminal-shell' import { getAppEnvironment } from '../../../shared/app-environment' @@ -156,11 +155,7 @@ export async function assemblePtySpawnLaunchOptions(input: PtySpawnLaunchOptions const env = input.preAdoptedStablePane || input.launchCommand === undefined ? openCodeLaunch.env - : await withAgentApiKeyLaunchEnv( - openCodeLaunch.env, - launchAgent, - getConnectionExecutionHostId(connectionId) - ) + : await withHostAgentApiKeyLaunchEnv(openCodeLaunch.env, launchAgent, connectionId) const pluginDir = !connectionId ? env?.ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR : undefined const launchCommand = pluginDir && openCodeLaunch.command diff --git a/src/main/ipc/pty/spawn-pane-env-ports.test.ts b/src/main/ipc/pty/spawn-pane-env-ports.test.ts new file mode 100644 index 00000000000..16225d1e7c6 --- /dev/null +++ b/src/main/ipc/pty/spawn-pane-env-ports.test.ts @@ -0,0 +1,35 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../workspace-ports/workspace-port-block-registry', () => ({ + getWorkspacePortBlockForWorktreeId: async (worktreeId: string) => + worktreeId.endsWith('/a') ? { base: 21000, count: 10 } : { base: 21010, count: 10 } +})) + +const { stampWorkspacePortEnv, stampPtySpawnPaneEnv } = await import('./spawn-pane-env') + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('workspace port env', () => { + it('gives each workspace its own block even when the host process has ORCA_PORT (VM launcher)', async () => { + vi.stubEnv('ORCA_PORT', '3000') + const a: Record = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' } + const b: Record = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' } + await stampWorkspacePortEnv(a, 'repo::/w/a') + await stampWorkspacePortEnv(b, 'repo::/w/b') + expect(a).toEqual({ ORCA_PORT: '21000', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21000' }) + expect(b).toEqual({ ORCA_PORT: '21010', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21010' }) + }) + + it('scrubs an inherited block from a spawn that names no pane', () => { + const env: Record = { + ORCA_PORT: '3000', + ORCA_PORT_COUNT: '10', + CONDUCTOR_PORT: '3000' + } + stampPtySpawnPaneEnv(env, { pane: null, jcodeRuntimeDir: undefined }) + expect(env.ORCA_PORT).toBeUndefined() + expect(env.CONDUCTOR_PORT).toBeUndefined() + }) +}) diff --git a/src/main/ipc/pty/spawn-pane-env.ts b/src/main/ipc/pty/spawn-pane-env.ts index e924857248a..93b3896fda2 100644 --- a/src/main/ipc/pty/spawn-pane-env.ts +++ b/src/main/ipc/pty/spawn-pane-env.ts @@ -95,6 +95,8 @@ export async function stampWorkspacePortEnv( return } try { + // Always the workspace's own block: a host env's ORCA_PORT (a VM launcher sets one) would make + // every workspace on that host share it. const block = await getWorkspacePortBlockForWorktreeId(worktreeId) if (block) { Object.assign(env, buildWorkspacePortEnv(block)) diff --git a/src/main/ipc/runtime-environments/auth-callback-forward.ts b/src/main/ipc/runtime-environments/auth-callback-forward.ts index db72bf4b5bb..689e31f7f6e 100644 --- a/src/main/ipc/runtime-environments/auth-callback-forward.ts +++ b/src/main/ipc/runtime-environments/auth-callback-forward.ts @@ -157,7 +157,7 @@ export class AuthCallbackForward { ok: false, code: busy ? 'port_busy' : 'listen_failed', message: busy - ? `Port ${this.request.port} is busy on this computer.` + ? `Port ${this.request.port} is in use on this computer.` : 'Orca could not listen for the sign-in on this computer.' } } diff --git a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts index 74249f8a8f3..a9836bc6f4e 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts @@ -41,7 +41,7 @@ import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' import { noteRuntimeEnvironmentConnectRequested } from './runtime-environment-pairing-refusal-registry' import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' import { withWslOrcadAccountEnv } from '../../wsl/orcad/wsl-orcad-account-env' -import { withAgentApiKeyRuntimeEnv } from '../../agent-api-keys/agent-api-key-runtime-call' +import { withHostAgentApiKeyEnv } from '../../hosted-sandbox/cloud-desktop-keys' import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' import { disconnectManagedHostOfEnvironmentForUser, @@ -287,7 +287,7 @@ function registerPassiveCallHandler( getUserDataPath(), environment.id, args.method, - await withAgentApiKeyRuntimeEnv(environment.id, args.method, accounts.params, () => + await withHostAgentApiKeyEnv(environment.id, args.method, accounts.params, () => callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined) ), args.timeoutMs, diff --git a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts index 23b48dd9af6..c372aa82751 100644 --- a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts +++ b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts @@ -5,6 +5,7 @@ import { createHash, randomBytes } from 'node:crypto' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { + AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS, AGENT_SESSION_CHECKPOINT_UNDO_ID, agentSessionCheckpointPartialMessage, agentSessionCheckpointRefusalMessage, @@ -157,6 +158,9 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) return { available: true, changedFiles: changes.length, + paths: [...new Set(changes.map((change) => change.path))] + .sort() + .slice(0, AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS), headMoved, createdAt: found.checkpoint.createdAt, busy: diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts index 98586ac9d60..135597e3748 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts @@ -180,7 +180,12 @@ describe('rewind with file restore', () => { expect(await git('stash', 'list')).toBe('') const preview = await hostAgentSessionCheckpoints(host).preview(HOST_TEST_SESSION, second) - expect(preview).toMatchObject({ available: true, changedFiles: 3, headMoved: false }) + expect(preview).toMatchObject({ + available: true, + changedFiles: 3, + paths: ['app.ts', 'feature.ts', 'refactor/util.ts'], + headMoved: false + }) const restored = await hostAgentSessionCheckpoints(host).restore(HOST_TEST_SESSION, second) expect(restored.changedFiles).toBe(3) expect(await read('app.ts')).toBe('v1\n') diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index bc4cd0295b8..b5b6b097f65 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -1,4 +1,8 @@ import { resetCloudOfflineData } from '../hosted-sandbox/cloud-offline-reset' +import { + clearCloudReaderKey, + revokeCloudReaderKeyBestEffort +} from '../cloud-workspaces/cloud-reader-key-store' import type { ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -157,6 +161,11 @@ export async function signOutCurrentOrcaProfile( const active = ensureActiveOrcaProfile(userDataPath) const configState = getOrcaCloudAuthConfig() const session = readCloudSession(active.profile.id, userDataPath) + if (session.status === 'found') { + // While the session still mints tokens: revoke this device's reader key server-side so no + // later sleep seals to it. Bounded (a couple of seconds) and never fails the sign-out. + await revokeCloudReaderKeyBestEffort() + } // Fence before network I/O so in-flight refreshes cannot save after sign-out. invalidateCloudSessionChanges(active.profile.id, userDataPath) if (!isOrcaCloudDevAuthEnabled() && configState.configured && session.status === 'found') { @@ -175,6 +184,8 @@ export async function signOutCurrentOrcaProfile( const list = unlinkOrcaProfileFromCloud(active.profile.id, userDataPath) // Cached Orca Cloud transcripts and queued prompts belong to the signed-out account. resetCloudOfflineData() + // The next account signed in on this profile gets its own reader key. + await clearCloudReaderKey(active.profile.id, userDataPath) try { clearRelayRegionPreferenceCache(userDataPath) } catch { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index aeebd8bad02..67066396178 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -315,6 +315,23 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { return this.store?.getRemoteLayoutSnapshots?.() ?? {} } + /** The agent a terminal runs and its worktree, from host records (never from request params). */ + getTerminalHandleAgent(handle: string): { agent: string | null; worktreeId: string } | null { + const record = this.handles.get(handle) + if (!record) { + return null + } + return { + agent: record.ptyId ? this.getPtyAgent(record.ptyId) : null, + worktreeId: record.worktreeId + } + } + + /** Whether this host knows a worktree by id (a caller's hint is kept only when it does). */ + async isKnownWorktree(worktreeId: string): Promise { + return (await this.getResolvedWorktreeMap()).has(worktreeId) + } + /** Return the already-open record store without waiting. */ openedAgentSessionRecordStore(): AgentSessionRecordStore | null { return peekOpenedAgentSessionRecordStore() diff --git a/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts new file mode 100644 index 00000000000..6823510f6c5 --- /dev/null +++ b/src/main/runtime/rpc/methods/client-events/client-events-secret-requests.test.ts @@ -0,0 +1,148 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { getSecretRequestStore } from '../../../secrets/secret-request-store' +import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' +// Import the registry to avoid client-events' module-init cycle through ipc/ssh. +import { ALL_RPC_METHODS } from '../rpc-method-registry' + +const methods = eraseRpcMethods(ALL_RPC_METHODS) +const subscribeMethod = methods + .filter(isStreamingMethod) + .find((method) => method.name === 'runtime.clientEvents.subscribe') + +function makeRuntime(): { runtime: OrcaRuntimeService; cleanups: (() => void)[] } { + const cleanups: (() => void)[] = [] + const fake = { + getRuntimeId: () => 'runtime-a', + onClientEvent: () => () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: true }), + registerSubscriptionCleanup: (_id: string, cleanup: () => void) => { + cleanups.push(cleanup) + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the subscribe handler reads only these members. + return { runtime: fake as unknown as OrcaRuntimeService, cleanups } +} + +beforeEach(() => { + vi.stubEnv('ORCA_IS_CLOUD', '1') + vi.stubEnv('ORCA_SANDBOX_ID', 'sbx_test') +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +const secretEvents = (events: unknown[]): Record[] => + events.filter( + (event): event is Record => + typeof event === 'object' && + event !== null && + 'type' in event && + typeof event.type === 'string' && + event.type.startsWith('secrets.') + ) + +it('sends no secret requests from a desktop runtime', async () => { + vi.stubEnv('ORCA_IS_CLOUD', '') + if (!subscribeMethod) { + throw new Error('runtime.clientEvents.subscribe is not a streaming method') + } + getSecretRequestStore().request({ + name: 'LOCAL_ONLY', + reason: 'r', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + const { runtime, cleanups } = makeRuntime() + const seen: unknown[] = [] + const done = subscribeMethod.handler( + {}, + { runtime, connectionId: 'conn-0', clientKind: 'runtime' }, + (event) => seen.push(event) + ) + expect(secretEvents(seen)).toEqual([]) + cleanups.forEach((cleanup) => cleanup()) + await done + getSecretRequestStore().resolve(getSecretRequestStore().pendingEvents()[0].requestId, 'declined') +}) + +it('registers the secrets.* methods', () => { + const names = methods.map((method) => method.name) + for (const name of [ + 'secrets.request', + 'secrets.requestStatus', + 'secrets.touchRequest', + 'secrets.resolveRequest' + ]) { + expect(names).toContain(name) + } +}) + +it('replays pending secret requests on attach, streams new ones, and gives phones status only', async () => { + if (!subscribeMethod) { + throw new Error('runtime.clientEvents.subscribe is not a streaming method') + } + const store = getSecretRequestStore() + // Made while no client was attached. + const early = store.request({ + name: 'EARLY_SECRET', + reason: 'needed before anyone attached', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + sessionEnvNames: new Set() + }) + const { runtime, cleanups } = makeRuntime() + const desktopCtx: RpcContext = { runtime, connectionId: 'conn-1', clientKind: 'runtime' } + const phoneCtx: RpcContext = { runtime, connectionId: 'conn-2', clientKind: 'mobile' } + const desktop: unknown[] = [] + const phone: unknown[] = [] + const done = [ + subscribeMethod.handler({}, desktopCtx, (event) => desktop.push(event)), + subscribeMethod.handler({}, phoneCtx, (event) => phone.push(event)) + ] + + expect(secretEvents(desktop)).toEqual([ + expect.objectContaining({ + type: 'secrets.requested', + requestId: early.requestId, + reason: 'needed before anyone attached' + }) + ]) + expect(secretEvents(phone)).toHaveLength(1) + expect(secretEvents(phone)[0]).not.toHaveProperty('reason') + + const live = store.request({ + name: 'LIVE_SECRET', + reason: 'asked while attached', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + if (!live.requestId) { + throw new Error('expected a queued request') + } + store.resolve(live.requestId, 'declined') + expect(secretEvents(desktop).map((event) => event.type)).toEqual([ + 'secrets.requested', + 'secrets.requested', + 'secrets.requestSettled' + ]) + + cleanups.forEach((cleanup) => cleanup()) + await Promise.all(done) + const before = desktop.length + store.request({ + name: 'AFTER_CLOSE', + reason: 'r', + agent: null, + worktreeId: null, + terminalHandle: null, + sessionEnvNames: new Set() + }) + expect(desktop).toHaveLength(before) +}) diff --git a/src/main/runtime/rpc/methods/client-events/client-events.ts b/src/main/runtime/rpc/methods/client-events/client-events.ts index f78a7844631..ed23408c727 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events.ts @@ -16,6 +16,12 @@ import { } from '../../../../../shared/structured-chat-dispatch-telemetry' import { subscribeStructuredChatTelemetry } from '../../../../telemetry/structured-chat-dispatch' import { structuredCallerFor } from '../structured-sessions/creation/structured-agent-session-gate' +import { + getSecretRequestStore, + phoneSecretRequestEvent, + type SecretRequestStoreEvent +} from '../../../secrets/secret-request-store' +import { isCloudWorkspaceOrcad } from '../../../secrets/session-env-names' let clientEventSubscriptionSeq = 0 @@ -60,6 +66,13 @@ export const CLIENT_EVENT_METHODS = [ }) : undefined + // Agent secret requests (secrets.requested): phones get status only. + const emitSecretRequest = (event: SecretRequestStoreEvent): void => + emit(clientKind === 'mobile' ? phoneSecretRequestEvent(event) : event) + // Only a cloud workspace's orcad takes secret requests. + const secretRequests = isCloudWorkspaceOrcad() ? getSecretRequestStore() : null + const unsubscribeSecretRequests = secretRequests?.subscribe(emitSecretRequest) + const seq = ++clientEventSubscriptionSeq const subscriptionId = `runtime-client-events-${connectionId ?? 'inproc'}-${seq}` runtime.registerSubscriptionCleanup( @@ -68,6 +81,7 @@ export const CLIENT_EVENT_METHODS = [ unsubscribe() unregisterHostVolunteer?.() unsubscribeTelemetry?.() + unsubscribeSecretRequests?.() emit({ type: 'end' }) resolve() }, @@ -75,6 +89,10 @@ export const CLIENT_EVENT_METHODS = [ ) // Listen before snapshotting to close the subscribe race and replay sleep state missed during disconnect. + // Requests made while no client was attached wait here until they expire. + for (const event of secretRequests?.pendingEvents() ?? []) { + emitSecretRequest(event) + } for (const event of runtime.getTerminalSleepClientEventSnapshot?.() ?? []) { emit(event) } diff --git a/src/main/runtime/rpc/methods/orchestration/turn-sender.ts b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts index 696926a4499..891582cf604 100644 --- a/src/main/runtime/rpc/methods/orchestration/turn-sender.ts +++ b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts @@ -24,6 +24,21 @@ function plainTerminalHandle(ctx: RpcContext): string | null { return terminal && !terminal.launchTokenHash && terminal.paneKey === paneKey ? handle : null } +/** + * The terminal an agent's own CLI call came from, as orcad attests it: a token-launched terminal + * proves its launch token, a plain one must match handle and pane key. Never read from params. + */ +export function verifiedCallerTerminalHandle(ctx: RpcContext): string | null { + // Agents reach orcad through the local CLI only; paired devices are people, not agents. + if (ctx.caller?.kind !== 'local-cli') { + return null + } + const authority = ctx.runtime.verifyOrchestrationCompatibilityCaller( + ctx.orchestrationCompatibilityEvidence + ) + return authority?.terminalHandle ?? plainTerminalHandle(ctx) +} + /** * Who drove me? For an agent's own tools: the caller is the terminal or structured session orcad * attests from its launch evidence, so one agent can never read (or claim) another agent's sender. @@ -40,10 +55,7 @@ function turnSender(ctx: RpcContext): TurnSenderResult { sender: drivingDeviceFor(agentSessionSenderKey(sessionId)) } } - const authority = ctx.runtime.verifyOrchestrationCompatibilityCaller( - ctx.orchestrationCompatibilityEvidence - ) - const handle = authority?.terminalHandle ?? plainTerminalHandle(ctx) + const handle = verifiedCallerTerminalHandle(ctx) if (!handle) { return { caller: null, sender: null } } diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index 457fe71b374..8f6474dded0 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -47,6 +47,7 @@ import { MANAGED_SERVER_METHODS } from './host-management/managed-server' import { RECIPE_VM_WAKE_METHODS } from './host-management/recipe-vm-wake' import { ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS } from './orca-cloud/orca-cloud-device-enrollment' import { CLOUD_SSH_METHODS } from './cloud-ssh/cloud-ssh-methods' +import { SECRET_REQUEST_METHODS } from './secrets/secret-requests' import { ENVIRONMENT_DOCTOR_METHODS } from './host-management/environment-doctor' import { CLOUD_ENVIRONMENT_METHODS_RPC } from './cloud-environments/cloud-environments' import { SPEECH_METHODS } from './speech/speech' @@ -150,6 +151,7 @@ export const ALL_RPC_METHODS = [ ...MANAGED_SERVER_METHODS, ...RECIPE_VM_WAKE_METHODS, ...ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS, + ...SECRET_REQUEST_METHODS, ...CLOUD_SSH_METHODS, ...ENVIRONMENT_DOCTOR_METHODS, ...CLOUD_ENVIRONMENT_METHODS_RPC, diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts new file mode 100644 index 00000000000..fa06681e83d --- /dev/null +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from 'vitest' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { SecretRequestStore } from '../../../secrets/secret-request-store' +import type { RpcContext, RpcMethod } from '../../core' +import { eraseRpcMethods } from '../../core' +import { createSecretRequestMethods } from './secret-requests' + +/** `verified` stands in for the terminal orcad attests from launch evidence. */ +function setup( + options: { sessionEnv?: string[]; enabled?: boolean; verified?: string | null } = {} +) { + let seq = 0 + const store = new SecretRequestStore(Date.now, () => `sr_rpc${String(++seq).padStart(5, '0')}`) + const methods = new Map( + eraseRpcMethods( + createSecretRequestMethods({ + store: () => store, + sessionEnvNames: async () => new Set(options.sessionEnv ?? []), + enabled: () => options.enabled ?? true, + callerTerminal: (ctx) => + ctx.caller?.kind === 'local-cli' ? (options.verified ?? null) : null + }) + ).map((method) => [method.name, method]) + ) + const terminals: Record = { + 'term-codex': { agent: 'codex', worktreeId: 'wt-real' } + } + const fake = { + getTerminalHandleAgent: (handle: string) => terminals[handle] ?? null, + isKnownWorktree: async (id: string) => id === 'wt-known' + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers read only these members. + const runtime = fake as unknown as OrcaRuntimeService + const call = async (name: string, params: unknown, ctx: Partial = {}) => { + const method = methods.get(name) + if (!method) { + throw new Error(`${name} is not registered`) + } + const parsed = method.params ? method.params.parse(params) : undefined + return method.handler(parsed, { runtime, ...ctx }) + } + const events: unknown[] = [] + store.subscribe((event) => events.push(event)) + return { call, events } +} + +const desktop: Partial = { caller: { kind: 'paired-device', deviceId: 'dev-1' } } +const agentCli: Partial = { caller: { kind: 'local-cli' } } + +describe('secrets.* RPC', () => { + it('derives the agent and worktree from the verified calling terminal', async () => { + const { call, events } = setup({ verified: 'term-codex' }) + await expect( + call( + 'secrets.request', + { name: 'STRIPE_KEY', reason: 'tests', worktreeId: 'wt-known' }, + agentCli + ) + ).resolves.toEqual({ requestId: 'sr_rpc00001', status: 'pending' }) + expect(events[0]).toMatchObject({ + agent: 'codex', + worktreeId: 'wt-real', + terminalHandle: 'term-codex' + }) + }) + + it('takes no terminal or agent from params', async () => { + const { call } = setup() + for (const extra of [{ terminalHandle: 'term-codex' }, { agent: 'claude' }]) { + await expect( + call('secrets.request', { name: 'A', reason: 'r', ...extra }, agentCli) + ).rejects.toThrow() + } + }) + + it('without a verified terminal: agent unknown, worktree hint kept only if this host knows it', async () => { + const { call, events } = setup({ verified: null }) + await call('secrets.request', { name: 'A', reason: 'r', worktreeId: 'wt-known' }, agentCli) + await call('secrets.request', { name: 'B', reason: 'r', worktreeId: 'wt-made-up' }, agentCli) + expect(events[0]).toMatchObject({ agent: null, worktreeId: 'wt-known' }) + expect(events[0]).not.toHaveProperty('terminalHandle') + expect(events[1]).toMatchObject({ agent: null, worktreeId: null }) + }) + + it('refuses every method outside a cloud workspace orcad', async () => { + const { call } = setup({ enabled: false }) + await expect(call('secrets.request', { name: 'A', reason: 'r' })).rejects.toThrow( + 'secret_requests_unavailable' + ) + await expect( + call('secrets.requestStatus', { requestId: 'sr_rpc00001' }, desktop) + ).rejects.toThrow('secret_requests_unavailable') + }) + + it('answers already-set from the session env and refuses agent credentials', async () => { + const { call } = setup({ sessionEnv: ['SENTRY_DSN'] }) + await expect(call('secrets.request', { name: 'SENTRY_DSN', reason: 'r' })).resolves.toEqual({ + requestId: null, + status: 'already-set' + }) + await expect( + call('secrets.request', { name: 'ANTHROPIC_API_KEY', reason: 'r' }) + ).rejects.toThrow('use_sign_in_or_cloud_secrets') + }) + + it('strips control and bidi characters from the reason, and caps it at 200 characters', async () => { + const { call, events } = setup() + await call('secrets.request', { + name: 'A', + reason: 'Run‮ the\ntests\u0007 ⁦now⁩\u001b[31m' + }) + expect(events[0]).toMatchObject({ reason: 'Run the tests now [31m' }) + await expect(call('secrets.request', { name: 'B', reason: 'x'.repeat(201) })).rejects.toThrow() + await expect(call('secrets.request', { name: 'C', reason: '‮\n\u0000' })).rejects.toThrow() + }) + + it('lets a person, never the agent CLI, touch and resolve; anyone reads status', async () => { + const { call } = setup() + await call('secrets.request', { name: 'A', reason: 'r' }, agentCli) + const id = { requestId: 'sr_rpc00001' } + await expect(call('secrets.touchRequest', id, agentCli)).rejects.toThrow( + 'secret_request_forbidden' + ) + await expect( + call('secrets.resolveRequest', { ...id, outcome: 'provided' }, agentCli) + ).rejects.toThrow('secret_request_forbidden') + await expect(call('secrets.touchRequest', id, desktop)).resolves.toHaveProperty('expiresAt') + await expect( + call('secrets.resolveRequest', { ...id, outcome: 'provided' }, desktop) + ).resolves.toEqual({ outcome: 'provided' }) + await expect(call('secrets.requestStatus', id, agentCli)).resolves.toMatchObject({ + status: 'provided', + name: 'A' + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/secrets/secret-requests.ts b/src/main/runtime/rpc/methods/secrets/secret-requests.ts new file mode 100644 index 00000000000..3d52f1afd64 --- /dev/null +++ b/src/main/runtime/rpc/methods/secrets/secret-requests.ts @@ -0,0 +1,122 @@ +import { + SECRET_REQUEST_ERRORS, + SECRETS_REQUEST_METHOD, + SECRETS_REQUEST_STATUS_METHOD, + SECRETS_RESOLVE_REQUEST_METHOD, + SECRETS_TOUCH_REQUEST_METHOD, + SecretsRequestIdParamsSchema, + SecretsRequestParamsSchema, + SecretsResolveRequestParamsSchema, + type SecretsRequestResult, + type SecretsRequestStatusResult, + type SecretsResolveRequestResult, + type SecretsTouchRequestResult +} from '../../../../../shared/secret-request-contract' +import { + getSecretRequestStore, + SecretRequestError, + type SecretRequestStore +} from '../../../secrets/secret-request-store' +import { isCloudWorkspaceOrcad, readSessionEnvNames } from '../../../secrets/session-env-names' +import { defineMethod, type RpcContext } from '../../core' +import { isAgentRpcCaller } from '../../rpc-caller-identity' +import { verifiedCallerTerminalHandle } from '../orchestration/turn-sender' + +export type SecretRequestDeps = { + store: () => SecretRequestStore + sessionEnvNames: () => Promise> + /** Only a cloud workspace's orcad takes requests; a desktop's local runtime refuses them. */ + enabled: () => boolean + /** The terminal the call came from, as orcad verifies it. */ + callerTerminal: (ctx: RpcContext) => string | null +} + +const defaultDeps: SecretRequestDeps = { + store: getSecretRequestStore, + sessionEnvNames: () => readSessionEnvNames(), + enabled: () => isCloudWorkspaceOrcad(), + callerTerminal: verifiedCallerTerminalHandle +} + +type CallerRuntime = Pick + +/** Agent and worktree from the verified calling terminal; a worktree hint only if this host knows it. */ +export async function resolveSecretRequestCaller( + runtime: CallerRuntime, + terminalHandle: string | null, + worktreeHint: string | undefined +): Promise<{ agent: string | null; worktreeId: string | null; terminalHandle: string | null }> { + const terminal = terminalHandle ? runtime.getTerminalHandleAgent(terminalHandle) : null + if (terminal) { + return { agent: terminal.agent, worktreeId: terminal.worktreeId, terminalHandle } + } + const worktreeId = + worktreeHint && (await runtime.isKnownWorktree(worktreeHint)) ? worktreeHint : null + return { agent: null, worktreeId, terminalHandle: null } +} + +/** Only a person's client (desktop or paired device) answers a request, never the agent's own CLI. */ +function requirePersonCaller(ctx: Pick): void { + if (isAgentRpcCaller(ctx.caller)) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.forbidden) + } +} + +export function createSecretRequestMethods(deps: SecretRequestDeps = defaultDeps) { + // Registered everywhere so the RPC catalog is one shape; accepted only on cloud orcad. + const store = (): SecretRequestStore => { + if (!deps.enabled()) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.unavailable) + } + return deps.store() + } + return [ + defineMethod({ + name: SECRETS_REQUEST_METHOD, + permission: 'workspace', + params: SecretsRequestParamsSchema, + handler: async (params, ctx): Promise => { + const requests = store() + const caller = await resolveSecretRequestCaller( + ctx.runtime, + deps.callerTerminal(ctx), + params.worktreeId + ) + return requests.request({ + name: params.name, + reason: params.reason, + scope: params.scope, + ...caller, + sessionEnvNames: await deps.sessionEnvNames() + }) + } + }), + defineMethod({ + name: SECRETS_REQUEST_STATUS_METHOD, + permission: 'workspace', + params: SecretsRequestIdParamsSchema, + handler: async (params): Promise => + store().status(params.requestId) + }), + defineMethod({ + name: SECRETS_TOUCH_REQUEST_METHOD, + permission: 'workspace', + params: SecretsRequestIdParamsSchema, + handler: async (params, ctx): Promise => { + requirePersonCaller(ctx) + return store().touch(params.requestId) + } + }), + defineMethod({ + name: SECRETS_RESOLVE_REQUEST_METHOD, + permission: 'workspace', + params: SecretsResolveRequestParamsSchema, + handler: async (params, ctx): Promise => { + requirePersonCaller(ctx) + return store().resolve(params.requestId, params.outcome) + } + }) + ] +} + +export const SECRET_REQUEST_METHODS = createSecretRequestMethods() diff --git a/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts b/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts new file mode 100644 index 00000000000..7f5e6f0e7b5 --- /dev/null +++ b/src/main/runtime/rpc/methods/terminal/agent-session-key-env.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { withKeyEnvFolded } from './agent-session' + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('carried agent keys on the host', () => { + it('folds them into the launch env on an ordinary host', () => { + expect(withKeyEnvFolded({ keyEnv: { GEMINI_API_KEY: 'AIzaSy-real' } })).toEqual({ + keyEnv: undefined, + accountEnv: { GEMINI_API_KEY: 'AIzaSy-real' } + }) + }) + + it('drops them on an Orca Cloud VM', () => { + vi.stubEnv('ORCA_IS_CLOUD', '1') + expect( + withKeyEnvFolded({ keyEnv: { GEMINI_API_KEY: 'AIzaSy-real' }, accountEnv: { X: '1' } }) + ).toEqual({ + keyEnv: undefined, + accountEnv: { X: '1' } + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/terminal/agent-session.ts b/src/main/runtime/rpc/methods/terminal/agent-session.ts index 1c4f49cfa16..aee3b21890f 100644 --- a/src/main/runtime/rpc/methods/terminal/agent-session.ts +++ b/src/main/runtime/rpc/methods/terminal/agent-session.ts @@ -34,12 +34,17 @@ function withExecutionHostAgentPresentation; keyEnv?: Record } >(params: T): T { if (!params.keyEnv) { return params } + // An Orca Cloud VM never takes a desktop's keys (they would sit here in plaintext); its agents + // get Cloud secrets as egress placeholders instead. The desktop already withholds them. + if (process.env.ORCA_IS_CLOUD === '1') { + return { ...params, keyEnv: undefined } + } const accountEnv = withAgentKeyLaunchEnv(params.accountEnv, params.keyEnv) const folded: T = { ...params, keyEnv: undefined, ...(accountEnv ? { accountEnv } : {}) } return folded diff --git a/src/main/runtime/secrets/secret-request-store.test.ts b/src/main/runtime/secrets/secret-request-store.test.ts new file mode 100644 index 00000000000..e38a832e32f --- /dev/null +++ b/src/main/runtime/secrets/secret-request-store.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, it } from 'vitest' +import { SECRET_REQUEST_ERRORS } from '../../../shared/secret-request-contract' +import { + phoneSecretRequestEvent, + SecretRequestError, + SecretRequestStore, + type SecretRequestInput, + type SecretRequestStoreEvent +} from './secret-request-store' + +const MIN = 60_000 + +function makeStore() { + const clock = { now: 1_000_000 } + let seq = 0 + const timers: { at: number; run: () => void; cancelled: boolean }[] = [] + const store = new SecretRequestStore( + () => clock.now, + () => `sr_test${String(++seq).padStart(4, '0')}`, + (run, ms) => { + const timer = { at: clock.now + ms, run, cancelled: false } + timers.push(timer) + return { cancel: () => (timer.cancelled = true) } + } + ) + const events: SecretRequestStoreEvent[] = [] + store.subscribe((event) => events.push(event)) + /** Moves the clock and fires due timers. */ + const advance = (ms: number): void => { + clock.now += ms + for (const timer of timers.splice(0)) { + if (timer.cancelled) { + continue + } + if (timer.at <= clock.now) { + timer.run() + } else { + timers.push(timer) + } + } + } + return { store, clock, events, advance } +} + +function input(name: string, extra: Partial = {}): SecretRequestInput { + return { + name, + reason: 'Run the integration tests', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + sessionEnvNames: new Set(), + ...extra + } +} + +function errorCode(fn: () => unknown): string | undefined { + try { + fn() + } catch (error) { + return error instanceof SecretRequestError ? error.code : undefined + } + return undefined +} + +describe('SecretRequestStore', () => { + it('queues a request, announces it and defaults the scope to personal', () => { + const { store, events } = makeStore() + expect(store.request(input('STRIPE_KEY', { scope: undefined }))).toEqual({ + requestId: 'sr_test0001', + status: 'pending' + }) + expect(events).toEqual([ + { + type: 'secrets.requested', + requestId: 'sr_test0001', + name: 'STRIPE_KEY', + reason: 'Run the integration tests', + scope: 'personal', + agent: 'claude', + worktreeId: 'wt-1', + terminalHandle: 'term-1', + requestedAt: 1_000_000, + expiresAt: 1_000_000 + 15 * MIN + } + ]) + expect(store.status('sr_test0001')).toMatchObject({ status: 'pending', name: 'STRIPE_KEY' }) + }) + + it('answers already-set without queueing when the session env has the name', () => { + const { store, events } = makeStore() + expect( + store.request(input('SENTRY_DSN', { sessionEnvNames: new Set(['SENTRY_DSN']) })) + ).toEqual({ requestId: null, status: 'already-set' }) + expect(events).toEqual([]) + expect(store.pendingEvents()).toEqual([]) + }) + + it.each([ + ['lower_case', SECRET_REQUEST_ERRORS.invalidName], + ['1STARTS_WITH_DIGIT', SECRET_REQUEST_ERRORS.invalidName], + ['A'.repeat(129), SECRET_REQUEST_ERRORS.invalidName], + ['CLAUDE_CODE_OAUTH_TOKEN', SECRET_REQUEST_ERRORS.subscriptionTokenRefused], + ['PATH', SECRET_REQUEST_ERRORS.reservedName], + ['GITHUB_TOKEN', SECRET_REQUEST_ERRORS.reservedName], + ['ORCA_ANYTHING', SECRET_REQUEST_ERRORS.reservedName], + ['LD_PRELOAD', SECRET_REQUEST_ERRORS.reservedName], + ['GIT_CONFIG_GLOBAL', SECRET_REQUEST_ERRORS.reservedName], + ['ANTHROPIC_API_KEY', SECRET_REQUEST_ERRORS.agentCredential], + ['AWS_BEARER_TOKEN_BEDROCK', SECRET_REQUEST_ERRORS.agentCredential], + ['OPENAI_BASE_URL', SECRET_REQUEST_ERRORS.agentCredential] + ])('refuses %s with %s', (name, code) => { + const { store, events } = makeStore() + expect(errorCode(() => store.request(input(name)))).toBe(code) + expect(events).toEqual([]) + }) + + it('still allows names that are not agent credentials (AI_GATEWAY_API_KEY, general AWS_*)', () => { + const { store } = makeStore() + expect(store.request(input('AI_GATEWAY_API_KEY')).status).toBe('pending') + expect(store.request(input('AWS_SECRET_ACCESS_KEY')).status).toBe('pending') + }) + + it('dedupes the same name while pending, without a second card', () => { + const { store, events } = makeStore() + const first = store.request(input('DB_URL')) + const again = store.request(input('DB_URL', { reason: 'different words' })) + expect(again).toEqual(first) + expect(events).toHaveLength(1) + }) + + it('allows at most 3 pending requests', () => { + const { store } = makeStore() + for (const name of ['A1', 'A2', 'A3']) { + store.request(input(name)) + } + expect(errorCode(() => store.request(input('A4')))).toBe(SECRET_REQUEST_ERRORS.tooManyPending) + // Answering one frees a slot. + store.resolve('sr_test0001', 'declined') + expect(store.request(input('A4')).status).toBe('pending') + }) + + it('allows at most 10 requests per hour, counting answered ones', () => { + const { store, clock } = makeStore() + for (let i = 0; i < 10; i += 1) { + const { requestId } = store.request(input(`N${i}`)) + if (!requestId) { + throw new Error('expected a queued request') + } + store.resolve(requestId, 'provided') + clock.now += MIN + } + expect(errorCode(() => store.request(input('N10')))).toBe(SECRET_REQUEST_ERRORS.rateLimited) + // The first falls out of the hour window. + clock.now = 1_000_000 + 60 * MIN + expect(store.request(input('N10')).status).toBe('pending') + }) + + it('expires pending requests after 15 minutes and stops replaying them', () => { + const { store, clock } = makeStore() + store.request(input('TOKEN')) + clock.now += 15 * MIN - 1 + expect(store.pendingEvents()).toHaveLength(1) + clock.now += 1 + expect(store.status('sr_test0001').status).toBe('expired') + expect(store.pendingEvents()).toEqual([]) + // An expired request frees its name and slot. + expect(store.request(input('TOKEN')).requestId).toBe('sr_test0002') + }) + + it('touch extends to now + 15 minutes, capped at 60 minutes after the request', () => { + const { store, clock } = makeStore() + store.request(input('TOKEN')) + clock.now += 10 * MIN + expect(store.touch('sr_test0001')).toEqual({ expiresAt: clock.now + 15 * MIN }) + for (let i = 0; i < 4; i += 1) { + clock.now += 10 * MIN + store.touch('sr_test0001') + } + // 60 minutes after the request, however often it was touched. + expect(store.status('sr_test0001').expiresAt).toBe(1_000_000 + 60 * MIN) + clock.now = 1_000_000 + 60 * MIN + expect(store.status('sr_test0001').status).toBe('expired') + expect(errorCode(() => store.touch('sr_test0001'))).toBe(SECRET_REQUEST_ERRORS.notPending) + }) + + it('resolves once; a request that expired mid-save reports expired', () => { + const { store, clock, events } = makeStore() + store.request(input('A')) + store.request(input('B')) + expect(store.resolve('sr_test0001', 'provided')).toEqual({ outcome: 'provided' }) + expect(store.resolve('sr_test0001', 'declined')).toEqual({ outcome: 'provided' }) + expect(store.status('sr_test0001').status).toBe('provided') + clock.now += 16 * MIN + expect(store.resolve('sr_test0002', 'provided')).toEqual({ outcome: 'expired' }) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([ + { type: 'secrets.requestSettled', requestId: 'sr_test0001', status: 'provided' } + ]) + }) + + it('reports unknown ids, and forgets old ones', () => { + const { store, clock } = makeStore() + expect(errorCode(() => store.status('sr_missing00'))).toBe(SECRET_REQUEST_ERRORS.notFound) + store.request(input('A')) + clock.now += 2 * 60 * MIN + expect(errorCode(() => store.status('sr_test0001'))).toBe(SECRET_REQUEST_ERRORS.notFound) + }) + + it('gives phones status only: no reason or terminal handle', () => { + const { store, events } = makeStore() + store.request(input('A')) + const event = events[0] + const phone = phoneSecretRequestEvent(event) + expect(phone).not.toHaveProperty('reason') + expect(phone).not.toHaveProperty('terminalHandle') + expect(phone).toMatchObject({ name: 'A', agent: 'claude', requestId: event.requestId }) + }) + + it('announces a touch, and a natural expiry (at the touched time), to every client', () => { + const { store, events, advance } = makeStore() + store.request(input('TOKEN')) + advance(10 * MIN) + store.touch('sr_test0001') + expect(events.at(-1)).toEqual({ + type: 'secrets.requestUpdated', + requestId: 'sr_test0001', + expiresAt: 1_000_000 + 25 * MIN + }) + // The original 15-minute expiry no longer fires. + advance(6 * MIN) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([]) + advance(9 * MIN) + expect(events.at(-1)).toEqual({ + type: 'secrets.requestSettled', + requestId: 'sr_test0001', + status: 'expired' + }) + }) + + it('announces no expiry for an answered request', () => { + const { store, events, advance } = makeStore() + store.request(input('TOKEN')) + store.resolve('sr_test0001', 'provided') + advance(20 * MIN) + expect(events.filter((e) => e.type === 'secrets.requestSettled')).toEqual([ + { type: 'secrets.requestSettled', requestId: 'sr_test0001', status: 'provided' } + ]) + }) +}) diff --git a/src/main/runtime/secrets/secret-request-store.ts b/src/main/runtime/secrets/secret-request-store.ts new file mode 100644 index 00000000000..4201e9af520 --- /dev/null +++ b/src/main/runtime/secrets/secret-request-store.ts @@ -0,0 +1,273 @@ +import { randomBytes } from 'node:crypto' +import { + SECRET_REQUEST_ERRORS, + SECRET_REQUEST_MAX_LIFETIME_MS, + SECRET_REQUEST_MAX_PENDING, + SECRET_REQUEST_MAX_PER_HOUR, + SECRET_REQUEST_TTL_MS, + SECRETS_REQUEST_SETTLED_EVENT, + SECRETS_REQUEST_UPDATED_EVENT, + SECRETS_REQUESTED_EVENT, + type SecretRequestedEvent, + type SecretRequestScope, + type SecretRequestSettledEvent, + type SecretRequestUpdatedEvent, + type SecretRequestStatus, + type SecretsRequestResult, + type SecretsRequestStatusResult, + type SecretsResolveRequestResult, + type SecretsTouchRequestResult +} from '../../../shared/secret-request-contract' +import { secretRequestNameRefusal } from '../../../shared/secret-request-names' + +const HOUR_MS = 60 * 60_000 + +export class SecretRequestError extends Error { + constructor(readonly code: string) { + super(code) + this.name = 'SecretRequestError' + } +} + +type SecretRequestRecord = { + requestId: string + name: string + reason: string + scope: SecretRequestScope + agent: string | null + worktreeId: string | null + terminalHandle: string | null + requestedAt: number + expiresAt: number + outcome: 'provided' | 'declined' | null +} + +export type SecretRequestInput = { + name: string + reason: string + scope?: SecretRequestScope + /** Derived by the caller from the terminal's agent session, never from request params. */ + agent: string | null + worktreeId: string | null + terminalHandle: string | null + /** Names currently in the session env. */ + sessionEnvNames: ReadonlySet +} + +export type SecretRequestStoreEvent = + | SecretRequestedEvent + | SecretRequestUpdatedEvent + | SecretRequestSettledEvent + +/** Schedules `run` after `ms`; the result cancels it. */ +export type SecretRequestTimer = (run: () => void, ms: number) => { cancel: () => void } + +const realTimer: SecretRequestTimer = (run, ms) => { + const handle = setTimeout(run, ms) + // A pending request must never keep orcad alive. + handle.unref?.() + return { cancel: () => clearTimeout(handle) } +} + +/** In-memory only (never on disk): one orcad serves one cloud workspace, so limits and dedupe are + * per store. Records outlive their request by an hour so `--wait` can read the outcome. */ +export class SecretRequestStore { + private readonly records = new Map() + private readonly listeners = new Set<(event: SecretRequestStoreEvent) => void>() + private readonly expiryTimers = new Map void }>() + + constructor( + private readonly now: () => number = Date.now, + private readonly newId: () => string = () => `sr_${randomBytes(12).toString('base64url')}`, + private readonly timer: SecretRequestTimer = realTimer + ) {} + + request(input: SecretRequestInput): SecretsRequestResult { + const refusal = secretRequestNameRefusal(input.name) + if (refusal) { + throw new SecretRequestError(refusal) + } + if (input.sessionEnvNames.has(input.name)) { + return { requestId: null, status: 'already-set' } + } + const now = this.now() + this.prune(now) + const pending = [...this.records.values()].filter((r) => this.statusOf(r, now) === 'pending') + const same = pending.find((r) => r.name === input.name) + if (same) { + return { requestId: same.requestId, status: 'pending' } + } + if (pending.length >= SECRET_REQUEST_MAX_PENDING) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.tooManyPending) + } + const lastHour = [...this.records.values()].filter((r) => now - r.requestedAt < HOUR_MS) + if (lastHour.length >= SECRET_REQUEST_MAX_PER_HOUR) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.rateLimited) + } + const record: SecretRequestRecord = { + requestId: this.newId(), + name: input.name, + reason: input.reason, + scope: input.scope ?? 'personal', + agent: input.agent, + worktreeId: input.worktreeId, + terminalHandle: input.terminalHandle, + requestedAt: now, + expiresAt: now + SECRET_REQUEST_TTL_MS, + outcome: null + } + this.records.set(record.requestId, record) + this.scheduleExpiry(record) + this.emit(toRequestedEvent(record)) + return { requestId: record.requestId, status: 'pending' } + } + + status(requestId: string): SecretsRequestStatusResult { + const record = this.require(requestId) + return { + requestId, + name: record.name, + status: this.statusOf(record, this.now()), + expiresAt: record.expiresAt + } + } + + /** D3: the card is in use, so keep the agent waiting: now + 15 min, capped at 60 min after the request. */ + touch(requestId: string): SecretsTouchRequestResult { + const record = this.require(requestId) + const now = this.now() + if (this.statusOf(record, now) !== 'pending') { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.notPending) + } + record.expiresAt = Math.min( + now + SECRET_REQUEST_TTL_MS, + record.requestedAt + SECRET_REQUEST_MAX_LIFETIME_MS + ) + this.scheduleExpiry(record) + this.emit({ type: SECRETS_REQUEST_UPDATED_EVENT, requestId, expiresAt: record.expiresAt }) + return { expiresAt: record.expiresAt } + } + + /** First outcome wins. A request that expired mid-save reports `expired`; the saved value stands. */ + resolve(requestId: string, outcome: 'provided' | 'declined'): SecretsResolveRequestResult { + const record = this.require(requestId) + const status = this.statusOf(record, this.now()) + if (status !== 'pending') { + return { outcome: status } + } + record.outcome = outcome + this.clearExpiry(requestId) + this.emit({ type: SECRETS_REQUEST_SETTLED_EVENT, requestId, status: outcome }) + return { outcome } + } + + /** Requests still waiting, for replay to a client that attaches later. */ + pendingEvents(): SecretRequestedEvent[] { + const now = this.now() + return [...this.records.values()] + .filter((r) => this.statusOf(r, now) === 'pending') + .map(toRequestedEvent) + } + + subscribe(listener: (event: SecretRequestStoreEvent) => void): () => void { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + /** Natural expiry is announced too, so every client drops the card at the same moment. */ + private scheduleExpiry(record: SecretRequestRecord): void { + this.clearExpiry(record.requestId) + const handle = this.timer( + () => { + this.expiryTimers.delete(record.requestId) + const now = this.now() + if (record.outcome || now < record.expiresAt) { + if (!record.outcome) { + this.scheduleExpiry(record) + } + return + } + this.emit({ + type: SECRETS_REQUEST_SETTLED_EVENT, + requestId: record.requestId, + status: 'expired' + }) + }, + Math.max(0, record.expiresAt - this.now()) + ) + this.expiryTimers.set(record.requestId, handle) + } + + private clearExpiry(requestId: string): void { + this.expiryTimers.get(requestId)?.cancel() + this.expiryTimers.delete(requestId) + } + + private statusOf(record: SecretRequestRecord, now: number): SecretRequestStatus { + if (record.outcome) { + return record.outcome + } + return now >= record.expiresAt ? 'expired' : 'pending' + } + + private require(requestId: string): SecretRequestRecord { + this.prune(this.now()) + const record = this.records.get(requestId) + if (!record) { + throw new SecretRequestError(SECRET_REQUEST_ERRORS.notFound) + } + return record + } + + private prune(now: number): void { + for (const [id, record] of this.records) { + if (now - record.requestedAt >= SECRET_REQUEST_MAX_LIFETIME_MS + HOUR_MS) { + this.records.delete(id) + } + } + } + + private emit(event: SecretRequestStoreEvent): void { + for (const listener of this.listeners) { + try { + listener(event) + } catch { + // One broken subscriber must not keep the others from seeing the request. + } + } + } +} + +function toRequestedEvent(record: SecretRequestRecord): SecretRequestedEvent { + return { + type: SECRETS_REQUESTED_EVENT, + requestId: record.requestId, + name: record.name, + reason: record.reason, + scope: record.scope, + agent: record.agent, + worktreeId: record.worktreeId, + ...(record.terminalHandle ? { terminalHandle: record.terminalHandle } : {}), + requestedAt: record.requestedAt, + expiresAt: record.expiresAt + } +} + +/** Phones show status only: no agent-written text. */ +export function phoneSecretRequestEvent(event: SecretRequestStoreEvent): SecretRequestStoreEvent { + if (event.type !== SECRETS_REQUESTED_EVENT) { + return event + } + const { reason: _reason, terminalHandle: _terminalHandle, ...status } = event + return status +} + +let sharedStore: SecretRequestStore | null = null + +/** The process's store: orcad's requests live as long as orcad. */ +export function getSecretRequestStore(): SecretRequestStore { + sharedStore ??= new SecretRequestStore() + return sharedStore +} diff --git a/src/main/runtime/secrets/session-env-names.test.ts b/src/main/runtime/secrets/session-env-names.test.ts new file mode 100644 index 00000000000..c07cbea7ceb --- /dev/null +++ b/src/main/runtime/secrets/session-env-names.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { isCloudWorkspaceOrcad, readSessionEnvNames } from './session-env-names' + +describe('readSessionEnvNames', () => { + it('reads names (never values) from the session env file', async () => { + const paths: string[] = [] + const names = await readSessionEnvNames({ + uid: 1000, + read: async (path) => { + paths.push(path) + return 'STRIPE_KEY=c2VjcmV0\nDB_URL=\nnot a line\nlower=eA==\n' + } + }) + expect(paths).toEqual(['/dev/shm/orca-env-1000/session.env']) + expect([...names]).toEqual(['STRIPE_KEY', 'DB_URL']) + }) + + it("is empty when there's no session env file, never orcad's own env", async () => { + const names = await readSessionEnvNames({ + uid: 1000, + read: async () => { + throw Object.assign(new Error('missing'), { code: 'ENOENT' }) + } + }) + expect([...names]).toEqual([]) + }) +}) + +describe('isCloudWorkspaceOrcad', () => { + it('needs both the cloud flag and a sandbox id', () => { + expect(isCloudWorkspaceOrcad({ ORCA_IS_CLOUD: '1', ORCA_SANDBOX_ID: 'sbx_1' })).toBe(true) + expect(isCloudWorkspaceOrcad({ ORCA_IS_CLOUD: '1' })).toBe(false) + expect(isCloudWorkspaceOrcad({ ORCA_SANDBOX_ID: 'sbx_1' })).toBe(false) + expect(isCloudWorkspaceOrcad({})).toBe(false) + }) +}) diff --git a/src/main/runtime/secrets/session-env-names.ts b/src/main/runtime/secrets/session-env-names.ts new file mode 100644 index 00000000000..63eef164ff7 --- /dev/null +++ b/src/main/runtime/secrets/session-env-names.ts @@ -0,0 +1,36 @@ +import { readFile } from 'node:fs/promises' + +/** Where /opt/orca/bin/orca-sandbox-env keeps the cloud session env (tmpfs; `NAME=` lines). */ +export function sessionEnvFilePath(uid: number): string { + return `/dev/shm/orca-env-${uid}/session.env` +} + +/** Names only, never values. No file yet means the session env holds nothing; orcad's own process + * env is never consulted, so nothing about the host leaks through `already-set`. */ +export async function readSessionEnvNames( + options: { uid?: number; read?: (path: string) => Promise } = {} +): Promise> { + const uid = options.uid ?? process.getuid?.() + const read = options.read ?? ((path: string) => readFile(path, 'utf8')) + if (uid === undefined) { + return new Set() + } + let text: string + try { + text = await read(sessionEnvFilePath(uid)) + } catch { + return new Set() + } + return new Set( + text + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => line.slice(0, line.indexOf('='))) + .filter((name) => /^[A-Z_][A-Z0-9_]*$/.test(name)) + ) +} + +/** Secret requests exist only on a cloud workspace's orcad (orca-sandbox-start sets these). */ +export function isCloudWorkspaceOrcad(env: NodeJS.ProcessEnv = process.env): boolean { + return env.ORCA_IS_CLOUD === '1' && Boolean(env.ORCA_SANDBOX_ID?.trim()) +} diff --git a/src/main/startup/cli-command-names.ts b/src/main/startup/cli-command-names.ts index 13bd049c0bc..38dfd5329d7 100644 --- a/src/main/startup/cli-command-names.ts +++ b/src/main/startup/cli-command-names.ts @@ -66,6 +66,7 @@ export const CLI_COMMAND_NAMES = [ 'scroll', 'scrollintoview', 'search', + 'secret', 'select', 'select-all', 'sender', diff --git a/src/preload/api/cloud-secrets-bridge.ts b/src/preload/api/cloud-secrets-bridge.ts index 34e663d55c4..a311162c9f2 100644 --- a/src/preload/api/cloud-secrets-bridge.ts +++ b/src/preload/api/cloud-secrets-bridge.ts @@ -29,6 +29,11 @@ export type CloudSecretsApi = { effective: (request: { repo?: string }) => Promise> /** Best-effort nudge so a running workspace picks up new values now; the server also does it on write. */ refreshEnv: (request: { runtimeEnvironmentId: string }) => Promise> + /** Saves one of this computer's Agent API Keys as a personal Cloud secret (the value never leaves main). */ + saveDesktopKey: (request: { + agent: string + envName: string + }) => Promise> } export const cloudSecretsApi: CloudSecretsApi = { @@ -38,5 +43,6 @@ export const cloudSecretsApi: CloudSecretsApi = { remove: (request) => ipcRenderer.invoke('cloudSecrets:remove', request), batch: (request) => ipcRenderer.invoke('cloudSecrets:batch', request), effective: (request) => ipcRenderer.invoke('cloudSecrets:effective', request), - refreshEnv: (request) => ipcRenderer.invoke('cloudSecrets:refreshEnv', request) + refreshEnv: (request) => ipcRenderer.invoke('cloudSecrets:refreshEnv', request), + saveDesktopKey: (request) => ipcRenderer.invoke('cloudSecrets:saveDesktopKey', request) } diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 0e37a68192e..0e419815469 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -5,6 +5,7 @@ import type { CloudWorkspacePatch, OrgPrompts } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' export type CloudWorkspacesResult = | { ok: true; value: T } @@ -33,6 +34,8 @@ export type CloudWorkspacesApi = { openGrant: ( id: string ) => Promise> + /** A sleeping workspace's sealed read snapshot, opened in main with this device's reader key. Never wakes it. */ + readSnapshot: (id: string) => Promise> listGrants: (id: string) => Promise> revokeGrant: (id: string, grantId: string) => Promise> localWorkspaces: () => Promise diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index c35320aa55f..a8ea180d427 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -9,6 +9,7 @@ export const cloudWorkspacesApi = { resolveLink: (workspaceId, chatId) => ipcRenderer.invoke('cloudWorkspaces:resolveLink', { workspaceId, chatId }), openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }), + readSnapshot: (id) => ipcRenderer.invoke('cloudWorkspaces:readSnapshot', { id }), listGrants: (id) => ipcRenderer.invoke('cloudWorkspaces:listGrants', { id }), revokeGrant: (id, grantId) => ipcRenderer.invoke('cloudWorkspaces:revokeGrant', { id, grantId }), localWorkspaces: () => ipcRenderer.invoke('cloudWorkspaces:localWorkspaces'), diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 782d1d11619..7b625d60f2d 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -92,6 +92,7 @@ --color-accent-foreground: var(--accent-foreground); --color-destructive: var(--destructive); --color-destructive-foreground: var(--destructive-foreground); + --color-destructive-text: var(--destructive-text); --color-border: var(--border); --color-input: var(--input); --color-ring: var(--ring); @@ -452,6 +453,8 @@ color-scheme: light; --destructive: #e40014; --destructive-foreground: #fff; + /* Why: raw red on its own 10% tint is ~4.1:1; small red text on a tint needs the darker mix. */ + --destructive-text: color-mix(in srgb, var(--destructive) 85%, var(--foreground)); --status-success: #147638; --status-success-background: color-mix(in srgb, var(--status-success) 10%, transparent); --status-success-border: color-mix(in srgb, var(--status-success) 25%, transparent); @@ -490,6 +493,7 @@ --destructive: #ff6568; /* Dark --destructive is a light red, so its label needs dark ink to clear AA. */ --destructive-foreground: #450a0a; + --destructive-text: var(--destructive); --status-success: #86efac; --status-success-background: color-mix(in srgb, var(--status-success) 10%, transparent); --status-success-border: color-mix(in srgb, var(--status-success) 25%, transparent); diff --git a/src/renderer/src/assets/theme-token-contrast.test.ts b/src/renderer/src/assets/theme-token-contrast.test.ts index 71538f350dc..3336b9e6c4b 100644 --- a/src/renderer/src/assets/theme-token-contrast.test.ts +++ b/src/renderer/src/assets/theme-token-contrast.test.ts @@ -63,3 +63,27 @@ describe.each([':root', '.dark'] as const)('built-in %s token pairs', (selector) expect(contrastRatio(token('--status-success'), surface)).toBeGreaterThanOrEqual(4.5) }) }) + +const destructiveTextMix = Number( + css.match( + /--destructive-text: color-mix\(in srgb, var\(--destructive\) (\d+)%, var\(--foreground\)\)/ + )?.[1] +) + +// The destructive chip paints its text on bg-destructive/10 (and /15 on hover) over the page. +describe.each([0.1, 0.15])('destructive chip text on a %s tint', (amount) => { + it('meets WCAG AA in the light theme', () => { + const light = themeTokens(':root') + const destructive = light.get('--destructive')! + const text = tint(destructive, destructiveTextMix / 100, light.get('--foreground')!) + const surface = tint(destructive, amount, light.get('--background')!) + expect(contrastRatio(text, surface)).toBeGreaterThanOrEqual(4.5) + }) + + it('meets WCAG AA in the dark theme', () => { + const dark = themeTokens('.dark') + const destructive = dark.get('--destructive')! + const surface = tint(destructive, amount, dark.get('--background')!) + expect(contrastRatio(destructive, surface)).toBeGreaterThanOrEqual(4.5) + }) +}) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx index b3f28ab17bd..6df1f77f717 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx @@ -61,7 +61,12 @@ export const waitingCodex = shot( export const signedIn = shot(gate({ step: 'signed', email: 'nw@stably.ai' })) export const portBusy = shot( gate( - { step: 'error', kind: 'port_busy', message: 'Port 1455 is busy.', port: 1455 }, + { + step: 'error', + kind: 'port_busy', + message: 'Port 1455 is in use on this computer.', + port: 1455 + }, { agent: 'codex' } ) ) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx index ee0e671db45..fd6b2ecf5bb 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx @@ -336,7 +336,7 @@ function AgentSignInError({ case 'port_busy': return ( - -
-

- {t('auto.components.billing.paymentFailed', 'Payment failed')} -

-

- {payment.suspendRunning || payment.graceEndsAt === null - ? t( - 'auto.components.billing.paymentAsleepBody', - 'New sandboxes can’t start and running sandboxes are asleep. They can wake again once the payment goes through. Your files are safe.' - ) - : t( - 'auto.components.billing.paymentGraceBody2', - 'New sandboxes can’t start. Running sandboxes go to sleep on {{value0}} unless the payment goes through.', - { value0: when(payment.graceEndsAt) } - )} -

- {entitlement.canManageBilling ? ( - + + <> + {body}{' '} {t( 'auto.components.billing.paymentAskAdmin', 'Ask an owner or admin to update the payment method.' )} -

- )} -
- + + ) + } + action={ + entitlement.canManageBilling ? ( + + ) : undefined + } + /> ) } diff --git a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx index c07c627551b..930dab3c37f 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx @@ -126,3 +126,77 @@ export const suspendedAdmin = defineFixture({ /> ) }) + +/** First open of Settings › Orca account: the section holds its shape while billing answers. */ +export const loading = defineFixture({ + width: 600, + render: () => +}) + +/** Billing's 75% level: the early warning under the bar (still the neutral tone below 90%). */ +export const usageWarning75 = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +/** Billing's 90% level: the bar turns to the warning tone; one hour left reads singular. */ +export const usageWarning90 = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +/** An admin types a cap above billing's maximum: the field says what the maximum is. */ +export const capTooHigh = defineFixture({ + width: 600, + render: () => ( + + ), + interact: async (frame) => { + const input = frame.querySelector('input[inputmode="numeric"]') + if (!input) { + return + } + input.focus() + // React listens for native input events. + const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set + setValue?.call(input, '6000') + input.dispatchEvent(new Event('input', { bubbles: true })) + await new Promise((resolve) => setTimeout(resolve, 100)) + } +}) diff --git a/src/renderer/src/components/billing/PlanBillingSection.tsx b/src/renderer/src/components/billing/PlanBillingSection.tsx index 47cc1fc4c1d..d76cba535d8 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.tsx @@ -3,6 +3,7 @@ import { SettingsGroupHeader } from '@/components/settings/section-layout/Settin import { CreditCard, ExternalLink, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' +import { Skeleton } from '@/components/ui/skeleton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { formatCents } from './plans/plans-pricing' import { cn } from '@/lib/utils' @@ -18,11 +19,17 @@ import { OverageControls, UsageSummary } from './PlanBillingUsage' import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy' import { PlanStatusBadge } from './PlanStatusBadge' import { useOrcaBillingStatus } from './use-orca-billing-status' -import { invalidateOrcaCloudBilling } from '../new-workspace/orca-cloud-billing-cache' +import { useAppStore } from '@/store/index' +import { BILLING_CAPABILITY } from './register-plan-billing-menu-item' export function PlanBillingSection(): React.JSX.Element | null { const t = useTranslate() + const locale = useIntlLocale() const { loading, result, refresh } = useOrcaBillingStatus(true) + // Only billing-flagged accounts get a skeleton; others hear "unconfigured" and show nothing. + const billingFlagged = useAppStore( + (state) => state.orcaProfileAuthStatus?.capabilities?.flags[BILLING_CAPABILITY] === true + ) const [busy, setBusy] = useState(false) const [notice, setNotice] = useState(null) const [userRefreshing, setUserRefreshing] = useState(false) @@ -61,11 +68,12 @@ export function PlanBillingSection(): React.JSX.Element | null { })) setBusy(false) if (outcome.status === 'ok') { + // One shared store: this re-read also updates the Run-on picker's Orca Cloud row. refresh() - // The Run-on picker's Orca Cloud row reads a shared copy; overage/cap just changed it. - invalidateOrcaCloudBilling() } else { - const failure = overageFailureCopy(outcome, t) + const maxCap = + result?.status === 'ok' ? (result.entitlement.offers?.team.maxSpendCapCents ?? null) : null + const failure = overageFailureCopy(outcome, t, maxCap, locale) setNotice(failure ? { kind: 'error', text: failure } : null) setOverageFailures((count) => count + 1) } @@ -74,7 +82,7 @@ export function PlanBillingSection(): React.JSX.Element | null { return ( + } if (!result || result.status === 'unconfigured' || result.status === 'signed-out') { // The pane above already handles sign-in; billing stays out of builds without a service. return null @@ -268,3 +279,36 @@ export function PlanBillingView({ ) } + +/** Same rows as a loaded plan (header, plan line, usage, overage card) so nothing jumps in. */ +function PlanBillingSkeleton(): React.JSX.Element { + const t = useTranslate() + return ( +
+ +
+ + + +
+
+
+ + +
+ + +
+ + +
+ ) +} diff --git a/src/renderer/src/components/billing/PlanBillingUsage.tsx b/src/renderer/src/components/billing/PlanBillingUsage.tsx index 8f306414235..662c5e94884 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.tsx @@ -11,7 +11,14 @@ import type { OrcaBillingOverageArgs } from '../../../../shared/orca-billing' import { formatHours, includedUsagePercent } from './plan-billing-format' -import { formatCents } from './plans/plans-pricing' +import { + includedUsageTone, + sandboxHoursLeftLine, + sandboxHoursOverLine, + usageWarningLine +} from './plan-billing-usage-copy' +import { formatCents, formatRateCents } from './plans/plans-pricing' +import { capTooHighCopy } from './plan-billing-copy' import { ORCA_BILLING_OVERAGE_SECTION_ID } from '../new-workspace/orca-cloud-run-target-access' /** "Resets and renews Dec 2" when both land the same day (monthly); separate parts otherwise. */ @@ -55,6 +62,8 @@ export function UsageSummary({ const locale = useIntlLocale() const date = (ms: number): string => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(ms) + const overLine = sandboxHoursOverLine(entitlement, t) + const warning = usageWarningLine(entitlement, t) return (
@@ -68,51 +77,15 @@ export function UsageSummary({ } )} - - {t('auto.components.billing.sandboxHoursLeft', '{{value0}} sandbox hours left', { - value0: formatHours(entitlement.remainingIncludedSeconds) - })} - + {sandboxHoursLeftLine(entitlement, t)}
= 100 && !entitlement.overage.optedIn - ? 'warning' - : 'default' - } + tone={includedUsageTone(entitlement)} aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} /> - {entitlement.overageSeconds === 0 && - entitlement.usedSeconds > entitlement.includedSeconds && - entitlement.includedSeconds > 0 ? ( -

- {t('auto.components.billing.sandboxHoursOver', '{{count}} sandbox hours over', { - count: Math.round((entitlement.usedSeconds - entitlement.includedSeconds) / 360) / 10, - defaultValue_one: '{{count}} sandbox hour over' - })} -

- ) : null} - {entitlement.overageSeconds > 0 ? ( -

- {t('auto.components.billing.overageHoursOnly', '{{value0}} overage hours this month', { - value0: formatHours(entitlement.overageSeconds) - })} -

- ) : null} - {entitlement.usageWarningPercent !== null && entitlement.usageWarningPercent < 100 ? ( -

- {entitlement.usageWarningPercent >= 100 - ? t('auto.components.billing.warn100b', 'All of this month’s sandbox hours are used.') - : t( - 'auto.components.billing.warnPercent2', - 'You’ve used {{value0}}% of this month’s sandbox hours.', - { - value0: String(entitlement.usageWarningPercent) - } - )} -

- ) : null} + {overLine ?

{overLine}

: null} + {warning ?

{warning}

: null}

{resetLine(entitlement, date, t)}

) @@ -158,21 +131,24 @@ export function OverageControls({ } const optedIn = optimisticOn ?? overage.optedIn const parsedCap = Number(capDollars) - const capValid = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0 + const maxCapCents = entitlement.offers?.team.maxSpendCapCents ?? null + const capWhole = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0 + const capTooHigh = capWhole && maxCapCents !== null && parsedCap * 100 > maxCapCents + const capValid = capWhole && !capTooHigh const changed = capValid && capDollars.trim() !== savedDollars const paymentFailed = entitlement.payment.pastDueSince !== null const description = t( - 'auto.components.billing.overageDescription5', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default).', + 'auto.components.billing.overageDescription6', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default).', { - value0: formatCents(overage.centsPerHour, locale), - value1: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale) + rate: formatRateCents(overage.centsPerHour, locale), + cap: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale) } ) const descriptionOn = t( - 'auto.components.billing.overageDescriptionOn2', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set.', - { value0: formatCents(overage.centsPerHour, locale) } + 'auto.components.billing.overageDescriptionOn3', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set.', + { rate: formatRateCents(overage.centsPerHour, locale) } ) const capPercent = overage.spendCapCents > 0 @@ -279,13 +255,17 @@ export function OverageControls({ {t('auto.components.billing.capLabel2', 'Monthly spend cap')}
-
- +
+ $ {capValid ? null : (

- {t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')} + {capTooHigh && maxCapCents !== null + ? capTooHighCopy(maxCapCents, locale, t) + : t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')}

)}
diff --git a/src/renderer/src/components/billing/billing-summary-store.test.ts b/src/renderer/src/components/billing/billing-summary-store.test.ts new file mode 100644 index 00000000000..38de96b89e8 --- /dev/null +++ b/src/renderer/src/components/billing/billing-summary-store.test.ts @@ -0,0 +1,121 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' +import { + getBillingState, + getBillingSummary, + getLastBillingStatus, + mergeBillingResult, + recordBillingStatus, + refreshBillingStatus, + resetBillingSummary, + watchBillingStatus +} from './billing-summary-store' +import { sampleTeam } from './plan-billing-fixtures' + +const teamA: OrcaBillingStatusResult = { status: 'ok', entitlement: { ...sampleTeam } } +const teamB: OrcaBillingStatusResult = { + status: 'ok', + entitlement: { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +} +const offline: OrcaBillingStatusResult = { status: 'failed', error: 'offline' } + +let pending: ((result: OrcaBillingStatusResult) => void)[] = [] + +beforeEach(() => { + pending = [] + resetBillingSummary() + vi.stubGlobal('api', { + orcaProfiles: { + billingStatus: vi.fn( + () => new Promise((resolve) => pending.push(resolve)) + ) + } + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +async function answer(index: number, result: OrcaBillingStatusResult): Promise { + pending[index](result) + await Promise.resolve() + await Promise.resolve() +} + +describe('mergeBillingResult', () => { + it('keeps a good answer through a failure and replaces it otherwise', () => { + expect(mergeBillingResult(teamA, offline)).toBe(teamA) + expect(mergeBillingResult(null, offline)).toBe(offline) + expect(mergeBillingResult(teamA, teamB)).toBe(teamB) + expect(mergeBillingResult(teamA, { status: 'signed-out' })).toEqual({ status: 'signed-out' }) + }) +}) + +describe('billing store', () => { + it('keeps the last good result when a re-read fails', async () => { + const read = refreshBillingStatus() + await answer(0, teamA) + await read + expect(getBillingState()).toMatchObject({ result: teamA, loading: false }) + + const reread = refreshBillingStatus() + expect(getBillingState()).toMatchObject({ result: teamA, loading: true }) + await answer(1, offline) + await reread + expect(getBillingState()).toMatchObject({ result: teamA, loading: false }) + expect(getLastBillingStatus()).toBe(teamA) + expect(getBillingSummary()).toMatchObject({ subscribed: true, planLabel: 'Team' }) + }) + + it('re-reads after a kept failure instead of trusting it as fresh', async () => { + recordBillingStatus(teamA) + recordBillingStatus(offline) + void refreshBillingStatus({ maxAgeMs: 60_000 }) + expect(pending).toHaveLength(1) + }) + + it('joins a running read and only supersedes it when asked', async () => { + void refreshBillingStatus() + void refreshBillingStatus() + expect(pending).toHaveLength(1) + void refreshBillingStatus({ supersede: true }) + expect(pending).toHaveLength(2) + // The older read answers last; the newer one already wrote. + await answer(1, teamB) + await answer(0, teamA) + expect(getBillingState().result).toBe(teamB) + }) + + it('drops an answer that started before a team switch', async () => { + const read = refreshBillingStatus() + resetBillingSummary() + await answer(0, teamA) + await read + expect(getBillingState()).toMatchObject({ result: null, loading: false }) + expect(getLastBillingStatus()).toBeNull() + expect(getBillingSummary().subscribed).toBeNull() + }) + + it("never keeps the previous team's plan through the new team's failed read", async () => { + recordBillingStatus(teamA) + resetBillingSummary() + void refreshBillingStatus() + await answer(0, offline) + expect(getBillingState().result).toEqual(offline) + expect(getLastBillingStatus()).toBeNull() + }) + + it('reads the new team at once when a view is watching through the switch', async () => { + const release = watchBillingStatus() + void refreshBillingStatus() + resetBillingSummary() + expect(pending).toHaveLength(2) + expect(getBillingState()).toMatchObject({ result: null, loading: true }) + await answer(0, teamA) + await answer(1, teamB) + expect(getBillingState().result).toBe(teamB) + release() + }) +}) diff --git a/src/renderer/src/components/billing/billing-summary-store.ts b/src/renderer/src/components/billing/billing-summary-store.ts index b7115772237..5ffba23b560 100644 --- a/src/renderer/src/components/billing/billing-summary-store.ts +++ b/src/renderer/src/components/billing/billing-summary-store.ts @@ -1,6 +1,10 @@ -// What the always-visible upgrade entry points need to know: does this account have a plan? -// Read when the account (or org) changes and refreshed by any billing view that loads status. +// The one billing-status cache. Settings, the plans and Team pages, the build sheet, the Run-on +// picker and the account menu all read it, so they always agree and a read by one serves the others. +// It keeps the last good answer: a failed read (offline for a moment when the window regains focus) +// never replaces it. Answers are scoped to the account and team that asked for them. import { useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import { getOrcaAccountKey } from '@/hooks/use-orca-account-key' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { isActivePlan } from './team/team-seat-math' @@ -12,49 +16,85 @@ export type BillingSummary = { planLabel: string | null } -let summary: BillingSummary = { subscribed: null, canManageBilling: false, planLabel: null } +export type BillingStoreState = { + /** Last answer for the current account and team; 'failed' only when nothing good was read yet. */ + result: OrcaBillingStatusResult | null + /** A read for the current account is running. */ + loading: boolean + /** When `result` was last confirmed by the service; 0 when stale or never. */ + fetchedAt: number +} + +const EMPTY: BillingStoreState = { result: null, loading: false, fetchedAt: 0 } +const SUMMARY_MIN_REFRESH_MS = 60_000 + +let state: BillingStoreState = EMPTY +/** Account the current `result` belongs to. */ +let stateAccount: string | null = null +/** Bumped on every account/team switch; answers that started before it are dropped. */ +let generation = 0 +/** Only the newest read may write; an older one that answers late is dropped. */ +let latestRead = 0 +let inFlight: { generation: number; account: string; promise: Promise } | null = null +/** Mounted views that want billing kept current (re-read after a switch drops a read). */ +let watchers = 0 const listeners = new Set<() => void>() -let lastReadAt = 0 -let inFlight: Promise | null = null -const MIN_REFRESH_MS = 60_000 -let lastStatus: OrcaBillingStatusResult | null = null +function currentAccount(): string { + return getOrcaAccountKey(useAppStore.getState().orcaProfileAuthStatus) +} -/** The latest successful status for the current account, to seed views that open later. */ -export function getLastBillingStatus(): OrcaBillingStatusResult | null { - return lastStatus +function setState(next: BillingStoreState): void { + if ( + next.result === state.result && + next.loading === state.loading && + next.fetchedAt === state.fetchedAt + ) { + return + } + state = next + for (const listener of listeners) { + listener() + } +} + +function readBillingStatus(): Promise { + return window.api.orcaProfiles + .billingStatus() + .catch((error: unknown): OrcaBillingStatusResult => ({ + status: 'failed', + error: error instanceof Error ? error.message : String(error) + })) +} + +/** + * Merges an answer into the cache: a failure keeps the last good result for the same account + * (a brief offline moment must not blank the section); anything else replaces it. + */ +export function mergeBillingResult( + previous: OrcaBillingStatusResult | null, + next: OrcaBillingStatusResult +): OrcaBillingStatusResult { + return next.status === 'failed' && previous?.status === 'ok' ? previous : next } export function recordBillingStatus(result: OrcaBillingStatusResult): void { - if (result.status === 'ok') { - lastStatus = result - } else if (result.status !== 'failed') { - lastStatus = null - } - const next: BillingSummary = - result.status === 'ok' - ? { - subscribed: isActivePlan(result.entitlement), - canManageBilling: result.entitlement.canManageBilling, - planLabel: isActivePlan(result.entitlement) ? result.entitlement.planLabel : null - } - : result.status === 'failed' - ? summary - : { subscribed: null, canManageBilling: false, planLabel: null } - if ( - next.subscribed !== summary.subscribed || - next.canManageBilling !== summary.canManageBilling || - next.planLabel !== summary.planLabel - ) { - summary = next - for (const listener of listeners) { - listener() - } - } + const account = currentAccount() + const previous = stateAccount === account ? state.result : null + const merged = mergeBillingResult(previous, result) + stateAccount = account + setState({ + result: merged, + loading: inFlight !== null, + // A result kept through a failure counts as stale, so the next look reads again. + fetchedAt: merged === result ? Date.now() : 0 + }) } -/** Bumped on every account/org switch; answers from an older account are ignored. */ -let generation = 0 +/** The latest good status for the current account, to seed views that open later. */ +export function getLastBillingStatus(): OrcaBillingStatusResult | null { + return stateAccount === currentAccount() && state.result?.status === 'ok' ? state.result : null +} export function getBillingGeneration(): number { return generation @@ -70,47 +110,153 @@ export function recordBillingStatusIfCurrent( } } -/** Forget the previous account's plan at once (sign-out, account or org switch). */ +/** Forget the previous account's plan at once (sign-out, account or team switch). */ export function resetBillingSummary(): void { generation++ + latestRead++ inFlight = null - lastReadAt = 0 - recordBillingStatus({ status: 'signed-out' }) -} - -/** Re-reads billing status at most once a minute unless `force` (account or org switched). */ -export function refreshBillingSummary(force = false): Promise { - if (!force && (inFlight || Date.now() - lastReadAt < MIN_REFRESH_MS)) { - return inFlight ?? Promise.resolve() + stateAccount = null + setState(EMPTY) + if (watchers > 0) { + // Views still on screen read the new account's billing at once. + void refreshBillingStatus() } - const requestGeneration = generation - lastReadAt = Date.now() - const request = window.api.orcaProfiles - .billingStatus() - .then((result) => { - if (requestGeneration === generation) { - recordBillingStatus(result) - } - }) - .catch(() => undefined) - .finally(() => { - if (inFlight === request) { - inFlight = null - } - }) - inFlight = request - return request } -export function getBillingSummary(): BillingSummary { - return summary +/** Marks the cached answer stale (billing changed elsewhere) so the next read doesn't trust it. */ +export function markBillingStale(): void { + setState({ ...state, fetchedAt: 0 }) } -export function subscribeBillingSummary(listener: () => void): () => void { +export function hasBillingWatchers(): boolean { + return watchers > 0 +} + +/** A mounted view that wants billing current; returns its release. */ +export function watchBillingStatus(): () => void { + watchers++ + let released = false + return () => { + if (!released) { + released = true + watchers-- + } + } +} + +/** The running read for the current account, if any (callers wait on it). */ +export function getBillingReadInFlight(): Promise | null { + return inFlight?.promise ?? null +} + +/** + * Reads billing status. Joins a running read for the same account unless `supersede` (billing just + * changed in-app, so a read that started earlier may be stale). With `maxAgeMs`, a cached answer + * younger than that is trusted and nothing is read. + */ +export function refreshBillingStatus({ + supersede = false, + maxAgeMs = 0 +}: { supersede?: boolean; maxAgeMs?: number } = {}): Promise { + const account = currentAccount() + if ( + !supersede && + inFlight && + inFlight.generation === generation && + inFlight.account === account + ) { + return inFlight.promise + } + if ( + maxAgeMs > 0 && + stateAccount === account && + state.result && + Date.now() - state.fetchedAt < maxAgeMs + ) { + return Promise.resolve() + } + if (stateAccount !== account) { + // Another account's answer must not stay on screen while this one's loads. + stateAccount = account + setState(EMPTY) + } + const startedGeneration = generation + const mine = ++latestRead + const promise = readBillingStatus().then((result): Promise | void => { + if (mine !== latestRead) { + // Superseded by a newer read or a reset; that one writes. + return + } + inFlight = null + if (startedGeneration !== generation || account !== currentAccount()) { + // The account or team changed mid-read: the answer is for the old one. Read again for + // whoever is still looking. + if (watchers > 0) { + return refreshBillingStatus() + } + setState({ ...state, loading: false }) + return + } + recordBillingStatus(result) + }) + inFlight = { generation: startedGeneration, account, promise } + setState({ ...state, loading: true }) + return promise +} + +/** Re-reads billing status at most once a minute unless `force` (account or team switched). */ +export function refreshBillingSummary(force = false): Promise { + return refreshBillingStatus(force ? {} : { maxAgeMs: SUMMARY_MIN_REFRESH_MS }) +} + +export function getBillingState(): BillingStoreState { + return state +} + +export function subscribeBillingState(listener: () => void): () => void { listeners.add(listener) return () => listeners.delete(listener) } +export function useBillingState(): BillingStoreState { + return useSyncExternalStore(subscribeBillingState, getBillingState) +} + +const UNKNOWN_SUMMARY: BillingSummary = { + subscribed: null, + canManageBilling: false, + planLabel: null +} +let summaryFor: OrcaBillingStatusResult | null = null +let summary: BillingSummary = UNKNOWN_SUMMARY + +export function getBillingSummary(): BillingSummary { + const result = state.result + if (result === summaryFor) { + return summary + } + summaryFor = result + const next: BillingSummary = + result?.status === 'ok' + ? { + subscribed: isActivePlan(result.entitlement), + canManageBilling: result.entitlement.canManageBilling, + planLabel: isActivePlan(result.entitlement) ? result.entitlement.planLabel : null + } + : UNKNOWN_SUMMARY + // Keep the same object when nothing visible changed, so subscribers don't re-render. + if ( + next.subscribed !== summary.subscribed || + next.canManageBilling !== summary.canManageBilling || + next.planLabel !== summary.planLabel + ) { + summary = next + } + return summary +} + +export const subscribeBillingSummary = subscribeBillingState + export function useBillingSummary(): BillingSummary { - return useSyncExternalStore(subscribeBillingSummary, getBillingSummary) + return useSyncExternalStore(subscribeBillingState, getBillingSummary) } diff --git a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx index d3d50bb8f35..7b2922b2552 100644 --- a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx +++ b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx @@ -8,7 +8,6 @@ import type { OrcaBillingOffers } from '../../../../../shared/orca-billing' import { openFailureCopy } from '../plan-billing-copy' import { formatCents, periodTotalCents } from '../plans/plans-pricing' import type { CheckoutPhase } from './checkout-flow' -import { seatCountLabel } from '../team/team-copy' export type CheckoutPanelProps = { phase: Exclude @@ -37,45 +36,57 @@ function OrderSummary({ renews.setMonth(renews.getMonth() + 1) } const renewsLabel = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(renews) + const seatCount = new Intl.NumberFormat(locale).format(seats) return ( -
-
-
- {interval === 'year' - ? t('auto.components.billing.checkout.planAnnual', '{{value0}} · Annual', { - value0: team.label - }) - : t('auto.components.billing.checkout.planMonthly', '{{value0}} · Monthly', { - value0: team.label - })} -
-
- {perSeat === null - ? null - : t( - 'auto.components.billing.checkout.seatsTimes2', - '{{value0}} × {{value1}}{{value2}}', - { - value0: seatCountLabel(seats, t), - value1: formatCents(perSeat, locale), - value2: - interval === 'year' - ? t('auto.components.billing.checkout.perYr', '/yr') - : t('auto.components.billing.checkout.perMo', '/mo') - } - )} -
-
-
-
- {phase.kind === 'paid' - ? t('auto.components.billing.checkout.paidRow', 'Paid') - : t('auto.components.billing.checkout.dueToday', 'Due today')} -
-
- {total === null ? '—' : formatCents(total, locale)} -
-
+
+
+
+
+ {interval === 'year' + ? t('auto.components.billing.checkout.planAnnual', '{{value0}} · Annual', { + value0: team.label + }) + : t('auto.components.billing.checkout.planMonthly', '{{value0}} · Monthly', { + value0: team.label + })} +
+
+ {perSeat === null + ? null + : interval === 'year' + ? t( + 'auto.components.billing.checkout.lineItemYearly', + '{{seats}} × {{price}} per seat, billed yearly', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat, billed yearly' + } + ) + : t( + 'auto.components.billing.checkout.lineItemMonthly', + '{{seats}} × {{price}} per seat per month', + { + count: seats, + seats: seatCount, + price: formatCents(perSeat, locale), + defaultValue_one: '{{seats}} × {{price}} per seat per month' + } + )} +
+
+
+
+ {phase.kind === 'paid' + ? t('auto.components.billing.checkout.paidRow', 'Paid') + : t('auto.components.billing.checkout.dueToday', 'Due today')} +
+
+ {total === null ? '—' : formatCents(total, locale)} +
+
+

{t( 'auto.components.billing.checkout.renewsNote', @@ -83,7 +94,7 @@ function OrderSummary({ { value0: renewsLabel } )}

-
+
) } @@ -92,7 +103,7 @@ function StatusIcon({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JS return ( diff --git a/src/renderer/src/components/billing/checkout/checkout-return.ts b/src/renderer/src/components/billing/checkout/checkout-return.ts new file mode 100644 index 00000000000..e600549131a --- /dev/null +++ b/src/renderer/src/components/billing/checkout/checkout-return.ts @@ -0,0 +1,49 @@ +import { useAppStore } from '@/store/index' +import { + takeOrcaCloudCheckoutReturn, + emitOrcaCloudCheckoutReturn +} from '@/lib/orca-cloud-after-checkout' +import { requestOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in' +import { invalidateOrcaCloudBilling } from '@/components/new-workspace/orca-cloud-billing-cache' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { closePlansPage } from '../plans/plans-page-store' +import { closeTeamPage, openTeamPage } from '../team/team-page-store' + +/** + * A paid Checkout closes the plans page and goes back to the work that hit the wall: the open + * composer with Orca Cloud picked, or the refused create, retried. Without an intent it lands on + * the Team page's "You're on Team" confirmation. + */ +export function returnAfterPaidCheckout(paidSeats: number): void { + closePlansPage() + const store = useAppStore.getState() + const target = takeOrcaCloudCheckoutReturn({ + composerOpen: store.activeModal === 'new-workspace-composer', + hasCreation: (creationId) => Boolean(store.pendingWorktreeCreations[creationId]) + }) + if (target.kind === 'team-page') { + openTeamPage({ kind: 'checkout-success', seats: paidSeats }) + return + } + closeTeamPage() + // The Run-on row cached "no plan"; read the new entitlement now so it shows hours, not Upgrade. + invalidateOrcaCloudBilling() + switch (target.kind) { + case 'retry': + // Lazy: the creation flow's import graph is heavy and billing never needs it otherwise. + void import('@/lib/workspace/creation/worktree-creation-flow').then( + ({ retryBackgroundWorktreeCreation }) => retryBackgroundWorktreeCreation(target.creationId) + ) + return + case 'select-in-composer': + // The composer's recipe list reloads and consumes this, as it does after signing in. + requestOrcaCloudSelectionAfterSignIn() + emitOrcaCloudCheckoutReturn() + return + case 'open-composer': + store.openModal('new-workspace-composer', { + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + telemetrySource: 'unknown' + }) + } +} diff --git a/src/renderer/src/components/billing/plan-billing-copy.ts b/src/renderer/src/components/billing/plan-billing-copy.ts index a584182fd4a..8563da88b66 100644 --- a/src/renderer/src/components/billing/plan-billing-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-copy.ts @@ -5,6 +5,7 @@ import type { OrcaBillingOpenResult, OrcaBillingOverageResult } from '../../../../shared/orca-billing' +import { formatCents } from './plans/plans-pricing' export function denyReasonCopy( reason: OrcaBillingDenyReason, @@ -113,12 +114,27 @@ export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): st } } -export function overageFailureCopy(result: OrcaBillingOverageResult, t: Translate): string | null { +/** "The spend cap can be at most $5,000." */ +export function capTooHighCopy(maxCents: number, locale: string, t: Translate): string { + return t('auto.components.billing.capAtMost', 'The spend cap can be at most {{max}}.', { + max: formatCents(maxCents, locale) + }) +} + +export function overageFailureCopy( + result: OrcaBillingOverageResult, + t: Translate, + /** The service's highest allowed cap; null from older services that don't send it. */ + maxCapCents: number | null = null, + locale = 'en-US' +): string | null { switch (result.status) { case 'ok': return null case 'cap-too-high': - return t('auto.components.billing.capTooHigh', 'That spend cap is above the allowed maximum.') + return maxCapCents === null + ? t('auto.components.billing.capTooHigh', 'That spend cap is above the allowed maximum.') + : capTooHighCopy(maxCapCents, locale, t) case 'no-subscription': return t('auto.components.billing.overageNoPlan', 'Overage needs an active plan.') case 'forbidden': diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index bed4b7c4667..696ede6ee78 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -7,8 +7,8 @@ const HOUR = 3600 export const sampleOffers: OrcaBillingOffers = { team: { label: 'Team', - monthlyPriceLabel: '$50/seat/mo', - annualPriceLabel: '$480/seat/yr', + monthlyPriceLabel: '$50 per seat per month', + annualPriceLabel: '$480 per seat, billed yearly', monthlyPriceCentsPerSeat: 5000, annualPriceCentsPerSeat: 48000, largeMachineWeight: 1, @@ -16,7 +16,8 @@ export const sampleOffers: OrcaBillingOffers = { concurrentSandboxesPerSeat: 3, idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 100, - defaultSpendCapCents: 2500 + defaultSpendCapCents: 2500, + maxSpendCapCents: 500_000 }, enterprise: { label: 'Enterprise', diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts new file mode 100644 index 00000000000..57bf4e51b26 --- /dev/null +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest' +import { translate } from '@/i18n/i18n' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' +import { sampleTeam } from './plan-billing-fixtures' +import { + accountMenuUsageLines, + includedUsageTone, + sandboxHoursCount, + sandboxHoursLeftLine, + sandboxHoursOverLine, + usageWarningLine +} from './plan-billing-usage-copy' + +const HOUR = 3600 +const t = translate +const team = (patch: Partial): OrcaBillingEntitlement => ({ + ...sampleTeam, + ...patch +}) + +describe('sandbox hours copy', () => { + it('counts hours to one decimal', () => { + expect(sandboxHoursCount(78.5 * HOUR)).toBe(78.5) + expect(sandboxHoursCount(HOUR + 1)).toBe(1) + expect(sandboxHoursCount(-5)).toBe(0) + }) + + it('pluralizes the hours left', () => { + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: 78.5 * HOUR }), t)).toBe( + '78.5 sandbox hours left' + ) + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: HOUR }), t)).toBe( + '1 sandbox hour left' + ) + expect(sandboxHoursLeftLine(team({ remainingIncludedSeconds: 0 }), t)).toBe( + '0 sandbox hours left' + ) + }) + + it('says how far over the included amount the team is, billed or not', () => { + expect(sandboxHoursOverLine(team({}), t)).toBeNull() + expect( + sandboxHoursOverLine(team({ usedSeconds: 123 * HOUR, overageSeconds: 3 * HOUR }), t) + ).toBe('3 sandbox hours over the included amount this month') + expect(sandboxHoursOverLine(team({ usedSeconds: 121 * HOUR, overageSeconds: 0 }), t)).toBe( + '1 sandbox hour over the included amount this month' + ) + }) + + it('warns at the level billing reports until the hours run out', () => { + expect(usageWarningLine(team({ usageWarningPercent: null }), t)).toBeNull() + expect(usageWarningLine(team({ usageWarningPercent: 75 }), t)).toBe( + 'Your team has used 75% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 90% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 80 }), t)).toBe( + 'Your team has used 80% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usageWarningPercent: 100 }), t)).toBeNull() + }) + + it('states the actual share used, floored, not the level that triggered it', () => { + expect(usageWarningLine(team({ usedSeconds: 119 * HOUR, usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 99% of this month’s sandbox hours.' + ) + expect(usageWarningLine(team({ usedSeconds: 92 * HOUR, usageWarningPercent: 75 }), t)).toBe( + 'Your team has used 76% of this month’s sandbox hours.' + ) + // Never "100%" while billing still reports hours left. + expect(usageWarningLine(team({ usedSeconds: 119.9 * HOUR, usageWarningPercent: 90 }), t)).toBe( + 'Your team has used 99% of this month’s sandbox hours.' + ) + }) + + it('turns the hours bar to the warning tone at 90%', () => { + expect(includedUsageTone(team({ usedSeconds: 107 * HOUR }))).toBe('default') + expect(includedUsageTone(team({ usedSeconds: 108 * HOUR }))).toBe('warning') + expect(includedUsageTone(team({ usedSeconds: 200 * HOUR }))).toBe('warning') + }) + + it('gives the account menu hours and the usage warning only on a plan', () => { + expect( + accountMenuUsageLines( + { + status: 'ok', + entitlement: team({ remainingIncludedSeconds: 20 * HOUR, usageWarningPercent: 90 }) + }, + t + ) + ).toEqual({ + hoursLeft: '20 sandbox hours left', + warning: 'Your team has used 90% of this month’s sandbox hours.' + }) + expect( + accountMenuUsageLines( + { status: 'ok', entitlement: team({ plan: null, planLabel: null, status: 'none' }) }, + t + ) + ).toBeNull() + expect(accountMenuUsageLines({ status: 'failed', error: 'offline' }, t)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.ts new file mode 100644 index 00000000000..4b2852f860c --- /dev/null +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.ts @@ -0,0 +1,100 @@ +// Sandbox-hours lines shared by Plan & billing, the plans page and the account menu, so every +// surface counts, pluralizes and warns the same way. +import type { Translate } from '@/i18n/use-translate' +import type { + OrcaBillingEntitlement, + OrcaBillingStatusResult +} from '../../../../shared/orca-billing' +import { includedUsagePercent } from './plan-billing-format' +import { isActivePlan } from './team/team-seat-math' + +/** The included-hours bar turns to the warning tone from this share of the month's hours. */ +export const INCLUDED_HOURS_WARNING_PERCENT = 90 + +/** Hours as a plural count: one decimal, whole numbers without it (41.5, 78, 1). */ +export function sandboxHoursCount(seconds: number): number { + return Math.round(Math.max(0, seconds) / 360) / 10 +} + +export function includedUsageTone(entitlement: OrcaBillingEntitlement): 'default' | 'warning' { + return includedUsagePercent(entitlement) >= INCLUDED_HOURS_WARNING_PERCENT ? 'warning' : 'default' +} + +/** "78.5 sandbox hours left" / "1 sandbox hour left". */ +export function sandboxHoursLeftLine(entitlement: OrcaBillingEntitlement, t: Translate): string { + return t('auto.components.billing.sandboxHoursLeftCount', '{{count}} sandbox hours left', { + count: sandboxHoursCount(entitlement.remainingIncludedSeconds), + defaultValue_one: '{{count}} sandbox hour left' + }) +} + +/** Hours past the included amount this month (billed as overage or not), or 0. */ +export function hoursOverIncludedSeconds(entitlement: OrcaBillingEntitlement): number { + if (entitlement.includedSeconds <= 0) { + return entitlement.overageSeconds + } + return Math.max(entitlement.overageSeconds, entitlement.usedSeconds - entitlement.includedSeconds) +} + +/** "3 sandbox hours over the included amount this month", or null when within it. */ +export function sandboxHoursOverLine( + entitlement: OrcaBillingEntitlement, + t: Translate +): string | null { + const count = sandboxHoursCount(hoursOverIncludedSeconds(entitlement)) + if (count <= 0) { + return null + } + return t( + 'auto.components.billing.sandboxHoursOverIncluded', + '{{count}} sandbox hours over the included amount this month', + { + count, + defaultValue_one: '{{count}} sandbox hour over the included amount this month' + } + ) +} + +/** + * The share of included hours actually used, floored, for the warning sentence: never below the + * level billing reported (its count may be fresher) and never 100 while hours remain. + */ +export function usedPercentForWarning(entitlement: OrcaBillingEntitlement): number { + const level = entitlement.usageWarningPercent ?? 0 + const used = + entitlement.includedSeconds > 0 + ? Math.floor((entitlement.usedSeconds / entitlement.includedSeconds) * 100) + : level + return Math.min(99, Math.max(level, used)) +} + +/** + * Shown once billing reports a warning level (75%, 90%) until the hours run out; the sentence states + * the actual share used, not the level. At 100% the bar, the hours-left line and the out-of-hours + * states say it instead. + */ +export function usageWarningLine(entitlement: OrcaBillingEntitlement, t: Translate): string | null { + const level = entitlement.usageWarningPercent + if (level === null || level >= 100) { + return null + } + return t( + 'auto.components.billing.teamUsedPercent', + 'Your team has used {{percent}}% of this month’s sandbox hours.', + { percent: String(usedPercentForWarning(entitlement)) } + ) +} + +/** The account menu's plan lines: hours left, and the early warning once the team reaches it. */ +export function accountMenuUsageLines( + result: OrcaBillingStatusResult | null, + t: Translate +): { hoursLeft: string; warning: string | null } | null { + if (result?.status !== 'ok' || !isActivePlan(result.entitlement)) { + return null + } + return { + hoursLeft: sandboxHoursLeftLine(result.entitlement, t), + warning: usageWarningLine(result.entitlement, t) + } +} diff --git a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx index 16e304cc02c..fca2a5f2531 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx @@ -30,10 +30,12 @@ export function PlansDialogContent( : 'top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-4xl [@media(max-height:800px)]:top-4 [@media(max-height:800px)]:max-h-[calc(100vh-2rem)]' } onOpenAutoFocus={(event) => { - // The dialog itself first; PlansView moves focus to the primary action once plans load. + // The heading, not the first button: Enter on "Continue" would start a monthly Checkout, + // and Tab from here reaches the interval toggle before the plan cards. event.preventDefault() if (event.currentTarget instanceof HTMLElement) { - event.currentTarget.focus() + const heading = event.currentTarget.querySelector('[data-plans-heading]') + ;(heading ?? event.currentTarget).focus() } }} > @@ -41,7 +43,7 @@ export function PlansDialogContent(

{t('auto.components.billing.plans.eyebrow', 'Orca Cloud')}

- + {checkout ? checkoutState === 'paid' ? t('auto.components.billing.checkout.titlePaid', 'Welcome to Orca Cloud') diff --git a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx index a18897ec431..33fd15573a7 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react' +import { useState } from 'react' import { Dialog } from '@/components/ui/dialog' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' @@ -7,7 +7,8 @@ import { CheckoutPanel } from '../checkout/CheckoutPanel' import { useCheckoutFlow } from '../checkout/use-checkout-flow' import { openFailureCopy } from '../plan-billing-copy' import type { PlanBillingNotice } from '../PlanBillingSection' -import { openTeamPage } from '../team/team-page-store' +import { returnAfterPaidCheckout } from '../checkout/checkout-return' +import { cancelOrcaCloudAfterCheckout } from '@/lib/orca-cloud-after-checkout' import { useOrcaBillingStatus } from '../use-orca-billing-status' import { PlansDialogContent } from './PlansDialogContent' import { closePlansPage, usePlansPageState } from './plans-page-store' @@ -17,7 +18,7 @@ import { useOrgSeatCount } from './use-org-seat-count' * The plans page. A dialog because choosing a plan is a decision step in front of Checkout; * it reads the billing service's offers, so prices and limits are never hardcoded here. * Checkout itself runs on Stripe's hosted page in the browser; this dialog follows it and, - * once paid, hands over to the Team page. + * once paid, returns to the Orca Cloud wall that opened it, or hands over to the Team page. */ export function PlansDialogHost(): React.JSX.Element { const t = useTranslate() @@ -29,11 +30,7 @@ export function PlansDialogHost(): React.JSX.Element { const [notice, setNotice] = useState(null) const [orderedAt, setOrderedAt] = useState(0) - const onPaid = useCallback((paidSeats: number) => { - closePlansPage() - openTeamPage({ kind: 'checkout-success', seats: paidSeats }) - }, []) - const checkout = useCheckoutFlow({ onPaid }) + const checkout = useCheckoutFlow({ onPaid: returnAfterPaidCheckout }) const openPortal = async (): Promise => { setBusy(true) @@ -69,6 +66,8 @@ export function PlansDialogHost(): React.JSX.Element { // Closing ends the watch: polling stops and the next open starts from the plans. checkout.reset() closePlansPage() + // Leaving without paying: nothing to return to Orca Cloud for. + cancelOrcaCloudAfterCheckout() setNotice(null) } }} diff --git a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx index 627ee89ebd9..c496a5b2947 100644 --- a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx @@ -105,3 +105,23 @@ export const loadFailed = defineFixture({ width, render: () => }) + +/** Billing's 90% level on the plans page: the strip warns under the bar. */ +export const currentPlanUsageWarning = defineFixture({ + width, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index dee2a120e06..65c1e3fb12d 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -15,6 +15,12 @@ import { PlanStatusBadge } from '../PlanStatusBadge' import type { PlanBillingNotice } from '../PlanBillingSection' import { seatCountLabel } from '../team/team-copy' import { formatHours, includedUsagePercent } from '../plan-billing-format' +import { + includedUsageTone, + sandboxHoursCount, + sandboxHoursLeftLine, + usageWarningLine +} from '../plan-billing-usage-copy' import { EnterprisePlanCard } from './EnterprisePlanCard' import { PlansIntervalToggle } from './PlansIntervalToggle' import { TeamPlanCard, type TeamPlanCardMode } from './TeamPlanCard' @@ -56,8 +62,8 @@ function ValueProps(): React.JSX.Element { icon: Zap, title: t('auto.components.billing.plans.vpWakeTitle', 'Wake in seconds'), body: t( - 'auto.components.billing.plans.vpWakeBody2', - 'Idle sandboxes sleep to save hours and wake with your files as you left them.' + 'auto.components.billing.plans.vpWakeBody3', + 'Idle sandboxes sleep to save sandbox hours and wake with your files as you left them.' ) }, { @@ -96,6 +102,7 @@ function CurrentPlanStrip({ const resets = entitlement.usageWindow ? new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(entitlement.usageWindow.end) : null + const warning = usageWarningLine(entitlement, t) return (
@@ -113,7 +120,7 @@ function CurrentPlanStrip({
= 100 ? 'warning' : 'default'} + tone={includedUsageTone(entitlement)} aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} />
@@ -130,16 +137,18 @@ function CurrentPlanStrip({ {resets ? t( - 'auto.components.billing.plans.leftResets', - '{{value0}} hours left · resets {{value1}}', + 'auto.components.billing.plans.sandboxHoursLeftResets', + '{{count}} sandbox hours left · resets {{date}}', { - value0: formatHours(entitlement.remainingIncludedSeconds), - value1: resets + count: sandboxHoursCount(entitlement.remainingIncludedSeconds), + date: resets, + defaultValue_one: '{{count}} sandbox hour left · resets {{date}}' } ) - : null} + : sandboxHoursLeftLine(entitlement, t)}
+ {warning ?

{warning}

: null}
) } @@ -226,15 +235,16 @@ export function PlansView(props: PlansViewProps): React.JSX.Element { const seats = clampSeats(props.seats, ORCA_BILLING_MAX_SEATS) const result = props.result const ready = result?.status === 'ok' - // Once plans load (or after "Back to plans"), land on this state's primary action, but only if - // focus is still on the dialog or nowhere; never steal it from something the user picked. + // Once plans load (or after "Back to plans"), land on the dialog heading, never on a buy button + // (Enter would start Checkout): Tab then reaches the interval toggle before the cards. Only when + // focus is on the dialog or nowhere; never steal it from something the user picked. useEffect(() => { const active = document.activeElement if ( ready && (!active || active === document.body || active.getAttribute('role') === 'dialog') ) { - document.querySelector('[role="dialog"] [data-plans-primary]')?.focus() + document.querySelector('[role="dialog"] [data-plans-heading]')?.focus() } }, [ready]) diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index 5d91a56424c..b4cd0843ff7 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -7,7 +7,12 @@ import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaBillingInterval, OrcaBillingOffers } from '../../../../../shared/orca-billing' import { PlanCardShell } from './PlanCardShell' -import { formatCents, perSeatMonthlyCents, periodTotalCents } from './plans-pricing' +import { + formatCents, + formatRateCents, + perSeatMonthlyCents, + periodTotalCents +} from './plans-pricing' import { ORCA_CLOUD_SANDBOX_SPEC } from '../../../../../shared/hosted-sandbox/hosted-sandbox-wire' export type TeamPlanCardMode = 'choose' | 'current' | 'locked' @@ -65,11 +70,11 @@ export function TeamPlanCard({ ), t('auto.components.billing.plans.featureReady', 'Ready in seconds, nothing to set up or host'), t( - 'auto.components.billing.plans.featureOverage5', - 'Optional overage at {{value0}}/hour, up to a monthly spend cap you set ({{value1}} by default)', + 'auto.components.billing.plans.featureOverage6', + 'Optional overage at {{rate}} per sandbox hour, up to a monthly spend cap you set ({{cap}} by default)', { - value0: formatCents(team.overageCentsPerHour, locale), - value1: formatCents(team.defaultSpendCapCents, locale) + rate: formatRateCents(team.overageCentsPerHour, locale), + cap: formatCents(team.defaultSpendCapCents, locale) } ) ] @@ -130,11 +135,11 @@ export function TeamPlanCard({ {total === null ? null : (

{interval === 'year' - ? t('auto.components.billing.plans.totalYear', '{{value0}} / year', { - value0: formatCents(total, locale) + ? t('auto.components.billing.plans.totalPerYear', '{{total}} per year', { + total: formatCents(total, locale) }) - : t('auto.components.billing.plans.totalMonth', '{{value0}} / month', { - value0: formatCents(total, locale) + : t('auto.components.billing.plans.totalPerMonth', '{{total}} per month', { + total: formatCents(total, locale) })}

)} @@ -150,7 +155,6 @@ export function TeamPlanCard({ className="w-full" aria-disabled={busy || undefined} onClick={busy ? undefined : onCheckout} - data-plans-primary="" > {busy ? : null} {busy @@ -187,7 +191,6 @@ export function TeamPlanCard({ className="w-full" aria-disabled={busy || undefined} onClick={busy ? undefined : onManage} - data-plans-primary="" > {t('auto.components.billing.manageBilling', 'Manage billing')} diff --git a/src/renderer/src/components/billing/plans/plans-pricing.test.ts b/src/renderer/src/components/billing/plans/plans-pricing.test.ts index 19dd7bb2c5b..047e7075978 100644 --- a/src/renderer/src/components/billing/plans/plans-pricing.test.ts +++ b/src/renderer/src/components/billing/plans/plans-pricing.test.ts @@ -4,6 +4,7 @@ import { annualSavingsPercent, clampSeats, formatCents, + formatRateCents, perSeatMonthlyCents, periodTotalCents } from './plans-pricing' @@ -38,6 +39,11 @@ describe('plans pricing', () => { expect(formatCents(144000, 'en-US')).toBe('$1,440') }) + it('always shows cents on a per-hour rate', () => { + expect(formatRateCents(100, 'en-US')).toBe('$1.00') + expect(formatRateCents(75, 'en-US')).toBe('$0.75') + }) + it('clamps seats to 1..max', () => { expect(clampSeats(0, 500)).toBe(1) expect(clampSeats(Number.NaN, 500)).toBe(1) diff --git a/src/renderer/src/components/billing/plans/plans-pricing.ts b/src/renderer/src/components/billing/plans/plans-pricing.ts index 5e94f0aac1b..1d83adea42b 100644 --- a/src/renderer/src/components/billing/plans/plans-pricing.ts +++ b/src/renderer/src/components/billing/plans/plans-pricing.ts @@ -46,6 +46,16 @@ export function formatCents(cents: number, locale: string): string { }).format(cents / 100) } +/** A per-hour rate always shows cents ("$1.00", "$0.75"), unlike whole-dollar prices. */ +export function formatRateCents(cents: number, locale: string): string { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2 + }).format(cents / 100) +} + export const MIN_SEATS = 1 export function clampSeats(value: number, max: number): number { diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index 5485dadf76d..d074ed1f666 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 { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' function TeamPageBody({ arrival }: { arrival: ReturnType['arrival'] }) { const t = useTranslate() @@ -34,10 +35,13 @@ function TeamPageBody({ arrival }: { arrival: ReturnType(null) const [now] = useState(() => Date.now()) + const refreshRoster = roster.refresh + const refreshBilling = billing.refresh + // Both refreshes are stable callbacks; depending on the hook results would rebuild this each render. const quietRefresh = useCallback(() => { - roster.refresh() - billing.refresh() - }, [roster, billing]) + refreshRoster() + refreshBilling() + }, [refreshRoster, refreshBilling]) const actions = useTeamActions({ orgId: orgId ?? '', onChanged: quietRefresh }) const rosterResult = @@ -199,7 +203,11 @@ function TeamPageBody({ arrival }: { arrival: ReturnType { closeTeamPage() - openModal('new-workspace-composer', { telemetrySource: 'unknown' }) + // The plan is for Orca Cloud, so the composer opens on it rather than this computer. + openModal('new-workspace-composer', { + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + telemetrySource: 'unknown' + }) }} onDismissArrival={clearTeamPageArrival} onContactSales={(url) => void window.api.shell.openUrl(url)} diff --git a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx index 7eb546947e2..9aca7ee62cc 100644 --- a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx +++ b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx @@ -77,8 +77,8 @@ function impactCopy( const price = formatCents(impact.perSeatPeriodCents, locale) const then = impact.interval === 'year' - ? t('auto.components.billing.team.perYear', '{{value0}}/year', { value0: price }) - : t('auto.components.billing.team.perMonth', '{{value0}}/month', { value0: price }) + ? t('auto.components.billing.team.totalPerYear', '{{total}} per year', { total: price }) + : t('auto.components.billing.team.totalPerMonth', '{{total}} per month', { total: price }) if (count === 1) { const first = candidates[0]!.email.split('@')[0] ?? candidates[0]!.email return t( diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx new file mode 100644 index 00000000000..57411710e07 --- /dev/null +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -0,0 +1,46 @@ +// @vitest-environment happy-dom +import { cleanup, render } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles' +import { TeamMemberList } from './TeamMemberList' +import { teamRows } from './team-roster-rows' + +afterEach(cleanup) + +const roster: OrcaOrgMembersRoster = { + viewerRole: 'owner', + canManageMembers: true, + members: [ + { userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' }, + { userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' } + ], + pendingInvites: [] +} + +const noop = (): void => {} + +it('marks a busy row with aria-busy and a spinner, without dimming it', () => { + const { container } = render( + + ) + const busy = container.querySelector('[data-team-row="member:u-grace"]')! + const idle = container.querySelector('[data-team-row="member:u-neil"]')! + expect(busy.getAttribute('aria-busy')).toBe('true') + expect(idle.hasAttribute('aria-busy')).toBe(false) + // Dimming dropped the email under AA; the row keeps full opacity. + expect(busy.className).not.toMatch(/opacity-/) + expect(busy.querySelector('.animate-spin')).not.toBeNull() + expect(idle.querySelector('.animate-spin')).toBeNull() +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index 4670e261dfa..b731209e6aa 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -18,7 +18,6 @@ import { } from '@/components/ui/select' import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles' import { PersonAvatar } from './TeamAvatar' import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy' @@ -226,10 +225,8 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { key={row.key} data-team-row={row.key} aria-busy={state.busy || undefined} - className={cn( - 'group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none', - state.busy && 'opacity-70' - )} + // Busy rows keep full contrast; the spinner and aria-busy say a change is pending. + className="group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none" >
diff --git a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx index 7b77ce5bb85..ecba2386576 100644 --- a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx +++ b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx @@ -246,9 +246,9 @@ export function TeamUpgradeCard({ 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop.' ) : t( - 'auto.components.billing.upgrade.body2', - 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{value0}}/seat/month.', - { value0: formatCents(monthly, locale) } + 'auto.components.billing.upgrade.body3', + 'Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{price}} per seat per month.', + { price: formatCents(monthly, locale) } )}

{entitlement.canManageBilling ? null : ( diff --git a/src/renderer/src/components/billing/use-orca-billing-status.test.tsx b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx new file mode 100644 index 00000000000..5bb5464963c --- /dev/null +++ b/src/renderer/src/components/billing/use-orca-billing-status.test.tsx @@ -0,0 +1,130 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' + +import { useAppStore } from '@/store' +import { getLastBillingStatus, resetBillingSummary } from './billing-summary-store' +import { sampleTeam } from './plan-billing-fixtures' +import { useOrcaBillingStatus } from './use-orca-billing-status' + +const teamA: OrcaBillingStatusResult = { status: 'ok', entitlement: { ...sampleTeam } } +const teamB: OrcaBillingStatusResult = { + status: 'ok', + entitlement: { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +} + +type Pending = { resolve: (result: OrcaBillingStatusResult) => void } +let pending: Pending[] = [] + +/** Signs in as `user-1` acting for `orgId`, as the auth status would after a team pick. */ +function setAccount(orgId: string): void { + useAppStore.setState({ + orcaProfileAuthStatus: { + activeProfileId: 'local-default', + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: { + cloudProfileId: 'cloud-1', + userId: 'user-1', + email: 'ada@example.com', + linkedAt: 0, + activeOrgId: orgId + } + } + }) +} + +beforeEach(() => { + setAccount('team-a') + pending = [] + resetBillingSummary() + vi.stubGlobal('api', { + orcaProfiles: { + billingStatus: vi.fn( + () => + new Promise((resolve) => { + pending.push({ resolve }) + }) + ) + } + }) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +/** What the auth subscriber does on a team switch: bump the generation, then re-render. */ +function switchTeam(rerender: () => void, next: string): void { + act(() => { + setAccount(next) + resetBillingSummary() + rerender() + }) +} + +describe('useOrcaBillingStatus on a team switch', () => { + it('drops the previous team plan and reads the new team', async () => { + const { result, rerender } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve(teamA)) + expect(result.current.result).toEqual(teamA) + + switchTeam(rerender, 'team-b') + expect(result.current).toMatchObject({ loading: true, result: null }) + expect(pending).toHaveLength(2) + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + expect(getLastBillingStatus()).toEqual(teamB) + }) + + it('never shows or records an answer that started before the switch', async () => { + const { result, rerender } = renderHook(() => useOrcaBillingStatus(true)) + expect(pending).toHaveLength(1) + + switchTeam(rerender, 'team-b') + await act(async () => pending[0].resolve(teamA)) + expect(result.current).toMatchObject({ loading: true, result: null }) + expect(getLastBillingStatus()).toBeNull() + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + }) + + it('re-reads when the generation moved while a read was in flight', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + // The account changed under the hook (e.g. reconnect) before its key re-rendered. + act(() => resetBillingSummary()) + await act(async () => pending[0].resolve(teamA)) + expect(result.current.result).toBeNull() + expect(getLastBillingStatus()).toBeNull() + expect(pending).toHaveLength(2) + + await act(async () => pending[1].resolve(teamB)) + expect(result.current).toMatchObject({ loading: false, result: teamB }) + }) +}) + +describe('useOrcaBillingStatus on a failed re-read', () => { + it('keeps the last good plan when a focus re-read fails', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve(teamA)) + + act(() => { + window.dispatchEvent(new Event('focus')) + }) + expect(pending).toHaveLength(2) + await act(async () => pending[1].resolve({ status: 'failed', error: 'offline' })) + + expect(result.current).toMatchObject({ loading: false, result: teamA }) + }) + + it('shows the failure when nothing was read yet', async () => { + const { result } = renderHook(() => useOrcaBillingStatus(true)) + await act(async () => pending[0].resolve({ status: 'failed', error: 'offline' })) + expect(result.current.result).toEqual({ status: 'failed', error: 'offline' }) + }) +}) diff --git a/src/renderer/src/components/billing/use-orca-billing-status.ts b/src/renderer/src/components/billing/use-orca-billing-status.ts index 41737882049..1c85b9baf1d 100644 --- a/src/renderer/src/components/billing/use-orca-billing-status.ts +++ b/src/renderer/src/components/billing/use-orca-billing-status.ts @@ -1,64 +1,49 @@ -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect } from 'react' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' -import { - getBillingGeneration, - getLastBillingStatus, - recordBillingStatusIfCurrent -} from './billing-summary-store' +import { refreshBillingStatus, useBillingState, watchBillingStatus } from './billing-summary-store' type BillingStatusState = { + /** True until the first answer for this account arrives, and while a read runs. */ loading: boolean result: OrcaBillingStatusResult | null } -function readBillingStatus(): Promise { - return window.api.orcaProfiles - .billingStatus() - .catch((error: unknown): OrcaBillingStatusResult => ({ - status: 'failed', - error: error instanceof Error ? error.message : String(error) - })) -} - /** - * Reads the billing status while `enabled`, again on `refresh()`, and whenever the window regains - * focus (the user comes back from Checkout or the Portal in their browser). + * The shared billing status while `enabled`: read on mount, again on `refresh()`, and whenever the + * window regains focus (the user comes back from Checkout or the Portal in their browser). A failed + * re-read keeps the last good answer. A team or account switch drops the previous team's status and + * reads the new one; an answer that started before the switch is never shown or recorded. */ export function useOrcaBillingStatus( enabled: boolean ): BillingStatusState & { refresh: () => void } { - const [state, setState] = useState(() => ({ - loading: enabled, - result: enabled ? getLastBillingStatus() : null - })) - const [reloadKey, setReloadKey] = useState(0) - const refresh = useCallback(() => setReloadKey((key) => key + 1), []) + const snapshot = useBillingState() + const accountKey = useOrcaAccountKey() + // Billing just changed in-app (or the user asked): a read that started earlier may be stale. + const refresh = useCallback(() => void refreshBillingStatus({ supersede: true }), []) useEffect(() => { if (!enabled) { return } - let disposed = false - let latest = 0 - const load = (): void => { - const request = ++latest - const startedGeneration = getBillingGeneration() - setState((previous) => ({ ...previous, loading: true })) - void readBillingStatus().then((result) => { - // A newer request, or unmounting, supersedes this one. - if (!disposed && request === latest) { - recordBillingStatusIfCurrent(startedGeneration, result) - setState({ loading: false, result }) - } - }) - } + const release = watchBillingStatus() + const load = (): void => void refreshBillingStatus() load() window.addEventListener('focus', load) return () => { - disposed = true + release() window.removeEventListener('focus', load) } - }, [enabled, reloadKey]) + }, [enabled, accountKey]) - return { ...state, refresh } + if (!enabled) { + return { loading: false, result: null, refresh } + } + return { + // No answer yet means one is on its way (the read starts after the first paint). + loading: snapshot.loading || snapshot.result === null, + result: snapshot.result, + refresh + } } diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx index 045af8c6965..5f4a7c54f99 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx @@ -55,6 +55,7 @@ function sheet( onCancel={noop} onRetry={noop} onDismiss={noop} + onReturnToComposer={noop} onEditRecipe={noop} cloudAgentStep={ @@ -89,10 +90,16 @@ export const buildSaved = sheet( { kind: 'saved', saved: { agents: ['claude'], scope: 'org' } } ) -export const buildReadyDesktopKey = sheet({ - readiness: { claude: 'desktop-key', codex: null }, - canShare: false -}) +const DESKTOP_KEYS = [ + { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' }, + { id: 'k2', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '9fZk' } +] as const + +/** This computer has Agent API Keys: the key form offers each one as a Cloud secret. */ +export const buildKeysWithDesktopKeys = sheet( + { readiness: NONE, canShare: false, desktopKeys: [...DESKTOP_KEYS] }, + { kind: 'keys' } +) export const buildReadyTeam = sheet({ readiness: { claude: 'team', codex: 'team' }, @@ -150,6 +157,8 @@ function dialog( canShare?: boolean failure?: CloudAgentSetupFailure pendingSave?: boolean + desktopKeys?: boolean + desktopKeyFailure?: boolean interact?: (frame: HTMLElement) => Promise } = {} ) { @@ -161,6 +170,8 @@ function dialog( readiness={options.readiness ?? NONE} canShare={options.canShare ?? false} steadyHeight + desktopKeys={options.desktopKeys ? [...DESKTOP_KEYS] : []} + onSaveDesktopKey={async () => (options.desktopKeyFailure ? 'unavailable' : null)} onSave={options.pendingSave ? () => new Promise(() => {}) : async () => null} onSaved={noop} onCancel={noop} @@ -177,6 +188,19 @@ export const dialogSubscription = dialog('sign-in', { readiness: { claude: 'team export const dialogApiKeyAdmin = dialog('api-key', { canShare: true }) +export const dialogDesktopKeys = dialog('api-key', { desktopKeys: true }) + +/** One key saved, the next one failed: each row keeps its own outcome. */ +export const dialogDesktopKeysSavedAndFailed = dialog('api-key', { + desktopKeys: true, + desktopKeyFailure: true, + interact: async (frame) => { + const buttons = frame.querySelectorAll('[aria-label^="Save "]') + buttons[1]?.click() + await settle() + } +}) + export const dialogApiKeySaving = dialog('api-key', { pendingSave: true, interact: async (frame) => { diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx index 8d9905fc846..3964bc609f0 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupDialog.tsx @@ -19,7 +19,7 @@ function DialogBody({ escapeGuardRef: React.Ref<() => boolean> }): React.JSX.Element { const t = useTranslate() - const { model, save } = useCloudAgentSetup({ repo: null }) + const { model, save, saveDesktopKey } = useCloudAgentSetup({ repo: null }) const [saved, setSaved] = useState(null) if (saved) { return @@ -38,6 +38,8 @@ function DialogBody({ const KEY_OPTIONS: readonly KeyOption[] = ['api-key', 'gateway', 'custom'] +const NO_DESKTOP_KEYS: readonly CloudOfferableDesktopKey[] = [] const EMPTY_DRAFTS: Record = { 'api-key': EMPTY_DRAFT, gateway: EMPTY_DRAFT, @@ -43,18 +47,16 @@ function agentStatusLine(readiness: CloudAgentReadiness, t: Translate): string { const state = source === 'team' ? t('cloudAgentSetup.status.team', 'provided by your team') - : source === 'desktop-key' - ? t('cloudAgentSetup.status.desktopKey', 'API key from Orca on this computer') - : source === 'cloud-secret' - ? t('cloudAgentSetup.status.cloudSecret', 'your cloud secret') - : t('cloudAgentSetup.status.none', 'not set up') + : source === 'cloud-secret' + ? t('cloudAgentSetup.status.cloudSecret', 'your cloud secret') + : t('cloudAgentSetup.status.none', 'not set up') return `${AGENT_NAME[agent]}: ${state}` }).join(' · ') } /** "Your team provides Claude and Codex access · …": one clause per source, agents grouped. */ export function cloudAgentReadinessSummary(readiness: CloudAgentReadiness, t: Translate): string { - const sources: CloudAgentCredentialSource[] = ['desktop-key', 'team', 'cloud-secret'] + const sources: CloudAgentCredentialSource[] = ['team', 'cloud-secret'] return sources .flatMap((source) => { const agents = CLOUD_SETUP_AGENTS.filter((agent) => readiness[agent] === source) @@ -66,16 +68,6 @@ export function cloudAgentReadinessSummary(readiness: CloudAgentReadiness, t: Tr ? t('cloudAgentSetup.source.both', 'Claude and Codex') : AGENT_NAME[agents[0]] switch (source) { - case 'desktop-key': - return [ - t( - 'cloudAgentSetup.source.desktopKey', - '{{agent}} uses the API key from Orca on this computer', - { - agent - } - ) - ] case 'team': return [ t('cloudAgentSetup.source.team', 'Your team provides {{agent}} access', { agent }) @@ -139,6 +131,9 @@ export type CloudAgentSetupViewProps = { * ask before a typed key is thrown away. */ escapeGuardRef?: React.Ref<() => boolean> + /** This computer's Agent API Keys no Cloud secret covers yet, each offered with its own Save. */ + desktopKeys?: readonly CloudOfferableDesktopKey[] + onSaveDesktopKey?: (key: CloudOfferableDesktopKey) => Promise /** Fixtures only. */ initialOption?: CloudAgentSetupOption initialFailure?: CloudAgentSetupFailure | null @@ -155,6 +150,8 @@ export function CloudAgentSetupView({ focusOnOpen = false, steadyHeight = false, escapeGuardRef, + desktopKeys = NO_DESKTOP_KEYS, + onSaveDesktopKey, initialOption, initialFailure = null }: CloudAgentSetupViewProps): React.JSX.Element { @@ -288,6 +285,9 @@ export function CloudAgentSetupView({ {summary}
) : null} + {onSaveDesktopKey ? ( + + ) : null} Promise +}): React.JSX.Element | null { + const t = useTranslate() + const [states, setStates] = useState>({}) + if (keys.length === 0) { + return null + } + const save = async (key: CloudOfferableDesktopKey): Promise => { + if (states[key.id]?.kind === 'saving') { + return + } + setStates((current) => ({ ...current, [key.id]: { kind: 'saving' } })) + const error = await onSave(key) + setStates((current) => ({ + ...current, + [key.id]: error ? { kind: 'failed', error } : { kind: 'saved' } + })) + } + return ( +
+

+ {t('cloudAgentSetup.desktopKeys.title', 'Keys on this computer')} +

+

+ {t( + 'cloudAgentSetup.desktopKeys.detail', + 'Cloud workspaces don’t get the API keys saved in Orca on this computer. Save one as a personal Cloud secret and the workspace only ever sees a stand-in for it.' + )} +

+
    + {keys.map((key) => { + const state = states[key.id] ?? { kind: 'idle' } + return ( +
  • +
    + + + {formatAgentTypeLabel(key.agent)}{' '} + {key.envName}{' '} + + ••••{key.hint} + + + {state.kind === 'saved' ? ( + + + {t('cloudAgentSetup.desktopKeys.saved', 'Saved as a Cloud secret')} + + ) : ( + + )} +
    + {state.kind === 'failed' ? ( + void save(key)} + /> + ) : null} +
  • + ) + })} +
+
+ ) +} diff --git a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx index a41c7655da9..a837d418ab7 100644 --- a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx +++ b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx @@ -12,7 +12,11 @@ import { HOST_AGENT_SIGN_IN_AGENTS } from '../../../../shared/host-agent-sign-in import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' import { cloudSecretRepoKey } from '../settings/cloud-secrets/cloud-secret-repos' -import { isCloudAgentReady, type CloudAgentReadiness } from './cloud-agent-readiness' +import { + isCloudAgentReady, + type CloudAgentReadiness, + type CloudOfferableDesktopKey +} from './cloud-agent-readiness' import { CloudAgentSetupView, cloudAgentReadinessSummary, @@ -25,6 +29,7 @@ import { useCloudAgentSetup } from './use-cloud-agent-setup' export type VmBuildCloudAgentStepModel = { readiness: CloudAgentReadiness canShare: boolean + desktopKeys?: readonly CloudOfferableDesktopKey[] } export type VmBuildCloudAgentStepMode = @@ -36,6 +41,7 @@ export type VmBuildCloudAgentStepMode = export type VmBuildCloudAgentStepActions = { onSave: CloudAgentSetupViewProps['onSave'] + onSaveDesktopKey?: CloudAgentSetupViewProps['onSaveDesktopKey'] /** The step is done (saved, signing in, or skipped); remember that it ran. */ onDone: () => void onSignIn: () => void @@ -265,6 +271,8 @@ export function VmBuildCloudAgentStepView({ setSignInRequested(true), onCancelSignIn: () => setSignInRequested(false), diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts index 9c4d977ae24..04645ea729e 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts @@ -1,28 +1,82 @@ import { describe, expect, it } from 'vitest' -import { deriveCloudAgentReadiness } from './cloud-agent-readiness' +import type { AgentApiKeySummary } from '../../../../shared/agent-api-keys/agent-api-key-catalog' +import { deriveCloudAgentReadiness, offerableDesktopKeys } from './cloud-agent-readiness' describe('deriveCloudAgentReadiness', () => { - it('prefers an every-host desktop key, then a team key, then the user’s own secret', () => { - expect( - deriveCloudAgentReadiness( - [{ agent: 'claude', hostScope: { kind: 'all' } }], - [{ name: 'OPENAI_API_KEY', scope: 'org' }] - ) - ).toEqual({ claude: 'desktop-key', codex: 'team' }) - expect( - deriveCloudAgentReadiness([], [{ name: 'AI_GATEWAY_API_KEY', scope: 'personal' }]) - ).toEqual({ claude: 'cloud-secret', codex: 'cloud-secret' }) + it('prefers a team key, then the user’s own secret; this computer’s keys never count', () => { + expect(deriveCloudAgentReadiness([{ name: 'OPENAI_API_KEY', scope: 'org' }])).toEqual({ + claude: null, + codex: 'team' + }) + expect(deriveCloudAgentReadiness([{ name: 'AI_GATEWAY_API_KEY', scope: 'personal' }])).toEqual({ + claude: 'cloud-secret', + codex: 'cloud-secret' + }) }) - it('ignores host-scoped desktop keys and variables that are not credentials', () => { + it('ignores variables that are not credentials', () => { expect( - deriveCloudAgentReadiness( - [{ agent: 'codex', hostScope: { kind: 'hosts', hostIds: ['ssh:devbox'] } }], - [ - { name: 'ANTHROPIC_MODEL', scope: 'org' }, - { name: 'DATABASE_URL', scope: 'repo' } - ] - ) + deriveCloudAgentReadiness([ + { name: 'ANTHROPIC_MODEL', scope: 'org' }, + { name: 'DATABASE_URL', scope: 'repo' } + ]) ).toEqual({ claude: null, codex: null }) }) }) + +describe('offerableDesktopKeys', () => { + const key = ( + id: string, + agent: 'claude' | 'gemini' | 'cursor', + envName: string, + all = true + ): Pick => ({ + id, + agent, + envName, + hint: id.slice(-4), + hostScope: all ? { kind: 'all' } : { kind: 'hosts', hostIds: ['ssh:devbox'] } + }) + + it('offers every-host keys whose variable no Cloud secret sets, once per variable', () => { + expect( + offerableDesktopKeys( + [ + key('k-0001', 'claude', 'ANTHROPIC_API_KEY'), + key('k-0002', 'gemini', 'GEMINI_API_KEY'), + key('k-0003', 'cursor', 'CURSOR_API_KEY', false), + key('k-0004', 'claude', 'GEMINI_API_KEY') + ], + [{ name: 'ANTHROPIC_API_KEY' }] + ) + ).toEqual([{ id: 'k-0002', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '0002' }]) + }) +}) + +describe('offerableDesktopKeys: only keys a workspace gets as a stand-in', () => { + it('never offers a key the proxy cannot swap (it would sit on the VM in full)', () => { + const all = { kind: 'all' } as const + expect( + offerableDesktopKeys( + [ + { + id: 'a', + agent: 'claude', + envName: 'AWS_BEARER_TOKEN_BEDROCK', + hint: 'aaaa', + hostScope: all + }, + { + id: 'b', + agent: 'opencode', + envName: 'OPENROUTER_API_KEY', + hint: 'bbbb', + hostScope: all + }, + { id: 'c', agent: 'cursor', envName: 'CURSOR_API_KEY', hint: 'cccc', hostScope: all } + ], + [] + ).map((key) => key.envName) + ).toEqual(['CURSOR_API_KEY']) + }) +}) diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts index 978222035f5..7f068de7b5f 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts @@ -1,11 +1,12 @@ import type { AgentApiKeySummary } from '../../../../shared/agent-api-keys/agent-api-key-catalog' +import { cloudSecretSwapped } from '../../../../shared/cloud-secrets/cloud-secret-rules' import type { CloudEffectiveSecret } from '../../../../shared/cloud-secrets/cloud-secrets-wire' export type CloudSetupAgent = 'claude' | 'codex' export const CLOUD_SETUP_AGENTS: readonly CloudSetupAgent[] = ['claude', 'codex'] /** Where an agent's credential comes from in a new cloud workspace, best first. */ -export type CloudAgentCredentialSource = 'desktop-key' | 'team' | 'cloud-secret' +export type CloudAgentCredentialSource = 'team' | 'cloud-secret' export type CloudAgentReadiness = Record @@ -23,17 +24,13 @@ const CREDENTIAL_NAMES: Record = { } /** - * Desktop keys for every host reach a brand-new VM at agent launch, so they win (zero clicks); host-scoped - * keys cannot name a VM that does not exist yet. Then a team-shared key, then the user's own cloud secret. + * A team-shared key, then the user's own cloud secret. This computer's Agent API Keys never reach a + * cloud VM (they would sit in it in plaintext); they are offered as Cloud secrets instead. */ export function deriveCloudAgentReadiness( - desktopKeys: readonly Pick[], effective: readonly Pick[] ): CloudAgentReadiness { const sourceFor = (agent: CloudSetupAgent): CloudAgentCredentialSource | null => { - if (desktopKeys.some((key) => key.agent === agent && key.hostScope.kind === 'all')) { - return 'desktop-key' - } const names = CREDENTIAL_NAMES[agent] const supplied = effective.filter((secret) => names.includes(secret.name)) if (supplied.some((secret) => secret.scope === 'org')) { @@ -44,6 +41,39 @@ export function deriveCloudAgentReadiness( return { claude: sourceFor('claude'), codex: sourceFor('codex') } } +/** A key on this computer a cloud workspace could use if the user saves it as a Cloud secret. */ +export type CloudOfferableDesktopKey = Pick + +/** + * This computer's keys for every host whose variable no Cloud secret sets yet (a key scoped to some + * hosts was never meant for a VM that does not exist yet). One entry per variable. + */ +export function offerableDesktopKeys( + desktopKeys: readonly Pick< + AgentApiKeySummary, + 'id' | 'agent' | 'envName' | 'hint' | 'hostScope' + >[], + effective: readonly Pick[] +): CloudOfferableDesktopKey[] { + const inCloud = new Set(effective.map((secret) => secret.name)) + const seen = new Set() + const offers: CloudOfferableDesktopKey[] = [] + for (const key of desktopKeys) { + // Only keys a workspace gets as a stand-in; anything else would sit on the VM in full. + if ( + key.hostScope.kind !== 'all' || + !cloudSecretSwapped(key.envName) || + inCloud.has(key.envName) || + seen.has(key.envName) + ) { + continue + } + seen.add(key.envName) + offers.push({ id: key.id, agent: key.agent, envName: key.envName, hint: key.hint }) + } + return offers +} + export function isCloudAgentReady(readiness: CloudAgentReadiness): boolean { return CLOUD_SETUP_AGENTS.some((agent) => readiness[agent] !== null) } diff --git a/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts b/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts index 34d4d0a7bac..bc856aac02c 100644 --- a/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts +++ b/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts @@ -3,7 +3,12 @@ import { cloudSecretsErrorCode, type CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire' -import { deriveCloudAgentReadiness, type CloudAgentReadiness } from './cloud-agent-readiness' +import { + deriveCloudAgentReadiness, + offerableDesktopKeys, + type CloudAgentReadiness, + type CloudOfferableDesktopKey +} from './cloud-agent-readiness' import { cloudAgentSetupProblem, cloudAgentSetupWrite, @@ -17,7 +22,13 @@ const NOT_CONFIGURED: CloudSecretsErrorCode = 'not_configured' export type CloudAgentSetupModel = | { status: 'loading' } - | { status: 'ready'; readiness: CloudAgentReadiness; canShare: boolean } + | { + status: 'ready' + readiness: CloudAgentReadiness + canShare: boolean + /** This computer's keys that no Cloud secret covers yet: offered, never sent unasked. */ + desktopKeys: CloudOfferableDesktopKey[] + } /** * What a new cloud workspace already has for agents (desktop keys, team and cloud secrets) and how to @@ -33,9 +44,12 @@ export function useCloudAgentSetup(args: { choice: CloudAgentSetupChoice, scope: CloudAgentSetupScope ) => Promise + saveDesktopKey: (key: CloudOfferableDesktopKey) => Promise } { const { repo, runtimeEnvironmentId = null, enabled = true } = args const [model, setModel] = useState({ status: 'loading' }) + // Bumped after a save so the model re-reads what the cloud now has. + const [generation, setGeneration] = useState(0) useEffect(() => { if (!enabled) { @@ -53,14 +67,16 @@ export function useCloudAgentSetup(args: { const view = cloud?.ok ? cloud.value : null setModel({ status: 'ready', - readiness: deriveCloudAgentReadiness(desktop?.keys ?? [], view?.secrets ?? []), - canShare: view?.caller.canWrite.org === true + readiness: deriveCloudAgentReadiness(view?.secrets ?? []), + canShare: view?.caller.canWrite.org === true, + // Without the cloud's answer nothing is offered: a save could shadow a key the team set. + desktopKeys: view ? offerableDesktopKeys(desktop?.keys ?? [], view.secrets) : [] }) }) return () => { cancelled = true } - }, [repo, enabled]) + }, [repo, enabled, generation]) const save = useCallback( async ( @@ -99,5 +115,29 @@ export function useCloudAgentSetup(args: { [runtimeEnvironmentId] ) - return { model, save } + const saveDesktopKey = useCallback( + async (key: CloudOfferableDesktopKey): Promise => { + const api = window.api.cloudSecrets + if (!api?.saveDesktopKey) { + return NOT_CONFIGURED + } + const result = await api + .saveDesktopKey({ agent: key.agent, envName: key.envName }) + .catch(() => null) + if (!result) { + return UNKNOWN + } + if (!result.ok) { + return result.error + } + if (runtimeEnvironmentId) { + void api.refreshEnv({ runtimeEnvironmentId }).catch(() => undefined) + } + setGeneration((value) => value + 1) + return null + }, + [runtimeEnvironmentId] + ) + + return { model, save, saveDesktopKey } } diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx index 90d57e271d7..80d1f85f836 100644 --- a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx +++ b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx @@ -27,7 +27,7 @@ type FailureCopy = { action: CloudRemoteDesktopNextAction | null /** Overrides the action's usual label (a failed wake retries the wake: "Try again"). */ actionLabel?: string - /** Asleep and starting are states, not errors. */ + /** Asleep, starting, signed out and not-available-here are states, not errors. */ tone?: 'neutral' } @@ -43,7 +43,8 @@ function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): Failur 'components.cloudRemoteDesktop.notCloudDetail', 'Create a cloud workspace to run apps with a screen.' ), - action: 'create_workspace' + action: 'create_workspace', + tone: 'neutral' } case 'not_running': return { @@ -95,7 +96,8 @@ function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): Failur 'components.cloudRemoteDesktop.notInstalledDetail', 'It was created before remote desktop was available. New cloud workspaces include it. Your files are safe.' ), - action: 'create_workspace' + action: 'create_workspace', + tone: 'neutral' } case 'signed_out': return { @@ -107,7 +109,8 @@ function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): Failur 'components.cloudRemoteDesktop.signedOutDetail', 'Sign in, then open the remote desktop again.' ), - action: 'sign_in' + action: 'sign_in', + tone: 'neutral' } case 'forward_failed': return { diff --git a/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx new file mode 100644 index 00000000000..36ac9eff10a --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudReadSnapshotSheet.tsx @@ -0,0 +1,70 @@ +// The team list's read-only view of an Asleep workspace: what it looked like when it went to +// sleep, read from the copy it sealed to this computer's key. Opening it never wakes the sandbox; +// "Wake to continue" runs the normal open flow. +import React, { useEffect, useRef, useState } from 'react' +import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { + CloudReadSnapshotView, + type CloudReadWake +} from '../orca-cloud/read-snapshot/CloudReadSnapshotView' +import { cloudWorkspaceTitle } from './open-cloud-workspace' +import { useCloudReadSnapshot } from './use-cloud-read-snapshot' + +export function CloudReadSnapshotSheet({ + workspace, + wake, + onWake, + onClose +}: { + /** Null keeps the sheet closed. */ + workspace: CloudWorkspace | null + wake: CloudReadWake | null + onWake: (w: CloudWorkspace) => void + onClose: () => void +}): React.JSX.Element { + const { state, retry, retrying } = useCloudReadSnapshot(workspace?.id ?? null) + const [now, setNow] = useState(() => Date.now()) + const headingRef = useRef(null) + useEffect(() => { + if (!workspace) { + return + } + setNow(Date.now()) + return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 30_000 }) + }, [workspace]) + const title = workspace ? cloudWorkspaceTitle(workspace) : '' + return ( + !open && onClose()}> + { + event.preventDefault() + headingRef.current?.focus() + }} + > + {/* The view's own heading is the visible title; Radix needs one for the dialog name. */} + {title} + {workspace ? ( + // The sheet owns its frame; this wrapper scrolls and pads (clear of the close button). +
+ onWake(workspace)} + onRetry={retry} + retrying={retrying} + headingRef={headingRef} + /> +
+ ) : null} +
+
+ ) +} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx index f2a64ecea27..ee915e435e5 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.fixture.tsx @@ -92,3 +92,26 @@ export const reassignAsAdmin = defineFixture({ /> ) }) + +/** Archiving a teammate's running workspace from the team list stops their agents (DS-01). */ +export const archiveTeammateRunning = defineFixture({ + width: 640, + render: () => + frame( + {}} + onConfirm={() => {}} + /> + ) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx index a5148df374d..ed37b4ff7ec 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceConfirmDialog.tsx @@ -1,5 +1,6 @@ -// Confirmation for the two row actions that take something away from people: making a shared -// workspace private (teammates' computers are disconnected) and handing ownership to someone else. +// Confirmation for row actions that take something away from people: making a shared workspace +// private (teammates' computers are disconnected), handing ownership to someone else, and archiving +// a teammate's running workspace (their agents stop). import React, { useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { @@ -18,6 +19,8 @@ import { cloudWorkspaceTitle } from './open-cloud-workspace' export type PendingConfirm = | { kind: 'private'; workspace: CloudWorkspace } | { kind: 'owner'; workspace: CloudWorkspace; ownerUserId: string } + /** Archiving a teammate's running workspace stops their agents. */ + | { kind: 'archive'; workspace: CloudWorkspace } /** Teammates who would lose access: here now, or holding an active device grant. */ function useConnectedTeammates(workspace: CloudWorkspace, selfId: string | null): string[] { @@ -100,10 +103,16 @@ export function CloudWorkspaceConfirmDialog({ ? t('auto.components.cloudWorkspaces.makePrivateTitle', 'Make {{title}} private?', { title: cloudWorkspaceTitle(w, t) }) - : t('auto.components.cloudWorkspaces.reassignTitle', 'Make {{name}} the owner?', { - name: memberName(directory, pending.ownerUserId, selfId, t) - }) + : pending.kind === 'archive' + ? t('auto.components.cloudWorkspaces.archiveConfirmTitle', 'Archive {{name}}?', { + name: cloudWorkspaceTitle(w, t) + }) + : t('auto.components.cloudWorkspaces.reassignTitle', 'Make {{name}} the owner?', { + name: memberName(directory, pending.ownerUserId, selfId, t) + }) const losesManagement = pending.kind === 'owner' && w.ownerUserId === selfId && !canAdmin + // Destructive for someone else (their agents stop, or you lose access): focus starts on Cancel. + const focusCancel = losesManagement || pending.kind === 'archive' return ( !next && onCancel()}> @@ -111,6 +120,14 @@ export function CloudWorkspaceConfirmDialog({ {title} {pending.kind === 'private' ? ( + ) : pending.kind === 'archive' ? ( + + {t( + 'auto.components.cloudWorkspaces.archiveConfirmBody', + "{{owner}}'s agents in this workspace will stop. Files are kept and it can be unarchived.", + { owner: memberName(directory, w.ownerUserId, selfId, t) } + )} + ) : ( {losesManagement @@ -127,13 +144,15 @@ export function CloudWorkspaceConfirmDialog({ {/* Giving away your own access starts on Cancel, so Enter cannot do it by accident. */} - - diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx index 19a4e7849f0..2475fb18c3e 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.fixture.tsx @@ -13,6 +13,7 @@ import { const WIDTH = 760 const ACTIONS: RowActions = { open: () => {}, + read: () => {}, copyLink: () => {}, copyWorkspaceLink: () => {}, goToChat: () => {}, diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index 5ff4cab6404..1677630ea69 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -11,7 +11,7 @@ import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-w import { CloudStateDot } from '../orca-cloud/CloudStateDot' import type { CloudDotState } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { MemberAvatar, PresenceStack } from './CloudMemberAvatars' -import { CloudWorkspaceRowMenu, type RowActions } from './CloudWorkspaceRowMenu' +import { CloudWorkspaceRowMenu, isReadableAsleep, type RowActions } from './CloudWorkspaceRowMenu' import { formatSandboxHours, formatRelative, @@ -111,6 +111,9 @@ export function CloudWorkspaceRow({ } }, [highlighted]) const canOpen = w.access !== 'none' + // Asleep: Enter / click reads the saved copy; waking is its own explicit action. + const readable = isReadableAsleep(w) + const primary = readable ? actions.read : actions.open // Hours are what the plan meters; a per-workspace dollar figure would overstate the bill. const hours = formatSandboxHours(w.cost.computeMs, intlLocale) const usage = t('auto.components.cloudWorkspaces.rowSandboxHours', '{{hours}} sandbox hours', { @@ -184,7 +187,7 @@ export function CloudWorkspaceRow({ )} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx index 756d4d776af..b5fa3c75bd0 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx @@ -3,11 +3,13 @@ import { Archive, ArchiveRestore, ArrowUpRight, + BookOpen, FolderInput, FolderPlus, Link2, Lock, MoreHorizontal, + Play, UserRoundCog, Users } from 'lucide-react' @@ -37,7 +39,10 @@ import { MemberAvatar } from './CloudMemberAvatars' import { memberName, presentMembers, type MemberDirectory } from './cloud-workspace-format' export type RowActions = { + /** Opens it, waking it first when it is asleep. */ open: (w: CloudWorkspace) => void + /** Asleep: the read-only copy it saved when it went to sleep (never wakes it). */ + read: (w: CloudWorkspace) => void /** The link to the chat you have in front when this workspace is in front, else the workspace. */ copyLink: (w: CloudWorkspace) => void copyWorkspaceLink: (w: CloudWorkspace) => void @@ -56,6 +61,15 @@ const NO_SECTION = '\u0000none' // Keeps submenus off the window edge when the row sits near the bottom of Home. const SUBMENU_COLLISION_PADDING = 8 +/** An Asleep workspace this account can open: its row reads the saved copy instead of waking. */ +export function isReadableAsleep(w: CloudWorkspace): boolean { + return ( + w.archivedAt === null && + w.access !== 'none' && + (w.status === 'suspended' || w.status === 'suspending') + ) +} + export function CloudWorkspaceRowMenu({ workspace: w, title, @@ -119,7 +133,20 @@ export function CloudWorkspaceRowMenu({ } }} > - {canOpen && ( + {canOpen && isReadableAsleep(w) && ( + <> + actions.read(w)}> + + {t('auto.components.cloudWorkspaces.viewAsleep', 'View read-only copy')} + ↵ + + actions.open(w)}> + + {t('components.orcaCloud.read.wakeToContinue', 'Wake to continue')} + + + )} + {canOpen && !isReadableAsleep(w) && ( actions.open(w)}> {t('auto.components.cloudWorkspaces.open', 'Open')} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx index 06bffc8fc40..065515832eb 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx @@ -6,6 +6,7 @@ import { teamWorkspaces, workspace } from './cloud-workspaces.test-fixture' +import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state' const WIDTH = 760 @@ -66,3 +67,123 @@ export const emptyTeam = defineFixture({ render: () => , interact: () => waitFor(() => document.querySelector('section p') !== null) }) + +const ASLEEP_ID = 'sbx_00000000000000000000a51e' + +function stubAsleep(answer: () => Promise): void { + const rows = [ + workspace({ + id: ASLEEP_ID, + title: 'Checkout retries', + status: 'suspended', + ownerUserId: 'user_grace', + createdBy: 'user_grace', + access: 'can_open' + }) + ] + stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) + Object.assign(window.api.cloudWorkspaces, { + readSnapshot: async () => ({ ok: true as const, value: await answer() }) + }) +} + +async function openAsleepRow(): Promise { + await waitFor(() => document.querySelector('[data-cloud-workspace-row] button') !== null) + document.querySelector('[data-cloud-workspace-row] button')?.click() + await waitFor( + () => + document.querySelector('[data-cloud-read-view]:not([data-cloud-read-view="loading"])') !== + null + ) +} + +/** Clicking a teammate's Asleep row opens its read-only copy in a sheet (no wake). */ +export const asleepReadView = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => + stubAsleep(async () => ({ + state: 'ready', + storedAt: Date.now() - 20 * 60_000, + snapshot: { + v: 1, + workspaceId: ASLEEP_ID, + snapshotId: 'snap_1', + capturedAt: Date.now() - 20 * 60_000, + reason: 'sleep', + pr: { + number: 412, + title: 'Retry checkout webhooks with backoff', + state: 'open', + url: 'https://github.com/acme/web/pull/412', + checksStatus: 'success', + checksSummary: '9/9 passed' + }, + git: { + branch: 'checkout-retries', + head: '3f95655', + changeCount: 1, + added: 88, + removed: 19, + changes: [ + { + path: 'src/payments/webhooks.ts', + status: 'modified', + area: 'unstaged', + added: 88, + removed: 19 + } + ], + commits: [] + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Retry failed checkout webhooks', + status: 'idle', + turnOutcome: 'done', + updatedAt: null, + truncated: false, + messages: [ + { itemId: 'm1', role: 'user', text: 'Retry failed webhooks with backoff.', at: 0 }, + { itemId: 'm2', role: 'assistant', text: 'Done. Tests pass.', at: 0 } + ] + } + ] + } + })), + render: () => , + interact: openAsleepRow +}) + +/** The snapshot predates this computer's reader key. */ +export const asleepNotSealedForKey = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubAsleep(async () => ({ state: 'not_sealed_for_key' })), + render: () => , + interact: openAsleepRow +}) + +/** Builds with Orca Cloud routines get a Routines entry next to the list they fill. */ +export const withRoutinesEntry = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => { + const rows = teamWorkspaces() + stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) + Object.assign(window.api, { + cloudApi: { + availability: async () => ({ status: 'ready', controlPlaneUrl: 'https://api.orca.dev' }) + } + }) + }, + render: () => , + interact: () => + waitFor( + () => + document.querySelector('[data-cloud-workspace-row]') !== null && + [...document.querySelectorAll('button')].some((b) => b.textContent === 'Routines') + ) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 2683d56f479..cb82ac23455 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -17,11 +17,13 @@ import { NEW_SECTION } from './CloudWorkspaceRowMenu' import { ANY, CloudWorkspacesToolbar, type CloudWorkspacesFilters } from './CloudWorkspacesToolbar' import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' +import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet' +import { useCloudReadPanel } from './use-cloud-read-panel' import { formatSandboxHours, sandboxHours, type MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' import { focusCloudChat } from './cloud-chat-focus' -import { archiveFromHome, unarchiveFromHome } from './cloud-workspace-home-archive' +import { homeArchiveActions, runHomeArchive } from './cloud-workspace-home-archive' import { frontCloudChat } from './cloud-workspace-links' import { cloudWorkspaceTitle, @@ -29,6 +31,7 @@ import { openCloudWorkspace } from './open-cloud-workspace' import { useCloudWorkspaces, useCloudWorkspacesAvailable } from './use-cloud-workspaces' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' const INITIAL_FILTERS: CloudWorkspacesFilters = { scope: 'team', @@ -81,16 +84,25 @@ export function CloudWorkspacesHome({ const available = useCloudWorkspacesAvailable() const orgId = cloud?.activeOrgId const selfId = cloud?.userId ?? null + const account = useOrcaAccountKey() const [filters, setFilters] = useState(INITIAL_FILTERS) + // 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_FILTERS) + } const [opening, setOpening] = useState(null) const [now, setNow] = useState(() => Date.now()) const [sectionFor, setSectionFor] = useState(null) const [confirm, setConfirm] = useState(null) + const { readingId, readingRef, setReadingId, readWake, setReadWake } = useCloudReadPanel() 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' }, - Boolean(cloud) + Boolean(cloud), + account ) // Relative "last active" times tick while the window is visible; hidden windows skip the work. @@ -166,19 +178,35 @@ export function CloudWorkspacesHome({ const totalMs = visible.reduce((sum, w) => sum + w.cost.computeMs, 0) /** Opens the workspace, then (going to a teammate's chat) the chat they have in front. */ - const open = useCallback(async (w: CloudWorkspace, chatId?: string | null) => { - setOpening(w.id) - try { - const outcome = await openCloudWorkspace(w) - if (!outcome.ok) { - toast.error(outcome.message) - } else if (chatId) { - await focusCloudChat(outcome.worktreeId, chatId) + const open = useCallback( + async (w: CloudWorkspace, chatId?: string | null) => { + setOpening(w.id) + const fromPanel = readingRef.current === w.id + if (fromPanel) { + setReadWake({ phase: 'waking', startedAt: Date.now() }) } - } finally { - setOpening((current) => (current === w.id ? null : current)) - } - }, []) + try { + const outcome = await openCloudWorkspace(w) + if (!outcome.ok) { + if (fromPanel && readingRef.current === w.id) { + // The panel shows the failure in place (with the reason) instead of a toast. + setReadWake({ phase: 'failed', message: outcome.message }) + } else { + toast.error(outcome.message) + } + return + } + // Woken from its read-only copy: the live workspace replaces it. + setReadingId((current) => (current === w.id ? null : current)) + if (chatId) { + await focusCloudChat(outcome.worktreeId, chatId) + } + } finally { + setOpening((current) => (current === w.id ? null : current)) + } + }, + [readingRef, setReadWake, setReadingId] + ) const patch = useCallback( async (w: CloudWorkspace, change: CloudWorkspacePatch, confirmed = false) => { @@ -227,6 +255,7 @@ export function CloudWorkspacesHome({ const actions = useMemo( () => ({ open: (w: CloudWorkspace) => void open(w), + read: (w: CloudWorkspace) => setReadingId(w.id), copyLink: (w: CloudWorkspace) => { const front = frontCloudChat() void copyCloudWorkspaceLink(w.id, front?.sandboxId === w.id ? front.chatId : null) @@ -234,12 +263,9 @@ export function CloudWorkspacesHome({ copyWorkspaceLink: (w: CloudWorkspace) => void copyCloudWorkspaceLink(w.id), goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId), patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change), - archive: (w: CloudWorkspace) => - void archiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh), - unarchive: (w: CloudWorkspace) => - void unarchiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh) + ...homeArchiveActions({ selfId, t, refresh, confirmArchive: setConfirm }) }), - [open, patch, refresh, t] + [open, patch, refresh, selfId, setReadingId, t] ) // Nothing (not even a skeleton) until we know this build has a control plane and you are in. @@ -364,6 +390,14 @@ export function CloudWorkspacesHome({ : null}
+ w.id === readingId) ?? null) : null} + wake={readWake} + onWake={(w) => void open(w)} + onClose={() => setReadingId(null)} + /> + {confirm && ( setConfirm(null)} onConfirm={() => { + if (confirm.kind === 'archive') { + setConfirm(null) + runHomeArchive(confirm.workspace, t, refresh) + return + } const change: CloudWorkspacePatch = confirm.kind === 'private' ? { visibility: 'private' } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx new file mode 100644 index 00000000000..866fc754bb3 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { ErrorState } from './CloudWorkspacesStates' + +afterEach(cleanup) + +it('shows an expired session as a neutral status with Sign in, not an alert with Retry', () => { + const onSignIn = vi.fn() + const onRetry = vi.fn() + render() + expect(screen.getByRole('status').textContent).toContain('Sign in to Orca again to continue.') + expect(screen.queryByRole('alert')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })) + expect(onSignIn).toHaveBeenCalledTimes(1) + expect(onRetry).not.toHaveBeenCalled() +}) + +it('keeps other failures as an alert with Retry', () => { + const onRetry = vi.fn() + render() + expect(screen.getByRole('alert')).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + expect(onRetry).toHaveBeenCalledTimes(1) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx index 6b03dee082e..017d87ffb54 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx @@ -12,6 +12,7 @@ import { InlineError } from '@/components/ui/inline-error' import { Input } from '@/components/ui/input' import { Skeleton } from '@/components/ui/skeleton' import { useTranslate } from '@/i18n/use-translate' +import { SignInAgainNotice } from '@/components/orca-cloud/SignInAgainButton' import { describeInlineError } from './cloud-workspace-errors' /** The list failed to load. An expired session offers Sign in; anything else offers Retry. */ @@ -29,18 +30,16 @@ export function ErrorState({ onSignIn: () => void }): React.JSX.Element { const t = useTranslate() - const signIn = error === 'unauthorized' + if (error === 'unauthorized') { + return + } return ( ) } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx index 27377f59967..605130b4307 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { Cloud, RefreshCw } from 'lucide-react' +import { CalendarClock, Cloud, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Select, @@ -10,12 +10,20 @@ import { } from '@/components/ui/select' import { Switch } from '@/components/ui/switch' import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsFormControls' +import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability' import { useTranslate } from '@/i18n/use-translate' +import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { repoLabel, type MemberDirectory } from './cloud-workspace-format' export const ANY = '__any' +function openRoutines(): void { + const state = useAppStore.getState() + state.openSettingsTarget({ pane: 'cloud-routines', repoId: null }) + state.openSettingsPage() +} + export type CloudWorkspacesFilters = { scope: 'team' | 'mine' by: string @@ -51,6 +59,8 @@ export function CloudWorkspacesToolbar({ onRefresh: () => void }): React.JSX.Element { const t = useTranslate() + // Routines start cloud workspaces on their own, so they sit next to the list they fill. + const routinesAvailable = useOrcaCloudApiAvailable() return (
@@ -68,7 +78,13 @@ export function CloudWorkspacesToolbar({ {meta} )} - + + {routinesAvailable ? ( + + ) : null}
) } + +const COLLAPSED_ITEMS = 3 + +/** The paths (or other names) an action touches: three, then the rest on request. */ +export function ConfirmationDialogItemList({ + list, + indented +}: { + list: NonNullable + /** Lines up under an option's label. */ + indented: boolean +}): React.JSX.Element { + const t = useTranslate() + const [expanded, setExpanded] = useState(false) + const shown = expanded ? list.items : list.items.slice(0, COLLAPSED_ITEMS) + const hidden = list.total - shown.length + return ( +
+
    + {shown.map((item) => ( +
  • + {item} +
  • + ))} +
+ {list.total > COLLAPSED_ITEMS ? ( + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/confirmation-dialog.test.tsx b/src/renderer/src/components/confirmation-dialog.test.tsx index 09e1c694f9c..c6545e5b89e 100644 --- a/src/renderer/src/components/confirmation-dialog.test.tsx +++ b/src/renderer/src/components/confirmation-dialog.test.tsx @@ -134,6 +134,21 @@ describe('ConfirmationDialogProvider', () => { await waitFor(() => expect(onSettled).toHaveBeenCalledWith(true)) }) + it('shows three listed items, then the rest on request', async () => { + renderDialog({ + title: 'Rewind to here?', + itemList: { label: 'Changed files', items: ['a', 'b', 'c', 'd', 'e'], total: 7 } + }) + await userEvent.click(screen.getByRole('button', { name: 'ask' })) + const list = await screen.findByRole('list', { name: 'Changed files' }) + expect(list.querySelectorAll('li')).toHaveLength(3) + await userEvent.click(screen.getByRole('button', { name: 'Show 4 more' })) + expect(list.querySelectorAll('li')).toHaveLength(5) + expect(screen.getByRole('button', { name: 'Show fewer' }).getAttribute('aria-expanded')).toBe( + 'true' + ) + }) + it('never saves the preference when the user backs out', async () => { const onConfirmed = vi.fn() const { onSettled } = renderDialog({ diff --git a/src/renderer/src/components/confirmation-dialog.tsx b/src/renderer/src/components/confirmation-dialog.tsx index 1404855494a..45d4fe4a146 100644 --- a/src/renderer/src/components/confirmation-dialog.tsx +++ b/src/renderer/src/components/confirmation-dialog.tsx @@ -20,7 +20,10 @@ import { import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { ConfirmationDialogOption } from '@/components/confirmation-dialog-option' +import { + ConfirmationDialogItemList, + ConfirmationDialogOption +} from '@/components/confirmation-dialog-option' type ConfirmationDialogRequest = { id: number @@ -197,6 +200,13 @@ export function ConfirmationDialogProvider({ onCheckedChange={setOptionChecked} /> ) : null} + {displayedRequest?.options.itemList ? ( + + ) : null} {displayedRequest?.options.fields ? (
{displayedRequest.options.fields.inputs.map((field) => ( diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx index a3092677604..26900727d1b 100644 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.tsx @@ -19,7 +19,7 @@ export function NativeChatRewindAction({ + ) +} + +/** + * An expired Orca session. It is a soft state (nothing failed or was lost), so it renders as a + * neutral status, not an alert, with the shared sentence and a Sign in action. + */ +export function SignInAgainNotice({ + onSignIn, + className +}: { + onSignIn: () => void + className?: string +}): React.JSX.Element { + const t = useTranslate() + return ( + } + /> + ) +} diff --git a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts index a96d8ed2fe5..702451e8949 100644 --- a/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts +++ b/src/renderer/src/components/orca-cloud/cloud-workspace-actions.ts @@ -6,6 +6,8 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { runSleepWorktree } from '@/components/sidebar/workspace-actions/sleep/sleep-worktree-flow' import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' +import { signInAgainToastAction } from '@/lib/orca-cloud/orca-sign-in-again-action' import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' import { activateWorktreeFromSidebar } from '@/lib/workspace/activation/sidebar-worktree-activation' import { @@ -37,6 +39,14 @@ function failureToast(title: string, result: CloudWorkspaceResult): void { }) return } + if (result.userMessage) { + toast.error(title, { description: result.userMessage }) + return + } + if (result.code === 'unauthorized') { + toast.error(title, { description: signInAgainMessage(), action: signInAgainToastAction() }) + return + } toast.error(title, { description: result.code === 'unavailable' @@ -44,9 +54,7 @@ function failureToast(title: string, result: CloudWorkspaceResult): void { 'orcaCloudWorkspace.error.unavailable', 'Orca Cloud isn’t reachable right now. Try again in a moment.' ) - : result.code === 'unauthorized' - ? translate('orcaCloudWorkspace.error.signIn', 'Sign in to Orca again, then try again.') - : translate('orcaCloudWorkspace.error.generic', 'Something went wrong. Try again.') + : translate('orcaCloudWorkspace.error.generic', 'Something went wrong. Try again.') }) } diff --git a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx index c81f83f95bb..652d8815bd7 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudOfflineChatPanel.tsx @@ -69,17 +69,19 @@ function QueuedPromptRow({ {prompt.text}
)} -
+
{prompt.state === 'sending' ? ( - + ) : null} {label} {prompt.error ? ` · ${prompt.error}` : ''} {prompt.state === 'queued' && !editing ? ( - // Quiet until the bubble is hovered or a control has focus. - + // Quiet until the bubble is hovered or a control has focus. Collapsed to no width while + // hidden so the caption sits flush right; still focusable (never display:none), and + // focusing a control expands it. + ))} diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx index be4b164e2dd..ceeecc4ad1a 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.fixture.tsx @@ -209,3 +209,44 @@ export const deliveryFailed = defineFixture({ /> ) }) + +/** Merged with the copy the workspace saved when it went to sleep: PR, line counts, "As of". */ +export const withCloudSnapshot = defineFixture({ + width: 900, + render: () => + frame( + ({ + ...change, + added: [120, 54, 8][index] ?? 0, + removed: [0, 37, 4][index] ?? 0 + })) + } + }} + queued={[]} + workspaceName="fix-auth-redirect" + now={NOW} + onWake={noop} + onQueue={yes} + onCancel={noop} + onEdit={yes} + /> + ) +}) diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx index bac1b590076..28d77c9b050 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { Moon, Play, SquareTerminal } from 'lucide-react' +import { Cloud, Play, SquareTerminal } from 'lucide-react' import type { CloudOfflineSnapshot, CloudQueuedPrompt @@ -7,9 +7,10 @@ import type { import { Button } from '@/components/ui/button' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { useTranslate } from '@/i18n/use-translate' -import { formatRelative } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { CloudGitChanges } from '../CloudGitChanges' import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' +import { asOfParts } from '../read-snapshot/cloud-read-snapshot-format' +import { CloudReadPrLink } from '../read-snapshot/CloudReadPrLink' import { ChatPanel } from './CloudOfflineChatPanel' export type CloudOfflineViewProps = { @@ -43,11 +44,12 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J const defaultTab = snapshot.chats.length > 0 ? 'chat' : snapshot.terminals.length > 0 ? 'terminals' : 'changes' const empty = snapshot.capturedAt === null - const stateLine = empty - ? t('orcaCloudWorkspace.asleep.noCopy', 'Asleep · nothing cached yet') - : t('orcaCloudWorkspace.asleep.copyFrom', 'Asleep · copy from {{when}}', { - when: formatRelative(snapshot.capturedAt!, now) - }) + const asOf = snapshot.capturedAt === null ? null : asOfParts(snapshot.capturedAt, now) + const stateLine = asOf + ? t('components.orcaCloud.read.asOf', 'Asleep · As of {{when}}', { when: asOf.relative }) + : t('orcaCloudWorkspace.asleep.noCopy', 'Asleep · nothing cached yet') + // Sections may come from the copy the workspace saved when it went to sleep (Orca Cloud). + const fromCloud = snapshot.source === 'cloud' || snapshot.source === 'mixed' return (
- {t('components.orcaCloud.offline.wake', 'Wake')} + {t('components.orcaCloud.read.wakeToContinue', 'Wake to continue')} } /> @@ -80,102 +85,110 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J )}

) : ( - - - - {t('components.orcaCloud.offline.tabChat', 'Chat')} - {snapshot.chats.length > 0 ? ( - {snapshot.chats.length} - ) : null} - - - {t('components.orcaCloud.offline.tabTerminals', 'Terminals')} - {snapshot.terminals.length > 0 ? ( - {snapshot.terminals.length} - ) : null} - - - {t('components.orcaCloud.offline.tabChanges', 'Changes')} - {changeCount > 0 ? ( - {changeCount} - ) : null} - - - - - - -
- {snapshot.terminals.length === 0 ? ( -

- {t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')} -

- ) : ( -
- {snapshot.terminals.map((terminal) => { - const title = terminal.title ?? terminal.handle - return ( -
-
-
-
+          {snapshot.pr ?  : null}
+          
+            
+              
+                {t('components.orcaCloud.offline.tabChat', 'Chat')}
+                {snapshot.chats.length > 0 ? (
+                  {snapshot.chats.length}
+                ) : null}
+              
+              
+                {t('components.orcaCloud.offline.tabTerminals', 'Terminals')}
+                {snapshot.terminals.length > 0 ? (
+                  {snapshot.terminals.length}
+                ) : null}
+              
+              
+                {t('components.orcaCloud.offline.tabChanges', 'Changes')}
+                {changeCount > 0 ? (
+                  {changeCount}
+                ) : null}
+              
+            
+            
+              
+            
+            
+              
+ {snapshot.terminals.length === 0 ? ( +

+ {t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')} +

+ ) : ( +
+ {snapshot.terminals.map((terminal) => { + const title = terminal.title ?? terminal.handle + return ( +
- {terminal.lines.join('\n')} -
-
- ) - })} -
- )} -
-
- -
- {snapshot.git ? ( - ({ - sha: commit.id, - subject: commit.subject, - at: commit.at - })) - }} - /> - ) : ( -

- {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} -

- )} -
-
-
+
+
+
+                            {terminal.lines.join('\n')}
+                          
+ + ) + })} +
+ )} +
+ + +
+ {snapshot.git ? ( + ({ + sha: commit.id, + subject: commit.subject, + at: commit.at + })) + }} + /> + ) : ( +

+ {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} +

+ )} +
+
+ + )} ) diff --git a/src/renderer/src/components/orca-cloud/offline/use-cloud-offline-data.ts b/src/renderer/src/components/orca-cloud/offline/use-cloud-offline-data.ts index cf8e064aeb7..be594958574 100644 --- a/src/renderer/src/components/orca-cloud/offline/use-cloud-offline-data.ts +++ b/src/renderer/src/components/orca-cloud/offline/use-cloud-offline-data.ts @@ -2,11 +2,16 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { CloudOfflineSnapshot, - CloudQueuedPrompt + CloudQueuedPrompt, + CloudWorkspaceOfflineApi } from '../../../../../shared/hosted-sandbox/cloud-workspace-offline-api' const ASLEEP_POLL_MS = 15_000 +function readBoth(api: CloudWorkspaceOfflineApi, workspaceId: string) { + return Promise.all([api.getSnapshot({ workspaceId }), api.listQueuedPrompts({ workspaceId })]) +} + /** * The asleep view's data: the client-side cached copy and the prompts queued to it. Reads only * while `enabled` (the workspace may be asleep); answers for another workspace are dropped, so a @@ -31,10 +36,14 @@ export function useCloudOfflineData( return } const asked = workspaceId - const [next, prompts] = await Promise.all([ - api.getSnapshot({ workspaceId: asked }), - api.listQueuedPrompts({ workspaceId: asked }) - ]) + let answers: Awaited> + try { + answers = await readBoth(api, asked) + } catch { + // A failed poll (main busy, window closing) keeps what is shown; the next beat retries. + return + } + const [next, prompts] = answers if (current.current !== asked) { return } diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx new file mode 100644 index 00000000000..553abc5d749 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadPrLink.tsx @@ -0,0 +1,56 @@ +import React from 'react' +import { CircleCheck, CircleDashed, CircleX, GitPullRequest, Minus } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { CloudOfflinePr } from '../../../../../shared/hosted-sandbox/cloud-workspace-offline-api' +import { + checksLabel, + checksTone, + prStateLabel, + type ChecksTone +} from './cloud-read-snapshot-format' + +const TONE: Record = { + success: { icon: CircleCheck, className: 'text-status-success' }, + failure: { icon: CircleX, className: 'text-destructive' }, + pending: { icon: CircleDashed, className: 'text-status-warning-text' }, + neutral: { icon: Minus, className: 'text-muted-foreground' } +} + +/** The workspace's pull request as of its last sleep: a link out plus its checks. */ +export function CloudReadPrLink({ pr }: { pr: CloudOfflinePr }): React.JSX.Element { + const t = useTranslate() + const tone = checksTone(pr.checksStatus) + const Icon = TONE[tone].icon + const checks = checksLabel(tone, t) + return ( + + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx new file mode 100644 index 00000000000..6b4d8b26204 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSessions.tsx @@ -0,0 +1,139 @@ +import React, { useId, useState } from 'react' +import { Bot, ChevronDown } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { + ReadSnapshotAgentStatus, + ReadSnapshotSession +} from '../../../../../shared/cloud-workspaces/read-snapshot' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' +import { agentStatusLabel } from './cloud-read-snapshot-format' + +/** The app's agent names ("Claude", "Codex"); an id it does not know is shown as sent. */ +function agentDisplayName(agent: string): string { + return getAgentCatalog().find((entry) => entry.id === agent)?.label ?? agent +} + +/** Messages shown before "Show more": enough to see where the agent left off. */ +const COLLAPSED_MESSAGES = 2 + +const STATUS_TONE: Record = { + working: 'text-foreground', + attention: 'text-status-warning-text', + idle: 'text-muted-foreground', + unknown: 'text-muted-foreground' +} + +function SessionCard({ session }: { session: ReadSnapshotSession }): React.JSX.Element { + const t = useTranslate() + const [expanded, setExpanded] = useState(false) + const listId = useId() + const hidden = Math.max(0, session.messages.length - COLLAPSED_MESSAGES) + const shown = expanded ? session.messages : session.messages.slice(-COLLAPSED_MESSAGES) + const title = + session.title ?? + session.messages.find((message) => message.role === 'user')?.text.slice(0, 80) ?? + t('components.orcaCloud.read.untitledChat', 'Untitled chat') + return ( +
  • +
    + + {title} + {session.agent ? ( + {agentDisplayName(session.agent)} + ) : null} + + {agentStatusLabel(session.status, session.turnOutcome, t)} + +
    + {session.messages.length === 0 ? ( +

    + {t('components.orcaCloud.read.noMessages', 'No messages were saved for this chat.')} +

    + ) : ( +
      + {shown.map((message) => ( +
    1. + + {message.role === 'user' + ? t('components.orcaCloud.read.roleUser', 'Person:') + : t('components.orcaCloud.read.roleAgent', 'Agent:')}{' '} + + {message.text} +
    2. + ))} +
    + )} + {hidden > 0 || session.truncated ? ( +
    + {hidden > 0 ? ( + + ) : null} + {session.truncated && (expanded || hidden === 0) ? ( + + {t( + 'components.orcaCloud.read.truncated', + 'Older messages are in the workspace. Wake it to read them.' + )} + + ) : null} +
    + ) : null} +
  • + ) +} + +/** Each agent chat as it was when the workspace went to sleep: agent, status and the tail. */ +export function CloudReadSessions({ + sessions +}: { + sessions: readonly ReadSnapshotSession[] +}): React.JSX.Element { + const t = useTranslate() + if (sessions.length === 0) { + return ( +

    + {t('components.orcaCloud.read.noSessions', 'No agent chats were open.')} +

    + ) + } + return ( +
      + {sessions.map((session) => ( + + ))} +
    + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx new file mode 100644 index 00000000000..58f6305db38 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.fixture.tsx @@ -0,0 +1,210 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' +import { + CloudReadSnapshotView, + type CloudReadViewState, + type CloudReadWake +} from './CloudReadSnapshotView' + +const NOW = 1_794_230_000_000 +const MIN = 60_000 + +const snapshot: ReadSnapshot = { + v: 1, + workspaceId: 'sbx_00000000000000000000beef', + snapshotId: 'snap_1', + capturedAt: NOW - 42 * MIN, + reason: 'sleep', + pr: { + number: 412, + title: 'Retry checkout webhooks with backoff', + state: 'open', + url: 'https://github.com/acme/web/pull/412', + checksStatus: 'failure', + checksSummary: '1 of 9 failed' + }, + git: { + branch: 'checkout-retries', + head: '3f95655684912ab', + changeCount: 3, + added: 131, + removed: 22, + changes: [ + { + path: 'src/payments/webhooks.ts', + status: 'modified', + area: 'unstaged', + added: 88, + removed: 19 + }, + { + path: 'src/payments/backoff.ts', + status: 'added', + area: 'untracked', + added: 41, + removed: 0 + }, + { path: 'README.md', status: 'modified', area: 'staged', added: 2, removed: 3 } + ], + commits: [ + { + id: '3f956556849', + subject: 'Back off webhook retries', + author: 'Grace', + at: NOW - 70 * MIN + }, + { + id: '41b60ea4b10', + subject: 'Log webhook failures', + author: 'Grace', + at: NOW - 3 * 60 * MIN + } + ] + }, + sessions: [ + { + sessionId: 's1', + agent: 'claude', + title: 'Retry failed checkout webhooks', + status: 'attention', + turnOutcome: null, + updatedAt: NOW - 43 * MIN, + truncated: true, + messages: [ + { + itemId: 'm1', + role: 'user', + text: 'Retry failed checkout webhooks with exponential backoff.', + at: NOW - 80 * MIN + }, + { + itemId: 'm2', + role: 'assistant', + text: 'Added a backoff helper and wired it into the webhook handler.', + at: NOW - 60 * MIN + }, + { itemId: 'm3', role: 'user', text: 'Cap it at 5 attempts.', at: NOW - 50 * MIN }, + { + itemId: 'm4', + role: 'assistant', + text: 'Capped at 5 attempts. One e2e check fails on a timeout unrelated to this change. Should I re-run it or skip it for now?', + at: NOW - 43 * MIN + } + ] + }, + { + sessionId: 's2', + agent: 'codex', + title: 'Write tests for backoff', + status: 'idle', + turnOutcome: 'done', + updatedAt: NOW - 45 * MIN, + truncated: false, + messages: [ + { + itemId: 'n1', + role: 'user', + text: 'Write unit tests for the backoff helper.', + at: NOW - 55 * MIN + }, + { itemId: 'n2', role: 'assistant', text: 'Added 6 tests. All pass.', at: NOW - 45 * MIN } + ] + } + ] +} + +const noop = (): void => {} + +function view( + state: CloudReadViewState, + extra: { wake?: CloudReadWake; retrying?: boolean; linux?: boolean } = {} +) { + return ( +
    + +
    + ) +} + +const WIDTH = 620 + +/** Two agents (one needs input, one done), PR with failing checks, changes with +/−. */ +export const ready = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }) +}) + +/** "Show earlier messages" opened on the first chat. */ +export const readyExpanded = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }), + interact: (frame) => { + frame.querySelector('[aria-expanded="false"]')?.click() + } +}) + +/** A saved copy with no PR, agents or source control state. */ +export const readyBare = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot: { ...snapshot, pr: null, git: null, sessions: [] } }) +}) + +export const loading = defineFixture({ width: WIDTH, render: () => view({ kind: 'loading' }) }) + +export const empty = defineFixture({ width: WIDTH, render: () => view({ kind: 'no_snapshot' }) }) + +export const notSealedForKey = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'not_sealed_for_key' }) +}) + +export const notFound = defineFixture({ width: WIDTH, render: () => view({ kind: 'not_found' }) }) + +export const keychainUnavailable = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'unavailable', message: 'no keychain' }) +}) + +export const error = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'error', message: "Couldn't reach Orca Cloud. Your files are safe." }) +}) + +/** Keychain missing on Linux: also names the keyring to set up. */ +export const keychainUnavailableLinux = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'unavailable', message: 'no keychain' }, { linux: true }) +}) + +/** "Wake to continue" pressed 3 s ago: Waking dot, elapsed time on the busy button. */ +export const waking3s = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot }, { wake: { phase: 'waking', startedAt: Date.now() - 3_000 } }) +}) + +/** Past 10 s: the "Taking longer than usual" line under the header. */ +export const waking12s = defineFixture({ + width: WIDTH, + render: () => + view({ kind: 'ready', snapshot }, { wake: { phase: 'waking', startedAt: Date.now() - 12_000 } }) +}) + +/** The wake failed: shared "Couldn't wake" copy with Try again; the copy stays readable. */ +export const wakeFailed = defineFixture({ + width: WIDTH, + render: () => view({ kind: 'ready', snapshot }, { wake: { phase: 'failed' } }) +}) + +/** A rollback was refused. */ +export const stale = defineFixture({ width: WIDTH, render: () => view({ kind: 'stale' }) }) diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx new file mode 100644 index 00000000000..b4e5d8d0e6e --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx @@ -0,0 +1,274 @@ +import React from 'react' +import { Cloud, Loader2, Play } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { Skeleton } from '@/components/ui/skeleton' +import { formatElapsedTime } from '@/components/worktree-creation/worktree-creation-clock' +import { useNow } from '@/hooks/use-now' +import { useTranslate } from '@/i18n/use-translate' +import { isLinuxUserAgent } from '@/lib/user-agent-platform' +import { WAKE_SLOW_S } from '../CloudWakingOverlay' +import type { ReadSnapshot } from '../../../../../shared/cloud-workspaces/read-snapshot' +import { CloudGitChanges } from '../CloudGitChanges' +import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' +import { asOfParts } from './cloud-read-snapshot-format' +import { CloudReadPrLink } from './CloudReadPrLink' +import { CloudReadSessions } from './CloudReadSessions' + +export type CloudReadViewState = + | { kind: 'loading' } + | { kind: 'ready'; snapshot: ReadSnapshot } + | { kind: 'no_snapshot' } + | { kind: 'not_sealed_for_key' } + | { kind: 'not_found' } + /** Older than a copy already shown here (a rollback); refused. */ + | { kind: 'stale' } + /** This computer cannot hold a reader key (no OS keychain). */ + | { kind: 'unavailable'; message: string } + | { kind: 'error'; message: string } + +export type CloudReadSnapshotViewProps = { + title: string + state: CloudReadViewState + now: number + /** Wakes, then the normal open (and the live workspace replaces this view). */ + onWake: () => void + /** A wake started here: in flight since `startedAt`, or failed. */ + wake?: CloudReadWake | null + onRetry: () => void + retrying: boolean + headingRef?: React.Ref + /** Linux names the keyring to set up; defaults to this renderer's platform. */ + linux?: boolean +} + +export type CloudReadWake = + | { phase: 'waking'; startedAt: number } + /** `message`: why, when the open flow said (e.g. the team's running limit). */ + | { phase: 'failed'; message?: string } + +function LoadingBody(): React.JSX.Element { + const t = useTranslate() + return ( +
    + + {t('components.orcaCloud.read.loading', 'Loading the saved copy')} + + + {[0, 1].map((i) => ( +
    + + + +
    + ))} + +
    + ) +} + +function SectionHeading({ id, children }: { id: string; children: React.ReactNode }) { + return ( +

    + {children} +

    + ) +} + +function ReadyBody({ snapshot, now }: { snapshot: ReadSnapshot; now: number }) { + const t = useTranslate() + const git = snapshot.git + return ( +
    + {snapshot.pr ? : null} +
    + + {t('components.orcaCloud.read.agents', 'Agents')} + + +
    +
    + + {t('components.orcaCloud.read.changes', 'Changes')} + + {git ? ( + ({ + sha: commit.id, + subject: commit.subject, + at: commit.at + })) + }} + /> + ) : ( +

    + {t('components.orcaCloud.offline.noGit', 'No source control state was saved.')} +

    + )} +
    +
    + ) +} + +/** + * A sleeping workspace, read from the copy it saved when it went to sleep (sealed to this + * computer's reader key). Read-only; the only way forward is the explicit "Wake to continue". + */ +export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React.JSX.Element { + const t = useTranslate() + const { state, now } = props + const asOf = state.kind === 'ready' ? asOfParts(state.snapshot.capturedAt, now) : null + const waking = props.wake?.phase === 'waking' ? props.wake : null + const failed = props.wake?.phase === 'failed' ? props.wake : null + const clock = useNow(1_000, waking !== null) + const elapsedMs = waking ? Math.max(0, clock - waking.startedAt) : 0 + const slow = waking !== null && elapsedMs >= WAKE_SLOW_S * 1_000 + const lifecycle = waking + ? t('orcaCloudWorkspace.state.waking', 'Waking') + : t('components.orcaCloud.read.asleep', 'Asleep') + const linux = props.linux ?? isLinuxUserAgent() + return ( +
    + + {waking ? : } + {waking ? ( + + {t('components.orcaCloud.read.wakingElapsed', 'Waking… {{elapsed}}', { + elapsed: formatElapsedTime(elapsedMs) + })} + + ) : ( + t('components.orcaCloud.read.wakeToContinue', 'Wake to continue') + )} + + } + /> + {/* Announced once when the wake crosses the slow mark (the text changes only then). */} +

    + {slow + ? t( + 'orcaCloudWorkspace.overlay.slow', + 'Taking longer than usual. Your files and chats are safe.' + ) + : ''} +

    + {failed ? ( + + {t('orcaCloudWorkspace.overlay.failedDetail', 'Your files and chats are saved.')} + {failed.message ? {failed.message} : null} + + } + retryLabel={t('orcaCloudWorkspace.overlay.tryAgain', 'Try again')} + onRetry={props.onWake} + /> + ) : null} + {state.kind === 'loading' ? : null} + {state.kind === 'ready' ? : null} + {state.kind === 'no_snapshot' ? ( + + ) : null} + {state.kind === 'not_sealed_for_key' ? ( + + ) : null} + {state.kind === 'stale' ? ( + + ) : null} + {state.kind === 'not_found' ? ( + + ) : null} + {state.kind === 'unavailable' ? ( + + ) : null} + {state.kind === 'error' ? ( + + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts b/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts new file mode 100644 index 00000000000..47553294d27 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/read-snapshot/cloud-read-snapshot-format.ts @@ -0,0 +1,85 @@ +// Display helpers for a sleeping workspace's read-only copy (owner asleep view and team read view). +import { uiDateTimeFormat } from '@/i18n/ui-intl-formatters' +import type { Translate } from '@/i18n/use-translate' +import { formatRelative } from '@/lib/orca-cloud/orca-cloud-workspace-state' +import type { ReadSnapshotAgentStatus } from '../../../../../shared/cloud-workspaces/read-snapshot' + +// Intl formatter caches key on option identity, so this must be a module constant. +const ABSOLUTE: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short' } + +/** "As of" parts: relative for the label, absolute (glossary dateStyle medium) for hover. */ +export function asOfParts(at: number, now: number): { relative: string; absolute: string } { + return { relative: formatRelative(at, now), absolute: uiDateTimeFormat(ABSOLUTE).format(at) } +} + +export type ChecksTone = 'success' | 'failure' | 'pending' | 'neutral' + +/** Check states arrive as free text from the sandbox; anything unknown reads as neutral. */ +export function checksTone(status: string | null): ChecksTone { + switch ((status ?? '').toLowerCase()) { + case 'success': + case 'passed': + case 'passing': + return 'success' + case 'failure': + case 'failed': + case 'failing': + case 'error': + return 'failure' + case 'pending': + case 'running': + case 'in_progress': + case 'queued': + return 'pending' + default: + return 'neutral' + } +} + +export function checksLabel(tone: ChecksTone, t: Translate): string { + switch (tone) { + case 'success': + return t('components.orcaCloud.read.checksPassed', 'Checks passed') + case 'failure': + return t('components.orcaCloud.read.checksFailed', 'Checks failed') + case 'pending': + return t('components.orcaCloud.read.checksPending', 'Checks running') + case 'neutral': + return t('components.orcaCloud.read.checksNone', 'No checks') + } +} + +/** Where the agent was when the workspace went to sleep. */ +export function agentStatusLabel( + status: ReadSnapshotAgentStatus, + turnOutcome: string | null, + t: Translate +): string { + switch (status) { + case 'working': + return t('components.orcaCloud.read.agentWorking', 'Was working') + case 'attention': + return t('components.orcaCloud.read.agentAttention', 'Needs input') + case 'idle': + return turnOutcome + ? t('components.orcaCloud.read.agentDone', 'Done') + : t('components.orcaCloud.read.agentIdle', 'Idle') + case 'unknown': + return t('components.orcaCloud.read.agentUnknown', 'Status unknown') + } +} + +export function prStateLabel(state: string, t: Translate): string { + switch (state.toLowerCase()) { + case 'open': + return t('components.orcaCloud.read.prOpen', 'Open') + case 'draft': + return t('components.orcaCloud.read.prDraft', 'Draft') + case 'merged': + return t('components.orcaCloud.read.prMerged', 'Merged') + case 'closed': + return t('components.orcaCloud.read.prClosed', 'Closed') + default: + return state + } +} diff --git a/src/renderer/src/components/right-sidebar/PortsPanel.tsx b/src/renderer/src/components/right-sidebar/PortsPanel.tsx index f776316f708..ccc0d966e10 100644 --- a/src/renderer/src/components/right-sidebar/PortsPanel.tsx +++ b/src/renderer/src/components/right-sidebar/PortsPanel.tsx @@ -7,7 +7,11 @@ import { LocalWorkspacePortsPanel } from './local-workspace-ports-panel' import { SshPortsPanel } from './ssh-ports-panel' import { HostScopedPortsPanel } from './host-scoped-ports-panel' import { CloudSharedLinksSection } from './cloud-share/cloud-shared-links-section' -import { SharePortMenuItem, useSharePortAction } from './cloud-share/use-share-port-action' +import { + SharePortButton, + SharePortMenuItem, + useSharePortAction +} from './cloud-share/use-share-port-action' import type { WorkspacePort } from '../../../../shared/workspace-ports' import { getPortsPanelOwnerKey, @@ -38,6 +42,12 @@ export default function PortsPanel({ isVisible }: { isVisible: boolean }): React ), [shareAvailable, openShareDialog] ) + const sharePortActions = useCallback( + (port: WorkspacePort) => ( + + ), + [shareAvailable, openShareDialog] + ) const scopedHost = useMemo( () => host.kind === 'host-scoped' && workspaceId @@ -62,6 +72,7 @@ export default function PortsPanel({ isVisible }: { isVisible: boolean }): React runtimeTarget={host.target} sshForwardTargetId={sshForwardTargetId} portMenuItems={shareAvailable ? sharePortMenuItems : undefined} + portActions={shareAvailable ? sharePortActions : undefined} isSandbox={shareAvailable} footer={(activePorts) => (
    -
    -
    +
    + {/* Dim the icon and port only: the Expired / Turned off status keeps full muted contrast. */} +
    -
    +
    {showPort && ( :{share.port} )} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts b/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts index e7ba5f2fb51..fe319e47751 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-link-status.ts @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { getIntlLocale, translate } from '@/i18n/i18n' import { formatUiNarrowDuration, formatUiNarrowRelativeTime } from '@/i18n/relative-time-format' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { signInAgainMessage } from '@/lib/orca-cloud/orca-sign-in-again' import type { CloudShareFailureCode } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' export function shareErrorMessage(code: CloudShareFailureCode): string { @@ -17,10 +18,7 @@ export function shareErrorMessage(code: CloudShareFailureCode): string { 'That link is no longer active.' ) case 'unauthorized': - return translate( - 'auto.components.right.sidebar.CloudShare.errorUnauthorized', - 'Sign in to Orca again, then try again.' - ) + return signInAgainMessage() case 'invalid_request': return translate( 'auto.components.right.sidebar.CloudShare.errorInvalid', diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx b/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx index f6df5b7cc5e..62d1df888e3 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-links.fixture.tsx @@ -4,6 +4,7 @@ import type { WorkspacePort } from '../../../../../shared/workspace-ports' import { LocalPortRow } from '../local-port-row' import { SharedLinksList, type SharedLinksListProps } from './shared-links-list' import { SharePortDialog } from './share-port-dialog' +import { SharePortButton, SharePortMenuItem } from './use-share-port-action' const NOW = Date.UTC(2026, 10, 9, 12, 0, 0) const HOUR = 3_600_000 @@ -177,6 +178,58 @@ export const besidePorts = defineFixture({ ) }) +const shareAction = { available: true, openShareDialog: noop } +// Shows the focus-ring as keyboard focus would (Chromium honors focusVisible). +const FOCUS_VISIBLE: FocusOptions & { focusVisible: boolean } = { focusVisible: true } + +/** A cloud port row as keyboard users get it: Open in browser, Share…, Copy, Stop, More actions. */ +function CloudPortRow({ tall = false }: { tall?: boolean }) { + return ( +
    + } + forwardMenuItems={} + /> +
    + ) +} + +/** Tabbing onto the row: the focus-ring outline shows and the row buttons appear. */ +export const portRowFocused = defineFixture({ + width: 300, + render: () => , + interact: (frame) => { + frame.querySelector('[role="group"]')?.focus(FOCUS_VISIBLE) + } +}) + +/** Share… reached from the keyboard: the row's Share button focused. */ +export const portRowShareFocused = defineFixture({ + width: 300, + render: () => , + interact: (frame) => { + frame + .querySelector('button[aria-label="Share port 3000…"]') + ?.focus(FOCUS_VISIBLE) + } +}) + +/** "More actions for port 3000" opens the same menu as right-click, Share… included. */ +export const portRowMoreActions = defineFixture({ + width: 300, + render: () => , + interact: async (frame) => { + frame + .querySelector('button[aria-label="More actions for port 3000"]') + ?.click() + await new Promise((resolve) => setTimeout(resolve, 50)) + } +}) + function Dialog({ port, created, diff --git a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx index 0a7a38a8aa5..98ee124cf67 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/share-port-dialog.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useId, useRef, useState } from 'react' -import { Loader2 } from 'lucide-react' +import { Loader2, LogIn } from 'lucide-react' import { Button } from '@/components/ui/button' import { Dialog, @@ -11,6 +11,7 @@ import { } from '@/components/ui/dialog' import { InlineError } from '@/components/ui/inline-error' import { OrcaSignInButton } from '@/components/OrcaSignInProgress' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsSegmentedControl' import { Switch } from '@/components/ui/switch' import { useTranslate } from '@/i18n/use-translate' @@ -286,7 +287,19 @@ export function SharePortDialog({ aria-describedby={`${formId}-wake-hint`} />
    - {error && ( + {error?.signedOut ? ( + // An expired session is a soft state, not a failure: neutral, with Sign in. + + + {signInAgainActionLabel(t)} + + } + /> + ) : error ? ( - )} - {error?.signedOut && ( - - {t('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca')} - - )} + ) : null} {alreadyShared.length > 0 && (

    diff --git a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx index 0667d63a06b..ad4280af1a7 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/shared-links-list.tsx @@ -1,9 +1,10 @@ import React, { useId, useRef, useState } from 'react' -import { ChevronRight, Share2 } from 'lucide-react' +import { ChevronRight, LogIn, Share2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' import { OrcaSignInButton } from '@/components/OrcaSignInProgress' +import { signInAgainActionLabel } from '@/lib/orca-cloud/orca-sign-in-again' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import type { ShareLink } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' @@ -142,7 +143,7 @@ export function SharedLinksList({ retryLabel={ needsSignIn ? undefined - : t('auto.components.right.sidebar.CloudShare.retry', 'Retry') + : t('auto.components.right.sidebar.CloudShare.tryAgain', 'Try again') } onRetry={needsSignIn ? undefined : onRetry} retrying={retrying} @@ -151,7 +152,8 @@ export function SharedLinksList({ {status === 'error' && needsSignIn && (

    - {t('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca')} + + {signInAgainActionLabel(t)}
    )} diff --git a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx index f96f1f1dbc2..75b76ac39f4 100644 --- a/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx +++ b/src/renderer/src/components/right-sidebar/cloud-share/use-share-port-action.tsx @@ -1,7 +1,9 @@ import React, { useCallback, useState } from 'react' import { Share2 } from 'lucide-react' import { toast } from 'sonner' +import { Button } from '@/components/ui/button' import { ContextMenuItem } from '@/components/ui/context-menu' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { @@ -9,13 +11,13 @@ import { useCloudShares, type CloudSharesController } from '@/lib/cloud-shares/cloud-shares-store' -import { useAppStore } from '@/store' import { SHARE_RESERVED_PORTS, type CloudShareFailureCode, type ShareLink } from '../../../../../shared/hosted-sandbox/hosted-sandbox-share-wire' import { shareErrorMessage } from './share-link-status' +import { signInAgainToastAction } from '@/lib/orca-cloud/orca-sign-in-again-action' import { SharePortDialog } from './share-port-dialog' const MENU_ITEM_CLASS = @@ -28,12 +30,7 @@ function signInAction(code: CloudShareFailureCode): { if (code !== 'unauthorized') { return {} } - return { - action: { - label: translate('auto.components.right.sidebar.CloudShare.signIn', 'Sign in to Orca'), - onClick: () => void useAppStore.getState().connectCurrentOrcaProfile() - } - } + return { action: signInAgainToastAction() } } export type SharePortAction = { @@ -144,3 +141,41 @@ export function SharePortMenuItem({ ) } + +/** "Share…" as a port row hover/focus button, so sharing doesn't need a right-click. */ +export function SharePortButton({ + port, + action +}: { + port: number + action: Pick +}): React.JSX.Element | null { + const t = useTranslate() + if (!action.available || SHARE_RESERVED_PORTS.includes(port)) { + return null + } + return ( + + + + + + {t('auto.components.right.sidebar.CloudShare.menuShare', 'Share…')} + + + ) +} diff --git a/src/renderer/src/components/right-sidebar/local-port-row.test.tsx b/src/renderer/src/components/right-sidebar/local-port-row.test.tsx new file mode 100644 index 00000000000..355b2ad4468 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/local-port-row.test.tsx @@ -0,0 +1,72 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { WorkspacePort } from '../../../../shared/workspace-ports' +import { LocalPortRow } from './local-port-row' +import { SharePortButton, SharePortMenuItem } from './cloud-share/use-share-port-action' + +const port: WorkspacePort = { + id: '127.0.0.1:3000:4242', + bindHost: '127.0.0.1', + connectHost: '127.0.0.1', + port: 3000, + pid: 4242, + processName: 'vite', + protocol: 'http', + kind: 'workspace', + owner: { + worktreeId: 'repo::/workspace/app', + repoId: 'repo', + displayName: 'app', + path: '/workspace/app', + confidence: 'cwd' + } +} + +function renderRow(openShareDialog = vi.fn(), available = true) { + const action = { available, openShareDialog } + render( + } + forwardMenuItems={} + /> + ) + return openShareDialog +} + +afterEach(cleanup) + +describe('LocalPortRow keyboard actions', () => { + it('offers Open in browser, Share… and More actions as row buttons', () => { + const openShareDialog = renderRow() + expect(screen.getByRole('button', { name: 'Open in browser' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Share port 3000…' })) + expect(openShareDialog).toHaveBeenCalledWith(3000) + expect(screen.getByRole('button', { name: 'More actions for port 3000' })).toBeTruthy() + }) + + it('hides Share… when sharing is unavailable', () => { + renderRow(vi.fn(), false) + expect(screen.queryByRole('button', { name: 'Share port 3000…' })).toBeNull() + }) + + it('opens the row menu, Share… included, from the More actions button', async () => { + const openShareDialog = renderRow() + fireEvent.click(screen.getByRole('button', { name: 'More actions for port 3000' })) + const share = await screen.findByRole('menuitem', { name: 'Share…' }) + expect(screen.getByRole('menuitem', { name: 'Copy address' })).toBeTruthy() + fireEvent.click(share) + expect(openShareDialog).toHaveBeenCalledWith(3000) + }) + + it('keeps the focus-ring outline on the row group', () => { + renderRow() + const group = screen.getByRole('group', { name: 'Port 3000 menu' }) + expect(group.className).not.toContain('focus:outline-none') + expect(group.className).toContain('focus-visible:outline-focus-ring') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/local-port-row.tsx b/src/renderer/src/components/right-sidebar/local-port-row.tsx index 3377dd1ccd5..fc4d0efcd0d 100644 --- a/src/renderer/src/components/right-sidebar/local-port-row.tsx +++ b/src/renderer/src/components/right-sidebar/local-port-row.tsx @@ -1,5 +1,14 @@ -import React, { useCallback } from 'react' -import { Box, Copy, ExternalLink, Info, Server, Trash2 } from 'lucide-react' +import React, { useCallback, useRef } from 'react' +import { + Box, + ClipboardList, + Copy, + Ellipsis, + ExternalLink, + Info, + Server, + Trash2 +} from 'lucide-react' import { getPortOpenBrowserTooltipLabel } from '@/lib/workspace-ports/workspace-port-actions' import { addressForPort } from '@/lib/workspace-ports/workspace-port-urls' import { Button } from '@/components/ui/button' @@ -28,7 +37,7 @@ export function LocalPortRow({ onOpenInBrowser, forwardStatus, forwardMenuItems, - forwardActions, + shareAction, copyAddress }: { port: WorkspacePort @@ -39,12 +48,13 @@ export function LocalPortRow({ /** A remote host's port: where it is forwarded on this computer, or how to forward it. */ forwardStatus?: React.ReactNode forwardMenuItems?: React.ReactNode - /** Hover actions for the forward (Stop Forwarding), next to Open/Copy. */ - forwardActions?: React.ReactNode + /** Orca Cloud: a "Share…" hover button after Open (the same action as the menu's Share…). */ + shareAction?: React.ReactNode /** Overrides the copied address, e.g. with the forwarded localhost one. */ copyAddress?: string }): React.JSX.Element { const t = useTranslate() + const menuTriggerRef = useRef(null) const handleCopy = useCallback(() => { void window.api.ui.writeClipboardText(copyAddress ?? addressForPort(port)) }, [copyAddress, port]) @@ -56,16 +66,6 @@ export function LocalPortRow({ [onOpenInBrowser, port] ) - const handleCopyButtonClick = useCallback( - (event: React.MouseEvent) => { - handleCopy() - if (event.detail > 0) { - event.currentTarget.blur() - } - }, - [handleCopy] - ) - const handleOpenBrowserButtonClick = useCallback( (event: React.MouseEvent) => { // Keyboard clicks have detail=0; only pointer clicks carry the system-browser modifier intent. @@ -77,15 +77,19 @@ export function LocalPortRow({ [handleOpenBrowser] ) - const handleStopButtonClick = useCallback( - (event: React.MouseEvent) => { - onStop(port) - if (event.detail > 0) { - event.currentTarget.blur() - } - }, - [onStop, port] - ) + // The row menu is a context menu; this opens it under the button so keyboard and trackpad users reach Share… and the rest. + const handleMoreActionsClick = useCallback((event: React.MouseEvent) => { + const rect = event.currentTarget.getBoundingClientRect() + menuTriggerRef.current?.dispatchEvent( + new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + button: 2, + clientX: rect.left, + clientY: rect.bottom + }) + ) + }, []) const processLabel = port.processName ?? @@ -103,9 +107,15 @@ export function LocalPortRow({ ) : t('auto.components.right.sidebar.PortsPanel.unassigned', 'Unassigned') const openBrowserLabel = t( - 'auto.components.right.sidebar.PortsPanel.b22b128b2a', - 'Open in Browser' + 'auto.components.right.sidebar.PortsPanel.openInBrowser', + 'Open in browser' ) + const moreActionsLabel = t( + 'auto.components.right.sidebar.PortsPanel.moreActionsForPort', + 'More actions for port {{port}}', + { port: port.port } + ) + const stopProcessLabel = t('auto.components.right.sidebar.PortsPanel.stopProcess', 'Stop process') const canStopProcess = port.kind === 'workspace' && Boolean(port.pid) && port.processName !== 'Electron' @@ -114,7 +124,8 @@ export function LocalPortRow({
    - {forwardActions} {onOpenInBrowser && ( @@ -168,6 +178,7 @@ export function LocalPortRow({ )} + {shareAction} - {t('auto.components.right.sidebar.PortsPanel.1004af16ab', 'Copy {{value0}}', { - value0: address - })} + {moreActionsLabel} - {canStopProcess && ( - - - - - - {t('auto.components.right.sidebar.PortsPanel.f9528da632', 'Stop Process')} - - - )}
    @@ -231,7 +215,7 @@ export function LocalPortRow({ )} - {t('auto.components.right.sidebar.PortsPanel.792baeb7ed', 'Copy Address')} + {t('auto.components.right.sidebar.PortsPanel.copyAddress', 'Copy address')} {forwardMenuItems} - - {t('auto.components.right.sidebar.PortsPanel.bdac206faf', 'Copy Details')} + + {t('auto.components.right.sidebar.PortsPanel.copyDetails', 'Copy details')} onShowDetails(port)} > - {t('auto.components.right.sidebar.PortsPanel.a223459512', 'Show Details')} + {t('auto.components.right.sidebar.PortsPanel.showDetails', 'Show details')} onStop(port)} > - {t('auto.components.right.sidebar.PortsPanel.f9528da632', 'Stop Process')} + {stopProcessLabel} diff --git a/src/renderer/src/components/right-sidebar/local-port-section.tsx b/src/renderer/src/components/right-sidebar/local-port-section.tsx index fcc1551dd16..45c2fb9dd6d 100644 --- a/src/renderer/src/components/right-sidebar/local-port-section.tsx +++ b/src/renderer/src/components/right-sidebar/local-port-section.tsx @@ -7,7 +7,8 @@ import { LocalPortRow } from './local-port-row' export type PortRowForwarding = { status: (port: WorkspacePort) => React.ReactNode menuItems: (port: WorkspacePort) => React.ReactNode - actions: (port: WorkspacePort) => React.ReactNode + /** Host row buttons after Open (Orca Cloud: Share…). */ + hostActions?: (port: WorkspacePort) => React.ReactNode copyAddress: (port: WorkspacePort) => string | undefined } @@ -71,7 +72,7 @@ export function LocalPortSection({ onOpenInBrowser={onOpenInBrowser} forwardStatus={forwarding?.status(port)} forwardMenuItems={forwarding?.menuItems(port)} - forwardActions={forwarding?.actions(port)} + shareAction={forwarding?.hostActions?.(port)} copyAddress={forwarding?.copyAddress(port)} /> )) diff --git a/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx b/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx index 27c04d9f65d..e3c0d5b3247 100644 --- a/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx +++ b/src/renderer/src/components/right-sidebar/local-workspace-ports-panel.tsx @@ -36,6 +36,7 @@ export function LocalWorkspacePortsPanel({ runtimeTarget, sshForwardTargetId = null, portMenuItems, + portActions, footer, isSandbox = false }: { @@ -46,6 +47,8 @@ export function LocalWorkspacePortsPanel({ sshForwardTargetId?: string | null /** Extra row actions for this host's ports (Orca Cloud: Share…); rides the forwarding menu. */ portMenuItems?: (port: WorkspacePort) => React.ReactNode + /** The same host actions as hover/focus row buttons (Orca Cloud: Share…), after Open. */ + portActions?: (port: WorkspacePort) => React.ReactNode /** Host-specific sections below the ports (Orca Cloud: shared links), given the listening ports. */ footer?: (activePorts: readonly WorkspacePort[]) => React.ReactNode /** An Orca Cloud sandbox: copy says "sandbox" and offers Wake. */ @@ -69,7 +72,12 @@ export function LocalWorkspacePortsPanel({ }) const scanKey = runtimeTarget ? `${workspacePortRuntimeTargetKey(runtimeTarget)}:all` : null - const runtimeForwarding = useRuntimePortRowForwarding(runtimeTarget, portMenuItems, isSandbox) + const runtimeForwarding = useRuntimePortRowForwarding( + runtimeTarget, + portMenuItems, + isSandbox, + portActions + ) const refresh = useCallback(() => { if (!activeRepoId || !runtimeTarget || !scanKey) { diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx index b3f0505276c..0d6702e63a8 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx @@ -58,7 +58,7 @@ const states: Record = { 5173: { kind: 'forwarded', forward: forward(5173) }, 3000: { kind: 'forwarded', forward: forward(3000, { localPort: 3001, reason: 'user' }) }, 8080: { kind: 'pending' }, - 4000: { kind: 'failed', message: 'localhost:4000 in use', busy: true }, + 4000: { kind: 'failed', message: 'localhost:4000 in use on this computer', busy: true }, 9000: { kind: 'failed', message: 'Host not reachable', busy: false }, 9229: { kind: 'unforwarded' } } @@ -90,7 +90,6 @@ function Panel({ empty = false }: { empty?: boolean }): React.JSX.Element { /> ), menuItems: () => null, - actions: () => null, copyAddress: (row) => { const state = states[row.port] return state?.kind === 'forwarded' ? `localhost:${state.forward.localPort}` : undefined diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx index beef4ebd57f..70f12be64bf 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx @@ -1,8 +1,7 @@ import React from 'react' -import { ArrowRight, LoaderCircle, Plug, RotateCw, TriangleAlert, Unplug } from 'lucide-react' +import { ArrowRight, LoaderCircle, Plug, RotateCw, TriangleAlert } from 'lucide-react' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' import type { RuntimePortForward } from '../../../../shared/runtime-port-forwards' @@ -134,7 +133,7 @@ export function RuntimePortForwardStatus({ } : { icon: , - label: t('auto.components.right.sidebar.RuntimePortForward.retry', 'Retry') + label: t('auto.components.right.sidebar.RuntimePortForward.tryAgain', 'Try again') } : { icon: , @@ -169,38 +168,3 @@ export function RuntimePortForwardStatus({ ) } - -/** Stop forwarding as a row hover action, beside Open and Copy. */ -export function RuntimePortForwardStopButton({ - remotePort, - onStop -}: { - remotePort: number - onStop: () => void -}): React.JSX.Element { - const t = useTranslate() - const label = t( - 'auto.components.right.sidebar.RuntimeForwardedPorts.stopLabel', - 'Stop forwarding port {{value0}}', - { value0: remotePort } - ) - return ( - - - - - - {t('auto.components.right.sidebar.RuntimePortForward.stopForwarding', 'Stop forwarding')} - - - ) -} diff --git a/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx b/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx index e8c3a8b26d3..0a3260b33f0 100644 --- a/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx +++ b/src/renderer/src/components/right-sidebar/ssh-forwarded-port-row.tsx @@ -88,8 +88,8 @@ export function SshForwardedPortRow({ const advertisedBrowserUrl = advertisedBrowserUrlForForwardedRow(entry) const openBrowserLabel = t( - 'auto.components.right.sidebar.PortsPanel.b22b128b2a', - 'Open in Browser' + 'auto.components.right.sidebar.PortsPanel.openInBrowser', + 'Open in browser' ) const openBrowserTitle = getPortOpenBrowserTooltipLabel( advertisedBrowserUrl diff --git a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx index 1bffd0d3471..b452a1b1a54 100644 --- a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx +++ b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx @@ -21,7 +21,6 @@ import type { WorkspacePort } from '../../../../shared/workspace-ports' import type { PortRowForwarding } from './local-port-section' import { RuntimePortForwardStatus, - RuntimePortForwardStopButton, type RuntimePortForwardRowState } from './runtime-port-forward-status' @@ -57,7 +56,9 @@ export function useRuntimePortRowForwarding( /** Host actions after the forward items (Orca Cloud: Share…). */ extraMenuItems?: (port: WorkspacePort) => ReactNode, /** Orca Cloud: copy says "sandbox", and offline offers Wake. */ - isSandbox = false + isSandbox = false, + /** Host row buttons after Open (Orca Cloud: Share…). */ + extraActions?: (port: WorkspacePort) => ReactNode ): RuntimePortRowForwarding | null { const t = useTranslate() const environmentId = runtimeTarget?.kind === 'environment' ? runtimeTarget.environmentId : null @@ -138,15 +139,6 @@ export function useRuntimePortRowForwarding( } /> ), - actions: (port) => { - const existing = forwardFor(port) - return existing ? ( - void closeRuntimePortForward(existing)} - /> - ) : null - }, menuItems: (port) => { const existing = forwardFor(port) const forwardItems = existing ? ( @@ -197,6 +189,7 @@ export function useRuntimePortRowForwarding( ) }, + hostActions: extraActions, copyAddress: (port) => { const existing = forwardFor(port) return existing ? `localhost:${existing.localPort}` : undefined @@ -204,6 +197,7 @@ export function useRuntimePortRowForwarding( } }, [ environmentId, + extraActions, extraMenuItems, failures, forward, diff --git a/src/renderer/src/components/run-actions/RunActionButton.tsx b/src/renderer/src/components/run-actions/RunActionButton.tsx index 9cfe1f9a49f..e803e5c5e41 100644 --- a/src/renderer/src/components/run-actions/RunActionButton.tsx +++ b/src/renderer/src/components/run-actions/RunActionButton.tsx @@ -13,6 +13,7 @@ import { startRunAction, stopRunAction } from '@/lib/run-actions/run-action-cont import { useWorktreeRunActionRuns, type RunActionRun } from '@/lib/run-actions/run-actions-store' import type { WorkspacePort } from '../../../../shared/workspace-ports' import { RunActionButtonView } from './RunActionButtonView' +import { findLiveRunTabId } from '@/lib/run-actions/run-action-tabs' const EMPTY_PORTS: WorkspacePort[] = [] @@ -57,7 +58,7 @@ function useWorktreePorts(worktreeId: string): WorkspacePort[] { function focusRunTab(run: RunActionRun): void { const state = useAppStore.getState() state.setActiveTabType('terminal', run.worktreeId) - state.setActiveTab(run.tabId) + state.setActiveTab(findLiveRunTabId(state, run.worktreeId, run.tabId) ?? run.tabId) } function openPortsPanel(): void { diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx new file mode 100644 index 00000000000..3c5a6bc38fe --- /dev/null +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx @@ -0,0 +1,33 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import type { OrcaProfileAuthStatus } from '../../../../../../shared/orca-profiles' +import { OrcaAccountSettingsPane } from './OrcaAccountSettingsPane' + +const width = 760 + +function pane(status: OrcaProfileAuthStatus) { + return defineFixture({ + width, + store: { orcaProfileAuthStatus: status }, + // The pane re-reads auth status on mount; answer with the same state so the frame holds it. + setup: () => { + Object.assign(window.api.orcaProfiles, { authStatus: () => Promise.resolve(status) }) + }, + render: () => + }) +} + +/** Signed out: the status line names Orca Cloud, Artifacts and Orca Relay. */ +export const signedOut = pane({ + activeProfileId: 'default', + configured: true, + state: 'local', + persistence: 'none' +}) + +/** The session expired: the status line says so and points back at Orca Cloud. */ +export const reconnectRequired = pane({ + activeProfileId: 'default', + configured: true, + state: 'reconnect-required', + persistence: 'encrypted' +}) diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index 37846fb52b9..6666979d8e1 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -4,6 +4,7 @@ import { BookOpen, Check, CircleUserRound, Files, Smartphone } from 'lucide-reac import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { useOrcaProfileAuthStatusRefresh } from '@/hooks/use-orca-profile-auth-status-refresh' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' @@ -27,7 +28,7 @@ function accountStatusCopy( if (state === 'reconnect-required') { return t( 'auto.components.settings.orcaAccount.reconnectRequired', - 'Your session expired. Sign in again to use cloud features.' + 'Your session expired. Sign in again to use Orca Cloud.' ) } if (state === 'unconfigured') { @@ -39,7 +40,7 @@ function accountStatusCopy( if (state === 'local') { return t( 'auto.components.settings.orcaAccount.signedOut', - 'Sign in to extend Orca with cloud features, including Artifacts and Orca Relay.' + 'Sign in to use Orca Cloud, Artifacts and Orca Relay.' ) } return t('auto.components.settings.orcaAccount.checking', 'Checking account status…') @@ -75,6 +76,8 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { const [signingOut, setSigningOut] = useState(false) const connected = authStatus?.state === 'connected' const canConnect = authStatus?.configured === true + // Team-scoped sections remount on a team switch so none of them shows the previous team's data. + const accountKey = useOrcaAccountKey() useOrcaProfileAuthStatusRefresh() @@ -134,19 +137,22 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { {connected ? null : }
    - {connected ? : null} + {connected ? : null} {connected && authStatus?.capabilities?.flags?.billing ? ( ) : null} - {connected ? : null} + {connected ? ( + + ) : null} {connected && authStatus?.capabilities?.flags?.sandbox ? ( ) : null} {connected ? ( diff --git a/src/renderer/src/components/settings/cloud-api/ApiKeyRow.tsx b/src/renderer/src/components/settings/cloud-api/ApiKeyRow.tsx new file mode 100644 index 00000000000..0c7fabf3c52 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/ApiKeyRow.tsx @@ -0,0 +1,99 @@ +import { Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { CloudApiKey, CloudApiMe } from '../../../../../shared/cloud-api/cloud-api-types' +import { formatAbsoluteTime, formatKeyPrefix, formatRelativeFromNow } from './cloud-api-format' +import { PersonSentence } from './PersonName' +import { ScopeSummary } from './ScopeSummary' + +const EXPIRY_WARNING_MS = 7 * 86_400_000 + +/** One Orca API key: name, masked prefix, permission badge, who made it and when it was used. */ +export function KeyRow({ + apiKey, + viewer, + now, + onRevoke +}: { + apiKey: CloudApiKey + viewer: CloudApiMe | null + now: number + onRevoke: () => void +}): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + const mine = viewer?.userId === apiKey.createdBy + const expiresSoon = apiKey.expiresAt !== null && apiKey.expiresAt - now < EXPIRY_WARNING_MS + const created = formatRelativeFromNow(apiKey.createdAt, now, locale) + return ( +
  • +
    +
    +

    + {apiKey.name} +

    + + {formatKeyPrefix(apiKey.prefix)} + + +
    +

    + + · + + {apiKey.lastUsedAt + ? t('auto.components.settings.cloudApi.keys.lastUsed', 'Last used {{time}}', { + time: formatRelativeFromNow(apiKey.lastUsedAt, now, locale) + }) + : t('auto.components.settings.cloudApi.keys.neverUsed', 'Never used')} + + {apiKey.expiresAt !== null ? ( + <> + · + + {apiKey.expiresAt <= now + ? t('auto.components.settings.cloudApi.keys.expired', 'Expired') + : t('auto.components.settings.cloudApi.keys.expires', 'Expires {{time}}', { + time: formatRelativeFromNow(apiKey.expiresAt, now, locale) + })} + + + ) : null} +

    +
    + +
  • + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx index b49d8efe499..64ef2dda3bb 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx @@ -13,8 +13,14 @@ import { CloudApiSignedOutNotice } from './CloudApiSignedOutNotice' import { cloudApiErrorCopy } from './cloud-api-copy' import { useOrcaCloudApiAvailability } from '@/hooks/useOrcaCloudApiAvailability' import { useRequestGeneration } from './use-request-generation' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' +/** Keys, settings and grants belong to one team: a team switch remounts and re-reads them. */ export function CloudApiKeysPane(): React.JSX.Element | null { + return +} + +function CloudApiKeysPaneBody(): React.JSX.Element | null { const t = useTranslate() const availability = useOrcaCloudApiAvailability() const api = window.api.cloudApi diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx index 1f37128ced1..c217e1546be 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx @@ -109,8 +109,11 @@ export function AccessLinks({ export function OrgSettings({ settings, - onToggle + onToggle, + blocked = false }: { + /** The page shows one load error; this section stays quiet instead of repeating it. */ + blocked?: boolean settings: CloudLoadState onToggle: (enabled: boolean) => Promise }): React.JSX.Element { @@ -158,7 +161,7 @@ export function OrgSettings({ ) : null}

    - {settings.status === 'error' ? ( + {settings.status === 'error' && !blocked ? ( ) : null} {error ? : null} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx index bd0a0b095b3..a31156a5809 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx @@ -192,10 +192,10 @@ export const error = defineFixture({ {...base} keys={{ status: 'error', - message: 'Could not reach Orca Cloud. Check your connection and try again.' + message: 'Couldn’t reach Orca Cloud. Check your connection and try again.' }} - settings={{ status: 'error', message: 'Could not reach Orca Cloud.' }} - grants={{ status: 'error', message: 'Could not reach Orca Cloud.' }} + settings={{ status: 'error', message: 'Couldn’t reach Orca Cloud.' }} + grants={{ status: 'error', message: 'Couldn’t reach Orca Cloud.' }} audit={null} /> ) diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx index e2498455926..9a428951663 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx @@ -1,8 +1,9 @@ import { useRef, useState } from 'react' import { toast } from 'sonner' -import { KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { KeyRound, Plus, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' -import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { InlineError } from '@/components/ui/inline-error' +import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import type { CloudApiApproval, @@ -24,12 +25,10 @@ import { CloudConfirmDialog } from './CloudConfirmDialog' import { CloudConnectedApps } from './CloudConnectedApps' import type { CloudLoadState } from './cloud-load-state' import { CreateApiKeyDialog } from './CreateApiKeyDialog' -import { formatAbsoluteTime, formatKeyPrefix, formatRelativeFromNow } from './cloud-api-format' +import { formatKeyPrefix } from './cloud-api-format' import { PersonSentence } from './PersonName' -import { ScopeSummary } from './ScopeSummary' -import { CloudApiEmptyState, CloudApiErrorNotice, CloudApiSkeletonRows } from './cloud-api-parts' - -const EXPIRY_WARNING_MS = 7 * 86_400_000 +import { CloudApiEmptyState, CloudApiSkeletonRows } from './cloud-api-parts' +import { KeyRow } from './ApiKeyRow' export type CloudApiKeysViewProps = { controlPlaneUrl: string @@ -119,8 +118,22 @@ export function CloudApiKeysView(props: CloudApiKeysViewProps): React.JSX.Elemen ) + // One failure, one message: a load error is shown once at the top, not in every section. + const pageError = keys.status === 'error' ? keys.message : null + return (
    + {pageError ? ( + + ) : null} ) : keys.status === 'error' ? ( -
    - -
    +

    + {t( + 'auto.components.settings.cloudApi.keys.unavailable', + 'Your keys appear here once Orca Cloud is reachable.' + )} +

    ) : keys.data.keys.length === 0 ? ( setApproveOpen(true)} /> - setApproveOpen(true)} - onRevoke={props.onRevokeGrant} - onRetry={props.onRefreshGrants} - initialRevokeId={initial?.revokeGrantId} - /> - - - - {props.audit ? ( - + setApproveOpen(true)} + onRevoke={props.onRevokeGrant} + onRetry={props.onRefreshGrants} + initialRevokeId={initial?.revokeGrantId} /> - ) : null} + + + + {props.audit ? ( + + ) : null} +
    ) } - -function KeyRow({ - apiKey, - viewer, - now, - onRevoke -}: { - apiKey: CloudApiKey - viewer: CloudApiMe | null - now: number - onRevoke: () => void -}): React.JSX.Element { - const t = useTranslate() - const locale = useIntlLocale() - const mine = viewer?.userId === apiKey.createdBy - const expiresSoon = apiKey.expiresAt !== null && apiKey.expiresAt - now < EXPIRY_WARNING_MS - const created = formatRelativeFromNow(apiKey.createdAt, now, locale) - return ( -
  • -
    -
    -

    - {apiKey.name} -

    - - {formatKeyPrefix(apiKey.prefix)} - - -
    -

    - - · - - {apiKey.lastUsedAt - ? t('auto.components.settings.cloudApi.keys.lastUsed', 'Last used {{time}}', { - time: formatRelativeFromNow(apiKey.lastUsedAt, now, locale) - }) - : t('auto.components.settings.cloudApi.keys.neverUsed', 'Never used')} - - {apiKey.expiresAt !== null ? ( - <> - · - - {apiKey.expiresAt <= now - ? t('auto.components.settings.cloudApi.keys.expired', 'Expired') - : t('auto.components.settings.cloudApi.keys.expires', 'Expires {{time}}', { - time: formatRelativeFromNow(apiKey.expiresAt, now, locale) - })} - - - ) : null} -

    -
    - -
  • - ) -} diff --git a/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx b/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx index 9a7b3ba9886..0032ed310d3 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudConnectedApps.tsx @@ -32,7 +32,8 @@ export function CloudConnectedApps({ onApprove, onRevoke, onRetry, - initialRevokeId + initialRevokeId, + blocked = false }: { grants: CloudLoadState viewer: CloudApiMe | null @@ -41,6 +42,8 @@ export function CloudConnectedApps({ onRevoke: (grant: CloudApiGrant) => Promise onRetry: () => void initialRevokeId?: string + /** The page shows one load error; this section stays quiet instead of repeating it. */ + blocked?: boolean }): React.JSX.Element | null { const t = useTranslate() const locale = useIntlLocale() @@ -81,9 +84,18 @@ export function CloudConnectedApps({ label={t('auto.components.settings.cloudApi.apps.loading', 'Loading connected apps')} /> ) : grants.status === 'error' ? ( -
    - -
    + blocked ? ( +

    + {t( + 'auto.components.settings.cloudApi.apps.unavailable', + 'Connected apps appear here once Orca Cloud is reachable.' + )} +

    + ) : ( +
    + +
    + ) ) : grants.data.length === 0 ? ( · {where} : null} {' · '} - {routine.agent === 'codex' - ? t('auto.components.settings.cloudRoutines.agentCodex', 'Codex') - : t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code')} + {formatAgentTypeLabel(routine.agent)} {viewerUserId && routine.createdBy !== viewerUserId ? ( diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx index 995090243bb..6bb25768433 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx @@ -146,8 +146,7 @@ const RUNS: RoutineRunPage = { status: 'failed', startedAt: NOW - 45 * HOUR, durationMs: 38_000, - error: - 'The agent could not clone acme/api: the Orca Cloud GitHub App is not installed on this repository.' + error: 'start_failed:clone_failed' }), run({ id: 'r1', status: 'timed_out', startedAt: NOW - 69 * HOUR, durationMs: 30 * MIN }), run({ @@ -161,6 +160,63 @@ const RUNS: RoutineRunPage = { } const loadRuns: LoadRoutineRuns = async () => ({ ok: true, data: RUNS }) + +/** Every failure code the control plane sends, as people read it (codes never on screen). */ +const FAILED_RUNS: RoutineRunPage = { + nextBefore: null, + runs: [ + run({ + id: 'f1', + status: 'failed', + startedAt: NOW - 1 * HOUR, + durationMs: 21_000, + error: 'start_failed:clone_failed' + }), + run({ + id: 'f2', + status: 'failed', + startedAt: NOW - 3 * HOUR, + durationMs: 412_000, + error: 'workspace_lost:suspended' + }), + run({ + id: 'f3', + status: 'failed', + startedAt: NOW - 5 * HOUR, + durationMs: 380_000, + error: 'post_failed:github_403' + }), + run({ + id: 'f4', + status: 'cancelled', + startedAt: NOW - 8 * HOUR, + durationMs: null, + error: 'queue_expired' + }), + run({ + id: 'f5', + status: 'failed', + startedAt: NOW - 12 * HOUR, + durationMs: 95_000, + error: 'agent_interrupted' + }), + run({ + id: 'f6', + status: 'cancelled', + startedAt: NOW - 20 * HOUR, + durationMs: null, + error: 'routine_changed' + }), + run({ + id: 'f7', + status: 'failed', + startedAt: NOW - 26 * HOUR, + durationMs: 4_000, + error: 'something_new' + }) + ] +} +const loadFailedRuns: LoadRoutineRuns = async () => ({ ok: true, data: FAILED_RUNS }) const loadNoRuns: LoadRoutineRuns = async () => ({ ok: true, data: { runs: [], nextBefore: null } }) const loadRunsFailing: LoadRoutineRuns = async () => ({ ok: false, error: 'network' }) @@ -206,7 +262,7 @@ export const error = defineFixture({ routines={{ status: 'error', code: 'network', - message: 'Could not reach Orca Cloud. Check your connection and try again.' + message: 'Couldn’t reach Orca Cloud. Check your connection and try again.' }} /> ) @@ -311,3 +367,10 @@ export const deleteConfirm = defineFixture({ width: 820, render: () => }) + +export const runHistoryFailures = defineFixture({ + width: 820, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx index 5d571c3e1e4..6e81a411bc8 100644 --- a/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx +++ b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx @@ -1,12 +1,29 @@ import { useId } from 'react' import { Input } from '@/components/ui/input' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' import { Textarea } from '@/components/ui/textarea' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls' import { FormField } from './cloud-api-parts' +import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' +import { + ROUTINE_AGENTS, + type RoutineAgent +} from '../../../../../shared/cloud-api/cloud-api-routine-types' import type { RoutineDraft, RoutineDraftField } from './routine-draft' +/** The Select hands back a string; only the image's agents are routine agents. */ +export function agentFrom(value: string): RoutineAgent { + return ROUTINE_AGENTS.find((agent) => agent === value) ?? 'claude' +} + export function routineFieldError( code: string | undefined, field: RoutineDraftField, @@ -84,23 +101,22 @@ export function RoutineAgentSection({

    {t('auto.components.settings.cloudRoutines.editor.agent', 'Agent')}

    - - size="sm" - value={draft.agent} - onChange={(agent) => update({ agent })} - equalWidth - ariaLabelledBy={`${ids}-agent`} - options={[ - { - value: 'claude', - label: t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code') - }, - { - value: 'codex', - label: t('auto.components.settings.cloudRoutines.agentCodex', 'Codex') - } - ]} - /> +
    {run.result.summary}

    ) : null} - {run.error ? ( -

    - - {t('auto.components.settings.cloudRoutines.runs.why', 'Why:')} - {' '} - {run.error} -

    - ) : null} + {run.error ? : null} ) } @@ -341,3 +338,10 @@ function RunAction({ ) } + +/** Why a run didn't succeed: one quiet line under the row; red icon only for real failures. */ +function RunFailure({ error }: { error: string }): React.JSX.Element { + const t = useTranslate() + const { text, tone } = describeRoutineRunError(error, t) + return +} diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts index 9cf5ce3d993..a0957e6f7da 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts @@ -71,7 +71,7 @@ export function cloudApiErrorCopy( case 'network': return t( 'auto.components.settings.cloudApi.error.network', - 'Couldn’t reach Orca Cloud, so nothing was changed. Check your connection and try again.' + 'Couldn’t reach Orca Cloud. Check your connection and try again.' ) case 'invalid-response': return t( @@ -170,3 +170,73 @@ export function routineRunTriggerLabel( return t('auto.components.settings.cloudRoutines.runTrigger.manual', 'Manual') } } + +/** + * A run's failure in plain words. The control plane sends a code, sometimes with detail after a + * colon ("workspace_lost:suspended"); codes and detail never reach the screen. + */ +export function routineRunErrorCopy(error: string, t: Translate = translate): string { + return describeRoutineRunError(error, t).text +} + +/** + * Copy plus tone: things that went wrong (couldn't start, couldn't post, interrupted, unknown) are + * errors; outcomes that are expected bookkeeping (skipped, superseded, workspace gone) are neutral. + */ +export function describeRoutineRunError( + error: string, + t: Translate = translate +): { text: string; tone: 'error' | 'neutral' } { + const neutral = (text: string) => ({ text, tone: 'neutral' as const }) + const failure = (text: string) => ({ text, tone: 'error' as const }) + const code = error.split(':', 1)[0]?.trim() ?? '' + if (code === 'start_failed') { + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.startFailed', + 'The workspace couldn’t start, so nothing was charged.' + ) + ) + } + if (code === 'workspace_lost') { + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.workspaceLost', + 'The workspace went to sleep or was deleted before the run finished.' + ) + ) + } + if (code === 'post_failed') { + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.postFailed', + 'The run finished, but Orca couldn’t post the results.' + ) + ) + } + if (code === 'queue_expired') { + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.queueExpired', + 'The run waited too long to start and was skipped.' + ) + ) + } + if (code.endsWith('_interrupted')) { + return failure( + t( + 'auto.components.settings.cloudRoutines.runError.interrupted', + 'Orca Cloud restarted during the run.' + ) + ) + } + if (code === 'routine_changed') { + return neutral( + t( + 'auto.components.settings.cloudRoutines.runError.routineChanged', + 'The routine changed while this run was queued.' + ) + ) + } + return failure(t('auto.components.settings.cloudRoutines.runError.generic', 'The run failed.')) +} diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts index 1312784f4ab..38137b52967 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest' import { CLOUD_API_SCOPES } from '../../../../../shared/cloud-api/cloud-api-types' -import { cloudApiErrorCopy, routineRunTone } from './cloud-api-copy' +import { + cloudApiErrorCopy, + describeRoutineRunError, + routineRunErrorCopy, + routineRunTone +} from './cloud-api-copy' import { describeRoutineTrigger, formatCountdown, @@ -83,3 +88,42 @@ describe('copy', () => { expect(routineRunTone('cancelled')).toBe('neutral') }) }) + +describe('run failure copy', () => { + it('maps control-plane codes (with detail) to plain words and never shows the code', () => { + expect(routineRunErrorCopy('start_failed:clone_failed')).toBe( + 'The workspace couldn’t start, so nothing was charged.' + ) + expect(routineRunErrorCopy('workspace_lost:suspended')).toBe( + 'The workspace went to sleep or was deleted before the run finished.' + ) + expect(routineRunErrorCopy('post_failed')).toBe( + 'The run finished, but Orca couldn’t post the results.' + ) + expect(routineRunErrorCopy('queue_expired')).toBe( + 'The run waited too long to start and was skipped.' + ) + expect(routineRunErrorCopy('agent_interrupted')).toBe('Orca Cloud restarted during the run.') + expect(routineRunErrorCopy('routine_changed')).toBe( + 'The routine changed while this run was queued.' + ) + expect(routineRunErrorCopy('totally_new:detail')).toBe('The run failed.') + }) +}) + +describe('run failure tone', () => { + it('keeps red for real failures and neutral for expected outcomes', () => { + const tone = (code: string) => describeRoutineRunError(code).tone + expect(['start_failed', 'post_failed', 'agent_interrupted', 'mystery'].map(tone)).toEqual([ + 'error', + 'error', + 'error', + 'error' + ]) + expect(['queue_expired', 'routine_changed', 'workspace_lost:suspended'].map(tone)).toEqual([ + 'neutral', + 'neutral', + 'neutral' + ]) + }) +}) diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx index 3d9a7c0c62f..631319eb2d2 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretEditor.tsx @@ -4,7 +4,8 @@ import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { cloudSecretNameError, - cloudSecretValueError + cloudSecretValueError, + cloudSecretStoredOnVm } from '../../../../../shared/cloud-secrets/cloud-secret-rules' import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' import { Button } from '../../ui/button' @@ -12,6 +13,7 @@ import { Input } from '../../ui/input' import { Label } from '../../ui/label' import { cloudSecretsErrorCopy } from './cloud-secrets-copy' import { SecretValueInput } from './SecretValueInput' +import { cloudSecretVmWarning } from './CloudSecretVmBadge' const NAME_EXAMPLE = 'DATABASE_URL' @@ -164,6 +166,12 @@ export function CloudSecretEditor({ ) : (

    {t('cloudSecrets.editor.help', 'Write-only. You won’t see it again after saving.')} + {cloudSecretStoredOnVm(name.trim()) ? ( + <> + {' '} + {cloudSecretVmWarning(t)} + + ) : null}

    )}
    diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx index ce73e1dd2bc..1ded5d704db 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretList.tsx @@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react' import { Check, ClipboardPaste, KeyRound, Plus } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' import { formatUiRelativeTime } from '@/i18n/relative-time-format' +import { SignInAgainNotice } from '@/components/orca-cloud/SignInAgainButton' +import { useAppStore } from '@/store/index' import type { CloudSecretView, CloudSecretsErrorCode @@ -14,6 +16,7 @@ import { cloudSecretKindLabel, cloudSecretsErrorCopy } from './cloud-secrets-cop import { CloudSecretEditor, type CloudSecretEditorTarget } from './CloudSecretEditor' import { CloudApiEmptyState } from '../cloud-api/cloud-api-parts' import { CloudSecretsPasteEnv } from './CloudSecretsPasteEnv' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import type { CloudSecretListModel } from './use-cloud-secrets' export type CloudSecretPeople = { @@ -85,6 +88,7 @@ function SecretRow({ {cloudSecretKindLabel(secret.name, t)} ) : null} + {maskedHint(secret.hint)} @@ -260,10 +264,15 @@ export function CloudSecretList({ } if (model.list.status === 'failed') { + if (model.list.error === 'unauthorized') { + const signIn = (): void => + void useAppStore.getState().connectCurrentOrcaProfile().then(model.reload) + return + } return ( + + {t('cloudSecrets.vm.badge', 'Stored on workspace')} + {why} + + ) +} + +export function cloudSecretVmWarning(t: ReturnType): string { + return t( + 'cloudSecrets.vm.warning', + 'Orca can’t swap this key at the network edge, so cloud workspaces get the real value. Anything running in the workspace can read it.' + ) +} diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx index c534e8a0275..e2c19391871 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsEffectiveView.tsx @@ -5,6 +5,7 @@ import type { CloudSecretsEffective } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' import { Badge } from '../../ui/badge' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import { InlineError } from '../../ui/inline-error' import { Skeleton } from '../../ui/skeleton' import { CloudApiEmptyState } from '../cloud-api/cloud-api-parts' @@ -132,6 +133,7 @@ export function CloudSecretsEffectiveView({ {cloudSecretKindLabel(secret.name, t)} ) : null} + diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx index de3a8341635..e1f9577b3be 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPasteRow.tsx @@ -12,6 +12,7 @@ import { type DotenvPasteIssue } from '../../../../../shared/cloud-secrets/dotenv-paste' import { Badge } from '../../ui/badge' +import { CloudSecretVmBadge } from './CloudSecretVmBadge' import { Button } from '../../ui/button' import { Input } from '../../ui/input' import { cloudSecretKindLabel, cloudSecretsErrorCopy } from './cloud-secrets-copy' @@ -176,6 +177,7 @@ export function PasteRowEditor({ {row.name && cloudSecretKind(row.name) === 'agent_key' ? ( {cloudSecretKindLabel(row.name, t)} ) : null} + {row.name ? : null} {removeButton}

    ok(true) + refreshEnv: () => ok(true), + saveDesktopKey: ({ envName }) => + ok({ + scope: 'personal' as const, + name: envName, + kind: 'agent_key' as const, + hint: 'x4Qa', + updatedAt: 0, + updatedBy: caller.userId + }) } } diff --git a/src/renderer/src/components/settings/ports/PortsPane.tsx b/src/renderer/src/components/settings/ports/PortsPane.tsx index 2e7fa14bd13..89ada6191e8 100644 --- a/src/renderer/src/components/settings/ports/PortsPane.tsx +++ b/src/renderer/src/components/settings/ports/PortsPane.tsx @@ -123,8 +123,8 @@ export function PortsPane({ settings }: { settings: GlobalSettings }): React.JSX [ { - title: translate('auto.components.settings.ports.search.title', 'Port Forwarding'), + title: translate('auto.components.settings.ports.search.titleSentenceCase', 'Port forwarding'), description: translate( 'auto.components.settings.ports.search.descriptionSandboxes', 'Forward dev servers in sandboxes and on remote hosts to this computer.' diff --git a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx index 7344db6d2ad..ef2ecb15032 100644 --- a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx +++ b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx @@ -71,9 +71,7 @@ function ServerRow({ {row.name} {mcpSyncRowStateLabel(row, t)} - - {AGENT_LABEL[row.agent]} - + {AGENT_LABEL[row.agent]} {row.target ? ( {row.target} diff --git a/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx b/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx index ee4a381618f..0e661f7425a 100644 --- a/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx +++ b/src/renderer/src/components/sidebar/SidebarToolbar.fixture.tsx @@ -1,5 +1,6 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' import SidebarToolbar from './SidebarToolbar' import { registerPlanBillingMenuItem } from '../billing/register-plan-billing-menu-item' import { recordBillingStatus } from '../billing/billing-summary-store' @@ -45,18 +46,20 @@ const signedInWithBilling: OrcaProfileAuthStatus = { } /** Registers the billing items as main.tsx does, with a known plan state. */ -const withBilling = (subscribed: boolean) => (): void => { - const result = { - status: 'ok' as const, - entitlement: subscribed - ? sampleTeam - : { ...sampleTeam, plan: null, planLabel: null, status: 'none' } +const withBilling = + (subscribed: boolean, usage: Partial = {}) => + (): void => { + const result = { + status: 'ok' as const, + entitlement: subscribed + ? { ...sampleTeam, ...usage } + : { ...sampleTeam, plan: null, planLabel: null, status: 'none' } + } + // The registration re-reads billing when the account changes; answer like the service would. + window.api.orcaProfiles.billingStatus = async () => result + registerPlanBillingMenuItem() + recordBillingStatus(result) } - // The registration re-reads billing when the account changes; answer like the service would. - window.api.orcaProfiles.billingStatus = async () => result - registerPlanBillingMenuItem() - recordBillingStatus(result) -} const signedOut: OrcaProfileAuthStatus = { activeProfileId: 'local-default', @@ -117,6 +120,18 @@ export const signedInMenuOnTeam = footer({ interact: openAccountMenu }) +/** The team at billing's 75% level: hours left and the early warning in the header. */ +export const signedInMenuUsageWarning = footer({ + height: 360, + authStatus: signedInWithBilling, + setup: withBilling(true, { + usedSeconds: 92 * 3600, + remainingIncludedSeconds: 28 * 3600, + usageWarningPercent: 75 + }), + interact: openAccountMenu +}) + const openTeamSwitcher = async (frame: HTMLElement): Promise => { await openAccountMenu(frame) const trigger = document.querySelector('[data-account-menu-team-switcher]') diff --git a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx index 7ad8dbc2ab7..4c15bd4dce6 100644 --- a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx +++ b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx @@ -16,7 +16,8 @@ import { useMountedRef } from '@/hooks/useMountedRef' import { useOptionalShortcutLabel } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import { useBillingSummary } from '../../billing/billing-summary-store' +import { useBillingState } from '../../billing/billing-summary-store' +import { accountMenuUsageLines } from '../../billing/plan-billing-usage-copy' import { SidebarTeamSubmenu } from './SidebarTeamSubmenu' import { useSetupGuideProgress } from '../../setup-guide/use-setup-guide-progress' import { getAccountMenuIdentity, type AccountMenuIdentity } from './account-menu-identity' @@ -68,21 +69,8 @@ export function SidebarAccountMenu(): React.JSX.Element { const mountedRef = useMountedRef() const identity = getAccountMenuIdentity(authStatus) - const billingSummary = useBillingSummary() - const orgName = authStatus?.state === 'connected' ? authStatus.cloud?.activeOrgName : undefined - // "Acme · Team plan": which team this account acts for, and its plan once billing has answered. - const orgLine = orgName - ? billingSummary.planLabel - ? t( - 'auto.components.sidebar.SidebarAccountMenu.teamPlanLine', - '{{value0}} · {{value1}} plan', - { - value0: orgName, - value1: billingSummary.planLabel - } - ) - : orgName - : null + // The team is named once, on the switcher below; the header carries the plan's hours instead. + const usage = accountMenuUsageLines(useBillingState().result, t) const visibleItems = selectVisibleAccountMenuItems(registeredItems, authStatus) // Freeze the item list while the menu is open: a billing answer arriving mid-read must not // swap rows under the pointer (e.g. Upgrade replacing Plan & billing). @@ -196,8 +184,13 @@ export function SidebarAccountMenu(): React.JSX.Element { {identity.email} ) : null} - {orgLine ? ( - {orgLine} + {usage ? ( + + {usage.hoursLeft} + + ) : null} + {usage?.warning ? ( + {usage.warning} ) : null} ) : ( diff --git a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx index e151b423321..df57cb1f8f6 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshIncludeDialog.tsx @@ -104,7 +104,7 @@ const CloudSshIncludeDialog = React.memo(function CloudSshIncludeDialog() { {t('auto.components.sidebar.CloudSshIncludeDialog.cancel', 'Cancel')} diff --git a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx index 0c5c986bbe3..c2ee41aa49b 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/cloud-ssh/CloudSshMenuItems.tsx @@ -136,7 +136,7 @@ export function CloudSshMenuItems({ aria-describedby={status.hasAccess ? undefined : hintId} > - {t('auto.components.sidebar.CloudSsh.copyCommand', 'Copy SSH Command')} + {t('auto.components.sidebar.CloudSsh.copySshCommand', 'Copy SSH command')} {status.hasAccess ? ( <> @@ -147,7 +147,7 @@ export function CloudSshMenuItems({ disabled={disabled} > - {t('auto.components.sidebar.CloudSsh.revoke', 'Revoke SSH Access')} + {t('auto.components.sidebar.CloudSsh.revokeSshAccess', 'Revoke SSH access')} {status.includeInstalled ? ( {VARIANTS.map((variant) => (

    - {variant} + {variant}