mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Merge pull request #97 from nwparker/cloud/core-ui-finish
Build sheet round 4 + create-path errors (GitHub not connected, no GitHub remote) + Orca Cloud host label
This commit is contained in:
@@ -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<HostedSandboxTiming | undefined> {
|
||||
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<HostedSandboxTiming | undefined> } | 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<HostedSandboxTiming | undefined> {
|
||||
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
|
||||
}
|
||||
@@ -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:<sub>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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 "<repo> VM <id tail>", so the sidebar showed it as a
|
||||
* raw VM. Renames those to the "<repo> sandbox <id tail>" 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<string, string>()
|
||||
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
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
const handlers = new Map<string, () => 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)
|
||||
})
|
||||
@@ -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<HostedSandboxControlPlaneClient, 'config' | 'connectGitHub'>
|
||||
): void {
|
||||
// Timings move slowly and the Worker caches them for 5 minutes; one read per app session is plenty.
|
||||
let config: Promise<HostedSandboxConfigResponse | null> | 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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<typeof HostedGithubConnectResponseSchema>
|
||||
|
||||
export type HostedSandboxControlPlaneClient = {
|
||||
create(
|
||||
@@ -71,6 +77,10 @@ export type HostedSandboxControlPlaneClient = {
|
||||
): Promise<HostedSandboxSshAccess>
|
||||
/** Starts the VM's remote desktop (idempotent); it listens on the VM's loopback only. */
|
||||
startDesktop(sandboxId: string, signal?: AbortSignal): Promise<HostedSandboxDesktop>
|
||||
/** Product constants and measured timings (GET /v1/config). */
|
||||
config(signal?: AbortSignal): Promise<HostedSandboxConfigResponse>
|
||||
/** Starts binding a GitHub App installation to the account; the browser finishes it. */
|
||||
connectGitHub(signal?: AbortSignal): Promise<HostedGithubConnectResponse>
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string | n
|
||||
return normalized?.startsWith('github.com/') ? `https://${normalized}.git` : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The sandbox can only clone from GitHub, so a repo without a GitHub remote is refused before the
|
||||
* control plane starts (and bills) a sandbox that could never open the workspace: the project has
|
||||
* no identity a sandbox checkout can match.
|
||||
*/
|
||||
export async function refuseOrcaCloudWithoutGithub(
|
||||
recipe: Pick<OrcaVmRecipe, 'provider'>,
|
||||
repoPath: string
|
||||
): Promise<EphemeralVmFailure | null> {
|
||||
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') }
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<string, (_event: unknown, args: never) => 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<object>()),
|
||||
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<string, unknown> = {}) =>
|
||||
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
|
||||
}
|
||||
@@ -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<string, string | number>
|
||||
}
|
||||
|
||||
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. */
|
||||
|
||||
@@ -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<EphemeralVmProvisionIpcResult> => {
|
||||
async (_event, args: EphemeralVmProvisionArgs): Promise<EphemeralVmProvisionIpcResult> => {
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
<NativeChatResumeRuntimeModal
|
||||
key={environment.id}
|
||||
store={store}
|
||||
machineName={environment.name}
|
||||
machineName={runtimeEnvironmentDisplayName(environment)}
|
||||
offerEnabled
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 <HostCreationRow repoName={repoName} />
|
||||
}
|
||||
@@ -89,7 +102,7 @@ export function PendingWorktreeRow({
|
||||
isError ? 'text-destructive/90' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{statusLabel(entry, t)}
|
||||
{statusLabel(entry, repos, t)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -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
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -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
|
||||
? {
|
||||
|
||||
@@ -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<OwnedUsage | null>(null)
|
||||
const ownedRef = useRef<OwnedUsage | null>(null)
|
||||
|
||||
|
||||
@@ -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: <Sparkles />,
|
||||
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: <CreditCard />,
|
||||
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: <CreditCard />,
|
||||
onClick: actions.onOpenBilling
|
||||
}
|
||||
]
|
||||
: [],
|
||||
more: []
|
||||
}
|
||||
case 'signIn':
|
||||
@@ -113,7 +132,7 @@ function failureActions(
|
||||
: t('auto.components.worktree.creation.VmBuildFailureCard.signIn', 'Sign in'),
|
||||
icon: signingIn ? <Loader2 className="motion-safe:animate-spin" /> : <LogIn />,
|
||||
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: <PanelLeft />,
|
||||
onClick: actions.onShowWorkspaces
|
||||
},
|
||||
tryAgain
|
||||
],
|
||||
more: []
|
||||
}
|
||||
case 'snapshotMissing':
|
||||
return {
|
||||
primary: [tryAgain],
|
||||
more: [
|
||||
{
|
||||
key: 'support',
|
||||
label: t(
|
||||
'auto.components.worktree.creation.VmBuildFailureCard.contactSupport',
|
||||
'Contact support'
|
||||
),
|
||||
icon: <LifeBuoy />,
|
||||
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 ? <Loader2 className="motion-safe:animate-spin" /> : <Github />,
|
||||
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: <SquareArrowOutUpRight />,
|
||||
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 ? <Trash2 /> : null}
|
||||
{destroys
|
||||
|
||||
@@ -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 (
|
||||
<div data-vm-build-sheet>
|
||||
<h2 data-vm-build-heading tabIndex={-1}>
|
||||
Starting your cloud workspace
|
||||
</h2>
|
||||
<VmBuildFailureCard
|
||||
failure={failure}
|
||||
cloud
|
||||
vmKept={false}
|
||||
firstErrorLine={null}
|
||||
canFixWithAgent={false}
|
||||
canManageBilling
|
||||
signingIn={false}
|
||||
connectingGitHub={connectingGitHub}
|
||||
repoName="acme/web"
|
||||
actions={handlers}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
it('announces only the cause and lands focus on it, then on the sheet heading after Try again', () => {
|
||||
const handlers = actions()
|
||||
const { rerender } = render(<Sheet failure={{ kind: 'unavailable' }} handlers={handlers} />)
|
||||
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(<Sheet failure={null} handlers={handlers} />))
|
||||
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(<Sheet failure={{ kind: 'githubNotConnected' }} connectingGitHub handlers={handlers} />)
|
||||
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)
|
||||
})
|
||||
@@ -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<HTMLDivElement>(null)
|
||||
const copy = visible
|
||||
? vmBuildFailureCopy(visible, { cloud, canManageBilling, repoName }, t)
|
||||
: null
|
||||
const headingRef = React.useRef<HTMLHeadingElement>(null)
|
||||
const cardRef = React.useRef<HTMLDivElement>(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<HTMLElement>('[data-vm-build-heading]')?.focus({ preventScroll: true })
|
||||
}
|
||||
}, [open, run])
|
||||
const detail =
|
||||
@@ -70,11 +85,12 @@ export function VmBuildFailureCard({
|
||||
{visible && copy ? (
|
||||
<div
|
||||
key={run}
|
||||
role={failure ? 'alert' : undefined}
|
||||
ref={cardRef}
|
||||
className="flex flex-col gap-3 rounded-lg border border-border bg-card px-4 py-3"
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div
|
||||
{/* Only the cause is announced; the actions and check rows are read on demand. */}
|
||||
<div role={failure ? 'alert' : undefined} className="flex flex-col gap-1">
|
||||
<h3
|
||||
ref={headingRef}
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
@@ -83,7 +99,7 @@ export function VmBuildFailureCard({
|
||||
)}
|
||||
>
|
||||
{copy.title}
|
||||
</div>
|
||||
</h3>
|
||||
{copy.body ? (
|
||||
<p className="break-words text-xs text-muted-foreground">{copy.body}</p>
|
||||
) : null}
|
||||
@@ -103,7 +119,9 @@ export function VmBuildFailureCard({
|
||||
cloud={cloud}
|
||||
vmKept={vmKept}
|
||||
canFixWithAgent={canFixWithAgent}
|
||||
canManageBilling={canManageBilling}
|
||||
signingIn={signingIn}
|
||||
connectingGitHub={connectingGitHub}
|
||||
actions={actions}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
@@ -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<HTMLDivElement>(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 (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{rows.length > 0 ? (
|
||||
{log !== '' ? (
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{hiddenCount > 0 ? (
|
||||
<span className="mr-auto text-xs text-muted-foreground">
|
||||
{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.'
|
||||
}
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
{firstError !== -1 ? (
|
||||
<Button type="button" variant="ghost" size="xs" onClick={jumpToFirstError}>
|
||||
<ArrowDownToLine />
|
||||
@@ -139,24 +154,24 @@ export function VmBuildLog({
|
||||
aria-live="off"
|
||||
aria-label={t('auto.components.worktree.creation.VmBuildLog.label', 'Build log')}
|
||||
tabIndex={0}
|
||||
className="scrollbar-sleek relative max-h-72 overflow-auto rounded-md bg-muted/40 py-2 font-mono text-[11px] leading-4 text-muted-foreground"
|
||||
className="scrollbar-sleek relative max-h-72 overflow-auto rounded-md bg-muted/40 py-2 font-mono text-xs leading-5 text-muted-foreground outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-focus-ring"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="px-3 text-muted-foreground/60">{emptyLabel}</div>
|
||||
<div className="px-3">{emptyLabel}</div>
|
||||
) : (
|
||||
rows.map((row, index) => {
|
||||
const stamp = stamps[index]
|
||||
const { stamp } = row
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
ref={index === firstError ? firstErrorRef : undefined}
|
||||
tabIndex={index === firstError ? -1 : undefined}
|
||||
className={cn(
|
||||
'flex gap-3 px-3 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
|
||||
row.isError && 'bg-destructive/10 text-destructive'
|
||||
'flex gap-3 px-3 outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-focus-ring',
|
||||
row.isError && 'font-medium text-destructive'
|
||||
)}
|
||||
>
|
||||
<span className="w-10 shrink-0 select-none text-right tabular-nums text-muted-foreground/60">
|
||||
<span className="w-12 shrink-0 select-none text-right tabular-nums text-muted-foreground">
|
||||
{stamp === undefined ? '' : formatElapsedTime(stamp - startedAt)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 whitespace-pre-wrap break-words">{row.text}</span>
|
||||
|
||||
@@ -1,82 +1,22 @@
|
||||
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 { VmBuildAgentSignInRowView, type VmBuildAgentSignInRowModel } from './VmBuildAgentSignInRow'
|
||||
import type { AgentSignInGate } from '@/lib/agent-sign-in/agent-sign-in-gate'
|
||||
import { formatElapsedTime } from './worktree-creation-clock'
|
||||
import {
|
||||
CLOUD_LOG,
|
||||
CLOUD_RECIPE,
|
||||
entry,
|
||||
FAILED_LOG,
|
||||
LOG,
|
||||
frame,
|
||||
LOG_LINES,
|
||||
NOW,
|
||||
sheet,
|
||||
stampsFor,
|
||||
T0
|
||||
} from './vm-build-sheet-fixture-support'
|
||||
|
||||
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.'
|
||||
]
|
||||
const LOG = LOG_LINES.join('\n')
|
||||
// Every fixture is drawn 102 seconds into its build, with lines arriving a second or so apart.
|
||||
const T0 = 1_700_000_000_000
|
||||
const NOW = T0 + 102_000
|
||||
const stampsFor = (lines: number): number[] =>
|
||||
Array.from({ length: lines }, (_, index) => T0 + 400 + index * 1300)
|
||||
|
||||
type Recipe = NonNullable<PendingWorktreeCreation['request']['ephemeralVmRecipe']>
|
||||
const LOCAL_RECIPE: Recipe = { sourceRepoId: 'repo', recipeId: 'sandbox', projectId: 'p' }
|
||||
const CLOUD_RECIPE: Recipe = { ...LOCAL_RECIPE, recipeId: 'cloud', provider: 'orca-cloud' }
|
||||
|
||||
function entry(
|
||||
patch: Partial<PendingWorktreeCreation>,
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
function sheet(
|
||||
value: PendingWorktreeCreation,
|
||||
error: string | null,
|
||||
now: number,
|
||||
agentSignInRow?: React.ReactNode
|
||||
) {
|
||||
return (
|
||||
<div className="bg-background p-3">
|
||||
<VmBuildSheet
|
||||
creationId="fixture"
|
||||
entry={value}
|
||||
now={now}
|
||||
elapsedLabel={formatElapsedTime(now - value.startedAt)}
|
||||
error={error}
|
||||
onCancel={() => {}}
|
||||
onRetry={() => {}}
|
||||
onDismiss={() => {}}
|
||||
onEditRecipe={() => {}}
|
||||
agentSignInRow={agentSignInRow}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function frame(
|
||||
value: PendingWorktreeCreation,
|
||||
error: string | null = null,
|
||||
now = NOW,
|
||||
agentSignInRow?: React.ReactNode
|
||||
) {
|
||||
return defineFixture({ width: 760, render: () => sheet(value, error, now, agentSignInRow) })
|
||||
}
|
||||
const noop = (): void => {}
|
||||
|
||||
function signInRow(model: VmBuildAgentSignInRowModel): React.ReactNode {
|
||||
@@ -211,17 +151,13 @@ export const checksFailed = frame(
|
||||
entry({ environmentCheck: { status: 'failed', checks: FAILED_CHECKS, ...CHECKS_FAILED_AT } })
|
||||
)
|
||||
|
||||
const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found`
|
||||
|
||||
export const provisionFailed = frame(
|
||||
entry({ status: 'error', provisioningLog: FAILED_LOG }),
|
||||
entry({ status: 'error', provisioningLog: FAILED_LOG, errorAt: T0 + 98_000 }),
|
||||
'Recipe exited with code 1.'
|
||||
)
|
||||
|
||||
// Orca Cloud
|
||||
|
||||
const CLOUD_LOG = '[orca-cloud] checking-entitlement\n[orca-cloud] provisioning'
|
||||
|
||||
export const cloudStarting = frame(
|
||||
entry({ provisioningLog: CLOUD_LOG }, CLOUD_RECIPE),
|
||||
null,
|
||||
@@ -277,68 +213,11 @@ export const cloudReady = frame(
|
||||
T0 + 9_400
|
||||
)
|
||||
|
||||
function cloudFailure(errorCode: string | undefined, error: string, log = CLOUD_LOG) {
|
||||
return frame(
|
||||
entry({ status: 'error', errorCode, provisioningLog: log }, 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 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)
|
||||
|
||||
export const cloudCreateFailed = frame(
|
||||
entry(
|
||||
{
|
||||
status: 'error',
|
||||
errorAt: T0 + 8_900,
|
||||
phase: 'creating',
|
||||
phaseLog: CLOUD_OPENING_PHASES,
|
||||
environmentCheck: CLOUD_CHECKS_PASSED,
|
||||
|
||||
@@ -1,33 +1,44 @@
|
||||
import React from 'react'
|
||||
import { AlertTriangle, ChevronRight, CircleAlert, CircleCheck, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open'
|
||||
import { useOrcaBillingStatus } from '@/components/billing/use-orca-billing-status'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useTranslate, type Translate } from '@/i18n/use-translate'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { resolveVmEnvironmentCheckDecision } from '@/lib/ephemeral-vm-environment-check-decision'
|
||||
import { openPlansPage } from '@/components/billing/plans/plans-page-store'
|
||||
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
|
||||
import { toast } from 'sonner'
|
||||
import type { EnvironmentSetupFailureContext } from '../../../../shared/environment-setup-agent-prompt'
|
||||
import { formatEnvironmentDoctorChecks } from '../../../../shared/environment-doctor-types'
|
||||
import { StepIcon } from './WorktreeSetupSteps'
|
||||
import { VmBuildStepRow } from './VmBuildStepRow'
|
||||
import { firstBuildLogErrorLine, VmBuildLog } from './VmBuildLog'
|
||||
import { VmBuildFailureCard } from './VmBuildFailureCard'
|
||||
import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow'
|
||||
import { VmBuildCloudAgentStep } from '../cloud-agent-setup/VmBuildCloudAgentStep'
|
||||
import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt'
|
||||
import { classifyVmBuildFailure, isAccountGate, type VmBuildFailure } from './vm-build-failure'
|
||||
import {
|
||||
deriveVmBuildSteps,
|
||||
isOrcaCloudBuild,
|
||||
ORCA_CLOUD_TYPICAL_STEP_SECONDS,
|
||||
type VmBuildStep
|
||||
} from './vm-build-steps'
|
||||
classifyVmBuildFailure,
|
||||
isAccountGate,
|
||||
isBillingFailure,
|
||||
nothingStarted,
|
||||
type VmBuildFailure
|
||||
} from './vm-build-failure'
|
||||
import { deriveVmBuildSteps, isOrcaCloudBuild, type VmBuildStep } from './vm-build-steps'
|
||||
import { useMinimumRunningSteps } from './use-minimum-running-steps'
|
||||
import { formatElapsedTime } from './worktree-creation-clock'
|
||||
import { headerTitle, stepLabel, stepStateLabel, type SheetState } from './vm-build-sheet-copy'
|
||||
import {
|
||||
connectOrcaCloudGitHub,
|
||||
orcaCloudRepoName,
|
||||
PUSH_TO_GITHUB_URL
|
||||
} from './vm-build-repo-actions'
|
||||
import { useVmBuildStepTimings, type VmBuildStepTimings } from './vm-build-timing'
|
||||
import { headerTitle, stepLabel, type SheetState } from './vm-build-sheet-copy'
|
||||
import { humanizeOrcaCloudLogLine, latestOrcaCloudPhaseLabel } from './orca-cloud-build-log'
|
||||
|
||||
const NO_STAMPS: readonly number[] = []
|
||||
const SUPPORT_URL = 'https://github.com/stablyai/orca/issues/new'
|
||||
|
||||
// Lazy: the agent-launch graph is heavy and only needed once the user asks for it.
|
||||
function startFixWithAgent(args: {
|
||||
repoId: string
|
||||
@@ -74,7 +85,8 @@ export function VmBuildSheet({
|
||||
onDismiss,
|
||||
onEditRecipe,
|
||||
agentSignInRow,
|
||||
cloudAgentStep
|
||||
cloudAgentStep,
|
||||
stepTimings
|
||||
}: {
|
||||
creationId: string
|
||||
entry: PendingWorktreeCreation
|
||||
@@ -83,12 +95,15 @@ export function VmBuildSheet({
|
||||
error: string | null
|
||||
onCancel: () => void
|
||||
onRetry: () => void
|
||||
/** Leaves the build; when a VM is still up the caller confirms before it is deleted. */
|
||||
onDismiss: () => void
|
||||
onEditRecipe: () => void
|
||||
/** Fixtures only: a fixed sign-in row in place of the live one. */
|
||||
agentSignInRow?: React.ReactNode
|
||||
/** Fixtures only: a fixed "Add an agent" step in place of the live one. */
|
||||
/** Fixtures only: a fixed "Add an agent" step (null for none) in place of the live one. */
|
||||
cloudAgentStep?: React.ReactNode
|
||||
/** Fixtures only: measured step timings in place of the control plane's. */
|
||||
stepTimings?: VmBuildStepTimings
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const logId = React.useId()
|
||||
@@ -97,6 +112,8 @@ export function VmBuildSheet({
|
||||
[entry.provisioningLog]
|
||||
)
|
||||
const cloud = isOrcaCloudBuild(entry)
|
||||
const measuredTimings = useVmBuildStepTimings(cloud && stepTimings === undefined)
|
||||
const timings = stepTimings ?? measuredTimings
|
||||
const formatLine = React.useMemo(
|
||||
() => (cloud ? (line: string) => humanizeOrcaCloudLogLine(line, t) : undefined),
|
||||
[cloud, t]
|
||||
@@ -106,10 +123,13 @@ export function VmBuildSheet({
|
||||
const recipe = entry.request.ephemeralVmRecipe
|
||||
const failure = classifyVmBuildFailure({ entry, error, cloud })
|
||||
const gated = isAccountGate(failure)
|
||||
const billing = useOrcaBillingStatus(isBillingFailure(failure))
|
||||
// Unknown roles get the owner's copy; only a known member is told to ask someone else.
|
||||
const canManageBilling =
|
||||
billing.result?.status !== 'ok' || billing.result.entitlement.canManageBilling
|
||||
const derived = deriveVmBuildSteps(entry, now).map((step) =>
|
||||
// Nothing started, so no step failed.
|
||||
(gated || failure?.kind === 'network') && step.state === 'failed'
|
||||
? { ...step, state: 'pending' as const }
|
||||
nothingStarted(failure) && step.state === 'failed'
|
||||
? { ...step, state: 'pending' as const, elapsedMs: null }
|
||||
: step
|
||||
)
|
||||
const steps = useMinimumRunningSteps(derived, failure === null, now)
|
||||
@@ -122,6 +142,16 @@ export function VmBuildSheet({
|
||||
: 'building'
|
||||
const building = state === 'building'
|
||||
|
||||
const sourceRepo = useAppStore((state) =>
|
||||
recipe ? state.repos.find((repo) => repo.id === recipe.sourceRepoId) : undefined
|
||||
)
|
||||
const repoName = orcaCloudRepoName(sourceRepo)
|
||||
const [connectingGitHub, setConnectingGitHub] = React.useState(false)
|
||||
const connectGitHub = (): void => {
|
||||
setConnectingGitHub(true)
|
||||
void connectOrcaCloudGitHub().finally(() => setConnectingGitHub(false))
|
||||
}
|
||||
|
||||
const signIn = (): void => {
|
||||
void useAppStore
|
||||
.getState()
|
||||
@@ -139,8 +169,8 @@ export function VmBuildSheet({
|
||||
return (
|
||||
<div data-vm-build-sheet className="flex min-h-full justify-center pt-12">
|
||||
<div className="flex w-full max-w-2xl flex-col gap-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
|
||||
<div className="flex min-h-7 items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="grid size-4 shrink-0 place-items-center">
|
||||
{building ? (
|
||||
<Loader2
|
||||
@@ -148,7 +178,7 @@ export function VmBuildSheet({
|
||||
className="size-4 text-muted-foreground motion-safe:animate-spin"
|
||||
/>
|
||||
) : state === 'ready' ? (
|
||||
<CircleCheck aria-hidden className="size-4 text-muted-foreground" />
|
||||
<CircleCheck aria-hidden className="size-4 text-foreground" />
|
||||
) : gated ? (
|
||||
<CircleAlert aria-hidden className="size-4 text-muted-foreground" />
|
||||
) : (
|
||||
@@ -158,56 +188,61 @@ export function VmBuildSheet({
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
{/* The failure card announces failures itself. */}
|
||||
<span aria-live={failure ? 'off' : 'polite'}>
|
||||
{/* Retry lands focus here once the failure card collapses. The card announces failures. */}
|
||||
<h2
|
||||
data-vm-build-heading
|
||||
tabIndex={-1}
|
||||
aria-live={failure ? 'off' : 'polite'}
|
||||
className="text-sm font-medium text-foreground outline-none"
|
||||
>
|
||||
{headerTitle(state, cloud, t, failure?.kind === 'create')}
|
||||
</span>
|
||||
<span className="text-xs font-normal tabular-nums text-muted-foreground">
|
||||
{elapsedLabel}
|
||||
</span>
|
||||
</h2>
|
||||
{/* Reserve the slot so the header never shifts when Cancel gives way to the card's actions. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
tabIndex={building ? undefined : -1}
|
||||
aria-hidden={!building}
|
||||
className={cn(
|
||||
'rounded-sm text-xs text-muted-foreground transition-opacity duration-150 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none',
|
||||
!building && 'pointer-events-none opacity-0'
|
||||
</h2>
|
||||
{gated ? null : (
|
||||
<span className="text-xs tabular-nums text-muted-foreground">{elapsedLabel}</span>
|
||||
)}
|
||||
>
|
||||
{t(
|
||||
'auto.components.worktree.creation.WorktreeCreationPanel.cancelProvisioning',
|
||||
'Cancel'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{building ? (
|
||||
<Button type="button" variant="ghost" size="xs" onClick={onCancel}>
|
||||
{t(
|
||||
'auto.components.worktree.creation.WorktreeCreationPanel.cancelProvisioning',
|
||||
'Cancel'
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ol className="flex flex-col rounded-lg border border-border bg-card px-4 py-2 text-sm">
|
||||
{steps.map((step) => (
|
||||
<StepRow
|
||||
key={step.id}
|
||||
step={step}
|
||||
cloud={cloud}
|
||||
detail={
|
||||
cloud && step.id === 'provision' && step.state === 'running'
|
||||
? latestOrcaCloudPhaseLabel(entry.provisioningLog ?? '', t)
|
||||
: null
|
||||
}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
{cloudAgentStep ?? <VmBuildCloudAgentStep creationId={creationId} entry={entry} />}
|
||||
{agentSignInRow ??
|
||||
(entry.vmEnvironmentId ? (
|
||||
<VmBuildAgentSignInRow
|
||||
creationId={creationId}
|
||||
environmentId={entry.vmEnvironmentId}
|
||||
{/* An account refusal happens before anything starts, so there are no steps to show. */}
|
||||
{gated ? null : (
|
||||
<ol className="flex flex-col rounded-lg border border-border bg-card px-4 py-2 text-sm">
|
||||
{steps.map((step) => (
|
||||
<VmBuildStepRow
|
||||
key={step.id}
|
||||
step={step}
|
||||
cloud={cloud}
|
||||
detail={
|
||||
cloud && step.id === 'provision' && step.state === 'running'
|
||||
? latestOrcaCloudPhaseLabel(entry.provisioningLog ?? '', t)
|
||||
: null
|
||||
}
|
||||
timing={timings[step.id] ?? null}
|
||||
t={t}
|
||||
/>
|
||||
) : null)}
|
||||
</ol>
|
||||
))}
|
||||
{cloudAgentStep !== undefined ? (
|
||||
cloudAgentStep
|
||||
) : (
|
||||
<VmBuildCloudAgentStep creationId={creationId} entry={entry} />
|
||||
)}
|
||||
{agentSignInRow ??
|
||||
(entry.vmEnvironmentId ? (
|
||||
<VmBuildAgentSignInRow
|
||||
creationId={creationId}
|
||||
environmentId={entry.vmEnvironmentId}
|
||||
/>
|
||||
) : null)}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<VmBuildFailureCard
|
||||
failure={failure}
|
||||
@@ -215,7 +250,10 @@ export function VmBuildSheet({
|
||||
vmKept={failure?.kind === 'checks' || Boolean(entry.request.ephemeralVmRuntimeId)}
|
||||
firstErrorLine={firstErrorLine}
|
||||
canFixWithAgent={Boolean(recipe)}
|
||||
canManageBilling={canManageBilling}
|
||||
signingIn={signingIn}
|
||||
connectingGitHub={connectingGitHub}
|
||||
repoName={repoName}
|
||||
actions={{
|
||||
onFixWithAgent: () => {
|
||||
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)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{building ? <OrcaCloudQueuedPrompt creationId={creationId} /> : null}
|
||||
|
||||
{cloud ? (
|
||||
<button
|
||||
{cloud && !gated ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
aria-expanded={logOpen}
|
||||
aria-controls={logId}
|
||||
onClick={() => setLogOpen(!logOpen)}
|
||||
className="flex items-center gap-1 self-start rounded-sm text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="self-start"
|
||||
>
|
||||
<ChevronRight
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'size-3.5 transition-transform duration-150 motion-reduce:transition-none',
|
||||
'transition-transform duration-150 motion-reduce:transition-none',
|
||||
logOpen && 'rotate-90'
|
||||
)}
|
||||
/>
|
||||
{logOpen
|
||||
? t('auto.components.worktree.creation.VmBuildSheet.hideLogs', 'Hide logs')
|
||||
: t('auto.components.worktree.creation.VmBuildSheet.viewLogs', 'View logs')}
|
||||
</button>
|
||||
</Button>
|
||||
) : null}
|
||||
{logOpen ? (
|
||||
{logOpen && !gated ? (
|
||||
<VmBuildLog
|
||||
id={logId}
|
||||
log={entry.provisioningLog ?? ''}
|
||||
stamps={entry.provisioningLogStamps ?? []}
|
||||
stamps={entry.provisioningLogStamps ?? NO_STAMPS}
|
||||
startedAt={entry.startedAt}
|
||||
emptyLabel={t(
|
||||
'auto.components.worktree.creation.VmBuildSheet.logEmpty',
|
||||
@@ -283,68 +327,3 @@ export function VmBuildSheet({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<li
|
||||
className="flex flex-col gap-1 py-1.5"
|
||||
aria-current={step.state === 'running' ? 'step' : undefined}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<StepIcon state={step.state} />
|
||||
<span
|
||||
id={labelId}
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate transition-colors duration-200 motion-reduce:transition-none',
|
||||
step.state === 'pending' && 'text-muted-foreground',
|
||||
step.state === 'failed' && 'text-destructive'
|
||||
)}
|
||||
>
|
||||
{stepLabel(step, cloud, t)}
|
||||
</span>
|
||||
<span className="sr-only">{stepStateLabel(step.state, t)}</span>
|
||||
{typical !== null ? (
|
||||
<span className="text-xs text-muted-foreground/70">
|
||||
{slow
|
||||
? t('auto.components.worktree.creation.VmBuildSheet.slow', 'Taking longer than usual')
|
||||
: t(
|
||||
'auto.components.worktree.creation.VmBuildSheet.usually',
|
||||
'usually ~{{seconds}}s',
|
||||
{ seconds: typical }
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
{step.percent !== null ? (
|
||||
<span className="w-9 text-right text-xs tabular-nums text-muted-foreground">
|
||||
{step.percent}%
|
||||
</span>
|
||||
) : null}
|
||||
{step.elapsedMs !== null && step.state !== 'pending' ? (
|
||||
<span className="w-12 text-right text-xs tabular-nums text-muted-foreground">
|
||||
{formatElapsedTime(step.elapsedMs)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{detail ? <p className="ml-6 text-xs text-muted-foreground">{detail}</p> : null}
|
||||
{step.percent !== null ? (
|
||||
<Progress value={step.percent} aria-labelledby={labelId} className="ml-6 h-1 w-auto" />
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<typeof cloudFailure>) {
|
||||
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)
|
||||
@@ -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 (
|
||||
<li
|
||||
className="flex flex-col gap-1 py-1.5"
|
||||
aria-current={step.state === 'running' ? 'step' : undefined}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
{step.skipped ? (
|
||||
<CircleSlash aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<StepIcon state={step.state} />
|
||||
)}
|
||||
<span
|
||||
id={labelId}
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate transition-colors duration-200 motion-reduce:transition-none',
|
||||
(step.state === 'pending' || step.skipped) && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{stepLabel(step, cloud, t)}
|
||||
</span>
|
||||
<span className="sr-only">
|
||||
{step.skipped
|
||||
? t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')
|
||||
: stepStateLabel(step.state, t)}
|
||||
</span>
|
||||
{step.skipped ? (
|
||||
<span aria-hidden className="text-xs text-muted-foreground">
|
||||
{t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')}
|
||||
</span>
|
||||
) : null}
|
||||
{hint ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{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) }
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
{step.percent !== null ? (
|
||||
<span className="w-9 text-right text-xs tabular-nums text-muted-foreground">
|
||||
{step.percent}%
|
||||
</span>
|
||||
) : null}
|
||||
{step.elapsedMs !== null && step.state !== 'pending' ? (
|
||||
<span className="w-12 text-right text-xs tabular-nums text-muted-foreground">
|
||||
{formatElapsedTime(step.elapsedMs)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{detail ? <p className="ml-6 text-xs text-muted-foreground">{detail}</p> : null}
|
||||
{step.percent !== null ? (
|
||||
<Progress value={step.percent} aria-labelledby={labelId} className="ml-6 h-1 w-auto" />
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{cloud
|
||||
? t(
|
||||
'auto.components.worktree.creation.VmDeleteConfirmDialog.titleCloud',
|
||||
'Delete this sandbox?'
|
||||
)
|
||||
: t(
|
||||
'auto.components.worktree.creation.VmDeleteConfirmDialog.titleVm',
|
||||
'Delete this VM?'
|
||||
)}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{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.'
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('auto.components.worktree.creation.VmDeleteConfirmDialog.keep', 'Keep it')}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={onConfirm}>
|
||||
{cloud
|
||||
? t(
|
||||
'auto.components.worktree.creation.VmBuildFailureCard.deleteSandbox',
|
||||
'Delete sandbox'
|
||||
)
|
||||
: t('auto.components.worktree.creation.VmBuildFailureCard.deleteVm', 'Delete VM')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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 ? (
|
||||
<VmDeleteConfirmDialog
|
||||
open={confirmingDelete}
|
||||
cloud={entry.request.ephemeralVmRecipe?.provider === 'orca-cloud'}
|
||||
onOpenChange={setConfirmingDelete}
|
||||
onConfirm={() => {
|
||||
setConfirmingDelete(false)
|
||||
dismiss()
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className="min-h-0 flex-1 p-3">
|
||||
{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({
|
||||
|
||||
@@ -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"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
|
||||
@@ -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 <CircleX aria-hidden className="size-3.5 shrink-0 text-destructive" />
|
||||
case 'pending':
|
||||
return <Circle aria-hidden className="size-3.5 shrink-0 text-muted-foreground/60" />
|
||||
return <Circle aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +80,7 @@ export function WorktreeSetupSteps({
|
||||
>
|
||||
{stepLabel(step.id, agentLabel, t)}
|
||||
</span>
|
||||
<span className="sr-only">{stepStateLabel(step.state, t)}</span>
|
||||
{step.percent !== null ? (
|
||||
<span className="text-xs tabular-nums text-muted-foreground">{step.percent}%</span>
|
||||
) : null}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
|
||||
// The hosted provider streams `[orca-cloud] <phase>` progress lines; show them as words, not codes.
|
||||
// The hosted provider writes `[orca-cloud] <phase>` progress, `Orca Cloud: <deny reason>` 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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
: {})
|
||||
})
|
||||
}
|
||||
@@ -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<string, unknown>) =>
|
||||
fallback.replace(/\{\{(\w+)\}\}/g, (_slot, name: string) =>
|
||||
String(params?.[name] ?? '')
|
||||
)) as Parameters<typeof vmBuildFailureCopy>[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')
|
||||
})
|
||||
})
|
||||
@@ -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<Record<string, VmBuildAccountFailureKind>> = {
|
||||
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: <reason>`.
|
||||
const DENY_REASON = /^Orca Cloud: ([a-z_]+)$/m
|
||||
const DENY_REASON_KINDS: Partial<Record<string, VmBuildAccountFailureKind>> = {
|
||||
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<VmBuildFailure['kind']> = 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<VmBuildFailure['kind']> = 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)
|
||||
|
||||
@@ -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<Repo, 'displayName' | 'gitRemoteIdentity'> | 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<void> {
|
||||
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.'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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<PendingWorktreeCreation['request']['ephemeralVmRecipe']>
|
||||
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<PendingWorktreeCreation>,
|
||||
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 (
|
||||
<div className="bg-background p-3">
|
||||
<VmBuildSheet
|
||||
creationId="fixture"
|
||||
entry={value}
|
||||
now={now}
|
||||
elapsedLabel={formatElapsedTime(now - value.startedAt)}
|
||||
error={error}
|
||||
onCancel={() => {}}
|
||||
onRetry={() => {}}
|
||||
onDismiss={() => {}}
|
||||
onEditRecipe={() => {}}
|
||||
agentSignInRow={agentSignInRow}
|
||||
stepTimings={FIXTURE_STEP_TIMINGS}
|
||||
cloudAgentStep={null}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 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`
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<VmBuildStepId, number> = {
|
||||
provision: 5,
|
||||
checks: 3,
|
||||
create: 2
|
||||
}
|
||||
|
||||
type StepCore = Omit<VmBuildStep, 'startedAt'>
|
||||
|
||||
type VmBuildEntry = Pick<
|
||||
PendingWorktreeCreation,
|
||||
| 'status'
|
||||
@@ -36,6 +29,7 @@ type VmBuildEntry = Pick<
|
||||
| 'startedAt'
|
||||
| 'checkoutProgress'
|
||||
| 'worktreeId'
|
||||
| 'errorAt'
|
||||
>
|
||||
|
||||
export function isOrcaCloudBuild(entry: Pick<PendingWorktreeCreation, 'request'>): 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<Pick<VmBuildStep, 'skipped' | 'percent'>> = {}
|
||||
): 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]
|
||||
}
|
||||
|
||||
@@ -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<HostedSandboxTiming, 'p50Ms' | 'p95Ms'>
|
||||
|
||||
export type VmBuildStepTimings = Partial<Record<VmBuildStepId, VmBuildStepTiming>>
|
||||
|
||||
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<VmBuildStepTimings> | null = null
|
||||
|
||||
function loadMeasuredTimings(): Promise<VmBuildStepTimings> {
|
||||
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<VmBuildStepTimings>(() =>
|
||||
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))
|
||||
}
|
||||
+14
-4
@@ -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": {
|
||||
|
||||
@@ -3711,7 +3711,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Schließen",
|
||||
"34dd5ee38b": "Erneut versuchen",
|
||||
"a3346fc6ed": "Worktree-Erstellung abbrechen",
|
||||
"532aea14ce": "Abbrechen",
|
||||
"cancelProvisioning": "Abbrechen"
|
||||
}
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -3239,7 +3239,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Descartar",
|
||||
"34dd5ee38b": "Reintentar",
|
||||
"a3346fc6ed": "Cancelar creación del worktree",
|
||||
"532aea14ce": "Cancelar",
|
||||
"cancelProvisioning": "Cancelar"
|
||||
}
|
||||
|
||||
@@ -3464,7 +3464,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Ignorer",
|
||||
"34dd5ee38b": "Réessayer",
|
||||
"a3346fc6ed": "Annuler la création du worktree",
|
||||
"532aea14ce": "Annuler",
|
||||
"cancelProvisioning": "Annuler"
|
||||
}
|
||||
|
||||
@@ -3181,7 +3181,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "閉じる",
|
||||
"34dd5ee38b": "再試行",
|
||||
"a3346fc6ed": "ワークツリーの作成をキャンセルする",
|
||||
"532aea14ce": "キャンセル",
|
||||
"cancelProvisioning": "キャンセル"
|
||||
}
|
||||
|
||||
@@ -3181,7 +3181,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "닫기",
|
||||
"34dd5ee38b": "다시 시도",
|
||||
"a3346fc6ed": "작업 트리 생성 취소",
|
||||
"532aea14ce": "취소",
|
||||
"cancelProvisioning": "취소"
|
||||
}
|
||||
|
||||
@@ -19511,7 +19511,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Descartar",
|
||||
"34dd5ee38b": "Tentar novamente",
|
||||
"a3346fc6ed": "Cancelar criação da worktree",
|
||||
"532aea14ce": "Cancelar",
|
||||
"cancelProvisioning": "Cancelar"
|
||||
}
|
||||
|
||||
@@ -3809,7 +3809,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Скрыть",
|
||||
"34dd5ee38b": "Повторить",
|
||||
"a3346fc6ed": "Отменить создание рабочего дерева",
|
||||
"532aea14ce": "Отмена",
|
||||
"cancelProvisioning": "Отмена"
|
||||
}
|
||||
|
||||
@@ -3687,7 +3687,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "Kapat",
|
||||
"34dd5ee38b": "Yeniden dene",
|
||||
"a3346fc6ed": "Worktree oluşturmayı iptal et",
|
||||
"532aea14ce": "İptal",
|
||||
"cancelProvisioning": "İptal"
|
||||
}
|
||||
|
||||
@@ -3636,7 +3636,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "關閉",
|
||||
"34dd5ee38b": "重試",
|
||||
"a3346fc6ed": "取消工作樹建立",
|
||||
"532aea14ce": "取消",
|
||||
"cancelProvisioning": "取消"
|
||||
}
|
||||
|
||||
@@ -3181,7 +3181,6 @@
|
||||
"WorktreeCreationPanel": {
|
||||
"dabd226118": "关闭",
|
||||
"34dd5ee38b": "重试",
|
||||
"a3346fc6ed": "取消工作树创建",
|
||||
"532aea14ce": "取消",
|
||||
"cancelProvisioning": "取消"
|
||||
}
|
||||
|
||||
@@ -127,7 +127,11 @@ const COPY: Record<EphemeralVmFailureCode, (params: Params | undefined) => 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 {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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(() => () => {})
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ function stubApi(overrides: Partial<OrcaCloudWorkspaceApi> = {}): 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
|
||||
|
||||
@@ -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…')
|
||||
})
|
||||
@@ -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…')
|
||||
|
||||
@@ -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<PendingWorktreeCreation>) {
|
||||
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)
|
||||
})
|
||||
+2
-1
@@ -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<string, symbol>()
|
||||
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',
|
||||
|
||||
@@ -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<PendingWorktreeCreation>
|
||||
): 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type {
|
||||
HostedArchivePullRequest,
|
||||
HostedArchiveResponse,
|
||||
HostedSandboxConfigResponse,
|
||||
HostedWorkspaceStatus
|
||||
} from './hosted-sandbox-wire'
|
||||
|
||||
@@ -59,6 +60,10 @@ export type OrcaCloudWorkspaceApi = {
|
||||
}) => Promise<CloudWorkspaceResult<CloudArchiveInfo | null>>
|
||||
/** Workspace ids of every Orca Cloud workspace this desktop knows (the sidebar dot / hover card). */
|
||||
listCloudWorkspaceIds: () => Promise<string[]>
|
||||
/** Product constants and measured timings; null when the control plane can't be reached. */
|
||||
getConfig: () => Promise<HostedSandboxConfigResponse | null>
|
||||
/** Opens GitHub in the browser to give Orca Cloud access to the account's repositories. */
|
||||
connectGitHub: () => Promise<CloudWorkspaceResult<null>>
|
||||
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
|
||||
|
||||
@@ -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<typeof HostedSandboxTimingSchema>
|
||||
|
||||
/** 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<typeof HostedSandboxConfigResponseSchema>
|
||||
|
||||
/** 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.
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { RuntimeEnvironmentSource } from './runtime-environments'
|
||||
|
||||
// Saved server names must be unique, so an Orca Cloud server is stored as
|
||||
// "<repo> sandbox <runtime id tail>". 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 "<repo> VM <id tail>"; 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
|
||||
}
|
||||
Reference in New Issue
Block a user