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

ConnectionDiagnosisDetails.tsx

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