The best way to control Claude Code, Codex and more from any computer or phone

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