diff --git a/cloud/apps/billing/src/plans.ts b/cloud/apps/billing/src/plans.ts index 854b1d5f75a..86f9062f85f 100644 --- a/cloud/apps/billing/src/plans.ts +++ b/cloud/apps/billing/src/plans.ts @@ -6,6 +6,7 @@ // included hour is one hour on the Standard 4 vCPU / 8 GB box and a Large box burns 2x. // Included hours are a MONTHLY per-seat allowance pooled across the org, for annual plans too. import { z } from 'zod' +import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import type { Env } from './env' export const PLAN_IDS = ['team'] as const @@ -65,7 +66,8 @@ export const DEFAULT_PLANS: PlanCatalog = { includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, machineSizes: ['standard', 'large'], - idleSleepMinutes: 15, + // Same constant the control plane enforces and serves (GET /v1/config); never a literal here. + idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 75, defaultSpendCapCents: 2500, maxSpendCapCents: 500_000, diff --git a/cloud/apps/sandbox-control/image/golden-image.ts b/cloud/apps/sandbox-control/image/golden-image.ts index ac1d25a6b8d..ba3b56fb8ce 100644 --- a/cloud/apps/sandbox-control/image/golden-image.ts +++ b/cloud/apps/sandbox-control/image/golden-image.ts @@ -18,7 +18,9 @@ export const VM_SCRIPTS = [ 'orca-sandbox-grant', 'orca-sandbox-revoke', 'orca-sandbox-members', - 'orca-git-as' + 'orca-git-as', + 'orca-git-identity', + 'git' ] as const const Sha256 = z.string().regex(/^[a-f0-9]{64}$/) diff --git a/cloud/apps/sandbox-control/image/provision-golden.sh b/cloud/apps/sandbox-control/image/provision-golden.sh index 401d6ecbdba..46ca8ba2243 100755 --- a/cloud/apps/sandbox-control/image/provision-golden.sh +++ b/cloud/apps/sandbox-control/image/provision-golden.sh @@ -128,11 +128,14 @@ install_desktop() { rm -rf "$dir" && mkdir -p "$dir/novnc" "$dir/websockify" || return 1 tar -xzf "$tmp/novnc.tgz" -C "$dir/novnc" --strip-components 1 || return 1 tar -xzf "$tmp/websockify.tgz" -C "$dir/websockify" --strip-components 1 || return 1 - # Orca tab fit: title "Remote Desktop" (Xvnc's -desktop name), no noVNC favicon, control bar on - # the right (away from Orca's sidebar edge), and no reconnect loop on a stale per-boot password. + # Orca tab fit: title "Remote desktop" (Xvnc's -desktop name), no noVNC favicon, control bar on + # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one + # plain message instead of a reconnect loop. "Unencrypted" is noVNC's view of plain ws:// to + # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection. sed -i -e 's/document.title = e.detail.name + " - " + PAGE_TITLE;/document.title = e.detail.name;/' \ -e "s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/" \ - -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true;/' \ + -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus("This remote desktop session ended. Reopen it from the workspace menu.", "error"); return;/' \ + -e 's/_("Connected (unencrypted) to ")/_("Connected to ")/' \ "$dir/novnc/app/ui.js" || return 1 sed -i '/rel="icon"/d; /rel="apple-touch-icon"/d' "$dir/novnc/vnc.html" || return 1 rm -rf "$tmp" @@ -152,7 +155,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-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as; do +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-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity git; do var="ORCA_VM_SCRIPT_${name//[-.]/_}" printf '%s' "${!var}" | base64 -d >"$ORCA_HOME/bin/$name" chmod 0755 "$ORCA_HOME/bin/$name" diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 273d494419b..6039c2a10c9 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"],"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), [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 # 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\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), and no reconnect loop on a stale per-boot password.\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;/' \\\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-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as; 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\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" | 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\"\nsmoke_data=\"$(mktemp -d)\"\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$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\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\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini 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# 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\"\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\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"}\\n' \"$STATE/ready.json\"\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# 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 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\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\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\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --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\nfor _ in $(seq 1 1200); 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 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.05\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=''\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 esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex provider block (no secret values: env_key names the variable) ----\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}\nif [ -n \"$openai_base_url\" ] || grep -q '^# >>> orca-cloud managed' \"$codex_config\" 2>/dev/null; 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 if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then\n # Top-level keys must precede every table; skip ours if the user already chose a provider/model.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n {\n printf '# >>> orca-cloud managed (Orca Cloud provider; edit in Orca settings)\\n'\n if ! grep -Eq '^[[:space:]]*model_provider[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model_provider = \"orca_cloud\"\\n'\n fi\n if [ -n \"$openai_model\" ] && ! grep -Eq '^[[:space:]]*model[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\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 } >\"$next\"\n else\n cat \"$user_part\" >\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\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/.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\"; 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 prints one JSON line:\n# {\"schemaVersion\":1,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"password\":\"<8 chars>\"}\n# Xvnc (X server + VNC in one) listens on a unix socket only; websockify serves noVNC and bridges\n# WebSockets to that socket on 127.0.0.1 only. Nothing is reachable from outside the VM: the\n# desktop reaches it through Orca's port forward. The forward is a localhost port on the user's\n# computer, which any local process or web page can reach, so VNC auth with a per-boot random\n# password guards it (Xvnc blacklists repeated failures). 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\ncommand -v vncpasswd >/dev/null || fail 'not installed in this image (vncpasswd missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\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; }\nready_line() {\n printf '{\"schemaVersion\":1,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"password\":\"%s\"}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$(cat \"$STATE/password\")\"\n}\nlistening() { # websockify 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 -f \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\nif alive xvnc && alive websockify && listening && [ -s \"$STATE/password\" ]; 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 || [ ! -s \"$STATE/password\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # VNC auth uses 8 password bytes; 8 random alphanumerics (~48 bits) plus Xvnc's blacklist.\n password=\"$(LC_ALL=C tr -dc 'A-Za-z0-9' \"$STATE/passwd\"\n printf '%s' \"$password\" >\"$STATE/password\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket for websockify.\n start xvnc Xvnc \":$DISPLAY_NUM\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes VncAuth -PasswordFile \"$STATE/passwd\" \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote Desktop'\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 elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n start xterm xterm -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11\n fi\nfi\n\nif ! alive websockify || ! listening; then\n if alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\n PYTHONPATH=\"$DESKTOP/websockify\" start websockify python3 -P -W ignore::UserWarning -m websockify \\\n --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" \"127.0.0.1:$PORT\"\n for _ in $(seq 1 100); do\n listening && break\n alive websockify || { tail -n 20 \"$STATE/websockify.log\" >&2; fail 'websockify exited'; }\n sleep 0.05\n done\n listening || fail \"websockify is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\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\"\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# Writes one git config per workspace member for `orca-git-as`. No token ever lands here: each file\n# carries the member's egress placeholder (swapped for their GitHub token by the control plane's\n# egress proxy, for this workspace's repository only) and their GitHub author identity.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization}]. Prints {\"members\":}.\nset -euo pipefail\numask 077\nDIR=\"$HOME/.orca-sandbox/members\"\nmkdir -p \"$DIR\"\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d \"$DIR.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\")\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\necho \"{\\\"members\\\":$count}\"\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as a workspace member: their GitHub identity for pushes/PRs and their commit author.\n# orca-git-as e.g. orca-git-as \"$ORCA_SENDER_ID\" push origin HEAD\n# Falls back to plain git (the workspace's app identity) when the member never connected GitHub.\nset -euo pipefail\nuser=\"${1:-}\"\nshift || true\ncase \"$user\" in '' | *[!A-Za-z0-9_.:-]*) echo 'usage: orca-git-as ' >&2; exit 2 ;; esac\nfile=\"$HOME/.orca-sandbox/members/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\nif [ ! -f \"$file\" ]; then\n echo \"orca-git-as: $user has not connected GitHub; using the workspace identity\" >&2\n exec git \"$@\"\nfi\nexec git -c \"include.path=$file\" \"$@\"\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), [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 # 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\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-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity 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\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" | 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\"\nsmoke_data=\"$(mktemp -d)\"\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$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\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\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini 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# 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\"\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\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"}\\n' \"$STATE/ready.json\"\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 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\")\"\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \\\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\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --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\nfor _ in $(seq 1 1200); 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 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.05\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=''\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 esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex provider block (no secret values: env_key names the variable) ----\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}\nif [ -n \"$openai_base_url\" ] || grep -q '^# >>> orca-cloud managed' \"$codex_config\" 2>/dev/null; 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 if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then\n # Top-level keys must precede every table; skip ours if the user already chose a provider/model.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n {\n printf '# >>> orca-cloud managed (Orca Cloud provider; edit in Orca settings)\\n'\n if ! grep -Eq '^[[:space:]]*model_provider[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model_provider = \"orca_cloud\"\\n'\n fi\n if [ -n \"$openai_model\" ] && ! grep -Eq '^[[:space:]]*model[[:space:]]*=' <<<\"$head_keys\"; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\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 } >\"$next\"\n else\n cat \"$user_part\" >\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\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/.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\"; 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 prints one JSON line:\n# {\"schemaVersion\":1,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"password\":\"<8 chars>\"}\n# Xvnc (X server + VNC in one) listens on a unix socket only; websockify serves noVNC and bridges\n# WebSockets to that socket on 127.0.0.1 only. Nothing is reachable from outside the VM: the\n# desktop reaches it through Orca's port forward. The forward is a localhost port on the user's\n# computer, which any local process or web page can reach, so VNC auth with a per-boot random\n# password guards it (Xvnc blacklists repeated failures). 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\ncommand -v vncpasswd >/dev/null || fail 'not installed in this image (vncpasswd missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\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; }\nready_line() {\n printf '{\"schemaVersion\":1,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"password\":\"%s\"}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$(cat \"$STATE/password\")\"\n}\nlistening() { # websockify 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 -f \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\nif alive xvnc && alive websockify && listening && [ -s \"$STATE/password\" ]; 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 || [ ! -s \"$STATE/password\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # VNC auth uses 8 password bytes; 8 random alphanumerics (~48 bits) plus Xvnc's blacklist.\n password=\"$(LC_ALL=C tr -dc 'A-Za-z0-9' \"$STATE/passwd\"\n printf '%s' \"$password\" >\"$STATE/password\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket for websockify.\n start xvnc Xvnc \":$DISPLAY_NUM\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes VncAuth -PasswordFile \"$STATE/passwd\" \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\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 elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n start xterm xterm -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11\n fi\nfi\n\nif ! alive websockify || ! listening; then\n if alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\n PYTHONPATH=\"$DESKTOP/websockify\" start websockify python3 -P -W ignore::UserWarning -m websockify \\\n --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" \"127.0.0.1:$PORT\"\n for _ in $(seq 1 100); do\n listening && break\n alive websockify || { tail -n 20 \"$STATE/websockify.log\" >&2; fail 'websockify exited'; }\n sleep 0.05\n done\n listening || fail \"websockify is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\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\"\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","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_REPO (https://github.com//), ORCA_SRC_SHA (40-hex), 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\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 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\nlog \"fetch $ORCA_SRC_SHA\"\nsrc=\"$HOME/orca-src\"\nrm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\ngit init -q\n# The header lives only in this one command's config, not in .git/config.\ngit -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\nunset ORCA_SRC_AUTH\ngit -c advice.detachedHead=false checkout -q FETCH_HEAD\ntest \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\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\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/git b/cloud/apps/sandbox-control/image/vm/git new file mode 100755 index 00000000000..ecee43f4ffc --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/git @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish +# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the +# sender's paired device; root-only member identities). Everything else is plain git, untouched. +real=/usr/bin/git +sub='' +skip=0 +for arg in "$@"; do + if [ "$skip" = 1 ]; then skip=0; continue; fi + case "$arg" in + -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;; + -*) ;; + *) sub="$arg"; break ;; + esac +done +case "$sub" in + commit | push | merge | rebase | cherry-pick | revert | am | pull | tag) + # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity. + if [ -n "${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}" ] && [ -x /opt/orca/bin/orca-git-as ]; then + PATH="/usr/bin:/bin:$PATH" exec /opt/orca/bin/orca-git-as "$@" 2> >(grep -v '^orca-git-as: no teammate identity' >&2) + fi + ;; +esac +exec "$real" "$@" diff --git a/cloud/apps/sandbox-control/image/vm/orca-desktop-start b/cloud/apps/sandbox-control/image/vm/orca-desktop-start index 60b4a54c832..32335610aeb 100644 --- a/cloud/apps/sandbox-control/image/vm/orca-desktop-start +++ b/cloud/apps/sandbox-control/image/vm/orca-desktop-start @@ -76,7 +76,7 @@ if ! alive xvnc || [ ! -s "$STATE/password" ]; then start xvnc Xvnc ":$DISPLAY_NUM" -geometry "$GEOMETRY" -depth 24 -nolisten tcp \ -rfbport -1 -rfbunixpath "$SOCKET" -rfbunixmode 0600 \ -SecurityTypes VncAuth -PasswordFile "$STATE/passwd" \ - -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote Desktop' + -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop' for _ in $(seq 1 100); do [ -S "$SOCKET" ] && break alive xvnc || { tail -n 20 "$STATE/xvnc.log" >&2; fail 'Xvnc exited'; } diff --git a/cloud/apps/sandbox-control/image/vm/orca-git-as b/cloud/apps/sandbox-control/image/vm/orca-git-as index 3395b6d3a76..56b30ab4243 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-git-as +++ b/cloud/apps/sandbox-control/image/vm/orca-git-as @@ -1,14 +1,31 @@ #!/usr/bin/env bash -# Runs git as a workspace member: their GitHub identity for pushes/PRs and their commit author. -# orca-git-as e.g. orca-git-as "$ORCA_SENDER_ID" push origin HEAD -# Falls back to plain git (the workspace's app identity) when the member never connected GitHub. +# Runs git as the teammate whose message started this agent's turn: their GitHub identity for +# pushes/PRs (this repository only) and their commit author. +# orca-git-as e.g. orca-git-as push origin HEAD +# orca-git-as --as refuses unless that member really sent the message +# Orca attests the sender from the paired device that sent the message, never from arguments or +# message text. Without an attested sender (not run from an agent, or the owner's local session) it +# runs plain git with the workspace identity. set -euo pipefail -user="${1:-}" -shift || true -case "$user" in '' | *[!A-Za-z0-9_.:-]*) echo 'usage: orca-git-as ' >&2; exit 2 ;; esac -file="$HOME/.orca-sandbox/members/$(printf '%s' "$user" | tr ':' '_').gitconfig" -if [ ! -f "$file" ]; then - echo "orca-git-as: $user has not connected GitHub; using the workspace identity" >&2 - exec git "$@" +expect='' +if [ "${1:-}" = '--as' ]; then + expect="${2:-}" + shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; } + case "$expect" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac fi -exec git -c "include.path=$file" "$@" +set +e +file="$(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 \ + /opt/orca/bin/orca-git-identity)" +status=$? +set -e +case "$status" in + 0) + trap 'rm -f "$file"' EXIT + git -c "include.path=$file" "$@" + ;; + 3) + echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2 + exec git "$@" + ;; + *) exit 4 ;; +esac diff --git a/cloud/apps/sandbox-control/image/vm/orca-git-identity b/cloud/apps/sandbox-control/image/vm/orca-git-identity new file mode 100755 index 00000000000..a6cded392f5 --- /dev/null +++ b/cloud/apps/sandbox-control/image/vm/orca-git-identity @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the +# calling agent, which paired device sent the message that started the agent's latest turn +# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps +# that device to a workspace member, and prints that member's git config file for the caller to +# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused. +# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused. +set -euo pipefail +DIR=/etc/orca/members +caller="${SUDO_USER:-}" +case "$caller" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac +# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel). +orcad_pid="$(pgrep -u "$caller" -f orcad-server.js | head -n 1 || true)" +[ -n "$orcad_pid" ] || exit 3 +orcad_env() { tr '\0' '\n' <"/proc/$orcad_pid/environ" | sed -n "s/^$1=//p" | head -n 1; } +home="$(orcad_env HOME)" +data="$(orcad_env ORCA_USER_DATA)" +data="${data:-$home/.orcad-data}" +node="$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)" +cli=/opt/orca/runtime/orcad/out/cli/index.js +# Only the evidence variables orcad needs reach the query, which runs as the caller, not root. +answer="$(sudo -u "$caller" env -i HOME="$home" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH="$data" \ + ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE="$ORCA_TERMINAL_HANDLE"} \ + ${ORCA_PANE_KEY:+ORCA_PANE_KEY="$ORCA_PANE_KEY"} \ + ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN="$ORCA_AGENT_LAUNCH_TOKEN"} \ + ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID="$ORCA_AGENT_SESSION_ID"} \ + timeout 15 "$node" "$cli" sender --json 2>/dev/null || true)" +device="$(jq -r '.result.sender.deviceId // empty' <<<"$answer" 2>/dev/null || true)" +if [ -z "$device" ] || [ ! -s "$DIR/devices.json" ]; then + if [ -n "${ORCA_GIT_AS:-}" ]; then + echo "orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them." >&2 + exit 4 + fi + exit 3 +fi +member="$(jq -r --arg d "$device" '.[$d] // empty' "$DIR/devices.json")" +if [ -z "$member" ]; then + [ -n "${ORCA_GIT_AS:-}" ] && { echo "orca-git-as: the sender's device is not linked to a workspace member; refusing." >&2; exit 4; } + exit 3 +fi +if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$member" ]; then + echo "orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else." >&2 + exit 4 +fi +file="$DIR/$(printf '%s' "$member" | tr ':' '_').gitconfig" +[ -s "$file" ] || exit 3 +# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as). +out="$(sudo -u "$caller" mktemp)" +cat "$file" >"$out" +echo "$out" diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members index 216e3991564..6ec2b880a95 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members @@ -1,14 +1,22 @@ #!/usr/bin/env bash -# Writes one git config per workspace member for `orca-git-as`. No token ever lands here: each file -# carries the member's egress placeholder (swapped for their GitHub token by the control plane's -# egress proxy, for this workspace's repository only) and their GitHub author identity. -# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization}]. Prints {"members":}. +# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`: +# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity +# /etc/orca/members/devices.json {"": ""} (each member's paired devices) +# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a +# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad +# attests it. No token lives here: the placeholder is swapped at egress, for this repository only. +# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}] +# The VM user agents run as is orcad's own user (detected). Prints {"members":,"devices":}. set -euo pipefail umask 077 -DIR="$HOME/.orca-sandbox/members" -mkdir -p "$DIR" +DIR=/etc/orca/members +orcad_pid="$(pgrep -f orcad-server.js | head -n 1 || true)" +USER_NAME="$( [ -n "$orcad_pid" ] && ps -o user= -p "$orcad_pid" | tr -d ' ' || true)" +USER_NAME="${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}" +case "$USER_NAME" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac +mkdir -p /etc/orca json="$(printf '%s' "${ORCA_MEMBERS_B64:-W10=}" | base64 -d)" -tmp="$(mktemp -d "$DIR.XXXXXX")" +tmp="$(mktemp -d /etc/orca/members.XXXXXX)" count=0 while IFS= read -r row; do user="$(jq -r '.userId' <<<"$row")" @@ -21,8 +29,33 @@ while IFS= read -r row; do git config -f "$file" user.email "$(jq -r '.email' <<<"$row")" count=$((count + 1)) done < <(jq -c '.[]' <<<"$json") +jq -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" +devices="$(jq 'length' "$tmp/devices.json")" +chmod 0700 "$tmp" && chmod 0600 "$tmp"/* rm -rf "$DIR.old" [ -d "$DIR" ] && mv "$DIR" "$DIR.old" mv "$tmp" "$DIR" rm -rf "$DIR.old" -echo "{\"members\":$count}" +# Agents may ask for their own sender's identity, and only that (the helper checks with orcad). +rule="$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity" +printf '%s\n' "$rule" >/etc/sudoers.d/orca-git-identity.new +chmod 0440 /etc/sudoers.d/orca-git-identity.new +if visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then + mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity +else + rm -f /etc/sudoers.d/orca-git-identity.new + echo 'sudoers rule rejected' >&2 + exit 1 +fi +# Pre-attestation layout (agent-readable member files) must not linger. +user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)" +[ -n "$orcad_pid" ] && user_home="$(tr '\0' '\n' <"/proc/$orcad_pid/environ" | sed -n 's/^HOME=//p' | head -n 1)" +[ -n "$user_home" ] && rm -rf "$user_home/.orca-sandbox/members" +# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default). +if [ -n "$user_home" ]; then + sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email >/dev/null 2>&1 \ + || sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email 'cloud@users.noreply.onorca.dev' + sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name >/dev/null 2>&1 \ + || sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name 'Orca Cloud' +fi +echo "{\"members\":$count,\"devices\":$devices}" diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index 79fbae8e2f8..e664749cd83 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -78,6 +78,9 @@ if [ -n "${ORCA_GIT_EXTRAHEADER:-}" ]; then # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token. git config --global http.https://github.com/.extraheader "$ORCA_GIT_EXTRAHEADER" fi +# Commits outside a teammate's turn (or before any member connected GitHub) need an author too. +git config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev' +git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud' # First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both. clone_pid='' if [ ! -d "$PROJECT" ]; then diff --git a/cloud/apps/sandbox-control/migrations/0031_member_sends.sql b/cloud/apps/sandbox-control/migrations/0031_member_sends.sql new file mode 100644 index 00000000000..f74f03f8bfb --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0031_member_sends.sql @@ -0,0 +1,10 @@ +-- When each member last sent a message to a shared workspace, reported by the member's own +-- signed-in client (their Orca token, not the VM). The egress proxy honors a member's GitHub +-- identity only within a short window after this, so nothing inside the VM can push as a member +-- who is not actively driving the workspace. +CREATE TABLE workspace_member_sends ( + sandbox_id TEXT NOT NULL, + user_id TEXT NOT NULL, + sent_at INTEGER NOT NULL, + PRIMARY KEY (sandbox_id, user_id) +); diff --git a/cloud/apps/sandbox-control/migrations/0032_egress_user_hosts.sql b/cloud/apps/sandbox-control/migrations/0032_egress_user_hosts.sql new file mode 100644 index 00000000000..89cc3a8702e --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0032_egress_user_hosts.sql @@ -0,0 +1,4 @@ +-- Hosts the workspace's own agent tools need (remote MCP servers synced from the desktop), added to +-- the egress allowlist on every boot (comma list). Set by PUT /v1/sandboxes/:id/egress/hosts; unlike +-- egress_allow_hosts it is not recomputed from secrets. +ALTER TABLE sandboxes ADD COLUMN egress_user_hosts TEXT; diff --git a/cloud/apps/sandbox-control/migrations/0033_environment_build_usage.sql b/cloud/apps/sandbox-control/migrations/0033_environment_build_usage.sql new file mode 100644 index 00000000000..c7180bf49c8 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0033_environment_build_usage.sql @@ -0,0 +1,5 @@ +-- Build VMs are metered like workspaces: one usage segment per finished build (createdAt..finishedAt, +-- the build's sandbox size), attributed to the member who started it. Null until billing accepted it; +-- the cron retries unreported builds. +ALTER TABLE environment_builds ADD COLUMN usage_reported_at INTEGER; +CREATE INDEX environment_builds_unreported ON environment_builds (usage_reported_at, finished_at); diff --git a/cloud/apps/sandbox-control/src/auth.ts b/cloud/apps/sandbox-control/src/auth.ts index 3f78684e01b..ba55a585438 100644 --- a/cloud/apps/sandbox-control/src/auth.ts +++ b/cloud/apps/sandbox-control/src/auth.ts @@ -24,6 +24,8 @@ const ClaimsSchema = z.object({ orgRole: z.enum(['owner', 'admin', 'member']).optional(), /** Same role as Orca Cloud auth spells it in its tokens (`org_role`); either is accepted. */ org_role: z.enum(['owner', 'admin', 'member']).optional(), + /** Display name (auth sanitizes it, ≤80 chars). Untrusted text: label only, never identity. */ + name: z.string().max(200).optional(), purpose: z.literal('sandbox') }) @@ -37,6 +39,14 @@ export type SandboxCaller = { dev?: boolean /** Set when a companion device (phone) signed this request with its own enrolled key. */ deviceSessionId?: string + /** Display name from the token, for labels next to the user id; never used for access. */ + name?: string +} + +/** One line of plain text, ≤80 chars; anything else is dropped rather than trusted. */ +function displayName(value: string | undefined): string | undefined { + const clean = value?.replace(/[\u0000-\u001f\u007f"\\]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 80) + return clean || undefined } const keySets = new Map() @@ -86,6 +96,7 @@ async function verify( return { userId: claims.sub, accountId: accountIdFor(claims), + ...(displayName(claims.name) ? { name: displayName(claims.name) } : {}), ...(claims.org ? { orgId: claims.org, ...((claims.orgRole ?? claims.org_role) ? { orgRole: claims.orgRole ?? claims.org_role } : {}) } : {}) } } catch { diff --git a/cloud/apps/sandbox-control/src/egress-hosts.ts b/cloud/apps/sandbox-control/src/egress-hosts.ts new file mode 100644 index 00000000000..7fb5201a181 --- /dev/null +++ b/cloud/apps/sandbox-control/src/egress-hosts.ts @@ -0,0 +1,55 @@ +// Hosts a workspace's own agent tools need beyond the default allowlist — today the remote MCP +// servers the desktop syncs into the sandbox (MCP config sync). The desktop declares them with +// PUT /v1/sandboxes/:id/egress/hosts {hosts}; they persist on the row (every boot re-applies them) +// and a running sandbox's policy is rewritten at once. Public hostnames only: no wildcards, IPs, +// localhost or private suffixes, so the fail-closed allowlist can't be turned into "open". +import { z } from 'zod' +import { egressPolicy, refreshGitCredentials, type LifecycleDeps } from './lifecycle' +import { transition, type SandboxRow } from './store' + +export const MAX_USER_HOSTS = 32 +const HOST = /^([a-z0-9-]+\.)+[a-z]{2,63}$/ +const PRIVATE_SUFFIXES = ['.local', '.localhost', '.internal', '.lan', '.home', '.corp', '.intranet'] + +export const EgressHostsSchema = z + .object({ hosts: z.array(z.string().min(1).max(253)).max(MAX_USER_HOSTS) }) + .strict() + +/** Normalized, deduplicated, sorted; null when any entry is not an acceptable public hostname. */ +export function normalizeUserHosts(hosts: readonly string[]): string[] | null { + const out = new Set() + for (const raw of hosts) { + const host = raw.trim().toLowerCase().replace(/\.$/, '') + if (!HOST.test(host) || PRIVATE_SUFFIXES.some((suffix) => host.endsWith(suffix))) { + return null + } + out.add(host) + } + return [...out].sort() +} + +export function egressUserHosts(row: Pick): string[] { + return (row.egress_user_hosts ?? '').split(',').filter(Boolean) +} + +/** Records the hosts and, for a running sandbox, rewrites its policy now. */ +export async function setEgressUserHosts(deps: LifecycleDeps, row: SandboxRow, hosts: string[]): Promise { + const value = hosts.join(',') || null + if (value === row.egress_user_hosts) { + return row + } + const next = await transition(deps.db, row, { egress_user_hosts: value }, deps.now()) + if (!next) { + return null + } + if (next.status === 'running' && next.session_id) { + // A policy write replaces the whole policy, so the git route is re-minted alongside. + const git = await refreshGitCredentials(deps, next, next.session_id) + if (!git) { + await deps.provider.updateNetworkPolicy(next.session_id, egressPolicy(deps, next)) + } + } + // Counts only; hostnames are not secrets but stay out of logs anyway (they can name private tools). + console.log(JSON.stringify({ event: 'egress_user_hosts_set', sandboxId: row.id, count: hosts.length })) + return next +} diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index fef8b9fac5f..f6a6822b001 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -20,6 +20,8 @@ export type Env = { GOLDEN_SNAPSHOT_OVERRIDE?: string /** Git as the sender: `on`, `accounts:,` or off (default). See memberGitEnabled in index.ts. */ MEMBER_GIT_IDENTITY?: string + /** How long after a member's own send their GitHub identity stays usable (default 30). */ + MEMBER_GIT_WINDOW_MINUTES?: string /** `release:latest` | `release:v1.2.3`: build golden images from Orca's released orca-server tarball. */ GOLDEN_IMAGE_SOURCE?: string /** TTL for Worker-built golden images; unset/0 keeps them until rotated out. */ diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index a1279699d8a..9e993a9016f 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -32,6 +32,8 @@ const STARTING_STUCK_MS = 5 * 60_000 const SNAPSHOTTING_STUCK_MS = 3 * 60_000 /** A secret value shorter than this is not redacted from logs (too likely to match ordinary text). */ const MIN_REDACTED_SECRET = 6 +/** Event-stream keepalive; desktop watchers treat ~90 s of silence as a dead connection. */ +const HEARTBEAT_MS = 20_000 /** Succeeded builds whose snapshot is kept (rollback window); older ones keep their record and log. */ export const KEPT_BUILDS = 5 const MAX_LOG_BYTES = 2 * 1024 * 1024 @@ -75,6 +77,8 @@ export type BuildRow = { updated_at: number generation: number snapshot_deleted_at: number | null + /** When billing accepted this build's VM time (null: not yet). */ + usage_reported_at: number | null } export type BuildConfig = { @@ -457,6 +461,7 @@ async function completeBuild(deps: BuildDeps, row: BuildRow, snapshotId: string) // Ours to delete only when this pass is the one that failed the build. await deps.provider.deleteSnapshot(snapshotId).catch(() => undefined) log('environment_build_failed', { buildId: row.id, number: row.number, step: 'snapshot', error: 'smoke_failed' }) + await reportBuildUsage(deps, failed) return failed } return (await getBuild(deps.db, row.environment_id, row.id)) ?? row @@ -485,6 +490,7 @@ async function completeBuild(deps: BuildDeps, row: BuildRow, snapshotId: string) log('environment_build_prune_failed', { buildId: row.id, error: String(error).slice(0, 200) }) ) log('environment_build_succeeded', { buildId: row.id, number: row.number, ms: now - row.created_at, snapshotId }) + await reportBuildUsage(deps, done) return done } @@ -570,6 +576,7 @@ async function failBuild(deps: BuildDeps, row: BuildRow, step: string, error: st } await deps.provider.deleteSandbox(row.provider_name).catch(() => undefined) log('environment_build_failed', { buildId: row.id, number: row.number, step, error }) + await reportBuildUsage(deps, failed) } return failed ?? (await getBuild(deps.db, row.environment_id, row.id)) } @@ -590,6 +597,7 @@ export async function cancelBuild(deps: BuildDeps, caller: SandboxCaller, row: B await storeLogs(deps, canceled, { live: true }).catch(() => undefined) await deps.provider.deleteSandbox(row.provider_name).catch(() => undefined) log('environment_build_canceled', { buildId: row.id }) + await reportBuildUsage(deps, canceled) return (await getBuild(deps.db, row.environment_id, row.id)) ?? canceled } @@ -692,12 +700,61 @@ export async function storedLogs(db: D1Database, buildId: string): Promise r.data).join('') } +/** + * A build ran a sandbox from its creation to its end (including the smoke boot): bill that time like + * a workspace's, at the build's sandbox size, to the member who started it. Idempotent per build + * (`build:`); a billing outage leaves it for the cron. + */ +export async function reportBuildUsage(deps: Pick, row: BuildRow): Promise { + if (row.usage_reported_at !== null || row.finished_at === null || !TERMINAL.has(row.status)) { + return false + } + // A build that never got a VM (refused before boot) used nothing. + const startedAt = row.created_at + const endedAt = Math.max(row.finished_at, startedAt) + if (!row.session_id && row.status !== 'succeeded') { + await deps.db.prepare('UPDATE environment_builds SET usage_reported_at = ? WHERE id = ?').bind(deps.now(), row.id).run() + return false + } + let machineSize: MachineSize = 'standard' + try { + machineSize = parseConfig(row).machineSize ?? 'standard' + } catch { + machineSize = 'standard' + } + try { + await deps.entitlements.reportUsage({ + usageId: `build:${row.id}`, + accountId: row.account_id, + sandboxId: row.id, + machineSize, + startedAt, + endedAt, + userId: row.created_by + }) + } catch (error) { + log('environment_build_usage_failed', { buildId: row.id, error: String(error).slice(0, 120) }) + return false + } + await deps.db.prepare('UPDATE environment_builds SET usage_reported_at = ? WHERE id = ?').bind(deps.now(), row.id).run() + return true +} + /** Cron: advance every unfinished build (finalize the ones nobody is watching). */ export async function advanceAllBuilds(deps: BuildDeps): Promise { const { results } = await deps.db .prepare(`SELECT * FROM environment_builds WHERE status IN ('starting', 'running', 'snapshotting') ORDER BY updated_at LIMIT 20`) .all() let moved = 0 + const { results: unbilled } = await deps.db + .prepare( + `SELECT * FROM environment_builds WHERE usage_reported_at IS NULL AND finished_at IS NOT NULL + AND status IN ('succeeded', 'failed', 'canceled') ORDER BY finished_at LIMIT 20` + ) + .all() + for (const row of unbilled) { + await reportBuildUsage(deps, row) + } for (const row of results) { try { const next = await advanceBuild(deps, row) @@ -726,6 +783,11 @@ export function streamBuildEvents( const { readable, writable } = new TransformStream() const writer = writable.getWriter() const send = (event: unknown) => writer.write(encoder.encode(`${JSON.stringify(event)}\n`)) + // A quiet step (snapshot, a long compile) prints nothing for minutes: a heartbeat tells watchers the + // stream is alive so they don't reconnect (and replay the whole log) for nothing. + const heartbeat = setInterval(() => { + send({ type: 'heartbeat', at: deps.now() }).catch(() => clearInterval(heartbeat)) + }, HEARTBEAT_MS) const run = async () => { let row = initial await send({ type: 'build', build: await view(row) }) @@ -809,7 +871,10 @@ export function streamBuildEvents( log('environment_build_stream_failed', { buildId: initial.id, error: String(error).slice(0, 200) }) return send({ type: 'error', error: 'stream_failed' }).catch(() => undefined) }) - .finally(() => writer.close().catch(() => undefined)) + .finally(() => { + clearInterval(heartbeat) + return writer.close().catch(() => undefined) + }) return readable } diff --git a/cloud/apps/sandbox-control/src/golden-images.ts b/cloud/apps/sandbox-control/src/golden-images.ts index 34b0462cd22..6aca5e966d1 100644 --- a/cloud/apps/sandbox-control/src/golden-images.ts +++ b/cloud/apps/sandbox-control/src/golden-images.ts @@ -314,6 +314,30 @@ async function stepBuild(deps: GoldenImageDeps, row: GoldenRow): Promise from VM_SCRIPT_SOURCES (same bytes a release build installs). */ +/** Stable fingerprint of the control plane's VM entry points (FNV-1a over names and bytes). */ +export function entryPointsVersion(): string { + let hash = 0x811c9dc5 + for (const name of VM_SCRIPTS) { + for (const char of `${name}\u0000${VM_SCRIPT_SOURCES[name]}\u0000`) { + hash = Math.imul(hash ^ char.charCodeAt(0), 0x01000193) >>> 0 + } + } + return hash.toString(16).padStart(8, '0') +} + +/** + * Sandboxes booted from an older image get the control plane's current entry points (grant, revoke, + * member identities, sender-aware git) once per boot: a marker check, and an install only if stale. + */ +export async function ensureEntryPoints(deps: { provider: Pick }, sessionId: string): Promise { + const probe = await deps.provider + .runCommand(sessionId, { command: 'test', args: ['-e', `/opt/orca/bin/.entry-points-${entryPointsVersion()}`], timeoutMs: 15_000 }) + .catch(() => null) + if (probe?.exitCode !== 0) { + await installEntryPoints(deps, sessionId) + } +} + export async function installEntryPoints(deps: { provider: Pick }, sessionId: string): Promise { const env = provisionEnv({ manifest: MANIFEST, provisionScript: PROVISION_SCRIPT, vmScripts: VM_SCRIPT_SOURCES, buildId: 'sync' }) const scriptEnv = Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith('ORCA_VM_SCRIPT_'))) @@ -325,6 +349,8 @@ export async function installEntryPoints(deps: { provider: Pick Promise ): Promise { - const first = await run().catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: String(error) })) - if (first.exitCode === 0) { - return first - } - const probe = await deps.provider.runCommand(sessionId, { command: 'test', args: ['-x', command], timeoutMs: 15_000 }).catch(() => null) - if (!probe || probe.exitCode === 0) { - return first - } - await installEntryPoints(deps, sessionId) + // Stale or missing scripts from an older image are replaced first (one marker check when current). + await ensureEntryPoints(deps, sessionId).catch(() => undefined) + void command return run() } @@ -275,17 +269,17 @@ export function revokeGrantsForDeviceSession(deps: LifecycleDeps, deviceSessionI * The creator's desktop pairs with the create's own offer; record that device (its id is in the * offer, not secret) so reassigning the workspace or removing the member revokes it like any grant. */ -export async function recordOwnerDevice(db: D1Database, row: SandboxRow, pairingCode: string, now: number): Promise { +export async function recordOwnerDevice(db: D1Database, row: SandboxRow, pairingCode: string, now: number): Promise { const deviceId = pairedDeviceIdOf(pairingCode) if (!deviceId) { - return + return false } const existing = await db .prepare('SELECT id FROM workspace_grants WHERE sandbox_id = ? AND orcad_device_id = ?') .bind(row.id, deviceId) .first<{ id: string }>() if (existing) { - return + return false } await db .prepare( @@ -294,6 +288,14 @@ export async function recordOwnerDevice(db: D1Database, row: SandboxRow, pairing ) .bind(randomGrantId(), row.id, row.account_id, row.user_id, deviceId, now) .run() + return true +} + +/** Records the owner's device and, when it is new, lets the VM map it to the owner (git as the sender). */ +export async function recordOwnerDeviceAndSync(deps: LifecycleDeps, row: SandboxRow, pairingCode: string): Promise { + if ((await recordOwnerDevice(deps.db, row, pairingCode, deps.now())) && row.status === 'running' && row.session_id) { + await syncMemberGit(deps, row, row.session_id) + } } export function pairedDeviceIdOf(pairingCode: string): string | null { diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 28c2f13fcb6..3caf271cbe2 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -30,6 +30,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 { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' import { maintainPool, poolConfigFromEnv } from './pool' import { authenticateDesktop } from './auth' @@ -84,6 +85,7 @@ import { reconcile } from './reconcile' import { egressSecretHosts, secretPlaceholder } from './secret-egress' import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' +import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts' import { cachedProviderEnv } from './session-env' import { credentialTargets } from './provider-env' import type { Keyring } from './secrets-crypto' @@ -114,7 +116,7 @@ import { GrantRequestSchema, issueGrant, listGrants, - recordOwnerDevice, + recordOwnerDeviceAndSync, revokeForAccessChange, revokeGrantsForDeviceSession, revokeGrantsForMember, @@ -130,7 +132,7 @@ import { storeUserToken, userAuthorizeUrl } from './github-user-tokens' -import { memberGitRoutes } from './member-git' +import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git' import { PatchSchema, PresenceSchema, @@ -216,8 +218,10 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => db: env.SANDBOX_DB, identity: async (row, userId) => { const keyring = keyringFor(env) - return keyring && memberGit(row.account_id) - ? memberGitIdentity(env.SANDBOX_DB, await keyring, githubConnect(env, deps), row.account_id, userId, (deps.now ?? Date.now)()) + const now = (deps.now ?? Date.now)() + // Only while the member is actively driving this workspace (their own client reported a send). + return keyring && memberGit(row.account_id) && (await memberSentWithin(env.SANDBOX_DB, row.id, userId, now, memberGitWindowMs(env))) + ? memberGitIdentity(env.SANDBOX_DB, await keyring, githubConnect(env, deps), row.account_id, userId, now) : null } }) @@ -587,18 +591,28 @@ export function egressPlaceholderMode(value: string | undefined): boolean | Read } /** - * Git as the sender is opt-in (MEMBER_GIT_IDENTITY = on | accounts:,; default off): members - * of a shared workspace share one VM user and the sender id is not yet stamped by orcad, so a member - * could push as another member of the same workspace (to that repository only). Off = app identity. + * Git as the sender (MEMBER_GIT_IDENTITY: unset = on for every account, `off`, `on`, or + * `accounts:,`). orcad attests which paired device sent each turn and the root-only + * orca-git-identity hands an agent only that member's identity. Residual risk: members share the VM + * user, so a member with a shell could subvert orcad itself; agents and prompts cannot. */ +function memberGitWindowMs(env: Env): number { + const minutes = Number(env.MEMBER_GIT_WINDOW_MINUTES) + return Number.isFinite(minutes) && minutes > 0 ? minutes * 60_000 : MEMBER_GIT_WINDOW_MS +} + export function memberGitEnabled(env: Env): (accountId: string) => boolean { + // On by default: orcad attests each turn's sender and orca-git-identity refuses any other member. + if (env.MEMBER_GIT_IDENTITY === undefined || env.MEMBER_GIT_IDENTITY.trim() === '') { + return () => true + } const mode = egressPlaceholderMode(env.MEMBER_GIT_IDENTITY) return (accountId) => mode === true || (mode instanceof Set && mode.has(accountId)) } async function memberIdentityFor(env: Env, deps: Deps): Promise { const keyring = keyringFor(env) - if (!keyring || env.MEMBER_GIT_IDENTITY === undefined || env.MEMBER_GIT_IDENTITY === 'off') { + if (!keyring || env.MEMBER_GIT_IDENTITY === 'off') { return undefined } const enabled = memberGitEnabled(env) @@ -751,6 +765,10 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) })) ?? fail('not_found', 404) ) } + if (url.pathname === '/v1/config' && request.method === 'GET') { + // Public product constants (no auth): every client reads these instead of hardcoding them. + return json({ idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES }) + } if (url.pathname === '/v1/github/dev-connect' && env.SANDBOX_ENV !== 'prod') { // Dev-only, link-shareable start of the user flow: mints a fresh 10-min state per click for a dev: // account (desktop builds call POST /v1/github/connect instead). @@ -967,7 +985,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) return await workspaceRoute(request, url, env, deps, caller) } const match = - /^\/v1\/sandboxes(?:\/([A-Za-z0-9_]+)(?:\/(suspend|resume|lease|rollover|wake|restart|status|archive|unarchive|env\/refresh|ssh-keys|desktop))?)?$/.exec( + /^\/v1\/sandboxes(?:\/([A-Za-z0-9_]+)(?:\/(suspend|resume|lease|rollover|wake|restart|status|archive|unarchive|env\/refresh|egress\/hosts|ssh-keys|desktop))?)?$/.exec( url.pathname ) if (!match) { @@ -1001,7 +1019,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) return fail('invalid_request', 400) } const ready = await createSandbox(life, caller, body.data) - await recordOwnerDevice(life.db, ready.row, ready.connection.pairingCode, life.now()) + await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode) return readyResponse(ready) } const row = await getSandbox(env.SANDBOX_DB, id) @@ -1034,12 +1052,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) return json({ sandbox: view(await suspendSandbox(life, row)) }) case 'POST resume': { const ready = await resumeSandbox(life, row) - await recordOwnerDevice(life.db, ready.row, ready.connection.pairingCode, life.now()) + await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode) return readyResponse(ready) } case 'POST rollover': { const ready = await rolloverSandbox(life, row) - await recordOwnerDevice(life.db, ready.row, ready.connection.pairingCode, life.now()) + await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode) return readyResponse(ready) } case 'POST wake': @@ -1048,7 +1066,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) // User-triggered and unbounded otherwise: shares the per-account start rate limit. await consumeCreateToken(life.db, life.config.guardrails!, caller.accountId, life.now()) const ready = await restartSandbox(life, row) - await recordOwnerDevice(life.db, ready.row, ready.connection.pairingCode, life.now()) + await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode) return json(readyView(ready.row, ready.connection)) } case 'GET status': @@ -1068,6 +1086,20 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) } case 'POST env/refresh': return json({ applied: await refreshSandboxEnv(life, row) }) + case 'GET egress/hosts': + return json({ hosts: egressUserHosts(row) }) + case 'PUT egress/hosts': { + const body = EgressHostsSchema.safeParse(await readJson(request)) + const hosts = body.success ? normalizeUserHosts(body.data.hosts) : null + if (!hosts) { + return fail('invalid_request', 400, 'invalid_host') + } + const next = await setEgressUserHosts(life, row, hosts) + if (!next) { + return fail('conflict', 409, 'concurrent_transition') + } + return json({ hosts: egressUserHosts(next) }) + } case 'POST desktop': { // Runs only the image's fixed entry point; the desktop listens on the VM's loopback and is // reached through the paired runtime's port forward, never a public route. @@ -1153,7 +1185,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)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) + const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) if (!match) { return fail('not_found', 404) } @@ -1164,6 +1196,14 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, if (route === 'GET ') { return json({ workspace: await view() }) } + 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)) { + throw new WorkspaceError('not_found') + } + await recordMemberSend(db, row.id, caller.userId, now) + return json({ ok: true }) + } if (route === 'POST presence') { const body = PresenceSchema.safeParse(await readJson(request)) if (!body.success) { diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 2749dbe6618..bdcb5ac41cc 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -12,6 +12,7 @@ import { } from './guardrails' import { DEFAULT_EGRESS_ALLOWLIST, compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute } from './network-policy' import { applyQueuedRevokes } from './grant-revokes' +import { ensureEntryPoints } from './golden-images' import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' import { connectedMembers, memberGitConfigs } from './member-git' import type { RetentionConfig } from './retention' @@ -300,7 +301,7 @@ async function boot( // Nothing in the VM uses git or model keys before orcad answers and the desktop attaches. const needsPolicy = !options.policyApplied && - (git || routed.egress_secret_hosts || row.egress_secret_hosts || routed.egress_allow_hosts || row.egress_allow_hosts) + (git || routed.egress_secret_hosts || row.egress_secret_hosts || routed.egress_allow_hosts || row.egress_allow_hosts || row.egress_user_hosts) // Members revoked while the VM slept must be gone before orcad accepts its first sign-in. await applyQueuedRevokes(deps.db, deps.provider, row.id, state.session.id, deps.now()) const [, connection] = await Promise.all([ @@ -382,10 +383,11 @@ export async function syncMemberGit(deps: LifecycleDeps, row: SandboxRow, sessio return 0 } try { + await ensureEntryPoints(deps, sessionId) await refreshGitCredentials(deps, row, sessionId) const configs = await memberGitConfigs({ db: deps.db, identity: deps.memberIdentity }, row) const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(configs)))) - await deps.provider.runCommand(sessionId, { command: MEMBERS_COMMAND, env: { ORCA_MEMBERS_B64: encoded }, timeoutMs: 30_000 }) + await deps.provider.runCommand(sessionId, { command: MEMBERS_COMMAND, env: { ORCA_MEMBERS_B64: encoded }, sudo: true, timeoutMs: 30_000 }) return configs.length } catch { return 0 diff --git a/cloud/apps/sandbox-control/src/member-git.ts b/cloud/apps/sandbox-control/src/member-git.ts index b756b97c718..87ff1518e49 100644 --- a/cloud/apps/sandbox-control/src/member-git.ts +++ b/cloud/apps/sandbox-control/src/member-git.ts @@ -2,15 +2,38 @@ // grant) who connected GitHub gets a placeholder of their own. The VM's `orca-git-as ` sends // it; the egress proxy swaps it for that member's GitHub user token, and only for the workspace // repository (git smart HTTP on github.com, REST under /repos// on api.github.com). -// Trust note: members of a shared workspace share one VM user, so a member can push as another -// member of the same workspace to the same repository; tokens never enter the VM and cannot be -// used for any other repository or API. +// Who may use which identity is decided in the VM by orcad's attestation: orca-git-identity (root) +// maps the paired device that sent the agent's latest turn to a member and refuses any other member; +// member files are root-only. Tokens never enter the VM and work for this repository only. Residual +// risk: members share the VM user, so a member with a shell could subvert orcad itself. import type { ProxiedRoute } from './egress-proxy' import { parseGitHubRepo } from './github-app' import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens' import { gitBasicAuthorization } from './network-policy' import type { SandboxRow } from './store' +/** A member's GitHub identity works only this long after they themselves sent a message (default). */ +export const MEMBER_GIT_WINDOW_MS = 30 * 60_000 + +/** Their own client reports each send (their Orca token): the window cannot be opened from the VM. */ +export async function recordMemberSend(db: D1Database, sandboxId: string, userId: string, now: number): Promise { + await db + .prepare( + `INSERT INTO workspace_member_sends (sandbox_id, user_id, sent_at) VALUES (?, ?, ?) + ON CONFLICT (sandbox_id, user_id) DO UPDATE SET sent_at = excluded.sent_at` + ) + .bind(sandboxId, userId, now) + .run() +} + +export async function memberSentWithin(db: D1Database, sandboxId: string, userId: string, now: number, windowMs: number): Promise { + const row = await db + .prepare('SELECT sent_at FROM workspace_member_sends WHERE sandbox_id = ? AND user_id = ?') + .bind(sandboxId, userId) + .first<{ sent_at: number }>() + return row !== null && now - row.sent_at <= windowMs +} + export type MemberGitDeps = { db: D1Database identity: (row: SandboxRow, userId: string) => Promise @@ -86,7 +109,7 @@ export function memberGitRoutes(deps: MemberGitDeps) { /** What the VM writes per member for `orca-git-as` (no token: the placeholder and author identity). */ export async function memberGitConfigs(deps: MemberGitDeps, row: SandboxRow) { - const out: { userId: string; name: string; email: string; authorization: string }[] = [] + const out: { userId: string; name: string; email: string; authorization: string; deviceIds: string[] }[] = [] for (const userId of await connectedMembers(deps.db, row)) { const identity = await deps.identity(row, userId) if (identity) { @@ -94,9 +117,21 @@ export async function memberGitConfigs(deps: MemberGitDeps, row: SandboxRow) { userId, name: identity.name, email: identity.email, - authorization: gitBasicAuthorization(await memberPlaceholder(row.id, userId)) + authorization: gitBasicAuthorization(await memberPlaceholder(row.id, userId)), + // The member's paired orcad devices: orca-git-identity maps orcad's attested sender to a member. + deviceIds: await memberDeviceIds(deps.db, row.id, userId) }) } } return out } + +async function memberDeviceIds(db: D1Database, sandboxId: string, userId: string): Promise { + const { results } = await db + .prepare( + `SELECT orcad_device_id FROM workspace_grants WHERE sandbox_id = ? AND user_id = ? AND status = 'active' AND orcad_device_id IS NOT NULL` + ) + .bind(sandboxId, userId) + .all<{ orcad_device_id: string }>() + return results.map((r) => r.orcad_device_id) +} diff --git a/cloud/apps/sandbox-control/src/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index f704b4941b4..e039f8cd2b1 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -84,6 +84,7 @@ export async function sessionSecretEnv( return { env: swapped.env, egressSecretHosts: encodeEgressSecretHosts(swapped.targets), egressAllowHosts } } -export function egressAllowHosts(row: Pick): string[] { - return (row.egress_allow_hosts ?? '').split(',').filter(Boolean) +/** Provider hosts from the session's secrets plus the workspace's declared tool hosts (MCP). */ +export function egressAllowHosts(row: Pick & Partial>): string[] { + return [...(row.egress_allow_hosts ?? '').split(','), ...(row.egress_user_hosts ?? '').split(',')].filter(Boolean) } diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index e95ea8997d2..99d08aeda19 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -40,6 +40,8 @@ export type SandboxRow = { egress_secret_hosts: string | null /** Comma list of custom model-provider hosts added to this session's egress allowlist. */ egress_allow_hosts: string | null + /** Comma list of hosts the workspace's own tools need (synced remote MCP servers); set by the desktop. */ + egress_user_hosts: string | null retention_warned_at: number | null /** Environment build this sandbox first booted from (null: the golden image). Never changes. */ environment_id: string | null @@ -178,7 +180,7 @@ type Patch = Partial([ 'status', 'session_id', 'session_started_at', 'session_deadline_at', 'lease_expires_at', 'usage_settled_at', 'last_error', 'destroyed_at', 'github_token_expires_at', - 'egress_secret_hosts', 'egress_allow_hosts', 'repo_url', 'retention_warned_at', 'orcad_endpoint', 'ready_at', + 'egress_secret_hosts', 'egress_allow_hosts', 'egress_user_hosts', 'repo_url', 'retention_warned_at', 'orcad_endpoint', 'ready_at', 'archived_at', 'archive_expires_at' ]) diff --git a/cloud/apps/sandbox-control/test/agent-providers.test.ts b/cloud/apps/sandbox-control/test/agent-providers.test.ts index 32ef3849816..f564e04c6b1 100644 --- a/cloud/apps/sandbox-control/test/agent-providers.test.ts +++ b/cloud/apps/sandbox-control/test/agent-providers.test.ts @@ -327,3 +327,27 @@ describe('staged egress placeholder rollout', () => { expect(row!.egress_secret_hosts).toBe('ANTHROPIC_AUTH_TOKEN@llm.example.com') }) }) + +describe('workspace tool hosts (synced remote MCP servers)', () => { + it('opens declared hosts on the running sandbox now and on every later boot; refuses wildcards and private names', async () => { + const { h, as } = await setup() + const mia = await as('mia') + const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + const box = () => [...h.vercel.boxes.values()][0]! + expect(box().policy.allow['mcp.linear.app']).toBeUndefined() + const put = await h.call('PUT', `/v1/sandboxes/${id}/egress/hosts`, { bearer: mia, body: { hosts: ['MCP.linear.app', 'mcp.notion.com.', 'mcp.linear.app'] } }) + expect(put.body).toEqual({ hosts: ['mcp.linear.app', 'mcp.notion.com'] }) + expect(box().policy.allow['mcp.linear.app']).toEqual([]) + expect(box().policy.allow['*']).toBeUndefined() + for (const bad of ['*', '*.example.com', '10.0.0.1', 'localhost', 'box.internal', 'http://x.example.com']) { + expect((await h.call('PUT', `/v1/sandboxes/${id}/egress/hosts`, { bearer: mia, body: { hosts: [bad] } })).status).toBe(400) + } + expect((await h.call('PUT', `/v1/sandboxes/${id}/egress/hosts`, { bearer: await as('bob'), body: { hosts: ['x.example.com'] } })).status).toBe(404) + // Sleep and wake: the hosts come back with the new session's policy. + await h.call('POST', `/v1/sandboxes/${id}/suspend`, { bearer: mia }) + await h.call('POST', `/v1/sandboxes/${id}/resume`, { bearer: mia }) + expect(box().policy.allow['mcp.notion.com']).toEqual([]) + expect((await h.call('GET', `/v1/sandboxes/${id}/egress/hosts`, { bearer: mia })).body).toEqual({ hosts: ['mcp.linear.app', 'mcp.notion.com'] }) + }) +}) diff --git a/cloud/apps/sandbox-control/test/config.test.ts b/cloud/apps/sandbox-control/test/config.test.ts new file mode 100644 index 00000000000..1d43a6d9da1 --- /dev/null +++ b/cloud/apps/sandbox-control/test/config.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { + HostedSandboxConfigResponseSchema, + ORCA_CLOUD_IDLE_SLEEP_MINUTES +} from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' +import { DEFAULT_PLANS } from '../../billing/src/plans' +import { createHarness } from './harness' + +describe('GET /v1/config', () => { + it('serves the idle-sleep minutes every client reads; billing advertises the same constant', async () => { + const h = await createHarness() + const res = await h.send(new Request('https://sandbox.test/v1/config')) + expect(res.status).toBe(200) + const body = HostedSandboxConfigResponseSchema.parse(await res.json()) + expect(body.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) + expect(DEFAULT_PLANS.team.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) + }) +}) diff --git a/cloud/apps/sandbox-control/test/environments.test.ts b/cloud/apps/sandbox-control/test/environments.test.ts index e202f382adf..a1b6c5beac7 100644 --- a/cloud/apps/sandbox-control/test/environments.test.ts +++ b/cloud/apps/sandbox-control/test/environments.test.ts @@ -93,6 +93,37 @@ describe('org environments', () => { expect([...h.vercel.boxes.keys()].filter((name) => name.includes('envbuild'))).toEqual([]) }) + it('bills build sandbox time to the member who started it, retrying when billing is down, and refuses blocked orgs', async () => { + const { h, adminCall, envId, build } = await setup() + await adminCall('PATCH', `/v1/environments/${envId}`, { machineSize: 'large' }) + h.billing.down = true + const first = await build(0) + expect(h.billing.usage).toEqual([]) + const unreported = h.raw.prepare('SELECT usage_reported_at FROM environment_builds WHERE id = ?').get(first.id) as { usage_reported_at: number | null } + expect(unreported.usage_reported_at).toBeNull() + h.billing.down = false + const { advanceAllBuilds } = await import('../src/environment-builds') + await advanceAllBuilds({ + db: h.env.SANDBOX_DB, + provider: h.vercel, + entitlements: { checkStart: async () => h.billing.decision, reportUsage: async (s) => { h.billing.usage.push(s); return h.billing.usageAnswer }, listSuspensions: async () => [] }, + now: h.now, + config: { environment: 'test', goldenSnapshotId: 'snap_golden', region: 'iad1' } + }) + expect(h.billing.usage).toEqual([ + expect.objectContaining({ usageId: `build:${first.id}`, sandboxId: first.id, machineSize: 'large', userId: 'alice', accountId: 'org:acme' }) + ]) + const failed = await build(20) + expect(h.billing.usage.at(-1)).toMatchObject({ usageId: `build:${failed.id}`, userId: 'alice' }) + const usage = h.billing.usage.at(-1)! + expect(usage.endedAt).toBeGreaterThan(usage.startedAt) + // Out of sandbox hours / payment failed: builds are refused like starts. + h.billing.decision = { allow: false, reason: 'hours_exhausted', suspendRunning: false } + const refused = await adminCall('POST', `/v1/environments/${envId}/builds`) + expect(refused.status).toBe(403) + expect(refused.body.reason).toBe('hours_exhausted') + }) + it('refuses a second concurrent build and can cancel one', async () => { const { adminCall, envId } = await setup() const started = await adminCall('POST', `/v1/environments/${envId}/builds`) diff --git a/cloud/apps/sandbox-control/test/member-git.test.ts b/cloud/apps/sandbox-control/test/member-git.test.ts index 293778eaf63..3db88cad416 100644 --- a/cloud/apps/sandbox-control/test/member-git.test.ts +++ b/cloud/apps/sandbox-control/test/member-git.test.ts @@ -12,7 +12,7 @@ const KEK = Buffer.alloc(32, 7).toString('base64') const OP = 'o'.repeat(40) const REPO = 'https://github.com/acme/app' -async function setup(memberGit: string | undefined = 'on') { +async function setup(memberGit: string | undefined = undefined) { const { privateKey, publicKey } = await generateKeyPair('RS256') const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid: 'v1', alg: 'RS256' }] } const upstream: { url: string; authorization: string | null }[] = [] @@ -37,11 +37,19 @@ async function setup(memberGit: string | undefined = 'on') { body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: REPO }, visibility: 'team' } }) const id: string = created.body.sandbox.id - const seed = (userId: string, login: string, githubUserId: number) => - h.call('POST', '/v1/internal/dev/member-github', { + const sent = async (userId: string) => + h.call('POST', `/v1/team/workspaces/${id}/sent`, { bearer: await as(userId) }) + // Connect GitHub, then (their own client) report a send so their identity window is open. + const seed = async (userId: string, login: string, githubUserId: number, send = true) => { + const stored = await h.call('POST', '/v1/internal/dev/member-github', { bearer: OP, body: { accountId: 'org:acme', userId, repoUrl: REPO, login, githubUserId, name: `${login} name` } }) + if (send) { + await sent(userId) + } + return stored + } async function oidc() { return new SignJWT({ team_id: 'team_orca', project_id: 'prj_orca', sandbox_id: 'sbx-v', sandbox_name: `orca-test-${id}` }) .setProtectedHeader({ alg: 'RS256', kid: 'v1' }) @@ -68,7 +76,7 @@ async function setup(memberGit: string | undefined = 'on') { ) return { status: response.status, body: await response.text() } } - return { h, id, as, seed, proxied, upstream } + return { h, id, as, seed, sent, proxied, upstream } } describe('git as the sender', () => { @@ -109,6 +117,10 @@ describe('git as the sender', () => { expect(githubRules).toContain(bobPh) const sync = t.h.vercel.commands.filter((c) => c.command === MEMBERS_COMMAND).at(-1)! const members = JSON.parse(Buffer.from(sync.env.ORCA_MEMBERS_B64!, 'base64').toString()) + // orca-git-identity maps orcad's attested sender device to the member (bob's grant device here). + expect(members.find((m: { userId: string }) => m.userId === 'bob').deviceIds).toEqual([ + [...t.h.vercel.boxes.values()][0]!.devices.at(-1) + ]) expect(members.map((m: { userId: string; email: string }) => [m.userId, m.email])).toEqual([ ['alice', '11+alice-gh@users.noreply.github.com'], ['bob', '22+bob-gh@users.noreply.github.com'] @@ -121,11 +133,26 @@ describe('git as the sender', () => { expect(await t.proxied('github.com', '/acme/app.git/info/refs', bobPh)).toEqual({ status: 403, body: 'placeholder_missing' }) }) - it('is off unless the org opted in: member placeholders get no credential, the VM no member configs', async () => { + it('MEMBER_GIT_IDENTITY=off turns it off: member placeholders get no credential, the VM no member configs', async () => { const t = await setup('off') await t.seed('alice', 'alice-gh', 11) const alicePh = await memberPlaceholder(t.id, 'alice') expect(await t.proxied('github.com', '/acme/app.git/git-receive-pack', gitBasicAuthorization(alicePh))).toEqual({ status: 403, body: 'credential_unavailable' }) expect(t.h.vercel.commands.some((c) => c.command === MEMBERS_COMMAND)).toBe(false) }) + + it('honors a member identity only within the window after their own client reported a send', async () => { + const t = await setup() + await t.seed('alice', 'alice-gh', 11, false) + const ph = gitBasicAuthorization(await memberPlaceholder(t.id, 'alice')) + // Connected, but never sent: nothing in the VM can use Alice's identity. + expect(await t.proxied('github.com', '/acme/app.git/git-receive-pack', ph)).toEqual({ status: 403, body: 'credential_unavailable' }) + await t.sent('alice') + expect((await t.proxied('github.com', '/acme/app.git/git-receive-pack', ph)).status).toBe(200) + t.h.advance(31 * 60_000) + expect(await t.proxied('github.com', '/acme/app.git/git-receive-pack', ph)).toEqual({ status: 403, body: 'credential_unavailable' }) + // A teammate cannot open Alice's window for her. + expect((await t.h.call('POST', `/v1/team/workspaces/${t.id}/sent`, { bearer: await t.as('bob') })).status).toBe(200) + expect(await t.proxied('github.com', '/acme/app.git/git-receive-pack', ph)).toEqual({ status: 403, body: 'credential_unavailable' }) + }) }) diff --git a/cloud/apps/sandbox-control/wrangler.dev.jsonc b/cloud/apps/sandbox-control/wrangler.dev.jsonc index 809aaf69f00..1a373b1f18d 100644 --- a/cloud/apps/sandbox-control/wrangler.dev.jsonc +++ b/cloud/apps/sandbox-control/wrangler.dev.jsonc @@ -38,8 +38,6 @@ // Golden image from image/build-golden-image.ts; lifecycle routes answer 503 without one. "GOLDEN_SNAPSHOT_ID": "snap_vpcmcCAgTtISiTZgsCosOlThQbFd", "GITHUB_APP_SLUG": "orca-cloud-dev", - "EGRESS_PROXY_URL": "https://orca-sandbox-control-dev.lovecast.workers.dev/v1/egress/proxy", - // Git as the sender is opt-in per org (see memberGitEnabled); dev: only the W4 rehearsal org. - "MEMBER_GIT_IDENTITY": "accounts:dev:org:w4org" + "EGRESS_PROXY_URL": "https://orca-sandbox-control-dev.lovecast.workers.dev/v1/egress/proxy" } } diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index 4222e7a5add..abfae50fd7f 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -264,5 +264,19 @@ "text": "text-[13px] leading-5", "dynamic": false, "count": 1 + }, + { + "filePath": "src/renderer/src/components/cloud-environment/cloud-environment-fixture-data.ts", + "kind": "object-property:error", + "text": "install_failed", + "dynamic": false, + "count": 1 + }, + { + "filePath": "src/renderer/src/components/cloud-environment/cloud-environment-fixture-data.ts", + "kind": "object-property:error", + "text": "canceled", + "dynamic": false, + "count": 1 } ] diff --git a/config/scripts/cloud-integration/premerge-check.sh b/config/scripts/cloud-integration/premerge-check.sh new file mode 100755 index 00000000000..5b683312d81 --- /dev/null +++ b/config/scripts/cloud-integration/premerge-check.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Gate for merging into cloud/integration (no CI on nwparker/orca-private): run from your branch's clone. +# Merges the current private/cloud/integration into a throwaway worktree with your branch, then requires +# typecheck, the full lint suite (pre-commit hooks only lint staged files) and the tests your branch changed. +set -euo pipefail +branch=$(git rev-parse --abbrev-ref HEAD) +git fetch -q private +cloud/integration:refs/remotes/private/cloud/integration +dir=$(mktemp -d "${TMPDIR:-/tmp}/cloud-premerge-XXXX") +trap 'git worktree remove --force "$dir" >/dev/null 2>&1 || true' EXIT +git worktree add -q --detach "$dir" HEAD +cd "$dir" +git merge -q --no-edit private/cloud/integration +pnpm install --frozen-lockfile >/dev/null +pnpm typecheck +pnpm lint +tests=$(git diff --name-only --diff-filter=AM private/cloud/integration...HEAD -- 'src/*.test.ts' 'src/*.test.tsx' | tr '\n' ' ') +if [[ -n "$tests" ]]; then + node config/scripts/native-build/node-addons/ensure-native-runtime.mjs --runtime=node >/dev/null + npx vitest run --config config/vitest.config.ts $tests +fi +for app in $(git diff --name-only private/cloud/integration...HEAD -- cloud/apps | cut -d/ -f1-3 | sort -u); do + (cd "$app" && npx vitest run) +done +echo "premerge OK: $branch merges cleanly into cloud/integration with typecheck, lint and tests green." diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 9cc19bf9f86..9fd4f3ead36 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -233,6 +233,17 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ keys: ['diagnostics memory', 'terminal-daemon status', 'terminal-daemon restart'], load: async () => (await import('./handlers/diagnostics.js')).DIAGNOSTICS_HANDLERS }, + { + name: 'cloud-env', + keys: [ + 'cloud env show', + 'cloud env set-install-script', + 'cloud env build', + 'cloud env builds', + 'cloud env logs' + ], + load: async () => (await import('./handlers/cloud-env.js')).CLOUD_ENV_HANDLERS + }, { name: 'speech', keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'], diff --git a/src/cli/handlers/cloud-env-format.ts b/src/cli/handlers/cloud-env-format.ts new file mode 100644 index 00000000000..6dab6f290e1 --- /dev/null +++ b/src/cli/handlers/cloud-env-format.ts @@ -0,0 +1,123 @@ +// Human-readable output for `orca cloud env ...`. +import type { + CloudEnvironmentBuildsData, + CloudEnvironmentShowData +} from '../../shared/hosted-sandbox/hosted-environment-cli-contract' +import type { HostedEnvironmentBuildView } from '../../shared/hosted-sandbox/hosted-environment-wire' + +export function formatOutcome(build: HostedEnvironmentBuildView): string { + if (build.status === 'succeeded') { + return `Build #${build.number} succeeded in ${formatDuration(build.durationMs)}.${build.active ? ' It is now the active build.' : ''}` + } + if (build.status === 'canceled') { + return `Build #${build.number} was canceled.` + } + if (build.status === 'failed') { + const step = build.failedStep ? ` at the ${build.failedStep} step` : '' + return `Build #${build.number} failed${step}: ${build.error ?? 'unknown error'}.` + } + return `Build #${build.number} is ${build.status}.` +} + +export function formatShow(data: CloudEnvironmentShowData): string { + const env = data.environment + const lines = [ + `Environment: ${env.name} (${env.id})`, + `Sandbox size: ${env.machineSize === 'large' ? 'Large (8 vCPU · 16 GB)' : 'Standard (4 vCPU · 8 GB)'} Revision: ${env.revision}${data.canAdmin ? '' : ' (read-only: ask an owner or admin to change it)'}`, + 'Repos:', + ...(env.repos.length > 0 + ? env.repos.map( + (repo, index) => + ` ${repo.url}${repo.defaultBranch ? ` (${repo.defaultBranch})` : ''}${index === 0 ? ' <- install script runs here' : ''}` + ) + : [' (none)']), + `Variables from Cloud secrets (Shared) passed to the install script: ${env.envVarNames.length > 0 ? env.envVarNames.join(', ') : '(none)'}`, + `Active build: ${data.activeBuild ? describeBuild(data.activeBuild) : '(none)'}`, + `Latest build: ${data.latestBuild ? describeBuild(data.latestBuild) : '(none)'}` + ] + if (data.staleness) { + lines.push( + `Freshness: ${describeStaleness(data.staleness.recommendation, data.staleness.configChanged)}` + ) + } + lines.push('Install script:') + lines.push(env.installScript ? indent(env.installScript) : ' (empty)') + if (data.environments.length > 1) { + lines.push( + `Other environments (pick with --env): ${data.environments + .filter((other) => other.id !== env.id) + .map((other) => `${other.name} (${other.id})`) + .join(', ')}` + ) + } + return lines.join('\n') +} + +function describeStaleness(recommendation: string, configChanged: boolean): string { + switch (recommendation) { + case 'no_build': + return 'no active build yet' + case 'deps_changed': + return 'a lockfile changed since the active build; rebuild recommended' + case 'config_changed': + return 'the configuration changed since the active build; rebuild recommended' + case 'image_updated': + return 'the base image was updated since the active build; rebuild recommended' + case 'branch_moved': + return 'the default branch moved since the active build' + case 'up_to_date': + return configChanged ? 'configuration changed since the active build' : 'up to date' + default: + return 'unknown' + } +} + +function describeBuild(build: HostedEnvironmentBuildView): string { + const parts = [`#${build.number} ${build.status}`] + if (build.status === 'failed') { + parts.push( + `${build.failedStep ? `at ${build.failedStep}` : ''}${build.error ? ` (${build.error})` : ''}`.trim() + ) + } + if (build.durationMs !== null) { + parts.push(formatDuration(build.durationMs)) + } + parts.push(new Date(build.createdAt).toISOString()) + parts.push(build.id) + return parts.filter(Boolean).join(' ') +} + +export function formatBuilds(data: CloudEnvironmentBuildsData): string { + if (data.builds.length === 0) { + return `${data.environment.name} has no builds yet. Start one with: orca cloud env build --wait` + } + const outcomes = data.builds.map((build) => + build.status === 'failed' + ? `failed${build.failedStep ? ` at ${build.failedStep}` : ''}${build.error ? ` (${build.error})` : ''}` + : build.status + ) + // Column width from the widest outcome, so a long failure never shifts the columns after it. + const width = Math.max(...outcomes.map((outcome) => outcome.length)) + const rows = data.builds.map((build, index) => { + const outcome = outcomes[index]! + return `${build.active ? '*' : ' '} #${String(build.number).padEnd(4)} ${outcome.padEnd(width)} ${formatDuration(build.durationMs).padEnd(8)} ${new Date(build.createdAt).toISOString()} ${build.id}` + }) + return [`Builds of ${data.environment.name} (newest first, * = active):`, ...rows].join('\n') +} + +function formatDuration(ms: number | null): string { + if (ms === null) { + return '-' + } + const seconds = Math.round(ms / 1000) + return seconds < 60 + ? `${seconds}s` + : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s` +} + +function indent(text: string): string { + return text + .split('\n') + .map((line) => ` ${line}`) + .join('\n') +} diff --git a/src/cli/handlers/cloud-env.test.ts b/src/cli/handlers/cloud-env.test.ts new file mode 100644 index 00000000000..a8a9ab1b805 --- /dev/null +++ b/src/cli/handlers/cloud-env.test.ts @@ -0,0 +1,110 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { CLOUD_ENV_HANDLERS } from './cloud-env' +import type { HandlerContext } from '../dispatch' +import { CLOUD_ENVIRONMENT_METHODS } from '../../shared/hosted-sandbox/hosted-environment-cli-contract' + +const ENV = { id: 'env_03b89d4bf1c74787a7ce', name: 'Web' } +const build = (status: string, extra: Record = {}) => ({ + id: 'bld_0123456789abcdef', + number: 7, + status, + active: false, + durationMs: 61_000, + failedStep: null, + error: null, + ...extra +}) + +function context( + responder: (method: string, params: Record) => unknown, + flags: Record = {} +): HandlerContext { + return { + flags: new Map(Object.entries(flags)), + cwd: '/tmp', + json: flags.json === true, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the cloud env handlers only use client.call + client: { + call: vi.fn(async (method: string, params: Record) => ({ + id: '1', + ok: true, + result: responder(method, params), + _meta: { runtimeId: 'r' } + })) + } as unknown as HandlerContext['client'] + } +} + +let stdout: string +let stderr: string +beforeEach(() => { + stdout = '' + stderr = '' + process.exitCode = undefined + vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + stdout += String(chunk) + return true + }) + vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + stderr += String(chunk) + return true + }) + vi.spyOn(console, 'log').mockImplementation((value) => { + stdout += `${String(value)}\n` + }) +}) +afterEach(() => { + vi.restoreAllMocks() + process.exitCode = undefined +}) + +describe('orca cloud env build --wait', () => { + it('streams the log and exits non-zero with the failed step', async () => { + const polls = [ + { + chunks: [{ stream: 'stdout', data: '::orca-step:: install\n' }], + done: false, + build: build('running') + }, + { + chunks: [{ stream: 'stderr', data: 'npm ERR! missing\n' }], + done: true, + build: build('failed', { failedStep: 'install', error: 'install_failed' }) + } + ] + let poll = 0 + const ctx = context( + (method) => { + if (method === CLOUD_ENVIRONMENT_METHODS.startBuild) { + return { ok: true, data: { environment: ENV, build: build('running') } } + } + const next = polls[poll++] + return { + ok: true, + data: { environment: ENV, cursor: poll, truncated: false, error: null, ...next } + } + }, + { wait: true } + ) + await CLOUD_ENV_HANDLERS['cloud env build'](ctx) + expect(stdout).toContain('::orca-step:: install') + expect(stderr).toContain('npm ERR! missing') + expect(stderr).toContain('Build #7 failed at the install step: install_failed.') + expect(process.exitCode).toBe(1) + }) + + it('surfaces control-plane refusals as errors', async () => { + const ctx = context(() => ({ + ok: false, + error: { + code: 'conflict', + reason: 'build_in_progress', + message: 'A build is already running.' + } + })) + await expect(CLOUD_ENV_HANDLERS['cloud env build'](ctx)).rejects.toMatchObject({ + code: 'cloud_conflict', + message: 'A build is already running.' + }) + }) +}) diff --git a/src/cli/handlers/cloud-env.ts b/src/cli/handlers/cloud-env.ts new file mode 100644 index 00000000000..022f6b673c7 --- /dev/null +++ b/src/cli/handlers/cloud-env.ts @@ -0,0 +1,289 @@ +// `orca cloud env ...`: lets a local agent read the org environment, replace its install script and +// run builds. The desktop app holds the Orca Cloud session, so every call goes through its runtime. +import { readFile, stat } from 'node:fs/promises' +import { resolve } from 'node:path' +import type { CommandHandler, HandlerContext } from '../dispatch' +import { RuntimeClientError } from '../runtime-client' +import { + CLOUD_ENVIRONMENT_METHODS, + type CloudEnvironmentBuildsData, + type CloudEnvironmentFollowData, + type CloudEnvironmentRpcResult, + type CloudEnvironmentSetInstallScriptData, + type CloudEnvironmentShowData, + type CloudEnvironmentStartBuildData +} from '../../shared/hosted-sandbox/hosted-environment-cli-contract' +import { HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS } from '../../shared/hosted-sandbox/hosted-environment-wire' +import { formatBuilds, formatOutcome, formatShow } from './cloud-env-format' + +const FOLLOW_WAIT_MS = 10_000 +const FOLLOW_CALL_TIMEOUT_MS = 30_000 +// `--wait --json` reports this much of the end of the log, enough to see why a build failed. +const JSON_LOG_TAIL_CHARS = 16_000 +// A transient desktop hiccup should not abandon a 10-minute build. +const MAX_FOLLOW_FAILURES = 5 + +type Client = Pick + +async function callCloud( + client: Client, + method: string, + params: Record, + timeoutMs?: number +): Promise { + let response + try { + response = await client.call>( + method, + params, + timeoutMs ? { timeoutMs } : undefined + ) + } catch (error) { + if (error instanceof RuntimeClientError && error.code === 'method_not_found') { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This Orca app does not support Orca Cloud environments yet. Update Orca and try again.' + ) + } + throw error + } + const result = response.result + if (!result.ok) { + throw new RuntimeClientError( + `cloud_${result.error.code}`, + result.error.message, + result.error.reason ? { reason: result.error.reason } : undefined + ) + } + return result.data +} + +function envParam(flags: HandlerContext['flags']): { env?: string } { + const env = flags.get('env') + return typeof env === 'string' && env.trim() ? { env: env.trim() } : {} +} + +export const CLOUD_ENV_HANDLERS: Record = { + 'cloud env show': async ({ flags, client, json }) => { + const data = await callCloud(client, CLOUD_ENVIRONMENT_METHODS.show, { + ...envParam(flags), + ...(flags.get('refresh') === true ? { refresh: true } : {}) + }) + console.log(json ? JSON.stringify(data, null, 2) : formatShow(data)) + }, + + 'cloud env set-install-script': async ({ flags, client, cwd, json }) => { + const file = flags.get('file') + if (typeof file !== 'string' || !file) { + throw new RuntimeClientError( + 'invalid_argument', + 'Pass the script with --file (or --file - for stdin).' + ) + } + const script = file === '-' ? await readStdin() : await readScriptFile(resolve(cwd, file)) + if (script.length > HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS) { + throw new RuntimeClientError( + 'invalid_argument', + `The install script is ${script.length} characters; the limit is ${HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS}.` + ) + } + const data = await callCloud( + client, + CLOUD_ENVIRONMENT_METHODS.setInstallScript, + { ...envParam(flags), script } + ) + if (json) { + console.log(JSON.stringify(data, null, 2)) + return + } + const flag = flags.get('env') ? ` --env ${data.environment.id}` : '' + console.log( + `Saved the install script for ${data.environment.name} (${script.length} chars, revision ${data.environment.revision}).\nBuild it with: orca cloud env build${flag} --wait` + ) + }, + + 'cloud env build': async ({ flags, client, json }) => { + const started = await callCloud( + client, + CLOUD_ENVIRONMENT_METHODS.startBuild, + envParam(flags) + ) + if (flags.get('wait') !== true) { + console.log( + json + ? JSON.stringify(started, null, 2) + : `Started build #${started.build.number} (${started.build.id}) for ${started.environment.name}.\nFollow it with: orca cloud env logs ${started.build.number}${flags.get('env') ? ` --env ${started.environment.id}` : ''}` + ) + return + } + if (!json) { + process.stderr.write( + `Started build #${started.build.number} (${started.build.id}) for ${started.environment.name}. Streaming its log...\n` + ) + } + const final = await followBuild(client, started.environment.id, started.build.id, { json }) + reportFinal(final, json) + }, + + 'cloud env builds': async ({ flags, client, json }) => { + const data = await callCloud( + client, + CLOUD_ENVIRONMENT_METHODS.builds, + envParam(flags) + ) + console.log(json ? JSON.stringify(data, null, 2) : formatBuilds(data)) + }, + + 'cloud env logs': async ({ flags, client, json }) => { + const build = flags.get('build') + if (typeof build !== 'string' || !build) { + throw new RuntimeClientError( + 'invalid_argument', + 'Pass a build number or id: orca cloud env logs .' + ) + } + // Resolve the number to an id once, so polls skip the lookups. + const first = await callCloud( + client, + CLOUD_ENVIRONMENT_METHODS.followBuild, + { ...envParam(flags), build, cursor: 0, waitMs: 0 }, + FOLLOW_CALL_TIMEOUT_MS + ) + // Before the stream's first event there is no build view yet; the loop picks it up. + const final = await followBuild(client, first.environment.id, first.build?.id ?? build, { + json, + initial: first + }) + reportFinal(final, json, { quietSuccess: true }) + } +} + +type FollowOutcome = { + data: CloudEnvironmentFollowData + logTail: string +} + +async function followBuild( + client: Client, + envId: string, + build: string, + options: { json: boolean; initial?: CloudEnvironmentFollowData } +): Promise { + let tail = '' + const take = (data: CloudEnvironmentFollowData): void => { + if (data.truncated && !options.json) { + process.stderr.write( + '[orca] some log output was lost while following (dropped from the buffer, or the log restarted and lines may repeat)\n' + ) + } + for (const chunk of data.chunks) { + if (options.json) { + tail = (tail + chunk.data).slice(-JSON_LOG_TAIL_CHARS) + } else if (chunk.stream === 'stderr') { + process.stderr.write(chunk.data) + } else { + process.stdout.write(chunk.data) + } + } + } + let data = options.initial + if (data) { + take(data) + } + let cursor = data?.cursor ?? 0 + let failures = 0 + while (!data?.done) { + try { + data = await callCloud( + client, + CLOUD_ENVIRONMENT_METHODS.followBuild, + { env: envId, build: data?.build?.id ?? build, cursor, waitMs: FOLLOW_WAIT_MS }, + FOLLOW_CALL_TIMEOUT_MS + ) + failures = 0 + } catch (error) { + // Cloud-side refusals (not found, signed out) are final; transport hiccups get retried. + if ( + ++failures > MAX_FOLLOW_FAILURES || + (error instanceof RuntimeClientError && error.code.startsWith('cloud_')) + ) { + throw error + } + await new Promise((r) => setTimeout(r, 2_000 * failures)) + continue + } + take(data) + cursor = data.cursor + } + return { data, logTail: tail } +} + +function reportFinal( + outcome: FollowOutcome, + json: boolean, + options: { quietSuccess?: boolean } = {} +): void { + const { data } = outcome + const build = data.build + const succeeded = build?.status === 'succeeded' + if (json) { + console.log( + JSON.stringify( + { + environment: data.environment, + build, + ok: succeeded, + ...(data.error ? { followError: data.error } : {}), + logTail: outcome.logTail + }, + null, + 2 + ) + ) + } else if (data.error) { + process.stderr.write(`\n[orca] ${data.error}\n`) + } else if (build && !(succeeded && options.quietSuccess)) { + process.stderr.write(`\n${formatOutcome(build)}\n`) + } + // `logs` of a finished build succeeds whatever the build's outcome; `build --wait` reports it. + if (data.error || (!options.quietSuccess && !succeeded)) { + process.exitCode = 1 + } +} + +async function readScriptFile(path: string): Promise { + const info = await stat(path).catch(() => null) + if (!info?.isFile()) { + throw new RuntimeClientError('invalid_argument', `No file at ${path}.`) + } + // Characters, not bytes, are limited; 4 bytes per char bounds the read. + if (info.size > HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS * 4) { + throw new RuntimeClientError( + 'invalid_argument', + `${path} is too large for an install script (limit ${HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS} characters).` + ) + } + return readFile(path, 'utf8') +} + +async function readStdin( + stdin: AsyncIterable & { isTTY?: boolean } = process.stdin +): Promise { + if (stdin.isTTY) { + throw new RuntimeClientError( + 'invalid_argument', + 'Pipe the script on stdin when using --file -.' + ) + } + const chunks: Buffer[] = [] + let bytes = 0 + for await (const chunk of stdin) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)) + bytes += buffer.length + if (bytes > HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS * 4) { + throw new RuntimeClientError('invalid_argument', 'The install script on stdin is too large.') + } + chunks.push(buffer) + } + return Buffer.concat(chunks).toString('utf8') +} diff --git a/src/cli/handlers/pair.ts b/src/cli/handlers/pair.ts index bc2d7d18d8f..0ce320978c5 100644 --- a/src/cli/handlers/pair.ts +++ b/src/cli/handlers/pair.ts @@ -7,6 +7,10 @@ import { type PairingCreateOfferParams, type PairingCreateOfferResult } from '../../shared/remote-runtime/pairing/pairing-create-offer-contract' +import { + TURN_SENDER_METHOD, + type TurnSenderResult +} from '../../shared/remote-runtime/pairing/turn-sender-contract' import { PAIRING_REVOKE_DEVICE_METHOD, type PairingRevokeDeviceResult @@ -76,5 +80,13 @@ export const PAIR_HANDLERS: Record = { if (!response.result.available) { process.exitCode = 1 } + }, + sender: async ({ client, json }) => { + const response = await client.call(TURN_SENDER_METHOD, undefined) + printResult(response, json, (result) => + result.sender + ? `Last message from device ${result.sender.deviceId}.` + : 'No paired device has messaged this agent.' + ) } } diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 10e3f99ae0a..9264f64581d 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -79,6 +79,11 @@ export const ROOT_HELP_TEXT_PRIMARY = [ 'Environment Recipes:', ' vm recipe doctor Validate a per-workspace environment recipe', ' vm env doctor Check that this environment can run agents', + ' cloud env show Show the Orca Cloud environment and its builds', + ' cloud env set-install-script Replace the Orca Cloud install script from a file', + ' cloud env build Build the Orca Cloud environment (--wait streams the log)', + ' cloud env builds List recent Orca Cloud environment builds', + ' cloud env logs Print or follow an Orca Cloud build log', '', 'Automations:', ' automations list List scheduled Orca automations', diff --git a/src/cli/serve-pairing-handler-groups.ts b/src/cli/serve-pairing-handler-groups.ts index 4c1817c57bc..7877e2a65aa 100644 --- a/src/cli/serve-pairing-handler-groups.ts +++ b/src/cli/serve-pairing-handler-groups.ts @@ -9,7 +9,7 @@ export const SERVE_PAIRING_HANDLER_GROUPS: readonly HandlerGroup[] = [ }, { name: 'pair', - keys: ['pair'], + keys: ['pair', 'sender'], load: async () => (await import('./handlers/pair.js')).PAIR_HANDLERS } ] diff --git a/src/cli/specs/cloud-env.ts b/src/cli/specs/cloud-env.ts new file mode 100644 index 00000000000..5268ac9aed0 --- /dev/null +++ b/src/cli/specs/cloud-env.ts @@ -0,0 +1,69 @@ +import type { CommandSpec } from '../args' +import { GLOBAL_FLAGS } from '../args' + +const ENV_NOTE = + 'With several environments in the org, pick one with --env ; without it the first one is used.' + +export const CLOUD_ENV_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['cloud', 'env', 'show'], + summary: 'Show the Orca Cloud environment: repos, install script, builds and freshness', + usage: 'orca cloud env show [--env ] [--refresh] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'env', 'refresh'], + notes: [ + 'Needs the Orca desktop app signed in to Orca Cloud; the CLI asks it.', + ENV_NOTE, + '--refresh re-checks the repos on GitHub instead of using the minute-old answer.' + ], + examples: ['orca cloud env show', 'orca cloud env show --env web --json'] + }, + { + path: ['cloud', 'env', 'set-install-script'], + summary: 'Replace the environment install script with the contents of a file', + usage: 'orca cloud env set-install-script --file [--env ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'env', 'file'], + notes: [ + 'The script is bash; each build runs it once with `set -euo pipefail` in the first repo, with passwordless sudo. The log’s first line names the base image and its package manager (currently Ubuntu with apt-get).', + 'Only the install script changes. Repos, secrets and machine size are edited in Settings by org owners and admins.', + 'Fails with "Someone else saved changes; reload." when the environment changed since it was read.', + ENV_NOTE + ], + examples: [ + 'orca cloud env set-install-script --file /tmp/install.sh', + 'cat install.sh | orca cloud env set-install-script --file -' + ] + }, + { + path: ['cloud', 'env', 'build'], + summary: 'Start a build of the environment, optionally waiting for it and streaming its log', + usage: 'orca cloud env build [--wait] [--env ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'env', 'wait'], + notes: [ + 'A build boots a VM, clones the repos, runs the install script and snapshots the result. A succeeded build becomes the active one new workspaces start from.', + '--wait streams the log to stdout/stderr and exits 1 unless the build succeeds, printing the failed step and error. With --json it prints the final build and the end of the log instead.', + 'Interrupting --wait leaves the build running; follow it again with `orca cloud env logs `.', + ENV_NOTE + ], + examples: ['orca cloud env build --wait', 'orca cloud env build --wait --json'] + }, + { + path: ['cloud', 'env', 'builds'], + summary: 'List the environment’s recent builds, newest first', + usage: 'orca cloud env builds [--env ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'env'], + notes: [ENV_NOTE], + examples: ['orca cloud env builds', 'orca cloud env builds --json'] + }, + { + path: ['cloud', 'env', 'logs'], + summary: 'Print a build’s log, following it until the build finishes', + usage: 'orca cloud env logs [--env ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'env', 'build'], + positionalArgs: ['build'], + notes: [ + 'Lines starting with `::orca-step::` mark build steps; `::orca-error::` lines are Orca’s explanation of a failure.', + ENV_NOTE + ], + examples: ['orca cloud env logs 12', 'orca cloud env logs bld_0123456789abcdef'] + } +] diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index cd52155778b..010bf1dfbcc 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -24,6 +24,7 @@ import { JIRA_COMMAND_SPECS } from './jira' import { LINEAR_COMMAND_SPECS } from './linear' 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 { SKILL_COMMAND_SPECS } from './skills' import { ARTIFACT_COMMAND_SPECS } from './artifacts' @@ -62,6 +63,7 @@ export const COMMAND_SPECS: CommandSpec[] = [ ...LINEAR_COMMAND_SPECS, ...VM_COMMAND_SPECS, ...VM_ENV_COMMAND_SPECS, + ...CLOUD_ENV_COMMAND_SPECS, ...CLOUD_SSH_COMMAND_SPECS, ...EMULATOR_COMMAND_SPECS, ...SKILL_COMMAND_SPECS, diff --git a/src/cli/specs/pair.ts b/src/cli/specs/pair.ts index 6e3abd3c127..d19678afeba 100644 --- a/src/cli/specs/pair.ts +++ b/src/cli/specs/pair.ts @@ -34,5 +34,16 @@ export const PAIR_COMMAND_SPECS: CommandSpec[] = [ 'orca pair --address 100.64.1.20', 'orca pair --mobile --rotate --json' ] + }, + { + path: ['sender'], + summary: 'Show which paired device sent the latest message to the agent running this command', + usage: 'orca sender [--json]', + allowedFlags: [...GLOBAL_FLAGS], + notes: [ + 'Run it from inside an agent terminal or chat: Orca identifies the caller from its own launch evidence, not from arguments, so an agent only ever learns who drove it.', + 'Prints nothing useful outside an agent Orca launched. Shared Orca Cloud workspaces use it to run git as the teammate who asked for the work.' + ], + examples: ['orca sender --json'] } ] diff --git a/src/main/cloud-api/cloud-api-client.test.ts b/src/main/cloud-api/cloud-api-client.test.ts new file mode 100644 index 00000000000..783b62effa4 --- /dev/null +++ b/src/main/cloud-api/cloud-api-client.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, it, vi } from 'vitest' +import { CloudApiError, classifyCloudApiResponse, createCloudApiClient } from './cloud-api-client' + +const KEY = { + id: 'key_1', + name: 'CI', + prefix: 'orca_sk_Ab3x', + scopes: ['workspaces:read', 'future:scope'], + createdBy: 'u1', + createdAt: 1, + lastUsedAt: null, + expiresAt: null +} + +function respond(status: number, body: unknown, headers: Record = {}) { + return new Response(body === undefined ? null : JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json', ...headers } + }) +} + +function client(fetchImpl: typeof fetch, getAccessToken = async () => 'tok_secret') { + return createCloudApiClient({ + controlPlaneUrl: 'https://cp.example.dev/', + getAccessToken, + fetchImpl + }) +} + +async function cloudApiErrorOf(promise: Promise): Promise { + const caught = await promise.then( + () => null, + (error: unknown) => error + ) + if (!(caught instanceof CloudApiError)) { + throw new Error(`expected a CloudApiError, got ${String(caught)}`) + } + return caught +} + +async function codeOf(promise: Promise): Promise { + try { + await promise + } catch (error) { + if (error instanceof CloudApiError) { + return error.code + } + throw error + } + return 'ok' +} + +describe('createCloudApiClient', () => { + it('sends the bearer token, JSON body and query, and validates the answer', async () => { + const fetchImpl = vi.fn(async () => + respond(200, { keys: [KEY], availableScopes: ['audit:read'] }) + ) + const keys = await client(fetchImpl).listApiKeys() + expect(keys.keys[0]?.prefix).toBe('orca_sk_Ab3x') + // Unknown scopes from a newer server are dropped, not fatal. + expect(keys.keys[0]?.scopes).toEqual(['workspaces:read']) + const [url, init] = fetchImpl.mock.calls[0] ?? [] + expect(url).toBe('https://cp.example.dev/v1/api-keys') + expect(new Headers(init?.headers).get('authorization')).toBe('Bearer tok_secret') + expect(init?.redirect).toBe('error') + + const created = vi.fn(async () => + respond(201, { key: KEY, secret: `orca_sk_${'a'.repeat(32)}` }) + ) + await client(created).createApiKey({ + name: 'CI', + scopes: ['workspaces:read'] + }) + const [, createInit] = created.mock.calls[0] ?? [] + expect(createInit?.method).toBe('POST') + expect(JSON.parse(String(createInit?.body))).toEqual({ + name: 'CI', + scopes: ['workspaces:read'] + }) + + const runs = vi.fn(async () => respond(200, { runs: [], nextBefore: null })) + await client(runs).listRoutineRuns('rt/1', { limit: 20, before: 99 }) + expect(runs.mock.calls[0]?.[0]).toBe( + 'https://cp.example.dev/v1/routines/rt%2F1/runs?limit=20&before=99' + ) + }) + + it('rejects a malformed answer as invalid-response', async () => { + const fetchImpl = vi.fn(async () => respond(200, { keys: 'nope' })) + expect(await codeOf(client(fetchImpl).listApiKeys())).toBe('invalid-response') + const badSecret = vi.fn(async () => + respond(201, { key: KEY, secret: 'not-a-key' }) + ) + expect( + await codeOf( + client(badSecret).createApiKey({ + name: 'x', + scopes: ['audit:read'] + }) + ) + ).toBe('invalid-response') + }) + + it('maps network and token failures without leaking the token', async () => { + const offline = vi.fn(async () => { + throw new TypeError('fetch failed tok_secret') + }) + const error = await cloudApiErrorOf(client(offline).me()) + expect(error.code).toBe('network') + expect(error.message).not.toContain('tok_secret') + + const noToken = client(vi.fn(), async () => { + throw new Error('signed out') + }) + expect(await codeOf(noToken.me())).toBe('signed-out') + }) + + it('treats a missing routines route as not-available but a missing routine as not-found', async () => { + const missing = vi.fn(async () => respond(404, { error: 'not_found' })) + const c = client(missing) + expect(await codeOf(c.listRoutines())).toBe('not-available') + expect(await codeOf(c.getRoutine('rt_1'))).toBe('not-found') + }) + + it('carries retry-after on rate limits and accepts empty DELETE bodies', async () => { + const limited = vi.fn(async () => + respond(429, { error: 'rate_limited' }, { 'retry-after': '7' }) + ) + const error = await cloudApiErrorOf(client(limited).listApiKeys()) + expect(error.code).toBe('rate-limited') + expect(error.retryAfterSeconds).toBe(7) + + const deleted = vi.fn(async () => new Response(null, { status: 200 })) + await expect(client(deleted).revokeApiKey('key_1')).resolves.toBeUndefined() + }) +}) + +describe('response hardening', () => { + it('keeps a freshly minted secret even if the key metadata drifted', async () => { + const secret = `orca_sk_${'b'.repeat(32)}` + const fetchImpl = vi.fn(async () => respond(201, { key: { id: 7 }, secret })) + const created = await client(fetchImpl).createApiKey({ + name: 'x', + scopes: ['workspaces:read'] + }) + expect(created).toEqual({ key: null, secret }) + }) + + it('drops non-https links from the server', async () => { + const run = { + id: 'run_1', + routineId: 'rt_1', + trigger: 'manual', + triggerDetail: null, + status: 'succeeded', + workspaceId: null, + result: { prUrl: 'javascript:alert(1)' }, + error: null, + createdAt: 1, + startedAt: 1, + finishedAt: 2, + durationMs: 1 + } + const fetchImpl = vi.fn(async () => respond(202, { run })) + // A bad link is dropped, never opened, and doesn't fail the whole response. + const { run: parsed } = await client(fetchImpl).runRoutine('rt_1') + expect(parsed.result?.prUrl).toBeUndefined() + expect(parsed.status).toBe('succeeded') + }) +}) + +describe('classifyCloudApiResponse', () => { + it.each([ + [401, { error: 'unauthorized' }, 'signed-out'], + [403, { error: 'forbidden', reason: 'admin_required' }, 'admin-required'], + [403, { error: 'forbidden', reason: 'admin_scope:audit:read' }, 'admin-required'], + [403, { error: 'insufficient_scope', reason: 'routines:write' }, 'forbidden'], + [400, { error: 'invalid_request', reason: 'name: Too small' }, 'invalid-request'], + [503, { error: 'not_configured' }, 'not-available'], + [500, null, 'server'], + [502, { error: 'workspace_unavailable' }, 'server'] + ])('%i %j → %s', (status, body, code) => { + expect(classifyCloudApiResponse(status, body).code).toBe(code) + }) + + it('keeps the server validation reason as detail, truncated', () => { + expect(classifyCloudApiResponse(400, { reason: 'name: Too small' }).detail).toBe( + 'name: Too small' + ) + expect(classifyCloudApiResponse(400, { reason: 'x'.repeat(1000) }).detail).toHaveLength(200) + }) +}) diff --git a/src/main/cloud-api/cloud-api-client.ts b/src/main/cloud-api/cloud-api-client.ts new file mode 100644 index 00000000000..7b2a1b83390 --- /dev/null +++ b/src/main/cloud-api/cloud-api-client.ts @@ -0,0 +1,217 @@ +// HTTP client for the Orca Cloud control plane's public /v1 API, used by the desktop's API keys and +// routines settings. Pure (fetch + token source injected) so it is testable without Electron. The +// bearer token never leaves this module: callers get validated data or a CloudApiError code. +import { z } from 'zod' +import { + CloudApiApprovalSchema, + CloudApiAuditPageSchema, + CloudApiCreatedKeySchema, + CloudApiGrantListSchema, + CloudApiInstallationListSchema, + CloudApiKeyListSchema, + CloudApiMeSchema, + CloudApiProjectListSchema, + CloudApiSettingsSchema, + RoutineCreatedSchema, + RoutineEnvelopeSchema, + RoutineListSchema, + RoutineRunEnvelopeSchema, + RoutineRunPageSchema, + RoutineUpdatedSchema, + RoutineWebhookSchema, + type CloudApiErrorCode, + type CreateCloudApiApprovalInput, + type CreateCloudApiKeyInput, + type RoutineInput, + type RoutinePatch, + type RoutineRunsQuery +} from '../../shared/cloud-api/cloud-api-types' + +const REQUEST_TIMEOUT_MS = 20_000 +const MAX_DETAIL_CHARS = 200 + +export class CloudApiError extends Error { + constructor( + readonly code: CloudApiErrorCode, + /** Server-provided reason (e.g. a validation message), safe to show; never a secret. */ + readonly detail?: string, + readonly retryAfterSeconds?: number + ) { + super(detail ? `${code}: ${detail}` : code) + this.name = 'CloudApiError' + } +} + +export type CloudApiClientDeps = { + controlPlaneUrl: string + getAccessToken: () => Promise + fetchImpl?: typeof fetch + /** Maps a token-source failure (signed out, auth down) to an error code. */ + classifyTokenError?: (error: unknown) => CloudApiErrorCode +} + +type RequestOptions = { + body?: unknown + query?: Record + /** A 404 on this route means the deployment predates it, not a missing record. */ + notFoundMeansUnavailable?: boolean +} + +function readServerError(body: unknown): { error?: string; reason?: string } { + if (typeof body !== 'object' || body === null) { + return {} + } + const pick = (value: unknown): string | undefined => + typeof value === 'string' ? value.slice(0, MAX_DETAIL_CHARS) : undefined + return { + error: pick('error' in body ? body.error : undefined), + reason: pick('reason' in body ? body.reason : undefined) + } +} + +/** Maps a non-2xx control-plane answer to a stable code the renderer can word. */ +export function classifyCloudApiResponse( + status: number, + body: unknown, + options: { notFoundMeansUnavailable?: boolean } = {} +): { code: CloudApiErrorCode; detail?: string } { + const { error, reason } = readServerError(body) + if (status === 401) { + return { code: 'signed-out' } + } + if (status === 403) { + if (reason === 'admin_required' || reason?.startsWith('admin_scope:')) { + return { code: 'admin-required' } + } + return { code: 'forbidden', ...(reason ? { detail: reason } : {}) } + } + if (status === 404) { + return { code: options.notFoundMeansUnavailable ? 'not-available' : 'not-found' } + } + if (status === 400 || status === 409 || status === 422) { + return { code: 'invalid-request', ...(reason ? { detail: reason } : {}) } + } + if (status === 429) { + return { code: 'rate-limited' } + } + if (status === 503 && error === 'not_configured') { + return { code: 'not-available' } + } + return { code: 'server', detail: error ?? `HTTP ${status}` } +} + +export function createCloudApiClient(deps: CloudApiClientDeps) { + const fetchImpl = deps.fetchImpl ?? fetch + const base = `${deps.controlPlaneUrl.replace(/\/+$/, '')}/` + + async function request( + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', + path: string, + schema: S, + options: RequestOptions = {} + ): Promise> { + let token: string + try { + token = await deps.getAccessToken() + } catch (error) { + throw new CloudApiError(deps.classifyTokenError?.(error) ?? 'signed-out') + } + const url = new URL(path.replace(/^\//, ''), base) + for (const [name, value] of Object.entries(options.query ?? {})) { + if (value !== undefined) { + url.searchParams.set(name, String(value)) + } + } + let response: Response + try { + response = await fetchImpl(url.toString(), { + method, + headers: { + authorization: `Bearer ${token}`, + accept: 'application/json', + ...(options.body !== undefined ? { 'content-type': 'application/json' } : {}) + }, + ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}), + redirect: 'error', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) + }) + } catch { + throw new CloudApiError('network') + } + const body: unknown = await response.json().catch(() => null) + if (!response.ok) { + const { code, detail } = classifyCloudApiResponse(response.status, body, options) + const retryAfter = Number(response.headers.get('retry-after')) + throw new CloudApiError( + code, + detail, + code === 'rate-limited' && Number.isFinite(retryAfter) && retryAfter > 0 + ? retryAfter + : undefined + ) + } + const parsed = schema.safeParse(body) + if (!parsed.success) { + throw new CloudApiError('invalid-response') + } + return parsed.data + } + + const routinePath = (id: string, sub = ''): string => + `v1/routines/${encodeURIComponent(id)}${sub}` + + return { + me: () => request('GET', 'v1/me', CloudApiMeSchema), + listApiKeys: () => request('GET', 'v1/api-keys', CloudApiKeyListSchema), + createApiKey: (input: CreateCloudApiKeyInput) => + request('POST', 'v1/api-keys', CloudApiCreatedKeySchema, { body: input }), + revokeApiKey: async (id: string): Promise => { + await request('DELETE', `v1/api-keys/${encodeURIComponent(id)}`, z.unknown()) + }, + createApproval: (input: CreateCloudApiApprovalInput = {}) => + request('POST', 'v1/oauth-approvals', CloudApiApprovalSchema, { + body: input, + notFoundMeansUnavailable: true + }), + listGrants: () => + request('GET', 'v1/oauth-grants', CloudApiGrantListSchema, { + notFoundMeansUnavailable: true + }), + revokeGrant: async (id: string): Promise => { + await request('DELETE', `v1/oauth-grants/${encodeURIComponent(id)}`, z.unknown()) + }, + getSettings: () => request('GET', 'v1/settings', CloudApiSettingsSchema), + putSettings: (settings: { vmCliEnabled: boolean }) => + request('PUT', 'v1/settings', CloudApiSettingsSchema, { body: settings }), + listAudit: (query: { limit?: number; before?: number } = {}) => + request('GET', 'v1/audit', CloudApiAuditPageSchema, { query }), + listProjects: () => request('GET', 'v1/projects', CloudApiProjectListSchema), + listInstallations: () => + request('GET', 'v1/github/installations', CloudApiInstallationListSchema, { + notFoundMeansUnavailable: true + }), + listRoutines: () => + request('GET', 'v1/routines', RoutineListSchema, { notFoundMeansUnavailable: true }), + getRoutine: (id: string) => request('GET', routinePath(id), RoutineEnvelopeSchema), + createRoutine: (input: RoutineInput) => + request('POST', 'v1/routines', RoutineCreatedSchema, { body: input }), + updateRoutine: (id: string, patch: RoutinePatch) => + request('PATCH', routinePath(id), RoutineUpdatedSchema, { body: patch }), + deleteRoutine: async (id: string): Promise => { + await request('DELETE', routinePath(id), z.unknown()) + }, + runRoutine: (id: string) => request('POST', routinePath(id, '/run'), RoutineRunEnvelopeSchema), + rotateRoutineWebhook: (id: string) => + request('POST', routinePath(id, '/rotate-webhook'), RoutineWebhookSchema), + listRoutineRuns: (id: string, query: RoutineRunsQuery = {}) => + request('GET', routinePath(id, '/runs'), RoutineRunPageSchema, { query }), + getRoutineRun: (id: string, runId: string) => + request( + 'GET', + routinePath(id, `/runs/${encodeURIComponent(runId)}`), + RoutineRunEnvelopeSchema + ) + } +} + +export type CloudApiClient = ReturnType diff --git a/src/main/cloud-api/cloud-api-ipc.test.ts b/src/main/cloud-api/cloud-api-ipc.test.ts new file mode 100644 index 00000000000..517f6ecf9a5 --- /dev/null +++ b/src/main/cloud-api/cloud-api-ipc.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const callCloudApi = vi.fn(async (run: (client: unknown) => Promise) => ({ + ok: true, + data: await run(fakeClient) +})) +const fakeClient = { + createApiKey: vi.fn(async (input: unknown) => ({ echoed: input })), + revokeApiKey: vi.fn(async () => undefined), + createRoutine: vi.fn(async (input: unknown) => ({ echoed: input })) +} + +vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), removeHandler: vi.fn() } })) +vi.mock('./cloud-api-service', () => ({ + callCloudApi: (run: (client: unknown) => Promise) => callCloudApi(run), + getCloudApiAvailability: () => ({ status: 'unconfigured' }) +})) + +const { cloudApiHandlerFor, CLOUD_API_CHANNELS } = await import('./cloud-api-ipc') + +describe('cloud API IPC', () => { + beforeEach(() => { + callCloudApi.mockClear() + }) + + it('rejects malformed renderer input before any network call', async () => { + const create = cloudApiHandlerFor('cloudApi:createApiKey')! + expect(await create({ name: '', scopes: ['workspaces:read'] })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await create({ name: 'x', scopes: ['root:all'] })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await create({ name: 'x', scopes: ['audit:read'], extra: 1 })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await cloudApiHandlerFor('cloudApi:revokeApiKey')!(42)).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect( + await cloudApiHandlerFor('cloudApi:createRoutine')!({ + name: 'r', + repo: { url: 'http://insecure.example/repo' }, + trigger: { kind: 'webhook' }, + agent: 'claude', + prompt: 'p', + postResults: 'none' + }) + ).toEqual({ ok: false, error: 'invalid-request' }) + expect(callCloudApi).not.toHaveBeenCalled() + }) + + it('passes validated input through to the client', async () => { + const result = await cloudApiHandlerFor('cloudApi:createApiKey')!({ + name: ' CI ', + scopes: ['workspaces:read'], + expiresInDays: 30 + }) + expect(result).toEqual({ + ok: true, + data: { echoed: { name: 'CI', scopes: ['workspaces:read'], expiresInDays: 30 } } + }) + }) + + it('registers every channel the preload bridge uses', () => { + expect(CLOUD_API_CHANNELS).toEqual( + expect.arrayContaining([ + 'cloudApi:availability', + 'cloudApi:createApproval', + 'cloudApi:listRoutineRuns', + 'cloudApi:rotateRoutineWebhook' + ]) + ) + }) +}) diff --git a/src/main/cloud-api/cloud-api-ipc.ts b/src/main/cloud-api/cloud-api-ipc.ts new file mode 100644 index 00000000000..494cac86df7 --- /dev/null +++ b/src/main/cloud-api/cloud-api-ipc.ts @@ -0,0 +1,101 @@ +import { ipcMain } from 'electron' +import { z } from 'zod' +import { + CreateCloudApiApprovalInputSchema, + CreateCloudApiKeyInputSchema, + RoutineInputSchema, + RoutinePatchSchema, + RoutineRunsQuerySchema, + type CloudApiResult +} from '../../shared/cloud-api/cloud-api-types' +import type { CloudApiClient } from './cloud-api-client' +import { + callCloudApi, + findLocalWorkspaceForSandbox, + getCloudApiAvailability +} from './cloud-api-service' + +const Id = z.string().min(1).max(128) +const AuditQuery = z + .object({ + limit: z.number().int().min(1).max(200).optional(), + before: z.number().int().nonnegative().optional() + }) + .strict() +const SettingsInput = z.object({ vmCliEnabled: z.boolean() }).strict() + +type Handler = (...args: unknown[]) => Promise> + +/** Validates renderer input before it reaches the network; bad input never leaves main. */ +function call( + schemas: { [K in keyof A]: z.ZodType }, + run: (client: CloudApiClient, ...args: A) => Promise +): Handler { + return async (...raw) => { + const parsed: unknown[] = [] + for (const [index, schema] of schemas.entries()) { + const result = schema.safeParse(raw[index]) + if (!result.success) { + return { ok: false, error: 'invalid-request' } + } + parsed.push(result.data) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: parsed[i] is schemas[i]'s output and schemas is typed per A[i]; TS cannot prove a tuple built in a loop. + return callCloudApi((client) => run(client, ...(parsed as A))) + } +} + +const HANDLERS: Record = { + 'cloudApi:me': call([], (c) => c.me()), + 'cloudApi:listApiKeys': call([], (c) => c.listApiKeys()), + 'cloudApi:createApiKey': call([CreateCloudApiKeyInputSchema], (c, input) => + c.createApiKey(input) + ), + 'cloudApi:revokeApiKey': call([Id], (c, id) => c.revokeApiKey(id)), + 'cloudApi:createApproval': call([CreateCloudApiApprovalInputSchema.optional()], (c, input) => + c.createApproval(input ?? {}) + ), + 'cloudApi:listGrants': call([], (c) => c.listGrants()), + 'cloudApi:revokeGrant': call([Id], (c, id) => c.revokeGrant(id)), + 'cloudApi:getSettings': call([], (c) => c.getSettings()), + 'cloudApi:putSettings': call([SettingsInput], (c, input) => c.putSettings(input)), + 'cloudApi:listAudit': call([AuditQuery.optional()], (c, q) => c.listAudit(q ?? {})), + 'cloudApi:listProjects': call([], (c) => c.listProjects()), + 'cloudApi:listInstallations': call([], (c) => c.listInstallations()), + 'cloudApi:listRoutines': call([], (c) => c.listRoutines()), + 'cloudApi:createRoutine': call([RoutineInputSchema], (c, input) => c.createRoutine(input)), + 'cloudApi:updateRoutine': call([Id, RoutinePatchSchema], (c, id, patch) => + c.updateRoutine(id, patch) + ), + 'cloudApi:deleteRoutine': call([Id], (c, id) => c.deleteRoutine(id)), + 'cloudApi:runRoutine': call([Id], (c, id) => c.runRoutine(id)), + 'cloudApi:rotateRoutineWebhook': call([Id], (c, id) => c.rotateRoutineWebhook(id)), + 'cloudApi:listRoutineRuns': call([Id, RoutineRunsQuerySchema.optional()], (c, id, q) => + c.listRoutineRuns(id, q ?? {}) + ) +} + +export const CLOUD_API_CHANNELS = [ + 'cloudApi:availability', + 'cloudApi:localWorkspaceFor', + ...Object.keys(HANDLERS) +] + +/** Exposed for tests: the validated handler behind a channel. */ +export function cloudApiHandlerFor(channel: string): Handler | undefined { + return HANDLERS[channel] +} + +export function registerCloudApiHandlers(): void { + for (const channel of CLOUD_API_CHANNELS) { + ipcMain.removeHandler(channel) + } + ipcMain.handle('cloudApi:availability', () => getCloudApiAvailability()) + ipcMain.handle('cloudApi:localWorkspaceFor', (_event, sandboxId: unknown) => { + const parsed = Id.safeParse(sandboxId) + return parsed.success ? findLocalWorkspaceForSandbox(parsed.data) : null + }) + for (const [channel, handler] of Object.entries(HANDLERS)) { + ipcMain.handle(channel, (_event, ...args: unknown[]) => handler(...args)) + } +} diff --git a/src/main/cloud-api/cloud-api-service.ts b/src/main/cloud-api/cloud-api-service.ts new file mode 100644 index 00000000000..7c4337ba062 --- /dev/null +++ b/src/main/cloud-api/cloud-api-service.ts @@ -0,0 +1,103 @@ +import { app } from 'electron' +// Orca Cloud API access for the desktop settings. Uses the same hosted control plane + session +// token as Orca Cloud sandboxes, so it is only on in builds that configure ORCA_CLOUD_SANDBOX_URL. +// Every call resolves to a CloudApiResult value; nothing throws across IPC and no token is returned. +import type { + CloudApiAvailability, + CloudApiErrorCode, + CloudApiResult +} from '../../shared/cloud-api/cloud-api-types' +import { withCloudBuildDefaults } from '../cloud-build-defaults' +import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver' +import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' +import { findCloudRuntime } from '../hosted-sandbox/hosted-workspace-runtime' +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' +import { artifactCloudIdentity } from '../orca-profiles/profile-artifact-cloud-cleanup' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import { CloudApiError, createCloudApiClient, type CloudApiClient } from './cloud-api-client' + +let cached: { key: string; client: CloudApiClient; controlPlaneUrl: string } | null = null + +export function classifyTokenError(error: unknown): CloudApiErrorCode { + if (error instanceof EnvironmentProviderError) { + return error.code === 'unauthorized' ? 'signed-out' : 'network' + } + return 'signed-out' +} + +function resolveClient(): { client: CloudApiClient; controlPlaneUrl: string } | null { + const userDataPath = app.getPath('userData') + // Token caches are per profile *and* signed-in identity (user, cloud profile, active team): + // switching any of them must never reuse the previous account's token. + const profile = ensureActiveOrcaProfile(userDataPath).profile + const profileKey = `${profile.id}:${artifactCloudIdentity(profile.cloud)}` + if (cached?.key === profileKey) { + return cached + } + const config = getHostedSandboxConfig( + userDataPath, + withCloudBuildDefaults(process.env), + app.isPackaged + ) + if (!config) { + cached = null + return null + } + cached = { + key: profileKey, + controlPlaneUrl: config.controlPlaneUrl, + client: createCloudApiClient({ + controlPlaneUrl: config.controlPlaneUrl, + getAccessToken: () => config.getAccessToken(), + classifyTokenError + }) + } + return cached +} + +export function getCloudApiAvailability(): CloudApiAvailability { + const resolved = resolveClient() + return resolved + ? { status: 'ready', controlPlaneUrl: resolved.controlPlaneUrl } + : { status: 'unconfigured' } +} + +export async function callCloudApi( + run: (client: CloudApiClient) => Promise +): Promise> { + const resolved = resolveClient() + if (!resolved) { + return { ok: false, error: 'unconfigured' } + } + try { + return { ok: true, data: await run(resolved.client) } + } catch (error) { + if (error instanceof CloudApiError) { + return { + ok: false, + error: error.code, + ...(error.detail ? { detail: error.detail } : {}), + ...(error.retryAfterSeconds ? { retryAfterSeconds: error.retryAfterSeconds } : {}) + } + } + // Unknown failures stay generic: their messages could carry request internals. + return { ok: false, error: 'server' } + } +} + +/** + * The desktop workspace (worktree) that runs on a given Orca Cloud sandbox, if this computer + * has it (e.g. a routine run's workspace that was opened here before). Null otherwise. + */ +export function findLocalWorkspaceForSandbox(sandboxId: string): string | null { + const userDataPath = app.getPath('userData') + for (const runtime of listEphemeralVmRuntimes(userDataPath)) { + if (runtime.recipe?.provider !== 'orca-cloud' || !runtime.workspaceId) { + continue + } + if (findCloudRuntime(userDataPath, runtime.workspaceId)?.sandboxId === sandboxId) { + return runtime.workspaceId + } + } + return null +} diff --git a/src/main/cloud-secrets/cloud-secrets-client.test.ts b/src/main/cloud-secrets/cloud-secrets-client.test.ts new file mode 100644 index 00000000000..4305bbda085 --- /dev/null +++ b/src/main/cloud-secrets/cloud-secrets-client.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from 'vitest' +import { cloudSecretsFailureCode, createCloudSecretsClient } from './cloud-secrets-client' + +type Seen = { method: string; url: string; body: string | null; authorization: string | null } + +function fakeControlPlane(respond: (seen: Seen) => Response) { + const seen: Seen[] = [] + const fetchImpl: typeof fetch = async (input, init) => { + const request: Seen = { + method: init?.method ?? 'GET', + url: String(input), + body: typeof init?.body === 'string' ? init.body : null, + authorization: new Headers(init?.headers).get('authorization') + } + seen.push(request) + return respond(request) + } + const client = createCloudSecretsClient({ + baseUrl: 'https://control.test', + getAccessToken: async () => 'tok', + fetch: fetchImpl + }) + return { client, seen } +} + +const VIEW = { + scope: 'repo', + name: 'DATABASE_URL', + kind: 'env', + hint: 'ab12', + updatedAt: 5, + updatedBy: 'u1', + repo: 'github.com/acme/app' +} + +describe('createCloudSecretsClient', () => { + it('addresses scope, name and repo on the wire and sends the value only in the body', async () => { + const { client, seen } = fakeControlPlane(({ method }) => + Response.json(method === 'GET' ? { secrets: [VIEW] } : { secret: VIEW }) + ) + expect(await client.list({ scope: 'repo', repo: 'acme/app' })).toEqual([VIEW]) + await client.put({ scope: 'repo', repo: 'acme/app' }, 'DATABASE_URL', 'postgres://secret') + expect(seen).toEqual([ + { + method: 'GET', + url: 'https://control.test/v1/secrets?scope=repo&repo=acme%2Fapp', + body: null, + authorization: 'Bearer tok' + }, + { + method: 'PUT', + url: 'https://control.test/v1/secrets/repo/DATABASE_URL?repo=acme%2Fapp', + body: '{"value":"postgres://secret"}', + authorization: 'Bearer tok' + } + ]) + }) + + it('posts batches and reads partial success', async () => { + const result = { + secrets: [{ ...VIEW, scope: 'personal', repo: undefined }], + deleted: ['OLD'], + errors: [{ name: 'PATH', error: 'invalid_request', reason: 'reserved_name' }] + } + const { client, seen } = fakeControlPlane(() => Response.json(result)) + const out = await client.batch( + { scope: 'personal' }, + { set: { DATABASE_URL: 'x', PATH: '/bin' }, delete: ['OLD'] } + ) + expect(out.errors).toEqual([ + { name: 'PATH', error: 'invalid_request', reason: 'reserved_name' } + ]) + expect(seen[0].url).toBe('https://control.test/v1/secrets/personal/batch') + }) + + it('maps server refusals to their reason and never quotes the request', async () => { + const { client } = fakeControlPlane(() => + Response.json( + { error: 'invalid_request', reason: 'subscription_token_refused' }, + { status: 400 } + ) + ) + const error = await client + .put({ scope: 'personal' }, 'ANTHROPIC_API_KEY', 'sk-ant-oat01-very-secret') + .catch((caught: unknown) => caught) + expect(cloudSecretsFailureCode(error)).toBe('subscription_token_refused') + expect(String(error)).not.toContain('very-secret') + }) + + it.each([ + [403, { error: 'forbidden', reason: 'org_admin_required' }, 'org_admin_required'], + [409, { error: 'conflict', reason: 'secret_limit' }, 'secret_limit'], + [401, { error: 'unauthorized' }, 'unauthorized'], + [503, { error: 'internal_error' }, 'unavailable'] + ])('maps HTTP %i to %s', async (status, body, code) => { + const { client } = fakeControlPlane(() => Response.json(body, { status })) + const error = await client.list({ scope: 'org' }).catch((caught: unknown) => caught) + expect(cloudSecretsFailureCode(error)).toBe(code) + }) + + it('rejects a response that does not match the schema', async () => { + const { client } = fakeControlPlane(() => Response.json({ secrets: [{ name: 1 }] })) + const error = await client.list({ scope: 'personal' }).catch((caught: unknown) => caught) + expect(cloudSecretsFailureCode(error)).toBe('unavailable') + }) + + it('reads the effective view and refreshes a sandbox env', async () => { + const effective = { + caller: { + userId: 'u1', + orgId: 'org_1', + orgRole: 'member', + canWrite: { personal: true, org: false, repo: false } + }, + precedence: { env: ['repo', 'personal', 'org'], agent_key: ['org', 'repo', 'personal'] }, + secrets: [ + { + name: 'ANTHROPIC_API_KEY', + kind: 'agent_key', + scope: 'org', + hint: 'zz99', + updatedAt: 1, + shadowed: [{ scope: 'personal', hint: null }] + } + ] + } + const { client, seen } = fakeControlPlane(({ url }) => + Response.json(url.includes('/env/refresh') ? { applied: true } : effective) + ) + expect(await client.effective('acme/app')).toEqual(effective) + expect(await client.refreshEnv('sbx_1')).toBe(true) + expect(seen.map((request) => `${request.method} ${request.url}`)).toEqual([ + 'GET https://control.test/v1/secrets/effective?repo=acme%2Fapp', + 'POST https://control.test/v1/sandboxes/sbx_1/env/refresh' + ]) + }) +}) diff --git a/src/main/cloud-secrets/cloud-secrets-client.ts b/src/main/cloud-secrets/cloud-secrets-client.ts new file mode 100644 index 00000000000..19f9aeb88bb --- /dev/null +++ b/src/main/cloud-secrets/cloud-secrets-client.ts @@ -0,0 +1,121 @@ +// Orca Cloud secrets on the sandbox control plane. Write-only for values: requests carry them, no +// response or error does, and nothing here logs a request body. +import { + CloudEnvRefreshResponseSchema, + CloudSecretBatchResponseSchema, + CloudSecretDeleteResponseSchema, + CloudSecretListResponseSchema, + CloudSecretPutResponseSchema, + CloudSecretsEffectiveResponseSchema, + cloudSecretsErrorCode, + type CloudSecretBatchResult, + type CloudSecretsErrorCode, + type CloudSecretTarget, + type CloudSecretView, + type CloudSecretsEffective +} from '../../shared/cloud-secrets/cloud-secrets-wire' +import { isEnvironmentProviderError } from '../environment-providers/environment-provider-driver' +import { + createHostedSandboxRequest, + type HostedSandboxControlPlaneClientOptions +} from '../hosted-sandbox/hosted-sandbox-request' + +export type CloudSecretsClient = { + list(target: CloudSecretTarget, signal?: AbortSignal): Promise + put(target: CloudSecretTarget, name: string, value: string): Promise + remove(target: CloudSecretTarget, name: string): Promise + batch( + target: CloudSecretTarget, + change: { set?: Record; delete?: string[] } + ): Promise + effective(repo?: string, signal?: AbortSignal): Promise + refreshEnv(sandboxId: string): Promise +} + +function withRepo(path: string, repo: string | undefined): string { + return repo ? `${path}?${new URLSearchParams({ repo })}` : path +} + +export function createCloudSecretsClient( + options: HostedSandboxControlPlaneClientOptions +): CloudSecretsClient { + const call = createHostedSandboxRequest(options) + const secretPath = (target: CloudSecretTarget, suffix: string): string => + withRepo(`v1/secrets/${encodeURIComponent(target.scope)}/${suffix}`, target.repo) + + return { + list: async (target, signal) => + ( + await call( + 'GET', + `v1/secrets?${new URLSearchParams({ + scope: target.scope, + ...(target.repo ? { repo: target.repo } : {}) + })}`, + CloudSecretListResponseSchema, + { kind: 'control', signal } + ) + ).secrets, + put: async (target, name, value) => + ( + await call( + 'PUT', + secretPath(target, encodeURIComponent(name)), + CloudSecretPutResponseSchema, + { + body: { value }, + kind: 'control' + } + ) + ).secret, + remove: async (target, name) => { + await call( + 'DELETE', + secretPath(target, encodeURIComponent(name)), + CloudSecretDeleteResponseSchema, + { kind: 'control' } + ) + }, + batch: (target, change) => + call('POST', secretPath(target, 'batch'), CloudSecretBatchResponseSchema, { + body: change, + kind: 'control' + }), + effective: (repo, signal) => + call('GET', withRepo('v1/secrets/effective', repo), CloudSecretsEffectiveResponseSchema, { + kind: 'control', + signal + }), + refreshEnv: async (sandboxId) => + ( + await call( + 'POST', + `v1/sandboxes/${encodeURIComponent(sandboxId)}/env/refresh`, + CloudEnvRefreshResponseSchema, + { kind: 'control' } + ) + ).applied + } +} + +/** The code the renderer turns into copy: the server reason when it gave one. */ +export function cloudSecretsFailureCode(error: unknown): CloudSecretsErrorCode { + if (!isEnvironmentProviderError(error)) { + return 'unknown' + } + switch (error.code) { + case 'unauthorized': + return cloudSecretsErrorCode(error.reason, 'unauthorized') + case 'not_found': + return 'not_found' + case 'timeout': + return 'timeout' + case 'invalid_request': + case 'conflict': + return cloudSecretsErrorCode(error.reason) + case 'unavailable': + case 'aborted': + case 'invalid_response': + return 'unavailable' + } +} diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts new file mode 100644 index 00000000000..56033281053 --- /dev/null +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -0,0 +1,150 @@ +// Renderer bridge to Orca Cloud secrets. Values travel renderer -> main -> control plane once per save; +// nothing returns them, and failures surface as codes only (an error message could quote a value). +import { app, ipcMain } from 'electron' +import { z } from 'zod' +import { + CLOUD_SECRET_SCOPES, + MAX_CLOUD_SECRET_BATCH, + type CloudSecretsResult, + type CloudSecretsStatus +} from '../../shared/cloud-secrets/cloud-secrets-wire' +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' +import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter' +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 { + cloudSecretsFailureCode, + createCloudSecretsClient, + type CloudSecretsClient +} from './cloud-secrets-client' + +const Repo = z.string().trim().min(3).max(256) +const Target = z.object({ scope: z.enum(CLOUD_SECRET_SCOPES), repo: Repo.optional() }) +const Name = z + .string() + .max(128) + .regex(/^[A-Z_][A-Z0-9_]*$/) +const Value = z + .string() + .min(1) + .max(64 * 1024) +const PutRequest = z.object({ target: Target, name: Name, value: Value }) +const RemoveRequest = z.object({ target: Target, name: Name }) +const BatchRequest = z + .object({ + target: Target, + set: z.record(Name, Value).optional(), + delete: z.array(Name).max(MAX_CLOUD_SECRET_BATCH).optional() + }) + .refine( + (request) => + Object.keys(request.set ?? {}).length + (request.delete?.length ?? 0) <= + MAX_CLOUD_SECRET_BATCH + ) +const EffectiveRequest = z.object({ repo: Repo.optional() }) +const RefreshRequest = z.object({ runtimeEnvironmentId: z.string().min(1).max(256) }) + +const CHANNELS = [ + 'cloudSecrets:status', + 'cloudSecrets:list', + 'cloudSecrets:put', + 'cloudSecrets:remove', + 'cloudSecrets:batch', + 'cloudSecrets:effective', + 'cloudSecrets:refreshEnv' +] as const + +async function attempt( + client: CloudSecretsClient | null, + run: (client: CloudSecretsClient) => Promise +): Promise> { + if (!client) { + return { ok: false, error: 'not_configured' } + } + try { + return { ok: true, value: await run(client) } + } catch (error) { + const code = cloudSecretsFailureCode(error) + console.warn(`[cloud-secrets] request failed: ${code}`) + return { ok: false, error: code } + } +} + +function sandboxIdFor(userDataPath: string, runtimeEnvironmentId: string): string | null { + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (record) => + record.runtimeEnvironmentId === runtimeEnvironmentId && + record.recipe?.provider === 'orca-cloud' + ) + const handle = runtime?.recipeResult + ? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID) + : null + return handle?.environmentId ?? null +} + +export function registerCloudSecretsHandlers(userDataPath: string): void { + // Packaged integration builds read no shell env; their control-plane URL is baked in. + const config = getHostedSandboxConfig( + userDataPath, + withCloudBuildDefaults(process.env), + app.isPackaged + ) + const client = config + ? createCloudSecretsClient({ + baseUrl: config.controlPlaneUrl, + getAccessToken: config.getAccessToken + }) + : null + for (const channel of CHANNELS) { + ipcMain.removeHandler(channel) + } + // A malformed request is a renderer bug, not something the user typed. + const invalid = { ok: false, error: 'unknown' } as const + + ipcMain.handle('cloudSecrets:status', async (): Promise => ({ + available: client !== null && (await getOrcaCloudAvailability()) === 'offered' + })) + ipcMain.handle('cloudSecrets:list', (_event, raw: unknown) => { + const target = Target.safeParse(raw) + return target.success ? attempt(client, (c) => c.list(target.data)) : invalid + }) + ipcMain.handle('cloudSecrets:put', (_event, raw: unknown) => { + const request = PutRequest.safeParse(raw) + return request.success + ? attempt(client, (c) => c.put(request.data.target, request.data.name, request.data.value)) + : invalid + }) + ipcMain.handle('cloudSecrets:remove', (_event, raw: unknown) => { + const request = RemoveRequest.safeParse(raw) + return request.success + ? attempt(client, async (c) => { + await c.remove(request.data.target, request.data.name) + return true as const + }) + : invalid + }) + ipcMain.handle('cloudSecrets:batch', (_event, raw: unknown) => { + const request = BatchRequest.safeParse(raw) + return request.success + ? attempt(client, (c) => + c.batch(request.data.target, { set: request.data.set, delete: request.data.delete }) + ) + : invalid + }) + ipcMain.handle('cloudSecrets:effective', (_event, raw: unknown) => { + const request = EffectiveRequest.safeParse(raw ?? {}) + return request.success ? attempt(client, (c) => c.effective(request.data.repo)) : invalid + }) + ipcMain.handle('cloudSecrets:refreshEnv', (_event, raw: unknown) => { + const request = RefreshRequest.safeParse(raw) + if (!request.success) { + return invalid + } + const sandboxId = sandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) + return sandboxId + ? attempt(client, (c) => c.refreshEnv(sandboxId)) + : { ok: false, error: 'not_found' } + }) +} diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index f9913eec973..71453f65bd5 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -1,6 +1,6 @@ // HTTPS client for the team workspace registry on the sandbox control plane. Same auth as the // hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential. -import type { z } from 'zod' +import { z } from 'zod' import { errorMessage } from '../../shared/error-message' import { CloudWorkspaceGrantIssuedSchema, @@ -15,6 +15,8 @@ import { type OrgPrompts } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +const NoteSentSchema = z.object({ ok: z.literal(true) }) + export class CloudWorkspacesError extends Error { constructor( readonly status: number, @@ -127,6 +129,9 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption async patch(id: string, patch: CloudWorkspacePatch) { return call('PATCH', ws(id), CloudWorkspaceResponseSchema.extend({}).passthrough(), patch) }, + async noteSent(id: string) { + await call('POST', `${ws(id)}/sent`, NoteSentSchema, {}) + }, async presence( id: string, body: { clientId: string; state: 'viewing' | 'typing' | 'left'; chatId?: string | null } diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index 5625f4b53e3..6a3340a1c22 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -139,6 +139,7 @@ export function createCloudWorkspacesService(deps: { putOrgPrompts: (document: OrgPrompts['document'], revision: number) => wrap(() => client.putOrgPrompts(document, revision)), localWorkspaces: () => localWorkspaces(), + noteSent: (id: string) => wrap(() => client.noteSent(id)), /** * A per-device credential for a workspace this desktop does not own: a fresh X25519 key lives @@ -193,6 +194,7 @@ export function createCloudWorkspacesService(deps: { return } const changed = active?.sandboxId !== args.sandboxId + const previousChatId = active?.chatId ?? null if (changed && active) { void client .presence(active.sandboxId, { clientId: deps.clientId, state: 'left' }) @@ -200,7 +202,8 @@ export function createCloudWorkspacesService(deps: { } active = { sandboxId: args.sandboxId, - chatId: args.chatId ?? active?.chatId ?? null, + // undefined keeps the chat (typing beats); null means no chat is in front any more. + chatId: args.chatId !== undefined ? args.chatId : changed ? null : (active?.chatId ?? null), typingUntil: args.typing ? Date.now() + TYPING_HOLD_MS : changed @@ -208,7 +211,7 @@ export function createCloudWorkspacesService(deps: { : (active?.typingUntil ?? 0), leased: args.leased ?? active?.leased ?? false } - if (changed || args.typing) { + if (changed || args.typing || active.chatId !== previousChatId) { void beat() } renewLeaseIfDue() diff --git a/src/main/environment-doctor/environment-doctor-setup.ts b/src/main/environment-doctor/environment-doctor-setup.ts index 0f192a9e53a..edd30791626 100644 --- a/src/main/environment-doctor/environment-doctor-setup.ts +++ b/src/main/environment-doctor/environment-doctor-setup.ts @@ -9,6 +9,7 @@ import { type EnvironmentDoctorDeps } from './environment-doctor-check' import type { GitCheckoutProbe } from './environment-doctor-git' +import { hasEnvironmentBuildMarker } from '../workspace-hooks/environment-build-checkout' // Orca writes .cmd or .sh on Windows depending on the script's shell, so look for both. const SETUP_RUNNER_NAMES = ['orca/setup-runner.sh', 'orca/setup-runner.cmd'] as const @@ -26,6 +27,19 @@ export async function checkSetup( const yaml = await context.readRepoFile('orca.yaml') const script = yaml ? parseOrcaYaml(yaml)?.scripts.setup?.trim() : undefined if (!script) { + if ( + context.checkout.kind === 'checkout' && + (await hasEnvironmentBuildMarker(context.checkout.commonDir, context.root)) + ) { + return [ + check( + 'setup', + 'setup.script', + 'pass', + 'Dependencies come from the Orca Cloud environment build.' + ) + ] + } return [ context.impliesInstall ? check('setup', 'setup.script', 'warn', 'orca.yaml has no setup script.', { diff --git a/src/main/hosted-sandbox/cloud-message-queue-store.ts b/src/main/hosted-sandbox/cloud-message-queue-store.ts index 7d98869cbe1..1b29d35b1da 100644 --- a/src/main/hosted-sandbox/cloud-message-queue-store.ts +++ b/src/main/hosted-sandbox/cloud-message-queue-store.ts @@ -1,6 +1,7 @@ // Queued prompts on disk: sealed with the OS keychain; without one they live in memory only. -import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' +import { z } from 'zod' import type { CloudQueuedPrompt } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import type { OfflineCacheCodec } from './cloud-offline-cache' @@ -13,38 +14,103 @@ export type StoredPrompt = CloudQueuedPrompt & { nextAttemptAt: number } -export function readSealedPrompts(path: string, codec: OfflineCacheCodec | null): StoredPrompt[] { +// The sealed file is ours, but only its shape is checked here; a prompt that does not match is dropped. +const StoredPromptSchema = z.looseObject({ + id: z.string(), + clientOperationId: z.string(), + workspaceId: z.string(), + sessionId: z.string(), + text: z.string(), + state: z.enum(['queued', 'sending', 'delivered', 'failed', 'unconfirmed']), + createdAt: z.number(), + updatedAt: z.number(), + failures: z.number(), + nextAttemptAt: z.number(), + error: z.string().optional() +}) +const SealedQueueSchema = z.object({ version: z.literal(2), prompts: z.array(z.unknown()) }) + +export async function readSealedPrompts( + path: string, + codec: OfflineCacheCodec | null +): Promise { if (!codec) { return [] } try { - const parsed = JSON.parse(codec.decrypt(readFileSync(path))) as { - version: 2 - prompts: StoredPrompt[] + const parsed = SealedQueueSchema.safeParse(JSON.parse(codec.decrypt(await readFile(path)))) + if (!parsed.success) { + return [] } - return parsed.version === 2 && Array.isArray(parsed.prompts) ? parsed.prompts : [] + return parsed.data.prompts.flatMap((raw) => { + const prompt = StoredPromptSchema.safeParse(raw) + return prompt.success ? [prompt.data] : [] + }) } catch { return [] } } -export function writeSealedPrompts( +export async function writeSealedPrompts( path: string, codec: OfflineCacheCodec | null, prompts: readonly StoredPrompt[] -): void { +): Promise { if (!codec) { return } - mkdirSync(dirname(path), { recursive: true, mode: 0o700 }) + const sealed = codec.encrypt(JSON.stringify({ version: 2, prompts })) + await mkdir(dirname(path), { recursive: true, mode: 0o700 }) const temp = `${path}.${process.pid}.tmp` - writeFileSync(temp, codec.encrypt(JSON.stringify({ version: 2, prompts })), { mode: 0o600 }) - renameSync(temp, path) + await writeFile(temp, sealed, { mode: 0o600 }) + await rename(temp, path) } /** The first build kept the queue as plaintext JSON beside the sealed file; it is never read. */ -export function removeLegacyPlaintextQueue(path: string): void { - rmSync(join(dirname(path), 'orca-cloud-queued-prompts.json'), { force: true }) +export function removeLegacyPlaintextQueue(path: string): Promise { + return rm(join(dirname(path), 'orca-cloud-queued-prompts.json'), { force: true }) +} + +/** The sealed queue file: read once, then every write and removal in call order. */ +export function createSealedPromptDisk( + path: string, + codec: OfflineCacheCodec | null, + log: (line: string) => void +) { + const load = (async () => { + await removeLegacyPlaintextQueue(path).catch(() => undefined) + return readSealedPrompts(path, codec) + })() + // Nothing is written before the sealed file has been read. + let tail: Promise = load + function serial(task: () => Promise): Promise { + const run = tail.then(task) + tail = run.catch((error: unknown) => + log(`[orca-cloud] queued prompts write failed: ${String(error)}`) + ) + return run + } + return { + load, + write: (prompts: readonly StoredPrompt[]) => + serial(() => writeSealedPrompts(path, codec, prompts)), + remove: () => + serial(async () => { + await removeLegacyPlaintextQueue(path) + await rm(path, { force: true }) + }), + flushed: () => serial(async () => {}) + } +} + +export function earliestOwedAttempt(prompts: readonly StoredPrompt[]): number | null { + let earliest: number | null = null + for (const prompt of prompts) { + if (prompt.state === 'queued' || prompt.state === 'sending') { + earliest = earliest === null ? prompt.nextAttemptAt : Math.min(earliest, prompt.nextAttemptAt) + } + } + return earliest } /** Refusals that mean "not now", not "never": the same operation is sent again. */ @@ -87,11 +153,24 @@ export async function currentFence( ? { refused: code } : null } - const result = response.result as { ok: boolean; page?: { fence?: number }; fence?: number } + const parsed = FenceResultSchema.safeParse(response.result) + const result = parsed.success ? parsed.data : { ok: false } const fence = result.page?.fence ?? (result.ok ? undefined : result.fence) return typeof fence === 'number' ? fence : null } +const FenceResultSchema = z.looseObject({ + ok: z.boolean(), + page: z.looseObject({ fence: z.number().optional() }).optional(), + fence: z.number().optional() +}) + +/** `agentSession.send` answer: delivered, or refused with a code. */ +export const SendResultSchema = z.looseObject({ + ok: z.boolean(), + refusal: z.looseObject({ code: z.string().optional(), message: z.string().optional() }).optional() +}) + export type WorkspaceAvailability = | { kind: 'up'; environmentId: string } | { kind: 'asleep'; environmentId: string } @@ -133,4 +212,8 @@ export type CloudMessageQueue = { failPending(workspaceId: string, reason: string): void /** Sign-out / profile switch: forget everything. */ clear(): void + /** Resolves once every disk write requested so far has finished (shutdown, tests). */ + flushed(): Promise + /** Earliest background attempt still owed (ms epoch), or null when nothing is pending. */ + nextAttemptAt(): number | null } diff --git a/src/main/hosted-sandbox/cloud-message-queue.test.ts b/src/main/hosted-sandbox/cloud-message-queue.test.ts index 609caf86199..fad4f9d05cd 100644 --- a/src/main/hosted-sandbox/cloud-message-queue.test.ts +++ b/src/main/hosted-sandbox/cloud-message-queue.test.ts @@ -18,18 +18,14 @@ import { import type { OfflineCacheCodec } from './cloud-offline-cache' const SESSION = '0f8e7c1a-2b3d-4e5f-8a9b-0c1d2e3f4a5b' +/** Fixed test epoch: operation ids and the host's admission window both read this clock. */ +const T0 = 1_800_000_000_000 const codec: OfflineCacheCodec = { encrypt: (plain) => Buffer.from(Buffer.from(plain, 'utf8').map((b) => b ^ 0x5a)), decrypt: (sealed) => Buffer.from(sealed.map((b) => b ^ 0x5a)).toString('utf8') } -type Envelope = { - clientOperationId: string - expectedRuntimeFence: number - payloadFingerprint: string -} - /** * A host that admits operations with the real ledger rule (id format, age, replay by id) and * validates params with the real send schema. @@ -59,7 +55,7 @@ function realishHost(clock: () => number) { } } const parsed = SendParams.parse(params) - const envelope = parsed.envelope as Envelope + const envelope = parsed.envelope const decision = evaluateAgentSessionOperation({ rows, callerKey: 'desktop', @@ -78,9 +74,10 @@ function realishHost(clock: () => number) { } if (decision.decision === 'admit') { rows.set(agentSessionOperationKey('desktop', envelope.clientOperationId), decision.row) + const block = parsed.body.blocks[0] effects.push({ - text: (parsed.body.blocks[0] as { text: string }).text, - fence: envelope.expectedRuntimeFence + text: block?.type === 'text' ? block.text : '', + fence: envelope.expectedRuntimeFence ?? 0 }) } if (loseNextReply) { @@ -113,7 +110,7 @@ function setup( clock?: { now: number } } = {} ) { - const clock = opts.clock ?? { now: Date.now() } + const clock = opts.clock ?? { now: T0 } const path = opts.path ?? join(mkdtempSync(join(tmpdir(), 'orca-q-')), 'q.bin') const host = opts.host ?? realishHost(() => clock.now) let asleep = true @@ -132,14 +129,11 @@ function setup( call: host.call, log: () => {} }) - const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - return { queue, host, wake, path, clock, settle, sleep: () => (asleep = true) } + return { queue, host, wake, path, clock, sleep: () => (asleep = true) } } async function until(check: () => boolean) { - for (let i = 0; i < 100 && !check(); i++) { - await new Promise((resolve) => setTimeout(resolve, 1)) - } + await vi.waitFor(() => expect(check()).toBe(true)) } describe('cloud message queue', () => { @@ -155,15 +149,18 @@ describe('cloud message queue', () => { }) it('re-mints a never-sent id before it ages out of the host admission window', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) - const place = { current: { kind: 'asleep', environmentId: 'env' } as WorkspaceAvailability } + const place: { current: WorkspaceAvailability } = { + current: { kind: 'asleep', environmentId: 'env' } + } const parked = setup({ clock, host, place: () => place.current }) parked.wake.mockResolvedValueOnce(false) await parked.queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'a day later' }) // The wake failed: the prompt waits, queued, for the VM to be up. await until(() => parked.wake.mock.calls.length === 1) - await new Promise((resolve) => setTimeout(resolve, 5)) + // Joins the in-flight pass (never wakes on its own). + await parked.queue.drive('w') expect(parked.queue.list('w')[0]!.state).toBe('queued') clock.now += AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS + 60_000 place.current = { kind: 'up', environmentId: 'env' } @@ -177,9 +174,10 @@ describe('cloud message queue', () => { first.wake.mockResolvedValueOnce(false) await first.queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'after restart' }) await until(() => first.wake.mock.calls.length === 1) - await new Promise((resolve) => setTimeout(resolve, 5)) + await first.queue.drive('w') + await first.queue.flushed() expect(readFileSync(first.path).toString('utf8')).not.toContain('after restart') - const host = realishHost(() => Date.now()) + const host = realishHost(() => first.clock.now) let up = false const second = setup({ path: first.path, @@ -187,6 +185,7 @@ describe('cloud message queue', () => { place: () => up ? { kind: 'up', environmentId: 'env' } : { kind: 'asleep', environmentId: 'env' } }) + await second.queue.flushed() expect(second.queue.list('w').map((p) => p.state)).toEqual(['queued']) await second.queue.drive() expect(second.wake).not.toHaveBeenCalled() @@ -198,7 +197,7 @@ describe('cloud message queue', () => { }) it('is at most once when the reply is lost: the retry reuses the id and the host replays', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) const { queue, path } = setup({ clock, @@ -208,6 +207,7 @@ describe('cloud message queue', () => { host.loseNextReply() await queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'once' }) await until(() => queue.list('w')[0]!.state === 'sending') + await queue.flushed() clock.now += 60 * 60_000 const restarted = setup({ path, @@ -222,7 +222,7 @@ describe('cloud message queue', () => { }) it('never wakes from the background, and stops after its failure budget', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) host.setHistoryFails(true) const { queue, wake } = setup({ @@ -241,7 +241,7 @@ describe('cloud message queue', () => { }) it('backs off between background attempts', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) host.setHistoryFails(true) const { queue } = setup({ clock, host, place: () => ({ kind: 'up', environmentId: 'env' }) }) @@ -280,7 +280,7 @@ describe('cloud message queue', () => { }) it('does not send a prompt cancelled or edited while its fence was being read', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) let release: () => void = () => {} const gate = new Promise((resolve) => (release = resolve)) @@ -304,7 +304,6 @@ describe('cloud message queue', () => { expect(queue.cancel(a.id)).toBe(true) release() await queue.drive('w') - await new Promise((resolve) => setTimeout(resolve, 5)) expect(host.effects).toHaveLength(0) }) @@ -359,7 +358,7 @@ describe('cloud message queue', () => { }) it('does not resurrect a prompt a Sleep failed while its fence was being read', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) let release: () => void = () => {} const gate = new Promise((resolve) => (release = resolve)) @@ -382,13 +381,14 @@ describe('cloud message queue', () => { await new Promise((resolve) => setTimeout(resolve, 0)) queue.failPending('w', 'The workspace was put to sleep before this was sent.') release() - await new Promise((resolve) => setTimeout(resolve, 5)) + // Joins the pass that was waiting on the fence. + await queue.drive('w') expect(host.effects).toHaveLength(0) expect(queue.list('w')[0]!.state).toBe('failed') }) it('ends a sent-but-unconfirmed prompt as unconfirmed, not failed, at its budget', async () => { - const clock = { now: Date.now() } + const clock = { now: T0 } const host = realishHost(() => clock.now) const lossy: CloudMessageQueueDeps['call'] = async (env, method, params, t) => { const answer = await host.call(env, method, params, t) @@ -430,9 +430,11 @@ describe('cloud message queue', () => { }, log: () => {} }) + await queue.flushed() expect(existsSync(legacy)).toBe(false) writeFileSync(legacy, 'again') queue.clear() + await queue.flushed() expect(existsSync(legacy)).toBe(false) }) }) diff --git a/src/main/hosted-sandbox/cloud-message-queue.ts b/src/main/hosted-sandbox/cloud-message-queue.ts index e24e3034259..489ca6371ac 100644 --- a/src/main/hosted-sandbox/cloud-message-queue.ts +++ b/src/main/hosted-sandbox/cloud-message-queue.ts @@ -10,7 +10,6 @@ // Only the person queuing a prompt wakes a VM. Background retries deliver only to a VM that is // already up, never to one asleep, archived or manually disconnected, and stop after a budget. import { randomUUID } from 'node:crypto' -import { rmSync } from 'node:fs' import { CLOUD_QUEUED_PROMPT_MAX_CHARS } from '../../shared/hosted-sandbox/cloud-workspace-offline-api' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import { structuredAgentSessionMessageSendMutation } from '../../shared/agent-session/requests/structured-agent-session-send-mutation' @@ -21,12 +20,12 @@ import { import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation' import { SendParams } from '../../shared/rpc-contract/structured-agent-session-params' import { - readSealedPrompts, + createSealedPromptDisk, currentFence, + earliestOwedAttempt, publicView, RETRYABLE_REFUSALS, - removeLegacyPlaintextQueue, - writeSealedPrompts, + SendResultSchema, type CloudMessageQueue, type CloudMessageQueueDeps, type StoredPrompt @@ -52,26 +51,33 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa const log = deps.log ?? ((line: string) => console.error(line)) const driving = new Map>() const mintId = () => createStructuredAgentSessionOperationId(randomUUID, now()) - removeLegacyPlaintextQueue(deps.path) - let prompts: StoredPrompt[] = readSealedPrompts(deps.path, deps.codec) + let prompts: StoredPrompt[] = [] + // Bumped by clear() so a load still reading the old file cannot bring cleared prompts back. + let generation = 0 + const disk = createSealedPromptDisk(deps.path, deps.codec, log) + const loaded = disk.load.then((stored) => { + prompts = generation === 0 ? [...stored, ...prompts] : prompts + }) - function save(): void { + /** Resolves once the queue is on disk as of this call; rejects if that write failed. */ + function save(): Promise { const cutoff = now() - DELIVERED_RETENTION_MS prompts = prompts.filter((prompt) => prompt.state !== 'delivered' || prompt.updatedAt >= cutoff) - writeSealedPrompts(deps.path, deps.codec, prompts) + return disk.write(prompts) } - function update(prompt: StoredPrompt, patch: Partial): void { + function update(prompt: StoredPrompt, patch: Partial): Promise { Object.assign(prompt, patch, { updatedAt: now() }) - save() + const saved = save() deps.onChange?.(prompt.workspaceId) + return saved } function failOnce(prompt: StoredPrompt, error: string): void { const failures = prompt.failures + 1 if (failures >= MAX_FAILURES) { // A prompt that reached `sending` may already be on the host: say so, so nobody re-sends it. - update( + void update( prompt, prompt.state === 'sending' ? { @@ -83,7 +89,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa ) return } - update(prompt, { + void update(prompt, { failures, nextAttemptAt: now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1)) }) @@ -104,7 +110,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa prompt.state === 'queued' && now() - mintedAt > AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS - REMINT_MARGIN_MS ) { - update(prompt, { clientOperationId: mintId() }) + await update(prompt, { clientOperationId: mintId() }) } const before = { id: prompt.clientOperationId, text: prompt.text, state: prompt.state } let fence: number | { refused: string } | null @@ -129,7 +135,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa return 'stop' } if (typeof fence !== 'number') { - update(prompt, { state: 'failed', error: 'This chat is no longer on the workspace.' }) + await update(prompt, { state: 'failed', error: 'This chat is no longer on the workspace.' }) return 'next' } const params = structuredAgentSessionMessageSendMutation({ @@ -142,11 +148,11 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa }) // The host's own schema: a prompt it would reject outright is failed here, never retried. if (!SendParams.safeParse(params).success) { - update(prompt, { state: 'failed', error: 'This message cannot be sent to that chat.' }) + await update(prompt, { state: 'failed', error: 'This message cannot be sent to that chat.' }) return 'next' } // Durable before the send: from here on, any retry resends this same operation id. - update(prompt, { state: 'sending' }) + await update(prompt, { state: 'sending' }) let response: RuntimeRpcResponse try { response = await deps.call(environmentId, 'agentSession.send', params, SEND_TIMEOUT_MS) @@ -159,9 +165,10 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa failOnce(prompt, response.error.message.slice(0, 200)) return 'stop' } - const result = response.result as { ok: boolean; refusal?: { code?: string; message?: string } } + const parsed = SendResultSchema.safeParse(response.result) + const result = parsed.success ? parsed.data : { ok: false, refusal: undefined } if (result.ok) { - update(prompt, { state: 'delivered', error: undefined }) + await update(prompt, { state: 'delivered', error: undefined }) return 'next' } const code = result.refusal?.code ?? 'unknown' @@ -169,11 +176,12 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa failOnce(prompt, result.refusal?.message ?? code) return 'stop' } - update(prompt, { state: 'failed', error: result.refusal?.message ?? code }) + await update(prompt, { state: 'failed', error: result.refusal?.message ?? code }) return 'next' } async function driveWorkspace(workspaceId: string, allowWake: boolean): Promise { + await loaded if (pendingOf(workspaceId).length === 0) { return } @@ -233,6 +241,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa if (!trimmed || trimmed.length > CLOUD_QUEUED_PROMPT_MAX_CHARS) { throw new Error('Prompt is empty or too long.') } + await loaded const place = await deps.locate(workspaceId) if (place.kind === 'blocked') { throw new Error(place.reason) @@ -254,7 +263,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa nextAttemptAt: at } prompts.push(prompt) - save() + await save() deps.onChange?.(workspaceId) void run(workspaceId, true) return publicView(prompt) @@ -268,7 +277,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa return false } prompts = prompts.filter((p) => p !== prompt) - save() + void save() deps.onChange?.(prompt.workspaceId) return true }, @@ -284,9 +293,11 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa return false } // Never sent, so a new text is a new operation; nothing on the host knows the old id. - update(prompt, { text: trimmed, clientOperationId: mintId() }) + void update(prompt, { text: trimmed, clientOperationId: mintId() }) return true }, + nextAttemptAt: () => earliestOwedAttempt(prompts), + flushed: () => disk.flushed(), drive(workspaceId) { const ids = workspaceId ? [workspaceId] @@ -309,15 +320,15 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa } } if (changed) { - save() + void save() deps.onChange?.(workspaceId) } }, clear() { - removeLegacyPlaintextQueue(deps.path) + generation++ const workspaces = new Set(prompts.map((p) => p.workspaceId)) prompts = [] - rmSync(deps.path, { force: true }) + void disk.remove().catch(() => undefined) for (const workspaceId of workspaces) { deps.onChange?.(workspaceId) } diff --git a/src/main/hosted-sandbox/cloud-offline-beat.test.ts b/src/main/hosted-sandbox/cloud-offline-beat.test.ts new file mode 100644 index 00000000000..b433a4c8200 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-beat.test.ts @@ -0,0 +1,65 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createOwedWorkBeat } from './cloud-offline-beat' + +const T0 = 1_800_000_000_000 + +describe('owed-work beat', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(T0) + }) + afterEach(() => vi.useRealTimers()) + + it('stays idle with nothing owed, and backs off while passes change nothing', async () => { + let due: number | null = null + const pass = vi.fn(async () => {}) + const beat = createOwedWorkBeat({ + nextDueAt: () => due, + pass, + baseMs: 1_000, + maxBackoffSteps: 2 + }) + beat.poke() + await vi.advanceTimersByTimeAsync(60_000) + expect(pass).not.toHaveBeenCalled() + + due = T0 + beat.poke() + await vi.advanceTimersByTimeAsync(1_000) + expect(pass).toHaveBeenCalledTimes(1) + // Unchanged after that pass: the next waits 2 s, then 4 s (the cap). + await vi.advanceTimersByTimeAsync(1_999) + expect(pass).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(pass).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(4_000) + expect(pass).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(4_000) + expect(pass).toHaveBeenCalledTimes(4) + + due = null + await vi.advanceTimersByTimeAsync(4_000) + const settled = pass.mock.calls.length + await vi.advanceTimersByTimeAsync(60_000) + expect(pass).toHaveBeenCalledTimes(settled) + beat.dispose() + }) + + it('waits for a later due attempt and stops on dispose', async () => { + const pass = vi.fn(async () => {}) + const beat = createOwedWorkBeat({ + nextDueAt: () => T0 + 10_000, + pass, + baseMs: 1_000, + maxBackoffSteps: 2 + }) + beat.poke() + await vi.advanceTimersByTimeAsync(9_999) + expect(pass).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(pass).toHaveBeenCalledTimes(1) + beat.dispose() + await vi.advanceTimersByTimeAsync(60_000) + expect(pass).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/hosted-sandbox/cloud-offline-beat.ts b/src/main/hosted-sandbox/cloud-offline-beat.ts new file mode 100644 index 00000000000..9259d8a7351 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-offline-beat.ts @@ -0,0 +1,59 @@ +// Background delivery for queued Orca Cloud prompts runs only while prompts are owed: at the next +// due attempt, never sooner than the base cadence, doubling while a pass changes nothing. +export type OwedWorkBeat = { + /** Something changed (a prompt was queued or settled): arm at the base cadence again. */ + poke(): void + /** Run a pass now (startup), then keep the cadence while work is owed. */ + runNow(): Promise + dispose(): void +} + +export function createOwedWorkBeat(options: { + /** Earliest owed attempt (ms epoch), or null when nothing is owed: the beat stops. */ + nextDueAt: () => number | null + pass: () => Promise + baseMs: number + maxBackoffSteps: number + now?: () => number +}): OwedWorkBeat { + const now = options.now ?? Date.now + let timer: ReturnType | null = null + let idlePasses = 0 + let disposed = false + + function arm(): void { + const due = options.nextDueAt() + if (timer || disposed || due === null) { + return + } + const idleDelay = options.baseMs * 2 ** Math.min(idlePasses, options.maxBackoffSteps) + timer = setTimeout(() => void runNow(), Math.max(due - now(), idleDelay)) + timer.unref?.() + } + + async function runNow(): Promise { + if (timer) { + clearTimeout(timer) + timer = null + } + const before = options.nextDueAt() + await options.pass() + idlePasses = options.nextDueAt() === before ? idlePasses + 1 : 0 + arm() + } + + return { + poke() { + idlePasses = 0 + arm() + }, + runNow, + dispose() { + disposed = true + if (timer) { + clearTimeout(timer) + timer = null + } + } + } +} diff --git a/src/main/hosted-sandbox/cloud-offline-cache-types.ts b/src/main/hosted-sandbox/cloud-offline-cache-types.ts index bd04c3f6c3b..9656b8d442a 100644 --- a/src/main/hosted-sandbox/cloud-offline-cache-types.ts +++ b/src/main/hosted-sandbox/cloud-offline-cache-types.ts @@ -1,6 +1,8 @@ // Types, limits and small helpers of the Orca Cloud offline cache (see cloud-offline-cache.ts). -import { readdirSync, rmSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { readdir, rm } from 'node:fs/promises' import { join } from 'node:path' +import { z } from 'zod' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' /** Read-only methods whose answers stay meaningful while the VM sleeps. Nothing that mutates. */ @@ -76,14 +78,15 @@ export type CloudOfflineCache = { params: unknown, response: RuntimeRpcSuccess ): void - lookup(environmentId: string, method: string, params: unknown): OfflineCacheEntry | null - entries(environmentId: string, method?: string): OfflineCacheEntry[] - forget(environmentId: string): void + lookup(environmentId: string, method: string, params: unknown): Promise + entries(environmentId: string, method?: string): Promise + forget(environmentId: string): Promise /** Drop every environment not in `keep` (removed workspaces). */ - prune(keep: ReadonlySet): void + prune(keep: ReadonlySet): Promise /** Delete everything (sign-out, profile switch). */ - clear(): void - flush(): void + clear(): Promise + /** Writes pending changes; resolves once earlier records and file work have landed. */ + flush(): Promise } /** Key-order independent, so `{a,b}` and `{b,a}` hit the same entry. */ @@ -105,14 +108,51 @@ export function stableKey(method: string, params: unknown): string { return `${method} ${JSON.stringify(sort(params ?? null))}` } -export function removeLegacyPlaintextFiles(root: string): void { +export async function removeLegacyPlaintextFiles(root: string): Promise { try { - for (const name of readdirSync(root)) { + for (const name of await readdir(root)) { if (name.endsWith('.json')) { - rmSync(join(root, name), { force: true }) + await rm(join(root, name), { force: true }) } } } catch { // No cache directory yet. } } + +export const EnvironmentFileSchema = z.object({ + version: z.literal(2), + environmentId: z.string(), + updatedAt: z.number(), + entries: z.record( + z.string(), + z.object({ + method: z.string(), + params: z.unknown(), + resultJson: z.string(), + runtimeId: z.string(), + at: z.number(), + bytes: z.number() + }) + ) +}) + +export function fileName(environmentId: string): string { + return `${createHash('sha256').update(environmentId).digest('hex').slice(0, 32)}.bin` +} + +export function decode(entry: StoredEntry): OfflineCacheEntry { + const { resultJson, ...rest } = entry + const result: unknown = JSON.parse(resultJson) + return { ...rest, result } +} + +export const DISABLED_OFFLINE_CACHE: CloudOfflineCache = { + record: () => {}, + lookup: async () => null, + entries: async () => [], + forget: async () => {}, + prune: async () => {}, + clear: async () => {}, + flush: async () => {} +} diff --git a/src/main/hosted-sandbox/cloud-offline-cache.test.ts b/src/main/hosted-sandbox/cloud-offline-cache.test.ts index 6dfc1553dbf..e252e2b201d 100644 --- a/src/main/hosted-sandbox/cloud-offline-cache.test.ts +++ b/src/main/hosted-sandbox/cloud-offline-cache.test.ts @@ -11,6 +11,7 @@ import { import { archiveCheckoutsFromCache, buildOfflineSnapshot, + stringParam, stripAnsi } from './cloud-offline-snapshot' @@ -41,17 +42,17 @@ function setup(limits = {}) { } describe('cloud offline cache', () => { - it('keeps only allowlisted read-only methods', () => { + it('keeps only allowlisted read-only methods', async () => { const { cache } = setup() cache.record('env', 'git.status', { worktree: 'id:w' }, ok({ entries: [] })) cache.record('env', 'agentSession.send', { sessionId: 's' }, ok({})) cache.record('env', 'git.commit', { worktree: 'id:w' }, ok({})) - expect(cache.entries('env').map((e) => e.method)).toEqual(['git.status']) + expect((await cache.entries('env')).map((e) => e.method)).toEqual(['git.status']) expect(OFFLINE_READ_METHODS.has('terminal.send')).toBe(false) - expect(cache.lookup('env', 'agentSession.send', { sessionId: 's' })).toBeNull() + expect(await cache.lookup('env', 'agentSession.send', { sessionId: 's' })).toBeNull() }) - it('seals files at rest and reads them back after a reload', () => { + it('seals files at rest and reads them back after a reload', async () => { const { root, cache } = setup() cache.record( 'env', @@ -60,23 +61,27 @@ describe('cloud offline cache', () => { ok({ items: ['secret subject'] }) ) expect(stableKey('m', { a: 1, b: 2 })).toBe(stableKey('m', { b: 2, a: 1 })) + await cache.flush() const [name] = readdirSync(root) expect(readFileSync(join(root, name!)).toString('utf8')).not.toContain('secret subject') const reloaded = createCloudOfflineCache({ root, codec: testCodec, flushDelayMs: 0 }) - expect(reloaded.lookup('env', 'git.history', { limit: 20, worktree: 'id:w' })?.result).toEqual({ + expect( + (await reloaded.lookup('env', 'git.history', { limit: 20, worktree: 'id:w' }))?.result + ).toEqual({ items: ['secret subject'] }) }) - it('keeps nothing when the OS cannot seal files', () => { + it('keeps nothing when the OS cannot seal files', async () => { const root = mkdtempSync(join(tmpdir(), 'orca-offline-')) const cache = createCloudOfflineCache({ root, codec: null, flushDelayMs: 0 }) cache.record('env', 'git.status', {}, ok({ entries: [] })) - expect(cache.entries('env')).toEqual([]) + expect(await cache.entries('env')).toEqual([]) + await cache.flush() expect(readdirSync(root)).toEqual([]) }) - it('does not re-serialize a key polled again within the interval', () => { + it('does not re-serialize a key polled again within the interval', async () => { const root = mkdtempSync(join(tmpdir(), 'orca-offline-')) let now = 0 const cache = createCloudOfflineCache({ @@ -88,27 +93,24 @@ describe('cloud offline cache', () => { cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['a'] } })) now = 1_000 cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['b'] } })) - expect(cache.lookup('env', 'terminal.read', { terminal: 't' })?.result).toEqual({ + expect((await cache.lookup('env', 'terminal.read', { terminal: 't' }))?.result).toEqual({ terminal: { tail: ['a'] } }) now = 6_000 cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['c'] } })) - expect(cache.lookup('env', 'terminal.read', { terminal: 't' })?.result).toEqual({ + expect((await cache.lookup('env', 'terminal.read', { terminal: 't' }))?.result).toEqual({ terminal: { tail: ['c'] } }) }) - it('evicts the oldest entries past the per-workspace bound and refuses oversized answers', () => { + it('evicts the oldest entries past the per-workspace bound and refuses oversized answers', async () => { const { cache, tick } = setup({ maxEntriesPerEnvironment: 3, maxEntryBytes: 200 }) for (let i = 0; i < 5; i++) { tick() cache.record('env', 'terminal.read', { terminal: `t${i}` }, ok({ terminal: { tail: ['x'] } })) } expect( - cache - .entries('env') - .map((e) => (e.params as { terminal: string }).terminal) - .sort() + (await cache.entries('env')).map((e) => stringParam(e.params, 'terminal')).sort() ).toEqual(['t2', 't3', 't4']) cache.record( 'env', @@ -116,50 +118,53 @@ describe('cloud offline cache', () => { { terminal: 't4' }, ok({ terminal: { tail: ['y'.repeat(500)] } }) ) - expect(cache.lookup('env', 'terminal.read', { terminal: 't4' })).toBeNull() + expect(await cache.lookup('env', 'terminal.read', { terminal: 't4' })).toBeNull() }) - it('holds a bounded number of workspaces in memory and still reads evicted ones from disk', () => { + it('holds a bounded number of workspaces in memory and still reads evicted ones from disk', async () => { const { cache, tick } = setup({ maxLoadedEnvironments: 2 }) for (const env of ['a', 'b', 'c', 'd']) { tick() cache.record(env, 'git.status', { worktree: env }, ok({ branch: env })) } - expect(cache.lookup('a', 'git.status', { worktree: 'a' })?.result).toEqual({ branch: 'a' }) + expect((await cache.lookup('a', 'git.status', { worktree: 'a' }))?.result).toEqual({ + branch: 'a' + }) }) - it('evicts whole least-recent workspaces past the total bound, prunes removed ones, and clears on sign-out', () => { + it('evicts whole least-recent workspaces past the total bound, prunes removed ones, and clears on sign-out', async () => { const { root, cache, tick } = setup({ maxTotalBytes: 900 }) for (const env of ['a', 'b', 'c']) { tick(1000) cache.record(env, 'git.status', { worktree: env }, ok({ entries: ['z'.repeat(300)] })) } + await cache.flush() expect(readdirSync(root).length).toBeLessThan(3) - expect(cache.lookup('c', 'git.status', { worktree: 'c' })).not.toBeNull() - cache.prune(new Set(['c'])) + expect(await cache.lookup('c', 'git.status', { worktree: 'c' })).not.toBeNull() + await cache.prune(new Set(['c'])) expect(readdirSync(root)).toHaveLength(1) - cache.clear() + await cache.clear() expect(existsSync(root)).toBe(false) - expect(cache.lookup('c', 'git.status', { worktree: 'c' })).toBeNull() + expect(await cache.lookup('c', 'git.status', { worktree: 'c' })).toBeNull() }) }) describe('legacy plaintext cache files', () => { - it('are removed whatever the codec', () => { + it('are removed whatever the codec', async () => { for (const sealing of [testCodec, null]) { const root = mkdtempSync(join(tmpdir(), 'orca-offline-')) writeFileSync( join(root, 'abc.json'), '{"version":1,"entries":{"k":{"result":"old plaintext"}}}' ) - createCloudOfflineCache({ root, codec: sealing, flushDelayMs: 0 }) + await createCloudOfflineCache({ root, codec: sealing, flushDelayMs: 0 }).flush() expect(readdirSync(root)).toEqual([]) } }) }) describe('offline snapshot', () => { - it('builds chats, terminals and git state from cached answers', () => { + it('builds chats, terminals and git state from cached answers', async () => { const { cache, tick } = setup() cache.record( 'env', @@ -222,7 +227,7 @@ describe('offline snapshot', () => { } }) ) - const snapshot = buildOfflineSnapshot(cache, 'env', 'w', true) + const snapshot = await buildOfflineSnapshot(cache, 'env', 'w', true) expect(snapshot.asleep).toBe(true) expect(snapshot.terminals).toEqual([ { handle: 'h1', title: 'Dev server', lines: ['ready on :3000'], at: 1000 } @@ -237,7 +242,8 @@ describe('offline snapshot', () => { ['assistant', 'Done.'] ]) expect(snapshot.capturedAt).toBe(1001) - const [checkout] = archiveCheckoutsFromCache(cache, 'env', '/vercel/sandbox/project')! + const [checkout] = + (await archiveCheckoutsFromCache(cache, 'env', '/vercel/sandbox/project')) ?? [] expect(checkout).toMatchObject({ branch: 'feat', head: 'abcdef1', @@ -245,7 +251,7 @@ describe('offline snapshot', () => { }) }) - it('strips terminal escapes', () => { + it('strips terminal escapes', async () => { expect(stripAnsi('\u001b]0;title\u0007a\u001b[1;31mb\u001b[0m\rc')).toBe('abc') }) }) diff --git a/src/main/hosted-sandbox/cloud-offline-cache.ts b/src/main/hosted-sandbox/cloud-offline-cache.ts index 8ab341f12a2..f1b9a19458a 100644 --- a/src/main/hosted-sandbox/cloud-offline-cache.ts +++ b/src/main/hosted-sandbox/cloud-offline-cache.ts @@ -3,28 +3,21 @@ // servers; Orca keeps them on the VM (end-to-end encrypted), so the only copy outside the VM is // this one, on the user's own disk, sealed with the OS keychain. Without a keychain nothing is kept. // Bounded per workspace, in total, and in memory; one file per environment. -import { createHash } from 'node:crypto' -import { - mkdirSync, - readFileSync, - readdirSync, - renameSync, - rmSync, - statSync, - writeFileSync -} from 'node:fs' +import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { + decode, DEFAULT_OFFLINE_CACHE_LIMITS, + DISABLED_OFFLINE_CACHE, + EnvironmentFileSchema, + fileName, OFFLINE_READ_METHODS, removeLegacyPlaintextFiles, stableKey, type CloudOfflineCache, type EnvironmentFile, type OfflineCacheCodec, - type OfflineCacheEntry, - type OfflineCacheLimits, - type StoredEntry + type OfflineCacheLimits } from './cloud-offline-cache-types' export { @@ -37,90 +30,98 @@ export { type OfflineCacheLimits } from './cloud-offline-cache-types' -function fileName(environmentId: string): string { - return `${createHash('sha256').update(environmentId).digest('hex').slice(0, 32)}.bin` -} - -function decode(entry: StoredEntry): OfflineCacheEntry { - const { resultJson, ...rest } = entry - return { ...rest, result: JSON.parse(resultJson) as unknown } -} - -const DISABLED: CloudOfflineCache = { - record: () => {}, - lookup: () => null, - entries: () => [], - forget: () => {}, - prune: () => {}, - clear: () => {}, - flush: () => {} -} - export function createCloudOfflineCache(options: { root: string /** Null: the OS cannot seal files, so nothing is cached. */ codec: OfflineCacheCodec | null limits?: Partial now?: () => number - /** Write delay; 0 writes synchronously (tests). */ + /** Write delay; 0 writes as soon as a record lands (tests). */ flushDelayMs?: number }): CloudOfflineCache { - const codec = options.codec + // All file work runs one task at a time, in call order, off the main thread's sync fs path. + let io: Promise = Promise.resolve() + function serial(task: () => Promise): Promise { + const run = io.then(task, task) + io = run.catch(() => undefined) + return run + } // Plaintext v1 files from the first build are never read; remove them whatever the codec. - removeLegacyPlaintextFiles(options.root) + const legacyRemoved = serial(() => removeLegacyPlaintextFiles(options.root)) + const codec = options.codec if (!codec) { - return DISABLED + return { ...DISABLED_OFFLINE_CACHE, flush: () => legacyRemoved } } const limits = { ...DEFAULT_OFFLINE_CACHE_LIMITS, ...options.limits } const now = options.now ?? Date.now const flushDelayMs = options.flushDelayMs ?? 1_000 // Map insertion order is the LRU order: a touched environment is re-inserted at the end. const loaded = new Map() + const loading = new Map>() const dirty = new Set() + // Bumped by forget/prune/clear so a read that started before them is not cached afterwards. + let generation = 0 let timer: ReturnType | null = null const pathOf = (environmentId: string) => join(options.root, fileName(environmentId)) - function write(environmentId: string): void { - const file = loaded.get(environmentId) - if (!file) { - return - } - mkdirSync(options.root, { recursive: true, mode: 0o700 }) - const target = pathOf(environmentId) - const temp = `${target}.${process.pid}.tmp` - writeFileSync(temp, codec!.encrypt(JSON.stringify(file)), { mode: 0o600 }) - renameSync(temp, target) + function write(file: EnvironmentFile): Promise { + const serialized = codec!.encrypt(JSON.stringify(file)) + return serial(async () => { + await mkdir(options.root, { recursive: true, mode: 0o700 }) + const target = pathOf(file.environmentId) + const temp = `${target}.${process.pid}.tmp` + await writeFile(temp, serialized, { mode: 0o600 }) + await rename(temp, target) + }) } - function load(environmentId: string): EnvironmentFile { - const hit = loaded.get(environmentId) - if (hit) { - loaded.delete(environmentId) - loaded.set(environmentId, hit) - return hit - } - let file: EnvironmentFile = { version: 2, environmentId, updatedAt: 0, entries: {} } + async function readFromDisk(environmentId: string): Promise { try { - const parsed = JSON.parse( - codec!.decrypt(readFileSync(pathOf(environmentId))) - ) as EnvironmentFile - if (parsed.version === 2 && parsed.environmentId === environmentId && parsed.entries) { - file = parsed + const parsed = EnvironmentFileSchema.safeParse( + JSON.parse(codec!.decrypt(await readFile(pathOf(environmentId)))) + ) + if (parsed.success && parsed.data.environmentId === environmentId) { + return parsed.data } } catch { // Missing, unreadable or sealed by another keychain: start empty. A cache is never a source of truth. } - loaded.set(environmentId, file) - while (loaded.size > limits.maxLoadedEnvironments) { - const oldest = loaded.keys().next().value! - if (dirty.has(oldest)) { - write(oldest) - dirty.delete(oldest) - } - loaded.delete(oldest) + return { version: 2, environmentId, updatedAt: 0, entries: {} } + } + + function load(environmentId: string): Promise { + const hit = loaded.get(environmentId) + if (hit) { + loaded.delete(environmentId) + loaded.set(environmentId, hit) + return Promise.resolve(hit) } - return file + const pending = loading.get(environmentId) + if (pending) { + return pending + } + const startedAt = generation + const reading = serial(() => readFromDisk(environmentId)).then((file) => { + loading.delete(environmentId) + const raced = loaded.get(environmentId) + if (raced || startedAt !== generation) { + return raced ?? file + } + loaded.set(environmentId, file) + while (loaded.size > limits.maxLoadedEnvironments) { + const oldest = loaded.keys().next().value! + const evicted = loaded.get(oldest) + if (evicted && dirty.has(oldest)) { + dirty.delete(oldest) + void write(evicted).catch(logWriteFailure) + } + loaded.delete(oldest) + } + return file + }) + loading.set(environmentId, reading) + return reading } function evictWithin(file: EnvironmentFile): void { @@ -138,15 +139,16 @@ export function createCloudOfflineCache(options: { } /** Whole environments go least-recently-written first once the total passes its bound. */ - function evictTotal(): void { + async function evictTotal(): Promise { let files: { name: string; size: number; mtime: number }[] try { - files = readdirSync(options.root) - .filter((name) => name.endsWith('.bin')) - .map((name) => { - const stat = statSync(join(options.root, name)) - return { name, size: stat.size, mtime: stat.mtimeMs } + const names = (await readdir(options.root)).filter((name) => name.endsWith('.bin')) + files = await Promise.all( + names.map(async (name) => { + const info = await stat(join(options.root, name)) + return { name, size: info.size, mtime: info.mtimeMs } }) + ) } catch { return } @@ -155,7 +157,7 @@ export function createCloudOfflineCache(options: { if (total <= limits.maxTotalBytes) { break } - rmSync(join(options.root, file.name), { force: true }) + await rm(join(options.root, file.name), { force: true }) for (const environmentId of loaded.keys()) { if (fileName(environmentId) === file.name) { loaded.delete(environmentId) @@ -165,30 +167,33 @@ export function createCloudOfflineCache(options: { } } - function flush(): void { + function logWriteFailure(error: unknown): void { + console.error(`[orca-cloud] offline cache write failed: ${String(error)}`) + } + + // Records apply after their environment loads; flush waits for those still landing. + const applying = new Set>() + + async function flush(): Promise { if (timer) { clearTimeout(timer) timer = null } - for (const environmentId of dirty) { - try { - write(environmentId) - } catch (error) { - console.error(`[orca-cloud] offline cache write failed: ${String(error)}`) - } - } + await Promise.all(applying) + const files = [...dirty].flatMap((environmentId) => loaded.get(environmentId) ?? []) dirty.clear() - evictTotal() + await Promise.all(files.map((file) => write(file).catch(logWriteFailure))) + await serial(evictTotal) } function markDirty(environmentId: string): void { dirty.add(environmentId) if (flushDelayMs === 0) { - flush() + void flush() return } if (!timer) { - timer = setTimeout(flush, flushDelayMs) + timer = setTimeout(() => void flush(), flushDelayMs) timer.unref?.() } } @@ -198,81 +203,86 @@ export function createCloudOfflineCache(options: { if (!OFFLINE_READ_METHODS.has(method)) { return } - const file = load(environmentId) - const key = stableKey(method, params) - const existing = file.entries[key] const at = now() - if (existing && at - existing.at < limits.minRecordIntervalMs) { - return - } - const resultJson = JSON.stringify(response.result ?? null) - const bytes = resultJson.length + key.length - if (bytes > limits.maxEntryBytes) { - // Too big to keep; don't serve an older, smaller answer as if it were current either. - if (existing) { - delete file.entries[key] - markDirty(environmentId) + const applied = load(environmentId).then((file) => { + const key = stableKey(method, params) + const existing = file.entries[key] + if (existing && at - existing.at < limits.minRecordIntervalMs) { + return } - return - } - file.entries[key] = { - method, - params: params ?? null, - resultJson, - runtimeId: response._meta.runtimeId, - at, - bytes - } - file.updatedAt = at - evictWithin(file) - markDirty(environmentId) + const resultJson = JSON.stringify(response.result ?? null) + const bytes = resultJson.length + key.length + if (bytes > limits.maxEntryBytes) { + // Too big to keep; don't serve an older, smaller answer as if it were current either. + if (existing) { + delete file.entries[key] + markDirty(environmentId) + } + return + } + file.entries[key] = { + method, + params: params ?? null, + resultJson, + runtimeId: response._meta.runtimeId, + at, + bytes + } + file.updatedAt = at + evictWithin(file) + markDirty(environmentId) + }) + applying.add(applied) + void applied.finally(() => applying.delete(applied)) }, - lookup(environmentId, method, params) { + async lookup(environmentId, method, params) { if (!OFFLINE_READ_METHODS.has(method)) { return null } - const entry = load(environmentId).entries[stableKey(method, params)] + await Promise.all(applying) + const entry = (await load(environmentId)).entries[stableKey(method, params)] return entry ? decode(entry) : null }, - entries(environmentId, method) { - return Object.values(load(environmentId).entries) + async entries(environmentId, method) { + await Promise.all(applying) + return Object.values((await load(environmentId)).entries) .filter((entry) => method === undefined || entry.method === method) .sort((a, b) => b.at - a.at) .map(decode) }, forget(environmentId) { + generation++ loaded.delete(environmentId) dirty.delete(environmentId) - rmSync(pathOf(environmentId), { force: true }) + return serial(() => rm(pathOf(environmentId), { force: true })) }, prune(keep) { - const keepFiles = new Set([...keep].map(fileName)) - let names: string[] = [] - try { - names = readdirSync(options.root) - } catch { - return - } - for (const name of names) { - if (!keepFiles.has(name)) { - rmSync(join(options.root, name), { force: true }) - } - } + generation++ for (const environmentId of loaded.keys()) { if (!keep.has(environmentId)) { loaded.delete(environmentId) dirty.delete(environmentId) } } + const keepFiles = new Set([...keep].map(fileName)) + return serial(async () => { + const names = await readdir(options.root).catch(() => []) + for (const name of names) { + if (!keepFiles.has(name)) { + await rm(join(options.root, name), { force: true }) + } + } + }) }, clear() { if (timer) { clearTimeout(timer) timer = null } + generation++ loaded.clear() dirty.clear() - rmSync(options.root, { recursive: true, force: true }) + return serial(() => rm(options.root, { recursive: true, force: true })) }, flush } diff --git a/src/main/hosted-sandbox/cloud-offline-service.ts b/src/main/hosted-sandbox/cloud-offline-service.ts index 70c494d7ae5..89ee90f9d63 100644 --- a/src/main/hosted-sandbox/cloud-offline-service.ts +++ b/src/main/hosted-sandbox/cloud-offline-service.ts @@ -26,9 +26,15 @@ import { type CloudOfflineCache, type OfflineCacheCodec } from './cloud-offline-cache' +import { createOwedWorkBeat } from './cloud-offline-beat' import { setCloudOfflineReset } from './cloud-offline-reset' import { safeStorageCodec, setCloudOfflineObserver } from './cloud-offline-seam' -import { archiveCheckoutsFromCache, buildOfflineSnapshot } from './cloud-offline-snapshot' +import { + archiveCheckoutsFromCache, + buildOfflineSnapshot, + stringParam, + terminalHandlesOf +} from './cloud-offline-snapshot' import { getHostedWorkspaceService, setArchiveCheckoutsProvider } from './hosted-workspace-service' type CloudRuntimeInfo = { @@ -40,6 +46,9 @@ type CloudRuntimeInfo = { const CAPTURE_BUDGET_MS = 8_000 const MAX_CAPTURED_TERMINALS = 12 +/** Background delivery cadence while prompts are owed; doubles while nothing moves. */ +const BEAT_MS = 30_000 +const MAX_BEAT_BACKOFF_STEPS = 4 export type CloudOfflineService = { cache: CloudOfflineCache @@ -155,9 +164,8 @@ export function installCloudOfflineService(deps: { // Chats the window has read stay current: refresh their tail pages. const sessions = [ ...new Set( - cache - .entries(env, 'agentSession.history') - .map((entry) => (entry.params as { sessionId?: string } | null)?.sessionId) + (await cache.entries(env, 'agentSession.history')) + .map((entry) => stringParam(entry.params, 'sessionId')) .filter((id): id is string => typeof id === 'string') ) ].slice(0, 20) @@ -174,15 +182,11 @@ export function installCloudOfflineService(deps: { ) ) ]) - const terminals = ( - (list as { terminals?: { handle: string }[] } | null)?.terminals ?? [] - ).slice(0, MAX_CAPTURED_TERMINALS) + const handles = terminalHandlesOf(list).slice(0, MAX_CAPTURED_TERMINALS) await Promise.all( - terminals.map((terminal) => - readInto(env, 'terminal.read', { terminal: terminal.handle, limit: 400 }, deadline) - ) + handles.map((terminal) => readInto(env, 'terminal.read', { terminal, limit: 400 }, deadline)) ) - cache.flush() + await cache.flush() } async function locate(workspaceId: string): Promise { @@ -218,23 +222,43 @@ export function installCloudOfflineService(deps: { return opening === 'up' }, call: deps.call, - onChange: (workspaceId) => broadcast(CH.queuedPromptsChanged, { workspaceId }), + onChange: (workspaceId) => { + broadcast(CH.queuedPromptsChanged, { workspaceId }) + beat.poke() + }, log }) + // Background: deliver to VMs already up (never wakes) and drop removed workspaces, only while + // prompts are owed. A live answer from a workspace (it is up) delivers its prompts at once. + const beat = createOwedWorkBeat({ + nextDueAt: () => queue.nextAttemptAt(), + pass: async () => { + invalidate() + await queue.drive() + void cache.prune(new Set(runtimes().byEnvironment.keys())) + }, + baseMs: BEAT_MS, + maxBackoffSteps: MAX_BEAT_BACKOFF_STEPS + }) + setCloudOfflineObserver((environmentId, method, params, response) => { - if (response.ok && runtimes().byEnvironment.has(environmentId)) { + const info = runtimes().byEnvironment.get(environmentId) + if (response.ok && info) { cache.record(environmentId, method, params, response) + if (queue.nextAttemptAt() !== null) { + void queue.drive(info.workspaceId) + } } }) setCloudOfflineReset(() => { - cache.clear() + void cache.clear() queue.clear() }) setArchiveCheckoutsProvider(async (workspaceId) => { const info = runtimes().byWorkspace.get(workspaceId) return info - ? archiveCheckoutsFromCache( + ? await archiveCheckoutsFromCache( cache, info.environmentId, info.projectRoot ?? '/vercel/sandbox/project' @@ -247,11 +271,11 @@ export function installCloudOfflineService(deps: { } ipcMain.handle( CH.getSnapshot, - (_event, args: { workspaceId: string }): CloudOfflineSnapshot | null => { + async (_event, args: { workspaceId: string }): Promise => { invalidate() const info = runtimes().byWorkspace.get(args.workspaceId) return info - ? buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep) + ? await buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep) : null } ) @@ -273,14 +297,8 @@ export function installCloudOfflineService(deps: { queue.edit(args.id, args.text) ) - // Background: deliver to VMs that are already up (never wakes), and drop removed workspaces. - const beat = setInterval(() => { - invalidate() - void queue.drive() - cache.prune(new Set(runtimes().byEnvironment.keys())) - }, 30_000) - beat.unref?.() - const startup = setTimeout(() => void queue.drive(), 5_000) + // Startup: deliver what survived a restart (never wakes), and drop removed workspaces. + const startup = setTimeout(() => void beat.runNow(), 5_000) startup.unref?.() return { @@ -288,9 +306,10 @@ export function installCloudOfflineService(deps: { queue, capture, dispose() { - clearInterval(beat) + beat.dispose() clearTimeout(startup) - cache.flush() + void cache.flush() + void queue.flushed() setCloudOfflineObserver(null) setCloudOfflineReset(null) setArchiveCheckoutsProvider(null) diff --git a/src/main/hosted-sandbox/cloud-offline-snapshot.ts b/src/main/hosted-sandbox/cloud-offline-snapshot.ts index 4c8f124ae53..27233aa83a8 100644 --- a/src/main/hosted-sandbox/cloud-offline-snapshot.ts +++ b/src/main/hosted-sandbox/cloud-offline-snapshot.ts @@ -1,4 +1,5 @@ // Turns cached RPC answers into what the asleep view shows, and into archive git metadata. +import { z } from 'zod' import type { CloudOfflineChat, CloudOfflineChatMessage, @@ -26,40 +27,98 @@ export function stripAnsi(text: string): string { return text.replace(ANSI, '').replace(/\r(?!\n)/g, '') } -type HistoryResult = { - ok?: boolean - page?: { - sessionId?: string - items?: { - itemId: string - observedAt: number - body: { kind: string; role?: string; blocks?: { type: string; text?: string }[] } - }[] - } +// Cached answers came from the VM: parse leniently, and a malformed piece is skipped, never trusted. +const Text = z.string() +const ChatItemSchema = z.looseObject({ + itemId: Text, + observedAt: z.number(), + body: z.looseObject({ + kind: Text, + role: Text.optional(), + blocks: z.array(z.looseObject({ type: Text, text: z.unknown().optional() })).optional() + }) +}) +const HistoryResultSchema = z.looseObject({ + page: z + .looseObject({ sessionId: Text.optional(), items: z.array(z.unknown()).optional() }) + .optional() +}) +const TerminalListSchema = z.looseObject({ + terminals: z + .array( + z.looseObject({ + handle: Text, + title: Text.nullable().optional(), + paneTitle: Text.optional() + }) + ) + .catch([]) + .optional() +}) +// `terminal.read` answers `{terminal: RuntimeTerminalRead}`. +const TerminalReadSchema = z.looseObject({ + terminal: z.looseObject({ handle: Text.optional(), tail: z.array(Text).optional() }).optional() +}) +const StatusResultSchema = z.looseObject({ + entries: z + .array(z.looseObject({ path: Text, status: Text, area: Text })) + .catch([]) + .optional(), + head: Text.optional().catch(undefined), + branch: Text.optional().catch(undefined) +}) +const HistoryItemsSchema = z.looseObject({ + items: z + .array( + z.looseObject({ + id: Text, + subject: Text, + author: Text.optional(), + timestamp: z.number().optional() + }) + ) + .catch([]) + .optional() +}) +const ParamsSchema = z.record(z.string(), z.unknown()) + +/** A string field of a cached call's params, if it has one. */ +export function stringParam(params: unknown, key: string): string | undefined { + const parsed = ParamsSchema.safeParse(params) + const value = parsed.success ? parsed.data[key] : undefined + return typeof value === 'string' ? value : undefined +} + +/** Terminal handles from a cached `terminal.list` answer. */ +export function terminalHandlesOf(result: unknown): string[] { + const parsed = TerminalListSchema.safeParse(result) + return parsed.success ? (parsed.data.terminals ?? []).map((terminal) => terminal.handle) : [] } function chatOf(entry: OfflineCacheEntry): CloudOfflineChat | null { - const result = entry.result as HistoryResult - const sessionId = - result?.page?.sessionId ?? (entry.params as { sessionId?: string } | null)?.sessionId - if (!sessionId || !Array.isArray(result?.page?.items)) { + const parsed = HistoryResultSchema.safeParse(entry.result) + const page = parsed.success ? parsed.data.page : undefined + const sessionId = page?.sessionId ?? stringParam(entry.params, 'sessionId') + if (!sessionId || !Array.isArray(page?.items)) { return null } const messages: CloudOfflineChatMessage[] = [] - for (const item of result.page.items) { - if (item.body?.kind !== 'message' || !Array.isArray(item.body.blocks)) { + for (const raw of page.items) { + const item = ChatItemSchema.safeParse(raw) + if (!item.success || item.data.body.kind !== 'message' || !item.data.body.blocks) { continue } - const text = item.body.blocks - .filter((block) => block.type === 'text' && typeof block.text === 'string') - .map((block) => block.text) + const text = item.data.body.blocks + .flatMap((block) => + block.type === 'text' && typeof block.text === 'string' ? [block.text] : [] + ) .join('\n') .trim() - const role = item.body.role + const role = item.data.body.role if (!text || (role !== 'user' && role !== 'assistant' && role !== 'system')) { continue } - messages.push({ itemId: item.itemId, role, text, at: item.observedAt }) + messages.push({ itemId: item.data.itemId, role, text, at: item.data.observedAt }) } return { sessionId, at: entry.at, messages: messages.slice(-MAX_MESSAGES) } } @@ -68,7 +127,7 @@ function chatOf(entry: OfflineCacheEntry): CloudOfflineChat | null { function chatsOf(entries: OfflineCacheEntry[]): CloudOfflineChat[] { const bySession = new Map() for (const entry of entries) { - const direction = (entry.params as { direction?: string } | null)?.direction + const direction = stringParam(entry.params, 'direction') if (direction && direction !== 'tail') { continue } @@ -85,17 +144,15 @@ function chatsOf(entries: OfflineCacheEntry[]): CloudOfflineChat[] { return [...bySession.values()].sort((a, b) => b.at - a.at) } -function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineTerminal[] { +async function terminalsOf( + cache: CloudOfflineCache, + environmentId: string +): Promise { // Every listing contributes titles (a filtered listing can be empty); newest first wins. const titles = new Map() - for (const list of cache.entries(environmentId, 'terminal.list')) { - const listed = - ( - list.result as { - terminals?: { handle: string; title: string | null; paneTitle?: string }[] - } | null - )?.terminals ?? [] - for (const terminal of listed) { + for (const list of await cache.entries(environmentId, 'terminal.list')) { + const parsed = TerminalListSchema.safeParse(list.result) + for (const terminal of parsed.success ? (parsed.data.terminals ?? []) : []) { if (!titles.has(terminal.handle)) { titles.set(terminal.handle, terminal.paneTitle ?? terminal.title ?? null) } @@ -103,12 +160,11 @@ function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOffl } const seen = new Set() const terminals: CloudOfflineTerminal[] = [] - for (const entry of cache.entries(environmentId, 'terminal.read')) { - // `terminal.read` answers `{terminal: RuntimeTerminalRead}`. - const wrapped = entry.result as { terminal?: { handle?: string; tail?: string[] } } | null - const result = wrapped?.terminal - const handle = result?.handle ?? (entry.params as { terminal?: string } | null)?.terminal - if (!handle || seen.has(handle) || !Array.isArray(result?.tail)) { + for (const entry of await cache.entries(environmentId, 'terminal.read')) { + const parsed = TerminalReadSchema.safeParse(entry.result) + const result = parsed.success ? parsed.data.terminal : undefined + const handle = result?.handle ?? stringParam(entry.params, 'terminal') + if (!handle || seen.has(handle) || !result?.tail) { continue } seen.add(handle) @@ -122,22 +178,19 @@ function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOffl return terminals } -type StatusResult = { - entries?: { path: string; status: string; area: string }[] - head?: string - branch?: string -} -type HistoryItems = { - items?: { id: string; subject: string; author?: string; timestamp?: number }[] -} - -function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit | null { - const status = cache.entries(environmentId, 'git.status')[0] - const history = cache.entries(environmentId, 'git.history')[0] +async function gitOf( + cache: CloudOfflineCache, + environmentId: string +): Promise { + const status = (await cache.entries(environmentId, 'git.status'))[0] + const history = (await cache.entries(environmentId, 'git.history'))[0] if (!status && !history) { return null } - const statusResult = (status?.result ?? {}) as StatusResult + const parsedStatus = StatusResultSchema.safeParse(status?.result ?? {}) + const statusResult = parsedStatus.success ? parsedStatus.data : {} + const parsedHistory = HistoryItemsSchema.safeParse(history?.result ?? {}) + const items = parsedHistory.success ? (parsedHistory.data.items ?? []) : [] const entries = statusResult.entries ?? [] return { branch: statusResult.branch?.replace(/^refs\/heads\//, '') ?? null, @@ -146,7 +199,7 @@ function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit .slice(0, MAX_CHANGES) .map(({ path, status: s, area }) => ({ path, status: s, area })), changeCount: entries.length, - commits: (((history?.result ?? {}) as HistoryItems).items ?? []).slice(0, 20).map((item) => ({ + commits: items.slice(0, 20).map((item) => ({ id: item.id, subject: item.subject, author: item.author ?? null, @@ -156,15 +209,15 @@ function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit } } -export function buildOfflineSnapshot( +export async function buildOfflineSnapshot( cache: CloudOfflineCache, environmentId: string, workspaceId: string, asleep: boolean -): CloudOfflineSnapshot { - const git = gitOf(cache, environmentId) - const terminals = terminalsOf(cache, environmentId) - const chats = chatsOf(cache.entries(environmentId, 'agentSession.history')) +): Promise { + const git = await gitOf(cache, environmentId) + const terminals = await terminalsOf(cache, environmentId) + const chats = chatsOf(await cache.entries(environmentId, 'agentSession.history')) const times = [git?.at ?? 0, ...terminals.map((t) => t.at), ...chats.map((c) => c.at)].filter( (t) => t > 0 ) @@ -188,12 +241,12 @@ const STATUS_LETTER: Record = { } /** Archive metadata from the cache, for archiving a VM that is already asleep. */ -export function archiveCheckoutsFromCache( +export async function archiveCheckoutsFromCache( cache: CloudOfflineCache, environmentId: string, projectRoot: string -): HostedArchiveCheckout[] | null { - const git = gitOf(cache, environmentId) +): Promise { + const git = await gitOf(cache, environmentId) if (!git || (!git.branch && !git.head)) { return null } diff --git a/src/main/hosted-sandbox/cloud-transfer-steps.ts b/src/main/hosted-sandbox/cloud-transfer-steps.ts index 86dcfad4383..3a9a9b87fbc 100644 --- a/src/main/hosted-sandbox/cloud-transfer-steps.ts +++ b/src/main/hosted-sandbox/cloud-transfer-steps.ts @@ -5,11 +5,11 @@ // prepare: pack in the VM → download in chunks → fetch the branch into the local repo. // finish (after the window created the local worktree): apply staged/unstaged diffs, untracked // files, and install Claude/Codex sessions remapped to the new path so native resume works. -import { execFile } from 'node:child_process' import { createWriteStream } from 'node:fs' import { cp, lstat, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises' import { join, relative } from 'node:path' -import { promisify } from 'node:util' +import { z } from 'zod' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { CLOUD_TRANSFER_DIR, CLOUD_TRANSFER_LOG, @@ -24,7 +24,6 @@ import { } from '../../shared/hosted-sandbox/cloud-transfer-pack' import type { RuntimeCall } from './hosted-agent-auto-resume' -const run = promisify(execFile) const CHUNK_BYTES = 512 * 1024 const PACK_TIMEOUT_MS = 10 * 60_000 @@ -36,10 +35,33 @@ export type Prepared = { } async function git(cwd: string, args: string[]): Promise { - const { stdout } = await run('git', args, { cwd, maxBuffer: 64 * 1024 * 1024 }) + const { stdout } = await gitExecFileAsync(args, { + cwd, + maxBuffer: 64 * 1024 * 1024, + // Fetching a large bundle can outlast the default read deadline. + timeout: PACK_TIMEOUT_MS + }) return stdout.trim() } +// orcad RPC replies, validated instead of trusted: the VM side is not this process. +const TerminalCreatedSchema = z.looseObject({ + terminal: z.union([z.string(), z.looseObject({ handle: z.string().optional() })]).optional() +}) +const FileStatSchema = z.looseObject({ size: z.number().optional() }) +const FileChunkSchema = z.looseObject({ + contentBase64: z.string(), + bytesRead: z.number().optional(), + eof: z.boolean().optional() +}) + +async function readChunk( + call: RuntimeCall, + params: { worktree: string; relativePath: string; offset: number; length: number } +): Promise> { + return FileChunkSchema.parse(await call('files.readChunk', params)) +} + export async function fileSize(path: string): Promise { return stat(path) .then((s) => s.size) @@ -48,6 +70,14 @@ export async function fileSize(path: string): Promise { export type WorktreeRow = { id?: unknown; path?: unknown } +/** `worktree.list` reply: rows stay loose and pickCloudWorktree checks their fields. */ +export const WorktreeListingSchema = z.looseObject({ + worktrees: z + .array(z.looseObject({ id: z.unknown(), path: z.unknown() })) + .optional() + .catch(undefined) +}) + /** The orcad-side worktree for this workspace: its id, else the VM project root, else the only one. */ export function pickCloudWorktree( rows: WorktreeRow[], @@ -75,14 +105,16 @@ async function runInCloud( commandLine: string, title: string ): Promise { - const created = (await call('terminal.create', { - worktree, - command: commandLine, - title, - presentation: 'background', - focus: false, - activate: false - })) as { terminal?: { handle?: string } | string } + const created = TerminalCreatedSchema.parse( + await call('terminal.create', { + worktree, + command: commandLine, + title, + presentation: 'background', + focus: false, + activate: false + }) + ) const handle = typeof created.terminal === 'string' ? created.terminal : created.terminal?.handle if (!handle) { throw new Error('Could not run a command in the cloud workspace.') @@ -127,16 +159,9 @@ async function readCloudTail( worktree: string, relativePath: string ): Promise { - const stat = (await call('files.stat', { worktree, relativePath })) as { size?: number } + const stat = FileStatSchema.parse(await call('files.stat', { worktree, relativePath })) const offset = Math.max(0, (stat.size ?? 0) - 8192) - const page = (await call('files.readChunk', { - worktree, - relativePath, - offset, - length: 8192 - })) as { - contentBase64: string - } + const page = await readChunk(call, { worktree, relativePath, offset, length: 8192 }) return Buffer.from(page.contentBase64, 'base64').toString('utf8') } @@ -155,14 +180,7 @@ async function readCloudText( worktree: string, relativePath: string ): Promise { - const page = (await call('files.readChunk', { - worktree, - relativePath, - offset: 0, - length: CHUNK_BYTES - })) as { - contentBase64: string - } + const page = await readChunk(call, { worktree, relativePath, offset: 0, length: CHUNK_BYTES }) return Buffer.from(page.contentBase64, 'base64').toString('utf8') } @@ -178,16 +196,7 @@ export async function downloadCloudFile( let offset = 0 try { for (;;) { - const page = (await call('files.readChunk', { - worktree, - relativePath, - offset, - length: CHUNK_BYTES - })) as { - contentBase64: string - bytesRead: number - eof: boolean - } + const page = await readChunk(call, { worktree, relativePath, offset, length: CHUNK_BYTES }) const bytes = Buffer.from(page.contentBase64, 'base64') if (!out.write(bytes)) { await new Promise((resolve) => out.once('drain', () => resolve())) diff --git a/src/main/hosted-sandbox/cloud-transfer.test.ts b/src/main/hosted-sandbox/cloud-transfer.test.ts index 31215da800c..77cbc0285c0 100644 --- a/src/main/hosted-sandbox/cloud-transfer.test.ts +++ b/src/main/hosted-sandbox/cloud-transfer.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from 'node:child_process' -import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' @@ -128,9 +128,12 @@ describe('cloud transfer housekeeping', () => { mkdirSync(join(root, 'abandoned')) writeFileSync(join(root, 'abandoned', 'transfer.tar'), 'x') mkdirSync(join(root, 'kept', 'unapplied'), { recursive: true }) - expect(await sweepCloudTransfers(root, Date.now())).toBe(1) - expect(await sweepCloudTransfers(root, Date.now() + 31 * 86_400_000)).toBe(1) - expect(await sweepCloudTransfers(join(root, 'missing'), Date.now())).toBe(0) + // Fixed times: the leftovers were written at T0; the sweep runs a minute and a month later. + const T0 = 1_800_000_000_000 + utimesSync(join(root, 'kept', 'unapplied'), T0 / 1000, T0 / 1000) + expect(await sweepCloudTransfers(root, T0 + 60_000)).toBe(1) + expect(await sweepCloudTransfers(root, T0 + 31 * 86_400_000)).toBe(1) + expect(await sweepCloudTransfers(join(root, 'missing'), T0)).toBe(0) }) it('installs only session transcripts, never other files from the project folder', async () => { diff --git a/src/main/hosted-sandbox/cloud-transfer.ts b/src/main/hosted-sandbox/cloud-transfer.ts index 0fd95b01bc7..3b72b6c29cc 100644 --- a/src/main/hosted-sandbox/cloud-transfer.ts +++ b/src/main/hosted-sandbox/cloud-transfer.ts @@ -33,7 +33,7 @@ import { packInCloud, pickCloudWorktree, type Prepared, - type WorktreeRow + WorktreeListingSchema } from './cloud-transfer-steps' import { createHostedRuntimeEnvironmentCall } from './hosted-runtime-environment-call' import { findCloudRuntime } from './hosted-workspace-service' @@ -112,7 +112,7 @@ export function installCloudTransferHandlers(deps: { let selector: string | null = null try { step('packing') - const listing = (await call('worktree.list', {})) as { worktrees?: WorktreeRow[] } + const listing = WorktreeListingSchema.parse(await call('worktree.list', {})) const connection = runtime.recipeResult ? getEphemeralVmRecipeResultConnection(runtime.recipeResult) : null diff --git a/src/main/hosted-sandbox/environments/hosted-environment-build-followers.test.ts b/src/main/hosted-sandbox/environments/hosted-environment-build-followers.test.ts new file mode 100644 index 00000000000..030389f4c07 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-build-followers.test.ts @@ -0,0 +1,161 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + createHostedEnvironmentBuildFollowers, + type HostedEnvironmentBuildFollowers +} from './hosted-environment-build-followers' +import { + BUILD_ID, + ENV_ID, + buildView, + line, + ndjsonBody +} from './hosted-environment-fixtures.test-support' + +const finishedBuild = async () => buildView({ status: 'succeeded' }) + +let followers: HostedEnvironmentBuildFollowers | null = null +afterEach(() => followers?.dispose()) + +async function drain( + f: HostedEnvironmentBuildFollowers, + client: Parameters[0] +): Promise<{ text: string; status: string | undefined; polls: number }> { + let cursor = 0 + let text = '' + for (let polls = 1; polls < 50; polls++) { + const result = await f.poll(client, ENV_ID, BUILD_ID, cursor, 1_000) + text += result.chunks.map((chunk) => chunk.data).join('') + cursor = result.cursor + if (result.done) { + return { text, status: result.build?.status, polls } + } + } + throw new Error('never finished') +} + +describe('createHostedEnvironmentBuildFollowers', () => { + it('long-polls the log and skips what a reconnect replays', async () => { + let pass = 0 + const client = { + getBuild: finishedBuild, + openBuildEvents: async () => + pass++ === 0 + ? ndjsonBody([ + line({ type: 'build', build: buildView() }), + line({ type: 'log', stream: 'stdout', data: 'one\n' }), + line({ type: 'log', stream: 'stdout', data: 'tw' }) + ]) + : ndjsonBody([ + line({ type: 'build', build: buildView() }), + line({ type: 'log', stream: 'stdout', data: 'one\ntwo\n' }), + line({ type: 'log', stream: 'stderr', data: 'three\n' }), + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'end' }) + ]) + } + followers = createHostedEnvironmentBuildFollowers({ backoffMs: [1] }) + const result = await drain(followers, client) + expect(result.text).toBe('one\ntwo\nthree\n') + expect(result.status).toBe('succeeded') + }) + + it('reports a watch that gave up as done with its error', async () => { + followers = createHostedEnvironmentBuildFollowers() + const client = { + getBuild: finishedBuild, + openBuildEvents: async () => { + const { HostedEnvironmentRequestError } = await import('./hosted-environment-client') + throw new HostedEnvironmentRequestError('not_found', null, 'gone', 404) + } + } + let cursor = 0 + for (;;) { + const result = await followers.poll(client, ENV_ID, BUILD_ID, cursor, 1_000) + cursor = result.cursor + if (result.done) { + expect(result.error).toBe('That environment or build no longer exists.') + break + } + } + }) + + it('reuses one watch for concurrent pollers of the same build', async () => { + let opens = 0 + const client = { + getBuild: finishedBuild, + openBuildEvents: async () => { + opens++ + return ndjsonBody([ + line({ type: 'build', build: buildView({ status: 'failed', error: 'install_failed' }) }), + line({ type: 'log', stream: 'stdout', data: 'x' }), + line({ type: 'end' }) + ]) + } + } + followers = createHostedEnvironmentBuildFollowers() + const [a, b] = await Promise.all([drain(followers, client), drain(followers, client)]) + expect(a.text).toBe('x') + expect(b.text).toBe('x') + expect(opens).toBe(1) + }) + + it('restarts from the first byte when a cursor outlived its follower', async () => { + const client = { + getBuild: finishedBuild, + openBuildEvents: async () => + ndjsonBody([ + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'log', stream: 'stdout', data: 'a' }), + line({ type: 'log', stream: 'stdout', data: 'b' }), + line({ type: 'end' }) + ]) + } + followers = createHostedEnvironmentBuildFollowers() + // A CLI still holding cursor 40 from a follower that was swept and recreated. + const result = await followers.poll(client, ENV_ID, BUILD_ID, 40, 1_000) + expect(result.truncated).toBe(true) + let text = result.chunks.map((chunk) => chunk.data).join('') + let cursor = result.cursor + let done = result.done + while (!done) { + const next = await followers.poll(client, ENV_ID, BUILD_ID, cursor, 1_000) + expect(next.truncated).toBe(false) + text += next.chunks.map((chunk) => chunk.data).join('') + cursor = next.cursor + done = next.done + } + expect(text).toBe('ab') + }) + + it('caps the log buffered across every follower', async () => { + const chunk = 'x'.repeat(100) + const client = { + getBuild: finishedBuild, + openBuildEvents: async () => + ndjsonBody([ + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + ...Array.from({ length: 10 }, () => line({ type: 'log', stream: 'stdout', data: chunk })), + line({ type: 'end' }) + ]) + } + followers = createHostedEnvironmentBuildFollowers({ maxTotalBufferedChars: 500 }) + const other = 'bld_fedcba9876543210' + // Let both watches finish before reading, so both buffers filled up. + await followers.poll(client, ENV_ID, BUILD_ID, 0, 0) + await followers.poll(client, ENV_ID, other, 0, 0) + const [a, b] = await vi.waitFor(async () => { + const both = await Promise.all([ + followers!.poll(client, ENV_ID, BUILD_ID, 0, 0), + followers!.poll(client, ENV_ID, other, 0, 0) + ]) + expect(both.every((result) => result.done)).toBe(true) + return both + }) + const total = [...a.chunks, ...b.chunks].reduce((sum, entry) => sum + entry.data.length, 0) + expect(total).toBeLessThanOrEqual(500) + expect(a.truncated || b.truncated).toBe(true) + // Each keeps at least its newest chunk. + expect(a.chunks.length).toBeGreaterThan(0) + expect(b.chunks.length).toBeGreaterThan(0) + }) +}) diff --git a/src/main/hosted-sandbox/environments/hosted-environment-build-followers.ts b/src/main/hosted-sandbox/environments/hosted-environment-build-followers.ts new file mode 100644 index 00000000000..dff2d7a343b --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-build-followers.ts @@ -0,0 +1,282 @@ +// Pull-based build following for the CLI: the runtime RPC is request/response, so main keeps one +// watch per build, buffers its log (bounded), and answers cursor polls. Reconnect replays are +// deduplicated here, so a CLI tailing the log never prints a line twice. +import type { HostedEnvironmentBuildView } from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { watchHostedEnvironmentBuild } from './hosted-environment-build-watch' +import type { HostedEnvironmentClient } from './hosted-environment-client' + +export type HostedEnvironmentBuildLogChunk = { stream: 'stdout' | 'stderr'; data: string } + +export type HostedEnvironmentBuildFollowPoll = { + build: HostedEnvironmentBuildView | null + chunks: HostedEnvironmentBuildLogChunk[] + /** Pass back on the next poll. */ + cursor: number + /** Output was lost between polls: the cursor fell behind the buffer (older log dropped), or the + * follower was recreated and the log restarts from its first byte (some lines may repeat). */ + truncated: boolean + /** Final status reached and the whole log delivered (or the watch failed: see `error`). */ + done: boolean + error: string | null +} + +type Follower = { + chunks: { seq: number; chunk: HostedEnvironmentBuildLogChunk }[] + bufferedChars: number + nextSeq: number + build: HostedEnvironmentBuildView | null + done: boolean + error: string | null + lastPollAt: number + stop: () => void + waiters: Set<() => void> +} + +export type HostedEnvironmentBuildFollowers = { + poll( + client: Pick, + envId: string, + buildId: string, + cursor: number, + waitMs: number + ): Promise + dispose(): void +} + +const MAX_BUFFERED_CHARS = 4 * 1024 * 1024 +// Across every follower: 16 followers at their own cap would otherwise hold 64 MB. +const MAX_TOTAL_BUFFERED_CHARS = 16 * 1024 * 1024 +const MAX_CHUNKS_PER_POLL = 2_000 +const MAX_FOLLOWERS = 16 +// A CLI that stopped polling (Ctrl-C) lets its follower go after this. +const ABANDONED_AFTER_MS = 60_000 + +export function createHostedEnvironmentBuildFollowers( + options: { + now?: () => number + idleTimeoutMs?: number + backoffMs?: readonly number[] + maxTotalBufferedChars?: number + } = {} +): HostedEnvironmentBuildFollowers { + const now = options.now ?? Date.now + const maxTotal = options.maxTotalBufferedChars ?? MAX_TOTAL_BUFFERED_CHARS + const followers = new Map() + let totalChars = 0 + + const dropOldest = (follower: Follower): boolean => { + // The newest chunk stays so a poller always has something to resume from. + if (follower.chunks.length <= 1) { + return false + } + const dropped = follower.chunks.shift() + const size = dropped?.chunk.data.length ?? 0 + follower.bufferedChars -= size + totalChars -= size + return true + } + + const enforceTotalCap = (): void => { + while (totalChars > maxTotal) { + let largest: Follower | null = null + for (const candidate of followers.values()) { + if ( + candidate.chunks.length > 1 && + (!largest || candidate.bufferedChars > largest.bufferedChars) + ) { + largest = candidate + } + } + if (!largest || !dropOldest(largest)) { + return + } + } + } + + const remove = (key: string): void => { + const follower = followers.get(key) + if (follower) { + followers.delete(key) + totalChars -= follower.bufferedChars + follower.stop() + for (const wake of follower.waiters) { + wake() + } + } + } + + const sweep = (): void => { + for (const [key, follower] of followers) { + if (now() - follower.lastPollAt > ABANDONED_AFTER_MS) { + remove(key) + } + } + } + + const makeRoom = (): void => { + while (followers.size >= MAX_FOLLOWERS) { + const oldest = followers.keys().next().value + if (oldest === undefined) { + break + } + remove(oldest) + } + } + + // Followers whose CLI went away keep streaming until swept, so sweep on a slow beat too. + // Runs only while followers exist and stops once the last one is swept. + let sweeper: ReturnType | null = null + const ensureSweeper = (): void => { + if (sweeper) { + return + } + sweeper = setTimeout(() => { + sweeper = null + sweep() + if (followers.size > 0) { + ensureSweeper() + } + }, ABANDONED_AFTER_MS / 2) + sweeper.unref?.() + } + + const start = ( + client: Pick, + envId: string, + buildId: string + ): Follower => { + const follower: Follower = { + chunks: [], + bufferedChars: 0, + nextSeq: 0, + build: null, + done: false, + error: null, + lastPollAt: now(), + stop: () => undefined, + waiters: new Set() + } + // Chars of the log already buffered across passes, and how far the current replay has reached. + let deliveredChars = 0 + let replayChars = 0 + const wake = (): void => { + for (const resolve of follower.waiters) { + resolve() + } + follower.waiters.clear() + } + const push = (chunk: HostedEnvironmentBuildLogChunk): void => { + follower.chunks.push({ seq: follower.nextSeq++, chunk }) + follower.bufferedChars += chunk.data.length + totalChars += chunk.data.length + while (follower.bufferedChars > MAX_BUFFERED_CHARS && dropOldest(follower)) { + // Trimmed one chunk. + } + enforceTotalCap() + } + const watch = watchHostedEnvironmentBuild({ + client, + envId, + buildId, + ...(options.idleTimeoutMs ? { idleTimeoutMs: options.idleTimeoutMs } : {}), + ...(options.backoffMs ? { backoffMs: options.backoffMs } : {}), + onEvent: (event) => { + switch (event.type) { + case 'build': + follower.build = event.build + break + case 'reset': + replayChars = 0 + break + case 'reconnecting': + break + case 'log': { + // Skip the part of the replay already delivered, then pass the rest through. + const start = replayChars + replayChars += event.data.length + if (replayChars <= deliveredChars) { + return + } + const fresh = + start >= deliveredChars ? event.data : event.data.slice(deliveredChars - start) + deliveredChars = replayChars + push({ stream: event.stream, data: fresh }) + break + } + case 'end': + follower.done = true + break + case 'error': + follower.done = true + follower.error = event.message + break + } + wake() + } + }) + follower.stop = watch.stop + return follower + } + + return { + async poll(client, envId, buildId, requestedCursor, waitMs) { + const key = `${envId}/${buildId}` + sweep() + ensureSweeper() + let follower = followers.get(key) + if (!follower) { + makeRoom() + follower = start(client, envId, buildId) + followers.set(key, follower) + } + follower.lastPollAt = now() + // A cursor from a previous follower (swept or evicted, then recreated) points past this one's + // log: restart from its first byte and say output may repeat. + const restarted = requestedCursor > follower.nextSeq + const cursor = restarted ? 0 : requestedCursor + const hasNews = (): boolean => follower.done || (follower.chunks.at(-1)?.seq ?? -1) >= cursor + if (!hasNews() && waitMs > 0) { + await new Promise((resolve) => { + const timer = setTimeout(done, waitMs) + timer.unref?.() + function done(): void { + clearTimeout(timer) + follower!.waiters.delete(done) + resolve() + } + follower!.waiters.add(done) + }) + } + const first = follower.chunks[0]?.seq ?? follower.nextSeq + const truncated = restarted || cursor < first + const pending = follower.chunks.filter((entry) => entry.seq >= cursor) + const page = pending.slice(0, MAX_CHUNKS_PER_POLL) + const last = page.at(-1) + const nextCursor = last ? last.seq + 1 : Math.max(cursor, first) + const drained = page.length === pending.length + const result: HostedEnvironmentBuildFollowPoll = { + build: follower.build, + chunks: page.map((entry) => entry.chunk), + cursor: nextCursor, + truncated, + done: follower.done && drained, + error: follower.done && drained ? follower.error : null + } + if (result.done) { + // Keep it briefly so a retried final poll still answers; the sweep drops it later. + follower.lastPollAt = now() - ABANDONED_AFTER_MS + 5_000 + } + return result + }, + dispose() { + if (sweeper) { + clearTimeout(sweeper) + sweeper = null + } + // Deleting the current key while iterating a Map is safe. + for (const key of followers.keys()) { + remove(key) + } + } + } +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-build-watch.test.ts b/src/main/hosted-sandbox/environments/hosted-environment-build-watch.test.ts new file mode 100644 index 00000000000..64496d4142b --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-build-watch.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it, vi } from 'vitest' +import type { OrcaCloudEnvironmentBuildStreamEvent } from '../../../shared/hosted-sandbox/hosted-environment-api' +import { watchHostedEnvironmentBuild } from './hosted-environment-build-watch' +import { HostedEnvironmentRequestError } from './hosted-environment-client' +import { + BUILD_ID, + ENV_ID, + buildView, + line, + ndjsonBody +} from './hosted-environment-fixtures.test-support' + +const noSleep = async (): Promise => undefined +// The build route the idle probe asks; by default the build already finished (no vouching). +const finishedBuild = async () => buildView({ status: 'succeeded' }) + +function summarize(events: OrcaCloudEnvironmentBuildStreamEvent[]): string[] { + return events.map((event) => { + switch (event.type) { + case 'build': + return `build:${event.build.status}` + case 'log': + return `log:${event.stream}:${event.data}` + case 'error': + return `error:${event.message}` + case 'end': + case 'reset': + case 'reconnecting': + return event.type + } + }) +} + +describe('watchHostedEnvironmentBuild', () => { + it('parses lines split across chunks and stops at end once the build is final', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const openBuildEvents = vi.fn(async () => + ndjsonBody([ + line({ type: 'build', build: buildView() }).slice(0, 20), + line({ type: 'build', build: buildView() }).slice(20), + `${line({ type: 'log', stream: 'stdout', data: 'hello\n', at: 5 })}not json\n`, + line({ type: 'log', stream: 'stderr', data: 'warn\n' }), + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'end' }) + ]) + ) + const watch = watchHostedEnvironmentBuild({ + client: { openBuildEvents, getBuild: finishedBuild }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + sleep: noSleep + }) + await watch.done + expect(summarize(events)).toEqual([ + 'build:running', + 'log:stdout:hello\n', + 'log:stderr:warn\n', + 'build:succeeded', + 'end' + ]) + expect(events[1]).toMatchObject({ at: 5 }) + expect(openBuildEvents).toHaveBeenCalledTimes(1) + expect(openBuildEvents).toHaveBeenCalledWith(ENV_ID, BUILD_ID, expect.any(AbortSignal)) + }) + + it('reconnects with a reset when the stream drops before a final status', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const passes = [ + [ + line({ type: 'build', build: buildView() }), + line({ type: 'log', stream: 'stdout', data: 'a' }) + ], + // The control plane ended early (build still booting): follow again. + [ + line({ type: 'build', build: buildView() }), + line({ type: 'error', error: 'stream_failed' }) + ], + [ + line({ type: 'build', build: buildView() }), + line({ type: 'log', stream: 'stdout', data: 'ab' }), + line({ + type: 'build', + build: buildView({ status: 'failed', failedStep: 'install', error: 'install_failed' }) + }), + line({ type: 'end' }) + ] + ] + const sleep = vi.fn(noSleep) + let pass = 0 + const watch = watchHostedEnvironmentBuild({ + client: { openBuildEvents: async () => ndjsonBody(passes[pass++]), getBuild: finishedBuild }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + sleep + }) + await watch.done + expect(summarize(events)).toEqual([ + 'build:running', + 'log:stdout:a', + 'reconnecting', + 'reset', + 'build:running', + 'reconnecting', + 'reset', + 'build:running', + 'log:stdout:ab', + 'build:failed', + 'end' + ]) + expect(sleep).toHaveBeenCalledTimes(2) + }) + + it('treats an end before a final status as a drop', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + let pass = 0 + const watch = watchHostedEnvironmentBuild({ + client: { + getBuild: finishedBuild, + openBuildEvents: async () => + ndjsonBody( + pass++ === 0 + ? [ + line({ type: 'build', build: buildView({ status: 'starting' }) }), + line({ type: 'end' }) + ] + : [ + line({ type: 'build', build: buildView({ status: 'canceled' }) }), + line({ type: 'end' }) + ] + ) + }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + sleep: noSleep + }) + await watch.done + expect(summarize(events)).toEqual([ + 'build:starting', + 'reconnecting', + 'reset', + 'build:canceled', + 'end' + ]) + }) + + it('reconnects after the idle timeout when the build route says the build finished', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + let pass = 0 + const watch = watchHostedEnvironmentBuild({ + client: { + getBuild: finishedBuild, + openBuildEvents: async (_env, _build, signal) => + pass++ === 0 + ? ndjsonBody([line({ type: 'build', build: buildView() })], { hang: true, signal }) + : ndjsonBody([ + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'end' }) + ]) + }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + idleTimeoutMs: 30, + sleep: noSleep + }) + await watch.done + expect(summarize(events)).toEqual([ + 'build:running', + 'reconnecting', + 'reset', + 'build:succeeded', + 'end' + ]) + }) + + it('gives up on a final refusal and after repeated drops without progress', async () => { + const refused: OrcaCloudEnvironmentBuildStreamEvent[] = [] + await watchHostedEnvironmentBuild({ + client: { + getBuild: finishedBuild, + openBuildEvents: async () => { + throw new HostedEnvironmentRequestError('not_found', null, 'gone', 404) + } + }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => refused.push(event), + sleep: noSleep + }).done + expect(summarize(refused)).toEqual(['error:That environment or build no longer exists.']) + + const flaky: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const openBuildEvents = vi.fn(async () => { + throw new HostedEnvironmentRequestError('unavailable', null, 'down') + }) + await watchHostedEnvironmentBuild({ + client: { openBuildEvents, getBuild: finishedBuild }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => flaky.push(event), + maxStalledReconnects: 3, + sleep: noSleep + }).done + expect(openBuildEvents).toHaveBeenCalledTimes(4) + expect(flaky.map((event) => event.type)).toEqual([ + 'reconnecting', + 'reconnecting', + 'reconnecting', + 'error' + ]) + }) + + it('stops quietly on stop() while the stream is open', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const watch = watchHostedEnvironmentBuild({ + client: { + getBuild: finishedBuild, + openBuildEvents: async (_env, _build, signal) => + ndjsonBody([line({ type: 'build', build: buildView() })], { hang: true, signal }) + }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => { + events.push(event) + watch.stop() + }, + sleep: noSleep + }) + await watch.done + expect(summarize(events)).toEqual(['build:running']) + }) + + it('drops a line longer than the bound instead of buffering it', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const huge = 'x'.repeat(1024 * 1024 + 10) + await watchHostedEnvironmentBuild({ + client: { + getBuild: finishedBuild, + openBuildEvents: async () => + ndjsonBody([ + huge, + `${huge}\n`, + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'end' }) + ]) + }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + sleep: noSleep + }).done + expect(summarize(events)).toEqual(['build:succeeded', 'end']) + }) + + it('treats heartbeats as liveness and never forwards them', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const getBuild = vi.fn(finishedBuild) + const encoder = new TextEncoder() + const openBuildEvents = vi.fn(async () => { + let beats = 0 + return new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(line({ type: 'build', build: buildView() }))) + }, + // Six heartbeats 15 ms apart span three idle windows of 30 ms without a single log line. + async pull(controller) { + // ast-grep-ignore: test-no-real-time-wait -- the heartbeats must arrive in real time to straddle the stream's idle window. + await new Promise((resolve) => setTimeout(resolve, 15)) + if (beats++ < 6) { + controller.enqueue(encoder.encode(line({ type: 'heartbeat', at: beats }))) + return + } + controller.enqueue( + encoder.encode( + line({ type: 'build', build: buildView({ status: 'succeeded' }) }) + + line({ type: 'end' }) + ) + ) + controller.close() + } + }) + }) + await watchHostedEnvironmentBuild({ + client: { openBuildEvents, getBuild }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + idleTimeoutMs: 30, + sleep: noSleep + }).done + expect(summarize(events)).toEqual(['build:running', 'build:succeeded', 'end']) + expect(openBuildEvents).toHaveBeenCalledTimes(1) + expect(getBuild).not.toHaveBeenCalled() + }) + + it('keeps a silent stream open while the build route says the build is running', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + const getBuild = vi.fn(async () => buildView()) + const encoder = new TextEncoder() + const openBuildEvents = vi.fn( + async () => + new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(line({ type: 'build', build: buildView() }))) + // An old Worker: no heartbeat, then output after two idle windows. + setTimeout(() => { + controller.enqueue( + encoder.encode( + line({ type: 'log', stream: 'stdout', data: 'done installing\n' }) + + line({ type: 'build', build: buildView({ status: 'succeeded' }) }) + + line({ type: 'end' }) + ) + ) + controller.close() + }, 70) + } + }) + ) + await watchHostedEnvironmentBuild({ + client: { openBuildEvents, getBuild }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + idleTimeoutMs: 30, + sleep: noSleep + }).done + expect(summarize(events)).toEqual([ + 'build:running', + 'log:stdout:done installing\n', + 'build:succeeded', + 'end' + ]) + expect(openBuildEvents).toHaveBeenCalledTimes(1) + expect(getBuild).toHaveBeenCalled() + }) + + it('never gives up on a quiet build the API keeps vouching for', async () => { + const events: OrcaCloudEnvironmentBuildStreamEvent[] = [] + let opens = 0 + const openBuildEvents = vi.fn(async (_env: string, _build: string, signal: AbortSignal) => + // Every pass replays the same status and no new bytes, then goes silent. + ++opens <= 6 + ? ndjsonBody([line({ type: 'build', build: buildView() })], { hang: true, signal }) + : ndjsonBody([ + line({ type: 'build', build: buildView({ status: 'succeeded' }) }), + line({ type: 'end' }) + ]) + ) + await watchHostedEnvironmentBuild({ + client: { openBuildEvents, getBuild: async () => buildView() }, + envId: ENV_ID, + buildId: BUILD_ID, + onEvent: (event) => events.push(event), + idleTimeoutMs: 5, + maxQuietProbes: 1, + maxStalledReconnects: 2, + sleep: noSleep + }).done + expect(openBuildEvents).toHaveBeenCalledTimes(7) + expect(events.at(-1)).toEqual({ type: 'end' }) + expect(events.some((event) => event.type === 'error')).toBe(false) + }) +}) diff --git a/src/main/hosted-sandbox/environments/hosted-environment-build-watch.ts b/src/main/hosted-sandbox/environments/hosted-environment-build-watch.ts new file mode 100644 index 00000000000..0d4fb1a4794 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-build-watch.ts @@ -0,0 +1,321 @@ +// Follows one environment build's ndjson event stream until the build is final. The control plane +// always replays the log from byte 0, so a reconnect first emits `reset` for consumers to clear. +import type { OrcaCloudEnvironmentBuildStreamEvent } from '../../../shared/hosted-sandbox/hosted-environment-api' +import { hostedEnvironmentErrorMessage } from '../../../shared/hosted-sandbox/hosted-environment-errors' +import { + HostedEnvironmentBuildStreamLineSchema, + isTerminalHostedEnvironmentBuildStatus, + type HostedEnvironmentBuildStatus +} from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { + HostedEnvironmentRequestError, + type HostedEnvironmentClient +} from './hosted-environment-client' + +export type HostedEnvironmentBuildWatch = { + stop(): void + /** Settles after the final event (`end` or `error`) or after stop(). */ + done: Promise +} + +export type HostedEnvironmentBuildWatchOptions = { + client: Pick + envId: string + buildId: string + onEvent: (event: OrcaCloudEnvironmentBuildStreamEvent) => void + /** No bytes (heartbeats included) for this long: ask the build route whether it is still alive. */ + idleTimeoutMs?: number + /** Quiet periods in a row the build route vouched for before reopening the stream anyway. */ + maxQuietProbes?: number + /** Delay before reconnect attempt N (1-based), clamped to the last entry. */ + backoffMs?: readonly number[] + /** Reconnects in a row that brought no new status or log before giving up. */ + maxStalledReconnects?: number + sleep?: (ms: number, signal: AbortSignal) => Promise +} + +const DEFAULT_IDLE_TIMEOUT_MS = 90_000 +const DEFAULT_BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000] as const +const DEFAULT_MAX_STALLED_RECONNECTS = 12 +// Older control planes send no heartbeat: a silent install is normal, so a quiet stream whose build +// the API still reports as running is kept; only after this many quiet periods is it reopened. +const DEFAULT_MAX_QUIET_PROBES = 3 +// One ndjson line holds one log chunk; anything bigger is dropped rather than buffered. +const MAX_LINE_CHARS = 1024 * 1024 +const FATAL_CODES = new Set([ + 'not_found', + 'forbidden', + 'unauthorized', + 'invalid_request', + 'not_configured', + 'entitlement_denied' +]) + +type PassOutcome = + | { kind: 'end' } + | { kind: 'fatal'; message: string } + | { kind: 'dropped' } + | { kind: 'stopped' } + +export function watchHostedEnvironmentBuild( + options: HostedEnvironmentBuildWatchOptions +): HostedEnvironmentBuildWatch { + const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS + const backoff = options.backoffMs ?? DEFAULT_BACKOFF_MS + const maxStalled = options.maxStalledReconnects ?? DEFAULT_MAX_STALLED_RECONNECTS + const sleep = options.sleep ?? abortableSleep + const maxQuietProbes = options.maxQuietProbes ?? DEFAULT_MAX_QUIET_PROBES + const stopper = new AbortController() + + let lastStatus: HostedEnvironmentBuildStatus | null = null + let emittedAny = false + // Progress is measured against the longest replay so far: a replay of the same bytes is no progress. + let bestLogChars = 0 + let passLogChars = 0 + let passStatusChanged = false + // The build route confirmed the build alive during a quiet pass: its reconnect is not a stall. + let passVouched = false + + const emit = (event: OrcaCloudEnvironmentBuildStreamEvent): void => { + if (stopper.signal.aborted) { + return + } + try { + options.onEvent(event) + } catch (error) { + console.warn('[cloud-environments] build event listener threw:', error) + } + } + + const handleLine = (line: string): 'end' | 'error' | null => { + if (!line.trim()) { + return null + } + let raw: unknown + try { + raw = JSON.parse(line) + } catch { + return null + } + const parsed = HostedEnvironmentBuildStreamLineSchema.safeParse(raw) + if (!parsed.success) { + return null + } + const value = parsed.data + switch (value.type) { + case 'build': + if (value.build.status !== lastStatus) { + passStatusChanged = true + } + lastStatus = value.build.status + emittedAny = true + emit({ type: 'build', build: value.build }) + return null + case 'log': + passLogChars += value.data.length + emittedAny = true + emit({ + type: 'log', + stream: value.stream, + data: value.data, + ...(value.at === undefined ? {} : { at: value.at }) + }) + return null + case 'heartbeat': + // The read already re-armed the idle timer; nothing for consumers. + return null + case 'end': + return 'end' + case 'error': + return 'error' + } + } + + const runPass = async (): Promise => { + passLogChars = 0 + passStatusChanged = false + passVouched = false + const pass = new AbortController() + const onStop = (): void => pass.abort() + stopper.signal.addEventListener('abort', onStop, { once: true }) + let idle: ReturnType | null = null + let quietProbes = 0 + // A quiet stream is not a dead one: ask the build route before tearing the stream down. + const onIdle = async (): Promise => { + idle = null + if (pass.signal.aborted) { + return + } + quietProbes += 1 + const build = await options.client + .getBuild(options.envId, options.buildId, pass.signal) + .catch(() => null) + if (pass.signal.aborted) { + return + } + const alive = build !== null && !isTerminalHostedEnvironmentBuildStatus(build.status) + if (alive) { + passVouched = true + } + if (alive && build.status === lastStatus && quietProbes < maxQuietProbes) { + armIdle(false) + return + } + // Finished, changed status, unreachable, or quiet too long: reopen to replay the truth. + pass.abort() + } + const armIdle = (fromData = true): void => { + if (idle) { + clearTimeout(idle) + } + if (fromData) { + quietProbes = 0 + } + idle = setTimeout(() => void onIdle(), idleTimeoutMs) + idle.unref?.() + } + try { + armIdle() + let body: ReadableStream + try { + body = await options.client.openBuildEvents(options.envId, options.buildId, pass.signal) + } catch (error) { + if (stopper.signal.aborted) { + return { kind: 'stopped' } + } + if (error instanceof HostedEnvironmentRequestError && FATAL_CODES.has(error.code)) { + return { kind: 'fatal', message: hostedEnvironmentErrorMessage(error.code, error.reason) } + } + return { kind: 'dropped' } + } + if (emittedAny) { + emit({ type: 'reset' }) + } + const reader = body.getReader() + const decoder = new TextDecoder() + let buffered = '' + let discarding = false + try { + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + armIdle() + buffered += decoder.decode(value, { stream: true }) + let newline = buffered.indexOf('\n') + while (newline !== -1) { + const line = buffered.slice(0, newline) + buffered = buffered.slice(newline + 1) + if (discarding) { + discarding = false + } else { + const verdict = handleLine(line) + if (verdict === 'end') { + return lastStatus && isTerminalHostedEnvironmentBuildStatus(lastStatus) + ? { kind: 'end' } + : // Ended before a final status (still booting): follow again. + { kind: 'dropped' } + } + if (verdict === 'error') { + return { kind: 'dropped' } + } + } + newline = buffered.indexOf('\n') + } + if (buffered.length > MAX_LINE_CHARS) { + buffered = '' + discarding = true + } + } + const tail = discarding ? '' : buffered + decoder.decode() + if ( + tail && + handleLine(tail) === 'end' && + lastStatus && + isTerminalHostedEnvironmentBuildStatus(lastStatus) + ) { + return { kind: 'end' } + } + } catch { + // Aborted by idle timer or stop, or the socket broke. + } finally { + reader.cancel().catch(() => undefined) + } + return stopper.signal.aborted ? { kind: 'stopped' } : { kind: 'dropped' } + } finally { + if (idle) { + clearTimeout(idle) + } + stopper.signal.removeEventListener('abort', onStop) + pass.abort() + } + } + + const run = async (): Promise => { + let stalled = 0 + for (;;) { + const outcome = await runPass() + if (outcome.kind === 'stopped' || stopper.signal.aborted) { + return + } + if (outcome.kind === 'end') { + emit({ type: 'end' }) + return + } + if (outcome.kind === 'fatal') { + emit({ type: 'error', message: outcome.message }) + return + } + // A replay of the same status and bytes is no progress, unless the API vouched the build alive. + const progressed = passStatusChanged || passVouched || passLogChars > bestLogChars + bestLogChars = Math.max(bestLogChars, passLogChars) + stalled = progressed ? 1 : stalled + 1 + if (stalled > maxStalled) { + emit({ + type: 'error', + message: 'Lost the connection to this build’s log. Reopen it to retry.' + }) + return + } + emit({ type: 'reconnecting' }) + try { + await sleep(backoff[Math.min(stalled, backoff.length) - 1] ?? 1_000, stopper.signal) + } catch { + return + } + if (stopper.signal.aborted) { + return + } + } + } + + const done = run().catch((error: unknown) => { + console.warn('[cloud-environments] build watch failed:', error) + emit({ type: 'error', message: 'Could not follow this build.' }) + }) + + return { + stop: () => stopper.abort(), + done + } +} + +function abortableSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new Error('aborted')) + return + } + const timer = setTimeout(() => { + signal.removeEventListener('abort', onAbort) + resolve() + }, ms) + timer.unref?.() + const onAbort = (): void => { + clearTimeout(timer) + reject(new Error('aborted')) + } + signal.addEventListener('abort', onAbort, { once: true }) + }) +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.test.ts b/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.test.ts new file mode 100644 index 00000000000..af140e5223a --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it, vi } from 'vitest' +import { + followCloudEnvironmentBuild, + resolveCloudEnvironment, + setCloudEnvironmentInstallScript, + showCloudEnvironment +} from './hosted-environment-cli-operations' +import type { HostedEnvironmentBuildFollowers } from './hosted-environment-build-followers' +import type { HostedEnvironmentClient } from './hosted-environment-client' +import { toHostedEnvironmentError } from './hosted-environment-service' +import { + BUILD_ID, + ENV_ID, + buildView, + environmentEntry +} from './hosted-environment-fixtures.test-support' + +const OTHER_ID = 'env_ffffffffffffffffffff' + +function fakeClient(overrides: Partial = {}): HostedEnvironmentClient { + const client: HostedEnvironmentClient = { + list: vi.fn(async () => ({ + environments: [environmentEntry(), environmentEntry({ id: OTHER_ID, name: 'Mobile' })], + canAdmin: true + })), + get: vi.fn(async () => ({ + environment: environmentEntry(), + builds: [buildView({ number: 4, id: 'bld_aaaaaaaaaaaaaaaa' }), buildView()], + canAdmin: true + })), + create: vi.fn(), + update: vi.fn(async () => environmentEntry({ revision: 3 })), + remove: vi.fn(), + startBuild: vi.fn(), + getBuild: vi.fn(), + cancelBuild: vi.fn(), + activateBuild: vi.fn(), + staleness: vi.fn(async () => { + throw new Error('github down') + }), + openBuildEvents: vi.fn(), + ...overrides + } + return client +} + +describe('hosted environment CLI operations', () => { + it('picks the first environment by default, else by id or case-insensitive name', async () => { + const client = fakeClient() + expect((await resolveCloudEnvironment(client, undefined)).entry.id).toBe(ENV_ID) + expect((await resolveCloudEnvironment(client, OTHER_ID)).entry.name).toBe('Mobile') + expect((await resolveCloudEnvironment(client, 'mobile')).entry.id).toBe(OTHER_ID) + const missing = await resolveCloudEnvironment(client, 'nope').catch((e: unknown) => e) + expect(toHostedEnvironmentError(missing).message).toBe( + 'No environment named "nope". Known: Web, Mobile.' + ) + }) + + it('sends only the install script, guarded by the revision it read', async () => { + const client = fakeClient() + await setCloudEnvironmentInstallScript(client, undefined, 'npm ci\n') + expect(client.update).toHaveBeenCalledWith(ENV_ID, { + installScript: 'npm ci\n', + expectedRevision: 2 + }) + }) + + it('shows the environment even when the staleness check fails', async () => { + const data = await showCloudEnvironment(fakeClient(), undefined) + expect(data.staleness).toBeNull() + expect(data.environment).not.toHaveProperty('activeBuild') + expect(data.environments).toEqual([ + { id: ENV_ID, name: 'Web' }, + { id: OTHER_ID, name: 'Mobile' } + ]) + }) + + it('resolves a build number to its id before following', async () => { + const poll = vi.fn(async () => ({ + build: null, + chunks: [], + cursor: 0, + truncated: false, + done: false, + error: null + })) + const followers: HostedEnvironmentBuildFollowers = { poll, dispose: vi.fn() } + const client = fakeClient() + await followCloudEnvironmentBuild(client, followers, { build: '3' }) + expect(poll).toHaveBeenLastCalledWith(client, ENV_ID, BUILD_ID, 0, 0) + const unknown = await followCloudEnvironmentBuild(client, followers, { build: '99' }).catch( + (e: unknown) => e + ) + expect(toHostedEnvironmentError(unknown).code).toBe('not_found') + }) +}) diff --git a/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.ts b/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.ts new file mode 100644 index 00000000000..1dd2625c70e --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-cli-operations.ts @@ -0,0 +1,156 @@ +// What `orca cloud env ...` may do, resolved against the control plane. Deliberately narrow: an agent +// configuring the environment reads it, replaces the install script and runs builds. Repos, env var +// names, machine size and secrets stay with people in Settings. +import type { + CloudEnvironmentBuildsData, + CloudEnvironmentFollowData, + CloudEnvironmentRef, + CloudEnvironmentSetInstallScriptData, + CloudEnvironmentShowData, + CloudEnvironmentStartBuildData +} from '../../../shared/hosted-sandbox/hosted-environment-cli-contract' +import { + isHostedEnvironmentBuildId, + type HostedEnvironmentListEntry +} from '../../../shared/hosted-sandbox/hosted-environment-wire' +import type { HostedEnvironmentBuildFollowers } from './hosted-environment-build-followers' +import { + HostedEnvironmentUserError, + type HostedEnvironmentClient +} from './hosted-environment-client' + +const knownEnvironmentNames = new Map() + +export async function resolveCloudEnvironment( + client: Pick, + selector: string | undefined +): Promise<{ entry: HostedEnvironmentListEntry; all: CloudEnvironmentRef[]; canAdmin: boolean }> { + const { environments, canAdmin } = await client.list() + const all = environments.map((environment) => ({ id: environment.id, name: environment.name })) + knownEnvironmentNames.clear() + for (const environment of all) { + knownEnvironmentNames.set(environment.id, environment.name) + } + if (environments.length === 0) { + throw new HostedEnvironmentUserError( + 'not_found', + 'no_environments', + 'This org has no environment yet. Create one in Settings > Orca Cloud.' + ) + } + if (!selector) { + return { entry: environments[0], all, canAdmin } + } + const lowered = selector.toLowerCase() + const entry = + environments.find((environment) => environment.id === selector) ?? + environments.find((environment) => environment.name.toLowerCase() === lowered) + if (!entry) { + throw new HostedEnvironmentUserError( + 'not_found', + 'environment_not_found', + `No environment named "${selector.slice(0, 128)}". Known: ${all.map((env) => env.name).join(', ')}.` + ) + } + return { entry, all, canAdmin } +} + +const ref = (entry: { id: string; name: string }): CloudEnvironmentRef => ({ + id: entry.id, + name: entry.name +}) + +export async function showCloudEnvironment( + client: HostedEnvironmentClient, + selector: string | undefined, + refresh = false +): Promise { + const { entry, all, canAdmin } = await resolveCloudEnvironment(client, selector) + const { activeBuild, latestBuild, ...environment } = entry + // Staleness asks GitHub; a failure there should not hide the environment itself. + const staleness = await client.staleness(entry.id, refresh).catch(() => null) + return { environment, activeBuild, latestBuild, staleness, canAdmin, environments: all } +} + +export async function setCloudEnvironmentInstallScript( + client: HostedEnvironmentClient, + selector: string | undefined, + script: string, + expectedRevision?: number +): Promise { + const { entry } = await resolveCloudEnvironment(client, selector) + // Only the script: this surface must never carry repos, env var names or machine size. + const environment = await client.update(entry.id, { + installScript: script, + expectedRevision: expectedRevision ?? entry.revision + }) + return { environment } +} + +export async function startCloudEnvironmentBuild( + client: HostedEnvironmentClient, + selector: string | undefined +): Promise { + const { entry } = await resolveCloudEnvironment(client, selector) + return { environment: ref(entry), build: await client.startBuild(entry.id) } +} + +export async function listCloudEnvironmentBuilds( + client: HostedEnvironmentClient, + selector: string | undefined +): Promise { + const { entry } = await resolveCloudEnvironment(client, selector) + const detail = await client.get(entry.id) + return { environment: ref(entry), builds: detail.builds } +} + +export async function followCloudEnvironmentBuild( + client: HostedEnvironmentClient, + followers: HostedEnvironmentBuildFollowers, + args: { env?: string; build: string; cursor?: number; waitMs?: number } +): Promise { + // Polls repeat every few seconds: once the CLI holds both ids, skip the list round trip. + const envId = args.env + const known = envId ? knownEnvironmentNames.get(envId) : undefined + const environment = + envId && known !== undefined && isHostedEnvironmentBuildId(args.build) + ? { id: envId, name: known } + : ref((await resolveCloudEnvironment(client, args.env)).entry) + const buildId = await resolveBuildId(client, environment.id, args.build) + const poll = await followers.poll( + client, + environment.id, + buildId, + args.cursor ?? 0, + args.waitMs ?? 0 + ) + return { environment, ...poll } +} + +async function resolveBuildId( + client: Pick, + envId: string, + selector: string +): Promise { + if (isHostedEnvironmentBuildId(selector)) { + return selector + } + const number = /^#?(\d{1,9})$/.exec(selector)?.[1] + if (!number) { + throw new HostedEnvironmentUserError( + 'invalid_request', + 'build', + 'Pass a build number (e.g. 12) or a build id (bld_...).' + ) + } + const { builds } = await client.get(envId) + const build = builds.find((candidate) => candidate.number === Number(number)) + if (!build) { + throw new HostedEnvironmentUserError( + 'not_found', + 'build_not_found', + `Build #${number} is not among the 30 most recent builds; pass its id instead.` + ) + } + return build.id +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-client.test.ts b/src/main/hosted-sandbox/environments/hosted-environment-client.test.ts new file mode 100644 index 00000000000..e1664a83c09 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-client.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it, vi } from 'vitest' +import { EnvironmentProviderError } from '../../environment-providers/environment-provider-driver' +import { + createHostedEnvironmentClient, + HostedEnvironmentRequestError +} from './hosted-environment-client' +import { toHostedEnvironmentError } from './hosted-environment-service' +import { + BUILD_ID, + ENV_ID, + buildView, + environmentEntry +} from './hosted-environment-fixtures.test-support' + +const BASE = 'https://control.example.test' + +function client(handler: (url: URL, init: RequestInit) => Response | Promise) { + const fetchMock = vi.fn(async (input: URL, init: RequestInit) => handler(new URL(input), init)) + return { + fetchMock, + client: createHostedEnvironmentClient({ + baseUrl: BASE, + getAccessToken: async () => 'tok', + fetch: fetchMock + }) + } +} + +const json = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) + +describe('createHostedEnvironmentClient', () => { + it('lists environments with the bearer token and never follows redirects', async () => { + const { client: c, fetchMock } = client(() => + json({ environments: [{ ...environmentEntry(), futureField: 1 }], canAdmin: true }) + ) + const result = await c.list() + expect(result.canAdmin).toBe(true) + expect(result.environments[0].name).toBe('Web') + const [url, init] = fetchMock.mock.calls[0] + expect(String(url)).toBe(`${BASE}/v1/environments`) + expect(init?.redirect).toBe('manual') + expect(init?.headers).toMatchObject({ authorization: 'Bearer tok' }) + }) + + it('maps each route to its method and path', async () => { + const calls: string[] = [] + const { client: c } = client((url, init) => { + calls.push(`${init.method} ${url.pathname}${url.search}`) + if (url.pathname.endsWith('/staleness')) { + return json({ + staleness: { + checkedAt: 1, + activeBuildId: null, + configChanged: false, + recommendation: 'something_new', + repos: [] + } + }) + } + if ( + url.pathname.endsWith('/activate') || + init.method === 'PATCH' || + (init.method === 'POST' && url.pathname === '/v1/environments') + ) { + return json({ environment: environmentEntry() }) + } + if (init.method === 'DELETE') { + return json({ deleted: true }) + } + if (url.pathname.includes('/builds')) { + return json({ build: buildView() }) + } + return json({ environment: environmentEntry(), builds: [buildView()], canAdmin: false }) + }) + await c.get(ENV_ID) + await c.create({ name: 'Web', repos: [{ url: 'acme/web' }] }) + await c.update(ENV_ID, { installScript: 'x', expectedRevision: 2 }) + await c.remove(ENV_ID) + await c.startBuild(ENV_ID) + await c.getBuild(ENV_ID, BUILD_ID) + await c.cancelBuild(ENV_ID, BUILD_ID) + await c.activateBuild(ENV_ID, BUILD_ID) + const staleness = await c.staleness(ENV_ID, true) + expect(staleness.recommendation).toBe('unknown') + expect(calls).toEqual([ + `GET /v1/environments/${ENV_ID}`, + 'POST /v1/environments', + `PATCH /v1/environments/${ENV_ID}`, + `DELETE /v1/environments/${ENV_ID}`, + `POST /v1/environments/${ENV_ID}/builds`, + `GET /v1/environments/${ENV_ID}/builds/${BUILD_ID}`, + `POST /v1/environments/${ENV_ID}/builds/${BUILD_ID}/cancel`, + `POST /v1/environments/${ENV_ID}/builds/${BUILD_ID}/activate`, + `GET /v1/environments/${ENV_ID}/staleness?refresh=1` + ]) + }) + + it('refuses ids that could change the path', async () => { + const { client: c, fetchMock } = client(() => json({})) + await expect(c.get('env_../../v1/sandboxes')).rejects.toMatchObject({ code: 'invalid_request' }) + await expect(c.cancelBuild(ENV_ID, 'bld_x/../y')).rejects.toMatchObject({ + code: 'invalid_request' + }) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('maps control-plane refusals to friendly errors', async () => { + const { client: c } = client(() => json({ error: 'conflict', reason: 'stale_revision' }, 409)) + const error = await c.update(ENV_ID, { installScript: 'x' }).catch((e: unknown) => e) + expect(error).toBeInstanceOf(HostedEnvironmentRequestError) + expect(toHostedEnvironmentError(error)).toEqual({ + code: 'conflict', + reason: 'stale_revision', + message: 'Someone else saved changes. Reload to see them.' + }) + const admin = createHostedEnvironmentClient({ + baseUrl: BASE, + getAccessToken: async () => 'tok', + fetch: async () => json({ error: 'forbidden', reason: 'admin_required' }, 403) + }) + expect( + toHostedEnvironmentError(await admin.startBuild(ENV_ID).catch((e: unknown) => e)) + ).toMatchObject({ + message: 'Only owners and admins can change the environment. Ask an owner or admin.' + }) + }) + + it('treats redirects, oversized and malformed bodies as errors', async () => { + const redirect = client( + () => new Response(null, { status: 302, headers: { location: 'https://evil.test' } }) + ) + await expect(redirect.client.list()).rejects.toMatchObject({ code: 'invalid_response' }) + const huge = client(() => new Response('x'.repeat(3 * 1024 * 1024))) + await expect(huge.client.list()).rejects.toMatchObject({ code: 'invalid_response' }) + const wrong = client(() => json({ environments: 'nope' })) + await expect(wrong.client.list()).rejects.toMatchObject({ code: 'invalid_response' }) + }) + + it('reports sign-in problems from token minting', async () => { + const c = createHostedEnvironmentClient({ + baseUrl: BASE, + getAccessToken: async () => { + throw new EnvironmentProviderError('unauthorized', 'Sign in to Orca to use Orca Cloud.') + }, + fetch: async () => json({}) + }) + expect(toHostedEnvironmentError(await c.list().catch((e: unknown) => e))).toMatchObject({ + code: 'unauthorized', + message: 'Sign in to Orca to use Orca Cloud.' + }) + }) + + it('requires an https control plane', () => { + expect(() => + createHostedEnvironmentClient({ + baseUrl: 'http://control.example.test', + getAccessToken: async () => '' + }) + ).toThrow(/HTTPS/) + }) +}) diff --git a/src/main/hosted-sandbox/environments/hosted-environment-client.ts b/src/main/hosted-sandbox/environments/hosted-environment-client.ts new file mode 100644 index 00000000000..9fb3a3ee02e --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-client.ts @@ -0,0 +1,252 @@ +// HTTPS client for org environments on the Orca sandbox control plane (/v1/environments). Same +// bearer as /v1/sandboxes; the desktop holds only a short-lived Orca token. +import type { z } from 'zod' +import { + HostedEnvironmentBuildResponseSchema, + HostedEnvironmentDeletedResponseSchema, + HostedEnvironmentDetailResponseSchema, + HostedEnvironmentListResponseSchema, + HostedEnvironmentResponseSchema, + HostedEnvironmentStalenessResponseSchema, + isHostedEnvironmentBuildId, + isHostedEnvironmentId, + type HostedEnvironmentBuildView, + type HostedEnvironmentCreateInput, + type HostedEnvironmentDetailResponse, + type HostedEnvironmentListResponse, + type HostedEnvironmentStaleness, + type HostedEnvironmentUpdateInput, + type HostedEnvironmentView +} from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { + errorFromResponse, + HostedEnvironmentRequestError, + parseBaseUrl, + readJson, + transportError +} from './hosted-environment-http' + +export { + HostedEnvironmentRequestError, + HostedEnvironmentUserError +} from './hosted-environment-http' + +export type HostedEnvironmentClient = { + list(signal?: AbortSignal): Promise + get(envId: string, signal?: AbortSignal): Promise + create(input: HostedEnvironmentCreateInput, signal?: AbortSignal): Promise + update( + envId: string, + patch: HostedEnvironmentUpdateInput, + signal?: AbortSignal + ): Promise + remove(envId: string, signal?: AbortSignal): Promise<{ deleted: true }> + startBuild(envId: string, signal?: AbortSignal): Promise + getBuild( + envId: string, + buildId: string, + signal?: AbortSignal + ): Promise + cancelBuild( + envId: string, + buildId: string, + signal?: AbortSignal + ): Promise + activateBuild( + envId: string, + buildId: string, + signal?: AbortSignal + ): Promise + staleness( + envId: string, + refresh?: boolean, + signal?: AbortSignal + ): Promise + /** Opens the ndjson event stream; the caller owns the body and its cancellation via `signal`. */ + openBuildEvents( + envId: string, + buildId: string, + signal: AbortSignal + ): Promise> +} + +export type HostedEnvironmentClientOptions = { + baseUrl: string + getAccessToken: (signal?: AbortSignal) => Promise + fetch?: (input: URL, init: RequestInit) => Promise + /** Per-call ceiling for JSON routes; the event stream has none (the watcher runs an idle timer). */ + timeoutMs?: number +} + +const DEFAULT_TIMEOUT_MS = 60_000 + +export function createHostedEnvironmentClient( + options: HostedEnvironmentClientOptions +): HostedEnvironmentClient { + const base = parseBaseUrl(options.baseUrl) + const doFetch = options.fetch ?? fetch + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS + + async function send( + method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + path: string, + init: { body?: unknown; signal?: AbortSignal; accept?: string; timeout?: AbortSignal } + ): Promise { + const signals = [init.signal, init.timeout].filter((s): s is AbortSignal => s !== undefined) + const signal = signals.length > 1 ? AbortSignal.any(signals) : signals[0] + try { + const token = await options.getAccessToken(signal) + return await doFetch(new URL(path, base), { + method, + headers: { + authorization: `Bearer ${token}`, + accept: init.accept ?? 'application/json', + ...(init.body === undefined ? {} : { 'content-type': 'application/json' }) + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + // Why: a redirect could forward the bearer token to another origin. + redirect: 'manual', + signal + }) + } catch (error) { + throw transportError(error, init.signal, init.timeout) + } + } + + async function call( + method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + path: string, + schema: z.ZodType, + init: { body?: unknown; signal?: AbortSignal } = {} + ): Promise { + const timeout = AbortSignal.timeout(timeoutMs) + const response = await send(method, path, { ...init, timeout }) + let payload: unknown + try { + payload = await readJson(response) + } catch (error) { + throw transportError(error, init.signal, timeout) + } + if (!response.ok) { + throw errorFromResponse(response.status, payload) + } + const parsed = schema.safeParse(payload) + if (!parsed.success) { + throw new HostedEnvironmentRequestError( + 'invalid_response', + null, + 'Orca Cloud returned an unexpected response.', + response.status + ) + } + return parsed.data + } + + return { + list: (signal) => + call('GET', 'v1/environments', HostedEnvironmentListResponseSchema, { signal }), + get: async (envId, signal) => + call('GET', envPath(envId), HostedEnvironmentDetailResponseSchema, { signal }), + create: async (input, signal) => + ( + await call('POST', 'v1/environments', HostedEnvironmentResponseSchema, { + body: input, + signal + }) + ).environment, + update: async (envId, patch, signal) => + ( + await call('PATCH', envPath(envId), HostedEnvironmentResponseSchema, { + body: patch, + signal + }) + ).environment, + remove: async (envId, signal) => { + await call('DELETE', envPath(envId), HostedEnvironmentDeletedResponseSchema, { signal }) + return { deleted: true } + }, + startBuild: async (envId, signal) => + ( + await call('POST', envPath(envId, '/builds'), HostedEnvironmentBuildResponseSchema, { + signal + }) + ).build, + getBuild: async (envId, buildId, signal) => + ( + await call('GET', buildPath(envId, buildId), HostedEnvironmentBuildResponseSchema, { + signal + }) + ).build, + cancelBuild: async (envId, buildId, signal) => + ( + await call( + 'POST', + buildPath(envId, buildId, '/cancel'), + HostedEnvironmentBuildResponseSchema, + { signal } + ) + ).build, + activateBuild: async (envId, buildId, signal) => + ( + await call( + 'POST', + buildPath(envId, buildId, '/activate'), + HostedEnvironmentResponseSchema, + { + signal + } + ) + ).environment, + staleness: async (envId, refresh, signal) => + ( + await call( + 'GET', + envPath(envId, refresh ? '/staleness?refresh=1' : '/staleness'), + HostedEnvironmentStalenessResponseSchema, + { signal } + ) + ).staleness, + openBuildEvents: async (envId, buildId, signal) => { + // Only the response headers are bounded; the body streams for the whole build. + const headerTimeout = AbortSignal.timeout(timeoutMs) + const controller = new AbortController() + const onAbort = (): void => controller.abort() + signal.addEventListener('abort', onAbort, { once: true }) + headerTimeout.addEventListener('abort', onAbort, { once: true }) + let response: Response + try { + response = await send('GET', buildPath(envId, buildId, '/events'), { + signal: controller.signal, + accept: 'application/x-ndjson' + }) + } catch (error) { + throw transportError(error, signal, headerTimeout) + } finally { + headerTimeout.removeEventListener('abort', onAbort) + } + if (!response.ok || !response.body) { + const payload = await readJson(response).catch(() => null) + throw errorFromResponse(response.status, payload) + } + return response.body + } + } +} + +function envPath(envId: string, suffix = ''): string { + if (!isHostedEnvironmentId(envId)) { + throw new HostedEnvironmentRequestError( + 'invalid_request', + 'environment_id', + 'Invalid environment id.' + ) + } + return `v1/environments/${envId}${suffix}` +} + +function buildPath(envId: string, buildId: string, suffix = ''): string { + if (!isHostedEnvironmentBuildId(buildId)) { + throw new HostedEnvironmentRequestError('invalid_request', 'build_id', 'Invalid build id.') + } + return envPath(envId, `/builds/${buildId}${suffix}`) +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-fixtures.test-support.ts b/src/main/hosted-sandbox/environments/hosted-environment-fixtures.test-support.ts new file mode 100644 index 00000000000..4eaf75ba946 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-fixtures.test-support.ts @@ -0,0 +1,91 @@ +import type { + HostedEnvironmentBuildView, + HostedEnvironmentListEntry +} from '../../../shared/hosted-sandbox/hosted-environment-wire' + +export const ENV_ID = 'env_03b89d4bf1c74787a7ce' +export const BUILD_ID = 'bld_0123456789abcdef' + +export function buildView( + overrides: Partial = {} +): HostedEnvironmentBuildView { + return { + id: BUILD_ID, + number: 3, + status: 'running', + active: false, + createdBy: 'user_1', + createdAt: 1_700_000_000_000, + startedAt: 1_700_000_002_000, + snapshotStartedAt: null, + finishedAt: null, + durationMs: null, + activatable: false, + error: null, + failedStep: null, + revision: 2, + machineSize: 'standard', + repos: [{ url: 'https://github.com/acme/web.git', branch: 'main', commit: null }], + diskUsedBytes: null, + diskTotalBytes: null, + logBytes: 0, + logTruncated: false, + ...overrides + } +} + +export function environmentEntry( + overrides: Partial = {} +): HostedEnvironmentListEntry { + return { + id: ENV_ID, + name: 'Web', + repos: [{ url: 'https://github.com/acme/web.git', defaultBranch: 'main' }], + installScript: 'pnpm install', + envVarNames: ['NPM_TOKEN'], + machineSize: 'standard', + activeBuildId: null, + revision: 2, + createdBy: 'user_1', + updatedBy: 'user_1', + createdAt: 1_700_000_000_000, + updatedAt: 1_700_000_000_000, + activeBuild: null, + latestBuild: null, + ...overrides + } +} + +/** A body that yields the given ndjson chunks, then either closes or stays open until aborted. */ +export function ndjsonBody( + chunks: readonly string[], + options: { hang?: boolean; signal?: AbortSignal } = {} +): ReadableStream { + const encoder = new TextEncoder() + let index = 0 + return new ReadableStream({ + pull(controller) { + if (index < chunks.length) { + controller.enqueue(encoder.encode(chunks[index++])) + return + } + if (!options.hang) { + controller.close() + return + } + return new Promise((resolve) => { + const fail = (): void => { + controller.error(new Error('aborted')) + resolve() + } + if (options.signal?.aborted) { + fail() + } else { + options.signal?.addEventListener('abort', fail, { once: true }) + } + }) + } + }) +} + +export const line = (value: unknown): string => `${JSON.stringify(value)}\n` diff --git a/src/main/hosted-sandbox/environments/hosted-environment-http.ts b/src/main/hosted-sandbox/environments/hosted-environment-http.ts new file mode 100644 index 00000000000..1f1f97aa5d2 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-http.ts @@ -0,0 +1,115 @@ +// Transport helpers for the environment client: bounded JSON reads and error mapping. +import { HostedEnvironmentErrorResponseSchema } from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { EnvironmentProviderError } from '../../environment-providers/environment-provider-driver' + +// A detail view carries 30 builds plus a 20k-char script; list carries every environment. +const MAX_RESPONSE_BYTES = 2 * 1024 * 1024 + +/** `code` is the control plane's error (`forbidden`, `conflict`, ...) or a transport one. */ +export class HostedEnvironmentRequestError extends Error { + constructor( + readonly code: string, + readonly reason: string | null, + message: string, + readonly status: number | null = null + ) { + super(message) + this.name = 'HostedEnvironmentRequestError' + } +} + +/** A desktop-side refusal whose message is already written for the user (or the agent). */ +export class HostedEnvironmentUserError extends HostedEnvironmentRequestError {} + +export function parseBaseUrl(value: string): URL { + const url = new URL(value.endsWith('/') ? value : `${value}/`) + const loopback = url.hostname === '127.0.0.1' || url.hostname === 'localhost' + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) { + throw new Error('Orca Cloud control plane must be HTTPS.') + } + if (url.username || url.password || url.search || url.hash) { + throw new Error('Orca Cloud control plane URL must not carry credentials, query or fragment.') + } + return url +} + +/** Reads at most MAX_RESPONSE_BYTES; a larger body reads as unparseable instead of buffering it all. */ +export async function readJson(response: Response): Promise { + if (!response.body) { + return null + } + const reader = response.body.getReader() + const chunks: Uint8Array[] = [] + let total = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + total += value.byteLength + if (total > MAX_RESPONSE_BYTES) { + await reader.cancel().catch(() => undefined) + return null + } + chunks.push(value) + } + const text = Buffer.concat(chunks).toString('utf8') + try { + return text ? JSON.parse(text) : null + } catch { + return null + } +} + +export function errorFromResponse(status: number, payload: unknown): HostedEnvironmentRequestError { + const parsed = HostedEnvironmentErrorResponseSchema.safeParse(payload) + if (parsed.success) { + return new HostedEnvironmentRequestError( + parsed.data.error, + parsed.data.reason ?? null, + `Orca Cloud refused the request (${parsed.data.error}${parsed.data.reason ? `: ${parsed.data.reason}` : ''}).`, + status + ) + } + if (status >= 300 && status < 400) { + return new HostedEnvironmentRequestError( + 'invalid_response', + null, + 'Orca Cloud answered with a redirect.', + status + ) + } + return new HostedEnvironmentRequestError( + status === 401 + ? 'unauthorized' + : status === 403 + ? 'forbidden' + : status === 404 + ? 'not_found' + : 'unavailable', + null, + `Orca Cloud request failed (HTTP ${status}).`, + status + ) +} + +export function transportError( + error: unknown, + callerSignal: AbortSignal | undefined, + timeoutSignal: AbortSignal | undefined +): HostedEnvironmentRequestError { + if (error instanceof HostedEnvironmentRequestError) { + return error + } + // Token minting reports sign-in problems as provider errors. + if (error instanceof EnvironmentProviderError) { + return new HostedEnvironmentRequestError(error.code, error.reason ?? null, error.message) + } + if (callerSignal?.aborted) { + return new HostedEnvironmentRequestError('aborted', null, 'Orca Cloud request was cancelled.') + } + if (timeoutSignal?.aborted) { + return new HostedEnvironmentRequestError('timeout', null, 'Orca Cloud did not answer in time.') + } + return new HostedEnvironmentRequestError('unavailable', null, 'Could not reach Orca Cloud.') +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-install.ts b/src/main/hosted-sandbox/environments/hosted-environment-install.ts new file mode 100644 index 00000000000..59571c2d9fc --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-install.ts @@ -0,0 +1,26 @@ +import { app } from 'electron' +import { withCloudBuildDefaults } from '../../cloud-build-defaults' +import { getHostedSandboxConfig } from '../hosted-sandbox-config' +import { + createHostedEnvironmentService, + getHostedEnvironmentService, + registerHostedEnvironmentService, + type HostedEnvironmentService +} from './hosted-environment-service' + +/** One service per process, built on first use so startup never reads the profile for it. */ +export function installHostedEnvironmentService(): HostedEnvironmentService { + const existing = getHostedEnvironmentService() + if (existing) { + return existing + } + const service = createHostedEnvironmentService(() => + getHostedSandboxConfig( + app.getPath('userData'), + withCloudBuildDefaults(process.env), + app.isPackaged + ) + ) + registerHostedEnvironmentService(service) + return service +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.test.ts b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.test.ts new file mode 100644 index 00000000000..09b2d00e520 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.test.ts @@ -0,0 +1,69 @@ +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { readRepoSetupImports } from './hosted-environment-repo-imports' +import { toHostedEnvironmentError } from './hosted-environment-service' + +let base: string +let repo: string +let outside: string + +beforeEach(async () => { + base = await mkdtemp(join(tmpdir(), 'orca-env-imports-')) + repo = join(base, 'repo') + outside = join(base, 'outside') + await mkdir(repo) + await mkdir(outside) +}) + +afterEach(async () => { + await rm(base, { recursive: true, force: true }) +}) + +const devcontainer = (name: string) => + JSON.stringify({ postCreateCommand: 'npm ci', containerEnv: { [name]: 'value' } }) + +describe('readRepoSetupImports', () => { + it('reads names and a setup script from a registered repo', async () => { + await mkdir(join(repo, '.devcontainer')) + await writeFile(join(repo, '.devcontainer/devcontainer.json'), devcontainer('NPM_TOKEN')) + const result = await readRepoSetupImports(repo, [repo]) + expect(result.envVarNames).toEqual(['NPM_TOKEN']) + expect(result.installScript).toContain('npm ci') + expect(result.sources).toEqual([ + 'Dev Container (.devcontainer/devcontainer.json)', + 'Environment variable names (.devcontainer/devcontainer.json)' + ]) + }) + + it('refuses a folder that is not a project in Orca', async () => { + const error = await readRepoSetupImports(outside, [repo]).catch((e: unknown) => e) + expect(toHostedEnvironmentError(error)).toMatchObject({ + code: 'not_found', + reason: 'repo_not_registered' + }) + const relative = await readRepoSetupImports('repo', [repo]).catch((e: unknown) => e) + expect(toHostedEnvironmentError(relative).code).toBe('invalid_request') + }) + + it('ignores config reached through a symlink that leaves the repo', async () => { + await mkdir(join(outside, 'dc')) + await writeFile(join(outside, 'dc/devcontainer.json'), devcontainer('LEAKED_NAME')) + await symlink(join(outside, 'dc'), join(repo, '.devcontainer')) + await writeFile(join(outside, 'secrets.env'), 'OUTSIDE_SECRET=1\n') + await symlink(join(outside, 'secrets.env'), join(repo, '.env.example')) + const result = await readRepoSetupImports(repo, [repo]) + expect(result.envVarNames).toEqual([]) + expect(result.installScript).toBeUndefined() + expect(result.sources).toEqual([]) + }) + + it('follows a symlink that stays inside the repo', async () => { + await mkdir(join(repo, 'config')) + await writeFile(join(repo, 'config/env.example'), 'INSIDE_NAME=\n') + await symlink(join(repo, 'config/env.example'), join(repo, '.env.example')) + const result = await readRepoSetupImports(repo, [repo]) + expect(result.envVarNames).toEqual(['INSIDE_NAME']) + }) +}) diff --git a/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts new file mode 100644 index 00000000000..6f66155bdd8 --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts @@ -0,0 +1,81 @@ +// Seeds a new org environment from a local checkout: the first setup command Orca's importers find +// (Conductor, dev container, Cursor, ...) and the env var NAMES those configs expect. No values. +import { readFile, realpath, stat } from 'node:fs/promises' +import { isAbsolute, join, relative, sep } from 'node:path' +import type { OrcaCloudRepoSetupImports } from '../../../shared/hosted-sandbox/hosted-environment-api' +import { HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS } from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { inspectSetupEnvVarNames } from '../../../shared/workspace-setup/setup-env-var-name-imports' +import { SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES } from '../../../shared/workspace-setup/setup-script-import-limits' +import { inspectSetupScriptImportCandidates } from '../../../shared/workspace-setup/setup-script-imports' +import { HostedEnvironmentUserError } from './hosted-environment-client' + +/** + * `registeredRepoPaths` are the local checkouts in main's repo store; the renderer can only name + * one of them. Every file is resolved through realpath and must stay inside the repo, so a + * symlinked `.devcontainer/` or `.conductor/` cannot point the importer elsewhere on disk. + */ +export async function readRepoSetupImports( + repoPath: unknown, + registeredRepoPaths: readonly string[] +): Promise { + if (typeof repoPath !== 'string' || !isAbsolute(repoPath) || repoPath.length > 4096) { + throw new HostedEnvironmentUserError('invalid_request', 'repo_path', 'Invalid repository path.') + } + const root = await realpath(repoPath).catch(() => null) + const registered = await Promise.all( + registeredRepoPaths.map((path) => realpath(path).catch(() => null)) + ) + if (!root || !registered.includes(root)) { + throw new HostedEnvironmentUserError( + 'not_found', + 'repo_not_registered', + 'That folder is not a project in Orca. Add it as a project first.' + ) + } + if (!(await stat(root).catch(() => null))?.isDirectory()) { + throw new HostedEnvironmentUserError('not_found', null, 'Repository folder not found.') + } + + /** The file's real path when it is a regular file inside the repo, else null. */ + const resolveInside = async (relativePath: string): Promise => { + if (isAbsolute(relativePath)) { + return null + } + const real = await realpath(join(root, relativePath)).catch(() => null) + if (!real) { + return null + } + const rel = relative(root, real) + if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { + return null + } + const info = await stat(real).catch(() => null) + return info?.isFile() && info.size <= SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES ? real : null + } + const fileExists = async (relativePath: string): Promise => + (await resolveInside(relativePath)) !== null + const read = async (relativePath: string): Promise => { + const real = await resolveInside(relativePath) + return real ? readFile(real, 'utf8').catch(() => null) : null + } + + const [candidates, envNames] = await Promise.all([ + inspectSetupScriptImportCandidates(read, { fileExists }), + inspectSetupEnvVarNames(read) + ]) + const sources: string[] = [] + const first = candidates.find( + (candidate) => candidate.setup.length <= HOSTED_ENVIRONMENT_MAX_INSTALL_SCRIPT_CHARS + ) + if (first) { + sources.push(`${first.label} (${first.files.join(', ')})`) + } + for (const file of envNames.files) { + sources.push(`Environment variable names (${file})`) + } + return { + envVarNames: envNames.names, + ...(first ? { installScript: first.setup } : {}), + sources + } +} diff --git a/src/main/hosted-sandbox/environments/hosted-environment-service.ts b/src/main/hosted-sandbox/environments/hosted-environment-service.ts new file mode 100644 index 00000000000..233a4d82fbb --- /dev/null +++ b/src/main/hosted-sandbox/environments/hosted-environment-service.ts @@ -0,0 +1,92 @@ +// The desktop's one handle on org environments: a lazily built control-plane client plus the +// Result mapping the IPC and runtime RPC surfaces share. +import type { + OrcaCloudEnvironmentError, + OrcaCloudEnvironmentResult +} from '../../../shared/hosted-sandbox/hosted-environment-api' +import { hostedEnvironmentError } from '../../../shared/hosted-sandbox/hosted-environment-errors' +import type { HostedSandboxConfig } from '../hosted-sandbox-config' +import { + createHostedEnvironmentClient, + HostedEnvironmentRequestError, + HostedEnvironmentUserError, + type HostedEnvironmentClient +} from './hosted-environment-client' + +export type HostedEnvironmentService = { + isConfigured(): boolean + /** Throws HostedEnvironmentRequestError('not_configured') when this build has no control plane. */ + client(): HostedEnvironmentClient +} + +export function createHostedEnvironmentService( + loadConfig: () => HostedSandboxConfig | null, + fetchImpl?: typeof fetch +): HostedEnvironmentService { + let resolved: { client: HostedEnvironmentClient | null } | null = null + const resolve = (): HostedEnvironmentClient | null => { + if (!resolved) { + const config = loadConfig() + resolved = { + client: config + ? createHostedEnvironmentClient({ + baseUrl: config.controlPlaneUrl, + getAccessToken: config.getAccessToken, + fetch: fetchImpl + }) + : null + } + } + return resolved.client + } + return { + isConfigured: () => resolve() !== null, + client: () => { + const client = resolve() + if (!client) { + throw new HostedEnvironmentRequestError( + 'not_configured', + null, + 'Orca Cloud is not set up in this build of Orca.' + ) + } + return client + } + } +} + +export function toHostedEnvironmentError(error: unknown): OrcaCloudEnvironmentError { + if (error instanceof HostedEnvironmentUserError) { + return { + code: error.code, + ...(error.reason ? { reason: error.reason } : {}), + message: error.message + } + } + if (error instanceof HostedEnvironmentRequestError) { + return hostedEnvironmentError(error.code, error.reason) + } + console.warn('[cloud-environments] unexpected failure:', error) + return hostedEnvironmentError('unavailable') +} + +export async function hostedEnvironmentResult( + work: () => Promise +): Promise> { + try { + return { ok: true, data: await work() } + } catch (error) { + return { ok: false, error: toHostedEnvironmentError(error) } + } +} + +let registered: HostedEnvironmentService | null = null + +/** Desktop main publishes the service for the runtime RPC (CLI); a headless host has none. */ +export function registerHostedEnvironmentService(service: HostedEnvironmentService | null): void { + registered = service +} + +export function getHostedEnvironmentService(): HostedEnvironmentService | null { + return registered +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-config.ts b/src/main/hosted-sandbox/hosted-sandbox-config.ts index f076fdd9dee..9ff1fe9448a 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-config.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-config.ts @@ -122,7 +122,7 @@ async function mintSandboxToken( /** Dev builds only: sign with the dev operator key the dev control plane trusts (issuer orca-sandbox-dev-test). */ async function mintDevSandboxToken( keyFile: string, - cloud: { userId: string; activeOrgId?: string } | undefined, + cloud: { userId: string; activeOrgId?: string; displayName?: string } | undefined, env: NodeJS.ProcessEnv ): Promise<{ token: string; expiresAt: number }> { const userId = cloud?.userId @@ -144,6 +144,8 @@ async function mintDevSandboxToken( }) const payload = encode({ sub: userId ?? 'desktop-dogfood', + // Auth mints a display-name claim; dev tokens carry one so labels look real. + ...(cloud?.displayName ? { name: cloud.displayName.slice(0, 80) } : {}), ...org, purpose: 'sandbox', iss: 'orca-sandbox-dev-test', diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.ts index 2882ecb4e41..1d450b648ad 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.ts @@ -2,6 +2,7 @@ // Which provider runs the VM (Vercel today) is a control-plane detail the desktop never sees. import { HOSTED_SANDBOX_MACHINE_SIZES, + ORCA_CLOUD_IDLE_SLEEP_MINUTES, type HostedSandboxMachineSize, type HostedSandboxReadyResponse, type HostedSandboxView @@ -30,7 +31,7 @@ export const HOSTED_SANDBOX_CAPABILITIES: HostedEnvironmentCapabilities = Object maxSessionMs: 24 * 60 * 60_000, fsPersistOnStop: true, egressInjection: true, - idleStopMs: 20 * 60_000 + idleStopMs: ORCA_CLOUD_IDLE_SLEEP_MINUTES * 60_000 }) const STATUS: Record = { @@ -154,7 +155,13 @@ export function toReady(ready: HostedSandboxReadyResponse): HostedEnvironmentRea const handle: EnvironmentHandle = { driverId: HOSTED_SANDBOX_DRIVER_ID, environmentId: ready.sandbox.id, - driverState: { sandboxId: ready.sandbox.id } + driverState: { + sandboxId: ready.sandbox.id, + // Booted from an org environment build: dependencies are installed, so no setup-script nudge. + ...(ready.sandbox.environmentBuildId + ? { environmentBuildId: ready.sandbox.environmentBuildId } + : {}) + } } return { handle, diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 5d38a08eb28..a00846d3c98 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -25,6 +25,10 @@ import { import { createHostedSessionRegistry, type HostedSessionRegistry } from './hosted-session-registry' import { registerCloudShareHandlers } from './hosted-sandbox-share-ipc' import { setHostedSessionSync } from './hosted-session-sync' +import { + registerOrcaCloudEnvironmentHandlers, + type OrcaCloudEnvironmentRepoSource +} from '../ipc/cloud-environments/orca-cloud-environment-handlers' import { installCloudTransferHandlers } from './cloud-transfer' import { installCloudOfflineService, setCloudOfflineService } from './cloud-offline-service' import { @@ -46,7 +50,10 @@ export function getHostedSandboxControlPlaneClient(): HostedSandboxControlPlaneC return controlPlaneClient } -export function installHostedSandbox(): void { +/** `repos` is main's repo store: org-environment repo imports only read checkouts listed there. */ +export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): void { + // Idempotent; answers isConfigured() = false itself when this build has no control plane. + registerOrcaCloudEnvironmentHandlers(repos ? { repos } : {}) if (installed) { return } diff --git a/src/main/hosted-sandbox/hosted-sandbox-request.ts b/src/main/hosted-sandbox/hosted-sandbox-request.ts index 08b7f7358ac..e2d9a93ad47 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-request.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-request.ts @@ -21,7 +21,7 @@ const DEFAULT_TIMEOUTS = { boot: 180_000, control: 60_000 } const MAX_RESPONSE_BYTES = 256 * 1024 export type HostedSandboxRequest = ( - method: 'GET' | 'POST' | 'DELETE', + method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, schema: z.ZodType, init: { body?: unknown; kind: 'boot' | 'control'; signal?: AbortSignal } @@ -36,7 +36,7 @@ export function createHostedSandboxRequest( const timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts } return async function call( - method: 'GET' | 'POST' | 'DELETE', + method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, schema: z.ZodType, init: { body?: unknown; kind: 'boot' | 'control'; signal?: AbortSignal } diff --git a/src/main/ipc/cloud-environments/orca-cloud-environment-handlers.ts b/src/main/ipc/cloud-environments/orca-cloud-environment-handlers.ts new file mode 100644 index 00000000000..5ac91a6cef7 --- /dev/null +++ b/src/main/ipc/cloud-environments/orca-cloud-environment-handlers.ts @@ -0,0 +1,281 @@ +// IPC for window.api.orcaCloudEnvironments. Every call answers a Result so the renderer never sees +// a thrown control-plane error; build watches stream to the window that opened them. +import { randomUUID } from 'node:crypto' +import { ipcMain, type IpcMainInvokeEvent, type WebContents } from 'electron' +import { z } from 'zod' +import { getRepoDialableSshTargetId } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import { + ORCA_CLOUD_ENVIRONMENT_BUILD_EVENT_CHANNEL, + type OrcaCloudEnvironmentBuildEvent, + type OrcaCloudEnvironmentResult +} from '../../../shared/hosted-sandbox/hosted-environment-api' +import { hostedEnvironmentError } from '../../../shared/hosted-sandbox/hosted-environment-errors' +import { + HOSTED_ENVIRONMENT_BUILD_ID, + HOSTED_ENVIRONMENT_ID, + HostedEnvironmentCreateInputSchema, + HostedEnvironmentUpdateInputSchema +} from '../../../shared/hosted-sandbox/hosted-environment-wire' +import { watchHostedEnvironmentBuild } from '../../hosted-sandbox/environments/hosted-environment-build-watch' +import { installHostedEnvironmentService } from '../../hosted-sandbox/environments/hosted-environment-install' +import { readRepoSetupImports } from '../../hosted-sandbox/environments/hosted-environment-repo-imports' +import { + hostedEnvironmentResult, + type HostedEnvironmentService +} from '../../hosted-sandbox/environments/hosted-environment-service' + +const EnvId = z.string().regex(HOSTED_ENVIRONMENT_ID) +const BuildId = z.string().regex(HOSTED_ENVIRONMENT_BUILD_ID) +// A settings page shows one build log at a time; more than this per window is a leak. +const MAX_WATCHES_PER_SENDER = 8 + +const CHANNELS = [ + 'orcaCloudEnvironments:isConfigured', + 'orcaCloudEnvironments:list', + 'orcaCloudEnvironments:get', + 'orcaCloudEnvironments:create', + 'orcaCloudEnvironments:update', + 'orcaCloudEnvironments:remove', + 'orcaCloudEnvironments:startBuild', + 'orcaCloudEnvironments:cancelBuild', + 'orcaCloudEnvironments:activateBuild', + 'orcaCloudEnvironments:staleness', + 'orcaCloudEnvironments:watchBuild', + 'orcaCloudEnvironments:unwatchBuild', + 'orcaCloudEnvironments:readRepoSetupImports' +] as const + +type Watch = { + senderId: number + stop: () => void + /** Sends one last event to the renderer that owns the watch. */ + notify: (event: OrcaCloudEnvironmentBuildEvent['event']) => void +} + +export type OrcaCloudEnvironmentRepoSource = { getRepos(): Repo[] } + +const EVICTED_MESSAGE = + 'Stopped following this build: too many build logs are open in this window. Reopen it to resume.' + +// Main's repo store, set by whoever wires the handlers; without it no repo can be imported from. +let repoSource: OrcaCloudEnvironmentRepoSource | null = null + +/** Local checkouts the user added to Orca; SSH-backed repos never fall through to local reads. */ +function registeredLocalRepoPaths(): string[] { + return (repoSource?.getRepos() ?? []) + .filter((repo) => !getRepoDialableSshTargetId(repo)) + .map((repo) => repo.path) +} + +function invalid(field: string): OrcaCloudEnvironmentResult { + return { ok: false, error: hostedEnvironmentError('invalid_request', field) } +} + +let registered = false + +/** Idempotent: startup may wire Orca Cloud more than once. */ +export function registerOrcaCloudEnvironmentHandlers( + options: { repos?: OrcaCloudEnvironmentRepoSource; service?: HostedEnvironmentService } = {} +): void { + if (options.repos) { + repoSource = options.repos + } + if (registered) { + return + } + const service = options.service ?? installHostedEnvironmentService() + registered = true + for (const channel of CHANNELS) { + ipcMain.removeHandler(channel) + } + const watches = new Map() + const trackedSenders = new Set() + + const stopWatch = (watchId: string): void => { + const watch = watches.get(watchId) + if (watch) { + watches.delete(watchId) + watch.stop() + } + } + + const trackSender = (sender: WebContents): void => { + if (trackedSenders.has(sender.id)) { + return + } + trackedSenders.add(sender.id) + const senderId = sender.id + const cleanup = (): void => { + trackedSenders.delete(senderId) + for (const [watchId, watch] of watches) { + if (watch.senderId === senderId) { + stopWatch(watchId) + } + } + } + sender.once('destroyed', cleanup) + // A reload keeps the WebContents but drops every renderer listener. + sender.on('did-start-navigation', (details) => { + if (details.isMainFrame && !details.isSameDocument) { + for (const [watchId, watch] of watches) { + if (watch.senderId === senderId) { + stopWatch(watchId) + } + } + } + }) + } + + ipcMain.handle('orcaCloudEnvironments:isConfigured', () => service.isConfigured()) + + ipcMain.handle('orcaCloudEnvironments:list', () => + hostedEnvironmentResult(() => service.client().list()) + ) + + ipcMain.handle('orcaCloudEnvironments:get', (_event, envId: unknown) => { + const id = EnvId.safeParse(envId) + return id.success + ? hostedEnvironmentResult(() => service.client().get(id.data)) + : invalid('environment_id') + }) + + ipcMain.handle('orcaCloudEnvironments:create', (_event, input: unknown) => { + const parsed = HostedEnvironmentCreateInputSchema.safeParse(input) + if (!parsed.success) { + return invalid(parsed.error.issues[0]?.path.join('.') || 'input') + } + return hostedEnvironmentResult(async () => ({ + environment: await service.client().create(parsed.data) + })) + }) + + ipcMain.handle('orcaCloudEnvironments:update', (_event, envId: unknown, patch: unknown) => { + const id = EnvId.safeParse(envId) + const parsed = HostedEnvironmentUpdateInputSchema.safeParse(patch) + if (!id.success) { + return invalid('environment_id') + } + if (!parsed.success) { + return invalid(parsed.error.issues[0]?.path.join('.') || 'patch') + } + return hostedEnvironmentResult(async () => ({ + environment: await service.client().update(id.data, parsed.data) + })) + }) + + ipcMain.handle('orcaCloudEnvironments:remove', (_event, envId: unknown) => { + const id = EnvId.safeParse(envId) + return id.success + ? hostedEnvironmentResult(() => service.client().remove(id.data)) + : invalid('environment_id') + }) + + ipcMain.handle('orcaCloudEnvironments:startBuild', (_event, envId: unknown) => { + const id = EnvId.safeParse(envId) + return id.success + ? hostedEnvironmentResult(async () => ({ build: await service.client().startBuild(id.data) })) + : invalid('environment_id') + }) + + ipcMain.handle( + 'orcaCloudEnvironments:cancelBuild', + (_event, envId: unknown, buildId: unknown) => { + const id = EnvId.safeParse(envId) + const bid = BuildId.safeParse(buildId) + if (!id.success || !bid.success) { + return invalid(id.success ? 'build_id' : 'environment_id') + } + return hostedEnvironmentResult(async () => ({ + build: await service.client().cancelBuild(id.data, bid.data) + })) + } + ) + + ipcMain.handle( + 'orcaCloudEnvironments:activateBuild', + (_event, envId: unknown, buildId: unknown) => { + const id = EnvId.safeParse(envId) + const bid = BuildId.safeParse(buildId) + if (!id.success || !bid.success) { + return invalid(id.success ? 'build_id' : 'environment_id') + } + return hostedEnvironmentResult(async () => ({ + environment: await service.client().activateBuild(id.data, bid.data) + })) + } + ) + + ipcMain.handle('orcaCloudEnvironments:staleness', (_event, envId: unknown, refresh: unknown) => { + const id = EnvId.safeParse(envId) + return id.success + ? hostedEnvironmentResult(async () => ({ + staleness: await service.client().staleness(id.data, refresh === true) + })) + : invalid('environment_id') + }) + + ipcMain.handle( + 'orcaCloudEnvironments:watchBuild', + (event: IpcMainInvokeEvent, envId: unknown, buildId: unknown) => { + const id = EnvId.safeParse(envId) + const bid = BuildId.safeParse(buildId) + if (!id.success || !bid.success) { + return invalid(id.success ? 'build_id' : 'environment_id') + } + return hostedEnvironmentResult(async () => { + const client = service.client() + const sender = event.sender + trackSender(sender) + const senderWatches = [...watches].filter(([, watch]) => watch.senderId === sender.id) + // Oldest first (Map keeps insertion order): drop the ones a leaky caller forgot. + for (const [watchId, evicted] of senderWatches.slice( + 0, + Math.max(0, senderWatches.length - MAX_WATCHES_PER_SENDER + 1) + )) { + // Tell the evicted log why it went quiet before stopping it. + evicted.notify({ type: 'error', message: EVICTED_MESSAGE }) + stopWatch(watchId) + } + const watchId = randomUUID() + const send = (streamEvent: OrcaCloudEnvironmentBuildEvent['event']): void => { + if (sender.isDestroyed()) { + stopWatch(watchId) + return + } + const payload: OrcaCloudEnvironmentBuildEvent = { + watchId, + envId: id.data, + buildId: bid.data, + event: streamEvent + } + sender.send(ORCA_CLOUD_ENVIRONMENT_BUILD_EVENT_CHANNEL, payload) + } + const watch = watchHostedEnvironmentBuild({ + client, + envId: id.data, + buildId: bid.data, + onEvent: send + }) + watches.set(watchId, { senderId: sender.id, stop: watch.stop, notify: send }) + void watch.done.finally(() => { + if (watches.get(watchId)?.stop === watch.stop) { + watches.delete(watchId) + } + }) + return { watchId } + }) + } + ) + + ipcMain.handle('orcaCloudEnvironments:unwatchBuild', (event, watchId: unknown) => { + // Only the window that opened a watch may stop it. + if (typeof watchId === 'string' && watches.get(watchId)?.senderId === event.sender.id) { + stopWatch(watchId) + } + }) + + ipcMain.handle('orcaCloudEnvironments:readRepoSetupImports', (_event, repoPath: unknown) => + hostedEnvironmentResult(() => readRepoSetupImports(repoPath, registeredLocalRepoPaths())) + ) +} diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 56821480b8d..01df642c556 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -155,6 +155,13 @@ export function registerCloudWorkspacesHandlers(): void { const s = await getService() return !s ? NOT_CONFIGURED : parsed.success ? s.get(parsed.data.id) : INVALID }) + handle('cloudWorkspaces:noteSent', async (args) => { + const parsed = z.object({ id: Id }).safeParse(args) + const s = await getService() + if (s && parsed.success) { + await s.noteSent(parsed.data.id) + } + }) handle('cloudWorkspaces:patch', async (args) => { const parsed = z.object({ id: Id, patch: Patch }).safeParse(args) const s = await getService() diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index 365679fbb0a..acae3e96dca 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -64,6 +64,15 @@ export function listRecipes( } } +// Glossary: an Orca Cloud machine is a sandbox; "VM" stays only for bring-your-own recipes. +export function buildEphemeralEnvironmentName( + repo: string, + runtimeId: string, + recipe: { provider?: string } +): string { + return `${repo} ${recipe.provider === 'orca-cloud' ? 'sandbox' : 'VM'} ${runtimeId.slice(-8)}` +} + /** The Run-on picker's list, plus Orca Cloud availability so it can offer sign-in or an upsell. */ export async function listPickerRecipes( store: Store, diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 98ee254a60e..91b22536588 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -33,6 +33,7 @@ import { listRecipeCatalog, listRecipes, listPickerRecipes, + buildEphemeralEnvironmentName, resolveRecipeForRepo, type EphemeralVmRecipeCatalogEntry } from './ephemeral-vm-recipe-context' @@ -76,7 +77,7 @@ export type EphemeralVmProvisionIpcResult = } & EphemeralVmFailure) export function registerEphemeralVmHandlers(store: Store, pluginService?: PluginService): void { - installHostedSandbox() + installHostedSandbox(store) ipcMain.removeHandler('ephemeralVm:listRecipes') ipcMain.removeHandler('ephemeralVm:listRecipeCatalog') ipcMain.removeHandler('ephemeralVm:doctor') @@ -251,7 +252,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin let environment: ReturnType try { environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { - name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), + name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id, recipe), pairingCode: connection.pairingCode, source: 'ephemeral-vm' }) @@ -304,10 +305,6 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin ) } -function buildEphemeralEnvironmentName(repoName: string, runtimeId: string): string { - return `${repoName} VM ${runtimeId.slice(-8)}` -} - function provisionFailure(failure: EphemeralVmFailure): EphemeralVmProvisionIpcResult { return { ok: false, ...failure, stdout: '', stderr: '' } } diff --git a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts index 66dab1748ce..29e6a8ef904 100644 --- a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts @@ -1,4 +1,4 @@ -import { ORCA_ORG_NAME_MAX_LENGTH } from '../../../shared/orca-org-management' +import { isValidOrgName, ORCA_ORG_NAME_MAX_LENGTH } from '../../../shared/orca-org-management' import type { OrcaProfileOrgCreateResult } from '../../../shared/orca-org-management' import { ipcMain } from 'electron' import type { @@ -85,7 +85,7 @@ function orgMemberRemoveArgsFromUnknown(args: unknown): OrcaProfileOrgMemberRemo function orgCreateNameFromUnknown(args: unknown): string { const record = args && typeof args === 'object' ? (args as Record) : {} const name = typeof record.name === 'string' ? record.name.trim() : '' - if (!name || name.length > ORCA_ORG_NAME_MAX_LENGTH) { + if (!name || name.length > ORCA_ORG_NAME_MAX_LENGTH || !isValidOrgName(name)) { throw new Error('invalid_orca_org_name') } return name diff --git a/src/main/ipc/profiles/orca-profiles.ts b/src/main/ipc/profiles/orca-profiles.ts index 24b35961726..d9bec353b8c 100644 --- a/src/main/ipc/profiles/orca-profiles.ts +++ b/src/main/ipc/profiles/orca-profiles.ts @@ -99,11 +99,16 @@ function findProjectsByPathArgsFromUnknown(args: unknown): FindOrcaProfileProjec } } -function orgIdFromUnknown(args: unknown): string { +function orgIdFromUnknown(args: unknown): string | null { if (!args || typeof args !== 'object') { throw new Error('invalid_orca_profile_org_selection') } - const orgId = (args as SelectOrcaProfileOrgArgs).orgId?.trim() + const raw = (args as SelectOrcaProfileOrgArgs).orgId + // Explicit null = the personal account. + if (raw === null) { + return null + } + const orgId = raw?.trim() if (!orgId) { throw new Error('invalid_orca_profile_org_selection') } diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts b/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts index 38bc56ae4a8..0e8608793ce 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-request-preparation.test.ts @@ -2,8 +2,28 @@ // opening request is held to its caller's pairing as of before that wake, then to the pairing the // wake made; any other change still refuses it. import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -const BEFORE = { id: 'env-vm', pairingRevision: 1, runtimeId: 'before', createdAt: 0 } +const BEFORE: KnownRuntimeEnvironment = { + id: 'env-vm', + name: 'VM', + pairingRevision: 1, + runtimeId: 'before', + createdAt: 0, + updatedAt: 0, + lastUsedAt: null, + endpoints: [ + { + id: 'ep', + kind: 'websocket', + label: 'VM', + endpoint: 'ws://vm.test', + deviceToken: 'token', + publicKeyB64: 'key' + } + ], + preferredEndpointId: 'ep' +} const AFTER_WAKE = { id: 'env-vm', pairingRevision: 2, runtimeId: 'after', createdAt: 0 } type Prepared = { @@ -73,7 +93,7 @@ describe('a fenced request that waited through a wake already in flight', () => undefined, { pairingRevision, runtimeId: 'before' }, undefined, - { before: BEFORE as never, wokenPairingRevision } + { before: BEFORE, wokenPairingRevision } ) it('passes the pre-wake fence and then expects the pairing that wake made', async () => { diff --git a/src/main/orca-profiles/profile-cloud-client.ts b/src/main/orca-profiles/profile-cloud-client.ts index baa4cf1e471..7a7f9ade9ee 100644 --- a/src/main/orca-profiles/profile-cloud-client.ts +++ b/src/main/orca-profiles/profile-cloud-client.ts @@ -254,7 +254,8 @@ export async function createOrcaCloudProfile( export async function selectOrcaCloudOrg( config: OrcaCloudAuthConfig, session: OrcaCloudSession, - orgId: string + /** null asks auth to clear the active team (personal account). */ + orgId: string | null ): Promise { const response = await postJson<{ cloud: unknown diff --git a/src/main/orca-profiles/profile-cloud-dev-org-members.ts b/src/main/orca-profiles/profile-cloud-dev-org-members.ts index e5a72444869..877032a6f53 100644 --- a/src/main/orca-profiles/profile-cloud-dev-org-members.ts +++ b/src/main/orca-profiles/profile-cloud-dev-org-members.ts @@ -1,3 +1,4 @@ +import { isValidOrgName } from '../../shared/orca-org-management' import type { OrcaProfileOrgCreateResult } from '../../shared/orca-org-management' import { randomUUID } from 'node:crypto' import { addDevOrganization, removeDevOrganization } from './profile-cloud-dev-auth' @@ -160,7 +161,7 @@ export function removeDevOrcaCloudOrgMember( export function createDevOrcaCloudOrg(name: string): OrcaProfileOrgCreateResult { const trimmed = name.trim() - if (!trimmed) { + if (!isValidOrgName(trimmed)) { return { status: 'invalid' } } const orgId = `dev-team-${randomUUID().slice(0, 8)}` diff --git a/src/main/orca-profiles/profile-cloud-dev-service.ts b/src/main/orca-profiles/profile-cloud-dev-service.ts index 736e03a5562..3bdbaf3280b 100644 --- a/src/main/orca-profiles/profile-cloud-dev-service.ts +++ b/src/main/orca-profiles/profile-cloud-dev-service.ts @@ -71,7 +71,7 @@ export function refreshDevOrcaCloudProfile( export function selectDevOrcaCloudOrg( active: ActiveOrcaProfileState, userDataPath: string, - orgId: string + orgId: string | null ): DevMutationResult { if ( !active.profile.cloud || @@ -82,7 +82,7 @@ export function selectDevOrcaCloudOrg( const session = createDevOrcaCloudSession({ localProfileId: active.profile.id, cloudProfileId: active.profile.cloud.cloudProfileId, - orgId + orgId: orgId ?? undefined }) signInCloudSession(active.profile.id, userDataPath, session) return { diff --git a/src/main/orca-profiles/profile-cloud-org-members-service.ts b/src/main/orca-profiles/profile-cloud-org-members-service.ts index c06408e93a1..34769527669 100644 --- a/src/main/orca-profiles/profile-cloud-org-members-service.ts +++ b/src/main/orca-profiles/profile-cloud-org-members-service.ts @@ -285,6 +285,9 @@ export async function createOrcaProfileOrg( if (result.error.statusCode === 429) { return { status: 'rate-limited' } } + if (result.error.statusCode === 409) { + return { status: 'name-taken' } + } return result.error.statusCode === 400 ? { status: 'invalid' } : { status: 'failed', error: result.error.message } diff --git a/src/main/orca-profiles/profile-cloud-org-selection.ts b/src/main/orca-profiles/profile-cloud-org-selection.ts index 33adf841af6..bcad0383112 100644 --- a/src/main/orca-profiles/profile-cloud-org-selection.ts +++ b/src/main/orca-profiles/profile-cloud-org-selection.ts @@ -13,7 +13,8 @@ export async function selectCloudOrg(input: { config: OrcaCloudAuthConfig active: ActiveOrcaProfileState userDataPath: string - orgId: string + /** null clears the selection (personal account). */ + orgId: string | null }): Promise { const profileId = input.active.profile.id const cloud = input.active.profile.cloud @@ -43,7 +44,7 @@ export async function selectCloudOrg(input: { if ( selected.cloud.userId !== cloud.userId || selected.cloud.cloudProfileId !== cloud.cloudProfileId || - selected.cloud.activeOrgId !== input.orgId + (selected.cloud.activeOrgId ?? null) !== input.orgId ) { throw new Error('orca_cloud_org_selection_identity_mismatch') } @@ -51,5 +52,17 @@ export async function selectCloudOrg(input: { if (!list) { throw new Error('stale_cloud_session_mutation') } + // /auth/org updates the stored selection but not the access token, and some services read the + // team from the token. Refresh now so they follow the switch (best effort; the next refresh + // would pick it up anyway). + const current = readCloudSession(profileId, input.userDataPath) + if (current.status === 'found') { + await forceRefreshOrcaCloudSession( + input.config, + input.active, + input.userDataPath, + current.session + ).catch(() => undefined) + } return list } diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts index 58336bb4ca4..3bd183a06ce 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -1,6 +1,7 @@ import { createHash, randomBytes } from 'node:crypto' import { createServer, type Server, type ServerResponse } from 'node:http' -import { shell } from 'electron' +import { appendFile } from 'node:fs/promises' +import { app, shell } from 'electron' import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' import { ORCA_CLOUD_CALLBACK_RESPONSE_HEADERS, @@ -149,7 +150,15 @@ export function beginOrcaCloudPkceFlow( authorizeUrl.searchParams.set('code_challenge_method', 'S256') authorizeUrl.searchParams.set('local_profile_id', localProfileId) options.onAuthorizeUrl?.(authorizeUrl.toString()) - void shell.openExternal(authorizeUrl.toString()).catch((error) => { + // Dev automation only (unpackaged): hand the sign-in URL to a test driver instead of + // opening the developer's own browser. Same pattern as ORCA_BILLING_DEV_OPEN_URL_FILE. + const devUrlFile = app.isPackaged + ? '' + : (process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE?.trim() ?? '') + const open = devUrlFile + ? appendFile(devUrlFile, `${authorizeUrl.toString()}\n`, { mode: 0o600 }) + : shell.openExternal(authorizeUrl.toString()) + void open.catch((error) => { rejectFlow( error instanceof Error ? error : new Error('orca_cloud_auth_browser_open_failed') ) diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index 7525f0f90d8..bc4cd0295b8 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -246,7 +246,7 @@ export async function createCloudLinkedOrcaProfile( export async function selectCurrentOrcaProfileOrg( userDataPath: string, - orgId: string + orgId: string | null ): Promise { const active = ensureActiveOrcaProfile(userDataPath) if (isOrcaCloudDevAuthEnabled()) { diff --git a/src/main/orcad/orcad-disk-usage.test.ts b/src/main/orcad/orcad-disk-usage.test.ts new file mode 100644 index 00000000000..7bc128e4106 --- /dev/null +++ b/src/main/orcad/orcad-disk-usage.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it, vi } from 'vitest' +import { readOrcadDiskUsage, type DiskUsageFs } from './orcad-disk-usage' + +const GIB = 1024 ** 3 + +function fakeFs( + mounts: Record +): DiskUsageFs & { statfsCalls: string[] } { + const statfsCalls: string[] = [] + return { + statfsCalls, + stat: vi.fn(async (path: string) => { + const mount = mounts[path] + if (!mount) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + } + return { dev: mount.dev } + }), + statfs: vi.fn(async (path: string) => { + statfsCalls.push(path) + const mount = mounts[path]! + return { bsize: 4096, blocks: mount.blocks, bfree: mount.bfree, bavail: mount.bavail } + }) + } +} + +const blocks = (bytes: number): number => bytes / 4096 + +describe('readOrcadDiskUsage', () => { + it('reports total, free, available and df-style used percent', async () => { + const fs = fakeFs({ + '/vercel/sandbox': { + dev: 1, + blocks: blocks(32 * GIB), + bfree: blocks(2 * GIB), + bavail: blocks(1 * GIB) + } + }) + const result = await readOrcadDiskUsage(['/vercel/sandbox'], { fs, now: () => 42 }) + expect(result).toEqual({ + checkedAt: 42, + volumes: [ + { + path: '/vercel/sandbox', + totalBytes: 32 * GIB, + freeBytes: 2 * GIB, + availableBytes: 1 * GIB, + // used 30 / (used 30 + avail 1) + usedPercent: (30 / 31) * 100 + } + ] + }) + }) + + it('folds paths on one filesystem into one volume and keeps a distinct home', async () => { + const fs = fakeFs({ + '/vercel/sandbox': { dev: 1, blocks: 100, bfree: 50, bavail: 50 }, + '/vercel/sandbox/repo': { dev: 1, blocks: 100, bfree: 50, bavail: 50 }, + '/home/user': { dev: 2, blocks: 200, bfree: 10, bavail: 10 } + }) + const result = await readOrcadDiskUsage( + ['/vercel/sandbox', '/vercel/sandbox/repo', '/vercel/sandbox', '/home/user'], + { fs } + ) + expect(result.volumes.map((v) => v.path)).toEqual(['/vercel/sandbox', '/home/user']) + expect(fs.statfsCalls).toEqual(['/vercel/sandbox', '/home/user']) + }) + + it('measures a missing workspace dir at its nearest existing ancestor', async () => { + const fs = fakeFs({ '/home/user': { dev: 2, blocks: 100, bfree: 90, bavail: 90 } }) + const result = await readOrcadDiskUsage(['/home/user/orca/workspaces'], { fs }) + expect(result.volumes.map((v) => v.path)).toEqual(['/home/user']) + }) + + it('skips paths whose statfs fails without failing the probe', async () => { + const fs = fakeFs({ + '/a': { dev: 1, blocks: 100, bfree: 1, bavail: 1 }, + '/b': { dev: 2, blocks: 100, bfree: 1, bavail: 1 } + }) + fs.statfs = vi.fn(async (path: string) => { + if (path === '/a') { + throw new Error('EACCES') + } + return { bsize: 4096, blocks: 100, bfree: 1, bavail: 1 } + }) + const result = await readOrcadDiskUsage(['/a', '/b', null, undefined, ''], { fs }) + expect(result.volumes.map((v) => v.path)).toEqual(['/b']) + }) + + it('reads 0% used for an empty filesystem rather than dividing by zero', async () => { + const fs = fakeFs({ '/': { dev: 1, blocks: 0, bfree: 0, bavail: 0 } }) + const result = await readOrcadDiskUsage(['/'], { fs }) + expect(result.volumes[0]!.usedPercent).toBe(0) + }) + + it('statfs-es the real filesystem by default', async () => { + const result = await readOrcadDiskUsage([process.cwd()]) + expect(result.volumes).toHaveLength(1) + expect(result.volumes[0]!.totalBytes).toBeGreaterThan(0) + }) +}) diff --git a/src/main/orcad/orcad-disk-usage.ts b/src/main/orcad/orcad-disk-usage.ts new file mode 100644 index 00000000000..4a8e428a320 --- /dev/null +++ b/src/main/orcad/orcad-disk-usage.ts @@ -0,0 +1,84 @@ +// Free space on the filesystems a runtime host writes to, for the desktop's low-disk banner. +// statfs/stat only: this runs on a poll from every connected desktop and must stay cheap. +import { stat, statfs } from 'node:fs/promises' +import { dirname } from 'node:path' +import type { OrcadDiskUsageResult, OrcadDiskVolumeUsage } from '../../shared/orcad-disk-usage' + +export type DiskUsageFs = { + statfs: ( + path: string + ) => Promise<{ bsize: number; blocks: number; bfree: number; bavail: number }> + /** Only `dev` is read, to fold paths on one filesystem into one volume. */ + stat: (path: string) => Promise<{ dev: number }> +} + +const nodeFs: DiskUsageFs = { + statfs: (path) => statfs(path), + stat: (path) => stat(path) +} + +// Why a cap: repo lists can be long and repos almost always share the workspace filesystem. +const MAX_PROBED_PATHS = 16 + +/** The path itself, else its nearest existing ancestor (a configured workspace dir may not exist yet). */ +async function existingAncestor(fs: DiskUsageFs, path: string): Promise { + let current = path + for (;;) { + try { + await fs.stat(current) + return current + } catch { + const parent = dirname(current) + if (parent === current) { + return null + } + current = parent + } + } +} + +function toVolume( + path: string, + stats: { bsize: number; blocks: number; bfree: number; bavail: number } +): OrcadDiskVolumeUsage { + const totalBytes = stats.blocks * stats.bsize + const freeBytes = stats.bfree * stats.bsize + const availableBytes = stats.bavail * stats.bsize + // df's Use%: used over (used + available), so root-reserved blocks don't read as free. + const used = Math.max(0, totalBytes - freeBytes) + const denominator = used + availableBytes + const usedPercent = denominator > 0 ? Math.min(100, (used / denominator) * 100) : 0 + return { path, totalBytes, freeBytes, availableBytes, usedPercent } +} + +/** `paths` in priority order (workspace root first); unreadable paths are skipped, not fatal. */ +export async function readOrcadDiskUsage( + paths: readonly (string | null | undefined)[], + options: { fs?: DiskUsageFs; now?: () => number } = {} +): Promise { + const fs = options.fs ?? nodeFs + const seenPaths = new Set() + const seenDevices = new Set() + const volumes: OrcadDiskVolumeUsage[] = [] + for (const candidate of paths) { + if (!candidate || seenPaths.has(candidate) || seenPaths.size >= MAX_PROBED_PATHS) { + continue + } + seenPaths.add(candidate) + try { + const path = await existingAncestor(fs, candidate) + if (!path) { + continue + } + const { dev } = await fs.stat(path) + if (seenDevices.has(dev)) { + continue + } + seenDevices.add(dev) + volumes.push(toVolume(path, await fs.statfs(path))) + } catch { + // A path that vanished or denies access says nothing about free space elsewhere. + } + } + return { volumes, checkedAt: (options.now ?? Date.now)() } +} diff --git a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts index fd36b658d24..8259933320d 100644 --- a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts @@ -14,6 +14,7 @@ import { resolveHookCommandSourcePolicy } from '../../../shared/hook-command-sou import { getSetupConfig, getSetupTrustContent } from '../../../shared/orca-hook-setup-config' import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' import { isFolderRepo } from '../../../shared/repo-kind' +import { isEnvironmentBuildCheckout } from '../../workspace-hooks/environment-build-checkout' import { inspectSetupScriptImportCandidates } from '../../../shared/workspace-setup/setup-script-imports' import { joinWorktreeRelativePath } from '../files/paths/runtime-relative-paths' import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' @@ -88,7 +89,11 @@ export class RuntimeRepositoryHooksCommands { status: 'ok' as const, hasHooks: has, hooks, - mayNeedUpdate: has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) + mayNeedUpdate: has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path), + // Dependencies come from an Orca Cloud environment build: no setup-script nudge. + ...((await isEnvironmentBuildCheckout(repo.path)) + ? { environmentProvisioned: true as const } + : {}) } } diff --git a/src/main/runtime/rpc/methods/cloud-environments/cloud-environments.ts b/src/main/runtime/rpc/methods/cloud-environments/cloud-environments.ts new file mode 100644 index 00000000000..bb8ca07124e --- /dev/null +++ b/src/main/runtime/rpc/methods/cloud-environments/cloud-environments.ts @@ -0,0 +1,80 @@ +import { CLOUD_ENVIRONMENT_METHODS } from '../../../../../shared/hosted-sandbox/hosted-environment-cli-contract' +import { hostedEnvironmentError } from '../../../../../shared/hosted-sandbox/hosted-environment-errors' +import { + CloudEnvironmentFollowBuildParams, + CloudEnvironmentSelectParams, + CloudEnvironmentSetInstallScriptParams, + CloudEnvironmentShowParams +} from '../../../../../shared/rpc-contract/cloud-environment-params' +import { createHostedEnvironmentBuildFollowers } from '../../../../hosted-sandbox/environments/hosted-environment-build-followers' +import { + followCloudEnvironmentBuild, + listCloudEnvironmentBuilds, + setCloudEnvironmentInstallScript, + showCloudEnvironment, + startCloudEnvironmentBuild +} from '../../../../hosted-sandbox/environments/hosted-environment-cli-operations' +import type { HostedEnvironmentClient } from '../../../../hosted-sandbox/environments/hosted-environment-client' +import { + getHostedEnvironmentService, + hostedEnvironmentResult +} from '../../../../hosted-sandbox/environments/hosted-environment-service' +import { defineMethod } from '../../core' + +const followers = createHostedEnvironmentBuildFollowers() + +/** The desktop holds the Orca Cloud session; a headless server has no service registered. */ +function withClient(work: (client: HostedEnvironmentClient) => Promise) { + const service = getHostedEnvironmentService() + if (!service) { + return Promise.resolve({ + ok: false as const, + error: { + ...hostedEnvironmentError('not_configured'), + message: + 'Orca Cloud environments are managed from the Orca desktop app; run this where it is open.' + } + }) + } + return hostedEnvironmentResult(() => work(service.client())) +} + +// `workspace` like other agent-facing integrations; the surface itself can only edit the install +// script and run builds (see hosted-environment-cli-operations.ts). +export const CLOUD_ENVIRONMENT_METHODS_RPC = [ + defineMethod({ + name: CLOUD_ENVIRONMENT_METHODS.show, + permission: 'workspace', + params: CloudEnvironmentShowParams, + handler: ({ env, refresh }) => + withClient((client) => showCloudEnvironment(client, env, refresh === true)) + }), + defineMethod({ + name: CLOUD_ENVIRONMENT_METHODS.setInstallScript, + permission: 'workspace', + params: CloudEnvironmentSetInstallScriptParams, + handler: ({ env, script, expectedRevision }) => + withClient((client) => + setCloudEnvironmentInstallScript(client, env, script, expectedRevision) + ) + }), + defineMethod({ + name: CLOUD_ENVIRONMENT_METHODS.startBuild, + permission: 'workspace', + params: CloudEnvironmentSelectParams, + handler: ({ env }) => withClient((client) => startCloudEnvironmentBuild(client, env)) + }), + defineMethod({ + name: CLOUD_ENVIRONMENT_METHODS.builds, + permission: 'workspace', + params: CloudEnvironmentSelectParams, + handler: ({ env }) => withClient((client) => listCloudEnvironmentBuilds(client, env)) + }), + defineMethod({ + name: CLOUD_ENVIRONMENT_METHODS.followBuild, + permission: 'workspace', + params: CloudEnvironmentFollowBuildParams, + handler: (params) => + withClient((client) => followCloudEnvironmentBuild(client, followers, params)) + }) +] diff --git a/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.test.ts b/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.test.ts new file mode 100644 index 00000000000..913503dce5a --- /dev/null +++ b/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it, vi } from 'vitest' + +const read = vi.hoisted(() => vi.fn(async () => ({ volumes: [], checkedAt: 1 }))) +vi.mock('../../../../orcad/orcad-disk-usage', () => ({ readOrcadDiskUsage: read })) +vi.mock('node:os', async (importOriginal) => ({ + ...(await importOriginal()), + homedir: () => '/home/user' +})) + +import { ORCAD_DISK_USAGE_METHODS, orcadDiskUsageProbePaths } from './orcad-disk-usage-method' +import { ORCAD_DISK_USAGE_METHOD } from '../../../../../shared/orcad-disk-usage' + +describe('orcad.diskUsage', () => { + it('registers under the shared name with workspace permission', () => { + expect(ORCAD_DISK_USAGE_METHODS[0]!.name).toBe(ORCAD_DISK_USAGE_METHOD) + expect(ORCAD_DISK_USAGE_METHODS[0]!.permission).toBe('workspace') + }) + + it('probes the workspace dir, local repos and home', async () => { + const runtime = { + requireStore: () => ({ + getSettings: () => ({ workspaceDir: '/vercel/sandbox/workspaces' }), + getRepos: () => [ + { path: '/vercel/sandbox/app', connectionId: null }, + { path: '/remote/repo', connectionId: 'ssh-1' } + ] + }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler reads only the store members faked above. + const result = await ORCAD_DISK_USAGE_METHODS[0]!.handler({} as never, { runtime } as never) + expect(result).toEqual({ volumes: [], checkedAt: 1 }) + expect(read).toHaveBeenCalledWith([ + '/vercel/sandbox/workspaces', + '/vercel/sandbox/app', + '/home/user' + ]) + }) +}) + +describe('orcadDiskUsageProbePaths', () => { + it('drops SSH, runtime-owned and relative repos', () => { + expect( + orcadDiskUsageProbePaths({ + workspaceDir: null, + repos: [ + { path: '/a', connectionId: null, executionHostId: 'local' }, + { path: '/b', connectionId: 'ssh-1' }, + { path: '/c', executionHostId: 'runtime:env-1' }, + { path: 'relative' } + ], + home: '/home/user' + }) + ).toEqual(['/a', '/home/user']) + }) +}) diff --git a/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.ts b/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.ts new file mode 100644 index 00000000000..3a8609971af --- /dev/null +++ b/src/main/runtime/rpc/methods/orcad/orcad-disk-usage-method.ts @@ -0,0 +1,50 @@ +import { homedir } from 'node:os' +import { isAbsolute } from 'node:path' +import { defineMethod } from '../../core' +import { + ORCAD_DISK_USAGE_METHOD, + OrcadDiskUsageParamsSchema +} from '../../../../../shared/orcad-disk-usage' +import type { Repo } from '../../../../../shared/repo-types' +import { + getRepoExecutionHostId, + getRepoRoutingConnectionId, + LOCAL_EXECUTION_HOST_ID +} from '../../../../../shared/execution-host' +import { readOrcadDiskUsage } from '../../../../orcad/orcad-disk-usage' + +/** Workspace root first so it leads the result; then local repo checkouts and $HOME. */ +export function orcadDiskUsageProbePaths(args: { + workspaceDir: string | null | undefined + repos: readonly Pick[] + home: string +}): string[] { + const repoPaths = args.repos + .filter( + (repo) => + getRepoRoutingConnectionId(repo) === null && + getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID && + isAbsolute(repo.path) + ) + .map((repo) => repo.path) + return [args.workspaceDir ?? '', ...repoPaths, args.home].filter(Boolean) +} + +export const ORCAD_DISK_USAGE_METHODS = [ + defineMethod({ + name: ORCAD_DISK_USAGE_METHOD, + // Why workspace: free space is no more sensitive than the file listings this caller can already read. + permission: 'workspace', + params: OrcadDiskUsageParamsSchema, + handler: async (_params, { runtime }) => { + const store = runtime.requireStore() + return readOrcadDiskUsage( + orcadDiskUsageProbePaths({ + workspaceDir: store.getSettings().workspaceDir, + repos: store.getRepos(), + home: homedir() + }) + ) + } + }) +] diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration.ts b/src/main/runtime/rpc/methods/orchestration/orchestration.ts index 57ab816b30d..e80f02283d0 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration.ts @@ -12,6 +12,7 @@ import { ORCHESTRATION_ASK_METHODS } from './messaging/ask-methods' import { ORCHESTRATION_GATE_METHODS } from './gates/gates' import { ORCHESTRATION_RESET_METHODS } from './runs/reset-methods' import { ORCHESTRATION_CALLER_METHODS } from './caller-show' +import { ORCHESTRATION_TURN_SENDER_METHODS } from './turn-sender' // Every orchestration method reads the authority restored at startup. export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ @@ -27,5 +28,6 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ ...ORCHESTRATION_ASK_METHODS, ...ORCHESTRATION_GATE_METHODS, ...ORCHESTRATION_RESET_METHODS, - ...ORCHESTRATION_CALLER_METHODS + ...ORCHESTRATION_CALLER_METHODS, + ...ORCHESTRATION_TURN_SENDER_METHODS ]) diff --git a/src/main/runtime/rpc/methods/orchestration/turn-sender.ts b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts new file mode 100644 index 00000000000..696926a4499 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/turn-sender.ts @@ -0,0 +1,63 @@ +import { defineMethod, type RpcContext } from '../../core' +import { + TURN_SENDER_METHOD, + type TurnSenderResult +} from '../../../../../shared/remote-runtime/pairing/turn-sender-contract' +import { + agentSessionSenderKey, + drivingDeviceFor, + terminalSenderKey +} from '../../../sender/driving-device-registry' + +/** + * A plain terminal (no agent launch token): its handle and pane key must name the same live PTY. + * Terminals that were launched with a token must prove it (verifyOrchestrationCompatibilityCaller). + */ +function plainTerminalHandle(ctx: RpcContext): string | null { + const evidence = ctx.orchestrationCompatibilityEvidence + const handle = typeof evidence?.terminalHandle === 'string' ? evidence.terminalHandle.trim() : '' + const paneKey = typeof evidence?.paneKey === 'string' ? evidence.paneKey.trim() : '' + if (!handle || !paneKey || evidence?.host) { + return null + } + const terminal = ctx.runtime.getOrchestrationDispatchAuthority(handle) + return terminal && !terminal.launchTokenHash && terminal.paneKey === paneKey ? handle : null +} + +/** + * 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. + */ +function turnSender(ctx: RpcContext): TurnSenderResult { + // Agents reach orcad through the local CLI only; paired devices are people, not agents. + if (ctx.caller?.kind !== 'local-cli') { + return { caller: null, sender: null } + } + if (ctx.orchestrationCaller?.sessionId) { + const sessionId = ctx.orchestrationCaller.sessionId + return { + caller: { kind: 'session', sessionId }, + sender: drivingDeviceFor(agentSessionSenderKey(sessionId)) + } + } + const authority = ctx.runtime.verifyOrchestrationCompatibilityCaller( + ctx.orchestrationCompatibilityEvidence + ) + const handle = authority?.terminalHandle ?? plainTerminalHandle(ctx) + if (!handle) { + return { caller: null, sender: null } + } + return { + caller: { kind: 'terminal', handle }, + sender: drivingDeviceFor(terminalSenderKey(handle)) + } +} + +export const ORCHESTRATION_TURN_SENDER_METHODS = [ + defineMethod({ + name: TURN_SENDER_METHOD, + permission: 'workspace', + params: null, + handler: (_params, ctx): TurnSenderResult => turnSender(ctx) + }) +] diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index 15d7da0dffb..a39991b62d0 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -2,6 +2,7 @@ import { STATUS_METHODS } from './host-management/status' import { SIDEBAR_INPUT_METHODS } from './sidebar-inputs/sidebar-inputs' import { ORCAD_TERMINAL_CENSUS_METHODS } from './orcad/orcad-terminal-census' import { ORCAD_WORK_VERDICT_METHODS } from './orcad/orcad-work-verdict-method' +import { ORCAD_DISK_USAGE_METHODS } from './orcad/orcad-disk-usage-method' import { ORCAD_MIGRATION_METHODS } from './orcad/orcad-migration' import { SESSION_TERMINAL_SCROLLBACK_METHODS } from './terminal/session-terminal-scrollback' import { AI_VAULT_METHODS } from './history/ai-vault' @@ -46,6 +47,7 @@ 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 { ENVIRONMENT_DOCTOR_METHODS } from './host-management/environment-doctor' +import { CLOUD_ENVIRONMENT_METHODS_RPC } from './cloud-environments/cloud-environments' import { SPEECH_METHODS } from './speech/speech' import { CLIENT_UI_METHODS } from './client-state/client-ui' import { CLIENT_EVENT_METHODS } from './client-events/client-events' @@ -90,6 +92,7 @@ export const ALL_RPC_METHODS = [ ...STATUS_METHODS, ...ORCAD_TERMINAL_CENSUS_METHODS, ...ORCAD_WORK_VERDICT_METHODS, + ...ORCAD_DISK_USAGE_METHODS, ...ORCAD_MIGRATION_METHODS, ...SESSION_TERMINAL_SCROLLBACK_METHODS, ...AGENT_HOOK_METHODS, @@ -147,6 +150,7 @@ export const ALL_RPC_METHODS = [ ...ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS, ...CLOUD_SSH_METHODS, ...ENVIRONMENT_DOCTOR_METHODS, + ...CLOUD_ENVIRONMENT_METHODS_RPC, ...SPEECH_METHODS, ...WORKSPACE_PORT_METHODS, ...LINK_PREVIEW_METHODS, diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-send-compatibility.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-send-compatibility.ts index 5c47c91e586..0fc41012a41 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-send-compatibility.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-send-compatibility.ts @@ -12,6 +12,10 @@ import { } from '../creation/structured-agent-session-gate' import { readsQueuedImageCards } from '../attachments/structured-agent-session-queued-image-capability' import { recordMobileChatSend } from '../../../../../telemetry/mobile-client-telemetry' +import { + agentSessionSenderKey, + recordDrivingDevice +} from '../../../../sender/driving-device-registry' /** Older clients wait past acceptance until handoff/rejection because they cannot show later failure. * Command-queued replies avoid request timeout; clients predating pending replies still wait for provider response. */ @@ -27,6 +31,10 @@ export async function sendStructuredAgentSessionForClient( queuedImageCards: readsQueuedImageCards(context) }) recordMobileChatSend(context.clientKind, host.sessionAgent(params.envelope.sessionId), result) + if (result.ok) { + // The person behind this turn, for tools the agent runs (git as the sender). + recordDrivingDevice(agentSessionSenderKey(params.envelope.sessionId), context.caller) + } const capabilities = context.clientCapabilities ?? [] if ( !result.ok || diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts index 8f3f8f16817..d25eddac73c 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts @@ -1,3 +1,4 @@ +import { recordDrivingDevice, terminalSenderKey } from '../../../sender/driving-device-registry' import { isTerminalInputPaused, TerminalInputPausedError @@ -267,6 +268,9 @@ export const TERMINAL_SEND_METHODS = [ } if (result.accepted !== true) { mobileFloorClaim.current?.rollback() + } else if (inputSource !== 'programmatic' && params.text) { + // A person's message to the agent in this terminal (git as the sender reads it back). + recordDrivingDevice(terminalSenderKey(params.terminal), caller) } if ( result.accepted === true && diff --git a/src/main/runtime/sender/driving-device-registry.test.ts b/src/main/runtime/sender/driving-device-registry.test.ts new file mode 100644 index 00000000000..800b86ccaa6 --- /dev/null +++ b/src/main/runtime/sender/driving-device-registry.test.ts @@ -0,0 +1,112 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { ORCHESTRATION_TURN_SENDER_METHODS } from '../rpc/methods/orchestration/turn-sender' +import { + agentSessionSenderKey, + drivingDeviceFor, + recordDrivingDevice, + resetDrivingDevices, + terminalSenderKey +} from './driving-device-registry' + +type Ctx = Parameters<(typeof ORCHESTRATION_TURN_SENDER_METHODS)[0]['handler']>[1] +const handler = ORCHESTRATION_TURN_SENDER_METHODS[0]!.handler + +function ctx(partial: Record): Ctx { + const runtime = { + getOrchestrationDispatchAuthority: (handle: string) => + handle === 't-plain' + ? { paneKey: 'tab:leaf', launchTokenHash: null } + : handle === 't-agent' + ? { paneKey: 'tab:a', launchTokenHash: 'h' } + : null, + verifyOrchestrationCompatibilityCaller: ( + evidence: { terminalHandle?: string; launchToken?: string } | undefined + ) => (evidence?.launchToken === 'right' ? { terminalHandle: evidence.terminalHandle } : null) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler reads only these fields. + return { runtime, ...partial } as unknown as Ctx +} + +describe('driving device registry', () => { + beforeEach(() => resetDrivingDevices()) + + it('records only paired devices (people), never the local CLI or local windows', () => { + recordDrivingDevice(terminalSenderKey('t1'), { kind: 'local-cli' }, 1) + recordDrivingDevice(terminalSenderKey('t1'), { kind: 'desktop' }, 2) + expect(drivingDeviceFor(terminalSenderKey('t1'))).toBeNull() + recordDrivingDevice(terminalSenderKey('t1'), { kind: 'paired-device', deviceId: 'dev-bob' }, 3) + recordDrivingDevice(terminalSenderKey('t1'), { kind: 'local-cli' }, 4) + expect(drivingDeviceFor(terminalSenderKey('t1'))).toEqual({ deviceId: 'dev-bob', at: 3 }) + }) + + it('answers an agent only about itself, identified by orcad evidence, never a parameter', async () => { + recordDrivingDevice( + terminalSenderKey('t-alice'), + { kind: 'paired-device', deviceId: 'dev-alice' }, + 1 + ) + recordDrivingDevice( + terminalSenderKey('t-bob'), + { kind: 'paired-device', deviceId: 'dev-bob' }, + 2 + ) + recordDrivingDevice( + agentSessionSenderKey('s1'), + { kind: 'paired-device', deviceId: 'dev-carol' }, + 3 + ) + const asPlain = (terminalHandle: string, paneKey: string) => + handler( + undefined, + ctx({ + caller: { kind: 'local-cli' }, + orchestrationCompatibilityEvidence: { terminalHandle, paneKey } + }) + ) + const asTerminal = (terminalHandle: string, launchToken: string) => + handler( + undefined, + ctx({ + caller: { kind: 'local-cli' }, + orchestrationCompatibilityEvidence: { terminalHandle, launchToken } + }) + ) + expect(await asTerminal('t-bob', 'right')).toEqual({ + caller: { kind: 'terminal', handle: 't-bob' }, + sender: { deviceId: 'dev-bob', at: 2 } + }) + // A forged launch token proves nothing. + expect(await asTerminal('t-alice', 'forged')).toEqual({ caller: null, sender: null }) + expect( + await handler( + undefined, + ctx({ caller: { kind: 'local-cli' }, orchestrationCaller: { sessionId: 's1' } }) + ) + ).toEqual({ + caller: { kind: 'session', sessionId: 's1' }, + sender: { deviceId: 'dev-carol', at: 3 } + }) + // A plain terminal (no launch token) is matched by handle + pane key; an agent terminal must prove its token. + recordDrivingDevice( + terminalSenderKey('t-plain'), + { kind: 'paired-device', deviceId: 'dev-dan' }, + 4 + ) + expect(await asPlain('t-plain', 'tab:leaf')).toEqual({ + caller: { kind: 'terminal', handle: 't-plain' }, + sender: { deviceId: 'dev-dan', at: 4 } + }) + expect(await asPlain('t-plain', 'tab:other')).toEqual({ caller: null, sender: null }) + expect(await asPlain('t-agent', 'tab:a')).toEqual({ caller: null, sender: null }) + // Paired clients are people, not agents: they get no answer. + expect( + await handler( + undefined, + ctx({ + caller: { kind: 'paired-device', deviceId: 'dev-bob' }, + orchestrationCompatibilityEvidence: { terminalHandle: 't-bob', launchToken: 'right' } + }) + ) + ).toEqual({ caller: null, sender: null }) + }) +}) diff --git a/src/main/runtime/sender/driving-device-registry.ts b/src/main/runtime/sender/driving-device-registry.ts new file mode 100644 index 00000000000..16841cd1a56 --- /dev/null +++ b/src/main/runtime/sender/driving-device-registry.ts @@ -0,0 +1,49 @@ +// Which paired device last drove each agent: the person behind a turn, attested by the transport +// (never by the message text). Agents ask for their own entry through `orchestration.turnSender`, +// which identifies the asking terminal/session from orcad's own launch evidence, not from params. +// Shared cloud workspaces use it so `git push` runs as the teammate who asked for the work. +import type { RpcCallerIdentity } from '../rpc/rpc-caller-identity' + +export type DrivingDevice = { deviceId: string; at: number } + +const MAX_ENTRIES = 4096 +const entries = new Map() + +export function agentSessionSenderKey(sessionId: string): string { + return `session:${sessionId}` +} + +export function terminalSenderKey(handle: string): string { + return `terminal:${handle}` +} + +/** + * Records a person's input. Only paired devices are people with a device identity; the local CLI + * (agents, scripts) and local windows never overwrite who drove the agent. + */ +export function recordDrivingDevice( + key: string, + caller: RpcCallerIdentity | undefined, + now: number = Date.now() +): void { + if (caller?.kind !== 'paired-device' || !caller.deviceId) { + return + } + entries.delete(key) + entries.set(key, { deviceId: caller.deviceId, at: now }) + if (entries.size > MAX_ENTRIES) { + const oldest = entries.keys().next().value + if (oldest !== undefined) { + entries.delete(oldest) + } + } +} + +export function drivingDeviceFor(key: string): DrivingDevice | null { + return entries.get(key) ?? null +} + +/** Tests only. */ +export function resetDrivingDevices(): void { + entries.clear() +} diff --git a/src/main/startup/cli-command-names.ts b/src/main/startup/cli-command-names.ts index 63748cdab54..17fd31bf2f9 100644 --- a/src/main/startup/cli-command-names.ts +++ b/src/main/startup/cli-command-names.ts @@ -13,6 +13,7 @@ export const CLI_COMMAND_NAMES = [ 'check', 'claude-teams', 'clear', + 'cloud', 'click', 'clipboard', 'computer', diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index 463c0a58d89..09a0be7de7d 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -1,6 +1,8 @@ import { app, type BrowserWindow } from 'electron' import { registerAgentApiKeyHandlers } from '../agent-api-keys/agent-api-key-ipc' import { registerCloudWorkspacesHandlers } from '../ipc/cloud-workspaces' +import { registerCloudApiHandlers } from '../cloud-api/cloud-api-ipc' +import { registerCloudSecretsHandlers } from '../cloud-secrets/cloud-secrets-ipc' import { registerCoreHandlers } from '../ipc/register-core-handlers/register-core-handlers' import { attachMainWindowServices } from '../window/attach-main-window-services' import { initTccPromptNotice } from '../macos-permissions/macos-tcc-prompt-notice' @@ -69,6 +71,8 @@ export function attachMainWindowCoreServices( holdLaunchReconnectOptOuts(store.getSshTargets()) registerAgentApiKeyHandlers(app.getPath('userData')) registerCloudWorkspacesHandlers() + registerCloudApiHandlers() + registerCloudSecretsHandlers(app.getPath('userData')) registerCoreHandlers( store, runtime, diff --git a/src/main/workspace-hooks/environment-build-checkout.test.ts b/src/main/workspace-hooks/environment-build-checkout.test.ts new file mode 100644 index 00000000000..40bcf9c5424 --- /dev/null +++ b/src/main/workspace-hooks/environment-build-checkout.test.ts @@ -0,0 +1,25 @@ +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { hasEnvironmentBuildMarker, isEnvironmentBuildCheckout } from './environment-build-checkout' + +describe('environment build checkout marker', () => { + it('recognises a built primary checkout and its linked worktrees, and nothing else', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-env-build-')) + const primary = join(root, 'repo') + const commonDir = join(primary, '.git') + mkdirSync(join(commonDir, 'worktrees', 'wt'), { recursive: true }) + const worktree = join(root, 'wt') + mkdirSync(worktree) + writeFileSync(join(worktree, '.git'), `gitdir: ${join(commonDir, 'worktrees', 'wt')}\n`) + writeFileSync(join(commonDir, 'worktrees', 'wt', 'commondir'), '../..\n') + expect(await isEnvironmentBuildCheckout(primary)).toBe(false) + expect(await isEnvironmentBuildCheckout(worktree)).toBe(false) + writeFileSync(join(commonDir, 'orca-env-deps'), 'node_modules\n') + expect(await isEnvironmentBuildCheckout(primary)).toBe(true) + expect(await isEnvironmentBuildCheckout(worktree)).toBe(true) + expect(await hasEnvironmentBuildMarker('.git', primary)).toBe(true) + expect(await isEnvironmentBuildCheckout(join(root, 'missing'))).toBe(false) + }) +}) diff --git a/src/main/workspace-hooks/environment-build-checkout.ts b/src/main/workspace-hooks/environment-build-checkout.ts new file mode 100644 index 00000000000..51cb6b4af82 --- /dev/null +++ b/src/main/workspace-hooks/environment-build-checkout.ts @@ -0,0 +1,48 @@ +// Orca Cloud environment builds (cloud/apps/sandbox-control image/env/environment-build.sh) install a +// repo's dependencies once and leave `/orca-env-deps` behind; every workspace created +// from the build gets those folders. Such a checkout needs no per-workspace setup script, so Orca +// does not nudge for one. +import { access, readFile, stat } from 'node:fs/promises' +import { isAbsolute, join, resolve } from 'node:path' + +const MARKER = 'orca-env-deps' + +/** The git common dir of `repoPath` (primary checkout or linked worktree), or null. */ +async function gitCommonDir(repoPath: string): Promise { + const dotGit = join(repoPath, '.git') + try { + if ((await stat(dotGit)).isDirectory()) { + return dotGit + } + // A linked worktree: `.git` is a file naming its gitdir, which names the common dir. + const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim() + if (!pointer) { + return null + } + const gitDir = isAbsolute(pointer) ? pointer : resolve(repoPath, pointer) + const common = (await readFile(join(gitDir, 'commondir'), 'utf8')).trim() + return isAbsolute(common) ? common : resolve(gitDir, common) + } catch { + return null + } +} + +async function exists(path: string): Promise { + try { + await access(path) + return true + } catch { + return false + } +} + +export async function isEnvironmentBuildCheckout(repoPath: string): Promise { + const common = await gitCommonDir(repoPath) + return common !== null && (await exists(join(common, MARKER))) +} + +/** Same check from a known common dir (the environment doctor already has it). */ +export function hasEnvironmentBuildMarker(commonDir: string, root: string): Promise { + const dir = isAbsolute(commonDir) ? commonDir : resolve(root, commonDir) + return exists(join(dir, MARKER)) +} diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 70a84da0739..43b3290ac25 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1,4 +1,6 @@ import type { AgentApiKeysApi } from './api/agent-api-keys-bridge' +import type { CloudApiBridge } from './api/cloud-api-bridge' +import type { CloudSecretsApi } from './api/cloud-secrets-bridge' import type { ClaudeAccountsApi, CodexAccountsApi, @@ -46,6 +48,7 @@ import type { MobileApi } from './api/mobile-api' import type { NativeChatApi } from './api/native-chat-api' import type { OnboardingApi, StarNagApi } from './api/onboarding-api' import type { OrcaProfileApi } from './api/orca-profile-api' +import type { OrcaCloudEnvironmentsApi } from '../shared/hosted-sandbox/hosted-environment-api' import type { ComputerUsePermissionsApi, DeveloperPermissionsApi, @@ -86,6 +89,7 @@ type Merged = { [K in keyof T]: T[K] } export type PreloadApi = { app: AppApi orcaProfiles: OrcaProfileApi + orcaCloudEnvironments: OrcaCloudEnvironmentsApi platform: PlatformApi e2e: E2EApi repos: RepositoryApi @@ -178,6 +182,10 @@ export type PreloadApi = { plainSsh?: PlainSshTerminalApi /** Desktop only: the API keys Orca hands to agent launches. */ agentApiKeys?: AgentApiKeysApi + /** Desktop only: Orca Cloud API keys, org settings and routines (hosted builds). */ + cloudApi?: CloudApiBridge + /** Desktop only: Orca Cloud secrets (personal, team, repo) injected into cloud workspaces. */ + cloudSecrets?: CloudSecretsApi /** COMPAT(legacy-relay-bridge): desktop-only, revisit 2027-01-15. */ legacyRelayBridge?: LegacyRelayBridgeApi automations: AutomationsApi diff --git a/src/preload/api/cloud-api-bridge.ts b/src/preload/api/cloud-api-bridge.ts new file mode 100644 index 00000000000..918dafee590 --- /dev/null +++ b/src/preload/api/cloud-api-bridge.ts @@ -0,0 +1,82 @@ +import { ipcRenderer } from 'electron' +import type { + CloudApiApproval, + CloudApiAuditPage, + CloudApiAvailability, + CloudApiCreatedKey, + CloudApiGrant, + CloudApiInstallation, + CloudApiKeyList, + CloudApiMe, + CloudApiProject, + CloudApiResult, + CloudApiSettings, + CreateCloudApiApprovalInput, + CreateCloudApiKeyInput, + Routine, + RoutineCreated, + RoutineInput, + RoutinePatch, + RoutineRun, + RoutineRunPage, + RoutineRunsQuery, + RoutineUpdated +} from '../../shared/cloud-api/cloud-api-types' + +/** Desktop only: Orca Cloud API keys, org settings, audit and routines. The session token stays in main. */ +export type CloudApiBridge = { + availability: () => Promise + /** The desktop workspace running on this Orca Cloud sandbox, if this computer has it. */ + localWorkspaceFor: (sandboxId: string) => Promise + me: () => Promise> + listApiKeys: () => Promise> + createApiKey: (input: CreateCloudApiKeyInput) => Promise> + revokeApiKey: (id: string) => Promise> + createApproval: (input?: CreateCloudApiApprovalInput) => Promise> + listGrants: () => Promise> + revokeGrant: (id: string) => Promise> + getSettings: () => Promise> + putSettings: (input: { vmCliEnabled: boolean }) => Promise> + listAudit: (query?: { + limit?: number + before?: number + }) => Promise> + listProjects: () => Promise> + listInstallations: () => Promise> + listRoutines: () => Promise> + createRoutine: (input: RoutineInput) => Promise> + updateRoutine: (id: string, patch: RoutinePatch) => Promise> + deleteRoutine: (id: string) => Promise> + runRoutine: (id: string) => Promise> + rotateRoutineWebhook: (id: string) => Promise> + listRoutineRuns: (id: string, query?: RoutineRunsQuery) => Promise> +} + +const invoke = + (channel: string) => + (...args: unknown[]) => + ipcRenderer.invoke(channel, ...args) + +export const cloudApiBridge: CloudApiBridge = { + availability: invoke('cloudApi:availability'), + localWorkspaceFor: invoke('cloudApi:localWorkspaceFor'), + me: invoke('cloudApi:me'), + listApiKeys: invoke('cloudApi:listApiKeys'), + createApiKey: invoke('cloudApi:createApiKey'), + revokeApiKey: invoke('cloudApi:revokeApiKey'), + createApproval: invoke('cloudApi:createApproval'), + listGrants: invoke('cloudApi:listGrants'), + revokeGrant: invoke('cloudApi:revokeGrant'), + getSettings: invoke('cloudApi:getSettings'), + putSettings: invoke('cloudApi:putSettings'), + listAudit: invoke('cloudApi:listAudit'), + listProjects: invoke('cloudApi:listProjects'), + listInstallations: invoke('cloudApi:listInstallations'), + listRoutines: invoke('cloudApi:listRoutines'), + createRoutine: invoke('cloudApi:createRoutine'), + updateRoutine: invoke('cloudApi:updateRoutine'), + deleteRoutine: invoke('cloudApi:deleteRoutine'), + runRoutine: invoke('cloudApi:runRoutine'), + rotateRoutineWebhook: invoke('cloudApi:rotateRoutineWebhook'), + listRoutineRuns: invoke('cloudApi:listRoutineRuns') +} diff --git a/src/preload/api/cloud-secrets-bridge.ts b/src/preload/api/cloud-secrets-bridge.ts new file mode 100644 index 00000000000..34e663d55c4 --- /dev/null +++ b/src/preload/api/cloud-secrets-bridge.ts @@ -0,0 +1,42 @@ +import { ipcRenderer } from 'electron' +import type { + CloudSecretBatchResult, + CloudSecretTarget, + CloudSecretView, + CloudSecretsEffective, + CloudSecretsResult, + CloudSecretsStatus +} from '../../shared/cloud-secrets/cloud-secrets-wire' + +/** Desktop only. Values go in; only names, scopes and last-4 hints come back. */ +export type CloudSecretsApi = { + status: () => Promise + list: (target: CloudSecretTarget) => Promise> + put: (request: { + target: CloudSecretTarget + name: string + value: string + }) => Promise> + remove: (request: { + target: CloudSecretTarget + name: string + }) => Promise> + batch: (request: { + target: CloudSecretTarget + set?: Record + delete?: string[] + }) => Promise> + 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> +} + +export const cloudSecretsApi: CloudSecretsApi = { + status: () => ipcRenderer.invoke('cloudSecrets:status'), + list: (target) => ipcRenderer.invoke('cloudSecrets:list', target), + put: (request) => ipcRenderer.invoke('cloudSecrets:put', request), + 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) +} diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 2c02b2359f9..0e37a68192e 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -36,6 +36,8 @@ export type CloudWorkspacesApi = { listGrants: (id: string) => Promise> revokeGrant: (id: string, grantId: string) => Promise> localWorkspaces: () => Promise + /** "I just sent a message here" (opens my git-as-sender window on the control plane). */ + noteSent: (id: string) => Promise /** Remembers which local runtime environment a granted workspace was added as. */ bindEnvironment: ( sandboxId: string, diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index 9fa38c2f224..c35320aa55f 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -12,6 +12,7 @@ export const cloudWorkspacesApi = { listGrants: (id) => ipcRenderer.invoke('cloudWorkspaces:listGrants', { id }), revokeGrant: (id, grantId) => ipcRenderer.invoke('cloudWorkspaces:revokeGrant', { id, grantId }), localWorkspaces: () => ipcRenderer.invoke('cloudWorkspaces:localWorkspaces'), + noteSent: (id) => ipcRenderer.invoke('cloudWorkspaces:noteSent', { id }), bindEnvironment: (sandboxId, runtimeEnvironmentId, grantId) => ipcRenderer.invoke('cloudWorkspaces:bindEnvironment', { sandboxId, diff --git a/src/preload/api/orca-cloud-environments-bridge.ts b/src/preload/api/orca-cloud-environments-bridge.ts new file mode 100644 index 00000000000..b2bc017498a --- /dev/null +++ b/src/preload/api/orca-cloud-environments-bridge.ts @@ -0,0 +1,35 @@ +import { ipcRenderer } from 'electron' +import type { PreloadApi } from '../api-types' +import { + ORCA_CLOUD_ENVIRONMENT_BUILD_EVENT_CHANNEL, + type OrcaCloudEnvironmentBuildEvent +} from '../../shared/hosted-sandbox/hosted-environment-api' + +export const orcaCloudEnvironmentsApi = { + isConfigured: () => ipcRenderer.invoke('orcaCloudEnvironments:isConfigured'), + list: () => ipcRenderer.invoke('orcaCloudEnvironments:list'), + get: (envId) => ipcRenderer.invoke('orcaCloudEnvironments:get', envId), + create: (input) => ipcRenderer.invoke('orcaCloudEnvironments:create', input), + update: (envId, patch) => ipcRenderer.invoke('orcaCloudEnvironments:update', envId, patch), + remove: (envId) => ipcRenderer.invoke('orcaCloudEnvironments:remove', envId), + startBuild: (envId) => ipcRenderer.invoke('orcaCloudEnvironments:startBuild', envId), + cancelBuild: (envId, buildId) => + ipcRenderer.invoke('orcaCloudEnvironments:cancelBuild', envId, buildId), + activateBuild: (envId, buildId) => + ipcRenderer.invoke('orcaCloudEnvironments:activateBuild', envId, buildId), + staleness: (envId, refresh) => + ipcRenderer.invoke('orcaCloudEnvironments:staleness', envId, refresh === true), + watchBuild: (envId, buildId) => + ipcRenderer.invoke('orcaCloudEnvironments:watchBuild', envId, buildId), + unwatchBuild: async (watchId) => { + await ipcRenderer.invoke('orcaCloudEnvironments:unwatchBuild', watchId) + }, + onBuildEvent: (callback: (event: OrcaCloudEnvironmentBuildEvent) => void): (() => void) => { + const listener = (_event: unknown, payload: OrcaCloudEnvironmentBuildEvent): void => + callback(payload) + ipcRenderer.on(ORCA_CLOUD_ENVIRONMENT_BUILD_EVENT_CHANNEL, listener) + return () => ipcRenderer.removeListener(ORCA_CLOUD_ENVIRONMENT_BUILD_EVENT_CHANNEL, listener) + }, + readRepoSetupImports: (repoPath) => + ipcRenderer.invoke('orcaCloudEnvironments:readRepoSetupImports', repoPath) +} satisfies PreloadApi['orcaCloudEnvironments'] diff --git a/src/preload/index.ts b/src/preload/index.ts index fe2d93e21ee..6cc4d785126 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -5,6 +5,7 @@ import type { PreloadApi } from './api-types' import { installBrowserFindListener } from './preload-runtime-support' import { appApi } from './api/app-bridge' import { orcaProfilesApi } from './api/orca-profiles-bridge' +import { orcaCloudEnvironmentsApi } from './api/orca-cloud-environments-bridge' import { platformApi } from './api/platform-bridge' import { wslApi } from './api/wsl-bridge' import { wslMoveApi } from './api/wsl-move-bridge' @@ -91,6 +92,8 @@ import { cursorAccountsApi } from './api/cursor-accounts-bridge' import { sshApi } from './api/ssh-bridge' import { plainSshTerminalApi } from './api/plain-ssh-terminal-bridge' import { agentApiKeysApi } from './api/agent-api-keys-bridge' +import { cloudApiBridge } from './api/cloud-api-bridge' +import { cloudSecretsApi } from './api/cloud-secrets-bridge' import { legacyRelayBridgeApi } from './api/legacy-relay-bridge-api' import { automationsApi } from './api/automations-bridge' import { e2eApi } from './api/e2e-bridge' @@ -112,6 +115,7 @@ const telemetryGetConsentStateApi: PreloadApi['telemetryGetConsentState'] = () = const api = { app: appApi, orcaProfiles: orcaProfilesApi, + orcaCloudEnvironments: orcaCloudEnvironmentsApi, platform: platformApi, wsl: wslApi, wslMove: wslMoveApi, @@ -202,6 +206,8 @@ const api = { ssh: sshApi, plainSsh: plainSshTerminalApi, agentApiKeys: agentApiKeysApi, + cloudApi: cloudApiBridge, + cloudSecrets: cloudSecretsApi, legacyRelayBridge: legacyRelayBridgeApi, automations: automationsApi, e2e: e2eApi, diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index 4b890eccee7..df5297cb06d 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -9,6 +9,7 @@ import RightSidebar from '../components/right-sidebar' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' import { FloatingTerminalToggleButton } from '../components/floating-terminal/FloatingTerminalToggleButton' import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer' +import { WorkspaceLowDiskBanner } from '../components/low-disk/WorkspaceLowDiskBanner' import type { VirtualizedScrollAnchor } from '../hooks/useVirtualizedScrollAnchor' import { TitlebarLeftControls } from './TitlebarLeftControls' import { RightSidebarToggle, TitlebarMainStrip } from './TitlebarMainStrip' @@ -227,6 +228,9 @@ export function AppWorkspaceShell(props: { ) : null} + {layout.shouldMountTerminalWorkbench ? ( + + ) : null}

- {payment.suspendRunning - ? t( - 'auto.components.billing.paymentFailedSuspended', - 'Payment failed · sandboxes suspended' - ) - : t('auto.components.billing.paymentFailed', 'Payment failed')} + {t('auto.components.billing.paymentFailed', 'Payment failed')}

{payment.suspendRunning || payment.graceEndsAt === null ? t( - 'auto.components.billing.paymentSuspendedBody', - 'Running sandboxes were suspended and new ones cannot start. Update your payment method; everything resumes once the invoice is paid.' + '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.paymentGraceBody', - 'New sandboxes are paused. Running sandboxes will be suspended on {{value0}} unless the payment goes through. Stripe will retry the card and email your billing contact.', + '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) } )}

@@ -62,8 +57,8 @@ export function PaymentIssueNotice({ -
+ + + + } + /> ) if (result.status === 'failed') { @@ -142,41 +169,54 @@ export function PlanBillingView({ return (
{header} + {hasPlan ? (

{entitlement.planLabel}

- {t('auto.components.billing.seatsInterval', '{{value0}} seats · {{value1}}', { - value0: String(entitlement.seats), - value1: - entitlement.interval === 'year' - ? t('auto.components.billing.annual', 'Annual') - : t('auto.components.billing.monthly', 'Monthly') - })} + {entitlement.interval === 'year' + ? t('auto.components.billing.seatsAnnual', '{{count}} seats · Annual', { + count: entitlement.seats, + defaultValue_one: '{{count}} seat · Annual' + }) + : t('auto.components.billing.seatsMonthly', '{{count}} seats · Monthly', { + count: entitlement.seats, + defaultValue_one: '{{count}} seat · Monthly' + })}
- + {/* Overage is moot while sandboxes are suspended for a failed payment. */} + {entitlement.payment.suspendRunning ? null : ( + + )}
) : null} - - - {entitlement.reason && entitlement.payment.pastDueSince === null ? ( + {/* The overage card carries the cap-reached hint for admins; don't repeat it here. */} + {hasPlan && + entitlement.reason && + entitlement.payment.pastDueSince === null && + !(entitlement.reason === 'overage_cap_reached' && entitlement.canManageBilling) ? (

{denyReasonCopy(entitlement.reason, t, entitlement.canManageBilling)}

) : null} {!hasPlan ? ( -

+

{teamPrice ? t( - 'auto.components.billing.upsellLine', - 'Orca Cloud runs agents in hosted sandboxes. Team is {{value0}} per seat / month.', + 'auto.components.billing.upsellLine2', + 'Orca Cloud runs agents in sandboxes. Team is {{value0}} per seat per month.', { value0: teamPrice } ) : t( @@ -193,7 +233,13 @@ export function PlanBillingView({ )} {hasPlan && entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? ( - @@ -205,13 +251,20 @@ export function PlanBillingView({ ) : null}

- {!entitlement.canManageBilling ? ( + {/* The payment alert already says who to ask; don't ask twice. */} + {!entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? (

- {t('auto.components.billing.askAdmin', 'Ask an org owner or admin to change the plan.')} + {t('auto.components.billing.askAdmin2', 'Ask an owner or admin to change the plan.')}

) : null} - {notice ?

{notice}

: null} + {notice?.kind === 'error' ? ( + + ) : notice ? ( +

+ {notice.text} +

+ ) : null} ) } diff --git a/src/renderer/src/components/billing/PlanBillingUsage.tsx b/src/renderer/src/components/billing/PlanBillingUsage.tsx index 86bbb3e9f39..87c0f91b12a 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.tsx @@ -1,6 +1,7 @@ -import { useId, useState } from 'react' +import { useId, useRef, useState } from 'react' import { Check } from 'lucide-react' import { Button } from '@/components/ui/button' +import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip' import { Input } from '@/components/ui/input' import { Progress } from '@/components/ui/progress' import { Switch } from '@/components/ui/switch' @@ -11,6 +12,39 @@ import type { } from '../../../../shared/orca-billing' import { formatHours, includedUsagePercent } from './plan-billing-format' import { formatCents } from './plans/plans-pricing' +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. */ +function resetLine( + entitlement: OrcaBillingEntitlement, + date: (ms: number) => string, + t: ReturnType +): string | null { + const resets = entitlement.usageWindow ? date(entitlement.usageWindow.end) : null + const ends = entitlement.period ? date(entitlement.period.end) : null + if (ends && entitlement.cancelAtPeriodEnd) { + return resets + ? t('auto.components.billing.resetsEnds', 'Hours reset {{value0}} · Plan ends {{value1}}', { + value0: resets, + value1: ends + }) + : t('auto.components.billing.endsOn', 'Plan ends {{value0}}', { value0: ends }) + } + if (resets && ends) { + return resets === ends + ? t('auto.components.billing.resetsAndRenews', 'Resets and renews {{value0}}', { + value0: ends + }) + : t('auto.components.billing.resetsRenews', 'Hours reset {{value0}} · Renews {{value1}}', { + value0: resets, + value1: ends + }) + } + if (resets) { + return t('auto.components.billing.resets', 'Hours reset {{value0}}', { value0: resets }) + } + return ends ? t('auto.components.billing.renewsOn', 'Renews {{value0}}', { value0: ends }) : null +} export function UsageSummary({ entitlement @@ -26,8 +60,8 @@ export function UsageSummary({
{t( - 'auto.components.billing.hoursUsedMonth', - '{{value0}} of {{value1}} hours used this month', + 'auto.components.billing.sandboxHoursUsedMonth', + '{{value0}} of {{value1}} sandbox hours used this month', { value0: formatHours(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), value1: formatHours(entitlement.includedSeconds) @@ -35,68 +69,51 @@ export function UsageSummary({ )} - {t('auto.components.billing.hoursLeft', '{{value0}} hours left', { + {t('auto.components.billing.sandboxHoursLeft', '{{value0}} sandbox hours left', { value0: formatHours(entitlement.remainingIncludedSeconds) })}
= 100 && !entitlement.overage.optedIn + ? 'warning' + : 'default' + } + aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} /> {entitlement.overageSeconds === 0 && entitlement.usedSeconds > entitlement.includedSeconds && entitlement.includedSeconds > 0 ? (

- {t('auto.components.billing.overBy', 'Over by {{value0}} h this month', { - value0: formatHours(entitlement.usedSeconds - entitlement.includedSeconds) + {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.overageHours', - '{{value0}} overage hours · {{value1}} of {{value2}} cap', - { - value0: formatHours(entitlement.overageSeconds), - value1: formatCents(entitlement.overage.spentCents, locale), - value2: formatCents(entitlement.overage.spendCapCents, locale) - } - )} + {t('auto.components.billing.overageHoursOnly', '{{value0}} overage hours this month', { + value0: formatHours(entitlement.overageSeconds) + })}

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

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

) : null} -

- {entitlement.usageWindow - ? t('auto.components.billing.resets', 'Hours reset {{value0}}', { - value0: date(entitlement.usageWindow.end) - }) - : null} - {entitlement.period - ? ` · ${ - entitlement.cancelAtPeriodEnd - ? t('auto.components.billing.endsOn', 'Plan ends {{value0}}', { - value0: date(entitlement.period.end) - }) - : t('auto.components.billing.renewsOn', 'Renews {{value0}}', { - value0: date(entitlement.period.end) - }) - }` - : null} -

+

{resetLine(entitlement, date, t)}

) } @@ -104,113 +121,218 @@ export function UsageSummary({ export function OverageControls({ entitlement, busy, + failures = 0, onSetOverage }: { entitlement: OrcaBillingEntitlement busy: boolean + /** Bumped by the parent each time a change fails, to roll back the optimistic state. */ + failures?: number onSetOverage: (args: OrcaBillingOverageArgs) => void }): React.JSX.Element { const t = useTranslate() const locale = useIntlLocale() const capId = useId() + const descriptionId = useId() + const capErrorId = useId() + const savedRef = useRef(null) const { overage } = entitlement const savedDollars = String(Math.round(overage.spendCapCents / 100)) const [capDollars, setCapDollars] = useState(savedDollars) // Shows "Saved" after a successful cap change until the field is edited again (review M13). const [savedFlash, setSavedFlash] = useState(false) - // Re-seed the field when the saved cap changes (render-time adjustment, no effect). - const [seededFrom, setSeededFrom] = useState(savedDollars) - if (seededFrom !== savedDollars) { - setSeededFrom(savedDollars) + // The switch flips at once; the saved value takes over when billing answers. + const [optimisticOn, setOptimisticOn] = useState(null) + // Re-seed from the server whenever the saved values change (render-time adjustment, no effect). + const [seededFrom, setSeededFrom] = useState(`${savedDollars}:${overage.optedIn}`) + if (seededFrom !== `${savedDollars}:${overage.optedIn}`) { + setSeededFrom(`${savedDollars}:${overage.optedIn}`) setCapDollars(savedDollars) + setOptimisticOn(null) } + const [seenFailures, setSeenFailures] = useState(failures) + if (seenFailures !== failures) { + setSeenFailures(failures) + setOptimisticOn(null) + setSavedFlash(false) + } + const optedIn = optimisticOn ?? overage.optedIn const parsedCap = Number(capDollars) const capValid = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0 const changed = capValid && capDollars.trim() !== savedDollars const largeWeight = entitlement.offers?.team.largeMachineWeight ?? 2 - const suspended = entitlement.payment.suspendRunning || entitlement.payment.pastDueSince !== null - const canEdit = entitlement.canManageBilling && !suspended + const paymentFailed = entitlement.payment.pastDueSince !== null + const description = t( + 'auto.components.billing.overageDescription4', + 'Optional overage at {{value0}}/hour ({{value1}}/hour on Large), up to a monthly spend cap you set ({{value2}} by default).', + { + value0: formatCents(overage.centsPerHour, locale), + value1: formatCents(Math.round(overage.centsPerHour * largeWeight), locale), + value2: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale) + } + ) + const descriptionOn = t( + 'auto.components.billing.overageDescriptionOn', + 'Optional overage at {{value0}}/hour ({{value1}}/hour on Large), up to a monthly spend cap you set.', + { + value0: formatCents(overage.centsPerHour, locale), + value1: formatCents(Math.round(overage.centsPerHour * largeWeight), locale) + } + ) + const capPercent = + overage.spendCapCents > 0 + ? Math.min(100, Math.round((overage.spentCents / overage.spendCapCents) * 100)) + : 0 + const spent = ( +
+ = 100 ? 'warning' : 'default'} + aria-label={t('auto.components.billing.capUsedLabel', 'Overage spend cap used')} + /> +

+ {t('auto.components.billing.overageSpent', '{{value0}} of {{value1}} monthly cap spent', { + value0: formatCents(overage.spentCents, locale), + value1: formatCents(overage.spendCapCents, locale) + })} +

+
+ ) + + // Members see the setting as plain text: a switch they can't use only invites clicks. + if (!entitlement.canManageBilling) { + return ( +
+

+ + {t('auto.components.billing.overageTitle', 'Overage')} + + + {' · '} + {overage.optedIn + ? t('auto.components.billing.overageOnRead', 'On') + : t('auto.components.billing.overageOffRead', 'Off')} + +

+ {overage.optedIn ? spent : null} +

+ {t('auto.components.billing.overageMemberHint', 'Owners and admins can change overage.')} +

+
+ ) + } + + const toggleBlocked = busy || paymentFailed return ( -
+ // Deep-link target: the Run-on picker's "Turn on overage" / "Raise cap" lands here. +

{t('auto.components.billing.overageTitle', 'Overage')}

-

- {t( - 'auto.components.billing.overageDescription', - 'Keep starting sandboxes after included hours at {{value0}}/hr Standard ({{value1}}/hr Large).', - { - value0: formatCents(overage.centsPerHour, locale), - value1: formatCents(Math.round(overage.centsPerHour * largeWeight), locale) - } - )} +

+ {optedIn ? descriptionOn : description}

- onSetOverage({ enabled })} - aria-label={t('auto.components.billing.overageToggle', 'Allow overage')} - /> -
- {overage.optedIn ? ( -
-

- {t( - 'auto.components.billing.overageSpent', - '{{value0}} of {{value1}} monthly cap spent', - { - value0: formatCents(overage.spentCents, locale), - value1: formatCents(overage.spendCapCents, locale) + + { + if (toggleBlocked) { + return } - )} -

- {canEdit ? ( + setOptimisticOn(enabled) + onSetOverage({ enabled }) + }} + aria-label={t('auto.components.billing.overageToggle', 'Allow overage')} + /> + +
+ {optedIn ? ( +
+ {spent} + {paymentFailed ? null : (
{ event.preventDefault() - if (changed) { + if (changed && !busy) { onSetOverage({ enabled: true, spendCapCents: parsedCap * 100 }) setSavedFlash(true) + // Save turns into "Saving…" in place; move focus onto it. + window.requestAnimationFrame(() => savedRef.current?.focus()) } }} > -
diff --git a/src/renderer/src/components/billing/PlanStatusBadge.tsx b/src/renderer/src/components/billing/PlanStatusBadge.tsx index 279940e2113..1e4ef4ff3ca 100644 --- a/src/renderer/src/components/billing/PlanStatusBadge.tsx +++ b/src/renderer/src/components/billing/PlanStatusBadge.tsx @@ -9,7 +9,10 @@ export type PlanHealth = { label: string; dot: 'destructive' | 'warning' | null /** Names what is actually wrong (not just Stripe's status) so the badge never says "Active" in red. */ export function planHealth(entitlement: OrcaBillingEntitlement, t: Translate): PlanHealth { if (entitlement.reason === 'payment_grace_expired' || entitlement.payment.suspendRunning) { - return { label: t('auto.components.billing.health.suspended', 'Suspended'), dot: 'destructive' } + return { + label: t('auto.components.billing.paymentFailed', 'Payment failed'), + dot: 'destructive' + } } if (entitlement.payment.pastDueSince !== null || entitlement.status === 'past_due') { return { @@ -18,10 +21,16 @@ export function planHealth(entitlement: OrcaBillingEntitlement, t: Translate): P } } if (entitlement.reason === 'overage_cap_reached') { - return { label: t('auto.components.billing.health.capReached', 'Cap reached'), dot: 'warning' } + return { + label: t('auto.components.billing.health.spendCapReached', 'Spend cap reached'), + dot: 'warning' + } } if (entitlement.reason === 'included_hours_exhausted') { - return { label: t('auto.components.billing.health.outOfHours', 'Out of hours'), dot: 'warning' } + return { + label: t('auto.components.billing.health.outOfSandboxHours', 'Out of sandbox hours'), + dot: 'warning' + } } if (entitlement.cancelAtPeriodEnd) { return { label: t('auto.components.billing.health.ending', 'Ending'), dot: 'warning' } diff --git a/src/renderer/src/components/billing/billing-summary-store.ts b/src/renderer/src/components/billing/billing-summary-store.ts index 5ba33290158..b7115772237 100644 --- a/src/renderer/src/components/billing/billing-summary-store.ts +++ b/src/renderer/src/components/billing/billing-summary-store.ts @@ -18,7 +18,19 @@ let lastReadAt = 0 let inFlight: Promise | null = null const MIN_REFRESH_MS = 60_000 +let lastStatus: OrcaBillingStatusResult | null = null + +/** The latest successful status for the current account, to seed views that open later. */ +export function getLastBillingStatus(): OrcaBillingStatusResult | null { + return lastStatus +} + 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' ? { diff --git a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx index 9f1635fb1ac..d3d50bb8f35 100644 --- a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx +++ b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx @@ -68,7 +68,9 @@ function OrderSummary({
- {t('auto.components.billing.checkout.dueToday', 'Due today')} + {phase.kind === 'paid' + ? t('auto.components.billing.checkout.paidRow', 'Paid') + : t('auto.components.billing.checkout.dueToday', 'Due today')}
{total === null ? '—' : formatCents(total, locale)} @@ -160,16 +162,16 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element { case 'paid': title = t('auto.components.billing.checkout.paid', 'Payment confirmed') body = t( - 'auto.components.billing.checkout.paidBody', - 'You’re on {{value0}}. Opening your team…', + 'auto.components.billing.checkout.paidBody2', + '{{value0}} plan is active. Opening your team…', { value0: props.team.label } ) break case 'canceled': title = t('auto.components.billing.checkout.canceled', 'Checkout canceled') body = t( - 'auto.components.billing.checkout.canceledBody', - 'Nothing was charged. You can pick up where you left off any time.' + 'auto.components.billing.checkout.canceledBody2', + 'Nothing was charged. You can choose a plan again any time.' ) break case 'needs-attention': @@ -253,8 +255,8 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element {

{t( - 'auto.components.billing.checkout.secured', - 'Payments by Stripe · Cards, Apple Pay and Link · 3-D Secure' + 'auto.components.billing.checkout.secured2', + 'Payments by Stripe · Cards, Apple Pay and Link · Bank verification' )}

diff --git a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts index 87411d782c0..ef6d1900244 100644 --- a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts +++ b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts @@ -14,7 +14,7 @@ import { } from './checkout-flow' /** How long the "paid" check shows before the Team page takes over. */ -export const PAID_HANDOFF_MS = 1_400 +export const PAID_HANDOFF_MS = 2_200 export type CheckoutFlow = { phase: CheckoutPhase diff --git a/src/renderer/src/components/billing/plan-billing-copy.ts b/src/renderer/src/components/billing/plan-billing-copy.ts index 8bb52f5d815..a584182fd4a 100644 --- a/src/renderer/src/components/billing/plan-billing-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-copy.ts @@ -13,36 +13,56 @@ export function denyReasonCopy( ): string { switch (reason) { case 'no_subscription': - return t('auto.components.billing.reasonNoPlan', 'Hosted sandboxes need a paid plan.') + return t('auto.components.billing.reasonNoPlan2', 'Orca Cloud needs a Team plan.') case 'subscription_inactive': - return t( - 'auto.components.billing.reasonInactive', - 'Your plan is not active. Choose a plan to start sandboxes.' - ) + return canManage + ? t( + 'auto.components.billing.reasonInactive', + 'Your plan is not active. Choose a plan to start sandboxes.' + ) + : t( + 'auto.components.billing.reasonInactiveMember', + 'Your team’s plan is not active. Ask an owner or admin to choose a plan.' + ) case 'payment_grace_expired': - return t( - 'auto.components.billing.reasonGraceExpired', - 'Your payment is overdue, so sandboxes are suspended. Update your payment method to resume.' - ) + return canManage + ? t( + 'auto.components.billing.reasonGraceExpired3', + 'Payment failed. New sandboxes can’t start and running sandboxes are asleep. Update your payment method. Your files are safe.' + ) + : t( + 'auto.components.billing.reasonGraceExpiredMember2', + 'Payment failed. New sandboxes can’t start and running sandboxes are asleep. Ask an owner or admin to update the payment method. Your files are safe.' + ) case 'payment_past_due': - return t( - 'auto.components.billing.reasonPastDue', - 'Your last payment failed. Update your payment method to start new sandboxes.' - ) + return canManage + ? t( + 'auto.components.billing.reasonPastDue', + 'Your last payment failed. Update your payment method to start new sandboxes.' + ) + : t( + 'auto.components.billing.reasonPastDueMember', + 'Your team’s last payment failed. Ask an owner or admin to update the payment method.' + ) case 'included_hours_exhausted': - return t( - 'auto.components.billing.reasonExhaustedOptIn', - 'You have used all included hours this month. Turn on overage to keep starting sandboxes.' - ) + return canManage + ? t( + 'auto.components.billing.reasonExhausted3', + 'Out of sandbox hours for this month. Turn on overage to keep starting sandboxes. Your files are safe.' + ) + : t( + 'auto.components.billing.reasonExhaustedMember2', + 'Out of sandbox hours for this month. Ask an owner or admin to add hours. Your files are safe.' + ) case 'overage_cap_reached': return canManage ? t( - 'auto.components.billing.reasonCapAdmin', - 'This month’s overage cap is spent. Raise the cap to keep starting sandboxes.' + 'auto.components.billing.reasonCapAdmin2', + 'Spend cap reached. Raise the monthly spend cap to keep starting sandboxes. Your files are safe.' ) : t( - 'auto.components.billing.reasonCapMember', - 'This month’s overage cap is spent. Ask an owner or admin to raise it.' + 'auto.components.billing.reasonCapMember3', + 'Spend cap reached. Ask an owner or admin to raise the spend cap. Your files are safe.' ) } } @@ -68,8 +88,8 @@ export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): st return null case 'forbidden': return t( - 'auto.components.billing.openForbidden', - 'Only an org owner or admin can manage billing.' + 'auto.components.billing.openForbidden2', + 'Only an owner or admin can manage billing.' ) case 'already-subscribed': return t( @@ -82,7 +102,10 @@ export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): st 'There is no billing account yet. Choose a plan first.' ) case 'signed-out': - return t('auto.components.billing.openSignedOut', 'Sign in to Orca again to manage billing.') + return t( + 'auto.components.billing.openSignedOut2', + 'Sign in to Orca again to manage your team.' + ) case 'unconfigured': return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.') case 'failed': @@ -100,11 +123,14 @@ export function overageFailureCopy(result: OrcaBillingOverageResult, t: Translat return t('auto.components.billing.overageNoPlan', 'Overage needs an active plan.') case 'forbidden': return t( - 'auto.components.billing.openForbidden', - 'Only an org owner or admin can manage billing.' + 'auto.components.billing.openForbidden2', + 'Only an owner or admin can manage billing.' ) case 'signed-out': - return t('auto.components.billing.openSignedOut', 'Sign in to Orca again to manage billing.') + return t( + 'auto.components.billing.openSignedOut2', + 'Sign in to Orca again to manage your team.' + ) case 'unconfigured': return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.') case 'failed': diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index 396ba70166d..ec3dc45cb75 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -1,5 +1,6 @@ // Shared sample entitlements for billing tests and component fixtures. import type { OrcaBillingEntitlement, OrcaBillingOffers } from '../../../../shared/orca-billing' +import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' const HOUR = 3600 @@ -13,7 +14,7 @@ export const sampleOffers: OrcaBillingOffers = { largeMachineWeight: 2, includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, - idleSleepMinutes: 15, + idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 75, defaultSpendCapCents: 2500 }, diff --git a/src/renderer/src/components/billing/plans/EnterprisePlanCard.tsx b/src/renderer/src/components/billing/plans/EnterprisePlanCard.tsx index 9ab831628d7..08e50ef4d55 100644 --- a/src/renderer/src/components/billing/plans/EnterprisePlanCard.tsx +++ b/src/renderer/src/components/billing/plans/EnterprisePlanCard.tsx @@ -21,8 +21,8 @@ export function EnterprisePlanCard({ {enterprise.label} } - price={

{enterprise.priceLabel}

} - priceNote={t('auto.components.billing.plans.entPriced', 'Priced for your organization')} + price={

{enterprise.priceLabel}

} + priceNote={t('auto.components.billing.plans.entPriced2', 'Priced for your team')} featuresLead={t('auto.components.billing.plans.entLead', 'Everything in Team, plus:')} features={[ t('auto.components.billing.plans.entByoc', 'Run sandboxes in your own cloud account'), diff --git a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx index 9c3b6e3cf7b..16e304cc02c 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogContent.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogContent.tsx @@ -8,23 +8,32 @@ import { PlansView, isSubscribed, type PlansViewProps } from './PlansView' * Top-anchored so loading, plans and checkout never make the dialog jump (review M4). */ export function PlansDialogContent( - props: PlansViewProps & { checkout?: ReactNode } + props: PlansViewProps & { + checkout?: ReactNode + /** Checkout state, so the dialog title says what happened (paid, canceled). */ + checkoutState?: 'paid' | 'canceled' | 'other' + /** Payment landed: the Team page takes over, so this dialog leaves without its zoom-out. */ + handingOff?: boolean + } ): React.JSX.Element { const t = useTranslate() const subscribed = isSubscribed(props.result) - const { checkout, ...viewProps } = props + const { checkout, checkoutState, handingOff, ...viewProps } = props return ( { - // Land on the primary action for this state when it is already rendered (review P1-13); - // otherwise on the dialog itself so nothing looks pre-selected. + // The dialog itself first; PlansView moves focus to the primary action once plans load. event.preventDefault() if (event.currentTarget instanceof HTMLElement) { - const primary = event.currentTarget.querySelector('[data-plans-primary]') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: focusVisible is a valid FocusOptions member newer than this TS lib. - ;(primary ?? event.currentTarget).focus({ focusVisible: false } as FocusOptions) + event.currentTarget.focus() } }} > @@ -34,7 +43,11 @@ export function PlansDialogContent(

{checkout - ? t('auto.components.billing.checkout.title', 'Checkout') + ? checkoutState === 'paid' + ? t('auto.components.billing.checkout.titlePaid', 'Welcome to Orca Cloud') + : checkoutState === 'canceled' + ? t('auto.components.billing.checkout.titleCanceled', 'Checkout canceled') + : t('auto.components.billing.checkout.title', 'Checkout') : subscribed ? t('auto.components.billing.plans.titleSubscribed', 'Your Orca Cloud plan') : t('auto.components.billing.plans.title', 'Cloud sandboxes for your whole team')} diff --git a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx index fba92bd91c7..a18897ec431 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx @@ -6,6 +6,7 @@ import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing' 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 { useOrcaBillingStatus } from '../use-orca-billing-status' import { PlansDialogContent } from './PlansDialogContent' @@ -25,7 +26,7 @@ export function PlansDialogHost(): React.JSX.Element { const orgId = useAppStore((state) => state.orcaProfileAuthStatus?.cloud?.activeOrgId ?? null) const seats = useOrgSeatCount(open ? orgId : null) const [busy, setBusy] = useState(false) - const [notice, setNotice] = useState(null) + const [notice, setNotice] = useState(null) const [orderedAt, setOrderedAt] = useState(0) const onPaid = useCallback((paidSeats: number) => { @@ -44,13 +45,17 @@ export function PlansDialogHost(): React.JSX.Element { error: String(error) })) setBusy(false) + const failure = openFailureCopy(outcome, t) setNotice( - outcome.status === 'opened' - ? t( - 'auto.components.billing.continueInBrowser', - 'Continue in your browser. This updates when you come back.' - ) - : openFailureCopy(outcome, t) + failure + ? { kind: 'error', text: failure } + : { + kind: 'info', + text: t( + 'auto.components.billing.continueInBrowser', + 'Continue in your browser. This updates when you come back.' + ) + } ) } @@ -81,6 +86,14 @@ export function PlansDialogHost(): React.JSX.Element { onManage={() => void openPortal()} onContactSales={(url) => void window.api.shell.openUrl(url)} onRetry={billing.refresh} + checkoutState={ + checkout.phase.kind === 'paid' + ? 'paid' + : checkout.phase.kind === 'canceled' + ? 'canceled' + : 'other' + } + handingOff={checkout.phase.kind === 'paid'} checkout={ checkout.phase.kind !== 'idle' && team ? ( +
value={value} onChange={onChange} diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index 182f58090f9..dee2a120e06 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useEffect, useState } from 'react' import { Cloud, KeyRound, Zap } from 'lucide-react' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' @@ -12,6 +12,7 @@ import { } from '../../../../../shared/orca-billing' import { PaymentIssueNotice } from '../PaymentIssueNotice' import { PlanStatusBadge } from '../PlanStatusBadge' +import type { PlanBillingNotice } from '../PlanBillingSection' import { seatCountLabel } from '../team/team-copy' import { formatHours, includedUsagePercent } from '../plan-billing-format' import { EnterprisePlanCard } from './EnterprisePlanCard' @@ -22,7 +23,7 @@ import { annualSavingsPercent, clampSeats } from './plans-pricing' export type PlansViewProps = { result: OrcaBillingStatusResult | null busy: boolean - notice: string | null + notice: PlanBillingNotice | null /** Seats Checkout will bill: org members, or 1 for a personal account. */ seats: number onCheckout: (args: { interval: OrcaBillingInterval; seats: number }) => void @@ -55,21 +56,21 @@ function ValueProps(): React.JSX.Element { icon: Zap, title: t('auto.components.billing.plans.vpWakeTitle', 'Wake in seconds'), body: t( - 'auto.components.billing.plans.vpWakeBody', - 'Idle sandboxes sleep to save hours and resume right where they left off.' + 'auto.components.billing.plans.vpWakeBody2', + 'Idle sandboxes sleep to save hours and wake with your files as you left them.' ) }, { icon: KeyRound, - title: t('auto.components.billing.plans.vpSecretsTitle', 'Secrets never stored in the VM'), + title: t('auto.components.billing.plans.vpSecretsTitle3', 'API keys stay out of the sandbox'), body: t( - 'auto.components.billing.plans.vpSecretsBody2', - 'Credentials are injected into outbound requests and never touch the VM’s disk.' + 'auto.components.billing.plans.vpSecretsBody4', + 'API keys you add to Orca are never written to the sandbox. Agents and terminals get them as environment variables.' ) } ] return ( -
    +
      {items.map((item) => (
    • @@ -112,13 +113,14 @@ function CurrentPlanStrip({
= 100 ? 'warning' : 'default'} + aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')} />
{t( - 'auto.components.billing.hoursUsedMonth', - '{{value0}} of {{value1}} hours used this month', + 'auto.components.billing.sandboxHoursUsedMonth', + '{{value0}} of {{value1}} sandbox hours used this month', { value0: formatHours(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), value1: formatHours(entitlement.includedSeconds) @@ -146,7 +148,13 @@ function SkeletonLine({ className }: { className: string }): React.JSX.Element { return } -function SkeletonCard({ lines }: { lines: number }): React.JSX.Element { +function SkeletonCard({ + lines, + seatRow = false +}: { + lines: number + seatRow?: boolean +}): React.JSX.Element { return (
@@ -154,6 +162,7 @@ function SkeletonCard({ lines }: { lines: number }): React.JSX.Element {
+ {seatRow ? : null}
{Array.from({ length: lines }, (_, index) => ( @@ -178,12 +187,16 @@ function PlansSkeleton(): React.JSX.Element { >
- +
- +
+
+ + +
) } @@ -194,7 +207,7 @@ function PlansLoadError({ onRetry }: { onRetry: () => void }): React.JSX.Element
('month') 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. + useEffect(() => { + const active = document.activeElement + if ( + ready && + (!active || active === document.body || active.getAttribute('role') === 'dialog') + ) { + document.querySelector('[role="dialog"] [data-plans-primary]')?.focus() + } + }, [ready]) if (result?.status === 'signed-out' || result?.status === 'unconfigured') { return (

{result.status === 'signed-out' - ? t('auto.components.billing.openSignedOut', 'Sign in to Orca again to manage billing.') + ? t( + 'auto.components.billing.openSignedOut2', + 'Sign in to Orca again to manage your team.' + ) : t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')}

) @@ -278,13 +306,13 @@ export function PlansView(props: PlansViewProps): React.JSX.Element {

{t( - 'auto.components.billing.plans.footHours2', - 'Hours reset monthly, including on annual plans.' + 'auto.components.billing.plans.footHours3', + 'Hours reset every month, including on annual plans.' )}

{t( - 'auto.components.billing.plans.footTerms2', + 'auto.components.billing.plans.footTerms4', 'Prices in USD, before tax. Overage is off until an owner or admin turns it on. Cancel anytime; your plan runs to the end of the billing period.' )}

diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index 688d23cd74f..2bbb0a43b13 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -1,6 +1,8 @@ import { ExternalLink, Lock, Users } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import type { PlanBillingNotice } from '../PlanBillingSection' import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaBillingInterval, OrcaBillingOffers } from '../../../../../shared/orca-billing' @@ -26,7 +28,7 @@ export function TeamPlanCard({ /** choose: can buy; current: already on Team; locked: only owners/admins can buy. */ mode: TeamPlanCardMode busy: boolean - notice: string | null + notice: PlanBillingNotice | null /** A payment banner already offers the same Portal action. */ hideManage: boolean onCheckout: () => void @@ -42,29 +44,34 @@ export function TeamPlanCard({ const features = [ t( - 'auto.components.billing.plans.featureHours2', - '{{value0}} Standard hours (4 vCPU / 8 GB) per seat each month, pooled across your team', + 'auto.components.billing.plans.featureHours4', + '{{value0}} sandbox hours per seat each month, pooled across your team', { value0: String(team.includedHoursPerSeat) } ), t( - 'auto.components.billing.plans.featureLarge2', - 'Large (8 vCPU / 16 GB) uses hours at {{value0}}×', + 'auto.components.billing.plans.featureLarge3', + 'Standard (4 vCPU · 8 GB) sandboxes; Large (8 vCPU · 16 GB) uses sandbox hours at {{value0}}× the rate', { value0: String(team.largeMachineWeight) } ), - t('auto.components.billing.plans.featureConcurrency', '{{value0}} running sandboxes per seat', { - value0: String(team.concurrentSandboxesPerSeat) - }), + t( + 'auto.components.billing.plans.featureConcurrency2', + '{{value0}} sandboxes running at once per seat', + { + value0: String(team.concurrentSandboxesPerSeat) + } + ), t('auto.components.billing.plans.featureSleep2', 'Sleeps after {{value0}} minutes idle', { value0: String(team.idleSleepMinutes) }), t( - 'auto.components.billing.plans.featureOverage', - 'Optional overage at {{value0}}/hr ({{value1}}/hr Large) with a monthly spend cap', + 'auto.components.billing.plans.featureOverage3', + 'Optional overage at {{value0}}/hour ({{value1}}/hour on Large), capped at a monthly spend cap you set ({{value2}} by default)', { value0: formatCents(team.overageCentsPerHour, locale), - value1: formatCents(team.overageCentsPerHour * team.largeMachineWeight, locale) + value1: formatCents(team.overageCentsPerHour * team.largeMachineWeight, locale), + value2: formatCents(team.defaultSpendCapCents, locale) } ) ] @@ -90,7 +97,7 @@ export function TeamPlanCard({ {monthly === null ? null : ( - {t('auto.components.billing.plans.perSeatMonth', 'per seat / month')} + {t('auto.components.billing.plans.perSeatPerMonth', 'per seat per month')} )}

@@ -101,8 +108,8 @@ export function TeamPlanCard({ ? team.annualPriceCentsPerSeat === null ? t('auto.components.billing.plans.billedYearly', 'Billed yearly') : t( - 'auto.components.billing.plans.billedYearlyAmount', - 'Billed {{value0}} per seat yearly', + 'auto.components.billing.plans.billedYearlyAmount2', + '{{value0}} per seat, billed yearly', { value0: formatCents(team.annualPriceCentsPerSeat, locale) } @@ -113,9 +120,14 @@ export function TeamPlanCard({ mode === 'choose' ? (

- {t('auto.components.billing.plans.seatsOne', 'Seats: {{value0}} (one per team member)', { - value0: String(seats) - })} + {t( + 'auto.components.billing.plans.seatsPerMember', + '{{count}} seats, one per team member', + { + count: seats, + defaultValue_one: '{{count}} seat, one per team member' + } + )}

{total === null ? null : (

@@ -138,8 +150,8 @@ export function TeamPlanCard({ -

- {notice ?? - t( - 'auto.components.billing.plans.seatsFollow2', - 'Seats follow your team: new members add a seat now; removed seats drop off at renewal.' - )} -

+ {notice?.kind === 'error' ? ( + + ) : ( +

+ {notice?.text ?? + t( + 'auto.components.billing.plans.seatsFollow2', + 'Seats follow your team: new members add a seat now; removed seats drop off at renewal.' + )} +

+ )} ) } else if (mode === 'current') { @@ -171,20 +187,24 @@ export function TeamPlanCard({ type="button" variant="outline" className="w-full" - disabled={busy} - onClick={onManage} + aria-disabled={busy || undefined} + onClick={busy ? undefined : onManage} data-plans-primary="" > {t('auto.components.billing.manageBilling', 'Manage billing')} -

- {notice ?? - t( - 'auto.components.billing.plans.manageHint', - 'Switch monthly or annual, update payment, or cancel.' - )} -

+ {notice?.kind === 'error' ? ( + + ) : ( +

+ {notice?.text ?? + t( + 'auto.components.billing.plans.manageHint', + 'Switch monthly or annual, update payment, or cancel.' + )} +

+ )} ) } else { @@ -193,8 +213,8 @@ export function TeamPlanCard({

{t( - 'auto.components.billing.plans.lockedBody', - 'Only an owner or admin of your org can choose a plan. Ask one of them to open Plan & billing in Orca.' + 'auto.components.billing.plans.lockedBody2', + 'Only an owner or admin of your team can choose a plan. Ask one of them to open Plan & billing in Orca.' )}

diff --git a/src/renderer/src/components/billing/register-plan-billing-menu-item.test.ts b/src/renderer/src/components/billing/register-plan-billing-menu-item.test.ts index 8ba5aa8b144..2a8374fcdb6 100644 --- a/src/renderer/src/components/billing/register-plan-billing-menu-item.test.ts +++ b/src/renderer/src/components/billing/register-plan-billing-menu-item.test.ts @@ -38,8 +38,8 @@ describe('account menu billing items', () => { state: 'connected', persistence: 'encrypted', capabilities: { flags: {}, refreshedAt: 0 } - }) - ).toEqual([]) + }).map((item) => item.id) + ).toEqual(['orca.team']) expect(visible()).toEqual(['orca.team', 'orca.plan-billing']) const plans = getRegisteredAccountMenuItems().find((item) => item.id === 'orca.plan-billing') plans?.onSelect() diff --git a/src/renderer/src/components/billing/register-plan-billing-menu-item.ts b/src/renderer/src/components/billing/register-plan-billing-menu-item.ts index 092c9f71f78..408ed3848c6 100644 --- a/src/renderer/src/components/billing/register-plan-billing-menu-item.ts +++ b/src/renderer/src/components/billing/register-plan-billing-menu-item.ts @@ -1,4 +1,4 @@ -import { CreditCard, Sparkles, Users } from 'lucide-react' +import { Cloud, CreditCard, Users } from 'lucide-react' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { registerAccountMenuItem } from '../sidebar/account-menu/account-menu-items' @@ -36,7 +36,8 @@ export function registerPlanBillingMenuItem(): () => void { label: () => translate('auto.components.billing.team.menuItem', 'Team'), icon: Users, order: 10, - requiredCapability: BILLING_CAPABILITY, + // Team management doesn't depend on billing or a flag: any signed-in account can open it. + requiresSignIn: true, onSelect: () => openTeamPage() }) @@ -55,7 +56,7 @@ export function registerPlanBillingMenuItem(): () => void { disposeUpgrade = registerAccountMenuItem({ id: UPGRADE_ITEM_ID, label: () => translate('auto.components.billing.upgrade.menuItem', 'Upgrade to Orca Cloud'), - icon: Sparkles, + icon: Cloud, order: 9, tone: 'accent', requiredCapability: BILLING_CAPABILITY, diff --git a/src/renderer/src/components/billing/team/TeamCreateView.tsx b/src/renderer/src/components/billing/team/TeamCreateView.tsx index c28944a1703..f90867ee730 100644 --- a/src/renderer/src/components/billing/team/TeamCreateView.tsx +++ b/src/renderer/src/components/billing/team/TeamCreateView.tsx @@ -1,4 +1,4 @@ -import { ORCA_ORG_NAME_MAX_LENGTH } from '../../../../../shared/orca-org-management' +import { isValidOrgName, ORCA_ORG_NAME_MAX_LENGTH } from '../../../../../shared/orca-org-management' import { useId, useState } from 'react' import { ArrowRight, Users } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -7,6 +7,7 @@ import { LoadingSpinner } from '@/components/LoadingSpinner' import { useTranslate } from '@/i18n/use-translate' import type { OrcaCloudOrgSummary } from '../../../../../shared/orca-profiles' import { TeamMark } from './TeamAvatar' +import { normalizeOrgRole, roleLabel } from './team-roles' export type TeamCreateViewProps = { /** Teams the user already belongs to (switch instead of creating). */ @@ -26,6 +27,8 @@ export function TeamCreateView(props: TeamCreateViewProps): React.JSX.Element { const id = useId() const [name, setName] = useState('') const trimmed = name.trim() + const nameValid = isValidOrgName(trimmed) + const showRule = trimmed.length > 0 && !nameValid return (
{ event.preventDefault() - if (trimmed && !props.creating) { + if (nameValid && !props.creating && !props.unavailable) { props.onCreate(trimmed) } }} @@ -69,12 +72,18 @@ export function TeamCreateView(props: TeamCreateViewProps): React.JSX.Element { 'auto.components.billing.team.teamNamePlaceholder', 'Acme Engineering' )} - aria-invalid={props.error ? true : undefined} - aria-describedby={props.error ? `${id}-error` : undefined} + aria-invalid={props.error || showRule ? true : undefined} + aria-describedby={props.error ? `${id}-error` : showRule ? `${id}-rule` : undefined} onChange={(event) => setName(event.target.value)} - disabled={props.creating || props.unavailable} + readOnly={props.creating} + aria-disabled={props.creating || undefined} + disabled={props.unavailable} /> - @@ -90,6 +99,14 @@ export function TeamCreateView(props: TeamCreateViewProps): React.JSX.Element { )}

) : null} + {showRule && !props.error ? ( +

+ {t( + 'auto.components.billing.team.createInvalid2', + 'Use letters, numbers, spaces or underscores (up to 64).' + )} +

+ ) : null} {props.error ? (

{org.name}

{org.role ? ( -

- {org.role.toLowerCase()} +

+ {roleLabel(normalizeOrgRole(org.role), t)}

) : null}
@@ -119,8 +136,12 @@ export function TeamCreateView(props: TeamCreateViewProps): React.JSX.Element { type="button" variant="outline" size="sm" - disabled={props.switchingOrgId !== null} - onClick={() => props.onSwitch(org.orgId)} + aria-disabled={props.switchingOrgId !== null || undefined} + onClick={() => { + if (props.switchingOrgId === null) { + props.onSwitch(org.orgId) + } + }} > {props.switchingOrgId === org.orgId ? ( diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index ebb7d71334c..5485dadf76d 100644 --- a/src/renderer/src/components/billing/team/TeamDialogHost.tsx +++ b/src/renderer/src/components/billing/team/TeamDialogHost.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' @@ -73,12 +73,30 @@ function TeamPageBody({ arrival }: { arrival: ReturnType { if (outcome.status === 'created') { - await selectOrg(outcome.orgId) - toast.success( - t('auto.components.billing.team.createdToast', '{{value0}} created', { - value0: outcome.name - }) - ) + // Clear "create" first so the remount for the new team lands on its page, not a blank form. + clearTeamPageArrival() + const selected = await selectOrg(outcome.orgId) + if (selected?.status === 'selected') { + toast.success( + t('auto.components.billing.team.createdToast', '{{value0}} created', { + value0: outcome.name + }) + ) + } else { + toast.error( + t( + 'auto.components.billing.team.createdNotSwitched', + '{{value0}} was created, but Orca couldn’t switch to it.', + { value0: outcome.name } + ), + { + action: { + label: t('auto.components.billing.team.switch', 'Switch'), + onClick: () => void selectOrg(outcome.orgId) + } + } + ) + } } else if (outcome.status === 'unsupported') { setCreateUnavailable(true) } else { @@ -89,6 +107,7 @@ function TeamPageBody({ arrival }: { arrival: ReturnType { + clearTeamPageArrival() setSwitchingOrgId(target) void selectOrg(target).finally(() => setSwitchingOrgId(null)) } @@ -129,7 +148,8 @@ function TeamPageBody({ arrival }: { arrival: ReturnType void window.api.shell.openUrl(url)} /> ) } @@ -222,6 +243,15 @@ export function TeamDialogHost(): React.JSX.Element { const { open, arrival } = useTeamPageState() // Remount per team so optimistic rows and row errors never carry over to another org. const orgKey = useAppStore((state) => state.orcaProfileAuthStatus?.cloud?.activeOrgId ?? 'none') + // An arrival (create mode, or the post-checkout welcome) belongs to the team it was opened for; + // switching teams drops it so it never shows on another team. + const arrivalOrg = useRef(orgKey) + useEffect(() => { + if (arrivalOrg.current !== orgKey) { + arrivalOrg.current = orgKey + clearTeamPageArrival() + } + }, [orgKey]) return ( localInput.current?.focus()} > @@ -195,7 +195,7 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El className={cn( 'inline-flex max-w-full items-center gap-1 rounded-full border py-0.5 pr-0.5 pl-2 text-xs animate-in fade-in-0 zoom-in-95 duration-150 motion-reduce:animate-none', bad - ? 'border-destructive/50 bg-destructive/10 text-destructive' + ? 'border-destructive bg-destructive/10 text-foreground' : 'border-border bg-secondary text-secondary-foreground' )} title={ @@ -205,10 +205,18 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El : t('auto.components.billing.team.notAnEmail', 'Not an email address')) } > + {bad ? ( + + ) : null} {candidate.email} + {bad ? ( + + {error ?? t('auto.components.billing.team.notAnEmail', 'Not an email address')} + + ) : null}
@@ -326,17 +342,20 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El {impactCopy(impact, committedValid, locale, t)} {paymentFailed && committedValid.length > 0 ? ` ${t( - 'auto.components.billing.team.invitePaymentFailed', - 'New seats are charged once the payment issue is fixed.' + 'auto.components.billing.team.invitePaymentFailed2', + 'New seats are charged once the failed payment is fixed.' + )}` + : null} + {invalidCount > 0 + ? ` ${t( + 'auto.components.billing.team.skipInvalid', + 'Skipping {{count}} invalid entries.', + { + count: invalidCount, + defaultValue_one: 'Skipping {{count}} invalid entry.' + } )}` : null} - {invalidCount === 1 - ? ` ${t('auto.components.billing.team.skipOne', 'Skipping 1 invalid entry.')}` - : invalidCount > 1 - ? ` ${t('auto.components.billing.team.skipN', 'Skipping {{value0}} invalid entries.', { - value0: String(invalidCount) - })}` - : null}

{describedErrors.length > 0 ? (
    diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index b249732c8b5..4670e261dfa 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -1,5 +1,7 @@ import { Crown, LogOut, MailPlus, MoreHorizontal, UserMinus, XCircle } from 'lucide-react' +import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' import { DropdownMenu, DropdownMenuContent, @@ -19,7 +21,7 @@ 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 { memberStatusLabel, roleDescription } from './team-copy' +import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy' import { assignableRoles, roleLabel } from './team-roles' import type { TeamRow } from './team-roster-rows' @@ -68,7 +70,7 @@ function RoleControl({ const member = row.member if (!row.manageable) { return ( - + {roleLabel(member.role, t)} ) @@ -214,10 +216,11 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { ? row.member.displayName ? row.member.email : null - : t('auto.components.billing.team.invitedAgo', 'Invited {{value0}} as {{value1}}', { - value0: relativeSince(row.invite.createdAt, props.now, locale), - value1: roleLabel(row.invite.role, t).toLowerCase() - }) + : invitedAsCopy( + row.invite.role, + relativeSince(row.invite.createdAt, props.now, locale), + t + ) return (
  • ) : null} {row.status === 'active' ? null : ( - - {memberStatusLabel(row.status, t)} - + + + {memberStatusLabel(row.status, t)} + + )}

    {secondary ? ( @@ -264,17 +262,13 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { onChange={(role) => props.onChangeRole(row.member, role)} /> ) : ( - + {roleLabel(row.invite.role, t)} )}
- {state.error ? ( -

- {state.error} -

- ) : null} + {state.error ? : null} ) })} diff --git a/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx b/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx index ccbcc166765..e9c4c2b37d5 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx @@ -73,7 +73,8 @@ const base: TeamPageViewProps = { onSeePlans: noop, onManageBilling: noop, onCreateWorkspace: noop, - onDismissArrival: noop + onDismissArrival: noop, + onContactSales: noop } function Page(props: Partial): React.JSX.Element { @@ -225,3 +226,20 @@ export const invitePasted = defineFixture({ await new Promise((resolve) => setTimeout(resolve, 100)) } }) + +/** Short roster so the Enterprise SSO row and Leave sit inside the frame. */ +export const ssoAndLeave = defineFixture({ + width, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index 46b4b97c40d..25aa08ef480 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -1,5 +1,5 @@ -import { useRef } from 'react' -import { LogOut, RefreshCw } from 'lucide-react' +import { useEffect, useId, useRef } from 'react' +import { ExternalLink, LogOut, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' @@ -48,6 +48,8 @@ export type TeamPageViewProps = { onManageBilling: () => void onCreateWorkspace: () => void onDismissArrival: () => void + /** Opens the Enterprise contact page (SSO/SCIM are Enterprise; nothing here pretends otherwise). */ + onContactSales: (url: string) => void } function viewerRoleSentence(role: OrcaOrgRole, t: Translate): string { @@ -107,6 +109,18 @@ function SkeletonRows(): React.JSX.Element { export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { const t = useTranslate() const inviteInput = useRef(null) + const ssoTitleId = useId() + const hasRoster = props.roster !== null + useEffect(() => { + const active = document.activeElement + if ( + hasRoster && + (!active || active === document.body || active.getAttribute('role') === 'dialog') + ) { + document.querySelector('[data-team-page-heading]')?.focus() + } + }, [hasRoster]) + const leaveTitleId = useId() if (!props.org) { return ( @@ -120,6 +134,7 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { const roster = props.roster?.status === 'ok' ? props.roster.roster : null const entitlement = props.billing?.status === 'ok' ? props.billing.entitlement : null + const enterprise = entitlement?.offers?.enterprise ?? null const rows = roster ? teamRows(roster, props.viewerUserId) : [] const selfRow = rows.find((row) => row.self) const viewerRole = roster?.viewerRole ?? 'member' @@ -132,14 +147,20 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
-

{props.org.name}

+

+ {props.org.name} +

{roster ? [ memberCountLabel(roster.members.length, t), roster.pendingInvites.length > 0 - ? t('auto.components.billing.team.invitedN', '{{value0}} invited', { - value0: String(roster.pendingInvites.length) + ? t('auto.components.billing.team.invitedCount', '{{count}} invited', { + count: roster.pendingInvites.length }) : null, viewerRoleSentence(viewerRole, t) @@ -182,6 +203,18 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { ) : null} + {props.roster === null ? ( +

+ +
+ + + +
+ +
+ ) : null} + {roster?.canManageMembers ? ( @@ -237,8 +270,8 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { detail={ props.roster.status === 'reconnect-required' ? t( - 'auto.components.billing.openSignedOut', - 'Sign in to Orca again to manage billing.' + 'auto.components.billing.openSignedOut2', + 'Sign in to Orca again to manage your team.' ) : t( 'auto.components.billing.team.loadFailed2', @@ -260,51 +293,80 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { ) : null} - {selfRow ? ( -
-
-

- {t('auto.components.billing.team.leaveTitle', 'Leave {{value0}}', { - value0: props.org.name - })} -

-

- {canLeave - ? t( - 'auto.components.billing.team.leaveBody', - 'You lose access to the team’s cloud workspaces and secrets. An admin can invite you back.' - ) - : t( - 'auto.components.billing.team.leaveLastOwner', - 'You’re the only owner. Make someone else an owner first.' + {(roster?.canManageMembers && enterprise) || selfRow ? ( +

+ {roster?.canManageMembers && enterprise ? ( +
+
+

+ {t('auto.components.billing.team.ssoTitle', 'Single sign-on and provisioning')} +

+

+ {t( + 'auto.components.billing.team.ssoBody', + 'SAML SSO and SCIM user provisioning are part of {{value0}}.', + { value0: enterprise.label } )} -

-
- -
+ +
+ ) : null} + {selfRow ? ( +
- - {t('auto.components.billing.team.leaveCta', 'Leave team')} - - -
+
+

+ {t('auto.components.billing.team.leaveTitle', 'Leave {{value0}}', { + value0: props.org.name + })} +

+

+ {canLeave + ? t( + 'auto.components.billing.team.leaveBody2', + 'You lose access to the team’s cloud workspaces and secrets. An owner or admin can invite you back.' + ) + : t( + 'auto.components.billing.team.leaveLastOwner', + 'You’re the only owner. Make someone else an owner first.' + )} +

+
+ + + + + ) : null} +
) : null}
) diff --git a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx index c7a28df9a45..7b77ce5bb85 100644 --- a/src/renderer/src/components/billing/team/TeamPlanSummary.tsx +++ b/src/renderer/src/components/billing/team/TeamPlanSummary.tsx @@ -175,7 +175,7 @@ export function TeamSeatsCard({ } detail={ entitlement.offers - ? t('auto.components.billing.team.perSeatMo', '{{value0}} per seat / month', { + ? t('auto.components.billing.team.perSeatPerMonth', '{{value0}} per seat per month', { value0: formatCents( perSeatMonthlyCents(entitlement.offers.team, entitlement.interval ?? 'month') ?? 0, diff --git a/src/renderer/src/components/billing/team/TeamSettingsLink.tsx b/src/renderer/src/components/billing/team/TeamSettingsLink.tsx index 68d87bfec50..f65db470502 100644 --- a/src/renderer/src/components/billing/team/TeamSettingsLink.tsx +++ b/src/renderer/src/components/billing/team/TeamSettingsLink.tsx @@ -1,4 +1,5 @@ import { ChevronRight } from 'lucide-react' +import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup' import { useTranslate } from '@/i18n/use-translate' import { TeamMark } from './TeamAvatar' import { memberCountLabel } from './team-copy' @@ -18,13 +19,14 @@ export function TeamSettingsLink({ const members = roster.result?.status === 'ok' ? roster.result.roster.members.length : null return (
-

- {t('auto.components.billing.team.title', 'Team')} -

+ + ) +} + +function Field({ + id, + label, + helpId, + help, + error, + link, + children +}: { + id: string + label: string + helpId?: string + help?: string + error?: React.ReactNode + link?: React.ReactNode + children: React.ReactNode +}): React.JSX.Element { + return ( +
+
+ + {link} +
+ {children} + {error ? ( + + ) : help ? ( +

+ {help} +

+ ) : null} +
+ ) +} + +/** The inputs for one way in. Typed keys live only in the draft until they are sent. */ +export function CloudAgentSetupFields({ + option, + formId, + draft, + onDraft, + failure, + canShare, + share, + onShare, + onSignInInstead +}: { + option: Exclude + /** Shown inline after a refused subscription token. */ + onSignInInstead?: () => void + formId: string + draft: CloudAgentSetupDraft + onDraft: (patch: Partial) => void + failure: CloudAgentSetupFailure | null + canShare: boolean + share: boolean + onShare: (share: boolean) => void +}): React.JSX.Element { + const t = useTranslate() + const errorFor = (field: string): React.ReactNode => + failure?.field === field ? ( + <> + {cloudSecretsErrorCopy(failure.error, t)} + {failure.error === 'subscription_token_refused' && onSignInInstead ? ( + <> + {' '} + + + ) : null} + + ) : null + const ids = (field: string): { id: string; helpId: string } => ({ + id: `${formId}-${field}`, + helpId: `${formId}-${field}-help` + }) + const textInput = ( + field: 'model' | 'codexModel' | 'baseUrl', + placeholder: string + ): React.JSX.Element => ( + onDraft({ [field]: event.target.value })} + placeholder={placeholder} + aria-invalid={failure?.field === field || undefined} + aria-describedby={ids(field).helpId} + spellCheck={false} + autoComplete="off" + className="h-8" + /> + ) + const keyInput = (placeholder?: string): React.JSX.Element => ( + onDraft({ key })} + invalid={failure?.field === 'key' || failure?.field === 'token'} + describedBy={ids('key').helpId} + placeholder={placeholder} + /> + ) + const keyHelp = t('cloudAgentSetup.keyHelp', 'Write-only. You won’t see it again after saving.') + + return ( +
+ {option === 'api-key' ? ( +
+
+ + +
+ } + help={keyHelp} + error={errorFor('key')} + > + {keyInput(draft.provider === 'anthropic' ? 'sk-ant-api03-…' : 'sk-proj-…')} + +
+ ) : null} + + {option === 'gateway' ? ( +
+
+ } + help={keyHelp} + error={errorFor('key')} + > + {keyInput('vck_…')} + +
+ + {textInput('model', '')} + + + {textInput('codexModel', '')} + +
+ ) : null} + + {option === 'custom' ? ( +
+
+ + {textInput('baseUrl', 'https://api.example.com/anthropic')} + +
+ + {keyInput()} + + + {textInput('model', '')} + +
+ ) : null} + + {canShare ? ( +
+ +

+ {t('cloudAgentSetup.shareDetail', 'Every teammate’s cloud agents use it.')} +

+
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupView.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupView.tsx new file mode 100644 index 00000000000..f11175641ba --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetupView.tsx @@ -0,0 +1,370 @@ +import { useId, useState } from 'react' +import { CircleCheck, Loader2 } from 'lucide-react' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { HOST_AGENT_SIGN_IN_AGENT_NAME as AGENT_NAME } from '../../../../shared/host-agent-sign-in-status' +import { cn } from '@/lib/utils' +import { Button } from '../ui/button' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs' +import { cloudSecretsErrorCopy } from '../settings/cloud-secrets/cloud-secrets-copy' +import { + CLOUD_SETUP_AGENTS, + type CloudAgentCredentialSource, + type CloudAgentReadiness, + type CloudSetupAgent +} from './cloud-agent-readiness' +import type { + CloudAgentSetupChoice, + CloudAgentSetupFailure, + CloudAgentSetupOption, + CloudAgentSetupScope +} from './cloud-agent-setup-choices' +import { + CloudAgentSetupFields, + EMPTY_DRAFT, + type CloudAgentSetupDraft +} from './CloudAgentSetupFields' +import { isOwnKeyEvent } from '../settings/cloud-secrets/CloudSecretEditor' + +export type { CloudAgentSetupFailure, CloudAgentSetupOption, CloudAgentSetupScope } +export type CloudAgentSetupSaved = { agents: CloudSetupAgent[]; scope: CloudAgentSetupScope } +type KeyOption = Exclude + +const KEY_OPTIONS: readonly KeyOption[] = ['api-key', 'gateway', 'custom'] +const EMPTY_DRAFTS: Record = { + 'api-key': EMPTY_DRAFT, + gateway: EMPTY_DRAFT, + custom: EMPTY_DRAFT +} + +/** "Claude: provided by your team · Codex: not set up", for the Subscription tab. */ +function agentStatusLine(readiness: CloudAgentReadiness, t: Translate): string { + return CLOUD_SETUP_AGENTS.map((agent) => { + const source = readiness[agent] + 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') + 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'] + return sources + .flatMap((source) => { + const agents = CLOUD_SETUP_AGENTS.filter((agent) => readiness[agent] === source) + if (agents.length === 0) { + return [] + } + const agent = + agents.length > 1 + ? 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 }) + ] + case 'cloud-secret': + return [ + t('cloudAgentSetup.source.cloudSecret', '{{agent}} uses your cloud secret', { agent }) + ] + } + }) + .join(' · ') +} + +/** "Claude key saved · shared with your team". Says stored, not verified: nothing tested the key yet. */ +export function cloudAgentSavedSummary(saved: CloudAgentSetupSaved, t: Translate): string { + const agent = + saved.agents.length > 1 + ? t('cloudAgentSetup.source.both', 'Claude and Codex') + : AGENT_NAME[saved.agents[0]] + return saved.scope === 'org' + ? t('cloudAgentSetup.saved.team', '{{agent}} key saved · shared with your team', { agent }) + : t('cloudAgentSetup.saved.personal', '{{agent}} key saved · personal', { agent }) +} + +function agentsFor(choice: CloudAgentSetupChoice): CloudSetupAgent[] { + if (choice.kind === 'api-key') { + return [choice.provider === 'anthropic' ? 'claude' : 'codex'] + } + return choice.kind === 'gateway' ? ['claude', 'codex'] : ['claude'] +} + +function choiceFor(option: KeyOption, draft: CloudAgentSetupDraft): CloudAgentSetupChoice { + switch (option) { + case 'api-key': + return { kind: 'api-key', provider: draft.provider, key: draft.key } + case 'gateway': + return { kind: 'gateway', key: draft.key, model: draft.model, codexModel: draft.codexModel } + case 'custom': + return { kind: 'custom', baseUrl: draft.baseUrl, token: draft.key, model: draft.model } + } +} + +export type CloudAgentSetupViewProps = { + /** Shown above the choices in the dialog: what already works. */ + readiness: CloudAgentReadiness | null + canShare: boolean + /** Build sheet: start in-VM sign-in. Without it (Settings) the Subscription tab explains and closes. */ + onSignIn?: () => void + onSave: ( + choice: CloudAgentSetupChoice, + scope: CloudAgentSetupScope + ) => Promise + onSaved: (saved: CloudAgentSetupSaved) => void + onCancel: () => void + /** Build sheet: the form opens from a button that unmounts, so focus moves into it. */ + focusOnOpen?: boolean + /** Dialog: tabs of different heights keep one floor so the centred dialog does not jump. */ + steadyHeight?: boolean + /** Fixtures only. */ + initialOption?: CloudAgentSetupOption + initialFailure?: CloudAgentSetupFailure | null +} + +/** The ways Claude Code or Codex can get access in Orca Cloud with a key, plus sign-in in the dialog. */ +export function CloudAgentSetupView({ + readiness, + canShare, + onSignIn, + onSave, + onSaved, + onCancel, + focusOnOpen = false, + steadyHeight = false, + initialOption, + initialFailure = null +}: CloudAgentSetupViewProps): React.JSX.Element { + const t = useTranslate() + const formId = useId() + const options: readonly CloudAgentSetupOption[] = ['sign-in', ...KEY_OPTIONS] + const [option, setOption] = useState(initialOption ?? options[0]) + // One draft per way in, so moving between tabs never loses what was typed. + const [drafts, setDrafts] = useState>(EMPTY_DRAFTS) + const draft = option === 'sign-in' ? EMPTY_DRAFT : drafts[option] + const [share, setShare] = useState(false) + const [saving, setSaving] = useState(false) + const [failure, setFailure] = useState(initialFailure) + const summary = readiness ? cloudAgentReadinessSummary(readiness, t) : '' + + const labels: Record = { + 'sign-in': { + tab: t('cloudAgentSetup.option.signIn', 'Subscription'), + detail: t( + 'cloudAgentSetup.option.signInDialog', + 'Sign in once inside a cloud workspace. Agent sign-ins stay on the sandbox’s disk, including through sleep.' + ) + }, + 'api-key': { + tab: t('cloudAgentSetup.option.apiKey', 'Agent key'), + detail: t( + 'cloudAgentSetup.option.apiKeyDetail', + 'An Anthropic or OpenAI API key, billed by usage.' + ) + }, + gateway: { + tab: t('cloudAgentSetup.option.gateway', 'AI Gateway'), + detail: t( + 'cloudAgentSetup.option.gatewayDetail', + 'One Vercel AI Gateway key runs both Claude Code and Codex.' + ) + }, + custom: { + tab: t('cloudAgentSetup.option.custom', 'Custom provider'), + detail: t( + 'cloudAgentSetup.option.customDetail', + 'Any Anthropic-compatible endpoint, for Claude Code.' + ) + } + } + + const submit = async (event: React.FormEvent): Promise => { + event.preventDefault() + if (option === 'sign-in' || saving) { + return + } + const choice = choiceFor(option, draft) + const scope: CloudAgentSetupScope = canShare && share ? 'org' : 'personal' + setSaving(true) + setFailure(null) + const result = await onSave(choice, scope) + setSaving(false) + if (result) { + setFailure(result) + return + } + setDrafts(EMPTY_DRAFTS) + onSaved({ agents: agentsFor(choice), scope }) + } + + const canSubmit = + option !== 'sign-in' && + draft.key.trim() !== '' && + (option !== 'custom' || draft.baseUrl.trim() !== '') + // Field problems sit under their field; only ones without a field land in the footer. + const footerError = + failure && failure.field === undefined + ? failure.error === 'unavailable' || + failure.error === 'timeout' || + failure.error === 'unknown' + ? t( + 'cloudAgentSetup.notSaved', + 'Couldn’t reach Orca Cloud. Your key wasn’t saved. Try again.' + ) + : cloudSecretsErrorCopy(failure.error, t) + : null + + return ( +
void submit(event)} + onKeyDown={(event) => { + // Escape from a portaled Select or menu bubbles here too; let it close only that. + if (event.key === 'Escape' && !saving && isOwnKeyEvent(event)) { + event.stopPropagation() + onCancel() + } + }} + className="space-y-3" + aria-label={t('cloudAgentSetup.title', 'Add an agent')} + > + {summary ? ( +
+ + {summary} +
+ ) : null} + { + const match = options.find((entry) => entry === next) + if (match) { + setOption(match) + setFailure(null) + } + }} + > + + {options.map((entry) => ( + + {labels[entry].tab} + + ))} + + {options.map((entry) => ( + + {/* A fixed floor keeps the footer still while tabs of different heights swap. */} +
+

{labels[entry].detail}

+ {entry === 'sign-in' ? ( + readiness ? ( +

{agentStatusLine(readiness, t)}

+ ) : null + ) : ( + { + setDrafts((current) => ({ + ...current, + [entry]: { ...current[entry], ...patch } + })) + setFailure(null) + }} + failure={failure} + canShare={canShare} + share={share} + onShare={setShare} + onSignInInstead={() => setOption('sign-in')} + /> + )} +
+
+ ))} +
+ +
+

+ {footerError} +

+
+ {/* Settings' Subscription tab has nothing to cancel: Got it is the only way out. */} + {option === 'sign-in' && !onSignIn ? null : ( + + )} + {option === 'sign-in' ? ( + + ) : ( + + )} +
+
+
+ ) +} + +/** The dialog's confirmation after a save. */ +export function CloudAgentSetupSavedNotice({ + saved, + onClose +}: { + saved: CloudAgentSetupSaved + onClose: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( +
+
+ +
+

{cloudAgentSavedSummary(saved, t)}

+

+ {t( + 'cloudAgentSetup.saved.detail', + 'New terminals and agents in running cloud workspaces get it within seconds, no rebuild.' + )} +

+
+
+
+ +
+
+ ) +} diff --git a/src/renderer/src/components/cloud-agent-setup/ComposerCloudAgentHint.tsx b/src/renderer/src/components/cloud-agent-setup/ComposerCloudAgentHint.tsx new file mode 100644 index 00000000000..ce8f76e66b6 --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/ComposerCloudAgentHint.tsx @@ -0,0 +1,59 @@ +import { useState } from 'react' +import { KeyRound } from 'lucide-react' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { Button } from '../ui/button' +import { isCloudAgentReady } from './cloud-agent-readiness' +import { CloudAgentSetupDialog } from './CloudAgentSetupDialog' +import { useCloudAgentSetup } from './use-cloud-agent-setup' + +export function ComposerCloudAgentHintView({ + onSetUp, + onLater +}: { + onSetUp: () => void + onLater: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( +
+ +

+ {t( + 'cloudAgentSetup.composerHint', + 'Claude Code and Codex need access in Orca Cloud. Add it now, or sign in once the workspace starts.' + )} +

+ + +
+ ) +} + +/** + * "Add an agent" the moment Orca Cloud is picked for the first time, before anything is created, so a + * warm sandbox that starts in seconds cannot outrun it. Quiet once agents are covered or it was handled. + */ +export function ComposerCloudAgentHint(): React.JSX.Element | null { + const done = useAppStore((s) => s.cloudAgentSetupDone) + const markDone = useAppStore((s) => s.markCloudAgentSetupDone) + const [open, setOpen] = useState(false) + const { model } = useCloudAgentSetup({ repo: null, enabled: !done }) + if (done || model.status === 'loading' || isCloudAgentReady(model.readiness)) { + return null + } + return ( + <> + setOpen(true)} onLater={markDone} /> + + + ) +} diff --git a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx new file mode 100644 index 00000000000..8e1610b7dd3 --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx @@ -0,0 +1,402 @@ +import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react' +import { CircleCheck, KeyRound } from 'lucide-react' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { Button } from '@/components/ui/button' +import { startVmBuildAgentSignIn } from '@/lib/agent-sign-in/vm-build-agent-sign-in' +import { + readHostAgentSignInReport, + subscribeHostAgentSignInReports +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { HOST_AGENT_SIGN_IN_AGENTS } from '../../../../shared/host-agent-sign-in-status' +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 { + CloudAgentSetupView, + cloudAgentReadinessSummary, + cloudAgentSavedSummary, + type CloudAgentSetupSaved, + type CloudAgentSetupViewProps +} from './CloudAgentSetupView' +import { useCloudAgentSetup } from './use-cloud-agent-setup' + +export type VmBuildCloudAgentStepModel = { + readiness: CloudAgentReadiness + canShare: boolean +} + +export type VmBuildCloudAgentStepMode = + | { kind: 'offer' } + | { kind: 'keys' } + | { kind: 'signIn' } + | { kind: 'saved'; saved: CloudAgentSetupSaved } + | { kind: 'skipped' } + +export type VmBuildCloudAgentStepActions = { + onSave: CloudAgentSetupViewProps['onSave'] + /** The step is done (saved, signing in, or skipped); remember that it ran. */ + onDone: () => void + onSignIn: () => void + onCancelSignIn: () => void + onLater: () => void +} + +function Row({ + icon, + title, + detail, + actions +}: { + icon: React.ReactNode + title: React.ReactNode + detail: string + actions?: React.ReactNode +}): React.JSX.Element { + return ( +
+ {icon} +
+ {title} + {detail} +
+ {actions ?
{actions}
: null} +
+ ) +} + +const OFFER: VmBuildCloudAgentStepMode = { kind: 'offer' } +const KEY_ICON = +const DONE_ICON = + +/** + * One checklist row, never a gate: "Agents ready" when access is already covered, otherwise an + * optional "Add an agent" with in-VM sign-in first and keys one click away. + */ +export function VmBuildCloudAgentStepView({ + model, + actions, + initialMode = OFFER +}: { + model: VmBuildCloudAgentStepModel + actions: VmBuildCloudAgentStepActions + /** Fixtures only. */ + initialMode?: VmBuildCloudAgentStepMode +}): React.JSX.Element { + const t = useTranslate() + const [mode, setMode] = useState(initialMode) + const ready = isCloudAgentReady(model.readiness) + const offerRef = useRef(null) + const signInRef = useRef(null) + const rowRef = useRef(null) + // Every swap unmounts the button that had focus; move focus to the new row (or its action) and + // announce the change, so keyboard and screen-reader users are not dropped on . + const [announcement, setAnnouncement] = useState('') + const go = ( + next: VmBuildCloudAgentStepMode, + focus: 'row' | 'offer' | 'signIn' | 'none', + say = '' + ): void => { + setMode(next) + setAnnouncement(say) + requestAnimationFrame(() => { + const target = + focus === 'row' + ? rowRef.current + : focus === 'offer' + ? offerRef.current + : focus === 'signIn' + ? signInRef.current + : null + target?.focus({ preventScroll: true }) + }) + } + const status = ( + + {announcement} + + ) + + if (mode.kind === 'skipped') { + return ( +
  • + {status} + +
  • + ) + } + + if (mode.kind === 'saved') { + return ( +
  • + {status} + +
  • + ) + } + + if (mode.kind === 'signIn') { + return ( +
  • + {status} + { + actions.onCancelSignIn() + go(OFFER, 'signIn', t('cloudAgentSetup.signInCancelled', 'Sign-in cancelled')) + }} + > + {t('cloudAgentSetup.skipSignIn', 'Don’t sign in')} + + } + /> +
  • + ) + } + + if (ready && mode.kind === 'offer') { + return ( +
  • + {status} + go({ kind: 'keys' }, 'none')} + > + {t('cloudAgentSetup.change', 'Change')} + + } + /> +
  • + ) + } + + const title = ( + <> + {t('cloudAgentSetup.title', 'Add an agent')} + + {' · '} + {t('vmBuildAgentSignIn.optional', 'optional')} + + + ) + const signIn = (): void => { + actions.onSignIn() + actions.onDone() + go( + { kind: 'signIn' }, + 'row', + t('cloudAgentSetup.signInQueued', 'Agent sign-in will open when the sandbox is ready') + ) + } + + return ( +
  • + {status} + + + + + + ) : null + } + /> + {mode.kind === 'keys' ? ( +
    + { + actions.onDone() + go({ kind: 'saved', saved }, 'row', cloudAgentSavedSummary(saved, t)) + }} + onCancel={() => go(OFFER, 'offer')} + onSignIn={signIn} + /> +
    + ) : null} +
  • + ) +} + +/** Starts the in-VM sign-in once the VM has reported which agents are signed out. */ +function useSignInWhenReady( + creationId: string, + environmentId: string | null, + requested: boolean +): boolean { + const report = useSyncExternalStore(subscribeHostAgentSignInReports, () => + environmentId ? readHostAgentSignInReport(environmentId) : null + ) + const hostLabel = useAppStore( + (s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name + ) + const started = useRef(false) + const states = report + ? HOST_AGENT_SIGN_IN_AGENTS.map( + (agent) => report.agents.find((entry) => entry.agent === agent)?.state ?? 'unknown' + ) + : null + // Not latched while any agent is still being checked, so a later report can start it. + const settled = states !== null && !states.includes('unknown') + + useEffect(() => { + if (!requested || started.current || !environmentId || !report || !settled) { + return + } + started.current = true + const signedOut = HOST_AGENT_SIGN_IN_AGENTS.filter( + (agent) => report.agents.find((entry) => entry.agent === agent)?.state === 'signedOut' + ) + if (signedOut.length > 0) { + void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, signedOut) + } + }, [requested, environmentId, report, settled, creationId, hostLabel]) + + // Once the VM has answered, the checklist's own sign-in row takes over. + return requested && settled +} + +/** + * "Add an agent" before the first Orca Cloud workspace. Runs beside provisioning, never in front of it, + * and only once: when agents are already covered it is a one-line confirmation instead. + */ +export function VmBuildCloudAgentStep({ + creationId, + entry +}: { + creationId: string + entry: PendingWorktreeCreation +}): React.JSX.Element | null { + const done = useAppStore((s) => s.cloudAgentSetupDone) + const markDone = useAppStore((s) => s.markCloudAgentSetupDone) + // Decided once per build, so finishing the step mid-build does not yank its confirmation away. + const [eligible] = useState(() => !done) + const [signInRequested, setSignInRequested] = useState(false) + const isCloud = entry.request.ephemeralVmRecipe?.recipeId === ORCA_CLOUD_RECIPE_ID + const repoKey = useAppStore((s) => { + const repo = s.repos.find((candidate) => candidate.id === entry.request.repoId) + return repo ? cloudSecretRepoKey(repo) : null + }) + const environmentId = entry.vmEnvironmentId ?? null + const { model, save } = useCloudAgentSetup({ + repo: repoKey, + runtimeEnvironmentId: environmentId, + enabled: isCloud && eligible + }) + const handedToSignInRow = useSignInWhenReady(creationId, environmentId, signInRequested) + const alreadyReady = model.status === 'ready' && isCloudAgentReady(model.readiness) + + useEffect(() => { + if (alreadyReady) { + markDone() + } + }, [alreadyReady, markDone]) + + if ( + !isCloud || + !eligible || + handedToSignInRow || + model.status === 'loading' || + entry.status === 'error' + ) { + return null + } + return ( + setSignInRequested(true), + onCancelSignIn: () => setSignInRequested(false), + onLater: markDone + }} + /> + ) +} 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 new file mode 100644 index 00000000000..9c4d977ae24 --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { deriveCloudAgentReadiness } 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('ignores host-scoped desktop keys and 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' } + ] + ) + ).toEqual({ claude: null, codex: null }) + }) +}) 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 new file mode 100644 index 00000000000..978222035f5 --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-readiness.ts @@ -0,0 +1,49 @@ +import type { AgentApiKeySummary } from '../../../../shared/agent-api-keys/agent-api-key-catalog' +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 CloudAgentReadiness = Record + +/** Variables that alone let each CLI authenticate (the Worker derives the rest from a gateway key). */ +const CREDENTIAL_NAMES: Record = { + claude: [ + 'ANTHROPIC_API_KEY', + 'ANTHROPIC_AUTH_TOKEN', + 'AI_GATEWAY_API_KEY', + 'AWS_BEARER_TOKEN_BEDROCK', + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX' + ], + codex: ['OPENAI_API_KEY', 'AI_GATEWAY_API_KEY'] +} + +/** + * 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. + */ +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')) { + return 'team' + } + return supplied.length > 0 ? 'cloud-secret' : null + } + return { claude: sourceFor('claude'), codex: sourceFor('codex') } +} + +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/cloud-agent-setup-choices.ts b/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-choices.ts new file mode 100644 index 00000000000..6dae6c529e1 --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-choices.ts @@ -0,0 +1,67 @@ +import { cloudSecretValueError } from '../../../../shared/cloud-secrets/cloud-secret-rules' +import type { CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire' + +export type CloudAgentSetupOption = 'sign-in' | 'api-key' | 'gateway' | 'custom' +export type CloudAgentSetupScope = 'personal' | 'org' +export type CloudAgentSetupFailure = { error: CloudSecretsErrorCode; field?: string } + +/** Each preset is just secrets: the control plane derives base URLs and tokens for the VM. */ +export type CloudAgentSetupChoice = + | { kind: 'api-key'; provider: 'anthropic' | 'openai'; key: string } + | { kind: 'gateway'; key: string; model: string; codexModel: string } + | { kind: 'custom'; baseUrl: string; token: string; model: string } + +export type CloudAgentSetupWrite = { + set: Record + /** Which field each variable came from, so a server refusal lands on the right input. */ + field: Record +} + +export function cloudAgentSetupWrite(choice: CloudAgentSetupChoice): CloudAgentSetupWrite { + switch (choice.kind) { + case 'api-key': { + const name = choice.provider === 'anthropic' ? 'ANTHROPIC_API_KEY' : 'OPENAI_API_KEY' + return { set: { [name]: choice.key.trim() }, field: { [name]: 'key' } } + } + case 'gateway': { + const model = choice.model.trim() + const codexModel = choice.codexModel.trim() + return { + set: { + AI_GATEWAY_API_KEY: choice.key.trim(), + ...(model ? { ANTHROPIC_MODEL: model } : {}), + ...(codexModel ? { OPENAI_MODEL: codexModel } : {}) + }, + field: { AI_GATEWAY_API_KEY: 'key', ANTHROPIC_MODEL: 'model', OPENAI_MODEL: 'codexModel' } + } + } + case 'custom': { + const model = choice.model.trim() + return { + set: { + ANTHROPIC_BASE_URL: choice.baseUrl.trim(), + ANTHROPIC_AUTH_TOKEN: choice.token.trim(), + ...(model ? { ANTHROPIC_MODEL: model } : {}) + }, + field: { + ANTHROPIC_BASE_URL: 'baseUrl', + ANTHROPIC_AUTH_TOKEN: 'token', + ANTHROPIC_MODEL: 'model' + } + } + } + } +} + +/** The first local problem, with the field it belongs to, before anything is sent. */ +export function cloudAgentSetupProblem( + write: CloudAgentSetupWrite +): { field: string; error: CloudSecretsErrorCode } | null { + for (const [name, value] of Object.entries(write.set)) { + const error = cloudSecretValueError(name, value) + if (error) { + return { field: write.field[name] ?? 'key', error } + } + } + return 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 new file mode 100644 index 00000000000..34d4d0a7bac --- /dev/null +++ b/src/renderer/src/components/cloud-agent-setup/use-cloud-agent-setup.ts @@ -0,0 +1,103 @@ +import { useCallback, useEffect, useState } from 'react' +import { + cloudSecretsErrorCode, + type CloudSecretsErrorCode +} from '../../../../shared/cloud-secrets/cloud-secrets-wire' +import { deriveCloudAgentReadiness, type CloudAgentReadiness } from './cloud-agent-readiness' +import { + cloudAgentSetupProblem, + cloudAgentSetupWrite, + type CloudAgentSetupChoice +} from './cloud-agent-setup-choices' +import type { CloudAgentSetupFailure, CloudAgentSetupScope } from './CloudAgentSetupView' + +// Codes, not copy: the view turns them into words. +const UNKNOWN: CloudSecretsErrorCode = 'unknown' +const NOT_CONFIGURED: CloudSecretsErrorCode = 'not_configured' + +export type CloudAgentSetupModel = + | { status: 'loading' } + | { status: 'ready'; readiness: CloudAgentReadiness; canShare: boolean } + +/** + * What a new cloud workspace already has for agents (desktop keys, team and cloud secrets) and how to + * add more. A failed read counts as "nothing yet": the step then offers every option instead of hiding. + */ +export function useCloudAgentSetup(args: { + repo: string | null + runtimeEnvironmentId?: string | null + enabled?: boolean +}): { + model: CloudAgentSetupModel + save: ( + choice: CloudAgentSetupChoice, + scope: CloudAgentSetupScope + ) => Promise +} { + const { repo, runtimeEnvironmentId = null, enabled = true } = args + const [model, setModel] = useState({ status: 'loading' }) + + useEffect(() => { + if (!enabled) { + return + } + let cancelled = false + const keys = window.api.agentApiKeys?.list().catch(() => null) ?? Promise.resolve(null) + const effective = + window.api.cloudSecrets?.effective(repo ? { repo } : {}).catch(() => null) ?? + Promise.resolve(null) + void Promise.all([keys, effective]).then(([desktop, cloud]) => { + if (cancelled) { + return + } + const view = cloud?.ok ? cloud.value : null + setModel({ + status: 'ready', + readiness: deriveCloudAgentReadiness(desktop?.keys ?? [], view?.secrets ?? []), + canShare: view?.caller.canWrite.org === true + }) + }) + return () => { + cancelled = true + } + }, [repo, enabled]) + + const save = useCallback( + async ( + choice: CloudAgentSetupChoice, + scope: CloudAgentSetupScope + ): Promise => { + const api = window.api.cloudSecrets + if (!api) { + return { error: NOT_CONFIGURED } + } + const write = cloudAgentSetupWrite(choice) + const problem = cloudAgentSetupProblem(write) + if (problem) { + return problem + } + const result = await api.batch({ target: { scope }, set: write.set }).catch(() => null) + if (!result) { + return { error: UNKNOWN } + } + if (!result.ok) { + return { error: result.error } + } + const refused = result.value.errors[0] + if (refused) { + return { + error: cloudSecretsErrorCode(refused.reason), + field: write.field[refused.name] + } + } + if (runtimeEnvironmentId) { + // The control plane pushes writes to running sandboxes itself; this only shortens the wait. + void api.refreshEnv({ runtimeEnvironmentId }).catch(() => undefined) + } + return null + }, + [runtimeEnvironmentId] + ) + + return { model, save } +} diff --git a/src/renderer/src/components/cloud-environment/BuildHistoryList.tsx b/src/renderer/src/components/cloud-environment/BuildHistoryList.tsx new file mode 100644 index 00000000000..d924a33c408 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/BuildHistoryList.tsx @@ -0,0 +1,237 @@ +import { Loader2, RotateCcw, Square } from 'lucide-react' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { formatUiRelativeTime } from '@/i18n/relative-time-format' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import { formatStepDuration } from './build-steps' +import { FOCUS_RING } from '../orca-cloud/cloud-focus' +import { BuildStatusIcon, stepStatusFromBuild, useNow } from './BuildStatusIcon' +import { + buildStatusLabel, + isBuildInProgress, + repoDisplayName, + shortSha, + stepLabel +} from './cloud-environment-copy' +import type { EnvironmentBuildView } from './cloud-environment-types' + +const identityActor = (actor: string): string => actor + +export function BuildHistoryList({ + builds, + selectedBuildId, + canAdmin, + busyBuildId, + now: fixedNow, + actorName = identityActor, + onSelect, + onCancel, + onActivate +}: { + builds: readonly EnvironmentBuildView[] + selectedBuildId: string | null + canAdmin: boolean + /** A cancel/activate request is in flight for this build. */ + busyBuildId: string | null + /** Fixed clock (fixtures); otherwise the list ticks itself while a build runs. */ + now?: number + actorName?: (actor: string) => string + onSelect: (build: EnvironmentBuildView) => void + onCancel: (build: EnvironmentBuildView) => void + onActivate: (build: EnvironmentBuildView) => void +}): React.JSX.Element { + const t = useTranslate() + const intlLocale = useIntlLocale() + // The 1 s tick lives here, not in the panel, so the form and log don't re-render with it. + const anyInProgress = builds.some((build) => isBuildInProgress(build.status)) + const tickingNow = useNow(anyInProgress && fixedNow === undefined) + const now = fixedNow ?? tickingNow + if (builds.length === 0) { + return ( +

    + {t('cloudEnvironment.history.empty', 'No builds yet.')} +

    + ) + } + const multiRepo = builds.some((build) => build.repos.length > 1) + return ( +
      + {builds.map((build) => { + const selected = build.id === selectedBuildId + const inProgress = isBuildInProgress(build.status) + const busy = busyBuildId === build.id + const duration = + build.durationMs ?? (inProgress ? Math.max(0, now - build.createdAt) : null) + return ( +
    • + {selected ? ( + + ) : null} + + {canAdmin ? ( +
      + {inProgress ? ( + + + + ) : build.status === 'succeeded' && !build.active ? ( + + ) : null} +
      + ) : null} +
    • + ) + })} +
    + ) +} + +function ActivateButton({ + build, + busy, + onActivate +}: { + build: EnvironmentBuildView + busy: boolean + onActivate: (build: EnvironmentBuildView) => void +}): React.JSX.Element { + const t = useTranslate() + const button = ( + // Quiet until the row is hovered or the button focused; the wrapper owns the fade, not Button. + + + + ) + return ( + + {button} + + ) +} + +/** A disabled control that says why: the span keeps the tooltip reachable by pointer and keyboard. */ +function DisabledReason({ + reason, + children +}: { + reason: string | null + children: React.ReactElement +}): React.JSX.Element { + if (!reason) { + return children + } + return ( + + + + {children} + + + {reason} + + ) +} diff --git a/src/renderer/src/components/cloud-environment/BuildLogRows.tsx b/src/renderer/src/components/cloud-environment/BuildLogRows.tsx new file mode 100644 index 00000000000..1042856ccbc --- /dev/null +++ b/src/renderer/src/components/cloud-environment/BuildLogRows.tsx @@ -0,0 +1,353 @@ +import { memo } from 'react' +import type { ITheme } from '@xterm/xterm' +import { AlertTriangle, ChevronRight } from 'lucide-react' +import { getBuiltinTheme } from '@/lib/terminal-theme' +import { cn } from '@/lib/utils' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { getIntlLocale } from '@/i18n/i18n' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { FOCUS_RING } from '../orca-cloud/cloud-focus' +import { + DEFAULT_TERMINAL_THEME_DARK, + DEFAULT_TERMINAL_THEME_LIGHT +} from '../../../../shared/terminal-themes/terminal-theme-selection' +import { parseAnsiSegments, type AnsiColor } from '../editor/notebook/outputs/ipynb-ansi' +import type { LogLine } from './build-log-model' +import { formatLineTimestamp, formatStepDuration, type BuildStepView } from './build-steps' +import { BuildStatusIcon } from './BuildStatusIcon' +import type { BuildLogStreamState } from './BuildLogViewer' +import { buildErrorCopy, failedBuildSummary, stepLabel } from './cloud-environment-copy' +import type { EnvironmentBuildStep, EnvironmentBuildView } from './cloud-environment-types' + +/** Lines longer than this render truncated (the copy keeps them whole); minified bundles exist. */ +const MAX_RENDERED_LINE_CHARS = 2000 + +const ANSI_PALETTE_KEYS = [ + 'black', + 'red', + 'green', + 'yellow', + 'blue', + 'magenta', + 'cyan', + 'white', + 'brightBlack', + 'brightRed', + 'brightGreen', + 'brightYellow', + 'brightBlue', + 'brightMagenta', + 'brightCyan', + 'brightWhite' +] as const satisfies readonly (keyof ITheme)[] + +const ANSI_PALETTES = { + dark: ANSI_PALETTE_KEYS.map((key) => getBuiltinTheme(DEFAULT_TERMINAL_THEME_DARK)?.[key]), + light: ANSI_PALETTE_KEYS.map((key) => getBuiltinTheme(DEFAULT_TERMINAL_THEME_LIGHT)?.[key]) +} + +function AnsiLine({ text, dark }: { text: string; dark: boolean }): React.JSX.Element { + const palette = ANSI_PALETTES[dark ? 'dark' : 'light'] + const resolve = (color: AnsiColor | undefined): string | undefined => + typeof color === 'number' ? palette[color] : color + const clipped = + text.length > MAX_RENDERED_LINE_CHARS ? `${text.slice(0, MAX_RENDERED_LINE_CHARS)}…` : text + return ( + <> + {parseAnsiSegments(clipped).map((segment, index) => + segment.fg === undefined && segment.bg === undefined && !segment.bold ? ( + {segment.text} + ) : ( + + {segment.text} + + ) + )} + + ) +} + +export const LogLineRow = memo(function LogLineRow({ + line, + number, + origin, + showTimestamps, + dark +}: { + line: LogLine + number: number + origin: number + showTimestamps: boolean + dark: boolean +}): React.JSX.Element { + if (line.kind === 'orca-error') { + return ( +
    +
    + + {line.plain} +
    +
    + ) + } + return ( +
    + + {number} + + {showTimestamps ? ( + + {formatLineTimestamp(line.at, origin)} + + ) : null} + + + +
    + ) +}) + +export function StepHeaderRow({ + step, + expanded, + lineCount, + paused = false, + onToggle +}: { + step: BuildStepView + expanded: boolean + lineCount: number + /** The stream is down: show a running step frozen, not spinning. */ + paused?: boolean + onToggle: (step: EnvironmentBuildStep) => void +}): React.JSX.Element { + const t = useTranslate() + const muted = step.status === 'pending' || step.status === 'skipped' + return ( + + ) +} + +function stepStatusWord( + status: BuildStepView['status'], + t: ReturnType +): string { + switch (status) { + case 'running': + return t('cloudEnvironment.stepStatus.running', 'running') + case 'succeeded': + return t('cloudEnvironment.stepStatus.succeeded', 'done') + case 'failed': + return t('cloudEnvironment.stepStatus.failed', 'failed') + case 'canceled': + return t('cloudEnvironment.stepStatus.canceled', 'canceled') + case 'skipped': + return t('cloudEnvironment.stepStatus.skipped', 'skipped') + case 'pending': + return t('cloudEnvironment.stepStatus.pending', 'waiting') + } +} + +export function EmptyStepRow({ + step, + build, + streamState +}: { + step: EnvironmentBuildStep + build: EnvironmentBuildView + streamState: BuildLogStreamState +}): React.JSX.Element { + const t = useTranslate() + let copy: string + if (streamState === 'connecting') { + copy = t('cloudEnvironment.log.loading', 'Loading log…') + } else if (step === 'boot') { + copy = build.startedAt + ? t('cloudEnvironment.log.bootDone', 'Sandbox started.') + : t('cloudEnvironment.log.booting', 'Starting a fresh sandbox…') + } else if (step === 'snapshot') { + copy = build.finishedAt + ? t('cloudEnvironment.log.snapshotDone', 'Snapshot saved.') + : t('cloudEnvironment.log.snapshotting', 'Saving the snapshot…') + } else { + copy = t('cloudEnvironment.log.noOutput', 'No output.') + } + return ( +
    + {copy} +
    + ) +} + +/** "Build #7 failed — workspaces still use #6", the failed step in words, and Orca's own diagnosis. */ +export function FailureSummary({ + build, + activeBuildNumber, + onShowError +}: { + build: EnvironmentBuildView + activeBuildNumber: number | null + /** Scrolls to Orca's own error note in the log; null when the log has none. */ + onShowError: (() => void) | null +}): React.JSX.Element { + const t = useTranslate() + const summary = failedBuildSummary(build.number, build.failedStep, activeBuildNumber, t) + // Without an Orca note in the log, the plain-words reason is the only explanation there is. + const reason = onShowError ? null : buildErrorCopy(build.error, t) + return ( + + {summary.consequence} {reason} + + ) : ( + summary.consequence + ) + } + action={ + onShowError ? ( + + ) : undefined + } + /> + ) +} + +/** Stream health and truncation, below the log. Quiet unless something needs saying. */ +export function LogFooter({ + streamState, + streamError, + truncated, + onRetry +}: { + streamState: BuildLogStreamState + /** Main's plain-words reason when it stopped the watch. */ + streamError?: string | null + truncated: boolean + onRetry?: () => void +}): React.JSX.Element | null { + const t = useTranslate() + if (streamState === 'reconnecting' || streamState === 'error') { + return ( + + ) + } + if (!truncated) { + return null + } + return ( +

    + {t('cloudEnvironment.log.truncatedShort', 'Log truncated at its size limit.')} +

    + ) +} + +/** What screen readers hear as the build moves: one sentence per step change, never per line. */ +export function stepAnnouncement( + build: EnvironmentBuildView, + steps: readonly BuildStepView[], + activeBuildNumber: number | null, + t: Translate +): string { + if (build.status === 'failed') { + const summary = failedBuildSummary(build.number, build.failedStep, activeBuildNumber, t) + return t('cloudEnvironment.announce.failed', '{{headline}} {{consequence}}', summary) + } + if (build.status === 'succeeded') { + return t('cloudEnvironment.announce.succeeded', 'Build #{{number}} succeeded.', { + number: String(build.number) + }) + } + if (build.status === 'canceled') { + return t('cloudEnvironment.announce.canceled', 'Build #{{number}} was canceled.', { + number: String(build.number) + }) + } + const running = steps.find((step) => step.status === 'running') + return running + ? t('cloudEnvironment.announce.step', 'Build #{{number}}: {{step}}…', { + number: String(build.number), + step: stepLabel(running.id, t) + }) + : '' +} diff --git a/src/renderer/src/components/cloud-environment/BuildLogViewer.tsx b/src/renderer/src/components/cloud-environment/BuildLogViewer.tsx new file mode 100644 index 00000000000..85d6d28ec75 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/BuildLogViewer.tsx @@ -0,0 +1,440 @@ +import { + memo, + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, + useSyncExternalStore +} from 'react' +import { ArrowDown, Check, Copy } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' +import { useTranslate } from '@/i18n/use-translate' +import type { BuildLogBuffer } from './build-log-model' +import { + defaultExpanded, + failureScrollRow, + lastRowBoundary, + rowAtIndex, + type Row, + type Segment +} from './log-row-layout' +import { HEADER_ROW_PX, LINE_ROW_PX, useLogVirtualizer } from './use-log-virtualizer' +import { deriveBuildSteps, focusStep, formatStepDuration } from './build-steps' +import { + EmptyStepRow, + FailureSummary, + LogFooter, + LogLineRow, + stepAnnouncement, + StepHeaderRow +} from './BuildLogRows' +import { FOCUS_RING } from '../orca-cloud/cloud-focus' +import { cn } from '@/lib/utils' +import { BuildStatusIcon, stepStatusFromBuild, useNow } from './BuildStatusIcon' +import { buildStatusLabel, isBuildInProgress } from './cloud-environment-copy' +import type { EnvironmentBuildStep, EnvironmentBuildView } from './cloud-environment-types' +import { autoscrollReducer, initialAutoscrollState } from './log-autoscroll' + +export type BuildLogStreamState = 'connecting' | 'live' | 'reconnecting' | 'ended' | 'error' + +/** A whole number of lines; the viewport then stops at the last whole row below it. */ +const MAX_LOG_HEIGHT_PX = 23 * LINE_ROW_PX + +/** Memoized: the panel re-renders on polls and status changes that don't touch this build. */ +export const BuildLogViewer = memo(function BuildLogViewer({ + build, + buffer, + activeBuildNumber, + streamState, + streamError, + onRetryStream, + height = MAX_LOG_HEIGHT_PX, + now: fixedNow +}: { + build: EnvironmentBuildView + buffer: BuildLogBuffer + activeBuildNumber: number | null + streamState: BuildLogStreamState + streamError?: string | null + onRetryStream?: () => void + height?: number + /** Freeze the clock (fixtures). */ + now?: number +}): React.JSX.Element { + const t = useTranslate() + const dark = useDocumentDarkTheme() + const running = isBuildInProgress(build.status) + // While the stream is down the last-known state is stale: freeze the clock instead of guessing. + const disconnected = streamState === 'reconnecting' || streamState === 'error' + const tickingNow = useNow(running && !disconnected && fixedNow === undefined) + const now = fixedNow ?? tickingNow + const version = useSyncExternalStore(buffer.subscribe, buffer.getVersion) + const scrollRef = useRef(null) + // Follow the tail of a live build; a finished one opens at the top (or at its failure). + const [scroll, dispatch] = useReducer(autoscrollReducer, running, (live) => ({ + ...initialAutoscrollState, + following: live + })) + const [toggled, setToggled] = useState>>({}) + const [copied, setCopied] = useState(false) + const pending = useRef<{ copiedTimer: number | null; showErrorFrame: number | null }>({ + copiedTimer: null, + showErrorFrame: null + }) + useEffect(() => { + const handles = pending.current + return () => { + if (handles.copiedTimer !== null) { + window.clearTimeout(handles.copiedTimer) + } + if (handles.showErrorFrame !== null) { + cancelAnimationFrame(handles.showErrorFrame) + } + } + }, []) + + // `version` is the external-store tick: markers and line counts are read off the mutable buffer. + const steps = useMemo( + () => deriveBuildSteps(build, buffer.markers, now), + // eslint-disable-next-line react-hooks/exhaustive-deps -- buffer is mutable; version tracks it. + [build, buffer, version, now] + ) + const focus = focusStep(steps) + const lineTotal = buffer.lines.length + const showTimestamps = useMemo( + () => buffer.lines.length > 0 && buffer.lines[0].at !== null, + // eslint-disable-next-line react-hooks/exhaustive-deps -- buffer is mutable; version tracks it. + [buffer, version] + ) + + const segments = useMemo((): Segment[] => { + let row = 0 + return steps.map((step) => { + const range = buffer.stepRange(step.id) + const lineCount = range.end - range.start + const expanded = toggled[step.id] ?? defaultExpanded(step, focus, build) + const bodyRows = expanded ? Math.max(lineCount, step.status === 'pending' ? 0 : 1) : 0 + const segment = { + step, + firstRow: row, + rowCount: 1 + bodyRows, + lineStart: range.start, + lineCount, + expanded + } + row += segment.rowCount + return segment + }) + // eslint-disable-next-line react-hooks/exhaustive-deps -- buffer is mutable; version tracks it. + }, [steps, toggled, focus, build, buffer, version]) + + const rowCount = segments.reduce((sum, segment) => sum + segment.rowCount, 0) + + const rowAt = useCallback( + (index: number): Row => rowAtIndex(segments, buffer, index), + [segments, buffer] + ) + + const virtualizer = useLogVirtualizer(segments, buffer, rowCount, scrollRef) + + // Count lines that arrived while the user was reading history (feeds the pill). + const seenLines = useRef(lineTotal) + useLayoutEffect(() => { + const delta = lineTotal - seenLines.current + seenLines.current = lineTotal + if (delta > 0) { + dispatch({ type: 'append', count: delta }) + } else if (delta < 0) { + dispatch({ type: 'reset' }) + } + }, [lineTotal]) + + // Follow the tail: jump (not smooth-scroll) so a fast log never lags behind its own output. + useLayoutEffect(() => { + if (scroll.following && rowCount > 0) { + virtualizer.scrollToIndex(rowCount - 1, { align: 'end' }) + } + }, [scroll.following, rowCount, version, virtualizer]) + + // Hug short logs instead of leaving an empty slab; cap long ones on a row boundary. + const totalSize = virtualizer.getTotalSize() + const overflowing = totalSize > height + // Overflowing logs stop at the last whole row that fits from the top (rows are whole lines, but + // headers are two), so the resting view never shows half a row. + const viewportHeight = overflowing + ? lastRowBoundary(virtualizer.measurementsCache, height - (height % LINE_ROW_PX)) + : totalSize + + // A failed build opens on its failure, once its log is complete ('ended'): earlier, the log is + // still replaying and the error line may not exist yet, so the scroll would land short. + const failedStepId = build.status === 'failed' ? focus : null + const scrolledToFailure = useRef(null) + useLayoutEffect(() => { + if (!failedStepId || scrolledToFailure.current === build.id || streamState !== 'ended') { + return + } + scrolledToFailure.current = build.id + const row = failureScrollRow(segments, buffer, failedStepId, { + height: viewportHeight, + totalSize: virtualizer.getTotalSize(), + headerPx: HEADER_ROW_PX, + linePx: LINE_ROW_PX + }) + if (row !== null) { + dispatch({ type: 'release' }) + virtualizer.scrollToIndex(row, { align: 'start' }) + } + }, [failedStepId, build.id, segments, buffer, virtualizer, streamState, viewportHeight]) + + const onScroll = (): void => { + const element = scrollRef.current + if (element) { + dispatch({ + type: 'scroll', + scrollTop: element.scrollTop, + scrollHeight: element.scrollHeight, + clientHeight: element.clientHeight + }) + } + } + + const jumpToLatest = (): void => { + dispatch({ type: 'jump' }) + const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches + virtualizer.scrollToIndex(rowCount - 1, { + align: 'end', + behavior: reduceMotion ? 'auto' : 'smooth' + }) + } + + const onScrollerKeyDown = (event: React.KeyboardEvent): void => { + if (event.target !== event.currentTarget || rowCount === 0) { + return + } + if (event.key === 'Home') { + event.preventDefault() + dispatch({ type: 'release' }) + virtualizer.scrollToIndex(0, { align: 'start' }) + } else if (event.key === 'End') { + event.preventDefault() + dispatch({ type: 'jump' }) + virtualizer.scrollToIndex(rowCount - 1, { align: 'end' }) + } + } + + const showError = (): void => { + const index = buffer.orcaErrorLines.at(-1) + const segment = + index === undefined + ? undefined + : segments.find( + (entry) => index >= entry.lineStart && index < entry.lineStart + entry.lineCount + ) + if (index === undefined || !segment) { + return + } + dispatch({ type: 'release' }) + if (!segment.expanded) { + setToggled((previous) => ({ ...previous, [segment.step.id]: true })) + } + // After an expand the rows move; scroll on the next frame. + pending.current.showErrorFrame = requestAnimationFrame(() => { + pending.current.showErrorFrame = null + virtualizer.scrollToIndex(segment.firstRow + 1 + (index - segment.lineStart), { + align: 'start' + }) + }) + } + + const toggle = useCallback( + (stepId: EnvironmentBuildStep) => { + setToggled((previous) => { + const step = steps.find((entry) => entry.id === stepId) + const current = previous[stepId] ?? (step ? defaultExpanded(step, focus, build) : false) + return { ...previous, [stepId]: !current } + }) + }, + [steps, focus, build] + ) + + const copyLogs = (): void => { + // Machine-readable codes live here, not in the UI copy (they help support and agents). + const header = [ + `build=${build.id} number=${build.number} status=${build.status}`, + build.failedStep ? `failedStep=${build.failedStep}` : null, + build.error ? `error=${build.error}` : null, + streamError ? `stream=${streamError}` : null + ] + .filter(Boolean) + .join(' ') + void window.api.ui.writeClipboardText(`${header}\n${buffer.text()}`).then(() => { + setCopied(true) + if (pending.current.copiedTimer !== null) { + window.clearTimeout(pending.current.copiedTimer) + } + pending.current.copiedTimer = window.setTimeout(() => { + pending.current.copiedTimer = null + setCopied(false) + }, 1500) + }) + } + + const totalMs = build.durationMs ?? (running ? Math.max(0, now - build.createdAt) : null) + const statusWord = buildStatusLabel(build.status, t) + const failure = build.status === 'failed' + const items = virtualizer.getVirtualItems() + + return ( +
    +
    + +
    +

    + {t('cloudEnvironment.log.title', 'Build #{{number}}', { + number: String(build.number) + })} + + {' · '} + {disconnected && running + ? streamState === 'reconnecting' + ? t('cloudEnvironment.log.reconnectingShort', 'Reconnecting…') + : t('cloudEnvironment.log.disconnectedShort', '{{status}} · log disconnected', { + status: statusWord + }) + : statusWord} + +

    +
    + + {formatStepDuration(totalMs)} + + +
    + +

    + {stepAnnouncement(build, steps, activeBuildNumber, t)} +

    + + {failure ? ( + 0 ? showError : null} + /> + ) : null} + +
    +
    { + // Keyboard focus on a step header: stop following, or the next chunk scrolls it away. + if (event.target !== event.currentTarget) { + dispatch({ type: 'release' }) + } + }} + className={cn( + 'overflow-y-auto overscroll-contain bg-muted/30 font-mono text-xs text-foreground scrollbar-editor dark:bg-black/25', + FOCUS_RING, + 'focus-visible:ring-inset' + )} + style={{ height: viewportHeight }} + > +
    + {items.map((item) => { + const row = rowAt(item.index) + return ( +
    + {row.kind === 'header' ? ( + entry.step.id === row.step.id)?.expanded ?? false + } + paused={disconnected && running} + onToggle={toggle} + /> + ) : row.kind === 'line' ? ( + + ) : ( + + )} +
    + ) + })} +
    +
    + {running && !scroll.following && scroll.awayFromBottom && rowCount > 0 ? ( +
    + +
    + ) : null} +
    + + +
    + ) +}) diff --git a/src/renderer/src/components/cloud-environment/BuildStatusIcon.tsx b/src/renderer/src/components/cloud-environment/BuildStatusIcon.tsx new file mode 100644 index 00000000000..cf7aea103b4 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/BuildStatusIcon.tsx @@ -0,0 +1,76 @@ +import { useEffect, useState } from 'react' +import { + Ban, + CircleCheck, + CircleDashed, + CircleDot, + CircleX, + Loader2, + MinusCircle, + Pause +} from 'lucide-react' +import { cn } from '@/lib/utils' +import type { StepStatus } from './build-steps' +import type { EnvironmentBuildStatus } from './cloud-environment-types' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' + +export function stepStatusFromBuild(status: EnvironmentBuildStatus): StepStatus { + if (status === 'starting' || status === 'running' || status === 'snapshotting') { + return 'running' + } + return status +} + +/** Decorative: callers always put the status in words next to it (or in an sr-only label). */ +export function BuildStatusIcon({ + status, + className +}: { + /** `paused`: the build may still run, but the live stream is down (frozen, not spinning). */ + status: StepStatus | 'paused' + className?: string +}): React.JSX.Element { + const base = cn('size-4 shrink-0', className) + switch (status) { + case 'running': + // Reduced motion gets a static dot: a frozen spinner reads as a hang. + return ( + <> + + + + ) + case 'paused': + return + case 'succeeded': + return + case 'failed': + return + case 'canceled': + return + case 'skipped': + return + case 'pending': + return + } +} + +/** Wall clock that ticks only while `enabled` (a running build); otherwise frozen at mount. */ +export function useNow(enabled: boolean, intervalMs = 1000): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!enabled) { + return + } + setNow(Date.now()) + // An elapsed-time clock: hidden windows skip ticks and catch up when shown. + return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs }) + }, [enabled, intervalMs]) + return now +} diff --git a/src/renderer/src/components/cloud-environment/CloudEnvironment.fixture.tsx b/src/renderer/src/components/cloud-environment/CloudEnvironment.fixture.tsx new file mode 100644 index 00000000000..fdc385df394 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/CloudEnvironment.fixture.tsx @@ -0,0 +1,357 @@ +import { InlineError } from '@/components/ui/inline-error' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { BuildHistoryList } from './BuildHistoryList' +import { BuildLogViewer } from './BuildLogViewer' +import { + buildingLog, + failedLog, + FIXTURE_NOW, + longLog, + sampleBuild, + sampleEnvironment, + sampleHistory, + sampleStaleness, + succeededLog +} from './cloud-environment-fixture-data' +import { stalenessBannerCopy } from './cloud-environment-copy' +import { + CloudEnvironmentEmptyState, + CloudEnvironmentSkeleton, + CloudEnvironmentPanel +} from './CloudEnvironmentPanel' +import { draftFromEnvironment, emptyDraft } from './environment-draft' +import { EnvironmentForm, EnvironmentSummary } from './EnvironmentForm' +import type { LocalRepoSuggestion } from './EnvironmentFormFields' +import { StalenessBanner } from './StalenessBanner' + +const noop = (): void => {} + +const suggestions: LocalRepoSuggestion[] = [ + { repoId: 'r1', slug: 'acme/web', path: '/src/web', displayName: 'web' }, + { repoId: 'r2', slug: 'acme/api', path: '/src/api', displayName: 'api' }, + { + repoId: 'r3', + slug: 'acme/design-system', + path: '/src/ds', + displayName: 'design-system' + } +] + +const formHandlers = { + saving: false, + error: null, + conflict: false, + suggestions, + importProjects: suggestions, + onReadImports: async () => ({ + ok: true as const, + data: { + envVarNames: ['NPM_TOKEN', 'STRIPE_KEY'], + installScript: 'pnpm install', + sources: ['Conductor'] + } + }), + onSave: noop +} + +export const emptyState = defineFixture({ + width: 640, + render: () => +}) + +export const emptyStateMember = defineFixture({ + width: 640, + render: () => +}) + +export const loading = defineFixture({ + width: 680, + render: () => +}) + +export const networkError = defineFixture({ + width: 640, + render: () => ( + + ) +}) + +export const createForm = defineFixture({ + width: 680, + render: () => ( + + ) +}) + +export const formAdminUnsaved = defineFixture({ + width: 680, + render: () => { + const base = draftFromEnvironment(sampleEnvironment) + return ( + + ) + } +}) + +export const formAdminConflict = defineFixture({ + width: 680, + render: () => { + const base = draftFromEnvironment(sampleEnvironment) + return ( + + ) + } +}) + +export const formMemberReadOnly = defineFixture({ + width: 680, + render: () => +}) + +export const buildHistory = defineFixture({ + width: 680, + render: () => ( + + ) +}) + +export const buildHistoryMember = defineFixture({ + width: 680, + render: () => ( + + ) +}) + +const runningBuild = sampleHistory[0] +export const logBuilding = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +const okBuild = sampleBuild({ + number: 6, + active: true, + createdAt: FIXTURE_NOW - 26 * 60_000 +}) +export const logSucceeded = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +const failedBuild = sampleHistory[1] +export const logFailed = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +const longBuild = sampleBuild({ + number: 9, + createdAt: FIXTURE_NOW - 6 * 60_000, + snapshotStartedAt: FIXTURE_NOW - 6 * 60_000 + 240_000, + finishedAt: FIXTURE_NOW - 6 * 60_000 + 270_000, + durationMs: 270_000, + logBytes: 2_000_000, + logTruncated: true +}) +export const logLong = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const logReconnecting = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const logStreamError = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const stalenessBanners = defineFixture({ + width: 680, + render: () => ( +
    + {[sampleStaleness.deps, sampleStaleness.config, sampleStaleness.branch].map((staleness) => { + const copy = stalenessBannerCopy(staleness, 6) + return copy ? ( + + ) : null + })} +
    + ) +}) + +export const panelOverviewFailed = defineFixture({ + width: 760, + render: () => { + const builds = sampleHistory.slice(1) + return ( + + ) + } +}) + +export const panelMember = defineFixture({ + width: 760, + render: () => { + const builds = sampleHistory.slice(2) + return ( + + ) + } +}) diff --git a/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx b/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx new file mode 100644 index 00000000000..9ca9f1b0a77 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx @@ -0,0 +1,316 @@ +import { useState } from 'react' +import { Bot, Boxes, Hammer, Loader2, RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { Skeleton } from '@/components/ui/skeleton' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { BuildLogBuffer } from './build-log-model' +import { BuildHistoryList } from './BuildHistoryList' +import { BuildLogViewer, type BuildLogStreamState } from './BuildLogViewer' +import { + isBuildInProgress, + repoDisplayName, + type StalenessBannerCopy +} from './cloud-environment-copy' +import type { + EnvironmentBuildView, + EnvironmentDraft, + EnvironmentView +} from './cloud-environment-types' +import { draftFromEnvironment } from './environment-draft' +import { EnvironmentForm, EnvironmentSummary, type EnvironmentFormProps } from './EnvironmentForm' +import { StalenessBanner } from './StalenessBanner' + +function SubsectionTitle({ + children, + action +}: { + children: React.ReactNode + action?: React.ReactNode +}) { + return ( +
    +

    + {children} +

    + {action} +
    + ) +} + +export type CloudEnvironmentPanelProps = { + environment: EnvironmentView + /** The environment the form draft started from (defaults to `environment`). */ + formEnvironment?: EnvironmentView | null + builds: readonly EnvironmentBuildView[] + canAdmin: boolean + /** Fixed clock for fixtures; live views tick inside the history list only. */ + now?: number + selectedBuild: EnvironmentBuildView | null + log: { + buffer: BuildLogBuffer + state: BuildLogStreamState + error: string | null + onRetry: () => void + } | null + staleness: StalenessBannerCopy | null + starting: boolean + busyBuildId: string | null + actionError: string | null + actorName?: (actor: string) => string + /** Configure-with-agent is possible (a local project to run in exists). */ + agentAvailable: boolean + agentLaunching: boolean + form: Pick< + EnvironmentFormProps, + | 'saving' + | 'error' + | 'conflict' + | 'conflictEditor' + | 'suggestions' + | 'importProjects' + | 'onReadImports' + | 'onReload' + > & { + onSave: (draft: EnvironmentDraft) => void + initialDraft?: EnvironmentDraft + } + onBuild: () => void + onCancel: (build: EnvironmentBuildView) => void + onActivate: (build: EnvironmentBuildView) => void + onSelectBuild: (build: EnvironmentBuildView) => void + onConfigureWithAgent: () => void + /** Render the log viewer at a fixed clock (fixtures). */ + frozenNow?: number +} + +export function CloudEnvironmentPanel(props: CloudEnvironmentPanelProps): React.JSX.Element { + const t = useTranslate() + const { environment, builds, canAdmin, selectedBuild, log, staleness, starting, actionError } = + props + const activeBuild = builds.find((build) => build.active) ?? null + const inProgress = builds.some((build) => isBuildInProgress(build.status)) + const formEnvironment = props.formEnvironment ?? environment + const bannerOffersRebuild = staleness !== null && staleness.rebuild && !inProgress + const base = draftFromEnvironment(formEnvironment) + const [configOpen, setConfigOpen] = useState(builds.length === 0) + + return ( +
    +
    +
    + +
    +
    +

    + {activeBuild + ? t('cloudEnvironment.header.active', 'New workspaces start from build #{{number}}', { + number: String(activeBuild.number) + }) + : t( + 'cloudEnvironment.header.noActive', + 'No build yet: workspaces start from a fresh sandbox' + )} +

    +

    + {environment.repos.map((repo) => repoDisplayName(repo.url)).join(', ')} + {' · '} + {environment.machineSize === 'large' + ? t('cloudEnvironment.header.large', 'Large') + : t('cloudEnvironment.header.standard', 'Standard')} +

    +
    + {canAdmin ? ( +
    + + {/* One Rebuild per view: a staleness banner that offers one owns it. */} + {bannerOffersRebuild ? null : ( + + )} +
    + ) : null} +
    + + {actionError ? : null} + + {staleness && !inProgress ? ( + + ) : null} + + {selectedBuild && log ? ( + + ) : null} + +
    + + {t('cloudEnvironment.history.title', 'Builds')} + + +
    + +
    + setConfigOpen((open) => !open)} + > + {configOpen + ? t('cloudEnvironment.config.hide', 'Hide') + : canAdmin + ? t('cloudEnvironment.config.edit', 'Edit') + : t('cloudEnvironment.config.show', 'Show')} + + } + > + {t('cloudEnvironment.config.title', 'Configuration')} + +
    + {canAdmin ? ( + + ) : ( + + )} +
    +
    +
    + ) +} + +export function CloudEnvironmentEmptyState({ + canAdmin, + onStart +}: { + canAdmin: boolean + onStart: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( +
    +
    + +
    +
    +

    + {t('cloudEnvironment.empty.title', 'Create your environment')} +

    +

    + {t( + 'cloudEnvironment.empty.description', + 'Install your repos’ dependencies once, snapshot the sandbox, and every new cloud workspace starts ready to run in seconds.' + )} +

    +
    + {canAdmin ? ( + + ) : ( +

    + {t('cloudEnvironment.empty.memberAsk', 'Ask an owner or admin to set it up.')} +

    + )} +
    + ) +} + +/** Loading placeholder shaped like the panel (header row, banner, log). */ +export function CloudEnvironmentSkeleton(): React.JSX.Element { + const t = useTranslate() + return ( +
    + + {t('cloudEnvironment.loading', 'Loading environment…')} + +
    + +
    + + +
    + +
    + +
    + + +
    +
    + ) +} diff --git a/src/renderer/src/components/cloud-environment/CloudEnvironmentSection.tsx b/src/renderer/src/components/cloud-environment/CloudEnvironmentSection.tsx new file mode 100644 index 00000000000..bed8b7d0c14 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/CloudEnvironmentSection.tsx @@ -0,0 +1,349 @@ +import { useEffect, useMemo, useState } from 'react' +import { useConfirmationDialog } from '@/components/confirmation-dialog-context' +import { InlineError } from '@/components/ui/inline-error' +import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup' +import { useTranslate } from '@/i18n/use-translate' +import { + githubSlugForRepo, + launchCloudEnvironmentAgent, + pickCloudEnvironmentAgentRepo +} from '@/lib/cloud-environment-agent-launch' +import { useAppStore } from '@/store/index' +import { isGitRepoKind } from '../../../../shared/repo-kind' +import type { OrcaOrgMember } from '../../../../shared/orca-profiles' +import { stalenessBannerCopy } from './cloud-environment-copy' +import type { + EnvironmentBuildView, + EnvironmentDraft, + EnvironmentsApi +} from './cloud-environment-types' +import { + CloudEnvironmentEmptyState, + CloudEnvironmentSkeleton, + CloudEnvironmentPanel +} from './CloudEnvironmentPanel' +import { emptyDraft } from './environment-draft' +import { EnvironmentForm } from './EnvironmentForm' +import type { LocalRepoSuggestion } from './EnvironmentFormFields' +import { useBuildLogStream } from './use-build-log-stream' +import { useCloudEnvironment } from './use-cloud-environment' + +const LOG_TAIL_LINES = 80 + +/** Hidden unless this build talks to an Orca Cloud control plane. */ +export function useOrcaCloudEnvironmentsConfigured(): boolean { + const [configured, setConfigured] = useState(false) + useEffect(() => { + let disposed = false + void window.api.orcaCloudEnvironments + ?.isConfigured() + .then((value) => { + if (!disposed) { + setConfigured(value) + } + }) + .catch(() => undefined) + return () => { + disposed = true + } + }, []) + return configured +} + +function useLocalRepoSuggestions(): { + suggestions: LocalRepoSuggestion[] + importProjects: LocalRepoSuggestion[] +} { + const repos = useAppStore((state) => state.repos) + return useMemo(() => { + const local = repos.filter((repo) => isGitRepoKind(repo) && !repo.connectionId) + const importProjects = local.map((repo) => ({ + repoId: repo.id, + slug: githubSlugForRepo(repo) ?? '', + path: repo.path, + displayName: repo.displayName + })) + return { + suggestions: importProjects.filter((entry) => entry.slug !== ''), + importProjects + } + }, [repos]) +} + +/** Settings block: Orca Cloud environment (repos + install script → snapshot builds). */ +export function CloudEnvironmentSection({ + orgId, + viewerUserId +}: { + orgId: string | null + viewerUserId: string | null +}): React.JSX.Element | null { + const t = useTranslate() + const configured = useOrcaCloudEnvironmentsConfigured() + if (!configured) { + return null + } + return ( +
    + + {t('cloudEnvironment.title', 'Cloud environment')} + + } + description={t( + 'cloudEnvironment.descriptionTeam', + 'Your team’s repos and install script, built once into a snapshot so every cloud workspace starts with dependencies installed.' + )} + /> + +
    + ) +} + +function useActorName( + orgId: string | null, + viewerUserId: string | null +): (actor: string) => string { + const t = useTranslate() + const [members, setMembers] = useState([]) + useEffect(() => { + if (!orgId) { + return + } + let disposed = false + void window.api.orcaProfiles + .orgMembersList({ orgId }) + .then((result) => { + if (!disposed && result.status === 'ok') { + setMembers(result.roster.members) + } + }) + .catch(() => undefined) + return () => { + disposed = true + } + }, [orgId]) + return useMemo(() => { + const you = t('cloudEnvironment.you', 'You') + return (actor: string) => { + if (actor === viewerUserId) { + return you + } + const member = members.find((entry) => entry.userId === actor) + return member ? member.displayName?.trim() || member.email : actor + } + }, [members, viewerUserId, t]) +} + +function CloudEnvironmentController({ + api, + orgId, + viewerUserId +}: { + api: EnvironmentsApi + orgId: string | null + viewerUserId: string | null +}): React.JSX.Element { + const t = useTranslate() + const confirm = useConfirmationDialog() + const env = useCloudEnvironment(api) + const { suggestions, importProjects } = useLocalRepoSuggestions() + const repos = useAppStore((state) => state.repos) + const activeRepoId = useAppStore((state) => state.activeRepoId) + const actorName = useActorName(orgId, viewerUserId) + const [creating, setCreating] = useState(false) + const [selectedBuildId, setSelectedBuildId] = useState(null) + const [agentLaunching, setAgentLaunching] = useState(false) + + const ready = env.load.phase === 'ready' ? env.load : null + const builds = ready?.builds ?? [] + const selectedBuild = builds.find((build) => build.id === selectedBuildId) ?? builds[0] ?? null + const stream = useBuildLogStream( + api, + ready?.environment.id ?? null, + selectedBuild?.id ?? null, + env.applyBuild, + env.refreshAfterBuildEnd + ) + + if (env.load.phase === 'loading') { + return + } + if (env.load.phase === 'error') { + const { error } = env.load + const entitlement = error.code === 'forbidden' && error.reason !== 'admin_required' + return ( + + ) + } + + const readImports = (path: string) => api.readRepoSetupImports(path) + + if (env.load.phase === 'none') { + if (!creating) { + return ( + setCreating(true)} + /> + ) + } + const prefill = pickCloudEnvironmentAgentRepo(repos, [], activeRepoId) + const prefillSlug = prefill ? githubSlugForRepo(prefill) : null + return ( + setCreating(false)} + onSave={(draft: EnvironmentDraft) => { + void env.create(draft).then((build) => { + if (build) { + setSelectedBuildId(build.id) + } + setCreating(false) + }) + }} + /> + ) + } + + const { environment, canAdmin } = env.load + const activeBuild = builds.find((build) => build.active) ?? null + // The stream's view of the selected build is fresher than the list until the next poll. + const streamedBuild = + stream.build && selectedBuild && stream.build.id === selectedBuild.id ? stream.build : null + const logBuild = streamedBuild ?? selectedBuild + const agentRepo = pickCloudEnvironmentAgentRepo( + repos, + environment.repos.map((repo) => repo.url), + activeRepoId + ) + + const configureWithAgent = (): void => { + if (!agentRepo) { + return + } + const latest = builds[0] + const failure = + latest && latest.status === 'failed' + ? { + buildNumber: latest.number, + failedStep: latest.failedStep, + error: latest.error, + log: + latest.id === logBuild?.id + ? stream.buffer.lines + .slice(-LOG_TAIL_LINES) + .map((line) => line.plain) + .join('\n') + : undefined + } + : undefined + setAgentLaunching(true) + void launchCloudEnvironmentAgent({ + repoId: agentRepo.id, + envId: environment.id, + environmentName: environment.name, + repos: environment.repos.map((repo) => repo.url), + envVarNames: environment.envVarNames, + ...(failure ? { failure } : {}) + }) + .catch(() => false) + .then(() => setAgentLaunching(false)) + } + + const activate = (build: EnvironmentBuildView): void => { + void confirm({ + title: t('cloudEnvironment.activate.title', 'Use build #{{number}}?', { + number: String(build.number) + }), + description: t( + 'cloudEnvironment.activate.description', + 'New workspaces will start from build #{{number}}. Existing workspaces keep theirs.', + { number: String(build.number) } + ), + confirmLabel: t('cloudEnvironment.activate.confirm', 'Use this build') + }).then((accepted) => { + if (accepted) { + void env.activate(build) + } + }) + } + + return ( + void env.save(env.formBase ?? environment, draft) + }} + onBuild={() => { + void env.startBuild(environment.id).then((build) => { + if (build) { + setSelectedBuildId(build.id) + } + }) + }} + onCancel={(build) => void env.cancel(build)} + onActivate={activate} + onSelectBuild={(build) => setSelectedBuildId(build.id)} + onConfigureWithAgent={configureWithAgent} + /> + ) +} diff --git a/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx new file mode 100644 index 00000000000..b0193409681 --- /dev/null +++ b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx @@ -0,0 +1,330 @@ +import { useId, useState } from 'react' +import { Download, Loader2, Lock } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { useTranslate } from '@/i18n/use-translate' +import { repoDisplayName } from './cloud-environment-copy' +import type { + EnvironmentDraft, + EnvironmentResult, + RepoSetupImports +} from './cloud-environment-types' +import { draftsEqual, MAX_INSTALL_SCRIPT_CHARS, mergeEnvVarNames } from './environment-draft' +import { + FieldLabel, + InstallScriptEditor, + RepoListEditor, + type LocalRepoSuggestion +} from './EnvironmentFormFields' +import { EnvVarChipEditor, MachineSizeControl } from './EnvironmentSettingsFields' +import { ImportFromRepoDialog, type ImportReview } from './ImportFromRepoDialog' + +export type EnvironmentFormProps = { + mode: 'create' | 'edit' + /** The saved state; the form is dirty when its draft differs. Remount (key) on a new revision. */ + base: EnvironmentDraft + /** Starting draft when it differs from `base` (fixtures, pre-filled create). */ + initialDraft?: EnvironmentDraft + saving: boolean + error: string | null + /** Someone else saved first (stale_revision): offer to reload. */ + conflict: boolean + /** Who saved the newer revision, when known. */ + conflictEditor?: string | null + suggestions: readonly LocalRepoSuggestion[] + /** Local projects "Import from repo" can read. */ + importProjects: readonly LocalRepoSuggestion[] + onReadImports: (path: string) => Promise> + onSave: (draft: EnvironmentDraft) => void + onReload?: () => void + onCancel?: () => void +} + +export function EnvironmentForm({ + mode, + base, + initialDraft, + saving, + error, + conflict, + conflictEditor, + suggestions, + importProjects, + onReadImports, + onSave, + onReload, + onCancel +}: EnvironmentFormProps): React.JSX.Element { + const t = useTranslate() + const scriptId = useId() + const [draft, setDraft] = useState(initialDraft ?? base) + const [review, setReview] = useState(null) + const [importing, setImporting] = useState(null) + const [importError, setImportError] = useState(null) + const dirty = mode === 'create' || !draftsEqual(draft, base) + const invalid = draft.repos.length === 0 || draft.installScript.length > MAX_INSTALL_SCRIPT_CHARS + + const readImports = async (project: LocalRepoSuggestion): Promise => { + setImporting(project.repoId) + setImportError(null) + const result = await onReadImports(project.path).catch( + (cause: unknown): EnvironmentResult => ({ + ok: false, + error: { code: 'unavailable', message: String(cause) } + }) + ) + setImporting(null) + if (result.ok) { + setReview({ projectName: project.displayName, imports: result.data }) + } else { + setImportError(result.error.message) + } + } + + return ( +
    + {conflict ? ( + void window.api.ui.writeClipboardText(draft.installScript)} + /> + ) : null} + setDraft((current) => ({ ...current, repos }))} + /> + +
    +
    + + {t('cloudEnvironment.form.script', 'Install script')} + + {importProjects.length > 0 ? ( + + + + + + + {t( + 'cloudEnvironment.form.importHint', + 'Reads Conductor and dev container setup from a local project.' + )} + + {importProjects.map((project) => ( + void readImports(project)}> + {project.displayName} + {project.slug ? ( + + {project.slug} + + ) : null} + + ))} + + + ) : null} +
    + setDraft((current) => ({ ...current, installScript }))} + /> + {importError ? ( + + ) : null} +
    + + setDraft((current) => ({ ...current, envVarNames }))} + /> + + setDraft((current) => ({ ...current, machineSize }))} + /> + +
    + + {mode === 'edit' && dirty ? ( + + ) : null} + {mode === 'create' && onCancel ? ( + + ) : null} +

    + {conflict || error ? null : mode === 'edit' && dirty ? ( + + + {t( + 'cloudEnvironment.form.unsavedChanges', + 'Unsaved changes. Saving doesn’t rebuild; start a build when you’re ready.' + )} + + ) : draft.repos.length === 0 ? ( + t('cloudEnvironment.form.needRepo', 'Add at least one repository.') + ) : null} +

    +
    + {error && !conflict ? ( + + ) : null} + setReview(null)} + onApply={({ envVarNames, installScript }) => { + setDraft((current) => ({ + ...current, + envVarNames: mergeEnvVarNames(current.envVarNames, envVarNames), + installScript: installScript ?? current.installScript + })) + setReview(null) + }} + /> +
    + ) +} + +/** What members (no admin role) see: the same facts, nothing editable. */ +export function EnvironmentSummary({ base }: { base: EnvironmentDraft }): React.JSX.Element { + const t = useTranslate() + const scriptId = useId() + return ( +
    +

    + + {t( + 'cloudEnvironment.readOnlyAsk', + 'Ask an owner or admin to change the environment or start a build.' + )} +

    +
    + {t('cloudEnvironment.form.repos', 'Repositories')} +
      + {base.repos.map((repo) => ( +
    • + {repoDisplayName(repo.url)} + + {repo.defaultBranch ?? t('cloudEnvironment.form.defaultBranch', 'default branch')} + +
    • + ))} +
    +
    +
    + + {t('cloudEnvironment.form.script', 'Install script')} + + +
    + +
    + {t('cloudEnvironment.size.label', 'Sandbox size')} +

    + {base.machineSize === 'large' + ? t('cloudEnvironment.size.large', 'Large (8 vCPU · 16 GB)') + : t('cloudEnvironment.size.standard', 'Standard (4 vCPU · 8 GB)')} +

    +

    + {t('cloudEnvironment.size.rateNote', 'Large uses sandbox hours at 2× the rate.')} +

    +
    +
    + ) +} + +/** At the top, because Save is blocked until the user reloads (their draft would overwrite). */ +function ConflictNotice({ + editor, + onReload, + onCopyScript +}: { + editor: string | null + onReload?: () => void + onCopyScript: () => void +}): React.JSX.Element { + const t = useTranslate() + const [copied, setCopied] = useState(false) + return ( +
    + + {editor + ? t( + 'cloudEnvironment.form.conflictNamed', + '{{editor}} saved changes to this environment while you were editing. Reload to see them; your edits here will be discarded.', + { editor } + ) + : t( + 'cloudEnvironment.form.conflict', + 'Someone else saved changes to this environment. Reload to see them; your edits here will be discarded.' + )} + + + {onReload ? ( + + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/cloud-environment/EnvironmentFormFields.tsx b/src/renderer/src/components/cloud-environment/EnvironmentFormFields.tsx new file mode 100644 index 00000000000..51a9f6a384c --- /dev/null +++ b/src/renderer/src/components/cloud-environment/EnvironmentFormFields.tsx @@ -0,0 +1,334 @@ +import { useId, useRef, useState } from 'react' +import { GitBranch, Plus, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import { getIntlLocale } from '@/i18n/i18n' +import { normalizeRepoInput, repoDisplayName, repoKey } from './cloud-environment-copy' +import type { EnvironmentDraft } from './cloud-environment-types' +import { MAX_INSTALL_SCRIPT_CHARS } from './environment-draft' + +export type LocalRepoSuggestion = { + /** Orca project id. */ + repoId: string + /** `owner/repo` from the project's GitHub remote. */ + slug: string + path: string + displayName: string +} + +export function FieldLabel({ + htmlFor, + id, + children, + hint +}: { + htmlFor?: string + id?: string + children: React.ReactNode + hint?: React.ReactNode +}): React.JSX.Element { + return ( +
    + + {hint ?

    {hint}

    : null} +
    + ) +} + +export function RepoListEditor({ + repos, + onChange, + suggestions +}: { + repos: EnvironmentDraft['repos'] + onChange: (repos: EnvironmentDraft['repos']) => void + suggestions: readonly LocalRepoSuggestion[] +}): React.JSX.Element { + const t = useTranslate() + const inputId = useId() + const labelId = useId() + const [value, setValue] = useState('') + const [error, setError] = useState(null) + const present = new Set(repos.map((repo) => repoKey(repo.url))) + const offered = suggestions.filter((suggestion) => !present.has(suggestion.slug.toLowerCase())) + + const add = (raw: string): boolean => { + const slug = normalizeRepoInput(raw) + if (!slug) { + setError( + t( + 'cloudEnvironment.form.repoInvalid', + 'Enter a GitHub repository as owner/repo or a github.com URL.' + ) + ) + return false + } + if (present.has(slug.toLowerCase())) { + setError( + t('cloudEnvironment.form.repoDuplicate', '{{repo}} is already listed.', { repo: slug }) + ) + return false + } + setError(null) + onChange([...repos, { url: slug, defaultBranch: null }]) + return true + } + + const submit = (): void => { + if (add(value)) { + setValue('') + } + } + + return ( +
    + + {t('cloudEnvironment.form.repos', 'Repositories')} + + {repos.length > 0 ? ( +
      + {repos.map((repo, index) => { + const name = repoDisplayName(repo.url) + return ( +
    • + {name} + {index === 0 && repos.length > 1 ? ( + + {t('cloudEnvironment.form.primaryRepo', 'install script runs here')} + + ) : null} +
      + + { + const next = [...repos] + next[index] = { + ...repo, + defaultBranch: event.target.value + } + onChange(next) + }} + /> +
      + +
    • + ) + })} +
    + ) : null} +
    + { + setValue(event.target.value) + setError(null) + }} + placeholder={t( + 'cloudEnvironment.form.repoPlaceholder', + 'owner/repo or https://github.com/…' + )} + aria-invalid={error ? true : undefined} + aria-describedby={error ? `${inputId}-error` : undefined} + variant="code-body" + className="h-8" + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + submit() + } + }} + /> + +
    + {error ? ( +

    + {error} +

    + ) : null} + {offered.length > 0 ? ( +
    + + {t('cloudEnvironment.form.fromProjects', 'From your projects:')} + + {offered.slice(0, 8).map((suggestion) => ( + + ))} +
    + ) : null} +
    + ) +} + +/** Textarea with a synced line-number gutter; a full editor is overkill for a setup script. */ +export function InstallScriptEditor({ + value, + onChange, + readOnly = false, + id +}: { + value: string + onChange?: (value: string) => void + readOnly?: boolean + id?: string +}): React.JSX.Element { + const t = useTranslate() + const gutterRef = useRef(null) + const escaped = useRef(false) + const tabHintId = useId() + const lineCount = Math.max(1, value.split('\n').length) + const tooLong = value.length > MAX_INSTALL_SCRIPT_CHARS + return ( +
    +
    +
    + {Array.from({ length: lineCount }, (_, index) => ( +
    {index + 1}
    + ))} +
    +