@devries-cameron20 / t3code Mirror · read-only / commits / 0bdf33a34d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 20:45 UTC

refactor(web): the add environment dialog owns its form state (#22686)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 11:21 UTC 0bdf33a34dc520d3ab1364cd116686b3492184bd
2 files changed +668 -623
apps/web/src/components/settings/AddEnvironmentDialog.tsx new
+649
@@ -0,0 +1,649 @@
1 +import { ChevronsLeftRightEllipsisIcon, PlusIcon, TerminalIcon } from "lucide-react";
2 +import { useAtomValue } from "@effect/atom-react";
3 +import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
4 +import {
5 + type DesktopDiscoveredSshHost,
6 + type DesktopSshEnvironmentTarget,
7 +} from "@t3tools/contracts";
8 +import {
9 + RelayConnectionRegistration,
10 + RelayConnectionTarget,
11 +} from "@t3tools/client-runtime/connection";
12 +import {
13 + isAtomCommandInterrupted,
14 + squashAtomCommandFailure,
15 +} from "@t3tools/client-runtime/state/runtime";
16 +import * as Option from "effect/Option";
17 +
18 +import { cn } from "../../lib/utils";
19 +import { formatDesktopSshTarget } from "./EnvironmentRow";
20 +import { Input } from "../ui/input";
21 +import { CommandShortcut } from "../ui/command";
22 +import {
23 + Autocomplete,
24 + AutocompleteEmpty,
25 + AutocompleteInput,
26 + AutocompleteItem,
27 + AutocompleteList,
28 + AutocompletePopup,
29 +} from "../ui/autocomplete";
30 +import {
31 + Dialog,
32 + DialogDescription,
33 + DialogHeader,
34 + DialogPanel,
35 + DialogPopup,
36 + DialogTitle,
37 + DialogTrigger,
38 +} from "../ui/dialog";
39 +import { stackedThreadToast, toastManager } from "../ui/toast";
40 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41 +import { Alert, AlertDescription } from "../ui/alert";
42 +import { Button } from "../ui/button";
43 +import { AnimatedHeight } from "../AnimatedHeight";
44 +import { environmentCatalog } from "~/connection/catalog";
45 +import {
46 + connectPairing as connectPairingAtom,
47 + connectSshEnvironment as connectSshEnvironmentAtom,
48 +} from "~/connection/onboarding";
49 +import { useEnvironmentQuery } from "~/state/query";
50 +import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
51 +import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
52 +import { useAtomCommand } from "../../state/use-atom-command";
53 +import { primaryServerKeybindingsAtom } from "~/state/server";
54 +import {
55 + resolveShortcutCommand,
56 + shortcutLabelForCommand,
57 + threadJumpCommandForIndex,
58 + threadJumpIndexFromCommand,
59 +} from "../../keybindings";
60 +import {
61 + parseManualDesktopSshTarget,
62 + parsePairingUrlFields,
63 + parseRemotePairingFields,
64 + formatDesktopSshConnectionError,
65 +} from "./ConnectionsSettings.logic";
66 +
67 +const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
68 +
69 +export 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 +}
apps/web/src/components/settings/ConnectionsSettings.tsx
+19 -623
@@ -1,13 +1,7 @@
1 import { SessionPermissions } from "./SessionPermissions";
2 -import {
3 - ChevronRightIcon,
4 - ChevronsLeftRightEllipsisIcon,
5 - EllipsisIcon,
6 - PlusIcon,
7 - TerminalIcon,
8 -} from "lucide-react";
2 +import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
3 import { useAtomValue } from "@effect/atom-react";
10 -import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
4 +import { useState } from "react";
5 import {
6 AuthAccessReadScope,
7 AuthAccessWriteScope,
@@ -18,26 +12,18 @@ import {
12 type AuthPairingLink,
13 type AuthPairingCredentialResult,
14 type AdvertisedEndpoint,
21 - type DesktopDiscoveredSshHost,
22 - type DesktopSshEnvironmentTarget,
15 type DesktopServerExposureState,
16 type DesktopWslState,
17 type EnvironmentId,
18 resolveEnvironmentMachineKind,
19 } from "@t3tools/contracts";
28 -import {
29 - RelayConnectionRegistration,
30 - RelayConnectionTarget,
31 -} from "@t3tools/client-runtime/connection";
20 import {
21 isAtomCommandInterrupted,
22 settlePromise,
23 squashAtomCommandFailure,
24 } from "@t3tools/client-runtime/state/runtime";
25 import * as Cause from "effect/Cause";
38 -import * as Option from "effect/Option";
26
40 -import { cn } from "../../lib/utils";
27 import { isLocalEnvironmentDisabled } from "../../localEnvironment";
28 import {
29 applyWslEnableSelection,
@@ -49,20 +35,10 @@ import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsL
35 import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
36 import { searchableSetting } from "./settingsSearch";
37 import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
52 -import { formatDesktopSshTarget } from "./EnvironmentRow";
38 import { FoldedSettingsSection } from "./FoldedSettingsSection";
39 import { LoadBalancingSettings } from "./LoadBalancingSettings";
40 import { GitHubRoutingSettings } from "./GitHubRoutingSettings";
41 import { Input } from "../ui/input";
57 -import { CommandShortcut } from "../ui/command";
58 -import {
59 - Autocomplete,
60 - AutocompleteEmpty,
61 - AutocompleteInput,
62 - AutocompleteItem,
63 - AutocompleteList,
64 - AutocompletePopup,
65 -} from "../ui/autocomplete";
42 import {
43 Dialog,
44 DialogClose,
@@ -72,7 +48,6 @@ import {
48 DialogPanel,
49 DialogPopup,
50 DialogTitle,
75 - DialogTrigger,
51 } from "../ui/dialog";
52 import { ScrollArea } from "../ui/scroll-area";
53 import {
@@ -90,9 +65,7 @@ import { Menu, MenuPopup, MenuTrigger } from "../ui/menu";
65 import { Switch } from "../ui/switch";
66 import { stackedThreadToast, toastManager } from "../ui/toast";
67 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
93 -import { Alert, AlertDescription } from "../ui/alert";
68 import { Button } from "../ui/button";
95 -import { AnimatedHeight } from "../AnimatedHeight";
69 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
70 import {
71 revokeOtherServerClientSessions,
@@ -113,33 +86,23 @@ import { hasCloudPublicConfig } from "~/cloud/publicConfig";
86 import { RemoveT3ConnectEnvironmentDialog } from "../clerk/RemoveT3ConnectEnvironmentDialog";
87 import { authEnvironment } from "~/state/auth";
88 import { environmentCatalog } from "~/connection/catalog";
116 -import {
117 - connectPairing as connectPairingAtom,
118 - connectSshEnvironment as connectSshEnvironmentAtom,
119 -} from "~/connection/onboarding";
89 import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
90 import { useEnvironmentQuery } from "~/state/query";
91 import {
92 desktopNetworkAccessStateAtom,
93 refreshDesktopNetworkAccessState,
94 } from "~/state/desktopNetworkAccess";
126 -import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
95 import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState";
96 import { useDesktopUpdateState } from "~/state/desktopUpdate";
97 import {
98 type EnvironmentPresentation,
99 useEnvironments,
100 usePrimaryEnvironment,
133 - useRelayEnvironmentDiscovery,
101 } from "~/state/environments";
102 import { requestConfirmDialog } from "~/confirmDialog";
103 import { useAtomCommand } from "../../state/use-atom-command";
104 import { environmentIdsKey } from "~/state/environmentAtomList";
138 -import {
139 - environmentUpdateStatesAtom,
140 - primaryServerKeybindingsAtom,
141 - serverEnvironment,
142 -} from "~/state/server";
105 +import { environmentUpdateStatesAtom, serverEnvironment } from "~/state/server";
106 import {
107 ServerUpdateAction,
108 ServerUpdateProgress,
@@ -147,16 +110,6 @@ import {
110 type ServerUpdateTarget,
111 } from "../ServerUpdateAction";
112 import {
150 - resolveShortcutCommand,
151 - shortcutLabelForCommand,
152 - threadJumpCommandForIndex,
153 - threadJumpIndexFromCommand,
154 -} from "../../keybindings";
155 -import {
156 - parseManualDesktopSshTarget,
157 - parsePairingUrlFields,
158 - parseRemotePairingFields,
159 - formatDesktopSshConnectionError,
113 sortDesktopPairingLinks,
114 summarizeAuthorizedClients,
115 sortDesktopClientSessions,
@@ -179,10 +132,10 @@ import {
132 CloudRemoteEnvironmentRows,
133 SavedBackendListRow,
134 } from "./SavedEnvironmentRows";
135 +import { AddEnvironmentDialog } from "./AddEnvironmentDialog";
136
137 const DEFAULT_TAILSCALE_SERVE_PORT = 443;
138 const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
185 -const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
139
140 // Sentinels for the consolidated WSL backend picker. The colon is
141 // rejected by DISTRO_NAME_PATTERN (validated on the desktop side) so
@@ -202,18 +155,9 @@ function LocalVersionStatusLabel() {
155
156 export function ConnectionsSettings() {
157 const desktopBridge = window.desktopBridge;
205 - const keybindings = useAtomValue(primaryServerKeybindingsAtom);
158 const { environments } = useEnvironments();
159 const primaryEnvironment = usePrimaryEnvironment();
208 - const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
209 - const connectSshEnvironment = useAtomCommand(connectSshEnvironmentAtom, {
210 - reportFailure: false,
211 - });
160 const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
213 - const registerEnvironment = useAtomCommand(environmentCatalog.register, {
214 - reportFailure: false,
215 - });
216 - const relayDiscoveryState = useRelayEnvironmentDiscovery();
161 const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
162 reportFailure: false,
163 });
@@ -273,23 +217,6 @@ export function ConnectionsSettings() {
217 ...(primaryEnvironment ? [primaryEnvironment] : []),
218 ...savedEnvironments.filter((environment) => environment.entry.enabled),
219 ].filter((environment) => environment.connection.phase !== "unsupported");
276 - const savedDesktopSshEnvironmentKeys = (() => {
277 - const keys = new Set<string>();
278 - for (const environment of savedEnvironments) {
279 - const profile = environment.entry.profile;
280 - if (
281 - environment.entry.target._tag !== "SshConnectionTarget" ||
282 - Option.isNone(profile) ||
283 - profile.value._tag !== "SshConnectionProfile"
284 - ) {
285 - continue;
286 - }
287 - const target = profile.value.target;
288 - keys.add(target.alias);
289 - keys.add(formatDesktopSshTarget(target));
290 - }
291 - return keys;
292 - })();
220 const [desktopServerExposureMutationError, setDesktopServerExposureMutationError] = useState<
221 string | null
222 >(null);
@@ -311,16 +238,15 @@ export function ConnectionsSettings() {
238 const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
239 const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
240 const [routeTarget, setRouteTarget] = useState<EnvironmentPresentation | null>(null);
314 - const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
315 - const [savedBackendHost, setSavedBackendHost] = useState("");
316 - const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
317 - const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
318 - const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
319 - const [savedBackendSshPort, setSavedBackendSshPort] = useState("");
320 - const [sshHostSuggestionsOpen, setSshHostSuggestionsOpen] = useState(false);
321 - const highlightedSshHostRef = useRef<DesktopDiscoveredSshHost | undefined>(undefined);
241 const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
323 - const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false);
242 + const handleAddBackendDialogOpenChange = (open: boolean) => {
243 + setAddBackendDialogOpen(open);
244 + if (open) {
245 + setRouteTarget(null);
246 + } else {
247 + setSavedBackendError(null);
248 + }
249 + };
250 const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
251 useState<EnvironmentId | null>(null);
252 const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false);
@@ -372,40 +298,12 @@ export function ConnectionsSettings() {
298 const desktopNetworkAccess = useEnvironmentQuery(
299 canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null,
300 );
375 - const isSshDiscoveryActive =
376 - desktopBridge !== undefined && addBackendDialogOpen && savedBackendMode === "ssh";
377 - const desktopSshHosts = useEnvironmentQuery(
378 - isSshDiscoveryActive ? desktopSshHostsStateAtom : null,
379 - );
380 - // The discovery atom is kept alive across dialog opens, so re-read SSH config
381 - // each time the SSH tab is shown; stale hosts stay visible while it refreshes.
382 - const refreshDesktopSshHosts = desktopSshHosts.refresh;
383 - useEffect(() => {
384 - if (isSshDiscoveryActive) refreshDesktopSshHosts();
385 - }, [isSshDiscoveryActive, refreshDesktopSshHosts]);
301 const desktopWsl = useEnvironmentQuery(
302 canManageLocalBackend && desktopBridge ? desktopWslStateAtom : null,
303 );
304 const desktopWslState = desktopWsl.data;
305 const desktopWslError = desktopWslMutationError ?? desktopWsl.error;
306 const isLoadingWslState = desktopWsl.isPending && desktopWsl.data === null;
392 - const discoveredSshHosts = desktopSshHosts.data ?? EMPTY_DISCOVERED_SSH_HOSTS;
393 - const unsavedDiscoveredSshHosts = discoveredSshHosts.filter((target) => {
394 - const address = formatDesktopSshTarget(target);
395 - return (
396 - !savedDesktopSshEnvironmentKeys.has(target.alias) &&
397 - (target.source === "ssh-config" || !savedDesktopSshEnvironmentKeys.has(address))
398 - );
399 - });
400 - const filteredDiscoveredSshHosts = filterDiscoveredSshHosts(
401 - unsavedDiscoveredSshHosts,
402 - savedBackendSshHost,
403 - );
404 - const isLoadingDiscoveredSshHosts = desktopSshHosts.isPending && desktopSshHosts.data === null;
405 - const discoveredSshHostsError = desktopSshHosts.error;
406 - const hasSshHostSuggestionContent =
407 - desktopBridge !== undefined &&
408 - (isLoadingDiscoveredSshHosts || unsavedDiscoveredSshHosts.length > 0);
307 const desktopServerExposureState = desktopNetworkAccess.data?.serverExposureState ?? null;
308 const desktopAdvertisedEndpoints =
309 desktopNetworkAccess.data?.advertisedEndpoints ?? EMPTY_ADVERTISED_ENDPOINTS;
@@ -656,187 +554,6 @@ export function ConnectionsSettings() {
554 setIsRevokingOtherDesktopClients(false);
555 };
556
659 - const connectSavedBackendSshTarget = async (target: DesktopSshEnvironmentTarget) => {
660 - setIsAddingSavedBackend(true);
661 - setSavedBackendError(null);
662 - const result = await connectSshEnvironment({
663 - target,
664 - label: "",
665 - ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
666 - });
667 - if (result._tag === "Failure") {
668 - if (!isAtomCommandInterrupted(result)) {
669 - setSavedBackendError(formatDesktopSshConnectionError(squashAtomCommandFailure(result)));
670 - }
671 - setIsAddingSavedBackend(false);
672 - return;
673 - }
674 -
675 - setSavedBackendHost("");
676 - setSavedBackendPairingCode("");
677 - setSavedBackendSshHost("");
678 - setSavedBackendSshUsername("");
679 - setSavedBackendSshPort("");
680 - setAddBackendDialogOpen(false);
681 - toastManager.add({
682 - type: "success",
683 - title: routeTarget ? "Route added" : "Environment connected",
684 - description: routeTarget
685 - ? `${routeTarget.label} can now be reached over SSH ${target.alias}.`
686 - : `${target.alias} is ready over an SSH-managed tunnel.`,
687 - });
688 - setIsAddingSavedBackend(false);
689 - };
690 -
691 - const handleAddSavedBackend = async () => {
692 - if (savedBackendMode === "ssh") {
693 - let target: DesktopSshEnvironmentTarget;
694 - try {
695 - target = parseManualDesktopSshTarget({
696 - host: savedBackendSshHost,
697 - username: savedBackendSshUsername,
698 - port: savedBackendSshPort,
699 - });
700 - } catch (error) {
701 - setSavedBackendError(formatDesktopSshConnectionError(error));
702 - return;
703 - }
704 -
705 - await connectSavedBackendSshTarget(target);
706 - return;
707 - }
708 -
709 - setIsAddingSavedBackend(true);
710 - setSavedBackendError(null);
711 - let remotePairingInput: ReturnType<typeof parseRemotePairingFields>;
712 - try {
713 - remotePairingInput = parseRemotePairingFields({
714 - host: savedBackendHost,
715 - pairingCode: savedBackendPairingCode,
716 - });
717 - } catch (error) {
718 - const message = error instanceof Error ? error.message : "Failed to add backend.";
719 - setSavedBackendError(message);
720 - toastManager.add(
721 - stackedThreadToast({
722 - type: "error",
723 - title: "Could not add backend",
724 - description: message,
725 - }),
726 - );
727 - setIsAddingSavedBackend(false);
728 - return;
729 - }
730 -
731 - const result = await connectPairing({
732 - ...remotePairingInput,
733 - ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
734 - });
735 - if (result._tag === "Failure") {
736 - if (!isAtomCommandInterrupted(result)) {
737 - const error = squashAtomCommandFailure(result);
738 - const message = error instanceof Error ? error.message : "Failed to add backend.";
739 - setSavedBackendError(message);
740 - toastManager.add(
741 - stackedThreadToast({
742 - type: "error",
743 - title: "Could not add backend",
744 - description: message,
745 - }),
746 - );
747 - }
748 - setIsAddingSavedBackend(false);
749 - return;
750 - }
751 -
752 - setSavedBackendHost("");
753 - setSavedBackendPairingCode("");
754 - setSavedBackendSshHost("");
755 - setSavedBackendSshUsername("");
756 - setSavedBackendSshPort("");
757 - setAddBackendDialogOpen(false);
758 - toastManager.add(
759 - routeTarget
760 - ? {
761 - type: "success",
762 - title: "Route added",
763 - description: `${routeTarget.label} now has another way to connect.`,
764 - }
765 - : {
766 - type: "success",
767 - title: "Backend added",
768 - description: "The environment is saved and will reconnect on app startup.",
769 - },
770 - );
771 - setIsAddingSavedBackend(false);
772 - };
773 -
774 - const handleSavedBackendSshFieldKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
775 - if (event.nativeEvent.isComposing || event.keyCode === 229) return;
776 - if (event.key === "Enter" && savedBackendSshHost.trim().length > 0) {
777 - event.preventDefault();
778 - void handleAddSavedBackend();
779 - }
780 - };
781 -
782 - const handleSelectSshHostSuggestion = async (target: DesktopDiscoveredSshHost) => {
783 - if (isAddingSavedBackend || !desktopBridge) return;
784 -
785 - setIsAddingSavedBackend(true);
786 - setSavedBackendError(null);
787 - setSavedBackendSshHost(target.alias);
788 - let resolved: DesktopSshEnvironmentTarget;
789 - try {
790 - resolved = await desktopBridge.resolveSshHost(target.alias);
791 - } catch (error) {
792 - setSavedBackendError(formatDesktopSshConnectionError(error));
793 - setIsAddingSavedBackend(false);
794 - return;
795 - }
796 - setSavedBackendSshUsername(resolved.username ?? "");
797 - setSavedBackendSshPort(resolved.port === null ? "" : String(resolved.port));
798 - await connectSavedBackendSshTarget(resolved);
799 - };
800 -
801 - const handleSavedBackendSshHostKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
802 - if (event.nativeEvent.isComposing || event.keyCode === 229) return;
803 -
804 - const isSshHostPopupVisible = sshHostSuggestionsOpen && hasSshHostSuggestionContent;
805 - if (isSshHostPopupVisible) {
806 - const command = resolveShortcutCommand(event, keybindings, {
807 - platform: navigator.platform,
808 - context: { modelPickerOpen: false },
809 - });
810 - const index = threadJumpIndexFromCommand(command ?? "");
811 - const target = index === null ? undefined : filteredDiscoveredSshHosts[index];
812 - if (target) {
813 - event.preventDefault();
814 - event.stopPropagation();
815 - setSshHostSuggestionsOpen(false);
816 - void handleSelectSshHostSuggestion(target);
817 - return;
818 - }
819 -
820 - if (event.key === "Escape") {
821 - event.preventDefault();
822 - event.stopPropagation();
823 - return;
824 - }
825 - }
826 -
827 - const hasHighlightedSshHost =
828 - isSshHostPopupVisible && highlightedSshHostRef.current !== undefined;
829 - if (
830 - !event.defaultPrevented &&
831 - !hasHighlightedSshHost &&
832 - event.key === "Enter" &&
833 - savedBackendSshHost.trim().length > 0
834 - ) {
835 - event.preventDefault();
836 - void handleAddSavedBackend();
837 - }
838 - };
839 -
557 const handleSetSavedBackendEnabled = async (environmentId: EnvironmentId, enabled: boolean) => {
558 setSavedBackendError(null);
559 const result = await setEnvironmentEnabled({ environmentId, enabled });
@@ -917,273 +634,7 @@ export function ConnectionsSettings() {
634 const handleSetDefaultAdvertisedEndpoint = (endpoint: AdvertisedEndpoint) => {
635 setDefaultAdvertisedEndpointKey(endpointDefaultPreferenceKey(endpoint));
636 };
920 - const handleSavedBackendHostChange = (value: string) => {
921 - const parsedPairingUrl = parsePairingUrlFields(value);
922 - if (parsedPairingUrl) {
923 - setSavedBackendHost(parsedPairingUrl.host);
924 - setSavedBackendPairingCode(parsedPairingUrl.pairingCode);
925 - return;
926 - }
927 - setSavedBackendHost(value);
928 - };
929 -
930 - const renderConnectionModeCard = (input: {
931 - readonly mode: "remote" | "ssh";
932 - readonly title: string;
933 - readonly description: string;
934 - readonly icon?: ReactNode;
935 - }) => {
936 - const selected = savedBackendMode === input.mode;
937 - return (
938 - <button
939 - type="button"
940 - aria-pressed={selected}
941 - className={cn(
942 - "group flex min-h-24 items-start gap-3 rounded-lg border p-4 text-left",
943 - selected ? "border-primary/50 bg-primary/5" : "border-border/60 hover:bg-muted/40",
944 - )}
945 - disabled={isAddingSavedBackend}
946 - onClick={() => {
947 - setSavedBackendMode(input.mode);
948 - }}
949 - >
950 - {input.icon ? (
951 - <span
952 - className={cn(
953 - "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border",
954 - selected
955 - ? "border-primary/30 bg-primary/10 text-primary"
956 - : "border-border/70 bg-background text-muted-foreground group-hover:text-foreground",
957 - )}
958 - >
959 - {input.icon}
960 - </span>
961 - ) : null}
962 - <span className="min-w-0">
963 - <span className="block text-sm font-medium text-foreground">{input.title}</span>
964 - <span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
965 - {input.description}
966 - </span>
967 - </span>
968 - </button>
969 - );
970 - };
971 -
972 - const renderRemoteFields = () => (
973 - <div className="space-y-3">
974 - <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_10rem]">
975 - <label className="block">
976 - <span className="mb-1.5 block text-xs font-medium text-foreground">Host</span>
977 - <Input
978 - value={savedBackendHost}
979 - onChange={(event) => handleSavedBackendHostChange(event.target.value)}
980 - placeholder="backend.example.com"
981 - disabled={isAddingSavedBackend}
982 - spellCheck={false}
983 - />
984 - </label>
985 - <label className="block">
986 - <span className="mb-1.5 block text-xs font-medium text-foreground">Pairing code</span>
987 - <Input
988 - value={savedBackendPairingCode}
989 - onChange={(event) => setSavedBackendPairingCode(event.target.value)}
990 - placeholder="PAIRCODE"
991 - disabled={isAddingSavedBackend}
992 - spellCheck={false}
993 - />
994 - </label>
995 - </div>
996 - <div>
997 - <span className="mt-1 block text-2xs text-muted-foreground">
998 - Paste a full pairing URL here to fill both fields automatically.
999 - </span>
1000 - </div>
1001 - </div>
1002 - );
1003 - const relayRouteOffer =
1004 - routeTarget !== null &&
1005 - !routeTarget.relayManaged &&
1006 - relayDiscoveryState.environments.has(routeTarget.environmentId)
1007 - ? relayDiscoveryState.environments.get(routeTarget.environmentId)!.environment
1008 - : null;
1009 - const addRelayRoute = async () => {
1010 - if (relayRouteOffer === null || routeTarget === null) return;
1011 - setIsAddingSavedBackend(true);
1012 - const result = await registerEnvironment(
1013 - new RelayConnectionRegistration({
1014 - target: new RelayConnectionTarget({
1015 - environmentId: relayRouteOffer.environmentId,
1016 - label: routeTarget.label,
1017 - }),
1018 - }),
1019 - );
1020 - setIsAddingSavedBackend(false);
1021 - if (result._tag === "Failure") {
1022 - if (!isAtomCommandInterrupted(result)) {
1023 - const error = squashAtomCommandFailure(result);
1024 - setSavedBackendError(error instanceof Error ? error.message : "Could not add the route.");
1025 - }
1026 - return;
1027 - }
1028 - setAddBackendDialogOpen(false);
1029 - toastManager.add({
1030 - type: "success",
1031 - title: "Route added",
1032 - description: `${routeTarget.label} falls back to T3 Connect when its other routes are unreachable.`,
1033 - });
1034 - };
1035 - const renderRemoteModeBody = () => (
1036 - <div className="space-y-4">
1037 - {relayRouteOffer !== null ? (
1038 - <div className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2">
1039 - <p className="text-xs text-muted-foreground">
1040 - This machine is on your T3 Connect account. Use it as a fallback route.
1041 - </p>
1042 - <Button
1043 - size="xs"
1044 - variant="outline"
1045 - disabled={isAddingSavedBackend}
1046 - onClick={() => void addRelayRoute()}
1047 - >
1048 - Add T3 Connect
1049 - </Button>
1050 - </div>
1051 - ) : null}
1052 - {renderRemoteFields()}
1053 - {savedBackendError ? <p className="text-xs text-destructive">{savedBackendError}</p> : null}
1054 - <Button
1055 - variant="outline"
1056 - className="w-full"
1057 - disabled={isAddingSavedBackend}
1058 - onClick={() => void handleAddSavedBackend()}
1059 - >
1060 - <PlusIcon className="size-3.5" />
1061 - {isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
1062 - </Button>
1063 - </div>
1064 - );
1065 - const renderSshFields = () => (
1066 - <div className="space-y-4">
1067 - <div className="space-y-3">
1068 - <div className="block">
1069 - <label
1070 - htmlFor="saved-backend-ssh-host"
1071 - className="mb-1.5 block text-xs font-medium text-foreground"
1072 - >
1073 - SSH host or alias
1074 - </label>
1075 - <Autocomplete
1076 - items={filteredDiscoveredSshHosts}
1077 - itemToStringValue={(target) => target.alias}
1078 - mode="none"
1079 - openOnInputClick
1080 - open={sshHostSuggestionsOpen}
1081 - onOpenChange={setSshHostSuggestionsOpen}
1082 - onItemHighlighted={(target) => {
1083 - highlightedSshHostRef.current = target;
1084 - }}
1085 - value={savedBackendSshHost}
1086 - onValueChange={(value, eventDetails) => {
1087 - setSavedBackendSshHost(value);
1088 - if (eventDetails.reason !== "item-press") return;
637
1090 - const target = filteredDiscoveredSshHosts.find((host) => host.alias === value);
1091 - if (target) void handleSelectSshHostSuggestion(target);
1092 - }}
1093 - >
1094 - <AutocompleteInput
1095 - id="saved-backend-ssh-host"
1096 - onKeyDown={handleSavedBackendSshHostKeyDown}
1097 - placeholder="Search hosts or type devbox"
1098 - disabled={isAddingSavedBackend}
1099 - spellCheck={false}
1100 - />
1101 - {hasSshHostSuggestionContent ? (
1102 - <AutocompletePopup>
1103 - {isLoadingDiscoveredSshHosts ? (
1104 - <div className="px-3 py-2 text-xs text-muted-foreground">Loading hosts…</div>
1105 - ) : filteredDiscoveredSshHosts.length > 0 ? (
1106 - <AutocompleteList className="max-h-72">
1107 - {filteredDiscoveredSshHosts.map((target, index) => {
1108 - const address = formatDesktopSshTarget(target);
1109 - const shortcutCommand = index < 9 ? threadJumpCommandForIndex(index) : null;
1110 - const shortcutLabel = shortcutCommand
1111 - ? shortcutLabelForCommand(keybindings, shortcutCommand, navigator.platform)
1112 - : null;
1113 - return (
1114 - <AutocompleteItem
1115 - key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
1116 - value={target}
1117 - className="h-8 min-h-8 whitespace-nowrap"
1118 - >
1119 - <span className="min-w-0 truncate text-sm font-medium">
1120 - {target.alias}
1121 - </span>
1122 - {address !== target.alias ? (
1123 - <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
1124 - {address}
1125 - </span>
1126 - ) : (
1127 - <span className="flex-1" />
1128 - )}
1129 - {shortcutLabel ? (
1130 - <CommandShortcut className="shrink-0">{shortcutLabel}</CommandShortcut>
1131 - ) : null}
1132 - </AutocompleteItem>
1133 - );
1134 - })}
1135 - </AutocompleteList>
1136 - ) : (
1137 - <AutocompleteEmpty className="break-all">
1138 - No hosts match "{savedBackendSshHost.trim()}".
1139 - </AutocompleteEmpty>
1140 - )}
1141 - </AutocompletePopup>
1142 - ) : null}
1143 - </Autocomplete>
1144 - </div>
1145 - <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_7rem]">
1146 - <label className="block">
1147 - <span className="mb-1.5 block text-xs font-medium text-foreground">Username</span>
1148 - <Input
1149 - value={savedBackendSshUsername}
1150 - onChange={(event) => setSavedBackendSshUsername(event.target.value)}
1151 - onKeyDown={handleSavedBackendSshFieldKeyDown}
1152 - placeholder="root"
1153 - disabled={isAddingSavedBackend}
1154 - spellCheck={false}
1155 - />
1156 - </label>
1157 - <label className="block">
1158 - <span className="mb-1.5 block text-xs font-medium text-foreground">Port</span>
1159 - <Input
1160 - value={savedBackendSshPort}
1161 - onChange={(event) => setSavedBackendSshPort(event.target.value)}
1162 - onKeyDown={handleSavedBackendSshFieldKeyDown}
1163 - placeholder="22"
1164 - inputMode="numeric"
1165 - disabled={isAddingSavedBackend}
1166 - spellCheck={false}
1167 - />
1168 - </label>
1169 - </div>
1170 - {savedBackendError || discoveredSshHostsError ? (
1171 - <Alert variant="error">
1172 - <AlertDescription>{savedBackendError ?? discoveredSshHostsError}</AlertDescription>
1173 - </Alert>
1174 - ) : null}
1175 - <Button
1176 - variant="outline"
1177 - className="w-full"
1178 - disabled={isAddingSavedBackend}
1179 - onClick={() => void handleAddSavedBackend()}
1180 - >
1181 - <PlusIcon className="size-3.5" />
1182 - {isAddingSavedBackend ? "Adding…" : routeTarget ? "Add route" : "Add environment"}
1183 - </Button>
1184 - </div>
1185 - </div>
1186 - );
638 const renderNetworkAccessToggle = () => (
639 <Switch
640 checked={desktopServerExposureState?.mode === "network-accessible"}
@@ -2040,69 +1491,14 @@ export function ConnectionsSettings() {
1491 {savedServerUpdateTargets.length > 0 ? (
1492 <ServerUpdatesAction targets={savedServerUpdateTargets} variant="ghost-muted" />
1493 ) : null}
2043 - <Dialog
1494 + <AddEnvironmentDialog
1495 open={addBackendDialogOpen}
2045 - onOpenChange={(open) => {
2046 - setAddBackendDialogOpen(open);
2047 - if (open) {
2048 - setRouteTarget(null);
2049 - } else {
2050 - setSavedBackendError(null);
2051 - }
2052 - }}
2053 - >
2054 - <Tooltip>
2055 - <TooltipTrigger
2056 - render={
2057 - <DialogTrigger
2058 - render={
2059 - <Button size="xs" variant="ghost-muted" aria-label="Add environment">
2060 - <PlusIcon className="size-3" />
2061 - <span>Add environment</span>
2062 - </Button>
2063 - }
2064 - />
2065 - }
2066 - />
2067 - <TooltipPopup side="top">Add environment</TooltipPopup>
2068 - </Tooltip>
2069 - <DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
2070 - <DialogHeader>
2071 - <DialogTitle>
2072 - {routeTarget ? `Add a route to ${routeTarget.label}` : "Add Environment"}
2073 - </DialogTitle>
2074 - <DialogDescription>
2075 - {routeTarget
2076 - ? "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine."
2077 - : "Pair another environment to this client."}
2078 - </DialogDescription>
2079 - </DialogHeader>
2080 - <DialogPanel>
2081 - <div className="space-y-4">
2082 - <div className="grid gap-3 sm:grid-cols-2">
2083 - {renderConnectionModeCard({
2084 - mode: "remote",
2085 - title: "Remote link",
2086 - description: "Enter a backend host and pairing code.",
2087 - icon: <ChevronsLeftRightEllipsisIcon aria-hidden className="size-4" />,
2088 - })}
2089 - {desktopBridge
2090 - ? renderConnectionModeCard({
2091 - mode: "ssh",
2092 - title: "SSH",
2093 - description:
2094 - "Use local SSH config, agent, and tunnels for the backend.",
2095 - icon: <TerminalIcon aria-hidden className="size-4" />,
2096 - })
2097 - : null}
2098 - </div>
2099 - <AnimatedHeight>
2100 - {savedBackendMode === "ssh" ? renderSshFields() : renderRemoteModeBody()}
2101 - </AnimatedHeight>
2102 - </div>
2103 - </DialogPanel>
2104 - </DialogPopup>
2105 - </Dialog>
1496 + routeTarget={routeTarget}
1497 + error={savedBackendError}
1498 + savedEnvironments={savedEnvironments}
1499 + onOpenChange={handleAddBackendDialogOpenChange}
1500 + onErrorChange={setSavedBackendError}
1501 + />
1502 </div>
1503 }
1504 >