diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.test.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.test.tsx index 2883fdc5c..e3af7f426 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.test.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.test.tsx @@ -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: () => })) +// 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 ?
: null +})) + vi.mock('@/components/sparse/SparseCheckoutPresetSelect', () => ({ default: () =>
})) @@ -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> = {} ) { @@ -195,13 +280,51 @@ function changeInputValue(input: HTMLInputElement, value: string): void { }) } +function openRunTargetPicker(container: HTMLElement): void { + const runTargetButton = container.querySelector('button[role="combobox"]') + expect(runTargetButton).toBeTruthy() + act(() => runTargetButton?.click()) +} + +function findRunTargetItem(label: string): HTMLElement | undefined { + return [...document.body.querySelectorAll('[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( + const waitSwitch = current.container.querySelector( '[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( + '[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)[] = [] diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index c952431a5..02542787f 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -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['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(promise: Promise): Promise { + let timer: ReturnType | undefined + const timeout = new Promise((_, 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 } 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>( + () => 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 => { + 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 ( @@ -403,11 +527,13 @@ function WorkspaceRunTargetCombobox({ 'No run targets are ready for this project.' )} - {hostOptions.map((option) => ( + {readyHostOptions.map((option) => ( handleHostSelect(option.id)} + onPointerEnter={closeSubmenus} + onFocus={closeSubmenus} className="items-center gap-2 px-3 py-2" > ))} + {/* 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 ? ( + <> + + {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. + {}} + onPointerEnter={closeSubmenus} + onFocus={closeSubmenus} + className="items-center gap-2 px-3 py-2" + > +
+ + {/* 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) ? ( + + ) : option.attention ? ( + + ) : ( + + )} +
+
{option.label}
+
+ {option.detail} +
+
+
+ {option.connectAction && onConnectHost ? ( + + ) : null} +
+ ))} + + ) : 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 ? ( + + ) : null} {recipes.length > 0 ? ( {/* Why: a real CommandItem (not a raw button) so cmdk registers it — fixes missing rows, uneven height, and double-highlight. */} setVmRecipesOpen(true)} + onSelect={openVmRecipesSubmenu} + onPointerEnter={openVmRecipesSubmenu} + onFocus={openVmRecipesSubmenu} className="items-center gap-2 px-3 py-2" > ) : null} + + + + + +
+
+ {translate('auto.components.NewWorkspaceComposerCard.addHost', 'Add host')} +
+
+ {translate( + 'auto.components.NewWorkspaceComposerCard.addHostHint', + 'Register another machine or Orca server' + )} +
+
+ +
+
+ + {/* 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. */} + + + + +
+
+ {translate( + 'auto.components.NewWorkspaceComposerCard.addSshHost', + 'Add SSH host' + )} +
+
+ {translate( + 'auto.components.NewWorkspaceComposerCard.addSshHostHint', + 'Use an existing machine over SSH' + )} +
+
+
+ + +
+
+ {translate( + 'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServer', + 'Add Remote Orca Server' + )} +
+
+ {translate( + 'auto.components.NewWorkspaceComposerCard.addRemoteOrcaServerHint', + 'Pair another Orca runtime' + )} +
+
+
+
+
+
+
@@ -494,47 +781,14 @@ function WorkspaceRunTargetCombobox({ ) } -function SetupCommandPreview({ - setupConfig, - headerAction -}: { - setupConfig: SetupConfig - headerAction?: React.ReactNode -}): React.JSX.Element { - if (setupConfig.source === 'yaml') { - return ( -
-
-
- {translate('auto.components.NewWorkspaceComposerCard.23bb365554', 'orca.yaml')} -
- {headerAction} -
- {/* Why: long orca.yaml scripts must not grow the create dialog past the viewport. */} -
-          {setupConfig.command}
-        
-
- ) - } - +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 ( -
-
-
- {setupConfig.source === 'both' - ? translate( - 'auto.components.NewWorkspaceComposerCard.e5db1b0419', - 'Combined setup command' - ) - : translate( - 'auto.components.NewWorkspaceComposerCard.7711ad5122', - 'Local setup command' - )} -
- {headerAction} -
-
+    
+
         {setupConfig.command}
       
@@ -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(null) + const handleAddSshHost = React.useCallback((): void => { + setAddRemoteHostMode('ssh') + }, []) + const handleAddRemoteServer = React.useCallback((): void => { + setAddRemoteHostMode('server') + }, []) + const handleConnectRunTargetHost = React.useCallback( + async (option: NeedsSetupProjectHostOption): Promise => { + 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(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) => { 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({ )}

) : null} - {readyProjectHostSetupOptions.length > 1 || ephemeralVmRecipes.length > 0 ? ( + {shouldShowRunTargetPicker ? (
{ephemeralVmRecipeError ? (

@@ -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. */}

+ {/* 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. */}
- {/* Why: `orca.yaml` is the committed source of truth, so the preview reconstructs the real YAML shape rather than a raw shell blob. */} - + {/* 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. */} + + + {/* 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 ? ( +
+ {requiresExplicitSetupChoice ? null : ( +
+ + {setupRunLabel} + + + onSetupDecisionChange( + resolvedSetupDecision === 'run' ? 'skip' : 'run' + ) + } + ariaLabel={setupRunLabel} + /> +
+ )} + {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). +
- + {translate( + 'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent', + 'Wait for setup to complete before starting agent' )} - /> + + + {translate( + 'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgentHelp', + 'Turn this on when setup installs dependencies, MCP servers, or config files the agent needs during startup.' + )} + - - onSetupDecisionChange(event.target.checked ? 'run' : 'skip') + + 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' + )} /> - {setupRunLabel} - - ) - } - /> +
+ ) : null} +
+ ) : null} {requiresExplicitSetupChoice ? (
@@ -1335,39 +1695,6 @@ export default function NewWorkspaceComposerCard({ ) : null}
) : null} - - {showSetupAgentStartupPolicy ? ( -
- - - {translate( - 'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent', - 'Wait for setup to complete before starting agent' - )} - - - {translate( - 'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgentHelp', - 'Turn this on when setup installs dependencies, MCP servers, or config files the agent needs during startup.' - )} - - - - onSetupAgentStartupPolicyChange( - setupAgentStartupPolicy === 'wait-for-setup' - ? 'start-immediately' - : 'wait-for-setup' - ) - } - ariaLabel={translate( - 'auto.components.NewWorkspaceComposerCard.waitForSetupBeforeAgent', - 'Wait for setup to complete before starting agent' - )} - /> -
- ) : null}
) : null} @@ -1465,6 +1792,10 @@ export default function NewWorkspaceComposerCard({
+ {/* 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. */} +
) } diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index fb27f84cb..f04a8f80d 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -309,10 +309,11 @@ function QuickTabBody({ { diff --git a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx index af3e2be3e..180432395 100644 --- a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx +++ b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx @@ -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 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([]) const [isLoading, setIsLoading] = useState(false) @@ -268,6 +270,7 @@ export function RuntimeEnvironmentsPane({ const [removeError, setRemoveError] = useState(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 diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index d35ca4023..fdba33bf0 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -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} @@ -1615,7 +1622,9 @@ function Settings(): React.JSX.Element { )} searchEntries={getSectionSearchEntries('ssh')} > - {isSectionMounted('ssh') ? : null} + {isSectionMounted('ssh') ? ( + + ) : null} ) : null} diff --git a/src/renderer/src/components/settings/SshHostAdvancedFields.tsx b/src/renderer/src/components/settings/SshHostAdvancedFields.tsx new file mode 100644 index 000000000..3be7dca8f --- /dev/null +++ b/src/renderer/src/components/settings/SshHostAdvancedFields.tsx @@ -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 ( + + + {/* 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. */} + + + +
+
+ + onFormChange((f) => ({ ...f, proxyCommand: e.target.value }))} + placeholder={translate( + 'auto.components.settings.SshTargetForm.f42d844544', + 'e.g. cloudflared access ssh --hostname %h' + )} + /> +

+ {translate( + 'auto.components.settings.SshTargetForm.3b01ca44a0', + 'Optional. Used for tunneling (e.g. Cloudflare Access, ProxyCommand).' + )} +

+
+
+ + onFormChange((f) => ({ ...f, jumpHost: e.target.value }))} + placeholder={translate( + 'auto.components.settings.SshTargetForm.11bcb4507a', + 'bastion.example.com' + )} + /> +

+ {translate( + 'auto.components.settings.SshTargetForm.feae1d1e69', + 'Optional. Equivalent to ProxyJump / ssh -J.' + )} +

+
+
+
+ +

+ {translate( + 'auto.components.settings.SshTargetForm.53e9aabfc0', + 'Uses OpenSSH multiplexing when available. Turn off for hosts with custom SSH restrictions.' + )} +

+
+ + onFormChange((f) => ({ + ...f, + systemSshConnectionReuse: !f.systemSshConnectionReuse + })) + } + ariaLabel={translate( + 'auto.components.settings.SshTargetForm.8c922dffba', + 'Reuse SSH connection for faster setup' + )} + /> +
+
+
+ +

+ {translate( + 'auto.components.settings.SshTargetForm.b574994adc', + 'Use End Remote Terminals or Reset Relay when you want to stop them.' + )} +

+
+ + onFormChange((f) => ({ + ...f, + relayKeepAliveUntilReset: !f.relayKeepAliveUntilReset + })) + } + ariaLabel={translate( + 'auto.components.settings.SshTargetForm.71fc546097', + 'Keep terminals alive until reset' + )} + /> +
+
+ + + 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} + /> +

+ {translate( + 'auto.components.settings.SshTargetForm.1b19b00e93', + 'Bounded timeouts must be between 60 seconds and 7 days.' + )} +

+
+
+
+
+ ) +} diff --git a/src/renderer/src/components/settings/SshPane.tsx b/src/renderer/src/components/settings/SshPane.tsx index 2e66ca382..6bfde5b47 100644 --- a/src/renderer/src/components/settings/SshPane.tsx +++ b/src/renderer/src/components/settings/SshPane.tsx @@ -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([]) // 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 => { const savePayload = buildSshTargetSavePayload(form) if (!savePayload.ok) { @@ -350,16 +362,7 @@ export function SshPane(): React.JSX.Element { {translate('auto.components.settings.SshPane.51d7dba44d', 'Import')} {!showForm ? ( - diff --git a/src/renderer/src/components/settings/SshTargetAdvancedConnectionSection.tsx b/src/renderer/src/components/settings/SshTargetAdvancedConnectionSection.tsx deleted file mode 100644 index 0bdbd3d35..000000000 --- a/src/renderer/src/components/settings/SshTargetAdvancedConnectionSection.tsx +++ /dev/null @@ -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 ( - -
- - onFormChange((f) => ({ ...f, proxyCommand: e.target.value }))} - placeholder={translate( - 'auto.components.settings.SshTargetForm.f42d844544', - 'e.g. cloudflared access ssh --hostname %h' - )} - /> -

- {translate( - 'auto.components.settings.SshTargetForm.3b01ca44a0', - 'Optional. Used for tunneling (e.g. Cloudflare Access, ProxyCommand).' - )} -

-
-
- - onFormChange((f) => ({ ...f, jumpHost: e.target.value }))} - placeholder={translate( - 'auto.components.settings.SshTargetForm.11bcb4507a', - 'bastion.example.com' - )} - /> -

- {translate( - 'auto.components.settings.SshTargetForm.feae1d1e69', - 'Optional. Equivalent to ProxyJump / ssh -J.' - )} -

-
-
-
- -

- {translate( - 'auto.components.settings.SshTargetForm.53e9aabfc0', - 'Uses OpenSSH multiplexing when available. Turn off for hosts with custom SSH restrictions.' - )} -

-
- - onFormChange((f) => ({ - ...f, - systemSshConnectionReuse: !f.systemSshConnectionReuse - })) - } - ariaLabel={translate( - 'auto.components.settings.SshTargetForm.8c922dffba', - 'Reuse SSH connection for faster setup' - )} - /> -
-
- ) -} - -export function hasAdvancedConnectionValues(form: EditingTarget): boolean { - return ( - form.proxyCommand.trim().length > 0 || - form.jumpHost.trim().length > 0 || - !form.systemSshConnectionReuse - ) -} diff --git a/src/renderer/src/components/settings/SshTargetForm.tsx b/src/renderer/src/components/settings/SshTargetForm.tsx index fbba5918e..cec3d8b8b 100644 --- a/src/renderer/src/components/settings/SshTargetForm.tsx +++ b/src/renderer/src/components/settings/SshTargetForm.tsx @@ -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({ )}

- - diff --git a/src/renderer/src/components/settings/SshTargetFormCollapsibleSection.tsx b/src/renderer/src/components/settings/SshTargetFormCollapsibleSection.tsx deleted file mode 100644 index 13d9b3e78..000000000 --- a/src/renderer/src/components/settings/SshTargetFormCollapsibleSection.tsx +++ /dev/null @@ -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 ( - - - - - -
{children}
-
-
- ) -} diff --git a/src/renderer/src/components/settings/SshTargetTerminalPersistenceSection.tsx b/src/renderer/src/components/settings/SshTargetTerminalPersistenceSection.tsx deleted file mode 100644 index 0306bc3d3..000000000 --- a/src/renderer/src/components/settings/SshTargetTerminalPersistenceSection.tsx +++ /dev/null @@ -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 ( - -
-
- -

- {translate( - 'auto.components.settings.SshTargetForm.b574994adc', - 'Use End Remote Terminals or Reset Relay when you want to stop them.' - )} -

-
- - onFormChange((f) => ({ - ...f, - relayKeepAliveUntilReset: !f.relayKeepAliveUntilReset - })) - } - ariaLabel={translate( - 'auto.components.settings.SshTargetForm.71fc546097', - 'Keep terminals alive until reset' - )} - /> -
-
- - 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} - /> -

- {translate( - 'auto.components.settings.SshTargetForm.1b19b00e93', - 'Bounded timeouts must be between 60 seconds and 7 days.' - )} -

-
-
- ) -} diff --git a/src/renderer/src/components/settings/ssh-target-draft.ts b/src/renderer/src/components/settings/ssh-target-draft.ts index 2719f62ad..b9100232d 100644 --- a/src/renderer/src/components/settings/ssh-target-draft.ts +++ b/src/renderer/src/components/settings/ssh-target-draft.ts @@ -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) } diff --git a/src/renderer/src/components/settings/use-ssh-add-target-intent.ts b/src/renderer/src/components/settings/use-ssh-add-target-intent.ts new file mode 100644 index 000000000..f57aa4f2a --- /dev/null +++ b/src/renderer/src/components/settings/use-ssh-add-target-intent.ts @@ -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]) +} diff --git a/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx b/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx index 705d55370..1c31dfebe 100644 --- a/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx +++ b/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx @@ -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(mode ?? 'ssh') + if (mode !== null && mode !== renderMode) { + setRenderMode(mode) + } const [sshForm, setSshForm] = useState(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({ - {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')} - {mode === 'server' + {renderMode === 'server' ? translate( 'auto.components.sidebar.AddRemoteHostDialog.serverDescription', 'Pair with Orca running on another computer.' @@ -243,7 +256,7 @@ export function AddRemoteHostDialog({ - {mode === 'server' ? ( + {renderMode === 'server' ? ( - {mode === 'ssh' ? ( + {renderMode === 'ssh' ? (