feat(web): suggest ssh hosts in a dropdown under the host field (#9171)

Co-authored-by: shivam <[email protected]>
This commit is contained in:
oliverandshivam authored and GitHub committed 2026-09-03 06:07:50 +00:00
1 parent 9f9359bd81
commit b5f4e8137b
9 files changed
+365 -185

No files matched your search

@@ -21,6 +21,7 @@ import {
fetchSshEnvironmentDescriptor,
fetchSshSessionState,
issueSshWebSocketTicket,
resolveSshHost,
resolveSshPasswordPrompt,
} from "./methods/sshEnvironment.ts";
import {
@@ -68,6 +69,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(resolveSshHost);
yield* ipc.handle(ensureSshEnvironment);
yield* ipc.handle(disconnectSshEnvironment);
yield* ipc.handle(fetchSshEnvironmentDescriptor);
+1
View File
@@ -29,6 +29,7 @@ export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const RESOLVE_SSH_HOST_CHANNEL = "desktop:resolve-ssh-host";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
export const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
@@ -117,6 +117,16 @@ export const discoverSshHosts = DesktopIpc.makeIpcMethod({
}),
});
export const resolveSshHost = DesktopIpc.makeIpcMethod({
channel: IpcChannels.RESOLVE_SSH_HOST_CHANNEL,
payload: Schema.String,
result: DesktopSshEnvironmentTargetSchema,
handler: Effect.fn("desktop.ipc.sshEnvironment.resolveHost")(function* (alias) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.resolveHost(alias);
}),
});
export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
channel: IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL,
payload: DesktopSshEnvironmentEnsureInputSchema,
+1
View File
@@ -60,6 +60,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
resolveSshHost: (alias) => ipcRenderer.invoke(IpcChannels.RESOLVE_SSH_HOST_CHANNEL, alias),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
await ipcRenderer.invoke(IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL, {
@@ -5,6 +5,7 @@ import type {
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import * as SshAuth from "@t3tools/ssh/auth";
import { resolveSshTarget } from "@t3tools/ssh/command";
import { discoverSshHosts } from "@t3tools/ssh/config";
import {
SshCommandError,
@@ -54,6 +55,9 @@ export class DesktopSshEnvironment extends Context.Service<
readonly discoverHosts: (input?: {
readonly homeDir?: string;
}) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>;
readonly resolveHost: (
alias: string,
) => Effect.Effect<DesktopSshEnvironmentTarget, SshCommandError | SshInvalidTargetError>;
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
@@ -136,6 +140,11 @@ export const make = Effect.gen(function* () {
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.discoverHosts"),
),
resolveHost: (alias) =>
resolveSshTarget(alias.trim()).pipe(
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.resolveHost"),
),
ensureEnvironment: (target, ensureOptions) =>
manager
.ensureEnvironment(target, ensureOptions)
@@ -1,12 +1,16 @@
import {
ChevronsLeftRightEllipsisIcon,
PlusIcon,
QrCodeIcon,
RefreshCwIcon,
TerminalIcon,
} from "lucide-react";
import { ChevronsLeftRightEllipsisIcon, PlusIcon, QrCodeIcon, TerminalIcon } from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { type ReactNode, memo, useCallback, useId, useMemo, useState } from "react";
import {
type KeyboardEvent,
type ReactNode,
memo,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import {
AuthAccessReadScope,
AuthAccessWriteScope,
@@ -56,6 +60,15 @@ import {
import { searchableSetting } from "./settingsSearch";
import { EnvironmentIconPicker } from "./EnvironmentIconPicker";
import { Input } from "../ui/input";
import { CommandShortcut } from "../ui/command";
import {
Autocomplete,
AutocompleteEmpty,
AutocompleteInput,
AutocompleteItem,
AutocompleteList,
AutocompletePopup,
} from "../ui/autocomplete";
import { Checkbox } from "../ui/checkbox";
import {
Dialog,
@@ -123,7 +136,7 @@ import {
desktopNetworkAccessStateAtom,
refreshDesktopNetworkAccessState,
} from "~/state/desktopNetworkAccess";
import { desktopSshHostsStateAtom } from "~/state/desktopSshHosts";
import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState";
import {
type EnvironmentPresentation,
@@ -131,11 +144,17 @@ import {
usePrimaryEnvironment,
} from "~/state/environments";
import { useAtomCommand } from "../../state/use-atom-command";
import { serverEnvironment } from "~/state/server";
import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import {
resolveShortcutCommand,
shortcutLabelForCommand,
threadJumpCommandForIndex,
threadJumpIndexFromCommand,
} from "../../keybindings";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
@@ -1561,46 +1580,6 @@ function SavedBackendListRow({
);
}
interface DesktopSshHostRowProps {
target: DesktopDiscoveredSshHost;
connectingHostAlias: string | null;
onConnect: (target: DesktopDiscoveredSshHost) => void;
}
const DesktopSshHostRow = memo(function DesktopSshHostRow({
target,
connectingHostAlias,
onConnect,
}: DesktopSshHostRowProps) {
const address = formatDesktopSshTarget(target);
const showAddress = address !== target.alias;
const buttonLabel = connectingHostAlias === target.alias ? "Adding…" : "Add environment";
return (
<div className="rounded-xl px-3 py-3 sm:px-4">
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1">
<h3 className="truncate text-sm font-medium text-foreground">{target.alias}</h3>
{showAddress ? <p className="truncate text-xs text-muted-foreground">{address}</p> : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
<Button
size="xs"
variant="outline"
disabled={connectingHostAlias === target.alias}
onClick={() => onConnect(target)}
>
{connectingHostAlias === target.alias ? (
<RefreshCwIcon className="size-3 animate-spin" />
) : null}
{buttonLabel}
</Button>
</div>
</div>
</div>
);
});
function CloudLinkSwitch({
checked,
disabled,
@@ -1769,6 +1748,7 @@ function CloudRemoteEnvironmentRows({
export function ConnectionsSettings() {
const desktopBridge = window.desktopBridge;
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
@@ -1792,24 +1772,6 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
savedEnvironments.reduce<Record<string, EnvironmentPresentation>>(
(accumulator, environment) => {
const profile = environment.entry.profile;
if (
environment.entry.target._tag === "SshConnectionTarget" &&
Option.isSome(profile) &&
profile.value._tag === "SshConnectionProfile"
) {
accumulator[profile.value.target.alias] = environment;
}
return accumulator;
},
{},
),
[savedEnvironments],
);
const savedDesktopSshEnvironmentKeys = useMemo(() => {
const keys = new Set<string>();
for (const environment of savedEnvironments) {
@@ -1827,9 +1789,6 @@ export function ConnectionsSettings() {
}
return keys;
}, [savedEnvironments]);
const [sshConnectionError, setSshConnectionError] = useState<string | null>(null);
const [connectingSshHostAlias, setConnectingSshHostAlias] = useState<string | null>(null);
const [desktopServerExposureMutationError, setDesktopServerExposureMutationError] = useState<
string | null
>(null);
@@ -1850,6 +1809,9 @@ export function ConnectionsSettings() {
const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
const [savedBackendSshPort, setSavedBackendSshPort] = useState("");
const [sshHostSuggestionsOpen, setSshHostSuggestionsOpen] = useState(false);
// Tracks the arrow-key/hover highlight so Enter selects it instead of submitting the typed text.
const highlightedSshHostRef = useRef<DesktopDiscoveredSshHost | undefined>(undefined);
const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false);
const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
@@ -1915,11 +1877,17 @@ export function ConnectionsSettings() {
const desktopNetworkAccess = useEnvironmentQuery(
canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null,
);
const isSshDiscoveryActive =
desktopBridge !== undefined && addBackendDialogOpen && savedBackendMode === "ssh";
const desktopSshHosts = useEnvironmentQuery(
desktopBridge && addBackendDialogOpen && savedBackendMode === "ssh"
? desktopSshHostsStateAtom
: null,
isSshDiscoveryActive ? desktopSshHostsStateAtom : null,
);
// The discovery atom is kept alive across dialog opens, so re-read SSH config
// each time the SSH tab is shown; stale hosts stay visible while it refreshes.
const refreshDesktopSshHosts = desktopSshHosts.refresh;
useEffect(() => {
if (isSshDiscoveryActive) refreshDesktopSshHosts();
}, [isSshDiscoveryActive, refreshDesktopSshHosts]);
const desktopWsl = useEnvironmentQuery(
canManageLocalBackend && desktopBridge ? desktopWslStateAtom : null,
);
@@ -1938,10 +1906,15 @@ export function ConnectionsSettings() {
}),
[discoveredSshHosts, savedDesktopSshEnvironmentKeys],
);
const hasLoadedDiscoveredSshHosts =
desktopSshHosts.data !== null || desktopSshHosts.error !== null;
const isLoadingDiscoveredSshHosts = desktopSshHosts.isPending;
const discoveredSshHostsError = sshConnectionError ?? desktopSshHosts.error;
const filteredDiscoveredSshHosts = useMemo(
() => filterDiscoveredSshHosts(unsavedDiscoveredSshHosts, savedBackendSshHost),
[savedBackendSshHost, unsavedDiscoveredSshHosts],
);
const isLoadingDiscoveredSshHosts = desktopSshHosts.isPending && desktopSshHosts.data === null;
const discoveredSshHostsError = desktopSshHosts.error;
const hasSshHostSuggestionContent =
desktopBridge !== undefined &&
(isLoadingDiscoveredSshHosts || unsavedDiscoveredSshHosts.length > 0);
const desktopServerExposureState = desktopNetworkAccess.data?.serverExposureState ?? null;
const desktopAdvertisedEndpoints =
desktopNetworkAccess.data?.advertisedEndpoints ?? EMPTY_ADVERTISED_ENDPOINTS;
@@ -2165,23 +2138,11 @@ export function ConnectionsSettings() {
}
}, []);
const handleAddSavedBackend = useCallback(async () => {
if (savedBackendMode === "ssh") {
// Shared by manual SSH submission and discovered-host selection.
const connectSavedBackendSshTarget = useCallback(
async (target: DesktopSshEnvironmentTarget) => {
setIsAddingSavedBackend(true);
setSavedBackendError(null);
let target: DesktopSshEnvironmentTarget;
try {
target = parseManualDesktopSshTarget({
host: savedBackendSshHost,
username: savedBackendSshUsername,
port: savedBackendSshPort,
});
} catch (error) {
setSavedBackendError(formatDesktopSshConnectionError(error));
setIsAddingSavedBackend(false);
return;
}
const result = await connectSshEnvironment({ target, label: "" });
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
@@ -2203,6 +2164,25 @@ export function ConnectionsSettings() {
description: `${target.alias} is ready over an SSH-managed tunnel.`,
});
setIsAddingSavedBackend(false);
},
[connectSshEnvironment],
);
const handleAddSavedBackend = useCallback(async () => {
if (savedBackendMode === "ssh") {
let target: DesktopSshEnvironmentTarget;
try {
target = parseManualDesktopSshTarget({
host: savedBackendSshHost,
username: savedBackendSshUsername,
port: savedBackendSshPort,
});
} catch (error) {
setSavedBackendError(formatDesktopSshConnectionError(error));
return;
}
await connectSavedBackendSshTarget(target);
return;
}
@@ -2260,7 +2240,7 @@ export function ConnectionsSettings() {
setIsAddingSavedBackend(false);
}, [
connectPairing,
connectSshEnvironment,
connectSavedBackendSshTarget,
savedBackendHost,
savedBackendMode,
savedBackendPairingCode,
@@ -2269,6 +2249,92 @@ export function ConnectionsSettings() {
savedBackendSshUsername,
]);
const handleSavedBackendSshFieldKeyDown = useCallback(
(event: KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter" && savedBackendSshHost.trim().length > 0) {
event.preventDefault();
void handleAddSavedBackend();
}
},
[handleAddSavedBackend, savedBackendSshHost],
);
// Resolves a picked alias before connecting it through the manual SSH flow.
const handleSelectSshHostSuggestion = useCallback(
async (target: DesktopDiscoveredSshHost) => {
if (isAddingSavedBackend || !desktopBridge) return;
setIsAddingSavedBackend(true);
setSavedBackendError(null);
setSavedBackendSshHost(target.alias);
let resolved: DesktopSshEnvironmentTarget;
try {
resolved = await desktopBridge.resolveSshHost(target.alias);
} catch (error) {
setSavedBackendError(formatDesktopSshConnectionError(error));
setIsAddingSavedBackend(false);
return;
}
setSavedBackendSshUsername(resolved.username ?? "");
setSavedBackendSshPort(resolved.port === null ? "" : String(resolved.port));
await connectSavedBackendSshTarget(resolved);
},
[connectSavedBackendSshTarget, desktopBridge, isAddingSavedBackend],
);
const handleSavedBackendSshHostKeyDown = useCallback(
(event: KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
// The popup only renders when there is content, so an "open" flag alone is not enough.
const isSshHostPopupVisible = sshHostSuggestionsOpen && hasSshHostSuggestionContent;
if (isSshHostPopupVisible) {
const command = resolveShortcutCommand(event, keybindings, {
platform: navigator.platform,
context: { modelPickerOpen: false },
});
const index = threadJumpIndexFromCommand(command ?? "");
const target = index === null ? undefined : filteredDiscoveredSshHosts[index];
if (target) {
event.preventDefault();
event.stopPropagation();
setSshHostSuggestionsOpen(false);
void handleSelectSshHostSuggestion(target);
return;
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
return;
}
}
// A highlighted row means Enter belongs to the autocomplete, which selects it.
const hasHighlightedSshHost =
isSshHostPopupVisible && highlightedSshHostRef.current !== undefined;
if (
!event.defaultPrevented &&
!hasHighlightedSshHost &&
event.key === "Enter" &&
savedBackendSshHost.trim().length > 0
) {
event.preventDefault();
void handleAddSavedBackend();
}
},
[
filteredDiscoveredSshHosts,
handleAddSavedBackend,
handleSelectSshHostSuggestion,
hasSshHostSuggestionContent,
keybindings,
savedBackendSshHost,
sshHostSuggestionsOpen,
],
);
const handleConnectSavedBackend = useCallback(
async (environmentId: EnvironmentId) => {
setSavedBackendError(null);
@@ -2311,46 +2377,6 @@ export function ConnectionsSettings() {
[removeEnvironment],
);
const handleConnectSshHost = useCallback(
async (target: DesktopSshEnvironmentTarget, label?: string) => {
setConnectingSshHostAlias(target.alias);
if (savedBackendMode === "ssh") {
setSavedBackendError(null);
} else {
setSshConnectionError(null);
}
const result = await connectSshEnvironment({
target,
...(label === undefined ? {} : { label }),
});
setConnectingSshHostAlias(null);
if (result._tag === "Success") {
setSavedBackendSshHost("");
setSavedBackendSshUsername("");
setSavedBackendSshPort("");
setAddBackendDialogOpen(false);
toastManager.add({
type: "success",
title: savedDesktopSshEnvironmentsByAlias[target.alias]
? "Environment reconnected"
: "Environment connected",
description: `${label?.trim() || target.alias} is ready over an SSH-managed tunnel.`,
});
return;
}
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
const message = formatDesktopSshConnectionError(error);
if (savedBackendMode === "ssh") {
setSavedBackendError(message);
} else {
setSshConnectionError(message);
}
}
},
[connectSshEnvironment, savedBackendMode, savedDesktopSshEnvironmentsByAlias],
);
const visibleDesktopPairingLinks = desktopPairingLinks;
const tailscaleHttpsEndpoint = useMemo(
() => desktopAdvertisedEndpoints.find(isTailscaleHttpsEndpoint) ?? null,
@@ -2496,24 +2522,90 @@ export function ConnectionsSettings() {
const renderSshFields = () => (
<div className="space-y-4">
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">
<div className="block">
<label
htmlFor="saved-backend-ssh-host"
className="mb-1.5 block text-xs font-medium text-foreground"
>
SSH host or alias
</span>
<Input
</label>
<Autocomplete
items={filteredDiscoveredSshHosts}
itemToStringValue={(target) => target.alias}
mode="none"
openOnInputClick
open={sshHostSuggestionsOpen}
onOpenChange={setSshHostSuggestionsOpen}
onItemHighlighted={(target) => {
highlightedSshHostRef.current = target;
}}
value={savedBackendSshHost}
onChange={(event) => setSavedBackendSshHost(event.target.value)}
placeholder="Search hosts or type devbox"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
</label>
onValueChange={(value, eventDetails) => {
setSavedBackendSshHost(value);
if (eventDetails.reason !== "item-press") return;
const target = filteredDiscoveredSshHosts.find((host) => host.alias === value);
if (target) void handleSelectSshHostSuggestion(target);
}}
>
<AutocompleteInput
id="saved-backend-ssh-host"
onKeyDown={handleSavedBackendSshHostKeyDown}
placeholder="Search hosts or type devbox"
disabled={isAddingSavedBackend}
spellCheck={false}
/>
{hasSshHostSuggestionContent ? (
<AutocompletePopup>
{isLoadingDiscoveredSshHosts ? (
<div className="px-3 py-2 text-xs text-muted-foreground">Loading hosts…</div>
) : filteredDiscoveredSshHosts.length > 0 ? (
<AutocompleteList className="max-h-72">
{filteredDiscoveredSshHosts.map((target, index) => {
const address = formatDesktopSshTarget(target);
const shortcutCommand = index < 9 ? threadJumpCommandForIndex(index) : null;
const shortcutLabel = shortcutCommand
? shortcutLabelForCommand(keybindings, shortcutCommand, navigator.platform)
: null;
return (
<AutocompleteItem
key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
value={target}
className="h-8 min-h-8 gap-2 whitespace-nowrap"
>
<span className="min-w-0 truncate text-sm font-medium">
{target.alias}
</span>
{address !== target.alias ? (
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{address}
</span>
) : (
<span className="flex-1" />
)}
{shortcutLabel ? (
<CommandShortcut className="shrink-0">{shortcutLabel}</CommandShortcut>
) : null}
</AutocompleteItem>
);
})}
</AutocompleteList>
) : (
<AutocompleteEmpty className="break-all px-3 py-2 text-xs">
No hosts match "{savedBackendSshHost.trim()}".
</AutocompleteEmpty>
)}
</AutocompletePopup>
) : null}
</Autocomplete>
</div>
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_7rem]">
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground">Username</span>
<Input
value={savedBackendSshUsername}
onChange={(event) => setSavedBackendSshUsername(event.target.value)}
onKeyDown={handleSavedBackendSshFieldKeyDown}
placeholder="root"
disabled={isAddingSavedBackend}
spellCheck={false}
@@ -2524,6 +2616,7 @@ export function ConnectionsSettings() {
<Input
value={savedBackendSshPort}
onChange={(event) => setSavedBackendSshPort(event.target.value)}
onKeyDown={handleSavedBackendSshFieldKeyDown}
placeholder="22"
inputMode="numeric"
disabled={isAddingSavedBackend}
@@ -2546,46 +2639,6 @@ export function ConnectionsSettings() {
{isAddingSavedBackend ? "Adding…" : "Add environment"}
</Button>
</div>
<div className="overflow-hidden rounded-lg border border-border/60">
<div className="flex items-center justify-between gap-3 border-b border-border/60 bg-muted/30 px-3 py-2">
<div className="min-w-0">
<p className="text-xs font-medium text-foreground">Suggested hosts</p>
<p className="text-[11px] text-muted-foreground">From SSH config and known hosts</p>
</div>
<Button
size="xs"
variant="ghost"
disabled={isLoadingDiscoveredSshHosts}
onClick={desktopSshHosts.refresh}
>
{isLoadingDiscoveredSshHosts ? (
<RefreshCwIcon className="size-3 animate-spin" />
) : (
<RefreshCwIcon className="size-3" />
)}
Refresh
</Button>
</div>
<ScrollArea scrollFade className="max-h-56">
<div>
{unsavedDiscoveredSshHosts.map((target) => (
<DesktopSshHostRow
key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
target={target}
connectingHostAlias={connectingSshHostAlias}
onConnect={(nextTarget) => void handleConnectSshHost(nextTarget)}
/>
))}
{hasLoadedDiscoveredSshHosts &&
!isLoadingDiscoveredSshHosts &&
unsavedDiscoveredSshHosts.length === 0 ? (
<div className={ITEM_ROW_CLASSNAME}>
<p className="text-xs text-muted-foreground">No new SSH hosts were discovered.</p>
</div>
) : null}
</div>
</ScrollArea>
</div>
</div>
);
const renderNetworkAccessToggle = () => (
+81 -1
View File
@@ -4,7 +4,7 @@ import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { describe, expect, it, vi } from "vite-plus/test";
import { createDesktopSshHostsStateAtom } from "./desktopSshHosts";
import { createDesktopSshHostsStateAtom, filterDiscoveredSshHosts } from "./desktopSshHosts";
const hosts: ReadonlyArray<DesktopDiscoveredSshHost> = [
{
@@ -16,6 +16,86 @@ const hosts: ReadonlyArray<DesktopDiscoveredSshHost> = [
},
];
describe("filterDiscoveredSshHosts", () => {
const suggestions: ReadonlyArray<DesktopDiscoveredSshHost> = [
{
alias: "grape",
hostname: "grape",
port: null,
source: "known-hosts",
username: null,
},
{
alias: "Pinot",
hostname: "Pinot",
port: null,
source: "ssh-config",
username: null,
},
{
alias: "preprod",
hostname: "preprod",
port: 2222,
source: "ssh-config",
username: "deploy",
},
{
alias: "prod-z",
hostname: "prod-z",
port: null,
source: "ssh-config",
username: null,
},
{
alias: "prod-a",
hostname: "prod-a",
port: null,
source: "ssh-config",
username: null,
},
{
alias: "prod-m",
hostname: "prod-m",
port: null,
source: "ssh-config",
username: null,
},
];
it.each(["", " "])("returns every host for an empty query %j", (query) => {
expect(filterDiscoveredSshHosts(suggestions, query)).toEqual(suggestions);
});
it("trims the query", () => {
expect(filterDiscoveredSshHosts(suggestions, " pi ")).toEqual([suggestions[1]]);
});
it("ranks alias prefix matches before substring matches", () => {
expect(filterDiscoveredSshHosts(suggestions, "prod")).toEqual([
suggestions[3],
suggestions[4],
suggestions[5],
suggestions[2],
]);
});
it("preserves the original order within a match tier", () => {
expect(filterDiscoveredSshHosts(suggestions, "prod").slice(0, 3)).toEqual([
suggestions[3],
suggestions[4],
suggestions[5],
]);
});
it("matches case-insensitively", () => {
expect(filterDiscoveredSshHosts(suggestions, "PINOT")).toEqual([suggestions[1]]);
});
it("returns an empty array when no hosts match", () => {
expect(filterDiscoveredSshHosts(suggestions, "merlot")).toEqual([]);
});
});
describe("desktopSshHostsState", () => {
it("retains discovered hosts when the settings screen remounts", async () => {
const discoverSshHosts = vi.fn(async () => hosts);
+22
View File
@@ -5,6 +5,28 @@ import { Atom } from "effect/unstable/reactivity";
type DesktopSshDiscoveryBridge = Pick<DesktopBridge, "discoverSshHosts">;
/** Filters and ranks SSH host suggestions as the user types in the host field. */
export function filterDiscoveredSshHosts(
hosts: ReadonlyArray<DesktopDiscoveredSshHost>,
query: string,
): ReadonlyArray<DesktopDiscoveredSshHost> {
const normalizedQuery = query.trim().toLowerCase();
if (normalizedQuery.length === 0) return hosts;
const prefixMatches: Array<DesktopDiscoveredSshHost> = [];
const substringMatches: Array<DesktopDiscoveredSshHost> = [];
for (const host of hosts) {
const alias = host.alias.toLowerCase();
if (alias.startsWith(normalizedQuery)) {
prefixMatches.push(host);
} else if (alias.includes(normalizedQuery)) {
substringMatches.push(host);
}
}
return [...prefixMatches, ...substringMatches];
}
class DesktopSshDiscoveryUnavailableError extends Schema.TaggedErrorClass<DesktopSshDiscoveryUnavailableError>()(
"DesktopSshDiscoveryUnavailableError",
{},
+2
View File
@@ -1066,6 +1066,8 @@ export interface DesktopBridge {
setConnectionCatalog?: (catalog: string) => Promise<boolean>;
clearConnectionCatalog?: () => Promise<void>;
discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;
/** Resolves a suggested SSH alias before populating the connection form. */
resolveSshHost: (alias: string) => Promise<DesktopSshEnvironmentTarget>;
ensureSshEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { issuePairingToken?: boolean },