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,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 [];
}
}