refactor: split monolith into 3 microservices (frontend, backend, discord-gateway)
- Extract services into services/{frontend,backend,discord-gateway}
- Create packages/shared/ for shared logger, errors, utils, types
- Setup Modular MVC pattern in backend (controller→service→repository)
- Setup event-driven architecture in discord-gateway with Redis pub/sub
- Move Docker files to infra/docker/ with per-service Dockerfiles
- Update docker-compose.yml to use Traefik-only routing (no port exposes)
- Update GitHub Actions deploy workflow for multi-service matrix build
- Fix all import paths and resolve type errors across all services
- All 3 services pass tsc --noEmit clean
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
bda8304bb9
commit
c48a0c5e3b
@@ -0,0 +1,136 @@
|
||||
import type { MessageRecord } from "../../../shared/api/client";
|
||||
|
||||
interface MessageMetadata {
|
||||
stickers?: Array<{ name?: string; url?: string }>;
|
||||
attachments?: Array<{ name: string; url: string; contentType?: string }>;
|
||||
embeds?: Array<{ title?: string; image?: string; thumbnail?: string }>;
|
||||
}
|
||||
|
||||
interface ImageItem {
|
||||
url: string;
|
||||
title: string;
|
||||
kind: "attachment" | "embed" | "sticker";
|
||||
message: MessageRecord;
|
||||
}
|
||||
|
||||
function parseMetadata(value: string | null): MessageMetadata {
|
||||
if (!value) return {};
|
||||
try {
|
||||
return JSON.parse(value) as MessageMetadata;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function ImageGrid({ messages }: { messages: MessageRecord[] }) {
|
||||
const images: ImageItem[] = [];
|
||||
|
||||
for (const message of messages) {
|
||||
const metadata = parseMetadata(message.metadata);
|
||||
|
||||
// Stickers
|
||||
for (const sticker of metadata.stickers ?? []) {
|
||||
if (sticker.url) {
|
||||
images.push({
|
||||
url: sticker.url,
|
||||
title: sticker.name || "sticker",
|
||||
kind: "sticker",
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Attachments
|
||||
for (const attachment of metadata.attachments ?? []) {
|
||||
if (
|
||||
attachment.url &&
|
||||
(attachment.contentType?.startsWith("image/") ||
|
||||
/\.(png|jpe?g|gif|webp)$/i.test(attachment.name))
|
||||
) {
|
||||
images.push({
|
||||
url: attachment.url,
|
||||
title: attachment.name,
|
||||
kind: "attachment",
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Embed images
|
||||
for (const embed of metadata.embeds ?? []) {
|
||||
for (const imgUrl of [embed.image, embed.thumbnail].filter(Boolean)) {
|
||||
images.push({
|
||||
url: imgUrl as string,
|
||||
title: embed.title || "embed image",
|
||||
kind: "embed",
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (images.length === 0) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-dashed border-border p-10 text-center text-sm text-muted-foreground">
|
||||
No images found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{images.map((image, index) => {
|
||||
// Stable key using message.id + url
|
||||
const stableKey = `${image.message.id}-${image.kind}-${index}`;
|
||||
return (
|
||||
<a
|
||||
key={stableKey}
|
||||
href={image.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="group overflow-hidden rounded-2xl border border-border bg-card shadow-sm transition-all hover:border-primary/30 hover:shadow-md"
|
||||
>
|
||||
<div className="relative aspect-video overflow-hidden">
|
||||
{image.kind === "sticker" ? (
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.title}
|
||||
className="h-full w-full object-contain bg-muted/30 p-2 transition-transform group-hover:scale-105"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.title}
|
||||
className="h-full w-full object-cover transition-transform group-hover:scale-105"
|
||||
loading="lazy"
|
||||
/>
|
||||
)}
|
||||
<div className="absolute right-2 top-2 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wider text-white backdrop-blur">
|
||||
{image.kind}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<div className="truncate text-sm font-medium">{image.title}</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-4 w-4 overflow-hidden rounded-full">
|
||||
<img
|
||||
src={
|
||||
image.message.avatar_url ??
|
||||
"https://cdn.discordapp.com/embed/avatars/0.png"
|
||||
}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{image.message.username}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
CheckCircle2,
|
||||
Image as ImageIcon,
|
||||
Pencil,
|
||||
RotateCw,
|
||||
Smile,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import type { MessageRecord } from "../../../shared/api/client";
|
||||
import { Badge, Button, Skeleton } from "../../../shared/ui";
|
||||
|
||||
const CUSTOM_EMOJI_REGEX = /<(a)?:([a-zA-Z0-9_]+):(\d+)>/g;
|
||||
|
||||
/**
|
||||
* Renders message content with Discord custom emojis displayed as images
|
||||
* instead of raw text like `<:name:id>`.
|
||||
*/
|
||||
function renderContentWithCustomEmojis(content: string): React.ReactNode {
|
||||
const parts: React.ReactNode[] = [];
|
||||
const regex = new RegExp(CUSTOM_EMOJI_REGEX.source, "g");
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = regex.exec(content)) !== null) {
|
||||
// Text before the emoji
|
||||
if (match.index > lastIndex) {
|
||||
parts.push(content.slice(lastIndex, match.index));
|
||||
}
|
||||
|
||||
const [, animated, name, id] = match;
|
||||
const ext = animated ? "gif" : "png";
|
||||
const url = `https://cdn.discordapp.com/emojis/${id}.${ext}?size=128`;
|
||||
|
||||
parts.push(
|
||||
<img
|
||||
key={`${id}-${match.index}`}
|
||||
src={url}
|
||||
alt={name}
|
||||
className="inline-block h-[22px] w-[22px] align-middle object-contain"
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
title={`:${name}:`}
|
||||
/>,
|
||||
);
|
||||
|
||||
lastIndex = regex.lastIndex;
|
||||
}
|
||||
|
||||
// Remaining text after last emoji
|
||||
if (lastIndex < content.length) {
|
||||
parts.push(content.slice(lastIndex));
|
||||
}
|
||||
|
||||
// If no emojis were found, just return the raw content
|
||||
if (parts.length === 0) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return <Fragment>{parts}</Fragment>;
|
||||
}
|
||||
|
||||
interface MessageCardProps {
|
||||
message: MessageRecord;
|
||||
onReanalyze: (id: string) => Promise<void>;
|
||||
}
|
||||
|
||||
interface MessageMetadata {
|
||||
stickers?: Array<{ name?: string; url?: string }>;
|
||||
attachments?: Array<{ name: string; url: string; contentType?: string }>;
|
||||
embeds?: Array<{ title?: string; image?: string; thumbnail?: string }>;
|
||||
}
|
||||
|
||||
function parseMetadata(value: string | null): MessageMetadata {
|
||||
if (!value) return {};
|
||||
try {
|
||||
return JSON.parse(value) as MessageMetadata;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function parseStringList(value?: string | null): string[] {
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is string => typeof item === "string")
|
||||
: [];
|
||||
} catch {
|
||||
return value
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
}
|
||||
|
||||
function aiVariant(status: string) {
|
||||
if (status === "clean") return "success";
|
||||
if (status === "warn") return "warning";
|
||||
if (status === "flagged" || status === "error") return "destructive";
|
||||
return "secondary";
|
||||
}
|
||||
|
||||
function severityColor(severity: string) {
|
||||
switch (severity) {
|
||||
case "critical":
|
||||
return "bg-red-500/20 text-red-300 border-red-500/30";
|
||||
case "high":
|
||||
return "bg-orange-500/20 text-orange-300 border-orange-500/30";
|
||||
case "medium":
|
||||
return "bg-yellow-500/20 text-yellow-300 border-yellow-500/30";
|
||||
case "low":
|
||||
return "bg-blue-500/20 text-blue-300 border-blue-500/30";
|
||||
default:
|
||||
return "bg-muted text-muted-foreground border-border";
|
||||
}
|
||||
}
|
||||
|
||||
function formatTimeAgo(ts: number): string {
|
||||
const seconds = Math.floor((Date.now() - ts) / 1000);
|
||||
if (seconds < 60) return `${seconds}s ago`;
|
||||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
||||
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
||||
return new Date(ts).toLocaleDateString();
|
||||
}
|
||||
|
||||
export function MessageCard({ message, onReanalyze }: MessageCardProps) {
|
||||
const metadata = useMemo(
|
||||
() => parseMetadata(message.metadata),
|
||||
[message.metadata],
|
||||
);
|
||||
const displayContent = message.edited_content ?? message.content;
|
||||
const aiStatus = message.ai_status ?? "pending";
|
||||
const categories = useMemo(() => {
|
||||
const list = parseStringList(
|
||||
message.ai_categories ?? message.ai_moderation_flags,
|
||||
);
|
||||
return list.filter((c) => c !== "analysis_incomplete");
|
||||
}, [message.ai_categories, message.ai_moderation_flags]);
|
||||
const confidence =
|
||||
message.ai_confidence ?? message.ai_moderation_score ?? null;
|
||||
const [isReanalyzing, setIsReanalyzing] = useState(false);
|
||||
|
||||
const stickers = metadata.stickers ?? [];
|
||||
const attachments = metadata.attachments ?? [];
|
||||
const imageAttachments = attachments.filter(
|
||||
(a) =>
|
||||
a.contentType?.startsWith("image/") ||
|
||||
/\.(png|jpe?g|gif|webp)$/i.test(a.name),
|
||||
);
|
||||
const hasImages = imageAttachments.length > 0;
|
||||
|
||||
const handleReanalyze = async () => {
|
||||
setIsReanalyzing(true);
|
||||
try {
|
||||
await onReanalyze(message.id);
|
||||
} finally {
|
||||
setIsReanalyzing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<article
|
||||
className={`group rounded-2xl border border-border bg-card p-4 shadow-sm transition-all hover:border-primary/30 hover:shadow-md ${message.deleted_at ? "opacity-60" : ""}`}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<img
|
||||
src={
|
||||
message.avatar_url ??
|
||||
"https://cdn.discordapp.com/embed/avatars/0.png"
|
||||
}
|
||||
alt=""
|
||||
className="h-10 w-10 shrink-0 rounded-full object-cover ring-1 ring-border"
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-2.5">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="font-semibold text-foreground">
|
||||
{message.username || message.user_id}
|
||||
</span>
|
||||
<span
|
||||
className="text-xs text-muted-foreground"
|
||||
title={new Date(message.created_at).toLocaleString()}
|
||||
>
|
||||
{formatTimeAgo(message.created_at)}
|
||||
</span>
|
||||
{message.edited_at && (
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Pencil className="h-3 w-3" /> edited
|
||||
</span>
|
||||
)}
|
||||
{message.deleted_at && (
|
||||
<span className="flex items-center gap-1 text-xs text-destructive">
|
||||
<Trash2 className="h-3 w-3" /> deleted
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
<Badge
|
||||
variant={aiVariant(aiStatus)}
|
||||
className="flex items-center gap-1 text-xs"
|
||||
>
|
||||
{aiStatus === "clean" && (
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{aiStatus === "warn" && (
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{aiStatus === "flagged" && (
|
||||
<AlertCircle className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{aiStatus === "error" && (
|
||||
<AlertCircle className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{aiStatus}
|
||||
</Badge>
|
||||
{message.ai_severity && message.ai_severity !== "none" && (
|
||||
<Badge
|
||||
className={`text-xs ${severityColor(message.ai_severity)}`}
|
||||
>
|
||||
{message.ai_severity}
|
||||
</Badge>
|
||||
)}
|
||||
{confidence != null && (
|
||||
<Badge variant="outline" className="text-xs tabular-nums">
|
||||
{Math.round(confidence * 100)}%
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{displayContent ? (
|
||||
<p className="whitespace-pre-wrap break-words text-sm leading-6 text-foreground/90">
|
||||
{renderContentWithCustomEmojis(displayContent)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{stickers.length > 0 && (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{stickers.map((sticker) => (
|
||||
<div
|
||||
key={sticker.name || sticker.url}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{sticker.url ? (
|
||||
<img
|
||||
src={sticker.url}
|
||||
alt={sticker.name || "sticker"}
|
||||
className="h-16 w-16 rounded-xl border border-border object-contain bg-muted/50"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-xl border border-border bg-muted/50">
|
||||
<Smile className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<span
|
||||
className="text-xs text-muted-foreground max-w-[120px] truncate"
|
||||
title={sticker.name}
|
||||
>
|
||||
{sticker.name}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasImages && (
|
||||
<div className="flex gap-2 overflow-x-auto">
|
||||
{imageAttachments.slice(0, 4).map((img) => (
|
||||
<a
|
||||
key={img.url}
|
||||
href={img.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="shrink-0 overflow-hidden rounded-xl border border-border"
|
||||
>
|
||||
<img
|
||||
src={img.url}
|
||||
alt={img.name}
|
||||
className="h-20 w-20 object-cover transition-transform hover:scale-105"
|
||||
loading="lazy"
|
||||
/>
|
||||
</a>
|
||||
))}
|
||||
{imageAttachments.length > 4 && (
|
||||
<div className="flex h-20 w-20 items-center justify-center rounded-xl border border-border bg-muted text-xs text-muted-foreground">
|
||||
+{imageAttachments.length - 4}{" "}
|
||||
<ImageIcon className="ml-1 h-3 w-3" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{categories.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{categories.map((category) => (
|
||||
<Badge key={category} variant="secondary" className="text-xs">
|
||||
{category}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message.ai_analysis ? (
|
||||
<div className="rounded-xl bg-muted/60 p-3 text-sm text-muted-foreground leading-relaxed">
|
||||
{message.ai_analysis}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{message.ai_error ? (
|
||||
<div className="rounded-xl bg-destructive/10 p-3 text-sm text-destructive">
|
||||
AI error: {message.ai_error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant={aiStatus === "error" ? "destructive" : "outline"}
|
||||
onClick={handleReanalyze}
|
||||
disabled={aiStatus === "pending" || isReanalyzing}
|
||||
className="text-xs"
|
||||
>
|
||||
<RotateCw
|
||||
className={`h-3.5 w-3.5 ${isReanalyzing ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{isReanalyzing ? "Reanalyzing..." : "Re-analyze"}
|
||||
</Button>
|
||||
{aiStatus === "error" && (
|
||||
<span className="text-xs text-destructive/80">
|
||||
Click to retry analysis
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageCardSkeleton() {
|
||||
return (
|
||||
<article className="rounded-2xl border border-border bg-card p-4 shadow-sm">
|
||||
<div className="flex gap-3">
|
||||
<Skeleton className="h-10 w-10 shrink-0 rounded-full" />
|
||||
<div className="min-w-0 flex-1 space-y-3">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-6 w-16 rounded-full" />
|
||||
<Skeleton className="h-6 w-20 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { MessageRecord } from "../../../shared/api/client";
|
||||
import { ScrollArea } from "../../../shared/ui";
|
||||
import { MessageCard, MessageCardSkeleton } from "./MessageCard";
|
||||
|
||||
export interface MessageFeedProps {
|
||||
messages: MessageRecord[];
|
||||
onReanalyze: (id: string) => Promise<void>;
|
||||
emptyText?: string;
|
||||
loading?: boolean;
|
||||
onLoadMore?: () => void;
|
||||
hasMore?: boolean;
|
||||
loadingMore?: boolean;
|
||||
}
|
||||
|
||||
export function MessageFeed({
|
||||
messages,
|
||||
onReanalyze,
|
||||
emptyText = "No messages found.",
|
||||
loading,
|
||||
onLoadMore,
|
||||
hasMore,
|
||||
loadingMore,
|
||||
}: MessageFeedProps) {
|
||||
// IntersectionObserver for infinite scroll — fires when sentinel becomes visible
|
||||
const sentinelRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onLoadMore || !hasMore) return;
|
||||
const el = sentinelRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0]?.isIntersecting) onLoadMore();
|
||||
},
|
||||
{ rootMargin: "400px" }, // preload before user reaches bottom
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [onLoadMore, hasMore]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<ScrollArea className="h-[calc(100vh-260px)] pr-3">
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<MessageCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-dashed border-border p-10 text-center text-sm text-muted-foreground">
|
||||
{emptyText}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollArea className="h-[calc(100vh-260px)] pr-3">
|
||||
<div className="space-y-3">
|
||||
{messages.map((message) => (
|
||||
<MessageCard
|
||||
key={message.id}
|
||||
message={message}
|
||||
onReanalyze={onReanalyze}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Infinite-scroll sentinel */}
|
||||
{hasMore && (
|
||||
<div
|
||||
ref={sentinelRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
>
|
||||
{loadingMore ? (
|
||||
<MessageCardSkeleton />
|
||||
) : (
|
||||
<div className="h-2 w-2 rounded-full bg-muted-foreground/40" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import type { MessageRecord } from "../../../shared/api/client";
|
||||
import { listMessages, reanalyzeMessage } from "../../../shared/api/client";
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
export function mergeMessages(
|
||||
current: MessageRecord[],
|
||||
incoming: MessageRecord[],
|
||||
): MessageRecord[] {
|
||||
const byId = new Map(current.map((message) => [message.id, message]));
|
||||
for (const message of incoming) {
|
||||
byId.set(message.id, { ...byId.get(message.id), ...message });
|
||||
}
|
||||
// Removed .slice(0, 200) cap — let the message list grow unbounded.
|
||||
// Infinite scroll handles the data volume via cursor pagination.
|
||||
return Array.from(byId.values()).sort(
|
||||
(a, b) => b.created_at - a.created_at || b.id.localeCompare(a.id),
|
||||
);
|
||||
}
|
||||
|
||||
export function useMessages() {
|
||||
const [messages, setMessages] = useState<MessageRecord[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [cursor, setCursor] = useState<string | null>(null);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const currentChannel = useRef<string | null>(null);
|
||||
|
||||
const fetchMessages = useCallback(async (channelId?: string) => {
|
||||
if (!channelId) {
|
||||
setMessages([]);
|
||||
setCursor(null);
|
||||
setHasMore(false);
|
||||
return [];
|
||||
}
|
||||
currentChannel.current = channelId;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
limit: String(PAGE_SIZE),
|
||||
channelId,
|
||||
});
|
||||
const result = await listMessages(params);
|
||||
// Only update state if we're still on the same channel (avoid race conditions)
|
||||
if (currentChannel.current === channelId) {
|
||||
setMessages(result.data);
|
||||
setCursor(result.nextCursor);
|
||||
setHasMore(!!result.nextCursor);
|
||||
}
|
||||
return result.data;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
if (!cursor || !currentChannel.current || loadingMore) return;
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
limit: String(PAGE_SIZE),
|
||||
channelId: currentChannel.current,
|
||||
cursor,
|
||||
});
|
||||
const result = await listMessages(params);
|
||||
// Only update if still on the same channel
|
||||
if (
|
||||
currentChannel.current === result.data[0]?.channel_id ||
|
||||
currentChannel.current
|
||||
) {
|
||||
setMessages((prev) => [...prev, ...result.data]);
|
||||
setCursor(result.nextCursor);
|
||||
setHasMore(!!result.nextCursor);
|
||||
}
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [cursor, loadingMore]);
|
||||
|
||||
// BUG 5 FIX: reanalyze returns Promise<void> so callers can await it
|
||||
const reanalyze = useCallback(async (id: string): Promise<void> => {
|
||||
setMessages((prev) =>
|
||||
prev.map((message) =>
|
||||
message.id === id
|
||||
? {
|
||||
...message,
|
||||
ai_status: "pending" as const,
|
||||
ai_error: null,
|
||||
ai_analysis: null,
|
||||
}
|
||||
: message,
|
||||
),
|
||||
);
|
||||
await reanalyzeMessage(id);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
setMessages,
|
||||
loading,
|
||||
loadingMore,
|
||||
error,
|
||||
fetchMessages,
|
||||
reanalyze,
|
||||
loadMore,
|
||||
hasMore,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { Filter, Search, X } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { Channel, Guild, MessageRecord } from "../../shared/api/client";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Input,
|
||||
Select,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "../../shared/ui";
|
||||
import { ImageGrid } from "./components/ImageGrid";
|
||||
import { MessageFeed } from "./components/MessageFeed";
|
||||
|
||||
interface MessagesPanelProps {
|
||||
guilds: Guild[];
|
||||
channels: Channel[];
|
||||
selectedGuild: string;
|
||||
selectedChannel: string;
|
||||
messages: MessageRecord[];
|
||||
onGuildChange: (guildId: string) => void;
|
||||
onChannelChange: (channelId: string) => void;
|
||||
onReanalyze: (id: string) => Promise<void>;
|
||||
onLoadMore?: () => void;
|
||||
hasMore?: boolean;
|
||||
loadingMore?: boolean;
|
||||
}
|
||||
|
||||
type AiFilter = "all" | "clean" | "warn" | "flagged" | "error" | "pending";
|
||||
|
||||
export function MessagesPanel({
|
||||
guilds,
|
||||
channels,
|
||||
selectedGuild,
|
||||
selectedChannel,
|
||||
messages,
|
||||
onGuildChange,
|
||||
onChannelChange,
|
||||
onReanalyze,
|
||||
onLoadMore,
|
||||
hasMore,
|
||||
loadingMore,
|
||||
}: MessagesPanelProps) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [searchResults, setSearchResults] = useState<MessageRecord[]>([]);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const [showSearch, setShowSearch] = useState(false);
|
||||
const [aiFilter, setAiFilter] = useState<AiFilter>("all");
|
||||
const [viewTab, setViewTab] = useState<"all" | "images">("all");
|
||||
|
||||
const handleSearch = async () => {
|
||||
if (!searchQuery.trim()) {
|
||||
setSearchResults([]);
|
||||
setShowSearch(false);
|
||||
return;
|
||||
}
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
q: searchQuery,
|
||||
...(selectedChannel && { channelId: selectedChannel }),
|
||||
limit: "50",
|
||||
});
|
||||
const response = await fetch(`/api/analysis/search?${params}`);
|
||||
if (!response.ok) throw new Error("Search failed");
|
||||
const data = await response.json();
|
||||
setSearchResults(data.results || []);
|
||||
setShowSearch(true);
|
||||
} catch {
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const base = showSearch ? searchResults : messages;
|
||||
return {
|
||||
total: base.length,
|
||||
clean: base.filter((m) => m.ai_status === "clean").length,
|
||||
warn: base.filter((m) => m.ai_status === "warn").length,
|
||||
flagged: base.filter((m) => m.ai_status === "flagged").length,
|
||||
error: base.filter((m) => m.ai_status === "error").length,
|
||||
pending: base.filter((m) => m.ai_status === "pending" || !m.ai_status)
|
||||
.length,
|
||||
deleted: base.filter((m) => m.deleted_at).length,
|
||||
edited: base.filter((m) => m.edited_at).length,
|
||||
};
|
||||
}, [messages, searchResults, showSearch]);
|
||||
|
||||
const filteredMessages = useMemo(() => {
|
||||
const base = showSearch ? searchResults : messages;
|
||||
if (aiFilter === "all") return base;
|
||||
return base.filter((m) => {
|
||||
const status = m.ai_status ?? "pending";
|
||||
if (aiFilter === "pending")
|
||||
return status === "pending" || status === null || status === undefined;
|
||||
return status === aiFilter;
|
||||
});
|
||||
}, [messages, searchResults, showSearch, aiFilter]);
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Message Source</CardTitle>
|
||||
<CardDescription>
|
||||
Pick a guild and channel/thread to inspect captures.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 md:grid-cols-2">
|
||||
<Select
|
||||
value={selectedGuild}
|
||||
onChange={(e) => onGuildChange(e.target.value)}
|
||||
placeholder="Select text guild"
|
||||
options={guilds.map((g) => ({ value: g.id, label: g.name }))}
|
||||
/>
|
||||
<Select
|
||||
value={selectedChannel}
|
||||
onChange={(e) => onChannelChange(e.target.value)}
|
||||
placeholder="Select channel or thread"
|
||||
options={channels.map((c) => ({ value: c.id, label: c.name }))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{stats.total > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{stats.total} total{hasMore && !showSearch ? "+" : ""}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-green-400 border-green-400/30"
|
||||
>
|
||||
{stats.clean} clean
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-yellow-400 border-yellow-400/30"
|
||||
>
|
||||
{stats.warn} warn
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-red-400 border-red-400/30"
|
||||
>
|
||||
{stats.flagged} flagged
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-orange-400 border-orange-400/30"
|
||||
>
|
||||
{stats.error} error
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{stats.pending} pending
|
||||
</Badge>
|
||||
{stats.deleted > 0 && (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{stats.deleted} deleted
|
||||
</Badge>
|
||||
)}
|
||||
{stats.edited > 0 && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{stats.edited} edited
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search message content..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
|
||||
disabled={isSearching}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSearch}
|
||||
disabled={isSearching || !searchQuery.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{isSearching ? "Searching..." : "Search"}
|
||||
</Button>
|
||||
{showSearch && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setShowSearch(false);
|
||||
setSearchResults([]);
|
||||
setSearchQuery("");
|
||||
}}
|
||||
>
|
||||
<X className="mr-1 h-3 w-3" /> Clear
|
||||
</Button>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
<Filter className="h-4 w-4 text-muted-foreground" />
|
||||
{(
|
||||
[
|
||||
"all",
|
||||
"clean",
|
||||
"warn",
|
||||
"flagged",
|
||||
"error",
|
||||
"pending",
|
||||
] as AiFilter[]
|
||||
).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setAiFilter(f)}
|
||||
className={`rounded-md px-2 py-1 text-xs font-medium transition-colors ${aiFilter === f ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground hover:bg-muted"}`}
|
||||
>
|
||||
{f}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showSearch && searchResults.length > 0 && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Found {searchResults.length} result
|
||||
{searchResults.length !== 1 ? "s" : ""}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Tabs
|
||||
value={viewTab}
|
||||
onValueChange={(v) => setViewTab(v as "all" | "images")}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="all">
|
||||
{showSearch
|
||||
? `Search (${filteredMessages.length})`
|
||||
: `All (${filteredMessages.length})`}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="images">Images</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="all">
|
||||
<MessageFeed
|
||||
messages={filteredMessages}
|
||||
onReanalyze={onReanalyze}
|
||||
emptyText={
|
||||
showSearch
|
||||
? "No messages found matching your search."
|
||||
: selectedChannel
|
||||
? "No captures yet."
|
||||
: "Select a channel to view captures."
|
||||
}
|
||||
onLoadMore={showSearch ? undefined : onLoadMore}
|
||||
hasMore={showSearch ? false : hasMore}
|
||||
loadingMore={loadingMore}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="images">
|
||||
<ImageGrid messages={filteredMessages} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user