From cd884b94ea7cc4d49fd2e1e52b96aaf3f9a885cb Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:20:06 -0800 Subject: [PATCH] Run-on picker: Orca Cloud as a top-level target, entitlement pre-check, keyboard submenus (#50) * feat(run-on): Orca Cloud as a top-level Run-on target with entitlement pre-check and keyboard submenus * fix(run-on): reviewer fixes, sign-in/upsell row, glossary copy, current-row check * fix(run-on): main reports Orca Cloud availability; reload recipes on auth change * fix(run-on): an offline session refresh hides Orca Cloud instead of asking to sign in --- .../hosted-sandbox/hosted-sandbox-install.ts | 43 +++- .../hosted-sandbox/hosted-sandbox-recipe.ts | 2 +- src/main/ipc/ephemeral-vm-recipe-context.ts | 20 +- src/main/ipc/ephemeral-vm.ts | 3 +- .../orca-profiles/profile-cloud-dev-auth.ts | 5 +- src/preload/api/ephemeral-vm-api.ts | 4 +- .../components/NewWorkspaceComposerModal.tsx | 19 +- ...orkspaceComposerProjectSection.fixture.tsx | 39 ++- .../NewWorkspaceComposerProjectSection.tsx | 14 +- .../new-workspace/OrcaCloudSelectionHint.tsx | 68 +++++ .../new-workspace/ProjectComboboxRow.tsx | 11 +- .../RunTargetCombobox.fixture.tsx | 138 +++++++++- .../new-workspace/RunTargetCombobox.test.tsx | 190 ++++++++++++++ .../new-workspace/RunTargetCombobox.tsx | 238 ++++++++++++------ .../new-workspace/RunTargetComboboxRow.tsx | 30 ++- .../new-workspace/RunTargetField.tsx | 24 +- .../new-workspace/RunTargetOrcaCloudRow.tsx | 179 +++++++++++++ .../new-workspace/RunTargetRowList.tsx | 29 ++- .../new-workspace/RunTargetSubmenus.tsx | 93 ++++--- .../SmartWorkspaceSourceTabs.tsx | 2 +- .../new-workspace-composer-card-props.ts | 3 + .../orca-cloud-run-target-access.ts | 91 +++++++ .../new-workspace/run-target-keyboard.ts | 76 ++++++ .../new-workspace/run-target-options.ts | 152 ++++++++++- .../use-run-target-orca-cloud.ts | 77 ++++++ .../new-workspace/use-run-target-submenu.ts | 66 +++++ .../new-workspace/use-type-ahead-combobox.ts | 9 +- .../account-menu/SidebarHelpSubmenu.tsx | 6 +- .../composer-state/composer-card-contract.ts | 1 + .../composer-state/composer-card-props.ts | 2 + .../composer-state/runtime-target-model.ts | 3 + .../runtime-target-selection.ts | 13 +- .../useEphemeralVmRecipeOptions.test.tsx | 57 +++++ .../src/hooks/useEphemeralVmRecipeOptions.ts | 51 +++- .../src/i18n/en-runtime-required.json | 15 ++ src/renderer/src/i18n/locales/en.json | 26 +- src/shared/orca-yaml-hook-types.ts | 6 + 37 files changed, 1602 insertions(+), 203 deletions(-) create mode 100644 src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx create mode 100644 src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx create mode 100644 src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx create mode 100644 src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts create mode 100644 src/renderer/src/components/new-workspace/run-target-keyboard.ts create mode 100644 src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts create mode 100644 src/renderer/src/components/new-workspace/use-run-target-submenu.ts diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 77a9b2881ea..23520ce9574 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -4,7 +4,7 @@ import { app, BrowserWindow } from 'electron' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' import { readFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import type { OrcaCloudAvailability, OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' import type { PluginService } from '../plugins/plugin-service' import { getHostedSandboxConfig } from './hosted-sandbox-config' @@ -101,30 +101,49 @@ export function installHostedSandbox(): void { }) } -/** Orca Cloud auth's `sandbox` capability rolls it out per account; the dev key bypasses it in dev builds. */ -async function orcaCloudOffered(): Promise { +/** + * Orca Cloud auth's `sandbox` capability rolls it out per account; the dev key bypasses it in dev + * builds. Builds without a hosted-sandbox control plane never offer it, signed in or not. + */ +export async function getOrcaCloudAvailability(): Promise { + if (!installed) { + return 'unavailable' + } if (cloudDevSigningAllowed(app.isPackaged) && process.env.ORCA_CLOUD_SANDBOX_DEV_KEY_FILE) { - return true + return 'offered' } const auth = getOrcaCloudAuthConfig(process.env, app.isPackaged) + if (!auth.configured) { + return 'unavailable' + } const userDataPath = app.getPath('userData') const active = ensureActiveOrcaProfile(userDataPath) - if (!auth.configured || !active.profile.cloud) { - return false + if (!active.profile.cloud) { + return 'needs-sign-in' } const session = await readFreshOrcaCloudSession(auth.config, active, userDataPath).catch( () => null ) - return ( - session?.status === 'found' && - session.session.capabilities.flags[ORCA_CLOUD_SANDBOX_CAPABILITY] === true - ) + // A refresh that failed (offline) is not a sign-out; hide the row rather than ask to sign in. + if (session === null) { + return 'unavailable' + } + if (session.status !== 'found') { + return 'needs-sign-in' + } + return session.session.capabilities.flags[ORCA_CLOUD_SANDBOX_CAPABILITY] === true + ? 'offered' + : 'needs-capability' } /** Built-in providers (Orca Cloud) ride along with approved plugin recipes and lead every list. */ -export async function withProviderRecipes(pluginService?: PluginService): Promise { +export async function withProviderRecipes( + pluginService?: PluginService, + availability?: OrcaCloudAvailability +): Promise { + const orcaCloud = availability ?? (await getOrcaCloudAvailability()) return [ - ...(installed && (await orcaCloudOffered()) ? [ORCA_CLOUD_RECIPE] : []), + ...(orcaCloud === 'offered' ? [ORCA_CLOUD_RECIPE] : []), ...(await getApprovedPluginVmRecipes(pluginService)) ] } diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index 6d604568809..77f68dac259 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -28,7 +28,7 @@ export const ORCA_CLOUD_RECIPE_ID = 'cloud' export const ORCA_CLOUD_RECIPE: OrcaVmRecipe = { id: ORCA_CLOUD_RECIPE_ID, name: 'Orca Cloud', - description: 'A cloud VM run by Orca. Sleeps when idle; files persist.', + description: 'Hosted by Orca. Sleeps when idle and keeps your files.', provider: 'orca-cloud', create: 'orca-cloud create', suspend: 'orca-cloud suspend', diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index f699fea87cb..365679fbb0a 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -4,7 +4,12 @@ import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-re import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import { isFolderRepo, isGitRepoKind } from '../../shared/repo-kind' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import type { OrcaCloudAvailability, OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import type { PluginService } from '../plugins/plugin-service' +import { + getOrcaCloudAvailability, + withProviderRecipes +} from '../hosted-sandbox/hosted-sandbox-install' import { EphemeralVmFailureError, ephemeralVmFailure, @@ -59,6 +64,19 @@ export function listRecipes( } } +/** The Run-on picker's list, plus Orca Cloud availability so it can offer sign-in or an upsell. */ +export async function listPickerRecipes( + store: Store, + repoId: string, + pluginService?: PluginService +): Promise { + const orcaCloud = await getOrcaCloudAvailability() + return { + ...listRecipes(store, repoId, await withProviderRecipes(pluginService, orcaCloud)), + orcaCloud + } +} + export function listRecipeCatalog( store: Store, pluginRecipes: readonly OrcaVmRecipe[] = [] diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 5a5dd302a17..98ee254a60e 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -32,6 +32,7 @@ import { getRecipeRepo, listRecipeCatalog, listRecipes, + listPickerRecipes, resolveRecipeForRepo, type EphemeralVmRecipeCatalogEntry } from './ephemeral-vm-recipe-context' @@ -85,7 +86,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin reconcileInterruptedEphemeralVmProvisionsOnStartup(app.getPath('userData')) ipcMain.handle('ephemeralVm:listRecipes', async (_event, args: { repoId: string }) => { - return listRecipes(store, args.repoId, await withProviderRecipes(pluginService)) + return listPickerRecipes(store, args.repoId, pluginService) }) ipcMain.handle( diff --git a/src/main/orca-profiles/profile-cloud-dev-auth.ts b/src/main/orca-profiles/profile-cloud-dev-auth.ts index 137696e17ce..f578dabaaeb 100644 --- a/src/main/orca-profiles/profile-cloud-dev-auth.ts +++ b/src/main/orca-profiles/profile-cloud-dev-auth.ts @@ -25,7 +25,10 @@ function devCapabilities(): OrcaCloudCapabilities { 'share.manage': true, 'relay.use': true, 'team.member': true, - 'enterprise.sso': true + 'enterprise.sso': true, + // Dev sessions exercise the plans/team UI and the Orca Cloud Run-on row too. + billing: true, + sandbox: true }, refreshedAt: Date.now() } diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 4fdc1fc8932..0ae43b33eef 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -1,4 +1,4 @@ -import type { OrcaHooks } from '../../shared/orca-yaml-hook-types' +import type { OrcaCloudAvailability, OrcaHooks } from '../../shared/orca-yaml-hook-types' import type { HostedSessionIdleSleepEvent, HostedSessionWarningEvent @@ -21,6 +21,8 @@ export type EphemeralVmApi = { message?: string messageCode?: string messageParams?: Record + /** Absent from older mains and web clients; treat as unavailable. */ + orcaCloud?: OrcaCloudAvailability }> listRecipeCatalog: () => Promise< { diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index a30a54562d8..fb79a4a863f 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -9,6 +9,7 @@ import type { AgentPickerEntry } from '../../../shared/agent-launch/picker/agent-launch-picker' import { DirectWorkItemSetupDialog } from './new-workspace/DirectWorkItemSetupDialog' +import { isOrcaCloudSelection } from './new-workspace/run-target-options' import { agentChoicePending } from '@/lib/host-chat-program' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -315,13 +316,13 @@ function QuickTabBody({ }), [addProjectOpen, handleAddProjectCloseAutoFocus, handleProjectAdded, selectAddedProjectGroup] ) - const selectedProjectOption = cardProps.projectOptions.find( - (option) => option.id === cardProps.selectedProjectId - ) - const isFolderWorkspaceTarget = selectedProjectOption?.kind === 'project-group' + const isFolderWorkspaceTarget = + cardProps.projectOptions.find((option) => option.id === cardProps.selectedProjectId)?.kind === + 'project-group' + // An Orca Cloud sandbox is a whole workspace, not a local worktree. const primaryActionLabel = isFolderWorkspaceTarget ? getFolderWorkspacePrimaryActionLabel(t) - : cardProps.selectedRepoIsGit + : cardProps.selectedRepoIsGit && !isOrcaCloudSelection(cardProps) ? t('auto.components.NewWorkspaceComposerModal.createWorktree', 'Create worktree') : t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace') @@ -358,12 +359,8 @@ function QuickTabBody({ <> - {isFolderWorkspaceTarget - ? t( - 'auto.components.sidebar.FolderWorkspaceComposerDialog.title', - 'Create Folder Workspace' - ) - : primaryActionLabel} + {/* One title for every project type and target; only the button names the result. */} + {t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace')} {t( diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx index b4b91dc4cd5..ca83119094f 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx @@ -6,6 +6,8 @@ import { type ProjectHostSetupOption } from '@/lib/project-host-setup-options' import { NewWorkspaceComposerProjectSection } from './NewWorkspaceComposerProjectSection' +import type { EphemeralVmRecipeOption } from './run-target-options' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' const projects: NewWorkspaceProjectOption[] = [ { @@ -77,16 +79,30 @@ const hosts: ProjectHostSetupOption[] = [ } ] +const orcaCloudRecipe: EphemeralVmRecipeOption = { + id: 'cloud', + name: 'Orca Cloud', + description: 'Hosted by Orca. Sleeps when idle and keeps your files.', + provider: 'orca-cloud', + create: 'orca-cloud create' +} + function ProjectAndHostPreview({ - folderOnly = false + folderOnly = false, + orcaCloud, + cloudSelected = false }: { folderOnly?: boolean + /** Offers Orca Cloud with this entitlement. */ + orcaCloud?: OrcaCloudRunTargetAccess + cloudSelected?: boolean }): React.JSX.Element { const [project, setProject] = useState(folderOnly ? 'folder' : 'orca') const [host, setHost] = useState('local') + const [recipe, setRecipe] = useState(cloudSelected ? 'cloud' : null) return (
-

New worktree

+

Create workspace

{}} handleAddRemoteServer={() => {}} handleConnectRunTargetHost={async () => {}} @@ -159,3 +178,17 @@ function tooltipFixture(attribute: string) { export const projectTooltip = tooltipFixture('data-project-combobox-root') export const hostTooltip = tooltipFixture('data-run-target-combobox-root') + +const entitled: OrcaCloudRunTargetAccess = { state: 'entitled', remainingSeconds: 41 * 3600 } +export const hostMenuOrcaCloud = defineFixture({ + ...hostMenu, + render: () => +}) +export const hostMenuOrcaCloudLocked = defineFixture({ + ...hostMenu, + render: () => +}) +export const orcaCloudSelected = defineFixture({ + ...closed, + render: () => +}) diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx index 66053fe642a..81f3c479c5c 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx @@ -13,6 +13,9 @@ import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-card-props' import { EMPTY_PROJECT_OPTIONS } from './new-workspace-composer-card-props' +import { OrcaCloudSelectionHint } from './OrcaCloudSelectionHint' +import { isOrcaCloudSelection } from './run-target-options' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' type NewWorkspaceComposerProjectSectionProps = Pick< NewWorkspaceComposerCardProps, @@ -33,6 +36,7 @@ type NewWorkspaceComposerProjectSectionProps = Pick< | 'onEphemeralVmRecipeChange' | 'selectedEphemeralVmRecipeId' | 'ephemeralVmRecipeError' + | 'orcaCloudAvailability' > & { disabled?: boolean projectDescriptionId: string @@ -49,6 +53,8 @@ type NewWorkspaceComposerProjectSectionProps = Pick< sshStatusLabel: string connectButtonLabel: string selectedProjectName: string + /** Fixtures pin Orca Cloud entitlement; the app reads it from billing. */ + orcaCloudAccess?: OrcaCloudRunTargetAccess } export function NewWorkspaceComposerProjectSection({ @@ -77,13 +83,15 @@ export function NewWorkspaceComposerProjectSection({ handleConnectRunTargetHost, handleSetLocation, ephemeralVmRecipeError, + orcaCloudAvailability = 'unavailable', selectedRepoRequiresConnection, selectedRepoConnectionId, selectedRepoConnectInProgress, onConnectSelectedRepo, sshStatusLabel, connectButtonLabel, - selectedProjectName + selectedProjectName, + orcaCloudAccess }: NewWorkspaceComposerProjectSectionProps): React.JSX.Element { const t = useTranslate() return ( @@ -169,11 +177,15 @@ export function NewWorkspaceComposerProjectSection({ onAddRemoteServer={handleAddRemoteServer} onConnectHost={handleConnectRunTargetHost} onSetLocation={handleSetLocation} + orcaCloudAvailability={orcaCloudAvailability} + {...(orcaCloudAccess ? { orcaCloudAccess } : {})} /> {ephemeralVmRecipeError ? (

{ephemeralVmRecipeError}

+ ) : isOrcaCloudSelection({ ephemeralVmRecipes, selectedEphemeralVmRecipeId }) ? ( + ) : null}
) : null} diff --git a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx new file mode 100644 index 00000000000..edecc041da6 --- /dev/null +++ b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx @@ -0,0 +1,68 @@ +import React from 'react' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import { getOrcaCloudDetail } from './run-target-options' +import { + formatOrcaCloudHoursLeft, + useOrcaCloudRunTargetAccess, + type OrcaCloudRunTargetAccess +} from './orca-cloud-run-target-access' + +/** + * Machine and hours context under Run on once Orca Cloud is the committed target. A selection made + * before billing answered (or restored from a draft) surfaces its block here instead of at Create. + */ +export function OrcaCloudSelectionHint({ + access: accessOverride +}: { + /** Fixtures pin the entitlement; otherwise it is read from billing while mounted. */ + access?: OrcaCloudRunTargetAccess +}): React.JSX.Element { + const t = useTranslate() + const fetched = useOrcaCloudRunTargetAccess(!accessOverride) + const access = accessOverride ?? fetched + const status = ((): string | null => { + switch (access.state) { + case 'entitled': + return t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudHoursLeft', + '{{hours}} h left', + { + hours: formatOrcaCloudHoursLeft(access.remainingSeconds) + } + ) + case 'no-plan': + return t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudNeedsTeam', + 'Needs a Team plan' + ) + case 'out-of-hours': + return t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudNoHours', + 'No hours left' + ) + case 'payment-issue': + return t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentFailed', + 'Payment failed' + ) + default: + return null + } + })() + const blocked = + access.state === 'no-plan' || + access.state === 'out-of-hours' || + access.state === 'payment-issue' + return ( +

+ {status ? `${getOrcaCloudDetail(t)} · ${status}` : getOrcaCloudDetail(t)} +

+ ) +} diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx b/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx index 9cf579f7669..0254d7dd0fa 100644 --- a/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx +++ b/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { FolderOpen } from 'lucide-react' +import { Check, FolderOpen } from 'lucide-react' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { cn } from '@/lib/utils' import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' @@ -119,8 +119,7 @@ export function ProjectOptionRow({ onClick={onCommit} className={cn( 'flex cursor-default items-start gap-2 rounded-sm px-2 py-1.5 text-sm', - armed && 'bg-accent text-accent-foreground', - current && !armed && 'bg-accent/60' + armed && 'bg-accent text-accent-foreground' )} > @@ -138,6 +137,12 @@ export function ProjectOptionRow({ className={cn('text-xs', ambiguous ? 'text-foreground/80' : 'text-muted-foreground')} /> + {/* The committed row gets a check, not a second fill, so only the armed row is shaded. */} + {current ? ( + + + + ) : null} ) } diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx index 9dc75e7c7d9..b10740208cb 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx @@ -1,6 +1,8 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' import RunTargetCombobox from './RunTargetCombobox' +import type { EphemeralVmRecipeOption } from './run-target-options' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' // Shape produced by buildProjectHostSetupOptions with local + ephemeral VM setups and SSH hosts: // the VM is dropped entirely, SSH hosts become needs-setup rows. @@ -30,7 +32,34 @@ const options: ProjectHostSetupOption[] = [ ) ] -function Preview({ vmSelected }: { vmSelected: boolean }): React.JSX.Element { +// Mirrors ORCA_CLOUD_RECIPE from main plus one orca.yaml recipe for the submenu. +const orcaCloud: EphemeralVmRecipeOption = { + id: 'cloud', + name: 'Orca Cloud', + description: 'Hosted by Orca. Sleeps when idle and keeps your files.', + provider: 'orca-cloud', + create: 'orca-cloud create', + destroy: 'orca-cloud destroy' +} +const devboxRecipe: EphemeralVmRecipeOption = { + id: 'devbox', + name: 'Devbox', + create: './scripts/devbox-create.sh', + destroy: './scripts/devbox-destroy.sh' +} +const NO_RECIPES: EphemeralVmRecipeOption[] = [] + +function Preview({ + vmSelected = false, + recipes = NO_RECIPES, + recipeValue = null, + access +}: { + vmSelected?: boolean + recipes?: EphemeralVmRecipeOption[] + recipeValue?: string | null + access?: OrcaCloudRunTargetAccess +}): React.JSX.Element { return (
{}} - recipes={[]} - recipeValue={null} + recipes={recipes} + recipeValue={recipeValue} onAddSshHost={() => {}} onAddRemoteServer={() => {}} onConnectHost={async () => {}} onSetLocation={() => {}} + orcaCloudAvailability={ + recipes.some((recipe) => recipe.provider === 'orca-cloud') ? 'offered' : 'needs-sign-in' + } + {...(access ? { orcaCloudAccess: access } : {})} />
) } -const open = (frame: HTMLElement): void => { - frame.querySelector('[aria-label="Run on"][role="combobox"]')?.focus() +function input(frame: HTMLElement): HTMLInputElement | null { + return frame.querySelector('[aria-label="Run on"][role="combobox"]') } +const open = (frame: HTMLElement): void => { + input(frame)?.focus() +} +/** Opens the list, then drives it with keys so the keyboard-armed submenu row is captured. */ +const pressKeys = + (...keys: string[]) => + async (frame: HTMLElement): Promise => { + const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 30)) + open(frame) + await settle() + for (const key of keys) { + input(frame)?.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) + // Each key reads the arm the previous one committed. + await settle() + } + await new Promise((resolve) => setTimeout(resolve, 300)) + } + export const vmSelectedClosed = defineFixture({ width: 420, render: () => }) export const vmSelected = defineFixture({ ...vmSelectedClosed, interact: open }) export const localSelected = defineFixture({ width: 420, - render: () => , + render: () => , + interact: open +}) + +const withCloud = [orcaCloud, devboxRecipe] +export const orcaCloudEntitled = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) +export const orcaCloudNotEntitled = defineFixture({ + width: 420, + render: () => , + interact: open +}) +export const orcaCloudOutOfHours = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) +export const orcaCloudOutOfHoursMember = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) +export const orcaCloudPaymentIssue = defineFixture({ + width: 420, + render: () => ( + + ), + interact: open +}) +export const orcaCloudLapsed = defineFixture({ + width: 420, + render: () => , + interact: open +}) +export const orcaCloudSelectedClosed = defineFixture({ + width: 420, + render: () => ( + + ) +}) +export const orcaCloudSelected = defineFixture({ ...orcaCloudSelectedClosed, interact: open }) +// Local Mac, Orca Cloud, 6 bounded SSH hosts, then Per-Workspace Environment. +export const recipeSubmenuKeyboard = defineFixture({ + width: 720, + render: () => ( + + ), + interact: pressKeys(...Array(12).fill('ArrowDown'), 'ArrowUp', 'ArrowRight') +}) +export const addHostSubmenuKeyboard = defineFixture({ + width: 720, + render: () => , + interact: pressKeys(...Array(12).fill('ArrowDown'), 'Enter', 'ArrowDown') +}) +// No Orca Cloud recipe from main: the row still appears to sign in, or to upgrade without the capability. +export const orcaCloudSignedOut = defineFixture({ + width: 420, + render: () => , + interact: open +}) +export const orcaCloudNoCapability = defineFixture({ + width: 420, + render: () => , interact: open }) diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx new file mode 100644 index 00000000000..b5152cceb39 --- /dev/null +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.test.tsx @@ -0,0 +1,190 @@ +// @vitest-environment happy-dom + +import React, { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' +import { TooltipProvider } from '@/components/ui/tooltip' +import RunTargetCombobox from './RunTargetCombobox' +import { useAppStore } from '@/store/index' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import type { EphemeralVmRecipeOption } from './run-target-options' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' + +// Render popovers inline so submenu rows exist without Radix portals. +vi.mock('@/components/ui/popover', () => ({ + Popover: ({ children }: { children: React.ReactNode }) =>
{children}
, + PopoverAnchor: ({ children }: { children: React.ReactNode }) => <>{children}, + PopoverContent: ({ children }: { children: React.ReactNode }) =>
{children}
+})) + +const openPlansPage = vi.fn() +vi.mock('@/components/billing/plans/plans-page-store', () => ({ + openPlansPage: (source: string) => openPlansPage(source) +})) + +const hosts: ProjectHostSetupOption[] = [ + { + id: 'mac', + kind: 'ready', + projectId: 'p', + hostId: 'local', + repoId: 'mac', + label: 'Local Mac', + detail: 'desktop-app', + path: '/tmp/desktop-app' + } +] +const cloud: EphemeralVmRecipeOption = { + id: 'cloud', + name: 'Orca Cloud', + description: 'A cloud VM run by Orca.', + provider: 'orca-cloud', + create: 'orca-cloud create' +} +const devbox: EphemeralVmRecipeOption = { id: 'devbox', name: 'Devbox', create: './create.sh' } + +let container: HTMLDivElement +let root: Root + +function input(): HTMLInputElement { + const node = container.querySelector('[role="combobox"]') + if (!node) { + throw new Error('run target input not found') + } + return node +} + +function press(key: string): void { + act(() => { + input().dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) + }) +} + +function activeText(): string | null | undefined { + const id = input().getAttribute('aria-activedescendant') + return id ? document.getElementById(id)?.textContent : null +} + +function render( + access: OrcaCloudRunTargetAccess | undefined, + onRecipeChange = vi.fn(), + onAddRemoteServer = vi.fn(), + { + recipes = [cloud, devbox], + availability = 'offered' + }: { recipes?: EphemeralVmRecipeOption[]; availability?: OrcaCloudAvailability } = {} +): void { + act(() => { + root.render( + + {}} + onAddRemoteServer={onAddRemoteServer} + {...(access ? { orcaCloudAccess: access } : {})} + /> + + ) + }) + act(() => { + input().focus() + }) +} + +beforeEach(() => { + openPlansPage.mockClear() + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => { + root.unmount() + }) + container.remove() +}) + +describe('RunTargetCombobox', () => { + it('lists Orca Cloud as its own row, not inside the recipe submenu', () => { + render({ state: 'entitled', remainingSeconds: 12 * 3600 }) + const recipeLists = [...container.querySelectorAll('[role="listbox"]')].filter( + (list) => list.getAttribute('aria-label') === 'Custom environments' + ) + expect(recipeLists).toHaveLength(1) + expect(recipeLists[0]?.textContent).toContain('Devbox') + expect(recipeLists[0]?.textContent).not.toContain('Orca Cloud') + }) + + it('selects Orca Cloud through its recipe when entitled', () => { + const onRecipeChange = vi.fn() + render({ state: 'entitled', remainingSeconds: 3600 }, onRecipeChange) + press('ArrowDown') + expect(activeText()).toContain('Orca Cloud') + press('Enter') + expect(onRecipeChange).toHaveBeenCalledWith('cloud') + expect(openPlansPage).not.toHaveBeenCalled() + }) + + it('opens the plans page instead of building when there is no plan', () => { + const onRecipeChange = vi.fn() + render({ state: 'no-plan', lapsed: false }, onRecipeChange) + press('ArrowDown') + press('Enter') + expect(openPlansPage).toHaveBeenCalledWith('sandbox') + expect(onRecipeChange).not.toHaveBeenCalled() + }) + + it('moves keyboard focus into the recipe submenu and commits a recipe with Enter', () => { + const onRecipeChange = vi.fn() + render({ state: 'entitled', remainingSeconds: 3600 }, onRecipeChange) + press('ArrowDown') + press('ArrowDown') + expect(activeText()).toContain('Custom environments') + press('ArrowRight') + expect(activeText()).toContain('Devbox') + press('ArrowLeft') + expect(activeText()).toContain('Custom environments') + press('Enter') + expect(activeText()).toContain('Devbox') + press('Enter') + expect(onRecipeChange).toHaveBeenCalledWith('devbox') + }) + + it('reaches Add host submenu rows by keyboard', () => { + const onAddRemoteServer = vi.fn() + render({ state: 'unknown' }, vi.fn(), onAddRemoteServer) + for (let i = 0; i < 3; i++) { + press('ArrowDown') + } + expect(activeText()).toContain('Add host') + press('Enter') + expect(activeText()).toContain('Add SSH host') + press('ArrowDown') + expect(activeText()).toContain('Add remote Orca server') + press('Enter') + expect(onAddRemoteServer).toHaveBeenCalledTimes(1) + }) + + it('offers sign-in on the Orca Cloud row when nobody is signed in', () => { + const connect = vi.fn(async () => null) + useAppStore.setState({ connectCurrentOrcaProfile: connect }) + const onRecipeChange = vi.fn() + render(undefined, onRecipeChange, vi.fn(), { + recipes: [devbox], + availability: 'needs-sign-in' + }) + press('ArrowDown') + expect(activeText()).toContain('Sign in to use Orca Cloud') + press('Enter') + expect(connect).toHaveBeenCalledTimes(1) + expect(onRecipeChange).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index f66c82e5530..0572108994e 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -15,10 +15,22 @@ import { buildRunTargetRows, getEphemeralVmLabel, getRecipeDetail, + getRecipeSubmenuItemKey, + getRunTargetSubmenuItemKeys, + getRunTargetCurrentRowKey, + isOrcaCloudRecipe, RUN_TARGET_ADD_HOST_KEY, - type EphemeralVmRecipeOption + RUN_TARGET_ADD_REMOTE_SERVER_ITEM, + RUN_TARGET_ADD_SSH_HOST_ITEM, + type EphemeralVmRecipeOption, + type RunTargetSubmenu } from './run-target-options' -import { AddHostSubmenuRow } from './RunTargetSubmenus' +import { AddHostSubmenuRow, type RunTargetSubmenuArm } from './RunTargetSubmenus' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' +import { useRunTargetSubmenu } from './use-run-target-submenu' +import { getRunTargetOrcaCloudOffer, useRunTargetOrcaCloud } from './use-run-target-orca-cloud' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import { handleRunTargetKeyDown } from './run-target-keyboard' import RunTargetRowList from './RunTargetRowList' import RunTargetField from './RunTargetField' import { HostListOverflowNote } from '@/components/host-picker/HostListOverflowNote' @@ -35,6 +47,23 @@ type RunTargetComboboxProps = { onAddSshHost?: () => void onConnectHost?: (option: NeedsSetupProjectHostOption) => Promise | void onSetLocation?: (option: NeedsSetupProjectHostOption) => void + /** Fixtures/tests pin the entitlement; otherwise it is read from billing while the picker is open. */ + orcaCloudAccess?: OrcaCloudRunTargetAccess + /** From main: drives the sign-in/upsell row when there is no Orca Cloud recipe. */ + orcaCloudAvailability?: OrcaCloudAvailability +} + +/** Add-host actions open dialogs, so the picker closes before they run. */ +function closingFirst( + close: () => void, + action: (() => void) | undefined +): (() => void) | undefined { + return action + ? () => { + close() + action() + } + : undefined } const ROOT_ATTRIBUTE = 'data-run-target-combobox-root' @@ -51,27 +80,14 @@ export default function RunTargetCombobox({ onAddRemoteServer, onAddSshHost, onConnectHost, - onSetLocation + onSetLocation, + orcaCloudAccess: orcaCloudAccessOverride, + orcaCloudAvailability = 'unavailable' }: RunTargetComboboxProps): React.JSX.Element { const t = useTranslate() - const [submenu, setSubmenu] = useState<'recipes' | 'add-host' | null>(null) // Track in-flight connects per host so one stalling connect never blocks the others. const [connectingHostIds, setConnectingHostIds] = useState>(() => new Set()) - const hasAddHost = Boolean(onAddSshHost || onAddRemoteServer) - const deriveRowKeys = useCallback( - (query: string): string[] => - buildRunTargetRows({ hostOptions, recipes, query, hasAddHost }).rows.map((row) => row.key), - [hasAddHost, hostOptions, recipes] - ) - const combobox = useTypeAheadCombobox(deriveRowKeys) - const { query, setQuery, open, setOpen, armedKey, arm, moveArm, inputRef, listId, setListNode } = - combobox - - const { rows, matchedRecipes, hiddenHostCount } = useMemo( - () => buildRunTargetRows({ hostOptions, recipes, query, hasAddHost }), - [hasAddHost, hostOptions, query, recipes] - ) const readyHostOptions = useMemo( () => hostOptions.filter((option) => option.kind === 'ready'), [hostOptions] @@ -85,14 +101,50 @@ export default function RunTargetCombobox({ // An unlisted target (e.g. a per-workspace VM) shows "Choose target", never another host's name (#38669). null const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null + // Opening highlights the committed row, so only one row reads as chosen. + const currentRowKey = getRunTargetCurrentRowKey(selectedRecipe, selectedHost) + + const hasAddHost = Boolean(onAddSshHost || onAddRemoteServer) + const orcaCloudOffer = getRunTargetOrcaCloudOffer({ + recipes, + availability: orcaCloudAvailability, + override: orcaCloudAccessOverride + }) + const orcaCloudOffered = orcaCloudOffer !== null + const deriveRowKeys = useCallback( + (query: string): string[] => + buildRunTargetRows({ hostOptions, recipes, query, hasAddHost, orcaCloudOffered }).rows.map( + (row) => row.key + ), + [hasAddHost, hostOptions, orcaCloudOffered, recipes] + ) + const combobox = useTypeAheadCombobox(deriveRowKeys, currentRowKey) + const { query, setQuery, open, setOpen, armedKey, arm, moveArm, inputRef, listId, setListNode } = + combobox + + const { rows, matchedRecipes, hiddenHostCount } = useMemo( + () => buildRunTargetRows({ hostOptions, recipes, query, hasAddHost, orcaCloudOffered }), + [hasAddHost, hostOptions, orcaCloudOffered, query, recipes] + ) + const submenuItemKeys = useCallback( + (which: RunTargetSubmenu): string[] => + getRunTargetSubmenuItemKeys(which, { + matchedRecipes, + hasAddSshHost: Boolean(onAddSshHost), + hasAddRemoteServer: Boolean(onAddRemoteServer) + }), + [matchedRecipes, onAddRemoteServer, onAddSshHost] + ) + const { submenu, armedItemKey, openSubmenu, closeSubmenu, armItem, moveItemArm } = + useRunTargetSubmenu(submenuItemKeys) const armedRow = rows.find((row) => row.key === armedKey) ?? rows[0] ?? null const committed = query.length === 0 && (selectedRecipe !== null || selectedHost !== null) // Closing also drops any open submenu, which the shared hook doesn't know about. const close = useCallback((): void => { combobox.close() - setSubmenu(null) - }, [combobox]) + closeSubmenu() + }, [closeSubmenu, combobox]) const selectHost = useCallback( (option: ReadyProjectHostSetupOption): void => { @@ -111,6 +163,45 @@ export default function RunTargetCombobox({ [close, onRecipeChange] ) + const { + access: orcaCloudAccess, + runBlockedAction: runOrcaCloudBlockedAction, + select: selectOrcaCloud + } = useRunTargetOrcaCloud({ + recipes, + offer: orcaCloudOffer, + override: orcaCloudAccessOverride, + open, + close, + selectRecipe + }) + + const addSshHost = useMemo(() => closingFirst(close, onAddSshHost), [close, onAddSshHost]) + const addRemoteServer = useMemo( + () => closingFirst(close, onAddRemoteServer), + [close, onAddRemoteServer] + ) + + const commitSubmenuItem = useCallback( + (key: string): void => { + if (key === RUN_TARGET_ADD_SSH_HOST_ITEM) { + addSshHost?.() + return + } + if (key === RUN_TARGET_ADD_REMOTE_SERVER_ITEM) { + addRemoteServer?.() + return + } + const recipe = matchedRecipes.find( + (candidate) => getRecipeSubmenuItemKey(candidate.id) === key + ) + if (recipe) { + selectRecipe(recipe.id) + } + }, + [addRemoteServer, addSshHost, matchedRecipes, selectRecipe] + ) + const connectHost = useCallback( async (option: NeedsSetupProjectHostOption): Promise => { if (!option.connectAction || !onConnectHost || connectingHostIds.has(option.hostId)) { @@ -159,37 +250,23 @@ export default function RunTargetCombobox({ setLocation(row.option) return } - setSubmenu(row.kind === 'recipes' ? 'recipes' : 'add-host') + if (row.kind === 'orca-cloud') { + selectOrcaCloud(row.recipe) + return + } + // Keyboard opening moves the arm into the submenu so arrows and Enter reach its rows. + openSubmenu(row.kind === 'recipes' ? 'recipes' : 'add-host', true) }, - [rows, selectHost, setLocation] + [openSubmenu, rows, selectHost, selectOrcaCloud, setLocation] ) - const handleKeyDown = useCallback( - (event: React.KeyboardEvent): void => { - if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { - event.preventDefault() - setOpen(true) - moveArm(event.key === 'ArrowDown' ? 1 : -1) - setSubmenu(null) - return - } - if ((event.key === 'Enter' || event.key === 'ArrowRight') && open) { - event.preventDefault() - activate(armedRow?.key ?? null) - return - } - if (event.key === 'Escape' && (open || query.length > 0)) { - event.preventDefault() - event.stopPropagation() - if (submenu !== null) { - setSubmenu(null) - return - } - close() - } - }, - [activate, armedRow, close, moveArm, open, query, setOpen, submenu] - ) + const inSubmenu = submenu !== null && armedItemKey !== null + const handleKeyDown = (event: React.KeyboardEvent): void => + handleRunTargetKeyDown( + event, + { open, query, submenu, armedItemKey, armedRow }, + { setOpen, moveArm, moveItemArm, activate, commitSubmenuItem, closeSubmenu, close } + ) const handleOpenChange = useCallback( (next: boolean): void => { @@ -202,6 +279,18 @@ export default function RunTargetCombobox({ [close, setOpen] ) + const submenuArmFor = (which: RunTargetSubmenu): RunTargetSubmenuArm => ({ + listId: `${listId}-${which}`, + armedItemKey: submenu === which ? armedItemKey : null, + armedItemId: `${listId}-sub-armed`, + onArmItem: armItem + }) + const activeDescendantId = inSubmenu + ? `${listId}-sub-armed` + : armedRow + ? `${listId}-armed` + : undefined + const fieldLabel = selectedRecipe ? selectedRecipe.provider ? selectedRecipe.name @@ -218,18 +307,24 @@ export default function RunTargetCombobox({ onQueryChange={(value) => { setQuery(value) setOpen(true) - setSubmenu(null) + closeSubmenu() }} open={open} onOpenRequest={() => setOpen(true)} onToggle={() => setOpen(!open)} committed={committed} - isRecipe={selectedRecipe !== null} + recipeKind={ + selectedRecipe === null + ? null + : isOrcaCloudRecipe(selectedRecipe) + ? 'orca-cloud' + : 'recipe' + } hostId={selectedHost?.hostId ?? null} label={fieldLabel} detail={fieldDetail} - listId={listId} - hasArmedRow={armedRow !== null} + controlsId={submenu ? `${listId} ${listId}-${submenu}` : listId} + activeDescendantId={activeDescendantId} inputRef={inputRef} onKeyDown={handleKeyDown} /> @@ -281,16 +376,26 @@ export default function RunTargetCombobox({ selectedRecipeId={selectedRecipe?.id ?? null} matchedRecipes={matchedRecipes} recipesOpen={submenu === 'recipes'} + recipesSubmenuArm={submenuArmFor('recipes')} + orcaCloudAccess={orcaCloudAccess} connectingHostIds={connectingHostIds} canConnect={Boolean(onConnectHost)} canSetLocation={Boolean(onSetLocation)} onArm={(key, nextSubmenu) => { arm(key) - setSubmenu(nextSubmenu) + if (nextSubmenu === null) { + closeSubmenu() + } else if (submenu !== nextSubmenu) { + openSubmenu(nextSubmenu, false) + } }} - onRecipesOpenChange={(next) => setSubmenu(next ? 'recipes' : null)} + onRecipesOpenChange={(next) => + next ? openSubmenu('recipes', false) : closeSubmenu() + } onSelectHost={selectHost} onSelectRecipe={selectRecipe} + onSelectOrcaCloud={selectOrcaCloud} + onOrcaCloudBlockedAction={runOrcaCloudBlockedAction} onConnectHost={(option) => void connectHost(option)} onSetLocation={setLocation} /> @@ -299,29 +404,18 @@ export default function RunTargetCombobox({ {hasAddHost ? ( setSubmenu(next ? 'add-host' : null)} + onOpenChange={(next) => (next ? openSubmenu('add-host', false) : closeSubmenu())} armed={armedRow?.key === RUN_TARGET_ADD_HOST_KEY} optionId={armedRow?.key === RUN_TARGET_ADD_HOST_KEY ? `${listId}-armed` : undefined} + submenuArm={submenuArmFor('add-host')} onArm={() => { arm(RUN_TARGET_ADD_HOST_KEY) - setSubmenu('add-host') + if (submenu !== 'add-host') { + openSubmenu('add-host', false) + } }} - {...(onAddSshHost - ? { - onAddSshHost: () => { - close() - onAddSshHost() - } - } - : {})} - {...(onAddRemoteServer - ? { - onAddRemoteServer: () => { - close() - onAddRemoteServer() - } - } - : {})} + {...(addSshHost ? { onAddSshHost: addSshHost } : {})} + {...(addRemoteServer ? { onAddRemoteServer: addRemoteServer } : {})} /> ) : null} diff --git a/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx b/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx index e492811ac19..dc5e670b945 100644 --- a/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { ChevronRight } from 'lucide-react' +import { Check, ChevronRight } from 'lucide-react' import { cn } from '@/lib/utils' import { ProjectOptionDetail } from './ProjectComboboxRow' import { HostRowIcon } from '../host-row-icon' @@ -17,6 +17,8 @@ export function RunTargetRow({ dimmed = false, submenu = false, stacked = true, + labelBadge, + wrapDetail = false, onArm, onCommit, trailing @@ -36,14 +38,18 @@ export function RunTargetRow({ onArm: () => void onCommit: () => void trailing?: React.ReactNode + /** Stacked rows only: a small badge beside the label, keeping the detail line full width. */ + labelBadge?: React.ReactNode + /** Stacked rows only: plain copy that may wrap to two lines instead of path-eliding. */ + wrapDetail?: boolean }): React.JSX.Element { return (
event.preventDefault()} @@ -52,8 +58,7 @@ export function RunTargetRow({ className={cn( 'flex cursor-default gap-2 rounded-sm px-2 text-sm', stacked ? 'items-center py-1.5' : 'h-8 items-baseline', - armed && 'bg-accent text-accent-foreground', - current && !armed && 'bg-accent/60' + armed && 'bg-accent text-accent-foreground' )} > {stacked ? ( - {label} - {detail ? ( + + {label} + {labelBadge} + + {detail && wrapDetail ? ( + {detail} + ) : detail ? ( ) : null} @@ -94,6 +104,12 @@ export function RunTargetRow({ )} {trailing} + {/* The committed row gets a check, not a second fill, so only the armed row is shaded. */} + {current ? ( + + + + ) : null} {submenu ? ( diff --git a/src/renderer/src/components/new-workspace/RunTargetField.tsx b/src/renderer/src/components/new-workspace/RunTargetField.tsx index 463dacf5f73..9ff9d6836f8 100644 --- a/src/renderer/src/components/new-workspace/RunTargetField.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetField.tsx @@ -1,6 +1,6 @@ import { ImeInput } from '@/lib/ime-text-field' import React, { useState } from 'react' -import { ChevronDown, Cloud } from 'lucide-react' +import { Box, ChevronDown, Cloud } from 'lucide-react' import { PopoverAnchor } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -17,12 +17,12 @@ export default function RunTargetField({ onOpenRequest, onToggle, committed, - isRecipe, + recipeKind, hostId, label, detail, - listId, - hasArmedRow, + controlsId, + activeDescendantId, inputRef, onKeyDown }: { @@ -32,12 +32,14 @@ export default function RunTargetField({ onOpenRequest: () => void onToggle: () => void committed: boolean - isRecipe: boolean + /** A committed recipe selection; Orca Cloud keeps its own glyph. */ + recipeKind: 'orca-cloud' | 'recipe' | null hostId: ExecutionHostId | null label: string detail: string - listId: string - hasArmedRow: boolean + /** The main listbox id, plus an open submenu's listbox id. */ + controlsId: string + activeDescendantId: string | undefined inputRef: React.RefObject onKeyDown: (event: React.KeyboardEvent) => void }): React.JSX.Element { @@ -57,8 +59,10 @@ export default function RunTargetField({ > {committed ? ( - isRecipe ? ( + recipeKind === 'orca-cloud' ? ( + ) : recipeKind === 'recipe' ? ( + ) : hostId ? ( ) : null @@ -72,9 +76,9 @@ export default function RunTargetField({ data-run-target-combobox-root="true" aria-label={t('auto.components.new.workspace.RunTargetCombobox.label', 'Run on')} aria-expanded={open} - aria-controls={listId} + aria-controls={controlsId} aria-autocomplete="list" - aria-activedescendant={open && hasArmedRow ? `${listId}-armed` : undefined} + aria-activedescendant={open ? activeDescendantId : undefined} value={query} placeholder={ committed diff --git a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx new file mode 100644 index 00000000000..7f0766c3d32 --- /dev/null +++ b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx @@ -0,0 +1,179 @@ +import React from 'react' +import { Cloud } from 'lucide-react' +import { Badge } from '@/components/ui/badge' +import { buttonVariants } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import { RunTargetRow } from './RunTargetComboboxRow' +import { + getOrcaCloudDetail, + ORCA_CLOUD_LABEL, + type EphemeralVmRecipeOption +} from './run-target-options' +import { + formatOrcaCloudHoursLeft, + type OrcaCloudRunTargetAccess +} from './orca-cloud-run-target-access' + +const META = 'ml-2 shrink-0 self-center text-xs tabular-nums text-muted-foreground' + +/** + * Looks like a button but is plain option content: focus stays in the combobox input, Enter on the + * row runs the same action, and an option must not contain interactive descendants. + */ +function RowActionButton({ + label, + onAction +}: { + label: string + onAction: () => void +}): React.JSX.Element { + return ( + { + event.preventDefault() + event.stopPropagation() + }} + onClick={(event) => { + event.preventDefault() + event.stopPropagation() + onAction() + }} + > + {label} + + ) +} + +function OrcaCloudMeta({ + access, + onAction +}: { + access: OrcaCloudRunTargetAccess + onAction: () => void +}): React.JSX.Element | null { + const t = useTranslate() + switch (access.state) { + case 'entitled': + return ( + + {t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudHoursLeft', + '{{hours}} h left', + { + hours: formatOrcaCloudHoursLeft(access.remainingSeconds) + } + )} + + ) + case 'no-plan': + return ( + + ) + case 'out-of-hours': + return access.canManageBilling ? ( + + ) : ( + + {t('auto.components.new.workspace.RunTargetCombobox.orcaCloudNoHours', 'No hours left')} + + ) + case 'payment-issue': + return access.canManageBilling ? ( + + ) : ( + + {t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentFailed', + 'Payment failed' + )} + + ) + case 'signed-out': + return ( + + ) + case 'unknown': + return null + } +} + +/** Orca Cloud as a first-class Run-on target, with its hours or upsell trailing the row. */ +export function RunTargetOrcaCloudRow({ + recipe, + access, + armed, + current, + optionId, + onArm, + onSelect, + onBlockedAction +}: { + recipe: EphemeralVmRecipeOption | null + access: OrcaCloudRunTargetAccess + armed: boolean + current: boolean + optionId: string | undefined + onArm: () => void + onSelect: () => void + onBlockedAction: () => void +}): React.JSX.Element { + const t = useTranslate() + return ( + } + label={recipe?.name ?? ORCA_CLOUD_LABEL} + labelBadge={ + access.state === 'no-plan' ? ( + + {t('auto.components.new.workspace.RunTargetCombobox.orcaCloudTeamBadge', 'Team')} + + ) : undefined + } + detail={ + access.state === 'signed-out' + ? t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudSignIn', + 'Sign in to use Orca Cloud' + ) + : getOrcaCloudDetail(t) + } + wrapDetail + armed={armed} + current={current} + optionId={optionId} + onArm={onArm} + onCommit={onSelect} + trailing={} + /> + ) +} diff --git a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx index 355fd0439cc..80dbeed840a 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx @@ -5,7 +5,9 @@ import type { } from '@/lib/project-host-setup-options' import { HostRowIcon, RunTargetRow } from './RunTargetComboboxRow' import { ConnectHostButton, NeedsSetupHostIcon, SetLocationButton } from './RunTargetRowActions' -import { RecipesSubmenuRow } from './RunTargetSubmenus' +import { RecipesSubmenuRow, type RunTargetSubmenuArm } from './RunTargetSubmenus' +import { RunTargetOrcaCloudRow } from './RunTargetOrcaCloudRow' +import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' import type { EphemeralVmRecipeOption, RunTargetRowModel } from './run-target-options' /** The scrolling rows of the run-target picker; "Add host" is pinned outside this list. */ @@ -17,6 +19,8 @@ export default function RunTargetRowList({ selectedRecipeId, matchedRecipes, recipesOpen, + recipesSubmenuArm, + orcaCloudAccess, connectingHostIds, canConnect, canSetLocation, @@ -24,6 +28,8 @@ export default function RunTargetRowList({ onRecipesOpenChange, onSelectHost, onSelectRecipe, + onSelectOrcaCloud, + onOrcaCloudBlockedAction, onConnectHost, onSetLocation }: { @@ -35,6 +41,8 @@ export default function RunTargetRowList({ selectedRecipeId: string | null matchedRecipes: readonly EphemeralVmRecipeOption[] recipesOpen: boolean + recipesSubmenuArm: RunTargetSubmenuArm + orcaCloudAccess: OrcaCloudRunTargetAccess connectingHostIds: ReadonlySet canConnect: boolean canSetLocation: boolean @@ -43,6 +51,9 @@ export default function RunTargetRowList({ onRecipesOpenChange: (open: boolean) => void onSelectHost: (option: ReadyProjectHostSetupOption) => void onSelectRecipe: (recipeId: string) => void + onSelectOrcaCloud: (recipe: EphemeralVmRecipeOption | null) => void + /** Plans or billing, for an account that cannot start a sandbox. */ + onOrcaCloudBlockedAction: () => void onConnectHost: (option: NeedsSetupProjectHostOption) => void onSetLocation: (option: NeedsSetupProjectHostOption) => void }): React.JSX.Element { @@ -69,6 +80,21 @@ export default function RunTargetRowList({ /> ) } + if (row.kind === 'orca-cloud') { + return ( + onArm(row.key, null)} + onSelect={() => onSelectOrcaCloud(row.recipe)} + onBlockedAction={onOrcaCloudBlockedAction} + /> + ) + } if (row.kind === 'needs-setup') { const connecting = connectingHostIds.has(row.option.hostId) const hasConnect = Boolean(row.option.connectAction && canConnect) @@ -117,6 +143,7 @@ export default function RunTargetRowList({ optionId={optionId} recipes={matchedRecipes} selectedRecipeId={selectedRecipeId} + submenuArm={recipesSubmenuArm} onArm={() => onArm(row.key, 'recipes')} onSelectRecipe={onSelectRecipe} /> diff --git a/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx b/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx index 864f34dd663..dea4c0e66d9 100644 --- a/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { ChevronDown, Cloud, Plus, Server } from 'lucide-react' +import { Box, Boxes, ChevronDown, Network, Plus, Server } from 'lucide-react' import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' @@ -7,13 +7,29 @@ import { RunTargetRow } from './RunTargetComboboxRow' import { getEphemeralVmLabel, getRecipeDetail, + getRecipeSubmenuItemKey, RUN_TARGET_ADD_HOST_KEY, + RUN_TARGET_ADD_REMOTE_SERVER_ITEM, + RUN_TARGET_ADD_SSH_HOST_ITEM, type EphemeralVmRecipeOption } from './run-target-options' import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' const SUBMENU_CONTENT = cn('w-72 p-1', COMBOBOX_POPOVER_SURFACE) +/** Keyboard/pointer arm inside a submenu; the combobox input points `aria-activedescendant` at it. */ +export type RunTargetSubmenuArm = { + /** The submenu listbox id, so the input can list it in `aria-controls`. */ + listId: string + armedItemKey: string | null + armedItemId: string + onArmItem: (key: string | null) => void +} + +function itemId(arm: RunTargetSubmenuArm, key: string): string | undefined { + return arm.armedItemKey === key ? arm.armedItemId : undefined +} + /** The "Per-Workspace Environment" row and its nested recipe list. */ export function RecipesSubmenuRow({ open, @@ -22,6 +38,7 @@ export function RecipesSubmenuRow({ optionId, recipes, selectedRecipeId, + submenuArm, onArm, onSelectRecipe }: { @@ -31,24 +48,24 @@ export function RecipesSubmenuRow({ optionId: string | undefined recipes: readonly EphemeralVmRecipeOption[] selectedRecipeId: string | null + submenuArm: RunTargetSubmenuArm onArm: () => void onSelectRecipe: (recipeId: string) => void }): React.JSX.Element { const t = useTranslate() - const [hoveredKey, setHoveredKey] = React.useState(null) return (
} + icon={} label={getEphemeralVmLabel(t)} detail={t( - 'auto.components.NewWorkspaceComposerCard.perWorkspaceEnvHint', - 'Provision an on-demand environment from a recipe' + 'auto.components.NewWorkspaceComposerCard.customEnvironmentsHint', + 'Create a workspace from an orca.yaml recipe' )} armed={armed} - current={selectedRecipeId !== null} + current={selectedRecipeId !== null && recipes.some((r) => r.id === selectedRecipeId)} optionId={optionId} submenu onArm={onArm} @@ -63,25 +80,24 @@ export function RecipesSubmenuRow({ className={SUBMENU_CONTENT} onOpenAutoFocus={(event) => event.preventDefault()} > - {/* Nested rows own hover so pointer movement updates their highlight too. */} -
setHoveredKey(null)} - > - {recipes.map((recipe) => ( - } - label={recipe.name} - detail={getRecipeDetail(recipe, t)} - armed={hoveredKey === recipe.id} - current={recipe.id === selectedRecipeId} - optionId={undefined} - onArm={() => setHoveredKey(recipe.id)} - onCommit={() => onSelectRecipe(recipe.id)} - /> - ))} + {/* Hover arms like a native menu; leaving keeps the arm so keyboard users keep their place. */} +
+ {recipes.map((recipe) => { + const key = getRecipeSubmenuItemKey(recipe.id) + return ( + } + label={recipe.name} + detail={getRecipeDetail(recipe, t)} + armed={submenuArm.armedItemKey === key} + current={recipe.id === selectedRecipeId} + optionId={itemId(submenuArm, key)} + onArm={() => submenuArm.onArmItem(key)} + onCommit={() => onSelectRecipe(recipe.id)} + /> + ) + })}
@@ -94,6 +110,7 @@ export function AddHostSubmenuRow({ onOpenChange, armed, optionId, + submenuArm, onArm, onAddSshHost, onAddRemoteServer @@ -102,12 +119,12 @@ export function AddHostSubmenuRow({ onOpenChange: (open: boolean) => void armed: boolean optionId: string | undefined + submenuArm: RunTargetSubmenuArm onArm: () => void onAddSshHost?: () => void onAddRemoteServer?: () => void }): React.JSX.Element { const t = useTranslate() - const [hoveredKey, setHoveredKey] = React.useState(null) const addHostLabel = t('auto.components.NewWorkspaceComposerCard.addHost', 'Add host') return ( @@ -116,8 +133,8 @@ export function AddHostSubmenuRow({ role="option" id={optionId} aria-selected={armed} - // `option` supports aria-haspopup but not aria-expanded. - aria-haspopup="menu" + // `option` supports aria-haspopup but not aria-expanded; the submenu is a listbox. + aria-haspopup="listbox" data-armed={armed || undefined} data-run-target-add-host="true" onMouseDown={(event) => event.preventDefault()} @@ -144,7 +161,7 @@ export function AddHostSubmenuRow({ className={SUBMENU_CONTENT} onOpenAutoFocus={(event) => event.preventDefault()} > -
setHoveredKey(null)}> +
{onAddSshHost ? ( } @@ -153,30 +170,30 @@ export function AddHostSubmenuRow({ 'auto.components.NewWorkspaceComposerCard.addSshHostHint', 'Use an existing machine over SSH' )} - armed={hoveredKey === 'ssh'} + armed={submenuArm.armedItemKey === RUN_TARGET_ADD_SSH_HOST_ITEM} current={false} stacked - optionId={undefined} - onArm={() => setHoveredKey('ssh')} + optionId={itemId(submenuArm, RUN_TARGET_ADD_SSH_HOST_ITEM)} + onArm={() => submenuArm.onArmItem(RUN_TARGET_ADD_SSH_HOST_ITEM)} onCommit={onAddSshHost} /> ) : null} {onAddRemoteServer ? ( } + icon={} label={t( - 'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServer', - 'Add Remote Orca Server' + 'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServerSentence', + 'Add remote Orca server' )} detail={t( 'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServerHint', 'Pair another Orca runtime' )} - armed={hoveredKey === 'remote'} + armed={submenuArm.armedItemKey === RUN_TARGET_ADD_REMOTE_SERVER_ITEM} current={false} stacked - optionId={undefined} - onArm={() => setHoveredKey('remote')} + optionId={itemId(submenuArm, RUN_TARGET_ADD_REMOTE_SERVER_ITEM)} + onArm={() => submenuArm.onArmItem(RUN_TARGET_ADD_REMOTE_SERVER_ITEM)} onCommit={onAddRemoteServer} /> ) : null} diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx index 830ad898532..c1fb46a13a9 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx @@ -28,7 +28,7 @@ export function SmartWorkspaceSourceTabs({ { const previous = event.relatedTarget instanceof HTMLElement ? event.relatedTarget : null const list = event.currentTarget diff --git a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts b/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts index 9e80d89603c..06a5464c36b 100644 --- a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts +++ b/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts @@ -1,3 +1,4 @@ +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' import type { AgentPickerDraft, AgentPickerEntry @@ -69,6 +70,8 @@ export type NewWorkspaceComposerCardProps = { selectedEphemeralVmRecipeId?: string | null onEphemeralVmRecipeChange?: (recipeId: string | null) => void ephemeralVmRecipeError?: string | null + /** Orca Cloud for the selected project, from main; drives the picker's sign-in/upsell row. */ + orcaCloudAvailability?: OrcaCloudAvailability repoBackedSearchRepos?: readonly RepoOption[] repoBackedSourcesDisabled?: boolean allowSmartNameAddProject?: boolean diff --git a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts new file mode 100644 index 00000000000..10618b031f6 --- /dev/null +++ b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts @@ -0,0 +1,91 @@ +import { useMemo } from 'react' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' +import { useOrcaBillingStatus } from '@/components/billing/use-orca-billing-status' +import { openPlansPage } from '@/components/billing/plans/plans-page-store' +import { useAppStore } from '@/store/index' + +/** + * What the Run-on picker knows about the account's Orca Cloud access. + * - `unknown`: still loading, signed out, or billing unreachable; selection stays allowed and the build reports. + * - `signed-out`: the build offers Orca Cloud but nobody is signed in; picking starts sign-in. + * - `entitled`: can start a sandbox; `remainingSeconds` is the included time left this window. + * - `no-plan`: no active Team subscription (`lapsed` when one existed); routes to the plans page. + * - `out-of-hours`: included hours (and any overage cap) are spent; routes to plan & billing settings. + * - `payment-issue`: a failed payment blocks new starts; routes to plan & billing settings. + */ +export type OrcaCloudRunTargetAccess = + | { state: 'unknown' } + | { state: 'signed-out' } + | { state: 'entitled'; remainingSeconds: number } + | { state: 'no-plan'; lapsed: boolean } + | { state: 'out-of-hours'; canManageBilling: boolean } + | { state: 'payment-issue'; canManageBilling: boolean } + +export const UNKNOWN_ORCA_CLOUD_ACCESS: OrcaCloudRunTargetAccess = { state: 'unknown' } + +export function toOrcaCloudRunTargetAccess( + result: OrcaBillingStatusResult | null +): OrcaCloudRunTargetAccess { + if (result?.status !== 'ok') { + return UNKNOWN_ORCA_CLOUD_ACCESS + } + const { entitlement } = result + if (entitlement.canStartSandbox) { + return { + state: 'entitled', + remainingSeconds: Math.max(0, entitlement.remainingIncludedSeconds) + } + } + const { canManageBilling } = entitlement + switch (entitlement.reason) { + case 'included_hours_exhausted': + case 'overage_cap_reached': + return { state: 'out-of-hours', canManageBilling } + case 'payment_past_due': + case 'payment_grace_expired': + return { state: 'payment-issue', canManageBilling } + case 'subscription_inactive': + return { state: 'no-plan', lapsed: true } + default: + return { state: 'no-plan', lapsed: false } + } +} + +/** + * Where a blocked account goes instead of a build that would only fail, or null when picking may + * proceed. Plans for no plan; plan & billing settings (overage, payment) otherwise. + */ +export function orcaCloudBlockedAction(access: OrcaCloudRunTargetAccess): (() => void) | null { + switch (access.state) { + case 'signed-out': + return () => void useAppStore.getState().connectCurrentOrcaProfile() + case 'no-plan': + return () => openPlansPage('sandbox') + case 'out-of-hours': + case 'payment-issue': + return openPlanBillingSettings + default: + return null + } +} + +function openPlanBillingSettings(): void { + const state = useAppStore.getState() + state.openSettingsTarget({ pane: 'orca-account', repoId: null }) + state.openSettingsPage() +} + +/** Whole hours from 10 up, one decimal below so the last hours stay legible. */ +export function formatOrcaCloudHoursLeft(remainingSeconds: number): string { + const hours = remainingSeconds / 3600 + if (hours >= 10) { + return String(Math.floor(hours)) + } + return (Math.floor(hours * 10) / 10).toFixed(1) +} + +/** Reads billing only while `enabled` (picker open with Orca Cloud on offer), so composing never polls it. */ +export function useOrcaCloudRunTargetAccess(enabled: boolean): OrcaCloudRunTargetAccess { + const { result } = useOrcaBillingStatus(enabled) + return useMemo(() => toOrcaCloudRunTargetAccess(result), [result]) +} diff --git a/src/renderer/src/components/new-workspace/run-target-keyboard.ts b/src/renderer/src/components/new-workspace/run-target-keyboard.ts new file mode 100644 index 00000000000..83fed933575 --- /dev/null +++ b/src/renderer/src/components/new-workspace/run-target-keyboard.ts @@ -0,0 +1,76 @@ +import type { RunTargetRowModel, RunTargetSubmenu } from './run-target-options' + +export type RunTargetKeyboardState = { + open: boolean + query: string + submenu: RunTargetSubmenu | null + /** Non-null once keyboard (or pointer) focus has moved into the open submenu. */ + armedItemKey: string | null + armedRow: RunTargetRowModel | null +} + +export type RunTargetKeyboardActions = { + setOpen: (open: boolean) => void + moveArm: (step: number) => void + moveItemArm: (step: number) => void + activate: (key: string | null) => void + commitSubmenuItem: (key: string) => void + closeSubmenu: () => void + close: () => void +} + +/** + * Listbox-with-submenus keys for the Run-on input: Up/Down move within whichever list holds the + * arm, Enter commits it, Right/Enter on a submenu row moves into it, Left/Escape back out. + */ +export function handleRunTargetKeyDown( + event: Pick, + state: RunTargetKeyboardState, + actions: RunTargetKeyboardActions +): void { + const { open, query, submenu, armedItemKey, armedRow } = state + const inSubmenu = submenu !== null && armedItemKey !== null + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault() + const step = event.key === 'ArrowDown' ? 1 : -1 + if (inSubmenu) { + actions.moveItemArm(step) + return + } + actions.setOpen(true) + actions.moveArm(step) + actions.closeSubmenu() + return + } + if (event.key === 'Enter' && open) { + event.preventDefault() + if (inSubmenu) { + actions.commitSubmenuItem(armedItemKey) + return + } + actions.activate(armedRow?.key ?? null) + return + } + // Left/Right still move the caret unless they cross a submenu boundary. + const armedOpensSubmenu = armedRow?.kind === 'recipes' || armedRow?.kind === 'add-host' + if (event.key === 'ArrowRight' && open && !inSubmenu && armedOpensSubmenu) { + event.preventDefault() + actions.activate(armedRow.key) + return + } + if (event.key === 'ArrowLeft' && inSubmenu) { + event.preventDefault() + actions.closeSubmenu() + return + } + if (event.key === 'Escape' && (open || query.length > 0)) { + event.preventDefault() + event.stopPropagation() + // Escape backs out one level: out of a keyboard-entered submenu first, then the list. + if (inSubmenu) { + actions.closeSubmenu() + return + } + actions.close() + } +} diff --git a/src/renderer/src/components/new-workspace/run-target-options.ts b/src/renderer/src/components/new-workspace/run-target-options.ts index bbbfee753a7..e575bc80ba4 100644 --- a/src/renderer/src/components/new-workspace/run-target-options.ts +++ b/src/renderer/src/components/new-workspace/run-target-options.ts @@ -1,4 +1,5 @@ import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { getProjectHostSetupSelectionKey, type NeedsSetupProjectHostOption, @@ -13,16 +14,52 @@ export type EphemeralVmRecipeOption = NonNullable recipe.id === selectedEphemeralVmRecipeId) + return selected ? isOrcaCloudRecipe(selected) : false +} + +export function getOrcaCloudDetail(t: Translate = translate): string { + return t( + 'auto.components.new.workspace.RunTargetCombobox.orcaCloudDetail', + // Non-breaking spaces keep each number with its unit when the row wraps. + 'Hosted sandbox · 4\u00a0vCPU\u00a0/\u00a08\u00a0GB' + ) } export function getRecipeCommandDisplay(command: string): string { @@ -45,6 +82,9 @@ export function getRecipeDestroyLabel( } export function getRecipeDetail(recipe: EphemeralVmRecipeOption, t?: Translate): string { + if (isOrcaCloudRecipe(recipe)) { + return getOrcaCloudDetail(t) + } // Built-in providers run in-process; their lifecycle strings are labels, not commands to show. if (recipe.provider && recipe.description) { return recipe.description @@ -52,6 +92,21 @@ export function getRecipeDetail(recipe: EphemeralVmRecipeOption, t?: Translate): return `${getRecipeCommandDisplay(recipe.create)} · ${getRecipeDestroyLabel(recipe, t)}` } +export function getRunTargetHostRowKey(option: ReadyProjectHostSetupOption): string { + return `host:${getProjectHostSetupSelectionKey(option)}` +} + +/** The row that holds the committed selection, armed when the picker opens. */ +export function getRunTargetCurrentRowKey( + selectedRecipe: EphemeralVmRecipeOption | null, + selectedHost: ReadyProjectHostSetupOption | null +): string | null { + if (selectedRecipe) { + return isOrcaCloudRecipe(selectedRecipe) ? RUN_TARGET_ORCA_CLOUD_KEY : RUN_TARGET_RECIPES_KEY + } + return selectedHost ? getRunTargetHostRowKey(selectedHost) : null +} + function matches(haystack: string, query: string): boolean { return haystack.toLowerCase().includes(query) } @@ -60,7 +115,11 @@ function matches(haystack: string, query: string): boolean { function buildHostRows( hostOptions: readonly ProjectHostSetupOption[], query: string -): { rows: RunTargetRowModel[]; hiddenHostCount: number } { +): { + readyRows: RunTargetRowModel[] + needsSetupRows: RunTargetRowModel[] + hiddenHostCount: number +} { const hostMatches = (option: ProjectHostSetupOption): boolean => query === '' || matches(option.label, query) || @@ -86,19 +145,19 @@ function buildHostRows( // Why the query again: ranks an exact name first so typing it always reaches the host. { query } ) - const rows: RunTargetRowModel[] = [ - ...ready.map((option) => ({ - key: `host:${getProjectHostSetupSelectionKey(option)}`, + return { + readyRows: ready.map((option) => ({ + key: getRunTargetHostRowKey(option), kind: 'ready' as const, option })), - ...needsSetup.shown.map(({ id, option }) => ({ + needsSetupRows: needsSetup.shown.map(({ id, option }) => ({ key: `needs:${id}`, kind: 'needs-setup' as const, option - })) - ] - return { rows, hiddenHostCount: needsSetup.hiddenCount } + })), + hiddenHostCount: needsSetup.hiddenCount + } } function matchRecipes( @@ -115,6 +174,24 @@ function matchRecipes( ) } +export const ORCA_CLOUD_LABEL = 'Orca Cloud' + +function matchOrcaCloud( + recipes: readonly EphemeralVmRecipeOption[], + offerWithoutRecipe: boolean, + query: string, + t?: Translate +): { recipe: EphemeralVmRecipeOption | null } | null { + const recipe = recipes.find(isOrcaCloudRecipe) ?? null + if (!recipe && !offerWithoutRecipe) { + return null + } + if (query !== '' && !matches(ORCA_CLOUD_LABEL, query) && !matches(getOrcaCloudDetail(t), query)) { + return null + } + return { recipe } +} + function buildSubmenuRows(hasRecipes: boolean, hasAddHost: boolean): RunTargetRowModel[] { const rows: RunTargetRowModel[] = [] if (hasRecipes) { @@ -126,18 +203,47 @@ function buildSubmenuRows(hasRecipes: boolean, hasAddHost: boolean): RunTargetRo return rows } +/** Keys of a submenu's rows in display order, for keyboard arming. */ +export function getRunTargetSubmenuItemKeys( + submenu: RunTargetSubmenu, + { + matchedRecipes, + hasAddSshHost, + hasAddRemoteServer + }: { + matchedRecipes: readonly EphemeralVmRecipeOption[] + hasAddSshHost: boolean + hasAddRemoteServer: boolean + } +): string[] { + if (submenu === 'recipes') { + return matchedRecipes.map((recipe) => getRecipeSubmenuItemKey(recipe.id)) + } + return [ + ...(hasAddSshHost ? [RUN_TARGET_ADD_SSH_HOST_ITEM] : []), + ...(hasAddRemoteServer ? [RUN_TARGET_ADD_REMOTE_SERVER_ITEM] : []) + ] +} + +export function getRecipeSubmenuItemKey(recipeId: string): string { + return `recipe:${recipeId}` +} + /** Filter host/recipe rows but always keep Add host reachable; other submenus require matching contents. */ export function buildRunTargetRows( { hostOptions, recipes, query, - hasAddHost + hasAddHost, + orcaCloudOffered = false }: { hostOptions: readonly ProjectHostSetupOption[] recipes: readonly EphemeralVmRecipeOption[] query: string hasAddHost: boolean + /** Show the Orca Cloud row (sign-in or upsell) even when the account has no Orca Cloud recipe. */ + orcaCloudOffered?: boolean }, t?: Translate ): { @@ -147,10 +253,30 @@ export function buildRunTargetRows( hiddenHostCount: number } { const trimmed = query.trim().toLowerCase() - const matchedRecipes = matchRecipes(recipes, trimmed, t) + // Orca Cloud is a first-class target, so it never also appears inside the recipe submenu. + const orcaCloud = matchOrcaCloud(recipes, orcaCloudOffered, trimmed, t) + const matchedRecipes = matchRecipes( + recipes.filter((recipe) => !isOrcaCloudRecipe(recipe)), + trimmed, + t + ) const hostRows = buildHostRows(hostOptions, trimmed) + const isLocalRow = (row: RunTargetRowModel): boolean => + row.kind === 'ready' && row.option.hostId === LOCAL_EXECUTION_HOST_ID const rows: RunTargetRowModel[] = [ - ...hostRows.rows, + ...hostRows.readyRows.filter(isLocalRow), + // Right under this machine, so it never scrolls away behind a long host list. + ...(orcaCloud + ? [ + { + key: RUN_TARGET_ORCA_CLOUD_KEY, + kind: 'orca-cloud', + recipe: orcaCloud.recipe + } satisfies RunTargetRowModel + ] + : []), + ...hostRows.readyRows.filter((row) => !isLocalRow(row)), + ...hostRows.needsSetupRows, ...buildSubmenuRows(matchedRecipes.length > 0, hasAddHost) ] return { rows, matchedRecipes, hiddenHostCount: hostRows.hiddenHostCount } diff --git a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts new file mode 100644 index 00000000000..e4ec6523643 --- /dev/null +++ b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts @@ -0,0 +1,77 @@ +import { useCallback } from 'react' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import { isOrcaCloudRecipe, type EphemeralVmRecipeOption } from './run-target-options' +import { + orcaCloudBlockedAction, + useOrcaCloudRunTargetAccess, + type OrcaCloudRunTargetAccess +} from './orca-cloud-run-target-access' + +/** + * The Orca Cloud row's access when main sent no Orca Cloud recipe: signed-out and unentitled + * accounts still see the row, to sign in or upgrade. Null means no recipe-less row. + */ +export function getRunTargetOrcaCloudOffer({ + recipes, + availability, + override +}: { + recipes: readonly EphemeralVmRecipeOption[] + availability: OrcaCloudAvailability + override: OrcaCloudRunTargetAccess | undefined +}): OrcaCloudRunTargetAccess | null { + if (recipes.some(isOrcaCloudRecipe)) { + return null + } + switch (availability) { + case 'needs-sign-in': + return override ?? { state: 'signed-out' } + case 'needs-capability': + return override ?? { state: 'no-plan', lapsed: false } + default: + return null + } +} + +/** Resolves the row's access and routes picks: a blocked account goes to sign-in, plans or billing. */ +export function useRunTargetOrcaCloud({ + recipes, + offer, + override, + open, + close, + selectRecipe +}: { + recipes: readonly EphemeralVmRecipeOption[] + offer: OrcaCloudRunTargetAccess | null + override: OrcaCloudRunTargetAccess | undefined + open: boolean + close: () => void + selectRecipe: (recipeId: string) => void +}): { + access: OrcaCloudRunTargetAccess + runBlockedAction: () => void + select: (recipe: EphemeralVmRecipeOption | null) => void +} { + const fetched = useOrcaCloudRunTargetAccess(open && !override && recipes.some(isOrcaCloudRecipe)) + const access = offer ?? override ?? fetched + const blocked = orcaCloudBlockedAction(access) + const runBlockedAction = useCallback((): void => { + close() + blocked?.() + }, [blocked, close]) + // A blocked account would only get a failing build, so route it instead of selecting. + const select = useCallback( + (recipe: EphemeralVmRecipeOption | null): void => { + if (blocked) { + runBlockedAction() + return + } + if (recipe) { + selectRecipe(recipe.id) + } + }, + [blocked, runBlockedAction, selectRecipe] + ) + return { access, runBlockedAction, select } +} diff --git a/src/renderer/src/components/new-workspace/use-run-target-submenu.ts b/src/renderer/src/components/new-workspace/use-run-target-submenu.ts new file mode 100644 index 00000000000..111b6ef88c8 --- /dev/null +++ b/src/renderer/src/components/new-workspace/use-run-target-submenu.ts @@ -0,0 +1,66 @@ +import { useCallback, useMemo, useState } from 'react' +import type { RunTargetSubmenu } from './run-target-options' + +/** + * Which submenu is open and which of its rows holds the keyboard arm. A null arm means focus is + * still on the parent row (hover-opened); arrow keys then keep moving the main list. + */ +export function useRunTargetSubmenu( + itemKeysFor: (submenu: RunTargetSubmenu) => readonly string[] +): { + submenu: RunTargetSubmenu | null + armedItemKey: string | null + /** `armFirst` moves keyboard focus into the submenu, as Enter/ArrowRight do. */ + openSubmenu: (submenu: RunTargetSubmenu, armFirst: boolean) => void + closeSubmenu: () => void + armItem: (key: string | null) => void + /** Moves the arm by `step`, wrapping like a native menu. */ + moveItemArm: (step: number) => void +} { + const [state, setState] = useState<{ submenu: RunTargetSubmenu | null; armed: string | null }>({ + submenu: null, + armed: null + }) + const keys = useMemo( + () => (state.submenu ? itemKeysFor(state.submenu) : []), + [itemKeysFor, state.submenu] + ) + // A filtered-away arm reads as no arm rather than pointing at a missing row. + const armedItemKey = state.armed !== null && keys.includes(state.armed) ? state.armed : null + + const openSubmenu = useCallback( + (submenu: RunTargetSubmenu, armFirst: boolean): void => { + setState({ submenu, armed: armFirst ? (itemKeysFor(submenu)[0] ?? null) : null }) + }, + [itemKeysFor] + ) + // Unchanged state returns the same object so per-mousemove calls never re-render the picker. + const closeSubmenu = useCallback( + (): void => + setState((current) => + current.submenu === null && current.armed === null + ? current + : { submenu: null, armed: null } + ), + [] + ) + const armItem = useCallback( + (key: string | null): void => + setState((current) => (current.armed === key ? current : { ...current, armed: key })), + [] + ) + const moveItemArm = useCallback( + (step: number): void => { + if (keys.length === 0) { + return + } + const index = armedItemKey === null ? -1 : keys.indexOf(armedItemKey) + const next = + index === -1 ? (step > 0 ? 0 : keys.length - 1) : (index + step + keys.length) % keys.length + armItem(keys[next] ?? null) + }, + [armItem, armedItemKey, keys] + ) + + return { submenu: state.submenu, armedItemKey, openSubmenu, closeSubmenu, armItem, moveItemArm } +} diff --git a/src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts b/src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts index 1cb08cfd473..d16eee1185f 100644 --- a/src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts +++ b/src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts @@ -2,7 +2,11 @@ import React, { useCallback, useMemo, useRef, useState } from 'react' import { useWheelScrollable } from './use-wheel-scrollable' /** Track selection by row key and query so late host lists cannot retarget a keypress; clear queries on close to restore the committed display. */ -export function useTypeAheadCombobox(deriveRowKeys: (query: string) => readonly string[]): { +export function useTypeAheadCombobox( + deriveRowKeys: (query: string) => readonly string[], + /** Row armed before any key or hover, while the query is empty (e.g. the committed choice). */ + initialKey: string | null = null +): { query: string setQuery: (value: string) => void open: boolean @@ -32,7 +36,8 @@ export function useTypeAheadCombobox(deriveRowKeys: (query: string) => readonly // A stale arm (aimed at an earlier query) falls back to the first row. const armedKey = armed !== null && armed.query === query ? armed.key : null - const armedIndex = Math.max(armedKey === null ? -1 : rowKeys.indexOf(armedKey), 0) + const fallbackKey = query === '' ? initialKey : null + const armedIndex = Math.max(rowKeys.indexOf(armedKey ?? fallbackKey ?? ''), 0) const resolvedKey = rowKeys[armedIndex] ?? null React.useEffect(() => { diff --git a/src/renderer/src/components/sidebar/account-menu/SidebarHelpSubmenu.tsx b/src/renderer/src/components/sidebar/account-menu/SidebarHelpSubmenu.tsx index fc9e95a4fff..c684d3bea6a 100644 --- a/src/renderer/src/components/sidebar/account-menu/SidebarHelpSubmenu.tsx +++ b/src/renderer/src/components/sidebar/account-menu/SidebarHelpSubmenu.tsx @@ -149,12 +149,12 @@ export function SidebarHelpSubmenu({ - {t('auto.components.sidebar.SidebarSettingsHelpMenu.e565171a7c', 'Keyboard Shortcuts')} + {t('auto.components.sidebar.SidebarSettingsHelpMenu.e565171a7c', 'Keyboard shortcuts')} - {t('auto.components.sidebar.SidebarSettingsHelpMenu.4cf5b868d7', 'Send Feedback')} + {t('auto.components.sidebar.SidebarSettingsHelpMenu.4cf5b868d7', 'Send feedback')} {milestones ? ( @@ -219,7 +219,7 @@ export function SidebarHelpSubmenu({ ) : ( )} - {t('auto.components.sidebar.SidebarSettingsHelpMenu.29c56f30ee', 'Check for Updates')} + {t('auto.components.sidebar.SidebarSettingsHelpMenu.29c56f30ee', 'Check for updates')} diff --git a/src/renderer/src/hooks/composer-state/composer-card-contract.ts b/src/renderer/src/hooks/composer-state/composer-card-contract.ts index 3f69c579e46..b0bffeec100 100644 --- a/src/renderer/src/hooks/composer-state/composer-card-contract.ts +++ b/src/renderer/src/hooks/composer-state/composer-card-contract.ts @@ -13,6 +13,7 @@ export type ComposerCardSourceProps = Pick< | 'ephemeralVmRecipes' | 'selectedEphemeralVmRecipeId' | 'ephemeralVmRecipeError' + | 'orcaCloudAvailability' | 'name' | 'branchNameOverride' | 'parentWorktreeId' diff --git a/src/renderer/src/hooks/composer-state/composer-card-props.ts b/src/renderer/src/hooks/composer-state/composer-card-props.ts index d68bbdf09ba..af16b04cb47 100644 --- a/src/renderer/src/hooks/composer-state/composer-card-props.ts +++ b/src/renderer/src/hooks/composer-state/composer-card-props.ts @@ -36,6 +36,7 @@ export function buildComposerCardProps(state: ComposerModel) { ephemeralVmRecipeError, ephemeralVmRecipes, ephemeralVmsEnabled, + orcaCloudAvailability, filteredLinkItems, folderDetectedAgentIds, folderSourceRepos, @@ -161,6 +162,7 @@ export function buildComposerCardProps(state: ComposerModel) { selectedEphemeralVmRecipeId: isProjectGroupTarget || !ephemeralVmsEnabled ? null : selectedEphemeralVmRecipeId, onEphemeralVmRecipeChange: setSelectedEphemeralVmRecipeId, + orcaCloudAvailability, ephemeralVmRecipeError: isProjectGroupTarget || !ephemeralVmsEnabled ? null : ephemeralVmRecipeError, repoBackedSearchRepos: isProjectGroupTarget ? folderSourceRepos : undefined, diff --git a/src/renderer/src/hooks/composer-state/runtime-target-model.ts b/src/renderer/src/hooks/composer-state/runtime-target-model.ts index e6a7f51b8b3..2b9f5a2647f 100644 --- a/src/renderer/src/hooks/composer-state/runtime-target-model.ts +++ b/src/renderer/src/hooks/composer-state/runtime-target-model.ts @@ -1,3 +1,4 @@ +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import type { RefObject } from 'react' import type { ExecutionHostId, ParsedExecutionHost } from '../../../../shared/execution-host' @@ -52,6 +53,8 @@ export type ComposerRuntimeTargetModel = { selectedRecipeRepoId: string | null selectedRecipeRepoConnectionId: string | null ephemeralVmsEnabled: boolean + /** Orca Cloud for this project, from main; drives the picker's sign-in/upsell row. */ + orcaCloudAvailability: OrcaCloudAvailability ephemeralVmRecipes: OrcaVmRecipe[] selectedEphemeralVmRecipeId: string | null setSelectedEphemeralVmRecipeId: (recipeId: string | null) => void diff --git a/src/renderer/src/hooks/composer-state/runtime-target-selection.ts b/src/renderer/src/hooks/composer-state/runtime-target-selection.ts index c2fa25817ac..5fb44294462 100644 --- a/src/renderer/src/hooks/composer-state/runtime-target-selection.ts +++ b/src/renderer/src/hooks/composer-state/runtime-target-selection.ts @@ -251,16 +251,18 @@ export function useComposerRuntimeTargetSelection(input: ComposerRuntimeTargetSe const selectedRecipeRepoConnectionId = selectedRepo?.connectionId ?? null - // Only probe enabled experiments or hidden features can raise setup errors. - const ephemeralVmsEnabled = settings?.experimentalEphemeralVms === true - const { recipes: ephemeralVmRecipes, selectedRecipeId: selectedEphemeralVmRecipeId, setSelectedRecipeId: setSelectedEphemeralVmRecipeId, - error: ephemeralVmRecipeError + error: ephemeralVmRecipeError, + offered: ephemeralVmsEnabled, + orcaCloud: orcaCloudAvailability } = useEphemeralVmRecipeOptions({ - enabled: ephemeralVmsEnabled, + // Always load: Orca Cloud is gated by the account's sandbox capability in main, not this flag. + enabled: true, + // Only probe enabled experiments or hidden features can raise setup errors. + customRecipesEnabled: settings?.experimentalEphemeralVms === true, repoId: selectedRecipeRepoId, repoIsGit: selectedRepoIsGit, repoConnectionId: selectedRecipeRepoConnectionId, @@ -328,6 +330,7 @@ export function useComposerRuntimeTargetSelection(input: ComposerRuntimeTargetSe selectedRecipeRepoId, selectedRecipeRepoConnectionId, ephemeralVmsEnabled, + orcaCloudAvailability, ephemeralVmRecipes, selectedEphemeralVmRecipeId, setSelectedEphemeralVmRecipeId, diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx index 7e7d56051a0..62aeb7bed29 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx @@ -4,6 +4,7 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' import { useEphemeralVmRecipeOptions } from './useEphemeralVmRecipeOptions' +import { useAppStore } from '@/store' globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -60,15 +61,18 @@ function Harness({ repoId, initialRecipeId, enabled = true, + customRecipesEnabled = true, repoExecutionHostId = 'local' }: { repoId: string initialRecipeId?: string enabled?: boolean + customRecipesEnabled?: boolean repoExecutionHostId?: 'local' | `runtime:${string}` }): React.JSX.Element { const state = useEphemeralVmRecipeOptions({ enabled, + customRecipesEnabled, repoId, repoIsGit: true, repoConnectionId: null, @@ -141,6 +145,59 @@ describe('useEphemeralVmRecipeOptions', () => { expect(container.textContent).not.toContain('stale-project') }) + it('offers only Orca Cloud, without recipe diagnostics, while custom recipes are off', async () => { + installApi( + vi.fn().mockResolvedValue({ + status: 'error', + repoPath: '/repo', + diagnostics: [{ index: 0, field: 'create', message: 'missing' }], + message: 'orca.yaml is invalid', + recipes: [ + { id: 'cloud', name: 'Orca Cloud', provider: 'orca-cloud', create: 'orca-cloud create' }, + { id: 'devbox', name: 'devbox', create: './create.sh' } + ] + }) + ) + const { container } = await render() + + await vi.waitFor(() => + expect(container.querySelector('[data-testid="recipes"]')?.textContent).toBe('cloud') + ) + expect(container.querySelector('[data-testid="error"]')?.textContent).toBe('none') + }) + + it('reloads when the account signs in, so Orca Cloud appears without switching projects', async () => { + const listRecipes = vi + .fn() + .mockResolvedValueOnce({ ...result([]), orcaCloud: 'needs-sign-in' }) + .mockResolvedValueOnce({ + ...result([]), + recipes: [ + { id: 'cloud', name: 'Orca Cloud', provider: 'orca-cloud', create: 'orca-cloud create' } + ], + orcaCloud: 'offered' + }) + installApi(listRecipes) + const { container } = await render() + await vi.waitFor(() => expect(listRecipes).toHaveBeenCalledTimes(1)) + + await act(async () => + useAppStore.setState({ + orcaProfileAuthStatus: { + activeProfileId: 'p', + configured: true, + state: 'connected', + persistence: 'encrypted', + capabilities: { flags: { sandbox: true }, refreshedAt: 1 } + } + }) + ) + + await vi.waitFor(() => + expect(container.querySelector('[data-testid="recipes"]')?.textContent).toBe('cloud') + ) + }) + it('does not send a paired-runtime repo id to local recipe discovery', async () => { const listRecipes = vi.fn().mockResolvedValue({ status: 'error', diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts index 97750798d9e..461bb5e083c 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.ts @@ -1,12 +1,15 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import type { OrcaVmRecipe } from '../../../shared/orca-yaml-hook-types' +import type { OrcaCloudAvailability, OrcaVmRecipe } from '../../../shared/orca-yaml-hook-types' +import { useAppStore } from '@/store' import type { EphemeralVmFailure } from '../../../shared/ephemeral-vm-failure-copy' import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' type EphemeralVmRecipeOptionsArgs = { enabled: boolean + /** Off: only built-in Orca Cloud is offered, and orca.yaml recipe diagnostics stay hidden. */ + customRecipesEnabled: boolean repoId: string | null repoIsGit: boolean repoConnectionId: string | null @@ -20,11 +23,16 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): selectedRecipeId: string | null setSelectedRecipeId: (recipeId: string | null) => void error: string | null + /** Recipes may be picked: custom recipes are on, or the list holds Orca Cloud (all a flag-off list can hold). */ + offered: boolean + /** Orca Cloud for this target as main reports it; `unavailable` where recipe VMs can't run. */ + orcaCloud: OrcaCloudAvailability } { const [recipes, setRecipes] = useState([]) const [selectedRecipeId, setSelectedRecipeId] = useState(null) // Failures stay coded until render so a language switch relocalizes them. const [errors, setErrors] = useState([]) + const [orcaCloud, setOrcaCloud] = useState('unavailable') const requestGeneration = useRef(0) const canLoad = args.enabled && @@ -51,8 +59,12 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): if (generation !== requestGeneration.current) { return } - const nextRecipes = result.recipes ?? [] + // Orca Cloud rides its account capability, not the experimental VM-recipes flag. + const nextRecipes = (result.recipes ?? []).filter( + (recipe) => args.customRecipesEnabled || recipe.provider === 'orca-cloud' + ) setRecipes(nextRecipes) + setOrcaCloud(result.orcaCloud ?? 'unavailable') setSelectedRecipeId((current) => { if (resetSelection) { return args.initialRecipeId && @@ -67,6 +79,10 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): const fieldLabel = diagnostic.field ? `.${diagnostic.field}` : '' return { error: `${recipeLabel}${fieldLabel}: ${diagnostic.message}` } }) + if (!args.customRecipesEnabled) { + setErrors([]) + return + } setErrors([ ...(result.status === 'error' && result.message ? [ @@ -86,10 +102,14 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): } setRecipes([]) setSelectedRecipeId(null) - setErrors([{ error: cause instanceof Error ? cause.message : String(cause) }]) + setErrors( + args.customRecipesEnabled + ? [{ error: cause instanceof Error ? cause.message : String(cause) }] + : [] + ) }) }, - [args.initialRecipeId, args.repoId, canLoad] + [args.customRecipesEnabled, args.initialRecipeId, args.repoId, canLoad] ) useEffect(() => { @@ -99,6 +119,20 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): } }, [load]) + // Signing in or out, or a capability change, adds or drops the Orca Cloud recipe in main. + const authKey = useAppStore((state) => { + const status = state.orcaProfileAuthStatus + return `${status?.state ?? 'none'}:${status?.capabilities?.flags.sandbox === true}` + }) + const lastAuthKey = useRef(authKey) + useEffect(() => { + if (lastAuthKey.current === authKey) { + return + } + lastAuthKey.current = authKey + load(false) + }, [authKey, load]) + useEffect(() => { if (!window.api.plugins?.onChanged) { return @@ -112,5 +146,12 @@ export function useEphemeralVmRecipeOptions(args: EphemeralVmRecipeOptionsArgs): useUiLanguageRevision() const error = errors.map(ephemeralVmErrorText).filter(Boolean).join('\n') || null - return { recipes, selectedRecipeId, setSelectedRecipeId, error } + return { + recipes, + selectedRecipeId, + setSelectedRecipeId, + error, + offered: args.customRecipesEnabled || recipes.length > 0, + orcaCloud: canLoad ? orcaCloud : 'unavailable' + } } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 3d265637c65..8e0d0f7bda3 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -92,6 +92,11 @@ "resumingCount_one": "Resuming {{count}} chat", "resumingCount_other": "Resuming {{count}} chats" }, + "NewWorkspaceComposerCard": { + "addRemoteOrcaServer": "Add Remote Orca Server", + "ephemeralVm": "Per-Workspace Environment", + "perWorkspaceEnvHint": "Provision an on-demand environment from a recipe" + }, "PullRequestPage": { "filesViewed_one": "{{viewed}} / {{count}} file viewed", "filesViewed_other": "{{viewed}} / {{count}} files viewed" @@ -344,6 +349,13 @@ } } }, + "new": { + "workspace": { + "RunTargetCombobox": { + "orcaCloudPaymentIssue": "Payment issue" + } + } + }, "onboarding": { "AgentStep": { "showMoreAgents_one": "Show {{count}} more agent →", @@ -862,6 +874,9 @@ "moreChildren_one": "+{{count}} more", "moreChildren_other": "+{{count}} more" }, + "FolderWorkspaceComposerDialog": { + "title": "Create Folder Workspace" + }, "HostRemoveDialog": { "alsoRemoveWorkspaces_one": "Also remove this workspace from Orca", "alsoRemoveWorkspaces_other": "Also remove these {{count}} workspaces from Orca", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 1644cc53a9c..ccc0b155a21 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2843,7 +2843,10 @@ "runCommandsNow": "Run commands now", "skipForNow": "Skip for now", "skipCommands": "Skip commands", - "connectProject": "Connect {{name}}" + "connectProject": "Connect {{name}}", + "customEnvironmentsHint": "Create a workspace from an orca.yaml recipe", + "addRemoteOrcaServerSentence": "Add remote Orca server", + "customEnvironments": "Custom environments" }, "NewWorkspaceComposerModal": { "createWorktree": "Create worktree", @@ -6602,13 +6605,13 @@ }, "SidebarSettingsHelpMenu": { "ad3d3ed7f1": "Restart Orca", - "29c56f30ee": "Check for Updates", + "29c56f30ee": "Check for updates", "eb9884e55b": "Discord", "5687ab246a": "GitHub", "5f83d86d92": "Changelog", "cdc87f897e": "Docs", - "e565171a7c": "Keyboard Shortcuts", - "4cf5b868d7": "Send Feedback", + "e565171a7c": "Keyboard shortcuts", + "4cf5b868d7": "Send feedback", "a428c25998": "Settings", "2991a0106c": "Help", "4e8f5710d3": "Couldn't restart Orca.", @@ -15826,7 +15829,20 @@ "RunTargetCombobox": { "listLabel": "Run targets", "label": "Run on", - "browse": "Browse run targets" + "browse": "Browse run targets", + "orcaCloudHoursLeft": "{{hours}} h left", + "orcaCloudNoHours": "No hours left", + "orcaCloudPaymentIssue": "Payment issue", + "orcaCloudTeamBadge": "Team", + "orcaCloudUpgrade": "Upgrade", + "orcaCloudDetail": "Hosted sandbox · 4 vCPU / 8 GB", + "orcaCloudRenew": "Renew", + "orcaCloudAddHours": "Add hours", + "orcaCloudUpdatePayment": "Update payment", + "orcaCloudPaymentFailed": "Payment failed", + "orcaCloudSignIn": "Sign in to use Orca Cloud", + "orcaCloudNeedsTeam": "Needs a Team plan", + "orcaCloudSignInButton": "Sign in" }, "projectCombobox": { "recentHeading": "Recent", diff --git a/src/shared/orca-yaml-hook-types.ts b/src/shared/orca-yaml-hook-types.ts index 301b4417033..bd622fedfc4 100644 --- a/src/shared/orca-yaml-hook-types.ts +++ b/src/shared/orca-yaml-hook-types.ts @@ -46,6 +46,12 @@ export type OrcaVmRecipe = { export type OrcaVmRecipeProviderId = 'orca-cloud' +/** + * Whether this build and account can use Orca Cloud: `offered` adds its recipe; `needs-sign-in` and + * `needs-capability` let the picker show a sign-in or upsell row; `unavailable` hides it entirely. + */ +export type OrcaCloudAvailability = 'offered' | 'needs-sign-in' | 'needs-capability' | 'unavailable' + export type OrcaVmRecipeLifecycleMode = 'create' | 'suspend' | 'resume' | 'destroy' export type OrcaVmRecipeTimeoutSeconds = Partial>