feat: migrate frontend to Astro + expand AI moderation + backend admin/runtime config

Frontend:
- migrate from Vite to Astro (astro.config.mjs, pages/, layouts/)
- add admin panel, settings page, command palette, error boundary
- refactor App.tsx, MascotChatbot, Sidebar, Header, DashboardLayout
- update API client, WebSocket, auth, dashboard features

Backend:
- add admin module and config routes
- refactor middlewares, Redis connection, WebSocket server/bridge
- add runtime config loader

Discord Gateway:
- refactor AI moderation: circuit breaker, concurrency limiter, fallback processor
- add media analysis client, Seaxng search, user profile learner
- add new drizzle migration

Shared:
- extend database schema, add new config fields
This commit is contained in:
asepharyana
2026-07-02 00:02:41 +07:00
parent d5c22a3959
commit d59b59a7a7
91 changed files with 11165 additions and 674 deletions
+100 -14
View File
@@ -24,6 +24,7 @@ import type {
VoiceRecordingListResponse,
} from "../../entities/recording/types.js";
import type {
AdminSettings,
AppConfig,
DashboardTab,
UIState,
@@ -49,14 +50,53 @@ class ApiError extends Error {
}
}
// Cache admin password in memory — read from localStorage once on first call
let _cachedPassword: string | null = null;
// Cache admin session token in memory — read from sessionStorage once on first call
// NOTE: _cachedToken is intentionally removed; we read directly from sessionStorage
// to support multi-tab sync (L8 fix).
function getAdminPassword(): string | null {
if (_cachedPassword === null) {
_cachedPassword = localStorage.getItem("admin-password");
}
return _cachedPassword;
/**
* Get the current session token from sessionStorage.
* Always reads directly from sessionStorage to support multi-tab sync.
* Returns null if not authenticated.
*/
export function getSessionToken(): string | null {
return sessionStorage.getItem("admin-token");
}
/**
* Store a session token after successful login.
*/
export function setSessionToken(token: string): void {
sessionStorage.setItem("admin-token", token);
}
/**
* Clear the session token (logout).
*/
export function clearSessionToken(): void {
sessionStorage.removeItem("admin-token");
}
/**
* @deprecated Use getSessionToken() instead.
* Kept for backward compatibility during migration.
*/
export function getAdminPassword(): string | null {
return localStorage.getItem("admin-password");
}
/**
* @deprecated Use setSessionToken() instead.
*/
export function setAdminPassword(password: string): void {
localStorage.setItem("admin-password", password);
}
/**
* @deprecated Use clearSessionToken() instead.
*/
export function clearAdminPassword(): void {
localStorage.removeItem("admin-password");
}
function buildSearchParams(
@@ -76,16 +116,32 @@ export async function request<T>(
init?: RequestInit,
timeoutMs?: number,
): Promise<T> {
const password = getAdminPassword();
const token = getSessionToken();
const url = path.startsWith("http") ? path : `${BE_API_URL}${path}`;
const signal = AbortSignal.timeout(timeoutMs ?? DEFAULT_TIMEOUT_MS);
logger.debug("Request", { method: init?.method ?? "GET", url });
const headers: Record<string, string> = {};
// Only set Content-Type for non-FormData bodies
// FormData sets its own Content-Type (multipart/form-data with boundary)
if (!(init?.body instanceof FormData)) {
headers["Content-Type"] = "application/json";
}
// Prefer Bearer token (new auth method)
if (token) {
headers["Authorization"] = `Bearer ${token}`;
} else {
// Fallback: X-Admin-Password (for backward compatibility)
const password = getAdminPassword();
if (password) {
headers["X-Admin-Password"] = password;
}
}
const res = await fetch(url, {
headers: {
"Content-Type": "application/json",
...(password ? { "X-Admin-Password": password } : {}),
},
headers,
signal,
...init,
});
@@ -101,6 +157,13 @@ export async function request<T>(
// ignore parse errors
}
logger.error("Request failed", { url, status: res.status, code, message });
// Auto-logout on 401: token expired / invalidated
if (res.status === 401) {
clearSessionToken();
window.location.reload();
}
throw new ApiError(code, message, res.status);
}
@@ -117,6 +180,7 @@ export function getAPIURL(): string {
export type {
ActiveSpeaker,
AdminSettings,
AppConfig,
Channel,
ChatResponse,
@@ -271,13 +335,35 @@ export function deleteRecording(id: string): Promise<void> {
// ─── Auth ────────────────────────────────────────────────────────────────────
export function login(password: string): Promise<{ ok: boolean }> {
return request<{ ok: boolean }>("/api/auth/login", {
export function login(password: string): Promise<{ ok: boolean; token?: string }> {
return request<{ ok: boolean; token?: string }>("/api/auth/login", {
method: "POST",
body: JSON.stringify({ password }),
});
}
/**
* Server-side logout: increments token version, invalidating all sessions.
* Call this before clearing local state so the token is properly revoked.
*/
export function logout(): Promise<{ ok: boolean }> {
return request<{ ok: boolean }>("/api/auth/logout", { method: "POST" });
}
// ─── Admin Settings ──────────────────────────────────────────────────────────
export function getAdminSettings(): Promise<AdminSettings> {
return request<AdminSettings>("/api/admin/settings");
}
export function updateAdminSettings(
patch: Partial<{ dashboardIsPublic: boolean }>,
): Promise<AdminSettings> {
return request<AdminSettings>("/api/admin/settings", {
method: "PATCH",
body: JSON.stringify(patch),
});
}
// ─── Dashboard ─────────────────────────────────────────────────────────────────
export function getDashboardStats(): Promise<DashboardStats> {
@@ -0,0 +1,442 @@
import { AnimatePresence, motion } from "framer-motion";
import {
Command,
FileText,
HelpCircle,
MessageSquare,
Moon,
Search,
Settings,
Sun,
Volume2,
X,
} from "lucide-react";
import type { KeyboardEvent } from "react";
import {
useCallback,
useEffect,
useRef,
useState,
type ChangeEvent,
} from "react";
import type { MessageRecord } from "../api/client";
import { request } from "../api/client";
import { cn } from "../lib/utils";
import { Input } from "./index";
/* ─── Modal backdrop variants ──────────────────────────────────────────── */
const backdropVariants = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
};
const modalVariants = {
hidden: { opacity: 0, scale: 0.96, y: 20 },
visible: {
opacity: 1,
scale: 1,
y: 0,
transition: { type: "spring" as const, stiffness: 350, damping: 28 },
},
exit: { opacity: 0, scale: 0.96, y: 10, transition: { duration: 0.15 } },
} as const;
/* ─── Types ────────────────────────────────────────────────────────────── */
type ModalMode = "search" | "shortcuts" | null;
interface CommandPaletteProps {
isOpen: boolean;
mode: ModalMode;
onClose: () => void;
onNavigate: (tab: string) => void;
onToggleTheme: () => void;
isDark: boolean;
}
const shortcuts = [
{ keys: ["Ctrl", "K"], desc: "Open search" },
{ keys: ["?"], desc: "Show keyboard shortcuts" },
{ keys: ["Esc"], desc: "Close modal / cancel" },
{ keys: ["Ctrl", "1"], desc: "Messages & Moderation" },
{ keys: ["Ctrl", "2"], desc: "Voice & Media" },
{ keys: ["Ctrl", "3"], desc: "Dashboard" },
{ keys: ["Ctrl", "4"], desc: "Settings" },
{ keys: ["Space"], desc: "Push-to-talk (when in voice)" },
{ keys: ["T"], desc: "Toggle theme" },
];
/* ─── Help panel ───────────────────────────────────────────────────────── */
function ShortcutsPanel() {
return (
<div className="space-y-3 p-4">
<h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
<HelpCircle className="h-4 w-4 text-primary" />
Keyboard Shortcuts
</h3>
<div className="grid gap-1.5">
{shortcuts.map((s) => (
<div
key={s.keys.join("+")}
className="flex items-center justify-between rounded-lg px-2 py-1.5 hover:bg-accent/50 transition-colors"
>
<span className="text-sm text-muted-foreground">{s.desc}</span>
<kbd className="flex items-center gap-1">
{s.keys.map((k) => (
<span
key={k}
className="inline-flex h-6 min-w-[24px] items-center justify-center rounded-md border border-border bg-background px-1.5 text-xs font-mono text-foreground shadow-sm"
>
{k === "Ctrl" ? <Command className="h-3 w-3" /> : k}
</span>
))}
</kbd>
</div>
))}
</div>
</div>
);
}
/* ─── Quick actions ────────────────────────────────────────────────────── */
const quickActions = [
{ id: "messages", label: "Go to Messages", icon: MessageSquare },
{ id: "live", label: "Go to Voice & Media", icon: Volume2 },
{ id: "dashboard", label: "Go to Dashboard", icon: FileText },
{ id: "settings", label: "Open Settings", icon: Settings },
{ id: "theme", label: "Toggle theme", icon: Sun },
];
/* ─── Main component ───────────────────────────────────────────────────── */
export function CommandPalette({
isOpen,
mode,
onClose,
onNavigate,
onToggleTheme,
isDark,
}: CommandPaletteProps) {
const [query, setQuery] = useState("");
const [searchResults, setSearchResults] = useState<MessageRecord[]>([]);
const [isSearching, setIsSearching] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const [activeIndex, setActiveIndex] = useState(0);
// Focus input when search mode opens
useEffect(() => {
if (isOpen && mode === "search") {
// Small delay for the animation to settle
const focusTimer = setTimeout(() => inputRef.current?.focus(), 50);
return () => clearTimeout(focusTimer);
}
}, [isOpen, mode]);
// Reset state when closing
useEffect(() => {
if (!isOpen) {
setQuery("");
setSearchResults([]);
setActiveIndex(0);
}
}, [isOpen]);
const handleSearch = useCallback(async (q: string) => {
setQuery(q);
if (!q.trim()) {
setSearchResults([]);
return;
}
setIsSearching(true);
try {
const params = new URLSearchParams({ q, limit: "10" });
const data = await request<{ results: MessageRecord[] }>(
`/api/analysis/search?${params}`,
);
setSearchResults(data.results || []);
} catch {
setSearchResults([]);
} finally {
setIsSearching(false);
}
}, []);
const executeAction = useCallback(
(action: string) => {
if (action === "theme") {
onToggleTheme();
} else if (action === "settings") {
onNavigate("settings");
} else if (action === "messages") {
onNavigate("messages");
} else if (action === "live") {
onNavigate("live");
} else if (action === "dashboard") {
onNavigate("dashboard");
}
onClose();
},
[onNavigate, onToggleTheme, onClose],
);
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIndex((i) => (i < searchResults.length - 1 ? i + 1 : 0));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIndex((i) => (i > 0 ? i - 1 : searchResults.length - 1));
} else if (e.key === "Enter" && searchResults.length > 0) {
onClose();
} else if (e.key === "Escape") {
onClose();
}
},
[searchResults.length, onClose],
);
// Global keyboard listeners for search and help
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLSelectElement
)
return;
// Ctrl+K — open search
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
e.preventDefault();
// Don't toggle if already open — just close
if (isOpen) {
onClose();
}
return;
}
// ? — show shortcuts (only when no modal is open)
if (e.key === "?" && !isOpen) {
e.preventDefault();
return;
}
// Escape — close any modal
if (e.key === "Escape" && isOpen) {
onClose();
}
// Ctrl+1-4 — tab navigation
if (e.ctrlKey || e.metaKey) {
const tabMap: Record<string, string> = {
"1": "messages",
"2": "live",
"3": "dashboard",
"4": "settings",
};
const tab = tabMap[e.key];
if (tab) {
e.preventDefault();
onNavigate(tab);
}
}
// T — toggle theme (when no input focused)
if (e.key === "t" && !e.ctrlKey && !e.metaKey && !isOpen) {
e.preventDefault();
onToggleTheme();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [isOpen, onClose, onNavigate, onToggleTheme]);
const showSearch = mode === "search";
const showShortcuts = mode === "shortcuts";
return (
<AnimatePresence>
{isOpen && (
<motion.div
className="fixed inset-0 z-[9999] flex items-start justify-center pt-[12vh]"
variants={backdropVariants}
initial="hidden"
animate="visible"
exit="hidden"
transition={{ duration: 0.15 }}
>
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
onClick={onClose}
/>
{/* Modal */}
<motion.div
className="relative w-full max-w-xl overflow-hidden rounded-2xl border border-border/50 bg-card shadow-2xl"
variants={modalVariants}
initial="hidden"
animate="visible"
exit="exit"
>
{/* Search header */}
{showSearch && (
<div className="flex items-center gap-3 border-b border-border/50 px-4 py-3">
<Search className="h-4 w-4 shrink-0 text-muted-foreground" />
<input
ref={inputRef}
value={query}
onChange={(e) => handleSearch(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Search messages across all channels..."
className="flex-1 border-0 bg-transparent p-0 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none"
/>
{isSearching && (
<div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
)}
{!isSearching && query && (
<button
onClick={() => {
setQuery("");
setSearchResults([]);
}}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
)}
<kbd className="shrink-0 hidden sm:inline-flex h-5 items-center rounded-md border border-border bg-background px-1.5 text-[10px] font-mono text-muted-foreground">
ESC
</kbd>
</div>
)}
{/* Shortcuts header */}
{showShortcuts && (
<div className="flex items-center justify-between border-b border-border/50 px-4 py-3">
<span className="text-sm font-semibold text-foreground flex items-center gap-2">
<HelpCircle className="h-4 w-4 text-primary" />
Keyboard Shortcuts
</span>
<button
onClick={onClose}
className="rounded-lg p-1 text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
)}
{/* Search results */}
{showSearch && (
<div className="max-h-[320px] overflow-y-auto">
{/* Quick actions */}
{!query && (
<div className="p-2">
<p className="px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
Quick actions
</p>
{quickActions.map((action) => {
const Icon = action.icon;
const isThemeAction = action.id === "theme";
return (
<button
key={action.id}
onClick={() => executeAction(action.id)}
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-sm text-foreground hover:bg-accent transition-colors"
>
<Icon
className={cn(
"h-4 w-4",
isThemeAction && isDark
? "text-amber-400"
: isThemeAction
? "text-indigo-400"
: "text-primary",
)}
/>
<span>{action.label}</span>
{isThemeAction && (
<span className="ml-auto text-xs text-muted-foreground">
{isDark ? "→ Light" : "→ Dark"}
</span>
)}
</button>
);
})}
</div>
)}
{/* Results */}
{query && (
<div className="p-2">
{searchResults.length > 0 ? (
<>
<p className="px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
Messages ({searchResults.length})
</p>
{searchResults.map((msg, i) => (
<button
key={msg.id}
onClick={() => {
onClose();
}}
className={cn(
"flex w-full items-start gap-3 rounded-lg px-2 py-2 text-left transition-colors",
i === activeIndex
? "bg-accent"
: "hover:bg-accent/50",
)}
>
<MessageSquare className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground">
{msg.content || "(no content)"}
</p>
<p className="text-xs text-muted-foreground">
{msg.username || msg.user_id || "unknown"}
{msg.ai_status === "flagged" && (
<span className="ml-2 text-destructive">
flagged
</span>
)}
</p>
</div>
</button>
))}
</>
) : (
<p className="px-2 py-4 text-center text-sm text-muted-foreground">
{isSearching
? "Searching..."
: "No messages found matching your query."}
</p>
)}
</div>
)}
{/* Search footer hint */}
{!query && (
<div className="border-t border-border/50 px-4 py-2">
<p className="text-xs text-muted-foreground">
Type to search messages results are fetched from the
server
</p>
</div>
)}
</div>
)}
{/* Shortcuts content */}
{showShortcuts && <ShortcutsPanel />}
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
@@ -1,4 +1,5 @@
import { LayoutDashboard, MessageSquare, Radio } from "lucide-react";
import { motion } from "framer-motion";
import { LayoutDashboard, MessageSquare, Radio, Settings } from "lucide-react";
import type { DashboardTab } from "../../entities/ui/types.js";
import { cn } from "../lib/utils";
@@ -6,6 +7,7 @@ const tabs: Array<{ id: DashboardTab; label: string; Icon: typeof Radio }> = [
{ id: "messages", label: "Messages", Icon: MessageSquare },
{ id: "live", label: "Voice & Media", Icon: Radio },
{ id: "dashboard", label: "Dashboard", Icon: LayoutDashboard },
{ id: "settings" as const, label: "Admin", Icon: Settings },
];
interface MobileTabBarProps {
@@ -18,7 +20,7 @@ export function MobileTabBar({ activeTab, onTabChange }: MobileTabBarProps) {
<nav
aria-label="Main navigation"
role="tablist"
className="fixed bottom-0 left-0 right-0 z-50 flex border-t border-border bg-card shadow-lg md:hidden"
className="fixed bottom-0 left-0 right-0 z-50 flex border-t border-border bg-card shadow-lg shadow-black/5 md:hidden"
>
{tabs.map(({ id, label, Icon }) => (
<button
@@ -29,16 +31,26 @@ export function MobileTabBar({ activeTab, onTabChange }: MobileTabBarProps) {
type="button"
onClick={() => onTabChange(id)}
className={cn(
"flex flex-1 flex-col items-center gap-0.5 py-2 text-xs font-medium transition-colors",
activeTab === id ? "text-primary" : "text-muted-foreground",
"relative flex flex-1 flex-col items-center gap-0.5 py-2 text-xs font-medium transition-colors",
activeTab === id
? "text-primary"
: "text-muted-foreground hover:text-foreground",
)}
>
<Icon className="h-5 w-5" />
{activeTab === id && (
<motion.div
layoutId="tab-indicator"
transition={{ type: "spring", stiffness: 400, damping: 30 }}
className="absolute -top-px left-1/4 right-1/4 h-0.5 rounded-full bg-primary"
/>
)}
<Icon className={cn("h-5 w-5", activeTab === id && "drop-shadow-sm")} />
<span className="text-[10px]">{label}</span>
{activeTab === id && (
<span
aria-hidden="true"
className="h-0.5 w-6 rounded-full bg-primary mx-auto mt-0.5"
<motion.div
layoutId="tab-dot"
transition={{ type: "spring", stiffness: 400, damping: 30 }}
className="h-1 w-1 rounded-full bg-primary mt-0.5"
/>
)}
</button>
@@ -0,0 +1,77 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { AlertTriangle, RefreshCw } from "lucide-react";
import { Button } from "../ui/button";
import { cn } from "../lib/utils";
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
className?: string;
message?: string;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}
/**
* Error Boundary component — catches JavaScript errors in its child tree,
* logs them, and displays a fallback UI instead of crashing the whole app.
*/
export class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("[ErrorBoundary] Caught error:", error.message, errorInfo);
}
handleRetry = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div
className={cn(
"flex flex-col items-center justify-center rounded-xl border border-destructive/30 bg-destructive/5 p-8 text-center",
this.props.className,
)}
role="alert"
>
<AlertTriangle className="mb-3 h-8 w-8 text-destructive" />
<h3 className="mb-1 font-semibold text-foreground">
{this.props.message || "Something went wrong"}
</h3>
<p className="mb-4 text-sm text-muted-foreground">
{this.state.error?.message || "An unexpected error occurred."}
</p>
<Button
onClick={this.handleRetry}
variant="outline"
size="sm"
className="gap-2"
>
<RefreshCw className="h-3.5 w-3.5" />
Try Again
</Button>
</div>
);
}
return this.props.children;
}
}
+41 -8
View File
@@ -8,6 +8,7 @@ import type {
import { useCallback, useEffect, useRef, useState } from "react";
import type { MediaState } from "../../entities/media/types.js";
import { createLogger } from "../lib/logger.js";
import { getSessionToken } from "../api/client.js";
import type { ActiveSpeakerData } from "./events.js";
const logger = createLogger("socket");
@@ -79,6 +80,7 @@ let _wsInstance: WebSocket | null = null;
let _reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let _closed = false;
let _reconnectAttempts = 0;
let _heartbeatInterval: ReturnType<typeof setInterval> | null = null;
const _listeners = new Set<WsHandlers>();
const _statusCallbacks = new Set<(s: WsStatus) => void>();
@@ -90,7 +92,13 @@ function doConnect(): WebSocket {
const BE_WS_URL =
import.meta.env.VITE_BE_WS_URL ||
`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}`;
const url = BE_WS_URL.endsWith("/ws") ? BE_WS_URL : `${BE_WS_URL}/ws`;
let url = BE_WS_URL.endsWith("/ws") ? BE_WS_URL : `${BE_WS_URL}/ws`;
// ⚠️ Token is NOT appended to the URL — sending it in the query string
// would leak it into Nginx/Traefik access logs, browser history, and
// Referer headers. Instead, the frontend sends an auth message as the
// first WebSocket frame after connection.
const ws = new WebSocket(url);
ws.binaryType = "arraybuffer";
dispatchStatus("connecting");
@@ -100,12 +108,32 @@ function doConnect(): WebSocket {
_reconnectAttempts = 0;
dispatchStatus("connected");
logger.info("Connected");
// Send auth message — token is sent as the first WebSocket frame,
// NOT in the URL query string, to avoid exposure in access logs.
const sessionToken = getSessionToken();
if (sessionToken) {
ws.send(JSON.stringify({ type: "auth", token: sessionToken }));
}
// Heartbeat — send a ping every 25s to keep the connection alive
if (_heartbeatInterval) clearInterval(_heartbeatInterval);
_heartbeatInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "ping" }));
}
}, 25_000);
});
ws.addEventListener("error", () => {
dispatchStatus("error");
logger.error("WebSocket error");
});
ws.addEventListener("close", (event) => {
// Clean up heartbeat on disconnect
if (_heartbeatInterval) {
clearInterval(_heartbeatInterval);
_heartbeatInterval = null;
}
dispatchStatus("disconnected");
logger.info("Disconnected", { code: event.code, reason: event.reason });
if (!_closed && _listeners.size > 0) {
@@ -338,15 +366,20 @@ export function useDashboardSocket(handlers: WsHandlers) {
ensureConnected();
}
return () => {
return (): void => {
_listeners.delete(wrapper);
_statusCallbacks.delete(setStatus);
if (_listeners.size === 0) {
_closed = true;
if (_reconnectTimer) clearTimeout(_reconnectTimer);
_wsInstance?.close();
_wsInstance = null;
}
// Defer the close so that React Strict Mode double-invoke in dev
// doesn't kill the socket that the remount immediately re-creates.
const delayClose = setTimeout(() => {
if (_listeners.size === 0) {
_closed = true;
if (_reconnectTimer) clearTimeout(_reconnectTimer);
_wsInstance?.close();
_wsInstance = null;
}
}, 100);
delayClose.unref?.();
};
}, []);