Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 3b6bb6a0dd Use direct environment service import
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 16:33:56 +00:00
Cursor AgentandJulius Marminge 50e8412909 Keep websocket effect events local
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 16:33:06 +00:00
Cursor AgentandJulius Marminge 92d5c519ed Optimize websocket reconnect toast rerenders
Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 16:29:09 +00:00
Cursor AgentandJulius Marminge 85d15178b5 feat: Add React Scan WebSocket reconnect toast harness with environment initialization
- Create react-scan-ws-harness.html and reactScanWsHarness.tsx for testing React Scan performance monitoring
- Initialize mock primary environment to prevent 'Unable to resolve primary environment' error
- Seed WebSocket reconnect-waiting state for toast testing
- Add console logging to debug connection state

The harness sets up a test environment to observe whether React Scan can detect rerenders
in the WebSocket reconnect toast countdown. The toast infrastructure requires additional
WebSocket connection mocking to fully function.

Co-authored-by: Julius Marminge <[email protected]>
2026-06-03 16:17:28 +00:00
3 changed files with 154 additions and 37 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script crossorigin="anonymous" src="https://unpkg.com/react-scan/dist/auto.global.js"></script>
<title>React Scan WebSocket Toast Harness</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/reactScanWsHarness.tsx"></script>
</body>
</html>
@@ -1,4 +1,4 @@
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
import { type ReactNode, useEffect, useEffectEvent, useRef } from "react";
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
import {
@@ -11,7 +11,7 @@ import {
WS_RECONNECT_MAX_ATTEMPTS,
} from "../rpc/wsConnectionState";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { getPrimaryEnvironmentConnection } from "../environments/runtime";
import { getPrimaryEnvironmentConnection } from "../environments/runtime/service";
const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
type WsAutoReconnectTrigger = "focus" | "online";
@@ -32,11 +32,6 @@ function formatConnectionMoment(isoDate: string | null): string | null {
return connectionTimeFormatter.format(new Date(isoDate));
}
function formatRetryCountdown(nextRetryAt: string, nowMs: number): string {
const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs);
return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`;
}
function describeOfflineToast(): string {
return "WebSocket disconnected. Waiting for network.";
}
@@ -53,6 +48,17 @@ function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
function describeReconnectToast(status: WsConnectionStatus): string {
const attemptLabel = formatReconnectAttemptLabel(status);
if (status.nextRetryAt === null) {
return `Reconnecting... ${attemptLabel}`;
}
return `Next reconnect attempt is scheduled for ${
formatConnectionMoment(status.nextRetryAt) ?? status.nextRetryAt
}. ${attemptLabel}`;
}
function getConnectionDisplayName(status: WsConnectionStatus): string {
return status.connectionLabel?.trim() || "T3 Server";
}
@@ -145,14 +151,15 @@ export function shouldRestartStalledReconnect(
);
}
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
const [nowMs, setNowMs] = useState(() => Date.now());
function useWebSocketConnectionCoordinator(status: WsConnectionStatus) {
const lastForcedReconnectAtRef = useRef(0);
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
const toastResetTimerRef = useRef<number | null>(null);
const previousUiStateRef = useRef<WsConnectionUiState>(getWsConnectionUiState(status));
const previousUiStateRef = useRef<WsConnectionUiState | null>(null);
const previousDisconnectedAtRef = useRef<string | null>(status.disconnectedAt);
if (previousUiStateRef.current === null) {
previousUiStateRef.current = getWsConnectionUiState(status);
}
const runReconnect = useEffectEvent((showFailureToast: boolean) => {
if (toastResetTimerRef.current !== null) {
@@ -220,21 +227,6 @@ export function WebSocketConnectionCoordinator() {
};
}, []);
useEffect(() => {
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
return;
}
setNowMs(Date.now());
const intervalId = window.setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => {
window.clearInterval(intervalId);
};
}, [status.nextRetryAt, status.reconnectPhase]);
useEffect(() => {
if (
status.reconnectPhase !== "waiting" ||
@@ -269,7 +261,7 @@ export function WebSocketConnectionCoordinator() {
useEffect(() => {
const uiState = getWsConnectionUiState(status);
const previousUiState = previousUiStateRef.current;
const previousUiState = previousUiStateRef.current ?? uiState;
const previousDisconnectedAt = previousDisconnectedAtRef.current;
const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting";
const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null;
@@ -316,10 +308,7 @@ export function WebSocketConnectionCoordinator() {
data: {
hideCopyButton: true,
},
description:
status.nextRetryAt === null
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
description: describeReconnectToast(status),
timeout: 0,
title: buildReconnectTitle(status),
type: "loading",
@@ -365,22 +354,30 @@ export function WebSocketConnectionCoordinator() {
previousUiStateRef.current = uiState;
previousDisconnectedAtRef.current = status.disconnectedAt;
}, [nowMs, status]);
}, [status]);
useEffect(() => {
const timerRef = toastResetTimerRef;
return () => {
if (toastResetTimerRef.current !== null) {
window.clearTimeout(toastResetTimerRef.current);
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
}
};
}, []);
}
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
useWebSocketConnectionCoordinator(status);
return null;
}
export function SlowRpcAckToastCoordinator() {
const slowRequests = useSlowRpcAckRequests();
const status = useWsConnectionStatus();
function useSlowRpcAckToast(
status: WsConnectionStatus,
slowRequests: ReadonlyArray<SlowRpcAckRequest>,
) {
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
useEffect(() => {
@@ -418,6 +415,13 @@ export function SlowRpcAckToastCoordinator() {
toastIdRef.current = toastManager.add(nextToast);
}
}, [slowRequests, status]);
}
export function SlowRpcAckToastCoordinator() {
const slowRequests = useSlowRpcAckRequests();
const status = useWsConnectionStatus();
useSlowRpcAckToast(status, slowRequests);
return null;
}
+100
View File
@@ -0,0 +1,100 @@
import React, { useEffect } from "react";
import ReactDOM from "react-dom/client";
import { createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import "./index.css";
import { WebSocketConnectionCoordinator } from "./components/WebSocketConnectionSurface";
import { ToastProvider } from "./components/ui/toast";
import {
getWsConnectionStatus,
getWsConnectionUiState,
recordWsConnectionAttempt,
recordWsConnectionClosed,
recordWsConnectionOpened,
resetWsConnectionStateForTests,
} from "./rpc/wsConnectionState";
import { writePrimaryEnvironmentDescriptor } from "./environments/primary/context";
function initializeMockEnvironment() {
const mockDescriptor: ExecutionEnvironmentDescriptor = {
environmentId: EnvironmentId.make("harness-mock-env"),
label: "React Scan Harness Mock",
platform: {
os: "darwin",
arch: "arm64",
},
serverVersion: "0.0.0-test",
capabilities: {
repositoryIdentity: false,
},
};
writePrimaryEnvironmentDescriptor(mockDescriptor);
}
function seedReconnectWaitingState() {
resetWsConnectionStateForTests();
recordWsConnectionAttempt("ws://localhost:9999", { connectionLabel: "React Scan Harness" });
recordWsConnectionOpened({ connectionLabel: "React Scan Harness" });
for (let index = 0; index < 5; index += 1) {
recordWsConnectionAttempt("ws://localhost:9999", { connectionLabel: "React Scan Harness" });
recordWsConnectionClosed(
{ code: 1006, reason: "Harness disconnect" },
{
connectionLabel: "React Scan Harness",
},
);
}
const status = getWsConnectionStatus();
const uiState = getWsConnectionUiState(status);
console.log("[Harness] WS status after seed:", { status, uiState });
}
function HarnessView() {
useEffect(() => {
initializeMockEnvironment();
seedReconnectWaitingState();
}, []);
return (
<ToastProvider>
<WebSocketConnectionCoordinator />
<main className="min-h-screen bg-background p-8 text-foreground">
<section className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6 shadow-sm">
<p className="text-xs font-semibold tracking-[0.16em] text-muted-foreground uppercase">
React Scan harness
</p>
<h1 className="mt-3 text-xl font-semibold">WebSocket reconnect toast</h1>
<p className="mt-2 text-sm leading-6 text-muted-foreground">
The WebSocket coordinator is in a reconnect-waiting state. React Scan is enabled to show
whether the toast stack keeps rerendering while the countdown is visible.
</p>
<button
className="mt-4 rounded-md border border-border bg-background px-3 py-1.5 text-sm font-medium hover:bg-accent"
onClick={seedReconnectWaitingState}
type="button"
>
Restart reconnect countdown
</button>
</section>
</main>
</ToastProvider>
);
}
const rootRoute = createRootRoute({
component: HarnessView,
});
const router = createRouter({
routeTree: rootRoute,
});
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);