refactor(fe): align dashboard with backend & gateway data flow

- API/WS clients: same-origin by default, drop dead imphnen hardcode
- chatbot history: map BE rows {user_message,bot_response,created_at}
- message_deleted WS payload: object {id,deleted_at}, not bare string
- dashboard: wire top-channels chart + live mod queue from /api/review,
  add Users & Channels tabs consuming /api/dashboard/users|channels
- recordings: live WS sync via voice_recording_uploaded; duration_bytes optional
- remove dead widgets with no BE data source (trend chart, heatmap)
This commit is contained in:
Developer
2026-07-31 16:54:41 +07:00
parent 2addfb6492
commit 69213ebd75
17 changed files with 611 additions and 224 deletions
@@ -10,9 +10,15 @@ import {
useState,
} from "react";
import { chatbotApi } from "@/lib/api";
import type { ChatHistoryMessage } from "@/lib/types";
import type { ChatbotHistoryRow } from "@/lib/types";
export type ChatbotExpression = "idle" | "listening" | "surprise" | "happy" | "sad" | "talking";
export type ChatbotExpression =
| "idle"
| "listening"
| "surprise"
| "happy"
| "sad"
| "talking";
interface ChatbotMessage {
role: "user" | "assistant";
@@ -74,16 +80,29 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
if (historyFetched.current) return;
historyFetched.current = true;
chatbotApi.getHistory().then((history) => {
const mapped = (history ?? []).map((msg: ChatHistoryMessage) => ({
role: msg.role as "user" | "assistant",
content: msg.content,
timestamp: msg.timestamp,
}));
setMessages(mapped);
}).catch(() => {
// API may not be available yet — silently ignore
});
chatbotApi
.getHistory()
.then((res) => {
// Backend returns rows {user_message, bot_response, created_at} —
// interleave each user message with its bot reply.
const withReplies: ChatbotMessage[] = [];
for (const row of res.history ?? []) {
withReplies.push({
role: "user",
content: row.user_message,
timestamp: row.created_at,
});
withReplies.push({
role: "assistant",
content: row.bot_response,
timestamp: row.created_at,
});
}
setMessages(withReplies);
})
.catch(() => {
// API may not be available yet — silently ignore
});
}, []);
const sendMessage = useCallback(async (content: string) => {
@@ -1,62 +0,0 @@
"use client";
import { GlassCard } from "@/components/glass/card";
import { cn } from "@/lib/utils";
const HOURS = Array.from({ length: 24 }, (_, i) => i);
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
interface ActivityHeatmapProps {
data?: Record<string, number>; // key: "day-hour", value: count
}
export function ActivityHeatmap({ data = {} }: ActivityHeatmapProps) {
const maxVal = Math.max(...Object.values(data), 1);
const getIntensity = (day: string, hour: number) => {
const val = data[`${day}-${hour}`] || 0;
const pct = val / maxVal;
if (pct === 0) return "bg-surface";
if (pct < 0.25) return "bg-primary/15";
if (pct < 0.5) return "bg-primary/30";
if (pct < 0.75) return "bg-primary/50";
return "bg-primary/70";
};
return (
<GlassCard variant="base">
<div className="flex items-center gap-2 mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">Activity</span>
<span className="text-[10px] text-text-secondary/40">hour × day</span>
</div>
<div className="overflow-x-auto">
<div className="flex gap-0.5 min-w-[400px]">
{/* Hour labels */}
<div className="flex flex-col gap-0.5 mr-1">
<div className="h-4" />
{DAYS.map((d) => (
<div key={d} className="h-3 flex items-center text-[8px] text-text-secondary/40 font-mono">{d}</div>
))}
</div>
{/* Grid */}
<div className="flex gap-0.5">
{HOURS.map((hour) => (
<div key={hour} className="flex flex-col gap-0.5">
{DAYS.map((day) => (
<div
key={`${day}-${hour}`}
className={cn("size-3 rounded-sm transition-colors", getIntensity(day, hour))}
title={`${day} ${hour}:00 — ${data[`${day}-${hour}`] || 0}`}
/>
))}
<div className="h-3 flex items-center justify-center text-[8px] text-text-secondary/30 font-mono">
{hour % 4 === 0 ? hour : ""}
</div>
</div>
))}
</div>
</div>
</div>
</GlassCard>
);
}
@@ -0,0 +1,182 @@
"use client";
import { Hash, Search } from "lucide-react";
import { useCallback, useState } from "react";
import { GlassCard } from "@/components/glass/card";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
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 { useChannelDetail, useChannels } from "@/hooks";
import type { DashboardChannel } from "@/lib/types";
export function ChannelsSection({ guildId }: { guildId?: string }) {
const [search, setSearch] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const {
data: channels = [],
isLoading,
error,
refetch,
} = useChannels(guildId ?? "", search);
const { data: detail } = useChannelDetail(selectedId);
const handleSearch = useCallback((v: string) => {
setSearch(v);
setSelectedId(null);
}, []);
if (error) {
return (
<GlassCard variant="danger" className="p-6 text-sm">
Failed to load channels: {error.message}
<Button
variant="outline"
size="sm"
className="ml-2"
onClick={() => refetch()}
>
Retry
</Button>
</GlassCard>
);
}
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by channel ID or name…"
value={search}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9 h-9"
/>
</div>
{isLoading ? (
<LoadingSkeleton count={5} height="h-14" />
) : channels.length === 0 ? (
<EmptyState icon={Hash} title="No channels found" />
) : (
<div className="space-y-2">
{channels.map((channel) => (
<ChannelRow
key={channel.channel_id}
channel={channel}
active={selectedId === channel.channel_id}
onSelect={setSelectedId}
/>
))}
</div>
)}
</div>
<GlassCard variant="base" className="h-fit">
{detail ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Hash className="size-4 text-primary" />
<p className="text-sm font-semibold text-text-primary">
{detail.channel_name ?? detail.channel_id}
</p>
<p className="text-[10px] font-mono text-text-secondary/50 ml-auto">
{detail.channel_id}
</p>
</div>
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline">Messages: {detail.total_messages}</Badge>
<Badge variant="destructive">
Flagged: {detail.flagged_count}
</Badge>
<Badge
variant="outline"
className="border-green-500/40 text-green-500"
>
Clean: {detail.clean_count}
</Badge>
</div>
{detail.culture_summary && (
<div className="rounded-lg border border-border/40 bg-card/40 px-3 py-2">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50 mb-1">
Culture summary
</p>
<p className="text-xs leading-relaxed text-text-secondary">
{detail.culture_summary}
</p>
</div>
)}
{detail.recent_messages.length > 0 && (
<div className="space-y-1.5">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
Recent messages
</p>
{detail.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2"
>
<p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{msg.username}: {msg.content || "(no text content)"}
</p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{new Date(msg.created_at).toLocaleString()}
</p>
</div>
))}
</div>
)}
</div>
) : (
<div className="flex h-48 flex-col items-center justify-center text-center">
<Hash className="size-8 text-text-secondary/30 mb-2" />
<p className="text-xs text-text-secondary/60">
Select a channel to see its culture summary and recent messages.
</p>
</div>
)}
</GlassCard>
</div>
);
}
function ChannelRow({
channel,
active,
onSelect,
}: {
channel: DashboardChannel;
active: boolean;
onSelect: (id: string) => void;
}) {
return (
<Card
className={active ? "border-primary/40 bg-primary/5" : undefined}
onClick={() => onSelect(channel.channel_id)}
>
<CardContent className="flex cursor-pointer items-center gap-3 p-3">
<Hash className="size-4 shrink-0 text-text-secondary/50" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-text-primary">
{channel.channel_name ?? channel.channel_id}
</p>
<p className="truncate text-[10px] font-mono text-text-secondary/50">
{channel.channel_id}
</p>
</div>
<div className="flex shrink-0 gap-1.5">
<Badge variant="outline">{channel.total_messages}</Badge>
{channel.flagged_count > 0 && (
<Badge variant="destructive">{channel.flagged_count}</Badge>
)}
</div>
</CardContent>
</Card>
);
}
@@ -2,8 +2,9 @@
import { useEffect, useRef, useState } from "react";
import { GlassCard } from "@/components/glass/card";
import { useWebSocket } from "@/lib/ws/context";
import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
interface LiveMessage {
id: string;
@@ -20,12 +21,23 @@ export function LiveStream() {
const ws = useWebSocket();
useEffect(() => {
const unsub = ws.on("message_created", (data: any) => {
const unsub = ws.on("message_created", (data: MessageRecord) => {
// channel name lives inside the metadata JSON (channel.channelName)
let channelName: string | undefined;
try {
const meta =
typeof data.metadata === "string"
? JSON.parse(data.metadata)
: data.metadata;
channelName = meta?.channel?.channelName;
} catch {
channelName = undefined;
}
const msg: LiveMessage = {
id: data.id,
content: data.content || "(attachment)",
username: data.username || "unknown",
channelName: data.channelName,
channelName,
timestamp: new Date().toLocaleTimeString(),
flagged: data.ai_status === "flagged" || data.ai_status === "warn",
};
@@ -34,12 +46,6 @@ export function LiveStream() {
return () => unsub();
}, [ws]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = 0;
}
}, [messages]);
return (
<GlassCard variant="base" className="p-0 overflow-hidden">
<div className="flex items-center gap-2 px-4 py-2.5 border-b border-glass-border">
@@ -51,7 +57,10 @@ export function LiveStream() {
Live Stream
</span>
</div>
<div ref={scrollRef} className="overflow-y-auto max-h-[320px] space-y-0.5 p-2">
<div
ref={scrollRef}
className="overflow-y-auto max-h-[320px] space-y-0.5 p-2"
>
{messages.length === 0 ? (
<div className="flex items-center justify-center py-8 text-text-secondary/40 text-xs">
Waiting for messages...
@@ -1,48 +0,0 @@
"use client";
import { GlassCard } from "@/components/glass/card";
import { Area, AreaChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
interface MessageTrendChartProps {
data?: { date: string; messages: number; flagged: number }[];
}
export function MessageTrendChart({ data = [] }: MessageTrendChartProps) {
return (
<GlassCard variant="base">
<div className="flex items-center gap-2 mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">Message Trend</span>
<span className="text-[10px] text-text-secondary/40">7 days</span>
</div>
<div className="h-48">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data}>
<defs>
<linearGradient id="trend-msg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="var(--color-primary)" stopOpacity={0.3} />
<stop offset="100%" stopColor="var(--color-primary)" stopOpacity={0} />
</linearGradient>
<linearGradient id="trend-flag" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="var(--color-destructive)" stopOpacity={0.3} />
<stop offset="100%" stopColor="var(--color-destructive)" stopOpacity={0} />
</linearGradient>
</defs>
<XAxis dataKey="date" axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} />
<YAxis axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} />
<Tooltip
contentStyle={{
background: "oklch(0.11 0.02 245 / 0.9)",
border: "1px solid oklch(1 0 0 / 0.08)",
borderRadius: 8,
fontSize: 12,
color: "oklch(0.93 0.01 245)",
}}
/>
<Area type="monotone" dataKey="messages" stroke="var(--color-primary)" strokeWidth={2} fill="url(#trend-msg)" />
<Area type="monotone" dataKey="flagged" stroke="var(--color-destructive)" strokeWidth={1.5} fill="url(#trend-flag)" />
</AreaChart>
</ResponsiveContainer>
</div>
</GlassCard>
);
}
@@ -4,7 +4,7 @@ import { AlertCircle, Check, Trash2 } from "lucide-react";
import { GlassCard } from "@/components/glass/card";
import { cn } from "@/lib/utils";
interface ModQueueItem {
export interface ModQueueItem {
id: string;
content: string;
username: string;
@@ -48,16 +48,30 @@ export function ModQueue({ items = [] }: { items?: ModQueueItem[] }) {
)}
>
<div className="flex items-center gap-2">
<span className="font-medium text-xs text-text-primary">{item.username}</span>
<span className="text-[10px] font-mono uppercase text-text-secondary/60">{item.severity}</span>
<span className="font-medium text-xs text-text-primary">
{item.username}
</span>
<span className="text-[10px] font-mono uppercase text-text-secondary/60">
{item.severity}
</span>
</div>
<p className="text-xs text-text-secondary line-clamp-1">{item.content}</p>
<p className="text-[10px] text-text-secondary/50">{item.reason}</p>
<p className="text-xs text-text-secondary line-clamp-1">
{item.content}
</p>
<p className="text-[10px] text-text-secondary/50">
{item.reason}
</p>
<div className="flex gap-1 pt-1">
<button type="button" className="size-6 flex items-center justify-center rounded bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20 text-xs">
<button
type="button"
className="size-6 flex items-center justify-center rounded bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20 text-xs"
>
<Check className="size-3" />
</button>
<button type="button" className="size-6 flex items-center justify-center rounded bg-destructive/10 text-destructive hover:bg-destructive/20 text-xs">
<button
type="button"
className="size-6 flex items-center justify-center rounded bg-destructive/10 text-destructive hover:bg-destructive/20 text-xs"
>
<Trash2 className="size-3" />
</button>
</div>
@@ -0,0 +1,200 @@
"use client";
import { Search, Users, UserX } from "lucide-react";
import { useCallback, useState } from "react";
import { GlassCard } from "@/components/glass/card";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
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 { useUserDetail, useUsers } from "@/hooks";
import type { DashboardUser } from "@/lib/types";
export function UsersSection() {
const [search, setSearch] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: users = [], isLoading, error, refetch } = useUsers(search);
const { data: detail } = useUserDetail(selectedId);
const handleSearch = useCallback((v: string) => {
setSearch(v);
setSelectedId(null);
}, []);
if (error) {
return (
<GlassCard variant="danger" className="p-6 text-sm">
Failed to load users: {error.message}
<Button
variant="outline"
size="sm"
className="ml-2"
onClick={() => refetch()}
>
Retry
</Button>
</GlassCard>
);
}
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by user ID or username…"
value={search}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9 h-9"
/>
</div>
{isLoading ? (
<LoadingSkeleton count={5} height="h-16" />
) : users.length === 0 ? (
<EmptyState icon={Users} title="No users found" />
) : (
<div className="space-y-2">
{users.map((user) => (
<UserRow
key={user.user_id}
user={user}
active={selectedId === user.user_id}
onSelect={setSelectedId}
/>
))}
</div>
)}
</div>
<GlassCard variant="base" className="h-fit">
{detail ? (
<div className="space-y-3">
<div className="flex items-center gap-3">
<Avatar className="size-10">
<AvatarImage src={detail.avatar_url ?? undefined} />
<AvatarFallback>
{detail.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="text-sm font-semibold text-text-primary">
{detail.username ?? "Unknown user"}
</p>
<p className="text-[10px] font-mono text-text-secondary/50">
{detail.user_id}
</p>
</div>
</div>
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline">Messages: {detail.total_messages}</Badge>
<Badge variant="destructive">
Flagged: {detail.flagged_count}
</Badge>
<Badge
variant="outline"
className="border-green-500/40 text-green-500"
>
Clean: {detail.clean_count}
</Badge>
{detail.trust_score != null && (
<Badge variant="outline">Trust: {detail.trust_score}</Badge>
)}
{detail.clean_message_streak != null && (
<Badge variant="outline">
Streak: {detail.clean_message_streak}
</Badge>
)}
{detail.total_infractions != null && (
<Badge variant="destructive">
Infractions: {detail.total_infractions}
</Badge>
)}
</div>
{detail.profile_summary && (
<p className="text-xs leading-relaxed text-text-secondary">
{detail.profile_summary}
</p>
)}
{detail.recent_messages.length > 0 && (
<div className="space-y-1.5">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
Recent messages
</p>
{detail.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2"
>
<p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{msg.content || "(no text content)"}
</p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{msg.channel_id?.slice(0, 8)} ·{" "}
{new Date(msg.created_at).toLocaleString()}
</p>
</div>
))}
</div>
)}
</div>
) : (
<div className="flex h-48 flex-col items-center justify-center text-center">
<UserX className="size-8 text-text-secondary/30 mb-2" />
<p className="text-xs text-text-secondary/60">
Select a user to see their profile, trust score and recent
messages.
</p>
</div>
)}
</GlassCard>
</div>
);
}
function UserRow({
user,
active,
onSelect,
}: {
user: DashboardUser;
active: boolean;
onSelect: (id: string) => void;
}) {
return (
<Card
className={active ? "border-primary/40 bg-primary/5" : undefined}
onClick={() => onSelect(user.user_id)}
>
<CardContent className="flex cursor-pointer items-center gap-3 p-3">
<Avatar className="size-8 shrink-0">
<AvatarImage src={user.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{user.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-text-primary">
{user.username ?? "Unknown user"}
</p>
<p className="truncate text-[10px] font-mono text-text-secondary/50">
{user.user_id}
</p>
</div>
<div className="flex shrink-0 gap-1.5">
<Badge variant="outline">{user.total_messages}</Badge>
{user.flagged_count > 0 && (
<Badge variant="destructive">{user.flagged_count}</Badge>
)}
</div>
</CardContent>
</Card>
);
}