mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
Merge remote-tracking branch 'private/cloud/integration' into create-speed/ep5-cancel-create
This commit is contained in:
@@ -21,7 +21,7 @@ import {
|
||||
import type { GitHubAppMinter } from './github-app'
|
||||
import type { GoldenImageProviderApi } from './golden-image-provider'
|
||||
import { assertStartsOpen, type GuardrailConfig, DEFAULT_GUARDRAILS } from './guardrails'
|
||||
import { compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute } from './network-policy'
|
||||
import { compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute, type PlatformHostSuffixesConfigError } from './network-policy'
|
||||
import { SWAPPED_CREDENTIALS } from './provider-env'
|
||||
import { ProviderError, type SandboxProviderApi } from './sandbox-provider'
|
||||
import { ORCAD_PORT, startOrcad } from './sandbox-vm-commands'
|
||||
@@ -162,6 +162,10 @@ export type BuildDeps = {
|
||||
/** The default region: new builds run here. */
|
||||
region: string
|
||||
guardrails?: GuardrailConfig
|
||||
/** The workspace base allowlist (ORCA_PLATFORM_HOST_SUFFIXES included); the smoke boot uses it too. */
|
||||
egressAllowlist?: readonly string[]
|
||||
/** A malformed ORCA_PLATFORM_HOST_SUFFIXES: new builds refuse, running ones wait (their smoke needs the list). */
|
||||
egressAllowlistError?: PlatformHostSuffixesConfigError
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,6 +270,9 @@ export async function startBuild(
|
||||
options: { config?: BuildConfig } = {}
|
||||
): Promise<BuildRow> {
|
||||
requireAdmin(caller)
|
||||
if (deps.config.egressAllowlistError) {
|
||||
throw deps.config.egressAllowlistError
|
||||
}
|
||||
const repos = options.config?.repos ?? parseRepos(environment)
|
||||
if (repos.length === 0) {
|
||||
throw new EnvironmentError('invalid_request', 400, 'no_repos')
|
||||
@@ -445,7 +452,8 @@ function base64(text: string): string {
|
||||
*/
|
||||
export async function advanceBuild(deps: BuildDeps, row: BuildRow, options: { waitForExit?: boolean } = {}): Promise<BuildRow> {
|
||||
const now = deps.now()
|
||||
if (TERMINAL.has(row.status)) {
|
||||
// Reads of a build keep working; it resumes once the platform host list is fixed.
|
||||
if (TERMINAL.has(row.status) || deps.config.egressAllowlistError) {
|
||||
return row
|
||||
}
|
||||
if (row.status === 'starting') {
|
||||
@@ -549,7 +557,7 @@ async function smokeBoot(deps: BuildDeps, row: BuildRow, snapshotId: string): Pr
|
||||
region: row.region,
|
||||
timeoutMs: 5 * 60_000,
|
||||
ports: [ORCAD_PORT],
|
||||
networkPolicy: compileNetworkPolicy({ mode: 'allowlist' }),
|
||||
networkPolicy: compileNetworkPolicy({ mode: 'allowlist', allowlist: deps.config.egressAllowlist }),
|
||||
tags: { orcaEnvBuildSmoke: row.id, orcaEnv: deps.config.environment },
|
||||
snapshotExpirationMs: 0,
|
||||
persistent: false
|
||||
|
||||
@@ -39,6 +39,8 @@ export type GoldenImageDeps = {
|
||||
fetch?: typeof fetch
|
||||
/** ENV-STALE: where git-source builds publish their orcad bundle (runtime-bundles.ts). */
|
||||
runtimeBundle?: { baseUrl: string; secret: string }
|
||||
/** The workspace base allowlist (ORCA_PLATFORM_HOST_SUFFIXES included), so the smoke boots like a workspace. */
|
||||
egressAllowlist?: readonly string[]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,7 +455,7 @@ async function stepSmoke(deps: GoldenImageDeps, row: GoldenRow): Promise<GoldenT
|
||||
region: row.region,
|
||||
timeoutMs: 10 * 60_000,
|
||||
ports: [ORCAD_PORT],
|
||||
networkPolicy: compileNetworkPolicy({ mode: 'allowlist' }),
|
||||
networkPolicy: compileNetworkPolicy({ mode: 'allowlist', allowlist: deps.config.egressAllowlist }),
|
||||
tags: { orcaGoldenSmoke: row.id, orcaEnv: deps.config.environment },
|
||||
snapshotExpirationMs: 86_400_000
|
||||
})
|
||||
|
||||
@@ -202,7 +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 { egressAllowlistSetting, PlatformHostSuffixesConfigError } from './network-policy'
|
||||
import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs'
|
||||
import { getOrgSlug, putOrgSlug } from './org-slugs'
|
||||
import {
|
||||
@@ -948,7 +948,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
|
||||
config: {
|
||||
pool: poolConfigFromEnv(env),
|
||||
shareLinkSecret: shareSecret(env),
|
||||
egressAllowlist: egressAllowlistFor(env.ORCA_PLATFORM_HOST_SUFFIXES),
|
||||
...platformAllowlistConfig(env),
|
||||
extraEgressHosts: extraEgressHostsFor(env),
|
||||
dockerEnabled: env.SANDBOX_DOCKER?.trim().toLowerCase() !== 'off',
|
||||
egressPreset: parseEgressPreset(env.SANDBOX_EGRESS_PRESET),
|
||||
@@ -1036,7 +1036,9 @@ function buildDeps(life: LifecycleDeps, deps: Deps, env?: Env): BuildDeps {
|
||||
goldenSnapshotId: life.config.goldenSnapshotId,
|
||||
goldenSnapshots: life.config.goldenSnapshots,
|
||||
region: life.config.defaultRegion,
|
||||
guardrails: life.config.guardrails
|
||||
guardrails: life.config.guardrails,
|
||||
egressAllowlist: life.config.egressAllowlist,
|
||||
egressAllowlistError: life.config.egressAllowlistError
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1067,6 +1069,12 @@ async function githubRepoIsPublic(repoUrl: string): Promise<boolean> {
|
||||
* before expiry, rebuild on a new release or VM-touching commit. Regions advance independently.
|
||||
*/
|
||||
async function advanceGoldenImagesFromEnv(env: Env): Promise<void> {
|
||||
const platform = egressAllowlistSetting(env.ORCA_PLATFORM_HOST_SUFFIXES)
|
||||
if (platform.error) {
|
||||
// The smoke boots under this list: no rotation until it is fixed (the active image keeps serving).
|
||||
console.error(JSON.stringify({ event: 'config_error', variable: 'ORCA_PLATFORM_HOST_SUFFIXES', invalid: platform.error.invalid, skipped: 'golden_images' }))
|
||||
return
|
||||
}
|
||||
if (!env.VERCEL_TOKEN || !env.VERCEL_TEAM_ID || !env.VERCEL_PROJECT_ID) {
|
||||
return
|
||||
}
|
||||
@@ -1094,7 +1102,8 @@ async function advanceGoldenImagesFromEnv(env: Env): Promise<void> {
|
||||
github,
|
||||
seedSnapshotId: region === seeded ? env.GOLDEN_SNAPSHOT_ID : undefined,
|
||||
refreshBeforeMs: env.GOLDEN_REFRESH_BEFORE_HOURS ? Number(env.GOLDEN_REFRESH_BEFORE_HOURS) * 3_600_000 : undefined,
|
||||
runtimeBundle: runtimeBundleConfig(env)
|
||||
runtimeBundle: runtimeBundleConfig(env),
|
||||
egressAllowlist: platform.allowlist
|
||||
}
|
||||
})
|
||||
if (tick !== 'idle') {
|
||||
@@ -1229,6 +1238,9 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
try {
|
||||
return await routeRequest(request, env, deps)
|
||||
} catch (error) {
|
||||
if (error instanceof PlatformHostSuffixesConfigError) {
|
||||
return platformHostsMisconfigured(error)
|
||||
}
|
||||
// A stale-org token anywhere in routing (ORG-TOKEN-STALE): the desktop re-mints once and retries.
|
||||
if (error instanceof OrgMismatchError) {
|
||||
return orgMismatchResponse()
|
||||
@@ -1237,6 +1249,19 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
}
|
||||
}
|
||||
|
||||
/** The lifecycle's base allowlist, or the config error that refuses limited-mode policy compiles. */
|
||||
function platformAllowlistConfig(env: Env): { egressAllowlist?: readonly string[]; egressAllowlistError?: PlatformHostSuffixesConfigError } {
|
||||
const { allowlist, error } = egressAllowlistSetting(env.ORCA_PLATFORM_HOST_SUFFIXES)
|
||||
return error ? { egressAllowlistError: error } : { egressAllowlist: allowlist }
|
||||
}
|
||||
|
||||
/** 503 for whatever needs the platform host list (creates, wakes, builds, health), naming the bad entries. */
|
||||
function platformHostsMisconfigured(error: PlatformHostSuffixesConfigError): Response {
|
||||
console.error(JSON.stringify({ event: 'config_error', variable: 'ORCA_PLATFORM_HOST_SUFFIXES', invalid: error.invalid }))
|
||||
// Code only: /v1/health is public, so the bad entries stay in the log line above.
|
||||
return json({ error: 'platform_hosts_misconfigured' }, 503)
|
||||
}
|
||||
|
||||
function orgMismatchResponse(): Response {
|
||||
return json(
|
||||
{
|
||||
@@ -1398,6 +1423,11 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
})) ?? fail('not_found', 404)
|
||||
)
|
||||
}
|
||||
if (url.pathname === '/v1/health' && request.method === 'GET') {
|
||||
// Post-deploy smoke: no auth, no DB. 503 names a config error a deploy must not ship.
|
||||
const platform = egressAllowlistSetting(env.ORCA_PLATFORM_HOST_SUFFIXES)
|
||||
return platform.error ? platformHostsMisconfigured(platform.error) : json({ ok: true }, 200)
|
||||
}
|
||||
if (url.pathname === '/v1/config' && request.method === 'GET') {
|
||||
// Public product constants (no auth): every client reads these instead of hardcoding them.
|
||||
const createTiming = await cachedCreateTiming(env.SANDBOX_DB, (deps.now ?? Date.now)())
|
||||
@@ -2470,6 +2500,9 @@ function errorResponse(error: unknown): Response {
|
||||
if (error instanceof BillingUnavailableError) {
|
||||
return fail('billing_unavailable', 503)
|
||||
}
|
||||
if (error instanceof PlatformHostSuffixesConfigError) {
|
||||
return platformHostsMisconfigured(error)
|
||||
}
|
||||
if (error instanceof SecretsKmsError) {
|
||||
return secretsUnavailableResponse()
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
killSwitchOn,
|
||||
type GuardrailConfig
|
||||
} from './guardrails'
|
||||
import { DEFAULT_EGRESS_ALLOWLIST, DEFAULT_EGRESS_PRESET, compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute, type EgressPreset } from './network-policy'
|
||||
import { DEFAULT_EGRESS_ALLOWLIST, DEFAULT_EGRESS_PRESET, compileNetworkPolicy, gitBasicAuthorization, type CredentialRoute, type EgressPreset, type PlatformHostSuffixesConfigError } from './network-policy'
|
||||
import { applyQueuedRevokes } from './grant-revokes'
|
||||
import { ensureEntryPoints } from './golden-images'
|
||||
import { RUNTIME_REFRESH_SCRIPT, type RuntimeBundle } from './runtime-bundles'
|
||||
@@ -151,6 +151,8 @@ export type LifecycleDeps = {
|
||||
pool?: PoolConfig
|
||||
/** Base egress allowlist (egressAllowlistFor ORCA_PLATFORM_HOST_SUFFIXES); default DEFAULT_EGRESS_ALLOWLIST. */
|
||||
egressAllowlist?: readonly string[]
|
||||
/** A malformed ORCA_PLATFORM_HOST_SUFFIXES: whatever compiles a limited-mode policy refuses with it. */
|
||||
egressAllowlistError?: PlatformHostSuffixesConfigError
|
||||
/** Hosts allowed on top of the default egress allowlist (e.g. this control plane for the in-VM CLI). */
|
||||
extraEgressHosts?: readonly string[]
|
||||
/** PARITY-DOCKER: false (SANDBOX_DOCKER=off) makes the VM's `docker` refuse instead of installing or starting Docker. */
|
||||
@@ -268,6 +270,13 @@ export function effectiveEgressPreset(deps: Pick<LifecycleDeps, 'config'>, row:
|
||||
}
|
||||
const LOCAL_ENVIRONMENTS = new Set(['local', 'test'])
|
||||
|
||||
/** Refuses up front (503 platform_hosts_misconfigured) when this create or boot would compile a limited policy. */
|
||||
export function assertEgressAllowlistUsable(deps: Pick<LifecycleDeps, 'config'>, row: Pick<SandboxRow, 'id'>): void {
|
||||
if (deps.config.egressAllowlistError && effectiveEgressPreset(deps, row) === 'limited') {
|
||||
throw deps.config.egressAllowlistError
|
||||
}
|
||||
}
|
||||
|
||||
export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: string, memberPlaceholders: readonly string[] = []) {
|
||||
const proxyUrl = deps.config.egressProxyUrl
|
||||
const gitPlaceholder = gitBasicAuthorization(githubPlaceholderToken(row))
|
||||
@@ -337,6 +346,9 @@ export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: st
|
||||
}
|
||||
// Limited: custom model-provider hosts (ANTHROPIC_BASE_URL / OPENAI_BASE_URL secrets) recorded at
|
||||
// boot, MCP hosts the desktop declared, plus operator-configured extra hosts.
|
||||
if (deps.config.egressAllowlistError) {
|
||||
throw deps.config.egressAllowlistError
|
||||
}
|
||||
const allowlist = [...new Set([...(deps.config.egressAllowlist ?? DEFAULT_EGRESS_ALLOWLIST), ...(deps.config.extraEgressHosts ?? []), ...egressAllowHosts(row)])]
|
||||
return compileNetworkPolicy({ mode: 'allowlist', allowlist, credentials: all })
|
||||
}
|
||||
@@ -670,6 +682,7 @@ export async function createSandbox(
|
||||
},
|
||||
options: { pool?: boolean; fallback?: boolean } = {}
|
||||
): Promise<Ready> {
|
||||
assertEgressAllowlistUsable(deps, { id: request.workspaceId })
|
||||
const existing = await liveSandboxForWorkspace(deps.db, caller.accountId, request.workspaceId)
|
||||
if (existing) {
|
||||
if (existing.status !== 'running' || !existing.session_id) {
|
||||
@@ -983,6 +996,7 @@ export async function suspendSandbox(deps: LifecycleDeps, row: SandboxRow): Prom
|
||||
}
|
||||
|
||||
export async function resumeSandbox(deps: LifecycleDeps, row: SandboxRow): Promise<Ready> {
|
||||
assertEgressAllowlistUsable(deps, row)
|
||||
if (row.status === 'resuming') {
|
||||
const settled = await joinOrAdoptResume(deps, row)
|
||||
if ('connection' in settled) {
|
||||
@@ -1065,6 +1079,7 @@ export async function bootLiveSession(deps: LifecycleDeps, row: SandboxRow, stat
|
||||
}
|
||||
|
||||
export async function wake(deps: LifecycleDeps, row: SandboxRow): Promise<Ready> {
|
||||
assertEgressAllowlistUsable(deps, row)
|
||||
const timer = phaseTimer(deps.now)
|
||||
// The provider boot is the long pole; secrets and the repo token resolve alongside it.
|
||||
const [state, prep] = await Promise.all([
|
||||
|
||||
@@ -103,13 +103,48 @@ const BASE_EGRESS_HOSTS: readonly string[] = [
|
||||
'*.githubcopilot.com'
|
||||
]
|
||||
|
||||
const HOST = /^(\*\.)?([a-z0-9-]+\.)+[a-z]{2,63}$/
|
||||
|
||||
/** ORCA_PLATFORM_HOST_SUFFIXES names an entry no egress policy can hold; `invalid` quotes them (hosts, not secrets). */
|
||||
export class PlatformHostSuffixesConfigError extends Error {
|
||||
constructor(readonly invalid: readonly string[]) {
|
||||
super(`ORCA_PLATFORM_HOST_SUFFIXES has invalid hosts: ${invalid.join(', ')} (expected e.g. *.onorca.dev)`)
|
||||
this.name = 'PlatformHostSuffixesConfigError'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Orca's platform hosts from ORCA_PLATFORM_HOST_SUFFIXES (comma list, e.g. `*.onorca.dev`). Unset, blank
|
||||
* or only commas: DEFAULT_PLATFORM_HOST_SUFFIXES. Throws PlatformHostSuffixesConfigError on a malformed
|
||||
* entry, naming it, instead of an opaque failure in each limited-mode policy compile.
|
||||
*/
|
||||
export function platformHostSuffixesFrom(platformHostSuffixes?: string): readonly string[] {
|
||||
const configured = (platformHostSuffixes ?? '').split(',').map((host) => host.trim().toLowerCase()).filter(Boolean)
|
||||
const invalid = configured.filter((host) => !HOST.test(host))
|
||||
if (invalid.length > 0) {
|
||||
throw new PlatformHostSuffixesConfigError(invalid)
|
||||
}
|
||||
return configured.length > 0 ? configured : DEFAULT_PLATFORM_HOST_SUFFIXES
|
||||
}
|
||||
|
||||
/**
|
||||
* The base allowlist, or the config error when ORCA_PLATFORM_HOST_SUFFIXES is malformed. Only what
|
||||
* compiles an allowlist policy refuses on the error; reads, stops and the reconcile cron keep working.
|
||||
*/
|
||||
export function egressAllowlistSetting(platformHostSuffixes?: string): { allowlist?: readonly string[]; error?: PlatformHostSuffixesConfigError } {
|
||||
try {
|
||||
return { allowlist: egressAllowlistFor(platformHostSuffixes) }
|
||||
} catch (error) {
|
||||
if (error instanceof PlatformHostSuffixesConfigError) {
|
||||
return { error }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** The default allowlist with Orca's platform hosts (platformHostSuffixesFrom). */
|
||||
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
|
||||
const platform = platformHostSuffixesFrom(platformHostSuffixes)
|
||||
return [...new Set([...BASE_EGRESS_HOSTS, ...platform, ...EDITOR_REMOTE_SERVER_HOSTS])]
|
||||
}
|
||||
|
||||
@@ -155,7 +190,6 @@ export type EgressPolicyInput = {
|
||||
denyUnclaimed?: boolean
|
||||
}
|
||||
|
||||
const HOST = /^(\*\.)?([a-z0-9-]+\.)+[a-z]{2,63}$/
|
||||
|
||||
export function compileNetworkPolicy(input: EgressPolicyInput): NetworkPolicy {
|
||||
const allow: Record<string, NetworkPolicyRule[]> = {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PlatformHostSuffixesConfigError } from './network-policy'
|
||||
// Cron pass: the control plane, not the desktop, guarantees metering, the session deadline and cleanup,
|
||||
// so a closed laptop or a crash mid-call can never leave a sandbox billed-but-untracked.
|
||||
import { STOP_RUNNING_REASONS } from './entitlements'
|
||||
@@ -142,9 +143,17 @@ async function reconcileRunning(deps: LifecycleDeps, row: SandboxRow, summary: R
|
||||
}
|
||||
}
|
||||
if (row.github_token_expires_at !== null && row.session_id && row.github_token_expires_at - now < 15 * 60_000) {
|
||||
const git = await refreshGitCredentials(deps, row, row.session_id)
|
||||
const refreshed = await transition(deps.db, row, { github_token_expires_at: git?.expiresAt ?? null }, now)
|
||||
row = refreshed ?? row
|
||||
// A malformed ORCA_PLATFORM_HOST_SUFFIXES leaves the live policy as it is; usage still settles below.
|
||||
const git = await refreshGitCredentials(deps, row, row.session_id).catch((error: unknown) => {
|
||||
if (error instanceof PlatformHostSuffixesConfigError) {
|
||||
return 'skipped' as const
|
||||
}
|
||||
throw error
|
||||
})
|
||||
if (git !== 'skipped') {
|
||||
const refreshed = await transition(deps.db, row, { github_token_expires_at: git?.expiresAt ?? null }, now)
|
||||
row = refreshed ?? row
|
||||
}
|
||||
}
|
||||
const settled = await queueUsage(deps.db, row, now)
|
||||
const current = settled === row.usage_settled_at ? row : await transition(deps.db, row, { usage_settled_at: settled }, now)
|
||||
|
||||
@@ -14,8 +14,8 @@ const RESULT = JSON.stringify({
|
||||
})
|
||||
const log = (data: string, stream = 'stdout') => `${JSON.stringify({ data, stream })}\n`
|
||||
|
||||
async function setup(githubFetch?: typeof fetch) {
|
||||
const h = await createHarness({}, githubFetch ? { githubFetch } : {})
|
||||
async function setup(githubFetch?: typeof fetch, overrides: Parameters<typeof createHarness>[0] = {}) {
|
||||
const h = await createHarness(overrides, githubFetch ? { githubFetch } : {})
|
||||
h.vercel.buildResult = RESULT
|
||||
const admin = await h.token('alice', 'acme', 'sandbox', { orgRole: 'admin' })
|
||||
const member = await h.token('bob', 'acme', 'sandbox', { orgRole: 'member' })
|
||||
@@ -85,6 +85,33 @@ describe('org environments', () => {
|
||||
expect(lines.at(-1)).toEqual({ type: 'end' })
|
||||
})
|
||||
|
||||
it('smoke-boots a build under the configured platform hosts (ORCA_PLATFORM_HOST_SUFFIXES)', async () => {
|
||||
const { h, build } = await setup(undefined, { ORCA_PLATFORM_HOST_SUFFIXES: '*.orca.dev' })
|
||||
const policies: Record<string, unknown>[] = []
|
||||
const create = h.vercel.createSandbox.bind(h.vercel)
|
||||
h.vercel.createSandbox = async (params) => {
|
||||
if (params.name.includes('-smoke-')) {
|
||||
policies.push(params.networkPolicy.allow)
|
||||
}
|
||||
return create(params)
|
||||
}
|
||||
expect(await build(0)).toMatchObject({ status: 'succeeded' })
|
||||
expect(policies).toHaveLength(1)
|
||||
expect(policies[0]).toHaveProperty(['*.orca.dev'])
|
||||
expect(policies[0]).not.toHaveProperty(['*.onorca.dev'])
|
||||
})
|
||||
|
||||
it('refuses a new build under a malformed ORCA_PLATFORM_HOST_SUFFIXES, and still reads the old ones', async () => {
|
||||
const { h, adminCall, envId, build } = await setup()
|
||||
const good = await build(0)
|
||||
h.env.ORCA_PLATFORM_HOST_SUFFIXES = '*.orca.dev, not a host'
|
||||
const refused = await adminCall('POST', `/v1/environments/${envId}/builds`)
|
||||
expect(refused.status).toBe(503)
|
||||
expect(refused.body.error).toBe('platform_hosts_misconfigured')
|
||||
expect((await adminCall('GET', `/v1/environments/${envId}/builds/${good.id}`)).body.build).toMatchObject({ status: 'succeeded' })
|
||||
expect((await adminCall('GET', `/v1/environments/${envId}`)).status).toBe(200)
|
||||
})
|
||||
|
||||
it('fails a build whose image cannot start orcad, keeping the active one', async () => {
|
||||
const { h, adminCall, envId, build } = await setup()
|
||||
const good = await build(0)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createFakeD1 } from './d1-fake'
|
||||
import { SCRIPTS_STAMP_PATH, createFakeVercel } from './fake-vercel'
|
||||
import { GOLDEN, createHarness } from './harness'
|
||||
import { touchesVm } from '../src/golden-source'
|
||||
import { egressAllowlistFor } from '../src/network-policy'
|
||||
|
||||
const HOUR = 60 * 60_000
|
||||
|
||||
@@ -86,6 +87,31 @@ describe('golden image rotation', () => {
|
||||
expect([...t.vercel.boxes.keys()]).toEqual([])
|
||||
})
|
||||
|
||||
it('smoke-boots under the configured platform hosts, not the built-in *.onorca.dev', async () => {
|
||||
const t = setup({ seedExpiresInMs: 20 * HOUR })
|
||||
const policies: Record<string, unknown>[] = []
|
||||
const create = t.deps.provider.createSandbox.bind(t.deps.provider)
|
||||
const deps: GoldenImageDeps = {
|
||||
...t.deps,
|
||||
provider: {
|
||||
...t.deps.provider,
|
||||
createSandbox: async (params) => {
|
||||
if (params.name.includes('goldsmoke')) {
|
||||
policies.push(params.networkPolicy.allow)
|
||||
}
|
||||
return create(params)
|
||||
}
|
||||
},
|
||||
config: { ...t.deps.config, egressAllowlist: egressAllowlistFor('*.orca.dev') }
|
||||
}
|
||||
await advanceGoldenImages(deps)
|
||||
await advanceGoldenImages(deps)
|
||||
expect(await advanceGoldenImages(deps)).toBe('activated')
|
||||
expect(policies).toHaveLength(1)
|
||||
expect(policies[0]).toHaveProperty(['*.orca.dev'])
|
||||
expect(policies[0]).not.toHaveProperty(['*.onorca.dev'])
|
||||
})
|
||||
|
||||
it('keeps serving the previous image when the candidate fails its smoke boot', async () => {
|
||||
const t = setup({ seedExpiresInMs: 20 * HOUR })
|
||||
await advanceGoldenImages(t.deps)
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
DEFAULT_EGRESS_PRESET,
|
||||
EDITOR_REMOTE_SERVER_HOSTS,
|
||||
compileNetworkPolicy,
|
||||
PlatformHostSuffixesConfigError,
|
||||
egressAllowlistFor,
|
||||
gitBasicAuthorization,
|
||||
platformHostSuffixesFrom,
|
||||
parseEgressPreset
|
||||
} from '../src/network-policy'
|
||||
|
||||
@@ -153,4 +155,14 @@ describe('ORCA_PLATFORM_HOST_SUFFIXES', () => {
|
||||
expect(allow['*.onorca.dev']).toEqual([])
|
||||
expect(allow['*.example.dev']).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a malformed suffix up front, naming every bad entry', () => {
|
||||
expect(() => egressAllowlistFor('*.orca.dev,orca dev,https://x.dev')).toThrow(PlatformHostSuffixesConfigError)
|
||||
try {
|
||||
platformHostSuffixesFrom('*.orca.dev,orca dev,https://x.dev')
|
||||
} catch (error) {
|
||||
expect((error as PlatformHostSuffixesConfigError).invalid).toEqual(['orca dev', 'https://x.dev'])
|
||||
}
|
||||
expect(platformHostSuffixesFrom(' *.Orca.dev ')).toEqual(['*.orca.dev'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { reconcile } from '../src/reconcile'
|
||||
import { egressAllowlistSetting } from '../src/network-policy'
|
||||
import { GOLDEN, createHarness } from './harness'
|
||||
|
||||
const create = { workspaceId: 'ws-1', machineSize: 'standard' }
|
||||
const MALFORMED = '*.orca.dev, not a host'
|
||||
|
||||
/** A limited-mode deployment whose ORCA_PLATFORM_HOST_SUFFIXES is fine at first and then breaks. */
|
||||
async function limited() {
|
||||
const h = await createHarness({ SANDBOX_EGRESS_PRESET: 'limited' })
|
||||
const { body } = await h.call('POST', '/v1/sandboxes', { body: create })
|
||||
expect(body.sandbox.status).toBe('running')
|
||||
h.env.ORCA_PLATFORM_HOST_SUFFIXES = MALFORMED
|
||||
return { h, id: body.sandbox.id as string }
|
||||
}
|
||||
|
||||
describe('a malformed ORCA_PLATFORM_HOST_SUFFIXES (PLATFORM-SUFFIX-GUARDS)', () => {
|
||||
it('fails the health route a post-deploy smoke hits, with the code only; the log names the bad entry', async () => {
|
||||
const h = await createHarness()
|
||||
expect(await h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true } })
|
||||
h.env.ORCA_PLATFORM_HOST_SUFFIXES = MALFORMED
|
||||
const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
try {
|
||||
expect(await h.call('GET', '/v1/health')).toEqual({ status: 503, body: { error: 'platform_hosts_misconfigured' } })
|
||||
const line = JSON.parse(String(logged.mock.calls.at(-1)?.[0]))
|
||||
expect(line).toMatchObject({ event: 'config_error', variable: 'ORCA_PLATFORM_HOST_SUFFIXES', invalid: ['not a host'] })
|
||||
} finally {
|
||||
logged.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses a limited-mode create with 503 before anything is provisioned', async () => {
|
||||
const { h } = await limited()
|
||||
const boxes = h.vercel.boxes.size
|
||||
const refused = await h.call('POST', '/v1/sandboxes', { body: { ...create, workspaceId: 'ws-2' } })
|
||||
expect(refused.status).toBe(503)
|
||||
expect(refused.body.error).toBe('platform_hosts_misconfigured')
|
||||
expect(h.vercel.boxes.size).toBe(boxes)
|
||||
})
|
||||
|
||||
it('keeps reads, sleep and delete working, and refuses the wake', async () => {
|
||||
const { h, id } = await limited()
|
||||
expect((await h.call('GET', '/v1/sandboxes')).body.sandboxes).toHaveLength(1)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${id}/suspend`)).status).toBe(200)
|
||||
const resumed = await h.call('POST', `/v1/sandboxes/${id}/resume`)
|
||||
expect(resumed.status).toBe(503)
|
||||
expect(resumed.body.error).toBe('platform_hosts_misconfigured')
|
||||
const destroyed = await h.call('DELETE', `/v1/sandboxes/${id}`)
|
||||
expect(destroyed.status).toBe(200)
|
||||
expect(destroyed.body.sandbox.status).toBe('destroyed')
|
||||
})
|
||||
|
||||
it('leaves open-mode creates alone: they compile no allowlist', async () => {
|
||||
const h = await createHarness()
|
||||
h.env.ORCA_PLATFORM_HOST_SUFFIXES = MALFORMED
|
||||
expect((await h.call('POST', '/v1/sandboxes', { body: create })).body.sandbox.status).toBe('running')
|
||||
})
|
||||
|
||||
it('keeps the reconcile cron running for a limited-mode sandbox', async () => {
|
||||
const { h } = await limited()
|
||||
const summary = await reconcile({
|
||||
db: h.env.SANDBOX_DB,
|
||||
provider: h.vercel,
|
||||
entitlements: h.deps.entitlements!,
|
||||
now: h.now,
|
||||
config: {
|
||||
environment: 'test',
|
||||
goldenSnapshotId: GOLDEN,
|
||||
defaultRegion: 'iad1',
|
||||
egressPreset: 'limited',
|
||||
egressAllowlistError: egressAllowlistSetting(MALFORMED).error
|
||||
}
|
||||
})
|
||||
expect(summary.settled).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ import type { Translate } from '@/i18n/use-translate'
|
||||
import { useAppStore } from '@/store'
|
||||
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
|
||||
import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation'
|
||||
import { pickWorkspaceWorktree, type WorkspaceWorktreeCandidate } from './workspace-worktree-pick'
|
||||
import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler'
|
||||
import { RuntimeRpcCallError, unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result'
|
||||
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
@@ -44,17 +45,22 @@ export function cloudWorkspaceTitle(
|
||||
: (repoName ?? w.workspaceId)
|
||||
}
|
||||
|
||||
export function firstWorktreeOnHost(hostId: string): string | null {
|
||||
/**
|
||||
* The workspace's row on its server: with `branch`, the worktree on that branch (EP-6: never the
|
||||
* sandbox's base checkout while the workspace has its own); without, the first row on the server.
|
||||
*/
|
||||
export function firstWorktreeOnHost(hostId: string, branch?: string | null): string | null {
|
||||
const state = useAppStore.getState()
|
||||
const onHost: WorkspaceWorktreeCandidate[] = []
|
||||
for (const [repoId, worktrees] of Object.entries(selectWorktreesByRepo(state))) {
|
||||
const repo = state.repos.find((r) => r.id === repoId)
|
||||
for (const worktree of worktrees) {
|
||||
if (getWorktreeExecutionHostId(worktree, repo) === hostId) {
|
||||
return worktree.id
|
||||
onHost.push(worktree)
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
return branch === undefined ? (onHost[0]?.id ?? null) : pickWorkspaceWorktree(onHost, branch)
|
||||
}
|
||||
|
||||
function isPairingRejected(error: unknown): boolean {
|
||||
@@ -75,7 +81,9 @@ export type OpenCloudWorkspaceOptions = {
|
||||
async function connectAndReveal(
|
||||
environmentId: string,
|
||||
name: string,
|
||||
options: OpenCloudWorkspaceOptions = {}
|
||||
options: OpenCloudWorkspaceOptions = {},
|
||||
/** The workspace's branch: its own worktree is the one to open (EP-6). */
|
||||
branch: string | null = null
|
||||
): Promise<OpenOutcome> {
|
||||
options.onHost?.(toRuntimeExecutionHostId(environmentId))
|
||||
const environments = await window.api.runtimeEnvironments.list()
|
||||
@@ -105,7 +113,7 @@ async function connectAndReveal(
|
||||
(options) => useAppStore.getState().fetchWorktreeLineage(options)
|
||||
)
|
||||
const hostId = toRuntimeExecutionHostId(environment.id)
|
||||
const worktreeId = firstWorktreeOnHost(hostId)
|
||||
const worktreeId = firstWorktreeOnHost(hostId, branch)
|
||||
if (worktreeId) {
|
||||
activateAndRevealWorktree(worktreeId, { executionHostId: hostId })
|
||||
} else {
|
||||
@@ -176,7 +184,12 @@ async function pairAndReveal(
|
||||
return refused
|
||||
}
|
||||
try {
|
||||
return await connectAndReveal(binding.environmentId, name, options)
|
||||
return await connectAndReveal(
|
||||
binding.environmentId,
|
||||
name,
|
||||
options,
|
||||
workspace.repo?.branch ?? null
|
||||
)
|
||||
} catch (error) {
|
||||
// Only a rejected pairing is fixed by pairing again; anything else is surfaced as is.
|
||||
if (!isPairingRejected(error)) {
|
||||
@@ -228,7 +241,7 @@ async function pairAndReveal(
|
||||
}
|
||||
// Messages to this workspace now carry the sender line if it is shared with the team.
|
||||
void refreshCloudMessageSenders().catch(() => undefined)
|
||||
return await connectAndReveal(added.environment.id, name, options)
|
||||
return await connectAndReveal(added.environment.id, name, options, workspace.repo?.branch ?? null)
|
||||
}
|
||||
|
||||
async function openOnce(
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pickWorkspaceWorktree } from './workspace-worktree-pick'
|
||||
|
||||
const base = { id: 'r::/vercel/sandbox/project', branch: 'refs/heads/master', isMainWorktree: true }
|
||||
const own = {
|
||||
id: 'r::/home/ubuntu/orca/workspaces/Hello-World/endpass-n44',
|
||||
branch: 'refs/heads/endpass-n44',
|
||||
isMainWorktree: false
|
||||
}
|
||||
const other = {
|
||||
id: 'r::/home/ubuntu/orca/workspaces/Hello-World/scratch',
|
||||
branch: 'scratch',
|
||||
isMainWorktree: false
|
||||
}
|
||||
|
||||
describe('pickWorkspaceWorktree (EP-6)', () => {
|
||||
it("opens a shared workspace on its own worktree, not the sandbox's base checkout", () => {
|
||||
expect(pickWorkspaceWorktree([base, own], 'endpass-n44')).toBe(own.id)
|
||||
expect(pickWorkspaceWorktree([base, other, own], 'refs/heads/endpass-n44')).toBe(own.id)
|
||||
})
|
||||
|
||||
it('without a known branch, still prefers a linked worktree over the base checkout', () => {
|
||||
expect(pickWorkspaceWorktree([base, own], null)).toBe(own.id)
|
||||
expect(pickWorkspaceWorktree([base, own], 'gone-branch')).toBe(own.id)
|
||||
})
|
||||
|
||||
it('a GitHub-only workspace (only the primary) opens its primary; nothing listed yet is null', () => {
|
||||
expect(pickWorkspaceWorktree([base], 'master')).toBe(base.id)
|
||||
expect(pickWorkspaceWorktree([base], null)).toBe(base.id)
|
||||
expect(pickWorkspaceWorktree([], 'x')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
// EP-6: which of a cloud workspace's server rows is the workspace itself. A paired (shared)
|
||||
// workspace's server lists the sandbox's base checkout (its primary, the repo cloned at boot) next to
|
||||
// the workspace's own linked worktree; opening the workspace must land on the latter.
|
||||
|
||||
export type WorkspaceWorktreeCandidate = {
|
||||
id: string
|
||||
branch: string | null | undefined
|
||||
isMainWorktree: boolean
|
||||
}
|
||||
|
||||
function shortBranch(branch: string | null | undefined): string {
|
||||
return (branch ?? '').replace(/^refs\/heads\//, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace's branch when the server has it; else a linked worktree (never the base checkout
|
||||
* while the workspace has its own); else the first (a GitHub-only workspace is its primary).
|
||||
*/
|
||||
export function pickWorkspaceWorktree(
|
||||
candidates: readonly WorkspaceWorktreeCandidate[],
|
||||
branch?: string | null
|
||||
): string | null {
|
||||
const wanted = shortBranch(branch)
|
||||
const byBranch = wanted ? candidates.find((c) => shortBranch(c.branch) === wanted) : undefined
|
||||
return (byBranch ?? candidates.find((c) => !c.isMainWorktree) ?? candidates[0])?.id ?? null
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { matchingManagedSkillShareInstall } from './skill-share-package-selection'
|
||||
import { derivedBundleName } from './skill-bundle-name'
|
||||
import { noteSkillSharesChanged } from './skill-shares-changed'
|
||||
|
||||
type SkillShareDialogProps = {
|
||||
skills?: DiscoveredSkill[]
|
||||
@@ -216,6 +217,8 @@ export function SkillShareDialog({
|
||||
return
|
||||
}
|
||||
setShareUrl(result.value.share.url)
|
||||
// EP-7: Shared links (and its count) list the new link without reopening the page.
|
||||
noteSkillSharesChanged()
|
||||
} catch (cause) {
|
||||
console.warn('[skills] publish failed:', cause)
|
||||
setError(
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// EP-7: a published or revoked skill link changes the owner's shared links. Every mounted
|
||||
// "Shared links" list re-reads on this signal, so the count and list are right without reopening
|
||||
// the page.
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
/** Someone published or revoked a skill link on this computer. */
|
||||
export function noteSkillSharesChanged(): void {
|
||||
listeners.forEach((listener) => listener())
|
||||
}
|
||||
|
||||
export function onSkillSharesChanged(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { SkillCloudOwnedShare } from '../../../../../shared/skill-cloud-contract'
|
||||
import { noteSkillSharesChanged } from './skill-shares-changed'
|
||||
import { useOwnedSkillShares } from './use-owned-skill-shares'
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn() } }))
|
||||
|
||||
let server: SkillCloudOwnedShare[] = []
|
||||
const listOwnedShares = vi.fn(async () => ({ status: 'ok' as const, value: [...server] }))
|
||||
const revokeShare = vi.fn(async (id: string) => {
|
||||
server = server.filter((share) => share.id !== id)
|
||||
return { status: 'ok' as const }
|
||||
})
|
||||
|
||||
function share(id: string): SkillCloudOwnedShare {
|
||||
return {
|
||||
id,
|
||||
url: `https://share.example/s/${id}`,
|
||||
packageId: `pkg_${id}`,
|
||||
name: id,
|
||||
description: '',
|
||||
createdAt: '2026-11-13T00:00:00.000Z'
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
server = []
|
||||
listOwnedShares.mockClear()
|
||||
revokeShare.mockClear()
|
||||
Object.assign(window, { api: { skills: { listOwnedShares, revokeShare } } })
|
||||
})
|
||||
afterEach(() => cleanup())
|
||||
|
||||
describe('useOwnedSkillShares (EP-7)', () => {
|
||||
it('lists a link published after the page opened, without reopening it', async () => {
|
||||
const { result } = renderHook(() => useOwnedSkillShares())
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
expect(result.current.shares).toEqual([])
|
||||
|
||||
server = [share('shr_1')]
|
||||
act(() => noteSkillSharesChanged())
|
||||
await waitFor(() => expect(result.current.shares.map((s) => s.id)).toEqual(['shr_1']))
|
||||
expect(listOwnedShares).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('a revoke drops the link here and refreshes every other open list', async () => {
|
||||
server = [share('shr_1'), share('shr_2')]
|
||||
const here = renderHook(() => useOwnedSkillShares())
|
||||
const elsewhere = renderHook(() => useOwnedSkillShares())
|
||||
await waitFor(() => expect(elsewhere.result.current.shares).toHaveLength(2))
|
||||
|
||||
await act(async () => {
|
||||
await here.result.current.revoke(share('shr_1'))
|
||||
})
|
||||
expect(here.result.current.shares.map((s) => s.id)).toEqual(['shr_2'])
|
||||
await waitFor(() => expect(elsewhere.result.current.shares.map((s) => s.id)).toEqual(['shr_2']))
|
||||
})
|
||||
|
||||
it('stops listening once unmounted', async () => {
|
||||
const { unmount } = renderHook(() => useOwnedSkillShares())
|
||||
await waitFor(() => expect(listOwnedShares).toHaveBeenCalledTimes(1))
|
||||
unmount()
|
||||
act(() => noteSkillSharesChanged())
|
||||
expect(listOwnedShares).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import type { SkillCloudOwnedShare } from '../../../../../shared/skill-cloud-contract'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { noteSkillSharesChanged, onSkillSharesChanged } from './skill-shares-changed'
|
||||
|
||||
function inventoryError(status: string): string {
|
||||
return status === 'reconnect-required'
|
||||
@@ -58,7 +59,10 @@ export function useOwnedSkillShares(): OwnedSkillShares {
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
// EP-7: a link published (or revoked) anywhere on this computer shows here at once.
|
||||
const unsubscribe = onSkillSharesChanged(() => void load())
|
||||
return () => {
|
||||
unsubscribe()
|
||||
generation.current += 1
|
||||
}
|
||||
}, [load])
|
||||
@@ -73,6 +77,8 @@ export function useOwnedSkillShares(): OwnedSkillShares {
|
||||
return
|
||||
}
|
||||
setShares((current) => current.filter((candidate) => candidate.id !== share.id))
|
||||
// Other open lists (and the page's link count) re-read; this one already dropped it.
|
||||
noteSkillSharesChanged()
|
||||
toast.success(translate('auto.components.settings.shareSkills.linkRevoked', 'Link revoked'))
|
||||
} catch {
|
||||
setError(
|
||||
|
||||
@@ -84,6 +84,8 @@ describe('a paired-from-birth cloud workspace (PAIRED-NO-ROW)', () => {
|
||||
const hosts = parseOrcaCloudHostScopeKey(selectOrcaCloudHostScopeKey(state))
|
||||
expect(hosts.hiddenHostIds.has('runtime:gh')).toBe(false)
|
||||
expect(hosts.primaryHostIds.has('runtime:gh')).toBe(false)
|
||||
// EP-6: paired-scoped, so its base clone hides only beside a linked worktree.
|
||||
expect(hosts.pairedHostIds.has('runtime:gh')).toBe(true)
|
||||
// The owned sandboxes are still scoped by team exactly as before.
|
||||
expect([...hosts.hiddenHostIds]).toEqual(['runtime:b', 'runtime:unfiled'])
|
||||
// Its project survives the sidebar's repo scoping.
|
||||
@@ -115,6 +117,7 @@ describe('paired workspaces scoped by account (PAIRED-ACCOUNT-FILTER)', () => {
|
||||
const hosts = hostsFor('team-one', paired('org:team-one'))
|
||||
expect(hosts.hiddenHostIds.has('runtime:gh')).toBe(false)
|
||||
expect(hosts.primaryHostIds.has('runtime:gh')).toBe(false)
|
||||
expect(hosts.pairedHostIds.has('runtime:gh')).toBe(true)
|
||||
})
|
||||
|
||||
it("after a team switch, the other team's paired workspace is hidden like its owned rows", () => {
|
||||
|
||||
@@ -25,12 +25,12 @@ type CloudScopeState = Pick<AppState, 'runtimeEnvironments'> &
|
||||
* otherwise (another team's, or one whose team is not known yet). Newline-joined so the selector
|
||||
* compares by value.
|
||||
*
|
||||
* A PAIRED server (`orcaCloudPaired`, PAIRED-NO-ROW) of the active account is left out: its owner is
|
||||
* never in `cloudAccountIdByEnvironmentId` (that knows this desktop's own runtimes only), and its
|
||||
* primary checkout IS the workspace's row, so either treatment would hide a workspace this desktop
|
||||
* just paired with, a GitHub-only create included. A paired server stamped with ANOTHER account
|
||||
* (PAIRED-ACCOUNT-FILTER) is `-host`, like another team's owned sandbox; one saved before pairings
|
||||
* were stamped stays visible until the prune stamps it from the active team's list.
|
||||
* A PAIRED server (`orcaCloudPaired`, PAIRED-NO-ROW) of the active account is `~host`: its owner is
|
||||
* never in `cloudAccountIdByEnvironmentId` (that knows this desktop's own runtimes only), and on a
|
||||
* GitHub-only create its primary checkout IS the workspace's row. So its primary hides only beside a
|
||||
* linked worktree of the same project (EP-6: a teammate's shared workspace listed "master" too). A
|
||||
* paired server stamped with ANOTHER account (PAIRED-ACCOUNT-FILTER) is `-host`, like another team's
|
||||
* owned sandbox; one saved before pairings were stamped is `~host` until the prune stamps it.
|
||||
*/
|
||||
export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
|
||||
const active = orcaCloudAccountId(state.orcaProfileAuthStatus?.cloud)
|
||||
@@ -46,7 +46,7 @@ export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
|
||||
const hostId = toRuntimeExecutionHostId(environment.id)
|
||||
if (environment.orcaCloudPaired === true) {
|
||||
const account = environment.orcaCloudPairedAccountId
|
||||
return account && account !== active ? [`-${hostId}`] : []
|
||||
return [`${account && account !== active ? '-' : '~'}${hostId}`]
|
||||
}
|
||||
const inTeam = active !== null && owners[environment.id] === active
|
||||
return [`${inTeam ? '+' : '-'}${hostId}`]
|
||||
@@ -56,14 +56,21 @@ export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
|
||||
|
||||
export function parseOrcaCloudHostScopeKey(key: string): {
|
||||
primaryHostIds: ReadonlySet<string>
|
||||
pairedHostIds: ReadonlySet<string>
|
||||
hiddenHostIds: ReadonlySet<string>
|
||||
} {
|
||||
const primaryHostIds = new Set<string>()
|
||||
const pairedHostIds = new Set<string>()
|
||||
const hiddenHostIds = new Set<string>()
|
||||
for (const entry of key ? key.split('\n') : []) {
|
||||
;(entry.startsWith('+') ? primaryHostIds : hiddenHostIds).add(entry.slice(1))
|
||||
const set = entry.startsWith('+')
|
||||
? primaryHostIds
|
||||
: entry.startsWith('~')
|
||||
? pairedHostIds
|
||||
: hiddenHostIds
|
||||
set.add(entry.slice(1))
|
||||
}
|
||||
return { primaryHostIds, hiddenHostIds }
|
||||
return { primaryHostIds, pairedHostIds, hiddenHostIds }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -156,3 +156,68 @@ describe('Orca Cloud sandboxes', () => {
|
||||
expect(withoutHiddenVmWorktrees(rows, none)).toBe(rows)
|
||||
})
|
||||
})
|
||||
|
||||
describe("a paired cloud host's base clone (EP-6)", () => {
|
||||
const paired = 'runtime:paired-teammate'
|
||||
const base = {
|
||||
repoId: 'r',
|
||||
path: '/vercel/sandbox/project',
|
||||
isMainWorktree: true,
|
||||
hostId: paired
|
||||
}
|
||||
const workspace = {
|
||||
repoId: 'r',
|
||||
path: '/home/vercel/ws/Hello-World/endpass-n44',
|
||||
isMainWorktree: false,
|
||||
hostId: paired
|
||||
}
|
||||
const local = { repoId: 'r', path: '/Users/me/repo', isMainWorktree: true, hostId: 'local' }
|
||||
const localLinked = { repoId: 'r', path: '/Users/me/wt', isMainWorktree: false, hostId: 'local' }
|
||||
const scope = withOrcaCloudHosts(readHiddenVmCheckouts(), {
|
||||
primaryHostIds: new Set(),
|
||||
pairedHostIds: new Set([paired]),
|
||||
hiddenHostIds: new Set()
|
||||
})
|
||||
|
||||
it('hides the base clone when the same host and repo lists a linked worktree', () => {
|
||||
expect(withoutHiddenVmWorktrees([base, workspace], scope)).toEqual([workspace])
|
||||
expect(withoutHiddenVmWorktreesByRepo({ r: [base, workspace] }, scope)).toEqual({
|
||||
r: [workspace]
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a GitHub-only paired workspace, whose only row is its primary checkout', () => {
|
||||
const rows = [base]
|
||||
expect(withoutHiddenVmWorktrees(rows, scope)).toBe(rows)
|
||||
})
|
||||
|
||||
it("leaves this computer's primary checkout alone, even beside a local linked worktree", () => {
|
||||
const rows = [local, localLinked, base]
|
||||
expect(withoutHiddenVmWorktrees(rows, scope)).toBe(rows)
|
||||
expect(withoutHiddenVmWorktrees([local, localLinked, base, workspace], scope)).toEqual([
|
||||
local,
|
||||
localLinked,
|
||||
workspace
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the base clone when the linked worktree belongs to another repo on that host', () => {
|
||||
const otherRepo = { ...workspace, repoId: 'other' }
|
||||
expect(withoutHiddenVmWorktrees([base, otherRepo], scope)).toEqual([base, otherRepo])
|
||||
})
|
||||
|
||||
it('applies to paired-server rows keyed by host-qualified identity', () => {
|
||||
const strip = <T extends { hostId: string }>({ hostId: _hostId, ...row }: T) => row
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the filter reads only repoId, path, isMainWorktree and the keys.
|
||||
const domains = {
|
||||
...EMPTY_SIDEBAR_FEED_DOMAINS,
|
||||
pairedServerRows: new Map([
|
||||
[composeWorktreeHostIdentity(paired, 'r::/vercel/sandbox/project'), strip(base)],
|
||||
[composeWorktreeHostIdentity(paired, `r::${workspace.path}`), strip(workspace)]
|
||||
])
|
||||
} as unknown as SidebarFeedDomains
|
||||
expect([...withoutHiddenVmCheckouts(domains, scope).pairedServerRows.values()]).toEqual([
|
||||
strip(workspace)
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -21,6 +21,8 @@ type CheckoutRow = {
|
||||
export type HiddenVmCheckouts = PendingVmCheckoutIndex & {
|
||||
/** Active-team Orca Cloud hosts: their primary checkout (the sandbox's clone) never lists. */
|
||||
readonly primaryHostIds?: ReadonlySet<string>
|
||||
/** Paired Orca Cloud hosts: their primary checkout hides only beside a linked worktree of its repo. */
|
||||
readonly pairedHostIds?: ReadonlySet<string>
|
||||
/** Orca Cloud hosts of another team, or of no team we can resolve: every row hides. */
|
||||
readonly hiddenHostIds?: ReadonlySet<string>
|
||||
}
|
||||
@@ -33,23 +35,61 @@ export type HiddenVmCheckouts = PendingVmCheckoutIndex & {
|
||||
*/
|
||||
export function withOrcaCloudHosts(
|
||||
checkouts: HiddenVmCheckouts,
|
||||
hosts: { primaryHostIds: ReadonlySet<string>; hiddenHostIds: ReadonlySet<string> }
|
||||
hosts: {
|
||||
primaryHostIds: ReadonlySet<string>
|
||||
pairedHostIds?: ReadonlySet<string>
|
||||
hiddenHostIds: ReadonlySet<string>
|
||||
}
|
||||
): HiddenVmCheckouts {
|
||||
return hosts.primaryHostIds.size === 0 && hosts.hiddenHostIds.size === 0
|
||||
const pairedHostIds = hosts.pairedHostIds ?? new Set<string>()
|
||||
return hosts.primaryHostIds.size === 0 &&
|
||||
pairedHostIds.size === 0 &&
|
||||
hosts.hiddenHostIds.size === 0
|
||||
? checkouts
|
||||
: { ...checkouts, primaryHostIds: hosts.primaryHostIds, hiddenHostIds: hosts.hiddenHostIds }
|
||||
: {
|
||||
...checkouts,
|
||||
primaryHostIds: hosts.primaryHostIds,
|
||||
pairedHostIds,
|
||||
hiddenHostIds: hosts.hiddenHostIds
|
||||
}
|
||||
}
|
||||
|
||||
function isHostScoped(checkouts: HiddenVmCheckouts): boolean {
|
||||
return Boolean(
|
||||
checkouts.primaryHostIds?.size || checkouts.pairedHostIds?.size || checkouts.hiddenHostIds?.size
|
||||
)
|
||||
}
|
||||
|
||||
function hidesNothing(checkouts: HiddenVmCheckouts): boolean {
|
||||
return (
|
||||
checkouts.keys.size === 0 && !checkouts.primaryHostIds?.size && !checkouts.hiddenHostIds?.size
|
||||
)
|
||||
return checkouts.keys.size === 0 && !isHostScoped(checkouts)
|
||||
}
|
||||
|
||||
function hostRepoKey(hostId: string, repoId: string): string {
|
||||
return `${hostId}\0${repoId}`
|
||||
}
|
||||
|
||||
/** Paired host+repo pairs that list a linked worktree, whose primary (the base clone) then hides. */
|
||||
function pairedLinkedHostRepos(
|
||||
checkouts: HiddenVmCheckouts,
|
||||
rows: Iterable<{ row: CheckoutRow; hostId: string | undefined }>
|
||||
): ReadonlySet<string> {
|
||||
const linked = new Set<string>()
|
||||
if (!checkouts.pairedHostIds?.size) {
|
||||
return linked
|
||||
}
|
||||
for (const { row, hostId } of rows) {
|
||||
if (hostId && row.isMainWorktree !== true && checkouts.pairedHostIds.has(hostId)) {
|
||||
linked.add(hostRepoKey(hostId, row.repoId))
|
||||
}
|
||||
}
|
||||
return linked
|
||||
}
|
||||
|
||||
function isHiddenCheckout(
|
||||
checkouts: HiddenVmCheckouts,
|
||||
row: CheckoutRow,
|
||||
hostId: string | undefined = row.hostId
|
||||
hostId: string | undefined = row.hostId,
|
||||
pairedLinked: ReadonlySet<string> = new Set()
|
||||
): boolean {
|
||||
if (hostId && checkouts.hiddenHostIds?.has(hostId)) {
|
||||
return true
|
||||
@@ -57,6 +97,9 @@ function isHiddenCheckout(
|
||||
if (row.isMainWorktree === true && hostId && checkouts.primaryHostIds?.has(hostId)) {
|
||||
return true
|
||||
}
|
||||
if (row.isMainWorktree === true && hostId && pairedLinked.has(hostRepoKey(hostId, row.repoId))) {
|
||||
return true
|
||||
}
|
||||
return checkouts.keys.size > 0 && isPendingVmCheckout(checkouts, row)
|
||||
}
|
||||
|
||||
@@ -186,7 +229,13 @@ export function withoutHiddenVmWorktrees<W extends CheckoutRow>(
|
||||
if (hidesNothing(checkouts)) {
|
||||
return worktrees
|
||||
}
|
||||
const kept = worktrees.filter((worktree) => !isHiddenCheckout(checkouts, worktree))
|
||||
const pairedLinked = pairedLinkedHostRepos(
|
||||
checkouts,
|
||||
worktrees.map((row) => ({ row, hostId: row.hostId }))
|
||||
)
|
||||
const kept = worktrees.filter(
|
||||
(worktree) => !isHiddenCheckout(checkouts, worktree, worktree.hostId, pairedLinked)
|
||||
)
|
||||
return kept.length === worktrees.length ? worktrees : kept
|
||||
}
|
||||
|
||||
@@ -198,7 +247,7 @@ export function withoutHiddenVmWorktreesByRepo<W extends CheckoutRow>(
|
||||
if (hidesNothing(checkouts)) {
|
||||
return worktreesByRepo
|
||||
}
|
||||
const hostScoped = Boolean(checkouts.primaryHostIds?.size || checkouts.hiddenHostIds?.size)
|
||||
const hostScoped = isHostScoped(checkouts)
|
||||
let next: Record<string, W[]> | null = null
|
||||
// Host-scoped rows can sit under any repo; pending checkouts only under theirs.
|
||||
const repoIds = hostScoped ? Object.keys(worktreesByRepo) : checkouts.repoIds
|
||||
@@ -221,10 +270,15 @@ function withoutHiddenRows<K extends string, V extends CheckoutRow>(
|
||||
checkouts: HiddenVmCheckouts
|
||||
): ReadonlyMap<K, V> {
|
||||
let kept: Map<K, V> | null = null
|
||||
for (const [key, row] of rows) {
|
||||
// Paired-server rows carry their host only in the host-qualified key.
|
||||
const hostId = row.hostId ?? getExecutionHostIdFromWorktreeHostIdentity(key)
|
||||
if (isHiddenCheckout(checkouts, row, hostId)) {
|
||||
// Paired-server rows carry their host only in the host-qualified key.
|
||||
const hosted = [...rows].map(([key, row]) => ({
|
||||
key,
|
||||
row,
|
||||
hostId: row.hostId ?? getExecutionHostIdFromWorktreeHostIdentity(key)
|
||||
}))
|
||||
const pairedLinked = pairedLinkedHostRepos(checkouts, hosted)
|
||||
for (const { key, row, hostId } of hosted) {
|
||||
if (isHiddenCheckout(checkouts, row, hostId, pairedLinked)) {
|
||||
kept ??= new Map(rows)
|
||||
kept.delete(key)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user