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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches relay discovery when its inputs change, unless hidden polling covers it, and reports readiness
127 useEffect(() => {
128 let active = true;
129 if (onDiscoveryReady || !refreshWhileEmpty || document.visibilityState === "visible") {
130 void refreshRelayEnvironments().then(() => {
131 if (active) onDiscoveryReady?.();
132 });
133 }
134 return () => {
135 active = false;
136 };
137 }, [refreshRelayEnvironments, refreshWhileEmpty, onDiscoveryReady]);
138
139 const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
140 if (
141 discoveredCompatibilityError(
142 environmentsState.environments.get(environment.environmentId)?.status,
143 ) !== null
144 )
145 return false;
146 setConnectingEnvironmentIds((current) => new Set([...current, environment.environmentId]));
147 const result = await connectRelayEnvironment(environment);
148 setConnectingEnvironmentIds((current) => {
149 const next = new Set(current);
150 next.delete(environment.environmentId);
151 return next;
152 });
153 if (result._tag === "Success") {
154 toastManager.add({
155 type: "success",
156 title: savedWithoutRelay.has(environment.environmentId)
157 ? "T3 Connect route added"
158 : "Environment added",
159 description: savedWithoutRelay.has(environment.environmentId)
160 ? `${environment.label} falls back to T3 Connect when its other routes are unreachable.`
161 : `Connecting to ${environment.label} through T3 Connect.`,
162 });
163 return true;
164 }
165 if (isAtomCommandInterrupted(result)) {
166 return false;
167 }
168 const cause = squashAtomCommandFailure(result);
169 const message =
170 cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
171 const traceId = findErrorTraceId(cause);
172 console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
173 toastManager.add({
174 type: "error",
175 title: "Could not connect environment",
176 description: message,
177 data: traceId
178 ? {
179 secondaryActionProps: {
180 children: "Copy trace ID",
181 onClick: () => void navigator.clipboard?.writeText(traceId),
182 },
183 }
184 : undefined,
185 });
186 return false;
187 };
188
189 // Omit machines saved over other routes; onboarding selection must not add a T3 Connect route.
190 const isVisibleEnvironment = (environmentId: EnvironmentId) =>
191 environmentId !== primaryEnvironmentId &&
192 (showSavedEnvironments || !savedById.has(environmentId)) &&
193 !(selection && savedWithoutRelay.has(environmentId));
194 const visibleEnvironments = [...environmentsState.environments.values()].filter(
195 ({ environment }) => isVisibleEnvironment(environment.environmentId),
196 );
197 const selectNewComputers = useEffectEvent(
198 (environments: typeof environmentsState.environments) => {
199 const seen = selection?.autoSelectedComputers;
200 if (!selection || !seen) return;
201 for (const { environment, status, availability } of environments.values()) {
202 if (!isVisibleEnvironment(environment.environmentId)) continue;
203 const id = environment.environmentId;
204 if (availability === "checking") continue;
205 if (
206 discoveredCompatibilityError(status) !== null ||
207 savedById.get(id)?.connection.phase === "unsupported"
208 ) {
209 seen.add(id);
210 if (selection.selectedIds.has(id)) selection.onChange(id, false);
211 continue;
212 }
213 if (seen.has(id)) continue;
214 seen.add(id);
215 selection.onChange(id, true);
216 if (!savedById.has(id)) {
217 void connectEnvironment(environment).then((connected) => {
218 if (!connected) selection.onChange(id, false);
219 });
220 }
221 }
222 },
223 );
224 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- auto-selects newly discovered machines from the discovery store and starts their relay connections
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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls relay discovery on a timer, focus and visibility change while no machine is found
235 useEffect(() => {
236 if (!shouldRefreshWhileEmpty) return;
237 let timer: ReturnType<typeof setTimeout> | undefined;
238 let disposed = false;
239 let pending = false;
240 const visible = () => document.visibilityState === "visible";
241 const schedule = () => {
242 clearTimeout(timer);
243 if (!disposed && visible()) {
244 timer = setTimeout(() => void refresh(), EMPTY_DISCOVERY_REFRESH_INTERVAL_MS);
245 }
246 };
247 const refresh = async () => {
248 if (disposed || pending || !visible()) return;
249 clearTimeout(timer);
250 pending = true;
251 await settlePromise(() => refreshDiscoveryWhenIdle());
252 pending = false;
253 schedule();
254 };
255 const onFocus = () => void refresh();
256 const onVisibilityChange = () => {
257 clearTimeout(timer);
258 if (visible()) void refresh();
259 };
260
261 schedule();
262 window.addEventListener("focus", onFocus);
263 document.addEventListener("visibilitychange", onVisibilityChange);
264 return () => {
265 disposed = true;
266 clearTimeout(timer);
267 window.removeEventListener("focus", onFocus);
268 document.removeEventListener("visibilitychange", onVisibilityChange);
269 };
270 }, [shouldRefreshWhileEmpty]);
271
272 const standalone = showSavedEnvironments || savedEnvironments.length === 0;
273
274 if (
275 !refreshWhileEmpty &&
276 standalone &&
277 visibleEnvironments.length === 0 &&
278 environmentsState.refreshing &&
279 environmentsState.environments.size === 0
280 ) {
281 return <RemoteEnvironmentRowsSkeleton />;
282 }
283
284 if (standalone && visibleEnvironments.length === 0) {
285 const discoveryProblem = environmentsState.offline
286 ? "You appear to be offline."
287 : (Option.getOrNull(environmentsState.error)?.message ?? null);
288 if (discoveryProblem !== null && !environmentsState.refreshing) {
289 return (
290 <div className={ITEM_ROW_CLASSNAME}>
291 <p className="text-sm font-medium text-destructive">
292 Could not load T3 Connect environments
293 </p>
294 <p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>
295 <Button
296 size="sm"
297 variant="outline"
298 className="mt-3"
299 onClick={() => void refreshRelayEnvironments()}
300 >
301 Try again
302 </Button>
303 </div>
304 );
305 }
306 return empty;
307 }
308
309 return visibleEnvironments.map(({ environment, availability, error, status }) => {
310 const savedEnvironment = savedById.get(environment.environmentId);
311 const compatibilityError = discoveredCompatibilityError(status);
312 const unsupported =
313 compatibilityError !== null || savedEnvironment?.connection.phase === "unsupported";
314 const unsupportedDetail =
315 compatibilityError?.message ?? savedEnvironment?.connection.error ?? null;
316 const savedConnection = unsupported
317 ? presentSavedCloudEnvironmentConnection({
318 phase: "unsupported",
319 error: unsupportedDetail,
320 traceId: null,
321 })
322 : savedEnvironment
323 ? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
324 : null;
325 const relayStatus = status === undefined ? null : Option.getOrNull(status);
326 const descriptor = relayStatus?.descriptor;
327 const offlineReason =
328 availability === "offline" && relayStatus !== null
329 ? relayOfflineReasonMessage(relayStatus)
330 : null;
331 const machineKind = resolveEnvironmentMachineKind(
332 savedEnvironment?.serverConfig ??
333 (descriptor === undefined ? null : { environment: descriptor }),
334 );
335 const dotClassName = savedConnection
336 ? savedConnection.tone === "connected"
337 ? "bg-success"
338 : savedConnection.tone === "connecting"
339 ? "bg-warning"
340 : savedConnection.tone === "error"
341 ? "bg-destructive"
342 : "bg-muted-foreground/35"
343 : availability === "online"
344 ? "bg-success"
345 : availability === "error"
346 ? "bg-destructive"
347 : availability === "checking"
348 ? "bg-warning"
349 : "bg-muted-foreground/35";
350 const notAdded = savedWithoutRelay.has(environment.environmentId)
351 ? "Saved without T3 Connect"
352 : "Not added";
353 const statusText =
354 unsupported && !savedEnvironment
355 ? `T3 Connect · ${notAdded} · Client not supported`
356 : offlineReason !== null
357 ? offlineReason
358 : savedConnection
359 ? savedConnection.statusText
360 : availability === "online"
361 ? `T3 Connect · ${notAdded} · Relay online`
362 : availability === "offline"
363 ? `T3 Connect · ${notAdded} · Relay offline`
364 : availability === "checking"
365 ? `T3 Connect · ${notAdded} · Checking relay status…`
366 : (Option.getOrNull(error)?.message ??
367 `T3 Connect · ${notAdded} · Relay status unavailable`);
368 if (selection) {
369 return (
370 <label
371 key={environment.environmentId}
372 className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 has-disabled:cursor-default"
373 >
374 <Checkbox
375 checked={!unsupported && selection.selectedIds.has(environment.environmentId)}
376 disabled={unsupported || connectingEnvironmentIds.has(environment.environmentId)}
377 onCheckedChange={async (checked) => {
378 if (unsupported) return;
379 selection.onChange(environment.environmentId, checked);
380 if (checked && !savedEnvironment) {
381 const connected = await connectEnvironment(environment);
382 if (!connected) selection.onChange(environment.environmentId, false);
383 }
384 }}
385 />
386 <EnvironmentMachineIcon
387 aria-hidden
388 kind={machineKind}
389 className="size-4 shrink-0 text-muted-foreground"
390 />
391 <span className="min-w-0 flex-1">
392 <span className="block truncate text-sm font-medium">{environment.label}</span>
393 {unsupportedDetail !== null ? (
394 <span className="mt-0.5 block text-xs text-muted-foreground">
395 {unsupportedDetail}
396 </span>
397 ) : null}
398 </span>
399 <Tooltip>
400 <TooltipTrigger
401 render={<span tabIndex={0} />}
402 className={cn(
403 "max-w-[45%] shrink-0 truncate text-xs",
404 savedConnection?.tone === "error" ? "text-destructive" : "text-muted-foreground",
405 )}
406 >
407 {connectingEnvironmentIds.has(environment.environmentId)
408 ? "Connecting…"
409 : (savedConnection?.buttonLabel ??
410 (availability === "online"
411 ? "Available"
412 : availability === "offline"
413 ? "Offline"
414 : availability === "error"
415 ? "Unavailable"
416 : "Checking…"))}
417 </TooltipTrigger>
418 <TooltipPopup>{unsupportedDetail ?? statusText}</TooltipPopup>
419 </Tooltip>
420 </label>
421 );
422 }
423 return (
424 <div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
425 <div className={ITEM_ROW_INNER_CLASSNAME}>
426 <div className="min-w-0">
427 <div className="flex items-center gap-2">
428 <ConnectionStatusDot
429 dotClassName={dotClassName}
430 pingClassName={
431 savedConnection?.tone === "connecting" ||
432 (savedConnection === null && availability === "checking")
433 ? "bg-warning/60 duration-2000"
434 : null
435 }
436 tooltipText={
437 unsupportedDetail !== null
438 ? unsupportedDetail
439 : offlineReason !== null
440 ? offlineReason
441 : savedConnection
442 ? savedConnection.statusText
443 : availability === "online"
444 ? "Relay online"
445 : availability === "offline"
446 ? "Relay offline"
447 : availability === "checking"
448 ? "Checking relay status"
449 : (Option.getOrNull(error)?.message ?? "Relay status unavailable")
450 }
451 />
452 <EnvironmentMachineIcon
453 aria-hidden
454 kind={machineKind}
455 className="size-4 shrink-0 text-muted-foreground"
456 />
457 <p className="truncate text-sm font-medium">{environment.label}</p>
458 </div>
459 <p
460 className={cn(
461 "mt-1 truncate text-xs",
462 savedConnection?.tone === "error" ||
463 (savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
464 (savedConnection === null && availability === "error")
465 ? "text-destructive"
466 : "text-muted-foreground",
467 )}
468 >
469 {statusText}
470 </p>
471 </div>
472 {unsupported && !savedEnvironment ? (
473 <Tooltip>
474 <TooltipTrigger render={<span className="inline-flex" tabIndex={0} />}>
475 <Button size="sm" disabled>
476 Add
477 </Button>
478 </TooltipTrigger>
479 <TooltipPopup>{unsupportedDetail ?? "Client not supported"}</TooltipPopup>
480 </Tooltip>
481 ) : savedConnection ? (
482 <Button size="sm" variant="outline" disabled>
483 {savedConnection.buttonLabel}
484 </Button>
485 ) : (
486 <Button
487 size="sm"
488 disabled={connectingEnvironmentIds.size > 0}
489 onClick={() => void connectEnvironment(environment)}
490 >
491 {connectingEnvironmentIds.has(environment.environmentId)
492 ? "Adding…"
493 : savedWithoutRelay.has(environment.environmentId)
494 ? "Add route"
495 : "Add"}
496 </Button>
497 )}
498 </div>
499 </div>
500 );
501 });
502}