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

AddEnvironmentDialog.tsx

651 lines23.7 KB

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