diff --git a/cloud/apps/sandbox-control/src/create-timing.ts b/cloud/apps/sandbox-control/src/create-timing.ts new file mode 100644 index 00000000000..9ad5b27c052 --- /dev/null +++ b/cloud/apps/sandbox-control/src/create-timing.ts @@ -0,0 +1,63 @@ +// Measured sandbox start times for GET /v1/config, so the desktop's "usually ~Ns" hint is a real median. +import type { HostedSandboxTiming } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' + +/** Latest rows only: a cheap rowid scan, and the hint should follow the current pool and image. */ +const RECENT_ROWS = 500 +/** Fewer starts than this is noise, so clients show no hint rather than a guess. */ +export const MIN_TIMING_SAMPLES = 10 +/** + * `ready_at` moves on every wake, so a long gap is a later wake, not a slow start. Real starts + * finish inside the boot budget well before this. + */ +const MAX_START_MS = 120_000 + +function percentile(sorted: readonly number[], fraction: number): number { + const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(fraction * sorted.length) - 1)) + return sorted[index] +} + +export function summarizeStartTimes(durations: readonly number[]): HostedSandboxTiming | undefined { + const sorted = durations.filter((ms) => ms >= 0 && ms <= MAX_START_MS).sort((a, b) => a - b) + if (sorted.length < MIN_TIMING_SAMPLES) { + return undefined + } + return { p50Ms: percentile(sorted, 0.5), p95Ms: percentile(sorted, 0.95), samples: sorted.length } +} + +/** Create-to-ready of the most recent sandboxes; undefined when too few have started. */ +export async function recentCreateTiming(db: D1Database): Promise { + const { results } = await db + .prepare( + `SELECT ready_at - created_at AS ms FROM sandboxes + WHERE ready_at IS NOT NULL + ORDER BY rowid DESC LIMIT ?` + ) + .bind(RECENT_ROWS) + .all<{ ms: number }>() + return summarizeStartTimes(results.map((row) => row.ms)) +} + +const CACHE_MS = 5 * 60_000 +let cache: { db: D1Database; at: number; value: Promise } | null = null + +/** + * GET /v1/config is public, so the query runs at most once per isolate every 5 minutes; a failed + * read is retried on the next request instead of being cached. + */ +export function cachedCreateTiming(db: D1Database, now: number): Promise { + if (cache && cache.db === db && now - cache.at < CACHE_MS) { + return cache.value + } + const entry = { + db, + at: now, + value: recentCreateTiming(db).catch(() => { + if (cache === entry) { + cache = null + } + return undefined + }) + } + cache = entry + return entry.value +} diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 3caf271cbe2..61e8781ec53 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -33,6 +33,7 @@ import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' import { maintainPool, poolConfigFromEnv } from './pool' +import { cachedCreateTiming } from './create-timing' import { authenticateDesktop } from './auth' import { authenticateApi } from './api/caller' import { handleApi, handleApiAs, isApiPath, type ApiContext, type ApiExtension } from './api/router' @@ -767,7 +768,11 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) } if (url.pathname === '/v1/config' && request.method === 'GET') { // Public product constants (no auth): every client reads these instead of hardcoding them. - return json({ idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES }) + const createTiming = await cachedCreateTiming(env.SANDBOX_DB, (deps.now ?? Date.now)()) + return Response.json( + { idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, ...(createTiming ? { createTiming } : {}) }, + { headers: { 'cache-control': 'public, max-age=300' } } + ) } if (url.pathname === '/v1/github/dev-connect' && env.SANDBOX_ENV !== 'prod') { // Dev-only, link-shareable start of the user flow: mints a fresh 10-min state per click for a dev: diff --git a/cloud/apps/sandbox-control/test/config.test.ts b/cloud/apps/sandbox-control/test/config.test.ts index 1d43a6d9da1..7ab866482ea 100644 --- a/cloud/apps/sandbox-control/test/config.test.ts +++ b/cloud/apps/sandbox-control/test/config.test.ts @@ -4,6 +4,7 @@ import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { DEFAULT_PLANS } from '../../billing/src/plans' +import { cachedCreateTiming, MIN_TIMING_SAMPLES, summarizeStartTimes } from '../src/create-timing' import { createHarness } from './harness' describe('GET /v1/config', () => { @@ -14,5 +15,61 @@ describe('GET /v1/config', () => { const body = HostedSandboxConfigResponseSchema.parse(await res.json()) expect(body.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) expect(DEFAULT_PLANS.team.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) + // No sandbox has started yet, so there is no measured start time to advertise. + expect(body.createTiming).toBeUndefined() + }) + + it('advertises the measured start time once enough sandboxes have started', async () => { + const h = await createHarness() + for (let index = 0; index < MIN_TIMING_SAMPLES; index++) { + const created = await h.call('POST', '/v1/sandboxes', { + body: { workspaceId: `ws-${index}`, machineSize: 'standard' }, + // One per user: the per-member running limit would refuse the fourth. + as: `user-${index}` + }) + expect(created.status).toBe(200) + } + const body = HostedSandboxConfigResponseSchema.parse( + await (await h.send(new Request('https://sandbox.test/v1/config'))).json() + ) + expect(body.createTiming?.samples).toBe(MIN_TIMING_SAMPLES) + }) +}) + +describe('summarizeStartTimes', () => { + it('reports p50 and p95 and drops gaps that are later wakes, not starts', () => { + const starts = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10_000, 3_600_000] + expect(summarizeStartTimes(starts)).toEqual({ p50Ms: 5000, p95Ms: 10_000, samples: 10 }) + }) + + it('shows no timing from too few starts', () => { + expect(summarizeStartTimes([1000, 2000])).toBeUndefined() + }) +}) + +describe('cachedCreateTiming', () => { + it('reads D1 at most once per 5 minutes, and retries after a failed read', async () => { + let reads = 0 + let fail = true + const db = { + prepare: () => ({ + bind: () => ({ + all: async () => { + reads++ + if (fail) { + throw new Error('d1 down') + } + return { results: [] } + } + }) + }) + } as unknown as D1Database + expect(await cachedCreateTiming(db, 0)).toBeUndefined() + fail = false + await cachedCreateTiming(db, 1_000) + await cachedCreateTiming(db, 2_000) + expect(reads).toBe(2) + await cachedCreateTiming(db, 1_000 + 5 * 60_000) + expect(reads).toBe(3) }) }) diff --git a/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts new file mode 100644 index 00000000000..8a24c9b655a --- /dev/null +++ b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts @@ -0,0 +1,67 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { + addEnvironmentFromPairingCode, + listEnvironments +} from '../../shared/remote-runtime/host-store/runtime-environment-store' +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { renameLegacyOrcaCloudEnvironments } from './legacy-orca-cloud-environment-names' + +const CLOUD_RUNTIME = '6f1c2a9e-0b4d-4c11-9a3e-7d2f22b5b1e7' +const RECIPE_RUNTIME = '0aa1c2a9-0b4d-4c11-9a3e-7d2f9c0ffee1' + +function runtime( + id: string, + runtimeEnvironmentId: string, + recipeId: string +): EphemeralVmRuntimeRecord { + return { id, recipeId, runtimeEnvironmentId } as EphemeralVmRuntimeRecord +} + +describe('renameLegacyOrcaCloudEnvironments', () => { + let userDataPath: string + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-legacy-cloud-names-')) + }) + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + }) + + function add(name: string, key: number): string { + return addEnvironmentFromPairingCode(userDataPath, { + name, + source: 'ephemeral-vm', + pairingCode: encodePairingOffer({ + v: 2, + endpoint: 'wss://server.example/runtime', + publicKeyB64: Buffer.alloc(32, key).toString('base64'), + deviceToken: `token-${key}` + }), + now: 100 + }).id + } + + it('renames an Orca Cloud server saved as a VM and leaves recipe VMs alone', () => { + const cloud = add('repo VM 22b5b1e7', 1) + const recipe = add('repo VM 9c0ffee1', 2) + + const renamed = renameLegacyOrcaCloudEnvironments(userDataPath, [ + runtime(CLOUD_RUNTIME, cloud, 'cloud'), + runtime(RECIPE_RUNTIME, recipe, 'docker') + ]) + + expect(renamed).toBe(1) + const names = Object.fromEntries( + listEnvironments(userDataPath).map((environment) => [environment.id, environment.name]) + ) + expect(names[cloud]).toBe('repo sandbox 22b5b1e7') + expect(names[recipe]).toBe('repo VM 9c0ffee1') + // Idempotent: a second start finds nothing left to rename. + expect( + renameLegacyOrcaCloudEnvironments(userDataPath, [runtime(CLOUD_RUNTIME, cloud, 'cloud')]) + ).toBe(0) + }) +}) diff --git a/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts new file mode 100644 index 00000000000..3e2e3939a85 --- /dev/null +++ b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts @@ -0,0 +1,55 @@ +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { ORCA_CLOUD_RECIPE_ID } from '../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { normalizeTypedName } from '../../shared/typed-name-normalization' +import { legacyOrcaCloudEnvironmentName } from '../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' +import { + readPersistedEnvironmentStore, + writeEnvironmentStore +} from '../../shared/remote-runtime/host-store/runtime-environment-store-file' + +function isOrcaCloudRuntime(runtime: EphemeralVmRuntimeRecord): boolean { + return runtime.recipe?.provider === 'orca-cloud' || runtime.recipeId === ORCA_CLOUD_RECIPE_ID +} + +/** + * Early builds saved an Orca Cloud server as " VM ", so the sidebar showed it as a + * raw VM. Renames those to the " sandbox " form every surface shows as "Orca Cloud". + * Only servers an Orca Cloud runtime record points at are touched; custom recipe VMs keep "VM". + */ +export function renameLegacyOrcaCloudEnvironments( + userDataPath: string, + runtimes: readonly EphemeralVmRuntimeRecord[] +): number { + const renames = new Map() + for (const runtime of runtimes) { + if (runtime.runtimeEnvironmentId && isOrcaCloudRuntime(runtime)) { + renames.set(runtime.runtimeEnvironmentId, runtime.id) + } + } + if (renames.size === 0) { + return 0 + } + const store = readPersistedEnvironmentStore(userDataPath) + const taken = new Set( + store.environments.map((environment) => normalizeTypedName(environment.name)) + ) + let renamed = 0 + const environments = store.environments.map((environment) => { + const runtimeId = renames.get(environment.id) + const next = + environment.source === 'ephemeral-vm' && runtimeId + ? legacyOrcaCloudEnvironmentName(environment.name, runtimeId) + : null + // Names stay unique: never take one another saved server already has. + if (!next || taken.has(normalizeTypedName(next))) { + return environment + } + taken.add(normalizeTypedName(next)) + renamed++ + return { ...environment, name: next } + }) + if (renamed > 0) { + writeEnvironmentStore(userDataPath, { ...store, environments }) + } + return renamed +} diff --git a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts index 957bf90b87b..c0fd9636c84 100644 --- a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts +++ b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts @@ -21,6 +21,7 @@ import type { ProvisionEphemeralVmRuntimeResult } from './runtime-service' import { cleanupFailedEphemeralVmStart } from './failed-start-cleanup' +import { renameLegacyOrcaCloudEnvironments } from './legacy-orca-cloud-environment-names' export type EphemeralVmWriteAhead = { instanceId: string @@ -160,6 +161,11 @@ export function reconcileInterruptedEphemeralVmProvisionsOnStartup(userDataPath: } catch (error) { console.warn('[ephemeral-vm] Could not reconcile interrupted provisions:', error) } + try { + renameLegacyOrcaCloudEnvironments(userDataPath, listEphemeralVmRuntimes(userDataPath)) + } catch (error) { + console.warn('[ephemeral-vm] Could not rename legacy Orca Cloud servers:', error) + } } /** Tracked VMs must go through Destroy; only result-less write-ahead rows can be dropped by hand. */ diff --git a/src/main/hosted-sandbox/hosted-account-ipc.test.ts b/src/main/hosted-sandbox/hosted-account-ipc.test.ts new file mode 100644 index 00000000000..c2258530261 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-account-ipc.test.ts @@ -0,0 +1,52 @@ +import { afterEach, expect, it, vi } from 'vitest' + +const handlers = new Map unknown>() +const { openExternal } = vi.hoisted(() => ({ openExternal: vi.fn(async () => {}) })) + +vi.mock('electron', () => ({ + ipcMain: { handle: (channel: string, handler: () => unknown) => handlers.set(channel, handler) }, + shell: { openExternal } +})) + +import { ORCA_CLOUD_WORKSPACE_CHANNELS as CH } from '../../shared/hosted-sandbox/cloud-workspace-api' +import { registerHostedAccountHandlers } from './hosted-account-ipc' + +afterEach(() => { + handlers.clear() + vi.clearAllMocks() +}) + +function register(installUrl: string, config = vi.fn(async () => ({ idleSleepMinutes: 15 }))) { + registerHostedAccountHandlers({ + config, + connectGitHub: async () => ({ installUrl, authorizeUrl: installUrl }) + }) + return config +} + +it('opens only a github.com page for Connect GitHub', async () => { + register('https://github.com/apps/orca-cloud-dev/installations/new?state=x') + expect(await handlers.get(CH.connectGitHub)?.()).toEqual({ ok: true, value: null }) + expect(openExternal).toHaveBeenCalledOnce() + + handlers.clear() + register('https://github.com.evil.example/install') + expect(await handlers.get(CH.connectGitHub)?.()).toMatchObject({ ok: false }) + expect(openExternal).toHaveBeenCalledOnce() +}) + +it('reads the config once, and again after a failed read', async () => { + let fail = true + const config = vi.fn(async () => { + if (fail) { + throw new Error('offline') + } + return { idleSleepMinutes: 15 } + }) + register('https://github.com/x', config) + expect(await handlers.get(CH.getConfig)?.()).toBeNull() + fail = false + await handlers.get(CH.getConfig)?.() + await handlers.get(CH.getConfig)?.() + expect(config).toHaveBeenCalledTimes(2) +}) diff --git a/src/main/hosted-sandbox/hosted-account-ipc.ts b/src/main/hosted-sandbox/hosted-account-ipc.ts new file mode 100644 index 00000000000..fcb9c52db80 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-account-ipc.ts @@ -0,0 +1,37 @@ +// Account-level Orca Cloud calls for the window: product config (measured timings) and GitHub connect. +import { ipcMain, shell } from 'electron' +import { ORCA_CLOUD_WORKSPACE_CHANNELS as CH } from '../../shared/hosted-sandbox/cloud-workspace-api' +import type { HostedSandboxConfigResponse } from '../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' +import { failure } from './hosted-workspace-runtime' + +export const HOSTED_ACCOUNT_CHANNELS = [CH.getConfig, CH.connectGitHub] as const + +export function registerHostedAccountHandlers( + client: Pick +): void { + // Timings move slowly and the Worker caches them for 5 minutes; one read per app session is plenty. + let config: Promise | null = null + ipcMain.handle(CH.getConfig, () => { + config ??= client.config().catch(() => { + // Offline now says nothing about later: ask again next time. + config = null + return null + }) + return config + }) + + ipcMain.handle(CH.connectGitHub, async () => { + try { + const { installUrl } = await client.connectGitHub() + // Only ever hand the browser a GitHub page, whatever the response says. + if (new URL(installUrl).origin !== 'https://github.com') { + return { ok: false, code: 'failed', message: 'Unexpected GitHub connect URL.' } + } + await shell.openExternal(installUrl) + return { ok: true, value: null } + } catch (error) { + return failure(error) + } + }) +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts index 800c19b3771..4768d0597f9 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts @@ -12,6 +12,9 @@ export { } from './hosted-sandbox-request' import { HostedSandboxDesktopResponseSchema, + HostedSandboxConfigResponseSchema, + HostedGithubConnectResponseSchema, + type HostedSandboxConfigResponse, HostedArchiveResponseSchema, HostedWakeResponseSchema, HostedWorkspaceStatusResponseSchema, @@ -29,6 +32,9 @@ import { type HostedSandboxReadyResponse, type HostedSandboxView } from '../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { z } from 'zod' + +type HostedGithubConnectResponse = z.infer export type HostedSandboxControlPlaneClient = { create( @@ -71,6 +77,10 @@ export type HostedSandboxControlPlaneClient = { ): Promise /** Starts the VM's remote desktop (idempotent); it listens on the VM's loopback only. */ startDesktop(sandboxId: string, signal?: AbortSignal): Promise + /** Product constants and measured timings (GET /v1/config). */ + config(signal?: AbortSignal): Promise + /** Starts binding a GitHub App installation to the account; the browser finishes it. */ + connectGitHub(signal?: AbortSignal): Promise } export function createHostedSandboxControlPlaneClient( @@ -192,6 +202,13 @@ export function createHostedSandboxControlPlaneClient( kind: 'control', signal }) - ).desktop + ).desktop, + config: (signal) => + call('GET', 'v1/config', HostedSandboxConfigResponseSchema, { kind: 'control', signal }), + connectGitHub: (signal) => + call('POST', 'v1/github/connect', HostedGithubConnectResponseSchema, { + kind: 'control', + signal + }) } } diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index e9a28ae01e1..2885d735584 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -2,7 +2,7 @@ // in-process through the HostedSandboxDriver, and answering like a recipe process would. import { z } from 'zod' import { EphemeralVmRecipeResultSchema } from '../../shared/ephemeral-vm-recipes' -import { ephemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' +import { ephemeralVmFailure, type EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' import { normalizeGitRemoteUrl } from '../../shared/git/remotes/git-remote-identity' import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' import { @@ -61,6 +61,21 @@ export async function hostedSandboxRepoUrl(repoPath: string): Promise, + repoPath: string +): Promise { + if (recipe.provider !== 'orca-cloud' || (await hostedSandboxRepoUrl(repoPath))) { + return null + } + return ephemeralVmFailure('cloudNoGithubRemote') +} + function ok(stdout: string): RecipeStepProviderResult { return { stdout, stderr: '', exitCode: 0, signal: null } } @@ -84,6 +99,13 @@ function failed(error: unknown): RecipeStepProviderResult { failure: ephemeralVmFailure('cloudPlanRequired') } } + if (isEnvironmentProviderError(error, 'conflict') && error.reason === 'github_not_connected') { + return { + ...base, + stderr: `Orca Cloud: ${error.reason}\n`, + failure: ephemeralVmFailure('cloudGithubNotConnected') + } + } if (isEnvironmentProviderError(error, 'unauthorized')) { return { ...base, stderr: '', failure: ephemeralVmFailure('cloudSignInRequired') } } diff --git a/src/main/hosted-sandbox/hosted-workspace-service.ts b/src/main/hosted-sandbox/hosted-workspace-service.ts index 5a86ccb93e8..c471144c35e 100644 --- a/src/main/hosted-sandbox/hosted-workspace-service.ts +++ b/src/main/hosted-sandbox/hosted-workspace-service.ts @@ -2,6 +2,7 @@ // progress and OOM notices. Maps the renderer's workspace id to its Orca Cloud runtime record. import { failQueuedCloudPrompts } from './cloud-offline-service' import { ipcMain, type BrowserWindow } from 'electron' +import { HOSTED_ACCOUNT_CHANNELS, registerHostedAccountHandlers } from './hosted-account-ipc' import { listEphemeralVmRuntimes, updateEphemeralVmRuntimeStatus @@ -168,7 +169,8 @@ export function installHostedWorkspaceService(deps: { CH.archive, CH.unarchive, CH.getArchive, - CH.listCloudWorkspaceIds + CH.listCloudWorkspaceIds, + ...HOSTED_ACCOUNT_CHANNELS ]) { ipcMain.removeHandler(channel) } @@ -182,6 +184,8 @@ export function installHostedWorkspaceService(deps: { .map((runtime) => runtime.workspaceId!) ) + registerHostedAccountHandlers(deps.client) + ipcMain.handle(CH.getStatus, async (_event, args: { workspaceId: string }) => { const found = findCloudRuntime(deps.userDataPath, args.workspaceId) if (!found) { diff --git a/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts new file mode 100644 index 00000000000..c8bc0727955 --- /dev/null +++ b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts @@ -0,0 +1,95 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { registerEphemeralVmRecipeStepProvider } from '../../shared/ephemeral-vm-recipe-step-providers' +import { ORCA_CLOUD_RECIPE } from '../hosted-sandbox/hosted-sandbox-recipe' + +const handlers = new Map unknown>() +const { getPathMock, handleMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(), + handleMock: vi.fn() +})) + +vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, + app: { getPath: getPathMock }, + ipcMain: { handle: handleMock, removeHandler: vi.fn() } +})) + +vi.mock('../hosted-sandbox/hosted-sandbox-install', async (importOriginal) => ({ + ...(await importOriginal()), + withProviderRecipes: async () => [ORCA_CLOUD_RECIPE] +})) + +import { registerEphemeralVmHandlers } from './ephemeral-vm' + +const tempDirs: string[] = [] +const unregister: (() => void)[] = [] + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + for (const off of unregister.splice(0)) { + off() + } + vi.clearAllMocks() +}) + +function setup(remote: string | null) { + const userDataPath = makeTempDir('orca-cloud-remote-user-data-') + const repoPath = makeTempDir('orca-cloud-remote-repo-') + execFileSync('git', ['init', '-q'], { cwd: repoPath }) + if (remote) { + execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: repoPath }) + } + getPathMock.mockReturnValue(userDataPath) + handleMock.mockImplementation((channel: string, handler: never) => handlers.set(channel, handler)) + const step = vi.fn(async () => ({ + stdout: '', + stderr: 'stopped here\n', + exitCode: 1, + signal: null + })) + unregister.push(registerEphemeralVmRecipeStepProvider('orca-cloud', step)) + const repo = { id: 'repo-1', path: repoPath, displayName: 'Repo', addedAt: 0 } + registerEphemeralVmHandlers({ + getRepo: vi.fn((id: string) => (id === repo.id ? repo : null)), + getRepos: vi.fn(() => [repo]), + getSettings: vi.fn(() => ({ activeRuntimeEnvironmentId: null })) + } as never) + const provision = (extra: Record = {}) => + handlers.get('ephemeralVm:provision')?.(null, { + repoId: 'repo-1', + recipeId: ORCA_CLOUD_RECIPE.id, + ...extra + } as never) as Promise<{ ok: boolean; errorCode?: string }> + return { step, provision } +} + +it('refuses a repository with no GitHub remote before Orca Cloud is asked for a sandbox', async () => { + const { step, provision } = setup(null) + const result = await provision() + expect(result).toMatchObject({ ok: false, errorCode: 'cloudNoGithubRemote' }) + expect(step).not.toHaveBeenCalled() +}) + +it('refuses a remote GitHub does not host, too', async () => { + const { step, provision } = setup('https://gitlab.com/acme/web.git') + expect(await provision()).toMatchObject({ ok: false, errorCode: 'cloudNoGithubRemote' }) + expect(step).not.toHaveBeenCalled() +}) + +it('starts the sandbox for a repo on GitHub', async () => { + const github = setup('git@github.com:acme/web.git') + await github.provision() + expect(github.step).toHaveBeenCalledOnce() +}) + +function makeTempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)) + tempDirs.push(dir) + return dir +} diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index acae3e96dca..a1b8be2e052 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -6,6 +6,7 @@ import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtime import { isFolderRepo, isGitRepoKind } from '../../shared/repo-kind' import type { OrcaCloudAvailability, OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' import type { PluginService } from '../plugins/plugin-service' +import { orcaCloudEnvironmentName } from '../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' import { getOrcaCloudAvailability, withProviderRecipes @@ -26,6 +27,17 @@ export type EphemeralVmRecipeListResult = { messageParams?: Record } +export type EphemeralVmProvisionArgs = { + repoId: string + recipeId: string + workspaceName?: string + projectId?: string + workspaceId?: string + branch?: string + ref?: string + provisionId?: string +} + export type EphemeralVmRecipeCatalogEntry = { repoId: string repoName: string @@ -70,7 +82,9 @@ export function buildEphemeralEnvironmentName( runtimeId: string, recipe: { provider?: string } ): string { - return `${repo} ${recipe.provider === 'orca-cloud' ? 'sandbox' : 'VM'} ${runtimeId.slice(-8)}` + return recipe.provider === 'orca-cloud' + ? orcaCloudEnvironmentName(repo, runtimeId) + : `${repo} VM ${runtimeId.slice(-8)}` } /** The Run-on picker's list, plus Orca Cloud availability so it can offer sign-in or an upsell. */ diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 91b22536588..91942f62517 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -35,11 +35,13 @@ import { listPickerRecipes, buildEphemeralEnvironmentName, resolveRecipeForRepo, - type EphemeralVmRecipeCatalogEntry + type EphemeralVmRecipeCatalogEntry, + type EphemeralVmProvisionArgs } from './ephemeral-vm-recipe-context' import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handlers' import type { PluginService } from '../plugins/plugin-service' import { installHostedSandbox, withProviderRecipes } from '../hosted-sandbox/hosted-sandbox-install' +import { refuseOrcaCloudWithoutGithub } from '../hosted-sandbox/hosted-sandbox-recipe' import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' import { @@ -119,19 +121,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin ipcMain.handle( 'ephemeralVm:provision', - async ( - _event, - args: { - repoId: string - recipeId: string - workspaceName?: string - projectId?: string - workspaceId?: string - branch?: string - ref?: string - provisionId?: string - } - ): Promise => { + async (_event, args: EphemeralVmProvisionArgs): Promise => { const repo = getRecipeRepo(store, args.repoId) if (!repo.ok) { return provisionFailure(repo.failure) @@ -144,6 +134,10 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin if (!recipe) { return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) } + const refused = await refuseOrcaCloudWithoutGithub(recipe, repo.repo.path) + if (refused) { + return provisionFailure(refused) + } const controller = args.provisionId ? new AbortController() : null if (args.provisionId && controller) { activeProvisionControllers.set(args.provisionId, controller) diff --git a/src/preload/api/orca-cloud-workspace-bridge.ts b/src/preload/api/orca-cloud-workspace-bridge.ts index e0e01655ba3..b43872e8143 100644 --- a/src/preload/api/orca-cloud-workspace-bridge.ts +++ b/src/preload/api/orca-cloud-workspace-bridge.ts @@ -18,6 +18,8 @@ export const orcaCloudWorkspaceApi = { unarchive: (args) => ipcRenderer.invoke(CH.unarchive, args), getArchive: (args) => ipcRenderer.invoke(CH.getArchive, args), listCloudWorkspaceIds: () => ipcRenderer.invoke(CH.listCloudWorkspaceIds), + getConfig: () => ipcRenderer.invoke(CH.getConfig), + connectGitHub: () => ipcRenderer.invoke(CH.connectGitHub), onWakeProgress: (callback) => { const listener = (_event: Electron.IpcRendererEvent, event: CloudWakeProgressEvent): void => callback(event) diff --git a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx b/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx index 373a69643f5..6353ba2687f 100644 --- a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx +++ b/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx @@ -6,6 +6,7 @@ import { import { NativeChatResumeOccurrenceModal } from './NativeChatResumeOnRestartModal' import { useNativeChatRestartOfferEnabled } from './native-chat-restart-offer-gate' import { useNativeChatRestartRuntimes } from './native-chat-restart-runtimes' +import { runtimeEnvironmentDisplayName } from '../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function NativeChatResumeOnRestartModal(): React.JSX.Element { const enabled = useNativeChatRestartOfferEnabled() @@ -17,7 +18,7 @@ export function NativeChatResumeOnRestartModal(): React.JSX.Element { ))} diff --git a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx index f62405cbfa1..d128804f98c 100644 --- a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx +++ b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx @@ -32,6 +32,7 @@ import { EventTime, ThreadAgentStateIndicator } from './activity-thread-controls import { activityThreadRowCopy, threadAgentStateLabel } from './activity-thread-presentation' import { getActivityThreadWorkspaceTitle } from '@/lib/activity-thread-display' import type { AgentPaneThread } from './activity-thread-types' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function ActivityThreadHoverCardSummary({ thread, @@ -59,7 +60,7 @@ export function ActivityThreadHoverCardSummary({ if (parsedHost?.kind === 'runtime') { const environment = runtimeEnvironments.find((entry) => entry.id === parsedHost.environmentId) if (environment?.name) { - return environment.name + return runtimeEnvironmentDisplayName(environment) } } if (parsedHost?.kind === 'ssh') { diff --git a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts index eb694afb229..9a8ae93052b 100644 --- a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts @@ -14,6 +14,7 @@ import type { AutomationsPageListState } from './use-automations-page-list-state import type { AutomationsPageLocalState } from './use-automations-page-local-state' import type { AutomationsPageStoreState } from './use-automations-page-store-state' import { useTranslate } from '../../i18n/use-translate' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' /** Display labels and action availability derived from the selected host row. */ export function useAutomationsPagePresentationState({ @@ -96,7 +97,10 @@ export function useAutomationsPagePresentationState({ labels.set(`ssh:${encodeURIComponent(targetId)}`, label) } for (const environment of runtimeEnvironments) { - labels.set(`runtime:${encodeURIComponent(environment.id)}`, environment.name) + labels.set( + `runtime:${encodeURIComponent(environment.id)}`, + runtimeEnvironmentDisplayName(environment) + ) } for (const [hostId, label] of hostLabelOverrides) { labels.set(hostId, label) diff --git a/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts b/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts index f74338407ed..45bffb83a04 100644 --- a/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts +++ b/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts @@ -19,6 +19,7 @@ import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-ov import { isFolderRepo } from '../../../../shared/repo-kind' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export type ActiveDashboardWorkspace = { projectId: string @@ -48,7 +49,7 @@ function buildHostLabelLookup( labels.set(toSshExecutionHostId(targetId), label) } for (const environment of state.runtimeEnvironments ?? []) { - labels.set(toRuntimeExecutionHostId(environment.id), environment.name) + labels.set(toRuntimeExecutionHostId(environment.id), runtimeEnvironmentDisplayName(environment)) } for (const [hostId, label] of getHostDisplayLabelOverrides(state.settings)) { labels.set(hostId, label) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx index 4600efedba4..cd22eb3311f 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx @@ -8,10 +8,22 @@ import { } from '@/lib/workspace/creation/pending-worktree-creation' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' +import { vmBuildFailureSummary } from '@/components/worktree-creation/vm-build-failure-toast' +import type { Repo } from '../../../../../../shared/repo-types' -function statusLabel(entry: PendingWorktreeCreation, t: Translate = translate): string { +function statusLabel( + entry: PendingWorktreeCreation, + repos: readonly Repo[], + t: Translate = translate +): string { if (entry.status === 'error') { + // An Orca Cloud refusal reads like its build-sheet card, never the raw provider text. + const cloud = + entry.request.ephemeralVmRecipe?.provider === 'orca-cloud' && entry.error + ? vmBuildFailureSummary(entry, entry.error, repos, t) + : null return ( + cloud?.title ?? entry.error ?? t('auto.components.sidebar.PendingWorktreeRow.creationFailed', 'Creation failed') ) @@ -47,6 +59,7 @@ export function PendingWorktreeRow({ const t = useTranslate() const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) const active = useAppStore((s) => s.activePendingCreationId === creationId) + const repos = useAppStore((s) => s.repos) if (!entry) { return } @@ -89,7 +102,7 @@ export function PendingWorktreeRow({ isError ? 'text-destructive/90' : 'text-muted-foreground' )} > - {statusLabel(entry, t)} + {statusLabel(entry, repos, t)} diff --git a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx index 49d3805fa3c..fccfc97f648 100644 --- a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx @@ -12,6 +12,7 @@ import { import { useNativeChatRestartRuntimes } from '../native-chat-restart-runtimes' import { resumeRunInFlight } from '../native-chat-resume-run' import { resumeRunFailures, resumeRunView } from '../native-chat-resume-run-view' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' // Keep offers and in-flight/results visible after dialog snooze; statusBarItems must not hide the remaining resume surface. @@ -153,7 +154,7 @@ export function NativeChatResumeStatusSegment({ key={environment.id} iconOnly={iconOnly} store={store} - machineName={environment.name} + machineName={runtimeEnvironmentDisplayName(environment)} offerEnabled /> ))} diff --git a/src/renderer/src/components/status-bar/SshStatusSegment.tsx b/src/renderer/src/components/status-bar/SshStatusSegment.tsx index f26680b1ba7..bce1b1966ee 100644 --- a/src/renderer/src/components/status-bar/SshStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/SshStatusSegment.tsx @@ -42,6 +42,7 @@ import { import { runtimeHostConnectionStateForEntry } from '@/runtime/hosts/connections/runtime-host-connection-state' import { isConnectedRuntimeHostState } from '../../../../shared/remote-runtime/host-status/runtime-host-connection-state' import { RuntimeRepairDialog } from '../runtime-access/RuntimeRepairDialog' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function SshStatusSegment({ compact, @@ -110,7 +111,7 @@ export function SshStatusSegment({ const repairRoute = runtimePairingRepairRoute(environment) return { id: environment.id, - label: registryHost?.label || environment.name || environment.id, + label: registryHost?.label || runtimeEnvironmentDisplayName(environment) || environment.id, blockedReason, blocked: blockedReason ? { diff --git a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts index 70256b50b4f..221237bf4a4 100644 --- a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts +++ b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts @@ -16,6 +16,7 @@ import { type OwnerUsageFailureReason, type OwnerUsageState } from './owner-usage-rate-limits' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' // Why: accounts.list({refreshUsage}) waits for the host's provider fetches. const REMOTE_USAGE_REFRESH_TIMEOUT_MS = 30_000 @@ -59,9 +60,10 @@ export function useOwnerUsageRateLimits(local: RateLimitState): OwnerUsageRateLi // Why: route by the focused workspace's owner, never by the Active Server setting. const { target } = useActiveAccountOwner(LOCAL_TARGET) const ownerId = runtimeTargetEnvironmentId(target) - const ownerName = useAppStore( - (s) => s.runtimeEnvironments.find((environment) => environment.id === ownerId)?.name ?? null - ) + const ownerName = useAppStore((s) => { + const environment = s.runtimeEnvironments.find((entry) => entry.id === ownerId) + return environment ? runtimeEnvironmentDisplayName(environment) : null + }) const [owned, setOwned] = useState(null) const ownedRef = useRef(null) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index c74991e69da..6411647f7ad 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -3,15 +3,18 @@ import { Bot, ChevronDown, CreditCard, + Github, Loader2, + LifeBuoy, LogIn, + PanelLeft, Pencil, RotateCcw, - Sparkles, SquareArrowOutUpRight, Trash2 } from 'lucide-react' import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' import { DropdownMenu, DropdownMenuContent, @@ -30,6 +33,10 @@ export type VmBuildFailureActions = { onSeePlans: () => void onOpenBilling: () => void onSignIn: () => void + onShowWorkspaces: () => void + onContactSupport: () => void + onConnectGitHub: () => void + onPushToGitHub: () => void } type Action = { @@ -38,6 +45,8 @@ type Action = { icon?: React.ReactNode onClick: () => void disabled?: boolean + /** In progress: stays focusable (aria-disabled + aria-busy) so keyboard focus isn't dropped. */ + pending?: boolean } /** At most two visible actions; the rest sit in a More menu so the way forward stays obvious. */ @@ -45,7 +54,9 @@ function failureActions( failure: VmBuildFailure, cloud: boolean, canFixWithAgent: boolean, + canManageBilling: boolean, signingIn: boolean, + connectingGitHub: boolean, actions: VmBuildFailureActions, t: Translate ): { primary: Action[]; more: Action[] } { @@ -75,32 +86,40 @@ function failureActions( { key: 'plans', label: t('auto.lib.orcaCloudSession.seePlans', 'See plans'), - icon: , onClick: actions.onSeePlans } ], more: [] } case 'hoursUsed': + case 'spendCap': case 'payment': + // Members can't change billing; their card tells them who can. return { - primary: [ - { - key: 'billing', - label: - failure.kind === 'payment' - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.updatePayment', - 'Update payment method' - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.manageBilling', - 'Manage billing' - ), - icon: , - onClick: actions.onOpenBilling - } - ], + primary: canManageBilling + ? [ + { + key: 'billing', + label: + failure.kind === 'payment' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.updatePayment', + 'Update payment method' + ) + : failure.kind === 'spendCap' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.raiseSpendCap', + 'Raise spend cap' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.turnOnOverage', + 'Turn on overage' + ), + icon: , + onClick: actions.onOpenBilling + } + ] + : [], more: [] } case 'signIn': @@ -113,7 +132,7 @@ function failureActions( : t('auto.components.worktree.creation.VmBuildFailureCard.signIn', 'Sign in'), icon: signingIn ? : , onClick: actions.onSignIn, - disabled: signingIn + pending: signingIn } ], more: [] @@ -153,9 +172,78 @@ function failureActions( more: [editRecipe] } case 'concurrency': + case 'memberConcurrency': + return { + primary: [ + { + key: 'workspaces', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.showWorkspaces', + 'Show cloud workspaces' + ), + icon: , + onClick: actions.onShowWorkspaces + }, + tryAgain + ], + more: [] + } + case 'snapshotMissing': + return { + primary: [tryAgain], + more: [ + { + key: 'support', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.contactSupport', + 'Contact support' + ), + icon: , + onClick: actions.onContactSupport + } + ] + } + case 'githubNotConnected': + return { + primary: [ + { + key: 'connectGitHub', + label: connectingGitHub + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.openingGitHub', + 'Opening GitHub…' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.connectGitHub', + 'Connect GitHub' + ), + icon: connectingGitHub ? : , + onClick: actions.onConnectGitHub, + pending: connectingGitHub + }, + tryAgain + ], + more: [] + } + case 'noGithubRemote': + return { + primary: [ + { + key: 'pushToGitHub', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.howToPushToGitHub', + 'How to push to GitHub' + ), + icon: , + onClick: actions.onPushToGitHub + }, + // After pushing, the same create works without leaving the sheet. + tryAgain + ], + more: [] + } case 'unavailable': case 'network': - case 'snapshotMissing': case 'create': return { primary: [tryAgain], more: [] } } @@ -166,7 +254,9 @@ export function FailureActionRow({ cloud, vmKept, canFixWithAgent, + canManageBilling, signingIn, + connectingGitHub, actions, t }: { @@ -174,11 +264,22 @@ export function FailureActionRow({ cloud: boolean vmKept: boolean canFixWithAgent: boolean + canManageBilling: boolean signingIn: boolean + connectingGitHub: boolean actions: VmBuildFailureActions t: Translate }): React.JSX.Element { - const { primary, more } = failureActions(failure, cloud, canFixWithAgent, signingIn, actions, t) + const { primary, more } = failureActions( + failure, + cloud, + canFixWithAgent, + canManageBilling, + signingIn, + connectingGitHub, + actions, + t + ) // Leaving a build that still holds a VM destroys it, so say so on the button. const destroys = vmKept return ( @@ -189,8 +290,10 @@ export function FailureActionRow({ type="button" size="xs" variant={index === 0 ? 'default' : 'outline'} - onClick={action.onClick} + onClick={action.pending ? undefined : action.onClick} disabled={action.disabled} + aria-disabled={action.pending || undefined} + aria-busy={action.pending || undefined} > {action.icon} {action.label} @@ -223,7 +326,8 @@ export function FailureActionRow({ variant={destroys ? 'destructive-chip' : 'ghost'} size="xs" onClick={actions.onDismiss} - className="ml-auto" + // Leaving is the quiet way out; only deleting a running sandbox earns the destructive chip. + className={cn('ml-auto', !destroys && 'text-muted-foreground hover:text-foreground')} > {destroys ? : null} {destroys diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx new file mode 100644 index 00000000000..80c51125f67 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment happy-dom + +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { VmBuildFailureCard, type VmBuildFailureActions } from './VmBuildFailureCard' +import type { VmBuildFailure } from './vm-build-failure' + +afterEach(cleanup) + +const actions = (): VmBuildFailureActions => ({ + onFixWithAgent: vi.fn(), + onRetry: vi.fn(), + onEditRecipe: vi.fn(), + onOpenAnyway: vi.fn(), + onDismiss: vi.fn(), + onSeePlans: vi.fn(), + onOpenBilling: vi.fn(), + onSignIn: vi.fn(), + onShowWorkspaces: vi.fn(), + onContactSupport: vi.fn(), + onConnectGitHub: vi.fn(), + onPushToGitHub: vi.fn() +}) + +function Sheet({ + failure, + connectingGitHub = false, + handlers +}: { + failure: VmBuildFailure | null + connectingGitHub?: boolean + handlers: VmBuildFailureActions +}) { + return ( +
+

