From 5696161da43e3fed607af504944de82a49ee08b4 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 06:55:42 -0800 Subject: [PATCH 01/11] feat(build-sheet): round-4 design fixes: plain cloud log, cause-specific cards, account gates, delete confirm, measured timings --- .../hosted-sandbox/hosted-sandbox-recipe.ts | 7 + .../VmBuildFailureActions.tsx | 90 ++++++-- .../worktree-creation/VmBuildFailureCard.tsx | 32 ++- .../worktree-creation/VmBuildLog.tsx | 50 ++-- .../VmBuildSheet.fixture.tsx | 151 ++---------- .../worktree-creation/VmBuildSheet.tsx | 215 +++++++----------- .../VmBuildSheetCloudFailures.fixture.tsx | 115 ++++++++++ .../worktree-creation/VmBuildStepRow.tsx | 89 ++++++++ .../VmDeleteConfirmDialog.tsx | 69 ++++++ .../WorktreeCreationPanel.tsx | 25 +- .../WorktreeCreationTabStrip.tsx | 6 +- .../worktree-creation/WorktreeSetupSteps.tsx | 4 +- .../worktree-creation/orca-cloud-build-log.ts | 149 +++++++++++- .../vm-build-failure-copy.ts | 157 +++++++++---- .../vm-build-failure-toast.ts | 29 +++ .../worktree-creation/vm-build-failure.ts | 43 +++- .../vm-build-sheet-fixture-support.tsx | 88 +++++++ .../worktree-creation/vm-build-steps.test.ts | 81 ++++++- .../worktree-creation/vm-build-steps.ts | 103 ++++----- .../worktree-creation/vm-build-timing.ts | 17 ++ .../src/i18n/en-runtime-required.json | 9 +- src/renderer/src/i18n/locales/de.json | 1 - src/renderer/src/i18n/locales/en.json | 81 +++++-- src/renderer/src/i18n/locales/es.json | 1 - src/renderer/src/i18n/locales/fr.json | 1 - src/renderer/src/i18n/locales/ja.json | 1 - src/renderer/src/i18n/locales/ko.json | 1 - src/renderer/src/i18n/locales/pt.json | 1 - src/renderer/src/i18n/locales/ru.json | 1 - src/renderer/src/i18n/locales/tr.json | 1 - src/renderer/src/i18n/locales/zh-Hant.json | 1 - src/renderer/src/i18n/locales/zh.json | 1 - .../src/lib/ephemeral-vm-error-copy.ts | 4 +- .../src/lib/ephemeral-vm-worktree-creation.ts | 7 +- .../creation/pending-worktree-creation.ts | 2 + .../create/pending-worktree-creation.ts | 19 +- src/shared/ephemeral-vm-failure-copy.ts | 12 +- 37 files changed, 1180 insertions(+), 484 deletions(-) create mode 100644 src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx create mode 100644 src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx create mode 100644 src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx create mode 100644 src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx create mode 100644 src/renderer/src/components/worktree-creation/vm-build-timing.ts diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index e9a28ae01e1..dd32beb345e 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -84,6 +84,13 @@ function failed(error: unknown): RecipeStepProviderResult { failure: ephemeralVmFailure('cloudPlanRequired') } } + if (isEnvironmentProviderError(error, 'conflict') && error.reason === 'github_not_connected') { + return { + ...base, + stderr: `Orca Cloud: ${error.reason}\n`, + failure: ephemeralVmFailure('cloudGithubNotConnected') + } + } if (isEnvironmentProviderError(error, 'unauthorized')) { return { ...base, stderr: '', failure: ephemeralVmFailure('cloudSignInRequired') } } diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index c74991e69da..3225d55c0c0 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -4,10 +4,11 @@ import { ChevronDown, CreditCard, Loader2, + LifeBuoy, LogIn, + PanelLeft, Pencil, RotateCcw, - Sparkles, SquareArrowOutUpRight, Trash2 } from 'lucide-react' @@ -30,6 +31,8 @@ export type VmBuildFailureActions = { onSeePlans: () => void onOpenBilling: () => void onSignIn: () => void + onShowWorkspaces: () => void + onContactSupport: () => void } type Action = { @@ -45,6 +48,7 @@ function failureActions( failure: VmBuildFailure, cloud: boolean, canFixWithAgent: boolean, + canManageBilling: boolean, signingIn: boolean, actions: VmBuildFailureActions, t: Translate @@ -75,32 +79,35 @@ function failureActions( { key: 'plans', label: t('auto.lib.orcaCloudSession.seePlans', 'See plans'), - icon: , onClick: actions.onSeePlans } ], more: [] } case 'hoursUsed': + case 'spendCap': case 'payment': + // Members can't change billing; their card tells them who can. return { - primary: [ - { - key: 'billing', - label: - failure.kind === 'payment' - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.updatePayment', - 'Update payment method' - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.manageBilling', - 'Manage billing' - ), - icon: , - onClick: actions.onOpenBilling - } - ], + primary: canManageBilling + ? [ + { + key: 'billing', + label: + failure.kind === 'payment' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.updatePayment', + 'Update payment method' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.manageBilling', + 'Manage billing' + ), + icon: , + onClick: actions.onOpenBilling + } + ] + : [], more: [] } case 'signIn': @@ -153,9 +160,40 @@ function failureActions( more: [editRecipe] } case 'concurrency': + case 'memberConcurrency': + return { + primary: [ + { + key: 'workspaces', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.showWorkspaces', + 'Show cloud workspaces' + ), + icon: , + onClick: actions.onShowWorkspaces + }, + tryAgain + ], + more: [] + } + case 'snapshotMissing': + return { + primary: [tryAgain], + more: [ + { + key: 'support', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.contactSupport', + 'Contact support' + ), + icon: , + onClick: actions.onContactSupport + } + ] + } + case 'githubNotConnected': case 'unavailable': case 'network': - case 'snapshotMissing': case 'create': return { primary: [tryAgain], more: [] } } @@ -166,6 +204,7 @@ export function FailureActionRow({ cloud, vmKept, canFixWithAgent, + canManageBilling, signingIn, actions, t @@ -174,11 +213,20 @@ export function FailureActionRow({ cloud: boolean vmKept: boolean canFixWithAgent: boolean + canManageBilling: boolean signingIn: 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, + actions, + t + ) // Leaving a build that still holds a VM destroys it, so say so on the button. const destroys = vmKept return ( diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index 973110e2334..b25324e8173 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -16,6 +16,7 @@ export function VmBuildFailureCard({ vmKept, firstErrorLine, canFixWithAgent, + canManageBilling, signingIn, actions }: { @@ -27,6 +28,7 @@ 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 actions: VmBuildFailureActions }): React.JSX.Element { @@ -46,18 +48,24 @@ export function VmBuildFailureCard({ setShown(failure) } const visible = failure ?? shown - const copy = visible ? vmBuildFailureCopy(visible, cloud, t) : null - const headingRef = React.useRef(null) + const copy = visible ? vmBuildFailureCopy(visible, { cloud, canManageBilling }, t) : null + const headingRef = React.useRef(null) + const cardRef = React.useRef(null) // Move focus to the card when it opens, so keyboard and screen-reader users land on the way forward. React.useEffect(() => { + const card = cardRef.current + const sheet = card?.closest('[data-vm-build-sheet]') + const active = document.activeElement if (open) { - const heading = headingRef.current - const active = document.activeElement // Never pull focus out of something the user is typing in elsewhere. - const sheet = heading?.closest('[data-vm-build-sheet]') - if (heading && (!active || active === document.body || sheet?.contains(active))) { - heading.focus({ preventScroll: true }) + if (!active || active === document.body || sheet?.contains(active)) { + headingRef.current?.focus({ preventScroll: true }) } + return + } + // A Retry collapses (and inerts) the card under the focused button, so hand focus to the sheet. + if (active && card?.contains(active)) { + sheet?.querySelector('[data-vm-build-heading]')?.focus({ preventScroll: true }) } }, [open, run]) const detail = @@ -70,11 +78,12 @@ export function VmBuildFailureCard({ {visible && copy ? (
-
-
+

{copy.title} -

+ {copy.body ? (

{copy.body}

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

    {detail}

    : null} - {step.percent !== null ? ( - - ) : null} -
  • - ) -} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx new file mode 100644 index 00000000000..783470780a7 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx @@ -0,0 +1,115 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { + CLOUD_FAILED_LOG, + CLOUD_LOG, + CLOUD_RECIPE, + entry, + FAILED_LOG, + LOG, + frame, + 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` +) + +export const cloudHoursUsedMember = defineFixture({ + ...cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: included_hours_exhausted` + ), + setup: () => { + // A team member: billing is someone else's to change. + 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 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 cloudFailedLogsOpen = defineFixture({ + ...cloudFailure('cloudUnavailable', 'Orca Cloud is unavailable right now.', CLOUD_FAILED_LOG), + interact: (frameElement) => { + Array.from(frameElement.querySelectorAll('button')) + .find((button) => button.textContent?.includes('View logs')) + ?.click() + } +}) + +export const cloudFailed = cloudFailure( + 'recipeExited', + 'Recipe exited with code 1.', + `${LOG}\nfatal: sandbox agent stopped unexpectedly` +) + +export const cloudHoursUsed = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: included_hours_exhausted` +) + +export const cloudPaymentDue = cloudFailure( + 'cloudPlanRequired', + 'Orca Cloud workspaces need a plan with cloud hours.', + `${CLOUD_LOG}\nOrca Cloud: payment_past_due` +) + +export const cloudNetwork = cloudFailure(undefined, 'fetch failed', CLOUD_LOG) diff --git a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx new file mode 100644 index 00000000000..359d2042f61 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx @@ -0,0 +1,89 @@ +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 { 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, + 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 timing = step.state === 'running' ? vmBuildStepTiming(step.id, cloud) : null + // A live percent already says how far along the step is. + const hint = timing && step.percent === null ? timing : null + const slow = hint !== null && step.elapsedMs !== null && step.elapsedMs > hint.p95Ms + + return ( +
  • +
    + {step.skipped ? ( + + ) : ( + + )} + + {stepLabel(step, cloud, t)} + + + {step.skipped + ? t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped') + : stepStateLabel(step.state, t)} + + {step.skipped ? ( + + {t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')} + + ) : null} + {hint ? ( + + {slow + ? t('auto.components.worktree.creation.VmBuildSheet.slow', 'Taking longer than usual') + : t( + 'auto.components.worktree.creation.VmBuildSheet.usually', + 'usually ~{{seconds}}s', + { seconds: Math.max(1, Math.round(hint.p50Ms / 1000)) } + )} + + ) : null} + {step.percent !== null ? ( + + {step.percent}% + + ) : null} + {step.elapsedMs !== null && step.state !== 'pending' ? ( + + {formatElapsedTime(step.elapsedMs)} + + ) : null} +
    + {detail ?

    {detail}

    : null} + {step.percent !== null ? ( + + ) : null} +
  • + ) +} diff --git a/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx b/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx new file mode 100644 index 00000000000..ac670a9ad29 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx @@ -0,0 +1,69 @@ +import type React from 'react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { useTranslate } from '@/i18n/use-translate' + +/** Leaving a build that still holds a VM deletes it; ask first, wherever the leave came from. */ +export function VmDeleteConfirmDialog({ + open, + cloud, + onOpenChange, + onConfirm +}: { + open: boolean + cloud: boolean + onOpenChange: (open: boolean) => void + onConfirm: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( + + + + + {cloud + ? t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.titleCloud', + 'Delete this sandbox?' + ) + : t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.titleVm', + 'Delete this VM?' + )} + + + {cloud + ? t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.bodyCloud', + 'The sandbox and anything on it are deleted, and the workspace isn’t created.' + ) + : t( + 'auto.components.worktree.creation.VmDeleteConfirmDialog.bodyVm', + 'The VM and anything on it are destroyed, and the workspace isn’t created.' + )} + + + + + + + + + ) +} diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index 14fc169c1e1..51033961eba 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -11,6 +11,7 @@ import { useTranslate } from '@/i18n/use-translate' import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' import { formatElapsedTime, useWorktreeCreationClock } from './worktree-creation-clock' import { VmBuildSheet } from './VmBuildSheet' +import { VmDeleteConfirmDialog } from './VmDeleteConfirmDialog' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ export default function WorktreeCreationPanel({ @@ -23,6 +24,7 @@ export default function WorktreeCreationPanel({ const t = useTranslate() const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) const progressLabelId = React.useId() + const [confirmingDelete, setConfirmingDelete] = React.useState(false) const checksFinishedAt = entry?.environmentCheck?.status === 'failed' ? entry.environmentCheck.finishedAt : undefined // Depend on primitives so stderr’s fresh entry objects cannot continuously reset the interval; @@ -35,11 +37,17 @@ export default function WorktreeCreationPanel({ } const dismiss = (): void => useAppStore.getState().removePendingWorktreeCreation(creationId) + // A failed or paused VM build still holds a VM that dismissing deletes, so confirm first. + const holdsVm = + entry.environmentCheck?.status === 'failed' || + (entry.status === 'error' && Boolean(entry.request.ephemeralVmRuntimeId)) + const leave = holdsVm ? () => setConfirmingDelete(true) : dismiss const isError = entry.status === 'error' // A VM build keeps its sheet through fetch and checkout, so it never drops to the one-line status. const isVmCreation = Boolean(entry.request.ephemeralVmRecipe) || entry.phase === 'provisioning-vm' const title = entry.request.displayName || entry.request.name - const elapsedLabel = formatElapsedTime((checksFinishedAt ?? now) - entry.startedAt) + const stoppedAt = checksFinishedAt ?? (isError ? entry.errorAt : undefined) + const elapsedLabel = formatElapsedTime((stoppedAt ?? now) - entry.startedAt) const checkoutProgress = getVisibleCheckoutProgress(entry) return ( @@ -48,8 +56,19 @@ export default function WorktreeCreationPanel({ title={title} isError={isError} reserveCollapsedSidebarHeaderSpace={reserveCollapsedSidebarHeaderSpace} - onCancel={dismiss} + onCancel={leave} /> + {holdsVm ? ( + { + setConfirmingDelete(false) + dismiss() + }} + /> + ) : null}
    {isVmCreation ? ( @@ -70,7 +89,7 @@ export default function WorktreeCreationPanel({ } onCancel={dismiss} onRetry={() => retryBackgroundWorktreeCreation(creationId)} - onDismiss={dismiss} + onDismiss={leave} onEditRecipe={() => { const state = useAppStore.getState() state.openSettingsTarget({ diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx index 0cba5eecb5b..88fcd828edc 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationTabStrip.tsx @@ -41,11 +41,11 @@ export default function WorktreeCreationTabStrip({ type="button" title={t('auto.components.worktree.creation.WorktreeCreationPanel.532aea14ce', 'Cancel')} aria-label={t( - 'auto.components.worktree.creation.WorktreeCreationPanel.a3346fc6ed', - 'Cancel worktree creation' + 'auto.components.worktree.creation.WorktreeCreationTabStrip.cancelLabel', + 'Cancel workspace creation' )} onClick={onCancel} - className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground" + className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-1 focus-visible:outline-focus-ring" > diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx index f2df248bd9a..a1575b6951a 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx @@ -7,6 +7,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { formatElapsedTime } from './worktree-creation-clock' import type { WorktreeSetupStep, WorktreeSetupStepId } from './worktree-setup-steps' +import { stepStateLabel } from './vm-build-sheet-copy' function stepLabel(id: WorktreeSetupStepId, agentLabel: string, t: Translate = translate): string { switch (id) { @@ -41,7 +42,7 @@ export function StepIcon({ state }: { state: WorktreeSetupStep['state'] }): Reac case 'failed': return case 'pending': - return + return } } @@ -79,6 +80,7 @@ export function WorktreeSetupSteps({ > {stepLabel(step.id, agentLabel, t)} + {stepStateLabel(step.state, t)} {step.percent !== null ? ( {step.percent}% ) : null} diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 2bf39cbdbc6..03b068dee8b 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -1,7 +1,10 @@ import type { Translate } from '@/i18n/use-translate' -// The hosted provider streams `[orca-cloud] ` progress lines; show them as words, not codes. +// The hosted provider writes `[orca-cloud] ` progress, `Orca Cloud: ` and a few +// fixed transport messages. Everything else is provider internals that the plain view hides. const PHASE_LINE = /^\[orca-cloud\] ([a-z-]+)$/ +const DENY_LINE = /^Orca Cloud: ([a-z_ ]+)$/ +const REFUSED_LINE = /^Orca Cloud refused the request \(([a-z_]+)\)\.$/ function phaseLabel(phase: string, t: Translate): string | null { switch (phase) { @@ -25,15 +28,151 @@ function phaseLabel(phase: string, t: Translate): string | null { 'auto.components.worktree.creation.orcaCloudBuildLog.connecting', 'Connecting to the sandbox…' ) + case 'resuming': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.resuming', + 'Waking the sandbox…' + ) + case 'suspending': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.suspending', + 'Putting the sandbox to sleep…' + ) + case 'renewing': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.renewing', + 'Extending the session…' + ) + 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.denyHours', + 'This month’s included sandbox hours are used up.' + ) + 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.denyPayment', + 'A payment is overdue.' + ) + case 'concurrency_limit': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyConcurrency', + 'Your team’s limit on running cloud workspaces is reached.' + ) + case 'member_concurrency_limit': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.denyMemberConcurrency', + 'Your limit on running cloud workspaces is reached.' + ) + 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.denyMachineSize', + 'This machine 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.refusedProvider', + 'The sandbox provider is unavailable.' + ) + case 'not_configured': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedNotConfigured', + 'Orca Cloud isn’t set up on the server.' + ) + case 'unauthorized': + case 'forbidden': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedSignIn', + 'Orca Cloud needs you to sign in again.' + ) + default: + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.refused', + 'Orca Cloud refused the request.' + ) + } +} + +/** A provider line in plain words, or null when it is an internal detail the plain view hides. */ +export function humanizeOrcaCloudLogLine(line: string, t: Translate): string | null { + const text = line.trim() + const phase = PHASE_LINE.exec(text)?.[1] + if (phase) { + return phaseLabel(phase, t) + } + const reason = DENY_LINE.exec(text)?.[1] + if (reason) { + return denyLabel(reason, t) + } + const refused = REFUSED_LINE.exec(text)?.[1] + if (refused) { + return refusedLabel(refused, t) + } + if (/^Orca Cloud request failed \(HTTP \d+\)\.$/.test(text)) { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.httpError', + 'Orca Cloud answered with an error.' + ) + } + if (text === 'Could not reach Orca Cloud.') { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.unreachable', + 'Couldn’t reach Orca Cloud.' + ) + } + if (text === 'Orca Cloud did not answer in time.') { + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.timeout', + 'Orca Cloud didn’t answer in time.' + ) + } + return null } // "Starting the sandbox…" would only repeat the step's own label. diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index 538b6031b30..544cfe48521 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -1,10 +1,16 @@ 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 + /** 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 }: VmBuildFailureCopyContext, t: Translate ): { title: string; body: string | null } { switch (failure.kind) { @@ -32,21 +38,47 @@ 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.planBody', + 'Cloud workspaces are part of the Team plan. Nothing was created, and you weren’t charged.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.planBodyMember', + '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' + 'You’ve used this month’s included 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.hoursUsedBody', + 'Turn on overage in Plan & billing to keep starting sandboxes. Nothing was created.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.hoursUsedBodyMember', + 'Ask an owner or admin to turn on overage. Nothing was created.' + ) + } + case 'spendCap': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapTitle', + 'You’ve reached this month’s spend cap' + ), + body: canManageBilling + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapBody', + 'Raise the monthly spend cap in Plan & billing to keep starting sandboxes. Nothing was created.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapBodyMember', + 'Ask an owner or admin to raise the monthly spend cap. Nothing was created.' + ) } case 'payment': return { @@ -54,20 +86,47 @@ export function vmBuildFailureCopy( 'auto.components.worktree.creation.VmBuildFailureCard.paymentTitle', 'Your Orca payment needs attention' ), - 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.paymentBody', + 'Update your payment method to start cloud workspaces again. Nothing was created.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.paymentBodyMember', + 'Ask an owner or admin to update the payment method. Nothing was created.' + ) } case 'concurrency': return { title: t( 'auto.components.worktree.creation.VmBuildFailureCard.concurrencyTitle', - 'All your cloud workspaces are in use' + 'Your team is running as many cloud workspaces as its plan allows' ), 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.' + 'Put a running cloud workspace to sleep or delete it, then try again. Nothing was created.' + ) + } + case 'memberConcurrency': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.memberConcurrencyTitle', + 'You’re running as many cloud workspaces as you can at once' + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.memberConcurrencyBody', + 'Put one of yours to sleep or delete it, then try again. Nothing was created.' + ) + } + case 'githubNotConnected': + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.githubTitle', + 'Connect GitHub to use this repository' + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.githubBody', + 'Orca Cloud needs access to GitHub to clone this private repository. Connect GitHub to your Orca account, then try again. Nothing was created.' ) } case 'signIn': @@ -77,8 +136,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.signInBody2', + 'Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created.' ) } case 'unavailable': @@ -99,8 +158,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.networkBody2', + 'Check your internet connection, then try again. Nothing was created.' ) } case 'snapshotMissing': @@ -110,35 +169,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.snapshotBody2', + 'The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created. Try again, or contact support if it keeps happening.' ) } case 'provision': - return { - title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.createFailedTitle', - 'Couldn’t create workspace' - ), - body: cloud - ? t( + return cloud + ? { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.provisionTitleCloud', + 'The sandbox didn’t start' + ), + body: t( 'auto.components.worktree.creation.VmBuildFailureCard.provisionBodyCloud', 'Something went wrong while starting the sandbox. Try again, or open the logs for details.' ) - : failure.error - } + } + : { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.provisionTitleVm', + 'The VM recipe failed' + ), + body: failure.error + } case 'create': - return { - title: t( - 'auto.components.worktree.creation.VmBuildFailureCard.createFailedTitle', - 'Couldn’t create workspace' - ), - body: cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.createBodyCloud', - 'Your sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details.' + return cloud + ? { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createTitleCloud', + 'Couldn’t open the workspace on the sandbox' + ), + body: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createBodyCloud2', + 'The sandbox started, but Orca couldn’t open the workspace on it. Try again, or open the logs for details.' ) - : failure.error - } + } + : { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.createTitleVm', + 'Couldn’t create the workspace on the VM' + ), + body: failure.error + } } } diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts new file mode 100644 index 00000000000..e88d68b9764 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts @@ -0,0 +1,29 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { classifyVmBuildFailure } from './vm-build-failure' +import { vmBuildFailureCopy } from './vm-build-failure-copy' +import { isOrcaCloudBuild } from './vm-build-steps' + +/** 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): void { + const cloud = isOrcaCloudBuild(entry) + const failure = classifyVmBuildFailure({ entry, error, cloud }) + if (!failure) { + return + } + // Unknown here; the card itself refines the copy for members once billing status loads. + const { title, body } = vmBuildFailureCopy(failure, { cloud, canManageBilling: true }, translate) + toast.error(title, { + ...(body ? { description: body } : {}), + ...(failure.kind === 'plan' + ? { + action: { + label: translate('auto.lib.orcaCloudSession.seePlans', 'See plans'), + onClick: () => openPlansPage('sandbox') + } + } + : {}) + }) +} diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index f0c4ee23dfb..968f05b436d 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -5,8 +5,11 @@ import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-w export type VmBuildAccountFailureKind = | 'plan' | 'hoursUsed' + | 'spendCap' | 'payment' | 'concurrency' + | 'memberConcurrency' + | 'githubNotConnected' | 'signIn' | 'unavailable' | 'network' @@ -24,16 +27,19 @@ const ERROR_CODE_KINDS: Partial> = { cloudPlanRequired: 'plan', cloudConcurrencyLimit: 'concurrency', cloudSignInRequired: 'signIn', - cloudUnavailable: 'unavailable' + cloudUnavailable: 'unavailable', + cloudGithubNotConnected: 'githubNotConnected' } // The hosted provider logs the control plane's deny reason as `Orca Cloud: `. const DENY_REASON = /^Orca Cloud: ([a-z_]+)$/m const DENY_REASON_KINDS: Partial> = { included_hours_exhausted: 'hoursUsed', - overage_cap_reached: 'hoursUsed', + overage_cap_reached: 'spendCap', payment_past_due: 'payment', - payment_grace_expired: 'payment' + payment_grace_expired: 'payment', + concurrency_limit: 'concurrency', + member_concurrency_limit: 'memberConcurrency' } const SNAPSHOT_MISSING = /\bsnapshot\b[^\n]*\bnot found\b/i @@ -58,9 +64,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 +89,36 @@ export function classifyVmBuildFailure(args: { const ACCOUNT_GATES: ReadonlySet = new Set([ 'plan', 'hoursUsed', + 'spendCap', 'payment', 'signIn', - 'concurrency' + 'concurrency', + 'memberConcurrency', + 'githubNotConnected' ]) +// Nothing started, so no step failed: steps stay pending instead of showing a red failure. +const NOTHING_STARTED: ReadonlySet = new Set([ + ...ACCOUNT_GATES, + 'unavailable', + 'network' +]) + +export function nothingStarted(failure: VmBuildFailure | null): boolean { + return failure !== null && NOTHING_STARTED.has(failure.kind) +} + +/** Billing refusals an owner or admin fixes in Plan & billing. */ +export function isBillingFailure(failure: VmBuildFailure | null): boolean { + return ( + failure !== null && + (failure.kind === 'plan' || + failure.kind === 'hoursUsed' || + failure.kind === 'spendCap' || + failure.kind === 'payment') + ) +} + /** Refused before anything started: an account limit, not a broken build. */ export function isAccountGate(failure: VmBuildFailure | null): boolean { return failure !== null && ACCOUNT_GATES.has(failure.kind) diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx new file mode 100644 index 00000000000..0e406cd369d --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -0,0 +1,88 @@ +// 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' + +export const LOG_LINES = [ + 'Creating sandbox from snapshot snap_7f2c…', + 'Sandbox ready: sbx_41d9 (us-east-1)', + 'Cloning repository…', + 'Starting orca serve on :7420', + 'Pairing code emitted.' +] +export const LOG = LOG_LINES.join('\n') +// Every fixture is drawn 102 seconds into its build, with lines arriving a second or so apart. +export const T0 = 1_700_000_000_000 +export const NOW = T0 + 102_000 +export const stampsFor = (lines: number): number[] => + Array.from({ length: lines }, (_, index) => T0 + 400 + index * 1300) + +export type Recipe = NonNullable +export const LOCAL_RECIPE: Recipe = { sourceRepoId: 'repo', recipeId: 'sandbox', projectId: 'p' } +export const CLOUD_RECIPE: Recipe = { ...LOCAL_RECIPE, recipeId: 'cloud', provider: 'orca-cloud' } + +export function entry( + patch: Partial, + recipe: Recipe = LOCAL_RECIPE +): PendingWorktreeCreation { + const log = patch.provisioningLog ?? LOG + return { + creationId: 'fixture', + phase: 'provisioning-vm', + status: 'creating', + startedAt: T0, + indeterminate: false, + loaderVisible: true, + provisioningLog: log, + provisioningLogStamps: stampsFor(log === '' ? 0 : log.split('\n').length), + phaseLog: [{ phase: 'provisioning-vm', at: T0 }], + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only name and ephemeralVmRecipe from the request. + request: { name: 'fix-login', ephemeralVmRecipe: recipe } as PendingWorktreeCreation['request'], + ...patch + } +} + +export function sheet( + value: PendingWorktreeCreation, + error: string | null, + now: number, + agentSignInRow?: React.ReactNode +) { + return ( +
    + {}} + onRetry={() => {}} + onDismiss={() => {}} + onEditRecipe={() => {}} + agentSignInRow={agentSignInRow} + /> +
    + ) +} + +export function frame( + value: PendingWorktreeCreation, + error: string | null = null, + now = NOW, + agentSignInRow?: React.ReactNode +) { + return defineFixture({ width: 760, render: () => sheet(value, error, now, agentSignInRow) }) +} + +export const CLOUD_LOG = '[orca-cloud] checking-entitlement\n[orca-cloud] provisioning' +// What the provider really prints around a failure: progress, internals the plain view hides, and the cause. +export const CLOUD_FAILED_LOG = [ + '[orca-cloud] checking-entitlement', + '[orca-cloud] provisioning', + 'sandbox sbx_41d9 scheduled on pool p-use1-3', + 'Orca Cloud refused the request (provider_unavailable).' +].join('\n') +export const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found` diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts index b3807a4e7fb..100dbd91d9c 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts @@ -6,6 +6,7 @@ import { appendStampedLog } from '@/lib/pending-creation-provisioning-log' import { deriveVmBuildSteps } from './vm-build-steps' import { classifyVmBuildFailure } from './vm-build-failure' import { holdRunningSteps } from './use-minimum-running-steps' +import { humanizeOrcaCloudLogLine } from './orca-cloud-build-log' const base = { status: 'creating' as const, @@ -31,18 +32,58 @@ describe('deriveVmBuildSteps', () => { 10_000 ) expect(steps).toEqual([ - { id: 'provision', state: 'done', elapsedMs: 5000, percent: null, startedAt: 1000 }, - { id: 'checks', state: 'done', elapsedMs: 3000, percent: null, startedAt: 6000 }, - { id: 'create', state: 'running', elapsedMs: 1000, percent: 40, startedAt: 9000 } + { + id: 'provision', + state: 'done', + elapsedMs: 5000, + percent: null, + startedAt: 1000, + skipped: false + }, + { + id: 'checks', + state: 'done', + elapsedMs: 3000, + percent: null, + startedAt: 6000, + skipped: false + }, + { + id: 'create', + state: 'running', + elapsedMs: 1000, + percent: 40, + startedAt: 9000, + skipped: false + } ]) }) - it('marks the workspace step failed when creation fails after the VM is up', () => { + it('marks the workspace step failed, with how long it ran, when creation fails on the VM', () => { const steps = deriveVmBuildSteps( - { ...base, status: 'error', phase: 'fetching', environmentCheck: { status: 'passed' } }, - 5000 + { + ...base, + status: 'error', + phase: 'fetching', + phaseLog: [ + { phase: 'provisioning-vm', at: 1000 }, + { phase: 'fetching', at: 4000 } + ], + errorAt: 6500, + environmentCheck: { status: 'passed' } + }, + 9000 ) expect(steps.map((step) => step.state)).toEqual(['done', 'done', 'failed']) + expect(steps[2].elapsedMs).toBe(2500) + }) + + it('shows skipped checks as skipped, not verified and not stuck pending', () => { + const steps = deriveVmBuildSteps( + { ...base, phase: 'fetching', environmentCheck: { status: 'skipped' } }, + 5000 + ) + expect(steps[1]).toMatchObject({ state: 'done', skipped: true }) }) it('reads as done once the worktree exists and is opening', () => { @@ -81,6 +122,20 @@ describe('classifyVmBuildFailure', () => { ).toEqual({ kind: 'hoursUsed' }) }) + it('tells a member limit apart from the team limit, and a spend cap from used hours', () => { + const refused = (errorCode: string, reason: string) => + classifyVmBuildFailure({ + entry: { ...entry, errorCode, provisioningLog: `Orca Cloud: ${reason}\n` }, + error: 'x', + cloud: true + }) + expect(refused('cloudConcurrencyLimit', 'member_concurrency_limit')).toEqual({ + kind: 'memberConcurrency' + }) + expect(refused('cloudConcurrencyLimit', 'concurrency_limit')).toEqual({ kind: 'concurrency' }) + expect(refused('cloudPlanRequired', 'overage_cap_reached')).toEqual({ kind: 'spendCap' }) + }) + it('names a missing snapshot only for Orca Cloud', () => { const failed = { entry: { ...entry, provisioningLog: 'Error: snapshot snap_1 not found' }, @@ -126,3 +181,17 @@ describe('holdRunningSteps', () => { ]) }) }) + +describe('humanizeOrcaCloudLogLine', () => { + const t = ((_key: string, fallback: string) => fallback) as Parameters< + typeof humanizeOrcaCloudLogLine + >[1] + + it('turns provider codes into sentences and hides internals', () => { + expect(humanizeOrcaCloudLogLine('Orca Cloud: included_hours_exhausted', t)).toBe( + 'This month’s included sandbox hours are used up.' + ) + expect(humanizeOrcaCloudLogLine('[orca-cloud] resuming', t)).toBe('Waking the sandbox…') + expect(humanizeOrcaCloudLogLine('sandbox sbx_41d9 scheduled on pool p-use1-3', t)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.ts index 2ac721b967b..7428734ee72 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.ts @@ -10,6 +10,8 @@ export type VmBuildStepId = 'provision' | 'checks' | 'create' export type VmBuildStep = { id: VmBuildStepId state: WorktreeSetupStepState + /** Done without running: an older VM server has no environment checks. */ + skipped: boolean /** Time spent so far (running) or in total (done/failed); null when unknown. */ elapsedMs: number | null /** Git's checkout percent while the workspace step checks out files. */ @@ -18,15 +20,6 @@ export type VmBuildStep = { startedAt: number | null } -/** Typical Orca Cloud step durations in seconds, shown as "usually ~Ns" while a step runs. */ -export const ORCA_CLOUD_TYPICAL_STEP_SECONDS: Record = { - provision: 5, - checks: 3, - create: 2 -} - -type StepCore = Omit - type VmBuildEntry = Pick< PendingWorktreeCreation, | 'status' @@ -36,6 +29,7 @@ type VmBuildEntry = Pick< | 'startedAt' | 'checkoutProgress' | 'worktreeId' + | 'errorAt' > export function isOrcaCloudBuild(entry: Pick): boolean { @@ -53,9 +47,27 @@ function span(start: number | undefined, end: number | undefined): number | null return start === undefined || end === undefined ? null : Math.max(0, end - start) } +function step( + id: VmBuildStepId, + state: WorktreeSetupStepState, + elapsedMs: number | null, + startedAt: number | undefined, + extra: Partial> = {} +): VmBuildStep { + return { + id, + state, + elapsedMs, + startedAt: startedAt ?? null, + skipped: extra.skipped ?? false, + percent: extra.percent ?? null + } +} + /** * Provision, then the VM's environment checks, then the workspace (fetch + checkout, folded into one - * row). A failed step keeps the steps before it done; a worktree id means the workspace is opening. + * row). A failed step keeps the steps before it done and shows how long it ran; a worktree id means + * the workspace is opening. */ export function deriveVmBuildSteps(entry: VmBuildEntry, now: number): VmBuildStep[] { const check = entry.environmentCheck @@ -66,58 +78,35 @@ export function deriveVmBuildSteps(entry: VmBuildEntry, now: number): VmBuildSte const createAt = phaseStart(entry, ['fetching', 'creating']) const provisionDone = Boolean(check) || workspacePhase - const provision: StepCore = provisionDone - ? { - id: 'provision', - state: 'done', - elapsedMs: span(provisionAt, check?.startedAt ?? createAt), - percent: null - } - : { - id: 'provision', - state: failed ? 'failed' : 'running', - elapsedMs: failed ? null : span(provisionAt, now), - percent: null - } + const provision = provisionDone + ? step('provision', 'done', span(provisionAt, check?.startedAt ?? createAt), provisionAt) + : failed + ? step('provision', 'failed', span(provisionAt, entry.errorAt), provisionAt) + : step('provision', 'running', span(provisionAt, now), provisionAt) - const checksState: WorktreeSetupStepState = !check - ? 'pending' + const checks = !check + ? step('checks', 'pending', null, undefined) : check.status === 'running' - ? 'running' - : check.status === 'failed' - ? 'failed' - : // An older VM server ran nothing, so the step must not read as verified. - check.status === 'skipped' - ? 'pending' - : 'done' - const checks: StepCore = { - id: 'checks', - state: checksState, - elapsedMs: - checksState === 'running' - ? span(check?.startedAt, now) - : checksState === 'pending' - ? null - : span(check?.startedAt, check?.finishedAt), - percent: null - } + ? step('checks', 'running', span(check.startedAt, now), check.startedAt) + : check.status === 'skipped' + ? // An older VM server ran nothing, so the step says so instead of reading as verified. + step('checks', 'done', null, check.startedAt, { skipped: true }) + : step( + 'checks', + check.status === 'failed' ? 'failed' : 'done', + span(check.startedAt, check.finishedAt), + check.startedAt + ) - const create: StepCore = !workspacePhase - ? { id: 'create', state: 'pending', elapsedMs: null, percent: null } + const create = !workspacePhase + ? step('create', 'pending', null, undefined) : ready - ? { id: 'create', state: 'done', elapsedMs: span(createAt, now), percent: null } + ? step('create', 'done', span(createAt, now), createAt) : failed - ? { id: 'create', state: 'failed', elapsedMs: null, percent: null } - : { - id: 'create', - state: 'running', - elapsedMs: span(createAt, now), + ? step('create', 'failed', span(createAt, entry.errorAt), createAt) + : step('create', 'running', span(createAt, now), createAt, { percent: getVisibleCheckoutProgress(entry)?.percent ?? null - } + }) - return [ - { ...provision, startedAt: provisionAt }, - { ...checks, startedAt: check?.startedAt ?? null }, - { ...create, startedAt: workspacePhase ? (createAt ?? null) : null } - ] + return [provision, checks, create] } diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts new file mode 100644 index 00000000000..bdfa11da25a --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -0,0 +1,17 @@ +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 = { p50Ms: number; p95Ms: number } + +/** + * Measured Orca Cloud timings (dev, warm pool on): create p50 2.9 s / p95 4.0 s, of which the VM is + * ~0.26 s and orcad 2.1 s / 3.4 s; wake p50 4.7 s / p95 7.3 s. Steps without a measurement show no + * hint rather than a guess. Tune here. + */ +export const ORCA_CLOUD_STEP_TIMING: Partial> = { + provision: { p50Ms: 2_900, p95Ms: 4_000 } +} + +export function vmBuildStepTiming(stepId: VmBuildStepId, cloud: boolean): VmBuildStepTiming | null { + return cloud ? (ORCA_CLOUD_STEP_TIMING[stepId] ?? null) : null +} diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index a411a75ed6a..60a39dcf119 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2121,20 +2121,21 @@ "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.", "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 +2145,13 @@ "remoteRepoUnsupported": "Ephemeral VM recipes run on the local desktop host in v1.", "repoNotFound": "Repo not found: {{repoId}}", "resumeExited": "Resume exited with code {{exitCode}}.", - "resumeExitedWithoutCode": "Resume exited with code unknown.", + "resumeExitedWithoutCode": "Resume exited without an exit code.", "runtimeNotFound": "Unknown ephemeral VM runtime: {{runtimeId}}", "runtimeRepoMissing": "Ephemeral VM runtime has no repo id: {{runtimeId}}", "sshTargetRemoveFailed": "Failed to remove the hidden SSH target.", "startRefUnresolved": "Could not resolve provisioned-root start ref: {{ref}}", "suspendExited": "Suspend exited with code {{exitCode}}.", - "suspendExitedWithoutCode": "Suspend exited with code unknown." + "suspendExitedWithoutCode": "Suspend exited without an exit code." } }, "jira": { diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index daa032aedde..0dd5d0df102 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -3711,7 +3711,6 @@ "WorktreeCreationPanel": { "dabd226118": "Schließen", "34dd5ee38b": "Erneut versuchen", - "a3346fc6ed": "Worktree-Erstellung abbrechen", "532aea14ce": "Abbrechen", "cancelProvisioning": "Abbrechen" } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3f86e77cad7..e1bd92b56c8 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4011,7 +4011,6 @@ "WorktreeCreationPanel": { "dabd226118": "Dismiss", "34dd5ee38b": "Retry", - "a3346fc6ed": "Cancel worktree creation", "532aea14ce": "Cancel", "cancelProvisioning": "Cancel", "somethingWentWrong": "Something went wrong while creating the workspace." @@ -4057,27 +4056,25 @@ "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.", + "hoursUsedTitle": "You’ve used this month’s included sandbox hours", + "hoursUsedBody": "Turn on overage in Plan & billing to keep starting sandboxes. 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.", + "concurrencyTitle": "Your team is running as many cloud workspaces as its plan allows", + "concurrencyBody": "Put a running cloud workspace to sleep or delete it, then try again. Nothing was created.", "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.", @@ -4089,7 +4086,26 @@ "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", + "planBodyMember": "Ask an owner or admin to choose a Team plan. Nothing was created, and you weren’t charged.", + "hoursUsedBodyMember": "Ask an owner or admin to turn on overage. Nothing was created.", + "spendCapTitle": "You’ve reached this month’s spend cap", + "spendCapBody": "Raise the monthly spend cap in Plan & billing to keep starting sandboxes. Nothing was created.", + "spendCapBodyMember": "Ask an owner or admin to raise the monthly spend cap. Nothing was created.", + "paymentBodyMember": "Ask an owner or admin to update the payment method. Nothing was created.", + "memberConcurrencyTitle": "You’re running as many cloud workspaces as you can at once", + "memberConcurrencyBody": "Put one of yours to sleep or delete it, then try again. Nothing was created.", + "githubTitle": "Connect GitHub to use this repository", + "githubBody": "Orca Cloud needs access to GitHub to clone this private repository. Connect GitHub to your Orca account, then try again. Nothing was created.", + "signInBody2": "Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created.", + "networkBody2": "Check your internet connection, then try again. Nothing was created.", + "snapshotBody2": "The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created. Try again, or contact support if it keeps happening.", + "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" }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -4097,13 +4113,35 @@ "copy": "Copy log", "label": "Build log", "copyFailed": "Couldn’t copy the log.", - "copiedStatus": "Log copied" + "copiedStatus": "Log copied", + "hiddenLines": "Technical lines hidden: {{count}}. 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…", + "renewing": "Extending the session…", + "rollingOver": "Starting a fresh session…", + "destroying": "Deleting the sandbox…", + "denyNoPlan": "Your account has no active Team plan.", + "denyHours": "This month’s included sandbox hours are used up.", + "denySpendCap": "This month’s spend cap is reached.", + "denyPayment": "A payment is overdue.", + "denyConcurrency": "Your team’s limit on running cloud workspaces is reached.", + "denyMemberConcurrency": "Your limit on running cloud workspaces is reached.", + "denyGithub": "GitHub isn’t connected to your Orca account.", + "denyMachineSize": "This machine size isn’t part of your plan.", + "refusedBilling": "Orca Cloud couldn’t check your plan.", + "refusedProvider": "The sandbox provider is unavailable.", + "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." }, "environmentCheckCopy": { "gitMissing": "git isn’t installed.", @@ -4122,6 +4160,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 +25661,13 @@ "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.", + "recipeExitedWithoutCode": "Recipe exited without an exit code.", + "destroyExitedWithoutCode": "Destroy exited without an exit code.", "suspendExited": "Suspend exited with code {{exitCode}}.", - "suspendExitedWithoutCode": "Suspend exited with code unknown.", + "suspendExitedWithoutCode": "Suspend exited without an exit code.", "resumeExited": "Resume exited with code {{exitCode}}.", - "resumeExitedWithoutCode": "Resume exited with code unknown.", + "resumeExitedWithoutCode": "Resume exited without an exit code.", "recipeTimedOut": "The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.", "provisionInterrupted": "Orca stopped while this VM was being created. Destroy it to release any provider resources.", "cloudConcurrencyLimit": "You already have as many Orca Cloud workspaces running as your plan allows. Sleep or delete one, then try again." diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 5c79ae5902f..f8f92a16236 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -3239,7 +3239,6 @@ "WorktreeCreationPanel": { "dabd226118": "Descartar", "34dd5ee38b": "Reintentar", - "a3346fc6ed": "Cancelar creación del worktree", "532aea14ce": "Cancelar", "cancelProvisioning": "Cancelar" } diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 4aa055dc657..06e4a793a76 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -3464,7 +3464,6 @@ "WorktreeCreationPanel": { "dabd226118": "Ignorer", "34dd5ee38b": "Réessayer", - "a3346fc6ed": "Annuler la création du worktree", "532aea14ce": "Annuler", "cancelProvisioning": "Annuler" } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 83673f53049..d2cf40ffb5e 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "閉じる", "34dd5ee38b": "再試行", - "a3346fc6ed": "ワークツリーの作成をキャンセルする", "532aea14ce": "キャンセル", "cancelProvisioning": "キャンセル" } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index a329d509fd3..ba9f60be77b 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "닫기", "34dd5ee38b": "다시 시도", - "a3346fc6ed": "작업 트리 생성 취소", "532aea14ce": "취소", "cancelProvisioning": "취소" } diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index a0f08564030..e08c9372a32 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -19511,7 +19511,6 @@ "WorktreeCreationPanel": { "dabd226118": "Descartar", "34dd5ee38b": "Tentar novamente", - "a3346fc6ed": "Cancelar criação da worktree", "532aea14ce": "Cancelar", "cancelProvisioning": "Cancelar" } diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 6d7b71a6321..5fa31c567ee 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -3809,7 +3809,6 @@ "WorktreeCreationPanel": { "dabd226118": "Скрыть", "34dd5ee38b": "Повторить", - "a3346fc6ed": "Отменить создание рабочего дерева", "532aea14ce": "Отмена", "cancelProvisioning": "Отмена" } diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 109931b761f..4eabf70df49 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -3687,7 +3687,6 @@ "WorktreeCreationPanel": { "dabd226118": "Kapat", "34dd5ee38b": "Yeniden dene", - "a3346fc6ed": "Worktree oluşturmayı iptal et", "532aea14ce": "İptal", "cancelProvisioning": "İptal" } diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 0af2dd5d4e0..8191a75518c 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -3636,7 +3636,6 @@ "WorktreeCreationPanel": { "dabd226118": "關閉", "34dd5ee38b": "重試", - "a3346fc6ed": "取消工作樹建立", "532aea14ce": "取消", "cancelProvisioning": "取消" } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d9fb1f95d19..7013413fced 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3181,7 +3181,6 @@ "WorktreeCreationPanel": { "dabd226118": "关闭", "34dd5ee38b": "重试", - "a3346fc6ed": "取消工作树创建", "532aea14ce": "取消", "cancelProvisioning": "取消" } diff --git a/src/renderer/src/lib/ephemeral-vm-error-copy.ts b/src/renderer/src/lib/ephemeral-vm-error-copy.ts index 6a7abc5dfd1..7c8fc0c118c 100644 --- a/src/renderer/src/lib/ephemeral-vm-error-copy.ts +++ b/src/renderer/src/lib/ephemeral-vm-error-copy.ts @@ -127,7 +127,9 @@ const COPY: Record strin translate('ephemeralVm.errors.cloudConcurrencyLimit', EN.cloudConcurrencyLimit), cloudSignInRequired: () => translate('ephemeralVm.errors.cloudSignInRequired', EN.cloudSignInRequired), - cloudUnavailable: () => translate('ephemeralVm.errors.cloudUnavailable', EN.cloudUnavailable) + cloudUnavailable: () => translate('ephemeralVm.errors.cloudUnavailable', EN.cloudUnavailable), + cloudGithubNotConnected: () => + translate('ephemeralVm.errors.cloudGithubNotConnected', EN.cloudGithubNotConnected) } function isEphemeralVmFailureCode(code: string): code is EphemeralVmFailureCode { diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 0e96cad01ae..884b80fc3f1 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -7,7 +7,7 @@ import type { Repo } from '../../../shared/repo-types' import { translate } from '@/i18n/i18n' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { gateVmCreateOnEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' -import { showOrcaCloudPlanUpsell } from '@/lib/orca-cloud-session-events' +import { showVmBuildFailureToast } from '@/components/worktree-creation/vm-build-failure-toast' import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' import { @@ -97,8 +97,9 @@ async function prepareEphemeralVmRecipeRequest( state.activePendingCreationId !== creationId || !selectWorktreeCreationSurfaceShown(state) ) { - if (preparedTarget.errorCode === 'cloudPlanRequired') { - showOrcaCloudPlanUpsell(preparedTarget.error) + const failed = state.pendingWorktreeCreations[creationId] + if (failed) { + showVmBuildFailureToast(failed, preparedTarget.error) } else { toast.error(ephemeralVmErrorText(preparedTarget)) } diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 030b52f9104..bc4baedd76a 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -169,6 +169,8 @@ export type PendingWorktreeCreation = { error?: string /** Machine-readable cause of `error`, e.g. `cloudPlanRequired`, so the sheet can offer the right fix. */ errorCode?: string + /** Set by the store when `status` turns to error. */ + errorAt?: number provisioningLog?: string /** Arrival time of each line in `provisioningLog`, index-aligned with its lines. */ provisioningLogStamps?: readonly number[] diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index 2aef311c27a..eae20e96f2c 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -44,6 +44,18 @@ function nextPhaseLog( return entry.phaseLog } +// When this attempt failed, so a failed step can show how long it ran. +function nextErrorAt( + entry: PendingWorktreeCreation, + patch: Partial +): number | undefined { + const status = patch.status ?? entry.status + if (status !== 'error') { + return undefined + } + return entry.status === 'error' ? entry.errorAt : Date.now() +} + export function createUpdatePendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet @@ -88,7 +100,12 @@ export function createUpdatePendingWorktreeCreation( return { pendingWorktreeCreations: { ...s.pendingWorktreeCreations, - [creationId]: { ...entry, ...changes, phaseLog: nextPhaseLog(entry, changes) } + [creationId]: { + ...entry, + ...changes, + phaseLog: nextPhaseLog(entry, changes), + errorAt: nextErrorAt(entry, changes) + } } } }) diff --git a/src/shared/ephemeral-vm-failure-copy.ts b/src/shared/ephemeral-vm-failure-copy.ts index 6a03be6dfb0..592cd732984 100644 --- a/src/shared/ephemeral-vm-failure-copy.ts +++ b/src/shared/ephemeral-vm-failure-copy.ts @@ -14,7 +14,7 @@ export const EPHEMERAL_VM_FAILURE_COPY = { startRefUnresolved: 'Could not resolve provisioned-root start ref: {{ref}}', defaultStartRefUnresolved: 'Could not resolve a default provisioned-root start ref.', recipeExited: 'Recipe exited with code {{exitCode}}.', - recipeExitedWithoutCode: 'Recipe exited with code unknown.', + recipeExitedWithoutCode: 'Recipe exited without an exit code.', recipeResultMissing: 'Recipe produced no JSON result.', recipeResultNotJsonObject: 'Recipe stdout must be one JSON object.', recipeResultPairingCodeInvalid: 'Recipe result pairingCode is not a valid Orca pairing code.', @@ -24,13 +24,13 @@ export const EPHEMERAL_VM_FAILURE_COPY = { provisionedRootNotConfigured: 'Recipe result requests provisioned-root checkout, but the recipe is not configured for it.', suspendExited: 'Suspend exited with code {{exitCode}}.', - suspendExitedWithoutCode: 'Suspend exited with code unknown.', + suspendExitedWithoutCode: 'Suspend exited without an exit code.', resumeExited: 'Resume exited with code {{exitCode}}.', - resumeExitedWithoutCode: 'Resume exited with code unknown.', + resumeExitedWithoutCode: 'Resume exited without an exit code.', recipeTimedOut: 'The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.', destroyExited: 'Destroy exited with code {{exitCode}}.', - destroyExitedWithoutCode: 'Destroy exited with code unknown.', + destroyExitedWithoutCode: 'Destroy exited without an exit code.', destroyFailed: 'Destroy failed.', destroyDisabled: 'Destroy is disabled for this recipe.', cleanupStopped: 'Cleanup stopped by user.', @@ -41,7 +41,9 @@ 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.' } as const export type EphemeralVmFailureCode = keyof typeof EPHEMERAL_VM_FAILURE_COPY From a8d6bb4698c0551403dcaffccaabfbf0ed4e1b0b Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:05:41 -0800 Subject: [PATCH 02/11] fix(cloud): build sheet round 4: glossary cards, GitHub not connected + no GitHub remote before any sandbox, measured start hint from /v1/config, Orca Cloud host label - Account/billing cards use glossary titles (Out of sandbox hours, Spend cap reached, Payment failed, running-sandbox limits), role-aware next steps, and 'Nothing was created, and you weren't charged.' - 409 github_not_connected: 'GitHub isn't connected for ' + Connect GitHub (POST /v1/github/connect, opens the GitHub install page) + Try again. - A repo without a GitHub remote is refused in main before the control plane is called, with Start empty / Push to GitHub first. - GET /v1/config serves createTiming (p50/p95 of recent create-to-ready); the sheet's 'usually ~Ns' reads it and shows no hint without a measurement. - Orca Cloud servers display as 'Orca Cloud' in sidebar host labels and the usage segment; legacy ' VM ' names are renamed at startup. --- .../apps/sandbox-control/src/create-timing.ts | 38 ++++++ cloud/apps/sandbox-control/src/index.ts | 8 +- .../apps/sandbox-control/test/config.test.ts | 30 +++++ ...egacy-orca-cloud-environment-names.test.ts | 67 ++++++++++ .../legacy-orca-cloud-environment-names.ts | 55 ++++++++ .../runtime-provisioning-persistence.ts | 6 + src/main/hosted-sandbox/hosted-account-ipc.ts | 37 ++++++ .../hosted-sandbox-control-plane-client.ts | 19 ++- .../hosted-sandbox/hosted-sandbox-recipe.ts | 18 ++- .../hosted-workspace-service.ts | 6 +- .../ephemeral-vm-orca-cloud-remote.test.ts | 99 ++++++++++++++ src/main/ipc/ephemeral-vm-recipe-context.ts | 18 ++- src/main/ipc/ephemeral-vm.ts | 22 ++- src/preload/api/ephemeral-vm-api.ts | 2 + .../api/orca-cloud-workspace-bridge.ts | 2 + .../NativeChatResumeRuntimeModal.tsx | 3 +- .../activity-thread-hover-card-summary.tsx | 3 +- ...use-automations-page-presentation-state.ts | 6 +- .../dashboard-snapshot-workspaces.ts | 3 +- .../NativeChatResumeStatusSegment.tsx | 3 +- .../status-bar/SshStatusSegment.tsx | 3 +- .../status-bar/use-owner-usage-rate-limits.ts | 8 +- .../VmBuildFailureActions.tsx | 68 +++++++++- .../worktree-creation/VmBuildFailureCard.tsx | 10 +- .../worktree-creation/VmBuildSheet.tsx | 32 ++++- .../VmBuildSheetCloudFailures.fixture.tsx | 82 ++++++++++-- .../worktree-creation/VmBuildStepRow.tsx | 10 +- .../vm-build-failure-copy.ts | 97 ++++++++------ .../vm-build-failure-toast.ts | 14 +- .../vm-build-failure.test.ts | 125 ++++++++++++++++++ .../worktree-creation/vm-build-failure.ts | 8 +- .../vm-build-repo-actions.ts | 48 +++++++ .../vm-build-sheet-fixture-support.tsx | 24 +++- .../worktree-creation/vm-build-timing.ts | 59 +++++++-- .../src/i18n/en-runtime-required.json | 1 + src/renderer/src/i18n/locales/en.json | 54 ++++---- .../src/lib/ephemeral-vm-error-copy.ts | 4 +- .../src/lib/ephemeral-vm-workspace-target.ts | 4 +- .../src/lib/ephemeral-vm-worktree-creation.ts | 1 + .../orca-cloud-workspace-store.test.ts | 2 + .../creation/pending-worktree-creation.ts | 2 + .../runtime-environment-disconnect-toast.ts | 3 +- src/shared/ephemeral-vm-failure-copy.ts | 4 +- .../execution-host/execution-host-registry.ts | 7 +- .../hosted-sandbox/cloud-workspace-api.ts | 7 + .../hosted-sandbox/hosted-sandbox-wire.ts | 19 ++- .../orca-cloud-environment-name.test.ts | 48 +++++++ .../orca-cloud-environment-name.ts | 40 ++++++ 48 files changed, 1093 insertions(+), 136 deletions(-) create mode 100644 cloud/apps/sandbox-control/src/create-timing.ts create mode 100644 src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts create mode 100644 src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts create mode 100644 src/main/hosted-sandbox/hosted-account-ipc.ts create mode 100644 src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-failure.test.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts create mode 100644 src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts create mode 100644 src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts diff --git a/cloud/apps/sandbox-control/src/create-timing.ts b/cloud/apps/sandbox-control/src/create-timing.ts new file mode 100644 index 00000000000..69644e0be97 --- /dev/null +++ b/cloud/apps/sandbox-control/src/create-timing.ts @@ -0,0 +1,38 @@ +// Measured sandbox start times for GET /v1/config, so the desktop's "usually ~Ns" hint is a real median. +import type { HostedSandboxTiming } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' + +/** Latest rows only: a cheap rowid scan, and the hint should follow the current pool and image. */ +const RECENT_ROWS = 500 +/** Fewer starts than this is noise, so clients show no hint rather than a guess. */ +export const MIN_TIMING_SAMPLES = 10 +/** + * `ready_at` moves on every wake, so a long gap is a later wake, not a slow start. Real starts + * finish inside the boot budget well before this. + */ +const MAX_START_MS = 120_000 + +function percentile(sorted: readonly number[], fraction: number): number { + const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(fraction * sorted.length) - 1)) + return sorted[index] +} + +export function summarizeStartTimes(durations: readonly number[]): HostedSandboxTiming | undefined { + const sorted = durations.filter((ms) => ms >= 0 && ms <= MAX_START_MS).sort((a, b) => a - b) + if (sorted.length < MIN_TIMING_SAMPLES) { + return undefined + } + return { p50Ms: percentile(sorted, 0.5), p95Ms: percentile(sorted, 0.95), samples: sorted.length } +} + +/** Create-to-ready of the most recent sandboxes; undefined when too few have started. */ +export async function recentCreateTiming(db: D1Database): Promise { + const { results } = await db + .prepare( + `SELECT ready_at - created_at AS ms FROM sandboxes + WHERE ready_at IS NOT NULL + ORDER BY rowid DESC LIMIT ?` + ) + .bind(RECENT_ROWS) + .all<{ ms: number }>() + return summarizeStartTimes(results.map((row) => row.ms)) +} diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 3caf271cbe2..414e8bb55cf 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -33,6 +33,7 @@ import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' import { maintainPool, poolConfigFromEnv } from './pool' +import { recentCreateTiming } 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,12 @@ 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 }) + // A timing read failure must never take the constants down with it. + const createTiming = await recentCreateTiming(env.SANDBOX_DB).catch(() => undefined) + return Response.json( + { idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, ...(createTiming ? { createTiming } : {}) }, + { headers: { 'cache-control': 'public, max-age=300' } } + ) } if (url.pathname === '/v1/github/dev-connect' && env.SANDBOX_ENV !== 'prod') { // Dev-only, link-shareable start of the user flow: mints a fresh 10-min state per click for a dev: diff --git a/cloud/apps/sandbox-control/test/config.test.ts b/cloud/apps/sandbox-control/test/config.test.ts index 1d43a6d9da1..d58a40069b3 100644 --- a/cloud/apps/sandbox-control/test/config.test.ts +++ b/cloud/apps/sandbox-control/test/config.test.ts @@ -4,6 +4,7 @@ import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { DEFAULT_PLANS } from '../../billing/src/plans' +import { MIN_TIMING_SAMPLES, summarizeStartTimes } from '../src/create-timing' import { createHarness } from './harness' describe('GET /v1/config', () => { @@ -14,5 +15,34 @@ 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() }) }) diff --git a/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts new file mode 100644 index 00000000000..8a24c9b655a --- /dev/null +++ b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.test.ts @@ -0,0 +1,67 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { + addEnvironmentFromPairingCode, + listEnvironments +} from '../../shared/remote-runtime/host-store/runtime-environment-store' +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { renameLegacyOrcaCloudEnvironments } from './legacy-orca-cloud-environment-names' + +const CLOUD_RUNTIME = '6f1c2a9e-0b4d-4c11-9a3e-7d2f22b5b1e7' +const RECIPE_RUNTIME = '0aa1c2a9-0b4d-4c11-9a3e-7d2f9c0ffee1' + +function runtime( + id: string, + runtimeEnvironmentId: string, + recipeId: string +): EphemeralVmRuntimeRecord { + return { id, recipeId, runtimeEnvironmentId } as EphemeralVmRuntimeRecord +} + +describe('renameLegacyOrcaCloudEnvironments', () => { + let userDataPath: string + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-legacy-cloud-names-')) + }) + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + }) + + function add(name: string, key: number): string { + return addEnvironmentFromPairingCode(userDataPath, { + name, + source: 'ephemeral-vm', + pairingCode: encodePairingOffer({ + v: 2, + endpoint: 'wss://server.example/runtime', + publicKeyB64: Buffer.alloc(32, key).toString('base64'), + deviceToken: `token-${key}` + }), + now: 100 + }).id + } + + it('renames an Orca Cloud server saved as a VM and leaves recipe VMs alone', () => { + const cloud = add('repo VM 22b5b1e7', 1) + const recipe = add('repo VM 9c0ffee1', 2) + + const renamed = renameLegacyOrcaCloudEnvironments(userDataPath, [ + runtime(CLOUD_RUNTIME, cloud, 'cloud'), + runtime(RECIPE_RUNTIME, recipe, 'docker') + ]) + + expect(renamed).toBe(1) + const names = Object.fromEntries( + listEnvironments(userDataPath).map((environment) => [environment.id, environment.name]) + ) + expect(names[cloud]).toBe('repo sandbox 22b5b1e7') + expect(names[recipe]).toBe('repo VM 9c0ffee1') + // Idempotent: a second start finds nothing left to rename. + expect( + renameLegacyOrcaCloudEnvironments(userDataPath, [runtime(CLOUD_RUNTIME, cloud, 'cloud')]) + ).toBe(0) + }) +}) diff --git a/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts new file mode 100644 index 00000000000..3e2e3939a85 --- /dev/null +++ b/src/main/ephemeral-vm/legacy-orca-cloud-environment-names.ts @@ -0,0 +1,55 @@ +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { ORCA_CLOUD_RECIPE_ID } from '../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { normalizeTypedName } from '../../shared/typed-name-normalization' +import { legacyOrcaCloudEnvironmentName } from '../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' +import { + readPersistedEnvironmentStore, + writeEnvironmentStore +} from '../../shared/remote-runtime/host-store/runtime-environment-store-file' + +function isOrcaCloudRuntime(runtime: EphemeralVmRuntimeRecord): boolean { + return runtime.recipe?.provider === 'orca-cloud' || runtime.recipeId === ORCA_CLOUD_RECIPE_ID +} + +/** + * Early builds saved an Orca Cloud server as " VM ", so the sidebar showed it as a + * raw VM. Renames those to the " sandbox " form every surface shows as "Orca Cloud". + * Only servers an Orca Cloud runtime record points at are touched; custom recipe VMs keep "VM". + */ +export function renameLegacyOrcaCloudEnvironments( + userDataPath: string, + runtimes: readonly EphemeralVmRuntimeRecord[] +): number { + const renames = new Map() + for (const runtime of runtimes) { + if (runtime.runtimeEnvironmentId && isOrcaCloudRuntime(runtime)) { + renames.set(runtime.runtimeEnvironmentId, runtime.id) + } + } + if (renames.size === 0) { + return 0 + } + const store = readPersistedEnvironmentStore(userDataPath) + const taken = new Set( + store.environments.map((environment) => normalizeTypedName(environment.name)) + ) + let renamed = 0 + const environments = store.environments.map((environment) => { + const runtimeId = renames.get(environment.id) + const next = + environment.source === 'ephemeral-vm' && runtimeId + ? legacyOrcaCloudEnvironmentName(environment.name, runtimeId) + : null + // Names stay unique: never take one another saved server already has. + if (!next || taken.has(normalizeTypedName(next))) { + return environment + } + taken.add(normalizeTypedName(next)) + renamed++ + return { ...environment, name: next } + }) + if (renamed > 0) { + writeEnvironmentStore(userDataPath, { ...store, environments }) + } + return renamed +} diff --git a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts index 957bf90b87b..c0fd9636c84 100644 --- a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts +++ b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts @@ -21,6 +21,7 @@ import type { ProvisionEphemeralVmRuntimeResult } from './runtime-service' import { cleanupFailedEphemeralVmStart } from './failed-start-cleanup' +import { renameLegacyOrcaCloudEnvironments } from './legacy-orca-cloud-environment-names' export type EphemeralVmWriteAhead = { instanceId: string @@ -160,6 +161,11 @@ export function reconcileInterruptedEphemeralVmProvisionsOnStartup(userDataPath: } catch (error) { console.warn('[ephemeral-vm] Could not reconcile interrupted provisions:', error) } + try { + renameLegacyOrcaCloudEnvironments(userDataPath, listEphemeralVmRuntimes(userDataPath)) + } catch (error) { + console.warn('[ephemeral-vm] Could not rename legacy Orca Cloud servers:', error) + } } /** Tracked VMs must go through Destroy; only result-less write-ahead rows can be dropped by hand. */ diff --git a/src/main/hosted-sandbox/hosted-account-ipc.ts b/src/main/hosted-sandbox/hosted-account-ipc.ts new file mode 100644 index 00000000000..fcb9c52db80 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-account-ipc.ts @@ -0,0 +1,37 @@ +// Account-level Orca Cloud calls for the window: product config (measured timings) and GitHub connect. +import { ipcMain, shell } from 'electron' +import { ORCA_CLOUD_WORKSPACE_CHANNELS as CH } from '../../shared/hosted-sandbox/cloud-workspace-api' +import type { HostedSandboxConfigResponse } from '../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' +import { failure } from './hosted-workspace-runtime' + +export const HOSTED_ACCOUNT_CHANNELS = [CH.getConfig, CH.connectGitHub] as const + +export function registerHostedAccountHandlers( + client: Pick +): void { + // Timings move slowly and the Worker caches them for 5 minutes; one read per app session is plenty. + let config: Promise | null = null + ipcMain.handle(CH.getConfig, () => { + config ??= client.config().catch(() => { + // Offline now says nothing about later: ask again next time. + config = null + return null + }) + return config + }) + + ipcMain.handle(CH.connectGitHub, async () => { + try { + const { installUrl } = await client.connectGitHub() + // Only ever hand the browser a GitHub page, whatever the response says. + if (new URL(installUrl).origin !== 'https://github.com') { + return { ok: false, code: 'failed', message: 'Unexpected GitHub connect URL.' } + } + await shell.openExternal(installUrl) + return { ok: true, value: null } + } catch (error) { + return failure(error) + } + }) +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts index 800c19b3771..4768d0597f9 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts @@ -12,6 +12,9 @@ export { } from './hosted-sandbox-request' import { HostedSandboxDesktopResponseSchema, + HostedSandboxConfigResponseSchema, + HostedGithubConnectResponseSchema, + type HostedSandboxConfigResponse, HostedArchiveResponseSchema, HostedWakeResponseSchema, HostedWorkspaceStatusResponseSchema, @@ -29,6 +32,9 @@ import { type HostedSandboxReadyResponse, type HostedSandboxView } from '../../shared/hosted-sandbox/hosted-sandbox-wire' +import type { z } from 'zod' + +type HostedGithubConnectResponse = z.infer export type HostedSandboxControlPlaneClient = { create( @@ -71,6 +77,10 @@ export type HostedSandboxControlPlaneClient = { ): Promise /** Starts the VM's remote desktop (idempotent); it listens on the VM's loopback only. */ startDesktop(sandboxId: string, signal?: AbortSignal): Promise + /** Product constants and measured timings (GET /v1/config). */ + config(signal?: AbortSignal): Promise + /** Starts binding a GitHub App installation to the account; the browser finishes it. */ + connectGitHub(signal?: AbortSignal): Promise } export function createHostedSandboxControlPlaneClient( @@ -192,6 +202,13 @@ export function createHostedSandboxControlPlaneClient( kind: 'control', signal }) - ).desktop + ).desktop, + config: (signal) => + call('GET', 'v1/config', HostedSandboxConfigResponseSchema, { kind: 'control', signal }), + connectGitHub: (signal) => + call('POST', 'v1/github/connect', HostedGithubConnectResponseSchema, { + kind: 'control', + signal + }) } } diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index dd32beb345e..0d3cefe73e5 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -2,7 +2,7 @@ // in-process through the HostedSandboxDriver, and answering like a recipe process would. import { z } from 'zod' import { EphemeralVmRecipeResultSchema } from '../../shared/ephemeral-vm-recipes' -import { ephemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' +import { ephemeralVmFailure, type EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' import { normalizeGitRemoteUrl } from '../../shared/git/remotes/git-remote-identity' import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' import { @@ -61,6 +61,22 @@ export async function hostedSandboxRepoUrl(repoPath: string): Promise, + repoPath: string, + startEmpty: boolean | undefined +): Promise { + if (recipe.provider !== 'orca-cloud' || startEmpty || (await hostedSandboxRepoUrl(repoPath))) { + return null + } + return ephemeralVmFailure('cloudNoGithubRemote') +} + function ok(stdout: string): RecipeStepProviderResult { return { stdout, stderr: '', exitCode: 0, signal: null } } diff --git a/src/main/hosted-sandbox/hosted-workspace-service.ts b/src/main/hosted-sandbox/hosted-workspace-service.ts index 5a86ccb93e8..c471144c35e 100644 --- a/src/main/hosted-sandbox/hosted-workspace-service.ts +++ b/src/main/hosted-sandbox/hosted-workspace-service.ts @@ -2,6 +2,7 @@ // progress and OOM notices. Maps the renderer's workspace id to its Orca Cloud runtime record. import { failQueuedCloudPrompts } from './cloud-offline-service' import { ipcMain, type BrowserWindow } from 'electron' +import { HOSTED_ACCOUNT_CHANNELS, registerHostedAccountHandlers } from './hosted-account-ipc' import { listEphemeralVmRuntimes, updateEphemeralVmRuntimeStatus @@ -168,7 +169,8 @@ export function installHostedWorkspaceService(deps: { CH.archive, CH.unarchive, CH.getArchive, - CH.listCloudWorkspaceIds + CH.listCloudWorkspaceIds, + ...HOSTED_ACCOUNT_CHANNELS ]) { ipcMain.removeHandler(channel) } @@ -182,6 +184,8 @@ export function installHostedWorkspaceService(deps: { .map((runtime) => runtime.workspaceId!) ) + registerHostedAccountHandlers(deps.client) + ipcMain.handle(CH.getStatus, async (_event, args: { workspaceId: string }) => { const found = findCloudRuntime(deps.userDataPath, args.workspaceId) if (!found) { diff --git a/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts new file mode 100644 index 00000000000..2bc554abb84 --- /dev/null +++ b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts @@ -0,0 +1,99 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { registerEphemeralVmRecipeStepProvider } from '../../shared/ephemeral-vm-recipe-step-providers' +import { ORCA_CLOUD_RECIPE } from '../hosted-sandbox/hosted-sandbox-recipe' + +const handlers = new Map unknown>() +const { getPathMock, handleMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(), + handleMock: vi.fn() +})) + +vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, + app: { getPath: getPathMock }, + ipcMain: { handle: handleMock, removeHandler: vi.fn() } +})) + +vi.mock('../hosted-sandbox/hosted-sandbox-install', async (importOriginal) => ({ + ...(await importOriginal()), + withProviderRecipes: async () => [ORCA_CLOUD_RECIPE] +})) + +import { registerEphemeralVmHandlers } from './ephemeral-vm' + +const tempDirs: string[] = [] +const unregister: (() => void)[] = [] + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + for (const off of unregister.splice(0)) { + off() + } + vi.clearAllMocks() +}) + +function setup(remote: string | null) { + const userDataPath = makeTempDir('orca-cloud-remote-user-data-') + const repoPath = makeTempDir('orca-cloud-remote-repo-') + execFileSync('git', ['init', '-q'], { cwd: repoPath }) + if (remote) { + execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: repoPath }) + } + getPathMock.mockReturnValue(userDataPath) + handleMock.mockImplementation((channel: string, handler: never) => handlers.set(channel, handler)) + const step = vi.fn(async () => ({ + stdout: '', + stderr: 'stopped here\n', + exitCode: 1, + signal: null + })) + unregister.push(registerEphemeralVmRecipeStepProvider('orca-cloud', step)) + const repo = { id: 'repo-1', path: repoPath, displayName: 'Repo', addedAt: 0 } + registerEphemeralVmHandlers({ + getRepo: vi.fn((id: string) => (id === repo.id ? repo : null)), + getRepos: vi.fn(() => [repo]), + getSettings: vi.fn(() => ({ activeRuntimeEnvironmentId: null })) + } as never) + const provision = (extra: Record = {}) => + handlers.get('ephemeralVm:provision')?.(null, { + repoId: 'repo-1', + recipeId: ORCA_CLOUD_RECIPE.id, + ...extra + } as never) as Promise<{ ok: boolean; errorCode?: string }> + return { step, provision } +} + +it('refuses a repository with no GitHub remote before Orca Cloud is asked for a sandbox', async () => { + const { step, provision } = setup(null) + const result = await provision() + expect(result).toMatchObject({ ok: false, errorCode: 'cloudNoGithubRemote' }) + expect(step).not.toHaveBeenCalled() +}) + +it('refuses a remote GitHub does not host, too', async () => { + const { step, provision } = setup('https://gitlab.com/acme/web.git') + expect(await provision()).toMatchObject({ ok: false, errorCode: 'cloudNoGithubRemote' }) + expect(step).not.toHaveBeenCalled() +}) + +it('starts the sandbox when the user chose to start empty, or the repo is on GitHub', async () => { + const empty = setup(null) + await empty.provision({ startEmpty: true }) + expect(empty.step).toHaveBeenCalledOnce() + + const github = setup('git@github.com:acme/web.git') + await github.provision() + expect(github.step).toHaveBeenCalledOnce() +}) + +function makeTempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)) + tempDirs.push(dir) + return dir +} diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index acae3e96dca..1539c7e534d 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -6,6 +6,7 @@ import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtime import { isFolderRepo, isGitRepoKind } from '../../shared/repo-kind' import type { OrcaCloudAvailability, OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' import type { PluginService } from '../plugins/plugin-service' +import { orcaCloudEnvironmentName } from '../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' import { getOrcaCloudAvailability, withProviderRecipes @@ -26,6 +27,19 @@ export type EphemeralVmRecipeListResult = { messageParams?: Record } +export type EphemeralVmProvisionArgs = { + repoId: string + recipeId: string + workspaceName?: string + projectId?: string + workspaceId?: string + branch?: string + ref?: string + provisionId?: string + /** Orca Cloud only: the user chose a workspace without their code (no GitHub remote). */ + startEmpty?: boolean +} + export type EphemeralVmRecipeCatalogEntry = { repoId: string repoName: string @@ -70,7 +84,9 @@ export function buildEphemeralEnvironmentName( runtimeId: string, recipe: { provider?: string } ): string { - return `${repo} ${recipe.provider === 'orca-cloud' ? 'sandbox' : 'VM'} ${runtimeId.slice(-8)}` + return recipe.provider === 'orca-cloud' + ? orcaCloudEnvironmentName(repo, runtimeId) + : `${repo} VM ${runtimeId.slice(-8)}` } /** The Run-on picker's list, plus Orca Cloud availability so it can offer sign-in or an upsell. */ diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 91b22536588..befd0bdb363 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -35,11 +35,13 @@ import { listPickerRecipes, buildEphemeralEnvironmentName, resolveRecipeForRepo, - type EphemeralVmRecipeCatalogEntry + type EphemeralVmRecipeCatalogEntry, + type EphemeralVmProvisionArgs } from './ephemeral-vm-recipe-context' import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handlers' import type { PluginService } from '../plugins/plugin-service' import { installHostedSandbox, withProviderRecipes } from '../hosted-sandbox/hosted-sandbox-install' +import { refuseOrcaCloudWithoutGithub } from '../hosted-sandbox/hosted-sandbox-recipe' import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' import { @@ -119,19 +121,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin ipcMain.handle( 'ephemeralVm:provision', - async ( - _event, - args: { - repoId: string - recipeId: string - workspaceName?: string - projectId?: string - workspaceId?: string - branch?: string - ref?: string - provisionId?: string - } - ): Promise => { + async (_event, args: EphemeralVmProvisionArgs): Promise => { const repo = getRecipeRepo(store, args.repoId) if (!repo.ok) { return provisionFailure(repo.failure) @@ -144,6 +134,10 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin if (!recipe) { return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) } + const refused = await refuseOrcaCloudWithoutGithub(recipe, repo.repo.path, args.startEmpty) + if (refused) { + return provisionFailure(refused) + } const controller = args.provisionId ? new AbortController() : null if (args.provisionId && controller) { activeProvisionControllers.set(args.provisionId, controller) diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 2c32e253eb4..1518c91e691 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -54,6 +54,8 @@ export type EphemeralVmApi = { branch?: string ref?: string provisionId?: string + /** Orca Cloud only: start without the repository when it has no GitHub remote. */ + startEmpty?: boolean }) => Promise< | { ok: true diff --git a/src/preload/api/orca-cloud-workspace-bridge.ts b/src/preload/api/orca-cloud-workspace-bridge.ts index e0e01655ba3..b43872e8143 100644 --- a/src/preload/api/orca-cloud-workspace-bridge.ts +++ b/src/preload/api/orca-cloud-workspace-bridge.ts @@ -18,6 +18,8 @@ export const orcaCloudWorkspaceApi = { unarchive: (args) => ipcRenderer.invoke(CH.unarchive, args), getArchive: (args) => ipcRenderer.invoke(CH.getArchive, args), listCloudWorkspaceIds: () => ipcRenderer.invoke(CH.listCloudWorkspaceIds), + getConfig: () => ipcRenderer.invoke(CH.getConfig), + connectGitHub: () => ipcRenderer.invoke(CH.connectGitHub), onWakeProgress: (callback) => { const listener = (_event: Electron.IpcRendererEvent, event: CloudWakeProgressEvent): void => callback(event) diff --git a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx b/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx index 373a69643f5..6353ba2687f 100644 --- a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx +++ b/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx @@ -6,6 +6,7 @@ import { import { NativeChatResumeOccurrenceModal } from './NativeChatResumeOnRestartModal' import { useNativeChatRestartOfferEnabled } from './native-chat-restart-offer-gate' import { useNativeChatRestartRuntimes } from './native-chat-restart-runtimes' +import { runtimeEnvironmentDisplayName } from '../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function NativeChatResumeOnRestartModal(): React.JSX.Element { const enabled = useNativeChatRestartOfferEnabled() @@ -17,7 +18,7 @@ export function NativeChatResumeOnRestartModal(): React.JSX.Element { ))} diff --git a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx index f62405cbfa1..d128804f98c 100644 --- a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx +++ b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx @@ -32,6 +32,7 @@ import { EventTime, ThreadAgentStateIndicator } from './activity-thread-controls import { activityThreadRowCopy, threadAgentStateLabel } from './activity-thread-presentation' import { getActivityThreadWorkspaceTitle } from '@/lib/activity-thread-display' import type { AgentPaneThread } from './activity-thread-types' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function ActivityThreadHoverCardSummary({ thread, @@ -59,7 +60,7 @@ export function ActivityThreadHoverCardSummary({ if (parsedHost?.kind === 'runtime') { const environment = runtimeEnvironments.find((entry) => entry.id === parsedHost.environmentId) if (environment?.name) { - return environment.name + return runtimeEnvironmentDisplayName(environment) } } if (parsedHost?.kind === 'ssh') { diff --git a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts index eb694afb229..9a8ae93052b 100644 --- a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts @@ -14,6 +14,7 @@ import type { AutomationsPageListState } from './use-automations-page-list-state import type { AutomationsPageLocalState } from './use-automations-page-local-state' import type { AutomationsPageStoreState } from './use-automations-page-store-state' import { useTranslate } from '../../i18n/use-translate' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' /** Display labels and action availability derived from the selected host row. */ export function useAutomationsPagePresentationState({ @@ -96,7 +97,10 @@ export function useAutomationsPagePresentationState({ labels.set(`ssh:${encodeURIComponent(targetId)}`, label) } for (const environment of runtimeEnvironments) { - labels.set(`runtime:${encodeURIComponent(environment.id)}`, environment.name) + labels.set( + `runtime:${encodeURIComponent(environment.id)}`, + runtimeEnvironmentDisplayName(environment) + ) } for (const [hostId, label] of hostLabelOverrides) { labels.set(hostId, label) diff --git a/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts b/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts index f74338407ed..45bffb83a04 100644 --- a/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts +++ b/src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts @@ -19,6 +19,7 @@ import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-ov import { isFolderRepo } from '../../../../shared/repo-kind' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export type ActiveDashboardWorkspace = { projectId: string @@ -48,7 +49,7 @@ function buildHostLabelLookup( labels.set(toSshExecutionHostId(targetId), label) } for (const environment of state.runtimeEnvironments ?? []) { - labels.set(toRuntimeExecutionHostId(environment.id), environment.name) + labels.set(toRuntimeExecutionHostId(environment.id), runtimeEnvironmentDisplayName(environment)) } for (const [hostId, label] of getHostDisplayLabelOverrides(state.settings)) { labels.set(hostId, label) diff --git a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx index 49d3805fa3c..fccfc97f648 100644 --- a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.tsx @@ -12,6 +12,7 @@ import { import { useNativeChatRestartRuntimes } from '../native-chat-restart-runtimes' import { resumeRunInFlight } from '../native-chat-resume-run' import { resumeRunFailures, resumeRunView } from '../native-chat-resume-run-view' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' // Keep offers and in-flight/results visible after dialog snooze; statusBarItems must not hide the remaining resume surface. @@ -153,7 +154,7 @@ export function NativeChatResumeStatusSegment({ key={environment.id} iconOnly={iconOnly} store={store} - machineName={environment.name} + machineName={runtimeEnvironmentDisplayName(environment)} offerEnabled /> ))} diff --git a/src/renderer/src/components/status-bar/SshStatusSegment.tsx b/src/renderer/src/components/status-bar/SshStatusSegment.tsx index f26680b1ba7..bce1b1966ee 100644 --- a/src/renderer/src/components/status-bar/SshStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/SshStatusSegment.tsx @@ -42,6 +42,7 @@ import { import { runtimeHostConnectionStateForEntry } from '@/runtime/hosts/connections/runtime-host-connection-state' import { isConnectedRuntimeHostState } from '../../../../shared/remote-runtime/host-status/runtime-host-connection-state' import { RuntimeRepairDialog } from '../runtime-access/RuntimeRepairDialog' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' export function SshStatusSegment({ compact, @@ -110,7 +111,7 @@ export function SshStatusSegment({ const repairRoute = runtimePairingRepairRoute(environment) return { id: environment.id, - label: registryHost?.label || environment.name || environment.id, + label: registryHost?.label || runtimeEnvironmentDisplayName(environment) || environment.id, blockedReason, blocked: blockedReason ? { diff --git a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts index 70256b50b4f..221237bf4a4 100644 --- a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts +++ b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.ts @@ -16,6 +16,7 @@ import { type OwnerUsageFailureReason, type OwnerUsageState } from './owner-usage-rate-limits' +import { runtimeEnvironmentDisplayName } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' // Why: accounts.list({refreshUsage}) waits for the host's provider fetches. const REMOTE_USAGE_REFRESH_TIMEOUT_MS = 30_000 @@ -59,9 +60,10 @@ export function useOwnerUsageRateLimits(local: RateLimitState): OwnerUsageRateLi // Why: route by the focused workspace's owner, never by the Active Server setting. const { target } = useActiveAccountOwner(LOCAL_TARGET) const ownerId = runtimeTargetEnvironmentId(target) - const ownerName = useAppStore( - (s) => s.runtimeEnvironments.find((environment) => environment.id === ownerId)?.name ?? null - ) + const ownerName = useAppStore((s) => { + const environment = s.runtimeEnvironments.find((entry) => entry.id === ownerId) + return environment ? runtimeEnvironmentDisplayName(environment) : null + }) const [owned, setOwned] = useState(null) const ownedRef = useRef(null) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index 3225d55c0c0..ea889611cd4 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -3,6 +3,8 @@ import { Bot, ChevronDown, CreditCard, + FolderPlus, + Github, Loader2, LifeBuoy, LogIn, @@ -33,6 +35,9 @@ export type VmBuildFailureActions = { onSignIn: () => void onShowWorkspaces: () => void onContactSupport: () => void + onConnectGitHub: () => void + onStartEmpty: () => void + onPushToGitHub: () => void } type Action = { @@ -50,6 +55,7 @@ function failureActions( canFixWithAgent: boolean, canManageBilling: boolean, signingIn: boolean, + connectingGitHub: boolean, actions: VmBuildFailureActions, t: Translate ): { primary: Action[]; more: Action[] } { @@ -99,10 +105,15 @@ function failureActions( 'auto.components.worktree.creation.VmBuildFailureCard.updatePayment', 'Update payment method' ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.manageBilling', - 'Manage billing' - ), + : failure.kind === 'spendCap' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.raiseSpendCap', + 'Raise spend cap' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.turnOnOverage', + 'Turn on overage' + ), icon: , onClick: actions.onOpenBilling } @@ -192,6 +203,52 @@ function failureActions( ] } case 'githubNotConnected': + return { + primary: [ + { + key: 'connectGitHub', + label: connectingGitHub + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.openingGitHub', + 'Opening GitHub…' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.connectGitHub', + 'Connect GitHub' + ), + icon: connectingGitHub ? : , + onClick: actions.onConnectGitHub, + disabled: connectingGitHub + }, + tryAgain + ], + more: [] + } + case 'noGithubRemote': + return { + primary: [ + { + key: 'startEmpty', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.startEmpty', + 'Start empty' + ), + icon: , + onClick: actions.onStartEmpty + }, + { + key: 'pushToGitHub', + label: t( + 'auto.components.worktree.creation.VmBuildFailureCard.pushToGitHubFirst', + 'Push to GitHub first' + ), + icon: , + onClick: actions.onPushToGitHub + } + ], + // After pushing, the same create works without leaving the sheet. + more: [tryAgain] + } case 'unavailable': case 'network': case 'create': @@ -206,6 +263,7 @@ export function FailureActionRow({ canFixWithAgent, canManageBilling, signingIn, + connectingGitHub, actions, t }: { @@ -215,6 +273,7 @@ export function FailureActionRow({ canFixWithAgent: boolean canManageBilling: boolean signingIn: boolean + connectingGitHub: boolean actions: VmBuildFailureActions t: Translate }): React.JSX.Element { @@ -224,6 +283,7 @@ export function FailureActionRow({ canFixWithAgent, canManageBilling, signingIn, + connectingGitHub, actions, t ) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index b25324e8173..3b34cc9768a 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -18,6 +18,8 @@ export function VmBuildFailureCard({ canFixWithAgent, canManageBilling, signingIn, + connectingGitHub, + repoName, actions }: { failure: VmBuildFailure | null @@ -30,6 +32,9 @@ export function VmBuildFailureCard({ 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() @@ -48,7 +53,9 @@ export function VmBuildFailureCard({ setShown(failure) } const visible = failure ?? shown - const copy = visible ? vmBuildFailureCopy(visible, { cloud, canManageBilling }, t) : null + const copy = visible + ? vmBuildFailureCopy(visible, { cloud, canManageBilling, repoName }, t) + : null const headingRef = React.useRef(null) const cardRef = React.useRef(null) // Move focus to the card when it opens, so keyboard and screen-reader users land on the way forward. @@ -114,6 +121,7 @@ export function VmBuildFailureCard({ canFixWithAgent={canFixWithAgent} canManageBilling={canManageBilling} signingIn={signingIn} + connectingGitHub={connectingGitHub} actions={actions} t={t} /> diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 4a7742efea0..261968a21e3 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -27,6 +27,13 @@ import { } from './vm-build-failure' import { deriveVmBuildSteps, isOrcaCloudBuild, type VmBuildStep } from './vm-build-steps' import { useMinimumRunningSteps } from './use-minimum-running-steps' +import { + connectOrcaCloudGitHub, + orcaCloudRepoName, + PUSH_TO_GITHUB_URL, + startOrcaCloudCreateEmpty +} 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' @@ -79,7 +86,8 @@ export function VmBuildSheet({ onDismiss, onEditRecipe, agentSignInRow, - cloudAgentStep + cloudAgentStep, + stepTimings }: { creationId: string entry: PendingWorktreeCreation @@ -95,6 +103,8 @@ export function VmBuildSheet({ agentSignInRow?: React.ReactNode /** Fixtures only: a fixed "Add an agent" step 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() @@ -103,6 +113,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] @@ -131,6 +143,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() @@ -204,6 +226,7 @@ export function VmBuildSheet({ ? latestOrcaCloudPhaseLabel(entry.provisioningLog ?? '', t) : null } + timing={timings[step.id] ?? null} t={t} /> ))} @@ -226,6 +249,8 @@ export function VmBuildSheet({ canFixWithAgent={Boolean(recipe)} canManageBilling={canManageBilling} signingIn={signingIn} + connectingGitHub={connectingGitHub} + repoName={repoName} actions={{ onFixWithAgent: () => { if (recipe) { @@ -251,7 +276,10 @@ export function VmBuildSheet({ }, onSignIn: signIn, onShowWorkspaces: () => useAppStore.getState().setSidebarOpen(true), - onContactSupport: () => openAppHttpLink(SUPPORT_URL) + onContactSupport: () => openAppHttpLink(SUPPORT_URL), + onConnectGitHub: connectGitHub, + onStartEmpty: () => startOrcaCloudCreateEmpty(creationId, onRetry), + onPushToGitHub: () => openAppHttpLink(PUSH_TO_GITHUB_URL) }} /> diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx index 783470780a7..26de3d6115a 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx @@ -7,6 +7,7 @@ import { FAILED_LOG, LOG, frame, + seedFixtureRepo, T0 } from './vm-build-sheet-fixture-support' @@ -56,22 +57,53 @@ export const cloudSpendCap = cloudFailure( `${CLOUD_LOG}\nOrca Cloud: overage_cap_reached` ) -export const cloudHoursUsedMember = defineFixture({ - ...cloudFailure( +// A team member: billing is someone else's to change, so the card says who can. +function asMember(fixture: ReturnType) { + return defineFixture({ + ...fixture, + setup: () => { + seedFixtureRepo() + window.api.orcaProfiles.billingStatus = () => + Promise.resolve({ + status: 'ok', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the card reads only canManageBilling. + entitlement: { canManageBilling: false } as never + }) + } + }) +} + +export const cloudHoursUsedMember = asMember( + cloudFailure( 'cloudPlanRequired', 'Orca Cloud workspaces need a plan with cloud hours.', `${CLOUD_LOG}\nOrca Cloud: included_hours_exhausted` - ), - setup: () => { - // A team member: billing is someone else's to change. - 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 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', @@ -85,6 +117,30 @@ export const cloudGithubNotConnected = cloudFailure( `${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 cloudNoGithubRemoteMore = defineFixture({ + ...cloudNoGithubRemote, + interact: (frameElement) => { + Array.from(frameElement.querySelectorAll('button')) + .find((button) => button.textContent?.includes('More')) + ?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) + } +}) + export const cloudFailedLogsOpen = defineFixture({ ...cloudFailure('cloudUnavailable', 'Orca Cloud is unavailable right now.', CLOUD_FAILED_LOG), interact: (frameElement) => { diff --git a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx index 359d2042f61..d3ba56c50b0 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx @@ -5,7 +5,7 @@ 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 { vmBuildStepTiming } from './vm-build-timing' +import { typicalStepSeconds, type VmBuildStepTiming } from './vm-build-timing' import { formatElapsedTime } from './worktree-creation-clock' import { stepLabel, stepStateLabel } from './vm-build-sheet-copy' @@ -14,18 +14,20 @@ 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() - const timing = step.state === 'running' ? vmBuildStepTiming(step.id, cloud) : null // A live percent already says how far along the step is. - const hint = timing && step.percent === null ? timing : null + const hint = step.state === 'running' && step.percent === null ? timing : null const slow = hint !== null && step.elapsedMs !== null && step.elapsedMs > hint.p95Ms return ( @@ -65,7 +67,7 @@ export function VmBuildStepRow({ : t( 'auto.components.worktree.creation.VmBuildSheet.usually', 'usually ~{{seconds}}s', - { seconds: Math.max(1, Math.round(hint.p50Ms / 1000)) } + { seconds: typicalStepSeconds(hint) } )} ) : null} diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index 544cfe48521..c2fb198362e 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -3,6 +3,8 @@ import type { VmBuildFailure } from './vm-build-failure' 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 } @@ -10,7 +12,7 @@ export type VmBuildFailureCopyContext = { /** The card's cause-specific title and one plain-language sentence on what to do next. */ export function vmBuildFailureCopy( failure: VmBuildFailure, - { cloud, canManageBilling }: VmBuildFailureCopyContext, + { cloud, canManageBilling, repoName }: VmBuildFailureCopyContext, t: Translate ): { title: string; body: string | null } { switch (failure.kind) { @@ -40,93 +42,106 @@ export function vmBuildFailureCopy( ), body: canManageBilling ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.planBody', + '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.planBodyMember', + '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 month’s included sandbox hours' + 'auto.components.worktree.creation.VmBuildFailureCard.outOfHoursTitle', + 'Out of sandbox hours' ), body: canManageBilling ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.hoursUsedBody', - 'Turn on overage in Plan & billing to keep starting sandboxes. Nothing was created.' + '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.hoursUsedBodyMember', - 'Ask an owner or admin to turn on overage. Nothing was created.' + '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.spendCapTitle', - 'You’ve reached this month’s spend cap' + 'auto.components.worktree.creation.VmBuildFailureCard.spendCapReachedTitle', + 'Spend cap reached' ), body: canManageBilling ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.spendCapBody', - 'Raise the monthly spend cap in Plan & billing to keep starting sandboxes. Nothing was created.' + '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.spendCapBodyMember', - 'Ask an owner or admin to raise the monthly spend cap. Nothing was created.' + '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: canManageBilling ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.paymentBody', - 'Update your payment method to start cloud workspaces again. Nothing was created.' + '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.paymentBodyMember', - 'Ask an owner or admin to update the payment method. Nothing was created.' + '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', - 'Your team is running as many cloud workspaces as its plan allows' + 'auto.components.worktree.creation.VmBuildFailureCard.teamLimitTitle', + 'You’re at your team’s limit of running sandboxes' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.concurrencyBody', - 'Put a running cloud workspace to sleep or delete it, then try again. Nothing was created.' + '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.memberConcurrencyTitle', - 'You’re running as many cloud workspaces as you can at once' + 'auto.components.worktree.creation.VmBuildFailureCard.memberLimitTitle', + 'You’re at your limit of running sandboxes' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.memberConcurrencyBody', - 'Put one of yours to sleep or delete it, then try again. Nothing was created.' + '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.githubTitle', - 'Connect GitHub to use this repository' + 'auto.components.worktree.creation.VmBuildFailureCard.githubNotConnectedTitle', + 'GitHub isn’t connected for {{repo}}', + { repo: repoName } ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.githubBody', - 'Orca Cloud needs access to GitHub to clone this private repository. Connect GitHub to your Orca account, then try again. Nothing was created.' + '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.noGithubRemoteBody', + 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, or start with an empty workspace. Nothing was created, and you weren’t charged.' ) } case 'signIn': @@ -136,8 +151,8 @@ export function vmBuildFailureCopy( 'Sign in to use Orca Cloud' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.signInBody2', - 'Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created.' + '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': @@ -147,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': @@ -158,8 +173,8 @@ export function vmBuildFailureCopy( 'Couldn’t reach Orca Cloud' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.networkBody2', - 'Check your internet connection, then try again. Nothing was created.' + 'auto.components.worktree.creation.VmBuildFailureCard.networkBody3', + 'Check your internet connection, then try again. Nothing was created, and you weren’t charged.' ) } case 'snapshotMissing': @@ -169,8 +184,8 @@ export function vmBuildFailureCopy( 'This project’s saved environment is missing' ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.snapshotBody2', - 'The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created. Try again, or contact support if it keeps happening.' + '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': diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts index e88d68b9764..3b84bdc93f0 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts @@ -5,6 +5,8 @@ import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-w import { classifyVmBuildFailure } 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 { useAppStore } from '@/store' /** 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): void { @@ -14,7 +16,17 @@ export function showVmBuildFailureToast(entry: PendingWorktreeCreation, error: s return } // Unknown here; the card itself refines the copy for members once billing status loads. - const { title, body } = vmBuildFailureCopy(failure, { cloud, canManageBilling: true }, translate) + const recipe = entry.request.ephemeralVmRecipe + const repoName = orcaCloudRepoName( + recipe + ? useAppStore.getState().repos.find((repo) => repo.id === recipe.sourceRepoId) + : undefined + ) + const { title, body } = vmBuildFailureCopy( + failure, + { cloud, canManageBilling: true, repoName }, + translate + ) toast.error(title, { ...(body ? { description: body } : {}), ...(failure.kind === 'plan' diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts new file mode 100644 index 00000000000..e7b7d9cdd03 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from 'vitest' +import { classifyVmBuildFailure, isAccountGate, type VmBuildFailure } from './vm-build-failure' +import { vmBuildFailureCopy } from './vm-build-failure-copy' +import { orcaCloudRepoName } from './vm-build-repo-actions' + +// English defaults with {{slots}} filled, like i18next with no catalog. +const t = ((_key: string, fallback: string, params?: Record) => + fallback.replace(/\{\{(\w+)\}\}/g, (_slot, name: string) => + String(params?.[name] ?? '') + )) as Parameters[2] + +function classify( + errorCode: string | undefined, + log = '', + error = 'failed' +): VmBuildFailure | null { + return classifyVmBuildFailure({ + entry: { + phase: 'provisioning-vm', + errorCode, + provisioningLog: log, + environmentCheck: undefined + }, + error, + cloud: true + }) +} + +describe('classifyVmBuildFailure', () => { + it('names each control-plane refusal from its streamed deny reason', () => { + const kinds = Object.fromEntries( + [ + ['cloudPlanRequired', 'included_hours_exhausted'], + ['cloudPlanRequired', 'overage_cap_reached'], + ['cloudPlanRequired', 'payment_grace_expired'], + ['cloudConcurrencyLimit', 'member_concurrency_limit'], + ['cloudConcurrencyLimit', 'concurrency_limit'] + ].map(([code, reason]) => [reason, classify(code, `Orca Cloud: ${reason}`)?.kind]) + ) + expect(kinds).toEqual({ + included_hours_exhausted: 'hoursUsed', + overage_cap_reached: 'spendCap', + payment_grace_expired: 'payment', + member_concurrency_limit: 'memberConcurrency', + concurrency_limit: 'concurrency' + }) + expect(classify('cloudPlanRequired')?.kind).toBe('plan') + }) + + it('treats GitHub refusals as gates that started nothing', () => { + for (const code of ['cloudGithubNotConnected', 'cloudNoGithubRemote']) { + expect(isAccountGate(classify(code))).toBe(true) + } + }) +}) + +describe('vmBuildFailureCopy', () => { + const kinds: VmBuildFailure[] = [ + { kind: 'plan' }, + { kind: 'hoursUsed' }, + { kind: 'spendCap' }, + { kind: 'payment' }, + { kind: 'concurrency' }, + { kind: 'memberConcurrency' }, + { kind: 'githubNotConnected' }, + { kind: 'noGithubRemote' }, + { kind: 'signIn' }, + { kind: 'unavailable' }, + { kind: 'network' }, + { kind: 'snapshotMissing' }, + { kind: 'provision', error: 'Recipe exited with code 1.' }, + { kind: 'create', error: 'checkout failed' } + ] + + it('never shows codes, ids or banned glossary terms on an Orca Cloud card', () => { + for (const canManageBilling of [true, false]) { + for (const failure of kinds) { + const { title, body } = vmBuildFailureCopy( + failure, + { cloud: true, canManageBilling, repoName: 'acme/web' }, + t + ) + const text = `${title} ${body ?? ''}` + expect(text).not.toMatch( + /[a-z]+_[a-z]+|\bVM\b|included hours|hours exhausted|overage limit/ + ) + // Nothing exists yet at create time, so there are no files to reassure about. + expect(text).not.toContain('Your files are safe') + } + } + }) + + it('uses the glossary titles and role-aware next steps for billing refusals', () => { + const copy = (kind: VmBuildFailure, canManageBilling: boolean) => + vmBuildFailureCopy(kind, { cloud: true, canManageBilling, repoName: 'acme/web' }, t) + expect(copy({ kind: 'hoursUsed' }, true).title).toBe('Out of sandbox hours') + expect(copy({ kind: 'spendCap' }, true).title).toBe('Spend cap reached') + expect(copy({ kind: 'payment' }, true).title).toBe('Payment failed') + expect(copy({ kind: 'hoursUsed' }, false).body).toContain('Ask an owner or admin to add hours.') + expect(copy({ kind: 'payment' }, false).body).toContain( + 'Ask an owner or admin to update the payment method.' + ) + }) + + it('names the repository GitHub needs to reach', () => { + const { title } = vmBuildFailureCopy( + { kind: 'githubNotConnected' }, + { cloud: true, canManageBilling: true, repoName: 'acme/web' }, + t + ) + expect(title).toBe('GitHub isn’t connected for acme/web') + }) +}) + +describe('orcaCloudRepoName', () => { + it('prefers the GitHub owner/name, falling back to the name in Orca', () => { + expect( + orcaCloudRepoName({ + displayName: 'web', + gitRemoteIdentity: { remoteUrl: 'git@github.com:acme/web.git' } + } as never) + ).toBe('acme/web') + expect(orcaCloudRepoName({ displayName: 'web', gitRemoteIdentity: null })).toBe('web') + }) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index 968f05b436d..9e9d28d59db 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -10,6 +10,8 @@ export type VmBuildAccountFailureKind = | 'concurrency' | 'memberConcurrency' | 'githubNotConnected' + /** Refused before the control plane was asked: the sandbox could not clone this repository. */ + | 'noGithubRemote' | 'signIn' | 'unavailable' | 'network' @@ -28,7 +30,8 @@ const ERROR_CODE_KINDS: Partial> = { cloudConcurrencyLimit: 'concurrency', cloudSignInRequired: 'signIn', cloudUnavailable: 'unavailable', - cloudGithubNotConnected: 'githubNotConnected' + cloudGithubNotConnected: 'githubNotConnected', + cloudNoGithubRemote: 'noGithubRemote' } // The hosted provider logs the control plane's deny reason as `Orca Cloud: `. @@ -94,7 +97,8 @@ const ACCOUNT_GATES: ReadonlySet = new Set([ 'signIn', 'concurrency', 'memberConcurrency', - 'githubNotConnected' + 'githubNotConnected', + 'noGithubRemote' ]) // Nothing started, so no step failed: steps stay pending instead of showing a red failure. diff --git a/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts new file mode 100644 index 00000000000..33d6282f136 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts @@ -0,0 +1,48 @@ +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import { normalizeGitRemoteUrl } from '../../../../shared/git/remotes/git-remote-identity' +import type { Repo } from '../../../../shared/repo-types' + +/** GitHub's guide to publishing a local repository: the fix for a repo Orca Cloud can't clone. */ +export const PUSH_TO_GITHUB_URL = + 'https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github' + +/** The repository as the user knows it: its GitHub owner/name, else its name in Orca. */ +export function orcaCloudRepoName( + repo: Pick | undefined +): string { + const remote = repo?.gitRemoteIdentity?.remoteUrl + const normalized = remote ? normalizeGitRemoteUrl(remote) : null + if (normalized?.startsWith('github.com/')) { + return normalized.slice('github.com/'.length) + } + return repo?.displayName ?? '' +} + +/** Retries the create without the repository: the user chose an empty cloud workspace. */ +export function startOrcaCloudCreateEmpty(creationId: string, retry: () => void): void { + const store = useAppStore.getState() + const entry = store.pendingWorktreeCreations[creationId] + const recipe = entry?.request.ephemeralVmRecipe + if (!entry || !recipe) { + return + } + store.updatePendingWorktreeCreation(creationId, { + request: { ...entry.request, ephemeralVmRecipe: { ...recipe, startEmpty: true } } + }) + retry() +} + +/** Opens GitHub so the account can give Orca Cloud access; the user comes back and tries again. */ +export async function connectOrcaCloudGitHub(): Promise { + const result = await window.api.orcaCloudWorkspace.connectGitHub().catch(() => null) + if (!result?.ok) { + toast.error( + translate( + 'auto.components.worktree.creation.VmBuildFailureCard.connectGitHubFailed', + 'Couldn’t open GitHub. Try again in a moment.' + ) + ) + } +} diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx index 0e406cd369d..31c43833920 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -4,6 +4,9 @@ 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…', @@ -63,18 +66,37 @@ export function sheet( onDismiss={() => {}} onEditRecipe={() => {}} agentSignInRow={agentSignInRow} + stepTimings={FIXTURE_STEP_TIMINGS} /> ) } +// 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, render: () => sheet(value, error, now, agentSignInRow) }) + return defineFixture({ + width: 760, + setup: () => seedFixtureRepo(), + render: () => sheet(value, error, now, agentSignInRow) + }) } export const CLOUD_LOG = '[orca-cloud] checking-entitlement\n[orca-cloud] provisioning' diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts index bdfa11da25a..6c96630350e 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -1,17 +1,56 @@ +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 = { p50Ms: number; p95Ms: number } +export type VmBuildStepTiming = Pick -/** - * Measured Orca Cloud timings (dev, warm pool on): create p50 2.9 s / p95 4.0 s, of which the VM is - * ~0.26 s and orcad 2.1 s / 3.4 s; wake p50 4.7 s / p95 7.3 s. Steps without a measurement show no - * hint rather than a guess. Tune here. - */ -export const ORCA_CLOUD_STEP_TIMING: Partial> = { - provision: { p50Ms: 2_900, p95Ms: 4_000 } +export type VmBuildStepTimings = Partial> + +const NONE: VmBuildStepTimings = {} + +// One read per window: the control plane measures recent sandbox starts (GET /v1/config) and +// main caches the answer, so every build sheet shows the same median. +let measured: VmBuildStepTimings | null = null +let pending: Promise | null = null + +function loadMeasuredTimings(): Promise { + pending ??= (window.api.orcaCloudWorkspace?.getConfig?.() ?? Promise.resolve(null)) + .then((config) => { + // 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 } -export function vmBuildStepTiming(stepId: VmBuildStepId, cloud: boolean): VmBuildStepTiming | null { - return cloud ? (ORCA_CLOUD_STEP_TIMING[stepId] ?? null) : null +/** Measured Orca Cloud step timings; empty for VM recipes and until the control plane answers. */ +export function useVmBuildStepTimings(cloud: boolean): VmBuildStepTimings { + const [timings, setTimings] = React.useState(() => + cloud ? (measured ?? NONE) : NONE + ) + React.useEffect(() => { + if (!cloud || measured) { + return + } + let live = true + void loadMeasuredTimings().then((next) => { + if (live) { + setTimings(next) + } + }) + return () => { + live = false + } + }, [cloud]) + return cloud ? (measured ?? timings) : NONE +} + +/** The hint in whole seconds, never "~0s". */ +export function typicalStepSeconds(timing: VmBuildStepTiming): number { + return Math.max(1, Math.round(timing.p50Ms / 1000)) } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 60a39dcf119..f13aa7c202f 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2122,6 +2122,7 @@ "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 first, or start with an empty workspace.", "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.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index e1bd92b56c8..38178fbb076 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4063,16 +4063,8 @@ "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 month’s included sandbox hours", - "hoursUsedBody": "Turn on overage in Plan & billing to keep starting sandboxes. Nothing was created.", - "paymentTitle": "Your Orca payment needs attention", - "paymentBody": "Update your payment method to start cloud workspaces again. Nothing was created.", - "concurrencyTitle": "Your team is running as many cloud workspaces as its plan allows", - "concurrencyBody": "Put a running cloud workspace to sleep or delete it, then try again. Nothing was created.", "signInTitle": "Sign in to use Orca Cloud", "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", "snapshotTitle": "This project’s saved environment is missing", "provisionBodyCloud": "Something went wrong while starting the sandbox. Try again, or open the logs for details.", @@ -4084,28 +4076,43 @@ "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.", "showWorkspaces": "Show cloud workspaces", "contactSupport": "Contact support", - "planBodyMember": "Ask an owner or admin to choose a Team plan. Nothing was created, and you weren’t charged.", - "hoursUsedBodyMember": "Ask an owner or admin to turn on overage. Nothing was created.", - "spendCapTitle": "You’ve reached this month’s spend cap", - "spendCapBody": "Raise the monthly spend cap in Plan & billing to keep starting sandboxes. Nothing was created.", - "spendCapBodyMember": "Ask an owner or admin to raise the monthly spend cap. Nothing was created.", - "paymentBodyMember": "Ask an owner or admin to update the payment method. Nothing was created.", - "memberConcurrencyTitle": "You’re running as many cloud workspaces as you can at once", - "memberConcurrencyBody": "Put one of yours to sleep or delete it, then try again. Nothing was created.", - "githubTitle": "Connect GitHub to use this repository", - "githubBody": "Orca Cloud needs access to GitHub to clone this private repository. Connect GitHub to your Orca account, then try again. Nothing was created.", - "signInBody2": "Cloud workspaces run on your Orca account. Sign in and Orca starts this one for you. Nothing was created.", - "networkBody2": "Check your internet connection, then try again. Nothing was created.", - "snapshotBody2": "The sandbox starts from a saved copy of your environment, and that copy couldn’t be found. Nothing was created. Try again, or contact support if it keeps happening.", "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" + "createTitleVm": "Couldn’t create the workspace on the VM", + "raiseSpendCap": "Raise spend cap", + "turnOnOverage": "Turn on overage", + "openingGitHub": "Opening GitHub…", + "connectGitHub": "Connect GitHub", + "startEmpty": "Start empty", + "pushToGitHubFirst": "Push to GitHub first", + "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", + "noGithubRemoteBody": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, or start with an empty workspace. Nothing was created, and you weren’t charged.", + "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." }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -25662,6 +25669,7 @@ "cloudSignInRequired": "Sign in to Orca to use Orca Cloud workspaces.", "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 first, or start with an empty workspace.", "recipeExitedWithoutCode": "Recipe exited without an exit code.", "destroyExitedWithoutCode": "Destroy exited without an exit code.", "suspendExited": "Suspend exited with code {{exitCode}}.", diff --git a/src/renderer/src/lib/ephemeral-vm-error-copy.ts b/src/renderer/src/lib/ephemeral-vm-error-copy.ts index 7c8fc0c118c..fd8feb8f1f7 100644 --- a/src/renderer/src/lib/ephemeral-vm-error-copy.ts +++ b/src/renderer/src/lib/ephemeral-vm-error-copy.ts @@ -129,7 +129,9 @@ const COPY: Record strin translate('ephemeralVm.errors.cloudSignInRequired', EN.cloudSignInRequired), cloudUnavailable: () => translate('ephemeralVm.errors.cloudUnavailable', EN.cloudUnavailable), cloudGithubNotConnected: () => - translate('ephemeralVm.errors.cloudGithubNotConnected', EN.cloudGithubNotConnected) + translate('ephemeralVm.errors.cloudGithubNotConnected', EN.cloudGithubNotConnected), + cloudNoGithubRemote: () => + translate('ephemeralVm.errors.cloudNoGithubRemote', EN.cloudNoGithubRemote) } function isEphemeralVmFailureCode(code: string): code is EphemeralVmFailureCode { diff --git a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts index ad0f768f2a1..0af833e0ee4 100644 --- a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts +++ b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts @@ -28,6 +28,7 @@ export type PrepareEphemeralVmWorkspaceTargetArgs = { branch?: string ref?: string provisionId?: string + startEmpty?: boolean setupExistingFolder: ( args: ProjectHostSetupExistingFolderArgs ) => Promise @@ -62,7 +63,8 @@ export async function prepareEphemeralVmWorkspaceTarget( workspaceName: args.workspaceName, ...(args.branch ? { branch: args.branch } : {}), ...(args.ref ? { ref: args.ref } : {}), - ...(args.provisionId ? { provisionId: args.provisionId } : {}) + ...(args.provisionId ? { provisionId: args.provisionId } : {}), + ...(args.startEmpty ? { startEmpty: true } : {}) }) if (!provisioned.ok) { return { diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 884b80fc3f1..dd53897d0d2 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -70,6 +70,7 @@ async function prepareEphemeralVmRecipeRequest( } : {}), provisionId: creationId, + ...(recipe.startEmpty ? { startEmpty: true } : {}), setupExistingFolder: async (args) => { const setup = await store.setupProjectExistingFolder(args) if (setup) { diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts index 7ac2b331c29..6c5c05fd076 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts @@ -38,6 +38,8 @@ function stubApi(overrides: Partial = {}): OrcaCloudWorks unarchive: vi.fn(async () => ok(null)), getArchive: vi.fn(async () => ok(null)), listCloudWorkspaceIds: vi.fn(async () => ['a', 'b']), + getConfig: vi.fn(async () => null), + connectGitHub: vi.fn(async () => ok(null)), onWakeProgress: vi.fn(() => () => {}), onOom: vi.fn(() => () => {}), ...overrides diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index bc4baedd76a..94cef24ba12 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -64,6 +64,8 @@ export type WorktreeCreationRequest = { checkoutMode?: 'orca-worktree' | 'provisioned-root' /** Set for the built-in hosted provider, whose build sheet speaks in plain language. */ provider?: 'orca-cloud' + /** Orca Cloud: the user chose to start without the repository (it has no GitHub remote). */ + startEmpty?: boolean } // Capture local/runtime progress routing at submit so focus changes cannot alter Retry behavior. worktreeCreateProgressMode?: WorktreeCreationProgressMode diff --git a/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts b/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts index 60a8dceba72..1d026692ac2 100644 --- a/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts +++ b/src/renderer/src/store/slices/runtime-status/runtime-environment-disconnect-toast.ts @@ -1,6 +1,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { RuntimeStatusSlice } from './runtime-status-types' +import { runtimeEnvironmentDisplayName } from '../../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' const activeRuntimeDisconnectedToasts = new Map() const RUNTIME_DISCONNECTED_TOAST_DURATION_MS = 4_000 @@ -23,7 +24,7 @@ export function showRuntimeDisconnectedToast( ? translate( 'auto.store.slices.runtime.status.runtimeHostUnreachableNamed', "Can't reach {{hostName}}", - { hostName: environment.name } + { hostName: runtimeEnvironmentDisplayName(environment) } ) : translate( 'auto.store.slices.runtime.status.runtimeHostUnreachable', diff --git a/src/shared/ephemeral-vm-failure-copy.ts b/src/shared/ephemeral-vm-failure-copy.ts index 592cd732984..1fb003790f8 100644 --- a/src/shared/ephemeral-vm-failure-copy.ts +++ b/src/shared/ephemeral-vm-failure-copy.ts @@ -43,7 +43,9 @@ export const EPHEMERAL_VM_FAILURE_COPY = { cloudSignInRequired: 'Sign in to Orca to use Orca Cloud workspaces.', 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.' + '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 first, or start with an empty workspace.' } as const export type EphemeralVmFailureCode = keyof typeof EPHEMERAL_VM_FAILURE_COPY diff --git a/src/shared/execution-host/execution-host-registry.ts b/src/shared/execution-host/execution-host-registry.ts index deb8e4dacf9..59ed1c1c96b 100644 --- a/src/shared/execution-host/execution-host-registry.ts +++ b/src/shared/execution-host/execution-host-registry.ts @@ -13,6 +13,7 @@ import { import type { SshConnectionState } from '../ssh-types' import type { RuntimeEnvironmentSource } from '../remote-runtime/host-catalog/runtime-environments' import type { GlobalSettings } from '../global-settings-types' +import { runtimeEnvironmentDisplayName } from '../remote-runtime/host-catalog/orca-cloud-environment-name' import type { Repo } from '../repo-types' import { annotateManagedOrcadExecutionHosts } from './managed-orcad-execution-host' import { getSshConnectionHealth, type EphemeralVmHostLifecycle } from './execution-host-health' @@ -134,7 +135,11 @@ export function buildExecutionHostRegistry(args: { addRuntimeHost( hosts, environmentId, - normalizeHostPart(environment.name) ?? environmentId, + (environment.name + ? normalizeHostPart( + runtimeEnvironmentDisplayName({ name: environment.name, source: environment.source }) + ) + : null) ?? environmentId, environment.source, args.runtimeStatusByEnvironmentId ) diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index 87a1ade907a..b369e2dc025 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -4,6 +4,7 @@ import type { HostedArchivePullRequest, HostedArchiveResponse, + HostedSandboxConfigResponse, HostedWorkspaceStatus } from './hosted-sandbox-wire' @@ -59,6 +60,10 @@ export type OrcaCloudWorkspaceApi = { }) => Promise> /** Workspace ids of every Orca Cloud workspace this desktop knows (the sidebar dot / hover card). */ listCloudWorkspaceIds: () => Promise + /** Product constants and measured timings; null when the control plane can't be reached. */ + getConfig: () => Promise + /** Opens GitHub in the browser to give Orca Cloud access to the account's repositories. */ + connectGitHub: () => Promise> onWakeProgress: (callback: (event: CloudWakeProgressEvent) => void) => () => void onOom: (callback: (event: CloudOomEvent) => void) => () => void } @@ -70,6 +75,8 @@ export const ORCA_CLOUD_WORKSPACE_CHANNELS = { unarchive: 'orcaCloudWorkspace:unarchive', getArchive: 'orcaCloudWorkspace:getArchive', listCloudWorkspaceIds: 'orcaCloudWorkspace:listIds', + getConfig: 'orcaCloudWorkspace:getConfig', + connectGitHub: 'orcaCloudWorkspace:connectGitHub', wakeProgress: 'orcaCloudWorkspace:wakeProgress', oom: 'orcaCloudWorkspace:oom' } as const diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index 133f36be511..587871a76de 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -9,9 +9,26 @@ import { z } from 'zod' */ export const ORCA_CLOUD_IDLE_SLEEP_MINUTES = 15 +/** Median and slow-tail durations of a recent operation, as the control plane measured them. */ +export const HostedSandboxTimingSchema = z.object({ + p50Ms: z.number().nonnegative(), + p95Ms: z.number().nonnegative(), + samples: z.number().int().positive() +}) +export type HostedSandboxTiming = z.infer + /** GET /v1/config: product constants clients (desktop, mobile, CLI, marketing) must not hardcode. */ export const HostedSandboxConfigResponseSchema = z.object({ - idleSleepMinutes: z.number().int().positive() + idleSleepMinutes: z.number().int().positive(), + /** Recent sandbox starts (create until orcad is ready); absent until enough were measured. */ + createTiming: HostedSandboxTimingSchema.optional() +}) +export type HostedSandboxConfigResponse = z.infer + +/** POST /v1/github/connect: where the browser binds a GitHub App installation to the account. */ +export const HostedGithubConnectResponseSchema = z.object({ + installUrl: z.string().url(), + authorizeUrl: z.string().url() }) // Billing sells exactly these; larger boxes need a Vercel Enterprise plan. diff --git a/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts new file mode 100644 index 00000000000..50c3c4e62fa --- /dev/null +++ b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { + legacyOrcaCloudEnvironmentName, + orcaCloudEnvironmentName, + runtimeEnvironmentDisplayName +} from './orca-cloud-environment-name' +import { buildExecutionHostRegistry } from '../../execution-host/execution-host-registry' + +const RUNTIME_ID = '6f1c2a9e-0b4d-4c11-9a3e-7d2f22b5b1e7' + +describe('Orca Cloud server names', () => { + it('shows a cloud sandbox as Orca Cloud, never its id tail', () => { + const name = orcaCloudEnvironmentName('repo', RUNTIME_ID) + expect(name).toBe('repo sandbox 22b5b1e7') + expect(runtimeEnvironmentDisplayName({ name, source: 'ephemeral-vm' })).toBe('Orca Cloud') + }) + + it('leaves custom recipe VMs and user-named servers alone', () => { + expect( + runtimeEnvironmentDisplayName({ name: 'repo VM 22b5b1e7', source: 'ephemeral-vm' }) + ).toBe('repo VM 22b5b1e7') + expect(runtimeEnvironmentDisplayName({ name: 'repo sandbox 22b5b1e7', source: 'manual' })).toBe( + 'repo sandbox 22b5b1e7' + ) + }) + + it('renames only the legacy name built from this runtime', () => { + expect(legacyOrcaCloudEnvironmentName('repo VM 22b5b1e7', RUNTIME_ID)).toBe( + 'repo sandbox 22b5b1e7' + ) + expect(legacyOrcaCloudEnvironmentName('repo VM 00000000', RUNTIME_ID)).toBeNull() + expect(legacyOrcaCloudEnvironmentName(' VM 22b5b1e7', RUNTIME_ID)).toBeNull() + }) + + it('labels the sidebar host Orca Cloud', () => { + const hosts = buildExecutionHostRegistry({ + repos: [], + settings: null, + runtimeEnvironments: [ + { id: 'env-1', name: 'repo sandbox 22b5b1e7', source: 'ephemeral-vm' }, + { id: 'env-2', name: 'build box', source: 'manual' } + ] + }) + const labels = Object.fromEntries(hosts.map((host) => [host.id, host.label])) + expect(labels['runtime:env-1']).toBe('Orca Cloud') + expect(labels['runtime:env-2']).toBe('build box') + }) +}) diff --git a/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts new file mode 100644 index 00000000000..eec877ba10b --- /dev/null +++ b/src/shared/remote-runtime/host-catalog/orca-cloud-environment-name.ts @@ -0,0 +1,40 @@ +import type { RuntimeEnvironmentSource } from './runtime-environments' + +// Saved server names must be unique, so an Orca Cloud server is stored as +// " sandbox ". People see "Orca Cloud": the workspace row already names +// the workspace, and the id tail means nothing to them. +const ORCA_CLOUD_ENVIRONMENT_NAME = /^.+ sandbox [0-9A-Za-z]{8}$/ + +/** The host label for every Orca Cloud server, like "Local Mac" for this computer. */ +export const ORCA_CLOUD_HOST_LABEL = 'Orca Cloud' + +/** The saved (unique) name of the server behind one Orca Cloud workspace. */ +export function orcaCloudEnvironmentName(repoName: string, runtimeId: string): string { + return `${repoName} sandbox ${runtimeId.slice(-8)}` +} + +/** Builds before the glossary named the server " VM "; the runtime record proves it was Orca Cloud. */ +export function legacyOrcaCloudEnvironmentName(name: string, runtimeId: string): string | null { + const suffix = ` VM ${runtimeId.slice(-8)}` + return name.endsWith(suffix) && name.length > suffix.length + ? orcaCloudEnvironmentName(name.slice(0, -suffix.length), runtimeId) + : null +} + +export function isOrcaCloudRuntimeEnvironment(environment: { + name?: string | null + source?: RuntimeEnvironmentSource +}): boolean { + return ( + environment.source === 'ephemeral-vm' && + ORCA_CLOUD_ENVIRONMENT_NAME.test(environment.name?.trim() ?? '') + ) +} + +/** The name to show for a saved server: "Orca Cloud" for a cloud sandbox, otherwise its saved name. */ +export function runtimeEnvironmentDisplayName(environment: { + name: string + source?: RuntimeEnvironmentSource +}): string { + return isOrcaCloudRuntimeEnvironment(environment) ? ORCA_CLOUD_HOST_LABEL : environment.name +} From 7dab1aa21537e38c83ab5ed9f6a0bdff728f98a5 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:07:48 -0800 Subject: [PATCH 03/11] fix(build-sheet): fixtures render without the live Add an agent step --- .../src/components/worktree-creation/VmBuildSheet.tsx | 8 ++++++-- .../worktree-creation/vm-build-sheet-fixture-support.tsx | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 261968a21e3..6f953fa8806 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -101,7 +101,7 @@ export function VmBuildSheet({ 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 @@ -230,7 +230,11 @@ export function VmBuildSheet({ t={t} /> ))} - {cloudAgentStep ?? } + {cloudAgentStep !== undefined ? ( + cloudAgentStep + ) : ( + + )} {agentSignInRow ?? (entry.vmEnvironmentId ? ( {}} agentSignInRow={agentSignInRow} stepTimings={FIXTURE_STEP_TIMINGS} + cloudAgentStep={null} /> ) From 991d8ad665389786be1bcad746e79d99a9dda65a Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:19:14 -0800 Subject: [PATCH 04/11] fix(sandbox-control): a workspace started without a repo gets an empty repository Orca can open --- .../image/env/workspace-prelude.sh | 4 ++++ .../sandbox-control/image/vm-scripts.generated.ts | 2 +- cloud/apps/sandbox-control/src/lifecycle.ts | 9 ++++++--- .../sandbox-control/test/empty-workspace.test.ts | 15 +++++++++++++++ 4 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 cloud/apps/sandbox-control/test/empty-workspace.test.ts diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index 694ee3e485d..ce68822cc30 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -10,6 +10,7 @@ # and checked out; if that fails the workspace still opens at the build's commit. # - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty # first commit on the requested branch, which Orca needs to create the workspace's worktree. +# - No repo at all (the user chose "Start empty"): a fresh repository with that same first commit. set -uo pipefail P=/vercel/sandbox/project ROOT=/vercel/sandbox/repos @@ -50,5 +51,8 @@ elif [ ! -e "$P" ] && [ -n "${ORCA_REPO_URL:-}" ]; then fi fi first_commit +elif [ ! -e "$P" ]; then + git init --quiet "$P" || exit 1 + first_commit fi exit 0 diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 6039c2a10c9..e5d4dc97373 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -7,4 +7,4 @@ export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start" export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_REPO (https://github.com//), ORCA_SRC_SHA (40-hex), ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nlog \"fetch $ORCA_SRC_SHA\"\nsrc=\"$HOME/orca-src\"\nrm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\ngit init -q\n# The header lives only in this one command's config, not in .git/config.\ngit -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\nunset ORCA_SRC_AUTH\ngit -c advice.detachedHead=false checkout -q FETCH_HEAD\ntest \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# - No repo at all (the user chose \"Start empty\"): a fresh repository with that same first commit.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ]; then\n git init --quiet \"$P\" || exit 1\n first_commit\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index bdcb5ac41cc..4f34c741391 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -457,9 +457,12 @@ export async function createSandbox( deps.background?.(refill) } const claimedAt = deps.now() - const prelude: StartInputs['prelude'] = request.repo - ? { script: WORKSPACE_PRELUDE_SCRIPT, env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {} } - : undefined + // Every first boot gets the prelude: with no repo it makes an empty repository, so Orca can still + // create the workspace's worktree in it. + const prelude: StartInputs['prelude'] = { + script: WORKSPACE_PRELUDE_SCRIPT, + env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {} + } const id = pooled?.id ?? randomId() // Write-ahead row and the VM-independent prep (secrets, repo token) run together. const [row, prep] = await timer.time('prepare', async () => { diff --git a/cloud/apps/sandbox-control/test/empty-workspace.test.ts b/cloud/apps/sandbox-control/test/empty-workspace.test.ts new file mode 100644 index 00000000000..519c29f109d --- /dev/null +++ b/cloud/apps/sandbox-control/test/empty-workspace.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest' +import { createHarness } from './harness' + +describe('a workspace started without a repo ("Start empty")', () => { + it('still runs the prelude, which makes an empty repository Orca can open', async () => { + const h = await createHarness() + const created = await h.call('POST', '/v1/sandboxes', { + body: { workspaceId: 'empty', machineSize: 'standard' } + }) + expect(created.status).toBe(200) + const start = h.vercel.commands.filter((c) => c.command === '/opt/orca/bin/orca-sandbox-start').at(-1)! + expect(start.env.ORCA_REPO_URL).toBeUndefined() + expect(start.env.ORCA_PRELUDE).toContain('git init --quiet "$P"') + }) +}) From f4032bf36fd4ce6aaf00ecab46da6aae0e72111a Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:28:46 -0800 Subject: [PATCH 05/11] fix(cloud): drop Start empty (a host-local project can't open on a sandbox), Try again after pushing; sidebar pending row uses sandbox wording and the card's title --- .../hosted-sandbox/hosted-sandbox-recipe.ts | 9 ++-- .../ephemeral-vm-orca-cloud-remote.test.ts | 6 +-- src/main/ipc/ephemeral-vm-recipe-context.ts | 2 - src/main/ipc/ephemeral-vm.ts | 2 +- src/preload/api/ephemeral-vm-api.ts | 2 - .../worktree-list/rows/PendingWorktreeRow.tsx | 7 ++++ .../VmBuildFailureActions.tsx | 18 ++------ .../worktree-creation/VmBuildSheet.tsx | 4 +- .../VmBuildSheetCloudFailures.fixture.tsx | 9 ---- .../vm-build-failure-copy.ts | 4 +- .../vm-build-failure-toast.ts | 41 ++++++++++++------- .../vm-build-repo-actions.ts | 15 ------- .../src/i18n/en-runtime-required.json | 2 +- src/renderer/src/i18n/locales/en.json | 11 ++--- .../src/lib/ephemeral-vm-workspace-target.ts | 4 +- .../src/lib/ephemeral-vm-worktree-creation.ts | 3 +- .../creation/pending-worktree-creation.ts | 8 +++- src/shared/ephemeral-vm-failure-copy.ts | 2 +- 18 files changed, 63 insertions(+), 86 deletions(-) diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index 0d3cefe73e5..2885d735584 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -63,15 +63,14 @@ export async function hostedSandboxRepoUrl(repoPath: string): Promise, - repoPath: string, - startEmpty: boolean | undefined + repoPath: string ): Promise { - if (recipe.provider !== 'orca-cloud' || startEmpty || (await hostedSandboxRepoUrl(repoPath))) { + if (recipe.provider !== 'orca-cloud' || (await hostedSandboxRepoUrl(repoPath))) { return null } return ephemeralVmFailure('cloudNoGithubRemote') diff --git a/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts index 2bc554abb84..c8bc0727955 100644 --- a/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts +++ b/src/main/ipc/ephemeral-vm-orca-cloud-remote.test.ts @@ -82,11 +82,7 @@ it('refuses a remote GitHub does not host, too', async () => { expect(step).not.toHaveBeenCalled() }) -it('starts the sandbox when the user chose to start empty, or the repo is on GitHub', async () => { - const empty = setup(null) - await empty.provision({ startEmpty: true }) - expect(empty.step).toHaveBeenCalledOnce() - +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() diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index 1539c7e534d..a1b8be2e052 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -36,8 +36,6 @@ export type EphemeralVmProvisionArgs = { branch?: string ref?: string provisionId?: string - /** Orca Cloud only: the user chose a workspace without their code (no GitHub remote). */ - startEmpty?: boolean } export type EphemeralVmRecipeCatalogEntry = { diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index befd0bdb363..91942f62517 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -134,7 +134,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin if (!recipe) { return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) } - const refused = await refuseOrcaCloudWithoutGithub(recipe, repo.repo.path, args.startEmpty) + const refused = await refuseOrcaCloudWithoutGithub(recipe, repo.repo.path) if (refused) { return provisionFailure(refused) } diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 1518c91e691..2c32e253eb4 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -54,8 +54,6 @@ export type EphemeralVmApi = { branch?: string ref?: string provisionId?: string - /** Orca Cloud only: start without the repository when it has no GitHub remote. */ - startEmpty?: boolean }) => Promise< | { ok: true diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx index 4600efedba4..effd434e661 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx @@ -8,10 +8,17 @@ 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' function statusLabel(entry: PendingWorktreeCreation, 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, useAppStore.getState().repos, t) + : null return ( + cloud?.title ?? entry.error ?? t('auto.components.sidebar.PendingWorktreeRow.creationFailed', 'Creation failed') ) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index ea889611cd4..cae01ecc7c5 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -3,7 +3,6 @@ import { Bot, ChevronDown, CreditCard, - FolderPlus, Github, Loader2, LifeBuoy, @@ -36,7 +35,6 @@ export type VmBuildFailureActions = { onShowWorkspaces: () => void onContactSupport: () => void onConnectGitHub: () => void - onStartEmpty: () => void onPushToGitHub: () => void } @@ -227,15 +225,6 @@ function failureActions( case 'noGithubRemote': return { primary: [ - { - key: 'startEmpty', - label: t( - 'auto.components.worktree.creation.VmBuildFailureCard.startEmpty', - 'Start empty' - ), - icon: , - onClick: actions.onStartEmpty - }, { key: 'pushToGitHub', label: t( @@ -244,10 +233,11 @@ function failureActions( ), icon: , onClick: actions.onPushToGitHub - } + }, + // After pushing, the same create works without leaving the sheet. + tryAgain ], - // After pushing, the same create works without leaving the sheet. - more: [tryAgain] + more: [] } case 'unavailable': case 'network': diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 6f953fa8806..a16219c229a 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -30,8 +30,7 @@ import { useMinimumRunningSteps } from './use-minimum-running-steps' import { connectOrcaCloudGitHub, orcaCloudRepoName, - PUSH_TO_GITHUB_URL, - startOrcaCloudCreateEmpty + 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' @@ -282,7 +281,6 @@ export function VmBuildSheet({ onShowWorkspaces: () => useAppStore.getState().setSidebarOpen(true), onContactSupport: () => openAppHttpLink(SUPPORT_URL), onConnectGitHub: connectGitHub, - onStartEmpty: () => startOrcaCloudCreateEmpty(creationId, onRetry), onPushToGitHub: () => openAppHttpLink(PUSH_TO_GITHUB_URL) }} /> diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx index 26de3d6115a..fec59dc74aa 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheetCloudFailures.fixture.tsx @@ -132,15 +132,6 @@ export const cloudNoGithubRemote = defineFixture({ setup: () => seedFixtureRepo(null) }) -export const cloudNoGithubRemoteMore = defineFixture({ - ...cloudNoGithubRemote, - interact: (frameElement) => { - Array.from(frameElement.querySelectorAll('button')) - .find((button) => button.textContent?.includes('More')) - ?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) - } -}) - export const cloudFailedLogsOpen = defineFixture({ ...cloudFailure('cloudUnavailable', 'Orca Cloud is unavailable right now.', CLOUD_FAILED_LOG), interact: (frameElement) => { diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index c2fb198362e..35f65e34928 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -140,8 +140,8 @@ export function vmBuildFailureCopy( { repo: repoName } ), body: t( - 'auto.components.worktree.creation.VmBuildFailureCard.noGithubRemoteBody', - 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, or start with an empty workspace. Nothing was created, and you weren’t charged.' + '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': diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts index 3b84bdc93f0..2651fff4057 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-toast.ts @@ -1,32 +1,45 @@ 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 } from './vm-build-failure' +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 { useAppStore } from '@/store' +import type { Repo } from '../../../../shared/repo-types' -/** 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): void { +/** 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 + return null } - // Unknown here; the card itself refines the copy for members once billing status loads. const recipe = entry.request.ephemeralVmRecipe const repoName = orcaCloudRepoName( - recipe - ? useAppStore.getState().repos.find((repo) => repo.id === recipe.sourceRepoId) - : undefined - ) - const { title, body } = vmBuildFailureCopy( - failure, - { cloud, canManageBilling: true, repoName }, - translate + 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' diff --git a/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts index 33d6282f136..3de7a828003 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-repo-actions.ts @@ -1,5 +1,4 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' import { translate } from '@/i18n/i18n' import { normalizeGitRemoteUrl } from '../../../../shared/git/remotes/git-remote-identity' import type { Repo } from '../../../../shared/repo-types' @@ -20,20 +19,6 @@ export function orcaCloudRepoName( return repo?.displayName ?? '' } -/** Retries the create without the repository: the user chose an empty cloud workspace. */ -export function startOrcaCloudCreateEmpty(creationId: string, retry: () => void): void { - const store = useAppStore.getState() - const entry = store.pendingWorktreeCreations[creationId] - const recipe = entry?.request.ephemeralVmRecipe - if (!entry || !recipe) { - return - } - store.updatePendingWorktreeCreation(creationId, { - request: { ...entry.request, ephemeralVmRecipe: { ...recipe, startEmpty: true } } - }) - retry() -} - /** Opens GitHub so the account can give Orca Cloud access; the user comes back and tries again. */ export async function connectOrcaCloudGitHub(): Promise { const result = await window.api.orcaCloudWorkspace.connectGitHub().catch(() => null) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index f13aa7c202f..55ff60c3f2d 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2122,7 +2122,7 @@ "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 first, or start with an empty workspace.", + "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.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 38178fbb076..dd633150736 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2107,7 +2107,9 @@ "creatingWorktree": "Creating worktree…", "fetchingBaseBranch": "Fetching base branch…", "checkingVmEnvironment": "Checking VM environment…", - "vmChecksFailed": "Environment checks failed" + "vmChecksFailed": "Environment checks failed", + "preparingCloudEnvironment": "Preparing environment…", + "startingSandbox": "Starting sandbox…" }, "duplicatePairedServers": { "ambiguousSameServer": "{{value0}} and {{value1}} are the same server paired twice. Remove one in Settings > Remote Orca Servers." @@ -4088,7 +4090,6 @@ "turnOnOverage": "Turn on overage", "openingGitHub": "Opening GitHub…", "connectGitHub": "Connect GitHub", - "startEmpty": "Start empty", "pushToGitHubFirst": "Push to GitHub first", "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.", @@ -4107,12 +4108,12 @@ "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", - "noGithubRemoteBody": "Orca Cloud clones your code from GitHub, and this repository has no GitHub remote. Push it to GitHub, or start with an empty workspace. Nothing was created, and you weren’t charged.", "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." + "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." }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -25669,7 +25670,7 @@ "cloudSignInRequired": "Sign in to Orca to use Orca Cloud workspaces.", "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 first, or start with an empty workspace.", + "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}}.", diff --git a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts index 0af833e0ee4..ad0f768f2a1 100644 --- a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts +++ b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts @@ -28,7 +28,6 @@ export type PrepareEphemeralVmWorkspaceTargetArgs = { branch?: string ref?: string provisionId?: string - startEmpty?: boolean setupExistingFolder: ( args: ProjectHostSetupExistingFolderArgs ) => Promise @@ -63,8 +62,7 @@ export async function prepareEphemeralVmWorkspaceTarget( workspaceName: args.workspaceName, ...(args.branch ? { branch: args.branch } : {}), ...(args.ref ? { ref: args.ref } : {}), - ...(args.provisionId ? { provisionId: args.provisionId } : {}), - ...(args.startEmpty ? { startEmpty: true } : {}) + ...(args.provisionId ? { provisionId: args.provisionId } : {}) }) if (!provisioned.ok) { return { diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index dd53897d0d2..abd67922fe2 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -70,7 +70,6 @@ async function prepareEphemeralVmRecipeRequest( } : {}), provisionId: creationId, - ...(recipe.startEmpty ? { startEmpty: true } : {}), setupExistingFolder: async (args) => { const setup = await store.setupProjectExistingFolder(args) if (setup) { @@ -100,7 +99,7 @@ async function prepareEphemeralVmRecipeRequest( ) { const failed = state.pendingWorktreeCreations[creationId] if (failed) { - showVmBuildFailureToast(failed, preparedTarget.error) + showVmBuildFailureToast(failed, preparedTarget.error, state.repos) } else { toast.error(ephemeralVmErrorText(preparedTarget)) } diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 94cef24ba12..4cd3a920c64 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -64,8 +64,6 @@ export type WorktreeCreationRequest = { checkoutMode?: 'orca-worktree' | 'provisioned-root' /** Set for the built-in hosted provider, whose build sheet speaks in plain language. */ provider?: 'orca-cloud' - /** Orca Cloud: the user chose to start without the repository (it has no GitHub remote). */ - startEmpty?: boolean } // Capture local/runtime progress routing at submit so focus changes cannot alter Retry behavior. worktreeCreateProgressMode?: WorktreeCreationProgressMode @@ -310,6 +308,12 @@ export function getCreationProgressLabel( if (entry.environmentCheck?.status === 'failed') { return t('auto.lib.pendingWorktreeCreation.vmChecksFailed', 'Environment checks failed') } + // Glossary: an Orca Cloud machine is a sandbox; "VM" stays only for bring-your-own recipes. + if (entry.request.ephemeralVmRecipe?.provider === 'orca-cloud') { + return entry.environmentCheck + ? t('auto.lib.pendingWorktreeCreation.preparingCloudEnvironment', 'Preparing environment…') + : t('auto.lib.pendingWorktreeCreation.startingSandbox', 'Starting sandbox…') + } return entry.environmentCheck ? t('auto.lib.pendingWorktreeCreation.checkingVmEnvironment', 'Checking VM environment…') : t('auto.lib.pendingWorktreeCreation.provisioningVm', 'Provisioning VM…') diff --git a/src/shared/ephemeral-vm-failure-copy.ts b/src/shared/ephemeral-vm-failure-copy.ts index 1fb003790f8..eabacaf6558 100644 --- a/src/shared/ephemeral-vm-failure-copy.ts +++ b/src/shared/ephemeral-vm-failure-copy.ts @@ -45,7 +45,7 @@ export const EPHEMERAL_VM_FAILURE_COPY = { 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 first, or start with an empty workspace.' + '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 From ee1f14b8711cec10207fd77c2f5ea99050e79dfd Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:29:45 -0800 Subject: [PATCH 06/11] Revert "fix(sandbox-control): a workspace started without a repo gets an empty repository Orca can open" This reverts commit 0c4ec3ac451e173fe0b0c5840a139b08728fc9fb. --- .../image/env/workspace-prelude.sh | 4 ---- .../sandbox-control/image/vm-scripts.generated.ts | 2 +- cloud/apps/sandbox-control/src/lifecycle.ts | 9 +++------ .../sandbox-control/test/empty-workspace.test.ts | 15 --------------- 4 files changed, 4 insertions(+), 26 deletions(-) delete mode 100644 cloud/apps/sandbox-control/test/empty-workspace.test.ts diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index ce68822cc30..694ee3e485d 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -10,7 +10,6 @@ # and checked out; if that fails the workspace still opens at the build's commit. # - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty # first commit on the requested branch, which Orca needs to create the workspace's worktree. -# - No repo at all (the user chose "Start empty"): a fresh repository with that same first commit. set -uo pipefail P=/vercel/sandbox/project ROOT=/vercel/sandbox/repos @@ -51,8 +50,5 @@ elif [ ! -e "$P" ] && [ -n "${ORCA_REPO_URL:-}" ]; then fi fi first_commit -elif [ ! -e "$P" ]; then - git init --quiet "$P" || exit 1 - first_commit fi exit 0 diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index e5d4dc97373..6039c2a10c9 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -7,4 +7,4 @@ export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start" export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_REPO (https://github.com//), ORCA_SRC_SHA (40-hex), ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nlog \"fetch $ORCA_SRC_SHA\"\nsrc=\"$HOME/orca-src\"\nrm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\ngit init -q\n# The header lives only in this one command's config, not in .git/config.\ngit -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\nunset ORCA_SRC_AUTH\ngit -c advice.detachedHead=false checkout -q FETCH_HEAD\ntest \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# - No repo at all (the user chose \"Start empty\"): a fresh repository with that same first commit.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ]; then\n git init --quiet \"$P\" || exit 1\n first_commit\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n if ! git \"${auth[@]}\" clone --quiet ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\" 2>/dev/null; then\n rm -rf -- \"$P\"\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n git \"${auth[@]}\" clone --quiet -- \"$ORCA_REPO_URL\" \"$P\" || exit 1\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 4f34c741391..bdcb5ac41cc 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -457,12 +457,9 @@ export async function createSandbox( deps.background?.(refill) } const claimedAt = deps.now() - // Every first boot gets the prelude: with no repo it makes an empty repository, so Orca can still - // create the workspace's worktree in it. - const prelude: StartInputs['prelude'] = { - script: WORKSPACE_PRELUDE_SCRIPT, - env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {} - } + const prelude: StartInputs['prelude'] = request.repo + ? { script: WORKSPACE_PRELUDE_SCRIPT, env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {} } + : undefined const id = pooled?.id ?? randomId() // Write-ahead row and the VM-independent prep (secrets, repo token) run together. const [row, prep] = await timer.time('prepare', async () => { diff --git a/cloud/apps/sandbox-control/test/empty-workspace.test.ts b/cloud/apps/sandbox-control/test/empty-workspace.test.ts deleted file mode 100644 index 519c29f109d..00000000000 --- a/cloud/apps/sandbox-control/test/empty-workspace.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createHarness } from './harness' - -describe('a workspace started without a repo ("Start empty")', () => { - it('still runs the prelude, which makes an empty repository Orca can open', async () => { - const h = await createHarness() - const created = await h.call('POST', '/v1/sandboxes', { - body: { workspaceId: 'empty', machineSize: 'standard' } - }) - expect(created.status).toBe(200) - const start = h.vercel.commands.filter((c) => c.command === '/opt/orca/bin/orca-sandbox-start').at(-1)! - expect(start.env.ORCA_REPO_URL).toBeUndefined() - expect(start.env.ORCA_PRELUDE).toContain('git init --quiet "$P"') - }) -}) From d3a9385ab812f22df94d28646fd01160c9b3f4c2 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 08:32:54 -0800 Subject: [PATCH 07/11] fix(cloud): review round 1: cache /v1/config timing per isolate, pending actions stay focusable, retry config after offline, reactive repos in the sidebar row, focus + URL tests --- .../apps/sandbox-control/src/create-timing.ts | 25 ++++++ cloud/apps/sandbox-control/src/index.ts | 5 +- .../apps/sandbox-control/test/config.test.ts | 29 ++++++- .../hosted-sandbox/hosted-account-ipc.test.ts | 52 ++++++++++++ .../worktree-list/rows/PendingWorktreeRow.tsx | 12 ++- .../VmBuildFailureActions.tsx | 10 ++- .../VmBuildFailureCard.test.tsx | 82 +++++++++++++++++++ .../worktree-creation/vm-build-timing.ts | 7 +- 8 files changed, 211 insertions(+), 11 deletions(-) create mode 100644 src/main/hosted-sandbox/hosted-account-ipc.test.ts create mode 100644 src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx diff --git a/cloud/apps/sandbox-control/src/create-timing.ts b/cloud/apps/sandbox-control/src/create-timing.ts index 69644e0be97..9ad5b27c052 100644 --- a/cloud/apps/sandbox-control/src/create-timing.ts +++ b/cloud/apps/sandbox-control/src/create-timing.ts @@ -36,3 +36,28 @@ export async function recentCreateTiming(db: D1Database): Promise() return summarizeStartTimes(results.map((row) => row.ms)) } + +const CACHE_MS = 5 * 60_000 +let cache: { db: D1Database; at: number; value: Promise } | null = null + +/** + * GET /v1/config is public, so the query runs at most once per isolate every 5 minutes; a failed + * read is retried on the next request instead of being cached. + */ +export function cachedCreateTiming(db: D1Database, now: number): Promise { + if (cache && cache.db === db && now - cache.at < CACHE_MS) { + return cache.value + } + const entry = { + db, + at: now, + value: recentCreateTiming(db).catch(() => { + if (cache === entry) { + cache = null + } + return undefined + }) + } + cache = entry + return entry.value +} diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 414e8bb55cf..61e8781ec53 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -33,7 +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 { recentCreateTiming } from './create-timing' +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' @@ -768,8 +768,7 @@ 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. - // A timing read failure must never take the constants down with it. - const createTiming = await recentCreateTiming(env.SANDBOX_DB).catch(() => undefined) + 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' } } diff --git a/cloud/apps/sandbox-control/test/config.test.ts b/cloud/apps/sandbox-control/test/config.test.ts index d58a40069b3..7ab866482ea 100644 --- a/cloud/apps/sandbox-control/test/config.test.ts +++ b/cloud/apps/sandbox-control/test/config.test.ts @@ -4,7 +4,7 @@ import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { DEFAULT_PLANS } from '../../billing/src/plans' -import { MIN_TIMING_SAMPLES, summarizeStartTimes } from '../src/create-timing' +import { cachedCreateTiming, MIN_TIMING_SAMPLES, summarizeStartTimes } from '../src/create-timing' import { createHarness } from './harness' describe('GET /v1/config', () => { @@ -46,3 +46,30 @@ describe('summarizeStartTimes', () => { expect(summarizeStartTimes([1000, 2000])).toBeUndefined() }) }) + +describe('cachedCreateTiming', () => { + it('reads D1 at most once per 5 minutes, and retries after a failed read', async () => { + let reads = 0 + let fail = true + const db = { + prepare: () => ({ + bind: () => ({ + all: async () => { + reads++ + if (fail) { + throw new Error('d1 down') + } + return { results: [] } + } + }) + }) + } as unknown as D1Database + expect(await cachedCreateTiming(db, 0)).toBeUndefined() + fail = false + await cachedCreateTiming(db, 1_000) + await cachedCreateTiming(db, 2_000) + expect(reads).toBe(2) + await cachedCreateTiming(db, 1_000 + 5 * 60_000) + expect(reads).toBe(3) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-account-ipc.test.ts b/src/main/hosted-sandbox/hosted-account-ipc.test.ts new file mode 100644 index 00000000000..c2258530261 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-account-ipc.test.ts @@ -0,0 +1,52 @@ +import { afterEach, expect, it, vi } from 'vitest' + +const handlers = new Map unknown>() +const { openExternal } = vi.hoisted(() => ({ openExternal: vi.fn(async () => {}) })) + +vi.mock('electron', () => ({ + ipcMain: { handle: (channel: string, handler: () => unknown) => handlers.set(channel, handler) }, + shell: { openExternal } +})) + +import { ORCA_CLOUD_WORKSPACE_CHANNELS as CH } from '../../shared/hosted-sandbox/cloud-workspace-api' +import { registerHostedAccountHandlers } from './hosted-account-ipc' + +afterEach(() => { + handlers.clear() + vi.clearAllMocks() +}) + +function register(installUrl: string, config = vi.fn(async () => ({ idleSleepMinutes: 15 }))) { + registerHostedAccountHandlers({ + config, + connectGitHub: async () => ({ installUrl, authorizeUrl: installUrl }) + }) + return config +} + +it('opens only a github.com page for Connect GitHub', async () => { + register('https://github.com/apps/orca-cloud-dev/installations/new?state=x') + expect(await handlers.get(CH.connectGitHub)?.()).toEqual({ ok: true, value: null }) + expect(openExternal).toHaveBeenCalledOnce() + + handlers.clear() + register('https://github.com.evil.example/install') + expect(await handlers.get(CH.connectGitHub)?.()).toMatchObject({ ok: false }) + expect(openExternal).toHaveBeenCalledOnce() +}) + +it('reads the config once, and again after a failed read', async () => { + let fail = true + const config = vi.fn(async () => { + if (fail) { + throw new Error('offline') + } + return { idleSleepMinutes: 15 } + }) + register('https://github.com/x', config) + expect(await handlers.get(CH.getConfig)?.()).toBeNull() + fail = false + await handlers.get(CH.getConfig)?.() + await handlers.get(CH.getConfig)?.() + expect(config).toHaveBeenCalledTimes(2) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx index effd434e661..cd22eb3311f 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx @@ -9,13 +9,18 @@ import { 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, useAppStore.getState().repos, t) + ? vmBuildFailureSummary(entry, entry.error, repos, t) : null return ( cloud?.title ?? @@ -54,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 } @@ -96,7 +102,7 @@ export function PendingWorktreeRow({ isError ? 'text-destructive/90' : 'text-muted-foreground' )} > - {statusLabel(entry, t)} + {statusLabel(entry, repos, t)} diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index cae01ecc7c5..f525300f1b1 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -44,6 +44,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. */ @@ -129,7 +131,7 @@ function failureActions( : t('auto.components.worktree.creation.VmBuildFailureCard.signIn', 'Sign in'), icon: signingIn ? : , onClick: actions.onSignIn, - disabled: signingIn + pending: signingIn } ], more: [] @@ -216,7 +218,7 @@ function failureActions( ), icon: connectingGitHub ? : , onClick: actions.onConnectGitHub, - disabled: connectingGitHub + pending: connectingGitHub }, tryAgain ], @@ -287,8 +289,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} diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx new file mode 100644 index 00000000000..80c51125f67 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment happy-dom + +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { VmBuildFailureCard, type VmBuildFailureActions } from './VmBuildFailureCard' +import type { VmBuildFailure } from './vm-build-failure' + +afterEach(cleanup) + +const actions = (): VmBuildFailureActions => ({ + onFixWithAgent: vi.fn(), + onRetry: vi.fn(), + onEditRecipe: vi.fn(), + onOpenAnyway: vi.fn(), + onDismiss: vi.fn(), + onSeePlans: vi.fn(), + onOpenBilling: vi.fn(), + onSignIn: vi.fn(), + onShowWorkspaces: vi.fn(), + onContactSupport: vi.fn(), + onConnectGitHub: vi.fn(), + onPushToGitHub: vi.fn() +}) + +function Sheet({ + failure, + connectingGitHub = false, + handlers +}: { + failure: VmBuildFailure | null + connectingGitHub?: boolean + handlers: VmBuildFailureActions +}) { + return ( +
    +

    + Starting your cloud workspace +

    + +
    + ) +} + +it('announces only the cause and lands focus on it, then on the sheet heading after Try again', () => { + const handlers = actions() + const { rerender } = render() + const alert = screen.getByRole('alert') + expect(alert.textContent).toContain('Orca Cloud is unavailable right now') + // The buttons are read on demand, not announced with the cause. + expect(alert.querySelector('button')).toBeNull() + expect(document.activeElement?.textContent).toBe('Orca Cloud is unavailable right now') + + const retry = screen.getByRole('button', { name: /Try again/ }) + retry.focus() + fireEvent.click(retry) + expect(handlers.onRetry).toHaveBeenCalledOnce() + act(() => rerender()) + expect(document.activeElement?.hasAttribute('data-vm-build-heading')).toBe(true) +}) + +it('keeps a pending Connect GitHub focusable and ignores repeat clicks', () => { + const handlers = actions() + render() + const button = screen.getByRole('button', { name: /Opening GitHub/ }) + expect(button.hasAttribute('disabled')).toBe(false) + expect(button.getAttribute('aria-busy')).toBe('true') + button.focus() + fireEvent.click(button) + expect(handlers.onConnectGitHub).not.toHaveBeenCalled() + expect(document.activeElement).toBe(button) +}) diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts index 6c96630350e..ae045586dc5 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -17,8 +17,13 @@ let pending: Promise | null = null function loadMeasuredTimings(): Promise { pending ??= (window.api.orcaCloudWorkspace?.getConfig?.() ?? Promise.resolve(null)) .then((config) => { + if (!config) { + // Unreachable now says nothing about later: the next sheet asks again. + pending = null + return NONE + } // Only "Start sandbox" is measured. Without a measurement there is no hint, never a guess. - measured = config?.createTiming ? { provision: config.createTiming } : NONE + measured = config.createTiming ? { provision: config.createTiming } : NONE return measured }) .catch(() => { From dcb7cffcb994e2749a96549c1bdb22163fd74f57 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 09:01:24 -0800 Subject: [PATCH 08/11] fix(build-sheet): W10 round 8: glossary log lines, snapshot-missing starts nothing, plural hidden-lines note, How to push to GitHub, muted Dismiss --- .../VmBuildFailureActions.tsx | 8 ++++-- .../worktree-creation/VmBuildLog.tsx | 9 ++++-- .../worktree-creation/orca-cloud-build-log.ts | 28 +++++++++---------- .../worktree-creation/vm-build-failure.ts | 4 ++- .../src/i18n/en-runtime-required.json | 8 ++++++ src/renderer/src/i18n/locales/en.json | 23 +++++++-------- 6 files changed, 48 insertions(+), 32 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index f525300f1b1..6411647f7ad 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -14,6 +14,7 @@ import { Trash2 } from 'lucide-react' import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' import { DropdownMenu, DropdownMenuContent, @@ -230,8 +231,8 @@ function failureActions( { key: 'pushToGitHub', label: t( - 'auto.components.worktree.creation.VmBuildFailureCard.pushToGitHubFirst', - 'Push to GitHub first' + 'auto.components.worktree.creation.VmBuildFailureCard.howToPushToGitHub', + 'How to push to GitHub' ), icon: , onClick: actions.onPushToGitHub @@ -325,7 +326,8 @@ export function FailureActionRow({ variant={destroys ? 'destructive-chip' : 'ghost'} size="xs" onClick={actions.onDismiss} - className="ml-auto" + // Leaving is the quiet way out; only deleting a running sandbox earns the destructive chip. + className={cn('ml-auto', !destroys && 'text-muted-foreground hover:text-foreground')} > {destroys ? : null} {destroys diff --git a/src/renderer/src/components/worktree-creation/VmBuildLog.tsx b/src/renderer/src/components/worktree-creation/VmBuildLog.tsx index ac059c3dd9b..beabea4878d 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildLog.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildLog.tsx @@ -118,9 +118,12 @@ export function VmBuildLog({ {hiddenCount > 0 ? ( {t( - 'auto.components.worktree.creation.VmBuildLog.hiddenLines', - 'Technical lines hidden: {{count}}. Copy log includes them.', - { count: hiddenCount } + 'auto.components.worktree.creation.VmBuildLog.hiddenTechnicalLines', + '{{count}} technical lines hidden. Copy log includes them.', + { + count: hiddenCount, + defaultValue_one: '{{count}} technical line hidden. Copy log includes it.' + } )} ) : null} diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 03b068dee8b..4082ee88ead 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -40,8 +40,8 @@ function phaseLabel(phase: string, t: Translate): string | null { ) case 'renewing': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.renewing', - 'Extending the session…' + 'auto.components.worktree.creation.orcaCloudBuildLog.renewing2', + 'Keeping the sandbox running…' ) case 'rolling-over': return t( @@ -69,8 +69,8 @@ function denyLabel(reason: string, t: Translate): string | null { ) case 'included_hours_exhausted': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.denyHours', - 'This month’s included sandbox hours are used up.' + 'auto.components.worktree.creation.orcaCloudBuildLog.denyHours2', + 'Your team is out of sandbox hours this month.' ) case 'overage_cap_reached': return t( @@ -80,18 +80,18 @@ function denyLabel(reason: string, t: Translate): string | null { case 'payment_past_due': case 'payment_grace_expired': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.denyPayment', - 'A payment is overdue.' + 'auto.components.worktree.creation.orcaCloudBuildLog.denyPayment2', + 'Payment failed.' ) case 'concurrency_limit': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.denyConcurrency', - 'Your team’s limit on running cloud workspaces is reached.' + '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.denyMemberConcurrency', - 'Your limit on running cloud workspaces is reached.' + 'auto.components.worktree.creation.orcaCloudBuildLog.denyMemberConcurrency2', + 'You’re at your limit of running sandboxes.' ) case 'github_not_connected': return t( @@ -100,8 +100,8 @@ function denyLabel(reason: string, t: Translate): string | null { ) case 'machine_size_not_in_plan': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.denyMachineSize', - 'This machine size isn’t part of your plan.' + 'auto.components.worktree.creation.orcaCloudBuildLog.denyMachineSize2', + 'This sandbox size isn’t part of your plan.' ) default: return null @@ -117,8 +117,8 @@ function refusedLabel(code: string, t: Translate): string { ) case 'provider_unavailable': return t( - 'auto.components.worktree.creation.orcaCloudBuildLog.refusedProvider', - 'The sandbox provider is unavailable.' + 'auto.components.worktree.creation.orcaCloudBuildLog.refusedProvider2', + 'Orca Cloud is unavailable right now.' ) case 'not_configured': return t( diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index 9e9d28d59db..db4a9bb6bef 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -105,7 +105,9 @@ const ACCOUNT_GATES: ReadonlySet = new Set([ const NOTHING_STARTED: ReadonlySet = new Set([ ...ACCOUNT_GATES, 'unavailable', - 'network' + 'network', + // Refused while picking the saved environment, before any sandbox existed. + 'snapshotMissing' ]) export function nothingStarted(failure: VmBuildFailure | null): boolean { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 55ff60c3f2d..bbcfd5d5afd 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1287,6 +1287,14 @@ } } } + }, + "worktree": { + "creation": { + "VmBuildLog": { + "hiddenTechnicalLines_one": "{{count}} technical line hidden. Copy log includes it.", + "hiddenTechnicalLines_other": "{{count}} technical lines hidden. Copy log includes them." + } + } } }, "hooks": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index dd633150736..d2e20388b67 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4090,7 +4090,6 @@ "turnOnOverage": "Turn on overage", "openingGitHub": "Opening GitHub…", "connectGitHub": "Connect GitHub", - "pushToGitHubFirst": "Push to GitHub first", "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", @@ -4113,7 +4112,8 @@ "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." + "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", @@ -4122,7 +4122,8 @@ "label": "Build log", "copyFailed": "Couldn’t copy the log.", "copiedStatus": "Log copied", - "hiddenLines": "Technical lines hidden: {{count}}. Copy log includes them." + "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…", @@ -4131,25 +4132,25 @@ "connecting": "Connecting to the sandbox…", "resuming": "Waking the sandbox…", "suspending": "Putting the sandbox to sleep…", - "renewing": "Extending the session…", "rollingOver": "Starting a fresh session…", "destroying": "Deleting the sandbox…", "denyNoPlan": "Your account has no active Team plan.", - "denyHours": "This month’s included sandbox hours are used up.", "denySpendCap": "This month’s spend cap is reached.", - "denyPayment": "A payment is overdue.", - "denyConcurrency": "Your team’s limit on running cloud workspaces is reached.", - "denyMemberConcurrency": "Your limit on running cloud workspaces is reached.", "denyGithub": "GitHub isn’t connected to your Orca account.", - "denyMachineSize": "This machine size isn’t part of your plan.", "refusedBilling": "Orca Cloud couldn’t check your plan.", - "refusedProvider": "The sandbox provider is unavailable.", "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." + "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.", From 72f068107c226548d9f86331f70bf88b4a297866 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 09:02:33 -0800 Subject: [PATCH 09/11] fix(build-sheet): W10 round 8: glossary log lines, snapshot-missing starts nothing, plural hidden-lines note, How to push to GitHub, muted Dismiss --- .../src/components/worktree-creation/vm-build-steps.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts index 100dbd91d9c..fa862cd1a26 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts @@ -189,7 +189,7 @@ describe('humanizeOrcaCloudLogLine', () => { it('turns provider codes into sentences and hides internals', () => { expect(humanizeOrcaCloudLogLine('Orca Cloud: included_hours_exhausted', t)).toBe( - 'This month’s included sandbox hours are used up.' + '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() From af8648041716666c2cccead2ce995b2af0691db3 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 14:48:02 -0800 Subject: [PATCH 10/11] test(cloud): pin sandbox wording on the pending row and the right-sidebar collapse for cloud builds --- .../pending-worktree-creation-label.test.ts | 36 +++++++++++++++++++ .../worktree-creation-surface.test.ts | 34 ++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts create mode 100644 src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts new file mode 100644 index 00000000000..e3fb35e1a1c --- /dev/null +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation-label.test.ts @@ -0,0 +1,36 @@ +import { expect, it } from 'vitest' +import { getCreationProgressLabel, type PendingWorktreeCreation } from './pending-worktree-creation' + +const t = ((_key: string, fallback: string) => fallback) as Parameters< + typeof getCreationProgressLabel +>[1] + +function label( + provider: 'orca-cloud' | undefined, + environmentCheck?: PendingWorktreeCreation['environmentCheck'] +): string { + return getCreationProgressLabel( + { + status: 'creating', + phase: 'provisioning-vm', + indeterminate: false, + environmentCheck, + request: { + name: 'fix-login', + ephemeralVmRecipe: { sourceRepoId: 'r', recipeId: 'cloud', projectId: 'p', provider } + } as PendingWorktreeCreation['request'] + }, + t + ) +} + +it('speaks of a sandbox for Orca Cloud and keeps VM wording for bring-your-own recipes', () => { + expect(label('orca-cloud')).toBe('Starting sandbox…') + expect( + label('orca-cloud', { + status: 'running', + startedAt: 1 + } as PendingWorktreeCreation['environmentCheck']) + ).toBe('Preparing environment…') + expect(label(undefined)).toBe('Provisioning VM…') +}) diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts new file mode 100644 index 00000000000..2a80026cfbc --- /dev/null +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-surface.test.ts @@ -0,0 +1,34 @@ +import { expect, it } from 'vitest' +import type { PendingWorktreeCreation } from './pending-worktree-creation' +import { selectVmBuildSurfaceShown } from './worktree-creation-surface' + +function state(entry: Partial) { + return { + activeView: 'terminal' as const, + activePendingCreationId: 'c1', + pendingWorktreeCreations: { + c1: { status: 'creating', loaderVisible: true, ...entry } as PendingWorktreeCreation + } + } +} + +// The right sidebar closes while this is true, so a cloud build never sits beside an empty panel. +it('treats every Orca Cloud or VM build sheet as filling the window, from the first frame', () => { + const cloud = { + request: { + name: 'fix-login', + ephemeralVmRecipe: { + sourceRepoId: 'r', + recipeId: 'cloud', + projectId: 'p', + provider: 'orca-cloud' + } + } as PendingWorktreeCreation['request'] + } + expect(selectVmBuildSurfaceShown(state({ ...cloud, phase: 'provisioning-vm' }))).toBe(true) + expect( + selectVmBuildSurfaceShown(state({ ...cloud, status: 'error', loaderVisible: false })) + ).toBe(true) + const local = { request: { name: 'fix-login' } as PendingWorktreeCreation['request'] } + expect(selectVmBuildSurfaceShown(state(local))).toBe(false) +}) From ef107bb6118fdfca8c618099e839d87319db40d7 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 14:56:09 -0800 Subject: [PATCH 11/11] test(cloud): wake-store bridge stub gains getConfig/connectGitHub after rebase --- .../src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts index 40b7adab173..75e324fc891 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts @@ -33,6 +33,8 @@ function stub( unarchive: vi.fn(unused), getArchive: vi.fn(unused), listCloudWorkspaceIds: vi.fn(async () => ids), + getConfig: vi.fn(async () => null), + connectGitHub: vi.fn(unused), onWakeProgress: vi.fn(() => () => {}), onOom: vi.fn(() => () => {}) }