feat: migrate Leptos frontend to Next.js 16 (React 19)
Deploy to VPS / deploy (push) Failing after 42s

Complete migration from services/frontend.old/ (Leptos 0.7 WASM + Rust)
to services/frontend/ (Next.js 16 static export + TypeScript + Tailwind v4).

Summary:
- Port all shared types (message, guild, voice, media, dashboard, recording, ui)
- Build fetch-based API client covering all 30+ backend endpoints
- WebSocket client with auto-reconnect (exponential backoff, 20 attempts)
- React context provider for WS with typed event subscription (22 event types)
- Login page with localStorage auth + auto-redirect
- Dashboard layout with sidebar, header (WS status + theme toggle)
- Messages: feed, search, images tab, review tab, channel filter, detail modal
- Live: voice connection, music player, recordings, mic transmit, active speakers
- Dashboard: stats, user list, channel list, detail views
- Mascot chatbot with history + clear
- uiStateApi persistence for selected tab
- Add static export config, update deploy scripts and CI
This commit is contained in:
asepharyana
2026-07-26 11:27:21 +07:00
parent cbbe939fad
commit 5e01ec0806
165 changed files with 5035 additions and 16410 deletions
@@ -0,0 +1,109 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useRef } from "react";
import { uiStateApi } from "@/lib/api";
import { Header } from "@/components/layout/header";
import { MobileTabBar } from "@/components/layout/mobile-tab-bar";
import { Sidebar } from "@/components/layout/sidebar";
import { MascotChatbot } from "@/features/mascot/mascot-chatbot";
import { AuthProvider, useAuth } from "@/lib/hooks/use-auth";
import { WsProvider } from "@/lib/ws/context";
function DashboardGuard({ children }: { children: React.ReactNode }) {
const { authenticated, loading } = useAuth();
const router = useRouter();
useEffect(() => {
if (!loading && !authenticated) {
router.push("/");
}
}, [authenticated, loading, router]);
if (loading) {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="size-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
if (!authenticated) return null;
return <>{children}</>;
}
function DashboardShell({ children }: { children: React.ReactNode }) {
const searchParams = useSearchParams();
const router = useRouter();
const restored = useRef(false);
const activeTab = (searchParams.get("tab") ?? "messages") as
| "messages"
| "live"
| "dashboard";
// Restore persisted tab on mount (only if no explicit tab in URL)
useEffect(() => {
if (restored.current) return;
const tabParam = searchParams.get("tab");
if (tabParam) {
restored.current = true;
return; // explicit tab in URL — don't override
}
uiStateApi
.get()
.then((state) => {
restored.current = true;
const savedTab = state.active_tab;
if (savedTab && savedTab !== activeTab) {
router.replace(`/dashboard?tab=${savedTab}`);
}
})
.catch(() => {
restored.current = true;
});
}, [searchParams, activeTab, router]);
// Persist tab changes
useEffect(() => {
if (!restored.current) return;
uiStateApi.save({ active_tab: activeTab }).catch(() => {});
}, [activeTab]);
return (
<div className="min-h-screen bg-background">
<Sidebar activeTab={activeTab} />
<div className="md:pl-56 flex flex-col min-h-screen">
<Header />
<main className="flex-1 p-4 md:p-6 pb-20 md:pb-6">{children}</main>
</div>
<MobileTabBar activeTab={activeTab} />
</div>
);
}
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<AuthProvider>
<DashboardGuard>
<WsProvider>
<Suspense
fallback={
<div className="flex min-h-screen items-center justify-center">
<div className="size-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
}
>
<DashboardShell>{children}</DashboardShell>
</Suspense>
<MascotChatbot />
</WsProvider>
</DashboardGuard>
</AuthProvider>
);
}
@@ -0,0 +1,20 @@
"use client";
import { useSearchParams } from "next/navigation";
import { DashboardPanel } from "@/features/dashboard/dashboard-panel";
import { LivePanel } from "@/features/live/live-panel";
import { MessagesPanel } from "@/features/messages/messages-panel";
export default function DashboardPage() {
const searchParams = useSearchParams();
const tab = searchParams.get("tab") ?? "messages";
switch (tab) {
case "live":
return <LivePanel />;
case "dashboard":
return <DashboardPanel />;
default:
return <MessagesPanel />;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+130
View File
@@ -0,0 +1,130 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-sans);
--font-mono: var(--font-geist-mono);
--font-heading: var(--font-sans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Bete — Discord Moderation Dashboard",
description: "Live Discord monitoring and AI moderation dashboard",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
suppressHydrationWarning
>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
try {
const theme = localStorage.getItem('theme') || 'dark';
document.documentElement.classList.add(theme);
} catch(e) {}
`,
}}
/>
</head>
<body className="min-h-full flex flex-col">{children}</body>
</html>
);
}
+103
View File
@@ -0,0 +1,103 @@
"use client";
import { Loader2, Shield } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { login } from "@/lib/api";
export default function LoginPage() {
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [checking, setChecking] = useState(true);
const router = useRouter();
useEffect(() => {
const stored = localStorage.getItem("admin-password");
if (stored) {
login(stored)
.then((ok) => {
if (ok) router.replace("/dashboard");
else setChecking(false);
})
.catch(() => setChecking(false));
} else {
setChecking(false);
}
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setLoading(true);
try {
const ok = await login(password);
if (ok) {
localStorage.setItem("admin-password", password);
router.push("/dashboard");
} else {
setError("Invalid password");
}
} catch {
setError("Connection failed. Is the backend running?");
} finally {
setLoading(false);
}
};
if (checking) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-6">
<div className="flex flex-col items-center gap-2 text-center">
<div className="flex size-12 items-center justify-center rounded-full bg-primary/10">
<Shield className="size-6 text-primary" />
</div>
<h1 className="text-2xl font-semibold tracking-tight">Bete</h1>
<p className="text-sm text-muted-foreground">
Discord Moderation Dashboard
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<label
htmlFor="password"
className="text-sm font-medium leading-none"
>
Admin Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter admin password"
className="flex h-9 w-full rounded-lg border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"
disabled={loading}
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<button
type="submit"
disabled={loading || !password}
className="inline-flex w-full items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"
>
{loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
{loading ? "Signing in…" : "Sign in"}
</button>
</form>
</div>
</div>
);
}
@@ -0,0 +1,63 @@
"use client";
import { Moon, Sun, Wifi, WifiOff } from "lucide-react";
import { useEffect, useState } from "react";
import { useWebSocket } from "@/lib/ws/context";
export function Header() {
const { status } = useWebSocket();
const [theme, setTheme] = useState<"light" | "dark">("dark");
useEffect(() => {
const stored = localStorage.getItem("theme") as "light" | "dark" | null;
if (stored) setTheme(stored);
}, []);
const toggleTheme = () => {
const next = theme === "dark" ? "light" : "dark";
setTheme(next);
localStorage.setItem("theme", next);
document.documentElement.classList.remove("light", "dark");
document.documentElement.classList.add(next);
};
return (
<header className="sticky top-0 z-10 flex h-14 items-center gap-4 border-b bg-background px-4 md:px-6">
<div className="flex-1" />
{/* Connection status */}
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
{status === "connected" ? (
<>
<Wifi className="size-3 text-green-500" />
<span className="hidden sm:inline">Connected</span>
</>
) : status === "connecting" ? (
<>
<Wifi className="size-3 text-yellow-500" />
<span className="hidden sm:inline">Connecting</span>
</>
) : (
<>
<WifiOff className="size-3 text-destructive" />
<span className="hidden sm:inline">Disconnected</span>
</>
)}
</div>
{/* Theme toggle */}
<button
type="button"
onClick={toggleTheme}
className="inline-flex size-8 items-center justify-center rounded-lg border hover:bg-muted transition-colors"
aria-label="Toggle theme"
>
{theme === "dark" ? (
<Sun className="size-4" />
) : (
<Moon className="size-4" />
)}
</button>
</header>
);
}
@@ -0,0 +1,35 @@
"use client";
import { LayoutDashboard, MessageSquare, Radio } from "lucide-react";
import { useRouter } from "next/navigation";
const tabs = [
{ id: "messages", label: "Messages", icon: MessageSquare },
{ id: "live", label: "Live", icon: Radio },
{ id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
] as const;
type TabId = (typeof tabs)[number]["id"];
export function MobileTabBar({ activeTab }: { activeTab: TabId }) {
const router = useRouter();
return (
<nav className="md:hidden fixed bottom-0 inset-x-0 z-10 border-t bg-background">
<div className="flex">
{tabs.map(({ id, label, icon: Icon }) => (
<button
key={id}
type="button"
onClick={() => router.push(`/dashboard?tab=${id}`)}
data-active={activeTab === id ? "" : undefined}
className="flex-1 flex flex-col items-center gap-0.5 py-2 text-xs font-medium text-muted-foreground data-[active]:text-primary transition-colors"
>
<Icon className="size-5" />
{label}
</button>
))}
</div>
</nav>
);
}
@@ -0,0 +1,59 @@
"use client";
import { LayoutDashboard, LogOut, MessageSquare, Radio } from "lucide-react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/hooks/use-auth";
const tabs = [
{ id: "messages", label: "Messages", icon: MessageSquare },
{ id: "live", label: "Live", icon: Radio },
{ id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
] as const;
type TabId = (typeof tabs)[number]["id"];
export function Sidebar({ activeTab }: { activeTab: TabId }) {
const { logout } = useAuth();
const router = useRouter();
const handleTabClick = (tabId: TabId) => {
router.push(`/dashboard?tab=${tabId}`);
};
return (
<aside className="hidden md:flex md:w-56 md:flex-col md:fixed md:inset-y-0 border-r bg-sidebar">
<div className="flex h-14 items-center gap-2 border-b px-4">
<div className="size-7 rounded-full bg-primary/10 flex items-center justify-center">
<Radio className="size-4 text-primary" />
</div>
<span className="font-semibold text-sm">Bete</span>
</div>
<nav className="flex-1 space-y-1 p-3">
{tabs.map(({ id, label, icon: Icon }) => (
<button
key={id}
type="button"
onClick={() => handleTabClick(id)}
data-active={activeTab === id ? "" : undefined}
className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground data-[active]:bg-sidebar-accent data-[active]:text-sidebar-accent-foreground"
>
<Icon className="size-4 shrink-0" />
{label}
</button>
))}
</nav>
<div className="border-t p-3">
<button
type="button"
onClick={logout}
className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground transition-colors"
>
<LogOut className="size-4 shrink-0" />
Sign out
</button>
</div>
</aside>
);
}
@@ -0,0 +1,58 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant = "default",
size = "default",
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
@@ -0,0 +1,676 @@
"use client";
import {
AlertCircle,
ArrowLeft,
BarChart3,
ChevronRight,
Hash,
RefreshCw,
Search,
Shield,
Users,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { dashboardApi } from "@/lib/api";
import type {
DashboardChannel,
DashboardChannelDetail,
DashboardStats,
DashboardUser,
DashboardUserDetail,
} from "@/lib/types";
type View = "stats" | "users" | "channels" | "user-detail" | "channel-detail";
export function DashboardPanel() {
const [view, setView] = useState<View>("stats");
const [activeUser, setActiveUser] = useState<DashboardUserDetail | null>(
null,
);
const [activeChannel, setActiveChannel] =
useState<DashboardChannelDetail | null>(null);
const renderView = () => {
switch (view) {
case "stats":
return <StatsView onNavigate={(v) => setView(v)} />;
case "users":
return (
<UsersView
onSelectUser={async (userId) => {
try {
const detail = await dashboardApi.getUserDetail(userId);
setActiveUser(detail);
setView("user-detail");
} catch {
// ignore
}
}}
/>
);
case "channels":
return (
<ChannelsView
onSelectChannel={async (channelId) => {
try {
const detail = await dashboardApi.getChannelDetail(channelId);
setActiveChannel(detail);
setView("channel-detail");
} catch {
// ignore
}
}}
/>
);
case "user-detail":
return activeUser ? (
<UserDetailView user={activeUser} onBack={() => setView("users")} />
) : (
<UsersView onSelectUser={() => {}} />
);
case "channel-detail":
return activeChannel ? (
<ChannelDetailView
channel={activeChannel}
onBack={() => setView("channels")}
/>
) : (
<ChannelsView onSelectChannel={() => {}} />
);
}
};
return (
<div className="space-y-4">
{/* Sub-navigation */}
<div className="flex gap-1 rounded-lg border p-1 w-fit">
<button
onClick={() => setView("stats")}
data-active={view === "stats" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<BarChart3 className="size-4 inline mr-1.5" />
Stats
</button>
<button
onClick={() => setView("users")}
data-active={
view === "users" || view === "user-detail" ? "" : undefined
}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Users className="size-4 inline mr-1.5" />
Users
</button>
<button
onClick={() => setView("channels")}
data-active={
view === "channels" || view === "channel-detail" ? "" : undefined
}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Hash className="size-4 inline mr-1.5" />
Channels
</button>
</div>
{renderView()}
</div>
);
}
// ── Stats View ────────────────────────────────────────────
function StatsView({ onNavigate }: { onNavigate: (view: View) => void }) {
const [stats, setStats] = useState<DashboardStats | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchStats = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await dashboardApi.getStats();
setStats(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load stats");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchStats();
}, [fetchStats]);
if (error) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<AlertCircle className="size-8 text-destructive mb-2" />
<p className="text-sm text-muted-foreground mb-4">{error}</p>
<button
onClick={fetchStats}
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Retry
</button>
</div>
);
}
return (
<div className="space-y-4">
{/* Metric cards */}
{loading ? (
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="rounded-lg border p-4 space-y-2">
<div className="h-3 w-16 bg-muted rounded animate-pulse" />
<div className="h-8 w-20 bg-muted rounded animate-pulse" />
</div>
))}
</div>
) : stats ? (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<MetricCard label="Total Messages" value={stats.total_messages} />
<MetricCard label="Today" value={stats.today_messages} />
<MetricCard label="Users" value={stats.total_users} />
<MetricCard label="Active 24h" value={stats.active_users_24h} />
<MetricCard
label="Flagged"
value={stats.total_flagged}
variant="destructive"
/>
<MetricCard
label="Clean"
value={stats.total_clean}
variant="success"
/>
<MetricCard
label="Voice Recordings"
value={stats.total_voice_recordings}
/>
<MetricCard label="AI Profiles" value={stats.total_profiles} />
</div>
{/* Top Channels + Moderation Queue */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Hash className="size-4 text-muted-foreground" />
Top Channels
</h3>
{stats.top_channels.length === 0 ? (
<p className="text-sm text-muted-foreground">
No channel data yet.
</p>
) : (
<div className="space-y-2">
{stats.top_channels.map((ch) => (
<div
key={ch.channel_id}
className="flex items-center justify-between"
>
<span className="text-sm truncate">
#{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</span>
<span className="text-sm font-semibold">
{formatNumber(ch.message_count)}
</span>
</div>
))}
</div>
)}
</div>
<div className="rounded-lg border p-4 space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Shield className="size-4 text-muted-foreground" />
Moderation Queue
</h3>
<div className="grid grid-cols-3 gap-3">
<div className="rounded-lg bg-muted p-3 text-center space-y-1">
<div className="text-2xl font-semibold">
{stats.moderation_overview.pending}
</div>
<div className="text-xs text-muted-foreground">Pending</div>
</div>
<div className="rounded-lg bg-yellow-500/10 p-3 text-center space-y-1">
<div className="text-2xl font-semibold text-yellow-600 dark:text-yellow-400">
{stats.moderation_overview.processing}
</div>
<div className="text-xs text-muted-foreground">
Processing
</div>
</div>
<div className="rounded-lg bg-destructive/10 p-3 text-center space-y-1">
<div className="text-2xl font-semibold text-destructive">
{stats.moderation_overview.error}
</div>
<div className="text-xs text-muted-foreground">Errors</div>
</div>
</div>
</div>
</div>
</>
) : null}
</div>
);
}
function MetricCard({
label,
value,
variant,
}: {
label: string;
value: number;
variant?: "default" | "destructive" | "success";
}) {
const colorMap = {
default: "",
destructive: "text-destructive",
success: "text-green-600 dark:text-green-400",
};
return (
<div className="rounded-lg border p-4 space-y-1">
<p className="text-xs text-muted-foreground">{label}</p>
<p className={`text-2xl font-semibold ${colorMap[variant ?? "default"]}`}>
{formatNumber(value)}
</p>
</div>
);
}
// ── Users View ────────────────────────────────────────────
function UsersView({
onSelectUser,
}: {
onSelectUser: (userId: string) => void;
}) {
const [users, setUsers] = useState<DashboardUser[]>([]);
const [loading, setLoading] = useState(true);
const [_cursor, setCursor] = useState<string | null>(null);
const [search, setSearch] = useState("");
const fetchUsers = useCallback(async (searchQuery?: string) => {
setLoading(true);
try {
const result = await dashboardApi.listUsers(20, undefined, searchQuery);
setUsers(result.data);
setCursor(result.nextCursor);
} catch {
// ignore
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchUsers();
}, [fetchUsers]);
useEffect(() => {
const timer = setTimeout(() => {
if (search) fetchUsers(search);
else fetchUsers();
}, 300);
return () => clearTimeout(timer);
}, [search, fetchUsers]);
return (
<div className="space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input
type="text"
placeholder="Search users…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm"
/>
</div>
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="rounded-lg border p-4 space-y-2">
<div className="flex items-center gap-3">
<div className="size-10 rounded-full bg-muted animate-pulse" />
<div className="flex-1 space-y-1">
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
<div className="h-3 w-16 bg-muted rounded animate-pulse" />
</div>
</div>
</div>
))}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{users.map((user) => (
<button
key={user.user_id}
onClick={() => onSelectUser(user.user_id)}
className="rounded-lg border p-4 text-left hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-3">
<div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden">
{user.avatar_url ? (
<img
src={user.avatar_url}
alt=""
className="size-full object-cover"
/>
) : (
(user.username ?? "?").charAt(0).toUpperCase()
)}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{user.username ?? "Unknown"}
</p>
<p className="text-xs text-muted-foreground">
{user.total_messages} msgs
{user.flagged_count > 0 && (
<span className="text-destructive ml-2">
{user.flagged_count} flagged
</span>
)}
</p>
</div>
<ChevronRight className="size-4 text-muted-foreground shrink-0" />
</div>
</button>
))}
</div>
)}
</div>
);
}
// ── Channels View ─────────────────────────────────────────
function ChannelsView({
onSelectChannel,
}: {
onSelectChannel: (channelId: string) => void;
}) {
const [channels, setChannels] = useState<DashboardChannel[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState("");
const fetchChannels = useCallback(async (searchQuery?: string) => {
setLoading(true);
try {
const result = await dashboardApi.listChannels(20, searchQuery);
setChannels(result.data);
} catch {
// ignore
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchChannels();
}, [fetchChannels]);
useEffect(() => {
const timer = setTimeout(() => {
if (search) fetchChannels(search);
else fetchChannels();
}, 300);
return () => clearTimeout(timer);
}, [search, fetchChannels]);
return (
<div className="space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input
type="text"
placeholder="Search channels…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm"
/>
</div>
{loading ? (
<div className="space-y-2">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="rounded-lg border p-4 space-y-2">
<div className="h-4 w-32 bg-muted rounded animate-pulse" />
<div className="h-3 w-24 bg-muted rounded animate-pulse" />
</div>
))}
</div>
) : (
<div className="space-y-2">
{channels.map((ch) => (
<button
key={ch.channel_id}
onClick={() => onSelectChannel(ch.channel_id)}
className="w-full rounded-lg border p-4 text-left hover:bg-muted/50 transition-colors"
>
<div className="flex items-center justify-between">
<div className="min-w-0">
<p className="text-sm font-medium truncate">
#{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</p>
<p className="text-xs text-muted-foreground">
{ch.total_messages} messages
{ch.flagged_count > 0 && (
<span className="text-destructive ml-2">
{ch.flagged_count} flagged
</span>
)}
</p>
</div>
<ChevronRight className="size-4 text-muted-foreground shrink-0" />
</div>
{ch.culture_summary && (
<p className="text-xs text-muted-foreground mt-2 italic line-clamp-2">
{ch.culture_summary}
</p>
)}
</button>
))}
</div>
)}
</div>
);
}
// ── User Detail View ──────────────────────────────────────
function UserDetailView({
user,
onBack,
}: {
user: DashboardUserDetail;
onBack: () => void;
}) {
return (
<div className="space-y-4">
<button
onClick={onBack}
className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="size-4" />
Back to users
</button>
<div className="rounded-lg border p-6 space-y-4">
<div className="flex items-center gap-4">
<div className="size-16 rounded-full bg-muted flex items-center justify-center text-xl font-medium overflow-hidden">
{user.avatar_url ? (
<img
src={user.avatar_url}
alt=""
className="size-full object-cover"
/>
) : (
(user.username ?? "?").charAt(0).toUpperCase()
)}
</div>
<div>
<h2 className="text-xl font-semibold">
{user.username ?? "Unknown"}
</h2>
<p className="text-sm text-muted-foreground">#{user.user_id}</p>
</div>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<DetailStat label="Messages" value={user.total_messages} />
<DetailStat
label="Flagged"
value={user.flagged_count}
variant="destructive"
/>
<DetailStat label="Clean Streak" value={user.clean_message_streak} />
<DetailStat
label="Trust Score"
value={user.trust_score ?? 0}
suffix="%"
/>
</div>
{user.profile_summary && (
<div className="rounded-lg bg-muted/50 p-3">
<p className="text-xs text-muted-foreground mb-1">AI Profile</p>
<p className="text-sm">{user.profile_summary}</p>
</div>
)}
{/* Recent messages */}
{user.recent_messages.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold">Recent Messages</h3>
{user.recent_messages.slice(0, 5).map((msg) => (
<div key={msg.id} className="rounded-lg border p-3">
<p className="text-xs text-muted-foreground mb-1">
{new Date(msg.created_at).toLocaleString()}
</p>
<p className="text-sm">{msg.content}</p>
</div>
))}
</div>
)}
</div>
</div>
);
}
// ── Channel Detail View ───────────────────────────────────
function ChannelDetailView({
channel,
onBack,
}: {
channel: DashboardChannelDetail;
onBack: () => void;
}) {
return (
<div className="space-y-4">
<button
onClick={onBack}
className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="size-4" />
Back to channels
</button>
<div className="rounded-lg border p-6 space-y-4">
<div>
<h2 className="text-xl font-semibold">
#{channel.channel_name ?? channel.channel_id.slice(0, 8)}
</h2>
<p className="text-sm text-muted-foreground">{channel.channel_id}</p>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<DetailStat label="Messages" value={channel.total_messages} />
<DetailStat
label="Flagged"
value={channel.flagged_count}
variant="destructive"
/>
<DetailStat
label="Clean"
value={channel.clean_count}
variant="success"
/>
</div>
{channel.culture_summary && (
<div className="rounded-lg bg-muted/50 p-3">
<p className="text-xs text-muted-foreground mb-1">
Channel Culture
</p>
<p className="text-sm">{channel.culture_summary}</p>
</div>
)}
{channel.recent_messages.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold">Recent Messages</h3>
{channel.recent_messages.slice(0, 5).map((msg) => (
<div key={msg.id} className="rounded-lg border p-3">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium">{msg.username}</span>
<span className="text-xs text-muted-foreground">
{new Date(msg.created_at).toLocaleString()}
</span>
</div>
<p className="text-sm">{msg.content}</p>
</div>
))}
</div>
)}
</div>
</div>
);
}
// ── Shared Components ─────────────────────────────────────
function DetailStat({
label,
value,
variant,
suffix,
}: {
label: string;
value: number;
variant?: "default" | "destructive" | "success";
suffix?: string;
}) {
const colorMap = {
default: "",
destructive: "text-destructive",
success: "text-green-600 dark:text-green-400",
};
return (
<div className="rounded-lg border p-3">
<p className="text-xs text-muted-foreground">{label}</p>
<p className={`text-lg font-semibold ${colorMap[variant ?? "default"]}`}>
{formatNumber(value)}
{suffix}
</p>
</div>
);
}
// ── Helpers ───────────────────────────────────────────────
function formatNumber(n: number): string {
return n.toLocaleString();
}
@@ -0,0 +1,535 @@
"use client";
import {
Disc3,
Download,
Loader2,
Mic,
MicOff,
Play,
Radio,
RadioOff,
SkipForward,
Square,
Trash2,
Volume2,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { recordingsApi, voiceApi } from "@/lib/api";
import type {
ActiveSpeaker,
MediaState,
VoiceRecording,
VoiceStatus,
} from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context";
export function LivePanel() {
const ws = useWebSocket();
// Voice
const [voiceStatus, setVoiceStatus] = useState<VoiceStatus | null>(null);
const [speakers, setSpeakers] = useState<ActiveSpeaker[]>([]);
const [guilds, setGuilds] = useState<Array<{ id: string; name: string }>>([]);
const [voiceChannels, setVoiceChannels] = useState<
Array<{ id: string; name: string }>
>([]);
const [selectedGuild, setSelectedGuild] = useState("");
const [selectedChannel, setSelectedChannel] = useState("");
const [voiceLoading, setVoiceLoading] = useState(false);
const [micActive, setMicActive] = useState(false);
// Media
const [mediaState, setMediaState] = useState<MediaState | null>(null);
const [queueUrl, setQueueUrl] = useState("");
// Recordings
const [recordings, setRecordings] = useState<VoiceRecording[]>([]);
const [_recordingsCursor, setRecordingsCursor] = useState<string | null>(
null,
);
const [_recordingsHasMore, setRecordingsHasMore] = useState(false);
const fetchVoiceStatus = useCallback(async () => {
try {
const status = await voiceApi.getStatus();
setVoiceStatus(status);
} catch {
// ignore
}
}, []);
const fetchGuilds = useCallback(async () => {
try {
const g = await voiceApi.getGuilds();
setGuilds(g);
} catch {
// ignore
}
}, []);
const fetchRecordings = useCallback(async () => {
try {
const result = await recordingsApi.list(20);
setRecordings(result.items);
setRecordingsCursor(result.nextCursor);
setRecordingsHasMore(result.hasMore);
} catch {
// ignore
}
}, []);
useEffect(() => {
fetchVoiceStatus();
fetchGuilds();
fetchRecordings();
}, [fetchVoiceStatus, fetchGuilds, fetchRecordings]);
// Media status
const fetchMediaStatus = useCallback(async () => {
try {
const state = await voiceApi.getMediaStatus();
setMediaState(state);
} catch {
// ignore
}
}, []);
useEffect(() => {
fetchMediaStatus();
}, [fetchMediaStatus]);
// WS subscriptions
useEffect(() => {
const unsubSpeaker = ws.on("voice_active_user", (user) => {
const speaker = user as ActiveSpeaker;
setSpeakers((prev) => {
const existing = prev.findIndex((s) => s.user_id === speaker.user_id);
if (existing >= 0) {
const next = [...prev];
next[existing] = speaker;
return next;
}
return [...prev, speaker];
});
});
const unsubMedia = ws.on("media_state", (state) => {
setMediaState(state as MediaState);
});
const unsubRecording = ws.on("voice_recording_uploaded", (rec) => {
setRecordings((prev) => [rec as VoiceRecording, ...prev]);
});
return () => {
unsubSpeaker();
unsubMedia();
unsubRecording();
};
}, [ws]);
// Voice connect handler
const handleGuildChange = useCallback(async (guildId: string) => {
setSelectedGuild(guildId);
setSelectedChannel("");
if (!guildId) {
setVoiceChannels([]);
return;
}
try {
const channels = await voiceApi.getVoiceChannels(guildId);
setVoiceChannels(channels);
} catch {
setVoiceChannels([]);
}
}, []);
const handleConnect = useCallback(async () => {
if (!selectedGuild || !selectedChannel) return;
setVoiceLoading(true);
try {
const status = await voiceApi.connect(selectedGuild, selectedChannel);
setVoiceStatus(status);
} finally {
setVoiceLoading(false);
}
}, [selectedGuild, selectedChannel]);
const handleDisconnect = useCallback(async () => {
setVoiceLoading(true);
try {
const status = await voiceApi.disconnect();
setVoiceStatus(status);
} finally {
setVoiceLoading(false);
}
}, []);
// Media handlers
const handleQueueMedia = useCallback(async () => {
if (!queueUrl.trim()) return;
try {
const state = await voiceApi.mediaQueue(queueUrl.trim(), "music");
setMediaState(state);
setQueueUrl("");
} catch {
// ignore
}
}, [queueUrl]);
const handleSkip = useCallback(async () => {
try {
const state = await voiceApi.mediaSkip();
setMediaState(state);
} catch {
// ignore
}
}, []);
const handleStop = useCallback(async () => {
try {
const state = await voiceApi.mediaStop();
setMediaState(state);
} catch {
// ignore
}
}, []);
const handleVolume = useCallback(async (volume: number) => {
try {
const state = await voiceApi.mediaVolume(volume);
setMediaState(state);
} catch {
// ignore
}
}, []);
// Delete recording
const handleDeleteRecording = useCallback(async (id: string) => {
try {
await recordingsApi.delete(id);
setRecordings((prev) => prev.filter((r) => r.id !== id));
} catch {
// ignore
}
}, []);
return (
<div className="space-y-6">
{/* Voice Connection */}
<div className="rounded-lg border p-4 space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold flex items-center gap-2">
<Radio className="size-4" />
Voice Connection
</h2>
<span
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
voiceStatus?.connected
? "bg-green-500/15 text-green-600 dark:text-green-400"
: "bg-muted text-muted-foreground"
}`}
>
{voiceStatus?.connected ? "Connected" : "Disconnected"}
</span>
</div>
{voiceStatus?.connected && voiceStatus.activeChannelName && (
<p className="text-sm text-muted-foreground">
Connected to{" "}
<span className="font-medium text-foreground">
{voiceStatus.activeChannelName}
</span>
</p>
)}
<div className="flex flex-col sm:flex-row gap-2">
<select
value={selectedGuild}
onChange={(e) => handleGuildChange(e.target.value)}
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm"
>
<option value="">Select guild</option>
{guilds.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</select>
<select
value={selectedChannel}
onChange={(e) => setSelectedChannel(e.target.value)}
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm"
>
<option value="">Select channel</option>
{voiceChannels.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
{voiceStatus?.connected ? (
<button
onClick={handleDisconnect}
disabled={voiceLoading}
className="inline-flex items-center gap-2 rounded-lg bg-destructive px-4 py-1.5 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors disabled:opacity-50"
>
{voiceLoading ? (
<Loader2 className="size-4 animate-spin" />
) : (
<RadioOff className="size-4" />
)}
Disconnect
</button>
) : (
<button
onClick={handleConnect}
disabled={voiceLoading || !selectedGuild || !selectedChannel}
className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
{voiceLoading ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Radio className="size-4" />
)}
Connect
</button>
)}
</div>
</div>
{/* Active Speakers */}
{speakers.filter((s) => s.speaking).length > 0 && (
<div className="rounded-lg border p-4 space-y-3">
<h3 className="text-sm font-semibold">Active Speakers</h3>
<div className="flex flex-wrap gap-2">
{speakers
.filter((s) => s.speaking)
.map((s) => (
<div
key={s.user_id}
className="flex items-center gap-2 rounded-full border bg-muted/50 px-3 py-1.5"
>
<span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-green-400 opacity-75" />
<span className="relative inline-flex size-2 rounded-full bg-green-500" />
</span>
<span className="text-sm">{s.username}</span>
</div>
))}
</div>
</div>
)}
{/* Music Player */}
<div className="rounded-lg border p-4 space-y-4">
<h2 className="text-sm font-semibold flex items-center gap-2">
<Disc3 className="size-4" />
Music Player
</h2>
{/* Queue URL */}
<div className="flex gap-2">
<input
type="text"
placeholder="Queue a URL (YouTube, audio file…)"
value={queueUrl}
onChange={(e) => setQueueUrl(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleQueueMedia()}
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm"
/>
<button
onClick={handleQueueMedia}
disabled={!queueUrl.trim()}
className="inline-flex items-center gap-2 rounded-lg bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
<Play className="size-4" />
Queue
</button>
</div>
{/* Now Playing */}
{mediaState?.current && (
<div className="rounded-lg bg-muted/50 p-3 space-y-2">
<p className="text-xs text-muted-foreground">Now Playing</p>
<div className="flex items-start gap-3">
{mediaState.current.thumbnailUrl && (
<img
src={mediaState.current.thumbnailUrl}
alt=""
className="size-12 rounded object-cover"
/>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{mediaState.current.title ?? mediaState.current.source}
</p>
<p className="text-xs text-muted-foreground">
{mediaState.current.durationMs
? `${Math.floor(mediaState.current.durationMs / 60000)}:${String(
Math.floor(
(mediaState.current.durationMs % 60000) / 1000,
),
).padStart(2, "0")}`
: "Live"}
</p>
</div>
</div>
</div>
)}
{/* Controls */}
<div className="flex items-center gap-2">
<button
onClick={handleStop}
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<Square className="size-4" />
Stop
</button>
<button
onClick={handleSkip}
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<SkipForward className="size-4" />
Skip
</button>
<div className="flex items-center gap-2 ml-auto">
<Volume2 className="size-4 text-muted-foreground" />
<input
type="range"
min="0"
max="1"
step="0.05"
value={mediaState?.musicVolume ?? 0.5}
onChange={(e) => handleVolume(Number(e.target.value))}
className="w-24 h-2"
/>
</div>
</div>
{/* Queue */}
{mediaState && mediaState.queue.length > 0 && (
<div className="space-y-1">
<p className="text-xs text-muted-foreground">
Queue ({mediaState.queue.length})
</p>
{mediaState.queue.map((item, i) => (
<div
key={item.id ?? i}
className="flex items-center gap-2 rounded-md bg-muted/30 px-3 py-2"
>
<span className="text-xs text-muted-foreground w-4">
{i + 1}.
</span>
<span className="text-sm truncate flex-1">
{item.title ?? item.source}
</span>
</div>
))}
</div>
)}
</div>
{/* Recordings */}
<div className="rounded-lg border p-4 space-y-3">
<h2 className="text-sm font-semibold">Voice Recordings</h2>
{recordings.length === 0 ? (
<p className="text-sm text-muted-foreground">No recordings yet.</p>
) : (
<div className="space-y-2">
{recordings.map((rec) => (
<div
key={rec.id}
className="flex items-center gap-3 rounded-lg border p-3"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{rec.username}</p>
<p className="text-xs text-muted-foreground">
{rec.channel_name ?? rec.channel_id ?? "Unknown channel"}
{" — "}
{new Date(rec.created_at).toLocaleString()}
</p>
</div>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{formatBytes(rec.size_bytes)}
</span>
{rec.download_url && (
<a
href={rec.download_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center rounded-md border p-1.5 hover:bg-muted transition-colors"
>
<Download className="size-4" />
</a>
)}
<button
onClick={() => handleDeleteRecording(rec.id)}
className="inline-flex items-center rounded-md border p-1.5 hover:bg-destructive/10 hover:text-destructive transition-colors"
>
<Trash2 className="size-4" />
</button>
</div>
))}
</div>
)}
</div>
{/* Microphone Transmit */}
<div className="rounded-lg border p-4 space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold flex items-center gap-2">
<Mic className="size-4" />
Microphone
</h2>
<button
type="button"
onClick={async () => {
setMicActive(!micActive);
try {
await voiceApi.sendCommand(
micActive
? "voice:transmit:stop"
: "voice:transmit:start",
);
} catch {
setMicActive(micActive);
}
}}
disabled={!voiceStatus?.connected}
data-active={micActive ? "" : undefined}
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-destructive data-[active]:text-destructive-foreground hover:bg-muted disabled:opacity-50"
>
{micActive ? (
<MicOff className="size-4" />
) : (
<Mic className="size-4" />
)}
{micActive ? "Stop" : "Start"}
</button>
</div>
{!voiceStatus?.connected && (
<p className="text-xs text-muted-foreground">
Connect to a voice channel first.
</p>
)}
{micActive && (
<div className="flex items-center gap-2">
<span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-red-400 opacity-75" />
<span className="relative inline-flex size-2 rounded-full bg-red-500" />
</span>
<span className="text-sm text-muted-foreground">Transmitting</span>
</div>
)}
</div>
</div>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
@@ -0,0 +1,176 @@
"use client";
import { Bot, Loader2, MessageCircle, Send, Trash2, User, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { mascotApi } from "@/lib/api";
import type { ChatHistoryMessage } from "@/lib/types";
export function MascotChatbot() {
const [open, setOpen] = useState(false);
const [messages, setMessages] = useState<ChatHistoryMessage[]>([]);
const [input, setInput] = useState("");
const [sending, setSending] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
mascotApi
.getHistory()
.then(setMessages)
.catch(() => {});
}, [open]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages]);
const handleClear = useCallback(async () => {
try {
await mascotApi.clearHistory();
setMessages([]);
} catch {
// ignore
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || sending) return;
setSending(true);
const text = input.trim();
setInput("");
// Add optimistic user message
setMessages((prev) => [
...prev,
{ role: "user", content: text, timestamp: new Date().toISOString() },
]);
try {
const resp = await mascotApi.send(text);
setMessages((prev) => [
...prev,
{
role: "assistant",
content: resp.response,
timestamp: resp.timestamp,
},
]);
} catch {
setMessages((prev) => [
...prev,
{
role: "assistant",
content: "Sorry, I couldn't process that request.",
timestamp: new Date().toISOString(),
},
]);
} finally {
setSending(false);
}
}, [input, sending]);
return (
<>
{/* Toggle button */}
<button
onClick={() => setOpen(!open)}
className="fixed bottom-4 right-4 z-50 flex size-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors"
aria-label={open ? "Close chat" : "Open chat"}
>
{open ? <X className="size-5" /> : <MessageCircle className="size-5" />}
</button>
{/* Chat panel */}
{open && (
<div className="fixed bottom-20 right-4 z-50 flex w-80 flex-col rounded-lg border bg-background shadow-xl overflow-hidden">
{/* Header */}
<div className="flex items-center gap-2 border-b p-3">
<Bot className="size-5 text-primary" />
<span className="text-sm font-semibold flex-1">Mascot</span>
{messages.length > 0 && (
<button
type="button"
onClick={handleClear}
className="inline-flex size-6 items-center justify-center rounded hover:bg-muted transition-colors"
title="Clear history"
>
<Trash2 className="size-3.5 text-muted-foreground" />
</button>
)}
</div>
{/* Messages */}
<div
ref={scrollRef}
className="flex-1 space-y-3 overflow-y-auto p-3 max-h-80"
>
{messages.length === 0 && (
<p className="text-center text-xs text-muted-foreground py-8">
Ask me anything about the server!
</p>
)}
{messages.map((msg, i) => (
<div
key={i}
className={`flex items-start gap-2 ${
msg.role === "user" ? "flex-row-reverse" : ""
}`}
>
<div className="size-6 shrink-0 rounded-full bg-muted flex items-center justify-center">
{msg.role === "user" ? (
<User className="size-3" />
) : (
<Bot className="size-3" />
)}
</div>
<div
className={`rounded-lg px-3 py-2 text-sm max-w-[80%] ${
msg.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted"
}`}
>
{msg.content}
</div>
</div>
))}
{sending && (
<div className="flex items-center gap-2">
<div className="size-6 shrink-0 rounded-full bg-muted flex items-center justify-center">
<Bot className="size-3" />
</div>
<div className="rounded-lg bg-muted px-3 py-2">
<Loader2 className="size-4 animate-spin" />
</div>
</div>
)}
</div>
{/* Input */}
<div className="border-t p-3">
<div className="flex gap-2">
<input
type="text"
placeholder="Ask the mascot…"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSend()}
className="flex-1 h-8 rounded-md border border-input bg-background px-2 text-sm"
disabled={sending}
/>
<button
onClick={handleSend}
disabled={!input.trim() || sending}
className="inline-flex size-8 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
<Send className="size-4" />
</button>
</div>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,769 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { messagesApi, voiceApi } from "@/lib/api";
import type { MessageRecord, Channel, AttachmentRecord } from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context";
import {
Search,
RefreshCw,
Loader2,
AlertCircle,
Flag,
X,
Download,
ExternalLink,
} from "lucide-react";
import { useAppConfig } from "@/lib/hooks/use-config";
export function MessagesPanel() {
const { config } = useAppConfig();
const guildId = config?.monitorGuildId ?? "";
const [messages, setMessages] = useState<MessageRecord[]>([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [cursor, setCursor] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState<MessageRecord[] | null>(null);
const [searching, setSearching] = useState(false);
const [viewTab, setViewTab] = useState<"all" | "images" | "review">("all");
const [imageMessages, setImageMessages] = useState<MessageRecord[]>([]);
const [reviewMessages, setReviewMessages] = useState<MessageRecord[]>([]);
const [channels, setChannels] = useState<Channel[]>([]);
const [detailMessage, setDetailMessage] = useState<MessageRecord | null>(null);
const [detailAttachments, setDetailAttachments] = useState<AttachmentRecord[]>([]);
const [detailLoading, setDetailLoading] = useState(false);
const [selectedChannel, setSelectedChannel] = useState("");
const ws = useWebSocket();
// Fetch available text channels for filtering
useEffect(() => {
if (!guildId) return;
voiceApi.getTextChannels(guildId).then(setChannels).catch(() => {});
}, [guildId]);
// Fetch initial messages
const fetchMessages = useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await messagesApi.list(guildId, 50, selectedChannel || undefined);
setMessages(result.data);
setCursor(result.nextCursor);
setHasMore(result.nextCursor !== null);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load messages");
} finally {
setLoading(false);
}
}, [guildId, selectedChannel]);
// Fetch image messages
const fetchImages = useCallback(async () => {
try {
const result = await messagesApi.getImages(guildId, 50);
setImageMessages(result.data);
} catch {
// silently fail
}
}, [guildId]);
// Fetch review (flagged) messages
const fetchReview = useCallback(async () => {
try {
const result = await messagesApi.getReview(50, selectedChannel || undefined);
setReviewMessages(result.results);
} catch {
// silently fail
}
}, [selectedChannel]);
useEffect(() => {
fetchMessages();
fetchImages();
}, [fetchMessages, fetchImages]);
useEffect(() => {
if (viewTab === "review") fetchReview();
}, [viewTab, fetchReview]);
// WS subscription for real-time message updates
useEffect(() => {
const unsubCreated = ws.on("message_created", (msg) => {
setMessages((prev) => [msg as MessageRecord, ...prev]);
});
const unsubUpdated = ws.on("message_updated", (msg) => {
setMessages((prev) =>
prev.map((m) =>
(msg as MessageRecord).id === m.id ? (msg as MessageRecord) : m,
),
);
});
const unsubDeleted = ws.on("message_deleted", (id) => {
setMessages((prev) =>
prev.filter((m) => m.id !== (id as unknown as string)),
);
});
const unsubAnalyzed = ws.on("message_analyzed", (msg) => {
setMessages((prev) =>
prev.map((m) =>
(msg as MessageRecord).id === m.id ? (msg as MessageRecord) : m,
),
);
});
return () => {
unsubCreated();
unsubUpdated();
unsubDeleted();
unsubAnalyzed();
};
}, [ws]);
// Search handler
const handleSearch = useCallback(async () => {
if (!searchQuery.trim()) {
setSearchResults(null);
return;
}
setSearching(true);
try {
const result = await messagesApi.search(searchQuery, 50);
setSearchResults(result.results);
} catch {
setSearchResults([]);
} finally {
setSearching(false);
}
}, [searchQuery]);
// Load more (cursor pagination)
const handleLoadMore = useCallback(async () => {
if (!cursor || loadingMore) return;
setLoadingMore(true);
try {
const result = await messagesApi.list(guildId, 50, selectedChannel || undefined, cursor);
setMessages((prev) => [...prev, ...result.data]);
setCursor(result.nextCursor);
setHasMore(result.nextCursor !== null);
} catch {
// ignore
} finally {
setLoadingMore(false);
}
}, [cursor, loadingMore, guildId, selectedChannel]);
const handleMessageClick = useCallback(async (id: string) => {
setDetailLoading(true);
setDetailAttachments([]);
try {
const detail = await messagesApi.getDetail(id);
setDetailMessage(detail);
// Try to fetch attachments too
if (detail.channel_id && id) {
messagesApi
.getAttachments(detail.channel_id, 10)
.then((res) => setDetailAttachments(res.data))
.catch(() => {});
}
} catch {
setDetailMessage(null);
} finally {
setDetailLoading(false);
}
}, []);
const handleReanalyze = useCallback(async (id: string) => {
try {
await messagesApi.reanalyze(id);
} catch {
// ignore
}
}, []);
const handleReanalyzeBatch = useCallback(async () => {
try {
await messagesApi.reanalyzeBatch();
} catch {
// ignore
}
}, []);
const displayMessages = searchResults ?? messages;
const isEmpty = !loading && displayMessages.length === 0;
// Render
if (error) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<AlertCircle className="size-8 text-destructive mb-2" />
<p className="text-sm text-muted-foreground mb-4">{error}</p>
<button
onClick={fetchMessages}
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Retry
</button>
</div>
);
}
return (
<div className="space-y-4">
{/* Search + toolbar */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input
type="text"
placeholder="Search messages…"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
/>
</div>
{/* Channel filter */}
{channels.length > 0 && (
<select
value={selectedChannel}
onChange={(e) => setSelectedChannel(e.target.value)}
className="h-9 rounded-lg border border-input bg-background px-3 text-sm"
>
<option value="">All channels</option>
{channels.map((ch) => (
<option key={ch.id} value={ch.id}>
#{ch.name}
</option>
))}
</select>
)}
<button
onClick={handleReanalyzeBatch}
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Reanalyze Errors
</button>
</div>
{/* Tab bar */}
<div className="flex gap-1 rounded-lg border p-1 w-fit">
<button
type="button"
onClick={() => setViewTab("all")}
data-active={viewTab === "all" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
All ({messages.length})
</button>
<button
type="button"
onClick={() => setViewTab("images")}
data-active={viewTab === "images" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
Images
</button>
<button
type="button"
onClick={() => setViewTab("review")}
data-active={viewTab === "review" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Flag className="size-3.5 inline mr-1" />
Review ({reviewMessages.length})
</button>
</div>
{/* Search results count */}
{searchResults !== null && (
<p className="text-sm text-muted-foreground">
Found {searchResults.length} result
{searchResults.length !== 1 ? "s" : ""}
</p>
)}
{/* Messages feed */}
{viewTab === "all" ? (
<div className="space-y-2">
{loading ? (
<div className="space-y-3">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex gap-3 rounded-lg border p-4">
<div className="size-8 shrink-0 rounded-full bg-muted animate-pulse" />
<div className="flex-1 space-y-2">
<div className="h-4 w-32 bg-muted rounded animate-pulse" />
<div className="h-3 w-full bg-muted rounded animate-pulse" />
<div className="h-3 w-3/4 bg-muted rounded animate-pulse" />
</div>
</div>
))}
</div>
) : isEmpty ? (
<div className="flex flex-col items-center justify-center py-16 text-center">
<p className="text-sm text-muted-foreground">
{searchResults !== null
? "No messages found matching your search."
: "No captures yet."}
</p>
</div>
) : (
<>
{displayMessages.map((msg) => (
<MessageCard
key={msg.id}
message={msg}
onClick={handleMessageClick}
onReanalyze={handleReanalyze}
/>
))}
{/* Load more */}
{hasMore && searchResults === null && (
<div className="flex justify-center py-4">
<button
type="button"
onClick={handleLoadMore}
disabled={loadingMore}
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors disabled:opacity-50"
>
{loadingMore ? (
<Loader2 className="size-4 animate-spin" />
) : null}
{loadingMore ? "Loading…" : "Load more"}
</button>
</div>
)}
</>
)}
</div>
) : viewTab === "images" ? (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
{imageMessages.map((msg) => (
<div
key={msg.id}
className="aspect-square rounded-lg border bg-muted overflow-hidden"
>
{msg.content && (
<div className="p-2 text-xs text-muted-foreground truncate">
{msg.username}: {msg.content}
</div>
)}
</div>
))}
</div>
) : (
/* Review tab */
<div className="space-y-2">
{reviewMessages.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Flag className="size-8 text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">
No flagged messages to review.
</p>
</div>
) : (
reviewMessages.map((msg) => (
<MessageCard
key={msg.id}
message={msg}
onClick={handleMessageClick}
onReanalyze={handleReanalyze}
/>
))
)}
</div>
)}
{/* Message Detail Modal */}
{detailMessage && (
<div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 pt-12 px-4">
<div className="w-full max-w-2xl rounded-lg border bg-background shadow-xl overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between border-b p-4">
<h3 className="text-sm font-semibold">Message Detail</h3>
<button
type="button"
onClick={() => setDetailMessage(null)}
className="inline-flex size-7 items-center justify-center rounded-md hover:bg-muted transition-colors"
>
<X className="size-4" />
</button>
</div>
{/* Content */}
<div className="max-h-[70vh] overflow-y-auto p-4 space-y-4">
{detailLoading ? (
<div className="flex justify-center py-8">
<Loader2 className="size-6 animate-spin" />
</div>
) : (
<>
{/* Message info */}
<div className="flex items-start gap-3">
<div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden">
{detailMessage.avatar_url ? (
<img
src={detailMessage.avatar_url}
alt=""
className="size-full object-cover"
/>
) : (
detailMessage.username.charAt(0).toUpperCase()
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">
{detailMessage.username}
</span>
<span className="text-xs text-muted-foreground">
{new Date(detailMessage.created_at).toLocaleString()}
</span>
{detailMessage.type === "deleted" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-red-500/10 text-red-500">
deleted
</span>
)}
</div>
<p className="text-sm mt-1 whitespace-pre-wrap break-words">
{detailMessage.content}
</p>
</div>
</div>
{/* AI Analysis section */}
{detailMessage.ai_analysis && (
<div className="rounded-lg bg-muted/50 p-3">
<p className="text-xs text-muted-foreground mb-1">
AI Analysis
</p>
<p className="text-sm">{detailMessage.ai_analysis}</p>
</div>
)}
{/* AI flags */}
{detailMessage.ai_moderation_flags &&
detailMessage.ai_moderation_flags !== "[]" && (
<div className="space-y-1">
<p className="text-xs text-muted-foreground">
Moderation Flags
</p>
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(
detailMessage.ai_moderation_flags,
).map((flag) => (
<span
key={flag}
className="inline-flex items-center rounded-md bg-destructive/10 px-2 py-0.5 text-xs font-medium text-destructive"
>
{flag}
</span>
))}
</div>
</div>
)}
{/* AI Scores */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{detailMessage.ai_status && (
<div className="rounded-lg border p-2">
<p className="text-xs text-muted-foreground">Status</p>
<p className="text-sm font-medium">
{detailMessage.ai_status}
</p>
</div>
)}
{detailMessage.ai_severity &&
detailMessage.ai_severity !== "none" && (
<div className="rounded-lg border p-2">
<p className="text-xs text-muted-foreground">
Severity
</p>
<p className="text-sm font-medium text-destructive">
{detailMessage.ai_severity}
</p>
</div>
)}
{detailMessage.ai_confidence != null && (
<div className="rounded-lg border p-2">
<p className="text-xs text-muted-foreground">
Confidence
</p>
<p className="text-sm font-medium">
{(detailMessage.ai_confidence * 100).toFixed(0)}%
</p>
</div>
)}
{detailMessage.ai_recommended_action &&
detailMessage.ai_recommended_action !== "none" && (
<div className="rounded-lg border p-2">
<p className="text-xs text-muted-foreground">Action</p>
<p className="text-sm font-medium">
{detailMessage.ai_recommended_action}
</p>
</div>
)}
</div>
{/* Attachments */}
{detailAttachments.length > 0 && (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
Attachments ({detailAttachments.length})
</p>
<div className="grid grid-cols-2 gap-2">
{detailAttachments.map((att) => (
<a
key={att.id}
href={att.uploaded_url ?? att.discord_url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-2 rounded-lg border p-2 hover:bg-muted transition-colors"
>
<div className="flex-1 min-w-0">
<p className="text-xs font-medium truncate">
{att.filename}
</p>
<p className="text-xs text-muted-foreground">
{att.type} · {formatBytes(att.size)}
</p>
</div>
<ExternalLink className="size-3 shrink-0 text-muted-foreground" />
</a>
))}
</div>
</div>
)}
{/* Raw metadata */}
{detailMessage.metadata &&
detailMessage.metadata !== "{}" && (
<div className="space-y-1">
<p className="text-xs text-muted-foreground">
Metadata (raw)
</p>
<pre className="text-xs bg-muted rounded-lg p-3 overflow-x-auto max-h-32">
{JSON.stringify(
safeParseJsonObject(detailMessage.metadata),
null,
2,
)}
</pre>
</div>
)}
</>
)}
</div>
</div>
</div>
)}
</div>
);
}
// ── Message Card ──────────────────────────────────────────
function MessageCard({
message: msg,
onClick,
onReanalyze,
}: {
message: MessageRecord;
onClick: (id: string) => void;
onReanalyze: (id: string) => void;
}) {
const aiStatusColor: Record<string, string> = {
clean: "bg-green-500/15 text-green-600 dark:text-green-400",
warn: "bg-yellow-500/15 text-yellow-600 dark:text-yellow-400",
flagged: "bg-red-500/15 text-red-600 dark:text-red-400",
error: "bg-gray-500/15 text-gray-600 dark:text-gray-400",
pending: "bg-blue-500/15 text-blue-600 dark:text-blue-400",
processing: "bg-blue-500/15 text-blue-600 dark:text-blue-400",
};
const severityColor: Record<string, string> = {
none: "",
low: "border-l-green-400",
medium: "border-l-yellow-400",
high: "border-l-orange-400",
critical: "border-l-red-500",
};
const date = new Date(msg.created_at);
const timeStr = date.toLocaleString();
return (
<div
role="button"
tabIndex={0}
onClick={() => onClick(msg.id)}
onKeyDown={(e) => e.key === "Enter" && onClick(msg.id)}
className={`rounded-lg border p-4 space-y-2 transition-colors cursor-pointer hover:bg-muted/50 ${
msg.ai_severity ? severityColor[msg.ai_severity] ?? "" : ""
} ${msg.ai_severity && msg.ai_severity !== "none" ? "border-l-2" : ""}`}
>
{/* Header */}
<div className="flex items-start gap-3">
{/* Avatar */}
<div className="size-8 shrink-0 rounded-full bg-muted flex items-center justify-center text-xs font-medium overflow-hidden">
{msg.avatar_url ? (
<img
src={msg.avatar_url}
alt=""
className="size-full object-cover"
/>
) : (
msg.username.charAt(0).toUpperCase()
)}
</div>
<div className="flex-1 min-w-0">
{/* Username + time + badges */}
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">{msg.username}</span>
<span className="text-xs text-muted-foreground">{timeStr}</span>
<span className="text-xs text-muted-foreground">
#{msg.channel_id.slice(0, 8)}
</span>
{/* AI Status badge */}
{msg.ai_status && aiStatusColor[msg.ai_status] && (
<span
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${aiStatusColor[msg.ai_status]}`}
>
{msg.ai_status}
</span>
)}
{/* Severity badge */}
{msg.ai_severity && msg.ai_severity !== "none" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-destructive/10 text-destructive">
{msg.ai_severity}
</span>
)}
{/* Message type badge */}
{msg.type === "deleted" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-red-500/10 text-red-500">
deleted
</span>
)}
{msg.type === "edited" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-blue-500/10 text-blue-500">
edited
</span>
)}
</div>
{/* Content */}
<p className="text-sm mt-1 whitespace-pre-wrap break-words">
{msg.type === "deleted" ? (
<span className="italic text-muted-foreground line-through">
{msg.content}
</span>
) : (
msg.content
)}
</p>
{/* AI Details */}
{msg.ai_moderation_flags &&
msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1 mt-1">
{safeParseJsonArray(msg.ai_moderation_flags).map(
(flag) => (
<span
key={flag}
className="inline-flex items-center rounded-md bg-destructive/10 px-1.5 py-0.5 text-xs font-medium text-destructive"
>
{flag}
</span>
),
)}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-muted-foreground mt-1 italic line-clamp-2">
{msg.ai_analysis}
</p>
)}
{/* Confidence score */}
{msg.ai_confidence !== undefined &&
msg.ai_confidence !== null && (
<div className="flex items-center gap-2 mt-1">
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden max-w-24">
<div
className="h-full rounded-full bg-primary"
style={{
width: msg.ai_confidence * 100 + "%",
}}
/>
</div>
<span className="text-xs text-muted-foreground">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
)}
{/* Actions */}
<div className="flex gap-2 mt-2">
<button
type="button"
onClick={() => onReanalyze(msg.id)}
className="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium hover:bg-muted transition-colors"
title="Re-analyze this message"
>
<RefreshCw className="size-3" />
Reanalyze
</button>
</div>
</div>
</div>
</div>
);
}
// ── Helpers ───────────────────────────────────────────────
function safeParseJsonObject(
value: string | null | undefined,
): Record<string, unknown> {
if (!value) return {};
try {
const parsed = JSON.parse(value);
if (typeof parsed === "object" && parsed !== null) return parsed;
return {};
} catch {
return {};
}
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function safeParseJsonArray(
value: string | null | undefined,
): string[] {
if (!value) return [];
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) return parsed;
return [];
} catch {
return [];
}
}
+13
View File
@@ -0,0 +1,13 @@
import { ApiError, api } from "./client";
export async function login(password: string): Promise<boolean> {
try {
const resp = await api.post<{ ok: boolean }>("/api/auth/login", {
password,
});
return resp.ok;
} catch (err) {
if (err instanceof ApiError) return false;
throw err;
}
}
+63
View File
@@ -0,0 +1,63 @@
export class ApiError extends Error {
statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.name = "ApiError";
this.statusCode = statusCode;
}
}
function getBaseUrl(): string {
if (typeof window === "undefined") return "";
const protocol = window.location.protocol.replace(":", "");
const host = window.location.host;
// In dev, Next.js proxy can be configured, but default to same-host assumption
return `${protocol}://${host}`;
}
function getAuthHeader(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem("admin-password");
}
export async function apiRequest<T>(
method: string,
path: string,
body?: unknown,
): Promise<T> {
const url = `${getBaseUrl()}${path}`;
const password = getAuthHeader();
const headers: Record<string, string> = {};
if (password) {
headers["X-Admin-Password"] = password;
}
if (body !== undefined) {
headers["Content-Type"] = "application/json";
}
const response = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (response.status >= 400) {
const text = await response.text().catch(() => "");
throw new ApiError(text || `HTTP ${response.status}`, response.status);
}
// Handle 204 No Content (e.g., DELETE)
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
export const api = {
get: <T>(path: string) => apiRequest<T>("GET", path),
post: <T>(path: string, body?: unknown) => apiRequest<T>("POST", path, body),
delete: <T>(path: string) => apiRequest<T>("DELETE", path),
};
+6
View File
@@ -0,0 +1,6 @@
import type { AppConfig } from "@/lib/types";
import { api } from "./client";
export const configApi = {
get: () => api.get<AppConfig>("/api/config"),
};
@@ -0,0 +1,38 @@
import type {
DashboardChannelDetail,
DashboardStats,
DashboardUserDetail,
PaginatedChannels,
PaginatedUsers,
} from "@/lib/types";
import { api } from "./client";
export const dashboardApi = {
getStats: () => api.get<DashboardStats>("/api/dashboard/stats"),
listUsers: (limit?: number, cursor?: string, search?: string) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (cursor) params.set("cursor", cursor);
if (search) params.set("search", search);
const qs = params.toString();
return api.get<PaginatedUsers>(`/api/dashboard/users${qs ? `?${qs}` : ""}`);
},
getUserDetail: (userId: string) =>
api.get<DashboardUserDetail>(`/api/dashboard/users/${userId}`),
listChannels: (limit?: number, search?: string, guildId?: string) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (search) params.set("search", search);
if (guildId) params.set("guild_id", guildId);
const qs = params.toString();
return api.get<PaginatedChannels>(
`/api/dashboard/channels${qs ? `?${qs}` : ""}`,
);
},
getChannelDetail: (channelId: string) =>
api.get<DashboardChannelDetail>(`/api/dashboard/channels/${channelId}`),
};
+9
View File
@@ -0,0 +1,9 @@
export { login } from "./auth";
export { ApiError, api, apiRequest } from "./client";
export { configApi } from "./config";
export { dashboardApi } from "./dashboard";
export { mascotApi } from "./mascot";
export { messagesApi } from "./messages";
export { recordingsApi } from "./recordings";
export { uiStateApi } from "./ui-state";
export { voiceApi } from "./voice";
+11
View File
@@ -0,0 +1,11 @@
import type { ChatHistoryMessage, MascotChatResponse } from "@/lib/types";
import { api } from "./client";
export const mascotApi = {
send: (message: string) =>
api.post<MascotChatResponse>("/api/mascot/chat", { message }),
getHistory: () => api.get<ChatHistoryMessage[]>("/api/mascot/chat/history"),
clearHistory: () => api.delete<{ ok: boolean }>("/api/mascot/chat/history"),
};
+76
View File
@@ -0,0 +1,76 @@
import type { AttachmentRecord, MessageRecord } from "@/lib/types";
import { api } from "./client";
export const messagesApi = {
list: (
guildId: string,
limit?: number,
channelId?: string,
cursor?: string,
) => {
const params = new URLSearchParams({ guildId });
if (limit) params.set("limit", String(limit));
if (channelId) params.set("channelId", channelId);
if (cursor) params.set("cursor", cursor);
return api.get<{ data: MessageRecord[]; nextCursor: string | null }>(
`/api/messages?${params}`,
);
},
getByChannel: (channelId: string, limit?: number, cursor?: string) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (cursor) params.set("cursor", cursor);
const qs = params.toString();
return api.get<{ data: MessageRecord[]; nextCursor: string | null }>(
`/api/messages/${channelId}${qs ? `?${qs}` : ""}`,
);
},
getDetail: (id: string) =>
api.get<MessageRecord>(`/api/messages/detail/${id}`),
getImages: (guildId: string, limit?: number) => {
const params = new URLSearchParams({ guildId });
if (limit) params.set("limit", String(limit));
return api.get<{ data: MessageRecord[]; nextCursor: string | null }>(
`/api/messages/images?${params}`,
);
},
getAttachments: (channelId: string, limit?: number, cursor?: string) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (cursor) params.set("cursor", cursor);
const qs = params.toString();
return api.get<{ data: AttachmentRecord[]; nextCursor: string | null }>(
`/api/messages/${channelId}/attachments${qs ? `?${qs}` : ""}`,
);
},
getReview: (limit?: number, channelId?: string) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (channelId) params.set("channelId", channelId);
return api.get<{ results: MessageRecord[]; limit: number; cursor: null }>(
`/api/review?${params}`,
);
},
reanalyze: (id: string) =>
api.post<{ ok: boolean }>(`/api/messages/${id}/reanalyze`, {}),
reanalyzeBatch: (guildId?: string, channelId?: string) =>
api.post<{ ok: boolean; count: number }>("/api/messages/reanalyze-batch", {
guildId,
channelId,
}),
search: (query: string, limit?: number) => {
const params = new URLSearchParams({ q: query });
if (limit) params.set("limit", String(limit));
return api.get<{ results: MessageRecord[] }>(
`/api/analysis/search?${params}`,
);
},
};
@@ -0,0 +1,21 @@
import type { PaginatedRecordings } from "@/lib/types";
import { api } from "./client";
export const recordingsApi = {
list: (
limit?: number,
channelId?: string,
userId?: string,
cursor?: string,
) => {
const params = new URLSearchParams();
if (limit) params.set("limit", String(limit));
if (channelId) params.set("channelId", channelId);
if (userId) params.set("userId", userId);
if (cursor) params.set("cursor", cursor);
const qs = params.toString();
return api.get<PaginatedRecordings>(`/api/recordings${qs ? `?${qs}` : ""}`);
},
delete: (id: string) => api.delete<{ ok: boolean }>(`/api/recordings/${id}`),
};
@@ -0,0 +1,8 @@
import type { UiState } from "@/lib/types";
import { api } from "./client";
export const uiStateApi = {
get: () => api.get<UiState>("/api/ui-state"),
save: (state: UiState) => api.post<{ ok: boolean }>("/api/ui-state", state),
};
+30
View File
@@ -0,0 +1,30 @@
import type { Channel, Guild, MediaState, VoiceStatus } from "@/lib/types";
import { api } from "./client";
export const voiceApi = {
// Guilds
getGuilds: () => api.get<Guild[]>("/api/guilds"),
getTextChannels: (guildId: string) =>
api.get<Channel[]>(`/api/guilds/${guildId}/channels`),
getVoiceChannels: (guildId: string) =>
api.get<Channel[]>(`/api/guilds/${guildId}/voice-channels`),
// Voice connection
getStatus: () => api.get<VoiceStatus>("/api/voice/status"),
connect: (guildId: string, channelId: string) =>
api.post<VoiceStatus>("/api/voice/connect", { guildId, channelId }),
disconnect: () => api.post<VoiceStatus>("/api/voice/disconnect", {}),
sendCommand: (command: string) =>
api.post<{ success: boolean; command: string }>("/api/voice/command", {
command,
}),
// Media
getMediaStatus: () => api.get<MediaState>("/api/media/status"),
mediaQueue: (source: string, mode: string) =>
api.post<MediaState>("/api/media/queue", { source, mode }),
mediaSkip: () => api.post<MediaState>("/api/media/skip", {}),
mediaStop: () => api.post<MediaState>("/api/media/stop", {}),
mediaVolume: (volume: number) =>
api.post<MediaState>("/api/media/volume", { volume }),
};
@@ -0,0 +1,78 @@
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { login } from "@/lib/api";
interface AuthContextValue {
authenticated: boolean;
loading: boolean;
login: (password: string) => Promise<boolean>;
logout: () => void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const password = localStorage.getItem("admin-password");
if (password) {
// Verify stored password still works
login(password)
.then((ok) => {
setAuthenticated(ok);
setLoading(false);
})
.catch(() => {
localStorage.removeItem("admin-password");
setLoading(false);
});
} else {
setLoading(false);
}
}, []);
const handleLogin = useCallback(async (password: string) => {
const ok = await login(password);
if (ok) {
localStorage.setItem("admin-password", password);
setAuthenticated(true);
}
return ok;
}, []);
const handleLogout = useCallback(() => {
localStorage.removeItem("admin-password");
setAuthenticated(false);
}, []);
return (
<AuthContext.Provider
value={{
authenticated,
loading,
login: handleLogin,
logout: handleLogout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error("useAuth must be used within an AuthProvider");
}
return ctx;
}
@@ -0,0 +1,29 @@
import { useState, useEffect } from "react";
import { configApi } from "@/lib/api";
export interface AppConfig {
monitorGuildId: string | null;
webserverPort?: number;
nodeEnv?: string;
}
export function useAppConfig() {
const [config, setConfig] = useState<AppConfig | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
configApi
.get()
.then((cfg) => {
setConfig({
monitorGuildId: cfg.monitor_guild_id ?? null,
});
})
.catch(() => {
// silent — config fetch is not critical
})
.finally(() => setLoading(false));
}, []);
return { config, loading };
}
@@ -0,0 +1,83 @@
import type { MessageRecord } from "./message";
export interface DashboardStats {
total_messages: number;
total_users: number;
total_flagged: number;
total_clean: number;
total_warned: number;
total_error: number;
total_voice_recordings: number;
total_profiles: number;
today_messages: number;
today_flagged: number;
active_users_24h: number;
top_channels: TopChannel[];
moderation_overview: ModerationOverview;
}
export interface TopChannel {
channel_id: string;
channel_name?: string | null;
message_count: number;
}
export interface ModerationOverview {
pending: number;
processing: number;
error: number;
}
export interface DashboardUser {
user_id: string;
username?: string | null;
avatar_url?: string | null;
profile_summary?: string | null;
total_messages: number;
flagged_count: number;
last_message_at?: number | null;
trust_score?: number | null;
clean_message_streak?: number;
}
export interface DashboardUserDetail extends DashboardUser {
last_analyzed_at?: number | null;
clean_message_streak: number;
total_infractions: number;
clean_count: number;
recent_messages: MessageRecord[];
}
export interface DashboardChannel {
channel_id: string;
channel_name?: string | null;
guild_id?: string | null;
total_messages: number;
flagged_count: number;
last_message_at?: number | null;
culture_summary?: string | null;
last_analyzed_at?: number | null;
}
export interface DashboardChannelDetail {
channel_id: string;
channel_name?: string | null;
guild_id?: string | null;
total_messages: number;
flagged_count: number;
last_message_at?: number | null;
culture_summary?: string | null;
last_analyzed_at?: number | null;
clean_count: number;
recent_messages: MessageRecord[];
}
export interface PaginatedUsers {
data: DashboardUser[];
nextCursor: string | null;
}
export interface PaginatedChannels {
data: DashboardChannel[];
nextCursor: string | null;
}
+16
View File
@@ -0,0 +1,16 @@
export interface Guild {
id: string;
name: string;
icon?: string | null;
}
export interface Channel {
id: string;
name: string;
type?: string | null; // "voice" | "text"
parent_id?: string | null;
}
export interface AppConfig {
monitor_guild_id?: string | null;
}
+7
View File
@@ -0,0 +1,7 @@
export * from "./dashboard";
export * from "./guild";
export * from "./media";
export * from "./message";
export * from "./recording";
export * from "./ui";
export * from "./voice";
+17
View File
@@ -0,0 +1,17 @@
export type MediaMode = "music" | "screen";
export interface MediaItem {
id?: string | null;
source: string;
title?: string | null;
mode?: MediaMode | null;
durationMs?: number | null;
thumbnailUrl?: string | null;
}
export interface MediaState {
playing: boolean;
musicVolume: number;
current?: MediaItem | null;
queue: MediaItem[];
}
+135
View File
@@ -0,0 +1,135 @@
// ── AI Moderation Types ──────────────────────────────────────
export type AiStatus =
| "pending"
| "processing"
| "clean"
| "warn"
| "flagged"
| "error";
export type AiSeverity = "none" | "low" | "medium" | "high" | "critical";
export type AiRecommendedAction =
| "none"
| "monitor"
| "warn"
| "review"
| "delete"
| "escalate";
// ── Embeds & Metadata ────────────────────────────────────────
export interface EmbedMedia {
url: string;
width?: number | null;
height?: number | null;
}
export interface EmbedInfo {
title?: string | null;
description?: string | null;
url?: string | null;
color?: number | null;
image?: EmbedMedia | null;
thumbnail?: EmbedMedia | null;
author?: { name?: string; url?: string; icon_url?: string } | null;
footer?: { text: string; icon_url?: string } | null;
fields?: Array<{ name: string; value: string; inline?: boolean }>;
}
export interface StickerInfo {
name?: string | null;
url?: string | null;
}
export interface AttachmentRef {
name: string;
url: string;
contentType?: string | null;
}
export interface ChannelRef {
channelId: string;
channelName?: string | null;
threadId?: string | null;
threadName?: string | null;
}
export interface ReferenceInfo {
messageId?: string | null;
channelId?: string | null;
guildId?: string | null;
type?: string | null;
content?: string | null;
repliedUsername?: string | null;
repliedUserId?: string | null;
}
export interface MessageMetadata {
stickers?: StickerInfo[] | null;
attachments?: AttachmentRef[] | null;
embeds?: EmbedInfo[] | null;
channel?: ChannelRef | null;
reference?: ReferenceInfo | null;
}
// ── Message Record ──────────────────────────────────────────
export interface MessageRecord {
id: string;
guild_id: string;
channel_id: string;
thread_id?: string | null;
reference_message_id?: string | null;
user_id: string;
username: string;
avatar_url?: string | null;
content: string;
edited_content?: string | null;
type: string; // "text" | "edited" | "deleted"
is_reply?: boolean | null;
is_forward?: boolean | null;
is_crosspost?: boolean | null;
metadata?: string | null; // JSON string of MessageMetadata
created_at: number;
edited_at?: number | null;
deleted_at?: number | null;
ai_status?: AiStatus | null;
ai_severity?: AiSeverity | null;
ai_confidence?: number | null;
ai_moderation_flags?: string | null; // JSON string array
ai_moderation_score?: number | null;
ai_analysis?: string | null;
ai_categories?: string | null; // JSON string array
ai_recommended_action?: AiRecommendedAction | null;
ai_error?: string | null;
ai_analyzed_at?: number | null;
}
// ── Pagination ──────────────────────────────────────────────
export interface PageResult<T> {
data: T[];
nextCursor: string | null;
}
// ── Attachment ──────────────────────────────────────────────
export interface AttachmentRecord {
id: string;
message_id: string;
guild_id: string;
channel_id: string;
thread_id?: string | null;
user_id: string;
filename: string;
size: number;
type: string;
discord_url: string;
uploaded_url?: string | null;
upload_status: "pending" | "uploaded" | "failed";
upload_error?: string | null;
created_at: number;
uploaded_at?: number | null;
}
@@ -0,0 +1,23 @@
export interface VoiceRecording {
id: string;
user_id: string;
username: string;
avatar_url?: string | null;
guild_id?: string | null;
channel_id?: string | null;
channel_name?: string | null;
filename: string;
size_bytes: number;
download_url?: string | null;
upload_status: string;
upload_error?: string | null;
transcription?: string | null;
created_at: number;
uploaded_at?: number | null;
}
export interface PaginatedRecordings {
items: VoiceRecording[];
nextCursor: string | null;
hasMore: boolean;
}
+23
View File
@@ -0,0 +1,23 @@
export type DashboardTab = "messages" | "live" | "dashboard";
export interface UiState {
selected_guild?: string | null;
selected_voice_guild?: string | null;
selected_voice_channel?: string | null;
selected_text_guild?: string | null;
selected_text_channel?: string | null;
active_tab?: DashboardTab | null;
is_listening?: boolean | null;
is_streaming?: boolean | null;
}
export interface MascotChatResponse {
response: string;
timestamp: string;
}
export interface ChatHistoryMessage {
role: string;
content: string;
timestamp: string;
}
+22
View File
@@ -0,0 +1,22 @@
export interface GuildVoiceEntry {
guildId: string;
channelId: string;
channelName: string;
connectedAt: number;
}
export interface VoiceStatus {
connected: boolean;
activeGuildId?: string | null;
activeChannelId?: string | null;
activeChannelName?: string | null;
connections: GuildVoiceEntry[];
}
export interface ActiveSpeaker {
id?: string | null;
user_id: string;
username: string;
avatar?: string | null;
speaking: boolean;
}
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+144
View File
@@ -0,0 +1,144 @@
import type { WsEvent, WsStatus } from "./types";
type WsEventCallback = (event: WsEvent) => void;
function getWsUrl(): string {
if (typeof window === "undefined") return "ws://localhost:3001/ws";
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const host = window.location.host;
return `${protocol}://${host}/ws`;
}
export class WsConnection {
private ws: WebSocket | null = null;
private url: string;
private reconnectAttempt = 0;
private maxReconnectAttempts = 20;
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
private _status: WsStatus = "disconnected";
private statusListeners: Array<(status: WsStatus) => void> = [];
private eventListeners: Array<WsEventCallback> = [];
private destroyed = false;
constructor(url?: string) {
this.url = url ?? getWsUrl();
}
get status(): WsStatus {
return this._status;
}
onStatusChange(listener: (status: WsStatus) => void): () => void {
this.statusListeners.push(listener);
return () => {
this.statusListeners = this.statusListeners.filter((l) => l !== listener);
};
}
onEvent(listener: WsEventCallback): () => void {
this.eventListeners.push(listener);
return () => {
this.eventListeners = this.eventListeners.filter((l) => l !== listener);
};
}
connect(): void {
if (this.destroyed) return;
if (this._status === "connected" || this._status === "connecting") return;
this.setStatus("connecting");
try {
this.ws = new WebSocket(this.url);
} catch (_err) {
this.setStatus("error");
this.scheduleReconnect();
return;
}
this.ws.onopen = () => {
this.reconnectAttempt = 0;
this.setStatus("connected");
};
this.ws.onclose = () => {
this.setStatus("disconnected");
this.scheduleReconnect();
};
this.ws.onerror = () => {
this.setStatus("error");
};
this.ws.onmessage = (msg: MessageEvent) => {
if (typeof msg.data === "string") {
this.dispatchEvent({ type: "text", data: msg.data });
} else if (msg.data instanceof ArrayBuffer) {
this.dispatchEvent({ type: "binary", data: msg.data });
} else if (msg.data instanceof Blob) {
// Blob — convert to ArrayBuffer
msg.data.arrayBuffer().then((buffer) => {
this.dispatchEvent({ type: "binary", data: buffer });
});
}
};
}
disconnect(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
if (this.ws) {
this.ws.onclose = null; // prevent reconnect
this.ws.close();
this.ws = null;
}
this.setStatus("disconnected");
}
destroy(): void {
this.destroyed = true;
this.disconnect();
this.statusListeners = [];
this.eventListeners = [];
}
sendText(text: string): void {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(text);
}
}
sendBinary(data: ArrayBufferLike): void {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(data);
}
}
private setStatus(status: WsStatus): void {
if (this._status === status) return;
this._status = status;
this.statusListeners.forEach((l) => l(status));
}
private dispatchEvent(event: WsEvent): void {
this.eventListeners.forEach((l) => l(event));
}
private scheduleReconnect(): void {
if (this.destroyed || this.reconnectAttempt >= this.maxReconnectAttempts)
return;
// Full-jitter exponential backoff: min(1000 * 2^attempt, 30000) * (0.5 + random * 0.5)
const base = Math.min(1000 * 2 ** this.reconnectAttempt, 30000);
const jitter = 0.5 + Math.random() * 0.5;
const delay = Math.floor(base * jitter);
this.reconnectAttempt++;
this.reconnectTimeout = setTimeout(() => {
this.connect();
}, delay);
}
}
+165
View File
@@ -0,0 +1,165 @@
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { WsConnection } from "./connection";
import type { PcmChunk, WsEventHandler, WsEventType, WsStatus } from "./types";
interface WsContextValue {
status: WsStatus;
connect: () => void;
disconnect: () => void;
sendText: (text: string) => void;
sendBinary: (data: ArrayBufferLike) => void;
/** Subscribe to a typed WS event. Returns unsubscribe function. */
on: <E extends WsEventType>(
eventType: E,
handler: WsEventHandler<E>,
) => () => void;
/** Subscribe to binary PCM events. Returns unsubscribe function. */
onPcm: (handler: (chunk: PcmChunk) => void) => () => void;
}
const WsContext = createContext<WsContextValue | null>(null);
/** FNV-1a 32-bit hash matching the backend's hashUserId function */
function _hashUserId(userId: string): number {
let hash = 0x811c9dc5;
for (let i = 0; i < userId.length; i++) {
hash ^= userId.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
export function WsProvider({
children,
url,
}: {
children: ReactNode;
url?: string;
}) {
const connRef = useRef<WsConnection | null>(null);
const [status, setStatus] = useState<WsStatus>("disconnected");
// Event handler registry — Ref so listeners survive re-renders without reconnect
// Using unknown as internal store; typed at the subscribe interface
const handlersRef = useRef<Record<string, Set<(data: unknown) => void>>>({});
const pcmHandlersRef = useRef<Set<(chunk: PcmChunk) => void>>(new Set());
const handleJsonEvent = useCallback((json: string) => {
try {
const parsed = JSON.parse(json);
const eventType = parsed.type as string;
const data = parsed.data ?? parsed.state ?? parsed;
const handlers = handlersRef.current;
const eventHandlers = handlers[eventType as WsEventType];
if (eventHandlers && eventHandlers.size > 0) {
eventHandlers.forEach((h) => h(data));
}
} catch {
// ignore parse errors
}
}, []);
const handleBinaryEvent = useCallback((buffer: ArrayBuffer) => {
if (buffer.byteLength < 4 || pcmHandlersRef.current.size === 0) return;
const view = new DataView(buffer);
const userIdHash = view.getUint32(0, true);
const samples = new Int16Array(buffer, 4);
const chunk: PcmChunk = { userIdHash, samples };
pcmHandlersRef.current.forEach((h) => h(chunk));
}, []);
useEffect(() => {
const conn = new WsConnection(url);
connRef.current = conn;
const unsubStatus = conn.onStatusChange(setStatus);
const unsubEvent = conn.onEvent((event) => {
if (event.type === "text") {
handleJsonEvent(event.data);
} else {
handleBinaryEvent(event.data);
}
});
conn.connect();
return () => {
conn.destroy();
connRef.current = null;
unsubStatus();
unsubEvent();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url, handleBinaryEvent, handleJsonEvent]);
const subscribe = useCallback(
<E extends WsEventType>(_eventType: E, handler: WsEventHandler<E>) => {
const eventType = _eventType as string;
if (!handlersRef.current[eventType]) {
handlersRef.current[eventType] = new Set();
}
handlersRef.current[eventType].add(handler as (data: unknown) => void);
return () => {
handlersRef.current[eventType]?.delete(
handler as (data: unknown) => void,
);
};
},
[],
);
const subscribePcm = useCallback((handler: (chunk: PcmChunk) => void) => {
pcmHandlersRef.current.add(handler);
return () => {
pcmHandlersRef.current.delete(handler);
};
}, []);
const connect = useCallback(() => connRef.current?.connect(), []);
const disconnect = useCallback(() => connRef.current?.disconnect(), []);
const sendText = useCallback(
(text: string) => connRef.current?.sendText(text),
[],
);
const sendBinary = useCallback(
(data: ArrayBufferLike) => connRef.current?.sendBinary(data),
[],
);
return (
<WsContext.Provider
value={{
status,
connect,
disconnect,
sendText,
sendBinary,
on: subscribe,
onPcm: subscribePcm,
}}
>
{children}
</WsContext.Provider>
);
}
export function useWebSocket(): WsContextValue {
const ctx = useContext(WsContext);
if (!ctx) {
throw new Error("useWebSocket must be used within a WsProvider");
}
return ctx;
}
+68
View File
@@ -0,0 +1,68 @@
import type {
ActiveSpeaker,
MediaState,
MessageRecord,
VoiceRecording,
} from "@/lib/types";
// ── Connection Status ──────────────────────────────────────
export type WsStatus = "disconnected" | "connecting" | "connected" | "error";
// ── Raw Events (from WebSocket) ────────────────────────────
export type WsEvent = WsTextEvent | WsBinaryEvent;
export interface WsTextEvent {
type: "text";
data: string;
}
export interface WsBinaryEvent {
type: "binary";
data: ArrayBuffer;
}
// ── Typed Event Map ───────────────────────────────────────
export interface WsEventMap {
message_created: MessageRecord;
message_updated: MessageRecord;
message_deleted: string; // message ID
message_analyzed: MessageRecord;
attachment_created: unknown;
attachment_uploaded: unknown;
voice_recording_started: unknown;
voice_recording_stopped: unknown;
voice_recording_uploaded: VoiceRecording;
voice_active_user: ActiveSpeaker;
voice_pcm_data: { userId: string; pcm: string };
voice_analyzed: unknown;
analysis_queue_status: unknown;
reaction_added: unknown;
reaction_removed: unknown;
thread_created: unknown;
thread_deleted: unknown;
thread_updated: unknown;
channel_topic_updated: unknown;
presence_updated: unknown;
guild_member_added: unknown;
guild_member_removed: unknown;
media_state: MediaState;
user_state: unknown;
ui_state: unknown;
heartbeat: unknown;
}
export type WsEventType = keyof WsEventMap;
export type WsEventHandler<E extends WsEventType = WsEventType> = (
data: WsEventMap[E],
) => void;
// ── Binary PCM ─────────────────────────────────────────────
export interface PcmChunk {
userIdHash: number;
samples: Int16Array;
}