refactor(webui): separate presentation views and expand component gallery (#6179)

* refactor(webui): organize shared components with an internal gallery

* refactor(webui): decouple views and expand component gallery

* fix(docker): include channel sources in WebUI build

* refactor(webui): cover all channel interfaces in gallery

* docs(webui): remove manual paragraph wrapping
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-14 00:11:00 +08:00
1 parent db804ef94a
commit 30e43aec82
109 files changed
+7874 -3459

No files matched your search

+8 -180
View File
@@ -1,190 +1,18 @@
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useContext, useEffect, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import { HostConnectionStatus } from "./HostConnectionStatus";
import type { HostConnectionState } from "./remote-context";
import { HostNavigationContext } from "./host-navigation";
import { HostSwitcherView } from "./HostSwitcherView";
export interface HostPicker {
kind: "shell";
name: string;
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
offline: boolean;
offlineLabel?: string;
select: (id: string | null) => void;
manage: () => void;
cancel: () => void;
clearError: () => void;
restoreFocus: () => void;
}
interface EmbeddedPicker extends EmbeddedHost {
kind: "embedded";
open: (anchor: HostAnchor) => void;
}
export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);
export { HostNavigationContext, type HostPicker } from "./host-navigation";
export { RemoteHostMenu } from "./HostSwitcherView";
function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"
onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
<HostMenuItems picker={picker} />
</DropdownMenuContent>;
}
/** Mounted with the menu so every opening starts with a fresh, stable list. */
function HostMenuItems({ picker }: { picker: HostPicker }) {
const { t } = useTranslation();
const [searchable] = useState(() => picker.profiles.length > 5);
const [query, setQuery] = useState("");
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
const search = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const needle = query.trim().toLocaleLowerCase();
const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));
const showLocal = matches(t("remote.local"), picker.localName);
const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));
if (searchable) {
const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };
profiles.sort((a, b) => rank(a.id) - rank(b.id));
}
useEffect(() => {
// Don't summon the software keyboard when opening the picker on a touch device.
if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;
const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(frame);
}, [searchable]);
return <div className="flex min-h-0 flex-col"
onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onKeyDownCapture={(event) => {
if (!searchable) return;
if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }
const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));
if (event.target === search.current) {
// Keep spaces and IME input out of Radix's menu typeahead.
if (event.key !== "Escape") event.stopPropagation();
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {
event.preventDefault();
(event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();
}
} else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {
event.preventDefault(); event.stopPropagation(); search.current?.focus();
}
}}>
{searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">
<Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
<input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}
value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
className="touch-text-input h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />
</div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}
<div ref={list} role="group" aria-label={t("remote.switchHost")}
className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">
{showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}>
<Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
{!picker.currentId && <Check className="h-4 w-4" />}
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`}
title={`${profile.name}\n${profile.host}`} aria-current={picker.currentId === profile.id || undefined}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
<span id={`host-state-${profile.id}`}><HostConnectionStatus state={profile.state} compact /></span>
{picker.currentId === profile.id && <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0" />}
</DropdownMenuItem>)}
{!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}
</div>
<div className="shrink-0">
{picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
{picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">
<CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span>
</div>}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
</div>
</div>;
}
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
/** Connect the sidebar's presentation to the active host and client. */
export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) {
const picker = useContext(HostNavigationContext);
const { client } = useClient();
const { t } = useTranslation();
const [status, setStatus] = useState<ConnectionStatus>(client.status);
useEffect(() => client.onStatus(setStatus), [client]);
const buttonRef = useRef<HTMLButtonElement>(null);
if (!picker) return <ConnectionBadge />;
const shell = picker.kind === "shell" ? picker : null;
const remote = picker.kind === "embedded" || !!shell?.currentId;
const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
const currentStatus = shell?.currentId
? (shell.pending?.id === shell.currentId || shell.profiles.find((profile) => profile.id === shell.currentId)?.state === "connecting" ? "connecting" : shell.offline ? "closed" : "open")
: status;
// A failed switch describes the destination, not the still-active connection.
const failed = !!shell?.offline || currentStatus === "error" || currentStatus === "closed";
const waiting = !!pendingName || currentStatus === "connecting" || currentStatus === "reconnecting";
// The old host stays interactive until the new one is ready. Keep its identity
// visible; progress belongs to the target's row and the accessible status.
const label = picker.name;
const currentLabel = failed ? shell?.offlineLabel || t("remote.offline") : t(`connection.${currentStatus}`);
const identity = picker.name === picker.hostname ? picker.name : `${picker.name}, ${picker.hostname}`;
const current = `${identity}, ${currentLabel}`;
const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")}
data-host-switcher className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
onClick={picker.kind === "embedded" ? () => {
const rect = buttonRef.current?.getBoundingClientRect();
if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
} : undefined}>
<span className="relative flex shrink-0 items-center justify-center">
{waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />
: remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
{!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", currentStatus === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
</span>
{!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
<span className="sr-only" role="status">{detail}</span>
</Button>;
const trigger = <TooltipTrigger asChild>{button}</TooltipTrigger>;
// The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.
return <TooltipProvider><Tooltip>
{shell ? <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu> : trigger}
<TooltipContent side="top" className="max-w-[min(24rem,calc(100vw-2rem))] space-y-1 break-words">
<p className="font-medium">{picker.name}</p>
{picker.hostname !== picker.name ? <p className="font-mono text-xs text-muted-foreground">{picker.hostname}</p> : null}
<p>{currentLabel}</p>
{pendingName ? <p>{t("remote.preparing", { name: pendingName })}</p> : null}
{picker.error ? <p className="text-destructive">{picker.error}</p> : null}
</TooltipContent>
</Tooltip></TooltipProvider>;
}
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
<DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
} : { width: 0, height: 0 }} /></DropdownMenuTrigger>
<HostMenuContent picker={picker} />
</DropdownMenu>;
return <HostSwitcherView picker={picker} status={status} collapsed={collapsed} portalContainer={portalContainer} />;
}
@@ -0,0 +1,166 @@
import { useEffect, useRef, useState } from "react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor } from "./host-bridge";
import type { HostPicker, EmbeddedPicker } from "./host-navigation";
import { HostConnectionStatus } from "./HostConnectionStatus";
function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"
onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
<HostMenuItems picker={picker} />
</DropdownMenuContent>;
}
/** Mounted with the menu so every opening starts with a fresh, stable list. */
function HostMenuItems({ picker }: { picker: HostPicker }) {
const { t } = useTranslation();
const [searchable] = useState(() => picker.profiles.length > 5);
const [query, setQuery] = useState("");
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
const search = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const needle = query.trim().toLocaleLowerCase();
const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));
const showLocal = matches(t("remote.local"), picker.localName);
const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));
if (searchable) {
const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };
profiles.sort((a, b) => rank(a.id) - rank(b.id));
}
useEffect(() => {
// Don't summon the software keyboard when opening the picker on a touch device.
if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;
const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(frame);
}, [searchable]);
return <div className="flex min-h-0 flex-col"
onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onKeyDownCapture={(event) => {
if (!searchable) return;
if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }
const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));
if (event.target === search.current) {
// Keep spaces and IME input out of Radix's menu typeahead.
if (event.key !== "Escape") event.stopPropagation();
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {
event.preventDefault();
(event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();
}
} else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {
event.preventDefault(); event.stopPropagation(); search.current?.focus();
}
}}>
{searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">
<Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
<input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}
value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
className="touch-text-input h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />
</div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}
<div ref={list} role="group" aria-label={t("remote.switchHost")}
className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">
{showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}>
<Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
{!picker.currentId && <Check className="h-4 w-4" />}
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`}
title={`${profile.name}\n${profile.host}`} aria-current={picker.currentId === profile.id || undefined}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
<span id={`host-state-${profile.id}`}><HostConnectionStatus state={profile.state} compact /></span>
{picker.currentId === profile.id && <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0" />}
</DropdownMenuItem>)}
{!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}
</div>
<div className="shrink-0">
{picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
{picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">
<CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span>
</div>}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
</div>
</div>;
}
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
export function HostSwitcherView({ picker, status, collapsed = false, portalContainer }: {
picker: HostPicker | EmbeddedPicker | null;
status: ConnectionStatus;
collapsed?: boolean;
portalContainer?: HTMLElement | null;
}) {
const { t } = useTranslation();
const buttonRef = useRef<HTMLButtonElement>(null);
if (!picker) return <ConnectionBadge status={status} />;
const shell = picker.kind === "shell" ? picker : null;
const remote = picker.kind === "embedded" || !!shell?.currentId;
const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
const currentStatus = shell?.currentId
? (shell.pending?.id === shell.currentId || shell.profiles.find((profile) => profile.id === shell.currentId)?.state === "connecting" ? "connecting" : shell.offline ? "closed" : "open")
: status;
// A failed switch describes the destination, not the still-active connection.
const failed = !!shell?.offline || currentStatus === "error" || currentStatus === "closed";
const waiting = !!pendingName || currentStatus === "connecting" || currentStatus === "reconnecting";
// The old host stays interactive until the new one is ready. Keep its identity
// visible; progress belongs to the target's row and the accessible status.
const label = picker.name;
const currentLabel = failed ? shell?.offlineLabel || t("remote.offline") : t(`connection.${currentStatus}`);
const identity = picker.name === picker.hostname ? picker.name : `${picker.name}, ${picker.hostname}`;
const current = `${identity}, ${currentLabel}`;
const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")}
data-host-switcher className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
onClick={picker.kind === "embedded" ? () => {
const rect = buttonRef.current?.getBoundingClientRect();
if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
} : undefined}>
<span className="relative flex shrink-0 items-center justify-center">
{waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />
: remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
{!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", currentStatus === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
</span>
{!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
<span className="sr-only" role="status">{detail}</span>
</Button>;
const trigger = <TooltipTrigger asChild>{button}</TooltipTrigger>;
// The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.
return <TooltipProvider><Tooltip>
{shell ? <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu> : trigger}
<TooltipContent side="top" className="max-w-[min(24rem,calc(100vw-2rem))] space-y-1 break-words">
<p className="font-medium">{picker.name}</p>
{picker.hostname !== picker.name ? <p className="font-mono text-xs text-muted-foreground">{picker.hostname}</p> : null}
<p>{currentLabel}</p>
{pendingName ? <p>{t("remote.preparing", { name: pendingName })}</p> : null}
{picker.error ? <p className="text-destructive">{picker.error}</p> : null}
</TooltipContent>
</Tooltip></TooltipProvider>;
}
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
<DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
} : { width: 0, height: 0 }} /></DropdownMenuTrigger>
<HostMenuContent picker={picker} />
</DropdownMenu>;
}
@@ -1,11 +1,9 @@
import { useEffect, useRef, useState } from "react";
import { AlertCircle, Check, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction } from "@/lib/remote-instances";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettingsView } from "./PairRouteSettingsView";
/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */
export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string; onSaved?: () => void; showHint?: boolean }) {
@@ -38,21 +36,9 @@ export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string
if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));
} finally { if (alive.current) setBusy(false); }
};
return <div className="space-y-3">
{showHint && <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>}
<Select value={route} onValueChange={(value) => { setRoute(value); setError(""); setSaved(false); }} disabled={busy}><SelectTrigger className="w-full min-w-0" aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>
<SelectContent>
{hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}
<SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>
{connections?.directory?.profiles.filter((profile) => !profile.paired).map((profile) => <SelectItem key={profile.id} value={profile.id} className="h-auto min-h-9 max-w-[calc(100vw-3rem)] py-2 [overflow-wrap:anywhere]">{profile.name}</SelectItem>)}
</SelectContent>
</Select>
{error && <p role="alert" className="remote-alert items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{error}</span></p>}
<div className="flex flex-wrap items-center justify-end gap-3">
{saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}
<Button className="remote-action" size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={() => { void save(); }}>
{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
</Button>
</div>
</div>;
return <PairRouteSettingsView hasSavedRoute={hasSavedRoute}
routes={connections?.directory?.profiles.filter((profile) => !profile.paired) ?? []}
route={route} original={original} busy={busy} error={error} saved={saved} showHint={showHint}
onRouteChange={(value) => { setRoute(value); setError(""); setSaved(false); }}
onSave={() => { void save(); }} />;
}
@@ -0,0 +1,41 @@
import { AlertCircle, Check, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import type { RemoteProfile } from "@/lib/remote-instances";
export interface PairRouteSettingsViewProps {
hasSavedRoute: boolean;
routes: Array<Pick<RemoteProfile, "id" | "name">>;
route: string;
original: string;
busy: boolean;
error: string;
saved: boolean;
showHint?: boolean;
onRouteChange: (route: string) => void;
onSave: () => void;
}
export function PairRouteSettingsView({
hasSavedRoute, routes, route, original, busy, error, saved, showHint = true, onRouteChange, onSave,
}: PairRouteSettingsViewProps) {
const { t } = useTranslation();
return <div className="space-y-3">
{showHint && <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>}
<Select value={route} onValueChange={onRouteChange} disabled={busy}><SelectTrigger className="w-full min-w-0" aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>
<SelectContent>
{hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}
<SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>
{routes.map((profile) => <SelectItem key={profile.id} value={profile.id} className="h-auto min-h-9 max-w-[calc(100vw-3rem)] py-2 [overflow-wrap:anywhere]">{profile.name}</SelectItem>)}
</SelectContent>
</Select>
{error && <p role="alert" className="remote-alert items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{error}</span></p>}
<div className="flex flex-wrap items-center justify-end gap-3">
{saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}
<Button className="remote-action" size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={onSave}>
{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
</Button>
</div>
</div>;
}
+16 -136
View File
@@ -1,32 +1,19 @@
import { useEffect, useId, useRef, useState } from "react";
import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";
import { Textarea } from "@/components/ui/textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { copyTextToClipboard } from "@/lib/clipboard";
import { CodeBlock } from "@/components/CodeBlock";
import { remoteAction } from "@/lib/remote-instances";
import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";
import type { ConnectionStatus } from "@/lib/types";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettings } from "./PairRouteSettings";
import "./remote-layout.css";
type Request = { id: string; command: string; expires: number };
type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string;
existing_connection?: { id: string; name: string; connected: boolean } };
import { QuickPairSetupView, type PairInvitation, type PairConnectionPreview, type QuickPairPanel } from "./QuickPairSetupView";
/** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */
export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { returned?: PairReturn | null; active?: boolean; onSSH: () => void; onClose: () => void }) {
const { t } = useTranslation();
const { client } = useClient();
const connections = useRemoteConnections();
const [request, setRequest] = useState<Request | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);
const [preview, setPreview] = useState<Preview | null>(null);
const [request, setRequest] = useState<PairInvitation | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);
const [preview, setPreview] = useState<PairConnectionPreview | null>(null);
const [code, setCode] = useState(returned?.code || "");
const [saved, setSaved] = useState("");
const [busy, setBusy] = useState(false);
@@ -36,14 +23,10 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
const [copied, setCopied] = useState(false);
const [expired, setExpired] = useState(false);
const [manual, setManual] = useState(false);
const [panel, setPanel] = useState<"command" | "help" | null>(null);
const [panel, setPanel] = useState<QuickPairPanel>(null);
const alive = useRef(true);
const initialized = useRef(false);
const requestId = useRef(returned?.id || "");
const manualInput = useRef<HTMLTextAreaElement>(null);
const focusManual = useRef(false);
const codeId = useId();
const panelId = useId();
const waitingForLocal = status !== "open";
const pending = busy || (waitingForLocal && !error);
@@ -84,14 +67,14 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
};
const start = () => run(async () => {
if (requestId.current) await remoteAction(client, "pair_cancel", { id: requestId.current });
const result = await remoteAction<Request>(client, "pair_start", { return_origin: pairingReturnOrigin() });
const result = await remoteAction<PairInvitation>(client, "pair_start", { return_origin: pairingReturnOrigin() });
if (!alive.current) { await remoteAction(client, "pair_cancel", { id: result.id }); return; }
requestId.current = result.id;
setRequest(result); setPreview(null); setCode(""); setCopied(false); setExpired(false); setManual(false); setPanel(null);
});
const review = () => run(async () => {
if (!request) return;
const result = await remoteAction<Preview>(client, "pair_preview", { id: request.id, code });
const result = await remoteAction<PairConnectionPreview>(client, "pair_preview", { id: request.id, code });
if (alive.current) setPreview(result);
});
const connect = () => run(async () => {
@@ -131,116 +114,13 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
else { setPanel("command"); setError("remote.pair.copyFailed"); }
});
};
const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`);
const requestUnavailable = error === "remote.errors.pair_expired" || error === "remote.errors.pair_used";
const restartAvailable = !saved && (expired || requestUnavailable || (!!error && !request?.command && !preview && (!returned || invalidReturn)));
const visiblePreview = restartAvailable ? null : preview;
const reviewingReturn = !!returned && !request?.command && !visiblePreview && !manual && !restartAvailable;
const title = visiblePreview ? visiblePreview.existing_connection ? "remote.sameInstance.title" : "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"
: manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";
const description = visiblePreview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"
: manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";
const showCopied = copied && !manual && !visiblePreview && !restartAvailable;
const showIllustration = !visiblePreview && !manual && !reviewingReturn && !restartAvailable;
const showBusy = pending && busyVisible;
const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : visiblePreview ? saved ? "remote.retry" : visiblePreview.existing_connection ? "remote.sameInstance.saveAndOpen" : "remote.connect"
: manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";
const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : visiblePreview ? "remote.connecting" : !restartAvailable && (manual || returned)
? "remote.pair.checkingLink" : "remote.pair.preparing";
return <div className="remote-pair flex min-h-0 flex-col">
<div className="-mx-1 min-h-0 overflow-y-auto overscroll-contain px-1">
<DialogHeader className={showIllustration ? "space-y-0 text-center sm:text-center" : "pr-5 text-left"}>
{showIllustration && <RemoteConnectionIllustration />}
<div aria-live="polite" aria-atomic="true" className="space-y-1.5">
<DialogTitle className={showIllustration ? "flex min-h-5 items-center justify-center gap-2 text-xl leading-snug tracking-normal" : "flex min-h-5 items-center gap-2"}>
{showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}
<span className="min-w-0 [overflow-wrap:anywhere]">{t(title)}</span>
</DialogTitle>
<DialogDescription>{t(description)}</DialogDescription>
</div>
</DialogHeader>
{visiblePreview ? <div className="space-y-4 pt-4">
<div className="rounded-2xl bg-muted/50 p-4">
<p className="font-medium [overflow-wrap:anywhere]">{visiblePreview.existing_connection?.name || visiblePreview.hostname}</p>
<p className="mt-1 break-all text-xs text-muted-foreground">{visiblePreview.host}</p>
</div>
{visiblePreview.existing_connection && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.sameInstance.pairHint")}</p>}
<p className="text-[13px] leading-5">{t("remote.pair.access")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(visiblePreview.authorized_until * 1000).toLocaleDateString() })}</p>
<Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>
<p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{visiblePreview.fingerprint}</code>
<p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><CodeBlock language="bash" code={visiblePreview.revoke_command} highlight={false} className="min-w-0 [&_pre]:[overflow-wrap:anywhere]" />
</Disclosure>
{saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>
<Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}><PairRouteSettings id={saved} /></Disclosure>
</div>}
</div> : restartAvailable ? null : <>
{manual && <div className="space-y-2 pt-4"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>
<Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => { setCode(event.target.value); setError(""); }} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />
</div>}
<div>
<DisclosureContent id={panelId} open={panel === "command" && !!request?.command} className="pt-4">
<div className="rounded-2xl bg-muted/50 p-3">
<code className="block max-h-32 select-text overflow-y-auto text-[11px] leading-5 [overflow-wrap:anywhere]" aria-label={t("remote.pair.command")}>{request?.command}</code>
</div>
</DisclosureContent>
<DisclosureContent open={panel === "help"} className="pt-4">
<div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">
<p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>
<p>{t("remote.pair.requirements")}</p>
<p>{t("remote.pair.runHint")}</p>
<p>{t("remote.pair.validityHint")}</p>
</div>
</DisclosureContent>
</div>
</>}
{expired && !saved && <p role="status" className="mt-4 text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}
{error && <p role="alert" className="remote-alert mt-4 items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{t(error, { defaultValue: t("remote.errors.unknown") })}</span></p>}
</div>
<div className={visiblePreview ? "remote-dialog-actions shrink-0 pt-5" : "flex shrink-0 flex-col gap-2 pt-5"}>
{visiblePreview && (!saved ? <Button className="remote-action" variant="ghost" disabled={busy} onClick={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>
: <Button className="remote-action" variant="ghost" onClick={() => { connections?.cancel(); onClose(); }}>{t("common.cancel")}</Button>
)}
<Button variant={showCopied ? "outline" : "default"} className={showCopied ? "remote-action bg-transparent" : "remote-action"} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={pending} disabled={busy || waitingForLocal || (!restartAvailable && (!request || (!visiblePreview && (manual || reviewingReturn ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (visiblePreview) void connect(); else if (manual || reviewingReturn) void review(); else copyCommand(); }}>
{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !visiblePreview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}
<span role="status" className="min-w-0">{t(showBusy ? busyLabel : actionLabel)}</span>
</Button>
{!visiblePreview && <div className="remote-pair-alternatives -mx-3 gap-1">
{!restartAvailable && request?.command ? manual ? <Button className="remote-action" variant="ghost" size="sm" disabled={busy} onClick={() => { setManual(false); setPanel(null); setError(""); }}>{t("remote.back")}</Button>
: <Button variant="ghost" size="sm" className="remote-action justify-start text-left text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => setPanel(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="remote-action justify-end text-right text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5 shrink-0" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" onCloseAutoFocus={(event) => {
if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }
}}>
<DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; setManual(true); setPanel(null); setError(""); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>
<DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={restartAvailable} onSelect={() => setPanel(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>}
</div>
</div>;
}
/** Decorative overview, not a live connection-status indicator. */
function RemoteConnectionIllustration() {
return <svg viewBox="0 0 208 88" width="184" height="78" aria-hidden="true" focusable="false" className="mx-auto mb-4 shrink-0 text-foreground/70" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
<path d="M78 51 C111 65 114 28 146 36" className="text-muted-foreground/50" strokeWidth="2.5" />
<rect x="10" y="25" width="68" height="43" rx="3" />
<path d="M4 68 H84 V70 A5 5 0 0 1 79 75 H9 A5 5 0 0 1 4 70 Z" />
<g className="text-muted-foreground">
<rect x="27" y="34" width="34" height="26" rx="2" />
<path d="M32 39 h.01 M36 39 h.01 M40 39 h.01" strokeWidth="2.5" />
</g>
<rect x="146" y="10" width="50" height="70" rx="3" />
<image href="/brand/nanobot_mark.svg" x="155" y="17" width="32" height="32" />
<path d="M146 53 H196 M146 66 H196 M152 60 H177 M152 73 H177 M152 80 V83 H158 V80 M184 80 V83 H190 V80" />
<circle cx="188" cy="60" r="1.8" />
<circle cx="188" cy="73" r="1.8" />
</svg>;
return <QuickPairSetupView
state={{ request, preview, code, saved: !!saved, busy, busyVisible, error, status, copied, expired, manual, panel, returned: !!returned }}
routeSettings={saved ? <PairRouteSettings id={saved} /> : null}
onStart={() => { void start(); }} onReview={() => { void review(); }} onConnect={() => { void connect(); }}
onCopyCommand={copyCommand}
onCodeChange={(value) => { setCode(value); setError(""); }}
onManualChange={(value) => { setManual(value); setPanel(null); setError(""); }} onPanelChange={setPanel}
onBack={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}
onCancel={() => { connections?.cancel(); onClose(); }} onSSH={onSSH} />;
}
@@ -0,0 +1,186 @@
import { useId, useRef, type ReactNode } from "react";
import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";
import { Textarea } from "@/components/ui/textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { CodeBlock } from "@/components/CodeBlock";
import type { ConnectionStatus } from "@/lib/types";
import "./remote-layout.css";
export interface PairInvitation {
id: string;
command: string;
expires: number;
}
export interface PairConnectionPreview {
id: string;
host: string;
hostname: string;
fingerprint: string;
authorized_until: number;
revoke_command: string;
existing_connection?: { id: string; name: string; connected: boolean };
}
export type QuickPairPanel = "command" | "help" | null;
export interface QuickPairSetupState {
request: PairInvitation | null;
preview: PairConnectionPreview | null;
code: string;
saved: boolean;
busy: boolean;
busyVisible: boolean;
error: string;
status: ConnectionStatus;
copied: boolean;
expired: boolean;
manual: boolean;
panel: QuickPairPanel;
returned: boolean;
}
export interface QuickPairSetupViewProps {
state: QuickPairSetupState;
routeSettings: ReactNode;
onStart: () => void;
onReview: () => void;
onConnect: () => void;
onCopyCommand: () => void;
onCodeChange: (code: string) => void;
onManualChange: (manual: boolean) => void;
onPanelChange: (panel: QuickPairPanel) => void;
onBack: () => void;
onCancel: () => void;
onSSH: () => void;
}
export function QuickPairSetupView({
state, routeSettings, onStart, onReview, onConnect, onCopyCommand, onCodeChange, onManualChange,
onPanelChange, onBack, onCancel, onSSH,
}: QuickPairSetupViewProps) {
const { t } = useTranslation();
const { request, preview, code, saved, busy, busyVisible, error, status, copied, expired, manual, panel, returned } = state;
const manualInput = useRef<HTMLTextAreaElement>(null);
const focusManual = useRef(false);
const codeId = useId();
const panelId = useId();
const waitingForLocal = status !== "open";
const pending = busy || (waitingForLocal && !error);
const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`);
const requestUnavailable = error === "remote.errors.pair_expired" || error === "remote.errors.pair_used";
const restartAvailable = !saved && (expired || requestUnavailable || (!!error && !request?.command && !preview && (!returned || invalidReturn)));
const visiblePreview = restartAvailable ? null : preview;
const reviewingReturn = !!returned && !request?.command && !visiblePreview && !manual && !restartAvailable;
const title = visiblePreview ? visiblePreview.existing_connection ? "remote.sameInstance.title" : "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"
: manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";
const description = visiblePreview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"
: manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";
const showCopied = copied && !manual && !visiblePreview && !restartAvailable;
const showIllustration = !visiblePreview && !manual && !reviewingReturn && !restartAvailable;
const showBusy = pending && busyVisible;
const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : visiblePreview ? saved ? "remote.retry" : visiblePreview.existing_connection ? "remote.sameInstance.saveAndOpen" : "remote.connect"
: manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";
const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : visiblePreview ? "remote.connecting" : !restartAvailable && (manual || returned)
? "remote.pair.checkingLink" : "remote.pair.preparing";
return <div className="remote-pair flex min-h-0 flex-col">
<div className="-mx-1 min-h-0 overflow-y-auto overscroll-contain px-1">
<DialogHeader className={showIllustration ? "space-y-0 text-center sm:text-center" : "pr-5 text-left"}>
{showIllustration && <RemoteConnectionIllustration />}
<div aria-live="polite" aria-atomic="true" className="space-y-1.5">
<DialogTitle className={showIllustration ? "flex min-h-5 items-center justify-center gap-2 text-xl leading-snug tracking-normal" : "flex min-h-5 items-center gap-2"}>
{showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}
<span className="min-w-0 [overflow-wrap:anywhere]">{t(title)}</span>
</DialogTitle>
<DialogDescription>{t(description)}</DialogDescription>
</div>
</DialogHeader>
{visiblePreview ? <div className="space-y-4 pt-4">
<div className="rounded-2xl bg-muted/50 p-4">
<p className="font-medium [overflow-wrap:anywhere]">{visiblePreview.existing_connection?.name || visiblePreview.hostname}</p>
<p className="mt-1 break-all text-xs text-muted-foreground">{visiblePreview.host}</p>
</div>
{visiblePreview.existing_connection && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.sameInstance.pairHint")}</p>}
<p className="text-[13px] leading-5">{t("remote.pair.access")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(visiblePreview.authorized_until * 1000).toLocaleDateString() })}</p>
<Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>
<p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{visiblePreview.fingerprint}</code>
<p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><CodeBlock language="bash" code={visiblePreview.revoke_command} highlight={false} className="min-w-0 [&_pre]:[overflow-wrap:anywhere]" />
</Disclosure>
{saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>
<Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}>{routeSettings}</Disclosure>
</div>}
</div> : restartAvailable ? null : <>
{manual && <div className="space-y-2 pt-4"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>
<Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => onCodeChange(event.target.value)} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />
</div>}
<div>
<DisclosureContent id={panelId} open={panel === "command" && !!request?.command} className="pt-4">
<div className="rounded-2xl bg-muted/50 p-3">
<code className="block max-h-32 select-text overflow-y-auto text-[11px] leading-5 [overflow-wrap:anywhere]" aria-label={t("remote.pair.command")}>{request?.command}</code>
</div>
</DisclosureContent>
<DisclosureContent open={panel === "help"} className="pt-4">
<div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">
<p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>
<p>{t("remote.pair.requirements")}</p>
<p>{t("remote.pair.runHint")}</p>
<p>{t("remote.pair.validityHint")}</p>
</div>
</DisclosureContent>
</div>
</>}
{expired && !saved && <p role="status" className="mt-4 text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}
{error && <p role="alert" className="remote-alert mt-4 items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{t(error, { defaultValue: t("remote.errors.unknown") })}</span></p>}
</div>
<div className={visiblePreview ? "remote-dialog-actions shrink-0 pt-5" : "flex shrink-0 flex-col gap-2 pt-5"}>
{visiblePreview && (!saved ? <Button className="remote-action" variant="ghost" disabled={busy} onClick={onBack}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>
: <Button className="remote-action" variant="ghost" onClick={onCancel}>{t("common.cancel")}</Button>
)}
<Button variant={showCopied ? "outline" : "default"} className={showCopied ? "remote-action bg-transparent" : "remote-action"} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={pending} disabled={busy || waitingForLocal || (!restartAvailable && (!request || (!visiblePreview && (manual || reviewingReturn ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) onStart(); else if (visiblePreview) onConnect(); else if (manual || reviewingReturn) onReview(); else onCopyCommand(); }}>
{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !visiblePreview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}
<span role="status" className="min-w-0">{t(showBusy ? busyLabel : actionLabel)}</span>
</Button>
{!visiblePreview && <div className="remote-pair-alternatives -mx-3 gap-1">
{!restartAvailable && request?.command ? manual ? <Button className="remote-action" variant="ghost" size="sm" disabled={busy} onClick={() => onManualChange(false)}>{t("remote.back")}</Button>
: <Button variant="ghost" size="sm" className="remote-action justify-start text-left text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => onPanelChange(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="remote-action justify-end text-right text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5 shrink-0" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" onCloseAutoFocus={(event) => {
if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }
}}>
<DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; onManualChange(true); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>
<DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={restartAvailable} onSelect={() => onPanelChange(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>}
</div>
</div>;
}
/** Decorative overview, not a live connection-status indicator. */
function RemoteConnectionIllustration() {
return <svg viewBox="0 0 208 88" width="184" height="78" aria-hidden="true" focusable="false" className="mx-auto mb-4 shrink-0 text-foreground/70" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
<path d="M78 51 C111 65 114 28 146 36" className="text-muted-foreground/50" strokeWidth="2.5" />
<rect x="10" y="25" width="68" height="43" rx="3" />
<path d="M4 68 H84 V70 A5 5 0 0 1 79 75 H9 A5 5 0 0 1 4 70 Z" />
<g className="text-muted-foreground">
<rect x="27" y="34" width="34" height="26" rx="2" />
<path d="M32 39 h.01 M36 39 h.01 M40 39 h.01" strokeWidth="2.5" />
</g>
<rect x="146" y="10" width="50" height="70" rx="3" />
<image href="/brand/nanobot_mark.svg" x="155" y="17" width="32" height="32" />
<path d="M146 53 H196 M146 66 H196 M152 60 H177 M152 73 H177 M152 80 V83 H158 V80 M184 80 V83 H190 V80" />
<circle cx="188" cy="60" r="1.8" />
<circle cx="188" cy="73" r="1.8" />
</svg>;
}
+10 -62
View File
@@ -1,31 +1,23 @@
import { useCallback, useEffect, useId, useRef, useState, type RefObject } from "react";
import { Check, RefreshCw, Server } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction, type SSHDiscovery } from "@/lib/remote-instances";
import { SSHHostPickerView, type SSHHostPickerViewProps } from "./SSHHostPickerView";
type SSHHostPickerProps = Pick<SSHHostPickerViewProps,
"disabled" | "value" | "imported" | "suggestions" | "onChange" | "onBlur" | "inputRef"> & {
configFile: string;
};
/** One address field for both manual entry and existing SSH aliases. */
export function SSHHostPicker({ disabled, value, configFile, imported, suggestions = true, onChange, onBlur, inputRef }: {
disabled: boolean;
value: string;
configFile: string;
imported: boolean;
suggestions?: boolean;
onChange: (host: string) => void;
onBlur: () => void;
inputRef: RefObject<HTMLInputElement>;
}) {
export function SSHHostPicker({ configFile, suggestions = true, ...props }: SSHHostPickerProps) {
const { t } = useTranslation();
const { client } = useClient();
const id = useId();
const [result, setResult] = useState<{ file: string; data: SSHDiscovery } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const requestId = useRef(0);
const mounted = useRef(true);
const list = useRef<HTMLDivElement>(null);
const file = configFile.trim();
const load = useCallback(async (path: string) => {
const request = ++requestId.current;
@@ -64,50 +56,6 @@ export function SSHHostPicker({ disabled, value, configFile, imported, suggestio
// Never select cached suggestions belonging to a different config file.
const data = suggestions && result?.file === file ? result.data : null;
const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));
// A user recovering from a failed user@IP connection may select a custom
// config containing an alias. Keep that alias discoverable without asking
// them to know it already or silently replacing the address they entered.
const hosts = matched.length || !file ? matched : (data?.hosts ?? []);
return <div className="space-y-2.5">
<label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>
<Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}
placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}
onChange={(event) => onChange(event.target.value)}
onBlur={onBlur}
onKeyDown={(event) => {
if (event.key === "ArrowDown" && hosts.length && !busy) {
event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}} />
<p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>
{suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">
<div className="flex min-h-8 items-center justify-between gap-2 px-2">
<span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" aria-label={t("remote.refreshHosts")}
disabled={busy || disabled} onClick={() => { void load(file); }}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
<div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>
{hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}
title={host.source} aria-label={t("remote.useHost", { host: host.host })}
className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const next = index + (event.key === "ArrowDown" ? 1 : -1);
if (next < 0) inputRef.current?.focus();
else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}
}}
onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="min-w-0 flex-1 truncate">{host.host}</span>
{value === host.host && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
</button>)}
</div>
{error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}
</div>}
{data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}
</div>;
return <SSHHostPickerView {...props} suggestions={suggestions} customConfig={!!file}
discovery={data} busy={busy} error={error} onRefresh={() => { void load(file); }} />;
}
@@ -0,0 +1,75 @@
import { useId, useRef, type RefObject } from "react";
import { Check, RefreshCw, Server } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { SSHDiscovery } from "@/lib/remote-instances";
export interface SSHHostPickerViewProps {
disabled: boolean;
value: string;
imported: boolean;
suggestions?: boolean;
customConfig?: boolean;
discovery: SSHDiscovery | null;
busy: boolean;
error: string;
onRefresh: () => void;
onChange: (host: string) => void;
onBlur: () => void;
inputRef: RefObject<HTMLInputElement>;
}
export function SSHHostPickerView({ disabled, value, imported, suggestions = true, customConfig = false,
discovery, busy, error, onRefresh, onChange, onBlur, inputRef }: SSHHostPickerViewProps) {
const { t } = useTranslation();
const id = useId();
const list = useRef<HTMLDivElement>(null);
const data = suggestions ? discovery : null;
const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));
// A user recovering from a failed user@IP connection may select a custom
// config containing an alias. Keep that alias discoverable without asking
// them to know it already or silently replacing the address they entered.
const hosts = matched.length || !customConfig ? matched : (data?.hosts ?? []);
return <div className="space-y-2.5">
<label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>
<Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}
placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}
onChange={(event) => onChange(event.target.value)}
onBlur={onBlur}
onKeyDown={(event) => {
if (event.key === "ArrowDown" && hosts.length && !busy) {
event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}} />
<p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>
{suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">
<div className="flex min-h-8 items-center justify-between gap-2 px-2">
<span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" aria-label={t("remote.refreshHosts")}
disabled={busy || disabled} onClick={onRefresh}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
<div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>
{hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}
title={host.source} aria-label={t("remote.useHost", { host: host.host })}
className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const next = index + (event.key === "ArrowDown" ? 1 : -1);
if (next < 0) inputRef.current?.focus();
else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}
}}
onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="min-w-0 flex-1 truncate">{host.host}</span>
{value === host.host && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
</button>)}
</div>
{error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}
</div>}
{data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}
</div>;
}
@@ -0,0 +1,28 @@
import { createContext } from "react";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import type { HostConnectionState } from "./remote-context";
export interface HostPicker {
kind: "shell";
name: string;
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
offline: boolean;
offlineLabel?: string;
select: (id: string | null) => void;
manage: () => void;
cancel: () => void;
clearError: () => void;
restoreFocus: () => void;
}
export interface EmbeddedPicker extends EmbeddedHost {
kind: "embedded";
open: (anchor: HostAnchor) => void;
}
export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);