Show setup-needed hosts in workspace run picker (#7835)

Co-authored-by: Orca <help@stably.ai>
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
Jinwoo Hong
2026-07-21 23:08:34 -07:00
committed by GitHub
co-authored by Orca OrcaWin
parent 5d0c29f729
commit e60060039a
22 changed files with 1370 additions and 513 deletions
@@ -3,18 +3,43 @@
import React from 'react'
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import NewWorkspaceComposerCard from './NewWorkspaceComposerCard'
import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options'
import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options'
const storeMocks = vi.hoisted(() => ({
closeModal: vi.fn(),
openModal: vi.fn(),
openSettingsPage: vi.fn(),
openSettingsTarget: vi.fn(),
setRuntimeEnvironmentStatus: vi.fn()
}))
const apiMocks = vi.hoisted(() => ({
runtimeGetStatus: vi.fn(),
sshConnect: vi.fn()
}))
vi.mock('@/store', () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
openModal: vi.fn(),
activeModal: null,
settings: { defaultTuiAgent: null, disabledTuiAgents: [] },
updateSettings: vi.fn()
})
useAppStore: Object.assign(
(selector: (state: unknown) => unknown) =>
selector({
closeModal: storeMocks.closeModal,
openModal: storeMocks.openModal,
openSettingsPage: storeMocks.openSettingsPage,
openSettingsTarget: storeMocks.openSettingsTarget,
setRuntimeEnvironmentStatus: storeMocks.setRuntimeEnvironmentStatus,
activeModal: 'none',
settings: { defaultTuiAgent: null, disabledTuiAgents: [] },
updateSettings: vi.fn()
}),
{
getState: () => ({
setRuntimeEnvironmentStatus: storeMocks.setRuntimeEnvironmentStatus
})
}
)
}))
vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({
@@ -31,6 +56,13 @@ vi.mock('@/components/agent/AgentCombobox', () => ({
default: () => <button type="button">Agent picker</button>
}))
// Stub the host-add dialog to its `mode` — the composer's job is to open it with the right
// mode; the dialog's own SSH/runtime IPC has separate coverage.
vi.mock('@/components/sidebar/AddRemoteHostDialog', () => ({
AddRemoteHostDialog: ({ mode }: { mode: 'ssh' | 'server' | null }) =>
mode ? <div data-testid="add-remote-host-dialog" data-mode={mode} /> : null
}))
vi.mock('@/components/sparse/SparseCheckoutPresetSelect', () => ({
default: () => <div data-testid="sparse-select" />
}))
@@ -105,6 +137,59 @@ const sourceRepos = [
}
]
const localReadyHostOption: ProjectHostSetupOption = {
kind: 'ready',
id: 'setup-local',
projectId: 'project-group:platform',
hostId: 'local',
repoId: 'repo-a',
label: 'Local Mac',
detail: 'Orca',
path: '/Users/alice/orca'
}
const devboxNeedsSetupHostOption: ProjectHostSetupOption = {
kind: 'needs-setup',
id: 'needs-setup:ssh:devbox',
projectId: 'project-group:platform',
hostId: 'ssh:devbox',
label: 'Devbox',
detail: 'Project not set up on this host',
isAvailable: true,
attention: false
}
const disconnectedDevboxNeedsSetupHostOption: ProjectHostSetupOption = {
kind: 'needs-setup',
id: 'needs-setup:ssh:devbox',
projectId: 'project-group:platform',
hostId: 'ssh:devbox',
label: 'Devbox',
detail: 'Connect this host to set up projects',
isAvailable: false,
attention: false,
connectAction: { kind: 'ssh', targetId: 'devbox' }
}
const disconnectedBastionNeedsSetupHostOption: ProjectHostSetupOption = {
kind: 'needs-setup',
id: 'needs-setup:ssh:bastion',
projectId: 'project-group:platform',
hostId: 'ssh:bastion',
label: 'Bastion',
detail: 'Connect this host to set up projects',
isAvailable: false,
attention: false,
connectAction: { kind: 'ssh', targetId: 'bastion' }
}
function findConnectButton(label: string): HTMLButtonElement | undefined {
const item = findRunTargetItem(label)
return [...(item?.querySelectorAll('button') ?? [])].find((button) =>
button.textContent?.includes('Connect')
)
}
function renderCard(
overrides: Partial<React.ComponentProps<typeof NewWorkspaceComposerCard>> = {}
) {
@@ -195,13 +280,51 @@ function changeInputValue(input: HTMLInputElement, value: string): void {
})
}
function openRunTargetPicker(container: HTMLElement): void {
const runTargetButton = container.querySelector<HTMLButtonElement>('button[role="combobox"]')
expect(runTargetButton).toBeTruthy()
act(() => runTargetButton?.click())
}
function findRunTargetItem(label: string): HTMLElement | undefined {
return [...document.body.querySelectorAll<HTMLElement>('[cmdk-item]')].find((item) =>
item.textContent?.includes(label)
)
}
let current: { container: HTMLDivElement; root: Root } | null = null
describe('NewWorkspaceComposerCard folder task source mode', () => {
beforeEach(() => {
;(window as unknown as { api: unknown }).api = {
runtimeEnvironments: {
getStatus: apiMocks.runtimeGetStatus
},
ssh: {
connect: apiMocks.sshConnect
}
}
apiMocks.runtimeGetStatus.mockResolvedValue({
id: 'status',
ok: true,
result: {
runtimeId: 'runtime-devbox',
rendererGraphEpoch: 1,
graphStatus: 'ready',
authoritativeWindowId: null,
liveTabCount: 0,
liveLeafCount: 0
},
_meta: { runtimeId: 'runtime-devbox' }
})
apiMocks.sshConnect.mockResolvedValue(undefined)
})
afterEach(() => {
act(() => current?.root.unmount())
current?.container.remove()
current = null
vi.clearAllMocks()
})
it('passes folder child repos into the create-from field without a source trigger', () => {
@@ -320,11 +443,12 @@ describe('NewWorkspaceComposerCard folder task source mode', () => {
)
})
it('emits the setup startup policy toggle value', () => {
it('emits the setup startup policy toggle value when setup will run', () => {
const changes: string[] = []
current = renderCard({
advancedOpen: true,
setupControlsEnabled: true,
resolvedSetupDecision: 'run',
setupConfig: {
source: 'yaml',
command: 'pnpm install',
@@ -333,14 +457,38 @@ describe('NewWorkspaceComposerCard folder task source mode', () => {
onSetupAgentStartupPolicyChange: (next) => changes.push(next)
})
const waitSwitch = current.container.querySelector<HTMLElement>(
const waitSwitch = current.container.querySelector<HTMLButtonElement>(
'[role="switch"][aria-label="Wait for setup to complete before starting agent"]'
)
expect(waitSwitch).toBeTruthy()
expect(waitSwitch?.disabled).toBe(false)
act(() => waitSwitch?.click())
expect(changes).toEqual(['wait-for-setup'])
})
it('disables the wait-for-setup toggle when setup is set to skip', () => {
const changes: string[] = []
current = renderCard({
advancedOpen: true,
setupControlsEnabled: true,
resolvedSetupDecision: 'skip',
setupConfig: {
source: 'yaml',
command: 'pnpm install',
kind: 'setup'
},
onSetupAgentStartupPolicyChange: (next) => changes.push(next)
})
const waitSwitch = current.container.querySelector<HTMLButtonElement>(
'[role="switch"][aria-label="Wait for setup to complete before starting agent"]'
)
expect(waitSwitch?.disabled).toBe(true)
// Nothing to wait for when setup won't run — clicking is inert.
act(() => waitSwitch?.click())
expect(changes).toEqual([])
})
it('shows a git-only branch name field in Advanced and emits manual edits', () => {
const changes: (string | undefined)[] = []
current = renderCard({
@@ -420,6 +568,188 @@ describe('NewWorkspaceComposerCard folder task source mode', () => {
).toBe('false')
})
it('shows setup-needed hosts in the run target picker when one setup is ready', () => {
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, devboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local'
})
expect(current.container.textContent).toContain('Run on')
openRunTargetPicker(current.container)
const devboxItem = findRunTargetItem('Devbox')
expect(devboxItem?.textContent).toContain('Project not set up on this host')
// Not-connected rows stay highlightable (not disabled) so they hover like the other
// items; a separator sets them off instead of a heading.
expect(devboxItem?.getAttribute('aria-disabled')).toBe('false')
expect(devboxItem?.getAttribute('data-disabled')).toBe('false')
expect(document.body.querySelector('[cmdk-separator]')).toBeTruthy()
})
it('shows the run target picker for one ready setup so hosts can be added', () => {
current = renderCard({
projectHostSetupOptions: [localReadyHostOption],
selectedProjectHostSetupId: 'setup-local'
})
expect(current.container.textContent).toContain('Run on')
openRunTargetPicker(current.container)
expect(findRunTargetItem('Add host')).toBeTruthy()
})
it('does not select setup-needed run target rows', () => {
const hostChanges: string[] = []
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, devboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local',
onProjectHostSetupChange: (setupId) => hostChanges.push(setupId)
})
openRunTargetPicker(current.container)
const devboxItem = findRunTargetItem('Devbox')
expect(devboxItem).toBeTruthy()
act(() => devboxItem?.click())
expect(hostChanges).toEqual([])
})
it('connects disconnected setup-needed SSH hosts without selecting them', async () => {
const hostChanges: string[] = []
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, disconnectedDevboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local',
onProjectHostSetupChange: (setupId) => hostChanges.push(setupId)
})
openRunTargetPicker(current.container)
const devboxItem = findRunTargetItem('Devbox')
expect(
devboxItem?.getAttribute('aria-disabled') === 'true' ||
devboxItem?.hasAttribute('data-disabled')
).toBe(true)
const connectButton = [...(devboxItem?.querySelectorAll('button') ?? [])].find((button) =>
button.textContent?.includes('Connect')
)
expect(connectButton).toBeTruthy()
await act(async () => {
connectButton?.click()
})
expect(apiMocks.sshConnect).toHaveBeenCalledWith({ targetId: 'devbox' })
expect(hostChanges).toEqual([])
// The picker stays open so the connecting state is visible; the row is not auto-selected.
expect(findRunTargetItem('Devbox')).toBeTruthy()
})
it('keeps other hosts connectable while one connect is still in flight', async () => {
// First host's connect never resolves — a stalled connect must not disable the others.
apiMocks.sshConnect.mockImplementation(({ targetId }: { targetId: string }) =>
targetId === 'devbox' ? new Promise(() => {}) : Promise.resolve(undefined)
)
current = renderCard({
projectHostSetupOptions: [
localReadyHostOption,
disconnectedDevboxNeedsSetupHostOption,
disconnectedBastionNeedsSetupHostOption
],
selectedProjectHostSetupId: 'setup-local'
})
openRunTargetPicker(current.container)
await act(async () => {
findConnectButton('Devbox')?.click()
})
// The picker stays open through the connect, so the state is inspectable in place.
// Devbox is mid-connect: disabled, showing the connecting indicator; Bastion stays clickable.
const devboxButton = findConnectButton('Devbox')
expect(devboxButton?.disabled).toBe(true)
expect(devboxButton?.textContent).toContain('Connecting')
const bastionButton = findConnectButton('Bastion')
expect(bastionButton?.disabled).toBe(false)
expect(bastionButton?.textContent).toContain('Connect')
await act(async () => {
bastionButton?.click()
})
expect(apiMocks.sshConnect).toHaveBeenCalledWith({ targetId: 'bastion' })
})
it('stops the connecting indicator when the connect fails', async () => {
// A failed connect must clear the spinner and restore the Connect button so the user
// can retry — the row can't stay stuck on "Connecting" after the error.
apiMocks.sshConnect.mockRejectedValue(new Error('connection refused'))
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, disconnectedDevboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local'
})
openRunTargetPicker(current.container)
await act(async () => {
findConnectButton('Devbox')?.click()
})
const devboxButton = findConnectButton('Devbox')
expect(devboxButton?.disabled).toBe(false)
expect(devboxButton?.textContent).toContain('Connect')
expect(devboxButton?.textContent).not.toContain('Connecting')
})
it('opens the SSH host add dialog over the composer without leaving for Settings', () => {
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, devboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local'
})
openRunTargetPicker(current.container)
act(() => findRunTargetItem('Add host')?.click())
act(() => findRunTargetItem('Add SSH host')?.click())
const dialog = document.body.querySelector('[data-testid="add-remote-host-dialog"]')
expect(dialog?.getAttribute('data-mode')).toBe('ssh')
// The composer stays put — no navigation that would discard the in-progress form.
expect(storeMocks.closeModal).not.toHaveBeenCalled()
expect(storeMocks.openSettingsPage).not.toHaveBeenCalled()
expect(storeMocks.openSettingsTarget).not.toHaveBeenCalled()
})
it('opens the add-host submenu on hover without a click', () => {
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, devboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local'
})
openRunTargetPicker(current.container)
const addHost = findRunTargetItem('Add host')
expect(addHost).toBeTruthy()
// Hovering the row (no click) opens its submenu so it feels like a menu. React derives
// onPointerEnter from a bubbling pointerover, which is what jsdom dispatches here.
act(() => {
addHost?.dispatchEvent(new MouseEvent('pointerover', { bubbles: true }))
})
expect(findRunTargetItem('Add SSH host')).toBeTruthy()
expect(findRunTargetItem('Add Remote Orca Server')).toBeTruthy()
})
it('opens the remote Orca server add dialog over the composer without leaving for Settings', () => {
current = renderCard({
projectHostSetupOptions: [localReadyHostOption, devboxNeedsSetupHostOption],
selectedProjectHostSetupId: 'setup-local'
})
openRunTargetPicker(current.container)
act(() => findRunTargetItem('Add host')?.click())
act(() => findRunTargetItem('Add Remote Orca Server')?.click())
const dialog = document.body.querySelector('[data-testid="add-remote-host-dialog"]')
expect(dialog?.getAttribute('data-mode')).toBe('server')
expect(storeMocks.closeModal).not.toHaveBeenCalled()
expect(storeMocks.openSettingsPage).not.toHaveBeenCalled()
expect(storeMocks.openSettingsTarget).not.toHaveBeenCalled()
})
it('shows VM recipes inside the run target picker', () => {
const hostChanges: string[] = []
const recipeChanges: (string | null)[] = []
@@ -14,11 +14,18 @@ import {
FolderPlus,
LoaderCircle,
PlugZap,
Plus,
Settings2,
Server
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Command, CommandEmpty, CommandItem, CommandList } from '@/components/ui/command'
import {
Command,
CommandEmpty,
CommandItem,
CommandList,
CommandSeparator
} from '@/components/ui/command'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { SettingsSwitch } from '@/components/settings/SettingsFormControls'
@@ -52,15 +59,22 @@ import SmartWorkspaceNameField, {
} from '@/components/new-workspace/SmartWorkspaceNameField'
import type { SmartNameMode } from '@/components/new-workspace/smart-workspace-source-results'
import ProjectCombobox from '@/components/new-workspace/ProjectCombobox'
import {
AddRemoteHostDialog,
type AddRemoteHostMode
} from '@/components/sidebar/AddRemoteHostDialog'
import type { SetupConfig } from '@/lib/new-workspace'
import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options'
import type {
NeedsSetupProjectHostOption,
ProjectHostSetupOption,
ReadyProjectHostSetupOption
} from '@/lib/project-host-setup-options'
import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace-create-error-format'
import type { SshConnectionStatus } from '../../../shared/ssh-types'
import type { TaskSourceContext } from '../../../shared/task-source-context'
import type { RuntimeStatus } from '../../../shared/runtime-types'
import { unwrapRuntimeRpcResult } from '@/runtime/runtime-rpc-client'
import { translate } from '@/i18n/i18n'
type RepoOption = React.ComponentProps<typeof RepoCombobox>['repos'][number]
@@ -203,6 +217,33 @@ function getSshStatusLabel(status: SshConnectionStatus): string {
return SSH_STATUS_LABELS[status] ?? status
}
// Why: bound how long the run-target picker waits on a host connect so a stalled backend
// connect can't leave the row's disabled/spinner state stuck forever. The backend keeps going.
const RUN_TARGET_CONNECT_UI_TIMEOUT_MS = 20_000
async function withUiConnectTimeout<T>(promise: Promise<T>): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(
new Error(
translate(
'auto.components.NewWorkspaceComposerCard.connectTimedOut',
'Connection timed out. It may still be connecting in the background.'
)
)
)
}, RUN_TARGET_CONNECT_UI_TIMEOUT_MS)
})
try {
return await Promise.race([promise, timeout])
} finally {
if (timer) {
clearTimeout(timer)
}
}
}
function getRecipeCommandDisplay(command: string): string {
const trimmed = command.trim()
const quoted = trimmed.match(/^"([^"]+)"/) ?? trimmed.match(/^'([^']+)'/)
@@ -223,12 +264,15 @@ function getRecipeDestroyLabel(recipe: EphemeralVmRecipeOption): string {
}
type WorkspaceRunTargetComboboxProps = {
hostOptions: readonly ReadyProjectHostSetupOption[]
hostOptions: readonly ProjectHostSetupOption[]
hostValue: string | null
onHostChange?: (setupId: string) => void
recipes: EphemeralVmRecipeOption[]
recipeValue: string | null
onRecipeChange?: (recipeId: string | null) => void
onAddRemoteServer?: () => void
onAddSshHost?: () => void
onConnectHost?: (option: NeedsSetupProjectHostOption) => Promise<void> | void
}
type HostPathTooltipPosition = {
@@ -317,12 +361,35 @@ function WorkspaceRunTargetCombobox({
onHostChange,
recipes,
recipeValue,
onRecipeChange
onRecipeChange,
onAddRemoteServer,
onAddSshHost,
onConnectHost
}: WorkspaceRunTargetComboboxProps): React.JSX.Element {
const [open, setOpen] = React.useState(false)
const [vmRecipesOpen, setVmRecipesOpen] = React.useState(false)
const [hostActionsOpen, setHostActionsOpen] = React.useState(false)
// Why: track in-flight connects per host (a Set, not a single id) so connecting one host — or
// one connect stalling — never disables connecting to the others.
const [connectingHostIds, setConnectingHostIds] = React.useState<ReadonlySet<string>>(
() => new Set()
)
const readyHostOptions = React.useMemo(
() =>
hostOptions.filter(
(option): option is ReadyProjectHostSetupOption => option.kind === 'ready'
),
[hostOptions]
)
const needsSetupHostOptions = React.useMemo(
() =>
hostOptions.filter(
(option): option is NeedsSetupProjectHostOption => option.kind === 'needs-setup'
),
[hostOptions]
)
const selectedHost =
hostOptions.find((option) => option.id === hostValue) ?? hostOptions[0] ?? null
readyHostOptions.find((option) => option.id === hostValue) ?? readyHostOptions[0] ?? null
const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null
const selectedValue = selectedRecipe
? `recipe:${selectedRecipe.id}`
@@ -336,14 +403,14 @@ function WorkspaceRunTargetCombobox({
const handleHostSelect = React.useCallback(
(setupId: string): void => {
if (!hostOptions.some((candidate) => candidate.id === setupId)) {
if (!readyHostOptions.some((candidate) => candidate.id === setupId)) {
return
}
onHostChange?.(setupId)
onRecipeChange?.(null)
setOpen(false)
},
[hostOptions, onHostChange, onRecipeChange]
[onHostChange, onRecipeChange, readyHostOptions]
)
const handleRecipeSelect = React.useCallback(
@@ -358,6 +425,63 @@ function WorkspaceRunTargetCombobox({
[onRecipeChange, recipes]
)
const connectHost = React.useCallback(
async (option: NeedsSetupProjectHostOption): Promise<void> => {
if (!option.connectAction || !onConnectHost || connectingHostIds.has(option.hostId)) {
return
}
setConnectingHostIds((current) => new Set(current).add(option.hostId))
try {
await onConnectHost(option)
} finally {
// Why: always clear the in-flight id when the connect settles (success, failure, or
// timeout) so the row's spinner stops. No mounted-guard — a stale setState on an
// unmounted component is a harmless no-op in React 18, and the guard's ref was the
// source of a StrictMode bug that left the spinner stuck.
setConnectingHostIds((current) => {
if (!current.has(option.hostId)) {
return current
}
const next = new Set(current)
next.delete(option.hostId)
return next
})
}
},
[connectingHostIds, onConnectHost]
)
// Why: the submenu rows open their popover on hover/focus (not just click) to feel like a
// menu; opening one closes the other so the two right-side popovers never stack.
const openVmRecipesSubmenu = React.useCallback((): void => {
setHostActionsOpen(false)
setVmRecipesOpen(true)
}, [])
const openHostActionsSubmenu = React.useCallback((): void => {
setVmRecipesOpen(false)
setHostActionsOpen(true)
}, [])
// Why: hovering/highlighting a plain host row dismisses any submenu popover left open from
// passing over the recipe/add-host rows, so a stray submenu can't linger over the list.
const closeSubmenus = React.useCallback((): void => {
setVmRecipesOpen(false)
setHostActionsOpen(false)
}, [])
const handleAddSshHost = React.useCallback((): void => {
setHostActionsOpen(false)
setOpen(false)
onAddSshHost?.()
}, [onAddSshHost])
const handleAddRemoteServer = React.useCallback((): void => {
setHostActionsOpen(false)
setOpen(false)
onAddRemoteServer?.()
}, [onAddRemoteServer])
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
@@ -403,11 +527,13 @@ function WorkspaceRunTargetCombobox({
'No run targets are ready for this project.'
)}
</CommandEmpty>
{hostOptions.map((option) => (
{readyHostOptions.map((option) => (
<CommandItem
key={option.id}
value={`host:${option.id}`}
onSelect={() => handleHostSelect(option.id)}
onPointerEnter={closeSubmenus}
onFocus={closeSubmenus}
className="items-center gap-2 px-3 py-2"
>
<Check
@@ -423,13 +549,98 @@ function WorkspaceRunTargetCombobox({
</div>
</CommandItem>
))}
{/* Why: not-connected hosts are dormant, not errors — a separator (no heading) sets
them off as a secondary group without labeling the recipe/add-host rows below. */}
{needsSetupHostOptions.length > 0 ? (
<>
<CommandSeparator />
{needsSetupHostOptions.map((option) => (
// Why: setup-on-host is a follow-up; this row only explains why the host cannot
// run the workspace yet. It stays highlightable (no `disabled`) so it matches the
// hover of the other rows, but selecting it is a no-op since it isn't ready.
<CommandItem
key={option.id}
value={option.id}
onSelect={() => {}}
onPointerEnter={closeSubmenus}
onFocus={closeSubmenus}
className="items-center gap-2 px-3 py-2"
>
<div className="flex min-w-0 flex-1 items-center gap-2 opacity-60">
<Check className="size-4 opacity-0" />
{/* Why: show a spinner while connecting; otherwise reserve the alarm glyph for
a genuine connection error and give a dormant disconnected host the neutral
server icon. */}
{connectingHostIds.has(option.hostId) ? (
<LoaderCircle className="size-3.5 shrink-0 animate-spin text-muted-foreground" />
) : option.attention ? (
<AlertTriangle className="size-3.5 shrink-0 text-muted-foreground" />
) : (
<Server className="size-3.5 shrink-0 text-muted-foreground" />
)}
<div className="min-w-0 flex-1">
<div className="truncate text-sm">{option.label}</div>
<div className="mt-0.5 truncate text-[11px] text-muted-foreground">
{option.detail}
</div>
</div>
</div>
{option.connectAction && onConnectHost ? (
<Button
type="button"
variant="ghost"
size="xs"
className="ml-1 shrink-0 gap-1 text-muted-foreground/50 hover:text-muted-foreground"
// Why: only disable the row being connected — not every row — so one
// stuck/slow connect can't lock out connecting to the other hosts.
disabled={connectingHostIds.has(option.hostId)}
onPointerDown={(event) => {
event.preventDefault()
event.stopPropagation()
}}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
// Why: keep the picker open so the connecting state stays visible; the
// row updates in place from store SSH state once the connect resolves.
void connectHost(option)
}}
>
{connectingHostIds.has(option.hostId) ? (
<>
<LoaderCircle className="size-3 animate-spin" />
{translate(
'auto.components.NewWorkspaceComposerCard.connectingHost',
'Connecting…'
)}
</>
) : (
translate(
'auto.components.NewWorkspaceComposerCard.connectHost',
'Connect'
)
)}
</Button>
) : null}
</CommandItem>
))}
</>
) : null}
{/* Why: separate the host list from the environment/add-host actions below, mirroring
the divider above the not-connected group so the two action rows read as their own
section rather than trailing the hosts. */}
{readyHostOptions.length > 0 || needsSetupHostOptions.length > 0 ? (
<CommandSeparator />
) : null}
{recipes.length > 0 ? (
<Popover open={vmRecipesOpen} onOpenChange={setVmRecipesOpen}>
<PopoverTrigger asChild>
{/* Why: a real CommandItem (not a raw button) so cmdk registers it — fixes missing rows, uneven height, and double-highlight. */}
<CommandItem
value="per-workspace-env"
onSelect={() => setVmRecipesOpen(true)}
onSelect={openVmRecipesSubmenu}
onPointerEnter={openVmRecipesSubmenu}
onFocus={openVmRecipesSubmenu}
className="items-center gap-2 px-3 py-2"
>
<Check
@@ -487,6 +698,82 @@ function WorkspaceRunTargetCombobox({
</PopoverContent>
</Popover>
) : null}
<Popover open={hostActionsOpen} onOpenChange={setHostActionsOpen}>
<PopoverTrigger asChild>
<CommandItem
value="add-host"
onSelect={openHostActionsSubmenu}
onPointerEnter={openHostActionsSubmenu}
onFocus={openHostActionsSubmenu}
className="items-center gap-2 px-3 py-2"
>
<Check className="size-4 opacity-0" />
<Plus className="size-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm">
{translate('auto.components.NewWorkspaceComposerCard.addHost', 'Add host')}
</div>
<div className="mt-0.5 truncate text-[11px] text-muted-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.addHostHint',
'Register another machine or Orca server'
)}
</div>
</div>
<ChevronRight className="size-3.5 shrink-0 text-muted-foreground" />
</CommandItem>
</PopoverTrigger>
<PopoverContent side="right" align="start" sideOffset={6} className="w-72 p-0">
{/* Why: pin an empty value so cmdk doesn't auto-highlight the first row on open —
matches the recipes submenu, which leaves nothing highlighted by default. */}
<Command value="">
<CommandList>
<CommandItem
value="add-ssh-host"
onSelect={handleAddSshHost}
className="items-center gap-2 px-3 py-2"
>
<Server className="size-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm">
{translate(
'auto.components.NewWorkspaceComposerCard.addSshHost',
'Add SSH host'
)}
</div>
<div className="mt-0.5 truncate text-[11px] text-muted-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.addSshHostHint',
'Use an existing machine over SSH'
)}
</div>
</div>
</CommandItem>
<CommandItem
value="add-remote-orca-server"
onSelect={handleAddRemoteServer}
className="items-center gap-2 px-3 py-2"
>
<Cloud className="size-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm">
{translate(
'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServer',
'Add Remote Orca Server'
)}
</div>
<div className="mt-0.5 truncate text-[11px] text-muted-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServerHint',
'Pair another Orca runtime'
)}
</div>
</div>
</CommandItem>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</CommandList>
</Command>
</PopoverContent>
@@ -494,47 +781,14 @@ function WorkspaceRunTargetCombobox({
)
}
function SetupCommandPreview({
setupConfig,
headerAction
}: {
setupConfig: SetupConfig
headerAction?: React.ReactNode
}): React.JSX.Element {
if (setupConfig.source === 'yaml') {
return (
<div className="rounded-2xl border border-border/60 bg-muted/40 shadow-inner">
<div className="flex items-center justify-between gap-3 border-b border-border/60 px-4 py-2.5">
<div className="font-mono text-[11px] text-muted-foreground">
{translate('auto.components.NewWorkspaceComposerCard.23bb365554', 'orca.yaml')}
</div>
{headerAction}
</div>
{/* Why: long orca.yaml scripts must not grow the create dialog past the viewport. */}
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words px-4 py-3 font-mono text-[12px] leading-5 text-emerald-700 scrollbar-sleek dark:text-emerald-300/95">
{setupConfig.command}
</pre>
</div>
)
}
function SetupCommandPreview({ setupConfig }: { setupConfig: SetupConfig }): React.JSX.Element {
// Why: just the script in a quiet monochrome card — the source label (orca.yaml / local) and
// the run-setup toggle live in the section header above, so the card carries no chrome of its
// own. Neutral foreground avoids the colored-terminal look. max-h keeps long scripts from
// growing the dialog past the viewport.
return (
<div className="rounded-2xl border border-border/60 bg-muted/35 px-4 py-3 shadow-inner">
<div className="mb-2 flex items-center justify-between gap-3">
<div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
{setupConfig.source === 'both'
? translate(
'auto.components.NewWorkspaceComposerCard.e5db1b0419',
'Combined setup command'
)
: translate(
'auto.components.NewWorkspaceComposerCard.7711ad5122',
'Local setup command'
)}
</div>
{headerAction}
</div>
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-foreground scrollbar-sleek">
<div className="rounded-md border border-border/60 bg-muted/40 shadow-inner">
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words px-4 py-3 font-mono text-[12px] leading-5 text-foreground/90 scrollbar-sleek">
{setupConfig.command}
</pre>
</div>
@@ -801,6 +1055,61 @@ export default function NewWorkspaceComposerCard({
}
openModal('add-repo')
}, [onAddProjectOverride, openModal])
// Why: open the host-add form inline over the composer (not via Settings) so the user's
// in-progress workspace form survives; the new host lands in the store and flows straight
// back into the run-target picker without a navigation round-trip.
const [addRemoteHostMode, setAddRemoteHostMode] = React.useState<AddRemoteHostMode | null>(null)
const handleAddSshHost = React.useCallback((): void => {
setAddRemoteHostMode('ssh')
}, [])
const handleAddRemoteServer = React.useCallback((): void => {
setAddRemoteHostMode('server')
}, [])
const handleConnectRunTargetHost = React.useCallback(
async (option: NeedsSetupProjectHostOption): Promise<void> => {
const action = option.connectAction
if (!action) {
return
}
try {
if (action.kind === 'ssh') {
// Why: ssh.connect has no built-in timeout; a stalled connect would otherwise leave the
// row's spinner/disabled state stuck forever. Bound the UI wait — the backend keeps
// connecting and the picker updates from store SSH state if it later succeeds.
await withUiConnectTimeout(window.api.ssh.connect({ targetId: action.targetId }))
return
}
const response = await window.api.runtimeEnvironments.getStatus({
selector: action.environmentId,
timeoutMs: 15_000
})
const runtimeStatus = unwrapRuntimeRpcResult<RuntimeStatus>(response)
// Why: the composer button is only a reachability retry; the separate
// project setup flow remains a follow-up once the host is online.
useAppStore.getState().setRuntimeEnvironmentStatus(action.environmentId, {
status: runtimeStatus,
checkedAt: Date.now()
})
} catch (error) {
if (action.kind === 'runtime') {
useAppStore.getState().setRuntimeEnvironmentStatus(action.environmentId, {
status: null,
checkedAt: Date.now()
})
}
toast.error(
error instanceof Error
? error.message
: translate(
'auto.components.NewWorkspaceComposerCard.hostConnectionFailed',
'Connection failed'
)
)
}
},
[]
)
const handleNotePaste = React.useCallback((event: React.ClipboardEvent<HTMLTextAreaElement>) => {
const text = event.clipboardData.getData('text/plain')
const byteLengthMeasurement = measureTextControlPasteByteLength(text, {
@@ -838,6 +1147,16 @@ export default function NewWorkspaceComposerCard({
() => projectHostSetupOptions.filter((option) => option.kind === 'ready'),
[projectHostSetupOptions]
)
const needsSetupProjectHostSetupOptions = React.useMemo(
() => projectHostSetupOptions.filter((option) => option.kind === 'needs-setup'),
[projectHostSetupOptions]
)
// Why: the picker now also hosts the Add host handoff; even a single ready
// host needs this affordance for users who have not registered the target yet.
const shouldShowRunTargetPicker =
readyProjectHostSetupOptions.length > 0 ||
ephemeralVmRecipes.length > 0 ||
needsSetupProjectHostSetupOptions.length > 0
const handleProjectHostSetupChange = React.useCallback(
(setupId: string): void => {
onProjectHostSetupChange?.(setupId)
@@ -925,18 +1244,21 @@ export default function NewWorkspaceComposerCard({
)}
</p>
) : null}
{readyProjectHostSetupOptions.length > 1 || ephemeralVmRecipes.length > 0 ? (
{shouldShowRunTargetPicker ? (
<div className="space-y-1">
<label className="block min-w-0 truncate text-xs font-medium text-muted-foreground">
{translate('auto.components.NewWorkspaceComposerCard.runOn', 'Run on')}
</label>
<WorkspaceRunTargetCombobox
hostOptions={readyProjectHostSetupOptions}
hostOptions={projectHostSetupOptions}
hostValue={selectedProjectHostSetupId ?? null}
onHostChange={handleProjectHostSetupChange}
recipes={ephemeralVmRecipes}
recipeValue={selectedEphemeralVmRecipeId}
onRecipeChange={onEphemeralVmRecipeChange}
onAddSshHost={handleAddSshHost}
onAddRemoteServer={handleAddRemoteServer}
onConnectHost={handleConnectRunTargetHost}
/>
{ephemeralVmRecipeError ? (
<p className="whitespace-pre-line text-[11px] text-destructive">
@@ -1136,6 +1458,9 @@ export default function NewWorkspaceComposerCard({
{/* Why: keep the Advanced disclosure header grouped with the content below while preserving spacing from the Agent field above. */}
<div className="!mb-2">
{/* Why: -ml-2 pulls the button so its label aligns flush-left with the field labels above
while the padded hover highlight extends past the label on the left. The scroll
container's px-2 inset gives that overhang room so it isn't clipped. */}
<Button
type="button"
variant="ghost"
@@ -1244,7 +1569,9 @@ export default function NewWorkspaceComposerCard({
<label className="text-xs font-medium text-muted-foreground">
{setupConfigLabel}
</label>
<span className="rounded-full border border-border/70 bg-muted/45 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-foreground/70">
{/* Why: a quiet monospace filename chip (not an uppercase tag) — orca.yaml is a
literal filename, so it reads as code, matching the app's path styling. */}
<span className="rounded border border-border/50 bg-muted/30 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
{setupConfig.source === 'yaml'
? translate(
'auto.components.NewWorkspaceComposerCard.23bb365554',
@@ -1262,40 +1589,73 @@ export default function NewWorkspaceComposerCard({
</span>
</div>
{/* Why: `orca.yaml` is the committed source of truth, so the preview reconstructs the real YAML shape rather than a raw shell blob. */}
<SetupCommandPreview
setupConfig={setupConfig}
headerAction={
requiresExplicitSetupChoice ? null : (
<label className="group flex items-center gap-2 text-xs text-foreground">
{/* Why: `orca.yaml` is the committed source of truth for shared setup,
so the preview reconstructs the real YAML shape instead of showing a raw
shell blob that hides where the command came from. */}
<SetupCommandPreview setupConfig={setupConfig} />
{/* Why: group the run-setup and wait-for-setup toggles in one bordered box so
they read as a single settings cluster, aligned hard-right. */}
{!requiresExplicitSetupChoice || showSetupAgentStartupPolicy ? (
<div className="rounded-md border border-border/60 bg-muted/25">
{requiresExplicitSetupChoice ? null : (
<div className="flex items-center justify-between gap-3 p-3">
<span className="text-xs font-medium text-foreground">
{setupRunLabel}
</span>
<SettingsSwitch
checked={resolvedSetupDecision === 'run'}
onChange={() =>
onSetupDecisionChange(
resolvedSetupDecision === 'run' ? 'skip' : 'run'
)
}
ariaLabel={setupRunLabel}
/>
</div>
)}
{showSetupAgentStartupPolicy ? (
// Why: nothing to wait for when setup won't run — disable the toggle and
// dim the label so it reads as inactive (the switch dims itself).
<div className="flex items-start justify-between gap-3 p-3">
<span
className={cn(
'flex size-4 items-center justify-center rounded-[3px] border transition shadow-sm',
resolvedSetupDecision === 'run'
? 'border-emerald-500/60 bg-emerald-500 text-white'
: 'border-foreground/20 bg-background dark:border-white/20 dark:bg-muted/10'
'min-w-0 space-y-1',
resolvedSetupDecision === 'run' ? '' : 'opacity-50'
)}
>
<Check
className={cn(
'size-3 transition-opacity',
resolvedSetupDecision === 'run' ? 'opacity-100' : 'opacity-0'
<span className="block text-xs font-medium text-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent',
'Wait for setup to complete before starting agent'
)}
/>
</span>
<span className="block text-[11px] text-muted-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgentHelp',
'Turn this on when setup installs dependencies, MCP servers, or config files the agent needs during startup.'
)}
</span>
</span>
<input
type="checkbox"
checked={resolvedSetupDecision === 'run'}
onChange={(event) =>
onSetupDecisionChange(event.target.checked ? 'run' : 'skip')
<SettingsSwitch
checked={setupAgentStartupPolicy === 'wait-for-setup'}
disabled={resolvedSetupDecision !== 'run'}
onChange={() =>
onSetupAgentStartupPolicyChange(
setupAgentStartupPolicy === 'wait-for-setup'
? 'start-immediately'
: 'wait-for-setup'
)
}
className="sr-only"
ariaLabel={translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent',
'Wait for setup to complete before starting agent'
)}
/>
<span>{setupRunLabel}</span>
</label>
)
}
/>
</div>
) : null}
</div>
) : null}
{requiresExplicitSetupChoice ? (
<div className="space-y-2">
@@ -1335,39 +1695,6 @@ export default function NewWorkspaceComposerCard({
) : null}
</div>
) : null}
{showSetupAgentStartupPolicy ? (
<div className="flex items-start justify-between gap-3 rounded-md border border-border/60 bg-muted/25 p-3">
<span className="min-w-0 space-y-1">
<span className="block text-xs font-medium text-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent',
'Wait for setup to complete before starting agent'
)}
</span>
<span className="block text-[11px] text-muted-foreground">
{translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgentHelp',
'Turn this on when setup installs dependencies, MCP servers, or config files the agent needs during startup.'
)}
</span>
</span>
<SettingsSwitch
checked={setupAgentStartupPolicy === 'wait-for-setup'}
onChange={() =>
onSetupAgentStartupPolicyChange(
setupAgentStartupPolicy === 'wait-for-setup'
? 'start-immediately'
: 'wait-for-setup'
)
}
ariaLabel={translate(
'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent',
'Wait for setup to complete before starting agent'
)}
/>
</div>
) : null}
</div>
) : null}
@@ -1465,6 +1792,10 @@ export default function NewWorkspaceComposerCard({
</span>
</Button>
</div>
{/* Why: layer the host-add form over the composer instead of navigating to Settings so
the in-progress workspace form is preserved; on success the new host flows back into
the run-target picker via the store. */}
<AddRemoteHostDialog mode={addRemoteHostMode} onOpenChange={setAddRemoteHostMode} />
</div>
)
}
@@ -309,10 +309,11 @@ function QuickTabBody({
</DialogHeader>
<NewWorkspaceComposerCard
contextualTourSource={modalData.contextualTourSource}
// Why: the scroll container clips children, while Orca's standard
// field focus ring paints 3px outside the control. Inset both sides so
// keyboard focus stays fully visible at the dialog edges.
containerClassName="min-h-0 flex-1 overflow-y-auto px-1 scrollbar-sleek"
// Why: the scroll container clips children (overflow-y-auto forces overflow-x to auto),
// while Orca's standard field focus ring paints 3px outside the control and the ghost
// "Advanced" disclosure pulls its padded hover highlight ~8px left to align its label with
// the field labels. Inset px-2 so both stay fully visible instead of clipped at the edge.
containerClassName="min-h-0 flex-1 overflow-y-auto px-2 scrollbar-sleek"
composerRef={composerRef}
onComposerNodeChange={onComposerNodeChange}
nameInputRef={nameInputRef}
@@ -62,7 +62,8 @@ const needsSetupOption: NeedsSetupProjectHostOption = {
hostId: 'ssh:builder',
label: 'Builder',
detail: 'Project not set up on this host',
isAvailable: true
isAvailable: true,
attention: false
}
const unavailableOption: NeedsSetupProjectHostOption = {
@@ -72,7 +73,8 @@ const unavailableOption: NeedsSetupProjectHostOption = {
hostId: 'runtime:old',
label: 'Old server',
detail: 'Update Orca on this host to set up projects',
isAvailable: false
isAvailable: false,
attention: false
}
beforeEach(() => {
@@ -12,7 +12,7 @@ import {
Share2,
Trash2
} from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
import { useMountedRef } from '@/hooks/useMountedRef'
import type { GlobalSettings } from '../../../../shared/types'
@@ -65,6 +65,7 @@ type RuntimeEnvironmentsPaneProps = {
switchRuntimeEnvironment: (environmentId: string | null) => Promise<boolean>
canGeneratePairingUrl?: boolean
allowLocalRuntime?: boolean
addServerIntentSignal?: number
}
export type RuntimeHostDetails = {
@@ -247,7 +248,8 @@ export function RuntimeEnvironmentsPane({
settings,
switchRuntimeEnvironment,
canGeneratePairingUrl = true,
allowLocalRuntime = true
allowLocalRuntime = true,
addServerIntentSignal
}: RuntimeEnvironmentsPaneProps): React.JSX.Element {
const [environments, setEnvironments] = useState<PublicKnownRuntimeEnvironment[]>([])
const [isLoading, setIsLoading] = useState(false)
@@ -268,6 +270,7 @@ export function RuntimeEnvironmentsPane({
const [removeError, setRemoveError] = useState<string | null>(null)
const [name, setName] = useState('')
const [pairingCode, setPairingCode] = useState('')
const consumedAddServerIntentSignalRef = useRef(0)
const mountedRef = useMountedRef()
const activeValue =
settings.activeRuntimeEnvironmentId ??
@@ -378,6 +381,19 @@ export function RuntimeEnvironmentsPane({
void loadEnvironments()
}, [loadEnvironments])
useEffect(() => {
if (
!addServerIntentSignal ||
consumedAddServerIntentSignalRef.current === addServerIntentSignal
) {
return
}
consumedAddServerIntentSignalRef.current = addServerIntentSignal
// Why: composer deep-links should land on the existing pairing form, not just
// the server list.
setAddServerFormOpen(true)
}, [addServerIntentSignal])
const closeAddServerForm = (): void => {
if (isSaving) {
return
@@ -366,6 +366,8 @@ function Settings(): React.JSX.Element {
)
const [pendingNavRequestTick, setPendingNavRequestTick] = useState(0)
const [quickCommandAddIntentSignal, setQuickCommandAddIntentSignal] = useState(0)
const [sshHostAddIntentSignal, setSshHostAddIntentSignal] = useState(0)
const [remoteServerAddIntentSignal, setRemoteServerAddIntentSignal] = useState(0)
const [hasUnsavedCommitPromptChanges, setHasUnsavedCommitPromptChanges] = useState(false)
const [hasUnsavedBranchPromptChanges, setHasUnsavedBranchPromptChanges] = useState(false)
const [sourceControlAiPromptDiscardSignal, setSourceControlAiPromptDiscardSignal] = useState(0)
@@ -649,6 +651,10 @@ function Settings(): React.JSX.Element {
}
if (settingsNavigationTarget.intent === 'add-quick-command') {
setQuickCommandAddIntentSignal((signal) => signal + 1)
} else if (settingsNavigationTarget.intent === 'add-ssh-host') {
setSshHostAddIntentSignal((signal) => signal + 1)
} else if (settingsNavigationTarget.intent === 'add-remote-orca-server') {
setRemoteServerAddIntentSignal((signal) => signal + 1)
}
setMountedSectionIds((previous) => {
if (previous.has(paneSectionId)) {
@@ -1601,6 +1607,7 @@ function Settings(): React.JSX.Element {
switchRuntimeEnvironment={switchRuntimeEnvironment}
canGeneratePairingUrl={!isWebClient}
allowLocalRuntime={!isWebClient}
addServerIntentSignal={remoteServerAddIntentSignal}
/>
) : null}
</SettingsSection>
@@ -1615,7 +1622,9 @@ function Settings(): React.JSX.Element {
)}
searchEntries={getSectionSearchEntries('ssh')}
>
{isSectionMounted('ssh') ? <SshPane /> : null}
{isSectionMounted('ssh') ? (
<SshPane addTargetIntentSignal={sshHostAddIntentSignal} />
) : null}
</SettingsSection>
) : null}
@@ -0,0 +1,180 @@
import { ChevronDown } from 'lucide-react'
import {
DEFAULT_BOUNDED_SSH_RELAY_GRACE_PERIOD_SECONDS,
MAX_SSH_RELAY_GRACE_PERIOD_SECONDS,
MIN_SSH_RELAY_GRACE_PERIOD_SECONDS
} from '../../../../shared/ssh-types'
import { Button } from '@/components/ui/button'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { cn } from '@/lib/utils'
import { SettingsSwitch } from './SettingsFormControls'
import type { EditingTarget } from './ssh-target-draft'
import { translate } from '@/i18n/i18n'
// Why: mirror the composer's "Advanced" disclosure (ghost button + rotating chevron) so the
// add-host dialog reads the same, while reusing the exact field labels/help text from the
// Settings SSH form (proxy, jump host, connection reuse, terminal persistence).
export function SshHostAdvancedFields({
open,
onOpenChange,
form,
disabled,
onFormChange
}: {
open: boolean
onOpenChange: (open: boolean) => void
form: EditingTarget
disabled: boolean
onFormChange: (updater: (prev: EditingTarget) => EditingTarget) => void
}): React.JSX.Element {
return (
<Collapsible open={open} onOpenChange={onOpenChange} className="col-span-2 sm:col-span-2">
<CollapsibleTrigger asChild>
{/* Why: no negative margin — the button's highlight would overhang and get clipped by the
dialog/settings containers. A small left padding keeps it flush without overflow. */}
<Button type="button" variant="ghost" size="sm" className="px-2 text-xs">
{translate('auto.components.sidebar.AddRemoteHostDialog.advanced', 'Advanced')}
<ChevronDown className={cn('size-4 transition-transform', open && 'rotate-180')} />
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="collapsible-height-content">
<div className="space-y-4 pt-3">
<div className="space-y-1.5">
<Label htmlFor="add-ssh-proxy-command">
{translate('auto.components.settings.SshTargetForm.c7d0e18ecb', 'Proxy Command')}
</Label>
<Input
id="add-ssh-proxy-command"
value={form.proxyCommand}
disabled={disabled}
onChange={(e) => onFormChange((f) => ({ ...f, proxyCommand: e.target.value }))}
placeholder={translate(
'auto.components.settings.SshTargetForm.f42d844544',
'e.g. cloudflared access ssh --hostname %h'
)}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.3b01ca44a0',
'Optional. Used for tunneling (e.g. Cloudflare Access, ProxyCommand).'
)}
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="add-ssh-jump-host">
{translate('auto.components.settings.SshTargetForm.b2ab248ded', 'Jump Host')}
</Label>
<Input
id="add-ssh-jump-host"
value={form.jumpHost}
disabled={disabled}
onChange={(e) => onFormChange((f) => ({ ...f, jumpHost: e.target.value }))}
placeholder={translate(
'auto.components.settings.SshTargetForm.11bcb4507a',
'bastion.example.com'
)}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.feae1d1e69',
'Optional. Equivalent to ProxyJump / ssh -J.'
)}
</p>
</div>
<div className="flex items-start justify-between gap-4 py-1 text-xs">
<div className="min-w-0 flex-1 space-y-0.5">
<Label className="text-xs font-medium">
{translate(
'auto.components.settings.SshTargetForm.8c922dffba',
'Reuse SSH connection for faster setup'
)}
</Label>
<p className="text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.53e9aabfc0',
'Uses OpenSSH multiplexing when available. Turn off for hosts with custom SSH restrictions.'
)}
</p>
</div>
<SettingsSwitch
checked={form.systemSshConnectionReuse}
disabled={disabled}
onChange={() =>
onFormChange((f) => ({
...f,
systemSshConnectionReuse: !f.systemSshConnectionReuse
}))
}
ariaLabel={translate(
'auto.components.settings.SshTargetForm.8c922dffba',
'Reuse SSH connection for faster setup'
)}
/>
</div>
<div className="flex items-start justify-between gap-4 py-1 text-xs">
<div className="min-w-0 flex-1 space-y-0.5">
<Label className="text-xs font-medium">
{translate(
'auto.components.settings.SshTargetForm.71fc546097',
'Keep terminals alive until reset'
)}
</Label>
<p className="text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.b574994adc',
'Use End Remote Terminals or Reset Relay when you want to stop them.'
)}
</p>
</div>
<SettingsSwitch
checked={form.relayKeepAliveUntilReset}
disabled={disabled}
onChange={() =>
onFormChange((f) => ({
...f,
relayKeepAliveUntilReset: !f.relayKeepAliveUntilReset
}))
}
ariaLabel={translate(
'auto.components.settings.SshTargetForm.71fc546097',
'Keep terminals alive until reset'
)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="add-ssh-relay-grace-period" className="text-xs text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.55c56cf2c7',
'Timeout after disconnect (seconds)'
)}
</Label>
<Input
id="add-ssh-relay-grace-period"
type={form.relayKeepAliveUntilReset ? 'text' : 'number'}
value={
form.relayKeepAliveUntilReset
? translate('auto.components.settings.SshTargetForm.7c13f58c91', 'Until reset')
: form.relayGracePeriodSeconds
}
disabled={disabled || form.relayKeepAliveUntilReset}
onChange={(e) =>
onFormChange((f) => ({ ...f, relayGracePeriodSeconds: e.target.value }))
}
placeholder={String(DEFAULT_BOUNDED_SSH_RELAY_GRACE_PERIOD_SECONDS)}
min={MIN_SSH_RELAY_GRACE_PERIOD_SECONDS}
max={MAX_SSH_RELAY_GRACE_PERIOD_SECONDS}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.1b19b00e93',
'Bounded timeouts must be between 60 seconds and 7 days.'
)}
</p>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)
}
@@ -17,9 +17,12 @@ import { resolveSshHostRemoval } from '../sidebar/ssh-host-remove-resolution'
import { getAllWorktreesFromState } from '@/store/selectors'
import { toSshExecutionHostId } from '../../../../shared/execution-host'
import { translate } from '@/i18n/i18n'
import { useSshAddTargetIntent } from './use-ssh-add-target-intent'
export { getSshPaneSearchEntries } from './ssh-search'
export function SshPane(): React.JSX.Element {
type SshPaneProps = { addTargetIntentSignal?: number }
export function SshPane({ addTargetIntentSignal }: SshPaneProps): React.JSX.Element {
const [targets, setTargets] = useState<SshTarget[]>([])
// Why: connection states are already hydrated and kept up-to-date by the
// global store (via useIpcEvents.ts). Reading from the store avoids
@@ -83,6 +86,15 @@ export function SshPane(): React.JSX.Element {
return () => abortController.abort()
}, [loadTargets])
const openAddTargetForm = useCallback((): void => {
// Why: composer deep-links should land on the existing add form, not just
// the host management pane.
setEditingId(null)
setForm(EMPTY_FORM)
setShowForm(true)
}, [])
useSshAddTargetIntent(addTargetIntentSignal, openAddTargetForm)
const handleSave = async (): Promise<void> => {
const savePayload = buildSshTargetSavePayload(form)
if (!savePayload.ok) {
@@ -350,16 +362,7 @@ export function SshPane(): React.JSX.Element {
{translate('auto.components.settings.SshPane.51d7dba44d', 'Import')}
</Button>
{!showForm ? (
<Button
variant="outline"
size="xs"
onClick={() => {
setEditingId(null)
setForm(EMPTY_FORM)
setShowForm(true)
}}
className="gap-1.5"
>
<Button variant="outline" size="xs" onClick={openAddTargetForm} className="gap-1.5">
<Plus className="size-3" />
{translate('auto.components.settings.SshPane.639ceb3698', 'Add Target')}
</Button>
@@ -1,106 +0,0 @@
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { SettingsSwitch } from './SettingsFormControls'
import { SshTargetFormCollapsibleSection } from './SshTargetFormCollapsibleSection'
import type { EditingTarget } from './ssh-target-draft'
import { translate } from '@/i18n/i18n'
type SshTargetAdvancedConnectionSectionProps = {
open: boolean
onOpenChange: (open: boolean) => void
form: EditingTarget
onFormChange: (updater: (prev: EditingTarget) => EditingTarget) => void
}
export function SshTargetAdvancedConnectionSection({
open,
onOpenChange,
form,
onFormChange
}: SshTargetAdvancedConnectionSectionProps): React.JSX.Element {
return (
<SshTargetFormCollapsibleSection
open={open}
onOpenChange={onOpenChange}
title={translate('auto.components.settings.SshTargetForm.4a342f44c1', 'Advanced Connection')}
description={translate(
'auto.components.settings.SshTargetForm.e9609ddca6',
'Proxy, jump host, and connection reuse'
)}
>
<div className="space-y-1.5">
<Label>
{translate('auto.components.settings.SshTargetForm.c7d0e18ecb', 'Proxy Command')}
</Label>
<Input
value={form.proxyCommand}
onChange={(e) => onFormChange((f) => ({ ...f, proxyCommand: e.target.value }))}
placeholder={translate(
'auto.components.settings.SshTargetForm.f42d844544',
'e.g. cloudflared access ssh --hostname %h'
)}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.3b01ca44a0',
'Optional. Used for tunneling (e.g. Cloudflare Access, ProxyCommand).'
)}
</p>
</div>
<div className="space-y-1.5">
<Label>{translate('auto.components.settings.SshTargetForm.b2ab248ded', 'Jump Host')}</Label>
<Input
value={form.jumpHost}
onChange={(e) => onFormChange((f) => ({ ...f, jumpHost: e.target.value }))}
placeholder={translate(
'auto.components.settings.SshTargetForm.11bcb4507a',
'bastion.example.com'
)}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.feae1d1e69',
'Optional. Equivalent to ProxyJump / ssh -J.'
)}
</p>
</div>
<div className="flex items-start justify-between gap-4 py-1 text-xs">
<div className="min-w-0 flex-1 space-y-0.5">
<Label className="text-xs font-medium">
{translate(
'auto.components.settings.SshTargetForm.8c922dffba',
'Reuse SSH connection for faster setup'
)}
</Label>
<p className="text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.53e9aabfc0',
'Uses OpenSSH multiplexing when available. Turn off for hosts with custom SSH restrictions.'
)}
</p>
</div>
<SettingsSwitch
checked={form.systemSshConnectionReuse}
onChange={() =>
onFormChange((f) => ({
...f,
systemSshConnectionReuse: !f.systemSshConnectionReuse
}))
}
ariaLabel={translate(
'auto.components.settings.SshTargetForm.8c922dffba',
'Reuse SSH connection for faster setup'
)}
/>
</div>
</SshTargetFormCollapsibleSection>
)
}
export function hasAdvancedConnectionValues(form: EditingTarget): boolean {
return (
form.proxyCommand.trim().length > 0 ||
form.jumpHost.trim().length > 0 ||
!form.systemSshConnectionReuse
)
}
@@ -3,12 +3,12 @@ import { FileKey } from 'lucide-react'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { SshHostAdvancedFields } from './SshHostAdvancedFields'
import {
SshTargetAdvancedConnectionSection,
hasAdvancedConnectionValues
} from './SshTargetAdvancedConnectionSection'
import { SshTargetTerminalPersistenceSection } from './SshTargetTerminalPersistenceSection'
import { applyParsedSshHostInput, type EditingTarget } from './ssh-target-draft'
applyParsedSshHostInput,
hasAdvancedConnectionValues,
type EditingTarget
} from './ssh-target-draft'
import { translate } from '@/i18n/i18n'
export { EMPTY_FORM, type EditingTarget } from './ssh-target-draft'
@@ -27,9 +27,10 @@ export function SshTargetForm({
onSave,
onCancel
}: SshTargetFormProps): React.JSX.Element {
// Why: reveal Advanced by default when editing a target that already has custom proxy/jump/
// reuse values, so those aren't hidden; otherwise it starts collapsed.
const hasAdvancedConnectionFields = hasAdvancedConnectionValues(form)
const [advancedConnectionOpen, setAdvancedConnectionOpen] = useState(hasAdvancedConnectionFields)
const [terminalPersistenceOpen, setTerminalPersistenceOpen] = useState(true)
const [advancedOpen, setAdvancedOpen] = useState(hasAdvancedConnectionFields)
const lastEditingIdRef = useRef(editingId)
useEffect(() => {
@@ -37,8 +38,7 @@ export function SshTargetForm({
return
}
lastEditingIdRef.current = editingId
setAdvancedConnectionOpen(hasAdvancedConnectionFields)
setTerminalPersistenceOpen(true)
setAdvancedOpen(hasAdvancedConnectionFields)
}, [editingId, hasAdvancedConnectionFields])
return (
@@ -122,16 +122,11 @@ export function SshTargetForm({
)}
</p>
</div>
<SshTargetAdvancedConnectionSection
open={advancedConnectionOpen}
onOpenChange={setAdvancedConnectionOpen}
form={form}
onFormChange={onFormChange}
/>
<SshTargetTerminalPersistenceSection
open={terminalPersistenceOpen}
onOpenChange={setTerminalPersistenceOpen}
<SshHostAdvancedFields
open={advancedOpen}
onOpenChange={setAdvancedOpen}
form={form}
disabled={false}
onFormChange={onFormChange}
/>
</div>
@@ -1,50 +0,0 @@
import { ChevronDown } from 'lucide-react'
import { Button } from '../ui/button'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible'
import { cn } from '@/lib/utils'
type SshTargetFormCollapsibleSectionProps = {
open: boolean
onOpenChange: (open: boolean) => void
title: string
description: string
children: React.ReactNode
}
export function SshTargetFormCollapsibleSection({
open,
onOpenChange,
title,
description,
children
}: SshTargetFormCollapsibleSectionProps): React.JSX.Element {
return (
<Collapsible
open={open}
onOpenChange={onOpenChange}
className="col-span-2 border-t border-border/50 pt-2"
>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className="-ml-2 h-auto w-[calc(100%+0.5rem)] justify-between gap-3 px-2 py-1.5 text-left"
>
<span className="min-w-0 space-y-0.5">
<span className="block text-sm font-medium text-foreground">{title}</span>
<span className="block text-[11px] font-normal text-muted-foreground">
{description}
</span>
</span>
<ChevronDown
className={cn('size-4 shrink-0 transition-transform', open && 'rotate-180')}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="collapsible-height-content">
<div className="space-y-4 pt-3">{children}</div>
</CollapsibleContent>
</Collapsible>
)
}
@@ -1,98 +0,0 @@
import {
DEFAULT_BOUNDED_SSH_RELAY_GRACE_PERIOD_SECONDS,
MAX_SSH_RELAY_GRACE_PERIOD_SECONDS,
MIN_SSH_RELAY_GRACE_PERIOD_SECONDS
} from '../../../../shared/ssh-types'
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { SettingsSwitch } from './SettingsFormControls'
import { SshTargetFormCollapsibleSection } from './SshTargetFormCollapsibleSection'
import type { EditingTarget } from './ssh-target-draft'
import { translate } from '@/i18n/i18n'
type SshTargetTerminalPersistenceSectionProps = {
open: boolean
onOpenChange: (open: boolean) => void
form: EditingTarget
onFormChange: (updater: (prev: EditingTarget) => EditingTarget) => void
}
export function SshTargetTerminalPersistenceSection({
open,
onOpenChange,
form,
onFormChange
}: SshTargetTerminalPersistenceSectionProps): React.JSX.Element {
return (
<SshTargetFormCollapsibleSection
open={open}
onOpenChange={onOpenChange}
title={translate(
'auto.components.settings.SshTargetForm.92f80edbfd',
'Remote Terminal Persistence'
)}
description={translate(
'auto.components.settings.SshTargetForm.137e88ce8d',
'Remote terminals keep running after Orca disconnects from this host.'
)}
>
<div className="flex items-start justify-between gap-4 py-1 text-xs">
<div className="min-w-0 flex-1 space-y-0.5">
<Label className="text-xs font-medium">
{translate(
'auto.components.settings.SshTargetForm.71fc546097',
'Keep terminals alive until reset'
)}
</Label>
<p className="text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.b574994adc',
'Use End Remote Terminals or Reset Relay when you want to stop them.'
)}
</p>
</div>
<SettingsSwitch
checked={form.relayKeepAliveUntilReset}
onChange={() =>
onFormChange((f) => ({
...f,
relayKeepAliveUntilReset: !f.relayKeepAliveUntilReset
}))
}
ariaLabel={translate(
'auto.components.settings.SshTargetForm.71fc546097',
'Keep terminals alive until reset'
)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="ssh-relay-grace-period" className="text-xs text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.55c56cf2c7',
'Timeout after disconnect (seconds)'
)}
</Label>
<Input
id="ssh-relay-grace-period"
type={form.relayKeepAliveUntilReset ? 'text' : 'number'}
value={
form.relayKeepAliveUntilReset
? translate('auto.components.settings.SshTargetForm.7c13f58c91', 'Until reset')
: form.relayGracePeriodSeconds
}
onChange={(e) => onFormChange((f) => ({ ...f, relayGracePeriodSeconds: e.target.value }))}
placeholder={String(DEFAULT_BOUNDED_SSH_RELAY_GRACE_PERIOD_SECONDS)}
min={MIN_SSH_RELAY_GRACE_PERIOD_SECONDS}
max={MAX_SSH_RELAY_GRACE_PERIOD_SECONDS}
disabled={form.relayKeepAliveUntilReset}
/>
<p className="text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.SshTargetForm.1b19b00e93',
'Bounded timeouts must be between 60 seconds and 7 days.'
)}
</p>
</div>
</SshTargetFormCollapsibleSection>
)
}
@@ -137,6 +137,14 @@ export function getSshTargetDraftConnectionFields(draft: EditingTarget): {
}
}
export function hasAdvancedConnectionValues(form: EditingTarget): boolean {
return (
form.proxyCommand.trim().length > 0 ||
form.jumpHost.trim().length > 0 ||
!form.systemSshConnectionReuse
)
}
export function parseRelayGracePeriodSeconds(draft: EditingTarget): number {
return draft.relayKeepAliveUntilReset ? 0 : Number.parseInt(draft.relayGracePeriodSeconds, 10)
}
@@ -0,0 +1,19 @@
import { useEffect, useRef } from 'react'
export function useSshAddTargetIntent(
addTargetIntentSignal: number | undefined,
openAddTargetForm: () => void
): void {
const consumedAddTargetIntentSignalRef = useRef(0)
useEffect(() => {
if (
!addTargetIntentSignal ||
consumedAddTargetIntentSignalRef.current === addTargetIntentSignal
) {
return
}
consumedAddTargetIntentSignalRef.current = addTargetIntentSignal
openAddTargetForm()
}, [addTargetIntentSignal, openAddTargetForm])
}
@@ -33,6 +33,13 @@ export function AddRemoteHostDialog({
onOpenChange
}: AddRemoteHostDialogProps): React.JSX.Element {
const open = mode !== null
// Why: `mode` drives both open-state and which form renders. On close it goes null while the
// dialog is still animating out, so the title/fields would flash to the SSH default. Latch the
// last non-null mode for rendering so the closing dialog keeps showing what the user saw.
const [renderMode, setRenderMode] = useState<AddRemoteHostMode>(mode ?? 'ssh')
if (mode !== null && mode !== renderMode) {
setRenderMode(mode)
}
const [sshForm, setSshForm] = useState<EditingTarget>(EMPTY_FORM)
const [serverName, setServerName] = useState('')
const [pairingCode, setPairingCode] = useState('')
@@ -95,6 +102,9 @@ export function AddRemoteHostDialog({
}
const identityFile = sshForm.identityFile.trim() || undefined
const proxyCommand = sshForm.proxyCommand.trim() || undefined
const jumpHost = sshForm.jumpHost.trim() || undefined
const systemSshConnectionReuse = sshForm.systemSshConnectionReuse ? undefined : false
const target = {
label: sshForm.label.trim() || (username ? `${username}@${host}` : configHost),
configHost,
@@ -102,7 +112,10 @@ export function AddRemoteHostDialog({
port,
username,
relayGracePeriodSeconds: graceSeconds,
...(identityFile ? { identityFile } : {})
...(identityFile ? { identityFile } : {}),
...(proxyCommand ? { proxyCommand } : {}),
...(jumpHost ? { jumpHost } : {}),
...(systemSshConnectionReuse === false ? { systemSshConnectionReuse } : {})
}
setIsSaving(true)
@@ -223,7 +236,7 @@ export function AddRemoteHostDialog({
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>
{mode === 'server'
{renderMode === 'server'
? translate(
'auto.components.sidebar.AddRemoteHostDialog.serverTitle',
'Add remote server'
@@ -231,7 +244,7 @@ export function AddRemoteHostDialog({
: translate('auto.components.sidebar.AddRemoteHostDialog.sshTitle', 'Add SSH host')}
</DialogTitle>
<DialogDescription>
{mode === 'server'
{renderMode === 'server'
? translate(
'auto.components.sidebar.AddRemoteHostDialog.serverDescription',
'Pair with Orca running on another computer.'
@@ -243,7 +256,7 @@ export function AddRemoteHostDialog({
</DialogDescription>
</DialogHeader>
{mode === 'server' ? (
{renderMode === 'server' ? (
<RemoteServerFields
name={serverName}
pairingCode={pairingCode}
@@ -262,7 +275,7 @@ export function AddRemoteHostDialog({
)}
<DialogFooter className="sm:justify-between">
{mode === 'ssh' ? (
{renderMode === 'ssh' ? (
<button
type="button"
className="self-center text-left text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:cursor-not-allowed disabled:opacity-50"
@@ -290,7 +303,9 @@ export function AddRemoteHostDialog({
</Button>
<Button
type="button"
onClick={mode === 'server' ? () => void saveRemoteServer() : () => void saveSshHost()}
onClick={
renderMode === 'server' ? () => void saveRemoteServer() : () => void saveSshHost()
}
disabled={isSaving || isImporting}
>
{isSaving
@@ -1,7 +1,9 @@
import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { translate } from '@/i18n/i18n'
import { applyParsedSshHostInput, type EditingTarget } from '../settings/ssh-target-draft'
import { SshHostAdvancedFields } from '../settings/SshHostAdvancedFields'
export function SshHostFields({
form,
@@ -14,6 +16,7 @@ export function SshHostFields({
onFormChange: (updater: (prev: EditingTarget) => EditingTarget) => void
onSubmit: () => void
}) {
const [advancedOpen, setAdvancedOpen] = useState(false)
return (
<form
className="grid gap-3 sm:grid-cols-2"
@@ -103,12 +106,13 @@ export function SshHostFields({
)}
/>
</div>
<p className="text-xs text-muted-foreground sm:col-span-2">
{translate(
'auto.components.sidebar.AddRemoteHostDialog.sshPersistenceDefault',
'Remote terminals on this host stay alive until you end them or reset the relay.'
)}
</p>
<SshHostAdvancedFields
open={advancedOpen}
onOpenChange={setAdvancedOpen}
form={form}
disabled={disabled}
onFormChange={onFormChange}
/>
</form>
)
}
@@ -1,5 +1,6 @@
import { LoaderCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { translate } from '@/i18n/i18n'
import type { SparsePresetDirectoryParseResult } from '@/lib/sparse-preset-draft'
@@ -34,7 +35,10 @@ export function SparseCheckoutPresetDraftForm({
onSave
}: SparseCheckoutPresetDraftFormProps): React.JSX.Element {
return (
// Why: bg-popover matches the opaque surface the cmdk list (Command root) paints, so the draft
// form doesn't show the translucent PopoverContent through it while the list looks solid.
<form
className="rounded-md bg-popover text-popover-foreground"
onSubmit={(event) => {
event.preventDefault()
onSave()
@@ -56,22 +60,20 @@ export function SparseCheckoutPresetDraftForm({
>
{translate('auto.components.sparse.SparseCheckoutPresetSelect.b3a500c623', 'Name')}
</label>
<div className="rounded-md border border-border/70 bg-muted/20 px-2.5 shadow-xs transition focus-within:border-ring/70 focus-within:ring-1 focus-within:ring-ring/30">
<input
id="sparse-preset-name"
ref={setNameInputNode}
value={draft.name}
onChange={(event) => onDraftChange({ ...draft, name: event.target.value })}
placeholder={translate(
'auto.components.sparse.SparseCheckoutPresetSelect.064c1e2d12',
'Renderer UI'
)}
maxLength={80}
autoComplete="off"
spellCheck={false}
className="h-8 w-full bg-transparent text-xs text-foreground outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground"
/>
</div>
<Input
id="sparse-preset-name"
ref={setNameInputNode}
value={draft.name}
onChange={(event) => onDraftChange({ ...draft, name: event.target.value })}
placeholder={translate(
'auto.components.sparse.SparseCheckoutPresetSelect.064c1e2d12',
'Renderer UI'
)}
maxLength={80}
autoComplete="off"
spellCheck={false}
className="h-8 text-xs"
/>
</div>
<div className="space-y-1">
<label
@@ -83,20 +85,20 @@ export function SparseCheckoutPresetDraftForm({
'Directories'
)}
</label>
<div className="rounded-md border border-border/70 bg-muted/20 px-2.5 py-1.5 shadow-xs transition focus-within:border-ring/70 focus-within:ring-1 focus-within:ring-ring/30">
<textarea
id="sparse-preset-directories"
value={draft.directoriesText}
onChange={(event) => onDraftChange({ ...draft, directoriesText: event.target.value })}
placeholder={translate(
'auto.components.sparse.SparseCheckoutPresetSelect.ddbcaef7be',
'src/renderer packages/ui'
)}
rows={3}
spellCheck={false}
className="max-h-28 w-full min-w-0 resize-none bg-transparent font-mono text-xs leading-5 text-foreground outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground"
/>
</div>
{/* Why: match the app's canonical textarea (composer Note field) — border-input +
standard focus ring — instead of a one-off wrapper. font-mono since these are paths. */}
<textarea
id="sparse-preset-directories"
value={draft.directoriesText}
onChange={(event) => onDraftChange({ ...draft, directoriesText: event.target.value })}
placeholder={translate(
'auto.components.sparse.SparseCheckoutPresetSelect.ddbcaef7be',
'src/renderer packages/ui'
)}
rows={3}
spellCheck={false}
className="max-h-28 w-full min-w-0 resize-none rounded-md border border-input bg-transparent px-3 py-1.5 font-mono text-xs leading-5 shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
/>
</div>
</div>
<div className="flex min-h-11 items-center justify-between gap-3 border-t border-border px-3 py-2">
@@ -1,6 +1,7 @@
import React, { useCallback, useMemo, useRef, useState } from 'react'
import { Check, ChevronsUpDown, LoaderCircle, Pencil, Plus, RefreshCcw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Command, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
@@ -225,7 +226,7 @@ export default function SparseCheckoutPresetSelect({
aria-expanded={open}
aria-busy={isLoadingPresets}
disabled={disabled || isLoadingPresets}
className="h-9 w-full justify-between px-3 text-sm font-normal text-foreground"
className="h-9 w-full justify-between border-input px-3 text-sm font-normal text-foreground focus:border-ring focus:ring-[3px] focus:ring-ring/50"
>
<span className="truncate">{triggerLabel}</span>
{isLoadingPresets ? (
@@ -281,39 +282,37 @@ export default function SparseCheckoutPresetSelect({
</button>
</div>
) : (
<div>
<div className="py-1">
<button
type="button"
className="mx-1 flex h-9 w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 text-left text-xs hover:bg-accent hover:text-accent-foreground"
onClick={handleSelectOff}
// Why: cmdk Command/CommandItem so this dropdown matches the other composer pickers
// (run-target, project, agent) — same padding, keyboard-highlight, and check placement.
<Command value={selectedPreset ? `preset:${selectedPreset.id}` : 'off'}>
<CommandList>
<CommandItem
value="off"
onSelect={handleSelectOff}
className="items-center gap-2 px-3 py-2"
>
<Check className={cn('size-4', selectedPreset ? 'opacity-0' : 'opacity-100')} />
{translate('auto.components.sparse.SparseCheckoutPresetSelect.c7f9b3f0c1', 'Off')}
</button>
</div>
{visiblePresets.length > 0 ? (
<>
<div className="h-px bg-border" />
<div className="space-y-0.5 py-1">
<span className="truncate">
{translate('auto.components.sparse.SparseCheckoutPresetSelect.c7f9b3f0c1', 'Off')}
</span>
</CommandItem>
{visiblePresets.length > 0 ? (
<>
<CommandSeparator />
{visiblePresets.map((preset) => (
<div
<CommandItem
key={preset.id}
className="mx-1 flex items-center rounded-md hover:bg-accent hover:text-accent-foreground"
value={`preset:${preset.id}`}
onSelect={() => handleSelectPreset(preset)}
className="items-center gap-2 px-3 py-2"
>
<button
type="button"
className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-l-md px-2 text-left text-xs"
onClick={() => handleSelectPreset(preset)}
>
<Check
className={cn(
'size-4 shrink-0',
selectedPreset?.id === preset.id ? 'opacity-100' : 'opacity-0'
)}
/>
<span className="truncate">{preset.name}</span>
</button>
<Check
className={cn(
'size-4 shrink-0',
selectedPreset?.id === preset.id ? 'opacity-100' : 'opacity-0'
)}
/>
<span className="min-w-0 flex-1 truncate">{preset.name}</span>
<Button
type="button"
variant="ghost"
@@ -323,31 +322,41 @@ export default function SparseCheckoutPresetSelect({
'Edit {{value0}}',
{ value0: preset.name }
)}
className="mr-1 size-7 shrink-0 rounded-md text-muted-foreground hover:bg-background/35 hover:text-foreground"
onClick={() => startEditPreset(preset)}
className="ml-1 size-6 shrink-0 rounded-md text-muted-foreground hover:bg-background/35 hover:text-foreground"
// Why: the pencil opens the edit draft; stop the event so cmdk doesn't
// also select the preset row underneath it.
onPointerDown={(event) => {
event.preventDefault()
event.stopPropagation()
}}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
startEditPreset(preset)
}}
>
<Pencil className="size-3.5" />
</Button>
</div>
</CommandItem>
))}
</div>
</>
) : null}
<div className="border-t border-border">
<Button
type="button"
variant="ghost"
onClick={startNewPreset}
className="mx-1 my-1 h-8 w-[calc(100%-0.5rem)] justify-start rounded-md px-2 text-xs font-normal"
</>
) : null}
<CommandSeparator />
<CommandItem
value="new-preset"
onSelect={startNewPreset}
className="items-center gap-2 px-3 py-2 text-muted-foreground"
>
<Plus className="size-3.5 text-muted-foreground" />
{translate(
'auto.components.sparse.SparseCheckoutPresetSelect.c4ac80151d',
'New preset'
)}
</Button>
</div>
</div>
<Plus className="size-4 shrink-0" />
<span className="truncate">
{translate(
'auto.components.sparse.SparseCheckoutPresetSelect.c4ac80151d',
'New preset'
)}
</span>
</CommandItem>
</CommandList>
</Command>
)}
</PopoverContent>
</Popover>
+15 -7
View File
@@ -1195,15 +1195,18 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const selectedRepoSettingsRef = useRef(selectedRepoSettings)
selectedRepoSettingsRef.current = selectedRepoSettings
// Why: depend on the persisted policy *value*, not the selectedRepo object. Background repo
// refetches (git polling) hand back a new repo reference with the same hookSettings; keying on
// the object would re-run this and briefly flip the toggle back to the stale value — the glitch.
const persistedSetupAgentStartupPolicy = getRepoSetupAgentStartupPolicy(selectedRepo)
useEffect(() => {
const nextPolicy = getRepoSetupAgentStartupPolicy(selectedRepo)
const draft = setupAgentStartupPolicyDraftRef.current
if (draft?.repoId === repoId && draft.policy !== nextPolicy) {
if (draft?.repoId === repoId && draft.policy !== persistedSetupAgentStartupPolicy) {
return
}
setupAgentStartupPolicyRef.current = nextPolicy
setSetupAgentStartupPolicy(nextPolicy)
}, [repoId, selectedRepo])
setupAgentStartupPolicyRef.current = persistedSetupAgentStartupPolicy
setSetupAgentStartupPolicy(persistedSetupAgentStartupPolicy)
}, [repoId, persistedSetupAgentStartupPolicy])
const persistSetupAgentStartupPolicy = useCallback(
async (
@@ -1691,7 +1694,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
}
}
void readRuntimeIssueCommand(selectedRepoSettings, repoId)
void readRuntimeIssueCommand(selectedRepoSettingsRef.current, repoId)
.then((result) => {
if (!cancelled) {
setIssueCommandTemplate(result.effectiveContent ?? '')
@@ -1708,13 +1711,18 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
return () => {
cancelled = true
}
// Why: key on the stable runtime-env id, not the selectedRepoSettings object. `updateRepo`
// (e.g. saving the setup toggle from this very composer) replaces selectedRepo — and thus the
// memoized selectedRepoSettings — by reference; depending on the object would re-run this
// effect, blank yamlHooks to null, and make the whole setup section vanish for a frame.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
commitHookCheckIfCurrent,
enableIssueAutomation,
loadHookCheckForRepo,
repoId,
selectedRepoIsGit,
selectedRepoSettings
runtimeEnvironmentId
])
const onConnectSelectedRepo = useCallback(async (): Promise<void> => {
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
import { getExecutionHostLabel, type ExecutionHostId } from '../../../shared/execution-host'
import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host-registry'
import type {
ExecutionHostHealth,
ExecutionHostRegistryEntry
} from '../../../shared/execution-host-registry'
import {
PROJECT_HOST_SETUP_RUNTIME_CAPABILITY,
WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY
@@ -157,6 +160,29 @@ describe('buildProjectHostSetupOptions', () => {
expect(options.some((o) => String(o.hostId).includes('runtime-ssh-'))).toBe(false)
})
it('omits hidden host categories from setup-needed choices', () => {
const runtimeSshHostId = 'ssh:runtime-ssh-orca-e37aa3a9' as ExecutionHostId
const ephemeralHostId = 'runtime:90d880b2-de1b-44be-b7b8-8e15274e184e' as ExecutionHostId
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [
host('local'),
host(runtimeSshHostId),
host(ephemeralHostId, {
source: 'ephemeral-vm',
capabilities: FULL_HOST_MODEL_RUNTIME_CAPABILITIES
})
],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options).toEqual([
expect.objectContaining({ id: 'local', kind: 'ready', label: LOCAL_HOST_LABEL })
])
})
it('omits setups that are not ready or cannot create through an eligible repo', () => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
@@ -193,6 +219,110 @@ describe('buildProjectHostSetupOptions', () => {
])
})
it.each([
['connecting' as const, 'Connecting to host'],
['disconnected' as const, 'Connect this host to set up projects'],
['error' as const, 'Host connection needs attention']
])(
'marks %s hosts unavailable before project setup guidance',
(health: ExecutionHostHealth, detail: string) => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [host('local'), host('ssh:builder', { label: 'Builder', health })],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options.at(-1)).toMatchObject({
id: 'needs-setup:ssh:builder',
kind: 'needs-setup',
label: 'Builder',
detail,
isAvailable: false
})
}
)
it.each([
['connecting' as const, false],
['disconnected' as const, false],
['error' as const, true]
])('flags only errored %s hosts for attention', (health: ExecutionHostHealth, attention) => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [host('local'), host('ssh:builder', { label: 'Builder', health })],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options.at(-1)).toMatchObject({ kind: 'needs-setup', attention })
})
it.each([
['ssh:builder' as const, { kind: 'ssh', targetId: 'builder' }],
['runtime:gpu' as const, { kind: 'runtime', environmentId: 'gpu' }]
])('adds a connect action for disconnected %s setup-needed hosts', (hostId, connectAction) => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [
host('local'),
host(hostId, {
label: 'Builder',
health: 'disconnected'
})
],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options.at(-1)).toMatchObject({
id: `needs-setup:${hostId}`,
kind: 'needs-setup',
connectAction
})
})
it('adds a connect action for errored setup-needed hosts', () => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [
host('local'),
host('ssh:builder', {
label: 'Builder',
health: 'error'
})
],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options.at(-1)).toMatchObject({
id: 'needs-setup:ssh:builder',
kind: 'needs-setup',
connectAction: { kind: 'ssh', targetId: 'builder' }
})
})
it.each(['available' as const, 'connecting' as const, 'blocked' as const])(
'does not add a connect action for %s setup-needed hosts',
(health) => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
eligibleRepos: [repo('local-repo')],
hosts: [
host('local'),
host('ssh:builder', {
label: 'Builder',
health
})
],
projectHostSetups: [setup('local', 'project-1', 'local', 'local-repo')]
})
expect(options.at(-1)).not.toHaveProperty('connectAction')
}
)
it('shows pending setup status for known hosts with non-ready setup metadata', () => {
const options = buildProjectHostSetupOptions({
projectId: 'project-1',
@@ -32,6 +32,10 @@ export type ProjectHostSetupOption =
label: string
detail: string
isAvailable: boolean
// Why: only a genuine connection error warrants an alarm glyph; a dormant
// disconnected host is merely not-yet-connected, not broken.
attention: boolean
connectAction?: { kind: 'ssh'; targetId: string } | { kind: 'runtime'; environmentId: string }
}
export type ReadyProjectHostSetupOption = Extract<ProjectHostSetupOption, { kind: 'ready' }>
@@ -150,6 +154,7 @@ function buildNeedsSetupOptions({
.map((host) => {
const pendingSetup = pendingSetupByHost.get(host.id)
const availability = getHostSetupAvailability(host)
const connectAction = getHostConnectAction(host)
return {
id: `needs-setup:${host.id}`,
kind: 'needs-setup' as const,
@@ -161,7 +166,9 @@ function buildNeedsSetupOptions({
? getPendingSetupDetail(pendingSetup)
: 'Project not set up on this host'
: availability.detail,
isAvailable: availability.isAvailable
isAvailable: availability.isAvailable,
attention: host.health === 'error',
...(connectAction ? { connectAction } : {})
}
})
}
@@ -188,6 +195,15 @@ function getHostSetupAvailability(host: ExecutionHostRegistryEntry): {
detail: 'Orca server version is incompatible'
}
}
// Why: disconnected hosts cannot confirm project setup or runtime capabilities,
// so connection state needs to win over setup guidance.
const healthUnavailableDetail = getHostHealthUnavailableDetail(host.health)
if (healthUnavailableDetail) {
return {
isAvailable: false,
detail: healthUnavailableDetail
}
}
if (host.kind === 'runtime') {
if (!host.capabilities) {
return {
@@ -211,6 +227,39 @@ function getHostSetupAvailability(host: ExecutionHostRegistryEntry): {
}
}
function getHostHealthUnavailableDetail(
health: ExecutionHostRegistryEntry['health']
): string | null {
switch (health) {
case 'connecting':
return 'Connecting to host'
case 'disconnected':
return 'Connect this host to set up projects'
case 'error':
return 'Host connection needs attention'
case 'available':
case 'blocked':
case 'local':
return null
}
}
function getHostConnectAction(
host: ExecutionHostRegistryEntry
): NeedsSetupProjectHostOption['connectAction'] | undefined {
if (host.health !== 'disconnected' && host.health !== 'error') {
return undefined
}
const parsed = parseExecutionHostId(host.id)
if (parsed?.kind === 'ssh') {
return { kind: 'ssh', targetId: parsed.targetId }
}
if (parsed?.kind === 'runtime') {
return { kind: 'runtime', environmentId: parsed.environmentId }
}
return undefined
}
function getPendingSetupDetail(setup: ProjectHostSetup): string {
switch (setup.setupState) {
case 'not-set-up':
+1 -1
View File
@@ -738,7 +738,7 @@ export type UISlice = {
pane: SettingsNavTarget
repoId: string | null
sectionId?: string
intent?: 'add-quick-command'
intent?: 'add-quick-command' | 'add-remote-orca-server' | 'add-ssh-host'
} | null
openSettingsTarget: (target: NonNullable<UISlice['settingsNavigationTarget']>) => void
clearSettingsTarget: () => void