feat: add recordings, settings, and voice pages with WebSocket integration
Deploy to VPS / deploy (push) Failing after 1m36s

- Implemented RecordingsPage to display and manage voice recordings with live updates via WebSocket.
- Created SettingsPage for user preferences, including theme toggling and server configuration display.
- Developed VoicePage for managing voice connections, including guild and channel selection, and active speaker display.
- Introduced GuildSelector component for selecting Discord guilds with error handling and loading states.
- Added utility functions for formatting numbers and bytes, and safely parsing JSON.
- Established navigation structure for the dashboard with relevant links for new features.
This commit is contained in:
asepharyana
2026-07-26 15:34:08 +07:00
parent eae0d7ce56
commit c2502a0e5f
20 changed files with 1520 additions and 1036 deletions
@@ -0,0 +1,192 @@
"use client";
import { Loader2, RefreshCw, Search, Sparkles } from "lucide-react";
import { useCallback, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { messagesApi } from "@/lib/api";
import { safeParseJsonArray } from "@/lib/format";
import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
export default function AnalysisPage() {
const [query, setQuery] = useState("");
const [results, setResults] = useState<MessageRecord[] | null>(null);
const [searching, setSearching] = useState(false);
const [searched, setSearched] = useState(false);
const handleSearch = useCallback(async () => {
if (!query.trim()) return;
setSearching(true);
setSearched(true);
try {
const result = await messagesApi.search(query, 50);
setResults(result.results);
} catch {
setResults([]);
} finally {
setSearching(false);
}
}, [query]);
const handleReanalyze = useCallback(async (id: string) => {
try {
await messagesApi.reanalyze(id);
} catch {
// ignore
}
}, []);
return (
<div className="space-y-5 animate-fade-in-up">
{/* Search */}
<div className="flex gap-2">
<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 message content, AI flags, analysis text…"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="pl-9 h-9"
/>
</div>
<Button onClick={handleSearch} disabled={!query.trim() || searching}>
{searching && <Loader2 className="size-4 animate-spin mr-1.5" />}
Search
</Button>
</div>
{/* Results */}
{searching ? (
<div className="space-y-3">
{Array.from({ length: 5 }, (_, i) => (
<Skeleton key={i} className="h-28 rounded-xl" />
))}
</div>
) : results !== null ? (
<>
<p className="text-sm text-muted-foreground">
Found {results.length} result
{results.length !== 1 ? "s" : ""}
</p>
{results.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20 text-center">
<Search className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">
No messages found matching your query.
</p>
</div>
) : (
<div className="space-y-2">
{results.map((msg) => (
<Card key={msg.id}>
<CardContent className="p-4">
<div className="flex items-start gap-3">
<Avatar className="size-8 shrink-0 mt-0.5">
<AvatarImage src={msg.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{msg.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-2">
<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">
{new Date(msg.created_at).toLocaleString()}
</span>
{msg.ai_status && (
<Badge
variant="outline"
className={cn(
"text-[10px] px-1.5 py-0 h-4",
msg.ai_status === "clean" &&
"text-green-500",
msg.ai_status === "flagged" &&
"text-red-500",
)}
>
{msg.ai_status}
</Badge>
)}
</div>
<p className="text-sm leading-relaxed">{msg.content}</p>
{msg.ai_moderation_flags &&
msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(
msg.ai_moderation_flags,
).map((flag) => (
<Badge
key={flag}
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{flag}
</Badge>
))}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
<Sparkles className="size-3 inline mr-1" />
{msg.ai_analysis}
</p>
)}
{msg.ai_confidence != null && (
<div className="flex items-center gap-2 max-w-40">
<Progress
value={msg.ai_confidence * 100}
className="h-1.5"
/>
<span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
)}
<Button
variant="ghost"
size="xs"
onClick={() => handleReanalyze(msg.id)}
>
<RefreshCw className="size-3 mr-1" />
Reanalyze
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
</>
) : !searched ? (
<div className="flex flex-col items-center justify-center py-24 text-center">
<Search className="size-12 text-muted-foreground/30 mb-4" />
<p className="text-sm text-muted-foreground">
Enter a search query to find messages across all channels.
</p>
<p className="text-xs text-muted-foreground/60 mt-1">
Searches message content, AI flags, and analysis text.
</p>
</div>
) : null}
</div>
);
}
@@ -0,0 +1,807 @@
"use client";
import {
AlertCircle,
ArrowLeft,
BarChart3,
ChevronRight,
Clock,
Hash,
RefreshCw,
Search,
Shield,
Sparkles,
Users,
} from "lucide-react";
import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { GuildSelector } from "@/components/shared/guild-selector";
import { dashboardApi } from "@/lib/api";
import { formatNumber } from "@/lib/format";
import type {
DashboardChannel,
DashboardChannelDetail,
DashboardStats,
DashboardUser,
DashboardUserDetail,
} from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
type View = "stats" | "users" | "channels" | "user-detail" | "channel-detail";
export default function DashboardPage() {
const [view, setView] = useState<View>("stats");
const [guildId, setGuildId] = useState("");
const [activeUser, setActiveUser] = useState<DashboardUserDetail | null>(
null,
);
const [activeChannel, setActiveChannel] =
useState<DashboardChannelDetail | null>(null);
// WS connection for real-time awareness
useWebSocket();
const renderView = () => {
switch (view) {
case "stats":
return <StatsView />;
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
guildId={guildId}
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 guildId={guildId} onSelectChannel={() => {}} />
);
}
};
return (
<div className="space-y-5">
<GuildSelector value={guildId} onChange={setGuildId} />
<Tabs
value={
view === "user-detail"
? "users"
: view === "channel-detail"
? "channels"
: view
}
onValueChange={(v) => setView(v as View)}
>
<TabsList>
<TabsTrigger value="stats" onClick={() => setView("stats")}>
<BarChart3 className="size-4" />
Stats
</TabsTrigger>
<TabsTrigger value="users" onClick={() => setView("users")}>
<Users className="size-4" />
Users
</TabsTrigger>
<TabsTrigger value="channels" onClick={() => setView("channels")}>
<Hash className="size-4" />
Channels
</TabsTrigger>
</TabsList>
</Tabs>
{renderView()}
</div>
);
}
// ── Stats View ──────────────────────────────────
function StatsView() {
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-20 text-center">
<AlertCircle className="size-10 text-destructive mb-3" />
<p className="text-sm text-muted-foreground mb-4 max-w-sm">{error}</p>
<Button variant="outline" onClick={fetchStats}>
<RefreshCw className="size-4 mr-2" />
Retry
</Button>
</div>
);
}
return (
<div className="space-y-5 animate-fade-in-up">
{loading ? (
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{Array.from({ length: 8 }, (_, i) => (
<Skeleton key={i} className="h-28 rounded-xl" />
))}
</div>
) : stats ? (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<StatCard
label="Total Messages"
value={stats.total_messages}
icon={Hash}
/>
<StatCard
label="Today"
value={stats.today_messages}
icon={Clock}
/>
<StatCard label="Users" value={stats.total_users} icon={Users} />
<StatCard
label="Active 24h"
value={stats.active_users_24h}
icon={Sparkles}
/>
<StatCard
label="Flagged"
value={stats.total_flagged}
variant="danger"
icon={AlertCircle}
/>
<StatCard
label="Clean"
value={stats.total_clean}
variant="success"
icon={Shield}
/>
<StatCard
label="Voice Recordings"
value={stats.total_voice_recordings}
icon={Hash}
/>
<StatCard
label="AI Profiles"
value={stats.total_profiles}
icon={Sparkles}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Hash className="size-4 text-muted-foreground" />
Top Channels
</CardTitle>
</CardHeader>
<CardContent>
{stats.top_channels.length === 0 ? (
<p className="text-sm text-muted-foreground py-6 text-center">
No channel data yet.
</p>
) : (
<div className="space-y-2">
{stats.top_channels.map((ch, i) => {
const maxCount = stats.top_channels[0].message_count;
const pct =
maxCount > 0
? (ch.message_count / maxCount) * 100
: 0;
return (
<div key={ch.channel_id} className="space-y-1">
<div className="flex items-center justify-between text-sm">
<span className="truncate font-medium">
#
{ch.channel_name ??
ch.channel_id.slice(0, 8)}
</span>
<span className="text-muted-foreground tabular-nums">
{formatNumber(ch.message_count)}
</span>
</div>
<Progress value={pct} className="h-1.5" />
</div>
);
})}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Shield className="size-4 text-muted-foreground" />
Moderation Queue
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-3">
<div className="rounded-lg bg-muted/50 p-3 text-center space-y-1.5">
<div className="text-2xl font-bold tabular-nums">
{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.5">
<div className="text-2xl font-bold tabular-nums text-yellow-500">
{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.5">
<div className="text-2xl font-bold tabular-nums text-destructive">
{stats.moderation_overview.error}
</div>
<div className="text-xs text-muted-foreground">Errors</div>
</div>
</div>
</CardContent>
</Card>
</div>
</>
) : null}
</div>
);
}
function StatCard({
label,
value,
variant,
icon: Icon,
}: {
label: string;
value: number;
variant?: "default" | "danger" | "success";
icon: React.ComponentType<{ className?: string }>;
}) {
return (
<Card>
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="space-y-1.5">
<p className="text-xs text-muted-foreground">{label}</p>
<p
className={cn(
"text-2xl font-bold tabular-nums tracking-tight",
variant === "danger" && "text-destructive",
variant === "success" && "text-green-500",
)}
>
{formatNumber(value)}
</p>
</div>
<div
className={cn(
"flex size-9 shrink-0 items-center justify-center rounded-lg",
variant === "danger"
? "bg-destructive/10 text-destructive"
: variant === "success"
? "bg-green-500/10 text-green-500"
: "bg-primary/10 text-primary",
)}
>
<Icon className="size-4" />
</div>
</div>
</CardContent>
</Card>
);
}
// ── 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-4 animate-fade-in-up">
<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="pl-9 h-9"
/>
</div>
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Array.from({ length: 6 }, (_, i) => (
<Skeleton key={i} className="h-20 rounded-xl" />
))}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{users.length === 0 ? (
<div className="col-span-full flex flex-col items-center justify-center py-16 text-center">
<Users className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">No users found.</p>
</div>
) : (
users.map((user) => (
<Card
key={user.user_id}
className="cursor-pointer hover:bg-accent/5 transition-colors"
onClick={() => onSelectUser(user.user_id)}
>
<CardContent className="p-3">
<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 ring-1 ring-border">
{user.avatar_url ? (
<Image
src={user.avatar_url}
alt=""
width={40}
height={40}
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 flex items-center gap-2">
<span>{user.total_messages} messages</span>
{user.flagged_count > 0 && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{user.flagged_count} flagged
</Badge>
)}
</p>
</div>
<ChevronRight className="size-4 text-muted-foreground shrink-0" />
</div>
</CardContent>
</Card>
))
)}
</div>
)}
</div>
);
}
// ── Channels View ───────────────────────────────
function ChannelsView({
onSelectChannel,
guildId,
}: {
onSelectChannel: (channelId: string) => void;
guildId: string;
}) {
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,
guildId || undefined,
);
setChannels(result.data);
} catch {
// ignore
} finally {
setLoading(false);
}
},
[guildId],
);
useEffect(() => {
fetchChannels();
}, [fetchChannels]);
useEffect(() => {
const timer = setTimeout(() => {
if (search) fetchChannels(search);
else fetchChannels();
}, 300);
return () => clearTimeout(timer);
}, [search, fetchChannels]);
return (
<div className="space-y-4 animate-fade-in-up">
<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="pl-9 h-9"
/>
</div>
{loading ? (
<div className="space-y-2">
{Array.from({ length: 6 }, (_, i) => (
<Skeleton key={i} className="h-20 rounded-xl" />
))}
</div>
) : (
<div className="space-y-2">
{channels.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Hash className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">
No channels found.
</p>
</div>
) : (
channels.map((ch) => (
<Card
key={ch.channel_id}
className="cursor-pointer hover:bg-accent/5 transition-colors"
onClick={() => onSelectChannel(ch.channel_id)}
>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<Hash className="size-3.5 text-muted-foreground shrink-0" />
<p className="text-sm font-medium truncate">
{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</p>
</div>
<p className="text-xs text-muted-foreground mt-0.5 flex items-center gap-2">
<span>{ch.total_messages} messages</span>
{ch.flagged_count > 0 && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{ch.flagged_count} flagged
</Badge>
)}
</p>
</div>
<ChevronRight className="size-4 text-muted-foreground shrink-0 ml-2" />
</div>
{ch.culture_summary && (
<p className="text-xs text-muted-foreground/70 mt-2 italic line-clamp-2 border-t border-border/50 pt-2">
&ldquo;{ch.culture_summary}&rdquo;
</p>
)}
</CardContent>
</Card>
))
)}
</div>
)}
</div>
);
}
// ── User Detail View ────────────────────────────
function UserDetailView({
user,
onBack,
}: {
user: DashboardUserDetail;
onBack: () => void;
}) {
return (
<div className="space-y-5 animate-fade-in-up">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={onBack}>
<ArrowLeft className="size-4 mr-1" />
Back
</Button>
</div>
<Card>
<CardContent className="p-6 space-y-5">
<div className="flex items-center gap-4">
<div className="size-14 shrink-0 rounded-full bg-muted flex items-center justify-center text-xl font-medium overflow-hidden ring-2 ring-border">
{user.avatar_url ? (
<Image
src={user.avatar_url}
alt=""
width={56}
height={56}
className="size-full object-cover"
/>
) : (
(user.username ?? "?").charAt(0).toUpperCase()
)}
</div>
<div className="min-w-0">
<h2 className="text-lg font-semibold">
{user.username ?? "Unknown"}
</h2>
<p className="text-sm text-muted-foreground font-mono text-xs">
{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="danger"
/>
<DetailStat
label="Clean Streak"
value={user.clean_message_streak ?? 0}
/>
<DetailStat
label="Trust Score"
value={user.trust_score ?? 0}
suffix="%"
/>
</div>
{user.profile_summary && (
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<div className="flex items-center gap-2 mb-2">
<Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
AI Profile
</p>
</div>
<p className="text-sm leading-relaxed">{user.profile_summary}</p>
</div>
)}
{user.recent_messages.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Clock className="size-4 text-muted-foreground" />
Recent Messages
</h3>
<div className="space-y-2 max-h-80 overflow-y-auto">
{user.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
>
<p className="text-xs text-muted-foreground mb-1 flex items-center gap-2">
<Clock className="size-3" />
{new Date(msg.created_at).toLocaleString()}
</p>
<p className="text-sm">{msg.content}</p>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
}
// ── Channel Detail View ─────────────────────────
function ChannelDetailView({
channel,
onBack,
}: {
channel: DashboardChannelDetail;
onBack: () => void;
}) {
return (
<div className="space-y-5 animate-fade-in-up">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={onBack}>
<ArrowLeft className="size-4 mr-1" />
Back
</Button>
</div>
<Card>
<CardContent className="p-6 space-y-5">
<div>
<h2 className="text-lg font-semibold flex items-center gap-2">
<Hash className="size-5 text-muted-foreground" />
{channel.channel_name ?? channel.channel_id.slice(0, 8)}
</h2>
<p className="text-xs text-muted-foreground font-mono mt-0.5">
{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="danger"
/>
<DetailStat
label="Clean"
value={channel.clean_count}
variant="success"
/>
</div>
{channel.culture_summary && (
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<div className="flex items-center gap-2 mb-2">
<Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
Channel Culture
</p>
</div>
<p className="text-sm leading-relaxed italic">
&ldquo;{channel.culture_summary}&rdquo;
</p>
</div>
)}
{channel.recent_messages.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Clock className="size-4 text-muted-foreground" />
Recent Messages
</h3>
<div className="space-y-2">
{channel.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
>
<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>
)}
</CardContent>
</Card>
</div>
);
}
// ── Shared Components ───────────────────────────
function DetailStat({
label,
value,
variant,
suffix,
}: {
label: string;
value: number;
variant?: "default" | "danger" | "success";
suffix?: string;
}) {
return (
<Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">{label}</p>
<p
className={cn(
"text-lg font-bold tabular-nums",
variant === "danger" && "text-destructive",
variant === "success" && "text-green-500",
)}
>
{formatNumber(value)}
{suffix}
</p>
</CardContent>
</Card>
);
}
@@ -0,0 +1,45 @@
"use client";
import { Suspense } from "react";
import { Header } from "@/components/layout/header";
import { MobileTabBar } from "@/components/layout/mobile-tab-bar";
import { Sidebar } from "@/components/layout/sidebar";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { MascotChatbot } from "@/components/mascot/mascot-chatbot";
import { WsProvider } from "@/lib/ws/context";
function LoadingFallback() {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<div className="flex flex-col items-center gap-3">
<div className="size-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<p className="text-sm text-muted-foreground">Loading dashboard</p>
</div>
</div>
);
}
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<WsProvider>
<SidebarProvider defaultOpen={true}>
<div className="flex min-h-screen bg-background">
<Sidebar />
<SidebarInset className="flex flex-col">
<Header />
<main className="flex-1 p-4 md:p-6 pb-20 md:pb-6 animate-fade-in-up">
<Suspense fallback={<LoadingFallback />}>{children}</Suspense>
</main>
</SidebarInset>
<MobileTabBar />
</div>
</SidebarProvider>
<MascotChatbot />
</WsProvider>
);
}
@@ -0,0 +1,214 @@
"use client";
import {
Disc3,
Music,
Play,
SkipForward,
Square,
Volume2,
} from "lucide-react";
import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Slider } from "@/components/ui/slider";
import { voiceApi } from "@/lib/api";
import type { MediaState } from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context";
export default function MediaPage() {
const ws = useWebSocket();
const [mediaState, setMediaState] = useState<MediaState | null>(null);
const [queueUrl, setQueueUrl] = useState("");
const fetchMediaStatus = useCallback(async () => {
try {
const state = await voiceApi.getMediaStatus();
setMediaState(state);
} catch {
// ignore
}
}, []);
useEffect(() => {
fetchMediaStatus();
}, [fetchMediaStatus]);
// WS subscription
useEffect(() => {
const unsubMedia = ws.on("media_state", (state) => {
setMediaState(state as MediaState);
});
return () => {
unsubMedia();
};
}, [ws]);
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 (value: number | readonly number[]) => {
const vol = Array.isArray(value) ? value[0] : value;
try {
const state = await voiceApi.mediaVolume(vol);
setMediaState(state);
} catch {
// ignore
}
},
[],
);
return (
<div className="space-y-5 animate-fade-in-up">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Music className="size-4 text-primary" />
Music Player
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* 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"
/>
<Button onClick={handleQueueMedia} disabled={!queueUrl.trim()}>
<Play className="size-4 mr-1.5" />
Queue
</Button>
</div>
{/* Now Playing */}
{mediaState?.current && (
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4 space-y-2">
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider flex items-center gap-1.5">
<Disc3 className="size-3" />
Now Playing
</p>
<div className="flex items-start gap-3">
{mediaState.current.thumbnailUrl && (
<Image
src={mediaState.current.thumbnailUrl}
alt=""
width={56}
height={56}
className="size-14 rounded-lg object-cover shadow-sm"
/>
)}
<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 mt-0.5">
{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>
)}
{!mediaState?.current && !mediaState?.queue?.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
No media queued. Paste a URL above to start playing.
</p>
)}
{/* Controls */}
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleStop}>
<Square className="size-4 mr-1" />
Stop
</Button>
<Button variant="outline" size="sm" onClick={handleSkip}>
<SkipForward className="size-4 mr-1" />
Skip
</Button>
<div className="flex items-center gap-2 ml-auto">
<Volume2 className="size-4 text-muted-foreground" />
<Slider
className="w-24"
defaultValue={[mediaState?.musicVolume ?? 0.5]}
value={[mediaState?.musicVolume ?? 0.5]}
onValueChange={handleVolume}
min={0}
max={1}
step={0.05}
/>
</div>
</div>
{/* Queue */}
{mediaState && mediaState.queue.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs text-muted-foreground font-medium">
Queue ({mediaState.queue.length})
</p>
<div className="space-y-1">
{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 text-sm"
>
<span className="text-xs text-muted-foreground font-mono w-5 text-right">
{i + 1}.
</span>
<span className="truncate flex-1">
{item.title ?? item.source}
</span>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,885 @@
"use client";
import {
AlertCircle,
ExternalLink,
Flag,
Loader2,
MessageSquare,
RefreshCw,
Search,
Sparkles,
} from "lucide-react";
import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { GuildSelector } from "@/components/shared/guild-selector";
import { messagesApi, voiceApi } from "@/lib/api";
import { formatBytes, safeParseJsonArray } from "@/lib/format";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
export default function MessagesPage() {
const [guildId, setGuildId] = useState("");
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 channels when guild changes
useEffect(() => {
if (!guildId) return;
voiceApi
.getTextChannels(guildId)
.then(setChannels)
.catch(() => {});
}, [guildId]);
const fetchMessages = useCallback(async () => {
if (!guildId) return;
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]);
const fetchImages = useCallback(async () => {
if (!guildId) return;
try {
const result = await messagesApi.getImages(guildId, 50);
setImageMessages(result.data);
} catch {
// silently fail
}
}, [guildId]);
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 subscriptions
useEffect(() => {
if (!guildId) return;
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, guildId]);
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]);
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);
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(guildId);
} catch {
// ignore
}
}, [guildId]);
const displayMessages = searchResults ?? messages;
const isEmpty = !loading && displayMessages.length === 0;
if (error) {
return (
<div className="space-y-5">
<GuildSelector value={guildId} onChange={setGuildId} />
<div className="flex flex-col items-center justify-center py-20 text-center">
<AlertCircle className="size-10 text-destructive mb-3" />
<p className="text-sm text-muted-foreground mb-4 max-w-sm">
{error}
</p>
<Button variant="outline" onClick={fetchMessages}>
<RefreshCw className="size-4 mr-2" />
Retry
</Button>
</div>
</div>
);
}
return (
<div className="space-y-5">
<GuildSelector value={guildId} onChange={setGuildId} />
{/* 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="pl-9 h-9"
/>
</div>
{channels.length > 0 && (
<Select
value={selectedChannel}
onValueChange={(v) => v && setSelectedChannel(v)}
>
<SelectTrigger className="h-9 w-full sm:w-44">
<SelectValue placeholder="All channels" />
</SelectTrigger>
<SelectContent>
<SelectItem value=" ">All channels</SelectItem>
{channels.map((ch) => (
<SelectItem key={ch.id} value={ch.id}>
# {ch.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
<Button variant="outline" size="sm" onClick={handleReanalyzeBatch}>
<RefreshCw className="size-4 mr-1.5" />
Reanalyze Errors
</Button>
</div>
{/* Tab bar */}
<Tabs
value={viewTab}
onValueChange={(v) => setViewTab(v as "all" | "images" | "review")}
>
<TabsList>
<TabsTrigger value="all" onClick={() => setViewTab("all")}>
All ({messages.length})
</TabsTrigger>
<TabsTrigger value="images" onClick={() => setViewTab("images")}>
Images ({imageMessages.length})
</TabsTrigger>
<TabsTrigger value="review" onClick={() => setViewTab("review")}>
<Flag className="size-3.5 mr-1" />
Review ({reviewMessages.length})
</TabsTrigger>
</TabsList>
</Tabs>
{/* Search results count */}
{searchResults !== null && (
<p className="text-sm text-muted-foreground animate-fade-in-up">
Found {searchResults.length} result
{searchResults.length !== 1 ? "s" : ""}
</p>
)}
{/* Messages feed */}
{viewTab === "all" ? (
<div className="space-y-2 animate-fade-in-up">
{loading ? (
<div className="space-y-3">
{Array.from({ length: 8 }, (_, i) => (
<Skeleton key={i} className="h-28 rounded-xl" />
))}
</div>
) : isEmpty ? (
<div className="flex flex-col items-center justify-center py-20 text-center">
<Search className="size-10 text-muted-foreground/40 mb-3" />
<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}
/>
))}
{hasMore && searchResults === null && (
<div className="flex justify-center py-6">
<Button
variant="outline"
onClick={handleLoadMore}
disabled={loadingMore}
>
{loadingMore && (
<Loader2 className="size-4 animate-spin mr-2" />
)}
{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 animate-fade-in-up">
{imageMessages.length === 0 ? (
<div className="col-span-full flex flex-col items-center justify-center py-20 text-center">
<ImageIcon className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">No images yet.</p>
</div>
) : (
imageMessages.map((msg) => {
let imageUrl: string | null = null;
try {
const meta = JSON.parse(msg.metadata ?? "{}");
const attachments: Array<{
url: string;
contentType?: string;
}> = meta.attachments ?? [];
const img = attachments.find((a) =>
a.contentType?.startsWith("image/"),
);
imageUrl = img?.url ?? null;
} catch {
// metadata malformed
}
return (
<Card
key={msg.id}
className="group relative overflow-hidden cursor-pointer"
onClick={() => handleMessageClick(msg.id)}
>
<div className="aspect-square relative bg-muted">
{imageUrl ? (
<Image
src={imageUrl}
alt={msg.content || "Image"}
fill
className="object-cover transition-transform duration-300 group-hover:scale-105"
sizes="(max-width: 768px) 50vw, 25vw"
/>
) : (
<div className="flex items-center justify-center size-full text-muted-foreground text-xs">
No image
</div>
)}
{msg.content && (
<div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-end p-3">
<p className="text-xs text-white/90 line-clamp-2">
{msg.username}: {msg.content}
</p>
</div>
)}
</div>
</Card>
);
})
)}
</div>
) : (
/* Review tab */
<div className="space-y-2 animate-fade-in-up">
{reviewMessages.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20 text-center">
<Flag className="size-10 text-muted-foreground/40 mb-3" />
<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 Dialog */}
<Dialog
open={detailMessage !== null}
onOpenChange={(open) => {
if (!open) setDetailMessage(null);
}}
>
<DialogContent className="sm:max-w-2xl max-h-[85vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<MessageSquare className="size-4" />
Message Detail
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[70vh] pr-1">
<div className="space-y-5">
{detailLoading ? (
<div className="flex justify-center py-12">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : detailMessage ? (
<>
<div className="flex items-start gap-3">
<Avatar className="size-10">
<AvatarImage
src={detailMessage.avatar_url ?? undefined}
/>
<AvatarFallback>
{detailMessage.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<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" && (
<Badge variant="destructive" className="text-[10px]">
deleted
</Badge>
)}
{detailMessage.type === "edited" && (
<Badge variant="outline" className="text-[10px]">
edited
</Badge>
)}
</div>
<p className="text-sm mt-2 whitespace-pre-wrap break-words leading-relaxed">
{detailMessage.content}
</p>
</div>
</div>
{detailMessage.ai_analysis && (
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<div className="flex items-center gap-2 mb-2">
<Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium">
AI Analysis
</p>
</div>
<p className="text-sm leading-relaxed">
{detailMessage.ai_analysis}
</p>
</div>
)}
{detailMessage.ai_moderation_flags &&
detailMessage.ai_moderation_flags !== "[]" && (
<div className="space-y-2">
<p className="text-xs text-muted-foreground font-medium">
Moderation Flags
</p>
<div className="flex flex-wrap gap-1.5">
{safeParseJsonArray(
detailMessage.ai_moderation_flags,
).map((flag) => (
<Badge
key={flag}
variant="destructive"
className="text-[11px]"
>
{flag}
</Badge>
))}
</div>
</div>
)}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{detailMessage.ai_status && (
<Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">
Status
</p>
<p className="text-sm font-medium mt-0.5 capitalize">
{detailMessage.ai_status}
</p>
</CardContent>
</Card>
)}
{detailMessage.ai_severity &&
detailMessage.ai_severity !== "none" && (
<Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">
Severity
</p>
<p className="text-sm font-medium mt-0.5 text-destructive capitalize">
{detailMessage.ai_severity}
</p>
</CardContent>
</Card>
)}
{detailMessage.ai_confidence != null && (
<Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">
Confidence
</p>
<p className="text-sm font-medium mt-0.5 tabular-nums">
{(detailMessage.ai_confidence * 100).toFixed(0)}%
</p>
</CardContent>
</Card>
)}
{detailMessage.ai_recommended_action &&
detailMessage.ai_recommended_action !== "none" && (
<Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">
Action
</p>
<p className="text-sm font-medium mt-0.5 capitalize">
{detailMessage.ai_recommended_action}
</p>
</CardContent>
</Card>
)}
</div>
{detailAttachments.length > 0 && (
<div className="space-y-2">
<p className="text-xs text-muted-foreground font-medium">
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 border-border/50 p-2 hover:bg-muted transition-colors group"
>
<div className="flex-1 min-w-0">
<p className="text-xs font-medium truncate">
{att.filename}
</p>
<p className="text-[11px] text-muted-foreground">
{att.type} · {formatBytes(att.size)}
</p>
</div>
<ExternalLink className="size-3 shrink-0 text-muted-foreground/50 group-hover:text-muted-foreground transition-colors" />
</a>
))}
</div>
</div>
)}
{detailMessage.metadata &&
detailMessage.metadata !== "{}" && (
<div className="space-y-1">
<p className="text-xs text-muted-foreground font-medium">
Metadata (raw)
</p>
<pre className="text-xs bg-muted/50 rounded-lg p-3 overflow-x-auto max-h-32 border border-border/50">
{JSON.stringify(
safeParseObject(detailMessage.metadata),
null,
2,
)}
</pre>
</div>
)}
</>
) : null}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
</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 border-green-500/20",
warn: "bg-yellow-500/15 text-yellow-600 dark:text-yellow-400 border-yellow-500/20",
flagged: "bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/20",
error: "bg-gray-500/15 text-gray-600 dark:text-gray-400 border-gray-500/20",
pending:
"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/20",
processing:
"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/20",
};
const severityLeftBorder: Record<string, string> = {
low: "border-l-sky-400",
medium: "border-l-yellow-400",
high: "border-l-orange-400",
critical: "border-l-red-500",
};
const hasSeverity =
msg.ai_severity &&
msg.ai_severity !== "none" &&
severityLeftBorder[msg.ai_severity];
return (
<Card
className={cn(
"cursor-pointer transition-all duration-200 hover:bg-accent/5 hover:shadow-sm",
hasSeverity && "border-l-2",
hasSeverity && severityLeftBorder[msg.ai_severity as string],
)}
onClick={() => onClick(msg.id)}
>
<CardContent className="p-4">
<div className="flex items-start gap-3">
<Avatar className="size-8 shrink-0 mt-0.5">
<AvatarImage src={msg.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{msg.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-2">
<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">
{new Date(msg.created_at).toLocaleString()}
</span>
<span className="text-xs text-muted-foreground">
<HashIcon className="size-3 inline mr-0.5" />
{msg.channel_id.slice(0, 8)}
</span>
{msg.ai_status && aiStatusColor[msg.ai_status] && (
<Badge
variant="outline"
className={cn(
"text-[10px] px-1.5 py-0 h-4 font-medium",
aiStatusColor[msg.ai_status],
)}
>
{msg.ai_status}
</Badge>
)}
{msg.ai_severity && msg.ai_severity !== "none" && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{msg.ai_severity}
</Badge>
)}
{msg.type === "deleted" && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
deleted
</Badge>
)}
{msg.type === "edited" && (
<Badge
variant="outline"
className="text-[10px] px-1.5 py-0 h-4"
>
edited
</Badge>
)}
</div>
<p
className={cn(
"text-sm leading-relaxed",
msg.type === "deleted" &&
"italic text-muted-foreground line-through",
)}
>
{msg.content}
</p>
{msg.ai_moderation_flags && msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(msg.ai_moderation_flags).map((flag) => (
<Badge
key={flag}
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{flag}
</Badge>
))}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
{msg.ai_analysis}
</p>
)}
{msg.ai_confidence !== undefined &&
msg.ai_confidence !== null && (
<div className="flex items-center gap-2 max-w-40">
<Progress
value={msg.ai_confidence * 100}
className="h-1.5"
/>
<span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
)}
<div className="flex gap-1.5 pt-0.5">
<Button
variant="ghost"
size="xs"
onClick={(e) => {
e.stopPropagation();
onReanalyze(msg.id);
}}
>
<RefreshCw className="size-3 mr-1" />
Reanalyze
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
);
}
// ── Helpers ─────────────────────────────────────
function safeParseObject(
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 HashIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
role="img"
aria-label="Hash"
>
<title>Hash</title>
<line x1="4" x2="20" y1="9" y2="9" />
<line x1="4" x2="20" y1="15" y2="15" />
<line x1="10" x2="8" y1="3" y2="21" />
<line x1="16" x2="14" y1="3" y2="21" />
</svg>
);
}
function ImageIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
role="img"
aria-label="Image"
>
<title>Image</title>
<rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</svg>
);
}
@@ -0,0 +1,134 @@
"use client";
import { Download, Headphones, Trash2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { recordingsApi } from "@/lib/api";
import { formatBytes } from "@/lib/format";
import type { VoiceRecording } from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context";
export default function RecordingsPage() {
const ws = useWebSocket();
const [recordings, setRecordings] = useState<VoiceRecording[]>([]);
const [loading, setLoading] = useState(true);
const fetchRecordings = useCallback(async () => {
setLoading(true);
try {
const result = await recordingsApi.list(50);
setRecordings(result.items);
} catch {
// ignore
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchRecordings();
}, [fetchRecordings]);
// WS subscription for live updates
useEffect(() => {
const unsub = ws.on("voice_recording_uploaded", (rec) => {
setRecordings((prev) => [rec as VoiceRecording, ...prev]);
});
return () => unsub();
}, [ws]);
const handleDelete = useCallback(async (id: string) => {
try {
await recordingsApi.delete(id);
setRecordings((prev) => prev.filter((r) => r.id !== id));
} catch {
// ignore
}
}, []);
return (
<div className="space-y-5 animate-fade-in-up">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Headphones className="size-4 text-primary" />
Voice Recordings
</CardTitle>
</CardHeader>
<CardContent>
{loading ? (
<div className="space-y-2">
{Array.from({ length: 5 }, (_, i) => (
<div
key={i}
className="h-16 rounded-lg bg-muted/30 animate-pulse"
/>
))}
</div>
) : recordings.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">
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 border-border/50 p-3 hover:bg-muted/30 transition-colors"
>
<Avatar className="size-8">
<AvatarImage src={rec.avatar_url ?? undefined} />
<AvatarFallback>
{(rec.username ?? "?").charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<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>
<Badge
variant="outline"
className="text-[10px] font-mono shrink-0"
>
{formatBytes(rec.size_bytes)}
</Badge>
{rec.download_url && (
<Button
variant="ghost"
size="icon"
onClick={() =>
window.open(rec.download_url!, "_blank")
}
>
<Download className="size-4" />
</Button>
)}
<Button
variant="ghost"
size="icon"
onClick={() => handleDelete(rec.id)}
className="hover:text-destructive hover:bg-destructive/10"
>
<Trash2 className="size-4" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,215 @@
"use client";
import {
Moon,
Server,
Shield,
Sun,
Wifi,
} from "lucide-react";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { configApi } from "@/lib/api";
import type { AppConfig } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
export default function SettingsPage() {
const { status } = useWebSocket();
const [config, setConfig] = useState<AppConfig | null>(null);
const [configLoading, setConfigLoading] = useState(true);
const [theme, setTheme] = useState<"light" | "dark">("dark");
useEffect(() => {
const stored = localStorage.getItem("theme") as "light" | "dark" | null;
if (stored) setTheme(stored);
}, []);
useEffect(() => {
configApi
.get()
.then(setConfig)
.catch(() => {})
.finally(() => setConfigLoading(false));
}, []);
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);
};
const statusConfig = {
connected: {
label: "Connected",
variant: "default" as const,
dot: "bg-green-500 shadow-[0_0_6px] shadow-green-500/60",
},
connecting: {
label: "Connecting",
variant: "secondary" as const,
dot: "bg-yellow-500 animate-pulse",
},
disconnected: {
label: "Disconnected",
variant: "destructive" as const,
dot: "bg-destructive",
},
error: {
label: "Error",
variant: "destructive" as const,
dot: "bg-destructive",
},
}[status];
return (
<div className="space-y-5 animate-fade-in-up max-w-2xl">
{/* Connection Status */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Wifi className="size-4 text-primary" />
Connection
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm">WebSocket</span>
<Badge
variant={statusConfig.variant}
className="gap-1.5 px-2.5 py-1"
>
<span
className={cn("size-1.5 rounded-full", statusConfig.dot)}
/>
{statusConfig.label}
</Badge>
</div>
</CardContent>
</Card>
{/* Appearance */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
{theme === "dark" ? (
<Moon className="size-4 text-primary" />
) : (
<Sun className="size-4 text-primary" />
)}
Appearance
</CardTitle>
</CardHeader>
<CardContent>
<button
type="button"
onClick={toggleTheme}
className="flex items-center justify-between w-full text-sm cursor-pointer"
>
<span>Theme</span>
<Badge variant="outline" className="capitalize">
{theme}
</Badge>
</button>
</CardContent>
</Card>
{/* Server Config */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Server className="size-4 text-primary" />
Server Configuration
</CardTitle>
</CardHeader>
<CardContent>
{configLoading ? (
<div className="space-y-2">
{Array.from({ length: 6 }, (_, i) => (
<Skeleton key={i} className="h-6 w-full" />
))}
</div>
) : config ? (
<div className="space-y-2 text-sm">
<ConfigRow
label="Monitor Guild"
value={config.monitorGuildId ?? "Not configured"}
/>
<Separator />
<ConfigRow
label="Voice Guild"
value={config.voiceGuildId ?? "Not configured"}
/>
<Separator />
<ConfigRow
label="Voice Channel"
value={config.voiceChannelId ?? "Not configured"}
/>
<Separator />
<ConfigRow
label="AI Analysis"
value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"}
/>
<Separator />
<ConfigRow
label="Auto-Delete Flagged"
value={
config.autoDeleteFlaggedEnabled ? "Enabled" : "Disabled"
}
/>
</div>
) : (
<p className="text-sm text-muted-foreground">
Unable to load configuration.
</p>
)}
</CardContent>
</Card>
{/* About */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Shield className="size-4 text-primary" />
About
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-sm space-y-1">
<p>
<span className="text-gradient font-bold">Bete</span> Discord
Moderation Watcher
</p>
<p className="text-xs text-muted-foreground">
AI-powered message moderation, voice recording, and real-time
monitoring for Discord communities.
</p>
</div>
</CardContent>
</Card>
</div>
);
}
function ConfigRow({
label,
value,
}: {
label: string;
value: string;
}) {
return (
<div className="flex items-center justify-between py-1">
<span className="text-muted-foreground">{label}</span>
<span className="font-mono text-xs max-w-[280px] truncate text-right">
{value}
</span>
</div>
);
}
@@ -0,0 +1,323 @@
"use client";
import {
Headphones,
Loader2,
Mic,
Radio,
RadioOff,
UserCheck,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { voiceApi } from "@/lib/api";
import type { ActiveSpeaker, VoiceStatus } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
export default function VoicePage() {
const ws = useWebSocket();
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);
const [guildsLoading, setGuildsLoading] = useState(true);
const fetchVoiceStatus = useCallback(async () => {
try {
const status = await voiceApi.getStatus();
setVoiceStatus(status);
} catch {
// ignore
}
}, []);
const fetchGuilds = useCallback(async () => {
setGuildsLoading(true);
try {
const g = await voiceApi.getGuilds();
setGuilds(g);
} catch {
// ignore
} finally {
setGuildsLoading(false);
}
}, []);
useEffect(() => {
fetchVoiceStatus();
fetchGuilds();
}, [fetchVoiceStatus, fetchGuilds]);
// WS subscriptions
useEffect(() => {
const unsubSpeaker = ws.on("voice_active_user", (user) => {
const speaker = user as ActiveSpeaker;
setSpeakers((prev) => {
const existing = prev.findIndex(
(s) => s.userId === speaker.userId,
);
if (existing >= 0) {
const next = [...prev];
next[existing] = speaker;
return next;
}
return [...prev, speaker];
});
});
return () => {
unsubSpeaker();
};
}, [ws]);
const handleGuildChange = useCallback(async (guildId: string | null) => {
if (!guildId) {
setSelectedGuild("");
setVoiceChannels([]);
return;
}
setSelectedGuild(guildId);
setSelectedChannel("");
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);
setSpeakers([]);
} finally {
setVoiceLoading(false);
}
}, []);
const activeSpeakers = speakers.filter((s) => s.speaking);
return (
<div className="space-y-5 animate-fade-in-up">
{/* Voice Connection */}
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Radio className="size-4 text-primary" />
Voice Connection
</div>
<Badge
variant={voiceStatus?.connected ? "default" : "secondary"}
className={cn(
voiceStatus?.connected &&
"bg-green-500/15 text-green-600 dark:text-green-400 hover:bg-green-500/20",
)}
>
<span
className={cn(
"size-1.5 rounded-full mr-1.5 inline-block",
voiceStatus?.connected
? "bg-green-500 shadow-[0_0_6px] shadow-green-500/60"
: "bg-muted-foreground",
)}
/>
{voiceStatus?.connected ? "Connected" : "Disconnected"}
</Badge>
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{voiceStatus?.connected && voiceStatus.activeChannelName && (
<p className="text-sm text-muted-foreground flex items-center gap-1.5">
<Headphones className="size-4" />
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}
onValueChange={handleGuildChange}
disabled={guildsLoading}
>
<SelectTrigger className="flex-1 h-9">
<SelectValue
placeholder={
guildsLoading ? "Loading guilds…" : "Select guild…"
}
/>
</SelectTrigger>
<SelectContent>
{guilds.map((g) => (
<SelectItem key={g.id} value={g.id}>
{g.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={selectedChannel}
onValueChange={(v) => v && setSelectedChannel(v)}
disabled={!selectedGuild}
>
<SelectTrigger className="flex-1 h-9">
<SelectValue placeholder="Select channel…" />
</SelectTrigger>
<SelectContent>
{voiceChannels.map((c) => (
<SelectItem key={c.id} value={c.id}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
{voiceStatus?.connected ? (
<Button
variant="destructive"
onClick={handleDisconnect}
disabled={voiceLoading}
>
{voiceLoading ? (
<Loader2 className="size-4 animate-spin mr-1.5" />
) : (
<RadioOff className="size-4 mr-1.5" />
)}
Disconnect
</Button>
) : (
<Button
onClick={handleConnect}
disabled={
voiceLoading || !selectedGuild || !selectedChannel
}
>
{voiceLoading ? (
<Loader2 className="size-4 animate-spin mr-1.5" />
) : (
<Radio className="size-4 mr-1.5" />
)}
Connect
</Button>
)}
</div>
</CardContent>
</Card>
{/* Active Speakers */}
{activeSpeakers.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<UserCheck className="size-4 text-primary" />
Active Speakers
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{activeSpeakers.map((s) => (
<div
key={s.userId}
className="flex items-center gap-2 rounded-full border border-border/50 bg-card px-3 py-1.5 shadow-sm"
>
<span className="relative flex size-2">
<span className="absolute inline-flex size-full rounded-full bg-green-400 opacity-75 live-pulse-ring" />
<span className="relative inline-flex size-2 rounded-full bg-green-500" />
</span>
<span className="text-sm">{s.username}</span>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* Microphone */}
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2 text-sm font-semibold">
<Mic className="size-4 text-primary" />
Microphone
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
{micActive ? "On" : "Off"}
</span>
<Switch
checked={micActive}
onCheckedChange={async (checked) => {
setMicActive(checked);
try {
await voiceApi.sendCommand(
checked
? "voice:transmit:start"
: "voice:transmit:stop",
);
} catch {
setMicActive(!checked);
}
}}
disabled={!voiceStatus?.connected}
/>
</div>
</CardTitle>
</CardHeader>
<CardContent>
{!voiceStatus?.connected && (
<p className="text-xs text-muted-foreground">
Connect to a voice channel first.
</p>
)}
{micActive && (
<div className="flex items-center gap-2 mt-1">
<span className="relative flex size-2">
<span className="absolute inline-flex size-full rounded-full bg-red-400 opacity-75 live-pulse-ring" />
<span className="relative inline-flex size-2 rounded-full bg-red-500" />
</span>
<span className="text-sm text-muted-foreground">
Transmitting
</span>
</div>
)}
</CardContent>
</Card>
</div>
);
}
@@ -1,87 +0,0 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useRef } from "react";
import { Header } from "@/components/layout/header";
import { MobileTabBar } from "@/components/layout/mobile-tab-bar";
import { Sidebar } from "@/components/layout/sidebar";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { MascotChatbot } from "@/features/mascot/mascot-chatbot";
import { uiStateApi } from "@/lib/api";
import { WsProvider } from "@/lib/ws/context";
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;
}
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="flex min-h-screen bg-background">
<Sidebar activeTab={activeTab} />
<SidebarInset className="flex flex-col">
<Header />
<main className="flex-1 p-4 md:p-6 pb-20 md:pb-6 animate-fade-in-up">
{children}
</main>
</SidebarInset>
<MobileTabBar activeTab={activeTab} />
</div>
);
}
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<WsProvider>
<SidebarProvider defaultOpen={true}>
<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>
</SidebarProvider>
<MascotChatbot />
</WsProvider>
);
}
@@ -1,209 +0,0 @@
"use client";
import { AlertCircle, RefreshCw } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { DashboardPanel } from "@/features/dashboard/dashboard-panel";
import { LivePanel } from "@/features/live/live-panel";
import { MessagesPanel } from "@/features/messages/messages-panel";
import { voiceApi } from "@/lib/api";
import { useAppConfig } from "@/lib/hooks/use-config";
import type { Guild } from "@/lib/types";
export default function DashboardPage() {
const searchParams = useSearchParams();
const tab = searchParams.get("tab") ?? "messages";
const urlGuildId = searchParams.get("guildId");
const { config, loading: configLoading } = useAppConfig();
const [guilds, setGuilds] = useState<Guild[]>([]);
const [guildsLoading, setGuildsLoading] = useState(true);
const [guildsError, setGuildsError] = useState<string | null>(null);
const [selectedGuildId, setSelectedGuildId] = useState("");
// Resolve the active guild ID from:
// 1. URL param (?guildId=xxx)
// 2. Config monitorGuildId
// 3. First available guild from /api/guilds
// 4. Empty (user needs to select)
const resolveGuild = useCallback(() => {
if (urlGuildId) return urlGuildId;
if (config?.monitorGuildId) return config.monitorGuildId;
if (guilds.length > 0) return guilds[0].id;
return "";
}, [urlGuildId, config?.monitorGuildId, guilds]);
// Fetch guilds list from backend
useEffect(() => {
let cancelled = false;
setGuildsLoading(true);
setGuildsError(null);
voiceApi
.getGuilds()
.then((g) => {
if (!cancelled) setGuilds(g);
})
.catch((err) => {
if (!cancelled)
setGuildsError(
err instanceof Error ? err.message : "Failed to load guilds",
);
})
.finally(() => {
if (!cancelled) setGuildsLoading(false);
});
return () => {
cancelled = true;
};
}, []);
// Resolve guild ID once config and guilds are loaded
useEffect(() => {
if (configLoading || guildsLoading) return;
const resolved = resolveGuild();
if (resolved && resolved !== selectedGuildId) {
setSelectedGuildId(resolved);
}
}, [configLoading, guildsLoading, resolveGuild, selectedGuildId]);
const handleGuildChange = useCallback((guildId: string | null) => {
if (guildId) setSelectedGuildId(guildId);
}, []);
const handleRetry = useCallback(() => {
setGuildsLoading(true);
setGuildsError(null);
voiceApi
.getGuilds()
.then(setGuilds)
.catch((err) =>
setGuildsError(
err instanceof Error ? err.message : "Failed to load guilds",
),
)
.finally(() => setGuildsLoading(false));
}, []);
const isReady = !configLoading && !guildsLoading;
return (
<div className="space-y-5">
{/* Guild selector bar */}
<GuildBar
guilds={guilds}
loading={guildsLoading}
error={guildsError}
selectedGuildId={selectedGuildId}
onChange={handleGuildChange}
onRetry={handleRetry}
/>
{/* Main panel */}
{isReady ? (
<div className="animate-fade-in-up">
{tab === "live" && <LivePanel />}
{tab === "dashboard" && <DashboardPanel guildId={selectedGuildId} />}
{tab === "messages" && <MessagesPanel guildId={selectedGuildId} />}
</div>
) : (
<div className="flex items-center justify-center py-24">
<div className="flex flex-col items-center gap-3">
<div className="size-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<p className="text-sm text-muted-foreground">Loading dashboard</p>
</div>
</div>
)}
</div>
);
}
// ── Guild Bar ────────────────────────────────────
function GuildBar({
guilds,
loading,
error,
selectedGuildId,
onChange,
onRetry,
}: {
guilds: Guild[];
loading: boolean;
error: string | null;
selectedGuildId: string;
onChange: (id: string | null) => void;
onRetry: () => void;
}) {
// No guild bar if there's only one guild and it's already selected
if (guilds.length <= 1 && !loading && !error) return null;
if (loading) {
return (
<div className="flex items-center gap-3 rounded-xl border border-border/50 bg-card p-3">
<Skeleton className="h-8 w-36" />
<Skeleton className="h-8 w-8 rounded-full" />
</div>
);
}
if (error) {
return (
<div className="flex items-center justify-between rounded-xl border border-destructive/20 bg-destructive/5 p-3">
<div className="flex items-center gap-2">
<AlertCircle className="size-4 text-destructive shrink-0" />
<p className="text-sm text-muted-foreground">
Could not load guilds: {error}
</p>
</div>
<Button variant="outline" size="sm" onClick={onRetry}>
<RefreshCw className="size-3 mr-1" />
Retry
</Button>
</div>
);
}
if (guilds.length === 0) {
return (
<div className="rounded-xl border border-yellow-500/20 bg-yellow-500/5 p-3">
<div className="flex items-center gap-2">
<AlertCircle className="size-4 text-yellow-500 shrink-0" />
<p className="text-sm text-muted-foreground">
No guilds available. Make sure the Discord gateway is connected.
</p>
</div>
</div>
);
}
return (
<div className="flex items-center gap-3 rounded-xl border border-border/50 bg-card p-3">
<Badge variant="outline" className="shrink-0 text-xs font-normal">
Guild
</Badge>
<Select value={selectedGuildId} onValueChange={onChange}>
<SelectTrigger className="h-8 w-full max-w-xs">
<SelectValue placeholder="Select a guild…" />
</SelectTrigger>
<SelectContent>
{guilds.map((g) => (
<SelectItem key={g.id} value={g.id}>
{g.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
export default function RootPage() {
redirect("/dashboard?tab=messages");
redirect("/messages");
}