ui(remote): manage connections without switching hosts

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent f4e45c98d7
commit 715bdf45c8
9 files changed
+241 -50

No files matched your search

@@ -0,0 +1,20 @@
import { CircleAlert, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
export type HostConnectionState = "open" | "closed" | "connecting" | "error";
/** Connectivity is independent of which host the user is currently viewing. */
export function HostConnectionStatus({ state, compact = false }: {
state: HostConnectionState;
compact?: boolean;
}) {
const { t } = useTranslation();
const label = t(`connection.${state}`);
return <span role="status" title={label} className="inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
{state === "connecting" ? <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
: state === "error" ? <CircleAlert aria-hidden className="h-3.5 w-3.5 text-amber-600 dark:text-amber-400" />
: <span aria-hidden className={cn("h-1.5 w-1.5 rounded-full", state === "open" ? "bg-emerald-500" : "bg-muted-foreground/40")} />}
<span className={compact ? "sr-only" : undefined}>{label}</span>
</span>;
}
+5 -3
View File
@@ -8,6 +8,7 @@ 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, type HostConnectionState } from "./HostConnectionStatus";
export interface HostPicker {
kind: "shell";
@@ -15,7 +16,7 @@ export interface HostPicker {
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; ready: boolean }[];
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
@@ -100,11 +101,12 @@ function HostMenuItems({ picker }: { picker: HostPicker }) {
</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} · ${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>
{picker.pending?.id === profile.id ? <Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : picker.currentId === profile.id ? <Check className="h-4 w-4 shrink-0" />
: profile.ready ? <span className="shrink-0 text-[11px] text-muted-foreground">{t("remote.ready")}</span> : null}
<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>
@@ -16,6 +16,7 @@ import { useRemoteConnections } from "./RemoteInstances";
import { SSHHostPicker } from "./SSHHostPicker";
import { QuickPairSetup } from "./QuickPairSetup";
import { PairRouteSettings } from "./PairRouteSettings";
import { HostConnectionStatus } from "./HostConnectionStatus";
const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
name: "", host: "", port: null, ssh_config: "", identity_file: "",
@@ -23,9 +24,10 @@ const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
});
/** The page is a server directory. Add/edit/first-use verification share one dialog. */
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, inPanel = false, onBackToChat }: {
mainNavigationExpanded?: boolean;
hostChromeInset?: boolean;
inPanel?: boolean;
onBackToChat: () => void;
}) {
const { t } = useTranslation();
@@ -56,6 +58,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
const mounted = useRef(true);
const operation = useRef(0);
const optionsId = useId();
const statusId = useId();
const refresh = connections?.refresh;
// Keep confirmation content intact during Radix's exit animation.
@@ -248,31 +251,36 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
<div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">
<div data-settings-section="remote" data-main-navigation-expanded={mainNavigationExpanded}
className={cn("settings-grid settings-feature-page mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 py-6 duration-200 ease-out motion-reduce:animate-none sm:py-8 lg:py-12",
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]")}>
<div className="settings-feature-header mb-7">
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]",
inPanel && "px-6 py-4 sm:py-4 lg:py-4 [--settings-margin:0px] [--settings-inset:16px]")}>
{!inPanel && <div className="settings-feature-header mb-7">
<Button variant="ghost" size="sm" className="touch-target mb-4 gap-1 lg:hidden" onClick={onBackToChat}>
<ChevronLeft className="h-4 w-4" />{t("settings.backToChat")}
</Button>
<h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t("remote.title")}</h1>
</div>
</div>}
<div className="settings-stack">
<p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t("remote.description")}</p>
{directory?.available && <>
<SettingsGroup>
<div className="settings-list-row flex items-center gap-3 py-3">
<button type="button" className="settings-list-row settings-hover flex w-full items-center gap-3 py-3 text-left"
aria-current={connections.localActive || undefined} onClick={connections.selectLocal}>
<Laptop className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block text-[14px] font-medium">{t("remote.local")}</span>
{directory.machine_name && <span className="mt-0.5 block truncate text-xs text-muted-foreground">{directory.machine_name}</span>}</span>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>
</div>
{connections.localActive && <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>}
</button>
</SettingsGroup>
{directory.profiles.length > 0 && <SettingsGroup>
{directory.profiles.map((profile) => <div key={profile.id} className="settings-list-row settings-hover flex items-center gap-2 transition-colors">
<button type="button" className="flex min-h-[60px] min-w-0 flex-1 items-center gap-3 rounded-xl py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" disabled={!!busy} onClick={(event) => {
<button type="button" aria-label={`${profile.name} ${profile.host}`} aria-describedby={`${statusId}-${profile.id}`}
aria-current={connections.activeHostId === profile.id || undefined}
className="flex min-h-[60px] min-w-0 flex-1 items-center gap-3 rounded-xl py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" disabled={!!busy} onClick={(event) => {
editorTrigger.current = event.currentTarget; void connect(profile.id);
}}>
{busy === profile.id ? <Loader2 className="h-[18px] w-[18px] shrink-0 animate-spin text-muted-foreground" /> : <Server className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />}
<span className="min-w-0 flex-1"><span className="block truncate text-[14px] font-medium">{profile.name}</span><span className="mt-0.5 block truncate text-xs text-muted-foreground">{profile.host}</span>
<span id={`${statusId}-${profile.id}`} className="mt-1 block"><HostConnectionStatus state={connections.hostStates[profile.id] || "closed"} /></span>
{profile.paired && typeof profile.authorized_until === "number" && Number.isFinite(profile.authorized_until)
&& profile.authorized_until * 1000 <= Date.now() + 7 * 86_400_000 && <span className="mt-1 block text-xs leading-5 text-muted-foreground">
{t(profile.authorized_until * 1000 <= Date.now() ? "remote.pair.expiredDevice" : "remote.pair.expiringDevice", {
@@ -280,7 +288,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
})}
</span>}
</span>
<ArrowUpRight className="h-4 w-4 text-muted-foreground" />
{connections.activeHostId === profile.id ? <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0 text-muted-foreground" /> : <ArrowUpRight aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />}
</button>
<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" disabled={!!busy}
onPointerDown={(event) => { editorTrigger.current = event.currentTarget; }}
@@ -1,16 +1,23 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { Loader2, PlugZap } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances";
import { useHostSessions } from "./useHostSessions";
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
import { useSidebarHostBridge } from "./useSidebarHostBridge";
import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { RemoteConnectionsPage } from "./RemoteConnectionsPage";
import type { HostConnectionState } from "./HostConnectionStatus";
const RemoteContext = createContext<{
available: boolean;
localActive: boolean;
activeHostId: string | null;
hostStates: Record<string, HostConnectionState>;
managing: boolean;
selectLocal: () => void;
openHostIds: string[];
directory: RemoteDirectory | null;
directoryError: boolean;
@@ -25,6 +32,11 @@ export function useRemoteConnections() { return useContext(RemoteContext); }
export function RemoteInstances({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const hosts = useHostSessions();
const [managing, setManaging] = useState(false);
const managementOpen = useRef(false);
const managementConnect = useRef(false);
const managementPanel = useRef<HTMLDivElement>(null);
const legacyFooter = useRef<HTMLDivElement>(null);
const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);
const returnLocal = hosts.local;
useEffect(() => { if (returnedPair) returnLocal(); }, [returnedPair, returnLocal]);
@@ -45,7 +57,9 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
for (const id of bridge.readyIds) hosts.loaded(id);
}, [bridge.readyIds, hosts.loaded]);
const restoreFocus = () => {
if (activeHostId.current) bridge.focus(activeHostId.current);
const fallback = legacyFooter.current?.querySelector<HTMLElement>("[data-host-switcher]");
if (activeHostId.current && fallback) fallback.focus({ preventScroll: true });
else if (activeHostId.current) bridge.focus(activeHostId.current);
else restoreLocalFocus();
};
const available = directory?.available === true || hosts.directoryError;
@@ -53,7 +67,32 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
const offline = !!selected && (activeFrame?.offline || (!activeFrame && pending?.id !== selected.id));
const recoveryCode = (hosts.errorId === selected?.id ? error : "") || activeFrame?.error || "";
const recoveryMessage = recoveryCode ? t(`remote.errors.${recoveryCode}`, { defaultValue: t("remote.errors.unknown") }) : t("remote.noFallback");
const manage = () => { hosts.local(); window.location.hash = "/remote"; };
const changeManagement = (open: boolean) => {
managementOpen.current = open;
// Dismissing management cancels only work started there, not an existing
// switch or session restoration that happens to be running behind it.
if (!open && managementConnect.current) hosts.cancel();
setManaging(open);
};
const manage = () => { bridge.close(); changeManagement(true); };
const selectLocal = () => { hosts.local(); changeManagement(false); };
const connect = async (id: string, stillWanted: () => boolean = () => true) => {
const wanted = () => stillWanted() && (!managing || managementOpen.current);
if (!wanted()) return;
managementConnect.current = managing;
try {
await hosts.connect(id, wanted);
managementConnect.current = false;
if (wanted()) changeManagement(false);
} finally { managementConnect.current = false; }
};
const hostStates: Record<string, HostConnectionState> = {};
for (const profile of directory?.profiles || []) {
const frame = frames.find((item) => item.connection.id === profile.id);
hostStates[profile.id] = pending?.id === profile.id ? "connecting"
: hosts.directoryError || frame?.offline || hosts.errorId === profile.id || (profile.connection_error && profile.connection_error !== "disconnected") ? "error"
: profile.connected || (frame?.loaded && !frame.offline) ? "open" : "closed";
}
const switchHost = (id: string) => {
// The session module owns attempt-scoped errors, including cancelled work.
void hosts.connect(id).catch(() => {});
@@ -61,11 +100,10 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
const picker: HostPicker = {
kind: "shell", name: selected?.name || t("remote.localShort"), hostname: selected?.hostname || directory?.machine_name || "nanobot",
localName: directory?.machine_name || "nanobot", currentId: selected?.id || null, recentIds: hosts.recentIds,
profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host,
ready: frames.some((frame) => frame.connection.id === id && !frame.offline && frame.loaded) })),
profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host, state: hostStates[id] })),
pending, error: message, offline: !!offline, select: (id) => { if (id) switchHost(id); else hosts.local(); },
manage,
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus,
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus: () => { if (!managing) restoreFocus(); },
};
useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);
useEffect(() => {
@@ -89,8 +127,9 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
}, [selected]);
return <RemoteContext.Provider value={{ available, localActive: !selected, directory,
activeHostId: selected?.id || null, hostStates, managing, selectLocal,
openHostIds: frames.map((frame) => frame.connection.id),
directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
directoryError: hosts.directoryError, refresh: hosts.refresh, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
<div className="flex h-full min-h-0 flex-col bg-background">
<div className="relative min-h-0 flex-1 overflow-hidden">
@@ -126,10 +165,18 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
</div>
{/* Older remote bundles cannot host the control. Keep an explicit exit
in a compact bottom strip, never cover their sidebar controls. */}
{selected && (!bridge.readyIds.includes(selected.id) || offline) && <div data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
{selected && (!bridge.readyIds.includes(selected.id) || offline) && <div ref={legacyFooter} data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
<div className="flex w-52 min-w-0"><HostSwitcher /></div>
</div>}
<RemoteHostMenu picker={picker} anchor={bridge.anchor} onClose={bridge.close} />
<Sheet open={managing} onOpenChange={changeManagement}>
<SheetContent ref={managementPanel} aria-describedby={undefined} className="w-full gap-0 overflow-hidden bg-settings-canvas outline-none sm:max-w-xl"
onOpenAutoFocus={(event) => { event.preventDefault(); managementPanel.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); restoreFocus(); }}>
<div className="shrink-0 px-6 pb-2 pt-7 pr-12"><SheetTitle className="text-xl font-medium">{t("remote.title")}</SheetTitle></div>
<RemoteConnectionsPage inPanel onBackToChat={() => changeManagement(false)} />
</SheetContent>
</Sheet>
</div>
</HostNavigationContext.Provider>
</RemoteContext.Provider>;