@devries-cameron20 / t3code Mirror · read-only
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 21, 04:45 UTC

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