Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddEnvironmentDialog.tsx

650 lines23.7 KB

1import { ChevronsLeftRightEllipsisIcon, PlusIcon, TerminalIcon } from "lucide-react";
2import { useAtomValue } from "@effect/atom-react";
3import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
4import {
5 type DesktopDiscoveredSshHost,
6 type DesktopSshEnvironmentTarget,
7} from "@t3tools/contracts";
8import {
9 RelayConnectionRegistration,
10 RelayConnectionTarget,
11} from "@t3tools/client-runtime/connection";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import * as Option from "effect/Option";
17​
18import { cn } from "../../lib/utils";
19import { formatDesktopSshTarget } from "./EnvironmentRow";
20import { Input } from "../ui/input";
21import { CommandShortcut } from "../ui/command";
22import {
23 Autocomplete,
24 AutocompleteEmpty,
25 AutocompleteInput,
26 AutocompleteItem,
27 AutocompleteList,
28 AutocompletePopup,
29} from "../ui/autocomplete";
30import {
31 Dialog,
32 DialogDescription,
33 DialogHeader,
34 DialogPanel,
35 DialogPopup,
36 DialogTitle,
37 DialogTrigger,
38} from "../ui/dialog";
39import { stackedThreadToast, toastManager } from "../ui/toast";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import { Alert, AlertDescription } from "../ui/alert";
42import { Button } from "../ui/button";
43import { AnimatedHeight } from "../AnimatedHeight";
44import { environmentCatalog } from "~/connection/catalog";
45import {
46 connectPairing as connectPairingAtom,
47 connectSshEnvironment as connectSshEnvironmentAtom,
48} from "~/connection/onboarding";
49import { useEnvironmentQuery } from "~/state/query";
50import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
51import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
52import { useAtomCommand } from "../../state/use-atom-command";
53import { primaryServerKeybindingsAtom } from "~/state/server";
54import {
55 resolveShortcutCommand,
56 shortcutLabelForCommand,
57 threadJumpCommandForIndex,
58 threadJumpIndexFromCommand,
59} from "../../keybindings";
60import {
61 parseManualDesktopSshTarget,
62 parsePairingUrlFields,
63 parseRemotePairingFields,
64 formatDesktopSshConnectionError,
65} from "./ConnectionsSettings.logic";
66​
67const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
68​
69export function AddEnvironmentDialog({
70 open,
71 routeTarget,
72 error,
73 savedEnvironments,
74 onOpenChange,
75 onErrorChange,
76}: {
77 readonly open: boolean;
78 readonly routeTarget: EnvironmentPresentation | null;
79 readonly error: string | null;
80 readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
81 readonly onOpenChange: (open: boolean) => void;
82 readonly onErrorChange: (error: string | null) => void;
83}) {
84 const desktopBridge = window.desktopBridge;
85 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
86 const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
87 const connectSshEnvironment = useAtomCommand(connectSshEnvironmentAtom, {
88 reportFailure: false,
89 });
90 const registerEnvironment = useAtomCommand(environmentCatalog.register, {
91 reportFailure: false,
92 });
93 const relayDiscoveryState = useRelayEnvironmentDiscovery();
94 const savedDesktopSshEnvironmentKeys = (() => {
95 const keys = new Set<string>();
96 for (const environment of savedEnvironments) {
97 const profile = environment.entry.profile;
98 if (
99 environment.entry.target._tag !== "SshConnectionTarget" ||
100 Option.isNone(profile) ||
101 profile.value._tag !== "SshConnectionProfile"
102 ) {
103 continue;
104 }
105 const target = profile.value.target;
106 keys.add(target.alias);
107 keys.add(formatDesktopSshTarget(target));
108 }
109 return keys;
110 })();
111 const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
112 const [savedBackendHost, setSavedBackendHost] = useState("");
113 const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
114 const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
115 const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
116 const [savedBackendSshPort, setSavedBackendSshPort] = useState("");
117 const [sshHostSuggestionsOpen, setSshHostSuggestionsOpen] = useState(false);
118 const highlightedSshHostRef = useRef<DesktopDiscoveredSshHost | undefined>(undefined);
119 const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false);
120 const isSshDiscoveryActive = desktopBridge !== undefined && open && savedBackendMode === "ssh";
121 const desktopSshHosts = useEnvironmentQuery(
122 isSshDiscoveryActive ? desktopSshHostsStateAtom : null,
123 );
124 // The discovery atom is kept alive across dialog opens, so re-read SSH config
125 // each time the SSH tab is shown; stale hosts stay visible while it refreshes.
126 const refreshDesktopSshHosts = desktopSshHosts.refresh;
127 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rereads desktop SSH config through the bridge each time the SSH tab is shown
128 useEffect(() => {
129 if (isSshDiscoveryActive) refreshDesktopSshHosts();
130 }, [isSshDiscoveryActive, refreshDesktopSshHosts]);
131 const discoveredSshHosts = desktopSshHosts.data ?? EMPTY_DISCOVERED_SSH_HOSTS;
132 const unsavedDiscoveredSshHosts = discoveredSshHosts.filter((target) => {
133 const address = formatDesktopSshTarget(target);
134 return (
135 !savedDesktopSshEnvironmentKeys.has(target.alias) &&
136 (target.source === "ssh-config" || !savedDesktopSshEnvironmentKeys.has(address))
137 );
138 });
139 const filteredDiscoveredSshHosts = filterDiscoveredSshHosts(
140 unsavedDiscoveredSshHosts,
141 savedBackendSshHost,
142 );
143 const isLoadingDiscoveredSshHosts = desktopSshHosts.isPending && desktopSshHosts.data === null;
144 const discoveredSshHostsError = desktopSshHosts.error;
145 const hasSshHostSuggestionContent =
146 desktopBridge !== undefined &&
147 (isLoadingDiscoveredSshHosts || unsavedDiscoveredSshHosts.length > 0);
148 const connectSavedBackendSshTarget = async (target: DesktopSshEnvironmentTarget) => {
149 setIsAddingSavedBackend(true);
150 onErrorChange(null);
151 const result = await connectSshEnvironment({
152 target,
153 label: "",
154 ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
155 });
156 if (result._tag === "Failure") {
157 if (!isAtomCommandInterrupted(result)) {
158 onErrorChange(formatDesktopSshConnectionError(squashAtomCommandFailure(result)));
159 }
160 setIsAddingSavedBackend(false);
161 return;
162 }
163​
164 setSavedBackendHost("");
165 setSavedBackendPairingCode("");
166 setSavedBackendSshHost("");
167 setSavedBackendSshUsername("");
168 setSavedBackendSshPort("");
169 onOpenChange(false);
170 toastManager.add({
171 type: "success",
172 title: routeTarget ? "Route added" : "Environment connected",
173 description: routeTarget
174 ? `${routeTarget.label} can now be reached over SSH ${target.alias}.`
175 : `${target.alias} is ready over an SSH-managed tunnel.`,
176 });
177 setIsAddingSavedBackend(false);
178 };
179​
180 const handleAddSavedBackend = async () => {
181 if (savedBackendMode === "ssh") {
182 let target: DesktopSshEnvironmentTarget;
183 try {
184 target = parseManualDesktopSshTarget({
185 host: savedBackendSshHost,
186 username: savedBackendSshUsername,
187 port: savedBackendSshPort,
188 });
189 } catch (error) {
190 onErrorChange(formatDesktopSshConnectionError(error));
191 return;
192 }
193​
194 await connectSavedBackendSshTarget(target);
195 return;
196 }
197​
198 setIsAddingSavedBackend(true);
199 onErrorChange(null);
200 let remotePairingInput: ReturnType<typeof parseRemotePairingFields>;
201 try {
202 remotePairingInput = parseRemotePairingFields({
203 host: savedBackendHost,
204 pairingCode: savedBackendPairingCode,
205 });
206 } catch (error) {
207 const message = error instanceof Error ? error.message : "Failed to add backend.";
208 onErrorChange(message);
209 toastManager.add(
210 stackedThreadToast({
211 type: "error",
212 title: "Could not add backend",
213 description: message,
214 }),
215 );
216 setIsAddingSavedBackend(false);
217 return;
218 }
219​
220 const result = await connectPairing({
221 ...remotePairingInput,
222 ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
223 });
224 if (result._tag === "Failure") {
225 if (!isAtomCommandInterrupted(result)) {
226 const error = squashAtomCommandFailure(result);
227 const message = error instanceof Error ? error.message : "Failed to add backend.";
228 onErrorChange(message);
229 toastManager.add(
230 stackedThreadToast({
231 type: "error",
232 title: "Could not add backend",
233 description: message,
234 }),
235 );
236 }
237 setIsAddingSavedBackend(false);
238 return;
239 }
240​
241 setSavedBackendHost("");
242 setSavedBackendPairingCode("");
243 setSavedBackendSshHost("");
244 setSavedBackendSshUsername("");
245 setSavedBackendSshPort("");
246 onOpenChange(false);
247 toastManager.add(
248 routeTarget
249 ? {
250 type: "success",
251 title: "Route added",
252 description: `${routeTarget.label} now has another way to connect.`,
253 }
254 : {
255 type: "success",
256 title: "Backend added",
257 description: "The environment is saved and will reconnect on app startup.",
258 },
259 );
260 setIsAddingSavedBackend(false);
261 };
262​
263 const handleSavedBackendSshFieldKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
264 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
265 if (event.key === "Enter" && savedBackendSshHost.trim().length > 0) {
266 event.preventDefault();
267 void handleAddSavedBackend();
268 }
269 };
270​
271 const handleSelectSshHostSuggestion = async (target: DesktopDiscoveredSshHost) => {
272 if (isAddingSavedBackend || !desktopBridge) return;
273​
274 setIsAddingSavedBackend(true);
275 onErrorChange(null);
276 setSavedBackendSshHost(target.alias);
277 let resolved: DesktopSshEnvironmentTarget;
278 try {
279 resolved = await desktopBridge.resolveSshHost(target.alias);
280 } catch (error) {
281 onErrorChange(formatDesktopSshConnectionError(error));
282 setIsAddingSavedBackend(false);
283 return;
284 }
285 setSavedBackendSshUsername(resolved.username ?? "");
286 setSavedBackendSshPort(resolved.port === null ? "" : String(resolved.port));
287 await connectSavedBackendSshTarget(resolved);
288 };
289​
290 const handleSavedBackendSshHostKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
291 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
292​
293 const isSshHostPopupVisible = sshHostSuggestionsOpen && hasSshHostSuggestionContent;
294 if (isSshHostPopupVisible) {
295 const command = resolveShortcutCommand(event, keybindings, {
296 platform: navigator.platform,
297 context: { modelPickerOpen: false },
298 });
299 const index = threadJumpIndexFromCommand(command ?? "");
300 const target = index === null ? undefined : filteredDiscoveredSshHosts[index];
301 if (target) {
302 event.preventDefault();
303 event.stopPropagation();
304 setSshHostSuggestionsOpen(false);
305 void handleSelectSshHostSuggestion(target);
306 return;
307 }
308​
309 if (event.key === "Escape") {
310 event.preventDefault();
311 event.stopPropagation();
312 return;
313 }
314 }
315​
316 const hasHighlightedSshHost =
317 isSshHostPopupVisible && highlightedSshHostRef.current !== undefined;
318 if (
319 !event.defaultPrevented &&
320 !hasHighlightedSshHost &&
321 event.key === "Enter" &&
322 savedBackendSshHost.trim().length > 0
323 ) {
324 event.preventDefault();
325 void handleAddSavedBackend();
326 }
327 };
328​
329 const handleSavedBackendHostChange = (value: string) => {
330 const parsedPairingUrl = parsePairingUrlFields(value);
331 if (parsedPairingUrl) {
332 setSavedBackendHost(parsedPairingUrl.host);
333 setSavedBackendPairingCode(parsedPairingUrl.pairingCode);
334 return;
335 }
336 setSavedBackendHost(value);
337 };
338 const renderConnectionModeCard = (input: {
339 readonly mode: "remote" | "ssh";
340 readonly title: string;
341 readonly description: string;
342 readonly icon?: ReactNode;
343 }) => {
344 const selected = savedBackendMode === input.mode;
345 return (
346 <button
347 type="button"
348 aria-pressed={selected}
349 className={cn(
350 "group flex min-h-24 items-start gap-3 rounded-lg border p-4 text-left",
351 selected ? "border-primary/50 bg-primary/5" : "border-border/60 hover:bg-muted/40",
352 )}
353 disabled={isAddingSavedBackend}
354 onClick={() => {
355 setSavedBackendMode(input.mode);
356 }}
357 >
358 {input.icon ? (
359 <span
360 className={cn(
361 "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border",
362 selected
363 ? "border-primary/30 bg-primary/10 text-primary"
364 : "border-border/70 bg-background text-muted-foreground group-hover:text-foreground",
365 )}
366 >
367 {input.icon}
368 </span>
369 ) : null}
370 <span className="min-w-0">
371 <span className="block text-sm font-medium text-foreground">{input.title}</span>
372 <span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
373 {input.description}
374 </span>
375 </span>
376 </button>
377 );
378 };
379​
380 const renderRemoteFields = () => (
381 <div className="space-y-3">
382 <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_10rem]">
383 <label className="block">
384 <span className="mb-1.5 block text-xs font-medium text-foreground">Host</span>
385 <Input
386 value={savedBackendHost}
387 onChange={(event) => handleSavedBackendHostChange(event.target.value)}
388 placeholder="backend.example.com"
389 disabled={isAddingSavedBackend}
390 spellCheck={false}
391 />
392 </label>
393 <label className="block">
394 <span className="mb-1.5 block text-xs font-medium text-foreground">Pairing code</span>
395 <Input
396 value={savedBackendPairingCode}
397 onChange={(event) => setSavedBackendPairingCode(event.target.value)}
398 placeholder="PAIRCODE"
399 disabled={isAddingSavedBackend}
400 spellCheck={false}
401 />
402 </label>
403 </div>
404 <div>
405 <span className="mt-1 block text-2xs text-muted-foreground">
406 Paste a full pairing URL here to fill both fields automatically.
407 </span>
408 </div>
409 </div>
410 );
411 const relayRouteOffer =
412 routeTarget !== null &&
413 !routeTarget.relayManaged &&
414 relayDiscoveryState.environments.has(routeTarget.environmentId)
415 ? relayDiscoveryState.environments.get(routeTarget.environmentId)!.environment
416 : null;
417 const addRelayRoute = async () => {
418 if (relayRouteOffer === null || routeTarget === null) return;
419 setIsAddingSavedBackend(true);
420 const result = await registerEnvironment(
421 new RelayConnectionRegistration({
422 target: new RelayConnectionTarget({
423 environmentId: relayRouteOffer.environmentId,
424 label: routeTarget.label,
425 }),
426 }),
427 );
428 setIsAddingSavedBackend(false);
429 if (result._tag === "Failure") {
430 if (!isAtomCommandInterrupted(result)) {
431 const error = squashAtomCommandFailure(result);
432 onErrorChange(error instanceof Error ? error.message : "Could not add the route.");
433 }
434 return;
435 }
436 onOpenChange(false);
437 toastManager.add({
438 type: "success",
439 title: "Route added",
440 description: `${routeTarget.label} falls back to T3 Connect when its other routes are unreachable.`,
441 });
442 };
443 const renderRemoteModeBody = () => (
444 <div className="space-y-4">
445 {relayRouteOffer !== null ? (
446 <div className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2">
447 <p className="text-xs text-muted-foreground">
448 This machine is on your T3 Connect account. Use it as a fallback route.
449 </p>
450 <Button
451 size="xs"
452 variant="outline"
453 disabled={isAddingSavedBackend}
454 onClick={() => void addRelayRoute()}
455 >
456 Add T3 Connect
457 </Button>
458 </div>
459 ) : null}
460 {renderRemoteFields()}
461 {error ? <p className="text-xs text-destructive">{error}</p> : null}
462 <Button
463 variant="outline"
464 className="w-full"
465 disabled={isAddingSavedBackend}
466 onClick={() => void handleAddSavedBackend()}
467 >
468 <PlusIcon className="size-3.5" />
469 {isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
470 </Button>
471 </div>
472 );
473 const renderSshFields = () => (
474 <div className="space-y-4">
475 <div className="space-y-3">
476 <div className="block">
477 <label
478 htmlFor="saved-backend-ssh-host"
479 className="mb-1.5 block text-xs font-medium text-foreground"
480 >
481 SSH host or alias
482 </label>
483 <Autocomplete
484 items={filteredDiscoveredSshHosts}
485 itemToStringValue={(target) => target.alias}
486 mode="none"
487 openOnInputClick
488 open={sshHostSuggestionsOpen}
489 onOpenChange={setSshHostSuggestionsOpen}
490 onItemHighlighted={(target) => {
491 highlightedSshHostRef.current = target;
492 }}
493 value={savedBackendSshHost}
494 onValueChange={(value, eventDetails) => {
495 setSavedBackendSshHost(value);
496 if (eventDetails.reason !== "item-press") return;
497​
498 const target = filteredDiscoveredSshHosts.find((host) => host.alias === value);
499 if (target) void handleSelectSshHostSuggestion(target);
500 }}
501 >
502 <AutocompleteInput
503 id="saved-backend-ssh-host"
504 onKeyDown={handleSavedBackendSshHostKeyDown}
505 placeholder="Search hosts or type devbox"
506 disabled={isAddingSavedBackend}
507 spellCheck={false}
508 />
509 {hasSshHostSuggestionContent ? (
510 <AutocompletePopup>
511 {isLoadingDiscoveredSshHosts ? (
512 <div className="px-3 py-2 text-xs text-muted-foreground">Loading hosts…</div>
513 ) : filteredDiscoveredSshHosts.length > 0 ? (
514 <AutocompleteList className="max-h-72">
515 {filteredDiscoveredSshHosts.map((target, index) => {
516 const address = formatDesktopSshTarget(target);
517 const shortcutCommand = index < 9 ? threadJumpCommandForIndex(index) : null;
518 const shortcutLabel = shortcutCommand
519 ? shortcutLabelForCommand(keybindings, shortcutCommand, navigator.platform)
520 : null;
521 return (
522 <AutocompleteItem
523 key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
524 value={target}
525 className="h-8 min-h-8 whitespace-nowrap"
526 >
527 <span className="min-w-0 truncate text-sm font-medium">
528 {target.alias}
529 </span>
530 {address !== target.alias ? (
531 <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
532 {address}
533 </span>
534 ) : (
535 <span className="flex-1" />
536 )}
537 {shortcutLabel ? (
538 <CommandShortcut className="shrink-0">{shortcutLabel}</CommandShortcut>
539 ) : null}
540 </AutocompleteItem>
541 );
542 })}
543 </AutocompleteList>
544 ) : (
545 <AutocompleteEmpty className="break-all">
546 No hosts match "{savedBackendSshHost.trim()}".
547 </AutocompleteEmpty>
548 )}
549 </AutocompletePopup>
550 ) : null}
551 </Autocomplete>
552 </div>
553 <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_7rem]">
554 <label className="block">
555 <span className="mb-1.5 block text-xs font-medium text-foreground">Username</span>
556 <Input
557 value={savedBackendSshUsername}
558 onChange={(event) => setSavedBackendSshUsername(event.target.value)}
559 onKeyDown={handleSavedBackendSshFieldKeyDown}
560 placeholder="root"
561 disabled={isAddingSavedBackend}
562 spellCheck={false}
563 />
564 </label>
565 <label className="block">
566 <span className="mb-1.5 block text-xs font-medium text-foreground">Port</span>
567 <Input
568 value={savedBackendSshPort}
569 onChange={(event) => setSavedBackendSshPort(event.target.value)}
570 onKeyDown={handleSavedBackendSshFieldKeyDown}
571 placeholder="22"
572 inputMode="numeric"
573 disabled={isAddingSavedBackend}
574 spellCheck={false}
575 />
576 </label>
577 </div>
578 {error || discoveredSshHostsError ? (
579 <Alert variant="error">
580 <AlertDescription>{error ?? discoveredSshHostsError}</AlertDescription>
581 </Alert>
582 ) : null}
583 <Button
584 variant="outline"
585 className="w-full"
586 disabled={isAddingSavedBackend}
587 onClick={() => void handleAddSavedBackend()}
588 >
589 <PlusIcon className="size-3.5" />
590 {isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
591 </Button>
592 </div>
593 </div>
594 );
595​
596 return (
597 <Dialog open={open} onOpenChange={onOpenChange}>
598 <Tooltip>
599 <TooltipTrigger
600 render={
601 <DialogTrigger
602 render={
603 <Button size="xs" variant="ghost-muted" aria-label="Add environment">
604 <PlusIcon className="size-3" />
605 <span>Add environment</span>
606 </Button>
607 }
608 />
609 }
610 />
611 <TooltipPopup side="top">Add environment</TooltipPopup>
612 </Tooltip>
613 <DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
614 <DialogHeader>
615 <DialogTitle>
616 {routeTarget ? `Add a route to ${routeTarget.label}` : "Add Environment"}
617 </DialogTitle>
618 <DialogDescription>
619 {routeTarget
620 ? "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine."
621 : "Pair another environment to this client."}
622 </DialogDescription>
623 </DialogHeader>
624 <DialogPanel>
625 <div className="space-y-4">
626 <div className="grid gap-3 sm:grid-cols-2">
627 {renderConnectionModeCard({
628 mode: "remote",
629 title: "Remote link",
630 description: "Enter a backend host and pairing code.",
631 icon: <ChevronsLeftRightEllipsisIcon aria-hidden className="size-4" />,
632 })}
633 {desktopBridge
634 ? renderConnectionModeCard({
635 mode: "ssh",
636 title: "SSH",
637 description: "Use local SSH config, agent, and tunnels for the backend.",
638 icon: <TerminalIcon aria-hidden className="size-4" />,
639 })
640 : null}
641 </div>
642 <AnimatedHeight>
643 {savedBackendMode === "ssh" ? renderSshFields() : renderRemoteModeBody()}
644 </AnimatedHeight>
645 </div>
646 </DialogPanel>
647 </DialogPopup>
648 </Dialog>
649 );