From 23c4fa300cedf404b4615d5e692a9f593a7d1d34 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:26:48 -0800 Subject: [PATCH] fix(cloud): scope Orca Cloud workspaces to the active team; never list sandbox clones Bug 6: a team switch left the previous team's cloud workspace in the sidebar (as its own project header) and kept its lease scheduler, wake and orcad calls running under the new team's token. - Orca Cloud runtime records carry the owning control-plane account (cloudAccountId, sandbox-control's org: / user: form), read once at the create write-ahead from the active profile. - Backfill: on the 30 s beat and on every auth change, list the active team's sandboxes (GET /v1/sandboxes is scoped to the caller's account) and file the listed records under that team; it re-lists only when the team or the unfiled set changes, and drops a list that answered for a team the user has since left. - The session registry, OOM polling and the window's cloud workspace ids skip every record outside the active team, so the old team's sandboxes get no keep-alive or orcad calls after a switch. - Sidebar rows, the jump palette and project headers hide another team's sandbox hosts and any whose team is unknown (or when signed out). Bug 7 (per coordinator): every Orca Cloud sandbox's primary clone stays hidden; each cloud workspace row appears once. --- .../runtime-provisioning-persistence.ts | 9 +- .../hosted-sandbox/cloud-account-backfill.ts | 91 ++++++++++ .../cloud-account-filing.test.ts | 167 ++++++++++++++++++ .../hosted-sandbox/hosted-sandbox-install.ts | 26 ++- ...hosted-session-registry-team-scope.test.ts | 86 +++++++++ .../hosted-sandbox/hosted-session-registry.ts | 10 +- ...osted-workspace-service-team-scope.test.ts | 82 +++++++++ .../hosted-workspace-service.ts | 32 ++-- .../orca-cloud-active-account.ts | 36 ++++ src/main/startup/main-window-core-services.ts | 3 + .../worktree-list/listing/WorktreeList.tsx | 4 +- .../use-worktree-jump-palette-store-state.ts | 14 +- .../use-sidebar-hidden-checkouts.test.ts | 77 ++++++-- .../use-sidebar-hidden-checkouts.ts | 70 ++++++-- .../lib/vm-create-hidden-checkouts.test.ts | 72 +++++--- .../src/lib/vm-create-hidden-checkouts.ts | 42 +++-- .../ephemeral-vm/ephemeral-vm-lifecycle.ts | 43 ++++- src/shared/ephemeral-vm-runtime-store.ts | 1 + src/shared/ephemeral-vm-runtimes.ts | 6 + .../hosted-sandbox/orca-cloud-account.ts | 27 +++ 20 files changed, 802 insertions(+), 96 deletions(-) create mode 100644 src/main/hosted-sandbox/cloud-account-backfill.ts create mode 100644 src/main/hosted-sandbox/cloud-account-filing.test.ts create mode 100644 src/main/hosted-sandbox/hosted-session-registry-team-scope.test.ts create mode 100644 src/main/hosted-sandbox/hosted-workspace-service-team-scope.test.ts create mode 100644 src/main/hosted-sandbox/orca-cloud-active-account.ts create mode 100644 src/shared/hosted-sandbox/orca-cloud-account.ts diff --git a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts index c0fd9636c84..c84ada676eb 100644 --- a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts +++ b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts @@ -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 diff --git a/src/main/hosted-sandbox/cloud-account-backfill.ts b/src/main/hosted-sandbox/cloud-account-backfill.ts new file mode 100644 index 00000000000..3247e4562b4 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-account-backfill.ts @@ -0,0 +1,91 @@ +// 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(['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 or the team changed. */ + run(): Promise +} + +export function createCloudAccountBackfill(deps: { + userDataPath: string + activeAccountId: () => string | null + list: () => Promise[]> + log?: (line: string) => void +}): CloudAccountBackfill { + // One list per (team, unfiled set): the 30 s beat must not list on every tick. + let lastKey: string | null = null + 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) + if (before.length === 0 || key === lastKey) { + return + } + let listed: ReadonlySet + 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)) + } + } +} + +/** 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]) +} diff --git a/src/main/hosted-sandbox/cloud-account-filing.test.ts b/src/main/hosted-sandbox/cloud-account-filing.test.ts new file mode 100644 index 00000000000..25ab666a4a7 --- /dev/null +++ b/src/main/hosted-sandbox/cloud-account-filing.test.ts @@ -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() + }) +}) diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 29cf66e0514..f305112da4f 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -35,6 +35,9 @@ 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 { createUsageAlertRefreshScheduler } from '../billing/usage-alert-refresh' import { sendToTrustedUIRenderer } from '../ipc/ui' import { ORCA_BILLING_REFRESH_CHANNEL } from '../../shared/orca-billing' @@ -92,6 +95,15 @@ 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 accountBackfill = createCloudAccountBackfill({ + userDataPath, + activeAccountId, + list: () => client.list() + }) const mcpSync = installCloudMcpSync(userDataPath, { baseUrl: config.controlPlaneUrl, getAccessToken: config.getAccessToken @@ -123,8 +135,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 => accountBackfill.run().finally(() => registry.sync()) const workspaces = installHostedWorkspaceService({ userDataPath, // Every status read also carries the control plane's idle-sleep minutes. @@ -149,7 +164,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 +199,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 +223,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 +237,7 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo setHostedWorkspaceService(null) setCloudArchiveCheck(null) setCloudAsleepCheck(null) + setOrcaCloudActiveAccountResolver(null) offline.dispose() setCloudOfflineService(null) }) diff --git a/src/main/hosted-sandbox/hosted-session-registry-team-scope.test.ts b/src/main/hosted-sandbox/hosted-session-registry-team-scope.test.ts new file mode 100644 index 00000000000..3e1510d41f2 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-session-registry-team-scope.test.ts @@ -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() + }) +}) diff --git a/src/main/hosted-sandbox/hosted-session-registry.ts b/src/main/hosted-sandbox/hosted-session-registry.ts index 9c1955bc056..b4dd60ca240 100644 --- a/src/main/hosted-sandbox/hosted-session-registry.ts +++ b/src/main/hosted-sandbox/hosted-session-registry.ts @@ -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() const log = deps.log ?? ((line: string) => console.error(line)) @@ -193,11 +199,13 @@ export function createHostedSessionRegistry(deps: { return { async sync() { const live = new Set() + 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 } diff --git a/src/main/hosted-sandbox/hosted-workspace-service-team-scope.test.ts b/src/main/hosted-sandbox/hosted-workspace-service-team-scope.test.ts new file mode 100644 index 00000000000..f04e821cfb3 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-workspace-service-team-scope.test.ts @@ -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 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']) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-workspace-service.ts b/src/main/hosted-sandbox/hosted-workspace-service.ts index 5c01538b59d..b001469bbe6 100644 --- a/src/main/hosted-sandbox/hosted-workspace-service.ts +++ b/src/main/hosted-sandbox/hosted-workspace-service.ts @@ -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() // Wakes in flight per workspace, so every phase carries the source the first one named. const wakes = new Map() @@ -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!) ) diff --git a/src/main/hosted-sandbox/orca-cloud-active-account.ts b/src/main/hosted-sandbox/orca-cloud-active-account.ts new file mode 100644 index 00000000000..4486f0e2bf2 --- /dev/null +++ b/src/main/hosted-sandbox/orca-cloud-active-account.ts @@ -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)) + ) +} diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index 8df56bbb260..72b0dd15af0 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -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: () => { diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.tsx b/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.tsx index a3a6335224c..979ed29b4be 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.tsx @@ -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) diff --git a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts index 1806af7e8c5..0634ebd21c2 100644 --- a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts +++ b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-store-state.ts @@ -7,7 +7,10 @@ import { usePluginNewFiles } from '@/store/plugins/file-creation/plugin-new-file import { useSettingsNavigationMetadata } from '@/hooks/useSettingsNavigationMetadata' import { dedupePaletteWorktrees } from '@/lib/workspace/search/palette-repo-resolution' import { withoutHiddenVmWorktreesByRepo } from '@/lib/vm-create-hidden-checkouts' -import { useSidebarHiddenCheckouts } from '@/lib/orca-cloud/use-sidebar-hidden-checkouts' +import { + useSidebarHiddenCheckouts, + withoutHiddenHostRepos +} from '@/lib/orca-cloud/use-sidebar-hidden-checkouts' import { selectPaletteIndexStatusSnapshot, selectPaletteStatusInputs @@ -39,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 storedRepos = useAppStore((state) => state.repos) const hiddenVmCheckouts = useSidebarHiddenCheckouts() - // Why: a VM create's checkout is not a workspace until the create adopts it; an Orca Cloud clone never is. + // 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( () => diff --git a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts index 6dc1de652e6..5233fda403b 100644 --- a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts +++ b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts @@ -1,18 +1,71 @@ import { describe, expect, it } from 'vitest' import type { AppState } from '@/store/types' -import { selectOrcaCloudHostIdsKey } from './use-sidebar-hidden-checkouts' +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' -describe('selectOrcaCloudHostIdsKey', () => { - it('names only Orca Cloud sandbox servers', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selector reads only id, name and source. - const state = { - runtimeEnvironments: [ - { id: 'a', name: 'orca-sandbox-push-test sandbox 1a2b3c4d', source: 'ephemeral-vm' }, - { id: 'b', name: 'orca-sandbox-push-test sandbox 5e6f7a8b', source: 'ephemeral-vm' }, - { id: 'vm', name: 'my recipe VM', source: 'ephemeral-vm' }, - { id: 'manual', name: 'orca-sandbox-push-test sandbox 1a2b3c4d', source: 'manual' } - ] +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 + 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 - expect(selectOrcaCloudHostIdsKey(state).split('\n')).toEqual(['runtime:a', 'runtime:b']) + 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]) }) }) diff --git a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts index 6e83c13220c..b8a0c8dc1d0 100644 --- a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts +++ b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts @@ -4,30 +4,74 @@ import type { AppState } from '@/store/types' import { readHiddenVmCheckouts, subscribeHiddenVmCheckouts, - withOrcaCloudPrimaryHosts, + withOrcaCloudHosts, type HiddenVmCheckouts } from '@/lib/vm-create-hidden-checkouts' -import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +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' -/** Orca Cloud sandbox hosts, newline-joined so the selector result compares by value. */ -export function selectOrcaCloudHostIdsKey(state: Pick): string { +type CloudScopeState = Pick & + Partial> + +/** + * 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) => toRuntimeExecutionHostId(environment.id)) + .map((environment) => { + const inTeam = active !== null && owners[environment.id] === active + return `${inTeam ? '+' : '-'}${toRuntimeExecutionHostId(environment.id)}` + }) .join('\n') } -/** What sidebar lists hide: VM checkouts whose create is in progress, and every Orca Cloud clone. */ +export function parseOrcaCloudHostScopeKey(key: string): { + primaryHostIds: ReadonlySet + hiddenHostIds: ReadonlySet +} { + const primaryHostIds = new Set() + const hiddenHostIds = new Set() + 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 cloudHostIdsKey = useAppStore(selectOrcaCloudHostIdsKey) + const scopeKey = useAppStore(selectOrcaCloudHostScopeKey) return useMemo( - () => - withOrcaCloudPrimaryHosts( - pending, - new Set(cloudHostIdsKey ? cloudHostIdsKey.split('\n') : []) - ), - [pending, cloudHostIdsKey] + () => withOrcaCloudHosts(pending, parseOrcaCloudHostScopeKey(scopeKey)), + [pending, scopeKey] ) } + +/** Repos without another team's sandbox projects, so none surfaces as its own project header. */ +export function withoutHiddenHostRepos>( + 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]) +} diff --git a/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts b/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts index 3a35bfd9827..50d449bc701 100644 --- a/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts +++ b/src/renderer/src/lib/vm-create-hidden-checkouts.test.ts @@ -7,7 +7,7 @@ import { readHiddenVmCheckouts, releaseVmCreateCheckout, settleVmCreateCheckoutAfterCleanup, - withOrcaCloudPrimaryHosts, + withOrcaCloudHosts, withoutHiddenVmCheckouts, withoutHiddenVmWorktrees, withoutHiddenVmWorktreesByRepo @@ -82,53 +82,77 @@ describe('hidden VM checkout lifecycle', () => { }) }) -describe('Orca Cloud sandbox primaries', () => { +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 cloudHosts = new Set([hostA, hostB]) - const cloneA = { + const hostC = 'runtime:sandbox-c' + const otherTeam = 'runtime:sandbox-other-team' + const clone = (hostId: string) => ({ repoId: 'r', path: '/vercel/sandbox/project', isMainWorktree: true, - hostId: hostA - } - const cloneB = { ...cloneA, hostId: hostB } + 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 neither clone as a row, keeping the cloud workspaces and the local primary', () => { - const hidden = withOrcaCloudPrimaryHosts(readHiddenVmCheckouts(), cloudHosts) - const rows = [local, cloneA, cloneB, sockeye, otter] + 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(withoutHiddenVmWorktrees(rows, hidden)).toEqual([local, sockeye, otter]) - expect(withoutHiddenVmWorktreesByRepo({ r: rows }, hidden)).toEqual({ + 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 { hostId: _a, ...rowA } = cloneA - const { hostId: _b, ...rowB } = cloneB - const { hostId: _s, ...rowS } = sockeye - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the filter reads only repoId, path, isMainWorktree and the key. + const strip = ({ 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'), rowA], - [composeWorktreeHostIdentity(hostB, 'r::/vercel/sandbox/project'), rowB], - [composeWorktreeHostIdentity(hostA, 'r::/w/sockeye'), rowS] + [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 hidden = withOrcaCloudPrimaryHosts(readHiddenVmCheckouts(), cloudHosts) + const filtered = withoutHiddenVmCheckouts(domains, scoped([otherTeam])) - expect([...withoutHiddenVmCheckouts(domains, hidden).pairedServerRows.values()]).toEqual([rowS]) + expect([...filtered.pairedServerRows.values()]).toEqual([rowS]) }) it('leaves lists untouched when no Orca Cloud host is known', () => { - const rows = [local, cloneA] - const hidden = withOrcaCloudPrimaryHosts(readHiddenVmCheckouts(), new Set()) - expect(withoutHiddenVmWorktrees(rows, hidden)).toBe(rows) + const rows = [local, clone(hostA)] + const none = withOrcaCloudHosts(readHiddenVmCheckouts(), { + primaryHostIds: new Set(), + hiddenHostIds: new Set() + }) + expect(withoutHiddenVmWorktrees(rows, none)).toBe(rows) }) }) diff --git a/src/renderer/src/lib/vm-create-hidden-checkouts.ts b/src/renderer/src/lib/vm-create-hidden-checkouts.ts index f05458b8670..e1c9b2f4d01 100644 --- a/src/renderer/src/lib/vm-create-hidden-checkouts.ts +++ b/src/renderer/src/lib/vm-create-hidden-checkouts.ts @@ -9,31 +9,43 @@ 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; hostId?: string } +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, plus the hosts - * whose primary checkout is never a workspace (withOrcaCloudPrimaryHosts). + * 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 + /** Orca Cloud hosts of another team, or of no team we can resolve: every row hides. */ + readonly hiddenHostIds?: ReadonlySet } /** * 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 " primary ยท - * Orca Cloud" row to its project. + * Orca Cloud" row to its project. Another team's sandbox lists nothing at all. */ -export function withOrcaCloudPrimaryHosts( +export function withOrcaCloudHosts( checkouts: HiddenVmCheckouts, - hostIds: ReadonlySet + hosts: { primaryHostIds: ReadonlySet; hiddenHostIds: ReadonlySet } ): HiddenVmCheckouts { - return hostIds.size === 0 ? checkouts : { ...checkouts, primaryHostIds: hostIds } + 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 + return ( + checkouts.keys.size === 0 && !checkouts.primaryHostIds?.size && !checkouts.hiddenHostIds?.size + ) } function isHiddenCheckout( @@ -41,6 +53,9 @@ function isHiddenCheckout( 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 } @@ -165,7 +180,7 @@ 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( worktrees: W[], checkouts: HiddenVmCheckouts @@ -177,7 +192,7 @@ export function withoutHiddenVmWorktrees( 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( worktreesByRepo: Record, checkouts: HiddenVmCheckouts @@ -185,9 +200,10 @@ export function withoutHiddenVmWorktreesByRepo( if (hidesNothing(checkouts)) { return worktreesByRepo } + const hostScoped = Boolean(checkouts.primaryHostIds?.size || checkouts.hiddenHostIds?.size) let next: Record | null = null - // Host-hidden primaries can sit under any repo; pending checkouts only under theirs. - const repoIds = checkouts.primaryHostIds?.size ? Object.keys(worktreesByRepo) : 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) { @@ -218,7 +234,7 @@ function withoutHiddenRows( 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 diff --git a/src/renderer/src/store/slices/ephemeral-vm/ephemeral-vm-lifecycle.ts b/src/renderer/src/store/slices/ephemeral-vm/ephemeral-vm-lifecycle.ts index 58a4de8049f..21c29db1cee 100644 --- a/src/renderer/src/store/slices/ephemeral-vm/ephemeral-vm-lifecycle.ts +++ b/src/renderer/src/store/slices/ephemeral-vm/ephemeral-vm-lifecycle.ts @@ -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 + /** Live Orca Cloud runtimes' owning team by runtime environment; unfiled ones are absent. */ + cloudAccountIdByEnvironmentId: Record /** Workspaces whose VM resume is in flight; the record only flips when it finishes. */ wakingEphemeralVmWorkspaceIds: Record refreshEphemeralVmRuntimes: () => Promise @@ -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 { + const byEnvironment: Record = {} + 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, b: Record): boolean { + const keys = Object.keys(a) + return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]) +} + function sameRuntimes( a: Record, b: Record @@ -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 => { - 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 diff --git a/src/shared/ephemeral-vm-runtime-store.ts b/src/shared/ephemeral-vm-runtime-store.ts index 608a2f9a046..fd0fa218cac 100644 --- a/src/shared/ephemeral-vm-runtime-store.ts +++ b/src/shared/ephemeral-vm-runtime-store.ts @@ -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() }) diff --git a/src/shared/ephemeral-vm-runtimes.ts b/src/shared/ephemeral-vm-runtimes.ts index 7afc9f38f9e..37ee91ae670 100644 --- a/src/shared/ephemeral-vm-runtimes.ts +++ b/src/shared/ephemeral-vm-runtimes.ts @@ -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:` or `user:`, + * 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 } diff --git a/src/shared/hosted-sandbox/orca-cloud-account.ts b/src/shared/hosted-sandbox/orca-cloud-account.ts new file mode 100644 index 00000000000..98b967022a2 --- /dev/null +++ b/src/shared/hosted-sandbox/orca-cloud-account.ts @@ -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, + activeAccountId: string | null +): boolean { + return activeAccountId !== null && runtime.cloudAccountId === activeAccountId +}