Compare commits
2
Commits
6df4f306dd
...
01c18b2060
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01c18b2060 | ||
|
|
1f91f99de3 |
@@ -1,6 +1,9 @@
|
||||
import { createChildLogger } from "@/shared/logger/index";
|
||||
import { encoding_for_model as encodingForModel } from "tiktoken";
|
||||
import { formatMediaEvidenceForPrompt } from "../message-capture/messageMetadata.js";
|
||||
import {
|
||||
formatMediaEvidenceForPrompt,
|
||||
renderDiscordMentions,
|
||||
} from "../message-capture/messageMetadata.js";
|
||||
import type { MessageRecord } from "../message-capture/types.js";
|
||||
import { sanitizeDiscordTokens } from "./discordTokens.js";
|
||||
|
||||
@@ -101,7 +104,7 @@ export function formatMessageForPrompt(
|
||||
label: "context" | "target",
|
||||
): string {
|
||||
const content = sanitizeDiscordTokens(
|
||||
msg.edited_content ?? msg.content,
|
||||
renderDiscordMentions(msg.edited_content ?? msg.content, msg.metadata),
|
||||
);
|
||||
const timestamp = formatTimestamp(msg.created_at);
|
||||
const mediaEvidence = formatMediaEvidenceForPrompt(msg.metadata);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import { messageStore } from "../message-capture/messageStore.js";
|
||||
import type { MessageRecord } from "../message-capture/types.js";
|
||||
import { renderDiscordMentions } from "../message-capture/messageMetadata.js";
|
||||
import { sanitizeDiscordTokens } from "./discordTokens.js";
|
||||
|
||||
/** Simple XML-escaping for content text. */
|
||||
@@ -30,7 +31,9 @@ export function getAnalysisContent(message: MessageRecord): string {
|
||||
/\[(?:Attachment|Sticker):[^\]]*\]|\[Embed\]/g,
|
||||
"",
|
||||
);
|
||||
return sanitizeDiscordTokens(stripped).trim();
|
||||
return sanitizeDiscordTokens(
|
||||
renderDiscordMentions(stripped, message.metadata),
|
||||
).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,6 +28,16 @@ export interface CustomEmojiEvidence {
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface MentionedRoleEvidence {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface MentionedUserEvidence {
|
||||
id: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface EmbedEvidence {
|
||||
title: string | null;
|
||||
description: string | null;
|
||||
@@ -64,6 +74,8 @@ export interface RichMessageMetadata {
|
||||
embeds: Array<EmbedEvidence>;
|
||||
attachments: Array<AttachmentEvidence>;
|
||||
customEmojis: Array<CustomEmojiEvidence>;
|
||||
mentionedRoles: Array<MentionedRoleEvidence>;
|
||||
mentionedUsers: Array<MentionedUserEvidence>;
|
||||
author: {
|
||||
id: string;
|
||||
username: string;
|
||||
@@ -268,6 +280,12 @@ export function getMessageMetadata(message: Message): RichMessageMetadata {
|
||||
embeds: getEmbedMetadata(message),
|
||||
attachments: getAttachmentMetadata(message),
|
||||
customEmojis: getCustomEmojiMetadata(message),
|
||||
mentionedRoles: Array.from(message.mentions?.roles?.values() ?? []).map(
|
||||
(role) => ({ id: role.id, name: role.name }),
|
||||
),
|
||||
mentionedUsers: Array.from(message.mentions?.users?.values() ?? []).map(
|
||||
(user) => ({ id: user.id, username: user.username }),
|
||||
),
|
||||
author: {
|
||||
id: message.author.id,
|
||||
username: message.author.username,
|
||||
@@ -315,6 +333,12 @@ export function parseRichMessageMetadata(
|
||||
customEmojis: Array.isArray(parsed.customEmojis)
|
||||
? parsed.customEmojis
|
||||
: [],
|
||||
mentionedRoles: Array.isArray(parsed.mentionedRoles)
|
||||
? parsed.mentionedRoles
|
||||
: [],
|
||||
mentionedUsers: Array.isArray(parsed.mentionedUsers)
|
||||
? parsed.mentionedUsers
|
||||
: [],
|
||||
author: parsed.author as RichMessageMetadata["author"],
|
||||
member: (parsed.member ?? null) as RichMessageMetadata["member"],
|
||||
channel: parsed.channel as RichMessageMetadata["channel"],
|
||||
@@ -463,3 +487,44 @@ export function getDisplayContent(message: Message): string {
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders Discord mention/emoji tokens in message content to readable names
|
||||
* using the captured metadata (mentionedRoles / mentionedUsers / customEmojis).
|
||||
*
|
||||
* - `<@&id>` → `@RoleName` (falls back to `@role`)
|
||||
* - `<@id>` / `<@!id>` → `@Username` (falls back to `@user`)
|
||||
* - `<:name:id>` → `:name:` (falls back to the literal name)
|
||||
*
|
||||
* Unresolvable tokens keep Discord's own name from the token, so no numeric
|
||||
* snowflake ever reaches the reader. Content without "<" is returned untouched.
|
||||
* Used by both the LLM prompt pipeline (conversationContext / moderationBuilders)
|
||||
* and mirrored in the frontend (lib/format.ts renderMessageContent).
|
||||
*/
|
||||
export function renderDiscordMentions(
|
||||
content: string,
|
||||
metadata: string | null | undefined,
|
||||
): string {
|
||||
if (!content || !content.includes("<")) return content;
|
||||
const parsed = parseRichMessageMetadata(metadata);
|
||||
const roleName = new Map(
|
||||
(parsed?.mentionedRoles ?? []).map((r) => [r.id, r.name] as const),
|
||||
);
|
||||
const userName = new Map(
|
||||
(parsed?.mentionedUsers ?? []).map((u) => [u.id, u.username] as const),
|
||||
);
|
||||
const emojiName = new Map(
|
||||
(parsed?.customEmojis ?? []).map((e) => [e.id, e.name] as const),
|
||||
);
|
||||
return content.replace(
|
||||
/<(?:a)?:([a-zA-Z0-9_]+):(\d{17,20})>|<@!?(\d{17,20})>|<@&(\d{17,20})>/g,
|
||||
(_full, emojiTokenName, emojiId, userId, roleId) => {
|
||||
if (emojiId !== undefined) {
|
||||
return `:${emojiName.get(emojiId) ?? emojiTokenName}:`;
|
||||
}
|
||||
if (roleId !== undefined) return `@${roleName.get(roleId) ?? "role"}`;
|
||||
if (userId !== undefined) return `@${userName.get(userId) ?? "user"}`;
|
||||
return _full;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.6.0",
|
||||
"@shadcn/react": "^0.2.1",
|
||||
"@tanstack/react-query": "^5.101.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
@@ -29,6 +28,7 @@
|
||||
"recharts": "3.8.0",
|
||||
"shadcn": "^4.15.0",
|
||||
"sonner": "^2.0.7",
|
||||
"swr": "^2.4.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
|
||||
Generated
+4536
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
allowBuilds:
|
||||
sharp: set this to true or false
|
||||
# pnpm 11 requires build-script approvals here (the legacy `pnpm` field in
|
||||
# package.json is ignored). Only packages that genuinely need a postinstall
|
||||
# build are listed; everything else installs with scripts skipped.
|
||||
onlyBuiltDependencies:
|
||||
- sharp
|
||||
@@ -24,13 +24,14 @@ type DashboardTab = "stats" | "live" | "users" | "channels";
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [tab, setTab] = useState<DashboardTab>("stats");
|
||||
const { data: stats, isLoading, error, refetch } = useStats();
|
||||
const { data: stats, isLoading, error, mutate: refetch } = useStats();
|
||||
const { data: review = [] } = useReview();
|
||||
|
||||
const modQueueItems: ModQueueItem[] = review.slice(0, 10).map((msg) => ({
|
||||
id: msg.id,
|
||||
content: msg.content || msg.id,
|
||||
username: msg.username,
|
||||
metadata: msg.metadata ?? null,
|
||||
severity:
|
||||
msg.ai_severity && msg.ai_severity !== "none"
|
||||
? (msg.ai_severity as ModQueueItem["severity"])
|
||||
|
||||
@@ -1,25 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { TopNav } from "@/components/layout/top-nav";
|
||||
import { MobileNav } from "@/components/layout/mobile-nav";
|
||||
import { WsProvider, useWebSocket } from "@/lib/ws/context";
|
||||
import { ChatbotProvider, useChatbot } from "@/components/chatbot/chatbot-context";
|
||||
import { SWRConfig } from "swr";
|
||||
import { ChatbotContainer } from "@/components/chatbot/chatbot-container";
|
||||
import {
|
||||
ChatbotProvider,
|
||||
useChatbot,
|
||||
} from "@/components/chatbot/chatbot-context";
|
||||
import { HiddenSidebar } from "@/components/layout/hidden-sidebar";
|
||||
import { MobileNav } from "@/components/layout/mobile-nav";
|
||||
import { TopNav } from "@/components/layout/top-nav";
|
||||
import { MiniPlayer } from "@/components/media/mini-player";
|
||||
import { MediaPlayerProvider } from "@/lib/hooks/use-media-player";
|
||||
import { HiddenSidebar } from "@/components/layout/hidden-sidebar";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 10_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
import { useWebSocket, WsProvider } from "@/lib/ws/context";
|
||||
|
||||
function ChatbotExpressionSync() {
|
||||
const ws = useWebSocket();
|
||||
@@ -54,14 +47,24 @@ export default function DashboardLayout({
|
||||
const [guildId, setGuildId] = useState("");
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SWRConfig
|
||||
value={{
|
||||
revalidateOnFocus: false,
|
||||
dedupingInterval: 10_000,
|
||||
shouldRetryOnError: (err) =>
|
||||
(err as { statusCode?: number })?.statusCode !== 404,
|
||||
}}
|
||||
>
|
||||
<WsProvider>
|
||||
<MediaPlayerProvider>
|
||||
<ChatbotProvider>
|
||||
<ChatbotExpressionSync />
|
||||
<div className="min-h-screen bg-canvas">
|
||||
<TopNav />
|
||||
<HiddenSidebar guildId={guildId} onGuildChange={(g) => setGuildId(g ?? "")} />
|
||||
<HiddenSidebar
|
||||
guildId={guildId}
|
||||
onGuildChange={(g) => setGuildId(g ?? "")}
|
||||
/>
|
||||
|
||||
{/* Sub-nav space — filled per-page */}
|
||||
<div className="pt-11">
|
||||
@@ -85,6 +88,6 @@ export default function DashboardLayout({
|
||||
</ChatbotProvider>
|
||||
</MediaPlayerProvider>
|
||||
</WsProvider>
|
||||
</QueryClientProvider>
|
||||
</SWRConfig>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { Flag, Image, Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { MessageList } from "@/components/messages/message-list";
|
||||
import { MessageDetailView } from "@/components/messages/message-detail-view";
|
||||
import { SearchOverlay } from "@/components/messages/search-overlay";
|
||||
import { extractFirstImage } from "@/components/messages/message-card";
|
||||
import { SubNav } from "@/components/layout/sub-nav";
|
||||
import { ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { GlassPanel } from "@/components/glass/panel";
|
||||
import { SubNav } from "@/components/layout/sub-nav";
|
||||
import { extractFirstImage } from "@/components/messages/message-card";
|
||||
import { MessageDetailView } from "@/components/messages/message-detail-view";
|
||||
import { MessageList } from "@/components/messages/message-list";
|
||||
import { SearchOverlay } from "@/components/messages/search-overlay";
|
||||
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { GuildSelector } from "@/components/shared/guild-selector";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
@@ -31,10 +32,10 @@ import {
|
||||
useReview,
|
||||
useTextChannels,
|
||||
} from "@/hooks";
|
||||
import { renderMessageContent } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
import { GuildSelector } from "@/components/shared/guild-selector";
|
||||
|
||||
type MessagesTab = "all" | "images" | "review";
|
||||
|
||||
@@ -184,10 +185,7 @@ export default function MessagesPage() {
|
||||
<div className="flex gap-4">
|
||||
{/* Left pane */}
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-2",
|
||||
detailId ? "w-1/2 lg:w-2/5" : "w-full",
|
||||
)}
|
||||
className={cn("space-y-2", detailId ? "w-1/2 lg:w-2/5" : "w-full")}
|
||||
>
|
||||
{tab === "all" && (
|
||||
<MessageList
|
||||
@@ -204,10 +202,7 @@ export default function MessagesPage() {
|
||||
<ImageGrid items={images ?? []} onSelect={setDetailId} />
|
||||
)}
|
||||
{tab === "review" && (
|
||||
<ReviewList
|
||||
items={reviews ?? []}
|
||||
onSelect={setDetailId}
|
||||
/>
|
||||
<ReviewList items={reviews ?? []} onSelect={setDetailId} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -215,7 +210,10 @@ export default function MessagesPage() {
|
||||
{detailId && (
|
||||
<div className="sticky top-16 hidden w-1/2 self-start md:block lg:w-3/5">
|
||||
{detailLoading ? (
|
||||
<GlassPanel dense className="flex items-center justify-center py-12">
|
||||
<GlassPanel
|
||||
dense
|
||||
className="flex items-center justify-center py-12"
|
||||
>
|
||||
<Loader2 className="size-5 animate-spin text-text-secondary/60" />
|
||||
</GlassPanel>
|
||||
) : detailMessage ? (
|
||||
@@ -287,9 +285,12 @@ function ImageGrid({
|
||||
);
|
||||
})}
|
||||
{items.length === 0 && (
|
||||
<div className="col-span-3 py-12 text-center text-xs text-text-secondary/40">
|
||||
No images
|
||||
</div>
|
||||
<EmptyState
|
||||
icon={Image}
|
||||
title="No images"
|
||||
description="Messages with image attachments will show up here."
|
||||
className="col-span-3"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -317,16 +318,18 @@ function ReviewList({
|
||||
<Flag className="mt-0.5 size-3.5 shrink-0 text-accent-purple" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="line-clamp-2 text-xs text-text-secondary">
|
||||
{item.content || item.id}
|
||||
{renderMessageContent(item.content, item.metadata) || item.id}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</GlassCard>
|
||||
))}
|
||||
{items.length === 0 && (
|
||||
<div className="py-12 text-center text-xs text-text-secondary/40">
|
||||
No flagged messages
|
||||
</div>
|
||||
<EmptyState
|
||||
icon={Flag}
|
||||
title="No flagged messages"
|
||||
description="Messages flagged by AI moderation will appear here for review."
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Clock, Database, Mic, Users } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { StatCard } from "@/components/dashboard/stat-card";
|
||||
import { SubNav } from "@/components/layout/sub-nav";
|
||||
import { RecordingCard } from "@/components/recordings/recording-card";
|
||||
import { RecordingPlayer } from "@/components/recordings/recording-player";
|
||||
import { ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { useRecordings, useRecordingsWsSync } from "@/hooks";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import type { VoiceRecording } from "@/lib/types";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
|
||||
type RecordingsTab = "library" | "stats";
|
||||
|
||||
export default function RecordingsPage() {
|
||||
const { data: recordings, isLoading, error, refetch } = useRecordings();
|
||||
const {
|
||||
data: recordings,
|
||||
isLoading,
|
||||
error,
|
||||
mutate: refetch,
|
||||
} = useRecordings();
|
||||
const [playingId, setPlayingId] = useState<string | null>(null);
|
||||
const [tab, setTab] = useState<RecordingsTab>("library");
|
||||
const ws = useWebSocket();
|
||||
@@ -25,6 +33,31 @@ export default function RecordingsPage() {
|
||||
? recordings.find((r: VoiceRecording) => r.id === playingId)
|
||||
: null;
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const list = recordings ?? [];
|
||||
const totalSize = list.reduce((sum, r) => sum + (r.size_bytes ?? 0), 0);
|
||||
const byUser = new Map<
|
||||
string,
|
||||
{ name: string; count: number; size: number }
|
||||
>();
|
||||
for (const rec of list) {
|
||||
const key = rec.user_id ?? rec.username;
|
||||
const cur = byUser.get(key) ?? { name: rec.username, count: 0, size: 0 };
|
||||
cur.count += 1;
|
||||
cur.size += rec.size_bytes ?? 0;
|
||||
byUser.set(key, cur);
|
||||
}
|
||||
const topUsers = [...byUser.values()]
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 8);
|
||||
return {
|
||||
total: list.length,
|
||||
totalSize,
|
||||
uniqueUsers: byUser.size,
|
||||
topUsers,
|
||||
};
|
||||
}, [recordings]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 animate-fade-in-up">
|
||||
<SubNav
|
||||
@@ -51,18 +84,72 @@ export default function RecordingsPage() {
|
||||
/>
|
||||
))}
|
||||
{(recordings ?? []).length === 0 && (
|
||||
<div className="py-12 text-center text-sm text-text-secondary/40">
|
||||
No recordings yet
|
||||
</div>
|
||||
<EmptyState
|
||||
icon={Mic}
|
||||
title="No recordings yet"
|
||||
description="Voice recordings will appear here once members speak in a monitored voice channel."
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{tab === "stats" && (
|
||||
<div className="py-12 text-center text-sm text-text-secondary/40">
|
||||
Recording stats coming soon
|
||||
</div>
|
||||
)}
|
||||
{tab === "stats" &&
|
||||
(isLoading ? (
|
||||
<LoadingSkeleton count={4} height="h-28" columns={3} />
|
||||
) : stats.total === 0 ? (
|
||||
<EmptyState
|
||||
icon={Clock}
|
||||
title="No recording stats yet"
|
||||
description="Recordings are captured from monitored voice channels."
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<StatCard
|
||||
label="Total Recordings"
|
||||
value={stats.total}
|
||||
icon={Mic}
|
||||
/>
|
||||
<StatCard
|
||||
label="Total Size"
|
||||
value={stats.totalSize}
|
||||
icon={Database}
|
||||
formatter={(v) => formatBytes(v)}
|
||||
/>
|
||||
<StatCard
|
||||
label="Unique Speakers"
|
||||
value={stats.uniqueUsers}
|
||||
icon={Users}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{stats.topUsers.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs text-text-secondary font-medium uppercase tracking-wide">
|
||||
Top Speakers
|
||||
</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
{stats.topUsers.map((u) => (
|
||||
<div
|
||||
key={u.name}
|
||||
className="flex items-center gap-3 rounded-lg border border-border/40 bg-card/40 px-3 py-2"
|
||||
>
|
||||
<span className="flex size-7 items-center justify-center rounded-md bg-primary/10 font-mono text-xs text-primary">
|
||||
{u.count}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0 truncate text-sm text-text-primary">
|
||||
{u.name}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-text-secondary/50">
|
||||
{formatBytes(u.size)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<RecordingPlayer
|
||||
url={currentTrack?.download_url ?? undefined}
|
||||
|
||||
@@ -7,8 +7,8 @@ import { GlassDivider } from "@/components/glass/divider";
|
||||
import { SubNav } from "@/components/layout/sub-nav";
|
||||
import { LoadingSkeleton } from "@/components/shared";
|
||||
import { useConfig } from "@/hooks";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
|
||||
type SettingsTab = "connection" | "appearance" | "config" | "about";
|
||||
|
||||
@@ -32,7 +32,8 @@ export default function SettingsPage() {
|
||||
};
|
||||
|
||||
const statusDot = {
|
||||
connected: "bg-emerald-500 shadow-[0_0_8px] shadow-emerald-500/60 animate-pulse",
|
||||
connected:
|
||||
"bg-emerald-500 shadow-[0_0_8px] shadow-emerald-500/60 animate-pulse",
|
||||
connecting: "bg-accent-amber animate-pulse",
|
||||
disconnected: "bg-destructive",
|
||||
error: "bg-destructive",
|
||||
@@ -49,9 +50,21 @@ export default function SettingsPage() {
|
||||
<div className="space-y-4 animate-fade-in-up max-w-2xl">
|
||||
<SubNav
|
||||
tabs={[
|
||||
{ id: "connection", label: "Connection", icon: <Wifi className="size-3" /> },
|
||||
{ id: "appearance", label: "Appearance", icon: <Sun className="size-3" /> },
|
||||
{ id: "config", label: "Config", icon: <Server className="size-3" /> },
|
||||
{
|
||||
id: "connection",
|
||||
label: "Connection",
|
||||
icon: <Wifi className="size-3" />,
|
||||
},
|
||||
{
|
||||
id: "appearance",
|
||||
label: "Appearance",
|
||||
icon: <Sun className="size-3" />,
|
||||
},
|
||||
{
|
||||
id: "config",
|
||||
label: "Config",
|
||||
icon: <Server className="size-3" />,
|
||||
},
|
||||
{ id: "about", label: "About", icon: <Shield className="size-3" /> },
|
||||
]}
|
||||
activeTab={tab}
|
||||
@@ -62,11 +75,15 @@ export default function SettingsPage() {
|
||||
<GlassCard variant="base">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<span className="text-sm font-semibold text-text-primary">WebSocket</span>
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
WebSocket
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={cn("size-2 rounded-full", statusDot)} />
|
||||
<span className="text-xs font-mono text-text-secondary">{statusLabel}</span>
|
||||
<span className="text-xs font-mono text-text-secondary">
|
||||
{statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</GlassCard>
|
||||
@@ -76,8 +93,14 @@ export default function SettingsPage() {
|
||||
<GlassCard variant="base">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{theme === "dark" ? <Moon className="size-4 text-primary" /> : <Sun className="size-4 text-primary" />}
|
||||
<span className="text-sm font-semibold text-text-primary">Theme</span>
|
||||
{theme === "dark" ? (
|
||||
<Moon className="size-4 text-primary" />
|
||||
) : (
|
||||
<Sun className="size-4 text-primary" />
|
||||
)}
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
Theme
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -97,18 +120,37 @@ export default function SettingsPage() {
|
||||
<LoadingSkeleton count={6} height="h-6" />
|
||||
) : config ? (
|
||||
<>
|
||||
<ConfigRow label="Monitor Guild" value={config.monitorGuildId || "Not configured"} />
|
||||
<ConfigRow
|
||||
label="Monitor Guild"
|
||||
value={config.monitorGuildId || "Not configured"}
|
||||
/>
|
||||
<GlassDivider />
|
||||
<ConfigRow label="Voice Guild" value={config.voiceGuildId || "Not configured"} />
|
||||
<ConfigRow
|
||||
label="Voice Guild"
|
||||
value={config.voiceGuildId || "Not configured"}
|
||||
/>
|
||||
<GlassDivider />
|
||||
<ConfigRow label="Voice Channel" value={config.voiceChannelId || "Not configured"} />
|
||||
<ConfigRow
|
||||
label="Voice Channel"
|
||||
value={config.voiceChannelId || "Not configured"}
|
||||
/>
|
||||
<GlassDivider />
|
||||
<ConfigRow label="AI Analysis" value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"} />
|
||||
<ConfigRow
|
||||
label="AI Analysis"
|
||||
value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"}
|
||||
/>
|
||||
<GlassDivider />
|
||||
<ConfigRow label="Auto-Delete Flagged" value={config.autoDeleteFlaggedEnabled ? "Enabled" : "Disabled"} />
|
||||
<ConfigRow
|
||||
label="Auto-Delete Flagged"
|
||||
value={
|
||||
config.autoDeleteFlaggedEnabled ? "Enabled" : "Disabled"
|
||||
}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xs text-text-secondary/60">Unable to load config.</p>
|
||||
<p className="text-xs text-text-secondary/60">
|
||||
Unable to load config.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</GlassCard>
|
||||
@@ -117,9 +159,12 @@ export default function SettingsPage() {
|
||||
{tab === "about" && (
|
||||
<GlassCard variant="base">
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-base font-bold text-primary">Discord Automod</h2>
|
||||
<h2 className="text-base font-bold text-primary">
|
||||
Discord Automod
|
||||
</h2>
|
||||
<p className="text-xs text-text-secondary/80 leading-relaxed">
|
||||
AI-powered message moderation, voice recording, and real-time monitoring for Discord communities.
|
||||
AI-powered message moderation, voice recording, and real-time
|
||||
monitoring for Discord communities.
|
||||
</p>
|
||||
<div className="text-[10px] font-mono text-text-secondary/40 mt-4">
|
||||
v0.1.0
|
||||
@@ -135,7 +180,9 @@ function ConfigRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-0.5">
|
||||
<span className="text-xs text-text-secondary">{label}</span>
|
||||
<span className="text-[11px] font-mono text-text-primary/80 max-w-[240px] truncate text-right">{value}</span>
|
||||
<span className="text-[11px] font-mono text-text-primary/80 max-w-[240px] truncate text-right">
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { VoiceConnectionCard } from "@/components/voice/connection-card";
|
||||
import { SpeakerWaveform } from "@/components/voice/speaker-waveform";
|
||||
import { MicControl } from "@/components/voice/mic-control";
|
||||
import { VoiceActivityTimeline } from "@/components/voice/activity-timeline";
|
||||
import { SubNav } from "@/components/layout/sub-nav";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
import { VoiceActivityTimeline } from "@/components/voice/activity-timeline";
|
||||
import { VoiceConnectionCard } from "@/components/voice/connection-card";
|
||||
import { MicControl } from "@/components/voice/mic-control";
|
||||
import { SpeakerWaveform } from "@/components/voice/speaker-waveform";
|
||||
import {
|
||||
useGuilds,
|
||||
useMicTransmit,
|
||||
@@ -16,6 +15,7 @@ import {
|
||||
useVoiceDisconnect,
|
||||
useVoiceStatus,
|
||||
} from "@/hooks";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
|
||||
type VoiceTab = "connection" | "activity";
|
||||
|
||||
@@ -83,7 +83,12 @@ export default function VoicePage() {
|
||||
selectedChannel={selectedChannel}
|
||||
onGuildChange={handleGuildChange}
|
||||
onChannelChange={(v) => setSelectedChannel(v ?? "")}
|
||||
onConnect={() => connectMut.mutate({ guildId: selectedGuild, channelId: selectedChannel })}
|
||||
onConnect={() =>
|
||||
connectMut.mutate({
|
||||
guildId: selectedGuild,
|
||||
channelId: selectedChannel,
|
||||
})
|
||||
}
|
||||
onDisconnect={() => disconnectMut.mutate(undefined)}
|
||||
connecting={connectMut.isPending}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Loader2, RefreshCw, Search, Sparkles } from "lucide-react";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
@@ -11,9 +10,8 @@ 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 { useReanalyze } from "@/hooks";
|
||||
import { messagesApi } from "@/lib/api";
|
||||
import { safeParseJsonArray } from "@/lib/format";
|
||||
import { useMessageSearch, useReanalyze } from "@/hooks";
|
||||
import { renderMessageContent, safeParseJsonArray } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -22,14 +20,10 @@ export function SearchPanel() {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const reanalyzeMut = useReanalyze();
|
||||
|
||||
const { data: results, isFetching } = useQuery<MessageRecord[]>({
|
||||
queryKey: ["analysis-search", query],
|
||||
queryFn: async () => {
|
||||
const result = await messagesApi.search(query, 50);
|
||||
return result.results;
|
||||
},
|
||||
const { data: results, isValidating: isFetching } = useMessageSearch(
|
||||
query,
|
||||
enabled,
|
||||
});
|
||||
);
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
if (!query.trim()) return;
|
||||
@@ -100,7 +94,9 @@ export function SearchPanel() {
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed">{msg.content}</p>
|
||||
<p className="text-sm leading-relaxed">
|
||||
{renderMessageContent(msg.content, msg.metadata)}
|
||||
</p>
|
||||
{msg.ai_moderation_flags &&
|
||||
msg.ai_moderation_flags !== "[]" && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
|
||||
@@ -9,6 +9,7 @@ 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 { renderMessageContent } from "@/lib/format";
|
||||
import type { DashboardChannel } from "@/lib/types";
|
||||
|
||||
export function ChannelsSection({ guildId }: { guildId?: string }) {
|
||||
@@ -19,7 +20,7 @@ export function ChannelsSection({ guildId }: { guildId?: string }) {
|
||||
data: channels = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
mutate: refetch,
|
||||
} = useChannels(guildId ?? "", search);
|
||||
const { data: detail } = useChannelDetail(selectedId);
|
||||
|
||||
@@ -123,7 +124,9 @@ export function ChannelsSection({ guildId }: { guildId?: string }) {
|
||||
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)"}
|
||||
{msg.username}:{" "}
|
||||
{renderMessageContent(msg.content, msg.metadata) ||
|
||||
"(no text content)"}
|
||||
</p>
|
||||
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { renderMessageContent } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useWebSocket } from "@/lib/ws/context";
|
||||
@@ -13,6 +14,7 @@ interface LiveMessage {
|
||||
channelName?: string;
|
||||
timestamp: string;
|
||||
flagged?: boolean;
|
||||
metadata?: string | null;
|
||||
}
|
||||
|
||||
export function LiveStream() {
|
||||
@@ -40,6 +42,7 @@ export function LiveStream() {
|
||||
channelName,
|
||||
timestamp: new Date().toLocaleTimeString(),
|
||||
flagged: data.ai_status === "flagged" || data.ai_status === "warn",
|
||||
metadata: data.metadata ?? null,
|
||||
};
|
||||
setMessages((prev) => [msg, ...prev].slice(0, 50));
|
||||
});
|
||||
@@ -80,7 +83,7 @@ export function LiveStream() {
|
||||
{msg.username}
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary truncate flex-1">
|
||||
{msg.content}
|
||||
{renderMessageContent(msg.content, msg.metadata)}
|
||||
</span>
|
||||
<span className="text-[10px] text-text-secondary/40 shrink-0">
|
||||
{msg.timestamp}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { AlertCircle, Check, Trash2 } from "lucide-react";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { renderMessageContent } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ModQueueItem {
|
||||
@@ -10,6 +11,7 @@ export interface ModQueueItem {
|
||||
username: string;
|
||||
severity: "low" | "medium" | "high" | "critical";
|
||||
reason: string;
|
||||
metadata?: string | null;
|
||||
}
|
||||
|
||||
export function ModQueue({ items = [] }: { items?: ModQueueItem[] }) {
|
||||
@@ -56,7 +58,7 @@ export function ModQueue({ items = [] }: { items?: ModQueueItem[] }) {
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-text-secondary line-clamp-1">
|
||||
{item.content}
|
||||
{renderMessageContent(item.content, item.metadata)}
|
||||
</p>
|
||||
<p className="text-[10px] text-text-secondary/50">
|
||||
{item.reason}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { type LucideIcon } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { Area, AreaChart, ResponsiveContainer } from "recharts";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Area, AreaChart, ResponsiveContainer } from "recharts";
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
@@ -43,7 +43,10 @@ export function StatCard({
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-2xl font-mono font-semibold tracking-tight" style={{ color: accentColor }}>
|
||||
<div
|
||||
className="text-2xl font-mono font-semibold tracking-tight"
|
||||
style={{ color: accentColor }}
|
||||
>
|
||||
{formatter(numValue)}
|
||||
</div>
|
||||
<div className="text-[11px] text-text-secondary font-medium mt-0.5 tracking-wide uppercase">
|
||||
@@ -56,7 +59,13 @@ export function StatCard({
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={sparklineData}>
|
||||
<defs>
|
||||
<linearGradient id={`spark-grad-${label}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<linearGradient
|
||||
id={`spark-grad-${label}`}
|
||||
x1="0"
|
||||
y1="0"
|
||||
x2="0"
|
||||
y2="1"
|
||||
>
|
||||
<stop offset="0%" stopColor={accentColor} stopOpacity={0.5} />
|
||||
<stop offset="100%" stopColor={accentColor} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
|
||||
interface TopChannelsChartProps {
|
||||
data?: { name: string; count: number }[];
|
||||
@@ -11,13 +18,27 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
|
||||
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">Top Channels</span>
|
||||
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
|
||||
Top Channels
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-48">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={data} layout="vertical">
|
||||
<XAxis type="number" axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} />
|
||||
<YAxis type="category" dataKey="name" axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} width={80} />
|
||||
<XAxis
|
||||
type="number"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
|
||||
/>
|
||||
<YAxis
|
||||
type="category"
|
||||
dataKey="name"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
|
||||
width={80}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
background: "oklch(0.11 0.02 245 / 0.9)",
|
||||
@@ -27,7 +48,11 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
|
||||
color: "oklch(0.93 0.01 245)",
|
||||
}}
|
||||
/>
|
||||
<Bar dataKey="count" fill="var(--color-primary)" radius={[0, 4, 4, 0]} />
|
||||
<Bar
|
||||
dataKey="count"
|
||||
fill="var(--color-primary)"
|
||||
radius={[0, 4, 4, 0]}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
@@ -10,13 +10,19 @@ 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 { renderMessageContent } from "@/lib/format";
|
||||
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: users = [],
|
||||
isLoading,
|
||||
error,
|
||||
mutate: refetch,
|
||||
} = useUsers(search);
|
||||
const { data: detail } = useUserDetail(selectedId);
|
||||
|
||||
const handleSearch = useCallback((v: string) => {
|
||||
@@ -134,7 +140,8 @@ export function UsersSection() {
|
||||
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)"}
|
||||
{renderMessageContent(msg.content, msg.metadata) ||
|
||||
"(no text content)"}
|
||||
</p>
|
||||
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
|
||||
{msg.channel_id?.slice(0, 8)} ·{" "}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { safeParseJsonArray, getMessageChannelLabel } from "@/lib/format";
|
||||
import { safeParseJsonArray, getMessageChannelLabel, renderMessageContent } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AiStatusBadge } from "./ai-status-badge";
|
||||
@@ -96,7 +96,7 @@ export function MessageCard({
|
||||
"italic text-muted-foreground line-through",
|
||||
)}
|
||||
>
|
||||
{msg.content}
|
||||
{renderMessageContent(msg.content, msg.metadata)}
|
||||
</p>
|
||||
{(() => {
|
||||
const u = extractFirstImage(msg.metadata);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ArrowLeft, MessageSquare, MessagesSquare } from "lucide-react";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { AttachmentsGrid } from "./attachments-grid";
|
||||
import { AiAnalysisPanel } from "./ai-analysis-panel";
|
||||
import { getMessageChannelLabel } from "@/lib/format";
|
||||
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
|
||||
import type { AttachmentRecord, MessageRecord } from "@/lib/types";
|
||||
|
||||
interface MessageDetailViewProps {
|
||||
@@ -34,7 +34,7 @@ export function MessageDetailView({ message, attachments, onBack }: MessageDetai
|
||||
|
||||
{/* Content */}
|
||||
<div className="text-sm text-text-primary/90 leading-relaxed mb-4 whitespace-pre-wrap">
|
||||
{message.content || "(no text content)"}
|
||||
{renderMessageContent(message.content, message.metadata) || "(no text content)"}
|
||||
</div>
|
||||
|
||||
{/* Attachments */}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ArrowLeft, MessageSquare, MessagesSquare } from "lucide-react";
|
||||
import { GlassCard } from "@/components/glass/card";
|
||||
import { AttachmentsGrid } from "./attachments-grid";
|
||||
import { AiAnalysisPanel } from "./ai-analysis-panel";
|
||||
import { getMessageChannelLabel } from "@/lib/format";
|
||||
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
|
||||
import type { AttachmentRecord, MessageRecord } from "@/lib/types";
|
||||
|
||||
interface MessageDetailProps {
|
||||
@@ -34,7 +34,7 @@ export function MessageDetail({ message, attachments, onBack }: MessageDetailPro
|
||||
|
||||
{/* Content */}
|
||||
<div className="text-sm text-text-primary/90 leading-relaxed mb-4 whitespace-pre-wrap">
|
||||
{message.content || "(no text content)"}
|
||||
{renderMessageContent(message.content, message.metadata) || "(no text content)"}
|
||||
</div>
|
||||
|
||||
{/* Attachments */}
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
import { Search, X } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { messagesApi } from "@/lib/api";
|
||||
import { getMessageChannelLabel } from "@/lib/format";
|
||||
import { useMessageSearch } from "@/hooks";
|
||||
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
|
||||
interface SearchOverlayProps {
|
||||
@@ -17,14 +16,7 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const { data: results } = useQuery<MessageRecord[]>({
|
||||
queryKey: ["messages-search", query],
|
||||
queryFn: async () => {
|
||||
const res = await messagesApi.search(query, 20);
|
||||
return res.results;
|
||||
},
|
||||
enabled: query.length >= 2,
|
||||
});
|
||||
const { data: results } = useMessageSearch(query, true);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -50,7 +42,12 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]">
|
||||
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Close search"
|
||||
className="absolute inset-0 bg-black/60 backdrop-blur-sm cursor-default"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div className="relative w-full max-w-lg glass-intense rounded-[var(--radius-card)] overflow-hidden shadow-2xl">
|
||||
{/* Input */}
|
||||
<div className="flex items-center gap-3 px-4 py-3 border-b border-glass-border">
|
||||
@@ -63,7 +60,11 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
|
||||
placeholder="Search messages..."
|
||||
className="flex-1 bg-transparent text-sm text-text-primary placeholder-text-secondary/40 outline-none"
|
||||
/>
|
||||
<button type="button" onClick={onClose} className="size-6 flex items-center justify-center rounded hover:bg-glass-bg">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="size-6 flex items-center justify-center rounded hover:bg-glass-bg"
|
||||
>
|
||||
<X className="size-3.5 text-text-secondary/60" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -72,21 +73,32 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
|
||||
<div className="max-h-80 overflow-y-auto p-2 space-y-1">
|
||||
{!results || results.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-text-secondary/40">
|
||||
{query.length < 2 ? "Type at least 2 characters" : "No results found"}
|
||||
{query.length < 2
|
||||
? "Type at least 2 characters"
|
||||
: "No results found"}
|
||||
</div>
|
||||
) : (
|
||||
results.map((msg) => (
|
||||
<button
|
||||
key={msg.id}
|
||||
type="button"
|
||||
onClick={() => { onSelect(msg.id); onClose(); }}
|
||||
onClick={() => {
|
||||
onSelect(msg.id);
|
||||
onClose();
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 rounded-lg hover:bg-glass-bg transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span className="font-medium text-text-primary">{msg.username}</span>
|
||||
<span className="text-text-secondary/40">{getMessageChannelLabel(msg)}</span>
|
||||
<span className="font-medium text-text-primary">
|
||||
{msg.username}
|
||||
</span>
|
||||
<span className="text-text-secondary/40">
|
||||
{getMessageChannelLabel(msg)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-text-secondary/80 line-clamp-1 mt-0.5">{msg.content}</p>
|
||||
<p className="text-xs text-text-secondary/80 line-clamp-1 mt-0.5">
|
||||
{renderMessageContent(msg.content, msg.metadata)}
|
||||
</p>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -3,20 +3,26 @@
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { Inbox } from "lucide-react";
|
||||
import { GlassPanel } from "@/components/glass/panel";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon?: LucideIcon;
|
||||
title?: string;
|
||||
description?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
icon: Icon = Inbox,
|
||||
title = "No data yet",
|
||||
description = "Nothing to display here yet.",
|
||||
className,
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<GlassPanel dense className="flex flex-col items-center gap-2 py-12">
|
||||
<GlassPanel
|
||||
dense
|
||||
className={cn("flex flex-col items-center gap-2 py-12", className)}
|
||||
>
|
||||
<Icon className="size-8 text-text-secondary/20" />
|
||||
<p className="text-sm text-text-secondary/60">{title}</p>
|
||||
<p className="text-xs text-text-secondary/40">{description}</p>
|
||||
|
||||
@@ -33,7 +33,7 @@ export function GuildSelector({
|
||||
onChange,
|
||||
autoHide = true,
|
||||
}: GuildSelectorProps) {
|
||||
const { data: guilds = [], isLoading, error, refetch } = useGuilds();
|
||||
const { data: guilds = [], isLoading, error, mutate: refetch } = useGuilds();
|
||||
const { data: config } = useConfig();
|
||||
|
||||
const initDone = useRef(false);
|
||||
|
||||
@@ -19,6 +19,7 @@ export {
|
||||
useImages,
|
||||
useLoadMore,
|
||||
useMessageDetail,
|
||||
useMessageSearch,
|
||||
useMessages,
|
||||
useMessagesHasMore,
|
||||
useMessagesWsSync,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
export interface UseActionState {
|
||||
isPending: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A lightweight mutation hook with a TanStack-compatible surface
|
||||
* ({ mutate, mutateAsync, isPending, error }) built on plain state —
|
||||
* the SWR replacement for useMutation. Fire-and-forget via `mutate`,
|
||||
* await the result via `mutateAsync`.
|
||||
*
|
||||
* `onSuccess` receives (data, args) and may perform SWR cache updates
|
||||
* (e.g. `mutate(key, data, { revalidate: false })`).
|
||||
*/
|
||||
export function useAction<TArgs = void, TResult = unknown>(
|
||||
fn: (args: TArgs) => Promise<TResult>,
|
||||
options?: {
|
||||
onSuccess?: (data: TResult, args: TArgs) => void | Promise<void>;
|
||||
},
|
||||
) {
|
||||
const [state, setState] = useState<UseActionState>({
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const fnRef = useRef(fn);
|
||||
fnRef.current = fn;
|
||||
const onSuccessRef = useRef(options?.onSuccess);
|
||||
onSuccessRef.current = options?.onSuccess;
|
||||
|
||||
const run = useCallback(async (args?: TArgs): Promise<TResult> => {
|
||||
setState({ isPending: true, error: null });
|
||||
try {
|
||||
const data = await fnRef.current(args as TArgs);
|
||||
await onSuccessRef.current?.(data, args as TArgs);
|
||||
setState({ isPending: false, error: null });
|
||||
return data;
|
||||
} catch (err) {
|
||||
setState({ isPending: false, error: err as Error });
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mutate: (args?: TArgs) => {
|
||||
void run(args);
|
||||
},
|
||||
mutateAsync: run,
|
||||
isPending: state.isPending,
|
||||
error: state.error,
|
||||
reset: () => setState({ isPending: false, error: null }),
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { configApi } from "@/lib/api";
|
||||
import type { AppConfig } from "@/lib/types";
|
||||
@@ -7,9 +7,7 @@ import type { AppConfig } from "@/lib/types";
|
||||
* Fetch the app configuration from the backend.
|
||||
*/
|
||||
export function useConfig() {
|
||||
return useQuery<AppConfig>({
|
||||
queryKey: ["config"],
|
||||
queryFn: () => configApi.get(),
|
||||
staleTime: 120_000,
|
||||
return useSWR<AppConfig>(["config"], () => configApi.get(), {
|
||||
dedupingInterval: 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { dashboardApi } from "@/lib/api";
|
||||
import type {
|
||||
@@ -8,40 +8,51 @@ import type {
|
||||
} from "@/lib/types";
|
||||
|
||||
export function useStats() {
|
||||
return useQuery<DashboardStats>({
|
||||
queryKey: ["dashboard-stats"],
|
||||
queryFn: () => dashboardApi.getStats(),
|
||||
});
|
||||
return useSWR<DashboardStats>(["dashboard-stats"], () =>
|
||||
dashboardApi.getStats(),
|
||||
);
|
||||
}
|
||||
|
||||
export function useUsers(search?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["dashboard-users", search ?? ""],
|
||||
queryFn: () => dashboardApi.listUsers(20, undefined, search),
|
||||
select: (data) => data.data,
|
||||
});
|
||||
return useSWR(
|
||||
["dashboard-users", search ?? ""],
|
||||
async () => {
|
||||
const res = await dashboardApi.listUsers(20, undefined, search);
|
||||
return res.data;
|
||||
},
|
||||
{
|
||||
keepPreviousData: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function useChannels(guildId?: string, search?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["dashboard-channels", guildId ?? "__all__", search ?? ""],
|
||||
queryFn: () => dashboardApi.listChannels(20, search, guildId || undefined),
|
||||
select: (data) => data.data,
|
||||
});
|
||||
return useSWR(
|
||||
["dashboard-channels", guildId ?? "__all__", search ?? ""],
|
||||
async () => {
|
||||
const res = await dashboardApi.listChannels(
|
||||
20,
|
||||
search,
|
||||
guildId || undefined,
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
{
|
||||
keepPreviousData: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function useUserDetail(userId: string | null) {
|
||||
return useQuery<DashboardUserDetail>({
|
||||
queryKey: ["dashboard-user", userId],
|
||||
queryFn: () => dashboardApi.getUserDetail(userId!),
|
||||
enabled: !!userId,
|
||||
});
|
||||
return useSWR<DashboardUserDetail>(
|
||||
userId ? ["dashboard-user", userId] : null,
|
||||
() => dashboardApi.getUserDetail(userId!),
|
||||
);
|
||||
}
|
||||
|
||||
export function useChannelDetail(channelId: string | null) {
|
||||
return useQuery<DashboardChannelDetail>({
|
||||
queryKey: ["dashboard-channel", channelId],
|
||||
queryFn: () => dashboardApi.getChannelDetail(channelId!),
|
||||
enabled: !!channelId,
|
||||
});
|
||||
return useSWR<DashboardChannelDetail>(
|
||||
channelId ? ["dashboard-channel", channelId] : null,
|
||||
() => dashboardApi.getChannelDetail(channelId!),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { voiceApi } from "@/lib/api";
|
||||
import type { Guild } from "@/lib/types";
|
||||
@@ -7,9 +7,7 @@ import type { Guild } from "@/lib/types";
|
||||
* Fetch the list of available Discord guilds.
|
||||
*/
|
||||
export function useGuilds() {
|
||||
return useQuery<Guild[]>({
|
||||
queryKey: ["guilds"],
|
||||
queryFn: () => voiceApi.getGuilds(),
|
||||
staleTime: 60_000,
|
||||
return useSWR<Guild[]>(["guilds"], () => voiceApi.getGuilds(), {
|
||||
dedupingInterval: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,58 +1,51 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useAction } from "@/hooks/use-action";
|
||||
import { mediaApi } from "@/lib/api";
|
||||
import type { MediaState } from "@/lib/types";
|
||||
import type { WsHook } from "@/lib/ws-hook";
|
||||
|
||||
const MEDIA_KEY = ["media-state"] as const;
|
||||
|
||||
export function useMediaState() {
|
||||
return useQuery<MediaState>({
|
||||
queryKey: ["media-state"],
|
||||
queryFn: () => mediaApi.getStatus(),
|
||||
retry: false,
|
||||
refetchInterval: 10_000,
|
||||
return useSWR<MediaState>(MEDIA_KEY, () => mediaApi.getStatus(), {
|
||||
refreshInterval: 10_000,
|
||||
shouldRetryOnError: false,
|
||||
});
|
||||
}
|
||||
|
||||
function useMediaAction<TArgs>(fn: (args: TArgs) => Promise<MediaState>) {
|
||||
const { mutate } = useSWRConfig();
|
||||
return useAction(fn, {
|
||||
onSuccess: (data) => {
|
||||
void mutate(MEDIA_KEY, data, { revalidate: false });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useMediaQueue() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (url: string) => mediaApi.queue(url, "music"),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
return useMediaAction((url: string) => mediaApi.queue(url, "music"));
|
||||
}
|
||||
|
||||
export function useMediaSkip() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => mediaApi.skip(),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
return useMediaAction(() => mediaApi.skip());
|
||||
}
|
||||
|
||||
export function useMediaStop() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => mediaApi.stop(),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
return useMediaAction(() => mediaApi.stop());
|
||||
}
|
||||
|
||||
export function useMediaVolume() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (volume: number) => mediaApi.volume(volume),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
return useMediaAction((volume: number) => mediaApi.volume(volume));
|
||||
}
|
||||
|
||||
/** Subscribe to WS media_state events to keep cache fresh */
|
||||
export function useMediaWsSync(ws: WsHook) {
|
||||
const qc = useQueryClient();
|
||||
const { mutate } = useSWRConfig();
|
||||
useEffect(() => {
|
||||
const unsub = ws.on("media_state", (data) => {
|
||||
qc.setQueryData(["media-state"], data as MediaState);
|
||||
void mutate(MEDIA_KEY, data as MediaState, { revalidate: false });
|
||||
});
|
||||
return unsub;
|
||||
}, [ws, qc]);
|
||||
}, [ws, mutate]);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useAction } from "@/hooks/use-action";
|
||||
import { messagesApi, voiceApi } from "@/lib/api";
|
||||
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
|
||||
import type { WsHook } from "@/lib/ws-hook";
|
||||
@@ -14,44 +14,48 @@ const msgKeys = {
|
||||
review: (channelId?: string) =>
|
||||
["messages-review", channelId ?? "__all__"] as const,
|
||||
detail: (id: string) => ["message-detail", id] as const,
|
||||
search: (query: string) => ["messages-search", query] as const,
|
||||
};
|
||||
|
||||
type MessagePage = { data: MessageRecord[]; nextCursor: string | null };
|
||||
|
||||
/**
|
||||
* Single source of truth for the paginated message list. Both useMessages and
|
||||
* useMessagesHasMore derive from this one SWR key, so the cursor probe no
|
||||
* longer triggers a duplicate API call.
|
||||
*/
|
||||
function useMessagesPage(guildId: string, channelId?: string) {
|
||||
const key = guildId ? msgKeys.list(guildId, channelId) : null;
|
||||
return useSWR<MessagePage>(key, () =>
|
||||
messagesApi.list(guildId, 50, channelId || undefined),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Messages list (paginated, cursor-based) ──────
|
||||
|
||||
export function useMessages(guildId: string, channelId?: string) {
|
||||
return useQuery<MessageRecord[]>({
|
||||
queryKey: msgKeys.list(guildId, channelId),
|
||||
queryFn: async () => {
|
||||
const result = await messagesApi.list(
|
||||
guildId,
|
||||
50,
|
||||
channelId || undefined,
|
||||
);
|
||||
return result.data;
|
||||
},
|
||||
enabled: !!guildId,
|
||||
});
|
||||
const page = useMessagesPage(guildId, channelId);
|
||||
return {
|
||||
...page,
|
||||
data: page.data?.data,
|
||||
refetch: () => page.mutate(),
|
||||
};
|
||||
}
|
||||
|
||||
export function useMessagesHasMore(guildId: string, channelId?: string) {
|
||||
return useQuery({
|
||||
queryKey: [...msgKeys.list(guildId, channelId), "cursor"],
|
||||
queryFn: async () => {
|
||||
const result = await messagesApi.list(
|
||||
guildId,
|
||||
50,
|
||||
channelId || undefined,
|
||||
);
|
||||
return { cursor: result.nextCursor, hasMore: result.nextCursor !== null };
|
||||
const page = useMessagesPage(guildId, channelId);
|
||||
return {
|
||||
data: {
|
||||
cursor: page.data?.nextCursor ?? null,
|
||||
hasMore: page.data ? page.data.nextCursor !== null : undefined,
|
||||
},
|
||||
enabled: !!guildId,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function useLoadMore() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
const { mutate } = useSWRConfig();
|
||||
return useAction(
|
||||
async ({
|
||||
guildId,
|
||||
channelId,
|
||||
cursor,
|
||||
@@ -66,76 +70,73 @@ export function useLoadMore() {
|
||||
channelId || undefined,
|
||||
cursor,
|
||||
);
|
||||
return { data: result.data, cursor: result.nextCursor };
|
||||
},
|
||||
onSuccess: (data, vars) => {
|
||||
const key = msgKeys.list(vars.guildId, vars.channelId);
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old ? [...old, ...data.data] : data.data,
|
||||
const key = msgKeys.list(guildId, channelId);
|
||||
await mutate(
|
||||
key,
|
||||
(old: MessagePage | undefined): MessagePage | undefined =>
|
||||
old
|
||||
? {
|
||||
data: [...old.data, ...result.data],
|
||||
nextCursor: result.nextCursor,
|
||||
}
|
||||
: result,
|
||||
{ revalidate: false },
|
||||
);
|
||||
qc.setQueryData([...key, "cursor"], {
|
||||
cursor: data.cursor,
|
||||
hasMore: data.cursor !== null,
|
||||
});
|
||||
return result;
|
||||
},
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
// ── Channels list ────────────────────────────────
|
||||
|
||||
export function useTextChannels(guildId: string) {
|
||||
return useQuery<Channel[]>({
|
||||
queryKey: ["text-channels", guildId],
|
||||
queryFn: () => voiceApi.getTextChannels(guildId),
|
||||
enabled: !!guildId,
|
||||
});
|
||||
return useSWR<Channel[]>(guildId ? ["text-channels", guildId] : null, () =>
|
||||
voiceApi.getTextChannels(guildId),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Images ───────────────────────────────────────
|
||||
|
||||
export function useImages(guildId: string) {
|
||||
return useQuery<MessageRecord[]>({
|
||||
queryKey: msgKeys.images(guildId),
|
||||
queryFn: async () => {
|
||||
return useSWR<MessageRecord[]>(
|
||||
guildId ? msgKeys.images(guildId) : null,
|
||||
async () => {
|
||||
const result = await messagesApi.getImages(guildId, 50);
|
||||
return result.data;
|
||||
},
|
||||
enabled: !!guildId,
|
||||
});
|
||||
);
|
||||
}
|
||||
|
||||
// ── Review ───────────────────────────────────────
|
||||
|
||||
export function useReview(channelId?: string) {
|
||||
return useQuery<MessageRecord[]>({
|
||||
queryKey: msgKeys.review(channelId),
|
||||
queryFn: async () => {
|
||||
return useSWR<MessageRecord[]>(
|
||||
msgKeys.review(channelId),
|
||||
async () => {
|
||||
const result = await messagesApi.getReview(50, channelId || undefined);
|
||||
return result.results;
|
||||
},
|
||||
});
|
||||
{
|
||||
refreshInterval: 15_000,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Detail ───────────────────────────────────────
|
||||
|
||||
export function useMessageDetail(id: string | null) {
|
||||
const detail = useQuery<MessageRecord>({
|
||||
queryKey: msgKeys.detail(id ?? ""),
|
||||
queryFn: () => messagesApi.getDetail(id!),
|
||||
enabled: !!id,
|
||||
});
|
||||
const attachments = useQuery<AttachmentRecord[]>({
|
||||
queryKey: [...msgKeys.detail(id ?? ""), "attachments"],
|
||||
queryFn: async () => {
|
||||
if (!id) return [];
|
||||
const res = await messagesApi.getAttachments(
|
||||
detail.data?.channel_id ?? "",
|
||||
10,
|
||||
);
|
||||
const detail = useSWR<MessageRecord>(id ? msgKeys.detail(id) : null, () =>
|
||||
messagesApi.getDetail(id!),
|
||||
);
|
||||
const attachments = useSWR<AttachmentRecord[]>(
|
||||
id && detail.data?.channel_id
|
||||
? [...msgKeys.detail(id), "attachments"]
|
||||
: null,
|
||||
async () => {
|
||||
const res = await messagesApi.getAttachments(detail.data!.channel_id, 10);
|
||||
return res.data;
|
||||
},
|
||||
enabled: !!id && !!detail.data?.channel_id,
|
||||
});
|
||||
);
|
||||
return {
|
||||
message: detail.data ?? null,
|
||||
attachments: attachments.data ?? [],
|
||||
@@ -147,52 +148,70 @@ export function useMessageDetail(id: string | null) {
|
||||
// ── Mutations ────────────────────────────────────
|
||||
|
||||
export function useReanalyze() {
|
||||
const _qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => messagesApi.reanalyze(id),
|
||||
});
|
||||
return useAction((id: string) => messagesApi.reanalyze(id));
|
||||
}
|
||||
|
||||
export function useReanalyzeBatch() {
|
||||
return useMutation({
|
||||
mutationFn: (guildId: string) => messagesApi.reanalyzeBatch(guildId),
|
||||
});
|
||||
return useAction((guildId: string) => messagesApi.reanalyzeBatch(guildId));
|
||||
}
|
||||
|
||||
// ── Search ───────────────────────────────────────
|
||||
|
||||
export function useMessageSearch(query: string, enabled: boolean) {
|
||||
return useSWR<MessageRecord[]>(
|
||||
enabled && query.trim().length >= 2 ? msgKeys.search(query) : null,
|
||||
async () => {
|
||||
const res = await messagesApi.search(query, 50);
|
||||
return res.results;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── WS sync helpers ──────────────────────────────
|
||||
|
||||
export function useMessagesWsSync(ws: WsHook, guildId: string) {
|
||||
const qc = useQueryClient();
|
||||
const { mutate } = useSWRConfig();
|
||||
useEffect(() => {
|
||||
if (!guildId) return;
|
||||
const key = msgKeys.list(guildId);
|
||||
const unsub1 = ws.on("message_created", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old ? [data as MessageRecord, ...old] : [data as MessageRecord],
|
||||
// Patch every message-list key for this guild (all channels + "__all__")
|
||||
const patchLists = (
|
||||
updater: (old: MessagePage | undefined) => MessagePage | undefined,
|
||||
) => {
|
||||
void mutate(
|
||||
(key) =>
|
||||
Array.isArray(key) && key[0] === "messages" && key[1] === guildId,
|
||||
updater,
|
||||
{ revalidate: false },
|
||||
);
|
||||
};
|
||||
|
||||
const unsub1 = ws.on("message_created", (data) => {
|
||||
const msg = data as MessageRecord;
|
||||
patchLists((old) => (old ? { ...old, data: [msg, ...old.data] } : old));
|
||||
});
|
||||
const unsub2 = ws.on("message_updated", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
const msg = data as MessageRecord;
|
||||
patchLists((old) =>
|
||||
old
|
||||
? old.map((m) =>
|
||||
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
|
||||
)
|
||||
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
|
||||
: old,
|
||||
);
|
||||
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
|
||||
});
|
||||
const unsub3 = ws.on("message_deleted", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old ? old.filter((m) => m.id !== (data as { id: string }).id) : old,
|
||||
const { id } = data as { id: string };
|
||||
patchLists((old) =>
|
||||
old ? { ...old, data: old.data.filter((m) => m.id !== id) } : old,
|
||||
);
|
||||
});
|
||||
const unsub4 = ws.on("message_analyzed", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
const msg = data as MessageRecord;
|
||||
patchLists((old) =>
|
||||
old
|
||||
? old.map((m) =>
|
||||
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
|
||||
)
|
||||
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
|
||||
: old,
|
||||
);
|
||||
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
|
||||
});
|
||||
return () => {
|
||||
unsub1();
|
||||
@@ -200,5 +219,5 @@ export function useMessagesWsSync(ws: WsHook, guildId: string) {
|
||||
unsub3();
|
||||
unsub4();
|
||||
};
|
||||
}, [ws, guildId, qc]);
|
||||
}, [ws, guildId, mutate]);
|
||||
}
|
||||
|
||||
@@ -1,37 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useAction } from "@/hooks/use-action";
|
||||
import { recordingsApi } from "@/lib/api";
|
||||
import type { VoiceRecording } from "@/lib/types";
|
||||
import type { WsHook } from "@/lib/ws-hook";
|
||||
|
||||
const RECORDINGS_KEY = ["recordings"] as const;
|
||||
|
||||
export function useRecordings() {
|
||||
return useQuery<VoiceRecording[]>({
|
||||
queryKey: ["recordings"],
|
||||
queryFn: async () => {
|
||||
const res = await recordingsApi.list(50);
|
||||
return res.items;
|
||||
},
|
||||
return useSWR<VoiceRecording[]>(RECORDINGS_KEY, async () => {
|
||||
const res = await recordingsApi.list(50);
|
||||
return res.items;
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRecording() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => recordingsApi.delete(id),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["recordings"] }),
|
||||
const { mutate } = useSWRConfig();
|
||||
return useAction((id: string) => recordingsApi.delete(id), {
|
||||
onSuccess: () => {
|
||||
void mutate(RECORDINGS_KEY);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRecordingsWsSync(ws: WsHook) {
|
||||
const qc = useQueryClient();
|
||||
const { mutate } = useSWRConfig();
|
||||
useEffect(() => {
|
||||
const unsub = ws.on("voice_recording_uploaded", (data) => {
|
||||
const rec = data as VoiceRecording;
|
||||
qc.setQueryData<VoiceRecording[]>(["recordings"], (old) =>
|
||||
old ? [rec, ...old] : [rec],
|
||||
void mutate(
|
||||
RECORDINGS_KEY,
|
||||
(old: VoiceRecording[] | undefined) => (old ? [rec, ...old] : [rec]),
|
||||
{ revalidate: false },
|
||||
);
|
||||
});
|
||||
return unsub;
|
||||
}, [ws, qc]);
|
||||
}, [ws, mutate]);
|
||||
}
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useAction } from "@/hooks/use-action";
|
||||
import { voiceApi } from "@/lib/api";
|
||||
import type { ActiveSpeaker, Channel, VoiceStatus } from "@/lib/types";
|
||||
import type { WsHook } from "@/lib/ws-hook";
|
||||
|
||||
const STATUS_KEY = ["voice-status"] as const;
|
||||
|
||||
export function useVoiceStatus() {
|
||||
return useQuery<VoiceStatus>({
|
||||
queryKey: ["voice-status"],
|
||||
queryFn: () => voiceApi.getStatus(),
|
||||
retry: false,
|
||||
return useSWR<VoiceStatus>(STATUS_KEY, () => voiceApi.getStatus(), {
|
||||
shouldRetryOnError: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useVoiceChannels(guildId: string) {
|
||||
return useQuery<Channel[]>({
|
||||
queryKey: ["voice-channels", guildId],
|
||||
queryFn: () => voiceApi.getVoiceChannels(guildId),
|
||||
enabled: !!guildId,
|
||||
});
|
||||
return useSWR<Channel[]>(guildId ? ["voice-channels", guildId] : null, () =>
|
||||
voiceApi.getVoiceChannels(guildId),
|
||||
);
|
||||
}
|
||||
|
||||
export function useSpeakers() {
|
||||
@@ -46,33 +44,31 @@ export function useSpeakers() {
|
||||
return { speakers, subscribe };
|
||||
}
|
||||
|
||||
function useStatusInvalidator() {
|
||||
const { mutate } = useSWRConfig();
|
||||
return () => {
|
||||
void mutate(STATUS_KEY);
|
||||
};
|
||||
}
|
||||
|
||||
export function useVoiceConnect() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
guildId,
|
||||
channelId,
|
||||
}: {
|
||||
guildId: string;
|
||||
channelId: string;
|
||||
}) => voiceApi.connect(guildId, channelId),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
|
||||
});
|
||||
const invalidate = useStatusInvalidator();
|
||||
return useAction(
|
||||
({ guildId, channelId }: { guildId: string; channelId: string }) =>
|
||||
voiceApi.connect(guildId, channelId),
|
||||
{ onSuccess: invalidate },
|
||||
);
|
||||
}
|
||||
|
||||
export function useVoiceDisconnect() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => voiceApi.disconnect(),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
|
||||
});
|
||||
const invalidate = useStatusInvalidator();
|
||||
return useAction(() => voiceApi.disconnect(), { onSuccess: invalidate });
|
||||
}
|
||||
|
||||
export function useMicTransmit() {
|
||||
return useMutation({
|
||||
mutationFn: (active: boolean) =>
|
||||
voiceApi.sendCommand(
|
||||
active ? "voice:transmit:start" : "voice:transmit:stop",
|
||||
),
|
||||
});
|
||||
return useAction((active: boolean) =>
|
||||
voiceApi.sendCommand(
|
||||
active ? "voice:transmit:start" : "voice:transmit:stop",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { MessageMetadata } from "@/lib/types/message";
|
||||
|
||||
/**
|
||||
* Format a number with locale separators.
|
||||
*/
|
||||
@@ -72,3 +74,65 @@ export function getMessageChannelLabel(msg: {
|
||||
if (channelName) return channelName;
|
||||
return msg.channel_id?.slice(0, 8) ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render Discord mention/emoji/sticker tokens in message content to readable
|
||||
* names using the captured metadata (mentionedRoles / mentionedUsers /
|
||||
* customEmojis / stickers). Mirror of the gateway's renderDiscordMentions.
|
||||
*
|
||||
* - `<@&id>` → `@RoleName` (falls back to `@role`)
|
||||
* - `<@id>` / `<@!id>` → `@Username` (falls back to `@user`)
|
||||
* - `<:name:id>` → `:name:` (falls back to the literal name)
|
||||
* - sticker-only content already stored as `[Sticker: name]`; when a message
|
||||
* has both text and stickers, append `[Sticker: name]` so stickers always
|
||||
* surface in the feed.
|
||||
*/
|
||||
export function renderMessageContent(
|
||||
content: string,
|
||||
metadata?: string | null,
|
||||
): string {
|
||||
if (!content) return content;
|
||||
let m: MessageMetadata | null = null;
|
||||
try {
|
||||
m = JSON.parse(metadata ?? "") as MessageMetadata;
|
||||
} catch {
|
||||
// metadata malformed — render tokens from their literal names only
|
||||
}
|
||||
|
||||
let rendered = content;
|
||||
if (rendered.includes("<")) {
|
||||
const roles = new Map(
|
||||
(m?.mentionedRoles ?? []).map((r) => [r.id, r.name] as const),
|
||||
);
|
||||
const users = new Map(
|
||||
(m?.mentionedUsers ?? []).map((u) => [u.id, u.username] as const),
|
||||
);
|
||||
const emojis = new Map(
|
||||
(m?.customEmojis ?? []).map((e) => [e.id, e.name] as const),
|
||||
);
|
||||
rendered = rendered.replace(
|
||||
/<(?:a)?:([a-zA-Z0-9_]+):(\d{17,20})>|<@!?(\d{17,20})>|<@&(\d{17,20})>/g,
|
||||
(_full, emojiTokenName, emojiId, userId, roleId) => {
|
||||
if (emojiId !== undefined) {
|
||||
return `:${emojis.get(emojiId) ?? emojiTokenName}:`;
|
||||
}
|
||||
if (roleId !== undefined) return `@${roles.get(roleId) ?? "role"}`;
|
||||
if (userId !== undefined) return `@${users.get(userId) ?? "user"}`;
|
||||
return _full;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const stickers = m?.stickers ?? [];
|
||||
if (
|
||||
stickers.length > 0 &&
|
||||
!rendered.includes("[Sticker:") &&
|
||||
!rendered.includes("[Attachment:")
|
||||
) {
|
||||
rendered += ` ${stickers
|
||||
.map((s) => `[Sticker: ${s.name ?? "unknown"}]`)
|
||||
.join(" ")}`;
|
||||
}
|
||||
|
||||
return rendered;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,23 @@ export interface StickerInfo {
|
||||
url?: string | null;
|
||||
}
|
||||
|
||||
export interface CustomEmojiInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
animated?: boolean;
|
||||
url?: string | null;
|
||||
}
|
||||
|
||||
export interface MentionedRoleInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface MentionedUserInfo {
|
||||
id: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface AttachmentRef {
|
||||
name: string;
|
||||
url: string;
|
||||
@@ -70,6 +87,9 @@ export interface MessageMetadata {
|
||||
stickers?: StickerInfo[] | null;
|
||||
attachments?: AttachmentRef[] | null;
|
||||
embeds?: EmbedInfo[] | null;
|
||||
customEmojis?: CustomEmojiInfo[] | null;
|
||||
mentionedRoles?: MentionedRoleInfo[] | null;
|
||||
mentionedUsers?: MentionedUserInfo[] | null;
|
||||
channel?: ChannelRef | null;
|
||||
reference?: ReferenceInfo | null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user