+ Starting your cloud workspace +

+ +
+ ) +} + +it('announces only the cause and lands focus on it, then on the sheet heading after Try again', () => { + const handlers = actions() + const { rerender } = render() + const alert = screen.getByRole('alert') + expect(alert.textContent).toContain('Orca Cloud is unavailable right now') + // The buttons are read on demand, not announced with the cause. + expect(alert.querySelector('button')).toBeNull() + expect(document.activeElement?.textContent).toBe('Orca Cloud is unavailable right now') + + const retry = screen.getByRole('button', { name: /Try again/ }) + retry.focus() + fireEvent.click(retry) + expect(handlers.onRetry).toHaveBeenCalledOnce() + act(() => rerender()) + expect(document.activeElement?.hasAttribute('data-vm-build-heading')).toBe(true) +}) + +it('keeps a pending Connect GitHub focusable and ignores repeat clicks', () => { + const handlers = actions() + render() + const button = screen.getByRole('button', { name: /Opening GitHub/ }) + expect(button.hasAttribute('disabled')).toBe(false) + expect(button.getAttribute('aria-busy')).toBe('true') + button.focus() + fireEvent.click(button) + expect(handlers.onConnectGitHub).not.toHaveBeenCalled() + expect(document.activeElement).toBe(button) +}) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index 973110e2334..3b34cc9768a 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -16,7 +16,10 @@ export function VmBuildFailureCard({ vmKept, firstErrorLine, canFixWithAgent, + canManageBilling, signingIn, + connectingGitHub, + repoName, actions }: { failure: VmBuildFailure | null @@ -27,7 +30,11 @@ export function VmBuildFailureCard({ /** First error in the build log, shown under a recipe's terse exit message. */ firstErrorLine: string | null canFixWithAgent: boolean + canManageBilling: boolean signingIn: boolean + connectingGitHub: boolean + /** How the user knows the repository, for cards that name it. */ + repoName: string actions: VmBuildFailureActions }): React.JSX.Element { const t = useTranslate() @@ -46,18 +53,26 @@ export function VmBuildFailureCard({ setShown(failure) } const visible = failure ?? shown - const copy = visible ? vmBuildFailureCopy(visible, cloud, t) : null - const headingRef = React.useRef(null) + const copy = visible + ? vmBuildFailureCopy(visible, { cloud, canManageBilling, repoName }, t) + : null + const headingRef = React.useRef(null) + const cardRef = React.useRef(null) // Move focus to the card when it opens, so keyboard and screen-reader users land on the way forward. React.useEffect(() => { + const card = cardRef.current + const sheet = card?.closest('[data-vm-build-sheet]') + const active = document.activeElement if (open) { - const heading = headingRef.current - const active = document.activeElement // Never pull focus out of something the user is typing in elsewhere. - const sheet = heading?.closest('[data-vm-build-sheet]') - if (heading && (!active || active === document.body || sheet?.contains(active))) { - heading.focus({ preventScroll: true }) + if (!active || active === document.body || sheet?.contains(active)) { + headingRef.current?.focus({ preventScroll: true }) } + return + } + // A Retry collapses (and inerts) the card under the focused button, so hand focus to the sheet. + if (active && card?.contains(active)) { + sheet?.querySelector('[data-vm-build-heading]')?.focus({ preventScroll: true }) } }, [open, run]) const detail = @@ -70,11 +85,12 @@ export function VmBuildFailureCard({ {visible && copy ? (
-
-
+

{copy.title} -

+ {copy.body ? (

{copy.body}

) : null} @@ -103,7 +119,9 @@ export function VmBuildFailureCard({ cloud={cloud} vmKept={vmKept} canFixWithAgent={canFixWithAgent} + canManageBilling={canManageBilling} signingIn={signingIn} + connectingGitHub={connectingGitHub} actions={actions} t={t} /> diff --git a/src/renderer/src/components/worktree-creation/VmBuildLog.tsx b/src/renderer/src/components/worktree-creation/VmBuildLog.tsx index e2d2ce3c389..beabea4878d 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildLog.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildLog.tsx @@ -46,8 +46,8 @@ export function VmBuildLog({ stamps: readonly number[] startedAt: number emptyLabel: string - /** Rewrites a line for display; copy still takes the raw log. */ - formatLine?: (line: string) => string + /** Rewrites a line for display, or hides it with null; Copy log still takes the raw log. */ + formatLine?: (line: string) => string | null }): React.JSX.Element { const t = useTranslate() const ref = React.useRef(null) @@ -55,16 +55,19 @@ export function VmBuildLog({ const pinnedToBottomRef = React.useRef(true) const [copied, setCopied] = React.useState(false) // The sheet re-renders every clock tick; only a new log needs re-scanning. - const rows = React.useMemo( - () => - splitBuildLog(log).map((line, position) => ({ - // Lines only append or trim from the front, so position plus text identifies a row. - id: `${position}:${line}`, - text: formatLine ? formatLine(line) : line, - isError: isBuildLogErrorLine(line) - })), - [log, formatLine] - ) + const { rows, hiddenCount } = React.useMemo(() => { + const all = splitBuildLog(log).map((line, position) => ({ + // Lines only append or trim from the front, so position plus text identifies a row. + id: `${position}:${line}`, + text: formatLine ? formatLine(line) : line, + stamp: stamps[position], + isError: isBuildLogErrorLine(line) + })) + const visible = all.filter( + (row): row is (typeof all)[number] & { text: string } => row.text !== null + ) + return { rows: visible, hiddenCount: all.length - visible.length } + }, [log, formatLine, stamps]) const firstError = rows.findIndex((row) => row.isError) const handleScroll = React.useCallback((): void => { @@ -110,8 +113,20 @@ export function VmBuildLog({ return (
- {rows.length > 0 ? ( + {log !== '' ? (
+ {hiddenCount > 0 ? ( + + {t( + 'auto.components.worktree.creation.VmBuildLog.hiddenTechnicalLines', + '{{count}} technical lines hidden. Copy log includes them.', + { + count: hiddenCount, + defaultValue_one: '{{count}} technical line hidden. Copy log includes it.' + } + )} + + ) : null} {firstError !== -1 ? ( +
+ {building ? ( + + ) : null}
-
    - {steps.map((step) => ( - - ))} - {cloudAgentStep ?? } - {agentSignInRow ?? - (entry.vmEnvironmentId ? ( - + {steps.map((step) => ( + - ) : null)} -
+ ))} + {cloudAgentStep !== undefined ? ( + cloudAgentStep + ) : ( + + )} + {agentSignInRow ?? + (entry.vmEnvironmentId ? ( + + ) : null)} + + )} { if (recipe) { @@ -239,38 +277,44 @@ export function VmBuildSheet({ store.openSettingsTarget({ pane: 'orca-account', repoId: null }) store.openSettingsPage() }, - onSignIn: signIn + onSignIn: signIn, + onShowWorkspaces: () => useAppStore.getState().setSidebarOpen(true), + onContactSupport: () => openAppHttpLink(SUPPORT_URL), + onConnectGitHub: connectGitHub, + onPushToGitHub: () => openAppHttpLink(PUSH_TO_GITHUB_URL) }} />
{building ? : null} - {cloud ? ( - + ) : null} - {logOpen ? ( + {logOpen && !gated ? ( ) } - -function StepRow({ - step, - cloud, - detail, - t -}: { - step: VmBuildStep - cloud: boolean - /** What the running step is doing right now, in plain words. */ - detail: string | null - t: Translate -}): React.JSX.Element { - const labelId = React.useId() - const typical = - cloud && step.state === 'running' ? ORCA_CLOUD_TYPICAL_STEP_SECONDS[step.id] : null - const slow = typical !== null && step.elapsedMs !== null && step.elapsedMs > typical * 2000 - - return ( -
  • -
    - - - {stepLabel(step, cloud, t)} - - {stepStateLabel(step.state, t)} - {typical !== null ? ( - - {slow - ? t('auto.components.worktree.creation.VmBuildSheet.slow', 'Taking longer than usual') - : t( - 'auto.components.worktree.creation.VmBuildSheet.usually', - 'usually ~{{seconds}}s', - { seconds: typical } - )} - - ) : null} - {step.percent !== null ? ( - - {step.percent}% - - ) : null} - {step.elapsedMs !== null && step.state !== 'pending' ? ( - - {formatElapsedTime(step.elapsedMs)} - - ) : null} -
    - {detail ?

    {detail}

    : null} - {step.percent !== null ? ( - - ) : null} -
  • - ) -} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx new file mode 100644 index 00000000000..fec59dc74aa --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx @@ -0,0 +1,162 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { + CLOUD_FAILED_LOG, + CLOUD_LOG, + CLOUD_RECIPE, + entry, + FAILED_LOG, + LOG, + frame, + seedFixtureRepo, + T0 +} from './vm-build-sheet-fixture-support' + +// Orca Cloud refusals and failures, one card each. + +function cloudFailure(errorCode: string | undefined, error: string, log = CLOUD_LOG) { + return frame( + entry({ status: 'error', errorCode, provisioningLog: log, errorAt: T0 + 2_000 }, CLOUD_RECIPE), + error, + T0 + 2_000 + ) +} + +export const cloudPlanRequired = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours. Open Plan & billing to choose one.', + '' +) + +export const cloudConcurrencyLimit = cloudFailure( + 'cloudConcurrencyLimit', + 'You already have as many Orca Cloud workspaces running as your plan allows.', + '' +) + +export const cloudUnavailable = cloudFailure( + 'cloudUnavailable', + 'Orca Cloud is unavailable right now. Try again in a moment.', + '' +) + +export const cloudSignInRequired = cloudFailure( + 'cloudSignInRequired', + 'Sign in to Orca to use Orca Cloud workspaces.', + '' +) + +export const cloudSnapshotMissing = cloudFailure( + 'recipeExited', + 'Recipe exited with code 1.', + FAILED_LOG +) + +export const cloudSpendCap = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: overage_cap_reached` +) + +// A team member: billing is someone else's to change, so the card says who can. +function asMember(fixture: ReturnType) { + return defineFixture({ + ...fixture, + setup: () => { + seedFixtureRepo() + window.api.orcaProfiles.billingStatus = () => + Promise.resolve({ + status: 'ok', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the card reads only canManageBilling. + entitlement: { canManageBilling: false } as never + }) + } + }) +} + +export const cloudHoursUsedMember = asMember( + cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: included_hours_exhausted` + ) +) + +export const cloudSpendCapMember = asMember( + cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: overage_cap_reached` + ) +) + +export const cloudPaymentFailedMember = asMember( + cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: payment_past_due` + ) +) + +export const cloudPlanRequiredMember = asMember( + cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours. Open Plan & billing to choose one.', + '' + ) +) + +export const cloudMemberConcurrency = cloudFailure( + 'cloudConcurrencyLimit', + 'You already have as many Orca Cloud workspaces running as your plan allows.', + `${CLOUD_LOG}\nOrca Cloud: member_concurrency_limit` +) + +export const cloudGithubNotConnected = cloudFailure( + 'cloudGithubNotConnected', + 'Connect GitHub to your Orca account so Orca Cloud can clone this repository.', + `${CLOUD_LOG}\nOrca Cloud: github_not_connected` +) + +export const cloudGithubNotConnectedHttps = defineFixture({ + ...cloudGithubNotConnected, + setup: () => seedFixtureRepo('https://github.com/nwparker/orca-sandbox-push-test.git') +}) + +// Refused on this computer before the control plane is asked: no sandbox, no charge. +export const cloudNoGithubRemote = defineFixture({ + ...cloudFailure( + 'cloudNoGithubRemote', + 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote.', + '' + ), + setup: () => seedFixtureRepo(null) +}) + +export const cloudFailedLogsOpen = defineFixture({ + ...cloudFailure('cloudUnavailable', 'Orca Cloud is unavailable right now.', CLOUD_FAILED_LOG), + interact: (frameElement) => { + Array.from(frameElement.querySelectorAll('button')) + .find((button) => button.textContent?.includes('View logs')) + ?.click() + } +}) + +export const cloudFailed = cloudFailure( + 'recipeExited', + 'Recipe exited with code 1.', + `${LOG}\nfatal: sandbox agent stopped unexpectedly` +) + +export const cloudHoursUsed = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: included_hours_exhausted` +) + +export const cloudPaymentDue = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: payment_past_due` +) + +export const cloudNetwork = cloudFailure(undefined, 'fetch failed', CLOUD_LOG) diff --git a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx new file mode 100644 index 00000000000..d3ba56c50b0 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx @@ -0,0 +1,91 @@ +import React from 'react' +import { CircleSlash } from 'lucide-react' +import { cn } from '@/lib/utils' +import type { Translate } from '@/i18n/use-translate' +import { Progress } from '@/components/ui/progress' +import { StepIcon } from './WorktreeSetupSteps' +import type { VmBuildStep } from './vm-build-steps' +import { typicalStepSeconds, type VmBuildStepTiming } from './vm-build-timing' +import { formatElapsedTime } from './worktree-creation-clock' +import { stepLabel, stepStateLabel } from './vm-build-sheet-copy' + +/** One timed row of the build checklist; the failure card, not the row, carries the red. */ +export function VmBuildStepRow({ + step, + cloud, + detail, + timing, + t +}: { + step: VmBuildStep + cloud: boolean + /** The step's measured duration, when there is one. */ + timing: VmBuildStepTiming | null + /** What the running step is doing right now, in plain words. */ + detail: string | null + t: Translate +}): React.JSX.Element { + const labelId = React.useId() + // A live percent already says how far along the step is. + const hint = step.state === 'running' && step.percent === null ? timing : null + const slow = hint !== null && step.elapsedMs !== null && step.elapsedMs > hint.p95Ms + + return ( +
  • +
    + {step.skipped ? ( + + ) : ( + + )} + + {stepLabel(step, cloud, t)} + + + {step.skipped + ? t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped') + : stepStateLabel(step.state, t)} + + {step.skipped ? ( + + {t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')} + + ) : null} + {hint ? ( + + {slow + ? t('auto.components.worktree.creation.VmBuildSheet.slow', 'Taking longer than usual') + : t( + 'auto.components.worktree.creation.VmBuildSheet.usually', + 'usually ~{{seconds}}s', + { seconds: typicalStepSeconds(hint) } + )} + + ) : null} + {step.percent !== null ? ( + + {step.percent}% + + ) : null} + {step.elapsedMs !== null && step.state !== 'pending' ? ( + + {formatElapsedTime(step.elapsedMs)} + + ) : null} +
    + {detail ?

    {detail}

    : null} + {step.percent !== null ? ( + + ) : null} +
  • + ) +} diff --git a/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx b/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx new file mode 100644 index 00000000000..ac670a9ad29 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx @@ -0,0 +1,69 @@ +import type React from 'react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { useTranslate } from '@/i18n/use-translate' + +/** Leaving a build that still holds a VM deletes it; ask first, wherever the leave came from. */ +export function VmDeleteConfirmDialog({ + open, + cloud, + onOpenChange, + onConfirm +}: { + open: boolean + cloud: boolean + onOpenChange: (open: boolean) => void + onConfirm: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( + + + + + {cloud + ? t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.titleCloud', + 'Delete this sandbox?' + ) + : t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.titleVm', + 'Delete this VM?' + )} + + + {cloud + ? t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.bodyCloud', + 'The sandbox and anything on it are deleted, and the workspace isn’t created.' + ) + : t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.bodyVm', + 'The VM and anything on it are destroyed, and the workspace isn’t created.' + )} + + + + + + + + + ) +} diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index 14fc169c1e1..51033961eba 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -11,6 +11,7 @@ import { useTranslate } from '@/i18n/use-translate' import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' import { formatElapsedTime, useWorktreeCreationClock } from './worktree-creation-clock' import { VmBuildSheet } from './VmBuildSheet' +import { VmDeleteConfirmDialog } from './VmDeleteConfirmDialog' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ export default function WorktreeCreationPanel({ @@ -23,6 +24,7 @@ export default function WorktreeCreationPanel({ const t = useTranslate() const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) const progressLabelId = React.useId() + const [confirmingDelete, setConfirmingDelete] = React.useState(false) const checksFinishedAt = entry?.environmentCheck?.status === 'failed' ? entry.environmentCheck.finishedAt : undefined // Depend on primitives so stderr’s fresh entry objects cannot continuously reset the interval; @@ -35,11 +37,17 @@ export default function WorktreeCreationPanel({ } const dismiss = (): void => useAppStore.getState().removePendingWorktreeCreation(creationId) + // A failed or paused VM build still holds a VM that dismissing deletes, so confirm first. + const holdsVm = + entry.environmentCheck?.status === 'failed' || + (entry.status === 'error' && Boolean(entry.request.ephemeralVmRuntimeId)) + const leave = holdsVm ? () => setConfirmingDelete(true) : dismiss const isError = entry.status === 'error' // A VM build keeps its sheet through fetch and checkout, so it never drops to the one-line status. const isVmCreation = Boolean(entry.request.ephemeralVmRecipe) || entry.phase === 'provisioning-vm' const title = entry.request.displayName || entry.request.name - const elapsedLabel = formatElapsedTime((checksFinishedAt ?? now) - entry.startedAt) + const stoppedAt = checksFinishedAt ?? (isError ? entry.errorAt : undefined) + const elapsedLabel = formatElapsedTime((stoppedAt ?? now) - entry.startedAt) const checkoutProgress = getVisibleCheckoutProgress(entry) return ( @@ -48,8 +56,19 @@ export default function WorktreeCreationPanel({ title={title} isError={isError} reserveCollapsedSidebarHeaderSpace={reserveCollapsedSidebarHeaderSpace} - onCancel={dismiss} + onCancel={leave} /> + {holdsVm ? ( + { + setConfirmingDelete(false) + dismiss() + }} + /> + ) : null}
    {isVmCreation ? ( @@ -70,7 +89,7 @@ export default function WorktreeCreationPanel({ } onCancel={dismiss} onRetry={() => retryBackgroundWorktreeCreation(creationId)} - onDismiss={dismiss} + onDismiss={leave} onEditRecipe={() => { const state = useAppStore.getState() state.openSettingsTarget({ diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx index 0cba5eecb5b..88fcd828edc 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx @@ -41,11 +41,11 @@ export default function WorktreeCreationTabStrip({ type="button" title={t('auto.components.worktree.creation.WorktreeCreationPanel.532aea14ce', 'Cancel')} aria-label={t( - 'auto.components.worktree.creation.WorktreeCreationPanel.a3346fc6ed', - 'Cancel worktree creation' + 'auto.components.worktree.creation.WorktreeCreationTabStrip.cancelLabel', + 'Cancel workspace creation' )} onClick={onCancel} - className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground" + className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-1 focus-visible:outline-focus-ring" > diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx index f2df248bd9a..a1575b6951a 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx @@ -7,6 +7,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { formatElapsedTime } from './worktree-creation-clock' import type { WorktreeSetupStep, WorktreeSetupStepId } from './worktree-setup-steps' +import { stepStateLabel } from './vm-build-sheet-copy' function stepLabel(id: WorktreeSetupStepId, agentLabel: string, t: Translate = translate): string { switch (id) { @@ -41,7 +42,7 @@ export function StepIcon({ state }: { state: WorktreeSetupStep['state'] }): Reac case 'failed': return case 'pending': - return + return } } @@ -79,6 +80,7 @@ export function WorktreeSetupSteps({ > {stepLabel(step.id, agentLabel, t)} + {stepStateLabel(step.state, t)} {step.percent !== null ? ( {step.percent}% ) : null} diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 2bf39cbdbc6..4082ee88ead 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -1,7 +1,10 @@ import type { Translate } from '@/i18n/use-translate' -// The hosted provider streams `[orca-cloud] ` progress lines; show them as words, not codes. +// The hosted provider writes `[orca-cloud] ` progress, `Orca Cloud: ` and a few +// fixed transport messages. Everything else is provider internals that the plain view hides. const PHASE_LINE = /^\[orca-cloud\] ([a-z-]+)$/ +const DENY_LINE = /^Orca Cloud: ([a-z_ ]+)$/ +const REFUSED_LINE = /^Orca Cloud refused the request \(([a-z_]+)\)\.$/ function phaseLabel(phase: string, t: Translate): string | null { switch (phase) { @@ -25,15 +28,151 @@ function phaseLabel(phase: string, t: Translate): string | null { 'auto.components.worktree.creation.orcaCloudBuildLog.connecting', 'Connecting to the sandbox…' ) + case 'resuming': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.resuming', + 'Waking the sandbox…' + ) + case 'suspending': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.suspending', + 'Putting the sandbox to sleep…' + ) + case 'renewing': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.renewing2', + 'Keeping the sandbox running…' + ) + case 'rolling-over': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.rollingOver', + 'Starting a fresh session…' + ) + case 'destroying': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.destroying', + 'Deleting the sandbox…' + ) default: return null } } -/** A progress line in plain words; any other line is returned unchanged. */ -export function humanizeOrcaCloudLogLine(line: string, t: Translate): string { - const phase = PHASE_LINE.exec(line.trim())?.[1] - return (phase && phaseLabel(phase, t)) ?? line +function denyLabel(reason: string, t: Translate): string | null { + switch (reason) { + case 'no plan': + case 'no_subscription': + case 'subscription_inactive': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyNoPlan', + 'Your account has no active Team plan.' + ) + case 'included_hours_exhausted': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyHours2', + 'Your team is out of sandbox hours this month.' + ) + case 'overage_cap_reached': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denySpendCap', + 'This month’s spend cap is reached.' + ) + case 'payment_past_due': + case 'payment_grace_expired': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyPayment2', + 'Payment failed.' + ) + case 'concurrency_limit': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyConcurrency2', + 'You’re at your team’s limit of running sandboxes.' + ) + case 'member_concurrency_limit': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyMemberConcurrency2', + 'You’re at your limit of running sandboxes.' + ) + case 'github_not_connected': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyGithub', + 'GitHub isn’t connected to your Orca account.' + ) + case 'machine_size_not_in_plan': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyMachineSize2', + 'This sandbox size isn’t part of your plan.' + ) + default: + return null + } +} + +function refusedLabel(code: string, t: Translate): string { + switch (code) { + case 'billing_unavailable': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedBilling', + 'Orca Cloud couldn’t check your plan.' + ) + case 'provider_unavailable': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedProvider2', + 'Orca Cloud is unavailable right now.' + ) + case 'not_configured': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedNotConfigured', + 'Orca Cloud isn’t set up on the server.' + ) + case 'unauthorized': + case 'forbidden': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedSignIn', + 'Orca Cloud needs you to sign in again.' + ) + default: + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refused', + 'Orca Cloud refused the request.' + ) + } +} + +/** A provider line in plain words, or null when it is an internal detail the plain view hides. */ +export function humanizeOrcaCloudLogLine(line: string, t: Translate): string | null { + const text = line.trim() + const phase = PHASE_LINE.exec(text)?.[1] + if (phase) { + return phaseLabel(phase, t) + } + const reason = DENY_LINE.exec(text)?.[1] + if (reason) { + return denyLabel(reason, t) + } + const refused = REFUSED_LINE.exec(text)?.[1] + if (refused) { + return refusedLabel(refused, t) + } + if (/^Orca Cloud request failed \(HTTP \d+\)\.$/.test(text)) { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.httpError', + 'Orca Cloud answered with an error.' + ) + } + if (text === 'Could not reach Orca Cloud.') { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.unreachable', + 'Couldn’t reach Orca Cloud.' + ) + } + if (text === 'Orca Cloud did not answer in time.') { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.timeout', + 'Orca Cloud didn’t answer in time.' + ) + } + return null } // "Starting the sandbox…" would only repeat the step's own label. diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index 538b6031b30..35f65e34928 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -1,10 +1,18 @@ import type { Translate } from '@/i18n/use-translate' import type { VmBuildFailure } from './vm-build-failure' -/** The card's title and one plain-language sentence on what happened and what to do. */ +export type VmBuildFailureCopyContext = { + cloud: boolean + /** How the user knows the repository: its GitHub owner/name, else its name in Orca. */ + repoName: string + /** False for team members who can't change billing; they are told to ask an owner or admin. */ + canManageBilling: boolean +} + +/** The card's cause-specific title and one plain-language sentence on what to do next. */ export function vmBuildFailureCopy( failure: VmBuildFailure, - cloud: boolean, + { cloud, canManageBilling, repoName }: VmBuildFailureCopyContext, t: Translate ): { title: string; body: string | null } { switch (failure.kind) { @@ -32,42 +40,108 @@ export function vmBuildFailureCopy( 'auto.components.worktree.creation.VmBuildFailureCard.planTitle', 'Orca Cloud needs a Team plan' ), - body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.planBody', - 'Cloud workspaces are part of the Team plan. Nothing was created, and you weren’t charged.' - ) + body: canManageBilling + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.planBody2', + 'Cloud workspaces are part of the Team plan. Nothing was created, and you weren’t charged.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.planBodyMember2', + 'Ask an owner or admin to choose a Team plan. Nothing was created, and you weren’t charged.' + ) } case 'hoursUsed': return { title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.hoursUsedTitle', - 'You’ve used this period’s sandbox hours' + 'auto.components.worktree.creation.VmBuildFailureCard.outOfHoursTitle', + 'Out of sandbox hours' ), - body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.hoursUsedBody', - 'Raise your overage limit or wait for your hours to reset. Nothing was created.' - ) + body: canManageBilling + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.outOfHoursBody', + 'Your team has used this month’s sandbox hours. Turn on overage to keep starting sandboxes. Nothing was created, and you weren’t charged.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.outOfHoursBodyMember', + 'Your team has used this month’s sandbox hours. Ask an owner or admin to add hours. Nothing was created, and you weren’t charged.' + ) + } + case 'spendCap': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapReachedTitle', + 'Spend cap reached' + ), + body: canManageBilling + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapReachedBody', + 'Your team has reached this month’s spend cap. Raise it to keep starting sandboxes. Nothing was created, and you weren’t charged.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapReachedBodyMember', + 'Your team has reached this month’s spend cap. Ask an owner or admin to add hours. Nothing was created, and you weren’t charged.' + ) } case 'payment': return { title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.paymentTitle', - 'Your Orca payment needs attention' + 'auto.components.worktree.creation.VmBuildFailureCard.paymentFailedTitle', + 'Payment failed' ), - body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.paymentBody', - 'Update your payment method to start cloud workspaces again. Nothing was created.' - ) + body: canManageBilling + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.paymentFailedBody', + 'New sandboxes can’t start until the payment goes through. Nothing was created, and you weren’t charged.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.paymentFailedBodyMember', + 'New sandboxes can’t start until the payment goes through. Ask an owner or admin to update the payment method. Nothing was created, and you weren’t charged.' + ) } case 'concurrency': return { title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.concurrencyTitle', - 'All your cloud workspaces are in use' + 'auto.components.worktree.creation.VmBuildFailureCard.teamLimitTitle', + 'You’re at your team’s limit of running sandboxes' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.concurrencyBody', - 'You’ve reached your plan’s limit on running cloud workspaces. Put one to sleep or delete it from the sidebar, then try again.' + 'auto.components.worktree.creation.VmBuildFailureCard.limitBody', + 'Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.' + ) + } + case 'memberConcurrency': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.memberLimitTitle', + 'You’re at your limit of running sandboxes' + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.limitBody', + 'Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.' + ) + } + case 'githubNotConnected': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.githubNotConnectedTitle', + 'GitHub isn’t connected for {{repo}}', + { repo: repoName } + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.githubNotConnectedBody', + 'Orca Cloud clones your code from GitHub and needs access to this repository first. Connect GitHub, then try again. Nothing was created, and you weren’t charged.' + ) + } + case 'noGithubRemote': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.noGithubRemoteTitle', + '{{repo}} isn’t on GitHub', + { repo: repoName } + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.noGithubRemoteBody2', + 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again. Nothing was created, and you weren’t charged.' ) } case 'signIn': @@ -77,8 +151,8 @@ export function vmBuildFailureCopy( 'Sign in to use Orca Cloud' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.signInBody', - 'Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you.' + 'auto.components.worktree.creation.VmBuildFailureCard.signInBody3', + 'Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created, and you weren’t charged.' ) } case 'unavailable': @@ -88,8 +162,8 @@ export function vmBuildFailureCopy( 'Orca Cloud is unavailable right now' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.unavailableBody', - 'The problem is on our side, not in your project. Nothing was created. Try again in a moment.' + 'auto.components.worktree.creation.VmBuildFailureCard.unavailableBody2', + 'The problem is on our side, not in your project. Nothing was created, and you weren’t charged. Try again in a moment.' ) } case 'network': @@ -99,8 +173,8 @@ export function vmBuildFailureCopy( 'Couldn’t reach Orca Cloud' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.networkBody', - 'Check your internet connection, then try again.' + 'auto.components.worktree.creation.VmBuildFailureCard.networkBody3', + 'Check your internet connection, then try again. Nothing was created, and you weren’t charged.' ) } case 'snapshotMissing': @@ -110,35 +184,47 @@ export function vmBuildFailureCopy( 'This project’s saved environment is missing' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.snapshotBody', - 'The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Try again; if it keeps happening, contact support.' + 'auto.components.worktree.creation.VmBuildFailureCard.snapshotBody3', + 'The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created, and you weren’t charged. Try again, or contact support if it keeps happening.' ) } case 'provision': - return { - title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.createFailedTitle', - 'Couldn’t create workspace' - ), - body: cloud - ? t( + return cloud + ? { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.provisionTitleCloud', + 'The sandbox didn’t start' + ), + body: t( 'auto.components.worktree.creation.VmBuildFailureCard.provisionBodyCloud', 'Something went wrong while starting the sandbox. Try again, or open the logs for details.' ) - : failure.error - } + } + : { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.provisionTitleVm', + 'The VM recipe failed' + ), + body: failure.error + } case 'create': - return { - title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.createFailedTitle', - 'Couldn’t create workspace' - ), - body: cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.createBodyCloud', - 'Your sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details.' + return cloud + ? { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createTitleCloud', + 'Couldn’t open the workspace on the sandbox' + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createBodyCloud2', + 'The sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details.' ) - : failure.error - } + } + : { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createTitleVm', + 'Couldn’t create the workspace on the VM' + ), + body: failure.error + } } } diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts new file mode 100644 index 00000000000..2651fff4057 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts @@ -0,0 +1,54 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { classifyVmBuildFailure, type VmBuildFailure } from './vm-build-failure' +import { vmBuildFailureCopy } from './vm-build-failure-copy' +import { isOrcaCloudBuild } from './vm-build-steps' +import { orcaCloudRepoName } from './vm-build-repo-actions' +import type { Repo } from '../../../../shared/repo-types' + +/** The build sheet card's words for a failed VM build, for surfaces that show it off the sheet. */ +export function vmBuildFailureSummary( + entry: PendingWorktreeCreation, + error: string, + repos: readonly Repo[], + t: Translate = translate +): { failure: VmBuildFailure; title: string; body: string | null } | null { + const cloud = isOrcaCloudBuild(entry) + const failure = classifyVmBuildFailure({ entry, error, cloud }) + if (!failure) { + return null + } + const recipe = entry.request.ephemeralVmRecipe + const repoName = orcaCloudRepoName( + recipe ? repos.find((repo) => repo.id === recipe.sourceRepoId) : undefined + ) + // Unknown here; the card itself refines the copy for members once billing status loads. + return { failure, ...vmBuildFailureCopy(failure, { cloud, canManageBilling: true, repoName }, t) } +} + +/** The build sheet's card as a toast, for a VM build that failed while its sheet was off screen. */ +export function showVmBuildFailureToast( + entry: PendingWorktreeCreation, + error: string, + repos: readonly Repo[] +): void { + const summary = vmBuildFailureSummary(entry, error, repos) + if (!summary) { + return + } + const { failure, title, body } = summary + toast.error(title, { + ...(body ? { description: body } : {}), + ...(failure.kind === 'plan' + ? { + action: { + label: translate('auto.lib.orcaCloudSession.seePlans', 'See plans'), + onClick: () => openPlansPage('sandbox') + } + } + : {}) + }) +} diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts new file mode 100644 index 00000000000..e7b7d9cdd03 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from 'vitest' +import { classifyVmBuildFailure, isAccountGate, type VmBuildFailure } from './vm-build-failure' +import { vmBuildFailureCopy } from './vm-build-failure-copy' +import { orcaCloudRepoName } from './vm-build-repo-actions' + +// English defaults with {{slots}} filled, like i18next with no catalog. +const t = ((_key: string, fallback: string, params?: Record) => + fallback.replace(/\{\{(\w+)\}\}/g, (_slot, name: string) => + String(params?.[name] ?? '') + )) as Parameters[2] + +function classify( + errorCode: string | undefined, + log = '', + error = 'failed' +): VmBuildFailure | null { + return classifyVmBuildFailure({ + entry: { + phase: 'provisioning-vm', + errorCode, + provisioningLog: log, + environmentCheck: undefined + }, + error, + cloud: true + }) +} + +describe('classifyVmBuildFailure', () => { + it('names each control-plane refusal from its streamed deny reason', () => { + const kinds = Object.fromEntries( + [ + ['cloudPlanRequired', 'included_hours_exhausted'], + ['cloudPlanRequired', 'overage_cap_reached'], + ['cloudPlanRequired', 'payment_grace_expired'], + ['cloudConcurrencyLimit', 'member_concurrency_limit'], + ['cloudConcurrencyLimit', 'concurrency_limit'] + ].map(([code, reason]) => [reason, classify(code, `Orca Cloud: ${reason}`)?.kind]) + ) + expect(kinds).toEqual({ + included_hours_exhausted: 'hoursUsed', + overage_cap_reached: 'spendCap', + payment_grace_expired: 'payment', + member_concurrency_limit: 'memberConcurrency', + concurrency_limit: 'concurrency' + }) + expect(classify('cloudPlanRequired')?.kind).toBe('plan') + }) + + it('treats GitHub refusals as gates that started nothing', () => { + for (const code of ['cloudGithubNotConnected', 'cloudNoGithubRemote']) { + expect(isAccountGate(classify(code))).toBe(true) + } + }) +}) + +describe('vmBuildFailureCopy', () => { + const kinds: VmBuildFailure[] = [ + { kind: 'plan' }, + { kind: 'hoursUsed' }, + { kind: 'spendCap' }, + { kind: 'payment' }, + { kind: 'concurrency' }, + { kind: 'memberConcurrency' }, + { kind: 'githubNotConnected' }, + { kind: 'noGithubRemote' }, + { kind: 'signIn' }, + { kind: 'unavailable' }, + { kind: 'network' }, + { kind: 'snapshotMissing' }, + { kind: 'provision', error: 'Recipe exited with code 1.' }, + { kind: 'create', error: 'checkout failed' } + ] + + it('never shows codes, ids or banned glossary terms on an Orca Cloud card', () => { + for (const canManageBilling of [true, false]) { + for (const failure of kinds) { + const { title, body } = vmBuildFailureCopy( + failure, + { cloud: true, canManageBilling, repoName: 'acme/web' }, + t + ) + const text = `${title} ${body ?? ''}` + expect(text).not.toMatch( + /[a-z]+_[a-z]+|\bVM\b|included hours|hours exhausted|overage limit/ + ) + // Nothing exists yet at create time, so there are no files to reassure about. + expect(text).not.toContain('Your files are safe') + } + } + }) + + it('uses the glossary titles and role-aware next steps for billing refusals', () => { + const copy = (kind: VmBuildFailure, canManageBilling: boolean) => + vmBuildFailureCopy(kind, { cloud: true, canManageBilling, repoName: 'acme/web' }, t) + expect(copy({ kind: 'hoursUsed' }, true).title).toBe('Out of sandbox hours') + expect(copy({ kind: 'spendCap' }, true).title).toBe('Spend cap reached') + expect(copy({ kind: 'payment' }, true).title).toBe('Payment failed') + expect(copy({ kind: 'hoursUsed' }, false).body).toContain('Ask an owner or admin to add hours.') + expect(copy({ kind: 'payment' }, false).body).toContain( + 'Ask an owner or admin to update the payment method.' + ) + }) + + it('names the repository GitHub needs to reach', () => { + const { title } = vmBuildFailureCopy( + { kind: 'githubNotConnected' }, + { cloud: true, canManageBilling: true, repoName: 'acme/web' }, + t + ) + expect(title).toBe('GitHub isn’t connected for acme/web') + }) +}) + +describe('orcaCloudRepoName', () => { + it('prefers the GitHub owner/name, falling back to the name in Orca', () => { + expect( + orcaCloudRepoName({ + displayName: 'web', + gitRemoteIdentity: { remoteUrl: 'git@github.com:acme/web.git' } + } as never) + ).toBe('acme/web') + expect(orcaCloudRepoName({ displayName: 'web', gitRemoteIdentity: null })).toBe('web') + }) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index f0c4ee23dfb..db4a9bb6bef 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -5,8 +5,13 @@ import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-w export type VmBuildAccountFailureKind = | 'plan' | 'hoursUsed' + | 'spendCap' | 'payment' | 'concurrency' + | 'memberConcurrency' + | 'githubNotConnected' + /** Refused before the control plane was asked: the sandbox could not clone this repository. */ + | 'noGithubRemote' | 'signIn' | 'unavailable' | 'network' @@ -24,16 +29,20 @@ const ERROR_CODE_KINDS: Partial> = { cloudPlanRequired: 'plan', cloudConcurrencyLimit: 'concurrency', cloudSignInRequired: 'signIn', - cloudUnavailable: 'unavailable' + cloudUnavailable: 'unavailable', + cloudGithubNotConnected: 'githubNotConnected', + cloudNoGithubRemote: 'noGithubRemote' } // The hosted provider logs the control plane's deny reason as `Orca Cloud: `. const DENY_REASON = /^Orca Cloud: ([a-z_]+)$/m const DENY_REASON_KINDS: Partial> = { included_hours_exhausted: 'hoursUsed', - overage_cap_reached: 'hoursUsed', + overage_cap_reached: 'spendCap', payment_past_due: 'payment', - payment_grace_expired: 'payment' + payment_grace_expired: 'payment', + concurrency_limit: 'concurrency', + member_concurrency_limit: 'memberConcurrency' } const SNAPSHOT_MISSING = /\bsnapshot\b[^\n]*\bnot found\b/i @@ -58,9 +67,9 @@ export function classifyVmBuildFailure(args: { return null } const coded = entry.errorCode ? ERROR_CODE_KINDS[entry.errorCode] : undefined - if (coded === 'plan') { + if (coded === 'plan' || coded === 'concurrency') { const reason = DENY_REASON.exec(entry.provisioningLog ?? '')?.[1] - return { kind: (reason === undefined ? undefined : DENY_REASON_KINDS[reason]) ?? 'plan' } + return { kind: (reason === undefined ? undefined : DENY_REASON_KINDS[reason]) ?? coded } } if (coded) { return { kind: coded } @@ -83,11 +92,39 @@ export function classifyVmBuildFailure(args: { const ACCOUNT_GATES: ReadonlySet = new Set([ 'plan', 'hoursUsed', + 'spendCap', 'payment', 'signIn', - 'concurrency' + 'concurrency', + 'memberConcurrency', + 'githubNotConnected', + 'noGithubRemote' ]) +// Nothing started, so no step failed: steps stay pending instead of showing a red failure. +const NOTHING_STARTED: ReadonlySet = new Set([ + ...ACCOUNT_GATES, + 'unavailable', + 'network', + // Refused while picking the saved environment, before any sandbox existed. + 'snapshotMissing' +]) + +export function nothingStarted(failure: VmBuildFailure | null): boolean { + return failure !== null && NOTHING_STARTED.has(failure.kind) +} + +/** Billing refusals an owner or admin fixes in Plan & billing. */ +export function isBillingFailure(failure: VmBuildFailure | null): boolean { + return ( + failure !== null && + (failure.kind === 'plan' || + failure.kind === 'hoursUsed' || + failure.kind === 'spendCap' || + failure.kind === 'payment') + ) +} + /** Refused before anything started: an account limit, not a broken build. */ export function isAccountGate(failure: VmBuildFailure | null): boolean { return failure !== null && ACCOUNT_GATES.has(failure.kind) diff --git a/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts new file mode 100644 index 00000000000..3de7a828003 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts @@ -0,0 +1,33 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { normalizeGitRemoteUrl } from '../../../../shared/git/remotes/git-remote-identity' +import type { Repo } from '../../../../shared/repo-types' + +/** GitHub's guide to publishing a local repository: the fix for a repo Orca Cloud can't clone. */ +export const PUSH_TO_GITHUB_URL = + 'https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github' + +/** The repository as the user knows it: its GitHub owner/name, else its name in Orca. */ +export function orcaCloudRepoName( + repo: Pick | undefined +): string { + const remote = repo?.gitRemoteIdentity?.remoteUrl + const normalized = remote ? normalizeGitRemoteUrl(remote) : null + if (normalized?.startsWith('github.com/')) { + return normalized.slice('github.com/'.length) + } + return repo?.displayName ?? '' +} + +/** Opens GitHub so the account can give Orca Cloud access; the user comes back and tries again. */ +export async function connectOrcaCloudGitHub(): Promise { + const result = await window.api.orcaCloudWorkspace.connectGitHub().catch(() => null) + if (!result?.ok) { + toast.error( + translate( + 'auto.components.worktree.creation.VmBuildFailureCard.connectGitHubFailed', + 'Couldn’t open GitHub. Try again in a moment.' + ) + ) + } +} diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx new file mode 100644 index 00000000000..26f66cb9b16 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -0,0 +1,111 @@ +// Shared builders for the VM build sheet fixtures. +import React from 'react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { VmBuildSheet } from './VmBuildSheet' +import { formatElapsedTime } from './worktree-creation-clock' +import type { VmBuildStepTimings } from './vm-build-timing' +import { useAppStore } from '@/store' +import type { Repo } from '../../../../shared/repo-types' + +export const LOG_LINES = [ + 'Creating sandbox from snapshot snap_7f2c…', + 'Sandbox ready: sbx_41d9 (us-east-1)', + 'Cloning repository…', + 'Starting orca serve on :7420', + 'Pairing code emitted.' +] +export const LOG = LOG_LINES.join('\n') +// Every fixture is drawn 102 seconds into its build, with lines arriving a second or so apart. +export const T0 = 1_700_000_000_000 +export const NOW = T0 + 102_000 +export const stampsFor = (lines: number): number[] => + Array.from({ length: lines }, (_, index) => T0 + 400 + index * 1300) + +export type Recipe = NonNullable +export const LOCAL_RECIPE: Recipe = { sourceRepoId: 'repo', recipeId: 'sandbox', projectId: 'p' } +export const CLOUD_RECIPE: Recipe = { ...LOCAL_RECIPE, recipeId: 'cloud', provider: 'orca-cloud' } + +export function entry( + patch: Partial, + recipe: Recipe = LOCAL_RECIPE +): PendingWorktreeCreation { + const log = patch.provisioningLog ?? LOG + return { + creationId: 'fixture', + phase: 'provisioning-vm', + status: 'creating', + startedAt: T0, + indeterminate: false, + loaderVisible: true, + provisioningLog: log, + provisioningLogStamps: stampsFor(log === '' ? 0 : log.split('\n').length), + phaseLog: [{ phase: 'provisioning-vm', at: T0 }], + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only name and ephemeralVmRecipe from the request. + request: { name: 'fix-login', ephemeralVmRecipe: recipe } as PendingWorktreeCreation['request'], + ...patch + } +} + +export function sheet( + value: PendingWorktreeCreation, + error: string | null, + now: number, + agentSignInRow?: React.ReactNode +) { + return ( +
    + {}} + onRetry={() => {}} + onDismiss={() => {}} + onEditRecipe={() => {}} + agentSignInRow={agentSignInRow} + stepTimings={FIXTURE_STEP_TIMINGS} + cloudAgentStep={null} + /> +
    + ) +} + +// What the dev control plane measured (GET /v1/config): starts p50 2.9 s, p95 4.0 s. +const FIXTURE_STEP_TIMINGS: VmBuildStepTimings = { provision: { p50Ms: 2_900, p95Ms: 4_000 } } + +/** The repository a cloud card names: a GitHub remote reads as owner/name. */ +export function seedFixtureRepo(remoteUrl: string | null = 'git@github.com:acme/web.git'): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only id, displayName and gitRemoteIdentity. + const repo = { + id: 'repo', + displayName: 'web', + gitRemoteIdentity: remoteUrl ? { remoteUrl } : null + } as unknown as Repo + useAppStore.setState({ repos: [repo] }) +} + +export function frame( + value: PendingWorktreeCreation, + error: string | null = null, + now = NOW, + agentSignInRow?: React.ReactNode +) { + return defineFixture({ + width: 760, + setup: () => seedFixtureRepo(), + render: () => sheet(value, error, now, agentSignInRow) + }) +} + +export const CLOUD_LOG = '[orca-cloud] checking-entitlement\n[orca-cloud] provisioning' +// What the provider really prints around a failure: progress, internals the plain view hides, and the cause. +export const CLOUD_FAILED_LOG = [ + '[orca-cloud] checking-entitlement', + '[orca-cloud] provisioning', + 'sandbox sbx_41d9 scheduled on pool p-use1-3', + 'Orca Cloud refused the request (provider_unavailable).' +].join('\n') +export const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found` diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts index b3807a4e7fb..fa862cd1a26 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts @@ -6,6 +6,7 @@ import { appendStampedLog } from '@/lib/pending-creation-provisioning-log' import { deriveVmBuildSteps } from './vm-build-steps' import { classifyVmBuildFailure } from './vm-build-failure' import { holdRunningSteps } from './use-minimum-running-steps' +import { humanizeOrcaCloudLogLine } from './orca-cloud-build-log' const base = { status: 'creating' as const, @@ -31,18 +32,58 @@ describe('deriveVmBuildSteps', () => { 10_000 ) expect(steps).toEqual([ - { id: 'provision', state: 'done', elapsedMs: 5000, percent: null, startedAt: 1000 }, - { id: 'checks', state: 'done', elapsedMs: 3000, percent: null, startedAt: 6000 }, - { id: 'create', state: 'running', elapsedMs: 1000, percent: 40, startedAt: 9000 } + { + id: 'provision', + state: 'done', + elapsedMs: 5000, + percent: null, + startedAt: 1000, + skipped: false + }, + { + id: 'checks', + state: 'done', + elapsedMs: 3000, + percent: null, + startedAt: 6000, + skipped: false + }, + { + id: 'create', + state: 'running', + elapsedMs: 1000, + percent: 40, + startedAt: 9000, + skipped: false + } ]) }) - it('marks the workspace step failed when creation fails after the VM is up', () => { + it('marks the workspace step failed, with how long it ran, when creation fails on the VM', () => { const steps = deriveVmBuildSteps( - { ...base, status: 'error', phase: 'fetching', environmentCheck: { status: 'passed' } }, - 5000 + { + ...base, + status: 'error', + phase: 'fetching', + phaseLog: [ + { phase: 'provisioning-vm', at: 1000 }, + { phase: 'fetching', at: 4000 } + ], + errorAt: 6500, + environmentCheck: { status: 'passed' } + }, + 9000 ) expect(steps.map((step) => step.state)).toEqual(['done', 'done', 'failed']) + expect(steps[2].elapsedMs).toBe(2500) + }) + + it('shows skipped checks as skipped, not verified and not stuck pending', () => { + const steps = deriveVmBuildSteps( + { ...base, phase: 'fetching', environmentCheck: { status: 'skipped' } }, + 5000 + ) + expect(steps[1]).toMatchObject({ state: 'done', skipped: true }) }) it('reads as done once the worktree exists and is opening', () => { @@ -81,6 +122,20 @@ describe('classifyVmBuildFailure', () => { ).toEqual({ kind: 'hoursUsed' }) }) + it('tells a member limit apart from the team limit, and a spend cap from used hours', () => { + const refused = (errorCode: string, reason: string) => + classifyVmBuildFailure({ + entry: { ...entry, errorCode, provisioningLog: `Orca Cloud: ${reason}\n` }, + error: 'x', + cloud: true + }) + expect(refused('cloudConcurrencyLimit', 'member_concurrency_limit')).toEqual({ + kind: 'memberConcurrency' + }) + expect(refused('cloudConcurrencyLimit', 'concurrency_limit')).toEqual({ kind: 'concurrency' }) + expect(refused('cloudPlanRequired', 'overage_cap_reached')).toEqual({ kind: 'spendCap' }) + }) + it('names a missing snapshot only for Orca Cloud', () => { const failed = { entry: { ...entry, provisioningLog: 'Error: snapshot snap_1 not found' }, @@ -126,3 +181,17 @@ describe('holdRunningSteps', () => { ]) }) }) + +describe('humanizeOrcaCloudLogLine', () => { + const t = ((_key: string, fallback: string) => fallback) as Parameters< + typeof humanizeOrcaCloudLogLine + >[1] + + it('turns provider codes into sentences and hides internals', () => { + expect(humanizeOrcaCloudLogLine('Orca Cloud: included_hours_exhausted', t)).toBe( + 'Your team is out of sandbox hours this month.' + ) + expect(humanizeOrcaCloudLogLine('[orca-cloud] resuming', t)).toBe('Waking the sandbox…') + expect(humanizeOrcaCloudLogLine('sandbox sbx_41d9 scheduled on pool p-use1-3', t)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.ts index 2ac721b967b..7428734ee72 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.ts @@ -10,6 +10,8 @@ export type VmBuildStepId = 'provision' | 'checks' | 'create' export type VmBuildStep = { id: VmBuildStepId state: WorktreeSetupStepState + /** Done without running: an older VM server has no environment checks. */ + skipped: boolean /** Time spent so far (running) or in total (done/failed); null when unknown. */ elapsedMs: number | null /** Git's checkout percent while the workspace step checks out files. */ @@ -18,15 +20,6 @@ export type VmBuildStep = { startedAt: number | null } -/** Typical Orca Cloud step durations in seconds, shown as "usually ~Ns" while a step runs. */ -export const ORCA_CLOUD_TYPICAL_STEP_SECONDS: Record = { - provision: 5, - checks: 3, - create: 2 -} - -type StepCore = Omit - type VmBuildEntry = Pick< PendingWorktreeCreation, | 'status' @@ -36,6 +29,7 @@ type VmBuildEntry = Pick< | 'startedAt' | 'checkoutProgress' | 'worktreeId' + | 'errorAt' > export function isOrcaCloudBuild(entry: Pick): boolean { @@ -53,9 +47,27 @@ function span(start: number | undefined, end: number | undefined): number | null return start === undefined || end === undefined ? null : Math.max(0, end - start) } +function step( + id: VmBuildStepId, + state: WorktreeSetupStepState, + elapsedMs: number | null, + startedAt: number | undefined, + extra: Partial> = {} +): VmBuildStep { + return { + id, + state, + elapsedMs, + startedAt: startedAt ?? null, + skipped: extra.skipped ?? false, + percent: extra.percent ?? null + } +} + /** * Provision, then the VM's environment checks, then the workspace (fetch + checkout, folded into one - * row). A failed step keeps the steps before it done; a worktree id means the workspace is opening. + * row). A failed step keeps the steps before it done and shows how long it ran; a worktree id means + * the workspace is opening. */ export function deriveVmBuildSteps(entry: VmBuildEntry, now: number): VmBuildStep[] { const check = entry.environmentCheck @@ -66,58 +78,35 @@ export function deriveVmBuildSteps(entry: VmBuildEntry, now: number): VmBuildSte const createAt = phaseStart(entry, ['fetching', 'creating']) const provisionDone = Boolean(check) || workspacePhase - const provision: StepCore = provisionDone - ? { - id: 'provision', - state: 'done', - elapsedMs: span(provisionAt, check?.startedAt ?? createAt), - percent: null - } - : { - id: 'provision', - state: failed ? 'failed' : 'running', - elapsedMs: failed ? null : span(provisionAt, now), - percent: null - } + const provision = provisionDone + ? step('provision', 'done', span(provisionAt, check?.startedAt ?? createAt), provisionAt) + : failed + ? step('provision', 'failed', span(provisionAt, entry.errorAt), provisionAt) + : step('provision', 'running', span(provisionAt, now), provisionAt) - const checksState: WorktreeSetupStepState = !check - ? 'pending' + const checks = !check + ? step('checks', 'pending', null, undefined) : check.status === 'running' - ? 'running' - : check.status === 'failed' - ? 'failed' - : // An older VM server ran nothing, so the step must not read as verified. - check.status === 'skipped' - ? 'pending' - : 'done' - const checks: StepCore = { - id: 'checks', - state: checksState, - elapsedMs: - checksState === 'running' - ? span(check?.startedAt, now) - : checksState === 'pending' - ? null - : span(check?.startedAt, check?.finishedAt), - percent: null - } + ? step('checks', 'running', span(check.startedAt, now), check.startedAt) + : check.status === 'skipped' + ? // An older VM server ran nothing, so the step says so instead of reading as verified. + step('checks', 'done', null, check.startedAt, { skipped: true }) + : step( + 'checks', + check.status === 'failed' ? 'failed' : 'done', + span(check.startedAt, check.finishedAt), + check.startedAt + ) - const create: StepCore = !workspacePhase - ? { id: 'create', state: 'pending', elapsedMs: null, percent: null } + const create = !workspacePhase + ? step('create', 'pending', null, undefined) : ready - ? { id: 'create', state: 'done', elapsedMs: span(createAt, now), percent: null } + ? step('create', 'done', span(createAt, now), createAt) : failed - ? { id: 'create', state: 'failed', elapsedMs: null, percent: null } - : { - id: 'create', - state: 'running', - elapsedMs: span(createAt, now), + ? step('create', 'failed', span(createAt, entry.errorAt), createAt) + : step('create', 'running', span(createAt, now), createAt, { percent: getVisibleCheckoutProgress(entry)?.percent ?? null - } + }) - return [ - { ...provision, startedAt: provisionAt }, - { ...checks, startedAt: check?.startedAt ?? null }, - { ...create, startedAt: workspacePhase ? (createAt ?? null) : null } - ] + return [provision, checks, create] } diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts new file mode 100644 index 00000000000..ae045586dc5 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -0,0 +1,61 @@ +import React from 'react' +import type { HostedSandboxTiming } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { VmBuildStepId } from './vm-build-steps' + +/** p50 drives the "usually ~Ns" hint; past p95 the step reads as slower than usual. */ +export type VmBuildStepTiming = Pick + +export type VmBuildStepTimings = Partial> + +const NONE: VmBuildStepTimings = {} + +// One read per window: the control plane measures recent sandbox starts (GET /v1/config) and +// main caches the answer, so every build sheet shows the same median. +let measured: VmBuildStepTimings | null = null +let pending: Promise | null = null + +function loadMeasuredTimings(): Promise { + pending ??= (window.api.orcaCloudWorkspace?.getConfig?.() ?? Promise.resolve(null)) + .then((config) => { + if (!config) { + // Unreachable now says nothing about later: the next sheet asks again. + pending = null + return NONE + } + // Only "Start sandbox" is measured. Without a measurement there is no hint, never a guess. + measured = config.createTiming ? { provision: config.createTiming } : NONE + return measured + }) + .catch(() => { + pending = null + return NONE + }) + return pending +} + +/** Measured Orca Cloud step timings; empty for VM recipes and until the control plane answers. */ +export function useVmBuildStepTimings(cloud: boolean): VmBuildStepTimings { + const [timings, setTimings] = React.useState(() => + cloud ? (measured ?? NONE) : NONE + ) + React.useEffect(() => { + if (!cloud || measured) { + return + } + let live = true + void loadMeasuredTimings().then((next) => { + if (live) { + setTimings(next) + } + }) + return () => { + live = false + } + }, [cloud]) + return cloud ? (measured ?? timings) : NONE +} + +/** The hint in whole seconds, never "~0s". */ +export function typicalStepSeconds(timing: VmBuildStepTiming): number { + return Math.max(1, Math.round(timing.p50Ms / 1000)) +} diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index a411a75ed6a..bbcfd5d5afd 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1287,6 +1287,14 @@ } } } + }, + "worktree": { + "creation": { + "VmBuildLog": { + "hiddenTechnicalLines_one": "{{count}} technical line hidden. Copy log includes it.", + "hiddenTechnicalLines_other": "{{count}} technical lines hidden. Copy log includes them." + } + } } }, "hooks": { @@ -2121,20 +2129,22 @@ "cleanupInterrupted": "Cleanup was interrupted. Retry cleanup to continue.", "cleanupStopped": "Cleanup stopped by user.", "cloudConcurrencyLimit": "You already have as many Orca Cloud workspaces running as your plan allows. Sleep or delete one, then try again.", + "cloudGithubNotConnected": "Connect GitHub to your Orca account so Orca Cloud can clone this repository.", + "cloudNoGithubRemote": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again.", "cloudPlanRequired": "Orca Cloud workspaces need a plan with cloud hours. Open Plan & billing to choose one.", "cloudSignInRequired": "Sign in to Orca to use Orca Cloud workspaces.", "cloudUnavailable": "Orca Cloud is unavailable right now. Try again in a moment.", "defaultStartRefUnresolved": "Could not resolve a default provisioned-root start ref.", "destroyDisabled": "Destroy is disabled for this recipe.", "destroyExited": "Destroy exited with code {{exitCode}}.", - "destroyExitedWithoutCode": "Destroy exited with code unknown.", + "destroyExitedWithoutCode": "Destroy exited without an exit code.", "destroyFailed": "Destroy failed.", "provisionCancelled": "Provisioning cancelled.", "provisionInterrupted": "Orca stopped while this VM was being created. Destroy it to release any provider resources.", "provisionedRootNotConfigured": "Recipe result requests provisioned-root checkout, but the recipe is not configured for it.", "provisionedRootResultRequired": "Provisioned-root recipes must return schemaVersion 2 with checkoutMode \"provisioned-root\".", "recipeExited": "Recipe exited with code {{exitCode}}.", - "recipeExitedWithoutCode": "Recipe exited with code unknown.", + "recipeExitedWithoutCode": "Recipe exited without an exit code.", "recipeNotFound": "Recipe not found: {{recipeId}}", "recipeResultMissing": "Recipe produced no JSON result.", "recipeResultNotJsonObject": "Recipe stdout must be one JSON object.", @@ -2144,13 +2154,13 @@ "remoteRepoUnsupported": "Ephemeral VM recipes run on the local desktop host in v1.", "repoNotFound": "Repo not found: {{repoId}}", "resumeExited": "Resume exited with code {{exitCode}}.", - "resumeExitedWithoutCode": "Resume exited with code unknown.", + "resumeExitedWithoutCode": "Resume exited without an exit code.", "runtimeNotFound": "Unknown ephemeral VM runtime: {{runtimeId}}", "runtimeRepoMissing": "Ephemeral VM runtime has no repo id: {{runtimeId}}", "sshTargetRemoveFailed": "Failed to remove the hidden SSH target.", "startRefUnresolved": "Could not resolve provisioned-root start ref: {{ref}}", "suspendExited": "Suspend exited with code {{exitCode}}.", - "suspendExitedWithoutCode": "Suspend exited with code unknown." + "suspendExitedWithoutCode": "Suspend exited without an exit code." } }, "jira": { diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index daa032aedde..0dd5d0df102 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -3711,7 +3711,6 @@ "WorktreeCreationPanel": { "dabd226118": "Schließen", "34dd5ee38b": "Erneut versuchen", - "a3346fc6ed": "Worktree-Erstellung abbrechen", "532aea14ce": "Abbrechen", "cancelProvisioning": "Abbrechen" } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3f86e77cad7..d2e20388b67 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2107,7 +2107,9 @@ "creatingWorktree": "Creating worktree…", "fetchingBaseBranch": "Fetching base branch…", "checkingVmEnvironment": "Checking VM environment…", - "vmChecksFailed": "Environment checks failed" + "vmChecksFailed": "Environment checks failed", + "preparingCloudEnvironment": "Preparing environment…", + "startingSandbox": "Starting sandbox…" }, "duplicatePairedServers": { "ambiguousSameServer": "{{value0}} and {{value1}} are the same server paired twice. Remove one in Settings > Remote Orca Servers." @@ -4011,7 +4013,6 @@ "WorktreeCreationPanel": { "dabd226118": "Dismiss", "34dd5ee38b": "Retry", - "a3346fc6ed": "Cancel worktree creation", "532aea14ce": "Cancel", "cancelProvisioning": "Cancel", "somethingWentWrong": "Something went wrong while creating the workspace." @@ -4057,27 +4058,17 @@ "stateRunning": "In progress", "stateDone": "Done", "stateFailed": "Failed", - "openFailedCloud": "Couldn’t open your cloud workspace" + "openFailedCloud": "Couldn’t open your cloud workspace", + "stateSkipped": "Skipped" }, "VmBuildFailureCard": { "createFailedTitle": "Couldn’t create workspace", "checksTitleCloud": "The sandbox is up, but its environment checks failed", "planTitle": "Orca Cloud needs a Team plan", - "planBody": "Cloud workspaces are part of the Team plan. Nothing was created, and you weren’t charged.", - "hoursUsedTitle": "You’ve used this period’s sandbox hours", - "hoursUsedBody": "Raise your overage limit or wait for your hours to reset. Nothing was created.", - "paymentTitle": "Your Orca payment needs attention", - "paymentBody": "Update your payment method to start cloud workspaces again. Nothing was created.", - "concurrencyTitle": "All your cloud workspaces are in use", - "concurrencyBody": "You’ve reached your plan’s limit on running cloud workspaces. Put one to sleep or delete it from the sidebar, then try again.", "signInTitle": "Sign in to use Orca Cloud", - "signInBody": "Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you.", "unavailableTitle": "Orca Cloud is unavailable right now", - "unavailableBody": "The problem is on our side, not in your project. Nothing was created. Try again in a moment.", "networkTitle": "Couldn’t reach Orca Cloud", - "networkBody": "Check your internet connection, then try again.", "snapshotTitle": "This project’s saved environment is missing", - "snapshotBody": "The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Try again; if it keeps happening, contact support.", "provisionBodyCloud": "Something went wrong while starting the sandbox. Try again, or open the logs for details.", "stillRunningCloud": "The sandbox is running and using sandbox hours until you choose.", "stillRunningLocal": "The VM is running and using hours until you choose.", @@ -4087,9 +4078,42 @@ "deleteSandbox": "Delete sandbox", "deleteVm": "Delete VM", "updatePayment": "Update payment method", - "manageBilling": "Manage billing", "checksBodyCloud": "Open anyway to fix these inside the workspace, or retry the checks after changing your project.", - "createBodyCloud": "Your sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details." + "showWorkspaces": "Show cloud workspaces", + "contactSupport": "Contact support", + "provisionTitleCloud": "The sandbox didn’t start", + "provisionTitleVm": "The VM recipe failed", + "createTitleCloud": "Couldn’t open the workspace on the sandbox", + "createBodyCloud2": "The sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details.", + "createTitleVm": "Couldn’t create the workspace on the VM", + "raiseSpendCap": "Raise spend cap", + "turnOnOverage": "Turn on overage", + "openingGitHub": "Opening GitHub…", + "connectGitHub": "Connect GitHub", + "planBody2": "Cloud workspaces are part of the Team plan. Nothing was created, and you weren’t charged.", + "planBodyMember2": "Ask an owner or admin to choose a Team plan. Nothing was created, and you weren’t charged.", + "outOfHoursTitle": "Out of sandbox hours", + "outOfHoursBody": "Your team has used this month’s sandbox hours. Turn on overage to keep starting sandboxes. Nothing was created, and you weren’t charged.", + "outOfHoursBodyMember": "Your team has used this month’s sandbox hours. Ask an owner or admin to add hours. Nothing was created, and you weren’t charged.", + "spendCapReachedTitle": "Spend cap reached", + "spendCapReachedBody": "Your team has reached this month’s spend cap. Raise it to keep starting sandboxes. Nothing was created, and you weren’t charged.", + "spendCapReachedBodyMember": "Your team has reached this month’s spend cap. Ask an owner or admin to add hours. Nothing was created, and you weren’t charged.", + "paymentFailedTitle": "Payment failed", + "paymentFailedBody": "New sandboxes can’t start until the payment goes through. Nothing was created, and you weren’t charged.", + "paymentFailedBodyMember": "New sandboxes can’t start until the payment goes through. Ask an owner or admin to update the payment method. Nothing was created, and you weren’t charged.", + "teamLimitTitle": "You’re at your team’s limit of running sandboxes", + "limitBody": "Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", + "memberLimitTitle": "You’re at your limit of running sandboxes", + "githubNotConnectedTitle": "GitHub isn’t connected for {{repo}}", + "githubNotConnectedBody": "Orca Cloud clones your code from GitHub and needs access to this repository first. Connect GitHub, then try again. Nothing was created, and you weren’t charged.", + "noGithubRemoteTitle": "{{repo}} isn’t on GitHub", + "signInBody3": "Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created, and you weren’t charged.", + "unavailableBody2": "The problem is on our side, not in your project. Nothing was created, and you weren’t charged. Try again in a moment.", + "networkBody3": "Check your internet connection, then try again. Nothing was created, and you weren’t charged.", + "snapshotBody3": "The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created, and you weren’t charged. Try again, or contact support if it keeps happening.", + "connectGitHubFailed": "Couldn’t open GitHub. Try again in a moment.", + "noGithubRemoteBody2": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again. Nothing was created, and you weren’t charged.", + "howToPushToGitHub": "How to push to GitHub" }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -4097,13 +4121,36 @@ "copy": "Copy log", "label": "Build log", "copyFailed": "Couldn’t copy the log.", - "copiedStatus": "Log copied" + "copiedStatus": "Log copied", + "hiddenTechnicalLines_one": "{{count}} technical line hidden. Copy log includes it.", + "hiddenTechnicalLines_other": "{{count}} technical lines hidden. Copy log includes them." }, "orcaCloudBuildLog": { "checkingPlan": "Checking your plan…", "provisioning": "Starting the sandbox…", "booting": "Booting the sandbox…", - "connecting": "Connecting to the sandbox…" + "connecting": "Connecting to the sandbox…", + "resuming": "Waking the sandbox…", + "suspending": "Putting the sandbox to sleep…", + "rollingOver": "Starting a fresh session…", + "destroying": "Deleting the sandbox…", + "denyNoPlan": "Your account has no active Team plan.", + "denySpendCap": "This month’s spend cap is reached.", + "denyGithub": "GitHub isn’t connected to your Orca account.", + "refusedBilling": "Orca Cloud couldn’t check your plan.", + "refusedNotConfigured": "Orca Cloud isn’t set up on the server.", + "refusedSignIn": "Orca Cloud needs you to sign in again.", + "refused": "Orca Cloud refused the request.", + "httpError": "Orca Cloud answered with an error.", + "unreachable": "Couldn’t reach Orca Cloud.", + "timeout": "Orca Cloud didn’t answer in time.", + "renewing2": "Keeping the sandbox running…", + "denyHours2": "Your team is out of sandbox hours this month.", + "denyPayment2": "Payment failed.", + "denyConcurrency2": "You’re at your team’s limit of running sandboxes.", + "denyMemberConcurrency2": "You’re at your limit of running sandboxes.", + "denyMachineSize2": "This sandbox size isn’t part of your plan.", + "refusedProvider2": "Orca Cloud is unavailable right now." }, "environmentCheckCopy": { "gitMissing": "git isn’t installed.", @@ -4122,6 +4169,16 @@ "warning": "Warning", "passed": "Passed", "toolMissingFixCloud": "Install {{command}} in the workspace, or add it to your project’s setup script." + }, + "WorktreeCreationTabStrip": { + "cancelLabel": "Cancel workspace creation" + }, + "VmDeleteConfirmDialog": { + "titleCloud": "Delete this sandbox?", + "titleVm": "Delete this VM?", + "bodyCloud": "The sandbox and anything on it are deleted, and the workspace isn’t created.", + "bodyVm": "The VM and anything on it are destroyed, and the workspace isn’t created.", + "keep": "Keep it" } } }, @@ -25613,12 +25670,14 @@ "cloudPlanRequired": "Orca Cloud workspaces need a plan with cloud hours. Open Plan & billing to choose one.", "cloudSignInRequired": "Sign in to Orca to use Orca Cloud workspaces.", "cloudUnavailable": "Orca Cloud is unavailable right now. Try again in a moment.", - "recipeExitedWithoutCode": "Recipe exited with code unknown.", - "destroyExitedWithoutCode": "Destroy exited with code unknown.", + "cloudGithubNotConnected": "Connect GitHub to your Orca account so Orca Cloud can clone this repository.", + "cloudNoGithubRemote": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again.", + "recipeExitedWithoutCode": "Recipe exited without an exit code.", + "destroyExitedWithoutCode": "Destroy exited without an exit code.", "suspendExited": "Suspend exited with code {{exitCode}}.", - "suspendExitedWithoutCode": "Suspend exited with code unknown.", + "suspendExitedWithoutCode": "Suspend exited without an exit code.", "resumeExited": "Resume exited with code {{exitCode}}.", - "resumeExitedWithoutCode": "Resume exited with code unknown.", + "resumeExitedWithoutCode": "Resume exited without an exit code.", "recipeTimedOut": "The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.", "provisionInterrupted": "Orca stopped while this VM was being created. Destroy it to release any provider resources.", "cloudConcurrencyLimit": "You already have as many Orca Cloud workspaces running as your plan allows. Sleep or delete one, then try again." diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 5c79ae5902f..f8f92a16236 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -3239,7 +3239,6 @@ "WorktreeCreationPanel": { "dabd226118": "Descartar", "34dd5ee38b": "Reintentar", - "a3346fc6ed": "Cancelar creación del worktree", "532aea14ce": "Cancelar", "cancelProvisioning": "Cancelar" } diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 4aa055dc657..06e4a793a76 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -3464,7 +3464,6 @@ "WorktreeCreationPanel": { "dabd226118": "Ignorer", "34dd5ee38b": "Réessayer", - "a3346fc6ed": "Annuler la création du worktree", "532aea14ce": "Annuler", "cancelProvisioning": "Annuler" } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 83673f53049..d2cf40ffb5e 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "閉じる", "34dd5ee38b": "再試行", - "a3346fc6ed": "ワークツリーの作成をキャンセルする", "532aea14ce": "キャンセル", "cancelProvisioning": "キャンセル" } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index a329d509fd3..ba9f60be77b 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "닫기", "34dd5ee38b": "다시 시도", - "a3346fc6ed": "작업 트리 생성 취소", "532aea14ce": "취소", "cancelProvisioning": "취소" } diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index a0f08564030..e08c9372a32 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -19511,7 +19511,6 @@ "WorktreeCreationPanel": { "dabd226118": "Descartar", "34dd5ee38b": "Tentar novamente", - "a3346fc6ed": "Cancelar criação da worktree", "532aea14ce": "Cancelar", "cancelProvisioning": "Cancelar" } diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 6d7b71a6321..5fa31c567ee 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -3809,7 +3809,6 @@ "WorktreeCreationPanel": { "dabd226118": "Скрыть", "34dd5ee38b": "Повторить", - "a3346fc6ed": "Отменить создание рабочего дерева", "532aea14ce": "Отмена", "cancelProvisioning": "Отмена" } diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 109931b761f..4eabf70df49 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -3687,7 +3687,6 @@ "WorktreeCreationPanel": { "dabd226118": "Kapat", "34dd5ee38b": "Yeniden dene", - "a3346fc6ed": "Worktree oluşturmayı iptal et", "532aea14ce": "İptal", "cancelProvisioning": "İptal" } diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 0af2dd5d4e0..8191a75518c 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -3636,7 +3636,6 @@ "WorktreeCreationPanel": { "dabd226118": "關閉", "34dd5ee38b": "重試", - "a3346fc6ed": "取消工作樹建立", "532aea14ce": "取消", "cancelProvisioning": "取消" } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d9fb1f95d19..7013413fced 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "关闭", "34dd5ee38b": "重试", - "a3346fc6ed": "取消工作树创建", "532aea14ce": "取消", "cancelProvisioning": "取消" } diff --git a/src/renderer/src/lib/ephemeral-vm-error-copy.ts b/src/renderer/src/lib/ephemeral-vm-error-copy.ts index 6a7abc5dfd1..fd8feb8f1f7 100644 --- a/src/renderer/src/lib/ephemeral-vm-error-copy.ts +++ b/src/renderer/src/lib/ephemeral-vm-error-copy.ts @@ -127,7 +127,11 @@ const COPY: Record strin translate('ephemeralVm.errors.cloudConcurrencyLimit', EN.cloudConcurrencyLimit), cloudSignInRequired: () => translate('ephemeralVm.errors.cloudSignInRequired', EN.cloudSignInRequired), - cloudUnavailable: () => translate('ephemeralVm.errors.cloudUnavailable', EN.cloudUnavailable) + cloudUnavailable: () => translate('ephemeralVm.errors.cloudUnavailable', EN.cloudUnavailable), + cloudGithubNotConnected: () => + translate('ephemeralVm.errors.cloudGithubNotConnected', EN.cloudGithubNotConnected), + cloudNoGithubRemote: () => + translate('ephemeralVm.errors.cloudNoGithubRemote', EN.cloudNoGithubRemote) } function isEphemeralVmFailureCode(code: string): code is EphemeralVmFailureCode { diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 0e96cad01ae..abd67922fe2 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -7,7 +7,7 @@ import type { Repo } from '../../../shared/repo-types' import { translate } from '@/i18n/i18n' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { gateVmCreateOnEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' -import { showOrcaCloudPlanUpsell } from '@/lib/orca-cloud-session-events' +import { showVmBuildFailureToast } from '@/components/worktree-creation/vm-build-failure-toast' import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' import { @@ -97,8 +97,9 @@ async function prepareEphemeralVmRecipeRequest( state.activePendingCreationId !== creationId || !selectWorktreeCreationSurfaceShown(state) ) { - if (preparedTarget.errorCode === 'cloudPlanRequired') { - showOrcaCloudPlanUpsell(preparedTarget.error) + const failed = state.pendingWorktreeCreations[creationId] + if (failed) { + showVmBuildFailureToast(failed, preparedTarget.error, state.repos) } else { toast.error(ephemeralVmErrorText(preparedTarget)) } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts index 40b7adab173..75e324fc891 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts @@ -33,6 +33,8 @@ function stub( unarchive: vi.fn(unused), getArchive: vi.fn(unused), listCloudWorkspaceIds: vi.fn(async () => ids), + getConfig: vi.fn(async () => null), + connectGitHub: vi.fn(unused), onWakeProgress: vi.fn(() => () => {}), onOom: vi.fn(() => () => {}) } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts index 7ac2b331c29..6c5c05fd076 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts @@ -38,6 +38,8 @@ function stubApi(overrides: Partial = {}): OrcaCloudWorks unarchive: vi.fn(async () => ok(null)), getArchive: vi.fn(async () => ok(null)), listCloudWorkspaceIds: vi.fn(async () => ['a', 'b']), + getConfig: vi.fn(async () => null), + connectGitHub: vi.fn(async () => ok(null)), onWakeProgress: vi.fn(() => () => {}), onOom: vi.fn(() => () => {}), ...overrides diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts new file mode 100644 index 00000000000..e3fb35e1a1c --- /dev/null +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts @@ -0,0 +1,36 @@ +import { expect, it } from 'vitest' +import { getCreationProgressLabel, type PendingWorktreeCreation } from './pending-worktree-creation' + +const t = ((_key: string, fallback: string) => fallback) as Parameters< + typeof getCreationProgressLabel +>[1] + +function label( + provider: 'orca-cloud' | undefined, + environmentCheck?: PendingWorktreeCreation['environmentCheck'] +): string { + return getCreationProgressLabel( + { + status: 'creating', + phase: 'provisioning-vm', + indeterminate: false, + environmentCheck, + request: { + name: 'fix-login', + ephemeralVmRecipe: { sourceRepoId: 'r', recipeId: 'cloud', projectId: 'p', provider } + } as PendingWorktreeCreation['request'] + }, + t + ) +} + +it('speaks of a sandbox for Orca Cloud and keeps VM wording for bring-your-own recipes', () => { + expect(label('orca-cloud')).toBe('Starting sandbox…') + expect( + label('orca-cloud', { + status: 'running', + startedAt: 1 + } as PendingWorktreeCreation['environmentCheck']) + ).toBe('Preparing environment…') + expect(label(undefined)).toBe('Provisioning VM…') +}) diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 030b52f9104..4cd3a920c64 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -169,6 +169,8 @@ export type PendingWorktreeCreation = { error?: string /** Machine-readable cause of `error`, e.g. `cloudPlanRequired`, so the sheet can offer the right fix. */ errorCode?: string + /** Set by the store when `status` turns to error. */ + errorAt?: number provisioningLog?: string /** Arrival time of each line in `provisioningLog`, index-aligned with its lines. */ provisioningLogStamps?: readonly number[] @@ -306,6 +308,12 @@ export function getCreationProgressLabel( if (entry.environmentCheck?.status === 'failed') { return t('auto.lib.pendingWorktreeCreation.vmChecksFailed', 'Environment checks failed') } + // Glossary: an Orca Cloud machine is a sandbox; "VM" stays only for bring-your-own recipes. + if (entry.request.ephemeralVmRecipe?.provider === 'orca-cloud') { + return entry.environmentCheck + ? t('auto.lib.pendingWorktreeCreation.preparingCloudEnvironment', 'Preparing environment…') + : t('auto.lib.pendingWorktreeCreation.startingSandbox', 'Starting sandbox…') + } return entry.environmentCheck ? t('auto.lib.pendingWorktreeCreation.checkingVmEnvironment', 'Checking VM environment…') : t('auto.lib.pendingWorktreeCreation.provisioningVm', 'Provisioning VM…') diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts new file mode 100644 index 00000000000..2a80026cfbc --- /dev/null +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts @@ -0,0 +1,34 @@ +import { expect, it } from 'vitest' +import type { PendingWorktreeCreation } from './pending-worktree-creation' +import { selectVmBuildSurfaceShown } from './worktree-creation-surface' + +function state(entry: Partial) { + return { + activeView: 'terminal' as const, + activePendingCreationId: 'c1', + pendingWorktreeCreations: { + c1: { status: 'creating', loaderVisible: true, ...entry } as PendingWorktreeCreation + } + } +} + +// The right sidebar closes while this is true, so a cloud build never sits beside an empty panel. +it('treats every Orca Cloud or VM build sheet as filling the window, from the first frame', () => { + const cloud = { + request: { + name: 'fix-login', + ephemeralVmRecipe: { + sourceRepoId: 'r', + recipeId: 'cloud', + projectId: 'p', + provider: 'orca-cloud' + } + } as PendingWorktreeCreation['request'] + } + expect(selectVmBuildSurfaceShown(state({ ...cloud, phase: 'provisioning-vm' }))).toBe(true) + expect( + selectVmBuildSurfaceShown(state({ ...cloud, status: 'error', loaderVisible: false })) + ).toBe(true) + const local = { request: { name: 'fix-login' } as PendingWorktreeCreation['request'] } + expect(selectVmBuildSurfaceShown(state(local))).toBe(false) +}) diff --git a/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts b/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts index 60a8dceba72..1d026692ac2 100644 --- a/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts +++ b/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts @@ -1,6 +1,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { RuntimeStatusSlice } from './runtime-status-types' +import { runtimeEnvironmentDisplayName } from '../../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' const activeRuntimeDisconnectedToasts = new Map() const RUNTIME_DISCONNECTED_TOAST_DURATION_MS = 4_000 @@ -23,7 +24,7 @@ export function showRuntimeDisconnectedToast( ? translate( 'auto.store.slices.runtime.status.runtimeHostUnreachableNamed', "Can't reach {{hostName}}", - { hostName: environment.name } + { hostName: runtimeEnvironmentDisplayName(environment) } ) : translate( 'auto.store.slices.runtime.status.runtimeHostUnreachable', diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index 2aef311c27a..eae20e96f2c 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -44,6 +44,18 @@ function nextPhaseLog( return entry.phaseLog } +// When this attempt failed, so a failed step can show how long it ran. +function nextErrorAt( + entry: PendingWorktreeCreation, + patch: Partial +): number | undefined { + const status = patch.status ?? entry.status + if (status !== 'error') { + return undefined + } + return entry.status === 'error' ? entry.errorAt : Date.now() +} + export function createUpdatePendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet @@ -88,7 +100,12 @@ export function createUpdatePendingWorktreeCreation( return { pendingWorktreeCreations: { ...s.pendingWorktreeCreations, - [creationId]: { ...entry, ...changes, phaseLog: nextPhaseLog(entry, changes) } + [creationId]: { + ...entry, + ...changes, + phaseLog: nextPhaseLog(entry, changes), + errorAt: nextErrorAt(entry, changes) + } } } }) diff --git a/src/shared/ephemeral-vm-failure-copy.ts b/src/shared/ephemeral-vm-failure-copy.ts index 6a03be6dfb0..eabacaf6558 100644 --- a/src/shared/ephemeral-vm-failure-copy.ts +++ b/src/shared/ephemeral-vm-failure-copy.ts @@ -14,7 +14,7 @@ export const EPHEMERAL_VM_FAILURE_COPY = { startRefUnresolved: 'Could not resolve provisioned-root start ref: {{ref}}', defaultStartRefUnresolved: 'Could not resolve a default provisioned-root start ref.', recipeExited: 'Recipe exited with code {{exitCode}}.', - recipeExitedWithoutCode: 'Recipe exited with code unknown.', + recipeExitedWithoutCode: 'Recipe exited without an exit code.', recipeResultMissing: 'Recipe produced no JSON result.', recipeResultNotJsonObject: 'Recipe stdout must be one JSON object.', recipeResultPairingCodeInvalid: 'Recipe result pairingCode is not a valid Orca pairing code.', @@ -24,13 +24,13 @@ export const EPHEMERAL_VM_FAILURE_COPY = { provisionedRootNotConfigured: 'Recipe result requests provisioned-root checkout, but the recipe is not configured for it.', suspendExited: 'Suspend exited with code {{exitCode}}.', - suspendExitedWithoutCode: 'Suspend exited with code unknown.', + suspendExitedWithoutCode: 'Suspend exited without an exit code.', resumeExited: 'Resume exited with code {{exitCode}}.', - resumeExitedWithoutCode: 'Resume exited with code unknown.', + resumeExitedWithoutCode: 'Resume exited without an exit code.', recipeTimedOut: 'The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.', destroyExited: 'Destroy exited with code {{exitCode}}.', - destroyExitedWithoutCode: 'Destroy exited with code unknown.', + destroyExitedWithoutCode: 'Destroy exited without an exit code.', destroyFailed: 'Destroy failed.', destroyDisabled: 'Destroy is disabled for this recipe.', cleanupStopped: 'Cleanup stopped by user.', @@ -41,7 +41,11 @@ export const EPHEMERAL_VM_FAILURE_COPY = { cloudConcurrencyLimit: 'You already have as many Orca Cloud workspaces running as your plan allows. Sleep or delete one, then try again.', cloudSignInRequired: 'Sign in to Orca to use Orca Cloud workspaces.', - cloudUnavailable: 'Orca Cloud is unavailable right now. Try again in a moment.' + cloudUnavailable: 'Orca Cloud is unavailable right now. Try again in a moment.', + cloudGithubNotConnected: + 'Connect GitHub to your Orca account so Orca Cloud can clone this repository.', + cloudNoGithubRemote: + 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, then try again.' } as const export type EphemeralVmFailureCode = keyof typeof EPHEMERAL_VM_FAILURE_COPY diff --git a/src/shared/execution-host/execution-host-registry.ts b/src/shared/execution-host/execution-host-registry.ts index deb8e4dacf9..59ed1c1c96b 100644 --- a/src/shared/execution-host/execution-host-registry.ts +++ b/src/shared/execution-host/execution-host-registry.ts @@ -13,6 +13,7 @@ import { import type { SshConnectionState } from '../ssh-types' import type { RuntimeEnvironmentSource } from '../remote-runtime/host-catalog/runtime-environments' import type { GlobalSettings } from '../global-settings-types' +import { runtimeEnvironmentDisplayName } from '../remote-runtime/host-catalog/orca-cloud-environment-name' import type { Repo } from '../repo-types' import { annotateManagedOrcadExecutionHosts } from './managed-orcad-execution-host' import { getSshConnectionHealth, type EphemeralVmHostLifecycle } from './execution-host-health' @@ -134,7 +135,11 @@ export function buildExecutionHostRegistry(args: { addRuntimeHost( hosts, environmentId, - normalizeHostPart(environment.name) ?? environmentId, + (environment.name + ? normalizeHostPart( + runtimeEnvironmentDisplayName({ name: environment.name, source: environment.source }) + ) + : null) ?? environmentId, environment.source, args.runtimeStatusByEnvironmentId ) diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index 87a1ade907a..b369e2dc025 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -4,6 +4,7 @@ import type { HostedArchivePullRequest, HostedArchiveResponse, + HostedSandboxConfigResponse, HostedWorkspaceStatus } from './hosted-sandbox-wire' @@ -59,6 +60,10 @@ export type OrcaCloudWorkspaceApi = { }) => Promise> /** Workspace ids of every Orca Cloud workspace this desktop knows (the sidebar dot / hover card). */ listCloudWorkspaceIds: () => Promise + /** Product constants and measured timings; null when the control plane can't be reached. */ + getConfig: () => Promise + /** Opens GitHub in the browser to give Orca Cloud access to the account's repositories. */ + connectGitHub: () => Promise> onWakeProgress: (callback: (event: CloudWakeProgressEvent) => void) => () => void onOom: (callback: (event: CloudOomEvent) => void) => () => void } @@ -70,6 +75,8 @@ export const ORCA_CLOUD_WORKSPACE_CHANNELS = { unarchive: 'orcaCloudWorkspace:unarchive', getArchive: 'orcaCloudWorkspace:getArchive', listCloudWorkspaceIds: 'orcaCloudWorkspace:listIds', + getConfig: 'orcaCloudWorkspace:getConfig', + connectGitHub: 'orcaCloudWorkspace:connectGitHub', wakeProgress: 'orcaCloudWorkspace:wakeProgress', oom: 'orcaCloudWorkspace:oom' } as const diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index 133f36be511..587871a76de 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -9,9 +9,26 @@ import { z } from 'zod' */ export const ORCA_CLOUD_IDLE_SLEEP_MINUTES = 15 +/** Median and slow-tail durations of a recent operation, as the control plane measured them. */ +export const HostedSandboxTimingSchema = z.object({ + p50Ms: z.number().nonnegative(), + p95Ms: z.number().nonnegative(), + samples: z.number().int().positive() +}) +export type HostedSandboxTiming = z.infer + /** GET /v1/config: product constants clients (desktop, mobile, CLI, marketing) must not hardcode. */ export const HostedSandboxConfigResponseSchema = z.object({ - idleSleepMinutes: z.number().int().positive() + idleSleepMinutes: z.number().int().positive(), + /** Recent sandbox starts (create until orcad is ready); absent until enough were measured. */ + createTiming: HostedSandboxTimingSchema.optional() +}) +export type HostedSandboxConfigResponse = z.infer + +/** POST /v1/github/connect: where the browser binds a GitHub App installation to the account. */ +export const HostedGithubConnectResponseSchema = z.object({ + installUrl: z.string().url(), + authorizeUrl: z.string().url() }) // Billing sells exactly these; larger boxes need a Vercel Enterprise plan. diff --git a/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts new file mode 100644 index 00000000000..50c3c4e62fa --- /dev/null +++ b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { + legacyOrcaCloudEnvironmentName, + orcaCloudEnvironmentName, + runtimeEnvironmentDisplayName +} from './orca-cloud-environment-name' +import { buildExecutionHostRegistry } from '../../execution-host/execution-host-registry' + +const RUNTIME_ID = '6f1c2a9e-0b4d-4c11-9a3e-7d2f22b5b1e7' + +describe('Orca Cloud server names', () => { + it('shows a cloud sandbox as Orca Cloud, never its id tail', () => { + const name = orcaCloudEnvironmentName('repo', RUNTIME_ID) + expect(name).toBe('repo sandbox 22b5b1e7') + expect(runtimeEnvironmentDisplayName({ name, source: 'ephemeral-vm' })).toBe('Orca Cloud') + }) + + it('leaves custom recipe VMs and user-named servers alone', () => { + expect( + runtimeEnvironmentDisplayName({ name: 'repo VM 22b5b1e7', source: 'ephemeral-vm' }) + ).toBe('repo VM 22b5b1e7') + expect(runtimeEnvironmentDisplayName({ name: 'repo sandbox 22b5b1e7', source: 'manual' })).toBe( + 'repo sandbox 22b5b1e7' + ) + }) + + it('renames only the legacy name built from this runtime', () => { + expect(legacyOrcaCloudEnvironmentName('repo VM 22b5b1e7', RUNTIME_ID)).toBe( + 'repo sandbox 22b5b1e7' + ) + expect(legacyOrcaCloudEnvironmentName('repo VM 00000000', RUNTIME_ID)).toBeNull() + expect(legacyOrcaCloudEnvironmentName(' VM 22b5b1e7', RUNTIME_ID)).toBeNull() + }) + + it('labels the sidebar host Orca Cloud', () => { + const hosts = buildExecutionHostRegistry({ + repos: [], + settings: null, + runtimeEnvironments: [ + { id: 'env-1', name: 'repo sandbox 22b5b1e7', source: 'ephemeral-vm' }, + { id: 'env-2', name: 'build box', source: 'manual' } + ] + }) + const labels = Object.fromEntries(hosts.map((host) => [host.id, host.label])) + expect(labels['runtime:env-1']).toBe('Orca Cloud') + expect(labels['runtime:env-2']).toBe('build box') + }) +}) diff --git a/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts new file mode 100644 index 00000000000..eec877ba10b --- /dev/null +++ b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts @@ -0,0 +1,40 @@ +import type { RuntimeEnvironmentSource } from './runtime-environments' + +// Saved server names must be unique, so an Orca Cloud server is stored as +// " sandbox ". People see "Orca Cloud": the workspace row already names +// the workspace, and the id tail means nothing to them. +const ORCA_CLOUD_ENVIRONMENT_NAME = /^.+ sandbox [0-9A-Za-z]{8}$/ + +/** The host label for every Orca Cloud server, like "Local Mac" for this computer. */ +export const ORCA_CLOUD_HOST_LABEL = 'Orca Cloud' + +/** The saved (unique) name of the server behind one Orca Cloud workspace. */ +export function orcaCloudEnvironmentName(repoName: string, runtimeId: string): string { + return `${repoName} sandbox ${runtimeId.slice(-8)}` +} + +/** Builds before the glossary named the server " VM "; the runtime record proves it was Orca Cloud. */ +export function legacyOrcaCloudEnvironmentName(name: string, runtimeId: string): string | null { + const suffix = ` VM ${runtimeId.slice(-8)}` + return name.endsWith(suffix) && name.length > suffix.length + ? orcaCloudEnvironmentName(name.slice(0, -suffix.length), runtimeId) + : null +} + +export function isOrcaCloudRuntimeEnvironment(environment: { + name?: string | null + source?: RuntimeEnvironmentSource +}): boolean { + return ( + environment.source === 'ephemeral-vm' && + ORCA_CLOUD_ENVIRONMENT_NAME.test(environment.name?.trim() ?? '') + ) +} + +/** The name to show for a saved server: "Orca Cloud" for a cloud sandbox, otherwise its saved name. */ +export function runtimeEnvironmentDisplayName(environment: { + name: string + source?: RuntimeEnvironmentSource +}): string { + return isOrcaCloudRuntimeEnvironment(environment) ? ORCA_CLOUD_HOST_LABEL : environment.name +}