Open History to see the last commit
1import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react";
2import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
3
4import { APP_DISPLAY_NAME } from "../branding";
5import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
6import { useServerConfig } from "../rpc/serverState";
7import {
8 exhaustWsReconnectIfStillWaiting,
9 getWsConnectionStatus,
10 getWsConnectionUiState,
11 setBrowserOnlineStatus,
12 type WsConnectionStatus,
13 type WsConnectionUiState,
14 useWsConnectionStatus,
15 WS_RECONNECT_MAX_ATTEMPTS,
16} from "../rpc/wsConnectionState";
17import { Button } from "./ui/button";
18import { toastManager } from "./ui/toast";
19import { getWsRpcClient } from "~/wsRpcClient";
20
21const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
22type WsAutoReconnectTrigger = "focus" | "online";
23
24const connectionTimeFormatter = new Intl.DateTimeFormat(undefined, {
25 day: "numeric",
26 hour: "numeric",
27 minute: "2-digit",
28 month: "short",
29 second: "2-digit",
30});
31
32function formatConnectionMoment(isoDate: string | null): string | null {
33 if (!isoDate) {
34 return null;
35 }
36
37 return connectionTimeFormatter.format(new Date(isoDate));
38}
39
40function formatRetryCountdown(nextRetryAt: string, nowMs: number): string {
41 const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs);
42 return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`;
43}
44
45function describeOfflineToast(): string {
46 return "WebSocket disconnected. Waiting for network.";
47}
48
49function formatReconnectAttemptLabel(status: WsConnectionStatus): string {
50 const reconnectAttempt = Math.max(
51 1,
52 Math.min(status.reconnectAttemptCount, WS_RECONNECT_MAX_ATTEMPTS),
53 );
54 return `Attempt ${reconnectAttempt}/${status.reconnectMaxAttempts}`;
55}
56
57function describeExhaustedToast(): string {
58 return "Retries exhausted trying to reconnect";
59}
60
61function buildReconnectTitle(status: WsConnectionStatus): string {
62 if (status.nextRetryAt === null) {
63 return "Disconnected from T3 Server";
64 }
65
66 return "Disconnected from T3 Server";
67}
68
69function describeRecoveredToast(
70 previousDisconnectedAt: string | null,
71 connectedAt: string | null,
72): string {
73 const reconnectedAtLabel = formatConnectionMoment(connectedAt);
74 const disconnectedAtLabel = formatConnectionMoment(previousDisconnectedAt);
75
76 if (disconnectedAtLabel && reconnectedAtLabel) {
77 return `Disconnected at ${disconnectedAtLabel} and reconnected at ${reconnectedAtLabel}.`;
78 }
79
80 if (reconnectedAtLabel) {
81 return `Connection restored at ${reconnectedAtLabel}.`;
82 }
83
84 return "Connection restored.";
85}
86
87function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): ReactNode {
88 const count = requests.length;
89 const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000);
90
91 return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
92}
93
94export function shouldAutoReconnect(
95 status: WsConnectionStatus,
96 trigger: WsAutoReconnectTrigger,
97): boolean {
98 const uiState = getWsConnectionUiState(status);
99
100 if (trigger === "online") {
101 return (
102 uiState === "offline" ||
103 uiState === "reconnecting" ||
104 uiState === "error" ||
105 status.reconnectPhase === "exhausted"
106 );
107 }
108
109 return (
110 status.online &&
111 status.hasConnected &&
112 (uiState === "reconnecting" || status.reconnectPhase === "exhausted")
113 );
114}
115
116function buildBlockingCopy(
117 uiState: WsConnectionUiState,
118 status: WsConnectionStatus,
119): {
120 readonly description: string;
121 readonly eyebrow: string;
122 readonly title: string;
123} {
124 if (uiState === "connecting") {
125 return {
126 description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`,
127 eyebrow: "Starting Session",
128 title: `Connecting to ${APP_DISPLAY_NAME}`,
129 };
130 }
131
132 if (uiState === "offline") {
133 return {
134 description:
135 "Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.",
136 eyebrow: "Offline",
137 title: "WebSocket connection unavailable",
138 };
139 }
140
141 if (status.lastError?.trim()) {
142 return {
143 description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`,
144 eyebrow: "Connection Error",
145 title: "Cannot reach the T3 server",
146 };
147 }
148
149 return {
150 description:
151 "The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.",
152 eyebrow: "Connection Error",
153 title: "Cannot reach the T3 server",
154 };
155}
156
157function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string {
158 const details = [
159 `state: ${uiState}`,
160 `online: ${status.online ? "yes" : "no"}`,
161 `attempts: ${status.attemptCount}`,
162 ];
163
164 if (status.socketUrl) {
165 details.push(`socket: ${status.socketUrl}`);
166 }
167 if (status.connectedAt) {
168 details.push(`connectedAt: ${status.connectedAt}`);
169 }
170 if (status.disconnectedAt) {
171 details.push(`disconnectedAt: ${status.disconnectedAt}`);
172 }
173 if (status.lastErrorAt) {
174 details.push(`lastErrorAt: ${status.lastErrorAt}`);
175 }
176 if (status.lastError) {
177 details.push(`lastError: ${status.lastError}`);
178 }
179 if (status.closeCode !== null) {
180 details.push(`closeCode: ${status.closeCode}`);
181 }
182 if (status.closeReason) {
183 details.push(`closeReason: ${status.closeReason}`);
184 }
185
186 return details.join("\n");
187}
188
189function WebSocketBlockingState({
190 status,
191 uiState,
192}: {
193 readonly status: WsConnectionStatus;
194 readonly uiState: WsConnectionUiState;
195}) {
196 const copy = buildBlockingCopy(uiState, status);
197 const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt);
198 const Icon =
199 uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle;
200
201 return (
202 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
203 <div className="pointer-events-none absolute inset-0 opacity-90">
204 <div className="absolute inset-x-0 top-0 h-56 bg-[radial-gradient(48rem_18rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
205 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
206 </div>
207
208 <section className="relative w-full max-w-xl rounded-[1.75rem] border border-border/80 bg-card/92 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
209 <div className="flex items-start justify-between gap-4">
210 <div>
211 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
212 {copy.eyebrow}
213 </p>
214 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{copy.title}</h1>
215 </div>
216 <div className="rounded-2xl border border-border/70 bg-background/80 p-3 text-foreground shadow-sm">
217 <Icon className={uiState === "connecting" ? "size-5 animate-spin" : "size-5"} />
218 </div>
219 </div>
220
221 <p className="mt-3 text-sm leading-relaxed text-muted-foreground">{copy.description}</p>
222
223 <div className="mt-5 grid gap-3 rounded-2xl border border-border/70 bg-background/60 p-4 text-sm sm:grid-cols-2">
224 <div>
225 <p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
226 Connection
227 </p>
228 <p className="mt-1 font-medium text-foreground">
229 {uiState === "connecting"
230 ? "Opening WebSocket"
231 : uiState === "offline"
232 ? "Waiting for network"
233 : "Retrying server connection"}
234 </p>
235 </div>
236 <div>
237 <p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
238 Latest Event
239 </p>
240 <p className="mt-1 font-medium text-foreground">{disconnectedAt ?? "Pending"}</p>
241 </div>
242 </div>
243
244 <div className="mt-5 flex flex-wrap gap-2">
245 <Button size="sm" onClick={() => window.location.reload()}>
246 <RotateCw />
247 Reload app
248 </Button>
249 </div>
250
251 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
252 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
253 <span className="group-open:hidden">Show connection details</span>
254 <span className="hidden group-open:inline">Hide connection details</span>
255 </summary>
256 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
257 {buildConnectionDetails(status, uiState)}
258 </pre>
259 </details>
260 </section>
261 </div>
262 );
263}
264
265export function WebSocketConnectionCoordinator() {
266 const status = useWsConnectionStatus();
267 const [nowMs, setNowMs] = useState(() => Date.now());
268 const lastForcedReconnectAtRef = useRef(0);
269 const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
270 const toastResetTimerRef = useRef<number | null>(null);
271 const previousUiStateRef = useRef<WsConnectionUiState>(getWsConnectionUiState(status));
272 const previousDisconnectedAtRef = useRef<string | null>(status.disconnectedAt);
273
274 const runReconnect = useEffectEvent((showFailureToast: boolean) => {
275 if (toastResetTimerRef.current !== null) {
276 window.clearTimeout(toastResetTimerRef.current);
277 toastResetTimerRef.current = null;
278 }
279 lastForcedReconnectAtRef.current = Date.now();
280 void getWsRpcClient()
281 .reconnect()
282 .catch((error) => {
283 if (!showFailureToast) {
284 console.warn("Automatic WebSocket reconnect failed", { error });
285 return;
286 }
287 toastManager.add({
288 type: "error",
289 title: "Reconnect failed",
290 description: error instanceof Error ? error.message : "Unable to restart the WebSocket.",
291 data: {
292 dismissAfterVisibleMs: 8_000,
293 hideCopyButton: true,
294 },
295 });
296 });
297 });
298 const syncBrowserOnlineStatus = useEffectEvent(() => {
299 setBrowserOnlineStatus(navigator.onLine !== false);
300 });
301 const triggerManualReconnect = useEffectEvent(() => {
302 runReconnect(true);
303 });
304 const triggerAutoReconnect = useEffectEvent((trigger: WsAutoReconnectTrigger) => {
305 const currentStatus =
306 trigger === "online" ? setBrowserOnlineStatus(true) : getWsConnectionStatus();
307
308 if (!shouldAutoReconnect(currentStatus, trigger)) {
309 return;
310 }
311 if (Date.now() - lastForcedReconnectAtRef.current < FORCED_WS_RECONNECT_DEBOUNCE_MS) {
312 return;
313 }
314
315 runReconnect(false);
316 });
317
318 useEffect(() => {
319 const handleOnline = () => {
320 triggerAutoReconnect("online");
321 };
322 const handleFocus = () => {
323 triggerAutoReconnect("focus");
324 };
325
326 syncBrowserOnlineStatus();
327 window.addEventListener("online", handleOnline);
328 window.addEventListener("offline", syncBrowserOnlineStatus);
329 window.addEventListener("focus", handleFocus);
330 return () => {
331 window.removeEventListener("online", handleOnline);
332 window.removeEventListener("offline", syncBrowserOnlineStatus);
333 window.removeEventListener("focus", handleFocus);
334 };
335 }, []);
336
337 useEffect(() => {
338 if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
339 return;
340 }
341
342 setNowMs(Date.now());
343 const intervalId = window.setInterval(() => {
344 setNowMs(Date.now());
345 }, 1_000);
346
347 return () => {
348 window.clearInterval(intervalId);
349 };
350 }, [status.nextRetryAt, status.reconnectPhase]);
351
352 useEffect(() => {
353 if (
354 status.reconnectPhase !== "waiting" ||
355 status.nextRetryAt === null ||
356 !status.online ||
357 !status.hasConnected
358 ) {
359 return;
360 }
361
362 const nextRetryAt = status.nextRetryAt;
363 const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
364 const timeoutId = window.setTimeout(() => {
365 exhaustWsReconnectIfStillWaiting(nextRetryAt);
366 }, timeoutMs);
367
368 return () => {
369 window.clearTimeout(timeoutId);
370 };
371 }, [
372 status.hasConnected,
373 status.nextRetryAt,
374 status.online,
375 status.reconnectAttemptCount,
376 status.reconnectPhase,
377 ]);
378
379 useEffect(() => {
380 const uiState = getWsConnectionUiState(status);
381 const previousUiState = previousUiStateRef.current;
382 const previousDisconnectedAt = previousDisconnectedAtRef.current;
383 const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting";
384 const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null;
385 const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted";
386
387 if (
388 toastResetTimerRef.current !== null &&
389 (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast)
390 ) {
391 window.clearTimeout(toastResetTimerRef.current);
392 toastResetTimerRef.current = null;
393 }
394
395 if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) {
396 const toastPayload = shouldShowOfflineToast
397 ? {
398 description: describeOfflineToast(),
399 timeout: 0,
400 title: "Offline",
401 type: "warning" as const,
402 data: {
403 hideCopyButton: true,
404 },
405 }
406 : shouldShowExhaustedToast
407 ? {
408 actionProps: {
409 children: "Retry",
410 onClick: triggerManualReconnect,
411 },
412 description: describeExhaustedToast(),
413 timeout: 0,
414 title: "Disconnected from T3 Server",
415 type: "error" as const,
416 data: {
417 hideCopyButton: true,
418 },
419 }
420 : {
421 actionProps: {
422 children: "Retry now",
423 onClick: triggerManualReconnect,
424 },
425 description:
426 status.nextRetryAt === null
427 ? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
428 : `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
429 timeout: 0,
430 title: buildReconnectTitle(status),
431 type: "loading" as const,
432 data: {
433 hideCopyButton: true,
434 },
435 };
436
437 if (toastIdRef.current) {
438 toastManager.update(toastIdRef.current, toastPayload);
439 } else {
440 toastIdRef.current = toastManager.add(toastPayload);
441 }
442 } else if (toastIdRef.current) {
443 toastManager.close(toastIdRef.current);
444 toastIdRef.current = null;
445 }
446
447 if (
448 uiState === "connected" &&
449 (previousUiState === "offline" || previousUiState === "reconnecting") &&
450 previousDisconnectedAt !== null
451 ) {
452 const successToast = {
453 description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
454 title: "Reconnected to T3 Server",
455 type: "success" as const,
456 timeout: 0,
457 data: {
458 dismissAfterVisibleMs: 8_000,
459 hideCopyButton: true,
460 },
461 };
462
463 if (toastIdRef.current) {
464 toastManager.update(toastIdRef.current, successToast);
465 } else {
466 toastIdRef.current = toastManager.add(successToast);
467 }
468
469 toastResetTimerRef.current = window.setTimeout(() => {
470 toastIdRef.current = null;
471 toastResetTimerRef.current = null;
472 }, 8_250);
473 }
474
475 previousUiStateRef.current = uiState;
476 previousDisconnectedAtRef.current = status.disconnectedAt;
477 }, [nowMs, status]);
478
479 useEffect(() => {
480 return () => {
481 if (toastResetTimerRef.current !== null) {
482 window.clearTimeout(toastResetTimerRef.current);
483 }
484 };
485 }, []);
486
487 return null;
488}
489
490export function SlowRpcAckToastCoordinator() {
491 const slowRequests = useSlowRpcAckRequests();
492 const status = useWsConnectionStatus();
493 const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
494
495 useEffect(() => {
496 if (getWsConnectionUiState(status) !== "connected") {
497 if (toastIdRef.current) {
498 toastManager.close(toastIdRef.current);
499 toastIdRef.current = null;
500 }
501 return;
502 }
503
504 if (slowRequests.length === 0) {
505 if (toastIdRef.current) {
506 toastManager.close(toastIdRef.current);
507 toastIdRef.current = null;
508 }
509 return;
510 }
511
512 const nextToast = {
513 description: describeSlowRpcAckToast(slowRequests),
514 timeout: 0,
515 title: "Some requests are slow",
516 type: "warning" as const,
517 };
518
519 if (toastIdRef.current) {
520 toastManager.update(toastIdRef.current, nextToast);
521 } else {
522 toastIdRef.current = toastManager.add(nextToast);
523 }
524 }, [slowRequests, status]);
525
526 return null;
527}
528
529export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) {
530 const serverConfig = useServerConfig();
531 const status = useWsConnectionStatus();
532
533 if (serverConfig === null) {
534 const uiState = getWsConnectionUiState(status);
535 return (
536 <WebSocketBlockingState
537 status={status}
538 uiState={uiState === "connected" ? "connecting" : uiState}
539 />
540 );
541 }
542
543 return children;
544}