Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectionDiagnosisDetails.tsx

211 lines7.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 AVAILABLE_CONNECTION_STATE,
4 type ConnectionDiagnosis,
5 connectionDiagnosisText,
6 connectionRoutes,
7 hasRelayRoute,
8 presentConnectionDiagnosis,
9} from "@t3tools/client-runtime/connection";
10import * as Option from "effect/Option";
11import { AsyncResult } from "effect/reactivity";
12import { ChevronRightIcon } from "lucide-react";
13import { useEffect, useState } from "react";
14​
15import { APP_VERSION } from "~/branding";
16import { environmentCatalog } from "~/connection/catalog";
17import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
18import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
19import { cn } from "../../lib/utils";
20import { Button } from "../ui/button";
21import { stackedThreadToast, toastManager } from "../ui/toast";
22​
23/**
24 * What failed on the way to an environment, or null while it is connected, off,
25 * or has not failed. Reads the supervisor state itself so callers that only need
26 * the headline do not re-render on every attempt.
27 */
28export function useConnectionDiagnosis(environment: EnvironmentPresentation) {
29 const environmentId = environment.environmentId;
30 const state = Option.getOrElse(
31 AsyncResult.value(useAtomValue(environmentCatalog.stateAtom(environmentId))),
32 () => AVAILABLE_CONNECTION_STATE,
33 );
34 const relayStatus = useRelayEnvironmentDiscovery().environments.get(environmentId)?.status;
35 const routes = connectionRoutes(environment.entry);
36 const relayOnly = routes.length === 1 && hasRelayRoute(environment.entry);
37 const phase = environment.connection.phase;
38 const diagnosis =
39 environment.entry.enabled && phase !== "connected" && phase !== "unsupported"
40 ? presentConnectionDiagnosis({
41 hostLabel: environment.label,
42 state,
43 via: relayOnly ? "relay" : "direct",
44 // With a direct route as well, the relay's health says nothing about the route in use.
45 relayStatus: relayOnly ? Option.getOrNull(relayStatus ?? Option.none()) : null,
46 clientVersion: APP_VERSION,
47 serverVersion: environment.serverConfig?.environment.serverVersion,
48 })
49 : null;
50 return { diagnosis, state, relayOnly };
52​
53/** The failure headline alone, for banners outside Settings. */
54export function ConnectionDiagnosisHeadline({
55 environment,
56}: {
57 readonly environment: EnvironmentPresentation;
58}) {
59 return useConnectionDiagnosis(environment).diagnosis?.headline ?? null;
61​
62const HOP_MARK = { ok: "✓", failed: "✕", unchecked: "–" } as const;
63const HOP_NOTE = { ok: "", failed: "Failed", unchecked: "Not checked" } as const;
64​
65/** Ticks once per second, and only while a retry is scheduled, so the list around it does not re-render. */
66function RetryCountdown({ retryAt }: { readonly retryAt: number }) {
67 const [now, setNow] = useState(Date.now);
68 useEffect(() => {
69 if (retryAt <= Date.now()) return;
70 const timer = setInterval(() => setNow(Date.now()), 1_000);
71 return () => clearInterval(timer);
72 }, [retryAt]);
73 const seconds = Math.ceil((retryAt - now) / 1_000);
74 return <>{seconds > 0 ? `retrying in ${seconds}s` : "retrying"}</>;
76​
77/** The collapsed failure: the full headline, then the retry state and a Details toggle. */
78export function ConnectionDiagnosisSummary({
79 diagnosis,
80 retryAt,
81 attempt,
82 expanded,
83 onToggle,
84}: {
85 readonly diagnosis: ConnectionDiagnosis;
86 readonly retryAt: number | null;
87 readonly attempt: number;
88 readonly expanded: boolean;
89 readonly onToggle: () => void;
90}) {
91 return (
92 <div className="text-xs">
93 <p className="text-destructive">{diagnosis.headline}</p>
94 <p className="flex flex-wrap items-center gap-1 text-muted-foreground">
95 {retryAt !== null ? <RetryCountdown retryAt={retryAt} /> : null}
96 {retryAt !== null && attempt > 0 ? <span aria-hidden>·</span> : null}
97 {attempt > 0 ? <span>attempt {attempt}</span> : null}
98 {retryAt !== null || attempt > 0 ? <span aria-hidden>·</span> : null}
99 <button
100 type="button"
101 aria-expanded={expanded}
102 onClick={onToggle}
103 className="inline-flex items-center gap-0.5 rounded-sm outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
104 >
105 Details
106 <ChevronRightIcon
107 aria-hidden
108 className={cn(
109 "size-3 transition-transform duration-150 motion-reduce:transition-none",
110 expanded && "rotate-90",
111 )}
112 />
113 </button>
114 </p>
115 </div>
116 );
118​
119/** Hops in order, what to try, the facts, and the actions. */
120export function ConnectionDiagnosisPanel({
121 hostLabel,
122 diagnosis,
123 onRetry,
124 onAddRoute,
125}: {
126 readonly hostLabel: string;
127 readonly diagnosis: ConnectionDiagnosis;
128 readonly onRetry: () => void;
129 readonly onAddRoute: (() => void) | null;
130}) {
131 const { copyToClipboard } = useCopyToClipboard({
132 target: "connection diagnostics",
133 onCopy: () => toastManager.add({ type: "success", title: "Diagnostics copied" }),
134 onError: (error) =>
135 toastManager.add(
136 stackedThreadToast({
137 type: "error",
138 title: "Could not copy diagnostics",
139 description: error.message,
140 }),
141 ),
142 });
143 return (
144 <div className="mt-2 grid gap-3 border-t border-border/50 pt-2 text-xs">
145 <ol className="grid gap-0.5">
146 {diagnosis.hops.map((hop) => (
147 <li
148 key={hop.hop}
149 className={cn(
150 "flex gap-2",
151 hop.result === "failed" ? "text-destructive" : "text-muted-foreground",
152 )}
153 >
154 <span aria-hidden className="w-3 text-center">
155 {HOP_MARK[hop.result]}
156 </span>
157 <span className={cn(hop.result === "ok" && "text-foreground")}>{hop.label}</span>
158 <span>{HOP_NOTE[hop.result]}</span>
159 </li>
160 ))}
161 </ol>
162 <div>
163 <p className="font-medium text-foreground">What to try</p>
164 <ol className="list-decimal pl-4 text-muted-foreground">
165 {diagnosis.steps.map((step) => (
166 <li key={step}>{step}</li>
167 ))}
168 </ol>
169 {diagnosis.moreInfoUrl ? (
170 <a
171 href={diagnosis.moreInfoUrl}
172 target="_blank"
173 rel="noreferrer"
174 className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
175 >
176 More info
177 </a>
178 ) : null}
179 </div>
180 <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 font-mono text-muted-foreground">
181 {diagnosis.facts.map(([label, value]) => (
182 <div key={label} className="contents">
183 <dt>{label}</dt>
184 <dd className="break-all text-foreground">{value}</dd>
185 </div>
186 ))}
187 </dl>
188 <div className="flex flex-wrap gap-2">
189 <Button type="button" size="xs" variant="outline" onClick={onRetry}>
190 Retry now
191 </Button>
192 <Button
193 type="button"
194 size="xs"
195 variant="outline"
196 onClick={() => {
197 const text = connectionDiagnosisText(hostLabel, diagnosis);
198 copyToClipboard(text, undefined);
199 }}
200 >
201 Copy diagnostics
202 </Button>
203 {onAddRoute ? (
204 <Button type="button" size="xs" variant="outline" onClick={onAddRoute}>
205 Add direct route
206 </Button>
207 ) : null}
208 </div>
209 </div>
210 );