Merge pull request #309 from nwparker/np4-polish/cloud-project-rows

fix(cloud): one row per cloud workspace (hide sandbox clones); scope cloud workspaces to the active team (np4-e2e bugs 6, 7)
This commit is contained in:
Neil
2026-11-10 17:47:07 -08:00
committed by GitHub
32 changed files with 1483 additions and 69 deletions
@@ -22,12 +22,15 @@ import type {
} from './runtime-service'
import { cleanupFailedEphemeralVmStart } from './failed-start-cleanup'
import { renameLegacyOrcaCloudEnvironments } from './legacy-orca-cloud-environment-names'
import { readOrcaCloudActiveAccountId } from '../hosted-sandbox/orca-cloud-active-account'
export type EphemeralVmWriteAhead = {
instanceId: string
createdAt: number
/** Set once the create command's process started; before that no VM can exist. */
launched: boolean
/** Orca Cloud: the team the sandbox is created under, read once so a mid-create switch can't refile it. */
cloudAccountId?: string
}
// Creates owned by this process; any other `provisioning` record was orphaned by a crash or quit.
@@ -41,10 +44,13 @@ export function isEphemeralVmProvisionLive(instanceId: string): boolean {
export function beginEphemeralVmProvisioning(
args: ProvisionEphemeralVmRuntimeArgs
): EphemeralVmWriteAhead {
const cloudAccountId =
args.recipe.provider === 'orca-cloud' ? readOrcaCloudActiveAccountId() : null
const writeAhead: EphemeralVmWriteAhead = {
instanceId: `orca-${randomUUID()}`,
createdAt: args.now ?? Date.now(),
launched: false
launched: false,
...(cloudAccountId ? { cloudAccountId } : {})
}
if (args.recipe.checkoutMode) {
assertEphemeralVmRuntimeCheckoutModeCanPersist(args.userDataPath, {
@@ -214,6 +220,7 @@ function baseRuntimeRecord(
...(args.projectId ? { projectId: args.projectId } : {}),
...(args.workspaceId ? { workspaceId: args.workspaceId } : {}),
...(args.workspaceName ? { workspaceName: args.workspaceName } : {}),
...(writeAhead.cloudAccountId ? { cloudAccountId: writeAhead.cloudAccountId } : {}),
cleanupStatus: args.recipe.destroyDisabled ? 'disabled' : 'not_started',
...(args.recipe.destroyDisabled ? { cleanupDisabled: true } : {}),
createdAt: writeAhead.createdAt
@@ -0,0 +1,104 @@
// Files Orca Cloud runtime records under the team that owns them. The control plane lists only the
// caller's account's sandboxes, so a sandbox in the active team's list belongs to that team. This
// files records written before the team was recorded, and corrects one a create filed under the
// team a switch left behind. Records it can't place stay unfiled, and lists hide them.
import {
listEphemeralVmRuntimes,
updateEphemeralVmRuntimeStatus
} from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import type { HostedSandboxView } from '../../shared/hosted-sandbox/hosted-sandbox-wire'
import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
const RETIRED = new Set<EphemeralVmRuntimeRecord['status']>(['cleaned', 'cleanup_pending'])
function sandboxIdOf(runtime: EphemeralVmRuntimeRecord): string | null {
const handle = runtime.recipeResult
? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID)
: null
const id = handle?.driverState.sandboxId
return typeof id === 'string' && id ? id : null
}
export type CloudAccountBackfill = {
/**
* Lists the active team's sandboxes when a live record is unfiled, the team changed, or the last
* list is older than `relistMs` (the first run, at startup, always lists).
*/
run(): Promise<void>
}
export function createCloudAccountBackfill(deps: {
userDataPath: string
activeAccountId: () => string | null
list: () => Promise<readonly Pick<HostedSandboxView, 'id'>[]>
/** Each successful list, for the team it answered for (the gone-sandbox prune reads it). */
onListed?: (account: string, listed: ReadonlySet<string>) => Promise<void>
/** Re-list this often even when nothing changed, so a sandbox destroyed elsewhere is noticed. */
relistMs?: number
now?: () => number
log?: (line: string) => void
}): CloudAccountBackfill {
const now = deps.now ?? Date.now
// One list per (team, unfiled set) or per relistMs: the 30 s beat must not list on every tick.
let lastKey: string | null = null
let listedAt = Number.NEGATIVE_INFINITY
return {
async run() {
const account = deps.activeAccountId()
if (!account) {
return
}
const before = readCloud(deps.userDataPath)
// A team switch re-lists once even with nothing unfiled: it corrects a misfiled create.
const key = keyOf(account, before)
const stale = deps.relistMs !== undefined && now() - listedAt >= deps.relistMs
if (before.length === 0 || (key === lastKey && !stale)) {
return
}
let listed: ReadonlySet<string>
try {
listed = new Set((await deps.list()).map((sandbox) => sandbox.id))
} catch (error) {
deps.log?.(`[orca-cloud] could not list sandboxes to file them by team: ${String(error)}`)
return
}
// The list answered for whichever team the token was minted for; drop it if that moved.
if (deps.activeAccountId() !== account) {
return
}
for (const runtime of readCloud(deps.userDataPath)) {
const sandboxId = sandboxIdOf(runtime)
if (sandboxId && listed.has(sandboxId) && runtime.cloudAccountId !== account) {
updateEphemeralVmRuntimeStatus(deps.userDataPath, runtime.id, {
cloudAccountId: account,
updatedAt: runtime.updatedAt
})
}
}
// Keyed on what is still unfiled, so this team does not list again until that changes.
lastKey = keyOf(account, readCloud(deps.userDataPath))
listedAt = now()
await deps.onListed?.(account, listed)
}
}
}
/** Live Orca Cloud records with a sandbox to look for. */
function readCloud(userDataPath: string): EphemeralVmRuntimeRecord[] {
return listEphemeralVmRuntimes(userDataPath).filter(
(runtime) =>
runtime.recipe?.provider === 'orca-cloud' &&
!RETIRED.has(runtime.status) &&
sandboxIdOf(runtime) !== null
)
}
function keyOf(account: string, cloud: readonly EphemeralVmRuntimeRecord[]): string {
const unfiled = cloud
.filter((runtime) => !runtime.cloudAccountId)
.map((runtime) => runtime.id)
.sort()
return JSON.stringify([account, unfiled])
}
@@ -0,0 +1,167 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
listEphemeralVmRuntimes,
upsertEphemeralVmRuntime
} from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import {
beginEphemeralVmProvisioning,
endEphemeralVmProvisioning
} from '../ephemeral-vm/runtime-provisioning-persistence'
import { createCloudAccountBackfill } from './cloud-account-backfill'
import { ORCA_CLOUD_RECIPE } from './hosted-sandbox-recipe'
import { setOrcaCloudActiveAccountResolver } from './orca-cloud-active-account'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
const dirs: string[] = []
afterEach(() => {
setOrcaCloudActiveAccountResolver(null)
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function userData(): string {
const dir = mkdtempSync(join(tmpdir(), 'orca-cloud-account-'))
dirs.push(dir)
return dir
}
function cloudRecord(
id: string,
sandboxId: string,
cloudAccountId?: string
): EphemeralVmRuntimeRecord {
return {
id,
recipeId: ORCA_CLOUD_RECIPE.id,
recipe: {
id: ORCA_CLOUD_RECIPE.id,
name: 'Orca Cloud',
create: 'orca-cloud create',
provider: 'orca-cloud'
},
workspaceId: `ws-${id}`,
runtimeEnvironmentId: `env-${id}`,
status: 'running',
cleanupStatus: 'not_started',
createdAt: 1,
updatedAt: 1,
...(cloudAccountId ? { cloudAccountId } : {}),
recipeResult: {
schemaVersion: 1,
connection: {
type: 'orca-server',
pairingCode: 'code',
projectRoot: '/vercel/sandbox/project'
},
userData: {
environmentDriver: {
driverId: HOSTED_SANDBOX_DRIVER_ID,
environmentId: sandboxId,
driverState: { sandboxId }
}
}
}
}
}
function accountOf(path: string, id: string): string | undefined {
return listEphemeralVmRuntimes(path).find((runtime) => runtime.id === id)?.cloudAccountId
}
describe('Orca Cloud team filing at create', () => {
it('records the active team on an Orca Cloud runtime, read once at the write-ahead', () => {
const path = userData()
let team = 'org:team-one'
setOrcaCloudActiveAccountResolver(() => team)
const args = { userDataPath: path, repoPath: '/repo', recipe: ORCA_CLOUD_RECIPE }
const writeAhead = beginEphemeralVmProvisioning(args)
team = 'org:team-two'
expect(accountOf(path, writeAhead.instanceId)).toBe('org:team-one')
expect(writeAhead.cloudAccountId).toBe('org:team-one')
endEphemeralVmProvisioning(args, writeAhead)
})
it('leaves recipe VMs that are not Orca Cloud unfiled', () => {
const path = userData()
setOrcaCloudActiveAccountResolver(() => 'org:team-one')
const recipe = { id: 'vm', name: 'VM', create: 'make-vm' }
const writeAhead = beginEphemeralVmProvisioning({ userDataPath: path, repoPath: '/r', recipe })
expect(accountOf(path, writeAhead.instanceId)).toBeUndefined()
})
})
describe('Orca Cloud team backfill', () => {
it("files unfiled records the active team's list names, and only those", async () => {
const path = userData()
upsertEphemeralVmRuntime(path, cloudRecord('mine', 'sbx-mine'))
upsertEphemeralVmRuntime(path, cloudRecord('other', 'sbx-other'))
const list = vi.fn(async () => [{ id: 'sbx-mine' }])
const backfill = createCloudAccountBackfill({
userDataPath: path,
activeAccountId: () => 'org:team-one',
list
})
await backfill.run()
expect(accountOf(path, 'mine')).toBe('org:team-one')
expect(accountOf(path, 'other')).toBeUndefined()
// Nothing new to file for this team: the beat does not list again.
await backfill.run()
expect(list).toHaveBeenCalledTimes(1)
})
it('re-lists after a team switch and files that team, correcting a misfiled record', async () => {
const path = userData()
upsertEphemeralVmRuntime(path, cloudRecord('mine', 'sbx-mine', 'org:team-one'))
upsertEphemeralVmRuntime(path, cloudRecord('other', 'sbx-other', 'org:team-one'))
let team = 'org:team-one'
const list = vi.fn(async () => (team === 'org:team-two' ? [{ id: 'sbx-other' }] : []))
const backfill = createCloudAccountBackfill({
userDataPath: path,
activeAccountId: () => team,
list
})
await backfill.run()
team = 'org:team-two'
await backfill.run()
expect(list).toHaveBeenCalledTimes(2)
expect(accountOf(path, 'other')).toBe('org:team-two')
expect(accountOf(path, 'mine')).toBe('org:team-one')
})
it('files nothing when the team changed while listing', async () => {
const path = userData()
upsertEphemeralVmRuntime(path, cloudRecord('mine', 'sbx-mine'))
let team = 'org:team-one'
const backfill = createCloudAccountBackfill({
userDataPath: path,
activeAccountId: () => team,
list: async () => {
team = 'org:team-two'
return [{ id: 'sbx-mine' }]
}
})
await backfill.run()
expect(accountOf(path, 'mine')).toBeUndefined()
})
it('does not list when signed out', async () => {
const path = userData()
upsertEphemeralVmRuntime(path, cloudRecord('mine', 'sbx-mine'))
const list = vi.fn(async () => [])
await createCloudAccountBackfill({
userDataPath: path,
activeAccountId: () => null,
list
}).run()
expect(list).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,185 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { upsertEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver'
import { createCloudAccountBackfill } from './cloud-account-backfill'
import { createCloudSandboxGonePrune } from './cloud-sandbox-gone-prune'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
const TEAM = 'org:team-one'
function record(
id: string,
overrides: Partial<EphemeralVmRuntimeRecord> = {}
): EphemeralVmRuntimeRecord {
return {
id,
recipeId: 'orca-cloud',
recipe: { id: 'orca-cloud', name: 'Orca Cloud', create: 'c', provider: 'orca-cloud' },
workspaceId: `ws-${id}`,
runtimeEnvironmentId: `env-${id}`,
status: 'running',
cleanupStatus: 'not_started',
createdAt: 1,
updatedAt: 1,
cloudAccountId: TEAM,
recipeResult: {
schemaVersion: 1,
connection: { type: 'orca-server', pairingCode: 'code', projectRoot: '/p' },
userData: {
environmentDriver: {
driverId: HOSTED_SANDBOX_DRIVER_ID,
environmentId: `sbx-${id}`,
driverState: { sandboxId: `sbx-${id}` }
}
}
},
...overrides
}
}
function setup(
records: EphemeralVmRuntimeRecord[],
get: (id: string) => Promise<{ status: string }>
) {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-gone-prune-'))
dirs.push(userDataPath)
records.forEach((entry) => upsertEphemeralVmRuntime(userDataPath, entry))
let team: string | null = TEAM
const retired: string[] = []
const prune = createCloudSandboxGonePrune({
userDataPath,
activeAccountId: () => team,
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the prune reads only status.
get: get as never,
retire: async (runtime) => void retired.push(runtime.id)
})
return {
prune,
retired,
userDataPath,
switchTeam: (next: string | null) => {
team = next
}
}
}
const notFound = async (): Promise<never> => {
throw new EnvironmentProviderError('not_found', 'no such sandbox')
}
const offline = async (): Promise<never> => {
throw new EnvironmentProviderError('unavailable', 'offline')
}
describe('Orca Cloud gone-sandbox prune', () => {
it('retires a sandbox missing from the list once its own read says not found', async () => {
const h = setup([record('cusk'), record('crayfish')], notFound)
await h.prune.observeList(TEAM, new Set(['sbx-crayfish']))
expect(h.retired).toEqual(['cusk'])
})
it('retires on a destroyed answer, or on a second consecutive list without it', async () => {
const destroyed = setup([record('cusk')], async () => ({ status: 'destroyed' }))
await destroyed.prune.observeList(TEAM, new Set())
expect(destroyed.retired).toEqual(['cusk'])
const twice = setup([record('cusk')], offline)
await twice.prune.observeList(TEAM, new Set())
expect(twice.retired).toEqual([])
await twice.prune.observeList(TEAM, new Set())
expect(twice.retired).toEqual(['cusk'])
})
it('keeps it through a network blip: one miss plus an unreadable sandbox is not proof', async () => {
const h = setup([record('cusk')], offline)
await h.prune.observeList(TEAM, new Set())
// Listed again: the miss streak resets, so a later single miss is not a second one.
await h.prune.observeList(TEAM, new Set(['sbx-cusk']))
await h.prune.observeList(TEAM, new Set())
expect(h.retired).toEqual([])
})
it('keeps a sandbox still being created, which the list may not show yet', async () => {
const h = setup([record('cusk', { status: 'provisioning' })], notFound)
await h.prune.observeList(TEAM, new Set())
await h.prune.observeList(TEAM, new Set())
expect(h.retired).toEqual([])
})
it("keeps another team's sandbox, and one whose team is unknown", async () => {
const h = setup(
[
record('otter', { cloudAccountId: 'org:team-two' }),
record('legacy', { cloudAccountId: undefined })
],
notFound
)
await h.prune.observeList(TEAM, new Set())
await h.prune.observeList(TEAM, new Set())
expect(h.retired).toEqual([])
})
it('never retires an asleep (suspended or archived) sandbox the team still lists', async () => {
const get = vi.fn(async () => ({ status: 'suspended' }))
const h = setup([record('asleep', { status: 'suspended' }), record('archived')], get)
for (let round = 0; round < 3; round++) {
await h.prune.observeList(TEAM, new Set(['sbx-asleep', 'sbx-archived']))
}
expect(h.retired).toEqual([])
expect(get).not.toHaveBeenCalled()
})
it('drops the confirmation when the team switched while it was read', async () => {
const h = setup([record('cusk')], async () => {
h.switchTeam('org:team-two')
throw new EnvironmentProviderError('not_found', 'gone')
})
await h.prune.observeList(TEAM, new Set())
expect(h.retired).toEqual([])
})
})
describe('Orca Cloud list reconcile', () => {
it('reconciles at startup and on each re-list, but never on a failed list', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-gone-reconcile-'))
dirs.push(userDataPath)
upsertEphemeralVmRuntime(userDataPath, record('cusk'))
let clock = 0
let fail = true
const onListed = vi.fn(async () => {})
const backfill = createCloudAccountBackfill({
userDataPath,
activeAccountId: () => TEAM,
list: async () => {
if (fail) {
throw new EnvironmentProviderError('unavailable', 'offline')
}
return []
},
onListed,
relistMs: 1_000,
now: () => clock
})
await backfill.run()
expect(onListed).not.toHaveBeenCalled()
fail = false
await backfill.run()
expect(onListed).toHaveBeenCalledTimes(1)
await backfill.run()
expect(onListed).toHaveBeenCalledTimes(1)
clock = 1_000
await backfill.run()
expect(onListed).toHaveBeenCalledTimes(2)
})
})
@@ -0,0 +1,82 @@
// Retires Orca Cloud records whose sandbox no longer exists. A sandbox destroyed out of band (the
// team list's Delete on another desktop, the control plane) left its record, server and project
// here, and after a restart its clone came back as a stray folder project with a "Couldn't start"
// row. Only an authoritative answer retires one: missing from the active team's successful list,
// then confirmed by a second such list or by the sandbox itself answering not found or destroyed.
// Errors, a team switch mid-check, and asleep (suspended/archived, still listed) sandboxes never do.
import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import type { HostedSandboxView } from '../../shared/hosted-sandbox/hosted-sandbox-wire'
import { isEnvironmentProviderError } from '../environment-providers/environment-provider-driver'
import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter'
import { isEphemeralVmProvisionLive } from '../ephemeral-vm/runtime-provisioning-persistence'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
const RETIRED = new Set<EphemeralVmRuntimeRecord['status']>(['cleaned', 'cleanup_pending'])
function sandboxIdOf(runtime: EphemeralVmRuntimeRecord): string | null {
const handle = runtime.recipeResult
? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID)
: null
const id = handle?.driverState.sandboxId
return typeof id === 'string' && id ? id : null
}
export type CloudSandboxGonePrune = {
/** After a successful list of `account`'s sandboxes: retire that team's records it confirms gone. */
observeList(account: string, listed: ReadonlySet<string>): Promise<void>
}
export function createCloudSandboxGonePrune(deps: {
userDataPath: string
activeAccountId: () => string | null
get: (sandboxId: string) => Promise<Pick<HostedSandboxView, 'status'>>
/** The app's own teardown for a destroyed cloud workspace: record, server, project. */
retire: (runtime: EphemeralVmRuntimeRecord) => Promise<void>
log?: (line: string) => void
}): CloudSandboxGonePrune {
// Sandboxes one list has missed; a second miss in a row confirms them.
let missedOnce = new Set<string>()
/** True only on a definite answer that the sandbox is gone; any error is "don't know". */
async function confirmedGone(sandboxId: string): Promise<boolean> {
try {
return (await deps.get(sandboxId)).status === 'destroyed'
} catch (error) {
return isEnvironmentProviderError(error, 'not_found')
}
}
return {
async observeList(account, listed) {
const missing = listEphemeralVmRuntimes(deps.userDataPath).flatMap((runtime) => {
const sandboxId = runtime.recipe?.provider === 'orca-cloud' ? sandboxIdOf(runtime) : null
// A create in flight is not listed yet; its own outcome settles the record.
const creating = runtime.status === 'provisioning' || isEphemeralVmProvisionLive(runtime.id)
return sandboxId &&
runtime.cloudAccountId === account &&
!RETIRED.has(runtime.status) &&
!creating &&
!listed.has(sandboxId)
? [{ runtime, sandboxId }]
: []
})
const previous = missedOnce
missedOnce = new Set(missing.map(({ sandboxId }) => sandboxId))
for (const { runtime, sandboxId } of missing) {
const gone = previous.has(sandboxId) || (await confirmedGone(sandboxId))
// The confirming answer must still be for the team this list was for.
if (!gone || deps.activeAccountId() !== account) {
continue
}
try {
await deps.retire(runtime)
missedOnce.delete(sandboxId)
deps.log?.(`[orca-cloud] retired ${runtime.workspaceName ?? runtime.id}: sandbox is gone`)
} catch (error) {
deps.log?.(`[orca-cloud] could not retire a gone sandbox's records: ${String(error)}`)
}
}
}
}
}
@@ -0,0 +1,53 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
listEphemeralVmRuntimes,
upsertEphemeralVmRuntime
} from '../../shared/ephemeral-vm-runtime-store'
const sent = vi.hoisted((): string[] => [])
vi.mock('electron', () => ({
app: { getPath: () => tmpdir() },
BrowserWindow: {
getAllWindows: () => [
{ isDestroyed: () => false, webContents: { send: (channel: string) => sent.push(channel) } }
]
}
}))
const { retireGoneCloudSandbox } = await import('./cloud-sandbox-gone-retire')
const dirs: string[] = []
afterEach(() => {
sent.splice(0)
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
describe('retireGoneCloudSandbox', () => {
it('cleans the record and asks the window to refresh its servers, which purges the project', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-gone-retire-'))
dirs.push(userDataPath)
const runtime = upsertEphemeralVmRuntime(userDataPath, {
id: 'cusk',
recipeId: 'orca-cloud',
recipe: { id: 'orca-cloud', name: 'Orca Cloud', create: 'c', provider: 'orca-cloud' },
runtimeEnvironmentId: 'env-cusk',
status: 'resume_failed',
cleanupStatus: 'not_started',
createdAt: 1,
updatedAt: 1
})
await retireGoneCloudSandbox(userDataPath, undefined, runtime)
expect(listEphemeralVmRuntimes(userDataPath)[0]).toMatchObject({
status: 'cleaned',
cleanupStatus: 'succeeded'
})
expect(sent).toEqual(['runtimeEnvironments:catalogChanged'])
})
})
@@ -0,0 +1,38 @@
import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import { releaseEphemeralVmRuntimeEnvironments } from '../ephemeral-vm/runtime-environment-release'
import {
retireRemovedRuntimeEnvironment,
type RemovedServerStore
} from '../ipc/runtime-environments/runtime-environment-removal-cleanup'
import { invalidateRuntimeEnvironmentTransport } from '../ipc/runtime-environments/runtime-environments'
import { publishRuntimeEnvironmentCatalogChanged } from '../ipc/runtime-environments/runtime-environment-catalog-broadcast'
/**
* A sandbox destroyed out of band goes the way the app's own delete takes a destroyed one
* (cleanupOwnedEphemeralVmRuntime after its destroy): the record is cleaned and its server
* retired. The window's catalog refresh then purges that host's project and setup, so its clone
* can never come back as a folder project.
*/
export async function retireGoneCloudSandbox(
userDataPath: string,
store: RemovedServerStore | undefined,
runtime: EphemeralVmRuntimeRecord
): Promise<void> {
updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, {
status: 'cleaned',
cleanupStatus: 'succeeded',
cleanupLastError: null
})
await releaseEphemeralVmRuntimeEnvironments(userDataPath, runtime, (environmentId) => {
if (store) {
void retireRemovedRuntimeEnvironment(
environmentId,
invalidateRuntimeEnvironmentTransport,
store,
userDataPath
)
}
})
publishRuntimeEnvironmentCatalogChanged()
}
@@ -35,6 +35,12 @@ import {
import { createHostedSessionRegistry, type HostedSessionRegistry } from './hosted-session-registry'
import { registerCloudShareHandlers } from './hosted-sandbox-share-ipc'
import { setHostedSessionSync } from './hosted-session-sync'
import { orcaCloudAccountId } from '../../shared/hosted-sandbox/orca-cloud-account'
import { setOrcaCloudActiveAccountResolver } from './orca-cloud-active-account'
import { createCloudAccountBackfill } from './cloud-account-backfill'
import { createCloudSandboxGonePrune } from './cloud-sandbox-gone-prune'
import { retireGoneCloudSandbox } from './cloud-sandbox-gone-retire'
import type { RemovedServerStore } from '../ipc/runtime-environments/runtime-environment-removal-cleanup'
import { createUsageAlertRefreshScheduler } from '../billing/usage-alert-refresh'
import { sendToTrustedUIRenderer } from '../ipc/ui'
import { ORCA_BILLING_REFRESH_CHANNEL } from '../../shared/orca-billing'
@@ -68,7 +74,9 @@ export function getHostedSandboxControlPlaneClient(): HostedSandboxControlPlaneC
}
/** `repos` is main's repo store: org-environment repo imports only read checkouts listed there. */
export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): void {
export function installHostedSandbox(
repos?: OrcaCloudEnvironmentRepoSource & RemovedServerStore
): void {
// Idempotent; answers isConfigured() = false itself when this build has no control plane.
registerOrcaCloudEnvironmentHandlers(repos ? { repos } : {})
if (installed) {
@@ -92,6 +100,23 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
const client = createHostedSandboxRecipeClient(config)
const base = createHostedSandboxRecipeDriver(config, client)
controlPlaneClient = client
// The team the sandbox token is minted for; creates are filed under it and lists scope to it.
const activeAccountId = (): string | null =>
orcaCloudAccountId(ensureActiveOrcaProfile(userDataPath).profile.cloud)
setOrcaCloudActiveAccountResolver(activeAccountId)
const gonePrune = createCloudSandboxGonePrune({
userDataPath,
activeAccountId,
get: (sandboxId) => client.get(sandboxId),
retire: (runtime) => retireGoneCloudSandbox(userDataPath, repos, runtime)
})
const accountBackfill = createCloudAccountBackfill({
userDataPath,
activeAccountId,
list: () => client.list(),
onListed: (account, listed) => gonePrune.observeList(account, listed),
relistMs: 10 * 60_000
})
const mcpSync = installCloudMcpSync(userDataPath, {
baseUrl: config.controlPlaneUrl,
getAccessToken: config.getAccessToken
@@ -123,8 +148,11 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
driver,
windows: () => BrowserWindow.getAllWindows(),
onConnected: (runtimeEnvironmentId) => void mcpSync.sync(runtimeEnvironmentId, 'connect'),
onRunningChange: (anyRunning) => usageRefresh.setRunning(anyRunning)
onRunningChange: (anyRunning) => usageRefresh.setRunning(anyRunning),
activeAccountId
})
// Filing first, so a sandbox that just joined the active team gets its scheduler in this pass.
const syncSessions = (): Promise<void> => accountBackfill.run().finally(() => registry.sync())
const workspaces = installHostedWorkspaceService({
userDataPath,
// Every status read also carries the control plane's idle-sleep minutes.
@@ -149,7 +177,8 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
},
windows: () => BrowserWindow.getAllWindows(),
syncSessions: () => void registry.sync(),
stopSession: (environmentId) => registry.stopEnvironment(environmentId)
stopSession: (environmentId) => registry.stopEnvironment(environmentId),
activeAccountId
})
setHostedWorkspaceService(workspaces)
const disposeTransfer = installCloudTransferHandlers({
@@ -183,7 +212,7 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
beat = setTimeout(() => {
// OOM in the guest is checked every other beat (~1 min) for running cloud workspaces.
const oom = beats++ % 2 === 1 ? workspaces.pollOom() : Promise.resolve()
void Promise.all([registry.sync(), oom]).finally(() => schedule(30_000))
void Promise.all([syncSessions(), oom]).finally(() => schedule(30_000))
}, ms)
beat.unref?.()
}
@@ -207,7 +236,8 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
installed = { registry }
registerCloudRemoteDesktopHandlers(client)
registerOrcaCloudDeviceEnroller(createHostedSandboxDeviceEnroller(config))
setHostedSessionSync(() => void registry.sync())
// Also the team-switch nudge: the old team's schedulers stop and the new team's records file.
setHostedSessionSync(() => void syncSessions())
schedule(0)
app.once('will-quit', () => {
if (beat) {
@@ -220,6 +250,7 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
setHostedWorkspaceService(null)
setCloudArchiveCheck(null)
setCloudAsleepCheck(null)
setOrcaCloudActiveAccountResolver(null)
offline.dispose()
setCloudOfflineService(null)
})
@@ -0,0 +1,86 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { upsertEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import type { HostedEnvironmentProviderDriver } from './hosted-environment-provider'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
import { createHostedSessionRegistry } from './hosted-session-registry'
vi.mock('electron', () => ({ app: { getPath: () => tmpdir() }, ipcMain: {}, BrowserWindow: {} }))
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function record(id: string, cloudAccountId?: string): EphemeralVmRuntimeRecord {
return {
id,
recipeId: 'orca-cloud',
recipe: { id: 'orca-cloud', name: 'Orca Cloud', create: 'c', provider: 'orca-cloud' },
workspaceId: `ws-${id}`,
runtimeEnvironmentId: `env-${id}`,
status: 'running',
cleanupStatus: 'not_started',
createdAt: 1,
updatedAt: 1,
...(cloudAccountId ? { cloudAccountId } : {}),
recipeResult: {
schemaVersion: 1,
connection: { type: 'orca-server', pairingCode: 'code', projectRoot: '/p' },
userData: {
environmentDriver: {
driverId: HOSTED_SANDBOX_DRIVER_ID,
environmentId: `sbx-${id}`,
driverState: { sandboxId: `sbx-${id}` }
}
}
}
}
}
describe('hosted session registry team scope', () => {
it("keeps only the active team's sandboxes alive; other and unfiled teams get no calls", async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-registry-team-'))
dirs.push(userDataPath)
upsertEphemeralVmRuntime(userDataPath, record('mine', 'org:team-one'))
upsertEphemeralVmRuntime(userDataPath, record('other', 'org:team-two'))
upsertEphemeralVmRuntime(userDataPath, record('unfiled'))
// A stopped answer ends start() before any scheduler or orcad call.
const status = vi.fn(async (_handle: { environmentId: string }) => ({
status: 'stopped',
session: null
}))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: sync reads only status().
const driver = { status, capabilities: {} } as unknown as HostedEnvironmentProviderDriver
let team = 'org:team-one'
const running: boolean[] = []
const registry = createHostedSessionRegistry({
userDataPath,
driver,
windows: () => [],
log: () => {},
onRunningChange: (anyRunning) => running.push(anyRunning),
activeAccountId: () => team
})
await registry.sync()
expect(status.mock.calls.map(([handle]) => handle.environmentId)).toEqual(['sbx-mine'])
team = 'org:team-two'
status.mockClear()
await registry.sync()
expect(status.mock.calls.map(([handle]) => handle.environmentId)).toEqual(['sbx-other'])
status.mockClear()
team = 'org:team-three'
await registry.sync()
expect(status).not.toHaveBeenCalled()
expect(running).toEqual([true, true, false])
registry.dispose()
})
})
@@ -27,6 +27,7 @@ import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
import { createHostedRuntimeEnvironmentCall } from './hosted-runtime-environment-call'
import type { HostedActivitySample } from './hosted-session-lease-policy'
import { HostedSessionLeaseScheduler } from './hosted-session-lease-scheduler'
import { isOrcaCloudRuntimeInAccount } from '../../shared/hosted-sandbox/orca-cloud-account'
import { noteIdleSleepRequested } from './idle-sleep-requests'
import { cloudSshActiveAt } from '../cloud-ssh/cloud-ssh-activity'
import { getRuntimePortForwardManager } from '../runtime-port-forward/runtime-port-forward-manager'
@@ -64,6 +65,11 @@ export function createHostedSessionRegistry(deps: {
onConnected?: (runtimeEnvironmentId: string) => void
/** After each sync: whether any Orca Cloud workspace is recorded running. */
onRunningChange?: (anyRunning: boolean) => void
/**
* The active team (sandbox-control account). Another team's sandbox, or one not yet filed under
* a team, gets no scheduler: its lease, wake and orcad calls would only fail under this team.
*/
activeAccountId?: () => string | null
}): HostedSessionRegistry {
const running = new Map<string, Running>()
const log = deps.log ?? ((line: string) => console.error(line))
@@ -193,11 +199,13 @@ export function createHostedSessionRegistry(deps: {
return {
async sync() {
const live = new Set<string>()
const account = deps.activeAccountId ? deps.activeAccountId() : undefined
for (const runtime of listEphemeralVmRuntimes(deps.userDataPath)) {
if (
runtime.recipe?.provider !== 'orca-cloud' ||
runtime.status !== 'running' ||
!runtime.recipeResult
!runtime.recipeResult ||
(account !== undefined && !isOrcaCloudRuntimeInAccount(runtime, account))
) {
continue
}
@@ -0,0 +1,82 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { upsertEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver'
import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client'
const handlers = vi.hoisted(() => new Map<string, (...args: unknown[]) => unknown>())
vi.mock('electron', () => ({
app: { getPath: () => tmpdir() },
BrowserWindow: {},
ipcMain: {
handle: (channel: string, handler: (...args: unknown[]) => unknown) =>
handlers.set(channel, handler),
removeHandler: (channel: string) => handlers.delete(channel)
}
}))
const { installHostedWorkspaceService } = await import('./hosted-workspace-service')
const dirs: string[] = []
afterEach(() => {
handlers.clear()
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function record(id: string, cloudAccountId?: string): EphemeralVmRuntimeRecord {
return {
id,
recipeId: 'orca-cloud',
recipe: { id: 'orca-cloud', name: 'Orca Cloud', create: 'c', provider: 'orca-cloud' },
workspaceId: `ws-${id}`,
runtimeEnvironmentId: `env-${id}`,
status: 'running',
cleanupStatus: 'not_started',
createdAt: 1,
updatedAt: 1,
...(cloudAccountId ? { cloudAccountId } : {}),
recipeResult: {
schemaVersion: 1,
connection: { type: 'orca-server', pairingCode: 'code', projectRoot: '/p' },
userData: {
environmentDriver: {
driverId: HOSTED_SANDBOX_DRIVER_ID,
environmentId: `sbx-${id}`,
driverState: { sandboxId: `sbx-${id}` }
}
}
}
}
}
describe('hosted workspace service team scope', () => {
it("polls and lists only the active team's cloud workspaces", async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-workspace-team-'))
dirs.push(userDataPath)
upsertEphemeralVmRuntime(userDataPath, record('mine', 'org:team-one'))
upsertEphemeralVmRuntime(userDataPath, record('other', 'org:team-two'))
upsertEphemeralVmRuntime(userDataPath, record('unfiled'))
const workspaceStatus = vi.fn(async (_sandboxId: string) => ({ status: { metrics: null } }))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: pollOom reads only workspaceStatus().
const client = { workspaceStatus } as unknown as HostedSandboxControlPlaneClient
const service = installHostedWorkspaceService({
userDataPath,
client,
windows: () => [],
syncSessions: () => {},
stopSession: () => {},
log: () => {},
activeAccountId: () => 'org:team-one'
})
await service.pollOom()
expect(workspaceStatus.mock.calls.map(([sandboxId]) => sandboxId)).toEqual(['sbx-mine'])
const listIds = handlers.get('orcaCloudWorkspace:listIds')
expect(await listIds?.()).toEqual(['ws-mine'])
})
})
@@ -2,11 +2,9 @@
// progress and OOM notices. Maps the renderer's workspace id to its Orca Cloud runtime record.
import { failQueuedCloudPrompts } from './cloud-offline-seam'
import { ipcMain, type BrowserWindow } from 'electron'
import { listTeamCloudRuntimes } from './orca-cloud-active-account'
import { HOSTED_ACCOUNT_CHANNELS, registerHostedAccountHandlers } from './hosted-account-ipc'
import {
listEphemeralVmRuntimes,
updateEphemeralVmRuntimeStatus
} from '../../shared/ephemeral-vm-runtime-store'
import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store'
import {
ORCA_CLOUD_WORKSPACE_CHANNELS as CH,
type CloudWakeProgressEvent,
@@ -61,8 +59,13 @@ export function installHostedWorkspaceService(deps: {
/** Stop the lease scheduler of one environment (its session is about to be replaced). */
stopSession: (environmentId: string) => void
log?: (line: string) => void
/** The active team; OOM polling and the window's cloud ids skip every other team's sandbox. */
activeAccountId?: () => string | null
}): HostedWorkspaceService {
const log = deps.log ?? ((line: string) => console.error(line))
// Records this service reads on its own (not per a window's request) stay in the active team.
const activeCloudRuntimes = () =>
listTeamCloudRuntimes(deps.userDataPath, deps.activeAccountId?.())
const wakeSources = new Map<string, CloudWakeSource>()
// Wakes in flight per workspace, so every phase carries the source the first one named.
const wakes = new Map<string, { source: CloudWakeSource; startedAt: number }>()
@@ -135,22 +138,13 @@ export function installHostedWorkspaceService(deps: {
},
async pollOom() {
const live = new Set(
listEphemeralVmRuntimes(deps.userDataPath)
.filter(
(runtime) =>
runtime.recipe?.provider === 'orca-cloud' &&
runtime.status === 'running' &&
runtime.workspaceId
)
activeCloudRuntimes()
.filter((runtime) => runtime.status === 'running' && runtime.workspaceId)
.map((runtime) => findCloudRuntime(deps.userDataPath, runtime.workspaceId!)?.sandboxId)
)
oom.prune(live)
for (const runtime of listEphemeralVmRuntimes(deps.userDataPath)) {
if (
runtime.recipe?.provider !== 'orca-cloud' ||
runtime.status !== 'running' ||
!runtime.workspaceId
) {
for (const runtime of activeCloudRuntimes()) {
if (runtime.status !== 'running' || !runtime.workspaceId) {
continue
}
const found = findCloudRuntime(deps.userDataPath, runtime.workspaceId)
@@ -182,8 +176,8 @@ export function installHostedWorkspaceService(deps: {
service.dispose()
ipcMain.handle(CH.listCloudWorkspaceIds, () =>
listEphemeralVmRuntimes(deps.userDataPath)
.filter((runtime) => runtime.recipe?.provider === 'orca-cloud' && runtime.workspaceId)
activeCloudRuntimes()
.filter((runtime) => runtime.workspaceId)
.map((runtime) => runtime.workspaceId!)
)
@@ -0,0 +1,36 @@
import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store'
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import { isOrcaCloudRuntimeInAccount } from '../../shared/hosted-sandbox/orca-cloud-account'
// The Orca Cloud account (team) this desktop acts for right now, in sandbox-control's form. Set by
// the hosted-sandbox install; builds without Orca Cloud have no resolver and no cloud records.
let resolver: (() => string | null) | null = null
export function setOrcaCloudActiveAccountResolver(next: (() => string | null) | null): void {
resolver = next
}
/** Null when signed out of Orca Cloud or when this build has no Orca Cloud. */
export function readOrcaCloudActiveAccountId(): string | null {
try {
return resolver?.() ?? null
} catch {
// An unreadable profile index is "no team", which hides cloud records rather than misfiling them.
return null
}
}
/**
* Orca Cloud records in the given team; `undefined` (no team scoping wired) keeps them all, while
* null (signed out) keeps none.
*/
export function listTeamCloudRuntimes(
userDataPath: string,
account: string | null | undefined
): EphemeralVmRuntimeRecord[] {
return listEphemeralVmRuntimes(userDataPath).filter(
(runtime) =>
runtime.recipe?.provider === 'orca-cloud' &&
(account === undefined || isOrcaCloudRuntimeInAccount(runtime, account))
)
}
@@ -5,7 +5,8 @@ import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hi
export function withTailscaleHintForResponse<TResult>(
response: RuntimeRpcResponse<TResult>,
endpoint: string,
environment: Pick<KnownRuntimeEnvironment, 'orcadDeployment' | 'sshAccess'>
environment: Pick<KnownRuntimeEnvironment, 'orcadDeployment' | 'sshAccess'> &
Partial<Pick<KnownRuntimeEnvironment, 'name' | 'source'>>
): RuntimeRpcResponse<TResult> {
if (response.ok === true) {
return response
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint'
const FAILURE = 'Could not connect to the remote Orca runtime: socket closed.'
const ENDPOINT = 'wss://203.0.113.7:6768'
describe('withRuntimeUnreachableHint', () => {
it('hints Tailscale for a paired server on another network', () => {
expect(
withRuntimeUnreachableHint({ name: 'desk', source: 'manual' }, FAILURE, ENDPOINT)
).toMatch(/Tailscale/)
})
it('leaves an Orca Cloud sandbox failure without a Tailscale hint', () => {
const cloud = {
name: 'orca-sandbox-push-test sandbox 1a2b3c4d',
source: 'ephemeral-vm' as const
}
expect(withRuntimeUnreachableHint(cloud, FAILURE, ENDPOINT)).toBe(FAILURE)
})
})
@@ -1,15 +1,22 @@
import { withRemoteRuntimeTailscaleHint } from '../../../shared/remote-runtime/remote-runtime-tailscale-hint'
import { classifyRuntimeEnvironmentHost } from '../../../shared/remote-runtime/host-catalog/runtime-environment-host-kind'
import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments'
import { isOrcaCloudRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name'
const UNREACHABLE_RE =
/could not connect to the remote orca runtime|remote orca runtime closed the connection|timed out (?:waiting for|while connecting to) the remote orca runtime/i
export function withRuntimeUnreachableHint(
environment: Pick<KnownRuntimeEnvironment, 'orcadDeployment' | 'sshAccess'>,
environment: Pick<KnownRuntimeEnvironment, 'orcadDeployment' | 'sshAccess'> &
Partial<Pick<KnownRuntimeEnvironment, 'name' | 'source'>>,
message: string,
endpoint: string | null | undefined
): string {
// Orca Cloud sandboxes are reached through Orca Cloud, not the user's network: one that does not
// answer is asleep, gone, or another team's, and a Tailscale hint sends the user the wrong way.
if (isOrcaCloudRuntimeEnvironment(environment)) {
return message
}
const host = classifyRuntimeEnvironmentHost(environment)
switch (host.kind) {
case 'network':
@@ -29,6 +29,7 @@ import {
import { isRecoveryReloadInFlight } from './main-window-lifecycle-flags'
import { RELAY_HOST_CLOSE_REASON } from '../../shared/relay-host-close-reason'
import { holdLaunchReconnectOptOuts } from '../ipc/ssh/ssh-host-user-disconnect'
import { syncHostedSessions } from '../hosted-sandbox/hosted-session-sync'
export function attachMainWindowCoreServices(
window: BrowserWindow,
@@ -118,6 +119,8 @@ export function attachMainWindowCoreServices(
void state.desktopRelayInstaller?.authChanged()
state.desktopRelayService?.authMutated()
desktopConnectorCloud()?.accountChanged()
// A team switch moves Orca Cloud to another account: stop keeping the old team's sandboxes alive.
syncHostedSessions()
},
// Only sign-out fences paired phones; reasonless quit/relaunch must not look like logout.
onBeforeOrcaProfileSignOut: () => {
@@ -9,6 +9,7 @@ import {
} from '@/store/slices/worktrees/listing/use-worktree-catalog'
import { useProjectHostSetupProjection } from '@/store/projects/use-project-host-setup-projection'
import { useRepoMap } from '@/store/repos/use-repository-catalog'
import { useSidebarScopedRepos } from '@/lib/orca-cloud/use-sidebar-hidden-checkouts'
import type { ProjectGroup } from '../../../../../../shared/project-group-types'
import type { Repo } from '../../../../../../shared/repo-types'
import { openHeaderCreateComposer } from '../rows/header-create-workspace-target'
@@ -86,7 +87,8 @@ const WorktreeList = React.memo(function WorktreeList({
const allWorktrees = useAllWorktrees()
const repoMap = useRepoMap()
const worktreeMap = useWorktreeMap()
const repos = useAppStore((s) => s.repos)
// Another team's sandbox projects never get a header (or an empty-project placeholder).
const repos = useSidebarScopedRepos()
const worktreeLineageById = useAppStore((s) => s.worktreeLineageById)
const workspaceLineageByChildKey = useAppStore((s) => s.workspaceLineageByChildKey)
const crossStoreChildrenByFolderId = useAppStore(selectCrossStoreFolderChildrenById)
@@ -9,11 +9,8 @@ import {
} from '@/lib/sidebar-pending-layer'
import { useSidebarListSession } from '@/lib/sidebar-list-session'
import { readEndedCreations, subscribeEndedCreations } from '@/lib/sidebar-ended-creations'
import {
readHiddenVmCheckouts,
subscribeHiddenVmCheckouts,
withoutHiddenVmCheckouts
} from '@/lib/vm-create-hidden-checkouts'
import { withoutHiddenVmCheckouts } from '@/lib/vm-create-hidden-checkouts'
import { useSidebarHiddenCheckouts } from '@/lib/orca-cloud/use-sidebar-hidden-checkouts'
import '../../../../../../shared/folder-workspaces/folder-workspace-execution-host'
import { getFolderWorkspaceHostId } from '../../../../../../shared/folder-workspaces/folder-workspace-host-id'
import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types'
@@ -78,7 +75,7 @@ export function useMainSidebarListModel(args: SidebarListModelArgs): SidebarList
const feed = useDesktopSidebarFeed()
const pending = useSyncExternalStore(subscribeSidebarPendingLayer, readSidebarPendingLayer)
const endedCreationIds = useSyncExternalStore(subscribeEndedCreations, readEndedCreations)
const hiddenVmCheckouts = useSyncExternalStore(subscribeHiddenVmCheckouts, readHiddenVmCheckouts)
const hiddenVmCheckouts = useSidebarHiddenCheckouts()
const pendingCreationKeys = useAppStore(
useShallow((s) => selectPendingWorktreeCreationKeys(s.pendingWorktreeCreations))
)
@@ -1,5 +1,5 @@
import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents'
import { useMemo, useState, useSyncExternalStore } from 'react'
import { useMemo, useState } from 'react'
import { shallow } from 'zustand/shallow'
import type { AppState } from '@/store/types'
import { useAppStore } from '@/store'
@@ -24,11 +24,8 @@ import type { SidebarWorktreeFilters } from './use-filters'
import { useReusedArrayIdentity } from './use-reused-array-identity'
import { useSleepingSweepRetention } from './use-sleeping-sweep-retention'
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
import {
readHiddenVmCheckouts,
subscribeHiddenVmCheckouts,
withoutHiddenVmWorktrees
} from '@/lib/vm-create-hidden-checkouts'
import { withoutHiddenVmWorktrees } from '@/lib/vm-create-hidden-checkouts'
import { useSidebarHiddenCheckouts } from '@/lib/orca-cloud/use-sidebar-hidden-checkouts'
const EMPTY_WORKTREE_ID_SET: ReadonlySet<string> = new Set()
@@ -123,7 +120,7 @@ export function useVisibleSidebarWorktrees(args: {
worktreeIdsWithStructuredChat
})
const hiddenVmCheckouts = useSyncExternalStore(subscribeHiddenVmCheckouts, readHiddenVmCheckouts)
const hiddenVmCheckouts = useSidebarHiddenCheckouts()
const recomputedVisibleWorktrees = useMemo(() => {
const visible = computeVisibleWorktrees(worktreesByRepo, sortedIds, {
filterRepoIds,
@@ -1,4 +1,4 @@
import { useMemo, useSyncExternalStore } from 'react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useShallow } from 'zustand/react/shallow'
import { useAppStore } from '@/store/index'
@@ -6,11 +6,11 @@ import { usePluginCommands } from '@/store/plugins/catalog/plugin-contribution-c
import { usePluginNewFiles } from '@/store/plugins/file-creation/plugin-new-files'
import { useSettingsNavigationMetadata } from '@/hooks/useSettingsNavigationMetadata'
import { dedupePaletteWorktrees } from '@/lib/workspace/search/palette-repo-resolution'
import { withoutHiddenVmWorktreesByRepo } from '@/lib/vm-create-hidden-checkouts'
import {
readHiddenVmCheckouts,
subscribeHiddenVmCheckouts,
withoutHiddenVmWorktreesByRepo
} from '@/lib/vm-create-hidden-checkouts'
useSidebarHiddenCheckouts,
withoutHiddenHostRepos
} from '@/lib/orca-cloud/use-sidebar-hidden-checkouts'
import {
selectPaletteIndexStatusSnapshot,
selectPaletteStatusInputs
@@ -42,14 +42,19 @@ export function useWorktreeJumpPaletteStoreState({
const recordFeatureInteraction = useAppStore((state) => state.recordFeatureInteraction)
const revealSidebarRow = useAppStore((state) => state.revealSidebarRow)
const storedWorktreesByRepo = useAppStore((state) => selectWorktreesByRepo(state))
const hiddenVmCheckouts = useSyncExternalStore(subscribeHiddenVmCheckouts, readHiddenVmCheckouts)
// Why: a VM create's checkout is not a workspace until the create adopts it.
const storedRepos = useAppStore((state) => state.repos)
const hiddenVmCheckouts = useSidebarHiddenCheckouts()
// Why: a VM create's checkout is not a workspace until the create adopts it; a cloud clone beside
// its workspace is redundant, and another team's sandbox is out of scope.
const worktreesByRepo = useMemo(
() => withoutHiddenVmWorktreesByRepo(storedWorktreesByRepo, hiddenVmCheckouts),
[storedWorktreesByRepo, hiddenVmCheckouts]
)
const folderWorkspaces = useAppStore((state) => selectFolderWorkspaces(state))
const repos = useAppStore((state) => state.repos)
const repos = useMemo(
() => withoutHiddenHostRepos(storedRepos, hiddenVmCheckouts),
[storedRepos, hiddenVmCheckouts]
)
const projectGroups = useAppStore((state) => state.projectGroups)
const workspaces = useMemo(
() =>
@@ -19,6 +19,7 @@ import { registerBrowserStateIpcBridge } from './browser-state-ipc-bridge'
import { registerContentCreationIpcBridge } from './content-creation-ipc-bridge'
import { registerDirectSshStateIpcBridge } from './direct-ssh-state-ipc-bridge'
import { registerEphemeralVmLifecycleIpcBridge } from './ephemeral-vm-lifecycle-ipc-bridge'
import { installLeaveOutOfTeamCloudWorkspace } from '@/lib/orca-cloud/leave-out-of-team-cloud-workspace'
import { registerMobileAndTerminalCloseIpcBridge } from './mobile-terminal-close-ipc-bridge'
import { registerMobileDriverIpcBridge } from './mobile-driver-ipc-bridge'
import { registerOrcaProfileAuthIpcBridge } from './orca-profile-auth-ipc-bridge'
@@ -93,6 +94,8 @@ export function installAppLifetimeIpcEvents(): () => void {
registerBackgroundWorktreeRemovalBridge(unsubs)
registerWslHostIpcBridge(unsubs)
registerEphemeralVmLifecycleIpcBridge(unsubs)
// After a team switch, the old team's open cloud workspace leaves the main pane.
unsubs.push(installLeaveOutOfTeamCloudWorkspace(useAppStore))
registerProjectCatalogIpcBridge(
unsubs,
worktreeRuntime.worktreeChangeRefreshQueue,
@@ -0,0 +1,90 @@
import { describe, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import { installLeaveOutOfTeamCloudWorkspace } from './leave-out-of-team-cloud-workspace'
const environments = [
{ id: 'cusk', name: 'push-test sandbox 1a2b3c4d', source: 'ephemeral-vm' },
{ id: 'otter', name: 'push-test sandbox 5e6f7a8b', source: 'ephemeral-vm' }
]
const owners = { cusk: 'org:team-one', otter: 'org:team-two' }
type State = Parameters<typeof installLeaveOutOfTeamCloudWorkspace>[0] extends {
getState: () => infer S
}
? S
: never
function harness(initial: { activeHost: string | null; activeOrgId?: string }) {
const setActiveWorktree = vi.fn((id: string | null) => {
state = { ...state, activeWorktreeId: id, activeWorkspaceExecutionHostId: null }
})
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the observer reads only these fields.
let state = {
activeWorktreeId: initial.activeHost ? 'repo::/w/cusk' : null,
activeWorkspaceExecutionHostId: initial.activeHost,
folderWorkspaces: [],
projectGroups: [],
repos: [],
runtimeEnvironments: environments,
cloudAccountIdByEnvironmentId: owners,
orcaProfileAuthStatus: initial.activeOrgId
? { cloud: { userId: 'u1', activeOrgId: initial.activeOrgId } }
: null,
setActiveWorktree
} as unknown as State
const listeners = new Set<(next: State) => void>()
const store = {
getState: () => state,
subscribe: (listener: (next: State) => void) => {
listeners.add(listener)
return () => listeners.delete(listener)
}
}
installLeaveOutOfTeamCloudWorkspace(store)
const set = (patch: Partial<AppState>): void => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test patches only fields the observer reads.
state = { ...state, ...patch } as State
listeners.forEach((listener) => listener(state))
}
return { set, setActiveWorktree, active: () => state.activeWorktreeId }
}
function team(activeOrgId: string): Partial<AppState> {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only `cloud` is read.
return { orcaProfileAuthStatus: { cloud: { userId: 'u1', activeOrgId } } } as Partial<AppState>
}
describe('leaving an out-of-team cloud workspace', () => {
it('moves off the open cloud workspace when its team is switched away', () => {
const h = harness({ activeHost: 'runtime:cusk', activeOrgId: 'team-one' })
h.set(team('team-two'))
expect(h.setActiveWorktree).toHaveBeenCalledWith(null)
expect(h.setActiveWorktree).toHaveBeenCalledTimes(1)
expect(h.active()).toBeNull()
})
it('moves off it on sign-out too', () => {
const h = harness({ activeHost: 'runtime:cusk', activeOrgId: 'team-one' })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only `cloud` is read.
h.set({ orcaProfileAuthStatus: null } as Partial<AppState>)
expect(h.active()).toBeNull()
})
it('stays on a local workspace, or on the cloud workspace of the team switched to', () => {
const local = harness({ activeHost: 'local', activeOrgId: 'team-one' })
local.set(team('team-two'))
expect(local.setActiveWorktree).not.toHaveBeenCalled()
const otter = harness({ activeHost: 'runtime:otter', activeOrgId: 'team-one' })
otter.set(team('team-two'))
expect(otter.setActiveWorktree).not.toHaveBeenCalled()
})
it('keeps a restored cloud workspace while the team and runtimes are still loading', () => {
// Launch: no auth status yet, so every sandbox reads as out of scope until it loads.
const h = harness({ activeHost: 'runtime:cusk' })
h.set(team('team-one'))
expect(h.setActiveWorktree).not.toHaveBeenCalled()
expect(h.active()).toBe('repo::/w/cusk')
})
})
@@ -0,0 +1,68 @@
import type { AppState } from '@/store/types'
import { workspaceOwnerHostId } from '@/lib/workspace/ownership/workspace-row-owner-host'
import {
parseOrcaCloudHostScopeKey,
selectOrcaCloudHostScopeKey
} from './use-sidebar-hidden-checkouts'
type LeaveState = Pick<
AppState,
| 'activeWorktreeId'
| 'activeWorkspaceExecutionHostId'
| 'folderWorkspaces'
| 'projectGroups'
| 'repos'
| 'runtimeEnvironments'
| 'setActiveWorktree'
> &
Partial<Pick<AppState, 'orcaProfileAuthStatus' | 'cloudAccountIdByEnvironmentId'>>
function activeHostId(state: LeaveState): string | null {
if (!state.activeWorktreeId) {
return null
}
// The host-qualified selection first: a cloud project and its local twin share repo ids.
return state.activeWorkspaceExecutionHostId ?? workspaceOwnerHostId(state, state.activeWorktreeId)
}
/**
* The active workspace's host just left the active team's scope: it was the team's a moment ago
* and now is not (a team or account switch). Only that edge counts, so a launch whose team or
* runtimes are still loading never drops a restored cloud workspace.
*/
export function activeCloudWorkspaceLeftTeam(
previousScopeKey: string,
nextScopeKey: string,
hostId: string | null
): boolean {
if (!hostId || previousScopeKey === nextScopeKey) {
return false
}
return (
parseOrcaCloudHostScopeKey(previousScopeKey).primaryHostIds.has(hostId) &&
parseOrcaCloudHostScopeKey(nextScopeKey).hiddenHostIds.has(hostId)
)
}
/**
* Why: a team switch hides the old team's sandboxes from every list, but the main pane kept
* showing the one that was open. Move off it as a host removal does (no active workspace, the
* empty landing). Its terminals stay: the sandbox is still the old team's to come back to.
*/
export function installLeaveOutOfTeamCloudWorkspace(store: {
getState: () => LeaveState
subscribe: (listener: (state: LeaveState) => void) => () => void
}): () => void {
let scopeKey = selectOrcaCloudHostScopeKey(store.getState())
return store.subscribe((state) => {
const next = selectOrcaCloudHostScopeKey(state)
if (next === scopeKey) {
return
}
const previous = scopeKey
scopeKey = next
if (activeCloudWorkspaceLeftTeam(previous, next, activeHostId(state))) {
state.setActiveWorktree(null)
}
})
}
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest'
import type { AppState } from '@/store/types'
import { EMPTY_PENDING_VM_CHECKOUT_INDEX } from '../../../../shared/pending-vm-checkouts'
import { withOrcaCloudHosts } from '@/lib/vm-create-hidden-checkouts'
import {
parseOrcaCloudHostScopeKey,
selectOrcaCloudHostScopeKey,
withoutHiddenHostRepos
} from './use-sidebar-hidden-checkouts'
const environments = [
{ id: 'a', name: 'push-test sandbox 1a2b3c4d', source: 'ephemeral-vm' },
{ id: 'b', name: 'push-test sandbox 5e6f7a8b', source: 'ephemeral-vm' },
{ id: 'unfiled', name: 'push-test sandbox 9c0d1e2f', source: 'ephemeral-vm' },
{ id: 'vm', name: 'my recipe VM', source: 'ephemeral-vm' },
{ id: 'manual', name: 'push-test sandbox 1a2b3c4d', source: 'manual' }
]
// Sandbox a is team one's, b is team two's; `unfiled` has no team recorded yet.
const owners = { a: 'org:team-one', b: 'org:team-two' }
function scopeFor(activeOrgId: string | undefined) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selector reads only these fields.
const state = {
runtimeEnvironments: environments,
cloudAccountIdByEnvironmentId: owners,
orcaProfileAuthStatus: { cloud: { userId: 'u1', ...(activeOrgId ? { activeOrgId } : {}) } }
} as unknown as Pick<AppState, 'runtimeEnvironments'>
const { primaryHostIds, hiddenHostIds } = parseOrcaCloudHostScopeKey(
selectOrcaCloudHostScopeKey(state)
)
return { primary: [...primaryHostIds], hidden: [...hiddenHostIds] }
}
describe('Orca Cloud host scope', () => {
it("lists the active team's sandboxes and hides the other team's and unfiled ones", () => {
expect(scopeFor('team-one')).toEqual({
primary: ['runtime:a'],
hidden: ['runtime:b', 'runtime:unfiled']
})
})
it('flips with a team switch', () => {
expect(scopeFor('team-two')).toEqual({
primary: ['runtime:b'],
hidden: ['runtime:a', 'runtime:unfiled']
})
})
it('hides every sandbox when signed out of Orca Cloud', () => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selector reads only these fields.
const signedOut = {
runtimeEnvironments: environments,
cloudAccountIdByEnvironmentId: owners,
orcaProfileAuthStatus: null
} as unknown as Pick<AppState, 'runtimeEnvironments'>
expect(
parseOrcaCloudHostScopeKey(selectOrcaCloudHostScopeKey(signedOut)).primaryHostIds.size
).toBe(0)
})
it("drops another team's sandbox project so it never gets its own header", () => {
const local = { id: 'r', executionHostId: 'local' as const }
const mine = { id: 'r', executionHostId: 'runtime:a' as const }
const theirs = { id: 'otter', executionHostId: 'runtime:b' as const }
const scope = withOrcaCloudHosts(EMPTY_PENDING_VM_CHECKOUT_INDEX, {
primaryHostIds: new Set(['runtime:a']),
hiddenHostIds: new Set(['runtime:b'])
})
expect(withoutHiddenHostRepos([local, mine, theirs], scope)).toEqual([local, mine])
})
})
@@ -0,0 +1,77 @@
import { useMemo, useSyncExternalStore } from 'react'
import { useAppStore } from '@/store'
import type { AppState } from '@/store/types'
import {
readHiddenVmCheckouts,
subscribeHiddenVmCheckouts,
withOrcaCloudHosts,
type HiddenVmCheckouts
} from '@/lib/vm-create-hidden-checkouts'
import { getRepoExecutionHostId, toRuntimeExecutionHostId } from '../../../../shared/execution-host'
import { orcaCloudAccountId } from '../../../../shared/hosted-sandbox/orca-cloud-account'
import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name'
import type { Repo } from '../../../../shared/repo-types'
type CloudScopeState = Pick<AppState, 'runtimeEnvironments'> &
Partial<Pick<AppState, 'orcaProfileAuthStatus' | 'cloudAccountIdByEnvironmentId'>>
/**
* Every Orca Cloud server, `+host` when the active team owns it and `-host` otherwise (another
* team's, or one whose team is not known yet). Newline-joined so the selector compares by value.
*/
export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
const active = orcaCloudAccountId(state.orcaProfileAuthStatus?.cloud)
const owners = state.cloudAccountIdByEnvironmentId ?? {}
return (state.runtimeEnvironments ?? [])
.filter((environment) => isOrcaCloudRuntimeEnvironment(environment))
.map((environment) => {
const inTeam = active !== null && owners[environment.id] === active
return `${inTeam ? '+' : '-'}${toRuntimeExecutionHostId(environment.id)}`
})
.join('\n')
}
export function parseOrcaCloudHostScopeKey(key: string): {
primaryHostIds: ReadonlySet<string>
hiddenHostIds: ReadonlySet<string>
} {
const primaryHostIds = new Set<string>()
const hiddenHostIds = new Set<string>()
for (const entry of key ? key.split('\n') : []) {
;(entry.startsWith('+') ? primaryHostIds : hiddenHostIds).add(entry.slice(1))
}
return { primaryHostIds, hiddenHostIds }
}
/**
* What sidebar lists hide: VM checkouts whose create is in progress, an Orca Cloud clone beside its
* listed workspace, and every row of another team's sandbox.
*/
export function useSidebarHiddenCheckouts(): HiddenVmCheckouts {
const pending = useSyncExternalStore(subscribeHiddenVmCheckouts, readHiddenVmCheckouts)
const scopeKey = useAppStore(selectOrcaCloudHostScopeKey)
return useMemo(
() => withOrcaCloudHosts(pending, parseOrcaCloudHostScopeKey(scopeKey)),
[pending, scopeKey]
)
}
/** Repos without another team's sandbox projects, so none surfaces as its own project header. */
export function withoutHiddenHostRepos<R extends Pick<Repo, 'connectionId' | 'executionHostId'>>(
repos: readonly R[],
checkouts: HiddenVmCheckouts
): readonly R[] {
const hidden = checkouts.hiddenHostIds
if (!hidden?.size) {
return repos
}
const kept = repos.filter((repo) => !hidden.has(getRepoExecutionHostId(repo)))
return kept.length === repos.length ? repos : kept
}
/** The store's repos scoped like the sidebar's rows (useSidebarHiddenCheckouts). */
export function useSidebarScopedRepos(): readonly Repo[] {
const repos = useAppStore((state) => state.repos)
const hidden = useSidebarHiddenCheckouts()
return useMemo(() => withoutHiddenHostRepos(repos, hidden), [repos, hidden])
}
@@ -1,13 +1,16 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { EMPTY_SIDEBAR_FEED_DOMAINS } from '../../../shared/sidebar-feed-client/sidebar-feed-snapshot'
import type { SidebarFeedDomains } from '../../../shared/sidebar-list/sidebar-feed-domains'
import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity'
import {
hideVmCreateCheckout,
readHiddenVmCheckouts,
releaseVmCreateCheckout,
settleVmCreateCheckoutAfterCleanup,
withOrcaCloudHosts,
withoutHiddenVmCheckouts,
withoutHiddenVmWorktrees
withoutHiddenVmWorktrees,
withoutHiddenVmWorktreesByRepo
} from './vm-create-hidden-checkouts'
type Row = { repoId: string; path: string; isMainWorktree?: boolean }
@@ -78,3 +81,78 @@ describe('hidden VM checkout lifecycle', () => {
expect(isListed('vm')).toBe(true)
})
})
describe('Orca Cloud sandboxes', () => {
// Two cloud workspaces of one project: each sandbox lists its clone (master) as primary.
const hostA = 'runtime:sandbox-a'
const hostB = 'runtime:sandbox-b'
const hostC = 'runtime:sandbox-c'
const otherTeam = 'runtime:sandbox-other-team'
const clone = (hostId: string) => ({
repoId: 'r',
path: '/vercel/sandbox/project',
isMainWorktree: true,
hostId
})
const sockeye = { repoId: 'r', path: '/w/sockeye', isMainWorktree: false, hostId: hostA }
const otter = { repoId: 'r', path: '/w/otter', isMainWorktree: false, hostId: hostB }
const local = { repoId: 'r', path: '/Users/me/repo', isMainWorktree: true, hostId: 'local' }
const scoped = (hiddenHostIds: string[] = []) =>
withOrcaCloudHosts(readHiddenVmCheckouts(), {
primaryHostIds: new Set([hostA, hostB, hostC]),
hiddenHostIds: new Set(hiddenHostIds)
})
it('lists one row per cloud workspace across two sandboxes and no clone rows', () => {
const rows = [local, clone(hostA), clone(hostB), sockeye, otter]
const listed = withoutHiddenVmWorktrees(rows, scoped())
expect(listed).toEqual([local, sockeye, otter])
expect(listed.filter((row) => row.hostId !== 'local' && row.isMainWorktree)).toEqual([])
expect(withoutHiddenVmWorktreesByRepo({ r: rows }, scoped())).toEqual({
r: [local, sockeye, otter]
})
})
it("hides a sandbox's clone even when it is that sandbox's only row", () => {
expect(withoutHiddenVmWorktrees([local, clone(hostC)], scoped())).toEqual([local])
})
it("leaves this computer's primary checkout alone", () => {
const rows = [local]
expect(withoutHiddenVmWorktrees(rows, scoped())).toBe(rows)
})
it("hides every row of another team's sandbox, and leaves local rows alone", () => {
const foreign = { repoId: 'r', path: '/w/x', isMainWorktree: false, hostId: otherTeam }
const rows = [local, clone(otherTeam), foreign, clone(hostA), sockeye]
expect(withoutHiddenVmWorktrees(rows, scoped([otherTeam]))).toEqual([local, sockeye])
})
it("reads a paired-server row's host from its host-qualified key", () => {
const strip = <T extends { hostId: string }>({ hostId: _hostId, ...row }: T) => row
const rowS = strip(sockeye)
// 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(hostA, 'r::/vercel/sandbox/project'), strip(clone(hostA))],
[composeWorktreeHostIdentity(hostA, 'r::/w/sockeye'), rowS],
[composeWorktreeHostIdentity(hostC, 'r::/vercel/sandbox/project'), strip(clone(hostC))],
[composeWorktreeHostIdentity(otherTeam, 'r::/w/x'), rowS]
])
} as unknown as SidebarFeedDomains
const filtered = withoutHiddenVmCheckouts(domains, scoped([otherTeam]))
expect([...filtered.pairedServerRows.values()]).toEqual([rowS])
})
it('leaves lists untouched when no Orca Cloud host is known', () => {
const rows = [local, clone(hostA)]
const none = withOrcaCloudHosts(readHiddenVmCheckouts(), {
primaryHostIds: new Set(),
hiddenHostIds: new Set()
})
expect(withoutHiddenVmWorktrees(rows, none)).toBe(rows)
})
})
@@ -1,4 +1,5 @@
import type { SidebarFeedDomains } from '../../../shared/sidebar-list/sidebar-feed-domains'
import { getExecutionHostIdFromWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity'
import {
indexPendingVmCheckouts,
isPendingVmCheckout,
@@ -8,10 +9,58 @@ import {
/** A VM's primary checkout, registered on its host before the create that owns it finishes. */
export type HiddenVmCheckout = PendingVmCheckout
type CheckoutRow = { repoId: string; path: string; isMainWorktree?: boolean }
type CheckoutRow = {
repoId: string
path: string
isMainWorktree?: boolean
hostId?: string
}
/** What lists filter by: this window's pending VM checkouts and every other window's. */
export type HiddenVmCheckouts = PendingVmCheckoutIndex
/**
* What lists filter by: this window's pending VM checkouts and every other window's, plus the
* Orca Cloud hosts lists scope (withOrcaCloudHosts).
*/
export type HiddenVmCheckouts = PendingVmCheckoutIndex & {
/** Active-team Orca Cloud hosts: their primary checkout (the sandbox's clone) never lists. */
readonly primaryHostIds?: ReadonlySet<string>
/** Orca Cloud hosts of another team, or of no team we can resolve: every row hides. */
readonly hiddenHostIds?: ReadonlySet<string>
}
/**
* Why: each Orca Cloud workspace is its own sandbox whose clone is registered as the project there,
* and the workspace is a worktree beside it (orca-worktree mode). That clone is scaffolding, not a
* workspace: listed, every cloud workspace added another identical "<default branch> primary ·
* Orca Cloud" row to its project. Another team's sandbox lists nothing at all.
*/
export function withOrcaCloudHosts(
checkouts: HiddenVmCheckouts,
hosts: { primaryHostIds: ReadonlySet<string>; hiddenHostIds: ReadonlySet<string> }
): HiddenVmCheckouts {
return hosts.primaryHostIds.size === 0 && hosts.hiddenHostIds.size === 0
? checkouts
: { ...checkouts, primaryHostIds: hosts.primaryHostIds, hiddenHostIds: hosts.hiddenHostIds }
}
function hidesNothing(checkouts: HiddenVmCheckouts): boolean {
return (
checkouts.keys.size === 0 && !checkouts.primaryHostIds?.size && !checkouts.hiddenHostIds?.size
)
}
function isHiddenCheckout(
checkouts: HiddenVmCheckouts,
row: CheckoutRow,
hostId: string | undefined = row.hostId
): boolean {
if (hostId && checkouts.hiddenHostIds?.has(hostId)) {
return true
}
if (row.isMainWorktree === true && hostId && checkouts.primaryHostIds?.has(hostId)) {
return true
}
return checkouts.keys.size > 0 && isPendingVmCheckout(checkouts, row)
}
// Upper bound for a cleaned-up VM's rows to leave the lists (its host is retired asynchronously).
const HIDDEN_AFTER_CLEANUP_MS = 60_000
@@ -131,28 +180,31 @@ export function readHiddenVmCheckouts(): HiddenVmCheckouts {
return hidden
}
/** The window's sidebar list without the primary checkouts of VMs whose creates are in progress. */
/** The window's sidebar list without hidden VM checkouts, cloud clones and other teams' sandboxes. */
export function withoutHiddenVmWorktrees<W extends CheckoutRow>(
worktrees: W[],
checkouts: HiddenVmCheckouts
): W[] {
if (checkouts.keys.size === 0) {
if (hidesNothing(checkouts)) {
return worktrees
}
const kept = worktrees.filter((worktree) => !isPendingVmCheckout(checkouts, worktree))
const kept = worktrees.filter((worktree) => !isHiddenCheckout(checkouts, worktree))
return kept.length === worktrees.length ? worktrees : kept
}
/** Per-repo lists without pending VM checkouts; the same object when nothing matches. */
/** Per-repo lists without hidden checkouts; the same object when nothing matches. */
export function withoutHiddenVmWorktreesByRepo<W extends CheckoutRow>(
worktreesByRepo: Record<string, W[]>,
checkouts: HiddenVmCheckouts
): Record<string, W[]> {
if (checkouts.keys.size === 0) {
if (hidesNothing(checkouts)) {
return worktreesByRepo
}
const hostScoped = Boolean(checkouts.primaryHostIds?.size || checkouts.hiddenHostIds?.size)
let next: Record<string, W[]> | null = null
for (const repoId of checkouts.repoIds) {
// Host-scoped rows can sit under any repo; pending checkouts only under theirs.
const repoIds = hostScoped ? Object.keys(worktreesByRepo) : checkouts.repoIds
for (const repoId of repoIds) {
const list = worktreesByRepo[repoId]
if (!list) {
continue
@@ -166,13 +218,15 @@ export function withoutHiddenVmWorktreesByRepo<W extends CheckoutRow>(
return next ?? worktreesByRepo
}
function withoutHiddenRows<K, V extends CheckoutRow>(
function withoutHiddenRows<K extends string, V extends CheckoutRow>(
rows: ReadonlyMap<K, V>,
checkouts: HiddenVmCheckouts
): ReadonlyMap<K, V> {
let kept: Map<K, V> | null = null
for (const [key, row] of rows) {
if (isPendingVmCheckout(checkouts, row)) {
// Paired-server rows carry their host only in the host-qualified key.
const hostId = row.hostId ?? getExecutionHostIdFromWorktreeHostIdentity(key)
if (isHiddenCheckout(checkouts, row, hostId)) {
kept ??= new Map(rows)
kept.delete(key)
}
@@ -180,12 +234,12 @@ function withoutHiddenRows<K, V extends CheckoutRow>(
return kept ?? rows
}
/** Main's rows without the primary checkouts of VMs whose creates are still in progress. */
/** Main's rows without hidden VM checkouts, cloud clones and other teams' sandboxes. */
export function withoutHiddenVmCheckouts(
domains: SidebarFeedDomains,
checkouts: HiddenVmCheckouts
): SidebarFeedDomains {
if (checkouts.keys.size === 0) {
if (hidesNothing(checkouts)) {
return domains
}
const workspaces = withoutHiddenRows(domains.workspaces, checkouts)
@@ -39,6 +39,8 @@ function environmentBuildIdOf(record: EphemeralVmRuntimeRecord): string | undefi
export type EphemeralVmLifecycleSlice = {
/** Live (not cleaned up) VM runtimes by the workspace they back. */
ephemeralVmRuntimesByWorkspaceId: Record<string, EphemeralVmWorkspaceRuntime>
/** Live Orca Cloud runtimes' owning team by runtime environment; unfiled ones are absent. */
cloudAccountIdByEnvironmentId: Record<string, string>
/** Workspaces whose VM resume is in flight; the record only flips when it finishes. */
wakingEphemeralVmWorkspaceIds: Record<string, true>
refreshEphemeralVmRuntimes: () => Promise<void>
@@ -99,6 +101,29 @@ export function projectEphemeralVmWorkspaceRuntimes(
return byWorkspaceId
}
/** Which team owns each live Orca Cloud server, so lists can scope to the active team. */
export function projectCloudAccountsByEnvironment(
records: readonly EphemeralVmRuntimeRecord[]
): Record<string, string> {
const byEnvironment: Record<string, string> = {}
for (const record of records) {
if (
record.recipe?.provider === 'orca-cloud' &&
record.runtimeEnvironmentId &&
record.cloudAccountId &&
!RETIRED_STATUSES.has(record.status)
) {
byEnvironment[record.runtimeEnvironmentId] = record.cloudAccountId
}
}
return byEnvironment
}
function sameAccounts(a: Record<string, string>, b: Record<string, string>): boolean {
const keys = Object.keys(a)
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key])
}
function sameRuntimes(
a: Record<string, EphemeralVmWorkspaceRuntime>,
b: Record<string, EphemeralVmWorkspaceRuntime>
@@ -133,6 +158,7 @@ export const createEphemeralVmLifecycleSlice: StateCreator<
EphemeralVmLifecycleSlice
> = (set) => ({
ephemeralVmRuntimesByWorkspaceId: {},
cloudAccountIdByEnvironmentId: {},
wakingEphemeralVmWorkspaceIds: {},
refreshEphemeralVmRuntimes: () => {
const listRuntimes = window.api?.ephemeralVm?.listRuntimes
@@ -141,17 +167,24 @@ export const createEphemeralVmLifecycleSlice: StateCreator<
}
const sequence = ++refreshSequence
const refresh = (async (): Promise<void> => {
const next = projectEphemeralVmWorkspaceRuntimes(await listRuntimes())
const records = await listRuntimes()
const next = projectEphemeralVmWorkspaceRuntimes(records)
const accounts = projectCloudAccountsByEnvironment(records)
// Out-of-order replies must not roll a newer lifecycle status back; a superseded caller
// settles with the newer read, so it never acts on a store that has not caught up.
if (sequence !== refreshSequence) {
return latestRefresh
}
set((state) =>
sameRuntimes(state.ephemeralVmRuntimesByWorkspaceId, next)
set((state) => {
const runtimesSame = sameRuntimes(state.ephemeralVmRuntimesByWorkspaceId, next)
const accountsSame = sameAccounts(state.cloudAccountIdByEnvironmentId ?? {}, accounts)
return runtimesSame && accountsSame
? state
: { ephemeralVmRuntimesByWorkspaceId: next }
)
: {
...(runtimesSame ? {} : { ephemeralVmRuntimesByWorkspaceId: next }),
...(accountsSame ? {} : { cloudAccountIdByEnvironmentId: accounts })
}
})
})()
latestRefresh = refresh
return refresh
+1
View File
@@ -164,6 +164,7 @@ export function updateEphemeralVmRuntimeStatus(
: args.sshTargetId
? { sshTargetId: args.sshTargetId }
: {}),
...(args.cloudAccountId ? { cloudAccountId: args.cloudAccountId } : {}),
...(args.recipeResult ? { recipeResult: args.recipeResult } : {}),
updatedAt: args.updatedAt ?? Date.now()
})
+6
View File
@@ -61,6 +61,11 @@ export const EphemeralVmRuntimeRecordSchema = z.object({
connectionMode: EphemeralVmRuntimeConnectionModeSchema.optional(),
runtimeEnvironmentId: z.string().min(1).optional(),
sshTargetId: z.string().min(1).optional(),
/**
* Orca Cloud only: the control-plane account that owns the sandbox (`org:<id>` or `user:<id>`,
* see orcaCloudAccountId). Lists and keep-alive scope to the active team by it; absent until known.
*/
cloudAccountId: z.string().min(1).max(256).optional(),
status: EphemeralVmRuntimeStatusSchema,
cleanupStatus: EphemeralVmCleanupStatusSchema,
cleanupDisabled: z.boolean().optional(),
@@ -114,6 +119,7 @@ export type EphemeralVmRuntimeStatusPatch = {
connectionMode?: EphemeralVmRuntimeRecord['connectionMode'] | null
runtimeEnvironmentId?: string
sshTargetId?: string | null
cloudAccountId?: string
recipeResult?: EphemeralVmRuntimeRecord['recipeResult']
updatedAt?: number
}
@@ -0,0 +1,27 @@
import type { EphemeralVmRuntimeRecord } from '../ephemeral-vm-runtimes'
/**
* The control-plane account a sandbox token acts for, in sandbox-control's own form
* (cloud/apps/sandbox-control/src/auth.ts accountIdFor): the selected team pays for its members,
* otherwise the user is the account. The token is minted for the profile's active org, so
* `activeOrgId` and the token's `org` claim are the same id.
*/
export function orcaCloudAccountId(
cloud: { userId?: string | null; activeOrgId?: string | null } | null | undefined
): string | null {
if (cloud?.activeOrgId) {
return `org:${cloud.activeOrgId}`
}
return cloud?.userId ? `user:${cloud.userId}` : null
}
/**
* Whether an Orca Cloud runtime belongs to the active team. A record whose team is unknown (or no
* team is signed in) is not: another team's sandbox must never be listed or kept alive.
*/
export function isOrcaCloudRuntimeInAccount(
runtime: Pick<EphemeralVmRuntimeRecord, 'cloudAccountId'>,
activeAccountId: string | null
): boolean {
return activeAccountId !== null && runtime.cloudAccountId === activeAccountId
}