Open History to see the last commit
1import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2import {
3 type EnvironmentConnectionPresentation,
4 RelayConnectionRegistration,
5 RelayConnectionTarget,
6 orchestrationProtocolCompatibilityError,
7} from "@t3tools/client-runtime/connection";
8import { relayOfflineReasonMessage } from "@t3tools/client-runtime/relay";
9import {
10 isAtomCommandInterrupted,
11 settlePromise,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import {
15 type EnvironmentId,
16 resolveEnvironmentMachineKind,
17 type ServerConfig,
18} from "@t3tools/contracts";
19import type {
20 RelayClientEnvironmentRecord,
21 RelayEnvironmentStatusResponse,
22} from "@t3tools/contracts/relay";
23import * as Option from "effect/Option";
24import { type ReactNode, useEffect, useEffectEvent, useState } from "react";
25
26import { environmentCatalog } from "~/connection/catalog";
27import { cn } from "~/lib/utils";
28import { relayEnvironmentDiscovery } from "~/state/relay";
29import { useRelayEnvironmentDiscovery } from "~/state/environments";
30import { useAtomCommand } from "~/state/use-atom-command";
31import { ConnectionStatusDot } from "../ConnectionStatusDot";
32import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
33import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";
34import { Checkbox } from "../ui/checkbox";
35import { Button } from "../ui/button";
36import { Skeleton } from "../ui/skeleton";
37import { toastManager } from "../ui/toast";
38import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
39import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
40
41const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000;
42
43function discoveredCompatibilityError(
44 status: Option.Option<RelayEnvironmentStatusResponse> | undefined,
45) {
46 const descriptor = status === undefined ? undefined : Option.getOrNull(status)?.descriptor;
47 return descriptor === undefined ? null : orchestrationProtocolCompatibilityError(descriptor);
48}
49
50export interface SavedCloudEnvironmentConnection {
51 readonly environmentId: EnvironmentId;
52 readonly connection: EnvironmentConnectionPresentation;
53 readonly relayManaged: boolean;
54 readonly serverConfig?: Pick<ServerConfig, "environment"> | null;
55}
56
57function RemoteEnvironmentRowsSkeleton() {
58 return (
59 <div className={ITEM_ROW_CLASSNAME}>
60 <div className={ITEM_ROW_INNER_CLASSNAME}>
61 <div className="min-w-0 flex-1 space-y-2">
62 <Skeleton shape="pill" className="h-4 w-32" />
63 <Skeleton shape="pill" className="h-3 w-20" />
64 </div>
65 <Skeleton className="h-7 w-16" />
66 </div>
67 </div>
68 );
69}
70
71export function CloudEnvironmentConnectRows({
72 primaryEnvironmentId,
73 savedEnvironments,
74 showSavedEnvironments = false,
75 refreshWhileEmpty = false,
76 empty = null,
77 selection,
78 onDiscoveryReady,
79}: {
80 readonly primaryEnvironmentId: EnvironmentId | null;
81 readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;
82 readonly showSavedEnvironments?: boolean;
83 readonly refreshWhileEmpty?: boolean;
84 readonly empty?: ReactNode;
85 readonly onDiscoveryReady?: () => void;
86 readonly selection?: {
87 readonly autoSelectedComputers?: Set<EnvironmentId>;
88 readonly selectedIds: ReadonlySet<EnvironmentId>;
89 readonly onChange: (environmentId: EnvironmentId, selected: boolean) => void;
90 };
91}) {
92 const environmentsState = useRelayEnvironmentDiscovery();
93 const registerEnvironment = useAtomCommand(environmentCatalog.register, {
94 reportFailure: false,
95 });
96 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
97 reportFailure: false,
98 });
99 const refreshDiscoveryWhenIdle = useEffectEvent(async () => {
100 if (environmentsState.refreshing || environmentsState.offline) return;
101 await refreshRelayEnvironments();
102 });
103 const connectRelayEnvironment = (environment: RelayClientEnvironmentRecord) =>
104 registerEnvironment(
105 new RelayConnectionRegistration({
106 target: new RelayConnectionTarget({
107 environmentId: environment.environmentId,
108 label: environment.label,
109 }),
110 }),
111 );
112 const [connectingEnvironmentIds, setConnectingEnvironmentIds] = useState<
113 ReadonlySet<EnvironmentId>
114 >(new Set());
115 const savedById = new Map(
116 savedEnvironments
117 .filter((environment) => environment.relayManaged)
118 .map((environment) => [environment.environmentId, environment]),
119 );
120 const savedWithoutRelay = new Set(
121 savedEnvironments
122 .filter((environment) => !environment.relayManaged)
123 .map((environment) => environment.environmentId),
124 );
125
126 useEffect(() => {
127 let active = true;
128 if (onDiscoveryReady || !refreshWhileEmpty || document.visibilityState === "visible") {
129 void refreshRelayEnvironments().then(() => {
130 if (active) onDiscoveryReady?.();
131 });
132 }
133 return () => {
134 active = false;
135 };
136 }, [refreshRelayEnvironments, refreshWhileEmpty, onDiscoveryReady]);
137
138 const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
139 if (
140 discoveredCompatibilityError(
141 environmentsState.environments.get(environment.environmentId)?.status,
142 ) !== null
143 )
144 return false;
145 setConnectingEnvironmentIds((current) => new Set([...current, environment.environmentId]));
146 const result = await connectRelayEnvironment(environment);
147 setConnectingEnvironmentIds((current) => {
148 const next = new Set(current);
149 next.delete(environment.environmentId);
150 return next;
151 });
152 if (result._tag === "Success") {
153 toastManager.add({
154 type: "success",
155 title: savedWithoutRelay.has(environment.environmentId)
156 ? "T3 Connect route added"
157 : "Environment added",
158 description: savedWithoutRelay.has(environment.environmentId)
159 ? `${environment.label} falls back to T3 Connect when its other routes are unreachable.`
160 : `Connecting to ${environment.label} through T3 Connect.`,
161 });
162 return true;
163 }
164 if (isAtomCommandInterrupted(result)) {
165 return false;
166 }
167 const cause = squashAtomCommandFailure(result);
168 const message =
169 cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
170 const traceId = findErrorTraceId(cause);
171 console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
172 toastManager.add({
173 type: "error",
174 title: "Could not connect environment",
175 description: message,
176 data: traceId
177 ? {
178 secondaryActionProps: {
179 children: "Copy trace ID",
180 onClick: () => void navigator.clipboard?.writeText(traceId),
181 },
182 }
183 : undefined,
184 });
185 return false;
186 };
187
188 // During onboarding selection a machine saved over another route already
189 // has its own row elsewhere, and selecting it must not add a T3 Connect
190 // route as a side effect, so it is left out here.
191 const isVisibleEnvironment = (environmentId: EnvironmentId) =>
192 environmentId !== primaryEnvironmentId &&
193 (showSavedEnvironments || !savedById.has(environmentId)) &&
194 !(selection && savedWithoutRelay.has(environmentId));
195 const visibleEnvironments = [...environmentsState.environments.values()].filter(
196 ({ environment }) => isVisibleEnvironment(environment.environmentId),
197 );
198 const selectNewComputers = useEffectEvent(
199 (environments: typeof environmentsState.environments) => {
200 const seen = selection?.autoSelectedComputers;
201 if (!selection || !seen) return;
202 for (const { environment, status, availability } of environments.values()) {
203 if (!isVisibleEnvironment(environment.environmentId)) continue;
204 const id = environment.environmentId;
205 if (availability === "checking") continue;
206 if (
207 discoveredCompatibilityError(status) !== null ||
208 savedById.get(id)?.connection.phase === "unsupported"
209 ) {
210 seen.add(id);
211 if (selection.selectedIds.has(id)) selection.onChange(id, false);
212 continue;
213 }
214 if (seen.has(id)) continue;
215 seen.add(id);
216 selection.onChange(id, true);
217 if (!savedById.has(id)) {
218 void connectEnvironment(environment).then((connected) => {
219 if (!connected) selection.onChange(id, false);
220 });
221 }
222 }
223 },
224 );
225 useEffect(() => {
226 // oxlint-disable-next-line react/set-state-in-effect -- Discovery results arrive from an external store and auto-selection starts relay connections, which mark themselves connecting.
227 selectNewComputers(environmentsState.environments);
228 }, [environmentsState.environments]);
229
230 // Discovery clears its list on refresh, so poll only until a machine appears.
231 const shouldRefreshWhileEmpty =
232 refreshWhileEmpty && visibleEnvironments.length === 0 && !environmentsState.offline;
233
234 useEffect(() => {
235 if (!shouldRefreshWhileEmpty) return;
236 let timer: ReturnType<typeof setTimeout> | undefined;
237 let disposed = false;
238 let pending = false;
239 const visible = () => document.visibilityState === "visible";
240 const schedule = () => {
241 clearTimeout(timer);
242 if (!disposed && visible()) {
243 timer = setTimeout(() => void refresh(), EMPTY_DISCOVERY_REFRESH_INTERVAL_MS);
244 }
245 };
246 const refresh = async () => {
247 if (disposed || pending || !visible()) return;
248 clearTimeout(timer);
249 pending = true;
250 await settlePromise(() => refreshDiscoveryWhenIdle());
251 pending = false;
252 schedule();
253 };
254 const onFocus = () => void refresh();
255 const onVisibilityChange = () => {
256 clearTimeout(timer);
257 if (visible()) void refresh();
258 };
259
260 schedule();
261 window.addEventListener("focus", onFocus);
262 document.addEventListener("visibilitychange", onVisibilityChange);
263 return () => {
264 disposed = true;
265 clearTimeout(timer);
266 window.removeEventListener("focus", onFocus);
267 document.removeEventListener("visibilitychange", onVisibilityChange);
268 };
269 }, [shouldRefreshWhileEmpty]);
270
271 const standalone = showSavedEnvironments || savedEnvironments.length === 0;
272
273 if (
274 !refreshWhileEmpty &&
275 standalone &&
276 visibleEnvironments.length === 0 &&
277 environmentsState.refreshing &&
278 environmentsState.environments.size === 0
279 ) {
280 return <RemoteEnvironmentRowsSkeleton />;
281 }
282
283 if (standalone && visibleEnvironments.length === 0) {
284 const discoveryProblem = environmentsState.offline
285 ? "You appear to be offline."
286 : (Option.getOrNull(environmentsState.error)?.message ?? null);
287 if (discoveryProblem !== null && !environmentsState.refreshing) {
288 return (
289 <div className={ITEM_ROW_CLASSNAME}>
290 <p className="text-sm font-medium text-destructive">
291 Could not load T3 Connect environments
292 </p>
293 <p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>
294 <Button
295 size="sm"
296 variant="outline"
297 className="mt-3"
298 onClick={() => void refreshRelayEnvironments()}
299 >
300 Try again
301 </Button>
302 </div>
303 );
304 }
305 return empty;
306 }
307
308 return visibleEnvironments.map(({ environment, availability, error, status }) => {
309 const savedEnvironment = savedById.get(environment.environmentId);
310 const compatibilityError = discoveredCompatibilityError(status);
311 const unsupported =
312 compatibilityError !== null || savedEnvironment?.connection.phase === "unsupported";
313 const unsupportedDetail =
314 compatibilityError?.message ?? savedEnvironment?.connection.error ?? null;
315 const savedConnection = unsupported
316 ? presentSavedCloudEnvironmentConnection({
317 phase: "unsupported",
318 error: unsupportedDetail,
319 traceId: null,
320 })
321 : savedEnvironment
322 ? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
323 : null;
324 const relayStatus = status === undefined ? null : Option.getOrNull(status);
325 const descriptor = relayStatus?.descriptor;
326 const offlineReason =
327 availability === "offline" && relayStatus !== null
328 ? relayOfflineReasonMessage(relayStatus)
329 : null;
330 const machineKind = resolveEnvironmentMachineKind(
331 savedEnvironment?.serverConfig ??
332 (descriptor === undefined ? null : { environment: descriptor }),
333 );
334 const dotClassName = savedConnection
335 ? savedConnection.tone === "connected"
336 ? "bg-success"
337 : savedConnection.tone === "connecting"
338 ? "bg-warning"
339 : savedConnection.tone === "error"
340 ? "bg-destructive"
341 : "bg-muted-foreground/35"
342 : availability === "online"
343 ? "bg-success"
344 : availability === "error"
345 ? "bg-destructive"
346 : availability === "checking"
347 ? "bg-warning"
348 : "bg-muted-foreground/35";
349 const notAdded = savedWithoutRelay.has(environment.environmentId)
350 ? "Saved without T3 Connect"
351 : "Not added";
352 const statusText =
353 unsupported && !savedEnvironment
354 ? `T3 Connect · ${notAdded} · Client not supported`
355 : offlineReason !== null
356 ? offlineReason
357 : savedConnection
358 ? savedConnection.statusText
359 : availability === "online"
360 ? `T3 Connect · ${notAdded} · Relay online`
361 : availability === "offline"
362 ? `T3 Connect · ${notAdded} · Relay offline`
363 : availability === "checking"
364 ? `T3 Connect · ${notAdded} · Checking relay status…`
365 : (Option.getOrNull(error)?.message ??
366 `T3 Connect · ${notAdded} · Relay status unavailable`);
367 if (selection) {
368 return (
369 <label
370 key={environment.environmentId}
371 className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 has-disabled:cursor-default"
372 >
373 <Checkbox
374 checked={!unsupported && selection.selectedIds.has(environment.environmentId)}
375 disabled={unsupported || connectingEnvironmentIds.has(environment.environmentId)}
376 onCheckedChange={async (checked) => {
377 if (unsupported) return;
378 selection.onChange(environment.environmentId, checked);
379 if (checked && !savedEnvironment) {
380 const connected = await connectEnvironment(environment);
381 if (!connected) selection.onChange(environment.environmentId, false);
382 }
383 }}
384 />
385 <EnvironmentMachineIcon
386 aria-hidden
387 kind={machineKind}
388 className="size-4 shrink-0 text-muted-foreground"
389 />
390 <span className="min-w-0 flex-1 truncate text-sm font-medium">{environment.label}</span>
391 <Tooltip>
392 <TooltipTrigger
393 render={<span tabIndex={0} />}
394 className={cn(
395 "max-w-[45%] shrink-0 truncate text-xs",
396 savedConnection?.tone === "error" ? "text-destructive" : "text-muted-foreground",
397 )}
398 >
399 {connectingEnvironmentIds.has(environment.environmentId)
400 ? "Connecting…"
401 : (savedConnection?.buttonLabel ??
402 (availability === "online"
403 ? "Available"
404 : availability === "offline"
405 ? "Offline"
406 : availability === "error"
407 ? "Unavailable"
408 : "Checking…"))}
409 </TooltipTrigger>
410 <TooltipPopup>{unsupportedDetail ?? statusText}</TooltipPopup>
411 </Tooltip>
412 </label>
413 );
414 }
415 return (
416 <div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
417 <div className={ITEM_ROW_INNER_CLASSNAME}>
418 <div className="min-w-0">
419 <div className="flex items-center gap-2">
420 <ConnectionStatusDot
421 dotClassName={dotClassName}
422 pingClassName={
423 savedConnection?.tone === "connecting" ||
424 (savedConnection === null && availability === "checking")
425 ? "bg-warning/60 duration-2000"
426 : null
427 }
428 tooltipText={
429 unsupportedDetail !== null
430 ? unsupportedDetail
431 : offlineReason !== null
432 ? offlineReason
433 : savedConnection
434 ? savedConnection.statusText
435 : availability === "online"
436 ? "Relay online"
437 : availability === "offline"
438 ? "Relay offline"
439 : availability === "checking"
440 ? "Checking relay status"
441 : (Option.getOrNull(error)?.message ?? "Relay status unavailable")
442 }
443 />
444 <EnvironmentMachineIcon
445 aria-hidden
446 kind={machineKind}
447 className="size-4 shrink-0 text-muted-foreground"
448 />
449 <p className="truncate text-sm font-medium">{environment.label}</p>
450 </div>
451 <p
452 className={cn(
453 "mt-1 truncate text-xs",
454 savedConnection?.tone === "error" ||
455 (savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
456 (savedConnection === null && availability === "error")
457 ? "text-destructive"
458 : "text-muted-foreground",
459 )}
460 >
461 {statusText}
462 </p>
463 </div>
464 {unsupported && !savedEnvironment ? (
465 <Tooltip>
466 <TooltipTrigger render={<span className="inline-flex" tabIndex={0} />}>
467 <Button size="sm" disabled>
468 Add
469 </Button>
470 </TooltipTrigger>
471 <TooltipPopup>{unsupportedDetail ?? "Client not supported"}</TooltipPopup>
472 </Tooltip>
473 ) : savedConnection ? (
474 <Button size="sm" variant="outline" disabled>
475 {savedConnection.buttonLabel}
476 </Button>
477 ) : (
478 <Button
479 size="sm"
480 disabled={connectingEnvironmentIds.size > 0}
481 onClick={() => void connectEnvironment(environment)}
482 >
483 {connectingEnvironmentIds.has(environment.environmentId)
484 ? "Adding…"
485 : savedWithoutRelay.has(environment.environmentId)
486 ? "Add route"
487 : "Add"}
488 </Button>
489 )}
490 </div>
491 </div>
492 );
493 });
494}