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 // Omit machines saved over other routes; onboarding selection must not add a T3 Connect route.
189 const isVisibleEnvironment = (environmentId: EnvironmentId) =>
190 environmentId !== primaryEnvironmentId &&
191 (showSavedEnvironments || !savedById.has(environmentId)) &&
192 !(selection && savedWithoutRelay.has(environmentId));
193 const visibleEnvironments = [...environmentsState.environments.values()].filter(
194 ({ environment }) => isVisibleEnvironment(environment.environmentId),
195 );
196 const selectNewComputers = useEffectEvent(
197 (environments: typeof environmentsState.environments) => {
198 const seen = selection?.autoSelectedComputers;
199 if (!selection || !seen) return;
200 for (const { environment, status, availability } of environments.values()) {
201 if (!isVisibleEnvironment(environment.environmentId)) continue;
202 const id = environment.environmentId;
203 if (availability === "checking") continue;
204 if (
205 discoveredCompatibilityError(status) !== null ||
206 savedById.get(id)?.connection.phase === "unsupported"
207 ) {
208 seen.add(id);
209 if (selection.selectedIds.has(id)) selection.onChange(id, false);
210 continue;
211 }
212 if (seen.has(id)) continue;
213 seen.add(id);
214 selection.onChange(id, true);
215 if (!savedById.has(id)) {
216 void connectEnvironment(environment).then((connected) => {
217 if (!connected) selection.onChange(id, false);
218 });
219 }
220 }
221 },
222 );
223 useEffect(() => {
224 // 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.
225 selectNewComputers(environmentsState.environments);
226 }, [environmentsState.environments]);
227
228 // Discovery clears its list on refresh, so poll only until a machine appears.
229 const shouldRefreshWhileEmpty =
230 refreshWhileEmpty && visibleEnvironments.length === 0 && !environmentsState.offline;
231
232 useEffect(() => {
233 if (!shouldRefreshWhileEmpty) return;
234 let timer: ReturnType<typeof setTimeout> | undefined;
235 let disposed = false;
236 let pending = false;
237 const visible = () => document.visibilityState === "visible";
238 const schedule = () => {
239 clearTimeout(timer);
240 if (!disposed && visible()) {
241 timer = setTimeout(() => void refresh(), EMPTY_DISCOVERY_REFRESH_INTERVAL_MS);
242 }
243 };
244 const refresh = async () => {
245 if (disposed || pending || !visible()) return;
246 clearTimeout(timer);
247 pending = true;
248 await settlePromise(() => refreshDiscoveryWhenIdle());
249 pending = false;
250 schedule();
251 };
252 const onFocus = () => void refresh();
253 const onVisibilityChange = () => {
254 clearTimeout(timer);
255 if (visible()) void refresh();
256 };
257
258 schedule();
259 window.addEventListener("focus", onFocus);
260 document.addEventListener("visibilitychange", onVisibilityChange);
261 return () => {
262 disposed = true;
263 clearTimeout(timer);
264 window.removeEventListener("focus", onFocus);
265 document.removeEventListener("visibilitychange", onVisibilityChange);
266 };
267 }, [shouldRefreshWhileEmpty]);
268
269 const standalone = showSavedEnvironments || savedEnvironments.length === 0;
270
271 if (
272 !refreshWhileEmpty &&
273 standalone &&
274 visibleEnvironments.length === 0 &&
275 environmentsState.refreshing &&
276 environmentsState.environments.size === 0
277 ) {
278 return <RemoteEnvironmentRowsSkeleton />;
279 }
280
281 if (standalone && visibleEnvironments.length === 0) {
282 const discoveryProblem = environmentsState.offline
283 ? "You appear to be offline."
284 : (Option.getOrNull(environmentsState.error)?.message ?? null);
285 if (discoveryProblem !== null && !environmentsState.refreshing) {
286 return (
287 <div className={ITEM_ROW_CLASSNAME}>
288 <p className="text-sm font-medium text-destructive">
289 Could not load T3 Connect environments
290 </p>
291 <p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>
292 <Button
293 size="sm"
294 variant="outline"
295 className="mt-3"
296 onClick={() => void refreshRelayEnvironments()}
297 >
298 Try again
299 </Button>
300 </div>
301 );
302 }
303 return empty;
304 }
305
306 return visibleEnvironments.map(({ environment, availability, error, status }) => {
307 const savedEnvironment = savedById.get(environment.environmentId);
308 const compatibilityError = discoveredCompatibilityError(status);
309 const unsupported =
310 compatibilityError !== null || savedEnvironment?.connection.phase === "unsupported";
311 const unsupportedDetail =
312 compatibilityError?.message ?? savedEnvironment?.connection.error ?? null;
313 const savedConnection = unsupported
314 ? presentSavedCloudEnvironmentConnection({
315 phase: "unsupported",
316 error: unsupportedDetail,
317 traceId: null,
318 })
319 : savedEnvironment
320 ? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
321 : null;
322 const relayStatus = status === undefined ? null : Option.getOrNull(status);
323 const descriptor = relayStatus?.descriptor;
324 const offlineReason =
325 availability === "offline" && relayStatus !== null
326 ? relayOfflineReasonMessage(relayStatus)
327 : null;
328 const machineKind = resolveEnvironmentMachineKind(
329 savedEnvironment?.serverConfig ??
330 (descriptor === undefined ? null : { environment: descriptor }),
331 );
332 const dotClassName = savedConnection
333 ? savedConnection.tone === "connected"
334 ? "bg-success"
335 : savedConnection.tone === "connecting"
336 ? "bg-warning"
337 : savedConnection.tone === "error"
338 ? "bg-destructive"
339 : "bg-muted-foreground/35"
340 : availability === "online"
341 ? "bg-success"
342 : availability === "error"
343 ? "bg-destructive"
344 : availability === "checking"
345 ? "bg-warning"
346 : "bg-muted-foreground/35";
347 const notAdded = savedWithoutRelay.has(environment.environmentId)
348 ? "Saved without T3 Connect"
349 : "Not added";
350 const statusText =
351 unsupported && !savedEnvironment
352 ? `T3 Connect · ${notAdded} · Client not supported`
353 : offlineReason !== null
354 ? offlineReason
355 : savedConnection
356 ? savedConnection.statusText
357 : availability === "online"
358 ? `T3 Connect · ${notAdded} · Relay online`
359 : availability === "offline"
360 ? `T3 Connect · ${notAdded} · Relay offline`
361 : availability === "checking"
362 ? `T3 Connect · ${notAdded} · Checking relay status…`
363 : (Option.getOrNull(error)?.message ??
364 `T3 Connect · ${notAdded} · Relay status unavailable`);
365 if (selection) {
366 return (
367 <label
368 key={environment.environmentId}
369 className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 has-disabled:cursor-default"
370 >
371 <Checkbox
372 checked={!unsupported && selection.selectedIds.has(environment.environmentId)}
373 disabled={unsupported || connectingEnvironmentIds.has(environment.environmentId)}
374 onCheckedChange={async (checked) => {
375 if (unsupported) return;
376 selection.onChange(environment.environmentId, checked);
377 if (checked && !savedEnvironment) {
378 const connected = await connectEnvironment(environment);
379 if (!connected) selection.onChange(environment.environmentId, false);
380 }
381 }}
382 />
383 <EnvironmentMachineIcon
384 aria-hidden
385 kind={machineKind}
386 className="size-4 shrink-0 text-muted-foreground"
387 />
388 <span className="min-w-0 flex-1">
389 <span className="block truncate text-sm font-medium">{environment.label}</span>
390 {unsupportedDetail !== null ? (
391 <span className="mt-0.5 block text-xs text-muted-foreground">
392 {unsupportedDetail}
393 </span>
394 ) : null}
395 </span>
396 <Tooltip>
397 <TooltipTrigger
398 render={<span tabIndex={0} />}
399 className={cn(
400 "max-w-[45%] shrink-0 truncate text-xs",
401 savedConnection?.tone === "error" ? "text-destructive" : "text-muted-foreground",
402 )}
403 >
404 {connectingEnvironmentIds.has(environment.environmentId)
405 ? "Connecting…"
406 : (savedConnection?.buttonLabel ??
407 (availability === "online"
408 ? "Available"
409 : availability === "offline"
410 ? "Offline"
411 : availability === "error"
412 ? "Unavailable"
413 : "Checking…"))}
414 </TooltipTrigger>
415 <TooltipPopup>{unsupportedDetail ?? statusText}</TooltipPopup>
416 </Tooltip>
417 </label>
418 );
419 }
420 return (
421 <div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
422 <div className={ITEM_ROW_INNER_CLASSNAME}>
423 <div className="min-w-0">
424 <div className="flex items-center gap-2">
425 <ConnectionStatusDot
426 dotClassName={dotClassName}
427 pingClassName={
428 savedConnection?.tone === "connecting" ||
429 (savedConnection === null && availability === "checking")
430 ? "bg-warning/60 duration-2000"
431 : null
432 }
433 tooltipText={
434 unsupportedDetail !== null
435 ? unsupportedDetail
436 : offlineReason !== null
437 ? offlineReason
438 : savedConnection
439 ? savedConnection.statusText
440 : availability === "online"
441 ? "Relay online"
442 : availability === "offline"
443 ? "Relay offline"
444 : availability === "checking"
445 ? "Checking relay status"
446 : (Option.getOrNull(error)?.message ?? "Relay status unavailable")
447 }
448 />
449 <EnvironmentMachineIcon
450 aria-hidden
451 kind={machineKind}
452 className="size-4 shrink-0 text-muted-foreground"
453 />
454 <p className="truncate text-sm font-medium">{environment.label}</p>
455 </div>
456 <p
457 className={cn(
458 "mt-1 truncate text-xs",
459 savedConnection?.tone === "error" ||
460 (savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
461 (savedConnection === null && availability === "error")
462 ? "text-destructive"
463 : "text-muted-foreground",
464 )}
465 >
466 {statusText}
467 </p>
468 </div>
469 {unsupported && !savedEnvironment ? (
470 <Tooltip>
471 <TooltipTrigger render={<span className="inline-flex" tabIndex={0} />}>
472 <Button size="sm" disabled>
473 Add
474 </Button>
475 </TooltipTrigger>
476 <TooltipPopup>{unsupportedDetail ?? "Client not supported"}</TooltipPopup>
477 </Tooltip>
478 ) : savedConnection ? (
479 <Button size="sm" variant="outline" disabled>
480 {savedConnection.buttonLabel}
481 </Button>
482 ) : (
483 <Button
484 size="sm"
485 disabled={connectingEnvironmentIds.size > 0}
486 onClick={() => void connectEnvironment(environment)}
487 >
488 {connectingEnvironmentIds.has(environment.environmentId)
489 ? "Adding…"
490 : savedWithoutRelay.has(environment.environmentId)
491 ? "Add route"
492 : "Add"}
493 </Button>
494 )}
495 </div>
496 </div>
497 );
498 });
499}