diff --git a/.github/workflows/release-javascript-benchmark.yml b/.github/workflows/release-javascript-benchmark.yml index af297793dd4..75de57e10c4 100644 --- a/.github/workflows/release-javascript-benchmark.yml +++ b/.github/workflows/release-javascript-benchmark.yml @@ -15,7 +15,7 @@ concurrency: env: ORCA_BACKGROUND_LAUNCH: '1' - ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token + ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token ORCA_POSTHOG_WRITE_KEY: ci-build-comparison NODE_OPTIONS: --max-old-space-size=4096 diff --git a/cloud/apps/billing/src/auth.ts b/cloud/apps/billing/src/auth.ts index 944208b4248..b905157a37e 100644 --- a/cloud/apps/billing/src/auth.ts +++ b/cloud/apps/billing/src/auth.ts @@ -63,10 +63,22 @@ function devKeysFor(env: Env): JWTVerifyGetKey | null { return devKeys.keys } +/** + * A comma-separated issuer var as jwtVerify's `issuer` option: the token's `iss` must equal one entry. + * Unset or empty: no issuer check (as before lists). Blank entries are ignored; a value with no + * entries left accepts no issuer. + */ +export function issuerList(value: string | undefined): string[] | undefined { + if (!value) { + return undefined + } + return value.split(',').map((issuer) => issuer.trim()).filter(Boolean) +} + let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null /** Staging auth's keys and issuer; never honored when BILLING_ENV is 'prod'. */ -function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | null { +function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null { if (env.BILLING_ENV === 'prod' || !env.BILLING_STAGING_JWKS_URL || !env.BILLING_STAGING_AUTH_ISSUER) { return null } @@ -76,7 +88,7 @@ function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | n keys: createRemoteJWKSet(new URL(env.BILLING_STAGING_JWKS_URL)) } } - return { keys: stagingKeys.keys, issuer: env.BILLING_STAGING_AUTH_ISSUER } + return { keys: stagingKeys.keys, issuer: issuerList(env.BILLING_STAGING_AUTH_ISSUER) } } export function readBearer(value: string | null): string | null { @@ -102,7 +114,7 @@ export async function authenticateDesktop( if (!token) { return null } - const verify = (keys: JWTVerifyGetKey, issuer: string | undefined) => + const verify = (keys: JWTVerifyGetKey, issuer: string | string[] | undefined) => jwtVerify(token, keys, { audience: env.BILLING_JWT_AUDIENCE, algorithms: ['ES256'], @@ -114,7 +126,7 @@ export async function authenticateDesktop( try { // Production auth first; in dev only, then staging auth, then the operator key set. const attempts: Array<() => ReturnType> = [ - () => verify(keysFor(env), env.BILLING_AUTH_ISSUER) + () => verify(keysFor(env), issuerList(env.BILLING_AUTH_ISSUER)) ] const staging = stagingKeysFor(env) if (staging) { diff --git a/cloud/apps/billing/src/cloud-setup-urls.ts b/cloud/apps/billing/src/cloud-setup-urls.ts index 4ccc17b8461..552b14659fd 100644 --- a/cloud/apps/billing/src/cloud-setup-urls.ts +++ b/cloud/apps/billing/src/cloud-setup-urls.ts @@ -1,7 +1,19 @@ // URLs of the cloud setup pages on Orca Cloud auth (auth.onorca.dev/cloud/setup/...). import type { Env } from './env' +/** Thrown when CLOUD_SETUP_PAGES_URL is unset in prod; the index answers 503 billing_misconfigured. */ +export class SetupPagesConfigError extends Error { + constructor() { + super('cloud_setup_pages_url_missing') + this.name = 'SetupPagesConfigError' + } +} + function pagesOrigin(env: Env): string { + if (!env.CLOUD_SETUP_PAGES_URL && env.BILLING_ENV === 'prod') { + // Prod must name its pages origin; the fallback below is only a dev/staging convenience. + throw new SetupPagesConfigError() + } return (env.CLOUD_SETUP_PAGES_URL ?? 'https://auth.onorca.dev').replace(/\/$/, '') } diff --git a/cloud/apps/billing/src/env.ts b/cloud/apps/billing/src/env.ts index 1e798845dde..06c3f11d482 100644 --- a/cloud/apps/billing/src/env.ts +++ b/cloud/apps/billing/src/env.ts @@ -51,6 +51,7 @@ export type Env = { // BILLING_JWKS (inline set) is for local dev and tests only. BILLING_JWKS_URL?: string BILLING_JWKS?: string + // Accepted `iss` values, comma-separated (a single issuer is a one-item list); so is the staging one. BILLING_AUTH_ISSUER?: string BILLING_JWT_AUDIENCE: string // 'dev' | 'prod'. Dev may also accept BILLING_DEV_JWKS (issuer 'orca-billing-dev-test', a secret diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index ebc71c6162b..f7d22eea512 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -55,6 +55,7 @@ import { entitlementsView, offersFor, plansView } from './plans-api' import { reconcile } from './reconcile' import type { Env } from './env' import { MACHINE_SIZES, PlanConfigError, planCatalog, publicOffers } from './plans' +import { SetupPagesConfigError } from './cloud-setup-urls' import { OverageRequestSchema, updateOverage } from './overage' import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe' import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage' @@ -566,7 +567,12 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo if (error instanceof SyntaxError) { return json({ error: 'invalid_json' }, 400) } - if (error instanceof LiveModeRefusedError || error instanceof PlanConfigError || error instanceof CatalogUnavailableError) { + if ( + error instanceof LiveModeRefusedError || + error instanceof PlanConfigError || + error instanceof CatalogUnavailableError || + error instanceof SetupPagesConfigError + ) { return json({ error: 'billing_misconfigured' }, 503) } if (error instanceof MembershipUnavailableError) { diff --git a/cloud/apps/billing/test/auth-issuers.test.ts b/cloud/apps/billing/test/auth-issuers.test.ts new file mode 100644 index 00000000000..a1aa466a006 --- /dev/null +++ b/cloud/apps/billing/test/auth-issuers.test.ts @@ -0,0 +1,63 @@ +import { SignJWT, exportJWK, generateKeyPair } from 'jose' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { authenticateDesktop, issuerList } from '../src/auth' +import { createHarness } from './harness' + +const PROD = 'https://login.onorca.dev' +const NEXT = 'https://login.example.dev' +const NOW = Date.UTC(2026, 0, 15) + +async function issuerHarness(issuers: string) { + const { privateKey, publicKey } = await generateKeyPair('ES256') + const jwk = { ...(await exportJWK(publicKey)), kid: 'iss1', alg: 'ES256', use: 'sig' } + const h = await createHarness({ BILLING_JWKS: JSON.stringify({ keys: [jwk] }), BILLING_AUTH_ISSUER: issuers }) + const accepts = async (issuer: string): Promise => { + const iat = Math.floor(NOW / 1000) + const token = await new SignJWT({ sub: 'user_iss', purpose: 'billing' }) + .setProtectedHeader({ alg: 'ES256', kid: 'iss1' }) + .setIssuer(issuer) + .setAudience('orca-billing') + .setIssuedAt(iat) + .setExpirationTime(iat + 300) + .sign(privateKey) + const request = new Request('https://billing.test/v1/billing/entitlements', { headers: { authorization: `Bearer ${token}` } }) + return (await authenticateDesktop(h.env, request)) !== null + } + return { accepts } +} + +describe('BILLING_AUTH_ISSUER list', () => { + // jose checks exp/iat against Date; pin it so no wall clock is involved. + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('parses a comma list, ignoring whitespace and empty entries', () => { + expect(issuerList(undefined)).toBeUndefined() + expect(issuerList('')).toBeUndefined() + expect(issuerList(PROD)).toEqual([PROD]) + expect(issuerList(` ${PROD} ,, ${NEXT} , `)).toEqual([PROD, NEXT]) + }) + + it('a single issuer behaves as before', async () => { + const h = await issuerHarness(PROD) + expect(await h.accepts(PROD)).toBe(true) + expect(await h.accepts(NEXT)).toBe(false) + }) + + it('a list accepts each listed issuer and rejects others', async () => { + const h = await issuerHarness(` ${PROD} , ,${NEXT},`) + expect(await h.accepts(PROD)).toBe(true) + expect(await h.accepts(NEXT)).toBe(true) + expect(await h.accepts('https://login.evil.dev')).toBe(false) + }) + + it('a value with no entries accepts no issuer', async () => { + const h = await issuerHarness(' , ') + expect(await h.accepts(PROD)).toBe(false) + }) +}) diff --git a/cloud/apps/billing/test/cloud-setup-urls.test.ts b/cloud/apps/billing/test/cloud-setup-urls.test.ts new file mode 100644 index 00000000000..1e00346d13b --- /dev/null +++ b/cloud/apps/billing/test/cloud-setup-urls.test.ts @@ -0,0 +1,41 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SetupPagesConfigError, setupPageUrl } from '../src/cloud-setup-urls' +import { createHarness } from './harness' + +const NOW = Date.UTC(2026, 0, 15) + +describe('CLOUD_SETUP_PAGES_URL', () => { + // The harness and jose read Date; pin it so no wall clock is involved. + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('falls back to the current auth origin outside prod when unset', async () => { + for (const BILLING_ENV of [undefined, 'dev', 'staging']) { + const { env } = await createHarness({ BILLING_ENV }) + expect(setupPageUrl(env, '/start', { session: 's1' })).toBe('https://auth.onorca.dev/cloud/setup/start?session=s1') + } + }) + + it('uses the configured origin in every environment', async () => { + for (const BILLING_ENV of ['dev', 'prod']) { + const { env } = await createHarness({ BILLING_ENV, CLOUD_SETUP_PAGES_URL: 'https://pages.test/' }) + expect(setupPageUrl(env, '/plan', { session: 's1' })).toBe('https://pages.test/cloud/setup/plan?session=s1') + } + }) + + it('is a configuration error in prod when unset, answered as billing_misconfigured', async () => { + const h = await createHarness({ BILLING_ENV: 'prod' }) + expect(() => setupPageUrl(h.env, '/start', { session: 's1' })).toThrow(SetupPagesConfigError) + const token = await h.desktopToken({ sub: 'u1', email: 'neil@acme.dev' }) + const created = await h.call('POST', '/v1/cloud-setup/sessions', { + body: { repo: 'https://github.com/acme/web', needs: ['plan'], device: 'MacBook Pro' }, + headers: { authorization: `Bearer ${token}` } + }) + expect(created).toEqual({ status: 503, body: { error: 'billing_misconfigured' } }) + }) +}) diff --git a/cloud/apps/sandbox-control/image/env/environment-build.sh b/cloud/apps/sandbox-control/image/env/environment-build.sh index 0809efc70ad..8d607eab977 100644 --- a/cloud/apps/sandbox-control/image/env/environment-build.sh +++ b/cloud/apps/sandbox-control/image/env/environment-build.sh @@ -10,6 +10,7 @@ # the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get). # `::orca-step:: ` lines mark progress. # Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk. +# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing. set -uo pipefail umask 022 # One stream: the provider replays stdout and stderr separately after the fact, so a failed build's @@ -92,6 +93,65 @@ scan_secrets() { return 1 } +# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the +# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps +# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date +# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on. +# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log. +# ORCA_AUTO_INSTALL_TIMEOUT: tests only. +auto_install() { + local dir="$1" pm="" declared="" rc=0 started f + local cmd=() others=() + for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do + [ -f "$dir/$f" ] && others+=("$f") + done + if [ -f "$dir/package.json" ]; then + # package.json's packageManager ("pnpm@9.1.0") wins over the lockfile guess. + declared=$(sed -n 's/.*"packageManager"[[:space:]]*:[[:space:]]*"\([a-z]*\)@.*/\1/p' "$dir/package.json" | head -n 1) + case "$declared" in + pnpm | yarn | npm) pm="$declared" ;; + *) + if [ -f "$dir/pnpm-lock.yaml" ]; then pm=pnpm + elif [ -f "$dir/yarn.lock" ]; then pm=yarn + elif [ -f "$dir/package-lock.json" ] || [ -f "$dir/npm-shrinkwrap.json" ]; then pm=npm + fi + ;; + esac + fi + if [ "${#others[@]}" -gt 0 ]; then + echo "Not installed automatically: ${others[*]}. Add an install script to the environment to install these." + fi + if [ -z "$pm" ]; then + [ "${#others[@]}" -gt 0 ] || echo "No lockfile found; the build keeps the cloned repos." + return 0 + fi + # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack). + case "$pm" in + pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;; + yarn) + if [ -f "$dir/.yarnrc.yml" ]; then cmd=(corepack yarn install --immutable) + else cmd=(corepack yarn install --frozen-lockfile) + fi + ;; + npm) cmd=(npm ci) ;; + esac + echo "Installing dependencies automatically: ${cmd[*]}" + started=$(date +%s) + (cd "$dir" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout "${ORCA_AUTO_INSTALL_TIMEOUT:-900}" "${cmd[@]}") /dev/null || true + return 0 + fi + echo "Installed dependencies in $(($(date +%s) - started))s." +} + take_secrets step() { printf '\n::orca-step:: %s\n' "$1"; } started=$(date +%s) @@ -153,6 +213,8 @@ if [ -s "$OUT/install.sh" ]; then echo "::orca-error:: The install script exited with status $rc." exit 20 fi +elif [ "${ORCA_AUTO_INSTALL:-}" = 1 ] && [ -n "$first" ]; then + auto_install "$first" else echo "No install script; the build keeps the cloned repos." fi diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index 3f8787c7247..7e669dd72dd 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -31,7 +31,7 @@ ref="${ORCA_REPO_REF:-}" first_commit() { if ! git -C "$P" rev-parse --verify --quiet HEAD >/dev/null; then git -C "$P" checkout --quiet -B "${ref:-main}" 2>/dev/null || true - git -C "$P" -c user.name='Orca' -c user.email='cloud@onorca.dev' \ + git -C "$P" -c user.name='Orca' -c user.email='noreply@orca.dev' \ commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.' fi } diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 64a1c7816bb..0e858d06f5d 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,10 +3,10 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\n# [ORCA_VM_SCRIPTS_STAMP] (VM_SCRIPTS_STAMP of those scripts; written to /opt/orca/bin/.scripts-stamp).\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

ok

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

ok

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

';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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.orca.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\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at),\n // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of stored) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.signature = sign(out, signingKey(stateDir))\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { workspaceCheckout, seal, sign, signingKey, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca Cloud's name) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect your GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n"} -export const VM_SCRIPTS_HASH: string = "f4d18985" -export const VM_SCRIPTS_STAMP: number = 1794532639 +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\n# CREATE-GIT-ASYNC: a create answers before member identities are installed; `git` holds commits and\n# pushes until orca-sandbox-members (or the control plane) marks this setup ready or failed. Marked\n# before the already-started exit below: a pooled VM's orcad may be up before its create claims it.\nif [ \"${ORCA_GIT_SETUP:-}\" = pending ]; then\n rm -f \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\n date +%s >\"$STATE/git-setup.pending\"\nfi\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# Any other boot (wake, restart) installs identities before it answers: a resumed disk's marks are stale.\n[ \"${ORCA_GIT_SETUP:-}\" = pending ] || rm -f \"$STATE/git-setup.pending\" \"$STATE/git-setup.ready\" \"$STATE/git-setup.failed\"\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.\n# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.\ncase \"$(git config --global user.email 2>/dev/null || true)\" in\n cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)\n git config --global user.email 'noreply@orca.dev' ;;\nesac\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'\n# The fallback name is \"Orca\" (DOMAIN-1); a workspace still on the earlier default follows it.\n[ \"$(git config --global user.name 2>/dev/null || true)\" = 'Orca Cloud' ] \\\n && git config --global user.name 'Orca'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\n# N-02: the host is a cloud terminal's source of truth across app reopens, so orcad and its\n# daemon keep a local terminal's depth (5000 rows) instead of the desktop daemon's 1000-row live\n# window. Scoped to the VM: local desktop daemons keep their default.\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_DAEMON_SESSION_SCROLLBACK_ROWS=5000 \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\n# CR-cmd-quiet: Orca's staged agent launch (` . '/tmp/orca-launch-….sh'`) stays out of zsh history.\n# zsh records a line before running it, so the hook must exist first; the staged script itself\n# drops the line from bash's history. eval: bash parses this file too.\nif [ -n \"${ZSH_VERSION-}\" ]; then\n eval '__orca_skip_launch_history() { [[ $1 == *orca-launch-* ]] && return 1; return 0 }\n (( ${zshaddhistory_functions[(Ie)__orca_skip_launch_history]} )) || zshaddhistory_functions+=(__orca_skip_launch_history)'\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# This workspace's read-snapshot signer (public half), so the paired device pins it; best effort.\nsigner=\"$(\"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\" --signer-public-key 2>/dev/null || true)\"\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\n# Granted devices are listed so orcad can keep owner-only features (local commands) from them.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" ORCA_READ_SIGNER=\"$signer\" \\\n ORCA_GRANT_LEDGER=\"$STATE/grant-devices\" \"$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 if (process.env.ORCA_GRANT_LEDGER) require(\"node:fs\").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + \"\\n\", { mode: 0o600 })\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 signer = /^[A-Za-z0-9+/]{43}=$/.test(process.env.ORCA_READ_SIGNER || \"\") ? process.env.ORCA_READ_SIGNER : undefined\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope, ...(signer ? { readSignerPublicKeyB64: signer } : {}) }))\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 'noreply@orca.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'\nfi\n# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.\nif [ -n \"$user_home\" ] && [ -d \"$user_home/.orca-sandbox\" ]; then\n sudo -u \"$USER_NAME\" sh -c 'rm -f \"$1/git-setup.pending\" \"$1/git-setup.failed\" && date +%s >\"$1/git-setup.ready\"' \\\n _ \"$user_home/.orca-sandbox\" || true\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\nconst SIG_INFO = 'orca-cloud-read-sig-v1'\n\n/**\n * This VM's snapshot signing key (Ed25519), created once and kept on the VM's own disk (0600, never\n * printed). Devices pin its public half per workspace, so a snapshot the control plane forged or\n * swapped doesn't verify. Same file for the grant script, which hands the public half to pairing devices.\n */\nfunction signingKey(stateDir) {\n if (!path.isAbsolute(stateDir)) {\n throw new Error('no state dir')\n }\n const file = path.join(stateDir, 'read-signing-key.pem')\n const load = () => {\n try {\n const privateKey = crypto.createPrivateKey(fs.readFileSync(file, 'utf8'))\n return privateKey.asymmetricKeyType === 'ed25519' ? privateKey : null\n } catch {\n return null\n }\n }\n let privateKey = load()\n if (!privateKey) {\n fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 })\n // Written whole to a temp file, then linked into place: atomic, and a concurrent first run\n // (grant + capture) keeps whichever key landed first. A broken file is replaced (devices that\n // pinned the old signer then see \"signer changed\" until they trust the new one).\n const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`\n fs.writeFileSync(temp, crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 })\n try {\n fs.linkSync(temp, file)\n } catch {\n if (!load()) {\n fs.renameSync(temp, file)\n }\n } finally {\n fs.rmSync(temp, { force: true })\n }\n privateKey = load()\n if (!privateKey) {\n throw new Error('signing key unavailable')\n }\n }\n const publicKeyB64 = Buffer.from(crypto.createPublicKey(privateKey).export({ format: 'jwk' }).x, 'base64url').toString('base64')\n return { privateKey, publicKeyB64 }\n}\n\n/** Signs the sealed body: \"orca-cloud-read-sig-v1::::\" || ciphertext bytes. */\nfunction sign(out, key) {\n const message = Buffer.concat([\n Buffer.from(`${SIG_INFO}:${out.workspaceId}:${out.snapshotId}:${out.nonceB64}:`),\n Buffer.from(out.ciphertextB64, 'base64')\n ])\n return { publicKeyB64: key.publicKeyB64, signatureB64: crypto.sign(null, message, key.privateKey).toString('base64') }\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at),\n // \"::\": which checkout this chat works in.\n worktreePath: isObj(record.location) && typeof record.location.workspaceId === 'string' ? record.location.workspaceId.split('::').pop() : null\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/**\n * The checkout this workspace is about: the one its newest chat works in, else the most recently\n * active one (a workspace on its own branch is a separate worktree, not the base clone at\n * /vercel/sandbox/project), else the base clone.\n */\nfunction workspaceCheckout(worktrees, sessions) {\n const byPath = new Map(worktrees.filter((w) => typeof w.path === 'string').map((w) => [w.path, w]))\n const newest = sessions\n .filter((s) => s.worktreePath && byPath.has(s.worktreePath))\n .sort((a, b) => (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))[0]\n if (newest) {\n return byPath.get(newest.worktreePath)\n }\n const activity = (w) => Math.max(num(w.lastActivityAt) || 0, num(w.sortOrder) || 0)\n const ranked = [...byPath.values()].sort(\n (a, b) => activity(b) - activity(a) || Number(a.isMainWorktree === true) - Number(b.isMainWorktree === true)\n )\n return ranked[0] || null\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const stored = listSessions()\n const project = workspaceCheckout(worktrees, stored)\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of stored) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\n// Fails closed without HOME (signingKey refuses a relative path).\nconst stateDir = process.env.HOME ? path.join(process.env.HOME, '.orca-sandbox') : ''\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n if (process.argv[2] === '--signer-public-key') {\n // For orca-sandbox-grant: pairing devices learn (and pin) this workspace's signer.\n process.stdout.write(`${signingKey(stateDir).publicKeyB64}\\n`)\n return\n }\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n out.signature = sign(out, signingKey(stateDir))\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { workspaceCheckout, seal, sign, signingKey, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=\"${ORCA_REAL_GIT:-/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\n# CREATE-GIT-ASYNC: a new workspace answers before teammates' GitHub identities are installed. Until\n# they are (orca-sandbox-members writes git-setup.ready), commits and pushes wait up to 15 s rather\n# than go out under the workspace identity; a failed or stalled setup stops them with what to do.\n# Read-only git and fetches never wait (they use the workspace's own credentials, set before ready).\nhold_for_member_setup() {\n local state=\"${HOME:-/nonexistent}/.orca-sandbox\" ticks=0 since\n # A failed install on any boot (create or a later restart) refuses even with nothing pending.\n [ -f \"$state/git-setup.pending\" ] || [ -f \"$state/git-setup.failed\" ] || return 0\n since=\"$(cat \"$state/git-setup.pending\" 2>/dev/null || echo 0)\"\n case \"$since\" in '' | *[!0-9]*) since=0 ;; esac\n while [ -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.ready\" ] && [ ! -f \"$state/git-setup.failed\" ]; do\n # 15 s per command; a mark older than 2 min is a setup that died, not one still running.\n if [ \"$ticks\" -ge \"${ORCA_GIT_SETUP_WAIT_TICKS:-150}\" ] || [ $(($(date +%s) - since)) -gt 120 ]; then\n break\n fi\n sleep 0.1\n ticks=$((ticks + 1))\n done\n if [ -f \"$state/git-setup.ready\" ] || { [ ! -f \"$state/git-setup.pending\" ] && [ ! -f \"$state/git-setup.failed\" ]; }; then\n return 0\n fi\n if [ -f \"$state/git-setup.failed\" ]; then\n printf '%s\\n' \"orca: Orca couldn't set up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Restart this workspace (right-click it in the sidebar > Restart), then try again.\" >&2\n else\n printf '%s\\n' \"orca: Orca is still setting up your GitHub identity in this sandbox, so it stopped \\`git $sub\\` rather than use the wrong identity. Try again in a few seconds. If this keeps happening, restart this workspace (right-click it in the sidebar > Restart).\" >&2\n fi\n exit 1\n}\n# A commit under the workspace identity (Orca ) says once per session how to use your own\n# (design-squad). /dev/shm is per boot: a wake or restart says it again.\nnudge_once() {\n [ \"$sub\" = commit ] || return 0\n local mark=\"${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)\"\n [ -e \"$mark\" ] && return 0\n : >\"$mark\" 2>/dev/null || return 0\n printf '%s\\n' \"orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself.\" >&2\n}\n# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's\n# connected GitHub nor the App installation) must never fall through to git's own \"Username for\n# 'https://github.com':\" prompt. Prompts are off for that remote, and git's auth failure becomes one\n# plain line saying what to do.\ngithub_slug=''\ngithub_remote_slug() {\n local arg skip=0 seen=0 remote='' url\n for arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n if [ \"$seen\" = 0 ]; then\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n \"$sub\") seen=1 ;;\n esac\n continue\n fi\n case \"$arg\" in\n --repo=*) remote=\"${arg#--repo=}\"; break ;;\n -o | --push-option | --receive-pack | --upload-pack | --exec | --depth | --deepen | --shallow-since | --shallow-exclude | --refmap | --recurse-submodules-default | -j | --jobs) skip=1 ;;\n -*) ;;\n *) remote=\"$arg\"; break ;;\n esac\n done\n [ -n \"$remote\" ] || remote=\"$(\"$real\" config --get \"branch.$(\"$real\" symbolic-ref --short -q HEAD 2>/dev/null).remote\" 2>/dev/null || true)\"\n [ -n \"$remote\" ] || remote=origin\n case \"$remote\" in\n *://*) url=\"$remote\" ;;\n *) url=\"$(\"$real\" remote get-url \"$remote\" 2>/dev/null || printf '%s' \"$remote\")\" ;;\n esac\n case \"$url\" in\n https://github.com/* | https://*@github.com/*) url=\"${url#*github.com/}\" ;;\n *) return 0 ;;\n esac\n url=\"${url%.git}\"\n url=\"${url%/}\"\n case \"$url\" in */*/*) url=\"${url%%/*}/$(printf '%s' \"${url#*/}\" | cut -d/ -f1)\" ;; esac\n case \"$url\" in [A-Za-z0-9_.-]*/[A-Za-z0-9_.-]*) github_slug=\"$url\" ;; esac\n}\nno_access_line() {\n local owner=\"${github_slug%%/*}\" verb='push to'\n [ \"$sub\" = push ] || verb='read'\n printf '%s\\n' \"orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect your GitHub in Settings → Account.\" >&2\n}\n# GitHub's \"not found\" is a typo'd name or a private repo it won't confirm: say which half fits whom.\nnot_found_line() {\n printf '%s\\n' \"orca: Orca Cloud can't find $github_slug. Check the name, or install the Orca GitHub App on ${github_slug%%/*} if it's private.\" >&2\n}\n# orca-git-as's own fallback line is replaced by the nudge; GitHub auth failures by the plain line.\nfallback_filter() {\n local line said=0\n while IFS= read -r line || [ -n \"$line\" ]; do\n case \"$line\" in\n 'orca-git-as: no teammate identity'*) nudge_once ;;\n 'remote: Repository not found.'* | \"fatal: repository 'https://github.com/\"*\"' not found\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || not_found_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *\"could not read Username for 'https://github.com'\"* | *\"could not read Password for 'https://\"*\"github.com'\"* | \\\n *\"Authentication failed for 'https://github.com/\"* | 'remote: Permission to '*' denied to '* | \\\n *\"The requested URL returned error: 403\"*)\n if [ -n \"$github_slug\" ]; then\n [ \"$said\" = 1 ] || no_access_line\n said=1\n else\n printf '%s\\n' \"$line\"\n fi\n ;;\n *) printf '%s\\n' \"$line\" ;;\n esac\n done\n}\ncase \"$sub\" in\n push | pull | fetch)\n github_remote_slug \"$@\"\n if [ -n \"$github_slug\" ]; then\n export GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=never\n fi\n ;;\nesac\ngit_as=\"${ORCA_GIT_AS:-/opt/orca/bin/orca-git-as}\"\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n hold_for_member_setup\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 \"$git_as\" ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec \"$git_as\" \"$@\" 2> >(fallback_filter >&2)\n fi\n # No terminal or agent turn to attribute it to: the workspace identity.\n nudge_once\n ;;\nesac\nif [ -n \"$github_slug\" ]; then\n exec \"$real\" \"$@\" 2> >(fallback_filter >&2)\nfi\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPTS_HASH: string = "6e35ca58" +export const VM_SCRIPTS_STAMP: number = 1794567472 export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n # The stamp must describe this commit's scripts, never the Worker's: a commit from before stamps\n # leaves it unset (the image then reads as stamp 0).\n unset ORCA_VM_SCRIPTS_STAMP\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" -export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\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\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\ntake_secrets\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /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\" \"$OUT/.scan-since\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" +export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus\n# ORCA_BUILD_SECRET_NAMES (space list of the team secrets the environment names; each value rides in\n# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).\n# `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.\n# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.\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\"\n\n# SEC-2: the snapshot of this VM is the team's saved environment, booted by every member's workspace,\n# so a secret's value must never be in it. Secrets are for the install script alone: take_secrets\n# moves them out of this script's environment (clones and Orca's own steps never see them), the\n# install step hands them to that one child, and scan_secrets searches the disk before the build\n# may succeed.\nsecret_names=()\nsecret_values=()\ntake_secrets() {\n local name\n for name in ${ORCA_BUILD_SECRET_NAMES:-}; do\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n [ -n \"${!name:-}\" ] || continue\n secret_names+=(\"$name\")\n secret_values+=(\"${!name}\")\n unset \"$name\"\n done\n unset ORCA_BUILD_SECRET_NAMES\n # Only a file that changes after this marker can hold a value: the base image never saw one.\n : >\"$OUT/.scan-since\"\n}\n\n# Fails (non-zero) when a secret's value is in a file the build created or changed, anywhere on the\n# disk the snapshot captures. Plain text only: a value the script encoded, encrypted or compressed is\n# not found, and neither is one shorter than 8 characters (it would match ordinary text). A search\n# that cannot run fails too. Prints names and paths, never a value.\n# ORCA_SCAN_ROOT: tests only (a scratch tree); the control plane never sets it.\nscan_secrets() {\n [ \"${#secret_names[@]}\" -gt 0 ] || return 0\n local root=\"${ORCA_SCAN_ROOT:-/}\" i line pattern hit named=0\n local names=() patterns=() args=() newer=() sudo=()\n for i in \"${!secret_names[@]}\"; do\n # grep -F reads a newline as \"or\": a multi-line value (a PEM key) is searched by its longest line.\n pattern=\"\"\n while IFS= read -r line; do\n case \"$line\" in -----*) continue ;; esac\n if [ \"${#line}\" -gt \"${#pattern}\" ]; then pattern=\"$line\"; fi\n done < <(printf '%s\\n' \"${secret_values[$i]}\") # a pipe, not a here-string temp file\n [ \"${#pattern}\" -ge 8 ] || continue\n names+=(\"${secret_names[$i]}\")\n patterns+=(\"$pattern\")\n args+=(-e \"$pattern\")\n done\n [ \"${#patterns[@]}\" -gt 0 ] || return 0\n if ! command -v find >/dev/null 2>&1 || ! command -v grep >/dev/null 2>&1 || ! command -v xargs >/dev/null 2>&1; then\n echo \"::orca-error:: Orca couldn’t check the build for secrets, so the environment wasn’t saved.\"\n return 1\n fi\n # Root-owned files count too (`sudo npm config set` writes /root/.npmrc).\n if sudo -n true 2>/dev/null; then sudo=(sudo -n); fi\n # A missing marker (the install script removed it) means every file is searched.\n if [ -f \"$OUT/.scan-since\" ]; then newer=(-cnewer \"$OUT/.scan-since\"); fi\n changed_files() {\n ${sudo[@]+\"${sudo[@]}\"} find \"$root\" \\( -path /proc -o -path /sys -o -path /dev -o -path /run \\) -prune \\\n -o -type f ${newer[@]+\"${newer[@]}\"} -print0 2>/dev/null\n }\n # One pass for every value; the per-secret passes only run on a build that is about to fail.\n if [ -z \"$(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF \"${args[@]}\" -- 2>/dev/null | head -n 1)\" ]; then\n return 0\n fi\n for i in \"${!names[@]}\"; do\n while IFS= read -r hit; do\n [ -n \"$hit\" ] || continue\n named=1\n echo \"::orca-error:: ${names[$i]} was left in $hit. Saved environments are shared with your team, so remove it before the install script ends.\"\n done < <(changed_files | ${sudo[@]+\"${sudo[@]}\"} xargs -0 grep -lsF -e \"${patterns[$i]}\" -- 2>/dev/null | head -n 5)\n done\n if [ \"$named\" -eq 0 ]; then\n # The file moved between the two passes: still a build that held a value on disk.\n echo \"::orca-error:: The install script left a secret on disk, so the environment wasn’t saved. Remove it before the script ends, then save again.\"\n fi\n return 1\n}\n\n# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the\n# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps\n# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date\n# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.\n# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.\n# ORCA_AUTO_INSTALL_TIMEOUT: tests only.\nauto_install() {\n local dir=\"$1\" pm=\"\" declared=\"\" rc=0 started f\n local cmd=() others=()\n for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do\n [ -f \"$dir/$f\" ] && others+=(\"$f\")\n done\n if [ -f \"$dir/package.json\" ]; then\n # package.json's packageManager (\"pnpm@9.1.0\") wins over the lockfile guess.\n declared=$(sed -n 's/.*\"packageManager\"[[:space:]]*:[[:space:]]*\"\\([a-z]*\\)@.*/\\1/p' \"$dir/package.json\" | head -n 1)\n case \"$declared\" in\n pnpm | yarn | npm) pm=\"$declared\" ;;\n *)\n if [ -f \"$dir/pnpm-lock.yaml\" ]; then pm=pnpm\n elif [ -f \"$dir/yarn.lock\" ]; then pm=yarn\n elif [ -f \"$dir/package-lock.json\" ] || [ -f \"$dir/npm-shrinkwrap.json\" ]; then pm=npm\n fi\n ;;\n esac\n fi\n if [ \"${#others[@]}\" -gt 0 ]; then\n echo \"Not installed automatically: ${others[*]}. Add an install script to the environment to install these.\"\n fi\n if [ -z \"$pm\" ]; then\n [ \"${#others[@]}\" -gt 0 ] || echo \"No lockfile found; the build keeps the cloned repos.\"\n return 0\n fi\n # Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).\n case \"$pm\" in\n pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;\n yarn)\n if [ -f \"$dir/.yarnrc.yml\" ]; then cmd=(corepack yarn install --immutable)\n else cmd=(corepack yarn install --frozen-lockfile)\n fi\n ;;\n npm) cmd=(npm ci) ;;\n esac\n echo \"Installing dependencies automatically: ${cmd[*]}\"\n started=$(date +%s)\n (cd \"$dir\" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout \"${ORCA_AUTO_INSTALL_TIMEOUT:-900}\" \"${cmd[@]}\") /dev/null || true\n return 0\n fi\n echo \"Installed dependencies in $(($(date +%s) - started))s.\"\n}\n\ntake_secrets\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n for name in ${ORCA_BUILD_WITHHELD_SECRETS:-}; do\n echo \"$name is a model key, so environment builds don’t get it. Agents in workspaces still do.\"\n done\n (\n cd \"${first:-$ROOT}\" || exit 1\n if [ \"${#secret_names[@]}\" -gt 0 ]; then\n for i in \"${!secret_names[@]}\"; do export \"${secret_names[$i]}=${secret_values[$i]}\"; done\n fi\n exec bash -euo pipefail \"$OUT/install.sh\"\n ) /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\" \"$OUT/.scan-since\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\n\n# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target\n# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have\n# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.\nupdate_repo() {\n local base target status\n base=\"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\"\n target=\"${ref:-$base}\"\n [ -n \"$target\" ] || return 0\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$target:refs/remotes/origin/$target\"\n status=$?\n if [ \"$status\" -eq 0 ]; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$target\" --\n return $?\n fi\n [ \"$status\" -eq 124 ] && return 124\n { [ -n \"$base\" ] && [ \"$base\" != \"$target\" ]; } || return \"$status\"\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$base:refs/remotes/origin/$base\" || return $?\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$base\" --\n}\n\n# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command\n# returns while it runs; $CLONE_DIR/state reads running, then done or \"failed \".\nrun_detached() {\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n export -f clone_repo update_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\" ORCA_PRELUDE_STEP=\"$1\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n \"$ORCA_PRELUDE_STEP\" >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n elif [ \"$ORCA_PRELUDE_STEP\" = update_repo ]; then\n # Not fatal: the build'\"'\"'s checkout is there, just older. The status says so; the create goes on.\n echo \"done stale\" >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n # The desktop shows this as \"Update repository\" (GET /v1/sandboxes/:id/clone): fetch what changed\n # since the build, in the background. A failure leaves the build's commit, which still opens.\n mkdir -p \"$CLONE_DIR\"\n run_detached update_repo\n elif [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n run_detached clone_repo\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='noreply@orca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\n\n# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target\n# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have\n# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.\nupdate_repo() {\n local base target status\n base=\"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\"\n target=\"${ref:-$base}\"\n [ -n \"$target\" ] || return 0\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$target:refs/remotes/origin/$target\"\n status=$?\n if [ \"$status\" -eq 0 ]; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$target\" --\n return $?\n fi\n [ \"$status\" -eq 124 ] && return 124\n { [ -n \"$base\" ] && [ \"$base\" != \"$target\" ]; } || return \"$status\"\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$base:refs/remotes/origin/$base\" || return $?\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$base\" --\n}\n\n# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command\n# returns while it runs; $CLONE_DIR/state reads running, then done or \"failed \".\nrun_detached() {\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n export -f clone_repo update_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\" ORCA_PRELUDE_STEP=\"$1\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n \"$ORCA_PRELUDE_STEP\" >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n elif [ \"$ORCA_PRELUDE_STEP\" = update_repo ]; then\n # Not fatal: the build'\"'\"'s checkout is there, just older. The status says so; the create goes on.\n echo \"done stale\" >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n # The desktop shows this as \"Update repository\" (GET /v1/sandboxes/:id/clone): fetch what changed\n # since the build, in the background. A failure leaves the build's commit, which still opens.\n mkdir -p \"$CLONE_DIR\"\n run_detached update_repo\n elif [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n run_detached clone_repo\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/git b/cloud/apps/sandbox-control/image/vm/git index bba55f41db4..ce5630e4ee5 100755 --- a/cloud/apps/sandbox-control/image/vm/git +++ b/cloud/apps/sandbox-control/image/vm/git @@ -41,14 +41,14 @@ hold_for_member_setup() { fi exit 1 } -# A commit under the workspace identity (Orca Cloud's name) says once per session how to use your own +# A commit under the workspace identity (Orca ) says once per session how to use your own # (design-squad). /dev/shm is per boot: a wake or restart says it again. nudge_once() { [ "$sub" = commit ] || return 0 local mark="${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)" [ -e "$mark" ] && return 0 : >"$mark" 2>/dev/null || return 0 - printf '%s\n' "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours." >&2 + printf '%s\n' "orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself." >&2 } # PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's # connected GitHub nor the App installation) must never fall through to git's own "Username for diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members index eaf9e209eb7..c80dd27dc65 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-members +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-members @@ -54,9 +54,9 @@ user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)" # 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.orca.dev' + || sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email 'noreply@orca.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' + || sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name 'Orca' fi # CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot. if [ -n "$user_home" ] && [ -d "$user_home/.orca-sandbox" ]; then diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index c5922a9941e..b8524d3825c 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -119,11 +119,16 @@ if [ -n "${ORCA_GIT_EXTRAHEADER:-}" ]; then 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. -# The fallback moved to orca.dev with the domain; a workspace still on the old default follows it. -[ "$(git config --global user.email 2>/dev/null || true)" = 'cloud@users.noreply.onorca.dev' ] \ - && git config --global user.email 'cloud@users.noreply.orca.dev' -git config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.orca.dev' -git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud' +# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it. +case "$(git config --global user.email 2>/dev/null || true)" in + cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev) + git config --global user.email 'noreply@orca.dev' ;; +esac +git config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev' +# The fallback name is "Orca" (DOMAIN-1); a workspace still on the earlier default follows it. +[ "$(git config --global user.name 2>/dev/null || true)" = 'Orca Cloud' ] \ + && git config --global user.name 'Orca' +git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca' # 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/0055_workspace_follows.sql b/cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql new file mode 100644 index 00000000000..21cb02d977f --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql @@ -0,0 +1,12 @@ +-- PARITY-FOLLOW: a member follows a teammate's workspace to keep it in their sidebar's Following +-- section; everyone who can see the workspace sees its followers. One row per member per +-- workspace. Rows go with the workspace (destroy) and with the member (removal); a follower who can +-- no longer see the workspace (it turned private) is left out of every read. +CREATE TABLE IF NOT EXISTS workspace_follows ( + sandbox_id TEXT NOT NULL, + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (sandbox_id, user_id) +); +CREATE INDEX IF NOT EXISTS workspace_follows_member ON workspace_follows (account_id, user_id); diff --git a/cloud/apps/sandbox-control/migrations/0056_agent_credential_suspect.sql b/cloud/apps/sandbox-control/migrations/0056_agent_credential_suspect.sql new file mode 100644 index 00000000000..e7a8a627b2d --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0056_agent_credential_suspect.sql @@ -0,0 +1,5 @@ +-- RS-2: a failed auth check (count_tokens) alone no longer revokes an Orca-account sign-in. It marks the +-- sign-in "needs check" (suspect_at); the credential stays usable at egress so the next real agent request +-- can confirm it: a later 401 revokes, a success clears it. Never tested against a real OAuth token, so the +-- probe is a signal, not a verdict (agent-credential-checks.ts). +ALTER TABLE agent_credentials ADD COLUMN suspect_at INTEGER; diff --git a/cloud/apps/sandbox-control/src/agent-credential-checks.ts b/cloud/apps/sandbox-control/src/agent-credential-checks.ts index 2ea5948610d..08f7d6cd50a 100644 --- a/cloud/apps/sandbox-control/src/agent-credential-checks.ts +++ b/cloud/apps/sandbox-control/src/agent-credential-checks.ts @@ -1,12 +1,20 @@ // A provider 401 on an Orca-account request (the proxy swapped the real credential in) is a signal, not a -// verdict: one transient auth error must not sign a person out of every workspace. Before revoking, the -// control plane makes one cheap server-side auth check with the real credential (no tokens spent) and -// revokes only when that also says the credential is dead. The desktop can ask for the same check before a +// verdict: one transient auth error must not sign a person out of every workspace. The control plane makes +// one cheap server-side auth check with the real credential (no tokens spent). RS-2: that check alone never +// revokes either (it has never been tried against a real OAuth sign-in): a failed check marks the sign-in +// "needs check" (suspect), which stays usable at egress; a LATER real agent request that also gets a 401 +// revokes it, and a real request that succeeds (or a passing check) clears it. The desktop can ask for the same check before a // launch (POST /v1/agent-credentials/claude/verify). Checks are rate-limited per person and agent // (agent_credentials.checked_at), passes are remembered (verified_at), and every keep or revoke is audited // (agent_credential_audit). import type { AccountProvider } from './account-providers' -import { markAgentCredentialRevoked, readUsableAgentCredential } from './agent-credentials' +import { + agentCredentialSuspectAt, + clearAgentCredentialSuspect, + markAgentCredentialRevoked, + markAgentCredentialSuspect, + readUsableAgentCredential +} from './agent-credentials' import type { Keyring } from './secrets-crypto' /** At most one auth check (and so one revoke) per person and agent per minute. */ @@ -15,7 +23,7 @@ export const CREDENTIAL_CHECK_INTERVAL_MS = 60_000 export const CREDENTIAL_VERIFIED_FRESH_MS = 10 * 60_000 export type CredentialVerdict = 'valid' | 'invalid' | 'unknown' -export type CheckOutcome = 'revoked' | 'kept' | 'skipped' +export type CheckOutcome = 'revoked' | 'suspect' | 'kept' | 'skipped' type CheckContext = { db: D1Database @@ -28,7 +36,7 @@ type CheckContext = { async function audit( db: D1Database, - entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number } + entry: { userId: string; agent: string; action: 'revoked' | 'suspect' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number } ): Promise { await db .prepare( @@ -74,6 +82,8 @@ async function checkCredential( const base = { userId, agent, now, ...where } if (verdict === 'valid') { await db.prepare(`UPDATE agent_credentials SET verified_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run() + // A passing check clears "needs check". + await clearAgentCredentialSuspect(db, userId, agent, now) } if (verdict !== 'invalid') { // A pass on a pre-launch verify is routine; a 401 that didn't hold up, or any inconclusive check, is audited. @@ -83,21 +93,67 @@ async function checkCredential( } return 'kept' } - await markAgentCredentialRevoked(db, userId, agent, now) + // RS-2: the check's auth failure alone never revokes: the sign-in needs a real request to confirm it. + await markAgentCredentialSuspect(db, userId, agent, now) await audit(db, { ...base, - action: 'revoked', - reason: trigger.kind === 'verify' ? 'verify_confirmed_auth_failure' : 'provider_401_confirmed_by_check' + action: 'suspect', + reason: trigger.kind === 'verify' ? 'verify_check_auth_failure' : 'provider_401_check_auth_failure' }) - return 'revoked' + return 'suspect' } -export function handleAccountUnauthorized( +/** + * A real agent request got a 401 with the real credential swapped in. A sign-in already in question (a + * check failed after an EARLIER 401) is now confirmed dead: revoked. Otherwise one rate-limited check, which + * at most puts it in question. + */ +export async function handleAccountUnauthorized( ctx: CheckContext & { sandboxId: string; path: string } ): Promise { + // The 401 that triggered the failed check was consumed by that check, so any 401 seen here, with the + // sign-in already in question, is a different, later real request. + const suspectAt = await agentCredentialSuspectAt(ctx.db, ctx.userId, ctx.provider.agent) + if (suspectAt !== null) { + await markAgentCredentialRevoked(ctx.db, ctx.userId, ctx.provider.agent, ctx.now) + await audit(ctx.db, { + userId: ctx.userId, + agent: ctx.provider.agent, + action: 'revoked', + reason: 'provider_401_after_check_failure', + sandboxId: ctx.sandboxId, + path: ctx.path, + now: ctx.now + }) + return 'revoked' + } return checkCredential(ctx, { kind: 'egress_401', sandboxId: ctx.sandboxId, path: ctx.path }) } +/** RS-2: a real agent request with the real credential succeeded: a sign-in in question is fine after all. */ +export async function handleAccountRequestSucceeded(ctx: { + db: D1Database + agent: AccountProvider['agent'] + userId: string + sandboxId: string + path: string + now: number +}): Promise { + const cleared = await clearAgentCredentialSuspect(ctx.db, ctx.userId, ctx.agent, ctx.now) + if (cleared) { + await audit(ctx.db, { + userId: ctx.userId, + agent: ctx.agent, + action: 'kept', + reason: 'request_succeeded_after_check_failure', + sandboxId: ctx.sandboxId, + path: ctx.path, + now: ctx.now + }) + } + return cleared +} + /** * Pre-launch verify: a pass within CREDENTIAL_VERIFIED_FRESH_MS answers at once; otherwise one check (rate * limited). Returns what happened; the caller re-reads the state. diff --git a/cloud/apps/sandbox-control/src/agent-credentials.ts b/cloud/apps/sandbox-control/src/agent-credentials.ts index 182369da3bf..6abcb744ddf 100644 --- a/cloud/apps/sandbox-control/src/agent-credentials.ts +++ b/cloud/apps/sandbox-control/src/agent-credentials.ts @@ -12,7 +12,11 @@ import type { SandboxCaller } from './auth' import type { Env } from './env' import type { Keyring, SecretBinding } from './secrets-crypto' -export type CredentialState = 'none' | 'active' | 'expiring' | 'expired' | 'revoked' +/** + * 'suspect' (RS-2): an auth check failed but no real request has confirmed it yet. Still usable at egress; + * shown to the desktop as expired + needsCheck (an older desktop reads a new state as 'none'). + */ +export type CredentialState = 'none' | 'active' | 'expiring' | 'expired' | 'revoked' | 'suspect' const EXPIRING_MS = 30 * 24 * 60 * 60_000 /** `claude setup-token` issues a one-year token. */ const CLAUDE_SETUP_TOKEN_TTL_MS = 365 * 24 * 60 * 60_000 @@ -27,6 +31,8 @@ type CredentialRow = { label: string | null expires_at: number | null state: 'active' | 'revoked' + /** RS-2: when an auth check said this sign-in is dead; null when not in question. */ + suspect_at?: number | null updated_at: number } @@ -73,15 +79,18 @@ export function credentialState(row: Pick if (row.expires_at !== null && row.expires_at <= now) { return 'expired' } + if (row.suspect_at !== null && row.suspect_at !== undefined) { + return 'suspect' + } if (row.expires_at !== null && row.expires_at - now <= EXPIRING_MS) { return 'expiring' } return 'active' } -/** Usable for a request now: active or expiring (still valid). */ +/** Usable for a request now: active or expiring (still valid), or suspect (a real request must confirm it). */ export function isUsable(state: CredentialState): boolean { - return state === 'active' || state === 'expiring' + return state === 'active' || state === 'expiring' || state === 'suspect' } async function rowFor(db: D1Database, userId: string, agent: CredentialAgent): Promise { @@ -106,7 +115,7 @@ export async function putAgentCredential( ON CONFLICT (user_id, agent) DO UPDATE SET account_id = excluded.account_id, kek_id = excluded.kek_id, wrapped_dek = excluded.wrapped_dek, ciphertext = excluded.ciphertext, label = excluded.label, expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at, - checked_at = NULL, verified_at = NULL` + checked_at = NULL, verified_at = NULL, suspect_at = NULL` ) .bind(input.userId, input.accountId, input.agent, sealed.kekId, sealed.wrappedDek, sealed.ciphertext, input.label ?? null, input.expiresAt ?? null, now, now) .run() @@ -114,21 +123,61 @@ export async function putAgentCredential( /** The real value for egress, or null when there is none or it can't be used now. */ export async function readUsableAgentCredential(db: D1Database, keyring: Keyring, userId: string, agent: CredentialAgent, now: number): Promise { + return (await readUsableAgentCredentialState(db, keyring, userId, agent, now)).value +} + +/** The real value for egress, and whether the sign-in is in question (RS-2: a real request confirms it). */ +export async function readUsableAgentCredentialState( + db: D1Database, + keyring: Keyring, + userId: string, + agent: CredentialAgent, + now: number +): Promise<{ value: string | null; suspect: boolean }> { const row = await rowFor(db, userId, agent) - if (!isUsable(credentialState(row, now)) || !row) { - return null + const state = credentialState(row, now) + if (!isUsable(state) || !row) { + return { value: null, suspect: false } } try { - return await keyring.open(credentialBinding(userId, agent), { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext }) + const value = await keyring.open(credentialBinding(userId, agent), { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext }) + return { value, suspect: state === 'suspect' } } catch { console.log(JSON.stringify({ event: 'agent_credential_unreadable', agent })) - return null + return { value: null, suspect: false } } } +/** RS-2: an auth check failed. Not revoked: a real request must confirm it first. True when newly marked. */ +export async function markAgentCredentialSuspect(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise { + const result = await db + .prepare(`UPDATE agent_credentials SET suspect_at = ?, updated_at = ? WHERE user_id = ? AND agent = ? AND state = 'active' AND suspect_at IS NULL`) + .bind(now, now, userId, agent) + .run() + return result.meta.changes === 1 +} + +/** RS-2: a real request (or an auth check) succeeded: the sign-in is fine. True when it was in question. */ +export async function clearAgentCredentialSuspect(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise { + const result = await db + .prepare(`UPDATE agent_credentials SET suspect_at = NULL, updated_at = ? WHERE user_id = ? AND agent = ? AND suspect_at IS NOT NULL`) + .bind(now, userId, agent) + .run() + return result.meta.changes === 1 +} + +/** RS-2: when this sign-in was put in question, or null. */ +export async function agentCredentialSuspectAt(db: D1Database, userId: string, agent: CredentialAgent): Promise { + const row = await db + .prepare(`SELECT suspect_at FROM agent_credentials WHERE user_id = ? AND agent = ? AND state = 'active'`) + .bind(userId, agent) + .first<{ suspect_at: number | null }>() + return row?.suspect_at ?? null +} + /** The provider said the credential is no longer valid (401 at egress): stop using it until renewed. */ export async function markAgentCredentialRevoked(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise { - await db.prepare(`UPDATE agent_credentials SET state = 'revoked', updated_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run() + await db.prepare(`UPDATE agent_credentials SET state = 'revoked', suspect_at = NULL, updated_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run() } export async function deleteAgentCredential(db: D1Database, userId: string, agent: CredentialAgent): Promise { @@ -141,11 +190,19 @@ export async function agentCredentialsView(db: D1Database, env: Env, userId: str const view = (agent: CredentialAgent) => { const row = results.find((r) => r.agent === agent) ?? null const state = credentialState(row, now) - return { state, ...(row?.label ? { label: row.label } : {}), ...(row?.expires_at ? { expiresAt: row.expires_at } : {}) } + // RS-2: "needs check" reads as expired (the Renew strip) on every desktop, old ones included; newer + // desktops may read needsCheck. An unknown state would read as 'none' ("isn't set up") on old ones. + const wire = state === 'suspect' ? { state: 'expired' as const, needsCheck: true } : { state } + // RS-5: credentials saved before the fix carry an email or the Orca name; Claude's always reads true. + const label = agent === 'claude' && row ? CLAUDE_CREDENTIAL_LABEL : row?.label + return { ...wire, ...(label ? { label } : {}), ...(row?.expires_at ? { expiresAt: row.expires_at } : {}) } } return { claude: view('claude'), codex: view('codex'), providerEnabled: providerEnabled(env), providerState: providerStates(env) } } +/** RS-5: what a stored Claude credential is called (the approved account itself can't be known). */ +export const CLAUDE_CREDENTIAL_LABEL = 'Claude subscription' + // A Claude setup-token: `sk-ant-oat01-` then URL-safe characters. Shape-checked, never logged. const CLAUDE_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,500}$/ export const PutClaudeSchema = z @@ -173,7 +230,10 @@ export async function putClaudeCredential(db: D1Database, keyring: Keyring, env: accountId: caller.accountId, agent: 'claude', value: token, - label: body.label?.trim() || caller.name || null, + // RS-5 (design-squad): a true label only. Neither this computer's Claude Code email nor the Orca + // name says which account approved the setup-token (it prints no email, and its inference-only + // scope can't read the profile), so a Claude credential is always "Claude subscription". + label: CLAUDE_CREDENTIAL_LABEL, expiresAt: Math.min(body.expiresAt ?? now + CLAUDE_SETUP_TOKEN_TTL_MS, now + CLAUDE_SETUP_TOKEN_TTL_MS) }, now diff --git a/cloud/apps/sandbox-control/src/api/vm-agent.ts b/cloud/apps/sandbox-control/src/api/vm-agent.ts index d74e1b3bf25..2a13ab1d393 100644 --- a/cloud/apps/sandbox-control/src/api/vm-agent.ts +++ b/cloud/apps/sandbox-control/src/api/vm-agent.ts @@ -23,7 +23,7 @@ if [ ! -x "$O" ]; then echo '{"ok":false,"error":{"code":"orca_cli_missing"}}'; cd "$P" 2>/dev/null || cd "$HOME" if [ "$1" = "--prepare" ]; then shift - [ -d "$P/.git" ] || { git -C "$P" init -q && git -C "$P" -c user.name=Orca -c user.email=cloud@onorca.dev commit -q --allow-empty -m init; } >/dev/null 2>&1 || true + [ -d "$P/.git" ] || { git -C "$P" init -q && git -C "$P" -c user.name=Orca -c user.email=noreply@orca.dev commit -q --allow-empty -m init; } >/dev/null 2>&1 || true "$O" repo add --path "$P" --json >/dev/null 2>&1 || true C="$HOME/.claude.json" if command -v jq >/dev/null 2>&1; then diff --git a/cloud/apps/sandbox-control/src/auth.ts b/cloud/apps/sandbox-control/src/auth.ts index a0fed6fa3ae..cd653b5b2ed 100644 --- a/cloud/apps/sandbox-control/src/auth.ts +++ b/cloud/apps/sandbox-control/src/auth.ts @@ -97,10 +97,22 @@ export function accountIdFor(claims: { sub: string; org?: string }): string { return claims.org ? `org:${claims.org}` : `user:${claims.sub}` } +/** + * A comma-separated issuer var as jwtVerify's `issuer` option: the token's `iss` must equal one entry. + * Unset or empty: no issuer check (as before lists). Blank entries are ignored; a value with no + * entries left accepts no issuer. + */ +export function issuerList(value: string | undefined): string[] | undefined { + if (!value) { + return undefined + } + return value.split(',').map((issuer) => issuer.trim()).filter(Boolean) +} + let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null /** Staging auth's keys and issuer; never honored in prod. Same accounts as billing dev (it trusts staging too). */ -function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | null { +function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null { const source = env.SANDBOX_STAGING_JWKS_URL ?? (env.SANDBOX_STAGING_JWKS ? `inline:${env.SANDBOX_STAGING_JWKS}` : null) if (env.SANDBOX_ENV === 'prod' || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) { return null @@ -113,7 +125,7 @@ function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | n : createLocalJWKSet(JSON.parse(env.SANDBOX_STAGING_JWKS ?? '{"keys":[]}') as JSONWebKeySet) } } - return { keys: stagingKeys.keys, issuer: env.SANDBOX_STAGING_AUTH_ISSUER } + return { keys: stagingKeys.keys, issuer: issuerList(env.SANDBOX_STAGING_AUTH_ISSUER) } } /** Dev-only operator keys (issuer DEV_TEST_ISSUER) so live tests run before Orca auth mints sandbox tokens. */ @@ -124,7 +136,7 @@ async function verify( token: string, keys: JWTVerifyGetKey, env: Env, - issuer: string | undefined, + issuer: string | string[] | undefined, now: number ): Promise { try { @@ -163,7 +175,7 @@ export async function authenticateDesktop( } const staging = stagingKeysFor(env) const caller = - (await verify(token, keysFor(env), env, env.SANDBOX_AUTH_ISSUER, now)) ?? + (await verify(token, keysFor(env), env, issuerList(env.SANDBOX_AUTH_ISSUER), now)) ?? (staging ? await verify(token, staging.keys, env, staging.issuer, now) : null) if (caller || !env.SANDBOX_DEV_JWKS || env.SANDBOX_ENV === 'prod') { if (!caller || (await tokenPredatesRemoval(env.SANDBOX_DB, caller))) { diff --git a/cloud/apps/sandbox-control/src/auto-environments.ts b/cloud/apps/sandbox-control/src/auto-environments.ts index 76476b97ab5..e13fa604ff4 100644 --- a/cloud/apps/sandbox-control/src/auto-environments.ts +++ b/cloud/apps/sandbox-control/src/auto-environments.ts @@ -1,8 +1,8 @@ // Automatic environments: Conductor-style "the repo is already there". An environment build (golden + // the repo checked out, snapshotted) is opt-in for admins; without one every create of a repo cloned it // from scratch (stablyai/orca: ~55 s). So the first create of a repo that no environment of the account -// lists makes a default environment for it (just the repo, blobless, no install script) and builds it in -// the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and +// lists makes a default environment for it (the repo, blobless, plus its lockfile's JavaScript +// dependencies; no install script) and builds it in the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and // only fetch what changed. Scoped per account like every environment; the usual golden refresh keeps // it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited // it (that makes it an ordinary 'org' environment). @@ -38,7 +38,9 @@ function autoConfig(environment: EnvironmentRow): BuildConfig { envVarNames: [], machineSize: environment.machine_size, // History and trees only: a smaller snapshot and a faster build; file contents load on demand. - cloneFilter: 'blob:none' + cloneFilter: 'blob:none', + // Dependencies from the lockfile, so creates start warm (PARITY-AUTO-ENV-DEPS); soft on failure. + autoInstall: true } } diff --git a/cloud/apps/sandbox-control/src/codex-credentials.ts b/cloud/apps/sandbox-control/src/codex-credentials.ts index 82f9d06bc8a..06fcc044918 100644 --- a/cloud/apps/sandbox-control/src/codex-credentials.ts +++ b/cloud/apps/sandbox-control/src/codex-credentials.ts @@ -174,6 +174,18 @@ export const codexAccount: AccountProvider = { log('codex_token_unauthorized', { userId }) waitUntil(refreshCodexCredential({ db, keyring, now: () => now }, userId)) }, + // RS-4: a request still carrying this sandbox's placeholder once the account no longer applies gets a + // message saying what to do, not a bare proxy 403. Still a 403, never a 401: on a 401 from chatgpt.com + // Codex runs its own token refresh (against auth.openai.com, with a placeholder refresh token) and + // retries, so a 401 would only cost refresh attempts. On any other status Codex prints + // `unexpected status : `, so the body is the message, in ChatGPT's own error shape. + signedOut: { + status: 403, + contentType: 'application/json', + body: JSON.stringify({ + detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.' + }) + }, credential: async (db, keyring, userId, now) => { const value = await readUsableAgentCredential(db, keyring, userId, 'codex', now) const tokens = value ? parseStoredCodex(value) : null diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index b1881c50e92..373bc65b426 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -46,6 +46,7 @@ export type Env = { // SANDBOX_JWKS (inline set) is for local dev and tests only. SANDBOX_JWKS_URL?: string SANDBOX_JWKS?: string + /** Accepted `iss` values, comma-separated (a single issuer is a one-item list). */ SANDBOX_AUTH_ISSUER?: string SANDBOX_JWT_AUDIENCE: string /** Dev-only operator key set (issuer `orca-sandbox-dev-test`); ignored when SANDBOX_ENV=prod. */ @@ -194,6 +195,8 @@ export type Env = { PUBLIC_API_URL?: string /** Comma list of extra egress hosts every VM may reach (dev: this Worker's workers.dev host). */ EGRESS_EXTRA_HOSTS?: string + /** Comma list of Orca platform egress hosts every VM may reach (default `*.onorca.dev`). */ + ORCA_PLATFORM_HOST_SUFFIXES?: string /** Workspace sandbox egress preset: `open` (default, any host) or `limited` (fail-closed allowlist). */ SANDBOX_EGRESS_PRESET?: string /** GitHub App webhook secret (secret): verifies X-Hub-Signature-256 on /v1/github/webhook. */ diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index cd2d76ff033..e9d28f79ca5 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -94,6 +94,11 @@ export type BuildConfig = { machineSize: MachineSize /** `git clone --filter`: automatic environments clone blobless (auto-environments.ts). */ cloneFilter?: 'blob:none' + /** + * Automatic environments only, with no install script: install the first repo's JavaScript + * dependencies from its lockfile, never failing the build (environment-build.sh auto_install). + */ + autoInstall?: boolean } export type BuildResult = { @@ -101,6 +106,35 @@ export type BuildResult = { repos?: { url: string; dir: string; branch: string; commit: string; lockfiles: Record }[] diskUsedBytes?: number diskTotalBytes?: number + /** AUTO-ENV-DEPS-LABEL: what an automatic environment's lockfile install did (read from its log). */ + autoInstall?: AutoInstallOutcome +} + +export type AutoInstallOutcome = { manager: 'pnpm' | 'yarn' | 'npm'; outcome: 'installed' | 'skipped' } + +/** + * The automatic install's result, from environment-build.sh's own lines in the stored log (JSON lines + * of `{ data, stream }`): "Installing dependencies automatically: ", then "Installed dependencies + * in Ns." or "Automatic install skipped: …". Null when the build ran no automatic install. + */ +export function autoInstallFromLog(stored: string): AutoInstallOutcome | null { + let text = '' + for (const line of stored.split('\n')) { + try { + const parsed = JSON.parse(line) as { data?: unknown } + if (typeof parsed.data === 'string') { + text += parsed.data + } + } catch { + // A cut marker or a partial line: nothing to read. + } + } + const started = /^Installing dependencies automatically: (?:corepack )?(pnpm|yarn|npm)\b/m.exec(text) + if (!started) { + return null + } + const manager = started[1] as AutoInstallOutcome['manager'] + return { manager, outcome: /^Installed dependencies in \d+s\.$/m.test(text) ? 'installed' : 'skipped' } } export type BuildDeps = { @@ -368,7 +402,9 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P ORCA_INSTALL_SCRIPT_B64: base64(config.installScript), ORCA_LOCKFILES: LOCKFILES.join(' '), ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK), - ...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {}) + ...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {}), + // An admin's own install script always wins: auto_install runs only without one. + ...(config.autoInstall && !config.installScript.trim() ? { ORCA_AUTO_INSTALL: '1' } : {}) } // Counts only. log('environment_build_secrets', { @@ -459,7 +495,10 @@ const EXIT_STEPS: Record = { } async function finalize(deps: BuildDeps, row: BuildRow, exitCode: number): Promise { - await storeLogs(deps, row).catch((error: unknown) => log('environment_build_log_store_failed', { buildId: row.id, error: String(error).slice(0, 200) })) + const stored = await storeLogs(deps, row).catch((error: unknown) => { + log('environment_build_log_store_failed', { buildId: row.id, error: String(error).slice(0, 200) }) + return '' + }) if (exitCode !== 0) { const mapped = EXIT_STEPS[exitCode] ?? { step: 'install', error: `exit_${exitCode}` } return (await failBuild(deps, row, mapped.step, mapped.error)) ?? row @@ -475,8 +514,11 @@ async function finalize(deps: BuildDeps, row: BuildRow, exitCode: number): Promi if (check.exitCode !== 0) { return (await failBuild(deps, row, 'record', 'runtime_removed')) ?? row } - const result = check.stdout.trim().split('\n').at(-1) ?? '{}' - JSON.parse(result) + const recordedResult = check.stdout.trim().split('\n').at(-1) ?? '{}' + const parsedResult = JSON.parse(recordedResult) as BuildResult + // The image's result.json predates the automatic install; the Worker reads that from the log. + const autoInstall = autoInstallFromLog(stored) + const result = autoInstall ? JSON.stringify({ ...parsedResult, autoInstall }) : recordedResult // Recorded before the snapshot: if this Worker is cut off mid-snapshot, the next look adopts the // snapshot by the build box's name (recoverInterrupted) with the result already in place. const recorded = await transition(deps.db, row, { result }, deps.now()) @@ -676,9 +718,10 @@ export async function cancelBuild(deps: BuildDeps, caller: SandboxCaller, row: B } /** Copies the full provider log (bounded: head + tail) into D1 once the build is over. */ -async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boolean } = {}): Promise { +/** Stores the build's log (redacted, capped) and returns what it stored. */ +async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boolean } = {}): Promise { if (!row.session_id || !row.command_id) { - return + return '' } // A still-running command (cancel, timeout) never ends its stream: keep what arrives in a few seconds. const raw = await readUntil( @@ -714,6 +757,7 @@ async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boole deps.db.prepare('UPDATE environment_builds SET log_bytes = ?, log_truncated = ? WHERE id = ?').bind(text.length, truncated, row.id) ) await deps.db.batch(statements) + return stored } /** Reads a stream until it ends or `ms` pass, whichever is first; what arrived is returned. */ diff --git a/cloud/apps/sandbox-control/src/environment-routes.ts b/cloud/apps/sandbox-control/src/environment-routes.ts index a1edaae0abc..65dc4382472 100644 --- a/cloud/apps/sandbox-control/src/environment-routes.ts +++ b/cloud/apps/sandbox-control/src/environment-routes.ts @@ -77,6 +77,7 @@ export function buildView(row: BuildRow, activeBuildId: string | null) { }), diskUsedBytes: result?.diskUsedBytes ?? null, diskTotalBytes: result?.diskTotalBytes ?? null, + autoInstall: result?.autoInstall ?? null, logBytes: row.log_bytes, logTruncated: row.log_truncated === 1 } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index c85c7539a95..21d75c25f9c 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -59,6 +59,7 @@ import { provisionWorkspaceToken } from './api/settings' import { docsPage, openApiDocument } from './api/openapi' import { handleDeviceSessionsRoute } from './device-sessions' import { removeMember } from './member-removal' +import { setFollow } from './workspace-follows' import { createRoutinesApi } from './routines/api' import { handleRoutineHook, isRoutineHookPath } from './routines/hooks' import { tickRoutines } from './routines/runs' @@ -123,7 +124,7 @@ import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from ' import { SecretsKmsError } from './secrets-kms' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' import { ACCOUNT_PROVIDERS, accountProvider, isSharedWorkspace } from './account-providers' -import { handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks' +import { handleAccountRequestSucceeded, handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks' import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker' import { refreshCodexLeases } from './codex-credentials' import { @@ -133,7 +134,7 @@ import { deleteAgentCredential, providerEnabled, putClaudeCredential, - readUsableAgentCredential + readUsableAgentCredentialState } from './agent-credentials' import { AgentSourceError, @@ -201,6 +202,7 @@ import { userAuthorizeUrl } from './github-user-tokens' import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git' +import { egressAllowlistFor } from './network-policy' import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs' import { getOrgSlug, putOrgSlug } from './org-slugs' import { @@ -210,6 +212,7 @@ import { WORKSPACE_ERROR_STATUS, WorkspaceError, canOpen, + canSee, isOrgAdmin, listWorkspaces, patchWorkspace, @@ -396,6 +399,8 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => return [] } let real: string | null = null + // RS-2: this sign-in is in question (a check failed); a real request here confirms or clears it. + let suspect = false return [ { header: provider.header, @@ -420,7 +425,9 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => scheduleEnvRefresh(env, deps, row) return signedOut('account_disabled') } - real = await cachedAccountCredential(env.SANDBOX_DB, await keyring, row.user_id, agent, now) + const account = await cachedAccountCredential(env.SANDBOX_DB, await keyring, row.user_id, agent, now) + real = account.value + suspect = account.suspect if (!real) { scheduleEnvRefresh(env, deps, row) return signedOut('no_agent_credential') @@ -431,6 +438,25 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => // Reached only after the real credential was swapped in and sent (denied or unswapped requests // never get here). onUpstreamStatus: (status, request) => { + // RS-2: a real request the provider accepted (not a 401, not a server failure) clears "needs + // check". Only while it's in question, so a healthy account costs no writes. + if (suspect && !provider.onUnauthorized && status !== 401 && status < 500) { + suspect = false + const now = (deps.now ?? Date.now)() + const work = handleAccountRequestSucceeded({ + db: env.SANDBOX_DB, + agent, + userId: row.user_id, + sandboxId: row.id, + path: request.path, + now + }).then((cleared) => (cleared ? forgetAccountCredential(row.user_id, agent) : undefined)) + if (deps.waitUntil) { + deps.waitUntil(work.catch(() => undefined)) + } else { + void work.catch(() => undefined) + } + } if (status === 401) { const now = (deps.now ?? Date.now)() const waitUntil = (work: Promise) => (deps.waitUntil ? deps.waitUntil(work.catch(() => undefined)) : void work.catch(() => undefined)) @@ -451,7 +477,13 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => fetch: deps.egressFetch ?? fetch }) ) - .then((outcome) => outcome === 'revoked') + .then((outcome) => { + // In question, not revoked: still usable; the next lookup reads the new state. + if (outcome === 'suspect') { + forgetAccountCredential(row.user_id, agent) + } + return outcome === 'revoked' + }) // Every running sandbox of this person drops the dead placeholder, not only this one. const work = handled.then(async (changed) => { if (!changed) { @@ -508,14 +540,20 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => // Account credentials per person, decrypted at most once a minute per isolate; an edit or delete drops it. const ACCOUNT_CACHE_MS = 10_000 -const accountCache = new Map }>() -function cachedAccountCredential(db: D1Database, keyring: Keyring, userId: string, agent: 'claude' | 'codex', now: number): Promise { +const accountCache = new Map }>() +function cachedAccountCredential( + db: D1Database, + keyring: Keyring, + userId: string, + agent: 'claude' | 'codex', + now: number +): Promise<{ value: string | null; suspect: boolean }> { const key = `${userId}:${agent}` const hit = accountCache.get(key) if (hit && now - hit.at < ACCOUNT_CACHE_MS) { return hit.value } - const value = readUsableAgentCredential(db, keyring, userId, agent, now) + const value = readUsableAgentCredentialState(db, keyring, userId, agent, now) accountCache.set(key, { at: now, value }) value.catch(() => accountCache.delete(key)) return value @@ -624,6 +662,9 @@ async function agentCredentialsRoute(request: Request, url: URL, env: Env, deps: forgetAccountCredential(caller.userId, 'claude') await refreshOwnersSandboxes(env, deps, caller.userId) } + if (result.outcome === 'suspect') { + forgetAccountCredential(caller.userId, 'claude') + } const view = await agentCredentialsView(db, env, caller.userId, now) return noStore({ claude: view.claude, verifiedAt: result.verifiedAt, checked: result.outcome !== 'fresh' && result.outcome !== 'skipped' }) } @@ -907,6 +948,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise { // Clickjacking: never framed. form-action also covers the 302 to the client after submit. 'x-frame-options': 'DENY', 'content-security-policy': `default-src 'none'; style-src 'unsafe-inline'; img-src 'none'; script-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${formAction}`, - 'referrer-policy': 'no-referrer', + // Not no-referrer: under no-referrer browsers send `Origin: null` on the form POST, which the + // same-origin check in oauth.ts refuses, so every real approval failed. same-origin still sends + // no referrer (and so none of the query) to any other origin. + 'referrer-policy': 'same-origin', 'x-content-type-options': 'nosniff', 'cross-origin-opener-policy': 'same-origin' } diff --git a/cloud/apps/sandbox-control/src/member-removal.ts b/cloud/apps/sandbox-control/src/member-removal.ts index d53d3d580bc..86c1d72fe0b 100644 --- a/cloud/apps/sandbox-control/src/member-removal.ts +++ b/cloud/apps/sandbox-control/src/member-removal.ts @@ -9,6 +9,7 @@ import { memberChangeTime, recordMemberChange } from './member-changes' import { revokeMemberReaderKeys } from './read-snapshots' import { disableMemberRoutines } from './routines/runs' import { forgetMemberPokes } from './team-presence' +import { forgetMemberFollows } from './workspace-follows' export type MemberRemoval = { keysRevoked: number @@ -61,6 +62,8 @@ export async function removeMember( const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now) // Their Pokes opt-in goes (it doubles as proof of membership for receiving one). await forgetMemberPokes(life.db, accountId, userId, now) + // They no longer follow anything here, and stop showing as anyone's follower. + await forgetMemberFollows(life.db, accountId, userId) const grants = await revokeGrantsForMember(life, accountId, userId) // Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running. const routines = await disableMemberRoutines({ life }, accountId, userId) diff --git a/cloud/apps/sandbox-control/src/network-policy.ts b/cloud/apps/sandbox-control/src/network-policy.ts index d945a18e9ef..366b0ace158 100644 --- a/cloud/apps/sandbox-control/src/network-policy.ts +++ b/cloud/apps/sandbox-control/src/network-policy.ts @@ -44,8 +44,11 @@ export const EDITOR_REMOTE_SERVER_HOSTS: readonly string[] = [ 'openvsxorg.blob.core.windows.net' ] -/** Registries, git hosting and agent model/sign-in hosts a coding VM needs. */ -export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [ +/** Orca's own hosts when ORCA_PLATFORM_HOST_SUFFIXES is unset. */ +export const DEFAULT_PLATFORM_HOST_SUFFIXES: readonly string[] = ['*.onorca.dev'] + +/** Registries, git hosting and agent model/sign-in hosts a coding VM needs (platform hosts excluded). */ +const BASE_EGRESS_HOSTS: readonly string[] = [ 'registry.npmjs.org', 'registry.yarnpkg.com', 'pypi.org', @@ -97,11 +100,21 @@ export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [ 'models.dev', // GitHub Copilot CLI: Copilot API (per plan: api.individual., api.business., ...). 'api.githubcopilot.com', - '*.githubcopilot.com', - '*.onorca.dev', - ...EDITOR_REMOTE_SERVER_HOSTS + '*.githubcopilot.com' ] +/** + * The default allowlist with Orca's platform hosts from ORCA_PLATFORM_HOST_SUFFIXES (comma list, e.g. + * `*.onorca.dev`). Unset, blank or only commas: DEFAULT_PLATFORM_HOST_SUFFIXES. + */ +export function egressAllowlistFor(platformHostSuffixes?: string): readonly string[] { + const configured = (platformHostSuffixes ?? '').split(',').map((host) => host.trim()).filter(Boolean) + const platform = configured.length > 0 ? configured : DEFAULT_PLATFORM_HOST_SUFFIXES + return [...new Set([...BASE_EGRESS_HOSTS, ...platform, ...EDITOR_REMOTE_SERVER_HOSTS])] +} + +export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = egressAllowlistFor() + /** * Workspace sandbox egress presets. `open` (the default) reaches the whole internet, like Codespaces * or Devin; `limited` is the fail-closed allowlist above. Credential routes apply under both. diff --git a/cloud/apps/sandbox-control/src/routines/vm-runner.ts b/cloud/apps/sandbox-control/src/routines/vm-runner.ts index aaf9f5c93a9..b27a6ac51a1 100644 --- a/cloud/apps/sandbox-control/src/routines/vm-runner.ts +++ b/cloud/apps/sandbox-control/src/routines/vm-runner.ts @@ -136,7 +136,7 @@ echo "routine: agent exit $code" if [ "$code" = 0 ] && [ "$post" = pr ] && [ -n "$start_sha" ]; then git add -A >/dev/null 2>&1 || true if ! git diff --cached --quiet 2>/dev/null; then - git -c user.name="Orca Routine" -c user.email="routines@onorca.dev" commit -q -m "$(cat "$D/title.txt")" -m "$summary" || note=commit_failed + git -c user.name="Orca Routine" -c user.email="noreply@orca.dev" commit -q -m "$(cat "$D/title.txt")" -m "$summary" || note=commit_failed fi if [ "$(git rev-parse HEAD)" != "$start_sha" ]; then changed=true diff --git a/cloud/apps/sandbox-control/src/workspace-follows.ts b/cloud/apps/sandbox-control/src/workspace-follows.ts new file mode 100644 index 00000000000..77c494d0716 --- /dev/null +++ b/cloud/apps/sandbox-control/src/workspace-follows.ts @@ -0,0 +1,80 @@ +// PARITY-FOLLOW: persistent Follow on a team workspace (Conductor's Following section and +// follower avatars). +// PUT /v1/team/workspaces/:id/follow -> {following: true, followers} +// DELETE /v1/team/workspaces/:id/follow -> {following: false, followers} +// Anyone who can see a workspace may follow it, and sees who else follows it (team workspaces are +// visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old +// follow of a workspace that turned private is never shown and never counts. Archived workspaces +// may still be followed: they stay browsable. +import type { SandboxCaller } from './auth' +import type { SandboxRow } from './store' + +/** Followers of each workspace, oldest follow first. */ +export async function followersFor(db: D1Database, ids: readonly string[]): Promise> { + const out = new Map() + if (ids.length === 0) { + return out + } + const { results } = await db + .prepare( + `SELECT sandbox_id, user_id FROM workspace_follows WHERE sandbox_id IN (${ids.map(() => '?').join(', ')}) + ORDER BY created_at ASC, user_id ASC` + ) + .bind(...ids) + .all<{ sandbox_id: string; user_id: string }>() + for (const row of results) { + const list = out.get(row.sandbox_id) ?? [] + list.push(row.user_id) + out.set(row.sandbox_id, list) + } + return out +} + +/** + * The followers a caller may be shown for a row: none unless the caller can see it (`seen`); for a + * private row, only its owner (the only member who can see it). + */ +export function visibleFollowers( + row: Pick, + seen: boolean, + followers: readonly string[] +): string[] { + if (!seen) { + return [] + } + return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) +} + +/** The caller must be able to see the row (the route checks canSee first). */ +export async function setFollow( + db: D1Database, + caller: SandboxCaller, + row: SandboxRow, + follow: boolean, + now: number +): Promise<{ following: boolean; followers: string[] }> { + if (follow) { + await db + .prepare( + `INSERT INTO workspace_follows (sandbox_id, user_id, account_id, created_at) VALUES (?, ?, ?, ?) + ON CONFLICT (sandbox_id, user_id) DO NOTHING` + ) + .bind(row.id, caller.userId, row.account_id, now) + .run() + } else { + await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ? AND user_id = ?').bind(row.id, caller.userId).run() + } + const followers = visibleFollowers(row, true, (await followersFor(db, [row.id])).get(row.id) ?? []) + return { following: followers.includes(caller.userId), followers } +} + +/** The workspace is gone: nobody follows it any more. */ +export async function forgetWorkspaceFollows(db: D1Database, sandboxId: string): Promise { + await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ?').bind(sandboxId).run() +} + +/** The member left the account: their follows go, and they stop showing as a follower. */ +export async function forgetMemberFollows(db: D1Database, accountId: string, userId: string): Promise { + const result = await db.prepare('DELETE FROM workspace_follows WHERE account_id = ? AND user_id = ?').bind(accountId, userId).run() + return result.meta.changes +} diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 28664ab1184..20d67a837b7 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -4,6 +4,7 @@ // GET /v1/team/workspaces/:id // PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?} // POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?} +// PUT|DELETE /v1/team/workspaces/:id/follow (workspace-follows.ts) // GET /v1/team/links/resolve?w=&c= or ?org=&n=&c= // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a @@ -15,6 +16,7 @@ import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './st import { memberNamesFor } from './member-names' import { recordTokenSpend } from './member-usage' import { readSnapshotTimes } from './read-snapshots' +import { followersFor, visibleFollowers } from './workspace-follows' import { sandboxView } from './wire' import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs' import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' @@ -172,15 +174,17 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted, readAt, slug] = await Promise.all([ + const [presence, compute, granted, readAt, slug, follows] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), activeGrantUsers(db, ids, caller.userId), readSnapshotTimes(db, ids), - rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null) + rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null), + followersFor(db, ids) ]) + const followersOf = (row: SandboxRow) => visibleFollowers(row, canSee(caller, row), follows.get(row.id) ?? []) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => - [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( + [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id), ...followersOf(row)].filter( (id): id is string => typeof id === 'string' ) const names = await memberNamesFor( @@ -193,6 +197,7 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows // Private rows an admin sees for management show who/what, never live presence. const showPresence = access !== 'none' const live = showPresence ? (presence.get(row.id) ?? []) : [] + const followers = followersOf(row) const memberNames = Object.fromEntries( referenced(row, live).flatMap((id) => (names.has(id) ? [[id, names.get(id)!]] : [])) ) @@ -214,6 +219,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows cost: costView(row, compute.get(row.id) ?? 0, now), access, presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })), + // Who follows it (oldest first), and whether the caller does (PARITY-FOLLOW). + followers, + following: followers.includes(caller.userId), // Display names (token `name` claim) for the ids above; the roster wins where it has one. memberNames, // When its sleeping read-only copy was saved ("As of"); only for those who may read it. diff --git a/cloud/apps/sandbox-control/test/agent-accounts.test.ts b/cloud/apps/sandbox-control/test/agent-accounts.test.ts index 516bf5330b8..61107afb573 100644 --- a/cloud/apps/sandbox-control/test/agent-accounts.test.ts +++ b/cloud/apps/sandbox-control/test/agent-accounts.test.ts @@ -108,7 +108,8 @@ describe('Orca-account credentials (D11)', () => { expect((await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: 'sk-ant-api03-not-a-setup-token' } })).body.reason).toBe('invalid_token') const put = await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN, label: 'mia@example.com' } }) expect(put.status).toBe(200) - expect(put.body.claude).toMatchObject({ state: 'active', label: 'mia@example.com' }) + // RS-5: never the email a client sends (it may be another account's): always "Claude subscription". + expect(put.body.claude).toMatchObject({ state: 'active', label: 'Claude subscription' }) expect(put.body.providerEnabled).toEqual({ claude: true, codex: false }) // Codex's flag was never turned on: `off`, which clients word differently from the kill switch. expect(put.body.providerState).toEqual({ claude: 'on', codex: 'off' }) @@ -190,7 +191,7 @@ describe('egress-time Source (D10) and shared workspaces (D13)', () => { expectSignedOut(refused) }) - it('a 401 from the provider marks the account revoked and the session falls off it', async () => { + it('a 401 confirmed by a later real 401 revokes the account and the session falls off it', async () => { const { h, as, proxied, reply, lastEnv } = await setup() const mia = await as('mia') await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) @@ -200,7 +201,11 @@ describe('egress-time Source (D10) and shared workspaces (D13)', () => { const otherSession: string = other.body.sandbox.session.id reply.status = 401 expect((await proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` })).status).toBe(401) - // Confirmed by the control plane's own auth check (dead token), then revoked. + // RS-2: the auth check (dead token) only puts it in question; a later real request's 401 revokes it. + await vi.waitFor(async () => + expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toMatchObject({ state: 'expired', needsCheck: true }) + ) + expect((await proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` })).status).toBe(401) await vi.waitFor(async () => expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude.state).toBe('revoked')) // Already off the account: no placeholder in new shells, and the proxy refuses with a clear reason. await vi.waitFor(() => expect(lastEnv(ENV_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined()) @@ -334,12 +339,62 @@ describe('a provider 401 revokes only when confirmed', () => { expect(await state()).toBe('active') }) - it('a confirmed dead token is revoked once and audited', async () => { + it('RS-2: a failed auth check alone never revokes: "needs check" (shown as expired), still usable', async () => { + const { h, reply, send, state, auditRows, upstream, check } = await running() + reply.status = 401 + await send() + await vi.waitFor(async () => expect(await auditRows()).toEqual([{ action: 'suspect', reason: 'provider_401_check_auth_failure', upstream_path: '/v1/messages' }])) + expect(await state()).toBe('expired') + const mia = await h.token('mia', undefined, 'sandbox') + expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toMatchObject({ state: 'expired', needsCheck: true }) + // The real credential still goes out, so the next real request can confirm it either way. + reply.status = 200 + upstream.length = 0 + await send() + expect(upstream.at(-1)?.headers.get('authorization')).toBe(`Bearer ${SETUP_TOKEN}`) + expect(check.calls).toBe(1) + }) + + it('RS-2: needs check + a later real 401 revokes (audited); the probe alone never did', async () => { const { reply, send, state, auditRows } = await running() reply.status = 401 await send() + await vi.waitFor(async () => expect((await auditRows()).map((row) => row.action)).toEqual(['suspect'])) + await send() await vi.waitFor(async () => expect(await state()).toBe('revoked')) - expect(await auditRows()).toEqual([{ action: 'revoked', reason: 'provider_401_confirmed_by_check', upstream_path: '/v1/messages' }]) + expect(await auditRows()).toEqual([ + { action: 'suspect', reason: 'provider_401_check_auth_failure', upstream_path: '/v1/messages' }, + { action: 'revoked', reason: 'provider_401_after_check_failure', upstream_path: '/v1/messages' } + ]) + }) + + it('RS-2: needs check + a later real request that succeeds clears it back to active (audited)', async () => { + const { reply, send, state, auditRows } = await running() + reply.status = 401 + await send() + await vi.waitFor(async () => expect((await auditRows()).map((row) => row.action)).toEqual(['suspect'])) + reply.status = 200 + await send() + await vi.waitFor(async () => expect(await state()).toBe('active')) + expect((await auditRows()).at(-1)).toEqual({ action: 'kept', reason: 'request_succeeded_after_check_failure', upstream_path: '/v1/messages' }) + }) + + it('RS-2: a check that can\'t reach the provider changes nothing', async () => { + const ctx = await setup() + const mia = await ctx.as('mia') + await ctx.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + const created = await ctx.h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) + const id: string = created.body.sandbox.id + ctx.reply.status = 401 + ctx.check.status = 0 + await ctx.proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` }) + await vi.waitFor(async () => + expect((await ctx.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results).toEqual([ + { action: 'kept', reason: 'check_inconclusive' } + ]) + ) + expect((await ctx.h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toEqual(expect.objectContaining({ state: 'active' })) + expect((await ctx.h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude.needsCheck).toBeUndefined() }) }) @@ -358,14 +413,14 @@ describe('POST /v1/agent-credentials/claude/verify (pre-launch check)', () => { expect(check.calls).toBe(1) }) - it('a dead token is revoked (and audited); an inconclusive check keeps it', async () => { + it('RS-2: a dead token only needs a check (audited, never revoked by the probe); an inconclusive check keeps it', async () => { const dead = await setup() const mia = await dead.as('mia') await dead.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) - const revoked = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) - expect(revoked.body).toMatchObject({ claude: { state: 'revoked' }, checked: true, verifiedAt: null }) + const suspect = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + expect(suspect.body).toMatchObject({ claude: { state: 'expired', needsCheck: true }, checked: true, verifiedAt: null }) const rows = (await dead.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results - expect(rows).toEqual([{ action: 'revoked', reason: 'verify_confirmed_auth_failure' }]) + expect(rows).toEqual([{ action: 'suspect', reason: 'verify_check_auth_failure' }]) const flaky = await setup() const ada = await flaky.as('ada') diff --git a/cloud/apps/sandbox-control/test/auth-issuers.test.ts b/cloud/apps/sandbox-control/test/auth-issuers.test.ts new file mode 100644 index 00000000000..dc4d9b5ae7c --- /dev/null +++ b/cloud/apps/sandbox-control/test/auth-issuers.test.ts @@ -0,0 +1,53 @@ +import { SignJWT, exportJWK, generateKeyPair } from 'jose' +import { describe, expect, it } from 'vitest' +import { authenticateDesktop, issuerList } from '../src/auth' +import { createHarness } from './harness' + +const PROD = 'https://login.onorca.dev' +const NEXT = 'https://login.example.dev' + +async function issuerHarness(issuers: string) { + const { privateKey, publicKey } = await generateKeyPair('ES256') + const jwk = { ...(await exportJWK(publicKey)), kid: 'iss1', alg: 'ES256', use: 'sig' } + const h = await createHarness({ SANDBOX_JWKS: JSON.stringify({ keys: [jwk] }), SANDBOX_AUTH_ISSUER: issuers }) + const accepts = async (issuer: string): Promise => { + const iat = Math.floor(h.now() / 1000) + const token = await new SignJWT({ sub: 'user_iss', purpose: 'sandbox' }) + .setProtectedHeader({ alg: 'ES256', kid: 'iss1' }) + .setIssuer(issuer) + .setAudience('orca-sandbox') + .setIssuedAt(iat) + .setExpirationTime(iat + 300) + .sign(privateKey) + const request = new Request('https://sandbox.test/v1/config', { headers: { authorization: `Bearer ${token}` } }) + return (await authenticateDesktop(h.env, request, h.now())) !== null + } + return { accepts } +} + +describe('SANDBOX_AUTH_ISSUER list', () => { + it('parses a comma list, ignoring whitespace and empty entries', () => { + expect(issuerList(undefined)).toBeUndefined() + expect(issuerList('')).toBeUndefined() + expect(issuerList(PROD)).toEqual([PROD]) + expect(issuerList(` ${PROD} ,, ${NEXT} , `)).toEqual([PROD, NEXT]) + }) + + it('a single issuer behaves as before', async () => { + const h = await issuerHarness(PROD) + expect(await h.accepts(PROD)).toBe(true) + expect(await h.accepts(NEXT)).toBe(false) + }) + + it('a list accepts each listed issuer and rejects others', async () => { + const h = await issuerHarness(` ${PROD} , ,${NEXT},`) + expect(await h.accepts(PROD)).toBe(true) + expect(await h.accepts(NEXT)).toBe(true) + expect(await h.accepts('https://login.evil.dev')).toBe(false) + }) + + it('a value with no entries accepts no issuer', async () => { + const h = await issuerHarness(' , ') + expect(await h.accepts(PROD)).toBe(false) + }) +}) diff --git a/cloud/apps/sandbox-control/test/auto-environments.test.ts b/cloud/apps/sandbox-control/test/auto-environments.test.ts index cb12b135dc8..4503f931c7b 100644 --- a/cloud/apps/sandbox-control/test/auto-environments.test.ts +++ b/cloud/apps/sandbox-control/test/auto-environments.test.ts @@ -35,16 +35,16 @@ async function setup() { last_used_at: number | null }[] /** Lets the auto build's VM command succeed and finalizes it. */ - async function finishBuild(as = 'alice') { + async function finishBuild(as = 'alice', output = '::orca-step:: clone\n') { const env = environments().find((row) => row.deleted_at === null && !row.active_build_id)! const build = h.raw.prepare('SELECT id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(env.id) as { id: string } const command = [...h.vercel.buildCommands.values()].at(-1)! - command.logs = `${JSON.stringify({ data: '::orca-step:: clone\n', stream: 'stdout' })}\n` + command.logs = `${JSON.stringify({ data: output, stream: 'stdout' })}\n` command.exitCode = 0 h.advance(1000) const done = await h.call('GET', `/v1/environments/${env.id}/builds/${build.id}`, { as }) expect(done.body.build.status).toBe('succeeded') - return { env, buildId: build.id } + return { env, buildId: build.id, build: done.body.build } } return { h, settle, environments, finishBuild } } @@ -58,6 +58,8 @@ describe('automatic environments', () => { expect(environments()).toMatchObject([{ kind: 'auto', name: 'acme/web', active_build_id: null }]) const command = [...h.vercel.buildCommands.values()].at(-1)! expect(command.env.ORCA_CLONE_FILTER).toBe('blob:none') + // PARITY-AUTO-ENV-DEPS: its lockfile's dependencies too, so creates start warm. + expect(command.env.ORCA_AUTO_INSTALL).toBe('1') const { buildId } = await finishBuild() h.vercel.commands.length = 0 @@ -105,6 +107,30 @@ describe('automatic environments', () => { expect(environments().filter((row) => row.kind === 'auto')).toHaveLength(2) }) + it('the build says what its lockfile install did (AUTO-ENV-DEPS-LABEL)', async () => { + const { h, settle, finishBuild } = await setup() + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, headers: FEATURES }) + await settle() + const { build } = await finishBuild( + 'alice', + '::orca-step:: install\nInstalling dependencies automatically: corepack pnpm install --frozen-lockfile\nInstalled dependencies in 42s.\n' + ) + expect(build.autoInstall).toEqual({ manager: 'pnpm', outcome: 'installed' }) + }) + + it("an admin's environment never installs automatically, with or without its own script", async () => { + const { h } = await setup() + const admin = await h.token('carol', 'acme', 'sandbox', { orgRole: 'admin' }) + const created = await h.call('POST', '/v1/environments', { + bearer: admin, + body: { name: 'Web', repos: [{ url: 'acme/web' }], installScript: '' } + }) + expect(created.status).toBe(200) + expect((await h.call('POST', `/v1/environments/${created.body.environment.id}/builds`, { bearer: admin })).status).toBe(200) + const command = [...h.vercel.buildCommands.values()].at(-1)! + expect(command.env.ORCA_AUTO_INSTALL).toBeUndefined() + }) + it('boot-plan says clone before the environment exists and update after (PC-4)', async () => { const { h, settle, finishBuild } = await setup() const plan = async () => (await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`)).body diff --git a/cloud/apps/sandbox-control/test/codex-broker.test.ts b/cloud/apps/sandbox-control/test/codex-broker.test.ts index acae75da9aa..06c8323de73 100644 --- a/cloud/apps/sandbox-control/test/codex-broker.test.ts +++ b/cloud/apps/sandbox-control/test/codex-broker.test.ts @@ -368,7 +368,12 @@ describe('Codex account in workspaces (D10, D13)', () => { const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia }) const id: string = created.body.sandbox.id await h.env.SANDBOX_DB.prepare(`UPDATE sandboxes SET visibility = 'team' WHERE id = ?`).bind(id).run() - expect((await proxied(id, 'chatgpt.com', { authorization: `Bearer ${codexPlaceholder({ id })}` })).status).toBe(403) + const refused = await proxied(id, 'chatgpt.com', { authorization: `Bearer ${codexPlaceholder({ id })}` }) + // RS-4: still a 403 (a 401 would start Codex's own token refresh), now with words Codex prints. + expect(refused.status).toBe(403) + expect(JSON.parse(refused.body)).toEqual({ + detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.' + }) expect(lastEnv('/opt/orca/bin/orca-sandbox-env').ORCA_CODEX_AUTH_PLACEHOLDER).toBeUndefined() }) diff --git a/cloud/apps/sandbox-control/test/environment-build-auto-install-log.test.ts b/cloud/apps/sandbox-control/test/environment-build-auto-install-log.test.ts new file mode 100644 index 00000000000..bdb7259cc53 --- /dev/null +++ b/cloud/apps/sandbox-control/test/environment-build-auto-install-log.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { autoInstallFromLog } from '../src/environment-builds' + +const stored = (...lines: string[]): string => + lines.map((data) => JSON.stringify({ data: `${data}\n`, stream: 'stdout' })).join('\n') + +describe('autoInstallFromLog (AUTO-ENV-DEPS-LABEL)', () => { + it('reads the manager and whether it installed', () => { + expect( + autoInstallFromLog(stored('Installing dependencies automatically: corepack yarn install --immutable', 'Installed dependencies in 9s.')) + ).toEqual({ manager: 'yarn', outcome: 'installed' }) + expect( + autoInstallFromLog( + stored('Installing dependencies automatically: npm ci', 'Automatic install skipped: npm ci exited with status 1 (often a lockfile out of date).') + ) + ).toEqual({ manager: 'npm', outcome: 'skipped' }) + }) + + it('nothing for a build without an automatic install, or an unreadable log', () => { + expect(autoInstallFromLog(stored('No install script; the build keeps the cloned repos.'))).toBeNull() + expect(autoInstallFromLog(stored('Not installed automatically: uv.lock.'))).toBeNull() + expect(autoInstallFromLog('not json\n{"data":')).toBeNull() + }) +}) diff --git a/cloud/apps/sandbox-control/test/environment-build-auto-install.test.ts b/cloud/apps/sandbox-control/test/environment-build-auto-install.test.ts new file mode 100644 index 00000000000..1b742270dba --- /dev/null +++ b/cloud/apps/sandbox-control/test/environment-build-auto-install.test.ts @@ -0,0 +1,135 @@ +// PARITY-AUTO-ENV-DEPS: an automatic environment installs the first repo's JavaScript dependencies +// from its lockfile, so creates start warm, and never fails its build over it. The real script's +// auto_install, run by a real bash against a scratch repo with stub package managers on PATH. +import { execFileSync } from 'node:child_process' +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { ENVIRONMENT_BUILD_SCRIPT, VM_SCRIPTS_HASH } from '../image/vm-scripts.generated' + +const script = readFileSync(fileURLToPath(new URL('../image/env/environment-build.sh', import.meta.url).href), 'utf8') +const autoInstall = /^auto_install\(\) \{\n[\s\S]*?\n\}\n/m.exec(script)?.[0] + +let dir: string +let repo: string +let bin: string + +/** A stub command that logs its argv to calls.log and exits with $STUB__EXIT (default 0). */ +function stub(name: string): void { + const exitVar = `STUB_${name.toUpperCase()}_EXIT` + writeFileSync( + join(bin, name), + `#!/usr/bin/env bash\necho "${name} $*" >>"${join(dir, 'calls.log')}"\n` + + // A failing install leaves a half-written tree behind, as real ones do. + `mkdir -p node_modules/.half packages/a/node_modules\nexit "\${${exitVar}:-0}"\n` + ) + chmodSync(join(bin, name), 0o755) +} + +function run(env: Record = {}): { status: number; out: string; calls: string } { + const program = ['set -uo pipefail', autoInstall, 'auto_install "$REPO"', 'echo "status:$?"'].join('\n') + let out: string + let status = 0 + try { + out = execFileSync('bash', ['--noprofile', '--norc', '-c', program], { + env: { PATH: `${bin}:${process.env.PATH}`, REPO: repo, ...env }, + encoding: 'utf8' + }) + } catch (error) { + const failed = error as { status: number; stdout: string } + status = failed.status + out = failed.stdout + } + const log = join(dir, 'calls.log') + return { status, out, calls: existsSync(log) ? readFileSync(log, 'utf8') : '' } +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-auto-install-')) + repo = join(dir, 'repo') + bin = join(dir, 'bin') + mkdirSync(repo) + mkdirSync(bin) + stub('corepack') + stub('npm') +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const file = (path: string, content = ''): void => writeFileSync(join(repo, path), content) + +describe('environment-build.sh auto_install (PARITY-AUTO-ENV-DEPS)', () => { + it('is in the build script, runs only for automatic environments without an install script, and ships in the Worker', () => { + expect(autoInstall).toBeDefined() + expect(script).toMatch(/elif \[ "\$\{ORCA_AUTO_INSTALL:-\}" = 1 \] && \[ -n "\$first" \]; then\n {2}auto_install "\$first"\n/) + expect(ENVIRONMENT_BUILD_SCRIPT).toBe(script) + // env/ scripts ride in the Worker; the golden's VM scripts (and their hash) are untouched. + // Pin updated by DOMAIN-1 #666, which changes the VM scripts on purpose. + expect(VM_SCRIPTS_HASH).toBe('6e35ca58') + }) + + it('picks the package manager from the lockfile, frozen, through corepack', () => { + file('package.json', '{"name":"web"}') + file('pnpm-lock.yaml') + const pnpm = run() + expect(pnpm.out).toContain('status:0') + expect(pnpm.calls).toBe('corepack pnpm install --frozen-lockfile\n') + expect(pnpm.out).toMatch(/Installed dependencies in \d+s\./) + }) + + it('yarn berry is --immutable, classic --frozen-lockfile; npm is npm ci', () => { + file('package.json', '{}') + file('yarn.lock') + expect(run().calls).toBe('corepack yarn install --frozen-lockfile\n') + rmSync(join(dir, 'calls.log')) + file('.yarnrc.yml', 'nodeLinker: node-modules\n') + expect(run().calls).toBe('corepack yarn install --immutable\n') + rmSync(join(repo, 'yarn.lock')) + rmSync(join(repo, '.yarnrc.yml')) + rmSync(join(dir, 'calls.log')) + file('package-lock.json', '{}') + expect(run().calls).toBe('npm ci\n') + }) + + it("package.json's packageManager wins over the lockfile guess", () => { + file('package.json', '{"name":"web","packageManager":"pnpm@9.12.0"}') + file('package-lock.json', '{}') + expect(run().calls).toBe('corepack pnpm install --frozen-lockfile\n') + }) + + it('a failed install (often a lockfile out of date) never fails the build and leaves no half-installed tree', () => { + file('package.json', '{}') + file('pnpm-lock.yaml') + const failed = run({ STUB_COREPACK_EXIT: '1' }) + expect(failed.status).toBe(0) + expect(failed.out).toContain('status:0') + expect(failed.out).toContain('Automatic install skipped: corepack pnpm install --frozen-lockfile exited with status 1') + expect(failed.out).toContain('New workspaces start from the cloned repo and run their own setup.') + expect(existsSync(join(repo, 'node_modules'))).toBe(false) + expect(existsSync(join(repo, 'packages/a/node_modules'))).toBe(false) + }) + + it('stops at the time cap and says so, still without failing', () => { + file('package.json', '{}') + file('package-lock.json', '{}') + writeFileSync(join(bin, 'npm'), '#!/usr/bin/env bash\nsleep 5\n') + chmodSync(join(bin, 'npm'), 0o755) + const slow = run({ ORCA_AUTO_INSTALL_TIMEOUT: '1' }) + expect(slow.out).toContain('status:0') + expect(slow.out).toContain('took longer than 15 minutes') + }) + + it('names what the image cannot install, and does nothing without a lockfile', () => { + file('uv.lock') + file('Gemfile.lock') + const others = run() + expect(others.calls).toBe('') + expect(others.out).toContain('Not installed automatically: uv.lock Gemfile.lock.') + rmSync(join(repo, 'uv.lock')) + rmSync(join(repo, 'Gemfile.lock')) + const none = run() + expect(none.calls).toBe('') + expect(none.out).toContain('No lockfile found; the build keeps the cloned repos.') + }) +}) diff --git a/cloud/apps/sandbox-control/test/git-shim-identity-nudge.test.ts b/cloud/apps/sandbox-control/test/git-shim-identity-nudge.test.ts index 6a3a88fc090..94b5111b7e4 100644 --- a/cloud/apps/sandbox-control/test/git-shim-identity-nudge.test.ts +++ b/cloud/apps/sandbox-control/test/git-shim-identity-nudge.test.ts @@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url' import { afterEach, beforeEach, describe, expect, it } from 'vitest' const SHIM = fileURLToPath(new URL('../image/vm/git', import.meta.url).href) -const NUDGE = "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours." +const NUDGE = "orca: This commit is authored as Orca . Connect GitHub in Settings → Account to commit as yourself." let home = '' let cwd = '' diff --git a/cloud/apps/sandbox-control/test/mcp.test.ts b/cloud/apps/sandbox-control/test/mcp.test.ts index f9e35ac23a8..226e66ea0a3 100644 --- a/cloud/apps/sandbox-control/test/mcp.test.ts +++ b/cloud/apps/sandbox-control/test/mcp.test.ts @@ -425,6 +425,8 @@ describe('MCP authorization', () => { const page = await h.send(new Request(`${ORIGIN}/oauth/authorize?${h.authorizeParams(client.client_id, challenge)}`)) expect(page.headers.get('x-frame-options')).toBe('DENY') + // Browsers only send a real Origin on the approval POST when the page's policy allows it (END-PASS: no-referrer broke every browser). + expect(page.headers.get('referrer-policy')).toBe('same-origin') expect(page.headers.get('content-security-policy')).toContain("frame-ancestors 'none'") expect(page.headers.get('content-security-policy')).toContain('form-action \'self\' http://127.0.0.1:33418') expect(page.headers.get('set-cookie')).toMatch(/__Host-orca_mcp_csrf=\w+; Path=\/; Secure; HttpOnly; SameSite=Strict/) diff --git a/cloud/apps/sandbox-control/test/network-policy.test.ts b/cloud/apps/sandbox-control/test/network-policy.test.ts index 37109212019..5f64d3d0757 100644 --- a/cloud/apps/sandbox-control/test/network-policy.test.ts +++ b/cloud/apps/sandbox-control/test/network-policy.test.ts @@ -1,5 +1,13 @@ import { describe, expect, it } from 'vitest' -import { DEFAULT_EGRESS_PRESET, EDITOR_REMOTE_SERVER_HOSTS, compileNetworkPolicy, gitBasicAuthorization, parseEgressPreset } from '../src/network-policy' +import { + DEFAULT_EGRESS_ALLOWLIST, + DEFAULT_EGRESS_PRESET, + EDITOR_REMOTE_SERVER_HOSTS, + compileNetworkPolicy, + egressAllowlistFor, + gitBasicAuthorization, + parseEgressPreset +} from '../src/network-policy' const deny = { response: { statusCode: 403, body: 'orca-egress-denied', contentType: 'text/plain' } } @@ -123,3 +131,26 @@ describe('compileNetworkPolicy', () => { expect(allow['*']).toBeUndefined() }) }) + +describe('ORCA_PLATFORM_HOST_SUFFIXES', () => { + it('unset (or blank) keeps the default allowlist exactly as before', () => { + const editorAt = DEFAULT_EGRESS_ALLOWLIST.length - EDITOR_REMOTE_SERVER_HOSTS.length + expect(DEFAULT_EGRESS_ALLOWLIST).toHaveLength(56) + expect(DEFAULT_EGRESS_ALLOWLIST.slice(editorAt - 2, editorAt)).toEqual(['*.githubcopilot.com', '*.onorca.dev']) + expect(DEFAULT_EGRESS_ALLOWLIST.slice(editorAt)).toEqual(EDITOR_REMOTE_SERVER_HOSTS) + for (const unset of [undefined, '', ' , ']) { + expect(egressAllowlistFor(unset)).toEqual(DEFAULT_EGRESS_ALLOWLIST) + } + }) + + it('replaces the platform hosts with the configured suffixes, once each', () => { + const allowlist = egressAllowlistFor(' *.onorca.dev , ,*.example.dev,') + expect(allowlist.filter((host) => host === '*.onorca.dev')).toHaveLength(1) + expect(allowlist).toContain('*.example.dev') + expect(allowlist).toHaveLength(DEFAULT_EGRESS_ALLOWLIST.length + 1) + expect(egressAllowlistFor('*.example.dev')).not.toContain('*.onorca.dev') + const { allow } = compileNetworkPolicy({ mode: 'allowlist', allowlist }) + expect(allow['*.onorca.dev']).toEqual([]) + expect(allow['*.example.dev']).toEqual([]) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspace-follows.test.ts b/cloud/apps/sandbox-control/test/workspace-follows.test.ts new file mode 100644 index 00000000000..e075a408a84 --- /dev/null +++ b/cloud/apps/sandbox-control/test/workspace-follows.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest' +import { createHarness } from './harness' + +const AUTH_TOKEN = 'a'.repeat(40) + +async function team() { + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: AUTH_TOKEN }) + type Who = { sub: string; orgRole: 'owner' | 'admin' | 'member' } + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, 'acme', 'sandbox', { org_role: who.orgRole }), body }) + const alice: Who = { sub: 'alice', orgRole: 'member' } + const bob: Who = { sub: 'bob', orgRole: 'member' } + const carol: Who = { sub: 'carol', orgRole: 'member' } + const olga: Who = { sub: 'olga', orgRole: 'admin' } + const create = async (who: Who, visibility: 'team' | 'private') => { + const made = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${Math.random()}`, machineSize: 'standard', title: 'W' }) + expect(made.status).toBe(200) + const id = made.body.sandbox.id as string + if (visibility === 'team') { + await req(who, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' }) + } + return id + } + const internal = (path: string, body: unknown) => h.call('POST', path, { body, bearer: AUTH_TOKEN }) + return { h, req, alice, bob, carol, olga, create, internal } +} + +describe('workspace follows (PARITY-FOLLOW)', () => { + it('follows and unfollows; everyone who can see it sees followers, oldest first', async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + const bobFollow = await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect(bobFollow.status).toBe(200) + expect(bobFollow.body).toEqual({ following: true, followers: ['bob'] }) + t.h.advance(1_000) + await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`) + // Following twice is a no-op, and keeps Bob first. + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + + const seenByAlice = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + expect(seenByAlice).toMatchObject({ followers: ['bob', 'carol'], following: false }) + const listed = (await t.req(t.carol, 'GET', '/v1/team/workspaces?scope=team')).body.workspaces + expect(listed.find((w: { id: string }) => w.id === id)).toMatchObject({ followers: ['bob', 'carol'], following: true }) + + const unfollow = await t.req(t.bob, 'DELETE', `/v1/team/workspaces/${id}/follow`) + expect(unfollow.body).toEqual({ following: false, followers: ['carol'] }) + }) + + it("can't follow a private workspace you can't see, and old follows vanish when it turns private", async () => { + const t = await team() + const secret = await t.create(t.alice, 'private') + expect((await t.req(t.bob, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404) + // An admin may address a private row for management, but not follow it. + expect((await t.req(t.olga, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404) + + const shared = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${shared}/follow`) + t.h.advance(1_000) + await t.req(t.alice, 'PUT', `/v1/team/workspaces/${shared}/follow`) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'private' }) + // The owner still sees their own follow; Bob's is never shown while it is private. + const own = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace + expect(own).toMatchObject({ followers: ['alice'], following: true }) + const adminView = (await t.req(t.olga, 'GET', '/v1/team/workspaces?scope=all')).body.workspaces.find( + (w: { id: string }) => w.id === shared + ) + expect(adminView.followers).toEqual([]) + // Shared again: Bob's follow is back (it was hidden, not lost). + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace).toMatchObject({ + followers: ['bob', 'alice'], + following: true + }) + }) + + it('forgets every follow of a destroyed workspace', async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${id}`)).status).toBe(200) + const left = t.h.raw.prepare('SELECT COUNT(*) AS n FROM workspace_follows WHERE sandbox_id = ?').get(id) as { n: number } + expect(left.n).toBe(0) + }) + + it("forgets a removed member's follows, so they stop showing as a follower", async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect((await t.internal('/v1/internal/org-members/removed', { accountId: 'org:acme', userId: 'bob' })).status).toBe(200) + expect((await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace.followers).toEqual(['carol']) + }) +}) diff --git a/config/scripts/test-runtime/execution-policy/vitest-run-temp-directory.test.mjs b/config/scripts/test-runtime/execution-policy/vitest-run-temp-directory.test.mjs index b0d91a1a181..f9f3b2a6cfb 100644 --- a/config/scripts/test-runtime/execution-policy/vitest-run-temp-directory.test.mjs +++ b/config/scripts/test-runtime/execution-policy/vitest-run-temp-directory.test.mjs @@ -6,8 +6,11 @@ import { createRunTempDirectory, sweepStaleRunDirectories } from './vitest-run-t const bases = [] +// A run root past 50 chars falls back to /tmp (resolveRunTempBase), so a base under a long TMPDIR (the Linux +// premerge lane's is under the home directory) would test /tmp instead of the base it made. Keep POSIX bases short. function makeBase() { - const base = mkdtempSync(join(tmpdir(), 'orca-run-temp-')) + const root = process.platform === 'win32' ? tmpdir() : '/tmp' + const base = mkdtempSync(join(root, 'ort-')) bases.push(base) return base } diff --git a/mobile/app/cloud/[org]/[number].tsx b/mobile/app/cloud/[org]/[number].tsx index 49412b00873..4bb1296562e 100644 --- a/mobile/app/cloud/[org]/[number].tsx +++ b/mobile/app/cloud/[org]/[number].tsx @@ -6,11 +6,18 @@ import { MobileStateView } from '../../../src/components/MobileStateView' import { CloudWorkspaceScreen } from '../../../src/cloud/CloudWorkspaceScreen' import { resolveCloudWorkspaceLink } from '../../../src/cloud/cloud-workspace-prefs' import { loadCloudControlPlane } from '../../../src/cloud/cloud-session' +import { CloudStateGlyph } from '../../../src/cloud/CloudStateGlyph' +import { setCloudReturnTo } from '../../../src/cloud/cloud-return-to' +import { cloudNumberLinkState } from '../../../src/cloud/cloud-screen-states' import { useMobileTranslation } from '../../../src/i18n/use-mobile-translation' import { colors } from '../../../src/theme/mobile-theme' import { parseCloudWorkspaceLink } from '../../../../src/shared/cloud-workspaces/cloud-workspaces-wire' -type Resolved = { kind: 'loading' } | { kind: 'found'; sandboxId: string } | { kind: 'missing' } +type Resolved = + | { kind: 'loading' } + | { kind: 'found'; sandboxId: string } + | { kind: 'missing' } + | { kind: 'signin' } /** Team links with a number (orca://cloud//W-123, the desktop's "Copy link") open here. */ export default function CloudWorkspaceNumberLinkRoute() { @@ -26,8 +33,17 @@ export default function CloudWorkspaceNumberLinkRoute() { const plane = parsed ? await loadCloudControlPlane() : null const sandboxId = plane && parsed ? await resolveCloudWorkspaceLink(plane, parsed.target) : null + const state = cloudNumberLinkState({ + validLink: parsed !== null, + enrolled: plane !== null, + sandboxId + }) if (live) { - setResolved(sandboxId ? { kind: 'found', sandboxId } : { kind: 'missing' }) + setResolved( + state === 'found' && sandboxId + ? { kind: 'found', sandboxId } + : { kind: state === 'signin' ? 'signin' : 'missing' } + ) } })().catch(() => live && setResolved({ kind: 'missing' })) return () => { @@ -41,6 +57,23 @@ export default function CloudWorkspaceNumberLinkRoute() { {resolved.kind === 'loading' ? ( + ) : resolved.kind === 'signin' ? ( + // Same state as a share link opened before connecting: connect on Home, then come back here. + } + title={t('cloud.workspace.signIn', 'Sign in to Orca Cloud on this phone')} + message={t( + 'cloud.workspace.signInDetail', + 'This link opens a cloud workspace your team shared. Sign in to see it.' + )} + action={{ + label: t('cloud.workspace.signInAction', 'Sign in'), + onPress: () => { + setCloudReturnTo(`/cloud/${params.org ?? ''}/${params.number ?? ''}`) + router.replace('/') + } + }} + /> ) : ( diff --git a/mobile/src/cloud/CloudWorkspaceScreen.tsx b/mobile/src/cloud/CloudWorkspaceScreen.tsx index c5d802b7499..8a83e4018b2 100644 --- a/mobile/src/cloud/CloudWorkspaceScreen.tsx +++ b/mobile/src/cloud/CloudWorkspaceScreen.tsx @@ -333,17 +333,20 @@ export function CloudWorkspaceScreen({ /> ) : null} - - - {t('cloud.prompt.heading', 'Ask an agent')} - - - + {/* Archived is read-only here: nothing can wake it from the phone, so no prompt box. */} + {workspace.status === 'archived' ? null : ( + + + {t('cloud.prompt.heading', 'Ask an agent')} + + + + )} void start('send')} /> diff --git a/mobile/src/cloud/NewCloudWorkspaceScreen.tsx b/mobile/src/cloud/NewCloudWorkspaceScreen.tsx index bace0c8dfb9..d879c7a0655 100644 --- a/mobile/src/cloud/NewCloudWorkspaceScreen.tsx +++ b/mobile/src/cloud/NewCloudWorkspaceScreen.tsx @@ -137,7 +137,7 @@ export function NewCloudWorkspaceScreen() { return } setStartedAt(null) - setError(createErrorMessage(failure, t, role)) + setError(createErrorMessage(failure, t, role, repoUrl)) return } // The sandbox exists from here on: nothing below may report "couldn't create" or create again. diff --git a/mobile/src/cloud/cloud-delivery-run.test.ts b/mobile/src/cloud/cloud-delivery-run.test.ts new file mode 100644 index 00000000000..19e1a178974 --- /dev/null +++ b/mobile/src/cloud/cloud-delivery-run.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest' +import { runCloudDelivery, type CloudDeliveryDeps } from './cloud-delivery-run' +import type { QueuedCloudPrompt } from './cloud-prompt-queue' + +function prompt(id: string, status: QueuedCloudPrompt['status'] = 'queued'): QueuedCloudPrompt { + return { + id, + sandboxId: 'sbx_1', + text: `prompt ${id}`, + agent: 'claude', + operationId: `op-${id}`, + status, + createdAt: 1 + } +} + +/** An in-memory queue with the real delivery rules: failed prompts are skipped, not retried. */ +function fakeQueue(initial: QueuedCloudPrompt[], overrides: Partial = {}) { + let queue = [...initial] + const launched: string[] = [] + const deps: CloudDeliveryDeps = { + listQueued: async () => queue, + ensureWorktree: async () => 'wt-1', + launch: async (_worktreeId, entry) => { + launched.push(entry.id) + return { agent: entry.agent } + }, + deliverQueued: async (_sandboxId, deliver, errorCodeFor) => { + let delivered = 0 + const failed: QueuedCloudPrompt[] = [] + for (const entry of queue.filter((item) => item.status !== 'failed')) { + try { + await deliver(entry) + queue = queue.filter((item) => item.id !== entry.id) + delivered += 1 + } catch (error) { + const code = errorCodeFor(error) + queue = queue.map((item) => + item.id === entry.id ? { ...item, status: 'failed' as const, error: code } : item + ) + failed.push({ ...entry, status: 'failed', error: code }) + } + } + return { delivered, failed } + }, + markWaitingFailed: async (_sandboxId, code) => { + queue = queue.map((item) => + item.status === 'queued' ? { ...item, status: 'failed' as const, error: code } : item + ) + }, + errorCodeFor: (error) => (error instanceof Error ? error.message : 'launch_failed'), + ...overrides + } + return { deps, launched, queue: () => queue } +} + +describe('runCloudDelivery', () => { + it('opens when nothing is waiting, including when only failed prompts are left', async () => { + const empty = fakeQueue([]) + expect(await runCloudDelivery('sbx_1', 'open', empty.deps)).toEqual({ kind: 'open' }) + const onlyFailed = fakeQueue([prompt('a', 'failed')]) + expect(await runCloudDelivery('sbx_1', 'open', onlyFailed.deps)).toEqual({ kind: 'open' }) + expect(onlyFailed.launched).toEqual([]) + }) + + it('reports the last launched agent after a delivery', async () => { + const run = fakeQueue([prompt('a'), prompt('b')]) + expect(await runCloudDelivery('sbx_1', 'send', run.deps)).toEqual({ + kind: 'launched', + worktreeId: 'wt-1', + agent: { agent: 'claude' } + }) + expect(run.launched).toEqual(['a', 'b']) + }) + + it('a prompt that does not start still opens the workspace when the user asked to open it', async () => { + const run = fakeQueue([prompt('a')], { + launch: async () => { + throw new Error('launch_failed') + } + }) + expect(await runCloudDelivery('sbx_1', 'open', run.deps)).toEqual({ + kind: 'failed', + code: null, + open: true + }) + expect(run.queue()[0]).toMatchObject({ status: 'failed', error: 'launch_failed' }) + }) + + it('a failure before any launch marks every waiting prompt failed, so the next Open goes straight in', async () => { + const run = fakeQueue([prompt('a'), prompt('b')], { + ensureWorktree: async () => { + throw new Error('cloud_project_unavailable') + } + }) + expect(await runCloudDelivery('sbx_1', 'send', run.deps)).toEqual({ + kind: 'failed', + code: 'cloud_project_unavailable', + open: false + }) + expect(run.queue().map((entry) => entry.status)).toEqual(['failed', 'failed']) + // The stuck-prompt bug: Open used to re-run this delivery and fail again forever. + expect(await runCloudDelivery('sbx_1', 'open', run.deps)).toEqual({ kind: 'open' }) + }) +}) diff --git a/mobile/src/cloud/cloud-delivery-run.ts b/mobile/src/cloud/cloud-delivery-run.ts new file mode 100644 index 00000000000..06d4b36e8b5 --- /dev/null +++ b/mobile/src/cloud/cloud-delivery-run.ts @@ -0,0 +1,70 @@ +import type { QueuedCloudPrompt } from './cloud-prompt-queue' +import type { CloudLaunchedAgent } from './cloud-workspace-host-operations' + +/** What one delivery pass over a workspace's waiting prompts ended in. */ +export type CloudDeliveryOutcome = + | { kind: 'open' } + | { kind: 'launched'; worktreeId: string; agent: CloudLaunchedAgent } + /** A prompt didn't start. `open`: the user asked to open the workspace, so it opens anyway. */ + | { kind: 'failed'; code: string | null; open: boolean } + +export type CloudDeliveryDeps = { + listQueued: (sandboxId: string) => Promise + ensureWorktree: () => Promise + launch: (worktreeId: string, prompt: QueuedCloudPrompt) => Promise + deliverQueued: ( + sandboxId: string, + deliver: (prompt: QueuedCloudPrompt) => Promise, + errorCodeFor: (error: unknown) => string + ) => Promise<{ delivered: number; failed: QueuedCloudPrompt[] }> + markWaitingFailed: (sandboxId: string, code: string) => Promise + errorCodeFor: (error: unknown) => string +} + +const waiting = (queue: QueuedCloudPrompt[]) => queue.some((prompt) => prompt.status !== 'failed') + +/** + * Sends a workspace's waiting prompts once its host is connected. A prompt that can't start is + * marked failed (shown with Retry and Remove) rather than left waiting, so it never stands between + * the user and the workspace: "Open workspace" opens it whatever the prompts did. + */ +export async function runCloudDelivery( + sandboxId: string, + intent: 'open' | 'send', + deps: CloudDeliveryDeps +): Promise { + if (!waiting(await deps.listQueued(sandboxId))) { + return { kind: 'open' } + } + const launches: CloudLaunchedAgent[] = [] + let worktreeId: string + let failed = 0 + try { + worktreeId = await deps.ensureWorktree() + // Prompts typed while this ran are picked up too, so none is left "waiting" behind it. + for (let round = 0; round < 5; round++) { + const next = await deps.deliverQueued( + sandboxId, + async (prompt) => { + launches.push(await deps.launch(worktreeId, prompt)) + }, + deps.errorCodeFor + ) + failed += next.failed.length + if (next.delivered + next.failed.length === 0 || !waiting(await deps.listQueued(sandboxId))) { + break + } + } + } catch (error) { + // Nothing was launched (the project or connection failed first): every waiting prompt says why + // instead of "Waiting to connect", and Open no longer tries to send them again. + const code = deps.errorCodeFor(error) + await deps.markWaitingFailed(sandboxId, code).catch(() => undefined) + return { kind: 'failed', code, open: intent === 'open' } + } + if (failed > 0) { + return { kind: 'failed', code: null, open: intent === 'open' } + } + const last = launches[launches.length - 1] + return last ? { kind: 'launched', worktreeId, agent: last } : { kind: 'open' } +} diff --git a/mobile/src/cloud/cloud-return-to.ts b/mobile/src/cloud/cloud-return-to.ts index 5a61e05c9e7..94952f1ce68 100644 --- a/mobile/src/cloud/cloud-return-to.ts +++ b/mobile/src/cloud/cloud-return-to.ts @@ -6,8 +6,8 @@ const TTL_MS = 10 * 60_000 let returnTo: { path: string; at: number } | null = null export function setCloudReturnTo(path: string, now: number = Date.now()): void { - // Only an in-app cloud route, never an arbitrary destination. - returnTo = /^\/cloud\/[A-Za-z0-9_-]+$/.test(path) ? { path, at: now } : null + // Only an in-app cloud route (a workspace id, or a team slug and W-number), never anywhere else. + returnTo = /^\/cloud\/[A-Za-z0-9_-]+(?:\/W-[0-9]+)?$/.test(path) ? { path, at: now } : null } export function takeCloudReturnTo(now: number = Date.now()): string | null { diff --git a/mobile/src/cloud/cloud-screen-states.test.ts b/mobile/src/cloud/cloud-screen-states.test.ts index 34683b21133..5fe6a139e78 100644 --- a/mobile/src/cloud/cloud-screen-states.test.ts +++ b/mobile/src/cloud/cloud-screen-states.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { setCloudReturnTo, takeCloudReturnTo } from './cloud-return-to' -import { cloudHostGate, cloudMissingState } from './cloud-screen-states' +import { cloudHostGate, cloudMissingState, cloudNumberLinkState } from './cloud-screen-states' const base = { isPending: false, isFetching: false, isError: false } @@ -62,4 +62,34 @@ describe('return after connecting', () => { setCloudReturnTo('/cloud/sbx_abc', 0) expect(takeCloudReturnTo(11 * 60_000)).toBeNull() }) + + it('returns to a W-number link too, but not to other nested paths', () => { + setCloudReturnTo('/cloud/orca-eval-team/W-589') + expect(takeCloudReturnTo()).toBe('/cloud/orca-eval-team/W-589') + setCloudReturnTo('/cloud/orca-eval-team/settings') + expect(takeCloudReturnTo()).toBeNull() + }) +}) + +describe('W-number link', () => { + it('asks a phone not connected to Orca Cloud to sign in instead of calling it private or deleted', () => { + expect(cloudNumberLinkState({ validLink: true, enrolled: false, sandboxId: null })).toBe( + 'signin' + ) + }) + + it('opens the workspace it resolves to, and is missing when it resolves to none', () => { + expect(cloudNumberLinkState({ validLink: true, enrolled: true, sandboxId: 'sbx_1' })).toBe( + 'found' + ) + expect(cloudNumberLinkState({ validLink: true, enrolled: true, sandboxId: null })).toBe( + 'missing' + ) + }) + + it('is missing when the link is malformed, connected or not', () => { + expect(cloudNumberLinkState({ validLink: false, enrolled: false, sandboxId: null })).toBe( + 'missing' + ) + }) }) diff --git a/mobile/src/cloud/cloud-screen-states.ts b/mobile/src/cloud/cloud-screen-states.ts index a52294cbbbb..2b5e6d60b43 100644 --- a/mobile/src/cloud/cloud-screen-states.ts +++ b/mobile/src/cloud/cloud-screen-states.ts @@ -50,3 +50,24 @@ export function cloudHostGate(args: { } return args.status === 'sleeping' ? 'asleep' : 'pass' } + +export type CloudNumberLinkState = 'signin' | 'found' | 'missing' + +/** + * A W-number link (orca://cloud//W-123). Only the control plane can say which workspace it + * names, so a phone not connected to Orca Cloud asks to sign in, like a share link does, rather + * than calling the workspace private or deleted. A malformed link is missing either way. + */ +export function cloudNumberLinkState(args: { + validLink: boolean + enrolled: boolean + sandboxId: string | null +}): CloudNumberLinkState { + if (!args.validLink) { + return 'missing' + } + if (!args.enrolled) { + return 'signin' + } + return args.sandboxId ? 'found' : 'missing' +} diff --git a/mobile/src/cloud/cloud-workspace-copy.test.ts b/mobile/src/cloud/cloud-workspace-copy.test.ts index 382222ce560..c3d8c532052 100644 --- a/mobile/src/cloud/cloud-workspace-copy.test.ts +++ b/mobile/src/cloud/cloud-workspace-copy.test.ts @@ -13,9 +13,14 @@ vi.mock('./cloud-workspace-attach', () => ({ import type { Translate } from '../i18n/mobile-i18n' import { CloudRequestError } from './cloud-control-plane-request' import { CloudAttachError } from './cloud-workspace-attach' -import { attachErrorMessage, readSnapshotRefusedMessage } from './cloud-workspace-copy' +import { + attachErrorMessage, + createErrorMessage, + readSnapshotRefusedMessage +} from './cloud-workspace-copy' -const t: Translate = (_key, fallback) => fallback +const t: Translate = (_key, fallback, options) => + fallback.replace(/{{(\w+)}}/g, (_match, name: string) => String(options?.[name] ?? '')) describe('cloud workspace copy', () => { it('says a failed wake plainly, and keeps the generic line for anything else', () => { @@ -39,4 +44,23 @@ describe('cloud workspace copy', () => { expect(readSnapshotRefusedMessage('unsigned', t)).toBe(unsigned) expect(readSnapshotRefusedMessage('bad_signature', t)).toBe(unsigned) }) + + it('names the repo and the fix when Orca can’t access it (github_not_connected)', () => { + const denied = new CloudRequestError('conflict', 409, 'github_not_connected') + expect(createErrorMessage(denied, t, null, 'https://github.com/stablyai/orca-cloud')).toBe( + 'Orca can’t access stablyai/orca-cloud. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.' + ) + expect(createErrorMessage(denied, t)).toContain('Orca can’t access this repository.') + // Never the generic line it used to fall back to. + expect(createErrorMessage(denied, t, null, 'https://github.com/a/b')).not.toContain( + 'Couldn’t start' + ) + }) + + it('names the repo when its clone fails', () => { + const clone = new CloudRequestError('provider_unavailable', 503, 'orcad_start_failed') + expect(createErrorMessage(clone, t, null, 'https://github.com/octocat/Hello-World')).toMatch( + /^Couldn’t clone octocat\/Hello-World\. / + ) + }) }) diff --git a/mobile/src/cloud/cloud-workspace-copy.ts b/mobile/src/cloud/cloud-workspace-copy.ts index a05eabf4e15..f6af09c040c 100644 --- a/mobile/src/cloud/cloud-workspace-copy.ts +++ b/mobile/src/cloud/cloud-workspace-copy.ts @@ -5,7 +5,7 @@ import { CloudRequestError } from './cloud-control-plane-request' import type { CloudReadSnapshotRefusedError } from './cloud-read-snapshot' import { CloudAttachError, type CloudAttachPhase } from './cloud-workspace-attach' import { entitlementDeniedMessage } from './cloud-entitlement-copy' -import { formatElapsed } from './cloud-workspace-display' +import { cloudRepoLine, formatElapsed } from './cloud-workspace-display' // What the cloud workspace screen says about each state and failure. @@ -173,8 +173,11 @@ export function cloudPromptErrorMessage(code: string | undefined, t: Translate): export function createErrorMessage( error: unknown, t: Translate, - role: CloudRole | null = null + role: CloudRole | null = null, + /** The repository URL asked for, so the message names what Orca couldn't reach. */ + repoUrl: string | null = null ): string { + const repo = repoUrl ? cloudRepoLine({ repo: { url: repoUrl, branch: null } }) : null if (error instanceof CloudRequestError) { if (error.status === 401) { return t( @@ -185,11 +188,32 @@ export function createErrorMessage( if (error.code === 'entitlement_denied') { return entitlementDeniedMessage(error, role, 'create', t) } + // Not public, and no GitHub connection covers it (private, or a mistyped name). A phone can't + // connect GitHub, so the fix points at the computer, like the desktop's "Give Orca access". + if (error.reason === 'github_not_connected') { + return repo + ? t( + 'cloud.error.repoAccess', + 'Orca can’t access {{repo}}. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.', + { repo } + ) + : t( + 'cloud.error.repoAccessUnnamed', + 'Orca can’t access this repository. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.' + ) + } + // The clone runs in a sandbox that already booted (and was metered): it's deleted, not "never created". if (error.code === 'provider_unavailable' && error.reason === 'orcad_start_failed') { - return t( - 'cloud.error.clone', - 'Couldn’t clone the repository. Check the name and that the Orca Cloud GitHub app can see it. Nothing was created, and you weren’t charged.' - ) + return repo + ? t( + 'cloud.error.cloneNamed', + 'Couldn’t clone {{repo}}. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted.', + { repo } + ) + : t( + 'cloud.error.cloneDeleted', + 'Couldn’t clone the repository. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted.' + ) } if (error.code === 'timeout' || error.code === 'network_error' || error.status >= 500) { return t( diff --git a/mobile/src/cloud/cloud-workspace-display.test.ts b/mobile/src/cloud/cloud-workspace-display.test.ts index 86276028d77..fe0b44db460 100644 --- a/mobile/src/cloud/cloud-workspace-display.test.ts +++ b/mobile/src/cloud/cloud-workspace-display.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { cloudSandboxHours } from './cloud-workspace-display' +import type { Translate } from '../i18n/mobile-i18n' +import { cloudSandboxHours, cloudSpendLine } from './cloud-workspace-display' const HOUR = 3_600_000 @@ -11,3 +12,21 @@ describe('cloudSandboxHours', () => { expect(cloudSandboxHours(0)).toEqual({ value: 0, label: '0' }) }) }) + +describe('cloudSpendLine', () => { + const t: Translate = (_key, fallback) => fallback + it('says an archived workspace uses no hours, not that it is asleep', () => { + const line = cloudSpendLine({ status: 'archived', sandboxMs: 3_600_000 }, null, false, t) + expect(line).toBe('{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours.') + }) + + it('keeps the asleep and running lines', () => { + expect(cloudSpendLine({ status: 'sleeping', sandboxMs: 1 }, null, false, t)).toContain( + 'while asleep' + ) + expect(cloudSpendLine({ status: 'running', sandboxMs: 1 }, null, true, t)).toContain( + 'while running' + ) + expect(cloudSpendLine({ status: 'running', sandboxMs: null }, null, true, t)).toBeNull() + }) +}) diff --git a/mobile/src/cloud/cloud-workspace-display.ts b/mobile/src/cloud/cloud-workspace-display.ts index f1829026a47..f6a945859da 100644 --- a/mobile/src/cloud/cloud-workspace-display.ts +++ b/mobile/src/cloud/cloud-workspace-display.ts @@ -108,3 +108,51 @@ export function nextCloudWorkspaceTitle( } return `${base} ${n}` } + +/** Usage once, honestly: sandbox hours so far (what the plan meters), and whether it is using them + * now. No per-workspace dollars: included hours are not charged. */ +export function cloudSpendLine( + workspace: Pick, + usage: { totalMs: number } | null, + awake: boolean, + t: Translate +): string | null { + const ms = usage ? usage.totalMs : workspace.sandboxMs + if (ms === null) { + return null + } + const { value, label } = cloudSandboxHours(ms) + // Archived is not "asleep" to the user: it can't be woken from here at all. + if (workspace.status === 'archived') { + return t( + 'cloud.usage.archived', + '{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours.', + { + count: value, + hours: label, + defaultValue_one: + '{{hours}} sandbox hour used. Archived workspaces don’t use sandbox hours.' + } + ) + } + if (!awake) { + return t( + 'cloud.usage.asleep', + '{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.', + { + count: value, + hours: label, + defaultValue_one: '{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.' + } + ) + } + return t( + 'cloud.usage.running', + '{{hours}} sandbox hours so far. Uses sandbox hours while running.', + { + count: value, + hours: label, + defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.' + } + ) +} diff --git a/mobile/src/cloud/use-cloud-workspace-run.ts b/mobile/src/cloud/use-cloud-workspace-run.ts index 1343711a618..7b7ccf343cd 100644 --- a/mobile/src/cloud/use-cloud-workspace-run.ts +++ b/mobile/src/cloud/use-cloud-workspace-run.ts @@ -30,6 +30,7 @@ import { launchCloudPrompt, type CloudLaunchedAgent } from './cloud-workspace-host-operations' +import { runCloudDelivery } from './cloud-delivery-run' import { ownerForCloudError, roleForCloudError } from './cloud-entitlement-copy' import { cloudWorkspaceProjectRoot } from './cloud-workspace-links' import { removeHostAndCloseClient } from '../host-catalog/host-removal-lifecycle' @@ -113,76 +114,56 @@ export function useCloudWorkspaceRun(sandboxId: string, workspace: CloudWorkspac deliveryStarted.current = run const client = host.client const hostId = run.hostId + const intent = run.intent void (async () => { - try { - const waiting = await listQueuedCloudPrompts(sandboxId) - if (!waiting.some((prompt) => prompt.status !== 'failed')) { - // Nothing to send: the connection is proven, so open the sandbox's workspaces. - if (mountedRef.current) { - setRun({ kind: 'idle' }) - router.push(`/h/${hostId}`) - } - return - } - const projectRoot = (await cloudWorkspaceProjectRoot(sandboxId)) ?? undefined - const worktreeId = await ensureCloudProjectWorktree(client, projectRoot) - const launches: CloudLaunchedAgent[] = [] - let failed = 0 - // Prompts typed while this ran are picked up too, so none is left "waiting" behind it. - for (let round = 0; round < 5; round++) { - const next = await deliverQueuedCloudPrompts( - sandboxId, - async (prompt) => { - launches.push(await launchCloudPrompt(client, worktreeId, prompt)) - }, - cloudPromptErrorCode - ) - failed += next.failed.length - const pending = await listQueuedCloudPrompts(sandboxId) - if ( - next.delivered + next.failed.length === 0 || - !pending.some((prompt) => prompt.status !== 'failed') - ) { - break - } - } - invalidate() - if (!mountedRef.current) { - return - } - if (failed > 0) { - const stillQueued = (await listQueuedCloudPrompts(sandboxId)).some( - (prompt) => prompt.status !== 'failed' - ) - setRun({ - kind: 'error', - message: t( - 'cloud.error.deliver', - 'The workspace is running, but a prompt didn’t start. Your files are safe.' - ), - retry: stillQueued ? 'send' : null - }) - return - } - const last = launches[launches.length - 1] - if (last) { - // A cloud agent may still need its sign-in: say what happened before dropping into the - // session, and let the user pick the chat or the terminal. - setRun({ kind: 'launched', hostId, worktreeId, agent: last }) - return - } - setRun({ kind: 'idle' }) - router.push(`/h/${hostId}`) - } catch (error) { - if (mountedRef.current) { - // Delivery failures are about the prompt, not the sandbox: say which, never "something". - setRun({ - kind: 'error', - message: cloudPromptErrorMessage(cloudPromptErrorCode(error), t), - retry: 'send' - }) - } + const outcome = await runCloudDelivery(sandboxId, intent, { + listQueued: listQueuedCloudPrompts, + ensureWorktree: async () => + ensureCloudProjectWorktree( + client, + (await cloudWorkspaceProjectRoot(sandboxId)) ?? undefined + ), + launch: (worktreeId, prompt) => launchCloudPrompt(client, worktreeId, prompt), + deliverQueued: deliverQueuedCloudPrompts, + markWaitingFailed: markWaitingCloudPromptsFailed, + errorCodeFor: cloudPromptErrorCode + }).catch((error: unknown) => ({ + kind: 'failed' as const, + code: cloudPromptErrorCode(error), + open: intent === 'open' + })) + invalidate() + if (!mountedRef.current) { + return } + if (outcome.kind === 'launched') { + // A cloud agent may still need its sign-in: say what happened before dropping into the + // session, and let the user pick the chat or the terminal. + setRun({ kind: 'launched', hostId, worktreeId: outcome.worktreeId, agent: outcome.agent }) + return + } + if (outcome.kind === 'failed') { + // Delivery failures are about the prompt, not the sandbox: say which, never "something". + // The failed prompts wait in the list with Retry and Remove; nothing retries them here. + setRun({ + kind: 'error', + message: + outcome.code === null + ? t( + 'cloud.error.deliver', + 'The workspace is running, but a prompt didn’t start. Your files are safe.' + ) + : cloudPromptErrorMessage(outcome.code, t), + retry: null + }) + if (!outcome.open) { + return + } + } else { + setRun({ kind: 'idle' }) + } + // Nothing (more) to send, or the user asked to open: the connection is proven, so open it. + router.push(`/h/${hostId}`) })() }, [run, host.client, host.state, sandboxId, invalidate, router, t, title]) diff --git a/mobile/src/home/home-feed-layout.test.ts b/mobile/src/home/home-feed-layout.test.ts new file mode 100644 index 00000000000..80f1c0e9856 --- /dev/null +++ b/mobile/src/home/home-feed-layout.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { homeFeedLayout } from './home-feed-layout' + +const enrollment = { + controlPlaneUrl: 'https://cp.example', + deviceSessionId: 'ds_1', + label: 'iPhone', + enrolledAt: 1 +} + +describe('homeFeedLayout', () => { + it('waits for the host catalog', () => { + expect(homeFeedLayout({ hostCatalogLoaded: false, hostCount: 0, enrollment })).toBe('loading') + }) + + it('shows the feed whenever a host is paired', () => { + expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 1, enrollment: null })).toBe('feed') + }) + + it('keeps the Cloud section for an enrolled phone with no desktop paired', () => { + expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment })).toBe('feed') + }) + + it('shows the pairing empty state only to a phone with neither', () => { + expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment: null })).toBe( + 'pair-desktop' + ) + expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment: undefined })).toBe( + 'loading' + ) + }) +}) diff --git a/mobile/src/home/home-feed-layout.ts b/mobile/src/home/home-feed-layout.ts new file mode 100644 index 00000000000..7015bb3d447 --- /dev/null +++ b/mobile/src/home/home-feed-layout.ts @@ -0,0 +1,27 @@ +import type { CloudEnrollment } from '../cloud/cloud-device-identity' + +export type HomeFeedLayout = 'loading' | 'pair-desktop' | 'feed' + +/** + * The pairing empty state is only for a phone with nothing to show. A phone enrolled in Orca Cloud + * keeps its Cloud section with no desktop paired (unpaired later, or lost): the workspaces are + * reachable from the phone alone. + */ +export function homeFeedLayout(args: { + hostCatalogLoaded: boolean + hostCount: number + /** `undefined` while the keychain read is in flight. */ + enrollment: CloudEnrollment | null | undefined +}): HomeFeedLayout { + if (!args.hostCatalogLoaded) { + return 'loading' + } + if (args.hostCount > 0) { + return 'feed' + } + // Wait for the enrollment read rather than flash the pairing screen at an enrolled phone. + if (args.enrollment === undefined) { + return 'loading' + } + return args.enrollment ? 'feed' : 'pair-desktop' +} diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index 35bef14f2ac..2b24f959b23 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -12,6 +12,7 @@ import type { AgentListRowHandlers } from '../../agents/MobileAgentListRows' import type { HostCatalogEntry } from '../../host-catalog/host-profile' import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard' import { MobileHomeCloudSection } from '../MobileHomeCloudSection' +import { homeFeedLayout } from '../home-feed-layout' import { MobileHomeEmptyState } from '../MobileHomeEmptyState' import { MobileHomeHostList } from '../MobileHomeHostList' import { MobileHomeActiveAgents } from '../MobileHomeActiveAgents' @@ -52,10 +53,15 @@ export function MobileHomeFeedTab(props: { }, [data.connectedHosts, data.allClients, cloudHostIds]) const title = // Keychain reads can outlast the splash; show the title instead of a blank frame. - if (!data.hostCatalogLoaded) { + const layout = homeFeedLayout({ + hostCatalogLoaded: data.hostCatalogLoaded, + hostCount: data.hostCatalog.length, + enrollment + }) + if (layout === 'loading') { return title } - if (data.hostCatalog.length === 0) { + if (layout === 'pair-desktop') { return ( { const request = EffectiveRequest.safeParse(raw ?? {}) - return request.success ? attempt(client, (c) => c.effective(request.data.repo, undefined, request.data.workspace)) : invalid + return request.success + ? attempt(client, (c) => c.effective(request.data.repo, undefined, request.data.workspace)) + : invalid }) // One desktop-sealed key, unsealed here and sent once to the user's personal Cloud secrets; the // renderer names it (agent + variable) and never sees the value. Each call is one explicit click. diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index b1f8be21a22..fb6d14f4cc2 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -14,6 +14,7 @@ import { CloudWorkspaceListResponseSchema, CloudWorkspacePresenceResponseSchema, CloudWorkspaceResponseSchema, + CloudWorkspaceFollowSchema, OrgPromptsSchema, type CloudWorkspaceLinkTarget, type CloudWorkspaceListQuery, @@ -157,6 +158,9 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption async patch(id: string, patch: CloudWorkspacePatch) { return call('PATCH', ws(id), CloudWorkspaceResponseSchema.extend({}).passthrough(), patch) }, + async follow(id: string, follow: boolean) { + return call(follow ? 'PUT' : 'DELETE', `${ws(id)}/follow`, CloudWorkspaceFollowSchema) + }, async noteSent(id: string) { await call('POST', `${ws(id)}/sent`, NoteSentSchema, {}) }, diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index 9050dd334a3..7a187e5f504 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -213,6 +213,7 @@ export function createCloudWorkspacesService(deps: { return reader.read(id) }), get: (id: string) => wrap(() => client.get(id)), + follow: (id: string, follow: boolean) => wrap(() => client.follow(id, follow)), patch: (id: string, patch: CloudWorkspacePatch) => wrap(async () => (await client.patch(id, patch)).workspace), resolveLink: (target: CloudWorkspaceLinkTarget, chatId?: string | null) => diff --git a/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts index 6f66155bdd8..166b3f7182e 100644 --- a/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts +++ b/src/main/hosted-sandbox/environments/hosted-environment-repo-imports.ts @@ -76,6 +76,7 @@ export async function readRepoSetupImports( return { envVarNames: envNames.names, ...(first ? { installScript: first.setup } : {}), + ...(first?.ubuntuNote ? { ubuntuNote: first.ubuntuNote } : {}), sources } } diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index ed1724d6deb..cd97349d906 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -193,6 +193,15 @@ export function registerCloudWorkspacesHandlers( ? s.patch(parsed.data.id, parsed.data.patch) : INVALID }) + handle('cloudWorkspaces:follow', async (args) => { + const parsed = z.object({ id: Id, follow: z.boolean() }).safeParse(args) + const s = await getService() + return !s + ? NOT_CONFIGURED + : parsed.success + ? s.follow(parsed.data.id, parsed.data.follow) + : INVALID + }) handle('cloudWorkspaces:resolveLink', async (args) => { const parsed = z .object({ target: LinkTarget, chatId: ChatId.nullable().optional() }) diff --git a/src/main/orca-cloud-agents/agent-credentials-client.test.ts b/src/main/orca-cloud-agents/agent-credentials-client.test.ts index 75d83775e35..e6be3aee5e9 100644 --- a/src/main/orca-cloud-agents/agent-credentials-client.test.ts +++ b/src/main/orca-cloud-agents/agent-credentials-client.test.ts @@ -67,6 +67,7 @@ describe('createAgentCredentialsClient', () => { [409, { error: 'broker_in_progress' }], [429, { error: 'rate_limited' }], [502, { error: 'broker_unavailable' }], + [502, { error: 'device_auth_disabled' }], [503, { error: 'no_golden_image' }], [503, { error: 'not_configured' }], [401, { error: 'unauthorized' }] @@ -76,7 +77,7 @@ describe('createAgentCredentialsClient', () => { return Response.json(body, { status }) }) const codes: string[] = [] - for (let i = 0; i < 8; i++) { + for (let i = 0; i < 9; i++) { const error = await failure(() => i < 2 ? client.putClaude(TOKEN) : client.startCodexBroker() ) @@ -90,6 +91,7 @@ describe('createAgentCredentialsClient', () => { 'broker_in_progress', 'rate_limited', 'broker_unavailable', + 'device_auth_disabled', 'no_golden_image', 'not_configured', 'signed_out' diff --git a/src/main/orca-cloud-agents/agent-credentials-client.ts b/src/main/orca-cloud-agents/agent-credentials-client.ts index ae25831114c..4785bad5a11 100644 --- a/src/main/orca-cloud-agents/agent-credentials-client.ts +++ b/src/main/orca-cloud-agents/agent-credentials-client.ts @@ -107,6 +107,7 @@ const SERVER_CODES = new Map([ ['broker_in_progress', 'broker_in_progress'], ['rate_limited', 'rate_limited'], ['broker_unavailable', 'broker_unavailable'], + ['device_auth_disabled', 'device_auth_disabled'], ['no_golden_image', 'no_golden_image'], ['not_configured', 'not_configured'] ]) diff --git a/src/main/orca-cloud-agents/claude-setup-code.test.ts b/src/main/orca-cloud-agents/claude-setup-code.test.ts index 9f43fc3acf2..3307784eeef 100644 --- a/src/main/orca-cloud-agents/claude-setup-code.test.ts +++ b/src/main/orca-cloud-agents/claude-setup-code.test.ts @@ -155,7 +155,6 @@ describe('service: the code from the strip, Settings or the chat UI', () => { children.push(child) return child }, - readClaudeEmail: () => null, openExternal: vi.fn(async () => {}), broadcast: (setups) => broadcasts.push(setups), identity: () => 'p1:u1' diff --git a/src/main/orca-cloud-agents/claude-setup-code.ts b/src/main/orca-cloud-agents/claude-setup-code.ts index a3a41c06f08..762fd0f70b3 100644 --- a/src/main/orca-cloud-agents/claude-setup-code.ts +++ b/src/main/orca-cloud-agents/claude-setup-code.ts @@ -2,8 +2,11 @@ // person pastes it into Orca: the bare `code#state`, or the whole callback URL copied from the address // bar. Normalized here before it is typed into the waiting `claude setup-token`; never logged or kept. -// Anthropic's codes and states are URL-safe base64 joined by '#'. -const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}(?:#[A-Za-z0-9_-]{8,512})?$/ +// Anthropic's codes and states are URL-safe base64 joined by '#'. RS-1: Claude Code (2.1.323, its +// pasted-code prompt) trims the line, splits it on '#', and refuses anything without both halves +// ("Invalid code. Please make sure the full code was copied."), so a code without its state is refused +// here, before it reaches the CLI. +const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}#[A-Za-z0-9_-]{8,512}$/ const CALLBACK_HOSTS = new Set([ 'platform.claude.com', 'console.anthropic.com', @@ -13,7 +16,8 @@ const CALLBACK_HOSTS = new Set([ /** The code the CLI expects, or null when the paste isn't one (the caller says so, without echoing it). */ export function normalizeClaudeSetupCode(raw: string): string | null { - const value = raw.trim() + // A code copied across a wrapped line keeps its pieces; URL-safe base64 has no whitespace of its own. + const value = raw.replace(/\s+/g, '') // A setup-token or API key pasted here is not a sign-in code; it never goes to the CLI's prompt. if (/^sk-ant-/i.test(value)) { return null @@ -30,10 +34,10 @@ export function normalizeClaudeSetupCode(raw: string): string | null { } const code = url.searchParams.get('code') const state = url.searchParams.get('state') - if (!code) { + if (!code || !state) { return null } - const joined = state ? `${code}#${state}` : code + const joined = `${code}#${state}` return CODE_SHAPE.test(joined) ? joined : null } return CODE_SHAPE.test(value) ? value : null diff --git a/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts b/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts new file mode 100644 index 00000000000..abb7429fd85 --- /dev/null +++ b/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts @@ -0,0 +1,151 @@ +// RS-1: `claude setup-token` output and pasted codes as Claude Code really produces them. Every fixture +// below is built from Claude Code 2.1.323's own bundled source (read from the installed CLI binary, never +// run): the success block is +// ✓ Long-lived authentication token created successfully! (Ink ) +// Your OAuth token (valid for ): (gap: 1 between rows) +// (Ink , wraps at width) +// Store this token securely. You won't be able to see it again. +// Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN= +// the sign-in link is an OSC 8 hyperlink (`assumeSupport: true`) around the dim URL text, the prompt is +// "Paste code here if prompted > ", and a pasted line is trimmed and split on '#': without both halves the +// CLI answers "Invalid code. Please make sure the full code was copied."; a code from another sign-in gets +// "That code is not from this sign-in. Paste the code shown after opening the address above."; a code the +// server refuses gets "That code wasn't accepted. It may be incomplete, expired, …". A pseudo-terminal +// ends every line with CRLF. All tokens and codes here are fake. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + findAuthorizeUrl, + findSetupToken, + runClaudeSetupToken, + type SetupTokenProcess +} from './claude-setup-token-runner' +import { normalizeClaudeSetupCode } from './claude-setup-code' + +const TOKEN = `sk-ant-oat01-${'Zz9_-q'.repeat(16)}` +const AUTHORIZE = + 'https://claude.ai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=FAKEstate0123456789' +const ESC = '\u001b' +const green = (text: string) => `${ESC}[32m${text}${ESC}[39m` +const yellow = (text: string) => `${ESC}[33m${text}${ESC}[39m` +const dim = (text: string) => `${ESC}[2m${text}${ESC}[22m` +const osc8 = (url: string, text: string) => `${ESC}]8;;${url}${ESC}\\${text}${ESC}]8;;${ESC}\\` +const crlf = (...lines: string[]) => lines.join('\r\n') + +function successBlock(tokenRows: string[]): string { + return crlf( + '', + green('✓ Long-lived authentication token created successfully!'), + '', + 'Your OAuth token (valid for 1 year):', + '', + ...tokenRows.map(yellow), + '', + dim("Store this token securely. You won't be able to see it again."), + '', + dim('Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN='), + '' + ) +} + +describe('findSetupToken on real output (Claude Code 2.1.323)', () => { + it('reads the token from the CRLF, coloured success block, ignoring the "" hint line', () => { + expect(findSetupToken(successBlock([TOKEN]), false)).toBe(TOKEN) + }) + + it('a token Ink wrapped at the terminal width is joined, never captured cut short', () => { + for (const width of [40, 64, 80]) { + const rows = TOKEN.match(new RegExp(`.{1,${width}}`, 'g')) ?? [] + expect(rows.length).toBeGreaterThan(1) + expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN) + } + }) + + it('a wrapped row padded with trailing spaces (Ink fills the line) still joins', () => { + const rows = [`${TOKEN.slice(0, 50)} `, TOKEN.slice(50)] + expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN) + }) + + it('a banner before and trailing lines after never extend or replace the token', () => { + const banner = crlf(`${ESC}[?25l${ESC}[2K${ESC}[1G${dim('Welcome to Claude Code')}`, '') + const after = crlf('', `${ESC}[?25h`, 'Press Enter to continue') + expect(findSetupToken(`${banner}${successBlock([TOKEN])}${after}`, false)).toBe(TOKEN) + }) +}) + +describe('findAuthorizeUrl on real output (Claude Code 2.1.323)', () => { + it('finds the link inside its OSC 8 hyperlink, with CRLF around it', () => { + const screen = crlf( + `${dim("Browser didn't open? Use the url below to sign in ")}claude.ai`, + osc8(AUTHORIZE, dim(AUTHORIZE)), + '', + 'Paste code here if prompted > ' + ) + expect(findAuthorizeUrl(screen)).toBe(AUTHORIZE) + }) +}) + +describe('normalizeClaudeSetupCode on real pastes', () => { + const CODE = 'FAKEcode0123456789abcdef#FAKEstate0123456789' + it('takes the bare code#state and the full callback URL, both as code#state', () => { + expect(normalizeClaudeSetupCode(` ${CODE}\r\n`)).toBe(CODE) + expect( + normalizeClaudeSetupCode( + 'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef&state=FAKEstate0123456789' + ) + ).toBe(CODE) + }) + it('joins a code copied across a wrapped line', () => { + expect(normalizeClaudeSetupCode('FAKEcode0123\n456789abcdef#FAKEstate01234\r\n56789')).toBe( + CODE + ) + }) + it('refuses a code without its state (the CLI would answer "Invalid code")', () => { + expect(normalizeClaudeSetupCode('FAKEcode0123456789abcdef')).toBeNull() + expect( + normalizeClaudeSetupCode( + 'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef' + ) + ).toBeNull() + }) +}) + +describe('runClaudeSetupToken: the CLI refusing a pasted code (Claude Code 2.1.323 wording)', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + for (const refusal of [ + 'Invalid code. Please make sure the full code was copied.', + 'That code is not from this sign-in. Paste the code shown after opening the address above.', + "That code wasn't accepted. It may be incomplete, expired, already used, or from an earlier sign-in attempt. Sign in again to get a new code." + ]) { + it(`starts over on "${refusal.slice(0, 32)}…"`, async () => { + let onData: (chunk: string) => void = () => {} + const writes: string[] = [] + const child: SetupTokenProcess = { + onData: (listener) => { + onData = listener + }, + onExit: () => {}, + kill: () => {}, + write: (data) => void writes.push(data) + } + const submits: ((code: string) => boolean)[] = [] + const onCodeRejected = vi.fn() + const controller = new AbortController() + void runClaudeSetupToken({ + spawn: async () => child, + signal: controller.signal, + timeoutMs: 60_000, + onAcceptsCode: (submit) => void submits.push(submit), + onCodeRejected + }) + await vi.advanceTimersByTimeAsync(0) + onData(crlf(osc8(AUTHORIZE, AUTHORIZE), 'Paste code here if prompted > ')) + expect(submits[0]?.('FAKEcode0123456789abcdef#FAKEstate0123456789')).toBe(true) + await vi.advanceTimersByTimeAsync(200) + onData(crlf('', refusal, 'Paste code here if prompted > ')) + expect(onCodeRejected).toHaveBeenCalledTimes(1) + controller.abort() + }) + } +}) diff --git a/src/main/orca-cloud-agents/claude-setup-token-runner.ts b/src/main/orca-cloud-agents/claude-setup-token-runner.ts index 1cb3901a860..f28b5286f75 100644 --- a/src/main/orca-cloud-agents/claude-setup-token-runner.ts +++ b/src/main/orca-cloud-agents/claude-setup-token-runner.ts @@ -51,15 +51,41 @@ const DENIED = /\baccess_denied\b|authorization (?:request )?(?:was )?denied|sign-?in (?:was )?denied|login (?:was )?denied/i const AUTHORIZE_HOSTS = new Set(['claude.ai', 'claude.com', 'console.anthropic.com']) const LINK = /https:\/\/[^\s"'<>]+(?=\s)/g -// The CLI's answer to a pasted code it could not exchange; it then waits for Enter to start over. -const CODE_REJECTED = /code wasn.t accepted|Invalid authorization code|OAuth error/i +// The CLI's answer to a pasted code it could not take; it then waits for Enter to start over. RS-1: the +// wording is Claude Code's own (2.1.323): an exchange the server refused ("That code wasn't accepted…"), +// a paste without both halves ("Invalid code. Please make sure the full code was copied."), and a code +// from another sign-in ("That code is not from this sign-in…"). +const CODE_REJECTED = + /code wasn.t accepted|Invalid authorization code|Invalid code\b|code is not from this sign-in|OAuth error/i // Ink reads a chunk ending in Enter as a paste; the code and the Enter go in separately. const ENTER_AFTER_CODE_MS = 150 // Long enough to read the rejection; then Enter starts a fresh sign-in (new link, new code). const RETRY_AFTER_REJECT_MS = 500 function plainText(raw: string): string { - return raw.replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n') + // RS-1: a pseudo-terminal ends lines with CRLF; one line break, not two (a blank line means a gap). + return raw.replace(/\r\n/g, '\n').replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n') +} + +// RS-1: Claude Code prints the token as one Ink , which wraps at the terminal's width (2.1.323: +// `Your OAuth token (valid for …):`, the token, then a blank line and `Store this token securely…`). +// Orca's pty is 1000 columns, so it shouldn't wrap; if it ever does, the continuation is the very next +// line and holds only token characters, while the line after the whole token is blank. Join those, so a +// wrapped token is never captured cut short. +// A line that starts a new copy of the token (a repaint) is never a continuation. +const WRAPPED_TOKEN = + /(sk-ant-oat01-[A-Za-z0-9_-]+)[ \t]*\n[ \t]*(?!sk-ant-)([A-Za-z0-9_-]+)[ \t]*(?=\n|$)/g + +function joinWrappedToken(plain: string): string { + let joined = plain + for (let pass = 0; pass < 8; pass += 1) { + const next = joined.replace(WRAPPED_TOKEN, '$1$2') + if (next === joined) { + return joined + } + joined = next + } + return joined } /** @@ -68,7 +94,7 @@ function plainText(raw: string): string { * a repaint never beats the whole one. Exported for tests; callers never log its result. */ export function findSetupToken(text: string, final: boolean): string | null { - const plain = plainText(text) + const plain = joinWrappedToken(plainText(text)) let found: string | null = null for (const match of plain.matchAll(TOKEN_CANDIDATE)) { const end = (match.index ?? 0) + match[0].length diff --git a/src/main/orca-cloud-agents/codex-broker-driver.test.ts b/src/main/orca-cloud-agents/codex-broker-driver.test.ts index 9078792928b..f6e073f56df 100644 --- a/src/main/orca-cloud-agents/codex-broker-driver.test.ts +++ b/src/main/orca-cloud-agents/codex-broker-driver.test.ts @@ -46,6 +46,12 @@ describe('startCodexBrokerSession', () => { expect(updates.at(-1)).toEqual({ phase: 'failed', error: 'not_a_chatgpt_login' }) }) + it('RS-3: device-code sign-in turned off on the ChatGPT account keeps its own reason', async () => { + const { session, updates } = harness([{ status: 'failed', error: 'device_auth_disabled' }]) + await session.done + expect(updates.at(-1)).toEqual({ phase: 'failed', error: 'device_auth_disabled' }) + }) + it('cancels the broker when the code expires', async () => { const { session, updates, client } = harness( Array.from({ length: 20 }, () => ({ status: 'pending' as const })) diff --git a/src/main/orca-cloud-agents/codex-broker-driver.ts b/src/main/orca-cloud-agents/codex-broker-driver.ts index a37ec5c6c66..32d8164f3c4 100644 --- a/src/main/orca-cloud-agents/codex-broker-driver.ts +++ b/src/main/orca-cloud-agents/codex-broker-driver.ts @@ -44,8 +44,13 @@ const POLL_MS = 3_000 const MAX_WAIT_MS = 20 * 60_000 // A transient poll failure is retried; this many in a row ends the setup. const MAX_POLL_FAILURES = 5 -function isBrokerFailure(error: string): error is 'not_a_chatgpt_login' | 'store_failed' { - return error === 'not_a_chatgpt_login' || error === 'store_failed' +function isBrokerFailure( + error: string +): error is 'not_a_chatgpt_login' | 'store_failed' | 'device_auth_disabled' { + // RS-3: device-code sign-in turned off on the ChatGPT account gets its own words, not "couldn't save". + return ( + error === 'not_a_chatgpt_login' || error === 'store_failed' || error === 'device_auth_disabled' + ) } function defaultSleep(ms: number, signal: AbortSignal): Promise { diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts index a7c0b0e58c1..6c58b52b3b6 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts @@ -9,10 +9,6 @@ import { import { withCloudBuildDefaults } from '../cloud-build-defaults' import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' import { orcaCloudSandboxIdFor } from '../hosted-sandbox/orca-cloud-sandbox-id' -import { - claudeStateFile, - readClaudeFolderLogin -} from '../claude-accounts/sign-in/claude-account-folder' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { getOrcaProfileIndexGeneration } from '../orca-profiles/profile-index-generation' import { createAgentCredentialsClient } from './agent-credentials-client' @@ -61,14 +57,6 @@ function broadcast(setups: OrcaCloudAgentSetups): void { } } -function readClaudeEmail(): string | null { - try { - return readClaudeFolderLogin(claudeStateFile(process.env.CLAUDE_CONFIG_DIR))?.email ?? null - } catch { - return null - } -} - /** The signed-in Orca user, re-read only when the profile index changes (sign-in, sign-out, switch). */ function orcaIdentityReader(userDataPath: string): () => string | null { let cached: { generation: number; identity: string | null } | null = null @@ -110,7 +98,6 @@ function serviceFor(userDataPath: string): OrcaCloudAgentsService { }) : null, spawnSetupToken: spawnClaudeSetupTokenPty, - readClaudeEmail, openExternal: (url) => shell.openExternal(url), broadcast, identity: orcaIdentityReader(userDataPath) diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts index 12f57b6a794..ba4e50bc571 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts @@ -86,7 +86,6 @@ describe('orca cloud agents service', () => { const service = createOrcaCloudAgentsService({ client, spawnSetupToken: async () => child, - readClaudeEmail: () => 'a@acme.dev', openExternal, broadcast: (setups) => broadcasts.push(setups), identity @@ -102,7 +101,7 @@ describe('orca cloud agents service', () => { } } - it('captures the setup-token in main and stores it with the local account as label', async () => { + it('captures the setup-token in main and stores it with no label (RS-5: the server names it truly)', async () => { const { service, child, broadcasts, client, openExternal } = setup() const reply = service.start('claude') await tick() @@ -117,7 +116,8 @@ describe('orca cloud agents service', () => { child.emit(`Your OAuth token (valid for 1 year):\n\n${TOKEN}\n\nStore this token`) child.exit() await tick() - expect(client.putClaude).toHaveBeenCalledWith(TOKEN, 'a@acme.dev') + // RS-5: never this computer's Claude Code email; it may belong to another account. + expect(client.putClaude).toHaveBeenCalledWith(TOKEN, undefined) expect(service.setups().claude).toEqual({ phase: 'saved' }) expectNoToken(reply, broadcasts, service.setups(), await service.status()) }) @@ -211,7 +211,6 @@ describe('orca cloud agents service', () => { const service = createOrcaCloudAgentsService({ client: null, spawnSetupToken: async () => fakeChild(), - readClaudeEmail: () => null, openExternal: vi.fn(), broadcast: vi.fn() }) diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts index 8cfeae10a72..368c01ee56c 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts @@ -29,8 +29,6 @@ import { export type OrcaCloudAgentsServiceDeps = { client: AgentCredentialsClient | null spawnSetupToken: SpawnSetupToken - /** The Claude account signed in on this computer, used as the stored credential's label. */ - readClaudeEmail: () => string | null openExternal: (url: string) => Promise broadcast: (setups: OrcaCloudAgentSetups) => void /** @@ -161,7 +159,8 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) { isSignInUrl: (url) => isProviderSignInUrl('claude', url), onSetup: (setup) => update('claude', setup), onToken: async (token) => { - await storeClaude(token, deps.readClaudeEmail(), owner) + // RS-5: no label: this computer's Claude Code email may be another account's; the server names it. + await storeClaude(token, null, owner) }, onDone: () => { if (claudeRun === run) { diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts index 1cbbb8e9936..184bc6b9860 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts @@ -2,6 +2,7 @@ import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles' import type { ActiveOrcaProfileState } from '../profile-index-store' import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' import { readCloudSession } from '../cloud-session/profile-cloud-session-owner' +import { getReconnectReason } from '../cloud-session/profile-cloud-reconnect-reason' export function getOrcaProfileAuthStatusFromProfile( active: ActiveOrcaProfileState, @@ -48,12 +49,14 @@ export function getOrcaProfileAuthStatusFromProfile( } } + const reconnectReason = getReconnectReason(active.profile.id) return { activeProfileId: active.profile.id, configured, state: 'reconnect-required', persistence: 'none', cloud, + ...(reconnectReason ? { reconnectReason } : {}), credentialError: session.status === 'decrypt-failed' || session.status === 'unreadable' ? session.error diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts index c6285cd2bdf..984326d5da5 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts @@ -38,7 +38,9 @@ export class OrcaCloudRequestError extends Error { // Preserve the server error discriminator so callers can distinguish business 4xx outcomes. constructor( public readonly statusCode: number, - public readonly errorCode?: string + public readonly errorCode?: string, + /** Auth's finer `reason` beside `error` (a refused refresh: expired, revoked, sso_required…). */ + public readonly reason?: string ) { super(`orca_cloud_request_failed_${statusCode}`) this.name = 'OrcaCloudRequestError' @@ -171,18 +173,23 @@ export function isAmbiguousCloudRequestFailure(error: unknown): boolean { } // Proxies, CDNs and gateways answer with HTML; only the auth server's JSON carries a verdict. -async function readCloudErrorCode(response: Response): Promise { +async function readCloudError(response: Response): Promise<{ error?: string; reason?: string }> { if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) { await cancelUnreadResponseBody(response) - return undefined + return {} } try { const body: unknown = await response.json() - return body && typeof body === 'object' && 'error' in body && typeof body.error === 'string' - ? body.error - : undefined + if (!body || typeof body !== 'object') { + return {} + } + return { + ...('error' in body && typeof body.error === 'string' ? { error: body.error } : {}), + // Additive: older auth deployments send no reason. + ...('reason' in body && typeof body.reason === 'string' ? { reason: body.reason } : {}) + } } catch { - return undefined + return {} } } @@ -199,7 +206,8 @@ async function postJson(url: string, body: unknown, options?: PostJsonOptions signal: AbortSignal.timeout(options?.timeoutMs ?? CLOUD_REQUEST_TIMEOUT_MS) }) if (!response.ok) { - throw new OrcaCloudRequestError(response.status, await readCloudErrorCode(response)) + const failure = await readCloudError(response) + throw new OrcaCloudRequestError(response.status, failure.error, failure.reason) } return (await response.json()) as T } diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts index bc6b69f7632..4e56ca68ac8 100644 --- a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts @@ -35,7 +35,7 @@ describe('normalizeTeamMfaPolicy', () => { policy: null, self: 'on', setupUrl, - manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500 } + manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500, ssoHandled: false } }) }) @@ -63,6 +63,34 @@ describe('normalizeTeamMfaPolicy', () => { }) }) +describe('single sign-on', () => { + it('reads the delegated state and the team-level flag', () => { + const read = normalizeTeamMfaPolicy( + { + policy: { enforceAt: 200, setAt: 100 }, + self: { mfa: 'delegated' }, + setupUrl, + available: true, + pendingMembers: 0, + ssoHandled: true + }, + API + ) + expect(read.self).toBe('delegated') + expect(read.manage?.ssoHandled).toBe(true) + }) + + it('treats anything but true as not handled', () => { + for (const ssoHandled of [undefined, 'true', 1, null]) { + const read = normalizeTeamMfaPolicy( + { policy: null, self: { mfa: 'on' }, setupUrl, available: true, ssoHandled }, + API + ) + expect(read.manage?.ssoHandled).toBe(false) + } + }) +}) + describe('normalizePendingMembers', () => { it('keeps members with an email and maps unknown states to off', () => { expect( diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts index 88cb059de74..1ff75093a9d 100644 --- a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts @@ -29,7 +29,14 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null } -const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown'] +const SELF_STATES: readonly OrcaTeamMfaSelfState[] = [ + 'on', + 'off', + 'pending', + 'blocked', + 'unknown', + 'delegated' +] function finiteNumber(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? value : null @@ -80,7 +87,8 @@ export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): Orca manage: { available: record.available, pendingMembers: pendingMembers ?? 0, - ...(inactive !== null ? { inactiveEnforceAt: inactive } : {}) + ...(inactive !== null ? { inactiveEnforceAt: inactive } : {}), + ssoHandled: record.ssoHandled === true } } : {}) @@ -229,6 +237,9 @@ export async function setOrcaTeamMfaPolicy( if (errorCode === 'mfa_enforcement_not_entitled') { return { status: 'not-entitled' } } + if (errorCode === 'sso_team_needs_notice') { + return { status: 'sso-needs-notice' } + } } return unavailable(result) } diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts index 0e65797a227..6fbb301760c 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts @@ -6,7 +6,10 @@ import type { OrcaProfileOrgDeleteResult } from '../../../shared/orca-org-delete' import { ensureActiveOrcaProfile } from '../profile-index-store' -import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from '../cloud-auth/profile-cloud-auth-config' +import { + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from '../cloud-auth/profile-cloud-auth-config' import type { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' import { removeDevOrganization } from '../cloud-auth/profile-cloud-dev-auth' import { runOrgMemberCall } from './profile-cloud-org-members-service' diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts index 90e14c3e393..ef030dc561f 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts @@ -54,7 +54,7 @@ function optionalPictureUrl(value: unknown): string | undefined { } } -const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending'] +const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending', 'sso'] // Absent for plain members (the server leaves it out); an unknown value is dropped, never guessed. function normalizeMemberMfa( @@ -128,7 +128,8 @@ export function normalizeRoster(value: unknown): OrcaOrgMembersRoster { pendingInvites, // Malformed roles must not widen UI permissions; the server still authorizes mutations. viewerRole: normalizeRole(record.viewerRole, 'member'), - canManageMembers: record.canManageMembers === true + canManageMembers: record.canManageMembers === true, + ...(record.directoryManaged === true ? { directoryManaged: true } : {}) } } diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts new file mode 100644 index 00000000000..8aeb7952cac --- /dev/null +++ b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError, refreshOrcaCloudSession } from '../cloud-auth/profile-cloud-client' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { + getReconnectReason, + reconnectReasonFromRefusal, + rememberReconnectReason +} from './profile-cloud-reconnect-reason' + +const base = 'https://auth.test' +const config: OrcaCloudAuthConfig = { + apiBaseUrl: base, + authorizeEndpoint: `${base}/a`, + sessionEndpoint: `${base}/s`, + refreshEndpoint: `${base}/r`, + capabilitiesEndpoint: `${base}/c`, + profileEndpoint: `${base}/p`, + orgEndpoint: `${base}/o`, + logoutEndpoint: `${base}/l`, + relayTokenEndpoint: `${base}/rt`, + connectorTokenEndpoint: `${base}/ct`, + relayDirectorUrl: base, + clientId: 'orca-desktop', + scope: 'openid' +} +const session: OrcaCloudSession = { + accessToken: 'token', + refreshToken: 'refresh', + expiresAt: 0, + capabilities: { flags: {}, refreshedAt: 0 } +} + +afterEach(() => { + vi.unstubAllGlobals() + rememberReconnectReason('p1', undefined) +}) + +async function refusal(body: unknown): Promise { + vi.stubGlobal( + 'fetch', + vi.fn( + async () => + new Response(JSON.stringify(body), { + status: 401, + headers: { 'content-type': 'application/json' } + }) + ) + ) + return refreshOrcaCloudSession(config, session).catch((error: unknown) => error) +} + +describe('why a sign-in ended', () => { + it('a refused refresh carries auth’s reason beside its error', async () => { + const error = await refusal({ error: 'invalid_refresh_token', reason: 'sso_required' }) + expect(error).toBeInstanceOf(OrcaCloudRequestError) + expect(error).toMatchObject({ + statusCode: 401, + errorCode: 'invalid_refresh_token', + reason: 'sso_required' + }) + }) + + it('an older auth with no reason, or a non-string one, reads as none', async () => { + expect(await refusal({ error: 'invalid_refresh_token' })).toMatchObject({ reason: undefined }) + expect(await refusal({ error: 'invalid_refresh_token', reason: 7 })).toMatchObject({ + reason: undefined + }) + }) + + it('only single sign-on is told apart; every other reason stays the generic sign-in-again', () => { + expect(reconnectReasonFromRefusal('sso_required')).toBe('sso-required') + for (const reason of [ + 'expired', + 'signed_out', + 'revoked', + 'reused', + 'something_new', + undefined + ]) { + expect(reconnectReasonFromRefusal(reason)).toBeUndefined() + } + }) + + it('is remembered per profile and cleared by a refusal without one', () => { + rememberReconnectReason('p1', 'sso-required') + expect(getReconnectReason('p1')).toBe('sso-required') + expect(getReconnectReason('p2')).toBeUndefined() + rememberReconnectReason('p1', undefined) + expect(getReconnectReason('p1')).toBeUndefined() + }) +}) diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts new file mode 100644 index 00000000000..a4e33b068b5 --- /dev/null +++ b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts @@ -0,0 +1,31 @@ +// Why auth ended a profile's sign-in, when it said so in a way worth telling the person apart from +// "your session expired". Today that is one case: their team turned on single sign-on, and the +// sign-in they had predates it (refresh refused with `reason: "sso_required"`). +// +// Kept in memory only: after a restart the generic sign-in-again copy shows, which is still true, +// and the sign-in page offers SSO either way. +import type { OrcaProfileReconnectReason } from '../../../shared/orca-profile-reconnect-reason' + +const reasons = new Map() + +/** Auth's `reason` on a refused refresh, mapped to what the app explains; undefined for the rest. */ +export function reconnectReasonFromRefusal( + reason: string | undefined +): OrcaProfileReconnectReason | undefined { + return reason === 'sso_required' ? 'sso-required' : undefined +} + +export function rememberReconnectReason( + profileId: string, + reason: OrcaProfileReconnectReason | undefined +): void { + if (reason) { + reasons.set(profileId, reason) + } else { + reasons.delete(profileId) + } +} + +export function getReconnectReason(profileId: string): OrcaProfileReconnectReason | undefined { + return reasons.get(profileId) +} diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts index f7e33cbb48d..f4dcb66b4ae 100644 --- a/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts @@ -16,6 +16,10 @@ import { wasRefreshTokenAmbiguouslyAttempted } from './profile-cloud-refresh-replay-guard' import { emitOrcaCloudSessionInvalidated } from './profile-cloud-session-invalidation' +import { + reconnectReasonFromRefusal, + rememberReconnectReason +} from './profile-cloud-reconnect-reason' import { commitCloudSessionRotation, readCloudSession, @@ -65,6 +69,14 @@ function isRefreshTokenRejected(error: unknown): boolean { ) } +// Kept before the session is cleared, so the status the renderer re-reads already says why. +function rememberRefusalReason(profileId: string, error: unknown): void { + rememberReconnectReason( + profileId, + reconnectReasonFromRefusal(error instanceof OrcaCloudRequestError ? error.reason : undefined) + ) +} + const inflightCloudSessionRefreshes = new Map>() class StaleCloudSessionMutationError extends Error { @@ -218,6 +230,7 @@ export async function readFreshOrcaCloudSession( } } catch (error) { if (isRefreshTokenRejected(error)) { + rememberRefusalReason(active.profile.id, error) warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session.session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session.session) return { status: 'reconnect-required' } @@ -239,6 +252,7 @@ export async function forceRefreshOrcaCloudSession( } } catch (error) { if (isRefreshTokenRejected(error)) { + rememberRefusalReason(active.profile.id, error) warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session) return { status: 'reconnect-required' } diff --git a/src/main/orca-profiles/profile-cloud-org-members-client.test.ts b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts index 4c4751672ea..d6dffd43062 100644 --- a/src/main/orca-profiles/profile-cloud-org-members-client.test.ts +++ b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts @@ -41,7 +41,8 @@ describe('normalizeRoster', () => { { userId: 'c', email: 'c@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 1_800_000 }, { userId: 'd', email: 'd@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 'soon' }, { userId: 'e', email: 'e@x.dev', role: 'member', mfa: true }, - { userId: 'f', email: 'f@x.dev', role: 'member' } + { userId: 'f', email: 'f@x.dev', role: 'member' }, + { userId: 'g', email: 'g@x.dev', role: 'member', mfa: 'sso' } ] }) expect(roster.members.map((m) => [m.mfa, m.mfaDeadline])).toEqual([ @@ -51,7 +52,8 @@ describe('normalizeRoster', () => { ['pending', 1_800_000], ['pending', undefined], [undefined, undefined], - [undefined, undefined] + [undefined, undefined], + ['sso', undefined] ]) expect('mfa' in roster.members[5]!).toBe(false) }) diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 1a116b3c7d9..8466f5c6dda 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -1,5 +1,6 @@ import type { CloudWorkspace, + CloudWorkspaceFollow, CloudWorkspaceGrant, CloudOrgSlug, CloudWorkspaceLinkTarget, @@ -37,6 +38,8 @@ export type CloudWorkspacesApi = { list: (query: CloudWorkspaceListQuery) => Promise get: (id: string) => Promise> patch: (id: string, patch: CloudWorkspacePatch) => Promise> + /** Follow or unfollow a team workspace (PARITY-FOLLOW): the caller's state and its followers. */ + follow: (id: string, follow: boolean) => Promise> /** Resolves either link form; a slug link for another org fails with reason `other_org` and its `orgId`. */ resolveLink: ( target: CloudWorkspaceLinkTarget, diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index 4a700c65726..33d87488bdc 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -6,6 +6,7 @@ export const cloudWorkspacesApi = { list: (query) => ipcRenderer.invoke('cloudWorkspaces:list', query), get: (id) => ipcRenderer.invoke('cloudWorkspaces:get', { id }), patch: (id, patch) => ipcRenderer.invoke('cloudWorkspaces:patch', { id, patch }), + follow: (id, follow) => ipcRenderer.invoke('cloudWorkspaces:follow', { id, follow }), resolveLink: (target, chatId) => ipcRenderer.invoke('cloudWorkspaces:resolveLink', { target, chatId }), openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }), diff --git a/src/renderer/src/app-shell/TitlebarMainStrip.tsx b/src/renderer/src/app-shell/TitlebarMainStrip.tsx index 8845a4a8c59..7394d0dc8c5 100644 --- a/src/renderer/src/app-shell/TitlebarMainStrip.tsx +++ b/src/renderer/src/app-shell/TitlebarMainStrip.tsx @@ -11,6 +11,7 @@ import { hasCustomTitleBar } from './app-window-chrome' import type { AppChromeLayout } from './use-app-chrome-layout' import { RunActionButton } from '../components/run-actions/RunActionButton' import { CloudWorkspaceNumberChip } from '../components/cloud-workspaces/CloudWorkspaceNumberChip' +import { CloudWorkspacePeople } from '../components/cloud-workspaces/CloudWorkspacePeople' export function RightSidebarToggle(): React.JSX.Element { const t = useTranslate() @@ -70,7 +71,10 @@ export function TitlebarMainStrip({ layout }: { layout: AppChromeLayout }): Reac /> )} {layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? ( - + <> + + + ) : null} {layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? ( diff --git a/src/renderer/src/components/UnexpectedSignoutCard.tsx b/src/renderer/src/components/UnexpectedSignoutCard.tsx index 86dc10bc0f8..19ffa36ec88 100644 --- a/src/renderer/src/components/UnexpectedSignoutCard.tsx +++ b/src/renderer/src/components/UnexpectedSignoutCard.tsx @@ -175,16 +175,21 @@ export function UnexpectedSignoutCard(): React.JSX.Element | null {

- {email + {authStatus?.reconnectReason === 'sso-required' ? t( - 'auto.components.UnexpectedSignoutCard.7b4d9e1f2a', - 'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.', - { value0: email } + 'auto.components.UnexpectedSignoutCard.ssoRequired', + 'Your team now requires single sign-on. Sign in again and choose Sign in with SSO.' ) - : t( - 'auto.components.UnexpectedSignoutCard.5a1c8d3e6f', - 'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.' - )} + : email + ? t( + 'auto.components.UnexpectedSignoutCard.7b4d9e1f2a', + 'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.', + { value0: email } + ) + : t( + 'auto.components.UnexpectedSignoutCard.5a1c8d3e6f', + 'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.' + )}

diff --git a/src/renderer/src/components/agent-host-panel/cloud-sections/cloud-panel-sections-model.test.ts b/src/renderer/src/components/agent-host-panel/cloud-sections/cloud-panel-sections-model.test.ts index c45c8ee56db..89423a5f2c9 100644 --- a/src/renderer/src/components/agent-host-panel/cloud-sections/cloud-panel-sections-model.test.ts +++ b/src/renderer/src/components/agent-host-panel/cloud-sections/cloud-panel-sections-model.test.ts @@ -113,8 +113,10 @@ describe('shared workspaces (D13)', () => { expect(owner.withoutPersonal).toBe(true) expect(owner.missing).toEqual(['NPM_TOKEN']) expect( - cloudPanelSectionsData({ ...base, sharing: { shared: false, ownerName: null, isOwner: true } }) - .missing + cloudPanelSectionsData({ + ...base, + sharing: { shared: false, ownerName: null, isOwner: true } + }).missing ).toEqual([]) }) diff --git a/src/renderer/src/components/agent-pane/SecretRequestCard.tsx b/src/renderer/src/components/agent-pane/SecretRequestCard.tsx index 27923d79580..5f29edaa866 100644 --- a/src/renderer/src/components/agent-pane/SecretRequestCard.tsx +++ b/src/renderer/src/components/agent-pane/SecretRequestCard.tsx @@ -250,64 +250,64 @@ export function SecretRequestCard({ density="compact" /> ) : ( -
- -
-
{ - if (event.key === 'Enter' && canSave) { - event.preventDefault() - actions.onAdd() - } - }} - > - + +
+
{ + if (event.key === 'Enter' && canSave) { + event.preventDefault() + actions.onAdd() + } + }} + > + +
+
- + {model.fieldError ? ( + + ) : null} +

+ {t( + 'secretRequest.helpBeforeSave', + 'Saves to your Cloud secrets. Commands in this workspace can read it as ${{name}}.', + { name: model.name } + )} + {model.sharedWorkspace + ? ` ${t( + 'secretRequest.sharedRepoOnly', + 'This workspace is shared, so it only gets repository and shared values.' + )}` + : null} +

+ {model.suggestedRepo && model.scopes.includes('repo') ? ( +

+ {t('secretRequest.repoHint', '{{agent}} suggested Repository', { + agent: agentName + })} +

+ ) : null}
- {model.fieldError ? ( - - ) : null} -

- {t( - 'secretRequest.helpBeforeSave', - 'Saves to your Cloud secrets. Commands in this workspace can read it as ${{name}}.', - { name: model.name } - )} - {model.sharedWorkspace - ? ` ${t( - 'secretRequest.sharedRepoOnly', - 'This workspace is shared, so it only gets repository and shared values.' - )}` - : null} -

- {model.suggestedRepo && model.scopes.includes('repo') ? ( -

- {t('secretRequest.repoHint', '{{agent}} suggested Repository', { - agent: agentName - })} -

- ) : null} -
)} {model.phase === 'failed' ? ( >() + +export function canWriteRepo(repoKey: string): Promise { + let pending = repoWriteCache.get(repoKey) + if (!pending) { + const api = window.api.cloudSecrets + pending = api + ? api.effective({ repo: repoKey }).then( + (result) => result.ok && result.value.caller.canWrite.repo, + () => false + ) + : Promise.resolve(false) + // A failed read is retried next time rather than cached as "no". + void pending.then((value) => { + if (!value) { + repoWriteCache.delete(repoKey) + } + }) + repoWriteCache.set(repoKey, pending) + } + return pending +} + +export function resetSecretRequestCardCachesForTests(): void { + repoWriteCache.clear() +} diff --git a/src/renderer/src/components/agent-pane/use-secret-request-card.test.tsx b/src/renderer/src/components/agent-pane/use-secret-request-card.test.tsx index 136d4543f70..c54f49659b2 100644 --- a/src/renderer/src/components/agent-pane/use-secret-request-card.test.tsx +++ b/src/renderer/src/components/agent-pane/use-secret-request-card.test.tsx @@ -108,7 +108,9 @@ describe('S4-b secret request card', () => { render() await act(async () => {}) expect(workspaceSharing).toHaveBeenCalledWith({ runtimeEnvironmentId: 'env-1' }) - expect(screen.getByText('This workspace is shared, so it doesn’t get personal secrets.')).toBeTruthy() + expect( + screen.getByText('This workspace is shared, so it doesn’t get personal secrets.') + ).toBeTruthy() expect(screen.queryByLabelText('Value for NPM_TOKEN')).toBeNull() expect(screen.getByRole('button', { name: 'Add secret' }).getAttribute('aria-disabled')).toBe( 'true' diff --git a/src/renderer/src/components/agent-pane/use-secret-request-card.ts b/src/renderer/src/components/agent-pane/use-secret-request-card.ts index 9c944273351..c5b23277ad7 100644 --- a/src/renderer/src/components/agent-pane/use-secret-request-card.ts +++ b/src/renderer/src/components/agent-pane/use-secret-request-card.ts @@ -29,6 +29,7 @@ import { } from '../../../../shared/secret-request-contract' import { cloudWorkspaceSecretsMode } from '@/lib/orca-cloud/cloud-workspace-secrets-mode' import type { CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire' +import { canWriteRepo } from './secret-request-repo-write' import type { SecretRequestCardActions, SecretRequestCardModel, @@ -46,33 +47,7 @@ const TRANSPORT_FAILURES: ReadonlySet = new Set([ 'unknown' ]) -/** Whether this person can write the workspace repo's scope; asked once per repo per session. */ -const repoWriteCache = new Map>() - -function canWriteRepo(repoKey: string): Promise { - let pending = repoWriteCache.get(repoKey) - if (!pending) { - const api = window.api.cloudSecrets - pending = api - ? api.effective({ repo: repoKey }).then( - (result) => result.ok && result.value.caller.canWrite.repo, - () => false - ) - : Promise.resolve(false) - // A failed read is retried next time rather than cached as "no". - void pending.then((value) => { - if (!value) { - repoWriteCache.delete(repoKey) - } - }) - repoWriteCache.set(repoKey, pending) - } - return pending -} - -export function resetSecretRequestCardCachesForTests(): void { - repoWriteCache.clear() -} +export { resetSecretRequestCardCachesForTests } from './secret-request-repo-write' function useWorkspaceRepoKey(worktreeId: string | null): string | null { return useAppStore((state) => { @@ -220,7 +195,9 @@ export function useSecretRequestCard(args: { : repoScope ? ['personal', 'repo'] : ['personal'] - const effectiveScope: SecretRequestScope = scopes.includes(scope) ? scope : (scopes[0] ?? 'personal') + const effectiveScope: SecretRequestScope = scopes.includes(scope) + ? scope + : (scopes[0] ?? 'personal') const add = useCallback(async () => { const api = window.api.cloudSecrets @@ -259,7 +236,17 @@ export function useSecretRequestCard(args: { requestId, outcome === 'provided' ? 'saved' : 'savedAfterExpiry' ) - }, [value, local, scopes.length, environmentId, requestId, effectiveScope, repoKey, event.name, t]) + }, [ + value, + local, + scopes.length, + environmentId, + requestId, + effectiveScope, + repoKey, + event.name, + t + ]) const phase: SecretRequestCardPhase = local === 'saving' diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx index a35a5426763..96da8d236e0 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.fixture.tsx @@ -354,3 +354,9 @@ function AwaitingPane({
) } + +/** RS-3: device code sign-in is off for this ChatGPT account (a fixable setting: amber, not red). */ +export const notSetUpDeviceAuthOff = fixture({ + agent: 'codex', + setUp: { setup: { phase: 'failed', error: 'device_auth_disabled' } } +}) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts index 549ff3d28f6..4fc8cb3a779 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts @@ -2,7 +2,10 @@ // once" runs the same one-time setup as Settings › Accounts › Orca Cloud (S0) right in the pane, // and once it's saved the strip offers "Start {{agent}}". Pure: the strip renders what this returns. import type { Translate } from '@/i18n/use-translate' -import { setupFailureCopy } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' +import { + setupFailureCopy, + setupFailureTone +} from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' import type { OrcaCloudAgentSetup } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' import { HOST_AGENT_SIGN_IN_AGENT_NAME } from '../../../../shared/host-agent-sign-in-status' @@ -206,7 +209,7 @@ export function cloudAgentSetupStripModel(args: { const copy = setupFailureCopy(args.agent, setup.error, t) return { ...need, - status: 'error', + status: setupFailureTone(setup.error), title: copy.title, detail: copy.detail ?? need.detail, // An expired sign-in: "Open again" starts a fresh one with a new link (main restarts it). diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx index 849ae209ecc..7faca646904 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -102,8 +102,8 @@ it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRol const { container } = renderList({ ...rosterWithMfa, viewerRole }, 'u-neil') const cell = (key: string): Element => container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)! - expect(cell('member:u-neil').textContent).toBe('MFA on') - expect(cell('member:u-grace').textContent).toBe('MFA due Nov 24') + expect(cell('member:u-neil').textContent).toBe('2FA on') + expect(cell('member:u-grace').textContent).toBe('2FA due Nov 24') // A small muted badge, not bare text. expect(cell('member:u-neil').querySelector('[data-slot="badge"]')).not.toBeNull() // Invites keep an empty cell so the role column stays aligned. @@ -134,7 +134,7 @@ it('leaves the cell blank, not "off", for a member with no status', () => { ) const cell = (key: string): Element => container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)! - expect(cell('member:u-neil').textContent).toBe('MFA off') + expect(cell('member:u-neil').textContent).toBe('2FA off') expect(cell('member:u-grace').textContent).toBe('') }) @@ -154,3 +154,51 @@ it('shows no MFA badge for a member who has not signed in yet', () => { )! expect(pending.textContent).toBe('') }) + +it('a team its identity provider manages: no role or remove controls, and the row says why', () => { + const managed = teamRows({ ...roster, directoryManaged: true }, 'u-neil') + expect(managed.map((row) => [row.key, row.manageable])).toEqual([ + ['member:u-neil', false], + ['member:u-grace', false] + ]) + const { container } = render( + + ) + const grace = container.querySelector('[data-team-row="member:u-grace"]')! + // The role is text, not a select, and names the identity provider as its owner. + expect(grace.querySelector('[role="combobox"]')).toBeNull() + expect(grace.querySelector('[title="Managed by your identity provider"]')?.textContent).toBe( + 'Member' + ) + // Without the flag the owner can still manage the same member. + expect(teamRows(roster, 'u-neil').find((row) => row.key === 'member:u-grace')?.manageable).toBe( + true + ) +}) + +it('shows a member whose two-factor is their identity provider’s as via SSO', () => { + const { container } = renderList( + { + ...roster, + members: [ + { ...roster.members[0]!, mfa: 'on' }, + { ...roster.members[1]!, mfa: 'sso' } + ] + }, + 'u-neil' + ) + const cell = container.querySelector('[data-team-row="member:u-grace"] [data-team-mfa]')! + expect(cell.textContent).toBe('2FA via SSO') +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index c23a07c9b61..099ec1be9d4 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -82,7 +82,14 @@ function RoleControl({ const member = row.member if (!row.manageable) { return ( - + {roleLabel(member.role, t)} ) diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index 71edf46cc16..0b4ff7616eb 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -231,6 +231,14 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { ) : null} + {roster?.directoryManaged ? ( +

+ {t( + 'auto.components.billing.team.managedByIdpNote', + 'Managed by your identity provider. Add or remove people and change roles there.' + )} +

+ ) : null} {roster ? ( {} + +function panel(outcome: 'installed' | 'skipped') { + const builds = sampleHistory + .slice(2) + .map((build) => + build.active ? { ...build, autoInstall: { manager: 'pnpm' as const, outcome } } : build + ) + const active = builds.find((build) => build.active) ?? builds[0] + return defineFixture({ + width: 760, + render: () => ( + ({ + ok: true as const, + data: { envVarNames: [], sources: [] } + }), + onSave: noop + }} + onBuild={noop} + onCancel={noop} + onActivate={noop} + onSelectBuild={noop} + onConfigureWithAgent={noop} + onFixWithAgent={null} + onGiveAccess={null} + /> + ) + }) +} + +/** Dependencies installed from the lockfile. */ +export const autoInstalled = panel('installed') +/** The lockfile install failed (often a lockfile out of date); workspaces run their own setup. */ +export const autoSkipped = panel('skipped') diff --git a/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx b/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx index 1a07324b2a6..a88e0e0cd2f 100644 --- a/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx +++ b/src/renderer/src/components/cloud-environment/CloudEnvironmentPanel.tsx @@ -121,6 +121,23 @@ export function CloudEnvironmentPanel(props: CloudEnvironmentPanelProps): React.

{environment.repos.map((repo) => repoDisplayName(repo.url)).join(', ')}

+ {activeBuild?.autoInstall ? ( +

+ {activeBuild.autoInstall.outcome === 'installed' + ? t( + 'cloudEnvironment.header.depsInstalled', + 'Dependencies installed with {{manager}}', + { + manager: activeBuild.autoInstall.manager + } + ) + : t( + 'cloudEnvironment.header.depsSkipped', + 'Dependencies weren’t installed because {{manager}} install failed. New workspaces start without them.', + { manager: activeBuild.autoInstall.manager } + )} +

+ ) : null} {canAdmin ? (
diff --git a/src/renderer/src/components/cloud-environment/ImportFromRepoDialog.tsx b/src/renderer/src/components/cloud-environment/ImportFromRepoDialog.tsx index 07d96012efe..b1c1db868a0 100644 --- a/src/renderer/src/components/cloud-environment/ImportFromRepoDialog.tsx +++ b/src/renderer/src/components/cloud-environment/ImportFromRepoDialog.tsx @@ -1,3 +1,4 @@ +import { UbuntuSetupNote } from '@/components/sidebar/UbuntuSetupNote' import { useState } from 'react' import { Checkbox } from '@/components/ui/checkbox' import { Button } from '@/components/ui/button' @@ -173,6 +174,9 @@ function ImportReviewContent({
))} + {review.imports.ubuntuNote ? ( + + ) : null} ) : null} diff --git a/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.test.ts b/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.test.ts index 60397905026..5504d37546f 100644 --- a/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.test.ts +++ b/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.test.ts @@ -89,8 +89,12 @@ describe('writableScopes', () => { canWrite: { personal: true, org: false, repo: true } } expect(askScopes({ caller: MEMBER, repoKey: 'github.com/a/b', shared: true })).toEqual([]) - expect(askScopes({ caller: repoWriter, repoKey: 'github.com/a/b', shared: true })).toEqual(['repo']) - expect(askScopes({ caller: MEMBER, repoKey: 'github.com/a/b', shared: false })).toEqual(['personal']) + expect(askScopes({ caller: repoWriter, repoKey: 'github.com/a/b', shared: true })).toEqual([ + 'repo' + ]) + expect(askScopes({ caller: MEMBER, repoKey: 'github.com/a/b', shared: false })).toEqual([ + 'personal' + ]) }) }) diff --git a/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.ts b/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.ts index eb5538c0e43..22cc8472f66 100644 --- a/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.ts +++ b/src/renderer/src/components/cloud-secrets-ask/cloud-secrets-ask-model.ts @@ -93,7 +93,9 @@ export type CloudSecretsAskData = { } /** Where this person can save a missing value for this workspace; empty when nowhere reaches it. */ -export function askScopes(data: Pick): CloudSecretScope[] { +export function askScopes( + data: Pick +): CloudSecretScope[] { return writableScopes(data.caller, { repo: data.repoKey !== null, shared: true, diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.fixture.tsx new file mode 100644 index 00000000000..ad77273d8d5 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.fixture.tsx @@ -0,0 +1,81 @@ +// PARITY-FOLLOW (design review): the top bar's people on a cloud workspace, beside W-123. +import { defineFixture } from '../../component-fixtures/component-fixture' +import { CloudWorkspaceFollowers, workspaceFollowerEntries } from './CloudWorkspaceFollowers' +import { DIRECTORY, presence, SELF_ID } from './cloud-workspaces.test-fixture' + +function Bar({ label, children }: { label: string; children: React.ReactNode }): React.JSX.Element { + return ( +
+ {label} + {/* Stands in for the top bar's right side: the stack, then the W-123 chip. */} +
+ {children} + + W-582 + +
+
+ ) +} + +const noop = (): void => {} + +/** Creator first; followers; people here now ringed in their color; typing pulses; Follow last. */ +export const followerStacks = defineFixture({ + width: 640, + render: () => ( +
+ + + + + + + + + + + + +
+ ) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.test.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.test.tsx new file mode 100644 index 00000000000..14a62d10237 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.test.tsx @@ -0,0 +1,88 @@ +// @vitest-environment happy-dom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { CloudWorkspaceFollowers, workspaceFollowerEntries } from './CloudWorkspaceFollowers' +import { DIRECTORY, presence, SELF_ID } from './cloud-workspaces.test-fixture' + +afterEach(() => cleanup()) + +describe('workspaceFollowerEntries (PARITY-FOLLOW)', () => { + it('lists the creator, then followers, then visitors, each once, with live state', () => { + expect( + workspaceFollowerEntries({ + creatorId: 'user_grace', + followers: ['user_linus', 'user_grace'], + presence: [ + presence('user_mae'), + presence('user_grace', 'typing'), + { ...presence('user_mae', 'typing'), clientId: 'laptop-2' } + ] + }) + ).toEqual([ + { userId: 'user_grace', role: 'creator', state: 'typing' }, + { userId: 'user_linus', role: 'follower', state: null }, + { userId: 'user_mae', role: 'visitor', state: 'typing' } + ]) + }) +}) + +describe('CloudWorkspaceFollowers (PARITY-FOLLOW)', () => { + const entries = workspaceFollowerEntries({ + creatorId: 'user_grace', + followers: ['user_linus', 'user_mae', 'user_alan', SELF_ID], + presence: [presence('user_linus', 'typing')] + }) + + it('caps at 3 avatars with +N, says roles and presence in words, and leaves you out', () => { + render( + + {}} + /> + + ) + const people = screen.getAllByRole('button', { name: /·/ }) + expect(people.map((p) => p.getAttribute('aria-label'))).toEqual([ + 'Grace Hopper · Created this workspace', + 'Linus Park · Following · Typing now', + 'Mae Jemison · Following' + ]) + expect(screen.getByText('+1')).not.toBeNull() + expect(screen.queryByRole('button', { name: /Lovelace/ })).toBeNull() + }) + + it('offers Follow, and Following toggles back', () => { + const toggle = vi.fn() + const { rerender } = render( + + + + ) + fireEvent.click(screen.getByRole('button', { name: 'Follow' })) + expect(toggle).toHaveBeenCalledTimes(1) + rerender( + + + + ) + expect(screen.queryByRole('button', { name: 'Follow' })).toBeNull() + expect(screen.queryByRole('button', { name: /^(Following|Unfollow)/ })).toBeNull() + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.tsx new file mode 100644 index 00000000000..80ddb6559a5 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceFollowers.tsx @@ -0,0 +1,202 @@ +// PARITY-FOLLOW: who is on a cloud workspace, beside its W-123 chip in the top bar. The creator +// comes first, then the people following it, then anyone else looking at it now. Someone viewing +// gets a ring in their own color; typing adds the pulsing dot the picker rows use. "Follow" keeps a +// teammate's workspace in the sidebar's Following section until it is unfollowed. +import React from 'react' +import { Check, Plus } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/class-names' +import type { CloudWorkspacePresence } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { MemberAvatar } from './CloudMemberAvatars' +import { memberHue, memberName, type MemberDirectory } from './cloud-workspace-format' + +export type WorkspaceFollowerRole = 'creator' | 'follower' | 'visitor' + +export type WorkspaceFollowerEntry = { + userId: string + role: WorkspaceFollowerRole + /** Live presence on this workspace now, or null. */ + state: 'viewing' | 'typing' | null +} + +/** Creator, then followers (oldest follow first), then present visitors; each member once. */ +export function workspaceFollowerEntries(args: { + creatorId: string + followers: readonly string[] + presence: readonly CloudWorkspacePresence[] +}): WorkspaceFollowerEntry[] { + const live = new Map() + for (const p of args.presence) { + // A member typing on one device and viewing on another reads as typing. + if (live.get(p.userId) !== 'typing') { + live.set(p.userId, p.state) + } + } + const seen = new Set() + const out: WorkspaceFollowerEntry[] = [] + const add = (userId: string, role: WorkspaceFollowerRole): void => { + if (!seen.has(userId)) { + seen.add(userId) + out.push({ userId, role, state: live.get(userId) ?? null }) + } + } + add(args.creatorId, 'creator') + for (const id of args.followers) { + add(id, 'follower') + } + for (const id of live.keys()) { + add(id, 'visitor') + } + return out +} + +function entryLabel( + entry: WorkspaceFollowerEntry, + name: string, + t: ReturnType +): string { + const role = + entry.role === 'creator' + ? t('cloudFollow.role.creator', 'Created this workspace') + : entry.role === 'follower' + ? t('cloudFollow.role.follower', 'Following') + : null + const now = + entry.state === 'typing' + ? t('cloudFollow.state.typing', 'Typing now') + : entry.state === 'viewing' + ? t('cloudFollow.state.viewing', 'Here now') + : null + return [name, role, now].filter(Boolean).join(' · ') +} + +export function CloudWorkspaceFollowers({ + entries, + directory, + selfId, + following, + busy = false, + onToggleFollow, + onOpenMember, + max = 3 +}: { + entries: WorkspaceFollowerEntry[] + directory: MemberDirectory + selfId: string | null + /** Null hides Follow: the creator's own workspace, or a control plane without follows. */ + following: boolean | null + busy?: boolean + onToggleFollow?: () => void + /** Opens the teammate's profile. */ + onOpenMember?: (userId: string) => void + max?: number +}): React.JSX.Element | null { + const t = useTranslate() + const others = entries.filter((e) => e.userId !== selfId || e.role === 'creator') + if (others.length === 0 && following === null) { + return null + } + const shown = others.slice(0, max) + const extra = others.length - shown.length + return ( +
+ + {shown.map((entry) => { + const name = memberName(directory, entry.userId, selfId, t) + const label = entryLabel(entry, name, t) + const ring: React.CSSProperties & { '--avatar-hue': string } = { + '--avatar-hue': String(memberHue(entry.userId)) + } + return ( + + + + + + {label} + + + ) + })} + {extra > 0 ? ( + + + + +{extra} + + {t('auto.components.cloudWorkspaces.moreMembers', '{{count}} more', { + count: extra + })} + + + + {/* The full list, so the cap never hides who is here. */} + + {others.slice(max).map((entry) => ( +
+ {entryLabel(entry, memberName(directory, entry.userId, selfId, t), t)} +
+ ))} +
+
+ ) : null} +
+ {following !== null && onToggleFollow ? ( + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx new file mode 100644 index 00000000000..5fae8cac16a --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacePeople.tsx @@ -0,0 +1,84 @@ +// PARITY-FOLLOW: the people on the cloud workspace in front, beside its W-123 chip: its creator, +// its followers and who is here now, then Follow. Nothing for a local workspace, a personal +// account, or a workspace only you are on and nobody else could follow. +import React, { useState } from 'react' +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' +import { openTeammateProfile } from '@/components/teammates/teammate-profile-store' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { sandboxIdForWorktree, useCloudWorkspaceIdentities } from './cloud-workspace-identity' +import { CloudWorkspaceFollowers, workspaceFollowerEntries } from './CloudWorkspaceFollowers' +import { setCloudWorkspaceFollow, useTeamWorkspacesLive } from './team-workspaces-live' +import { useMemberDirectory } from './use-cloud-workspace-row-actions' +import { useCloudWorkspacesAvailable } from './use-cloud-workspaces' + +/** + * Follow is offered on a teammate's team workspace; never on your own (it is yours already), and not + * by a control plane that predates follows (`following` absent). + */ +export function followOffer(workspace: CloudWorkspace, selfId: string | null): boolean | null { + if (workspace.following === undefined || workspace.createdBy === selfId) { + return null + } + return workspace.following +} + +export function CloudWorkspacePeople({ + worktreeId +}: { + worktreeId: string +}): React.JSX.Element | null { + const t = useTranslate() + const cloud = useAppStore((s) => s.orcaProfileAuthStatus?.cloud) + const hostId = useAppStore((s) => s.activeWorkspaceExecutionHostId) + const account = useOrcaAccountKey() + const available = useCloudWorkspacesAvailable() + const identities = useCloudWorkspaceIdentities() + const [busy, setBusy] = useState(false) + const orgId = cloud?.activeOrgId ?? null + const selfId = cloud?.userId ?? null + const sandboxId = sandboxIdForWorktree({ id: worktreeId, hostId }, identities) + const live = useTeamWorkspacesLive(orgId && available && sandboxId ? account : null) + const workspace = sandboxId ? (live?.find((w) => w.id === sandboxId) ?? null) : null + const { directory } = useMemberDirectory(orgId ?? undefined, workspace ? [workspace] : []) + if (!workspace) { + return null + } + const following = followOffer(workspace, selfId) + const entries = workspaceFollowerEntries({ + creatorId: workspace.createdBy, + followers: workspace.followers ?? [], + presence: workspace.presence + }) + // Only you, on your own workspace: nothing to show. + if (following === null && entries.every((e) => e.userId === selfId)) { + return null + } + const toggle = (): void => { + const next = !following + setBusy(true) + void setCloudWorkspaceFollow(workspace.id, next).then((ok) => { + setBusy(false) + if (!ok) { + toast.error( + next + ? t('cloudFollow.followFailed', 'Couldn’t follow this workspace') + : t('cloudFollow.unfollowFailed', 'Couldn’t unfollow this workspace') + ) + } + }) + } + return ( + (userId === selfId ? undefined : openTeammateProfile(userId))} + /> + ) +} diff --git a/src/renderer/src/components/cloud-workspaces/team-workspaces-live.test.tsx b/src/renderer/src/components/cloud-workspaces/team-workspaces-live.test.tsx new file mode 100644 index 00000000000..23a2504fb5c --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/team-workspaces-live.test.tsx @@ -0,0 +1,60 @@ +// @vitest-environment happy-dom + +import { cleanup, render, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + setCloudWorkspaceFollow, + setTeamWorkspacesLiveForTests, + useTeamWorkspacesLive +} from './team-workspaces-live' +import { resetCloudWorkspacesAvailabilityForFixtures } from './use-cloud-workspaces' +import { workspace } from './cloud-workspaces.test-fixture' + +const list = vi.fn() +const follow = vi.fn() + +beforeEach(() => { + list.mockReset() + list.mockResolvedValue({ ok: true, value: [workspace({ title: 'Checkout' })] }) + Object.assign(window, { + api: { cloudWorkspaces: { available: async () => true, list, follow } } + }) + resetCloudWorkspacesAvailabilityForFixtures() +}) +afterEach(() => cleanup()) + +function Probe({ account, id }: { account: string | null; id: string }): React.JSX.Element { + const live = useTeamWorkspacesLive(account) + return {live ? live.map((w) => w.title).join(',') : 'none'} +} + +describe('useTeamWorkspacesLive (PARITY-FOLLOW)', () => { + it('shares one team read between surfaces', async () => { + const view = render( + <> + + + + ) + await waitFor(() => expect(view.getByTestId('a').textContent).toBe('Checkout')) + expect(view.getByTestId('b').textContent).toBe('Checkout') + expect(list).toHaveBeenCalledTimes(1) + expect(list).toHaveBeenCalledWith({ scope: 'team', archived: 'exclude' }) + }) + + it('reads nothing without a team account', () => { + const view = render() + expect(view.getByTestId('a').textContent).toBe('none') + expect(list).not.toHaveBeenCalled() + }) + + it('shows a follow at once from the server answer, and leaves the list alone on a refusal', async () => { + const w = workspace({ title: 'Checkout', following: false, followers: [] }) + setTeamWorkspacesLiveForTests('org:acme', [w]) + follow.mockResolvedValueOnce({ ok: true, value: { following: true, followers: ['user_ada'] } }) + expect(await setCloudWorkspaceFollow(w.id, true)).toBe(true) + expect(follow).toHaveBeenCalledWith(w.id, true) + follow.mockResolvedValueOnce({ ok: false, error: 'forbidden' }) + expect(await setCloudWorkspaceFollow(w.id, false)).toBe(false) + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/team-workspaces-live.ts b/src/renderer/src/components/cloud-workspaces/team-workspaces-live.ts new file mode 100644 index 00000000000..0e56023035f --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/team-workspaces-live.ts @@ -0,0 +1,122 @@ +// PARITY-FOLLOW: one shared read of the team's cloud workspaces (with live presence) for the +// surfaces that show who is where: the sidebar's Team list and the top bar's people. Mounted +// surfaces share one poller per account, so several of them cost one request per beat. +import { useEffect, useSyncExternalStore } from 'react' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { installWindowVisibilityTimeoutPoller } from '@/lib/window-activity/window-visibility-timeout-poller' +import { rememberCloudWorkspaces } from './cloud-workspace-identity' +import { cloudWorkspacesAvailable } from './use-cloud-workspaces' + +/** Presence lives 45 s on the server; a read every 15 s keeps "here now" honest at low cost. */ +export const TEAM_LIVE_POLL_MS = 15_000 + +type Snapshot = { account: string; workspaces: readonly CloudWorkspace[] } | null + +let snapshot: Snapshot = null +const listeners = new Set<() => void>() +let running: { account: string; consumers: number; stop: () => void } | null = null + +function publish(next: Snapshot): void { + snapshot = next + listeners.forEach((listener) => listener()) +} + +function start(account: string): () => void { + let stopped = false + const load = async (): Promise => { + if (!(await cloudWorkspacesAvailable())) { + stopped = true + return + } + const result = await window.api.cloudWorkspaces + .list({ scope: 'team', archived: 'exclude' }) + .catch(() => null) + if (stopped || running?.account !== account) { + return + } + if (result?.ok) { + rememberCloudWorkspaces(result.value) + publish({ account, workspaces: result.value }) + } else if (result && !result.ok && result.error === 'not_configured') { + stopped = true + } + // Any other failure keeps the last good read: presence fades on the next good one. + } + const stopPolling = installWindowVisibilityTimeoutPoller({ + run: load, + getDelayMs: () => (stopped ? null : TEAM_LIVE_POLL_MS) + }) + return () => { + stopped = true + stopPolling() + } +} + +function acquire(account: string): () => void { + if (running && running.account !== account) { + running.stop() + running = null + publish(null) + } + if (!running) { + running = { account, consumers: 0, stop: start(account) } + } + running.consumers += 1 + const held = running + return () => { + held.consumers -= 1 + if (held.consumers === 0 && running === held) { + held.stop() + running = null + } + } +} + +/** + * The team's live (unarchived) cloud workspaces for this account, or null until the first read. + * `account` null (signed out, not on a team) reads nothing. + */ +export function useTeamWorkspacesLive(account: string | null): readonly CloudWorkspace[] | null { + useEffect(() => (account ? acquire(account) : undefined), [account]) + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => (account && snapshot?.account === account ? snapshot.workspaces : null) + ) +} + +/** A local edit (a follow) shown at once, until the next read confirms it. */ +export function patchTeamWorkspaceLive(id: string, patch: Partial): void { + if (snapshot) { + publish({ + ...snapshot, + workspaces: snapshot.workspaces.map((w) => (w.id === id ? { ...w, ...patch } : w)) + }) + } +} + +/** + * Follow or unfollow (PARITY-FOLLOW). The live list updates from the server's answer; a refusal + * leaves it as it was and resolves false (the caller says so). + */ +export async function setCloudWorkspaceFollow(id: string, follow: boolean): Promise { + const result = await window.api.cloudWorkspaces.follow(id, follow).catch(() => null) + if (!result?.ok) { + return false + } + patchTeamWorkspaceLive(id, { + following: result.value.following, + followers: result.value.followers + }) + return true +} + +/** Test and fixture seam: what the shared read last returned. */ +export function setTeamWorkspacesLiveForTests( + account: string | null, + workspaces: readonly CloudWorkspace[] | null +): void { + publish(account && workspaces ? { account, workspaces } : null) +} diff --git a/src/renderer/src/components/orca-cloud/CloudSetupNotices.test.tsx b/src/renderer/src/components/orca-cloud/CloudSetupNotices.test.tsx index 1ec240795ca..6e6166a2273 100644 --- a/src/renderer/src/components/orca-cloud/CloudSetupNotices.test.tsx +++ b/src/renderer/src/components/orca-cloud/CloudSetupNotices.test.tsx @@ -12,8 +12,11 @@ const { pushAccess, copyRequest } = vi.hoisted(() => ({ copyRequest: vi.fn(async () => true) })) vi.mock('@/lib/orca-cloud/cloud-push-access', () => ({ - fetchCloudPushAccess: pushAccess, - copyOwnerPushRequest: copyRequest + fetchCloudPushAccess: pushAccess +})) +// The shared request (owner-request.ts) reads the install link from repo access, then copies. +vi.mock('@/lib/orca-cloud/use-orca-cloud-repo-access', () => ({ + fetchOrcaCloudRepoAccess: async () => null })) vi.mock('@/store', () => ({ useAppStore: (select: (state: unknown) => unknown) => @@ -116,12 +119,19 @@ describe('CloudSetupNoticesDock (DS-o, DS-q)', () => { repoUrl: 'https://github.com/acme/web', notices: [PUSH] }) + Object.defineProperty(window, 'api', { + configurable: true, + value: { ui: { writeClipboardText: copyRequest } } + }) render() await act(async () => {}) const [, shown] = stack.show.mock.calls.at(-1) ?? [] expect(shown.lines[0].action).toMatchObject({ label: 'Copy request for an owner' }) await act(async () => shown.lines[0].action.onClick()) - expect(copyRequest).toHaveBeenCalledWith('https://github.com/acme/web') + expect(copyRequest).toHaveBeenCalledWith( + expect.stringContaining('push from workspaces on this repository') + ) + expect(copyRequest).toHaveBeenCalledWith(expect.stringContaining('acme/web')) const [, copied] = stack.show.mock.calls.at(-1) ?? [] expect(copied.lines[0].action).toMatchObject({ label: 'Copied' }) }) diff --git a/src/renderer/src/components/orca-cloud/cloud-push-notice-line.tsx b/src/renderer/src/components/orca-cloud/cloud-push-notice-line.tsx index 394877a1ae6..472c3c39faa 100644 --- a/src/renderer/src/components/orca-cloud/cloud-push-notice-line.tsx +++ b/src/renderer/src/components/orca-cloud/cloud-push-notice-line.tsx @@ -5,6 +5,7 @@ import { Check, Copy, GitPullRequestArrow, Loader2, RefreshCw } from 'lucide-rea import type { Translate } from '@/i18n/use-translate' import { repoOwner, repoSlug } from '@/lib/orca-cloud/cloud-setup-notice-actions' import type { CloudPushAccess } from '@/lib/orca-cloud/cloud-push-access' +import { ownerRequestLabel } from '@/lib/orca-cloud/owner-request' import type { CloudSetupNoticeLine } from './CloudSetupNotices' export type CloudPushLineHandlers = { @@ -17,15 +18,13 @@ export type CloudPushLineHandlers = { rechecking?: boolean } -/** Copy a request for an owner (pushRequestMessage), reading "Copied" for a moment after. */ +/** Copy a request for an owner (owner-request.ts), reading "Copied" for a moment after. */ function copyRequestAction( h: CloudPushLineHandlers, t: Translate ): NonNullable { return { - label: h.copied - ? t('orcaCloud.setupNotices.copied', 'Copied') - : t('orcaCloud.setupNotices.copyRequest', 'Copy request for an owner'), + label: ownerRequestLabel(h.copied === true, t), icon: h.copied ? : , run: h.copyRequest } diff --git a/src/renderer/src/components/orca-cloud/use-cloud-push-notice.ts b/src/renderer/src/components/orca-cloud/use-cloud-push-notice.ts index b75e767164a..a6e411c445e 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-push-notice.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-push-notice.ts @@ -1,24 +1,19 @@ // The "can't push" notice's state: what installing can do for this person (cloud-push-access), the // re-checks after Install, Copy request's brief "Copied", and Check again where the App already // reaches the repository. +import { useOwnerRequestCopy } from '@/lib/orca-cloud/owner-request' import { useEffect, useRef, useState } from 'react' import { openOrcaGitHubAppInstall, recheckCloudPushAccess } from '@/lib/orca-cloud/cloud-setup-notice-actions' -import { - copyOwnerPushRequest, - fetchCloudPushAccess, - type CloudPushAccess -} from '@/lib/orca-cloud/cloud-push-access' +import { fetchCloudPushAccess, type CloudPushAccess } from '@/lib/orca-cloud/cloud-push-access' // After Install: GitHub's webhook usually lands within seconds, then the owner may take a while. const FAST_POLL_MS = 2_000 const FAST_POLL_WINDOW_MS = 3 * 60_000 const SLOW_POLL_MS = 10_000 const GIVE_UP_MS = 30 * 60_000 -/** How long "Copied" stays on the request button. */ -export const COPIED_MS = 1_500 export type CloudPushNoticeState = { access: CloudPushAccess @@ -137,9 +132,7 @@ export function useCloudPushNotice( ): CloudPushNoticeState { const access = usePushAccess(repoUrl, hasPush) const push = usePushRecheck(environmentId, hasPush) - const [copied, setCopied] = useState(false) - const copiedTimer = useRef | undefined>(undefined) - useEffect(() => () => clearTimeout(copiedTimer.current), []) + const request = useOwnerRequestCopy(repoUrl, 'push') const [rechecking, setRechecking] = useState(false) const recheckBusy = useRef(false) return { @@ -150,19 +143,8 @@ export function useCloudPushNotice( push.startInstall(repoUrl) } }, - copyRequest: () => { - if (!repoUrl) { - return - } - void copyOwnerPushRequest(repoUrl).then((ok) => { - if (ok) { - setCopied(true) - clearTimeout(copiedTimer.current) - copiedTimer.current = setTimeout(() => setCopied(false), COPIED_MS) - } - }) - }, - copied, + copyRequest: request.copy, + copied: request.copied, recheck: () => { if (!environmentId || recheckBusy.current) { return diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index d787c7cf87e..7e43cc32fe2 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -13,15 +13,23 @@ import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgr import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability' import { AccountMfaRow } from './AccountMfaRow' import { GitHubIdentityRow } from './GitHubIdentityRow' +import type { OrcaProfileReconnectReason } from '../../../../../../shared/orca-profile-reconnect-reason' -function accountStatusCopy( +export function accountStatusCopy( state: 'local' | 'unconfigured' | 'connected' | 'reconnect-required' | undefined, email: string | undefined, - t: Translate = translate + t: Translate = translate, + reconnectReason?: OrcaProfileReconnectReason ): string { if (state === 'connected') { return email ?? t('auto.components.settings.orcaAccount.connected', 'Connected') } + if (state === 'reconnect-required' && reconnectReason === 'sso-required') { + return t( + 'auto.components.settings.orcaAccount.ssoRequired', + 'Your team now requires single sign-on. Sign in again and choose Sign in with SSO.' + ) + } if (state === 'reconnect-required') { return t( 'auto.components.settings.orcaAccount.reconnectRequired', @@ -110,7 +118,12 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { ) : null}

- {accountStatusCopy(authStatus?.state, authStatus?.cloud?.email, t)} + {accountStatusCopy( + authStatus?.state, + authStatus?.cloud?.email, + t, + authStatus?.reconnectReason + )}

{connected ? ( diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx index 8d3067c05dc..7ce77c2f502 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx @@ -10,7 +10,13 @@ import type { OrcaCloudAgentsErrorCode } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import { RowShell } from './orca-cloud-account-row-shell' -import { agentName, keyPhrase, productName, setupFailureCopy } from './orca-cloud-accounts-copy' +import { + agentName, + keyPhrase, + productName, + setupFailureCopy, + setupFailureTone +} from './orca-cloud-accounts-copy' import type { OrcaCloudAccountsActions } from './orca-cloud-accounts-types' import { ActiveRow, ChoiceRow } from './OrcaCloudActiveRow' import { SetupRow } from './OrcaCloudSetupRow' @@ -86,7 +92,7 @@ export function AccountRow({ content = ( { + it('names the cause and the fix', () => { + expect(setupFailureCopy('codex', 'device_auth_disabled', translate)).toEqual({ + title: 'Device code sign-in is off for this ChatGPT account', + detail: + 'Turn it on in ChatGPT’s security settings, then try again. On a work or team account, a ChatGPT admin may need to turn it on.' + }) + expect(setupFailureTone('device_auth_disabled')).toBe('warning') + expect(setupFailureTone('broker_unavailable')).toBe('error') + expect(setupFailureCopy('codex', 'broker_unavailable', translate).title).toBe( + 'Couldn’t save to your Orca account.' + ) + }) +}) diff --git a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-copy.ts b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-copy.ts index cae18d3a67d..eacd9f4a376 100644 --- a/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-copy.ts +++ b/src/renderer/src/components/settings/agent-accounts/orca-cloud-accounts-copy.ts @@ -68,6 +68,11 @@ export function keySourceLabel(kind: AgentKeyKind, t: Translate): string { } } +/** RS-3 (design-squad): a fixable access setting reads as a warning (amber), not an error (red). */ +export function setupFailureTone(error: OrcaCloudAgentSetupFailure): 'warning' | 'error' { + return error === 'device_auth_disabled' ? 'warning' : 'error' +} + export function setupFailureCopy( agent: OrcaCloudAccountAgent, error: OrcaCloudAgentSetupFailure, @@ -115,6 +120,19 @@ export function setupFailureCopy( ), detail: nothingChanged } + case 'device_auth_disabled': + // RS-3: the broker started but ChatGPT refused to issue a device code for this account. + // (design-squad) a pointer that is right rather than a guessed setting name. + return { + title: t( + 'orcaCloudAccounts.error.deviceAuthDisabled', + 'Device code sign-in is off for this ChatGPT account' + ), + detail: t( + 'orcaCloudAccounts.error.deviceAuthDisabledDetail', + 'Turn it on in ChatGPT’s security settings, then try again. On a work or team account, a ChatGPT admin may need to turn it on.' + ) + } case 'invalid_token': return { title: t( diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesControls.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesControls.tsx new file mode 100644 index 00000000000..a7f7922ccf1 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesControls.tsx @@ -0,0 +1,162 @@ +// Settings › Workspaces controls: the By / In / search bar and each row's ⋯ menu, which offers +// only the actions teamWorkspaceActions allows. +import React from 'react' +import { Archive, ArrowUpRight, Moon, MoreHorizontal, Search } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { Input } from '@/components/ui/input' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' +import { useTranslate } from '@/i18n/use-translate' +import type { CloudWorkspace } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { + memberName, + repoLabel, + type MemberDirectory +} from '../../cloud-workspaces/cloud-workspace-format' +import { cloudWorkspaceTitle } from '../../cloud-workspaces/open-cloud-workspace' +import { ANY, teamWorkspaceActions, type TeamWorkspaceFilters } from './team-workspaces-model' + +export function RowActionsMenu({ + workspace: w, + canAdmin, + onOpen, + onSleep, + onArchive +}: { + workspace: CloudWorkspace + canAdmin: boolean + onOpen: (w: CloudWorkspace) => void + onSleep: (w: CloudWorkspace) => void + onArchive: (w: CloudWorkspace) => void +}): React.JSX.Element | null { + const t = useTranslate() + const allowed = teamWorkspaceActions(w, canAdmin) + if (!allowed.open && !allowed.sleep && !allowed.archive) { + // Nothing this account may do to it: no empty menu. + return + } + return ( + + + + + + {allowed.open ? ( + onOpen(w)}> + + {t('auto.components.cloudWorkspaces.open', 'Open')} + + ) : null} + {allowed.sleep ? ( + onSleep(w)}> + + {t('auto.components.cloudWorkspaces.sleep', 'Sleep')} + + ) : null} + {allowed.archive ? ( + onArchive(w)}> + + {t('auto.components.cloudWorkspaces.archive', 'Archive')} + + ) : null} + + + ) +} + +export function Filters({ + filters, + onChange, + people, + repos, + directory, + selfId +}: { + filters: TeamWorkspaceFilters + onChange: (next: Partial) => void + people: string[] + repos: string[] + directory: MemberDirectory + selfId: string | null +}): React.JSX.Element { + const t = useTranslate() + return ( +
+
+ + onChange({ search: event.target.value })} + /> +
+ + +
+ ) +} diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.fixture.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.fixture.tsx new file mode 100644 index 00000000000..c3a97db8a5e --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.fixture.tsx @@ -0,0 +1,69 @@ +// Settings › Workspaces (team owners and admins): the team's cloud workspaces as a table with By, +// In and search, and each row's allowed actions. +import { defineFixture } from '../../../component-fixtures/component-fixture' +import { TeamWorkspacesSettings } from './TeamWorkspacesSettings' +import { + AUTH_STATUS, + stubCloudWorkspacesApi, + teamWorkspaces +} from '../../cloud-workspaces/cloud-workspaces.test-fixture' + +const WIDTH = 820 + +async function waitFor(check: () => boolean): Promise { + const deadline = performance.now() + 3000 + while (!check() && performance.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 50)) + } +} + +const frame = (): React.JSX.Element => ( +
+ +
+) + +/** Every lifecycle state (running, starting, waking, asleep, couldn't start, archived), five people. */ +export const teamTable = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: teamWorkspaces() })), + render: frame, + interact: () => waitFor(() => document.querySelector('[data-team-workspace-row]') !== null) +}) + +/** A running teammate workspace's ⋯: Open, Sleep, Archive (nothing the server would refuse). */ +export const rowActions = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: teamWorkspaces() })), + render: frame, + interact: async () => { + await waitFor(() => document.querySelector('[data-team-workspace-row]') !== null) + const trigger = document.querySelector( + '[data-team-workspace-row] [data-slot="dropdown-menu-trigger"]' + ) + trigger?.dispatchEvent( + new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' }) + ) + await waitFor(() => document.querySelector('[data-slot="dropdown-menu-content"]') !== null) + } +}) + +/** Nobody on the team has started one. */ +export const empty = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: [] })), + render: frame, + interact: () => waitFor(() => document.querySelector('[data-team-workspaces] p') !== null) +}) + +/** The list could not be read. */ +export const error = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => stubCloudWorkspacesApi(() => Promise.resolve({ ok: false, error: 'unavailable' })), + render: frame, + interact: () => waitFor(() => document.querySelector('[data-slot="inline-error"]') !== null) +}) diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx new file mode 100644 index 00000000000..06be031a494 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.test.tsx @@ -0,0 +1,176 @@ +// @vitest-environment happy-dom +// Settings › Workspaces: the team's cloud workspaces as a table, filterable By / In / search, with +// only the actions the control plane allows an admin, through the same open, sleep and archive flows. +import { act, cleanup, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import type { CloudWorkspace } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { FIXTURE_NOW, workspace } from '../../cloud-workspaces/cloud-workspaces.test-fixture' +import type * as OpenCloudWorkspaceNs from '../../cloud-workspaces/open-cloud-workspace' +import type * as ArchiveNs from '../../cloud-workspaces/cloud-workspace-home-archive' + +type OpenModule = typeof OpenCloudWorkspaceNs +type ArchiveModule = typeof ArchiveNs + +const mocks = vi.hoisted(() => { + const state = { + orcaProfileAuthStatus: { + activeProfileId: 'profile-1', + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: { userId: 'user_ada', activeOrgId: 'org_acme', activeOrgName: 'Acme' } + }, + connectCurrentOrcaProfile: async () => {}, + keybindings: {}, + ephemeralVmRuntimesByWorkspaceId: {} + } + return { state, open: vi.fn(), sleep: vi.fn(), archive: vi.fn() } +}) + +vi.mock('@/store', () => ({ + useAppStore: Object.assign( + (selector: (s: typeof mocks.state) => unknown) => selector(mocks.state), + { getState: () => mocks.state, subscribe: () => () => {} } + ) +})) +vi.mock('../../billing/team/use-org-roster', async () => { + const { ROSTER } = await import('../../cloud-workspaces/cloud-workspaces.test-fixture') + const result = { status: 'ok' as const, roster: ROSTER } + return { useOrgRoster: () => ({ result }) } +}) +vi.mock('../../cloud-workspaces/open-cloud-workspace', async (importOriginal) => ({ + ...(await importOriginal()), + openCloudWorkspace: mocks.open +})) +vi.mock('../../cloud-workspaces/cloud-workspace-home-archive', async (importOriginal) => ({ + ...(await importOriginal()), + homeArchiveActions: () => ({ + sleep: mocks.sleep, + archive: mocks.archive, + unarchive: vi.fn(), + remove: vi.fn(), + restart: vi.fn() + }) +})) + +import { TeamWorkspacesSettings } from './TeamWorkspacesSettings' + +const RUNNING = workspace({ + title: 'Refund webhooks', + repo: { url: 'https://github.com/acme/web.git', branch: 'refunds' }, + ownerUserId: 'user_grace', + createdBy: 'user_grace', + access: 'can_open', + lastActivityAt: FIXTURE_NOW - 60_000 +}) +const ARCHIVED = workspace({ + title: 'Old spike', + ownerUserId: 'user_linus', + createdBy: 'user_linus', + access: 'can_open', + archivedAt: 1, + status: 'suspended', + lastActivityAt: FIXTURE_NOW - 86_400_000 +}) +const PRIVATE = workspace({ + title: 'Ada’s private notes', + visibility: 'private', + status: 'suspended', + lastActivityAt: FIXTURE_NOW - 3_600_000 +}) + +let list: CloudWorkspace[] + +beforeEach(() => { + list = [RUNNING, ARCHIVED, PRIVATE] + mocks.open.mockReset().mockResolvedValue({ ok: true, worktreeId: 'wt-1' }) + mocks.sleep.mockReset() + mocks.archive.mockReset() + vi.stubGlobal('api', { + cloudWorkspaces: { + available: () => Promise.resolve(true), + list: vi.fn((query: unknown) => { + expect(query).toEqual({ scope: 'team', archived: 'include' }) + return Promise.resolve({ ok: true, value: list }) + }) + } + }) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +async function renderPane(): Promise { + render( + + + + ) + await screen.findByText('Refund webhooks') +} + +const row = (title: string): HTMLElement => screen.getByText(title).closest('tr')! + +describe('Settings › Workspaces', () => { + it('lists every team workspace with who started it, its state, W-number and access', async () => { + await renderPane() + const refund = within(row('Refund webhooks')) + expect(refund.getByText('Grace Hopper')).toBeTruthy() + expect(refund.getByText('Running')).toBeTruthy() + expect(refund.getByText(`W-${RUNNING.number}`)).toBeTruthy() + expect(refund.getByText('Shared')).toBeTruthy() + expect(refund.getByText('acme/web · refunds')).toBeTruthy() + expect(within(row('Old spike')).getByText('Archived')).toBeTruthy() + expect(within(row('Ada’s private notes')).getByText('Private')).toBeTruthy() + expect(screen.getByText('3 of 3 workspaces')).toBeTruthy() + }) + + it('search narrows the table', async () => { + const user = userEvent.setup() + await renderPane() + await user.type(screen.getByRole('searchbox', { name: 'Search workspaces' }), 'grace') + expect(screen.queryByText('Old spike')).toBeNull() + expect(screen.getByText('1 of 3 workspaces')).toBeTruthy() + }) + + it('a running teammate workspace offers Open, Sleep and Archive; Open uses openCloudWorkspace', async () => { + const user = userEvent.setup() + await renderPane() + await user.click( + within(row('Refund webhooks')).getByRole('button', { name: 'Actions for Refund webhooks' }) + ) + const items = (await screen.findAllByRole('menuitem')).map((item) => item.textContent) + expect(items).toEqual(['Open', 'Sleep', 'Archive']) + await user.click(screen.getByRole('menuitem', { name: 'Open' })) + expect(mocks.open).toHaveBeenCalledWith(RUNNING) + }) + + it('Sleep and Archive go through the shared archive flows', async () => { + const user = userEvent.setup() + await renderPane() + const menu = (): HTMLElement => + within(row('Refund webhooks')).getByRole('button', { name: 'Actions for Refund webhooks' }) + await user.click(menu()) + await user.click(await screen.findByRole('menuitem', { name: 'Sleep' })) + expect(mocks.sleep).toHaveBeenCalledWith(RUNNING) + await user.click(menu()) + await user.click(await screen.findByRole('menuitem', { name: 'Archive' })) + expect(mocks.archive).toHaveBeenCalledWith(RUNNING) + }) + + it('an archived workspace has no actions to offer', async () => { + await renderPane() + expect(within(row('Old spike')).queryByRole('button')).toBeNull() + }) + + it('an empty team says so', async () => { + list = [] + render() + expect(await screen.findByText('No one on your team has a cloud workspace yet.')).toBeTruthy() + await act(async () => {}) + }) +}) diff --git a/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx new file mode 100644 index 00000000000..0b330812538 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/TeamWorkspacesSettings.tsx @@ -0,0 +1,276 @@ +// Settings › Workspaces: every cloud workspace on the team, for owners and admins to manage +// (Neil, HOME-1: the listing comes back only here). Open, Sleep and Archive use the same flows as +// the sidebar and "Open cloud workspace…"; an action the control plane would refuse is not shown. +import React, { useEffect, useMemo, useState } from 'react' +import { toast } from 'sonner' +import { Lock, RefreshCw, Users } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { CloudStatusGlyph } from '@/components/orca-cloud/CloudStatusGlyph' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/class-names' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' +import { useOrcaAccountKey } from '@/hooks/use-orca-account-key' +import { useAppStore } from '@/store' +import { + formatWorkspaceNumber, + type CloudWorkspace +} from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { MemberAvatar } from '../../cloud-workspaces/CloudMemberAvatars' +import { dotState, statusLabel } from '../../cloud-workspaces/CloudWorkspaceRow' +import { ErrorState, SkeletonRows } from '../../cloud-workspaces/CloudWorkspacesStates' +import { + CloudWorkspaceConfirmDialog, + type PendingConfirm +} from '../../cloud-workspaces/CloudWorkspaceConfirmDialog' +import * as archive from '../../cloud-workspaces/cloud-workspace-home-archive' +import { + formatRelative, + memberName, + repoLabel +} from '../../cloud-workspaces/cloud-workspace-format' +import { useListedCloudWorkspaces } from '../../cloud-workspaces/cloud-workspace-local-titles' +import { + cloudWorkspaceTitle, + openCloudWorkspace +} from '../../cloud-workspaces/open-cloud-workspace' +import { useMemberDirectory } from '../../cloud-workspaces/use-cloud-workspace-row-actions' +import { useCloudWorkspaces } from '../../cloud-workspaces/use-cloud-workspaces' +import { + ANY, + INITIAL_TEAM_WORKSPACE_FILTERS, + createdByOf, + teamWorkspaceFilterOptions, + teamWorkspaceRows, + type TeamWorkspaceFilters +} from './team-workspaces-model' +import { Filters, RowActionsMenu } from './TeamWorkspacesControls' + +const TEAM_QUERY = { scope: 'team', archived: 'include' } as const + +export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): React.JSX.Element { + const t = useTranslate() + const intlLocale = useIntlLocale() + const cloud = useAppStore((s) => s.orcaProfileAuthStatus?.cloud) + const signIn = useAppStore((s) => s.connectCurrentOrcaProfile) + const account = useOrcaAccountKey() + const selfId = cloud?.userId ?? null + const [filters, setFilters] = useState(INITIAL_TEAM_WORKSPACE_FILTERS) + const [confirm, setConfirm] = useState(null) + const [now, setNow] = useState(() => Date.now()) + const { state, stale, reading, refresh } = useCloudWorkspaces(TEAM_QUERY, Boolean(cloud), account) + useEffect( + () => installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 30_000 }), + [] + ) + const all = useListedCloudWorkspaces(state.status === 'ready' ? state.workspaces : null) + const { directory, canAdmin } = useMemberDirectory(orgId ?? undefined, all) + const { people, repos } = useMemo(() => teamWorkspaceFilterOptions(all), [all]) + // A person or repository that left the list stops filtering. + const effective = useMemo( + () => ({ + ...filters, + by: people.includes(filters.by) ? filters.by : ANY, + repo: repos.includes(filters.repo) ? filters.repo : ANY + }), + [filters, people, repos] + ) + const rows = useMemo( + () => teamWorkspaceRows(all, effective, directory), + [all, effective, directory] + ) + const archiveActions = useMemo( + () => archive.homeArchiveActions({ selfId, t, refresh, confirmArchive: setConfirm }), + [refresh, selfId, t] + ) + const open = (w: CloudWorkspace): void => { + void openCloudWorkspace(w).then((outcome) => { + if (!outcome.ok) { + toast.error(outcome.message) + } + }) + } + + return ( +
+
+ setFilters((previous) => ({ ...previous, ...next }))} + people={people} + repos={repos} + directory={directory} + selfId={selfId} + /> + +
+
+ {state.status === 'error' ? ( + { + void signIn().then(refresh) + }} + /> + ) : state.status !== 'ready' ? ( + + ) : rows.length === 0 ? ( +

+ {all.length === 0 + ? t( + 'settings.teamWorkspaces.emptyTeam', + 'No one on your team has a cloud workspace yet.' + ) + : t('settings.teamWorkspaces.emptyFiltered', 'No workspaces match these filters.')} +

+ ) : ( + + + + + + + + + + + + + + + + + + + + + + + {rows.map((w) => { + const creator = createdByOf(w) + const status = statusLabel(w, t) + return ( + + + + + + + + + + ) + })} + +
+ {t('settings.teamWorkspaces.colName', 'Workspace')} + + {t('settings.teamWorkspaces.colNumber', 'No.')} + + {t('settings.teamWorkspaces.colCreatedBy', 'Created by')} + + {t('settings.teamWorkspaces.colState', 'State')} + + {t('settings.teamWorkspaces.colLastActive', 'Last active')} + + {t('settings.teamWorkspaces.colAccess', 'Access')} + + + {t('settings.teamWorkspaces.colActions', 'Actions')} + +
+ + {cloudWorkspaceTitle(w, t)} + + {w.repo ? ( + + {repoLabel(w.repo.url)} + {w.repo.branch ? ` · ${w.repo.branch}` : ''} + + ) : null} + + {w.number ? formatWorkspaceNumber(w.number) : '—'} + + + + + {memberName(directory, creator, selfId, t)} + + + + + + {status} + + + {formatRelative(w.lastActivityAt, now, t, intlLocale)} + + + {w.visibility === 'private' ? ( + + ) : ( + + )} + {w.visibility === 'private' + ? t('auto.components.cloudWorkspaces.private', 'Private') + : t('settings.teamWorkspaces.shared', 'Shared')} + + + +
+ )} +
+ {state.status === 'ready' && all.length > 0 ? ( +

+ {t('settings.teamWorkspaces.shownOf', '{{shown}} of {{count}} workspaces', { + shown: rows.length, + count: all.length, + defaultValue_one: '{{shown}} of {{count}} workspace' + })} +

+ ) : null} + {confirm && ( + setConfirm(null)} + onConfirm={() => { + if (confirm.kind === 'archive' || confirm.kind === 'delete') { + archive.runConfirmed(confirm, t, refresh) + } + setConfirm(null) + }} + /> + )} +
+ ) +} diff --git a/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.test.ts b/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.test.ts new file mode 100644 index 00000000000..4ed59b691c3 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { + ANY, + INITIAL_TEAM_WORKSPACE_FILTERS as ALL, + teamWorkspaceActions, + teamWorkspaceFilterOptions, + teamWorkspaceRows +} from './team-workspaces-model' +import { DIRECTORY, workspace } from '../../cloud-workspaces/cloud-workspaces.test-fixture' + +const mine = workspace({ title: 'Checkout retries', lastActivityAt: 3 }) +const grace = workspace({ + title: 'Refund webhooks', + repo: { url: 'https://github.com/acme/web.git', branch: 'refunds' }, + ownerUserId: 'user_grace', + createdBy: 'user_grace', + access: 'can_open', + lastActivityAt: 5 +}) +const archived = workspace({ + title: 'Old spike', + ownerUserId: 'user_linus', + createdBy: 'user_linus', + access: 'can_open', + archivedAt: 1, + status: 'suspended', + lastActivityAt: 1 +}) + +describe('Settings › Workspaces filters', () => { + it('offers By for everyone who started one and In for every repository', () => { + const { people, repos } = teamWorkspaceFilterOptions([mine, grace, archived]) + expect(people).toEqual(['user_ada', 'user_grace', 'user_linus']) + expect(repos).toEqual([ + 'https://github.com/acme/payments.git', + 'https://github.com/acme/web.git' + ]) + }) + + it('lists everything, archived included, most recently active first', () => { + expect(teamWorkspaceRows([archived, mine, grace], ALL, DIRECTORY).map((w) => w.title)).toEqual([ + 'Refund webhooks', + 'Checkout retries', + 'Old spike' + ]) + }) + + it('narrows by person, by repository and by search', () => { + const titles = (patch: Partial) => + teamWorkspaceRows([mine, grace, archived], { ...ALL, ...patch }, DIRECTORY).map( + (w) => w.title + ) + expect(titles({ by: 'user_grace' })).toEqual(['Refund webhooks']) + expect(titles({ repo: 'https://github.com/acme/payments.git' })).toEqual([ + 'Checkout retries', + 'Old spike' + ]) + expect(titles({ search: 'linus park' })).toEqual(['Old spike']) + expect(titles({ search: `W-${grace.number}` })).toEqual(['Refund webhooks']) + expect(titles({ by: ANY, repo: ANY, search: 'nothing' })).toEqual([]) + }) +}) + +describe('Settings › Workspaces row actions (never one the server would refuse)', () => { + it('an admin may open, sleep and archive a teammate’s running workspace', () => { + expect(teamWorkspaceActions(grace, true)).toEqual({ open: true, sleep: true, archive: true }) + }) + + it('without admin rights, a teammate’s workspace can only be opened', () => { + expect(teamWorkspaceActions(grace, false)).toEqual({ open: true, sleep: false, archive: false }) + }) + + it('asleep: no Sleep; starting or mid-transition: no Archive', () => { + expect(teamWorkspaceActions({ ...grace, status: 'suspended' }, true)).toEqual({ + open: true, + sleep: false, + archive: true + }) + expect(teamWorkspaceActions({ ...grace, status: 'creating' }, true).archive).toBe(false) + expect(teamWorkspaceActions({ ...grace, status: 'suspending' }, true).archive).toBe(false) + }) + + it('archived: nothing to open, sleep or archive', () => { + expect(teamWorkspaceActions(archived, true)).toEqual({ + open: false, + sleep: false, + archive: false + }) + }) + + it('a private one you cannot open is not offered to open', () => { + expect(teamWorkspaceActions({ ...grace, access: 'none' }, true)).toMatchObject({ + open: false, + sleep: true + }) + }) +}) diff --git a/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.ts b/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.ts new file mode 100644 index 00000000000..dc876b219fc --- /dev/null +++ b/src/renderer/src/components/settings/cloud-workspaces/team-workspaces-model.ts @@ -0,0 +1,79 @@ +// Settings › Workspaces (team owners and admins): which rows the table shows for the By / In / +// search filters, and which actions each row offers. An action the control plane would refuse is +// never offered: only the owner or a team admin manages a workspace, Sleep needs it running, and +// Archive is refused while it is starting or mid-transition. +import type { CloudWorkspace } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { formatWorkspaceNumber } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import type { MemberDirectory } from '../../cloud-workspaces/cloud-workspace-format' + +export const ANY = '__any' + +export type TeamWorkspaceFilters = { by: string; repo: string; search: string } + +export const INITIAL_TEAM_WORKSPACE_FILTERS: TeamWorkspaceFilters = { + by: ANY, + repo: ANY, + search: '' +} + +/** Who started a workspace; the owner when the control plane didn't record it. */ +export function createdByOf(w: Pick): string { + return w.createdBy || w.ownerUserId +} + +/** The By filter's people and the In filter's repositories, from the listed workspaces. */ +export function teamWorkspaceFilterOptions(workspaces: readonly CloudWorkspace[]): { + people: string[] + repos: string[] +} { + return { + people: [...new Set(workspaces.map(createdByOf))], + repos: [...new Set(workspaces.flatMap((w) => (w.repo ? [w.repo.url] : [])))].sort() + } +} + +function matchesSearch(w: CloudWorkspace, search: string, directory: MemberDirectory): boolean { + const needle = search.trim().toLowerCase() + if (!needle) { + return true + } + return [ + w.title, + w.repo?.url, + w.repo?.branch, + w.number ? formatWorkspaceNumber(w.number) : null, + directory.get(createdByOf(w))?.name, + w.memberNames?.[createdByOf(w)] + ].some((value) => typeof value === 'string' && value.toLowerCase().includes(needle)) +} + +export function teamWorkspaceRows( + workspaces: readonly CloudWorkspace[], + filters: TeamWorkspaceFilters, + directory: MemberDirectory +): CloudWorkspace[] { + return workspaces + .filter( + (w) => + (filters.by === ANY || createdByOf(w) === filters.by) && + (filters.repo === ANY || w.repo?.url === filters.repo) && + matchesSearch(w, filters.search, directory) + ) + .sort((a, b) => b.lastActivityAt - a.lastActivityAt) +} + +export type TeamWorkspaceActions = { open: boolean; sleep: boolean; archive: boolean } + +export function teamWorkspaceActions( + w: Pick, + canAdmin: boolean +): TeamWorkspaceActions { + const live = w.archivedAt === null + const manage = live && (w.access === 'owner' || canAdmin) + return { + // Opening pairs this computer through a grant; a workspace you can't open has none to give. + open: live && w.access !== 'none', + sleep: manage && w.status === 'running', + archive: manage && (w.status === 'running' || w.status === 'suspended' || w.status === 'failed') + } +} diff --git a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsPane.tsx b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsPane.tsx index 404168c9481..9efc23cac6e 100644 --- a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsPane.tsx +++ b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsPane.tsx @@ -8,6 +8,7 @@ import { activeTeamRole } from '@/lib/orca-cloud/active-team-role' import { useAppStore } from '@/store' import { refreshBillingSummary, useBillingState } from '../../billing/billing-summary-store' import { canManageMembers } from '../../billing/team/team-roles' +import { EnterpriseMfaPolicy } from '../../team-mfa/EnterpriseMfaPolicy' import { EnterpriseSettingsView } from './EnterpriseSettingsView' import { ENTERPRISE_CONTACT_URL, type EnterpriseContact } from './EnterpriseUpsell' import { useEnterpriseAuditLog } from './use-enterprise-audit-log' @@ -39,6 +40,7 @@ function EnterpriseSettingsPaneBody(): React.JSX.Element | null { const role = activeTeamRole(authStatus) const admin = role !== null && canManageMembers(role) const contact = useEnterpriseContact() + const orgId = authStatus?.cloud?.activeOrgId ?? null const audit = useEnterpriseAuditLog(availability?.status === 'ready' && admin) const sso = useEnterpriseSso( authStatus?.cloud?.activeOrgId ?? null, @@ -80,6 +82,16 @@ function EnterpriseSettingsPaneBody(): React.JSX.Element | null { }} /> } + policies={ + orgId ? ( + + ) : undefined + } audit={{ log: audit.log, filters: audit.filters, diff --git a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx index dc8eb4fa11a..40b94cb40c0 100644 --- a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx +++ b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx @@ -77,12 +77,51 @@ describe('audit log', () => { ...FIXTURE_EVENTS[0]!, id: 'aud_new', category: 'security', - action: 'sso.went_live' + action: 'sso.something_new' } const { container } = render( ) - expect(rows(container)).toEqual(['sso.went_live | Security | Grace Hopper | 4 minutes ago']) + expect(rows(container)).toEqual(['sso.something_new | Security | Grace Hopper | 4 minutes ago']) + }) + + it('words every single sign-on and directory sync action auth sends', () => { + // The actions in orca-cloud apps/auth/src/audit/sso-audit.ts. + const actions = [ + 'sso.setup_link_created', + 'sso.configured', + 'sso.went_live', + 'sso.removed', + 'sso.sign_in_refused', + 'sso.sessions_ended', + 'sso.domain_added', + 'sso.domain_verified', + 'sso.domain_removed', + 'sso.domain_record_missing', + 'scim.enabled', + 'scim.disabled', + 'scim.key_created', + 'scim.key_revoked', + 'scim.group_changed', + 'scim.group_membership_changed' + ] + for (const action of actions) { + expect(isKnownAuditAction(action)).toBe(true) + const sentence = auditEventSentence({ ...FIXTURE_EVENTS[0]!, action, target: null }) + expect(sentence).not.toContain('.') + expect(sentence).not.toContain('_') + } + const about = (action: string, label: string): string => + auditEventSentence({ + ...FIXTURE_EVENTS[0]!, + action, + target: { type: 'sso_connection', id: null, label } + }) + expect(about('sso.went_live', 'Okta')).toBe('Turned on single sign-on with Okta') + expect(about('sso.domain_verified', 'acme.com')).toBe('Verified email domain acme.com') + expect(about('sso.domain_record_missing', 'acme.com')).toBe( + 'Found the DNS record for acme.com missing' + ) }) it('pages with Show more, and keeps the list when a page fails', () => { @@ -209,7 +248,11 @@ describe('without the Enterprise plan', () => { audit={fixtureAuditProps({ log: { status: 'upsell' }, actors: [], onContactSales })} /> ) - expect(screen.getByText('Single sign-on and the audit log are part of Enterprise')).toBeTruthy() + expect( + screen.getByText( + 'Single sign-on, two-factor requirements and the audit log are part of Enterprise' + ) + ).toBeTruthy() // The blocks keep their titles and say what they are, without a second button. expect(screen.getByText('Single sign-on and provisioning')).toBeTruthy() expect(screen.getByText('Audit log')).toBeTruthy() @@ -234,7 +277,11 @@ describe('without the Enterprise plan', () => { audit={fixtureAuditProps({ log: { status: 'upsell' }, actors: [], onContactSales })} /> ) - expect(screen.queryByText('Single sign-on and the audit log are part of Enterprise')).toBeNull() + expect( + screen.queryByText( + 'Single sign-on, two-factor requirements and the audit log are part of Enterprise' + ) + ).toBeNull() expect(screen.getByText('Audit log is part of Enterprise')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'Contact sales' })) expect(onContactSales).toHaveBeenCalledWith('https://orca.dev/enterprise') @@ -251,7 +298,11 @@ describe('without the Enterprise plan', () => { })} /> ) - expect(screen.getByText('Single sign-on and the audit log are part of Scale')).toBeTruthy() + expect( + screen.getByText( + 'Single sign-on, two-factor requirements and the audit log are part of Scale' + ) + ).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'Contact sales' })) expect(onContactSales).toHaveBeenCalledWith('https://orca.dev/scale') }) diff --git a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.tsx b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.tsx index 647e2ab7ef5..92c3a911b8c 100644 --- a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.tsx +++ b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.tsx @@ -53,8 +53,8 @@ export function EnterpriseSettingsView({ = { t('settings.enterprise.audit.action.secretDeleteNamed', 'Deleted secret {{name}}', { name }) }, ...ACCOUNT_AUDIT_ACTIONS, + ...SSO_AUDIT_ACTIONS, + 'mfa.policy.enabled': { + plain: (t) => + t('settings.enterprise.audit.action.mfaPolicyEnabled', 'Required two-factor authentication') + }, + 'mfa.policy.changed': { + plain: (t) => + t( + 'settings.enterprise.audit.action.mfaPolicyChanged', + 'Changed the two-factor authentication date' + ) + }, + 'mfa.policy.disabled': { + plain: (t) => + t( + 'settings.enterprise.audit.action.mfaPolicyDisabled', + 'Stopped requiring two-factor authentication' + ) + }, + 'mfa.reminder.resent': { + plain: (t) => + t( + 'settings.enterprise.audit.action.mfaReminderResent', + 'Sent a two-factor authentication reminder' + ) + }, + 'mfa.member.reset': { + plain: (t) => + t( + 'settings.enterprise.audit.action.mfaMemberReset', + 'Reset a member’s two-factor authentication' + ) + }, 'routine.create': { plain: (t) => t('settings.enterprise.audit.action.routineCreate', 'Created a routine') }, diff --git a/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts b/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts new file mode 100644 index 00000000000..263321bcd64 --- /dev/null +++ b/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts @@ -0,0 +1,109 @@ +// Wording for the single sign-on and directory sync events the auth service sends. `named` takes +// what the event is about: the identity provider's name, or the email domain. +import type { ActionCopy } from './enterprise-audit-account-copy' + +export const SSO_AUDIT_ACTIONS: Record = { + 'sso.setup_link_created': { + plain: (t) => + t('settings.enterprise.audit.action.ssoSetupLink', 'Created a single sign-on setup link') + }, + 'sso.configured': { + plain: (t) => t('settings.enterprise.audit.action.ssoConfigured', 'Set up single sign-on'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoConfiguredNamed', + 'Set up single sign-on with {{name}}', + { + name + } + ) + }, + 'sso.went_live': { + plain: (t) => t('settings.enterprise.audit.action.ssoWentLive', 'Turned on single sign-on'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoWentLiveNamed', + 'Turned on single sign-on with {{name}}', + { name } + ) + }, + 'sso.removed': { + plain: (t) => t('settings.enterprise.audit.action.ssoRemoved', 'Removed single sign-on') + }, + 'sso.sign_in_refused': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoSignInRefused', + 'Tried to sign in without single sign-on' + ) + }, + 'sso.sessions_ended': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoSessionsEnded', + 'Ended sign-ins made before single sign-on was turned on' + ) + }, + 'sso.domain_added': { + plain: (t) => t('settings.enterprise.audit.action.ssoDomainAdded', 'Added an email domain'), + named: (t, name) => + t('settings.enterprise.audit.action.ssoDomainAddedNamed', 'Added email domain {{name}}', { + name + }) + }, + 'sso.domain_verified': { + plain: (t) => + t('settings.enterprise.audit.action.ssoDomainVerified', 'Verified an email domain'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoDomainVerifiedNamed', + 'Verified email domain {{name}}', + { name } + ) + }, + 'sso.domain_removed': { + plain: (t) => t('settings.enterprise.audit.action.ssoDomainRemoved', 'Removed an email domain'), + named: (t, name) => + t('settings.enterprise.audit.action.ssoDomainRemovedNamed', 'Removed email domain {{name}}', { + name + }) + }, + 'sso.domain_record_missing': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoDomainRecordMissing', + 'Found an email domain’s DNS record missing' + ), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoDomainRecordMissingNamed', + 'Found the DNS record for {{name}} missing', + { name } + ) + }, + 'scim.enabled': { + plain: (t) => t('settings.enterprise.audit.action.scimEnabled', 'Turned on directory sync') + }, + 'scim.disabled': { + plain: (t) => t('settings.enterprise.audit.action.scimDisabled', 'Turned off directory sync') + }, + 'scim.key_created': { + plain: (t) => + t('settings.enterprise.audit.action.scimKeyCreated', 'Created a directory sync key') + }, + 'scim.key_revoked': { + plain: (t) => + t('settings.enterprise.audit.action.scimKeyRevoked', 'Revoked a directory sync key') + }, + 'scim.group_changed': { + plain: (t) => + t('settings.enterprise.audit.action.scimGroupChanged', 'Changed a directory group') + }, + 'scim.group_membership_changed': { + plain: (t) => + t( + 'settings.enterprise.audit.action.scimGroupMembershipChanged', + 'Changed who is in a directory group' + ) + } +} diff --git a/src/renderer/src/components/settings/navigation/settings-navigation-types.ts b/src/renderer/src/components/settings/navigation/settings-navigation-types.ts index 5cea2db888b..3b919669f05 100644 --- a/src/renderer/src/components/settings/navigation/settings-navigation-types.ts +++ b/src/renderer/src/components/settings/navigation/settings-navigation-types.ts @@ -49,6 +49,7 @@ const SETTINGS_NAV_TARGETS = [ 'cloud-billing', 'cloud-team', 'cloud-enterprise', + 'cloud-workspaces', 'cloud-secrets', 'cloud-environments', 'cloud-mcp', diff --git a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx index 76147988a74..d603f1b18f7 100644 --- a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx +++ b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx @@ -20,6 +20,7 @@ import { CloudPredictiveWakeSetting } from './CloudPredictiveWakeSetting' import { OrcaCloudMcpServersPane } from './OrcaCloudMcpServersPane' import { OrcaCloudLocalCommandsPane } from './OrcaCloudLocalCommandsPane' import { OrcaCloudSkillsPane } from './cloud-skills/OrcaCloudSkillsPane' +import { TeamWorkspacesSettings } from '../cloud-workspaces/TeamWorkspacesSettings' type OrcaCloudAccount = { orgId: string | null @@ -105,6 +106,15 @@ function OrcaCloudAccountGate({ ) } +/** Settings › Workspaces (team owners and admins): every team cloud workspace, to manage. */ +export function OrcaCloudWorkspacesPane(): React.JSX.Element { + return ( + + {(account) => } + + ) +} + /** Settings › Enterprise: single sign-on, sign-in policies and the team audit log. */ export function OrcaCloudEnterprisePane(): React.JSX.Element { return {() => } diff --git a/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts b/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts index b1ca6546f97..50864bf5d17 100644 --- a/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts +++ b/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts @@ -52,6 +52,22 @@ export const getOrcaCloudEnterpriseSearchEntries = createLocalizedCatalog(() => } ]) +export const getOrcaCloudWorkspacesSearchEntries = createLocalizedCatalog(() => [ + { + title: translate('settings.teamWorkspaces.title', 'Cloud workspaces'), + description: translate( + 'settings.teamWorkspaces.searchDescription', + 'Every cloud workspace on your team, to open, sleep or archive.' + ), + keywords: [ + ...translateSearchKeyword('settings.teamWorkspaces.keywordCloud', 'cloud workspaces'), + ...translateSearchKeyword('settings.teamWorkspaces.keywordTeam', 'team workspaces'), + ...translateSearchKeyword('settings.teamWorkspaces.keywordSandboxes', 'sandboxes'), + ...translateSearchKeyword('settings.teamWorkspaces.keywordArchive', 'archive') + ] + } +]) + export const getOrcaCloudSecretsSearchEntries = createLocalizedCatalog(() => [ { title: translate('cloudSecrets.title', 'Cloud secrets'), diff --git a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx index d4d004e20e2..41c3662a46e 100644 --- a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx @@ -5,7 +5,8 @@ import { OrcaCloudMcpPane, OrcaCloudSecretsPane, OrcaCloudSkillsSyncPane, - OrcaCloudTeamPane + OrcaCloudTeamPane, + OrcaCloudWorkspacesPane } from '../orca-cloud/OrcaCloudSettingsPanes' import { SettingsSection } from '../section-layout/SettingsSection' import { translate } from '@/i18n/i18n' @@ -27,6 +28,7 @@ export function renderOrcaCloudSettingsSections( const sections: { id: string; pane: React.JSX.Element; navOnly?: boolean }[] = [ { id: 'cloud-team', pane: }, // Listed in the nav for team owners and admins only; without the entry there is no page. + { id: 'cloud-workspaces', pane: , navOnly: true }, { id: 'cloud-enterprise', pane: , navOnly: true }, { id: 'cloud-secrets', pane: }, { id: 'cloud-skills', pane: }, diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx index cce3ceaa0c0..18ee67a480f 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx @@ -64,6 +64,7 @@ export const conductor = defineFixture({ setup: shortSetup, archive: null, editable: false, + ubuntuNote: null, skippedFields: ['environment_variables'], runActions: '# Web (web)\npnpm dev --port $CONDUCTOR_PORT\n\n# Worker (worker)\npnpm worker:dev' @@ -92,6 +93,7 @@ export const devcontainer = defineFixture({ setup: longSetup, archive: 'docker compose -f infra/docker-compose.dev.yml down --volumes', editable: false, + ubuntuNote: null, skippedFields: ['postStartCommand', 'postAttachCommand', 'features', 'forwardPorts'], runActions: null }} @@ -139,6 +141,7 @@ export const hugeReviewExpanded = defineFixture({ setup: hugeSetup, archive: hugeSetup, editable: false, + ubuntuNote: null, skippedFields: Array.from({ length: 30 }, (_, index) => `steps.${index}.uses`), runActions: null }} @@ -161,6 +164,7 @@ export const packageManager = defineFixture({ setup: 'pnpm install', archive: null, editable: true, + ubuntuNote: null, skippedFields: [], runActions: null }} @@ -168,3 +172,59 @@ export const packageManager = defineFixture({ ) }) + +/** PARITY-DNF: a Conductor setup from Amazon Linux; translated lines, and lines left to check. */ +export const conductorDnfReview = defineFixture({ + width: 720, + render: () => ( + + + + ), + interact: openReview +}) + +/** PARITY-DNF: every dnf install line translated. */ +export const conductorDnfTranslatedReview = defineFixture({ + width: 720, + render: () => ( + + + + ), + interact: openReview +}) diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx index ae8d7776385..da6289f4155 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx @@ -118,6 +118,7 @@ export function SetupScriptPromptCardShell({ archive={detectedSetupPreview.archive} runActions={detectedSetupPreview.runActions} skippedFields={detectedSetupPreview.skippedFields} + ubuntuNote={detectedSetupPreview.ubuntuNote} provenance={candidateProvenance} isSaving={isImporting} onSave={onImport} diff --git a/src/renderer/src/components/sidebar/SetupScriptReviewDialog.tsx b/src/renderer/src/components/sidebar/SetupScriptReviewDialog.tsx index af82dc66618..2c0a9676509 100644 --- a/src/renderer/src/components/sidebar/SetupScriptReviewDialog.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptReviewDialog.tsx @@ -1,3 +1,5 @@ +import { UbuntuSetupNote } from './UbuntuSetupNote' +import type { UbuntuNote } from '../../../../shared/workspace-setup/setup-script-imports' import React from 'react' import { Download, LoaderCircle } from 'lucide-react' import { Trans } from 'react-i18next' @@ -24,6 +26,8 @@ export type SetupScriptReviewDialogProps = { /** Imported run actions; saved with setup and started from the Run button. */ runActions?: string | null skippedFields: readonly string[] + /** PARITY-DNF: Amazon Linux install lines translated to apt-get, and what to check. */ + ubuntuNote?: UbuntuNote | null provenance: string | null isSaving: boolean onSave: () => void @@ -63,6 +67,7 @@ export function SetupScriptReviewDialog({ archive, runActions, skippedFields, + ubuntuNote = null, provenance, isSaving, onSave @@ -124,6 +129,7 @@ export function SetupScriptReviewDialog({ /> ) : null} + {ubuntuNote ? : null} {skippedFields.length > 0 ? : null} diff --git a/src/renderer/src/components/sidebar/UbuntuSetupNote.tsx b/src/renderer/src/components/sidebar/UbuntuSetupNote.tsx new file mode 100644 index 00000000000..867f8aaedc2 --- /dev/null +++ b/src/renderer/src/components/sidebar/UbuntuSetupNote.tsx @@ -0,0 +1,46 @@ +// PARITY-DNF: an imported setup from Conductor (Amazon Linux, dnf). Says what changed for Orca's +// Ubuntu sandboxes, and lists the lines that still use dnf so the person can check them. +import React from 'react' +import { useTranslate } from '@/i18n/use-translate' +import type { UbuntuNote } from '../../../../shared/workspace-setup/setup-script-imports' + +export function UbuntuSetupNote({ note }: { note: UbuntuNote }): React.JSX.Element { + const t = useTranslate() + const check = note.checkLines.length > 0 + const translated = note.translated > 0 + return ( +
+

+ {t('setupScriptImport.ubuntuNote.title', 'Written for dnf')} +

+

+ {translated && check + ? t( + 'setupScriptImport.ubuntuNote.mixed', + 'Orca’s sandboxes run Ubuntu, so this script’s dnf install lines now use apt-get. These lines still use dnf. Check them before saving:' + ) + : check + ? t( + 'setupScriptImport.ubuntuNote.check', + 'Orca’s sandboxes run Ubuntu, and these lines still use dnf. Check them before saving:' + ) + : t( + 'setupScriptImport.ubuntuNote.translated', + 'Orca’s sandboxes run Ubuntu, so this script’s dnf install lines now use apt-get.' + )} +

+ {check ? ( +
    + {note.checkLines.map((line) => ( +
  • + {/* Wrapped, never cut off: the person has to read the whole line. */} + + {line} + +
  • + ))} +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/index.tsx b/src/renderer/src/components/sidebar/index.tsx index 5b22a0a219c..57d46dce810 100644 --- a/src/renderer/src/components/sidebar/index.tsx +++ b/src/renderer/src/components/sidebar/index.tsx @@ -4,6 +4,7 @@ import { TooltipProvider } from '@/components/ui/tooltip' import { useSidebarResize } from '@/hooks/useSidebarResize' import SidebarHeader from './SidebarHeader' import SidebarNav from './SidebarNav' +import { SidebarTeamPanel } from './team/SidebarTeamPanel' import { setSidebarLiveWidth } from './sidebar-live-width' import SetupScriptPromptCard from './SetupScriptPromptCard' import WorktreeList from './worktree-list/listing/WorktreeList' @@ -186,6 +187,7 @@ function Sidebar({ {sidebarOpen && ( <> + s.orcaProfileAuthStatus?.cloud) + const account = useOrcaAccountKey() + const available = useCloudWorkspacesAvailable() + const orgId = cloud?.activeOrgId ?? null + const selfId = cloud?.userId ?? null + const live = useTeamWorkspacesLive(orgId && available ? account : null) + const roster = useOrgRoster(orgId) + const { directory } = useMemberDirectory(orgId ?? undefined, live ?? []) + const memberIds = useMemo( + () => + roster.result?.status === 'ok' + ? roster.result.roster.members.flatMap((m) => (m.userId ? [m.userId] : [])) + : [], + [roster.result] + ) + const members = useMemo(() => teammateActivities(memberIds, live), [memberIds, live]) + const followed = useMemo(() => followedWorkspaces(live, selfId), [live, selfId]) + if (!orgId || !available) { + return null + } + const open = (sandboxId: string): void => { + const workspace = live?.find((w) => w.id === sandboxId) + if (workspace) { + void openCloudWorkspace(workspace) + } + } + const unfollow = (sandboxId: string): void => { + void setCloudWorkspaceFollow(sandboxId, false).then((ok) => { + if (!ok) { + toast.error(t('cloudFollow.unfollowFailed', 'Couldn’t unfollow this workspace')) + } + }) + } + return ( + <> + openCloudWorkspacePicker({ kind: 'teammate', userId })} + /> + + + ) +} diff --git a/src/renderer/src/components/sidebar/team/SidebarTeamSections.fixture.tsx b/src/renderer/src/components/sidebar/team/SidebarTeamSections.fixture.tsx new file mode 100644 index 00000000000..f6c5854f8a2 --- /dev/null +++ b/src/renderer/src/components/sidebar/team/SidebarTeamSections.fixture.tsx @@ -0,0 +1,179 @@ +// PARITY-FOLLOW (design review): Team and Following in the sidebar, between the nav and Projects. +import { defineFixture } from '../../../component-fixtures/component-fixture' +import { DIRECTORY, SELF_ID } from '../../cloud-workspaces/cloud-workspaces.test-fixture' +import { + SidebarFollowingSection, + SidebarTeamList, + type SidebarFollowedWorkspace, + type SidebarTeammate +} from './SidebarTeamSections' + +const noop = (): void => {} + +const TEAM: SidebarTeammate[] = [ + { userId: SELF_ID, activity: null }, + { userId: 'user_alan', activity: null }, + { userId: 'user_grace', activity: { state: 'typing', workspaceLabel: 'Checkout retries' } }, + { userId: 'user_linus', activity: { state: 'viewing', workspaceLabel: 'Refund webhooks' } }, + { userId: 'user_mae', activity: null } +] + +const FOLLOWING: SidebarFollowedWorkspace[] = [ + { + sandboxId: 'sbx_a', + title: 'Checkout retries', + numberLabel: 'W-582', + creatorId: 'user_grace', + status: 'running', + hereNow: 2 + }, + { + sandboxId: 'sbx_b', + title: 'Refund webhooks', + numberLabel: 'W-577', + creatorId: 'user_linus', + status: 'asleep', + hereNow: 0 + }, + { + sandboxId: 'sbx_c', + title: 'Ledger migration with a long title that truncates', + numberLabel: 'W-561', + creatorId: 'user_mae', + status: 'archived', + hereNow: 0 + } +] + +/** Stands in for the sidebar column: nav above, Projects below. */ +function Column({ children }: { children: React.ReactNode }): React.JSX.Element { + return ( +
+
Tasks
+
Automations
+ {children} +
Projects
+
master
+
+ ) +} + +/** Both sections open: teammates active first; followed workspaces with status and who's here. */ +export const teamAndFollowing = defineFixture({ + width: 340, + render: () => ( + + + + + ) +}) + +/** Collapsed headers keep the count; nothing followed hides Following entirely. */ +export const collapsedAndEmpty = defineFixture({ + width: 340, + render: () => ( + + + + + ) +}) + +/** Hovering a row shows its action: a teammate's workspaces, or Unfollow. */ +export const rowHover = defineFixture({ + width: 340, + render: () => ( + + + + + ), + interact: async (frame) => { + for (const row of frame.querySelectorAll('.group\\/team-row')) { + if (row.textContent?.includes('Grace') || row.textContent?.includes('Refund')) { + row.classList.add('bg-worktree-sidebar-foreground/8') + for (const el of row.querySelectorAll('.group-hover\\/team-row\\:hidden')) { + el.style.display = 'none' + } + for (const el of row.querySelectorAll( + '.group-hover\\/team-row\\:opacity-100' + )) { + el.style.opacity = '1' + } + } + } + } +}) + +/** A big team: 6 rows, then "Show all 9". */ +export const teamCapped = defineFixture({ + width: 340, + render: () => ( + + ({ userId: `user_extra_${i}`, activity: null }) + ) + ]} + directory={ + new Map([ + ...DIRECTORY, + ...[ + 'Rosa Parks', + 'Ken Thompson', + 'Barbara Liskov', + 'Edsger Dijkstra', + 'Hedy Lamarr' + ].map((name, i): [string, { name: string; email: string | null }] => [ + `user_extra_${i}`, + { name, email: null } + ]) + ]) + } + selfId={SELF_ID} + onOpenProfile={noop} + onShowWorkspaces={noop} + /> + + ) +}) diff --git a/src/renderer/src/components/sidebar/team/SidebarTeamSections.test.tsx b/src/renderer/src/components/sidebar/team/SidebarTeamSections.test.tsx new file mode 100644 index 00000000000..5251ac0063b --- /dev/null +++ b/src/renderer/src/components/sidebar/team/SidebarTeamSections.test.tsx @@ -0,0 +1,132 @@ +// @vitest-environment happy-dom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { DIRECTORY, SELF_ID } from '../../cloud-workspaces/cloud-workspaces.test-fixture' +import { + SidebarFollowingSection, + SidebarTeamList, + type SidebarTeammate +} from './SidebarTeamSections' + +afterEach(() => cleanup()) +beforeEach(() => window.localStorage.clear()) + +const noop = (): void => {} + +function team(ids: string[], active: Record = {}): SidebarTeammate[] { + return ids.map((userId) => ({ + userId, + activity: active[userId] ? { state: active[userId], workspaceLabel: 'Checkout' } : null + })) +} + +function renderTeam(members: SidebarTeammate[], onShowWorkspaces = noop, onOpenProfile = noop) { + return render( + + + + ) +} + +describe('SidebarTeamList (PARITY-FOLLOW)', () => { + it('lists teammates, active first, never you', () => { + const { container } = renderTeam( + team([SELF_ID, 'user_alan', 'user_grace'], { user_grace: 'typing' }) + ) + const rows = [...container.querySelectorAll('div[role="button"]')] + expect(rows.map((r) => r.getAttribute('aria-label'))).toEqual([ + 'Grace Hopper, Typing in Checkout', + 'Alan Kay' + ]) + }) + + it('hides itself for a team of one', () => { + const { container } = renderTeam(team([SELF_ID])) + expect(container.textContent).toBe('') + }) + + it('caps the list at 6 with "Show all"', () => { + const ids = Array.from({ length: 8 }, (_, i) => `user_${i}`) + renderTeam(team(ids)) + expect(screen.getAllByRole('listitem')).toHaveLength(7) + fireEvent.click(screen.getByRole('button', { name: 'Show all 8' })) + expect(screen.getAllByRole('listitem')).toHaveLength(8) + }) + + it('opens a profile from the row and a teammate’s workspaces from its action', () => { + const openProfile = vi.fn() + const showWorkspaces = vi.fn() + renderTeam(team(['user_grace']), showWorkspaces, openProfile) + fireEvent.click(screen.getByRole('button', { name: 'Grace Hopper' })) + expect(openProfile).toHaveBeenCalledWith('user_grace') + fireEvent.click(screen.getByRole('button', { name: 'Grace Hopper’s workspaces' })) + expect(showWorkspaces).toHaveBeenCalledWith('user_grace') + expect(openProfile).toHaveBeenCalledTimes(1) + }) + + it('remembers its collapsed state for this member', () => { + renderTeam(team(['user_grace'])) + fireEvent.click(screen.getByRole('button', { name: /Team/ })) + expect(screen.queryByRole('listitem')).toBeNull() + cleanup() + renderTeam(team(['user_grace'])) + expect(screen.queryByRole('listitem')).toBeNull() + expect(screen.getByRole('button', { name: /Team/ }).getAttribute('aria-expanded')).toBe('false') + }) +}) + +describe('SidebarFollowingSection (PARITY-FOLLOW)', () => { + it('is hidden when nothing is followed', () => { + const { container } = render( + + + + ) + expect(container.textContent).toBe('') + }) + + it('opens a followed workspace and unfollows from the row action', () => { + const onOpen = vi.fn() + const onUnfollow = vi.fn() + render( + + + + ) + expect(screen.getByText('Asleep')).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Unfollow Checkout retries' })) + expect(onUnfollow).toHaveBeenCalledWith('sbx_a') + expect(onOpen).not.toHaveBeenCalled() + fireEvent.click(screen.getByText('Checkout retries')) + expect(onOpen).toHaveBeenCalledWith('sbx_a') + }) +}) diff --git a/src/renderer/src/components/sidebar/team/SidebarTeamSections.tsx b/src/renderer/src/components/sidebar/team/SidebarTeamSections.tsx new file mode 100644 index 00000000000..5c98ae31774 --- /dev/null +++ b/src/renderer/src/components/sidebar/team/SidebarTeamSections.tsx @@ -0,0 +1,360 @@ +// PARITY-FOLLOW: the sidebar's Team list and Following section, under the nav and above Projects, +// for a team account only. Team: each teammate with what they are doing now (from workspace +// presence); a row opens their profile, its hover action their workspaces. Following: teammates' +// cloud workspaces this member follows; a row opens the workspace, its hover action unfollows. +import React, { useCallback, useState } from 'react' +import { ChevronRight, LayoutList, Users, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/class-names' +import { MemberAvatar } from '@/components/cloud-workspaces/CloudMemberAvatars' +import { + memberHue, + type MemberDirectory +} from '@/components/cloud-workspaces/cloud-workspace-format' + +export type SidebarTeammate = { + userId: string + /** What they are doing now, from workspace presence; null when not in any workspace. */ + activity: { state: 'viewing' | 'typing'; workspaceLabel: string } | null +} + +export type SidebarFollowedWorkspace = { + sandboxId: string + title: string + /** W-123, when known. */ + numberLabel: string | null + creatorId: string + status: 'running' | 'asleep' | 'waking' | 'archived' + /** Teammates in it now (not counting this member). */ + hereNow: number +} + +/** Active first (typing, then viewing), then by name. */ +export function sortTeammates( + members: readonly SidebarTeammate[], + directory: MemberDirectory +): SidebarTeammate[] { + const rank = (m: SidebarTeammate): number => + m.activity?.state === 'typing' ? 0 : m.activity ? 1 : 2 + const name = (m: SidebarTeammate): string => directory.get(m.userId)?.name ?? m.userId + return [...members].sort((a, b) => rank(a) - rank(b) || name(a).localeCompare(name(b))) +} + +function hueStyle(userId: string): React.CSSProperties & { '--avatar-hue': string } { + return { '--avatar-hue': String(memberHue(userId)) } +} + +/** Team rows shown before "Show all". */ +export const TEAM_LIST_CAP = 6 + +/** A section's open state, remembered on this computer for this member. */ +export function useSidebarSectionOpen( + section: 'team' | 'following', + selfId: string | null, + defaultOpen: boolean +): [boolean, () => void] { + const key = `orca.sidebar.${section}.open:${selfId ?? 'anon'}` + const [open, setOpen] = useState(() => { + try { + const stored = window.localStorage.getItem(key) + return stored === null ? defaultOpen : stored === 'true' + } catch { + return defaultOpen + } + }) + const toggle = useCallback(() => { + const next = !open + setOpen(next) + try { + window.localStorage.setItem(key, String(next)) + } catch { + // Not remembered; the toggle still works for this session. + } + }, [key, open]) + return [open, toggle] +} + +const ROW = + 'group/team-row flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1 text-left text-[13px] tracking-tight text-worktree-sidebar-foreground/80 hover:bg-worktree-sidebar-foreground/8' + +function SectionHeader({ + title, + count, + open, + onToggle +}: { + title: string + count: number + open: boolean + onToggle: () => void +}): React.JSX.Element { + return ( + + ) +} + +function HoverAction({ + label, + onClick, + children +}: { + label: string + onClick: () => void + children: React.ReactNode +}): React.JSX.Element { + return ( + // Shown on the row's hover or focus; the wrapper owns that, the Button keeps its own look. + + + + + + + {label} + + + + ) +} + +export function SidebarTeamList({ + members, + directory, + selfId, + defaultOpen = true, + onOpenProfile, + onShowWorkspaces +}: { + members: SidebarTeammate[] + directory: MemberDirectory + selfId: string | null + defaultOpen?: boolean + onOpenProfile: (userId: string) => void + onShowWorkspaces: (userId: string) => void +}): React.JSX.Element | null { + const t = useTranslate() + const [open, toggle] = useSidebarSectionOpen('team', selfId, defaultOpen) + const [showAll, setShowAll] = useState(false) + const teammates = sortTeammates( + members.filter((m) => m.userId !== selfId), + directory + ) + if (teammates.length === 0) { + return null + } + return ( +
+ + {open ? ( +
    + {(showAll ? teammates : teammates.slice(0, TEAM_LIST_CAP)).map((m) => { + const name = directory.get(m.userId)?.name ?? m.userId + const doing = m.activity + ? m.activity.state === 'typing' + ? t('sidebarTeam.typingIn', 'Typing in {{workspace}}', { + workspace: m.activity.workspaceLabel + }) + : t('sidebarTeam.viewing', 'In {{workspace}}', { + workspace: m.activity.workspaceLabel + }) + : null + return ( +
  • +
    onOpenProfile(m.userId)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + onOpenProfile(m.userId) + } + }} + aria-label={doing ? `${name}, ${doing}` : name} + > + {/* Here now: a ring in their own color (as in the top bar); typing adds the + pulsing dot. Never the workspace status colors. */} + + + {m.activity?.state === 'typing' ? ( + + ) : null} + + + {name} + {doing ? ( + {doing} + ) : null} + + onShowWorkspaces(m.userId)} + > + + +
    +
  • + ) + })} + {!showAll && teammates.length > TEAM_LIST_CAP ? ( +
  • + +
  • + ) : null} +
+ ) : null} +
+ ) +} + +export function SidebarFollowingSection({ + workspaces, + directory, + selfId, + defaultOpen = true, + onOpen, + onUnfollow +}: { + workspaces: SidebarFollowedWorkspace[] + directory: MemberDirectory + selfId: string | null + defaultOpen?: boolean + onOpen: (sandboxId: string) => void + onUnfollow: (sandboxId: string) => void +}): React.JSX.Element | null { + const t = useTranslate() + const [open, toggle] = useSidebarSectionOpen('following', selfId, defaultOpen) + // Nothing followed: no section (Follow lives on the workspace, beside its W-123). + if (workspaces.length === 0) { + return null + } + const statusWord = (s: SidebarFollowedWorkspace['status']): string | null => + s === 'asleep' + ? t('sidebarFollowing.asleep', 'Asleep') + : s === 'waking' + ? t('sidebarFollowing.waking', 'Waking') + : s === 'archived' + ? t('sidebarFollowing.archived', 'Archived') + : null + return ( +
+ + {open ? ( +
    + {workspaces.map((w) => { + const word = statusWord(w.status) + return ( +
  • +
    onOpen(w.sandboxId)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + onOpen(w.sandboxId) + } + }} + > + + {w.title} + {w.hereNow > 0 ? ( + + + {w.hereNow} + + ) : null} + {word ? ( + + {word} + + ) : null} + {w.numberLabel ? ( + + {w.numberLabel} + + ) : null} + onUnfollow(w.sandboxId)} + > + + +
    +
  • + ) + })} +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/team/team-activity.test.ts b/src/renderer/src/components/sidebar/team/team-activity.test.ts new file mode 100644 index 00000000000..3e0262a3bf6 --- /dev/null +++ b/src/renderer/src/components/sidebar/team/team-activity.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { presence, workspace } from '../../cloud-workspaces/cloud-workspaces.test-fixture' +import { teammateActivities, workspaceDisplayLabel } from './team-activity' + +describe('teammateActivities (PARITY-FOLLOW)', () => { + it('says what each teammate is doing now, by workspace name, in roster order', () => { + const rows = teammateActivities( + ['user_grace', 'user_linus', 'user_alan'], + [ + workspace({ title: 'Checkout retries', presence: [presence('user_grace', 'typing')] }), + workspace({ title: 'Ledger', presence: [presence('user_linus')] }) + ] + ) + expect(rows).toEqual([ + { userId: 'user_grace', activity: { state: 'typing', workspaceLabel: 'Checkout retries' } }, + { userId: 'user_linus', activity: { state: 'viewing', workspaceLabel: 'Ledger' } }, + { userId: 'user_alan', activity: null } + ]) + }) + + it('prefers typing anywhere over viewing elsewhere, then the most recent', () => { + const viewing = { ...presence('user_grace'), at: 2_000 } + const typing = { ...presence('user_grace', 'typing'), at: 1_000 } + const rows = teammateActivities( + ['user_grace'], + [ + workspace({ title: 'A', presence: [viewing] }), + workspace({ title: 'B', presence: [typing] }) + ] + ) + expect(rows[0]?.activity).toEqual({ state: 'typing', workspaceLabel: 'B' }) + const newer = teammateActivities( + ['user_grace'], + [ + workspace({ title: 'Old', presence: [{ ...presence('user_grace'), at: 1 }] }), + workspace({ title: 'New', presence: [{ ...presence('user_grace'), at: 5 }] }) + ] + ) + expect(newer[0]?.activity?.workspaceLabel).toBe('New') + }) + + it('reads no activity before the first list arrives', () => { + expect(teammateActivities(['user_grace'], null)).toEqual([ + { userId: 'user_grace', activity: null } + ]) + }) + + it('names a workspace by title, then W-number, then repo', () => { + expect(workspaceDisplayLabel(workspace({ title: 'Checkout', number: 7 }))).toBe('Checkout') + expect(workspaceDisplayLabel(workspace({ title: ' ', number: 582 }))).toBe('W-582') + expect( + workspaceDisplayLabel( + workspace({ + title: null, + number: null, + repo: { url: 'https://github.com/acme/payments.git', branch: null } + }) + ) + ).toBe('acme/payments') + }) +}) diff --git a/src/renderer/src/components/sidebar/team/team-activity.ts b/src/renderer/src/components/sidebar/team/team-activity.ts new file mode 100644 index 00000000000..ed33bd54fda --- /dev/null +++ b/src/renderer/src/components/sidebar/team/team-activity.ts @@ -0,0 +1,77 @@ +// PARITY-FOLLOW: what each teammate is doing now, from the team workspace list's live presence. +import type { CloudWorkspace } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { formatWorkspaceNumber } from '../../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { repoLabel } from '@/components/cloud-workspaces/cloud-workspace-format' +import type { SidebarFollowedWorkspace, SidebarTeammate } from './SidebarTeamSections' + +/** A workspace by name (people recognise names); its W-number, then its repo, as fallbacks. */ +export function workspaceDisplayLabel( + w: Pick +): string { + const title = w.title?.trim() + if (title) { + return title + } + if (w.number) { + return formatWorkspaceNumber(w.number) + } + return w.repo ? repoLabel(w.repo.url) : w.id +} + +/** + * One row per teammate, in roster order: typing wins over viewing, and the most recent presence + * wins between workspaces of the same state. + */ +export function teammateActivities( + memberIds: readonly string[], + workspaces: readonly CloudWorkspace[] | null +): SidebarTeammate[] { + const best = new Map() + for (const w of workspaces ?? []) { + for (const p of w.presence) { + const current = best.get(p.userId) + const better = + !current || + (p.state === 'typing' && current.state !== 'typing') || + (p.state === current.state && p.at > current.at) + if (better) { + best.set(p.userId, { state: p.state, at: p.at, label: workspaceDisplayLabel(w) }) + } + } + } + return memberIds.map((userId) => { + const found = best.get(userId) + return { + userId, + activity: found ? { state: found.state, workspaceLabel: found.label } : null + } + }) +} + +function followedStatus(w: CloudWorkspace): SidebarFollowedWorkspace['status'] { + if (w.archivedAt !== null) { + return 'archived' + } + if (w.status === 'running') { + return 'running' + } + return w.status === 'creating' || w.status === 'resuming' ? 'waking' : 'asleep' +} + +/** Teammates' workspaces this member follows, most recently active first (PARITY-FOLLOW). */ +export function followedWorkspaces( + workspaces: readonly CloudWorkspace[] | null, + selfId: string | null +): SidebarFollowedWorkspace[] { + return (workspaces ?? []) + .filter((w) => w.following === true && w.createdBy !== selfId) + .sort((a, b) => b.lastActivityAt - a.lastActivityAt) + .map((w) => ({ + sandboxId: w.id, + title: workspaceDisplayLabel(w), + numberLabel: w.number ? formatWorkspaceNumber(w.number) : null, + creatorId: w.createdBy, + status: followedStatus(w), + hereNow: new Set(w.presence.map((p) => p.userId).filter((id) => id !== selfId)).size + })) +} diff --git a/src/renderer/src/components/sidebar/team/team-followed.test.ts b/src/renderer/src/components/sidebar/team/team-followed.test.ts new file mode 100644 index 00000000000..635a794c38d --- /dev/null +++ b/src/renderer/src/components/sidebar/team/team-followed.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { presence, SELF_ID, workspace } from '../../cloud-workspaces/cloud-workspaces.test-fixture' +import { followOffer } from '../../cloud-workspaces/CloudWorkspacePeople' +import { followedWorkspaces } from './team-activity' + +describe('followedWorkspaces (PARITY-FOLLOW)', () => { + it("lists teammates' workspaces you follow, most recently active first, with who's here", () => { + const rows = followedWorkspaces( + [ + workspace({ title: 'Old', createdBy: 'user_grace', following: true, lastActivityAt: 1 }), + workspace({ + title: 'Checkout', + number: 582, + createdBy: 'user_linus', + following: true, + lastActivityAt: 9, + presence: [presence('user_mae'), presence(SELF_ID), presence('user_mae', 'typing')] + }), + workspace({ title: 'Not followed', createdBy: 'user_grace', following: false }), + workspace({ title: 'Mine', createdBy: SELF_ID, following: true }), + workspace({ + title: 'Asleep', + createdBy: 'user_grace', + following: true, + status: 'suspended', + lastActivityAt: 0 + }) + ], + SELF_ID + ) + expect(rows.map((r) => [r.title, r.status, r.hereNow, r.numberLabel])).toEqual([ + ['Checkout', 'running', 1, 'W-582'], + ['Old', 'running', 0, expect.any(String)], + ['Asleep', 'asleep', 0, expect.any(String)] + ]) + }) +}) + +describe('followOffer (PARITY-FOLLOW)', () => { + it("offers Follow on a teammate's workspace, never on your own or from an older control plane", () => { + expect(followOffer(workspace({ createdBy: 'user_grace', following: false }), SELF_ID)).toBe( + false + ) + expect(followOffer(workspace({ createdBy: 'user_grace', following: true }), SELF_ID)).toBe(true) + expect(followOffer(workspace({ createdBy: SELF_ID, following: false }), SELF_ID)).toBeNull() + expect(followOffer(workspace({ createdBy: 'user_grace' }), SELF_ID)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index 6ec6883b9cb..1e61312530b 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -27,6 +27,7 @@ import { useWindowBackdropActive } from '@/app-shell/appearance/window-backdrop' import { EditorRevealFlash } from './EditorRevealFlash' import { SplitPaneLanding } from './SplitPaneLanding' import { CloudWorkspaceNumberChip } from '../cloud-workspaces/CloudWorkspaceNumberChip' +import { CloudWorkspacePeople } from '../cloud-workspaces/CloudWorkspacePeople' import { CloudGitSetupStrip } from '../orca-cloud/CloudGitSetupStrip' import { isSplitLandingGroup } from '@/store/slices/tabs/split-landing-groups' @@ -315,7 +316,10 @@ export default function TabGroupPanel({ > {/* One W-number and Run button per workspace: in the focused split, or the only group. */} {!hasSplitGroups || isFocused ? ( - + <> + + + ) : null} {!hasSplitGroups || isFocused ? : null} void + underBanner?: boolean +}): React.JSX.Element | null { + const t = useTranslate() + const { policy, refresh } = useTeamMfaPolicy(orgId) + const [pending, setPending] = useState(null) + const [busy, setBusy] = useState(false) + const [notice, setNotice] = useState(null) + const [now] = useState(() => Date.now()) + const active = policy?.policy ?? null + + const loadPending = useCallback(async (): Promise => { + try { + const result = await window.api.orcaProfiles.teamMfaPending({ orgId }) + setPending(result.status === 'ok' ? result.members : null) + } catch { + setPending(null) + } + }, [orgId]) + + useEffect(() => { + if (active) { + void loadPending() + } else { + setPending(null) + } + // Reload when the deadline changes, not on every policy read. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [active?.enforceAt, loadPending]) + + // Nothing until the first read answers, and nothing for a server without the policy API. + if (!policy?.manage) { + return null + } + + const change = async (enforce: OrcaTeamMfaGrace | 'off'): Promise => { + setBusy(true) + setNotice(null) + let status: string + try { + status = (await window.api.orcaProfiles.teamMfaPolicySet({ orgId, enforce })).status + } catch { + status = 'failed' + } + setBusy(false) + if (status === 'ok') { + await refresh() + return + } + const known: readonly ChangeStatus[] = [ + 'actor-needs-mfa', + 'not-entitled', + 'sso-needs-notice', + 'rate-limited', + 'forbidden' + ] + setNotice({ + kind: 'error', + message: mfaChangeError(known.find((candidate) => candidate === status) ?? 'other', t) + }) + } + + const remind = async (userId?: string): Promise => { + setBusy(true) + setNotice(null) + try { + const result = await window.api.orcaProfiles.teamMfaRemind({ + orgId, + ...(userId ? { userId } : {}) + }) + setNotice( + result.status === 'ok' + ? { + kind: 'reminded', + recipients: result.recipients, + // Only a server that says it emailed counts as sent. + emailed: result.delivery === 'test-inbox' + } + : { + kind: 'error', + message: mfaChangeError( + result.status === 'rate-limited' ? 'rate-limited' : 'other', + t + ) + } + ) + } catch { + setNotice({ kind: 'error', message: mfaChangeError('other', t) }) + } + setBusy(false) + } + + return ( + void change(grace)} + onTurnOff={() => void change('off')} + onRemind={(userId) => void remind(userId)} + onSetUpOwn={() => void window.api.shell.openUrl(policy.setupUrl)} + onContactSales={onContactSales} + underBanner={underBanner} + /> + ) +} + +export type EnterpriseMfaGroupProps = Omit & { + policy: OrcaTeamMfaPolicy + manage: NonNullable + contact: EnterpriseContact + onContactSales: (url: string) => void + /** The page banner already carries Contact sales: the locked state is a plain line, no button. */ + underBanner?: boolean +} + +/** + * The "Two-factor authentication" group as shown: the Require two-factor row when the plan + * includes it, the shared upsell when it does not, and the single sign-on note when the team's + * identity provider handles members who sign in that way. + */ +export function EnterpriseMfaGroup({ + policy, + manage, + contact, + onContactSales, + underBanner = false, + ...row +}: EnterpriseMfaGroupProps): React.JSX.Element { + const t = useTranslate() + const upsellBody = t( + 'auto.components.teamMfa.upsellBody', + 'Set a date after which members need two-factor authentication to use your team’s workspaces.' + ) + return ( + + {manage.available ? ( + // Padded like every other row in a settings card, so it does not sit on the card's edge. +
+ +
+ ) : underBanner ? ( + {upsellBody} + ) : ( + + )} +
+ ) +} diff --git a/src/renderer/src/components/team-mfa/RequireMfaRow.tsx b/src/renderer/src/components/team-mfa/RequireMfaRow.tsx index 8e45a9b8d25..9b68c9fc82d 100644 --- a/src/renderer/src/components/team-mfa/RequireMfaRow.tsx +++ b/src/renderer/src/components/team-mfa/RequireMfaRow.tsx @@ -39,7 +39,7 @@ export type RequireMfaRowProps = { } /** - * "Require MFA" in Settings, Enterprise, Multi-factor authentication. Rendered only for a team + * "Require two-factor" in Settings, Enterprise, Multi-factor authentication. Rendered only for a team * whose plan includes it; the pane shows its shared upsell otherwise. */ export function RequireMfaRow({ @@ -59,7 +59,7 @@ export function RequireMfaRow({ const active = policy.policy const pendingCount = policy.manage?.pendingMembers ?? 0 // The server refuses a change from someone without MFA; say so before they try. - const needsOwnMfa = policy.self !== 'on' + const needsOwnMfa = policy.self !== 'on' && policy.self !== 'delegated' const enforced = active !== null && active.enforceAt <= now return ( @@ -128,7 +128,7 @@ export function RequireMfaRow({ }} > {busy ? : null} - {t('auto.components.teamMfa.require', 'Require MFA')} + {t('auto.components.teamMfa.require', 'Require two-factor')} ) : ( @@ -167,7 +167,7 @@ export function RequireMfaRow({ link={policy.setupUrl} onClick={onSetUpOwn} > - {t('auto.components.teamMfa.setUp', 'Set up MFA')} + {t('auto.components.teamMfa.setUp', 'Set up two-factor')} } /> @@ -217,7 +217,10 @@ export function RequireMfaRow({ {pending && pending.length > 0 ? (
    {pending.map((member) => (
  • - {member.mfa === 'blocked' - ? t('auto.components.teamMfa.memberBlocked', 'No access') - : t('auto.components.teamMfa.memberPending', 'Pending')} + {member.userId === null + ? // No account to remind yet, which is why this row has no Remind button. + t('auto.components.teamMfa.memberNotSignedIn', 'Hasn’t signed in yet') + : member.mfa === 'blocked' + ? t('auto.components.teamMfa.memberBlocked', 'No access') + : t('auto.components.teamMfa.memberPending', 'Pending')} {member.userId ? ( + ) : null} ) diff --git a/src/renderer/src/components/team-mfa/team-mfa-copy.ts b/src/renderer/src/components/team-mfa/team-mfa-copy.ts index f5cc4296d33..7d7f45f3dda 100644 --- a/src/renderer/src/components/team-mfa/team-mfa-copy.ts +++ b/src/renderer/src/components/team-mfa/team-mfa-copy.ts @@ -43,7 +43,7 @@ export function mfaUrgency(enforceAt: number, now: number, blocked: boolean): Te return mfaDaysLeft(enforceAt, now) <= MFA_URGENT_DAYS ? 'soon' : 'quiet' } -/** "Acme requires MFA in 2 days": the title once the deadline is close. */ +/** "Acme requires two-factor authentication in 2 days": the title once the deadline is close. */ export function mfaSoonTitle( teamName: string, enforceAt: number, @@ -52,15 +52,23 @@ export function mfaSoonTitle( ): string { const days = mfaDaysLeft(enforceAt, now) if (days <= 0) { - return t('auto.components.teamMfa.soonTitleNow', '{{value0}} requires MFA now', { - value0: teamName - }) + return t( + 'auto.components.teamMfa.soonTitleNow', + '{{value0}} requires two-factor authentication now', + { + value0: teamName + } + ) } - return t('auto.components.teamMfa.soonTitle', '{{value0}} requires MFA in {{count}} days', { - value0: teamName, - count: days, - defaultValue_one: '{{value0}} requires MFA in {{count}} day' - }) + return t( + 'auto.components.teamMfa.soonTitle', + '{{value0}} requires two-factor authentication in {{count}} days', + { + value0: teamName, + count: days, + defaultValue_one: '{{value0}} requires two-factor authentication in {{count}} day' + } + ) } /** diff --git a/src/renderer/src/components/team-mfa/team-mfa.test.tsx b/src/renderer/src/components/team-mfa/team-mfa.test.tsx index 34bc8f81f65..7a8c323619a 100644 --- a/src/renderer/src/components/team-mfa/team-mfa.test.tsx +++ b/src/renderer/src/components/team-mfa/team-mfa.test.tsx @@ -6,6 +6,7 @@ import type { OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy' import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow' import { TeamMfaBanner } from './TeamMfaBanner' import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen' +import { EnterpriseMfaGroup, mfaChangeError } from './EnterpriseMfaPolicy' import { claimMfaToast, mfaCountdownLabel, @@ -55,7 +56,7 @@ describe('what the member sees', () => { ) }) - it('is nothing with MFA on, an unknown state, or no policy', () => { + it('is nothing with 2FA on, an unknown state, or no policy', () => { expect(teamMfaSurface(policy({ self: 'on' }))).toBe('none') expect(teamMfaSurface(policy({ self: 'unknown' }))).toBe('none') expect(teamMfaSurface(policy({ policy: null, self: 'off' }))).toBe('none') @@ -76,9 +77,11 @@ describe('banner', () => { onSetUp={onSetUp} /> ) - expect(container.textContent).toContain('Acme requires two-factor authentication. 6 days left.') + expect(container.textContent).toContain( + 'Acme requires two-factor authentication from November 24, 2026' + ) expect(container.textContent).toContain('November 24, 2026') - fireEvent.click(getByRole('button', { name: 'Set up MFA' })) + fireEvent.click(getByRole('button', { name: 'Set up two-factor' })) expect(onSetUp).toHaveBeenCalledTimes(1) }) }) @@ -103,7 +106,7 @@ describe('blocked screen', () => { const view = screen() expect(view.container.textContent).toContain('Set up two-factor authentication to use Acme') expect(view.container.textContent).toContain('Your workspaces and files are safe') - fireEvent.click(view.getByRole('button', { name: 'Set up MFA' })) + fireEvent.click(view.getByRole('button', { name: 'Set up two-factor' })) fireEvent.click(view.getByRole('button', { name: 'I’ve set it up' })) fireEvent.click(view.getByRole('button', { name: 'Use my personal account for now' })) expect(view.onSetUp).toHaveBeenCalledTimes(1) @@ -122,8 +125,8 @@ describe('blocked screen', () => { }) }) -describe('Require MFA row', () => { - const manage = { available: true, pendingMembers: 2 } +describe('Require two-factor row', () => { + const manage = { available: true, pendingMembers: 2, ssoHandled: false } const row = (props: Partial = {}) => { const handlers = { onRequire: vi.fn(), @@ -147,18 +150,18 @@ describe('Require MFA row', () => { it('requires MFA with the chosen grace period, 14 days by default', () => { const view = row() - fireEvent.click(view.getByRole('button', { name: 'Require MFA' })) + fireEvent.click(view.getByRole('button', { name: 'Require two-factor' })) expect(view.onRequire).toHaveBeenCalledWith(14) }) it('holds the change back from an admin without MFA, and points them to setup', () => { const view = row({ policy: policy({ policy: null, self: 'off', manage }) }) - fireEvent.click(view.getByRole('button', { name: 'Require MFA' })) + fireEvent.click(view.getByRole('button', { name: 'Require two-factor' })) expect(view.onRequire).not.toHaveBeenCalled() expect(view.container.textContent).toContain( 'Set up two-factor authentication on your own account first' ) - fireEvent.click(view.getByRole('button', { name: 'Set up MFA' })) + fireEvent.click(view.getByRole('button', { name: 'Set up two-factor' })) expect(view.onSetUpOwn).toHaveBeenCalledTimes(1) }) @@ -243,7 +246,7 @@ describe('banner after the deadline', () => { expect(container.textContent).toContain('until you set it up') expect(container.textContent).toContain('Your personal account isn’t affected') expect(container.textContent).not.toContain('days left') - expect(getByRole('button', { name: 'Set up MFA' })).toBeTruthy() + expect(getByRole('button', { name: 'Set up two-factor' })).toBeTruthy() }) }) @@ -259,9 +262,15 @@ describe('escalation', () => { }) it('names the days in the title once it is close', () => { - expect(mfaSoonTitle('Acme', NOW + 2 * DAY, NOW, translate)).toBe('Acme requires MFA in 2 days') - expect(mfaSoonTitle('Acme', NOW + DAY, NOW, translate)).toBe('Acme requires MFA in 1 day') - expect(mfaSoonTitle('Acme', NOW - 1, NOW, translate)).toBe('Acme requires MFA now') + expect(mfaSoonTitle('Acme', NOW + 2 * DAY, NOW, translate)).toBe( + 'Acme requires two-factor authentication in 2 days' + ) + expect(mfaSoonTitle('Acme', NOW + DAY, NOW, translate)).toBe( + 'Acme requires two-factor authentication in 1 day' + ) + expect(mfaSoonTitle('Acme', NOW - 1, NOW, translate)).toBe( + 'Acme requires two-factor authentication now' + ) }) it('marks the sidebar card with its urgency', () => { @@ -315,3 +324,147 @@ describe('one-time toast', () => { expect(claimMfaToast(broken, 'org_1', 100)).toBe(true) }) }) + +describe('single sign-on', () => { + const manage = { available: true, pendingMembers: 0, ssoHandled: true } + + it('shows nothing to a member whose two-factor is handled by their identity provider', () => { + expect(teamMfaSurface(policy({ self: 'delegated' }))).toBe('none') + }) + + it('lets an admin who signs in through SSO change the policy without their own factor', () => { + const onRequire = vi.fn() + const view = render( + {}} + onRemind={() => {}} + onSetUpOwn={() => {}} + /> + ) + expect(view.container.textContent).not.toContain('on your own account first') + fireEvent.click(view.getByRole('button', { name: 'Require two-factor' })) + expect(onRequire).toHaveBeenCalledWith(14) + }) + + it('explains a refused immediate deadline for a single sign-on team', () => { + expect(mfaChangeError('sso-needs-notice', translate)).toContain('at least 7 days out') + expect(mfaChangeError('actor-needs-mfa', translate)).toContain('your own account first') + expect(mfaChangeError('other', translate)).toBe('Couldn’t save the change. Try again.') + }) +}) + +describe('design follow-ups', () => { + const noop = (): void => {} + it('says a member has not signed in yet where there is no Remind button', () => { + const view = render( + + ) + const rows = Array.from(view.container.querySelectorAll('li')).map((row) => row.textContent) + expect(rows[0]).toContain('Pending') + expect(rows[1]).toContain('Hasn’t signed in yet') + expect(rows[1]).not.toContain('Pending') + expect(view.getAllByRole('button', { name: 'Remind' })).toHaveLength(1) + }) + + it('underlines the personal-account link at rest', () => { + const view = render( + + ) + const link = view.getByRole('button', { name: 'Use my personal account for now' }) + expect(link.className).toMatch(/(^| )underline( |$)/) + }) + + it('shows the single sign-on note only for a team whose identity provider handles it', () => { + const group = (ssoHandled: boolean): string => { + const manage = { available: true, pendingMembers: 0, ssoHandled } + const text = + render( + + ).container.textContent ?? '' + cleanup() + return text + } + expect(group(true)).toContain( + 'Members who sign in with single sign-on use your identity provider’s two-factor settings. This requirement applies only to members who sign in another way.' + ) + expect(group(false)).not.toContain('identity provider') + }) +}) + +describe('locked on a team without Enterprise', () => { + const noop = (): void => {} + const locked = (underBanner: boolean) => { + const manage = { available: false, pendingMembers: 0, ssoHandled: false } + return render( + + ) + } + + it('has its own Contact sales when the page has no banner', () => { + expect(locked(false).getAllByRole('button', { name: /Contact sales/ })).toHaveLength(1) + }) + + it('is a plain line with no button under the page banner', () => { + const view = locked(true) + expect(view.queryByRole('button')).toBeNull() + expect(view.container.textContent).toContain('Set a date after which members need') + }) +}) diff --git a/src/renderer/src/components/worktree-creation/clone-access-actions.tsx b/src/renderer/src/components/worktree-creation/clone-access-actions.tsx index 86e82dc152b..a4fc4a59d98 100644 --- a/src/renderer/src/components/worktree-creation/clone-access-actions.tsx +++ b/src/renderer/src/components/worktree-creation/clone-access-actions.tsx @@ -3,6 +3,7 @@ import { Check, Copy, FolderSearch, Github, Loader2 } from 'lucide-react' import type { Translate } from '@/i18n/use-translate' import type { CloneAccessPhase } from './use-clone-access-handoff' +import { ownerRequestLabel } from '@/lib/orca-cloud/owner-request' import { repoOwner } from './vm-build-clone-failure-copy' export type CloneAccessHandlers = { @@ -84,9 +85,7 @@ export function cloneAccessActions( return [ { key: 'copyRequest', - label: access.copied - ? t('worktreeCreation.cloneAccess.copied', 'Copied') - : t('worktreeCreation.cloneAccess.copyRequest', 'Copy request for an owner'), + label: ownerRequestLabel(access.copied === true, t), icon: access.copied ? : , onClick: access.copyRequest }, diff --git a/src/renderer/src/components/worktree-creation/use-clone-access-handoff.test.tsx b/src/renderer/src/components/worktree-creation/use-clone-access-handoff.test.tsx index 694b114effc..924f1898b4f 100644 --- a/src/renderer/src/components/worktree-creation/use-clone-access-handoff.test.tsx +++ b/src/renderer/src/components/worktree-creation/use-clone-access-handoff.test.tsx @@ -18,7 +18,6 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })) import { CLONE_ACCESS_WAIT_MS, - copyOwnerRequest, githubRepoUrlFor, useCloneAccessHandoff } from './use-clone-access-handoff' @@ -121,17 +120,6 @@ describe('CLONE-ACCESS-ERROR: a clone GitHub refused', () => { await waitFor(() => expect(hook.result.current.phase).toBe('missing')) }) - it('the request for an owner carries the install link that preselects the repository', async () => { - mocks.access.mockResolvedValue({ - ...answer('requested'), - installUrl: 'https://github.com/apps/orca/install' - }) - await copyOwnerRequest(REPO, githubRepoUrlFor(REPO)) - const [text] = mocks.clipboard.mock.calls[0] ?? [] - expect(text).toContain(REPO) - expect(text).toContain('https://github.com/apps/orca/install') - }) - it('names only owner/repo as a GitHub repository', () => { expect(githubRepoUrlFor('stablyai/orca')).toBe('https://github.com/stablyai/orca') expect(githubRepoUrlFor('My project')).toBeNull() diff --git a/src/renderer/src/components/worktree-creation/use-clone-access-handoff.ts b/src/renderer/src/components/worktree-creation/use-clone-access-handoff.ts index fa58a208f1a..eb829c86f28 100644 --- a/src/renderer/src/components/worktree-creation/use-clone-access-handoff.ts +++ b/src/renderer/src/components/worktree-creation/use-clone-access-handoff.ts @@ -3,10 +3,9 @@ // (repository preselected), and once access shows up starts the create again on its own. Someone // who can't install (GitHub turns their install into a request for an owner) is told who to ask. import { useCallback, useEffect, useRef, useState } from 'react' -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' import { openOrcaGitHubAppInstall } from '@/lib/orca-cloud/cloud-setup-notice-actions' import { fetchOrcaCloudRepoAccess } from '@/lib/orca-cloud/use-orca-cloud-repo-access' +import { useOwnerRequestCopy } from '@/lib/orca-cloud/owner-request' /** * `checking`: asking GitHub. `missing`: the App doesn't reach it (Give Orca access). `waiting`: @@ -17,8 +16,6 @@ export type CloneAccessPhase = 'checking' | 'missing' | 'waiting' | 'requested' /** Re-check delays while focused after Give Orca access (as REPO-ACCESS-REFRESH backs off). */ export const CLONE_ACCESS_POLL_DELAYS_MS = [4_000, 4_000, 8_000, 15_000, 30_000] as const -/** How long "Copied" stays on the request button. */ -export const COPIED_MS = 1_500 /** Stop waiting after this long: the button comes back. */ export const CLONE_ACCESS_WAIT_MS = 3 * 60_000 @@ -150,36 +147,7 @@ export function useCloneAccessHandoff({ }) }, [repoUrl]) - const [copied, setCopied] = useState(false) - const copiedTimer = useRef(undefined) - useEffect(() => () => window.clearTimeout(copiedTimer.current), []) - const copyRequest = useCallback(() => { - void copyOwnerRequest(repoName, repoUrl).then((ok) => { - if (ok) { - setCopied(true) - window.clearTimeout(copiedTimer.current) - copiedTimer.current = window.setTimeout(() => setCopied(false), COPIED_MS) - } - }) - }, [repoName, repoUrl]) + const { copy: copyRequest, copied } = useOwnerRequestCopy(repoUrl, 'start') return { phase, giveAccess, copyRequest, copied } } - -/** A message for an owner of the repository's org, with the install link that preselects it. */ -export async function copyOwnerRequest(repoName: string, repoUrl: string | null): Promise { - // The repo-access answer carries GitHub's install page with this repository preselected. - const link = repoUrl ? ((await fetchOrcaCloudRepoAccess(repoUrl))?.installUrl ?? null) : null - const message = translate( - 'worktreeCreation.cloneAccess.requestMessage', - 'Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to start workspaces from this repository.', - { repo: repoName } - ) - try { - await window.api.ui.writeClipboardText(link ? `${message}\n${link}` : message) - return true - } catch { - toast.error(translate('worktreeCreation.cloneAccess.requestCopyFailed', 'Couldn’t copy it.')) - return false - } -} diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts index f2bc2b3b428..f9a9578b03d 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts @@ -53,15 +53,19 @@ describe('Orca Cloud settings group', () => { expect(new Set(sections.map((section) => section.group))).toEqual(new Set(['orca-cloud'])) }) - it('adds Enterprise after Team for a team owner or admin only', () => { + it('adds Workspaces then Enterprise after Team for a team owner or admin only', () => { const ids = (patch: Parameters[0]) => buildOrcaCloudSettingsSections(options(patch)).map((section) => section.id) expect(ids({})).not.toContain('cloud-enterprise') expect(ids({ isOrcaTeamAdmin: false })).not.toContain('cloud-enterprise') + // HOME-1: the team's workspace list is an admin management view, never a member page. + expect(ids({})).not.toContain('cloud-workspaces') + expect(ids({ isOrcaTeamAdmin: false })).not.toContain('cloud-workspaces') const admin = ids({ isOrcaTeamAdmin: true }) - expect(admin.slice(0, 4)).toEqual([ + expect(admin.slice(0, 5)).toEqual([ 'cloud-billing', 'cloud-team', + 'cloud-workspaces', 'cloud-enterprise', 'cloud-secrets' ]) @@ -75,6 +79,7 @@ describe('Orca Cloud settings group', () => { .find((entry) => entry.id === id)! .searchEntries.flatMap((entry) => entry.keywords ?? []) expect(keywords('cloud-enterprise')).toContain('audit log') + expect(keywords('cloud-workspaces')).toContain('cloud workspaces') expect(keywords('cloud-api-keys')).not.toContain('audit log') // Never without a control plane, whatever the role. expect(ids({ isOrcaTeamAdmin: true, isOrcaCloudApiAvailable: false })).toEqual([]) diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts index edc2e5fc797..5173894c2e9 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts @@ -10,7 +10,8 @@ import { getOrcaCloudMcpSearchEntries, getOrcaCloudSkillsSearchEntries, getOrcaCloudSecretsSearchEntries, - getOrcaCloudTeamSearchEntries + getOrcaCloudTeamSearchEntries, + getOrcaCloudWorkspacesSearchEntries } from '@/components/settings/orca-cloud/orca-cloud-settings-search' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -22,6 +23,7 @@ import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles' import { BookOpenText, Boxes, + Cloud, Building2, CreditCard, KeySquare, @@ -69,6 +71,17 @@ export function buildOrcaCloudSettingsSections( // Team owners and admins only; members and personal accounts never see the entry. ...(isOrcaTeamAdmin ? [ + { + id: 'cloud-workspaces', + title: t('settings.teamWorkspaces.title', 'Cloud workspaces'), + description: t( + 'settings.teamWorkspaces.description', + 'Every cloud workspace on your team. Only owners and admins can see this page.' + ), + icon: Cloud, + searchEntries: getOrcaCloudWorkspacesSearchEntries(), + group + }, { id: 'cloud-enterprise', title: t('settings.enterprise.title', 'Enterprise'), diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index bf4e4552086..605ac027522 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1371,8 +1371,8 @@ "pendingCount_other": "{{count}} members still need it", "reminded_one": "Reminder sent to {{count}} member.", "reminded_other": "Reminder sent to {{count}} members.", - "soonTitle_one": "{{value0}} requires MFA in {{count}} day", - "soonTitle_other": "{{value0}} requires MFA in {{count}} days" + "soonTitle_one": "{{value0}} requires two-factor authentication in {{count}} day", + "soonTitle_other": "{{value0}} requires two-factor authentication in {{count}} days" }, "teammates": { "daySandboxHours_one": "{{hours}} sandbox hour", @@ -2810,6 +2810,10 @@ "permissionDenied": "Permission denied", "permissionDeniedPublickey": "Permission denied (publickey)" } + }, + "teamWorkspaces": { + "shownOf_one": "{{shown}} of {{count}} workspace", + "shownOf_other": "{{shown}} of {{count}} workspaces" } }, "sidebar": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5b08fa22735..097eb05b984 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1591,7 +1591,34 @@ "cancelScheduledOn": "Plan set to end on {{date}}", "seatsChangedDetail": "Seats changed from {{from}} to {{to}}", "spendCapChanged2": "Changed the monthly spend cap", - "spendCapChangedTo": "Changed the monthly spend cap to {{amount}}" + "spendCapChangedTo": "Changed the monthly spend cap to {{amount}}", + "ssoSetupLink": "Created a single sign-on setup link", + "ssoConfigured": "Set up single sign-on", + "ssoConfiguredNamed": "Set up single sign-on with {{name}}", + "ssoWentLive": "Turned on single sign-on", + "ssoWentLiveNamed": "Turned on single sign-on with {{name}}", + "ssoRemoved": "Removed single sign-on", + "ssoSignInRefused": "Tried to sign in without single sign-on", + "ssoSessionsEnded": "Ended sign-ins made before single sign-on was turned on", + "ssoDomainAdded": "Added an email domain", + "ssoDomainAddedNamed": "Added email domain {{name}}", + "ssoDomainVerified": "Verified an email domain", + "ssoDomainVerifiedNamed": "Verified email domain {{name}}", + "ssoDomainRemoved": "Removed an email domain", + "ssoDomainRemovedNamed": "Removed email domain {{name}}", + "ssoDomainRecordMissing": "Found an email domain’s DNS record missing", + "ssoDomainRecordMissingNamed": "Found the DNS record for {{name}} missing", + "scimEnabled": "Turned on directory sync", + "scimDisabled": "Turned off directory sync", + "scimKeyCreated": "Created a directory sync key", + "scimKeyRevoked": "Revoked a directory sync key", + "scimGroupChanged": "Changed a directory group", + "scimGroupMembershipChanged": "Changed who is in a directory group", + "mfaPolicyEnabled": "Required two-factor authentication", + "mfaPolicyChanged": "Changed the two-factor authentication date", + "mfaPolicyDisabled": "Stopped requiring two-factor authentication", + "mfaReminderResent": "Sent a two-factor authentication reminder", + "mfaMemberReset": "Reset a member’s two-factor authentication" }, "interval": { "month": "monthly", @@ -1675,7 +1702,6 @@ "keywordScim": "scim", "keywordCompliance": "compliance", "description": "Single sign-on, sign-in policies and the audit log for your team.", - "bannerTitle": "Single sign-on and the audit log are part of {{plan}}", "bannerBody": "Talk to us about moving your team to {{plan}}.", "contactUs": "Contact us", "scim": { @@ -1701,7 +1727,37 @@ "keyNote": "The setup page shows the SCIM address and key to enter in your identity provider. Orca never shows or stores the key.", "lastChange": "Last change received", "lastChangeSummary": "{{what}} · {{when}}" - } + }, + "bannerTitleAll": "Single sign-on, two-factor requirements and the audit log are part of {{plan}}" + }, + "teamWorkspaces": { + "search": "Search workspaces", + "searchPlaceholder": "Search name, repository, person, W-number…", + "filterBy": "Filter by person", + "byAnyone": "By anyone", + "byPerson": "By {{name}}", + "filterIn": "Filter by repository", + "inAnyRepo": "In any repository", + "inRepo": "In {{repo}}", + "emptyTeam": "No one on your team has a cloud workspace yet.", + "emptyFiltered": "No workspaces match these filters.", + "colName": "Workspace", + "colNumber": "No.", + "colCreatedBy": "Created by", + "colState": "State", + "colLastActive": "Last active", + "colAccess": "Access", + "colActions": "Actions", + "shared": "Shared", + "shownOf_one": "{{shown}} of {{count}} workspace", + "shownOf_other": "{{shown}} of {{count}} workspaces", + "title": "Cloud workspaces", + "searchDescription": "Every cloud workspace on your team, to open, sleep or archive.", + "keywordCloud": "cloud workspaces", + "keywordTeam": "team workspaces", + "keywordSandboxes": "sandboxes", + "keywordArchive": "archive", + "description": "Every cloud workspace on your team. Only owners and admins can see this page." } }, "menu": { @@ -14190,7 +14246,8 @@ "connect": "Connect GitHub", "title": "GitHub", "disconnectError": "Couldn't disconnect GitHub." - } + }, + "ssoRequired": "Your team now requires single sign-on. Sign in again and choose Sign in with SSO." }, "automations": { "showButtonDescription": "Show the Automations shortcut in the sidebar.", @@ -21038,7 +21095,8 @@ "4b7d2e8f1a": "Connect Orca Mobile to this desktop across cellular or any Wi-Fi.", "9a4c6b2d7e": "Skill sharing", "3d8e5f1b9c": "Share skills behind an unlisted link and install them on any machine you use.", - "c5b3e8a17d": "Sign in to Orca" + "c5b3e8a17d": "Sign in to Orca", + "ssoRequired": "Your team now requires single sign-on. Sign in again and choose Sign in with SSO." }, "NativeChatResumeOutcomeRow": { "openChat": "Open chat", @@ -21369,10 +21427,10 @@ "makeOwnerTitle": "Make {{value0}} an owner?", "members": "Members", "membersList": "Team members and invites", - "mfaOn": "MFA on", - "mfaOff": "MFA off", - "mfaPending": "MFA pending", - "mfaPendingBy": "MFA due {{value0}}", + "mfaOn": "2FA on", + "mfaOff": "2FA off", + "mfaPending": "2FA pending", + "mfaPendingBy": "2FA due {{value0}}", "nextInvoice": "Next invoice (est.)", "nextInvoiceOn": "{{value0}} · {{value1}}", "notAnEmail": "Not an email address", @@ -21454,7 +21512,10 @@ "seatRulesShort": "New members above your paid seats are charged now, prorated. Removed seats stay paid until renewal.", "inviteSeatRule": "Each invite uses a seat once accepted.", "enterpriseRowTitle": "Single sign-on, directory sync and the audit log", - "openEnterpriseSettings": "Open Enterprise settings" + "openEnterpriseSettings": "Open Enterprise settings", + "managedByIdp": "Managed by your identity provider", + "managedByIdpNote": "Managed by your identity provider. Add or remove people and change roles there.", + "mfaSso": "2FA via SSO" }, "manageBilling": "Manage billing", "comparePlans": "Compare plans", @@ -21884,15 +21945,15 @@ "grace7": "In 7 days", "grace14": "In 14 days", "grace30": "In 30 days", - "bannerTitle": "{{value0}} requires two-factor authentication. {{value1}}.", + "bannerTitle": "{{value0}} requires two-factor authentication from {{value1}}", "bannerBody": "Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.", "bannerBlockedTitle": "{{value0}} requires two-factor authentication", - "soonTitleNow": "{{value0}} requires MFA now", - "soonTitle_one": "{{value0}} requires MFA in {{count}} day", - "soonTitle_other": "{{value0}} requires MFA in {{count}} days", - "toast": "{{value0}} requires MFA from {{value1}}.", + "soonTitleNow": "{{value0}} requires two-factor authentication now", + "soonTitle_one": "{{value0}} requires two-factor authentication in {{count}} day", + "soonTitle_other": "{{value0}} requires two-factor authentication in {{count}} days", + "toast": "{{value0}} requires two-factor authentication from {{value1}}.", "bannerBlockedBody": "You can’t use this team’s workspaces until you set it up. Your personal account isn’t affected.", - "setUp": "Set up MFA", + "setUp": "Set up two-factor", "blockedTitle": "Set up two-factor authentication to use {{value0}}", "blockedBody": "{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.", "recheck": "I’ve set it up", @@ -21903,7 +21964,7 @@ "rowEnforced": "Required since {{value0}}. Members without it can’t use this team until they set it up.", "rowScheduled": "Required from {{value0}}. {{value1}}.", "graceLabel": "When to start requiring it", - "require": "Require MFA", + "require": "Require two-factor", "turnOff": "Stop requiring", "ownMfaTitle": "Set up two-factor authentication on your own account first", "ownMfaBody": "Only someone who already has it can change this, so nobody locks the team out.", @@ -21913,14 +21974,25 @@ "pendingCount_one": "{{count}} member still needs it", "pendingCount_other": "{{count}} members still need it", "remindAll": "Remind everyone", - "pendingList": "Members without MFA", + "pendingList": "Members without two-factor authentication", "memberBlocked": "No access", "memberPending": "Pending", "remindOne": "Remind", "reminded_one": "Reminder sent to {{count}} member.", "reminded_other": "Reminder sent to {{count}} members.", "remindedNoEmail": "Reminder recorded, but email delivery is off on this server, so nothing was sent.", - "requiredInline": "Your team requires two-factor authentication. Set it up in Settings, Account to use its cloud workspaces." + "requiredInline": "Your team requires two-factor authentication. Set it up in Settings, Account to use its cloud workspaces.", + "groupTitle": "Two-factor authentication", + "upsellTitle": "Requiring two-factor authentication is part of {{value0}}", + "upsellBody": "Set a date after which members need two-factor authentication to use your team’s workspaces.", + "errorActorNeedsMfa": "Set up two-factor authentication on your own account first.", + "errorNotEntitled": "Your team’s plan doesn’t include this.", + "errorSsoNotice": "Your team uses single sign-on, so pick a date at least 7 days out. Members need time to sign in again.", + "errorRateLimited": "Too many changes at once. Wait a minute and try again.", + "errorForbidden": "Only owners and admins can change this.", + "errorOther": "Couldn’t save the change. Try again.", + "memberNotSignedIn": "Hasn’t signed in yet", + "groupSsoNote": "Members who sign in with single sign-on use your identity provider’s two-factor settings. This requirement applies only to members who sign in another way." } }, "i18n": { @@ -27737,7 +27809,9 @@ }, "header": { "active": "New workspaces start from build #{{number}}", - "noActive": "No build yet: workspaces start from a fresh sandbox" + "noActive": "No build yet: workspaces start from a fresh sandbox", + "depsInstalled": "Dependencies installed with {{manager}}", + "depsSkipped": "Dependencies weren’t installed because {{manager}} install failed. New workspaces start without them." }, "agent": { "hint": "Starts your default agent in a local checkout. It writes the install script and builds until it succeeds.", @@ -28603,16 +28677,19 @@ "diskVeryLowMeaning": "Installs and builds may fail. Delete caches or build output you don’t need.", "diskLowMeaning": "Large dependency installs may run out of space.", "pushRequested": "Orca Cloud can read {{repo}} but can’t push yet. An owner of {{owner}} has been asked to approve the Orca GitHub App.", - "copied": "Copied", - "copyRequest": "Copy request for an owner", "pushCantInstall": "Orca Cloud can read {{repo}} but can’t push to it.", "pushCantInstallMeaning": "Pushing needs the Orca GitHub App on {{owner}}. Ask an owner of {{owner}} to install it.", - "pushNotYet": "Orca Cloud can’t push to {{repo}} yet.", - "pushRequestMessage": "Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to push from workspaces on this repository.", - "pushRequestCopyFailed": "Couldn’t copy it." + "pushNotYet": "Orca Cloud can’t push to {{repo}} yet." }, "toast": { "dismiss": "Dismiss" + }, + "ownerRequest": { + "messagePush": "Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to push from workspaces on this repository.", + "messageStart": "Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to start workspaces from this repository.", + "copyFailed": "Couldn’t copy it.", + "copied": "Copied", + "copy": "Copy request for an owner" } }, "runActions": { @@ -29040,6 +29117,8 @@ "codeExpired": "The code expired · start again", "notChatGpt": "That sign-in wasn’t a ChatGPT account. Use the ChatGPT account you use with Codex.", "brokerBusy": "A ChatGPT sign-in is already running. Finish it, or try again in a minute.", + "deviceAuthDisabled": "Device code sign-in is off for this ChatGPT account", + "deviceAuthDisabledDetail": "Turn it on in ChatGPT’s security settings, then try again. On a work or team account, a ChatGPT admin may need to turn it on.", "rateLimited": "Too many sign-in attempts. Try again in a few minutes.", "invalidToken": "This token isn’t valid · run claude setup-token again", "notEnabled": "Orca can’t use your {{product}} account in cloud workspaces right now.", @@ -29622,12 +29701,8 @@ "askOwnerBody": "Ask an owner of {{owner}} to give Orca access. Orca tries again once they do. The sandbox was deleted.", "body": "The Orca GitHub App on {{owner}} doesn’t include this repository. Give Orca access, and Orca tries again. The sandbox was deleted.", "chooseAnother": "Choose another repository", - "copyRequest": "Copy request for an owner", "waiting": "Waiting for GitHub…", - "giveAccess": "Give Orca access", - "requestMessage": "Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to start workspaces from this repository.", - "requestCopyFailed": "Couldn’t copy it.", - "copied": "Copied" + "giveAccess": "Give Orca access" } }, "renderer": { @@ -29664,5 +29739,44 @@ "copyLinkFailed": "Couldn’t copy the link.", "linkCopied": "Link copied", "signInLinkHint": "Open it in any browser on this computer." + }, + "cloudFollow": { + "role": { + "creator": "Created this workspace", + "follower": "Following" + }, + "state": { + "typing": "Typing now", + "viewing": "Here now" + }, + "stackLabel": "People on this workspace", + "following": "Following", + "unfollow": "Unfollow", + "follow": "Follow", + "unfollowNamed": "Unfollow {{title}}", + "followFailed": "Couldn’t follow this workspace", + "unfollowFailed": "Couldn’t unfollow this workspace" + }, + "sidebarTeam": { + "title": "Team", + "typingIn": "Typing in {{workspace}}", + "viewing": "In {{workspace}}", + "theirWorkspaces": "{{name}}’s workspaces", + "showAll": "Show all {{count}}" + }, + "sidebarFollowing": { + "asleep": "Asleep", + "waking": "Waking", + "archived": "Archived", + "title": "Following", + "hereNow": "{{count}} here now" + }, + "setupScriptImport": { + "ubuntuNote": { + "title": "Written for dnf", + "mixed": "Orca’s sandboxes run Ubuntu, so this script’s dnf install lines now use apt-get. These lines still use dnf. Check them before saving:", + "check": "Orca’s sandboxes run Ubuntu, and these lines still use dnf. Check them before saving:", + "translated": "Orca’s sandboxes run Ubuntu, so this script’s dnf install lines now use apt-get." + } } } diff --git a/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts b/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts index a90d42b945e..b41cf94fdda 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts @@ -121,6 +121,8 @@ describe('a held launch is remembered', () => { expect(readHeldCloudLaunches(ENV)).toMatchObject([ { tabId: TAB, agent: 'claude', prompt: 'fix the test', worktreeId: WT } ]) + // Start, once the account can run it (one that still can't holds again in place). + mocks.coverage = 'covered' releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') await launch expect(readHeldCloudLaunches(ENV)).toEqual([]) @@ -172,6 +174,7 @@ describe('after a restart', () => { prompt: 'fix the test' }) expect(create).not.toHaveBeenCalled() + mocks.coverage = 'covered' releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') await flush() await flush() @@ -230,6 +233,30 @@ describe('after a restart', () => { expect(create).not.toHaveBeenCalled() }) + it("V3-01-DOUBLE-SHELL: released while the account still isn't set up, it holds again in the SAME placeholder", async () => { + mocks.load = 'loading' + remember() + setTabs([TAB]) + const create = vi.fn(async () => created('host-agent')) + resumeHeldCloudLaunches(ENV, { create, waitMs: 5_000 }) + await flush() + await flush() + expect(readCloudAgentHold(cloudTabHoldKey(TAB))?.awaiting).toBe('unread') + // The read lands as "not set up", but this 'proceed' was decided before it (a stale Start). + mocks.load = 'ready' + releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') + await flush() + await flush() + // No second placeholder and no agent: the same tab holds on "Set up once", still remembered. + expect(create).not.toHaveBeenCalled() + expect(readCloudAgentHold(cloudTabHoldKey(TAB))).toMatchObject({ reason: 'notSetUp' }) + expect(readHeldCloudLaunches(ENV).map((record) => record.tabId)).toEqual([TAB]) + // Once it can run, Start launches it exactly once. + mocks.coverage = 'covered' + releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') + await vi.waitFor(() => expect(create).toHaveBeenCalledOnce()) + }) + it('restored and expired: a Renew turns it awaitingStart and starts nothing', async () => { mocks.coverage = 'expired' remember() diff --git a/src/renderer/src/lib/orca-cloud/cloud-push-access-can-install.test.ts b/src/renderer/src/lib/orca-cloud/cloud-push-access-can-install.test.ts new file mode 100644 index 00000000000..c464f0ea6df --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-push-access-can-install.test.ts @@ -0,0 +1,48 @@ +// REPO-CAN-INSTALL (#645): the control plane's `canInstall` decides the push notice's button when it +// knows; the person's gh read is asked only when it can't tell (null) or the Worker is older (absent). +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => { + const state: { answer: unknown; rights: ReturnType } = { + answer: null, + rights: vi.fn(async () => ({ ok: true, value: { admin: true, ownerType: 'Organization' } })) + } + return state +}) + +vi.mock('./use-orca-cloud-repo-access', () => ({ + fetchOrcaCloudRepoAccess: async () => mocks.answer +})) +vi.mock('./orca-cloud-workspace-store', () => ({ + cloudWorkspaceApi: () => ({ gitHubInstallRights: mocks.rights }) +})) + +import { fetchCloudPushAccess } from './cloud-push-access' + +const REPO = 'https://github.com/octocat/Hello-World' + +beforeEach(() => { + mocks.rights.mockClear() +}) + +describe('the push notice reads canInstall first', () => { + it('true: Install, without asking gh', async () => { + mocks.answer = { access: 'public', owner: 'octocat', repo: REPO, canInstall: true } + expect(await fetchCloudPushAccess(REPO)).toBe('install') + expect(mocks.rights).not.toHaveBeenCalled() + }) + + it('false: no Install, even though gh would have said admin', async () => { + mocks.answer = { access: 'missing', owner: 'octocat', repo: REPO, canInstall: false } + expect(await fetchCloudPushAccess(REPO)).toBe('cantInstall') + expect(mocks.rights).not.toHaveBeenCalled() + }) + + it('null (no connected GitHub) or absent (older Worker): falls back to gh', async () => { + mocks.answer = { access: 'public', owner: 'octocat', repo: REPO, canInstall: null } + expect(await fetchCloudPushAccess(REPO)).toBe('install') + mocks.answer = { access: 'public', owner: 'octocat', repo: REPO } + expect(await fetchCloudPushAccess(REPO)).toBe('install') + expect(mocks.rights).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-push-access.ts b/src/renderer/src/lib/orca-cloud/cloud-push-access.ts index 9b8cf994696..01a30d0ae5c 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-push-access.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-push-access.ts @@ -2,13 +2,10 @@ // the Orca GitHub App's access (repo-access) and what the person's own gh login says about installing // it. Install only shows where installing can work; a request already sent offers a copy for an owner; // a public repository someone else owns (octocat/Hello-World) gets a request to copy, no Install. -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' import type { HostedGithubRepoAccessResponse } from '../../../../shared/hosted-sandbox/hosted-github-wire' import type { GitHubInstallRights } from '../../../../shared/hosted-sandbox/cloud-workspace-api' import { cloudWorkspaceApi } from './orca-cloud-workspace-store' import { fetchOrcaCloudRepoAccess } from './use-orca-cloud-repo-access' -import { repoSlug } from './cloud-setup-notice-actions' /** * `install`: Install on {owner}. `requested`: an owner was asked; copy a request for them. @@ -58,27 +55,17 @@ export async function fetchCloudPushAccess( if (access !== 'missing' && access !== 'public') { return cloudPushAccess(access, null) } + // The control plane knows from the person's own GitHub (REPO-CAN-INSTALL, #645). Only when it + // can't tell (null: no connected GitHub, GitHub refused) or is older (absent) is gh asked. + if (answer?.canInstall === true) { + return 'install' + } + if (answer?.canInstall === false) { + return 'cantInstall' + } const rights = await cloudWorkspaceApi() ?.gitHubInstallRights({ repoUrl }) .then((result) => (result.ok ? result.value : null)) .catch(() => null) return cloudPushAccess(access, rights ?? null) } - -/** A message for an owner of the repository's org, with the install page that preselects it. */ -export async function copyOwnerPushRequest(repoUrl: string): Promise { - // The install page the control plane minted for this repository (preselects it), if any. - const link = (await fetchOrcaCloudRepoAccess(repoUrl).catch(() => null))?.installUrl ?? null - const message = translate( - 'orcaCloud.setupNotices.pushRequestMessage', - 'Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to push from workspaces on this repository.', - { repo: repoSlug(repoUrl) } - ) - try { - await window.api.ui.writeClipboardText(link ? `${message}\n${link}` : message) - return true - } catch { - toast.error(translate('orcaCloud.setupNotices.pushRequestCopyFailed', 'Couldn’t copy it.')) - return false - } -} diff --git a/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.ts b/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.ts index 9f1b98788ff..222dff86129 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.ts @@ -116,13 +116,22 @@ export async function settleHeldPlaceholder({ decided?: boolean restored?: boolean }): Promise { - const outcome = await holdCloudAgentLaunch({ - paneKey: cloudTabHoldKey(tabId), - agent, - prompt: args.prompt?.trim() || null, - decided, - restored - }).finally(() => forgetHeldCloudLaunch(tabId)) + const paneKey = cloudTabHoldKey(tabId) + const prompt = args.prompt?.trim() || null + let outcome: 'proceed' | 'cancel' + try { + outcome = await holdCloudAgentLaunch({ paneKey, agent, prompt, decided, restored }) + // V3-01-DOUBLE-SHELL: the agent's create below goes through the account hold too, so a launch + // released while its account still can't run it (a restored 'unread' hold on an account that + // isn't set up) would hold again in a SECOND placeholder. Hold again in this one instead, on the + // same read that decided it (decided: the hold takes the cached reason, so this can't spin). + while (outcome === 'proceed' && (await cloudAgentLaunchDecision(agent)) === 'hold') { + takeCloudAgentHoldStartedByPerson(paneKey) + outcome = await holdCloudAgentLaunch({ paneKey, agent, prompt, decided: true, restored }) + } + } finally { + forgetHeldCloudLaunch(tabId) + } if (outcome === 'cancel') { // NOACCT-MISLABEL: the confirmation answers the person's own Cancel, while the shell is still // there. A hold that ended because its tab or workspace went away (deleted, archived, closed) diff --git a/src/renderer/src/lib/orca-cloud/cloud-workspace-secrets-mode.test.tsx b/src/renderer/src/lib/orca-cloud/cloud-workspace-secrets-mode.test.tsx index 7022a9b3125..a7680450cab 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-workspace-secrets-mode.test.tsx +++ b/src/renderer/src/lib/orca-cloud/cloud-workspace-secrets-mode.test.tsx @@ -30,7 +30,16 @@ function answer(workspace: 'private' | 'shared'): { ok: true; value: CloudSecret secrets: workspace === 'shared' ? [] - : [{ name: 'SENTRY_DSN', kind: 'env', scope: 'personal', hint: null, updatedAt: 0, shadowed: [] }] + : [ + { + name: 'SENTRY_DSN', + kind: 'env', + scope: 'personal', + hint: null, + updatedAt: 0, + shadowed: [] + } + ] } } } @@ -110,7 +119,10 @@ describe('missing-secrets ask', () => { await waitFor(() => expect(result.current.load.status).toBe('ready')) expect(effective).toHaveBeenCalledWith({ repo: REPO, workspace: 'shared' }) const load = result.current.load - expect(load.status === 'ready' && load.data).toMatchObject({ shared: true, missing: ['SENTRY_DSN'] }) + expect(load.status === 'ready' && load.data).toMatchObject({ + shared: true, + missing: ['SENTRY_DSN'] + }) }) it('no runtime environment (the build sheet, before the workspace exists): default view', async () => { diff --git a/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts b/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts index 4ed25f8549d..bc0b8d97c69 100644 --- a/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts +++ b/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts @@ -149,6 +149,7 @@ function seederShellInFront( const active = state.activeTabId const tabs = state.tabsByWorktree[worktreeId] ?? [] return ( + // Belt-and-braces: a tab from another workspace is never this one's newest tab either. state.activeWorktreeId === worktreeId && active !== null && active !== heldTabId && diff --git a/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts b/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts index dcaf8b630d2..1d0685ac0b7 100644 --- a/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts +++ b/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts @@ -187,6 +187,11 @@ describe('PAIRED-HELD-ACTIVE: the held placeholder is in front after a GitHub-on await create() await vi.waitFor(() => expect(tabIds()).toEqual([HELD()])) useAppStore.setState({ activeWorktreeId: 'wt-2', activeTabId: 'web-terminal-elsewhere' }) + // The store's setActiveTab already ignores a tab outside the active workspace, so the end state + // alone can't show the guard: it must not even ask to activate the held tab. + const realSetActiveTab = useAppStore.getState().setActiveTab + const setActiveTab = vi.fn(realSetActiveTab) + useAppStore.setState({ setActiveTab }) // Fake time from here: the settle's recheck after the seeder's shell runs on a timer. vi.useFakeTimers() try { @@ -194,7 +199,9 @@ describe('PAIRED-HELD-ACTIVE: the held placeholder is in front after a GitHub-on await vi.advanceTimersByTimeAsync(600) } finally { vi.useRealTimers() + useAppStore.setState({ setActiveTab: realSetActiveTab }) } + expect(setActiveTab).not.toHaveBeenCalled() expect(useAppStore.getState()).toMatchObject({ activeWorktreeId: 'wt-2', activeTabId: 'web-terminal-elsewhere' diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-needs-check-wire.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-needs-check-wire.test.ts new file mode 100644 index 00000000000..4ce793381be --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-needs-check-wire.test.ts @@ -0,0 +1,45 @@ +// RS-2: a sign-in whose auth check failed ("needs check") reaches the desktop as `expired` plus +// `needsCheck: true`. Every desktop, old ones included, then shows the Renew strip; an unknown state would +// have read as 'none' ("isn't set up"). The wire never sends a state an old desktop could read as active. +import { describe, expect, it } from 'vitest' +import { + AgentCredentialsResponseSchema, + isUsableAgentCredential +} from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { cloudAgentHoldReason } from './cloud-agent-launch-hold' + +const wire = { + claude: { state: 'expired', needsCheck: true, label: 'ada@example.com' }, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } +} + +describe('RS-2 "needs check" on the wire', () => { + it('parses as expired (needsCheck tolerated), never usable', () => { + const parsed = AgentCredentialsResponseSchema.parse(wire) + expect(parsed.claude.state).toBe('expired') + expect(isUsableAgentCredential(parsed.claude.state)).toBe(false) + }) + + it('maps to the Renew strip (accountExpired), like any expired sign-in', () => { + const parsed = AgentCredentialsResponseSchema.parse(wire) + expect( + cloudAgentHoldReason('claude', { + load: { + kind: 'ready', + status: { + credentials: parsed, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } + } + }, + keyKinds: { claude: null, codex: null } + }) + ).toBe('accountExpired') + }) + + it('a raw unknown state (what an old server could never send) still never reads as active', () => { + const parsed = AgentCredentialsResponseSchema.parse({ ...wire, claude: { state: 'suspect' } }) + expect(parsed.claude.state).toBe('none') + expect(isUsableAgentCredential(parsed.claude.state)).toBe(false) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/owner-request.test.ts b/src/renderer/src/lib/orca-cloud/owner-request.test.ts new file mode 100644 index 00000000000..00adc81b9aa --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/owner-request.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ access: vi.fn(), clipboard: vi.fn() })) +vi.mock('./use-orca-cloud-repo-access', () => ({ fetchOrcaCloudRepoAccess: mocks.access })) +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) + +import { translate } from '@/i18n/i18n' +import { copyOwnerRequest, ownerRequestLabel } from './owner-request' + +const REPO_URL = 'https://github.com/stablyai/orca-plugins' + +describe('Copy request for an owner (REQUEST-COPY-SHARE)', () => { + beforeEach(() => { + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: { api: { ui: { writeClipboardText: mocks.clipboard } } } + }) + }) + afterEach(() => { + mocks.access.mockReset() + mocks.clipboard.mockReset() + }) + + it('names the repository and what the access is for, with the install link that preselects it', async () => { + mocks.access.mockResolvedValue({ + access: 'requested', + installUrl: 'https://github.com/apps/orca/install' + }) + await expect(copyOwnerRequest(REPO_URL, 'start')).resolves.toBe(true) + const [start] = mocks.clipboard.mock.calls[0] ?? [] + expect(start).toContain('stablyai/orca-plugins') + expect(start).toContain('start workspaces from this repository') + expect(start).toContain('https://github.com/apps/orca/install') + await copyOwnerRequest(REPO_URL, 'push') + const [push] = mocks.clipboard.mock.calls[1] ?? [] + expect(push).toContain('push from workspaces on this repository') + }) + + it('without an install link the message still goes; a clipboard failure says so', async () => { + mocks.access.mockResolvedValue(null) + await copyOwnerRequest(REPO_URL, 'push') + expect(mocks.clipboard.mock.calls[0]?.[0]).not.toContain('\n') + mocks.clipboard.mockRejectedValueOnce(new Error('no clipboard')) + await expect(copyOwnerRequest(REPO_URL, 'push')).resolves.toBe(false) + }) + + it('one label for both surfaces, Copied for a moment after', () => { + expect(ownerRequestLabel(false, translate)).toBe('Copy request for an owner') + expect(ownerRequestLabel(true, translate)).toBe('Copied') + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/owner-request.ts b/src/renderer/src/lib/orca-cloud/owner-request.ts new file mode 100644 index 00000000000..71d4757a6d9 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/owner-request.ts @@ -0,0 +1,78 @@ +// "Copy request for an owner" (REQUEST-COPY-SHARE): someone who can't install the Orca GitHub App +// copies a message for an owner of the repository's org, with the install page that preselects +// the repository. Shared by the refused-clone card (CLONE-ACCESS-ERROR) and the push notice. +import { useCallback, useEffect, useRef, useState } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { fetchOrcaCloudRepoAccess } from './use-orca-cloud-repo-access' + +/** What the access is for: starting workspaces from the repository, or pushing from them. */ +export type OwnerRequestPurpose = 'start' | 'push' + +/** How long "Copied" stays on the button. */ +export const OWNER_REQUEST_COPIED_MS = 1_500 + +function repoSlugOf(repoUrl: string): string { + return repoUrl.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '') +} + +function requestMessage(repo: string, purpose: OwnerRequestPurpose): string { + return purpose === 'push' + ? translate( + 'orcaCloud.ownerRequest.messagePush', + 'Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to push from workspaces on this repository.', + { repo } + ) + : translate( + 'orcaCloud.ownerRequest.messageStart', + 'Could you give the Orca GitHub App access to {{repo}}? Orca Cloud needs it to start workspaces from this repository.', + { repo } + ) +} + +/** Copies the request with the install link from the repo-access answer, when it has one. */ +export async function copyOwnerRequest( + repoUrl: string, + purpose: OwnerRequestPurpose +): Promise { + const link = (await fetchOrcaCloudRepoAccess(repoUrl).catch(() => null))?.installUrl ?? null + const message = requestMessage(repoSlugOf(repoUrl), purpose) + try { + await window.api.ui.writeClipboardText(link ? `${message}\n${link}` : message) + return true + } catch { + toast.error(translate('orcaCloud.ownerRequest.copyFailed', 'Couldn’t copy it.')) + return false + } +} + +/** The button's label: "Copied" for a moment after a copy. */ +export function ownerRequestLabel(copied: boolean, t: Translate): string { + return copied + ? t('orcaCloud.ownerRequest.copied', 'Copied') + : t('orcaCloud.ownerRequest.copy', 'Copy request for an owner') +} + +/** Copy the request, and say "Copied" on the button for OWNER_REQUEST_COPIED_MS. */ +export function useOwnerRequestCopy( + repoUrl: string | null, + purpose: OwnerRequestPurpose +): { copy: () => void; copied: boolean } { + const [copied, setCopied] = useState(false) + const timer = useRef | undefined>(undefined) + useEffect(() => () => clearTimeout(timer.current), []) + const copy = useCallback(() => { + if (!repoUrl) { + return + } + void copyOwnerRequest(repoUrl, purpose).then((ok) => { + if (ok) { + setCopied(true) + clearTimeout(timer.current) + timer.current = setTimeout(() => setCopied(false), OWNER_REQUEST_COPIED_MS) + } + }) + }, [purpose, repoUrl]) + return { copy, copied } +} diff --git a/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts b/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts index ce3b5aea16d..96351b742b9 100644 --- a/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts +++ b/src/renderer/src/runtime/repo-hooks/setup-script-prompt.ts @@ -1,7 +1,10 @@ import { formatRunActionsForTrust } from '../../../../shared/orca-yaml-run-actions' import { getDefaultRepoHookSettings } from '../../../../shared/constants' import { resolveHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy' -import type { SetupScriptImportCandidate } from '../../../../shared/workspace-setup/setup-script-imports' +import type { + SetupScriptImportCandidate, + UbuntuNote +} from '../../../../shared/workspace-setup/setup-script-imports' import type { RepoHookSettings } from '../../../../shared/orca-yaml-hook-types' import type { Repo } from '../../../../shared/repo-types' import type { HookCheckResult } from '@/runtime/repo-hooks/runtime-hooks-client' @@ -215,6 +218,8 @@ export type DetectedSetupPreviewContent = { skippedFields: readonly string[] /** Imported run actions, as the text the Run button will execute. */ runActions: string | null + /** PARITY-DNF: Amazon Linux install lines translated to apt-get, and what to check. */ + ubuntuNote: UbuntuNote | null } // Mirrors what buildImportedHookSettings saves; only package-manager guesses are editable before saving. @@ -228,7 +233,8 @@ export function getDetectedSetupPreviewContent( archive: candidate.archive ?? null, editable, skippedFields: candidate.unsupportedFields ?? [], - runActions: candidate.run?.length ? formatRunActionsForTrust(candidate.run) : null + runActions: candidate.run?.length ? formatRunActionsForTrust(candidate.run) : null, + ubuntuNote: candidate.ubuntuNote ?? null } } diff --git a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts index 041324fcfe2..1babcb8272a 100644 --- a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts +++ b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts @@ -11,6 +11,7 @@ export function createWebCloudWorkspacesApi(): PreloadApi['cloudWorkspaces'] { list: () => Promise.resolve(NOT_CONFIGURED), get: () => Promise.resolve(NOT_CONFIGURED), patch: () => Promise.resolve(NOT_CONFIGURED), + follow: () => Promise.resolve(NOT_CONFIGURED), resolveLink: () => Promise.resolve(NOT_CONFIGURED), openGrant: () => Promise.resolve(NOT_CONFIGURED), readSnapshot: () => Promise.resolve(NOT_CONFIGURED), diff --git a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts index 70332cbe133..72db5a57fb3 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts @@ -62,7 +62,11 @@ export const CloudWorkspaceSchema = z.object({ // Older control planes omit it. fromRoutine: z.boolean().optional().catch(undefined), // The routine that started it, for routine runs (shown as "Routine · "). - routineName: z.string().max(200).nullable().optional().catch(undefined) + routineName: z.string().max(200).nullable().optional().catch(undefined), + // Who follows it (oldest first) and whether the caller does (PARITY-FOLLOW). Older control planes + // omit them. + followers: z.array(Id).max(500).optional().catch(undefined), + following: z.boolean().optional().catch(undefined) }) export type CloudWorkspace = z.infer @@ -84,6 +88,12 @@ export const CloudWorkspaceListResponseSchema = z.object({ routineRuns: CloudWorkspaceRoutineRunsSchema.optional().catch(undefined) }) export const CloudWorkspaceResponseSchema = z.object({ workspace: CloudWorkspaceSchema }) +/** PUT/DELETE /v1/team/workspaces/:id/follow (PARITY-FOLLOW). */ +export const CloudWorkspaceFollowSchema = z.object({ + following: z.boolean(), + followers: z.array(Id) +}) +export type CloudWorkspaceFollow = z.infer export const CloudWorkspacePresenceResponseSchema = z.object({ presence: z.array(CloudWorkspacePresenceSchema) }) diff --git a/src/shared/hosted-sandbox/hosted-environment-api.ts b/src/shared/hosted-sandbox/hosted-environment-api.ts index 3201445906d..1d0868ef7de 100644 --- a/src/shared/hosted-sandbox/hosted-environment-api.ts +++ b/src/shared/hosted-sandbox/hosted-environment-api.ts @@ -1,5 +1,6 @@ // `window.api.orcaCloudEnvironments`: org environments (shared install script + snapshot builds) in // Orca Cloud. Main holds the token and talks to the control plane; the renderer sees only views. +import type { UbuntuNote } from '../workspace-setup/setup-script-imports' import type { HostedEnvironmentBuildView, HostedEnvironmentCreateInput, @@ -70,6 +71,8 @@ export type OrcaCloudRepoSetupImports = { installScript?: string /** Human labels of where the suggestions came from, e.g. "Conductor (.conductor/settings.toml)". */ sources: string[] + /** PARITY-DNF: the install script came from Amazon Linux (dnf); what was translated and what to check. */ + ubuntuNote?: UbuntuNote } export type OrcaCloudEnvironmentsApi = { diff --git a/src/shared/hosted-sandbox/hosted-environment-wire.ts b/src/shared/hosted-sandbox/hosted-environment-wire.ts index d5f246faac8..260e20e1c73 100644 --- a/src/shared/hosted-sandbox/hosted-environment-wire.ts +++ b/src/shared/hosted-sandbox/hosted-environment-wire.ts @@ -108,6 +108,13 @@ export const HostedEnvironmentBuildViewSchema = z.looseObject({ repos: z.array(HostedEnvironmentBuildRepoSchema).max(HOSTED_ENVIRONMENT_MAX_REPOS), diskUsedBytes: z.number().nonnegative().nullable(), diskTotalBytes: z.number().nonnegative().nullable(), + // AUTO-ENV-DEPS-LABEL: an automatic environment's lockfile install. Older control planes omit it, + // and an unknown manager or outcome from a newer one reads as none rather than failing the list. + autoInstall: z + .object({ manager: z.enum(['pnpm', 'yarn', 'npm']), outcome: z.enum(['installed', 'skipped']) }) + .nullable() + .optional() + .catch(null), logBytes: z.number().int().nonnegative(), logTruncated: z.boolean() }) diff --git a/src/shared/orca-account-mfa.ts b/src/shared/orca-account-mfa.ts index 2274d9784eb..8952e0b0c9d 100644 --- a/src/shared/orca-account-mfa.ts +++ b/src/shared/orca-account-mfa.ts @@ -17,7 +17,8 @@ export type OrcaAccountMfaResult = * for a member the provider said nothing about. 'pending': a team policy requires it by the * member's `mfaDeadline` and they have not set it up. */ -export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending' +// 'sso': the team's single sign-on is live and the member signs in through it. +export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending' | 'sso' /** The two-factor fields of a team member (OrcaOrgMember in orca-profiles.ts). */ export type OrcaOrgMemberMfaFields = { diff --git a/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts b/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts index abc6f1c01e5..a9d0c844145 100644 --- a/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts +++ b/src/shared/orca-cloud-agents/orca-cloud-agents-wire.ts @@ -115,6 +115,8 @@ export const ORCA_CLOUD_AGENTS_ERROR_CODES = [ 'broker_in_progress', 'rate_limited', 'broker_unavailable', + /** RS-3: the ChatGPT account has device-code sign-in turned off (the Codex broker can't print a code). */ + 'device_auth_disabled', 'no_golden_image', 'timeout', 'unavailable', diff --git a/src/shared/orca-org-roster.ts b/src/shared/orca-org-roster.ts new file mode 100644 index 00000000000..87638c568be --- /dev/null +++ b/src/shared/orca-org-roster.ts @@ -0,0 +1,11 @@ +// A team's roster as auth answers it (GET /v1/desktop/orgs/:orgId/members). +import type { OrcaOrgMember, OrcaOrgPendingInvite, OrcaOrgRole } from './orca-profiles' + +export type OrcaOrgMembersRoster = { + members: OrcaOrgMember[] + pendingInvites: OrcaOrgPendingInvite[] + viewerRole: OrcaOrgRole + canManageMembers: boolean + /** Directory sync is on: the team's identity provider owns membership and roles. */ + directoryManaged?: boolean +} diff --git a/src/shared/orca-profile-reconnect-reason.ts b/src/shared/orca-profile-reconnect-reason.ts new file mode 100644 index 00000000000..f6b4ddc51e0 --- /dev/null +++ b/src/shared/orca-profile-reconnect-reason.ts @@ -0,0 +1,6 @@ +/** + * With auth state `reconnect-required`: why auth ended the sign-in, when it is worth telling the + * person apart from "your session expired". + * `sso-required`: their team turned on single sign-on after they signed in. + */ +export type OrcaProfileReconnectReason = 'sso-required' diff --git a/src/shared/orca-profiles.ts b/src/shared/orca-profiles.ts index 1f8d3daf904..8242230dbc0 100644 --- a/src/shared/orca-profiles.ts +++ b/src/shared/orca-profiles.ts @@ -1,3 +1,5 @@ +import type { OrcaProfileReconnectReason } from './orca-profile-reconnect-reason' +import type { OrcaOrgMembersRoster } from './orca-org-roster' import type { OrcaOrgMemberMfaFields } from './orca-account-mfa' import './constants' import { ORCA_BROWSER_PARTITION } from './browser/browser-session-partition' @@ -56,6 +58,7 @@ export type OrcaProfileAuthStatus = { capabilities?: OrcaCloudCapabilities credentialError?: string setupMessage?: string + reconnectReason?: OrcaProfileReconnectReason } export type OrcaProfileSummary = { @@ -268,12 +271,7 @@ export type OrcaOrgPendingInvite = { createdAt: number } -export type OrcaOrgMembersRoster = { - members: OrcaOrgMember[] - pendingInvites: OrcaOrgPendingInvite[] - viewerRole: OrcaOrgRole - canManageMembers: boolean -} +export type { OrcaOrgMembersRoster } export type OrcaProfileOrgMembersListArgs = { orgId: string diff --git a/src/shared/orca-team-mfa-policy.ts b/src/shared/orca-team-mfa-policy.ts index 7e86956b4ed..8beff972a7b 100644 --- a/src/shared/orca-team-mfa-policy.ts +++ b/src/shared/orca-team-mfa-policy.ts @@ -11,8 +11,10 @@ export type OrcaTeamMfaGrace = (typeof ORCA_TEAM_MFA_GRACE_CHOICES)[number] * - `pending`: the team requires MFA, they have none, the deadline has not passed. * - `blocked`: the deadline passed; the team's workspaces and settings are closed to them. * - `unknown`: the identity provider did not say; never treated as blocked. + * - `delegated`: the team's single sign-on is live and they sign in through it, so their second + * factor is their identity provider's and the policy does not apply to them. */ -export type OrcaTeamMfaSelfState = 'on' | 'off' | 'pending' | 'blocked' | 'unknown' +export type OrcaTeamMfaSelfState = 'on' | 'off' | 'pending' | 'blocked' | 'unknown' | 'delegated' export type OrcaTeamMfaPolicy = { /** Null when the team has no policy in force. */ @@ -27,6 +29,8 @@ export type OrcaTeamMfaPolicy = { pendingMembers: number /** A stored policy the plan no longer covers: it enforces nothing. */ inactiveEnforceAt?: number + /** The team's single sign-on is live: members who use it are handled by their provider. */ + ssoHandled: boolean } } @@ -49,6 +53,8 @@ export type OrcaTeamMfaPolicySetResult = | { status: 'actor-needs-mfa' } /** The team's plan does not include MFA enforcement. */ | { status: 'not-entitled' } + /** The team uses single sign-on, so "now" is refused: members need time to sign in again. */ + | { status: 'sso-needs-notice' } | Unavailable export type OrcaTeamMfaPendingResult = diff --git a/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts b/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts index 12cfa49fbd3..24f4ec9df49 100644 --- a/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts +++ b/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts @@ -209,9 +209,7 @@ describe('pruneLocalTerminalScrollbackBuffers', () => { const buffer = result.terminalLayoutsByTabId['remote-tab'].buffersByLeafId?.['pane:1'] ?? '' expect(buffer.length).toBeGreaterThan(0) - expect(getUtf8ByteLength(buffer)).toBeLessThanOrEqual( - TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT - ) + expect(getUtf8ByteLength(buffer)).toBeLessThanOrEqual(TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT) expect(buffer).toHaveLength(TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT / 2) }) diff --git a/src/shared/workspace-setup/setup-script-dnf.test.ts b/src/shared/workspace-setup/setup-script-dnf.test.ts new file mode 100644 index 00000000000..133f69d28c4 --- /dev/null +++ b/src/shared/workspace-setup/setup-script-dnf.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' +import { dnfLinesIn, referencedScriptPaths, translateDnfInstalls } from './setup-script-dnf' +import { inspectConductorConfig } from './setup-script-import-conductor' + +const APT = 'sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y' + +describe('PARITY-DNF: Amazon Linux install lines in an imported setup', () => { + it('rewrites a plain dnf install where every package has a clear Ubuntu name', () => { + const { setup, translated, unresolved } = translateDnfInstalls( + 'sudo dnf install -y gcc-c++ make python3-devel openssl-devel libffi-devel\npnpm install' + ) + expect(setup).toBe(`${APT} g++ make python3-dev libssl-dev libffi-dev\npnpm install`) + expect(translated).toBe(1) + expect(unresolved).toEqual([]) + }) + + it('translates each piece of a chained line and keeps the rest as written', () => { + const { setup } = translateDnfInstalls( + 'yum -y install git jq && corepack enable && pnpm install --frozen-lockfile' + ) + expect(setup).toBe(`${APT} git jq && corepack enable && pnpm install --frozen-lockfile`) + }) + + it('leaves an unknown or ambiguous package as written and lists it (never guesses)', () => { + const line = 'sudo dnf install -y postgresql15 libpq-devel nodejs20' + const { setup, translated, unresolved } = translateDnfInstalls(`${line}\nbun install`) + expect(setup).toBe(`${line}\nbun install`) + expect(translated).toBe(0) + expect(unresolved).toEqual([line]) + }) + + it('leaves non-install dnf commands, variables and unknown options for the person', () => { + const { setup, unresolved } = translateDnfInstalls( + 'sudo dnf groupinstall -y "Development Tools"\nsudo dnf install -y $PACKAGES\ndnf install --enablerepo=epel jq\nsudo dnf update -y' + ) + expect(setup).toContain('groupinstall') + expect(unresolved).toHaveLength(4) + }) + + it('leaves a setup with no dnf untouched', () => { + expect(translateDnfInstalls('sudo apt-get install -y jq\nnpm ci')).toEqual({ + setup: 'sudo apt-get install -y jq\nnpm ci', + translated: 0, + unresolved: [] + }) + }) + + it('finds the script files a setup runs, and their dnf lines (read only)', () => { + expect(referencedScriptPaths('./conductor-setup.sh')).toEqual(['conductor-setup.sh']) + expect(referencedScriptPaths('bash scripts/setup.sh && pnpm dev')).toEqual(['scripts/setup.sh']) + expect(referencedScriptPaths('bash /etc/setup.sh; sh ../up.sh')).toEqual([]) + expect( + dnfLinesIn( + '#!/bin/bash\n# dnf install comment\nset -e\nsudo dnf install -y postgresql15\ncurl -fsSL x | bash\nyum install -y jq' + ) + ).toEqual(['sudo dnf install -y postgresql15', 'yum install -y jq']) + }) +}) + +describe('PARITY-DNF in the Conductor importer', () => { + function reader(files: Record) { + return async (path: string): Promise => files[path] ?? null + } + + it('translates an inline setup and says so', async () => { + const candidate = await inspectConductorConfig( + reader({ + '.conductor/settings.toml': + '[scripts]\nsetup = """\nsudo dnf install -y gcc-c++ make\npnpm install\n"""\n' + }) + ) + expect(candidate?.setup).toContain(`${APT} g++ make`) + expect(candidate?.ubuntuNote).toEqual({ translated: 1, checkLines: [] }) + }) + + it('a script file that uses dnf is listed, never changed', async () => { + const script = '#!/bin/bash\nset -e\nsudo dnf install -y postgresql15\nnpm ci\n' + const candidate = await inspectConductorConfig( + reader({ + 'conductor.json': JSON.stringify({ scripts: { setup: './conductor-setup.sh' } }), + 'conductor-setup.sh': script + }) + ) + expect(candidate?.setup).toBe('./conductor-setup.sh') + expect(candidate?.ubuntuNote).toEqual({ + translated: 0, + checkLines: ['conductor-setup.sh: sudo dnf install -y postgresql15'] + }) + }) + + it('no dnf anywhere: no note', async () => { + const candidate = await inspectConductorConfig( + reader({ '.conductor/settings.toml': '[scripts]\nsetup = "pnpm install"\n' }) + ) + expect(candidate?.setup).toBe('pnpm install') + expect(candidate?.ubuntuNote).toBeUndefined() + }) +}) diff --git a/src/shared/workspace-setup/setup-script-dnf.ts b/src/shared/workspace-setup/setup-script-dnf.ts new file mode 100644 index 00000000000..368e136d80d --- /dev/null +++ b/src/shared/workspace-setup/setup-script-dnf.ts @@ -0,0 +1,166 @@ +// PARITY-DNF: Conductor's cloud runs Amazon Linux (dnf/yum); Orca's sandboxes run Ubuntu (apt). +// An imported setup's own `dnf install` / `yum install` lines become apt-get when every package has +// a clear Ubuntu name; anything else stays as written and is listed for the person to check. A +// script file the setup runs is only read (never changed or run) to say which of its lines use dnf. + +/** Amazon Linux / Fedora package → its Ubuntu name, only where the mapping is unambiguous. */ +const DNF_TO_APT: Readonly> = { + 'bzip2-devel': 'libbz2-dev', + 'ca-certificates': 'ca-certificates', + curl: 'curl', + 'curl-minimal': 'curl', + findutils: 'findutils', + gcc: 'gcc', + 'gcc-c++': 'g++', + git: 'git', + 'git-lfs': 'git-lfs', + gzip: 'gzip', + htop: 'htop', + jq: 'jq', + less: 'less', + 'libffi-devel': 'libffi-dev', + 'libpq-devel': 'libpq-dev', + 'libxml2-devel': 'libxml2-dev', + 'libxslt-devel': 'libxslt1-dev', + 'libyaml-devel': 'libyaml-dev', + make: 'make', + 'ncurses-devel': 'libncurses-dev', + 'openssh-clients': 'openssh-client', + 'openssl-devel': 'libssl-dev', + patch: 'patch', + 'postgresql-devel': 'libpq-dev', + 'procps-ng': 'procps', + python3: 'python3', + 'python3-devel': 'python3-dev', + 'python3-pip': 'python3-pip', + 'readline-devel': 'libreadline-dev', + ripgrep: 'ripgrep', + rsync: 'rsync', + 'sqlite-devel': 'libsqlite3-dev', + tar: 'tar', + tmux: 'tmux', + unzip: 'unzip', + 'util-linux': 'util-linux', + vim: 'vim', + 'vim-enhanced': 'vim', + wget: 'wget', + which: 'debianutils', + 'xz-devel': 'liblzma-dev', + zip: 'zip', + 'zlib-devel': 'zlib1g-dev' +} + +/** dnf/yum options that only change how it asks or reports; apt-get's own flags replace them. */ +const DROPPED_OPTION = + /^(-y|--assumeyes|-q|--quiet|--nogpgcheck|--allowerasing|--skip-broken|--best|--setopt=\S+)$/ + +const INSTALL_COMMAND = /^(sudo\s+)?(dnf|yum|microdnf)\s+(.*)$/ +/** A line that calls dnf or yum at all (for scanning script files). */ +const USES_DNF = /(^|[\s;&|(`])(sudo\s+)?(dnf|yum|microdnf|amazon-linux-extras)\s/ + +export type DnfTranslation = { + /** The setup with every translatable install line rewritten. */ + setup: string + /** Lines rewritten to apt-get. */ + translated: number + /** dnf/yum commands left as written: an unknown or ambiguous package, or not an install. */ + unresolved: string[] +} + +/** One `cmd1 && cmd2; cmd3` piece; null when it is not a dnf/yum command at all. */ +function translateCommand(command: string): { apt: string } | { unresolved: true } | null { + const match = INSTALL_COMMAND.exec(command.trim()) + if (!match) { + return null + } + const words = (match[3] ?? '').split(/\s+/).filter(Boolean) + const verb = words.findIndex((word) => !word.startsWith('-')) + // Quotes, variables or globs could name anything: leave them for the person. + if (verb === -1 || words[verb] !== 'install' || /["'$`*?{}]/.test(command)) { + return { unresolved: true } + } + const packages: string[] = [] + for (const [index, word] of words.entries()) { + if (index === verb) { + continue + } + if (word.startsWith('-')) { + if (!DROPPED_OPTION.test(word)) { + return { unresolved: true } + } + continue + } + const apt = DNF_TO_APT[word] + if (!apt) { + return { unresolved: true } + } + if (!packages.includes(apt)) { + packages.push(apt) + } + } + if (packages.length === 0) { + return { unresolved: true } + } + return { + apt: `sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y ${packages.join(' ')}` + } +} + +/** Rewrites the setup's own dnf/yum install lines to apt-get where every package maps clearly. */ +export function translateDnfInstalls(setup: string): DnfTranslation { + let translated = 0 + const unresolved: string[] = [] + const lines = setup.split('\n').map((line) => { + // Keep the separators: `a && b; c` pieces are translated one by one. + const pieces = line.split(/(\s*(?:&&|\|\||;)\s*)/) + let changed = false + const out = pieces.map((piece, index) => { + if (index % 2 === 1) { + return piece + } + const result = translateCommand(piece) + if (!result) { + return piece + } + if ('unresolved' in result) { + unresolved.push(piece.trim()) + return piece + } + changed = true + const lead = /^\s*/.exec(piece)?.[0] ?? '' + return `${lead}${result.apt}` + }) + if (changed) { + translated += 1 + } + return out.join('') + }) + return { setup: lines.join('\n'), translated, unresolved } +} + +/** Script files a setup command runs by path (`./setup.sh`, `bash scripts/setup.sh`). */ +export function referencedScriptPaths(setup: string): string[] { + const paths = new Set() + for (const word of setup.split(/[\s;&|()]+/)) { + const path = word.replace(/^\.\//, '') + if (/\.(sh|bash)$/.test(word) && !word.startsWith('/') && !path.includes('..') && path) { + paths.add(path) + } + } + return [...paths] +} + +/** A script file's lines that call dnf or yum (trimmed, first `limit`). */ +export function dnfLinesIn(content: string, limit = 5): string[] { + const found: string[] = [] + for (const line of content.split('\n')) { + const text = line.trim() + if (text && !text.startsWith('#') && USES_DNF.test(text)) { + found.push(text) + if (found.length >= limit) { + break + } + } + } + return found +} diff --git a/src/shared/workspace-setup/setup-script-import-conductor.ts b/src/shared/workspace-setup/setup-script-import-conductor.ts index 8078ad63990..e9cd2fa2cfb 100644 --- a/src/shared/workspace-setup/setup-script-import-conductor.ts +++ b/src/shared/workspace-setup/setup-script-import-conductor.ts @@ -7,6 +7,7 @@ import { parseTomlObject } from './setup-script-import-parsers' import { parseOrcaRunScripts, type OrcaRunScripts } from '../orca-yaml-run-actions' +import { dnfLinesIn, referencedScriptPaths, translateDnfInstalls } from './setup-script-dnf' const CONDUCTOR_SETTINGS_PATH = '.conductor/settings.toml' const CONDUCTOR_LOCAL_SETTINGS_PATH = '.conductor/settings.local.toml' @@ -29,7 +30,32 @@ export async function inspectConductorConfig( const candidate = settings || localSettings ? buildSettingsTomlCandidate(settings, localSettings) : null // Conductor ignores conductor.json once settings.toml exists, so mirror that precedence. - return candidate ?? (settings ? null : inspectLegacyConductorJson(readFile)) + const found = candidate ?? (settings ? null : await inspectLegacyConductorJson(readFile)) + return found ? withUbuntuSetup(found, readFile) : null +} + +/** + * PARITY-DNF: Conductor's cloud runs Amazon Linux, Orca's sandboxes Ubuntu. The setup's own dnf/yum + * install lines become apt-get where every package maps clearly; a script file it runs is only read + * (never changed or run) to list the lines that still use dnf. + */ +async function withUbuntuSetup( + candidate: SetupScriptImportCandidate, + readFile: SetupScriptImportFileRead +): Promise { + const { setup, translated, unresolved } = translateDnfInstalls(candidate.setup) + const fileLines: string[] = [] + for (const path of referencedScriptPaths(candidate.setup)) { + const content = await readFile(path) + if (content) { + fileLines.push(...dnfLinesIn(content).map((line) => `${path}: ${line}`)) + } + } + const checkLines = [...unresolved, ...fileLines] + if (translated === 0 && checkLines.length === 0) { + return candidate + } + return { ...candidate, setup, ubuntuNote: { translated, checkLines } } } function buildSettingsTomlCandidate( diff --git a/src/shared/workspace-setup/setup-script-imports.ts b/src/shared/workspace-setup/setup-script-imports.ts index 1271f083dc1..0e6b917ba5c 100644 --- a/src/shared/workspace-setup/setup-script-imports.ts +++ b/src/shared/workspace-setup/setup-script-imports.ts @@ -32,8 +32,15 @@ export type SetupScriptImportCandidate = { runMode?: OrcaRunMode autoRunAfterSetup?: boolean | string unsupportedFields?: string[] + /** + * PARITY-DNF: the setup came from an Amazon Linux tool (Conductor). `translated` dnf/yum install + * lines now use apt-get; `checkLines` still use dnf or yum (in the setup or a script it runs). + */ + ubuntuNote?: UbuntuNote } +export type UbuntuNote = { translated: number; checkLines: string[] } + export type SetupScriptImportFileRead = (relativePath: string) => Promise export type SetupScriptImportFileExists = (relativePath: string) => Promise