From dc5f8d98fde0c4f3d8ffb48eda442d8909a2e4f6 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:51:47 -0800 Subject: [PATCH 1/5] fix(cloud): agents orcad starts directly get the live session env (RA-1) orcad's process env and its cached login-shell capture are frozen at sandbox start, while the control plane updates the session env live (tmpfs file). A Claude account signed in after the workspace started reached shells (profile hook) but not chat agents or PTYs orcad spawns itself: no CLAUDE_CODE_OAUTH_TOKEN placeholder, ORCA_SESSION_ENV_NAMES empty, Not logged in. Structured agent launches and the PTY daemon now lay the current file over their env (same name rules as the hook) and drop names the live env removed; a launch's explicit deletions still win. --- .../pty-subprocess/spawn-environment.ts | 5 +- .../structured-agent-shell-environment.ts | 15 ++-- .../structured-session-child-env.ts | 6 +- .../runtime/secrets/cloud-session-env.test.ts | 67 +++++++++++++++ src/main/runtime/secrets/cloud-session-env.ts | 82 +++++++++++++++++++ 5 files changed, 168 insertions(+), 7 deletions(-) create mode 100644 src/main/runtime/secrets/cloud-session-env.test.ts create mode 100644 src/main/runtime/secrets/cloud-session-env.ts diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index 5da6296bc0c..dfac14dc57f 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -6,6 +6,7 @@ import { dropInheritedOrcaFishHistory } from '../../pty/history/fish-history-ses import { removeAppImageRuntimeEnv } from '../../pty/shell-startup/appimage-terminal-env' import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromium-session-bus-env' import { stripInheritedBuildModeEnv } from '../../pty/shell-startup/build-mode-env' +import { withCloudSessionEnv } from '../../runtime/secrets/cloud-session-env' import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner-env' import { dropIncoherentCondaActivationEnv } from '../../pty/shell-startup/conda-activation-env' import { stripLegacyTerminalShimEnv } from '../../pty/shell-startup/legacy-terminal-shim-dir' @@ -181,7 +182,9 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record = { - ...mergeGitConfigEnvProtocol(inheritedEnv, opts.env), + // Orca Cloud: the daemon's env is from orcad's start; lay the live session env over it, under the + // launch's own values and before its requested deletions (an account strip must win). + ...mergeGitConfigEnvProtocol(withCloudSessionEnv(inheritedEnv), opts.env), TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'Orca', diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index e050391680d..d17fb610b27 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -1,4 +1,5 @@ import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' +import { withCloudSessionEnv } from '../../secrets/cloud-session-env' import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { @@ -203,12 +204,16 @@ export function createStructuredAgentEnvironmentResolvers( if (!injected && sources.prewarm !== false) { void hostShellEnvironment().catch(() => {}) } + // Orca Cloud: the shell capture is from orcad's start; the live session env (secrets, account + // placeholders) is reread for every launch. const resolveBase = async (cachedOnly = false): Promise> => - structuredAgentBaseEnvironment({ - shellEnv: await shellEnvironment(cachedOnly), - policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null), - processEnv: sources.processEnvironment - }) + withCloudSessionEnv( + structuredAgentBaseEnvironment({ + shellEnv: await shellEnvironment(cachedOnly), + policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null), + processEnv: sources.processEnvironment + }) + ) return { refreshAfterMissingProgram: injected ? async () => {} diff --git a/src/main/runtime/agent-session/environment/structured-session-child-env.ts b/src/main/runtime/agent-session/environment/structured-session-child-env.ts index 37bec85bfcf..46f88dc094d 100644 --- a/src/main/runtime/agent-session/environment/structured-session-child-env.ts +++ b/src/main/runtime/agent-session/environment/structured-session-child-env.ts @@ -4,6 +4,7 @@ * Empty remote selectors to mask the parent env; explicit flags still work, and login profiles can re-export selectors. * Omit pane identity: hooks and mobile status assume a live PTY leaf. Resolve worker identity at every spawn, including recovery and clear. */ +import { cloudSessionEnv } from '../../secrets/cloud-session-env' import { getAppEnvironment, hasAppEnvironment } from '../../../../shared/app-environment' import { ORCA_AGENT_SESSION_ID_ENV, @@ -40,9 +41,12 @@ export function sealStructuredSessionChild(input: { : input.env const identity = childIdentity(input.sessionId, paired) const named = new Set([...Object.keys(identity.commandEnv), ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]) + // Orca Cloud: orcad's own env still holds values the live session env has since dropped (a revoked + // account placeholder, a deleted secret); the child must not inherit them. + const dropped = (cloudSessionEnv(process.env)?.unset ?? []).filter((key) => !(key in paired)) return { env: { ...identity.env, [ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]: input.spawnToken }, - envToDelete: input.inheritedEnvToDelete.filter((key) => !named.has(key)), + envToDelete: [...input.inheritedEnvToDelete, ...dropped].filter((key) => !named.has(key)), commandEnv: identity.commandEnv } } diff --git a/src/main/runtime/secrets/cloud-session-env.test.ts b/src/main/runtime/secrets/cloud-session-env.test.ts new file mode 100644 index 00000000000..95a1a71f185 --- /dev/null +++ b/src/main/runtime/secrets/cloud-session-env.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { cloudSessionEnv, withCloudSessionEnv } from './cloud-session-env' + +const CLOUD = { ORCA_IS_CLOUD: '1', ORCA_SANDBOX_ID: 'sbx_1' } +const b64 = (value: string): string => Buffer.from(value).toString('base64') +const file = + (lines: string[]) => + (path: string): string => { + expect(path).toBe('/dev/shm/orca-env-1000/session.env') + return lines.join('\n') + } + +describe('cloud session env overlay (RA-1)', () => { + it('lays the live file over an env captured before a credential was added', () => { + const started = { PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' } + const env = withCloudSessionEnv(started, { + processEnv: CLOUD, + uid: 1000, + read: file([ + `CLAUDE_CODE_OAUTH_TOKEN=${b64('orca-ph-claude-account-sbx_1')}`, + `NPM_TOKEN=${b64('n')}` + ]) + }) + expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe('orca-ph-claude-account-sbx_1') + expect(env.NPM_TOKEN).toBe('n') + expect(env.ORCA_SESSION_ENV_NAMES).toBe('CLAUDE_CODE_OAUTH_TOKEN NPM_TOKEN') + expect(env.PATH).toBe('/usr/bin') + }) + + it('removes names an older session env set that the live one dropped (a revoked account)', () => { + const started = { + CLAUDE_CODE_OAUTH_TOKEN: 'orca-ph-claude-account-sbx_1', + ORCA_SESSION_ENV_NAMES: 'CLAUDE_CODE_OAUTH_TOKEN' + } + const current = cloudSessionEnv(started, { processEnv: CLOUD, uid: 1000, read: file([]) }) + expect(current?.unset).toEqual(['CLAUDE_CODE_OAUTH_TOKEN']) + expect(withCloudSessionEnv(started, { processEnv: CLOUD, uid: 1000, read: file([]) })).toEqual({ + ORCA_SESSION_ENV_NAMES: '' + }) + }) + + it('skips the names the shell hook skips', () => { + const env = withCloudSessionEnv( + { PATH: '/usr/bin' }, + { + processEnv: CLOUD, + uid: 1000, + read: file([ + `PATH=${b64('/evil')}`, + `ORCA_X=${b64('x')}`, + `LD_PRELOAD=${b64('x')}`, + `bad-name=${b64('x')}` + ]) + } + ) + expect(env).toEqual({ PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' }) + }) + + it('changes nothing off the cloud or before the file exists', () => { + const env = { A: '1' } + expect(withCloudSessionEnv(env, { processEnv: {}, uid: 1000, read: file([]) })).toBe(env) + const missing = (): string => { + throw new Error('ENOENT') + } + expect(withCloudSessionEnv(env, { processEnv: CLOUD, uid: 1000, read: missing })).toBe(env) + }) +}) diff --git a/src/main/runtime/secrets/cloud-session-env.ts b/src/main/runtime/secrets/cloud-session-env.ts new file mode 100644 index 00000000000..63dee08b54b --- /dev/null +++ b/src/main/runtime/secrets/cloud-session-env.ts @@ -0,0 +1,82 @@ +// Orca Cloud: the session env (secrets, agent placeholders such as CLAUDE_CODE_OAUTH_TOKEN) lives in a +// tmpfs file that the control plane rewrites live (orca-sandbox-env). Shells pick it up through the +// profile hook, but orcad's own process env and its cached login-shell capture are frozen at start, so +// anything orcad spawns directly (chat agents, PTYs launched without a shell) must lay the current file +// over the env it built. Same rules as the hook (image/vm/orca-session-env.sh). +import { readFileSync } from 'node:fs' +import { isCloudWorkspaceOrcad, sessionEnvFilePath } from './session-env-names' + +const NAME = /^[A-Z_][A-Z0-9_]*$/ + +function reserved(name: string): boolean { + return ( + name.startsWith('ORCA_') || + name === 'PATH' || + name === 'HOME' || + name.startsWith('LD_') || + name.startsWith('DYLD_') + ) +} + +export type CloudSessionEnv = { + /** Current values, plus ORCA_SESSION_ENV_NAMES listing them. */ + set: Record + /** Names `base` got from an older session env that the current one no longer has. */ + unset: string[] +} + +export type CloudSessionEnvOptions = { + processEnv?: NodeJS.ProcessEnv + uid?: number + read?: (path: string) => string +} + +/** Null outside a cloud workspace's orcad, or before the file exists (then nothing changes, as in the hook). */ +export function cloudSessionEnv( + base: Readonly>, + options: CloudSessionEnvOptions = {} +): CloudSessionEnv | null { + if (!isCloudWorkspaceOrcad(options.processEnv ?? process.env)) { + return null + } + const uid = options.uid ?? process.getuid?.() + if (uid === undefined) { + return null + } + let text: string + try { + text = (options.read ?? ((path: string) => readFileSync(path, 'utf8')))(sessionEnvFilePath(uid)) + } catch { + return null + } + const set: Record = {} + for (const line of text.split('\n')) { + const at = line.indexOf('=') + const name = at > 0 ? line.slice(0, at) : '' + if (!NAME.test(name) || reserved(name)) { + continue + } + set[name] = Buffer.from(line.slice(at + 1), 'base64').toString('utf8') + } + const names = Object.keys(set) + const unset = (base.ORCA_SESSION_ENV_NAMES ?? '') + .split(/\s+/) + .filter((name) => name && !(name in set)) + return { set: { ...set, ORCA_SESSION_ENV_NAMES: names.join(' ') }, unset } +} + +/** `env` with the current cloud session env laid over it and dropped names removed. */ +export function withCloudSessionEnv>( + env: T, + options: CloudSessionEnvOptions = {} +): T { + const current = cloudSessionEnv(env, options) + if (!current) { + return env + } + const next: Record = { ...env } + for (const name of current.unset) { + delete next[name] + } + return Object.assign(next, current.set) as T +} From 9942c75b864dd746ee1137389b0a8801f4f1a1d7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:56:51 -0800 Subject: [PATCH 2/5] fix(cloud): overloads instead of a generic cast for withCloudSessionEnv --- .../runtime/secrets/cloud-session-env.test.ts | 2 +- src/main/runtime/secrets/cloud-session-env.ts | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/secrets/cloud-session-env.test.ts b/src/main/runtime/secrets/cloud-session-env.test.ts index 95a1a71f185..40524b4723a 100644 --- a/src/main/runtime/secrets/cloud-session-env.test.ts +++ b/src/main/runtime/secrets/cloud-session-env.test.ts @@ -12,7 +12,7 @@ const file = describe('cloud session env overlay (RA-1)', () => { it('lays the live file over an env captured before a credential was added', () => { - const started = { PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' } + const started: Record = { PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' } const env = withCloudSessionEnv(started, { processEnv: CLOUD, uid: 1000, diff --git a/src/main/runtime/secrets/cloud-session-env.ts b/src/main/runtime/secrets/cloud-session-env.ts index 63dee08b54b..40c1f31120a 100644 --- a/src/main/runtime/secrets/cloud-session-env.ts +++ b/src/main/runtime/secrets/cloud-session-env.ts @@ -66,10 +66,18 @@ export function cloudSessionEnv( } /** `env` with the current cloud session env laid over it and dropped names removed. */ -export function withCloudSessionEnv>( - env: T, +export function withCloudSessionEnv( + env: Record, + options?: CloudSessionEnvOptions +): Record +export function withCloudSessionEnv( + env: NodeJS.ProcessEnv, + options?: CloudSessionEnvOptions +): NodeJS.ProcessEnv +export function withCloudSessionEnv( + env: Record, options: CloudSessionEnvOptions = {} -): T { +): Record { const current = cloudSessionEnv(env, options) if (!current) { return env @@ -78,5 +86,5 @@ export function withCloudSessionEnv for (const name of current.unset) { delete next[name] } - return Object.assign(next, current.set) as T + return Object.assign(next, current.set) } From c2e250bcfeba8e1b88080e2f9b52705efc3c3564 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:02:49 -0800 Subject: [PATCH 3/5] fix(cloud-start-gate): a sandbox going to sleep or an abandoned create no longer refuses a start The team and per-member concurrency counts (billing's checkStart input and the guardrail backstop) counted 'suspending' rows, which drain for up to 5 min after someone chose Sleep and read as asleep everywhere, and 'creating' rows whose Worker was cut off (until the cron released them). Both could refuse a start that the user's view says fits. The global capacity cap still counts them. --- cloud/apps/sandbox-control/src/guardrails.ts | 21 ++++------ cloud/apps/sandbox-control/src/index.ts | 2 +- cloud/apps/sandbox-control/src/lifecycle.ts | 15 ++++--- cloud/apps/sandbox-control/src/reconcile.ts | 6 +-- cloud/apps/sandbox-control/src/store.ts | 42 +++++++++++++++---- .../src/workspace-lifecycle.ts | 6 +-- .../sandbox-control/test/create-speed.test.ts | 20 +++++++++ 7 files changed, 78 insertions(+), 34 deletions(-) diff --git a/cloud/apps/sandbox-control/src/guardrails.ts b/cloud/apps/sandbox-control/src/guardrails.ts index 53af0905f2e..fb6235ae609 100644 --- a/cloud/apps/sandbox-control/src/guardrails.ts +++ b/cloud/apps/sandbox-control/src/guardrails.ts @@ -1,7 +1,7 @@ // Cost guardrails in front of every start (create, resume, rollover): the operator kill switch, a // global running cap, a per-account concurrency backstop (billing enforces the plan limit too) and a // per-account create rate limit. All are control-plane local, so a billing outage cannot lift them. -import { ACTIVE_STATUSES } from './store' +import { ACTIVE_STATUSES, countActiveSandboxes } from './store' export type GuardrailConfig = { /** Static kill switch from the deploy config (`SANDBOX_CREATES_DISABLED=true`). */ @@ -53,21 +53,16 @@ export function setKillSwitch(db: D1Database, on: boolean, now: number): Promise return setControlState(db, KILL_SWITCH, on ? 'on' : 'off', now) } -async function countActive(db: D1Database, accountId?: string): Promise { +/** Every VM-holding sandbox, all accounts: the global capacity guardrail. */ +export async function countAllActive(db: D1Database): Promise { const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') const row = await db - .prepare( - `SELECT COUNT(*) AS n FROM sandboxes WHERE status IN (${placeholders}) ${accountId ? 'AND account_id = ?' : ''}` - ) - .bind(...ACTIVE_STATUSES, ...(accountId ? [accountId] : [])) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE status IN (${placeholders})`) + .bind(...ACTIVE_STATUSES) .first<{ n: number }>() return row?.n ?? 0 } -export function countAllActive(db: D1Database): Promise { - return countActive(db) -} - /** Kill switch + global running cap; checked before billing is asked anything. */ export async function assertStartsOpen(db: D1Database, config: GuardrailConfig): Promise { if (await killSwitchOn(db, config)) { @@ -84,10 +79,12 @@ export async function assertAccountCapacity( db: D1Database, config: GuardrailConfig, accountId: string, - limits: { seats?: number; maxConcurrentSandboxes?: number } = {} + limits: { seats?: number; maxConcurrentSandboxes?: number } = {}, + now: number = Date.now() ): Promise { const cap = limits.maxConcurrentSandboxes ?? config.maxActivePerSeat * Math.max(1, Math.floor(limits.seats ?? 1)) - if ((await countActive(db, accountId)) >= cap) { + // The same count billing was given: a sandbox going to sleep or an abandoned create doesn't refuse a start. + if ((await countActiveSandboxes(db, accountId, now)) >= cap) { throw new GuardrailError('concurrency_limit') } } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 7bcf03e0ea0..45cb59d83b2 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -1555,7 +1555,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) { const [{ idleSleepMinutes, ...status }, hints] = await Promise.all([ workspaceStatus(life, row, workspaceConfig(env, deps)), - wakeHintsAware ? wakeHints(life.db, row) : null + wakeHintsAware ? wakeHints(life.db, row, life.now()) : null ]) return json({ sandbox: view(row), diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 5e8b1ef0fdd..9d3d7e4cf46 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -310,8 +310,8 @@ export function guardrails(deps: LifecycleDeps): GuardrailConfig { export async function requireStart(deps: LifecycleDeps, accountId: string, userId: string, machineSize: MachineSize) { const [, runningSandboxes, runningSandboxesForUser] = await Promise.all([ assertStartsOpen(deps.db, guardrails(deps)), - countActiveSandboxes(deps.db, accountId), - countActiveSandboxesForUser(deps.db, accountId, userId) + countActiveSandboxes(deps.db, accountId, deps.now()), + countActiveSandboxesForUser(deps.db, accountId, userId, deps.now()) ]) const decision = await deps.entitlements.checkStart({ accountId, @@ -326,10 +326,13 @@ export async function requireStart(deps: LifecycleDeps, accountId: string, userI if (!decision.allow) { throw new LifecycleError('entitlement_denied', decision.reason ?? 'denied') } - await assertAccountCapacity(deps.db, guardrails(deps), accountId, { - seats: decision.seats, - maxConcurrentSandboxes: decision.maxConcurrentSandboxes - }) + await assertAccountCapacity( + deps.db, + guardrails(deps), + accountId, + { seats: decision.seats, maxConcurrentSandboxes: decision.maxConcurrentSandboxes }, + deps.now() + ) } function orcadEndpoint(state: ProviderSandboxState): string | null { diff --git a/cloud/apps/sandbox-control/src/reconcile.ts b/cloud/apps/sandbox-control/src/reconcile.ts index ad8ae23caf2..af1d4935220 100644 --- a/cloud/apps/sandbox-control/src/reconcile.ts +++ b/cloud/apps/sandbox-control/src/reconcile.ts @@ -15,7 +15,7 @@ import { import { guardrails } from './lifecycle' import { killSwitchOn } from './guardrails' import { drainAll, housekeeping, openHold, type HousekeepingSummary } from './retention' -import { listByStatus, transition, type SandboxRow } from './store' +import { CREATE_ABANDONED_MS, listByStatus, transition, type SandboxRow } from './store' import { flushUsage, queueUsage } from './usage' import { expiredArchives } from './workspace-lifecycle' import { ACTIVITY_CHECK_BEFORE_LAPSE_MS, ACTIVITY_RENEW_MS, decideFromActivity, readVmActivity } from './vm-activity' @@ -24,9 +24,9 @@ const STUCK_MS = 15 * 60_000 /** * A create's longest legitimate run is a 30 s pooled try, a VM create and the 120 s start command. * Past this its Worker was cut off (the desktop gave up or disconnected): fail it and free the VM - * instead of leaving a billed 'creating' row for the full STUCK_MS. + * instead of leaving a billed 'creating' row for the full STUCK_MS. The start gate stops counting it then too. */ -export const CREATE_STUCK_MS = 5 * 60_000 +export const CREATE_STUCK_MS = CREATE_ABANDONED_MS /** The desktop rolls over at the deadline; the cron steps in only if it did not (provider cap is +10 min). */ const FORCED_STOP_GRACE_MS = 5 * 60_000 diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index 4b4584964f5..14ec858457b 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -89,9 +89,26 @@ export const NO_SESSION: SessionFields & Pick = { usage_settled_at: null } -/** Counted against the plan's concurrency limit. */ +/** Holding (or about to hold) a VM: capacity guardrails, retention and drains count these. */ export const ACTIVE_STATUSES: readonly SandboxStatus[] = ['creating', 'running', 'resuming', 'suspending'] +/** A create this old never finished: its Worker was cut off, and the cron releases it (reconcile.ts). */ +export const CREATE_ABANDONED_MS = 5 * 60_000 + +/** + * Counted against the plan's concurrency limits (team and per member). Not a sandbox going to sleep + * ('suspending' drains for up to 5 min after someone chose Sleep, and reads as asleep everywhere), and + * not a create abandoned more than CREATE_ABANDONED_MS ago: neither may refuse the next start. + */ +const START_GATE_STATUSES: readonly SandboxStatus[] = ['creating', 'running', 'resuming'] + +function startGateFilter(now: number): { sql: string; binds: (string | number)[] } { + return { + sql: `status IN (${START_GATE_STATUSES.map(() => '?').join(', ')}) AND NOT (status = 'creating' AND updated_at < ?)`, + binds: [...START_GATE_STATUSES, now - CREATE_ABANDONED_MS] + } +} + export async function insertSandbox( db: D1Database, row: Pick< @@ -155,20 +172,27 @@ export async function listAccountSandboxes(db: D1Database, accountId: string): P return results } -export async function countActiveSandboxes(db: D1Database, accountId: string): Promise { - const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') +/** Sandboxes that count against the account's concurrency limit at `now` (see START_GATE_STATUSES). */ +export async function countActiveSandboxes(db: D1Database, accountId: string, now: number): Promise { + const gate = startGateFilter(now) const row = await db - .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND status IN (${placeholders})`) - .bind(accountId, ...ACTIVE_STATUSES) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND ${gate.sql}`) + .bind(accountId, ...gate.binds) .first<{ n: number }>() return row?.n ?? 0 } -export async function countActiveSandboxesForUser(db: D1Database, accountId: string, userId: string): Promise { - const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') +/** The same, for one member's per-member limit. */ +export async function countActiveSandboxesForUser( + db: D1Database, + accountId: string, + userId: string, + now: number +): Promise { + const gate = startGateFilter(now) const row = await db - .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND user_id = ? AND status IN (${placeholders})`) - .bind(accountId, userId, ...ACTIVE_STATUSES) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND user_id = ? AND ${gate.sql}`) + .bind(accountId, userId, ...gate.binds) .first<{ n: number }>() return row?.n ?? 0 } diff --git a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts index e16b826a85c..838731a3154 100644 --- a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts +++ b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts @@ -418,10 +418,10 @@ export type WakeHints = { running: { owner: number; account: number } } -export async function wakeHints(db: D1Database, row: SandboxRow): Promise { +export async function wakeHints(db: D1Database, row: SandboxRow, now: number = Date.now()): Promise { const [owner, account] = await Promise.all([ - countActiveSandboxesForUser(db, row.account_id, row.user_id), - countActiveSandboxes(db, row.account_id) + countActiveSandboxesForUser(db, row.account_id, row.user_id, now), + countActiveSandboxes(db, row.account_id, now) ]) return { lastUserSleepAt: row.user_slept_at ?? null, running: { owner, account } } } diff --git a/cloud/apps/sandbox-control/test/create-speed.test.ts b/cloud/apps/sandbox-control/test/create-speed.test.ts index 82f0dc8dd4b..cb19f543a76 100644 --- a/cloud/apps/sandbox-control/test/create-speed.test.ts +++ b/cloud/apps/sandbox-control/test/create-speed.test.ts @@ -117,6 +117,26 @@ describe('repo-backed create', () => { expect(starts).toBe(1) }) + it('the start gate counts neither a sandbox going to sleep nor an abandoned create', async () => { + const h = await createHarness() + const ids: string[] = [] + // Billing's cap is 3 here (the guardrail backstop: 3 per seat, 1 seat). + for (const ws of ['ws-a', 'ws-b', 'ws-c']) { + ids.push(String((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: ws, machineSize: 'standard' } })).body.sandbox.id)) + } + // One is draining toward sleep; one is a create whose Worker was cut off 6 minutes ago. + h.raw.prepare(`UPDATE sandboxes SET status = 'suspending' WHERE id = ?`).run(ids[0]!) + h.raw.prepare(`UPDATE sandboxes SET status = 'creating', updated_at = ? WHERE id = ?`).run(h.now() - 6 * MIN, ids[1]!) + h.billing.requests.length = 0 + expect((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-d', machineSize: 'standard' } })).status).toBe(200) + expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 1, runningSandboxesForUser: 1 }) + // A create still in flight (recent) does count. + h.raw.prepare(`UPDATE sandboxes SET updated_at = ? WHERE id = ?`).run(h.now() - MIN, ids[1]!) + h.billing.requests.length = 0 + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-e', machineSize: 'standard' } }) + expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 3, runningSandboxesForUser: 3 }) + }) + it('a create whose Worker was cut off is failed after 5 minutes, not 15', async () => { const h = await createHarness() const { body } = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' } }) From beca0159198f931f3fa7af9b8a7664bf2087dd75 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:03:49 -0800 Subject: [PATCH 4/5] fix(cloud): read the cloud session env without sync fs (watched in-memory copy) --- .../pty-subprocess/spawn-environment.ts | 10 +- .../structured-agent-shell-environment.ts | 18 +-- .../structured-session-child-env.ts | 6 +- src/main/runtime/secrets/cloud-session-env.ts | 121 +++++++++++++----- 4 files changed, 110 insertions(+), 45 deletions(-) diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index dfac14dc57f..465058e8cd4 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -6,7 +6,10 @@ import { dropInheritedOrcaFishHistory } from '../../pty/history/fish-history-ses import { removeAppImageRuntimeEnv } from '../../pty/shell-startup/appimage-terminal-env' import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromium-session-bus-env' import { stripInheritedBuildModeEnv } from '../../pty/shell-startup/build-mode-env' -import { withCloudSessionEnv } from '../../runtime/secrets/cloud-session-env' +import { + applyCloudSessionEnv, + cachedCloudSessionEnv +} from '../../runtime/secrets/cloud-session-env' import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner-env' import { dropIncoherentCondaActivationEnv } from '../../pty/shell-startup/conda-activation-env' import { stripLegacyTerminalShimEnv } from '../../pty/shell-startup/legacy-terminal-shim-dir' @@ -184,7 +187,10 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record = { // Orca Cloud: the daemon's env is from orcad's start; lay the live session env over it, under the // launch's own values and before its requested deletions (an account strip must win). - ...mergeGitConfigEnvProtocol(withCloudSessionEnv(inheritedEnv), opts.env), + ...mergeGitConfigEnvProtocol( + applyCloudSessionEnv(inheritedEnv, cachedCloudSessionEnv(inheritedEnv)), + opts.env + ), TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'Orca', diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index d17fb610b27..ca8e06459a4 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -1,5 +1,5 @@ import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' -import { withCloudSessionEnv } from '../../secrets/cloud-session-env' +import { applyCloudSessionEnv, liveCloudSessionEnv } from '../../secrets/cloud-session-env' import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { @@ -206,14 +206,14 @@ export function createStructuredAgentEnvironmentResolvers( } // Orca Cloud: the shell capture is from orcad's start; the live session env (secrets, account // placeholders) is reread for every launch. - const resolveBase = async (cachedOnly = false): Promise> => - withCloudSessionEnv( - structuredAgentBaseEnvironment({ - shellEnv: await shellEnvironment(cachedOnly), - policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null), - processEnv: sources.processEnvironment - }) - ) + const resolveBase = async (cachedOnly = false): Promise> => { + const base = structuredAgentBaseEnvironment({ + shellEnv: await shellEnvironment(cachedOnly), + policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null), + processEnv: sources.processEnvironment + }) + return applyCloudSessionEnv(base, await liveCloudSessionEnv(base)) + } return { refreshAfterMissingProgram: injected ? async () => {} diff --git a/src/main/runtime/agent-session/environment/structured-session-child-env.ts b/src/main/runtime/agent-session/environment/structured-session-child-env.ts index 46f88dc094d..99b1410abef 100644 --- a/src/main/runtime/agent-session/environment/structured-session-child-env.ts +++ b/src/main/runtime/agent-session/environment/structured-session-child-env.ts @@ -4,7 +4,7 @@ * Empty remote selectors to mask the parent env; explicit flags still work, and login profiles can re-export selectors. * Omit pane identity: hooks and mobile status assume a live PTY leaf. Resolve worker identity at every spawn, including recovery and clear. */ -import { cloudSessionEnv } from '../../secrets/cloud-session-env' +import { cachedCloudSessionEnv } from '../../secrets/cloud-session-env' import { getAppEnvironment, hasAppEnvironment } from '../../../../shared/app-environment' import { ORCA_AGENT_SESSION_ID_ENV, @@ -43,7 +43,9 @@ export function sealStructuredSessionChild(input: { const named = new Set([...Object.keys(identity.commandEnv), ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]) // Orca Cloud: orcad's own env still holds values the live session env has since dropped (a revoked // account placeholder, a deleted secret); the child must not inherit them. - const dropped = (cloudSessionEnv(process.env)?.unset ?? []).filter((key) => !(key in paired)) + const dropped = (cachedCloudSessionEnv(process.env)?.unset ?? []).filter( + (key) => !(key in paired) + ) return { env: { ...identity.env, [ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]: input.spawnToken }, envToDelete: [...input.inheritedEnvToDelete, ...dropped].filter((key) => !named.has(key)), diff --git a/src/main/runtime/secrets/cloud-session-env.ts b/src/main/runtime/secrets/cloud-session-env.ts index 40c1f31120a..b7bea9eace9 100644 --- a/src/main/runtime/secrets/cloud-session-env.ts +++ b/src/main/runtime/secrets/cloud-session-env.ts @@ -3,7 +3,12 @@ // profile hook, but orcad's own process env and its cached login-shell capture are frozen at start, so // anything orcad spawns directly (chat agents, PTYs launched without a shell) must lay the current file // over the env it built. Same rules as the hook (image/vm/orca-session-env.sh). -import { readFileSync } from 'node:fs' +// +// The file is kept in memory and reread when its directory changes (a watch, no polling), so spawn paths +// read it without blocking on disk. +import { watch, type FSWatcher } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { dirname } from 'node:path' import { isCloudWorkspaceOrcad, sessionEnvFilePath } from './session-env-names' const NAME = /^[A-Z_][A-Z0-9_]*$/ @@ -25,28 +30,12 @@ export type CloudSessionEnv = { unset: string[] } -export type CloudSessionEnvOptions = { - processEnv?: NodeJS.ProcessEnv - uid?: number - read?: (path: string) => string -} - -/** Null outside a cloud workspace's orcad, or before the file exists (then nothing changes, as in the hook). */ -export function cloudSessionEnv( +/** The overlay for `base` from the file's text; null text (no file) changes nothing, as in the hook. */ +export function cloudSessionEnvFromText( base: Readonly>, - options: CloudSessionEnvOptions = {} + text: string | null ): CloudSessionEnv | null { - if (!isCloudWorkspaceOrcad(options.processEnv ?? process.env)) { - return null - } - const uid = options.uid ?? process.getuid?.() - if (uid === undefined) { - return null - } - let text: string - try { - text = (options.read ?? ((path: string) => readFileSync(path, 'utf8')))(sessionEnvFilePath(uid)) - } catch { + if (text === null) { return null } const set: Record = {} @@ -65,26 +54,94 @@ export function cloudSessionEnv( return { set: { ...set, ORCA_SESSION_ENV_NAMES: names.join(' ') }, unset } } -/** `env` with the current cloud session env laid over it and dropped names removed. */ -export function withCloudSessionEnv( +/** `env` with `overlay` laid over it and dropped names removed. */ +export function applyCloudSessionEnv( env: Record, - options?: CloudSessionEnvOptions + overlay: CloudSessionEnv | null ): Record -export function withCloudSessionEnv( +export function applyCloudSessionEnv( env: NodeJS.ProcessEnv, - options?: CloudSessionEnvOptions + overlay: CloudSessionEnv | null ): NodeJS.ProcessEnv -export function withCloudSessionEnv( +export function applyCloudSessionEnv( env: Record, - options: CloudSessionEnvOptions = {} + overlay: CloudSessionEnv | null ): Record { - const current = cloudSessionEnv(env, options) - if (!current) { + if (!overlay) { return env } const next: Record = { ...env } - for (const name of current.unset) { + for (const name of overlay.unset) { delete next[name] } - return Object.assign(next, current.set) + return Object.assign(next, overlay.set) +} + +type Cache = { path: string; text: string | null; loaded: Promise; watcher: FSWatcher | null } +let cache: Cache | null = null + +async function reload(into: Cache): Promise { + try { + into.text = await readFile(into.path, 'utf8') + } catch { + into.text = null + } +} + +/** Starts the in-memory copy once per process; null outside a cloud workspace's orcad. */ +function cloudCache(): Cache | null { + if (cache) { + return cache + } + const uid = process.getuid?.() + if (!isCloudWorkspaceOrcad() || uid === undefined) { + return null + } + const created: Cache = { + path: sessionEnvFilePath(uid), + text: null, + loaded: Promise.resolve(), + watcher: null + } + created.loaded = reload(created) + try { + // orca-sandbox-env replaces the file by rename, so watch the directory. + created.watcher = watch(dirname(created.path), { persistent: false }, () => { + created.loaded = reload(created) + }) + created.watcher.on('error', () => {}) + } catch { + // No directory yet: async reads go to disk each time instead. + created.watcher = null + } + cache = created + return created +} + +/** The live overlay for `base`, read fresh when unwatched (async paths: structured agent launches). */ +export async function liveCloudSessionEnv( + base: Readonly> +): Promise { + const current = cloudCache() + if (!current) { + return null + } + if (!current.watcher) { + current.loaded = reload(current) + } + await current.loaded + return cloudSessionEnvFromText(base, current.text) +} + +/** The last-read overlay for `base`, without waiting (sync spawn paths). */ +export function cachedCloudSessionEnv( + base: Readonly> +): CloudSessionEnv | null { + const current = cloudCache() + return current ? cloudSessionEnvFromText(base, current.text) : null +} + +export function resetCloudSessionEnvCacheForTests(): void { + cache?.watcher?.close() + cache = null } From 1075298bd7b159be8872f3b26150621e70a0bb9c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:04:47 -0800 Subject: [PATCH 5/5] test(cloud): cloud session env overlay against the in-memory reader --- .../runtime/secrets/cloud-session-env.test.ts | 66 +++++++------------ 1 file changed, 22 insertions(+), 44 deletions(-) diff --git a/src/main/runtime/secrets/cloud-session-env.test.ts b/src/main/runtime/secrets/cloud-session-env.test.ts index 40524b4723a..13c58e10bd8 100644 --- a/src/main/runtime/secrets/cloud-session-env.test.ts +++ b/src/main/runtime/secrets/cloud-session-env.test.ts @@ -1,30 +1,22 @@ import { describe, expect, it } from 'vitest' -import { cloudSessionEnv, withCloudSessionEnv } from './cloud-session-env' +import { applyCloudSessionEnv, cloudSessionEnvFromText } from './cloud-session-env' -const CLOUD = { ORCA_IS_CLOUD: '1', ORCA_SANDBOX_ID: 'sbx_1' } const b64 = (value: string): string => Buffer.from(value).toString('base64') -const file = - (lines: string[]) => - (path: string): string => { - expect(path).toBe('/dev/shm/orca-env-1000/session.env') - return lines.join('\n') - } +const lay = (env: Record, lines: string[] | null): Record => + applyCloudSessionEnv(env, cloudSessionEnvFromText(env, lines === null ? null : lines.join('\n'))) describe('cloud session env overlay (RA-1)', () => { it('lays the live file over an env captured before a credential was added', () => { - const started: Record = { PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' } - const env = withCloudSessionEnv(started, { - processEnv: CLOUD, - uid: 1000, - read: file([ - `CLAUDE_CODE_OAUTH_TOKEN=${b64('orca-ph-claude-account-sbx_1')}`, - `NPM_TOKEN=${b64('n')}` - ]) + const env = lay({ PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' }, [ + `CLAUDE_CODE_OAUTH_TOKEN=${b64('orca-ph-claude-account-sbx_1')}`, + `NPM_TOKEN=${b64('n')}` + ]) + expect(env).toEqual({ + PATH: '/usr/bin', + CLAUDE_CODE_OAUTH_TOKEN: 'orca-ph-claude-account-sbx_1', + NPM_TOKEN: 'n', + ORCA_SESSION_ENV_NAMES: 'CLAUDE_CODE_OAUTH_TOKEN NPM_TOKEN' }) - expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe('orca-ph-claude-account-sbx_1') - expect(env.NPM_TOKEN).toBe('n') - expect(env.ORCA_SESSION_ENV_NAMES).toBe('CLAUDE_CODE_OAUTH_TOKEN NPM_TOKEN') - expect(env.PATH).toBe('/usr/bin') }) it('removes names an older session env set that the live one dropped (a revoked account)', () => { @@ -32,36 +24,22 @@ describe('cloud session env overlay (RA-1)', () => { CLAUDE_CODE_OAUTH_TOKEN: 'orca-ph-claude-account-sbx_1', ORCA_SESSION_ENV_NAMES: 'CLAUDE_CODE_OAUTH_TOKEN' } - const current = cloudSessionEnv(started, { processEnv: CLOUD, uid: 1000, read: file([]) }) - expect(current?.unset).toEqual(['CLAUDE_CODE_OAUTH_TOKEN']) - expect(withCloudSessionEnv(started, { processEnv: CLOUD, uid: 1000, read: file([]) })).toEqual({ - ORCA_SESSION_ENV_NAMES: '' - }) + expect(cloudSessionEnvFromText(started, '')?.unset).toEqual(['CLAUDE_CODE_OAUTH_TOKEN']) + expect(lay(started, [])).toEqual({ ORCA_SESSION_ENV_NAMES: '' }) }) it('skips the names the shell hook skips', () => { - const env = withCloudSessionEnv( - { PATH: '/usr/bin' }, - { - processEnv: CLOUD, - uid: 1000, - read: file([ - `PATH=${b64('/evil')}`, - `ORCA_X=${b64('x')}`, - `LD_PRELOAD=${b64('x')}`, - `bad-name=${b64('x')}` - ]) - } - ) + const env = lay({ PATH: '/usr/bin' }, [ + `PATH=${b64('/evil')}`, + `ORCA_X=${b64('x')}`, + `LD_PRELOAD=${b64('x')}`, + `bad-name=${b64('x')}` + ]) expect(env).toEqual({ PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' }) }) - it('changes nothing off the cloud or before the file exists', () => { + it('changes nothing before the file exists', () => { const env = { A: '1' } - expect(withCloudSessionEnv(env, { processEnv: {}, uid: 1000, read: file([]) })).toBe(env) - const missing = (): string => { - throw new Error('ENOENT') - } - expect(withCloudSessionEnv(env, { processEnv: CLOUD, uid: 1000, read: missing })).toBe(env) + expect(lay(env, null)).toBe(env) }) })