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

ConnectionDiagnosisDetails.tsx

209 lines7.3 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 onError: (error) =>
133 toastManager.add(
134 stackedThreadToast({
135 type: "error",
136 title: "Could not copy diagnostics",
137 description: error.message,
138 }),
139 ),
140 });
141 return (
142 <div className="mt-2 grid gap-3 border-t border-border/50 pt-2 text-xs">
143 <ol className="grid gap-0.5">
144 {diagnosis.hops.map((hop) => (
145 <li
146 key={hop.hop}
147 className={cn(
148 "flex gap-2",
149 hop.result === "failed" ? "text-destructive" : "text-muted-foreground",
150 )}
151 >
152 <span aria-hidden className="w-3 text-center">
153 {HOP_MARK[hop.result]}
154 </span>
155 <span className={cn(hop.result === "ok" && "text-foreground")}>{hop.label}</span>
156 <span>{HOP_NOTE[hop.result]}</span>
157 </li>
158 ))}
159 </ol>
160 <div>
161 <p className="font-medium text-foreground">What to try</p>
162 <ol className="list-decimal pl-4 text-muted-foreground">
163 {diagnosis.steps.map((step) => (
164 <li key={step}>{step}</li>
165 ))}
166 </ol>
167 {diagnosis.moreInfoUrl ? (
168 <a
169 href={diagnosis.moreInfoUrl}
170 target="_blank"
171 rel="noreferrer"
172 className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
173 >
174 More info
175 </a>
176 ) : null}
177 </div>
178 <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 font-mono text-muted-foreground">
179 {diagnosis.facts.map(([label, value]) => (
180 <div key={label} className="contents">
181 <dt>{label}</dt>
182 <dd className="break-all text-foreground">{value}</dd>
183 </div>
184 ))}
185 </dl>
186 <div className="flex flex-wrap gap-2">
187 <Button type="button" size="xs" variant="outline" onClick={onRetry}>
188 Retry now
189 </Button>
190 <Button
191 type="button"
192 size="xs"
193 variant="outline"
194 onClick={() => {
195 const text = connectionDiagnosisText(hostLabel, diagnosis);
196 copyToClipboard(text, undefined);
197 }}
198 >
199 Copy diagnostics
200 </Button>
201 {onAddRoute ? (
202 <Button type="button" size="xs" variant="outline" onClick={onAddRoute}>
203 Add direct route
204 </Button>
205 ) : null}
206 </div>
207 </div>
208 );