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