Merge branch worktree-neo-surveillance-redesign into main — Neo Surveillance redesign
Full frontend redesign with glassmorphic dark theme, floating top nav, Live2D mascot, split-pane messages, and Ops Center dashboard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com
This commit is contained in:
co-authored by
Claude Opus 4.8 (1M context) <noreply@anthropic.com
parent
102b3bac1f
commit
3f4fa42098
@@ -146,6 +146,21 @@ export const configSchema = z
|
||||
.int()
|
||||
.positive()
|
||||
.default(60000),
|
||||
// ── AI Model (new unified keys) ───────────────────────────────────
|
||||
AI_MODEL_FAST_CLASSIFIER_ENABLED: z
|
||||
.string()
|
||||
.optional()
|
||||
.transform((v) => v === "true")
|
||||
.default(true)
|
||||
.describe("Enable Layer 1 fast heuristic classifier"),
|
||||
AI_MODEL_LLM_TIMEOUT_MS: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.default(30000)
|
||||
.describe("Timeout for individual LLM moderation calls"),
|
||||
|
||||
|
||||
|
||||
// ── AI Analysis Timing ──────────────────────────────────────────────
|
||||
AI_ANALYSIS_DEBOUNCE_MS: z.coerce.number().positive().default(500),
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
/**
|
||||
* ai-analysis-worker.ts
|
||||
*
|
||||
* Two-pass AI moderation analysis worker (Piscina-compatible).
|
||||
*
|
||||
* ## Pipeline
|
||||
*
|
||||
* Message → Layer 1 (fast classifier / heuristic)
|
||||
* │
|
||||
* ├─ clear match → final result (no LLM call)
|
||||
* └─ ambiguous → Layer 2 (LLM evaluator)
|
||||
*
|
||||
* Layer 1 runs synchronously in-memory. Layer 2 calls the LLM API via
|
||||
* the existing moderation pipeline (moderationOrchestrator).
|
||||
*
|
||||
* This file replaces the old `aiAnalysisWorker.ts` (archived) with a
|
||||
* simpler, unified worker that combines both layers.
|
||||
*/
|
||||
|
||||
import { createChildLogger } from "@bete/shared/logger";
|
||||
import { config } from "../../shared/config/config.js";
|
||||
import { initializeDatabase } from "../../shared/database/drizzle.js";
|
||||
import { messageStore } from "../message-capture/messageStore.js";
|
||||
import type { MessageRecord } from "../message-capture/types.js";
|
||||
import { buildConversationContext } from "./conversationContext.js";
|
||||
import { classifyMessage } from "./fastClassifier.js";
|
||||
import type { Layer1Result } from "./fastClassifier.js";
|
||||
import { runModerationAnalysis } from "./moderationOrchestrator.js";
|
||||
|
||||
const logger = createChildLogger("ai-analysis-worker");
|
||||
|
||||
let dbInitialized = false;
|
||||
let dbInitPromise: Promise<unknown> | null = null;
|
||||
|
||||
async function ensureDb(): Promise<void> {
|
||||
if (dbInitialized) return;
|
||||
if (!dbInitPromise) {
|
||||
dbInitPromise = initializeDatabase().then(() => {
|
||||
dbInitialized = true;
|
||||
});
|
||||
}
|
||||
await dbInitPromise;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AnalysisInput {
|
||||
batch: MessageBatch;
|
||||
config: WorkerConfig;
|
||||
}
|
||||
|
||||
export interface AnalysisResult {
|
||||
messageId: string;
|
||||
status: "clean" | "warn" | "flagged" | "error";
|
||||
flags: string[];
|
||||
categories: string[];
|
||||
severity: "none" | "low" | "medium" | "high" | "critical";
|
||||
confidence: number;
|
||||
recommendedAction:
|
||||
| "none"
|
||||
| "monitor"
|
||||
| "warn"
|
||||
| "review"
|
||||
| "delete"
|
||||
| "escalate";
|
||||
toxicityScore: number;
|
||||
harmScore: number;
|
||||
jailbreakScore: number;
|
||||
safetyScore: number;
|
||||
explanation: string;
|
||||
correctedFlags?: string[];
|
||||
}
|
||||
|
||||
export interface WorkerConfig {
|
||||
aiLlmApiKey: string;
|
||||
aiLlmBaseUrl: string;
|
||||
aiLlmModel: string;
|
||||
aiLlmTimeoutMs: number;
|
||||
}
|
||||
|
||||
export interface MessageBatch {
|
||||
conversationKey: string;
|
||||
messages: MessageRecord[];
|
||||
contextMessages: string[];
|
||||
}
|
||||
|
||||
// Worker job types (Piscina entry point)
|
||||
type WorkerJob =
|
||||
| { type: "batch"; conversationKey: string; messages: MessageRecord[] }
|
||||
| {
|
||||
type: "individual";
|
||||
message: MessageRecord;
|
||||
skipNormalAnalysis: boolean;
|
||||
};
|
||||
|
||||
type BatchOkResponse = {
|
||||
ok: true;
|
||||
conversationKey: string;
|
||||
rows: MessageRecord[];
|
||||
};
|
||||
type BatchErrorResponse = {
|
||||
ok: false;
|
||||
conversationKey: string;
|
||||
rows: MessageRecord[];
|
||||
error: string;
|
||||
};
|
||||
type IndividualOkResponse = { ok: true; results: AnalysisResult[] };
|
||||
type IndividualErrorResponse = {
|
||||
ok: false;
|
||||
results: AnalysisResult[];
|
||||
error: string;
|
||||
};
|
||||
|
||||
type WorkerResponse =
|
||||
| BatchOkResponse
|
||||
| BatchErrorResponse
|
||||
| IndividualOkResponse
|
||||
| IndividualErrorResponse;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default export — Piscina worker entry point
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default async function workerRouter(
|
||||
job: WorkerJob,
|
||||
): Promise<WorkerResponse> {
|
||||
if (!config.AI_LLM_API_KEY) {
|
||||
const errorMsg =
|
||||
"AI_LLM_API_KEY is missing from environment. Worker cannot process moderation requests without credentials.";
|
||||
logger.error({ error: errorMsg }, "AI_LLM_API_KEY is missing from environment");
|
||||
|
||||
if (job.type === "batch") {
|
||||
return {
|
||||
ok: false,
|
||||
conversationKey: job.conversationKey,
|
||||
rows: [],
|
||||
error: errorMsg,
|
||||
};
|
||||
}
|
||||
return { ok: false, results: [], error: errorMsg };
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureDb();
|
||||
} catch (dbError) {
|
||||
const msg = dbError instanceof Error ? dbError.message : String(dbError);
|
||||
if (job.type === "batch") {
|
||||
return {
|
||||
ok: false,
|
||||
conversationKey: job.conversationKey,
|
||||
rows: [],
|
||||
error: `Database init failed: ${msg}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
results: [],
|
||||
error: `Database init failed: ${msg}`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
if (job.type === "batch") {
|
||||
return await processBatch(job);
|
||||
}
|
||||
return await processIndividual(job);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorStack = error instanceof Error ? error.stack : undefined;
|
||||
logger.error(
|
||||
{ type: job.type, error: errorMessage, stack: errorStack },
|
||||
"Worker job failed",
|
||||
);
|
||||
if (job.type === "batch") {
|
||||
return {
|
||||
ok: false,
|
||||
conversationKey: job.conversationKey,
|
||||
rows: [],
|
||||
error: errorMessage,
|
||||
};
|
||||
}
|
||||
return { ok: false, results: [], error: errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Two-pass pipeline
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Runs the two-pass pipeline on a single message:
|
||||
* 1. Layer 1 — fast heuristic classifier
|
||||
* 2. Layer 2 (if cascade) — LLM-based evaluator
|
||||
*
|
||||
* Returns the combined AnalysisResult.
|
||||
*/
|
||||
async function runTwoPassPipeline(
|
||||
message: MessageRecord,
|
||||
contextText: string,
|
||||
attachments: Awaited<ReturnType<typeof messageStore.getAttachmentsForMessages>>,
|
||||
): Promise<AnalysisResult> {
|
||||
// ── Layer 1: Fast classifier ──────────────────────────────────────────
|
||||
const layer1Result: Layer1Result = classifyMessage(message);
|
||||
|
||||
logger.debug(
|
||||
{
|
||||
messageId: message.id,
|
||||
layer1Flags: layer1Result.flags,
|
||||
cascade: layer1Result.cascadeToLayer2,
|
||||
},
|
||||
"Layer 1 classification complete",
|
||||
);
|
||||
|
||||
if (!layer1Result.cascadeToLayer2) {
|
||||
// Layer 1 result is final — no LLM call needed
|
||||
return buildResultFromLayer1(message.id, layer1Result);
|
||||
}
|
||||
|
||||
// ── Layer 2: LLM-based evaluation ─────────────────────────────────────
|
||||
try {
|
||||
const moderationResult = await runModerationAnalysis({
|
||||
targets: [message],
|
||||
contextText,
|
||||
attachments,
|
||||
});
|
||||
|
||||
if (moderationResult.results.length === 0) {
|
||||
return buildFallbackResult(message.id, "No LLM result returned");
|
||||
}
|
||||
|
||||
const llmResult = moderationResult.results[0];
|
||||
return mergeLayers(layer1Result, llmResult);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
logger.warn(
|
||||
{ messageId: message.id, error: errorMsg },
|
||||
"Layer 2 (LLM) analysis failed — falling back to Layer 1 result",
|
||||
);
|
||||
// Fallback to Layer 1 with reduced confidence
|
||||
const fallback = buildResultFromLayer1(message.id, layer1Result);
|
||||
fallback.confidence = Math.min(fallback.confidence, 0.4);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Result builders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildResultFromLayer1(
|
||||
messageId: string,
|
||||
layer1: Layer1Result,
|
||||
): AnalysisResult {
|
||||
const status = layer1.severity === "none" ? "clean" as const : "flagged" as const;
|
||||
const recommendedAction = mapSeverityToAction(layer1.severity);
|
||||
|
||||
return {
|
||||
messageId,
|
||||
status,
|
||||
flags: layer1.flags,
|
||||
categories: layer1.flags,
|
||||
severity: layer1.severity === "high" ? "high" as const : layer1.severity === "medium" ? "medium" as const : "low" as const,
|
||||
confidence: layer1.confidence,
|
||||
recommendedAction,
|
||||
toxicityScore: layer1.toxicityScore,
|
||||
harmScore: layer1.harmScore,
|
||||
jailbreakScore: 0,
|
||||
safetyScore: 0,
|
||||
explanation: layer1.explanation,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFallbackResult(
|
||||
messageId: string,
|
||||
reason: string,
|
||||
): AnalysisResult {
|
||||
return {
|
||||
messageId,
|
||||
status: "error",
|
||||
flags: ["analysis_incomplete"],
|
||||
categories: ["analysis_incomplete"],
|
||||
severity: "none",
|
||||
confidence: 0,
|
||||
recommendedAction: "review",
|
||||
toxicityScore: 0,
|
||||
harmScore: 0,
|
||||
jailbreakScore: 0,
|
||||
safetyScore: 0,
|
||||
explanation: reason,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeLayers(
|
||||
layer1: Layer1Result,
|
||||
llmResult: AnalysisResult,
|
||||
): AnalysisResult {
|
||||
// Merge flags from both layers (deduplicate)
|
||||
const flagSet = new Set<string>([...layer1.flags, ...(llmResult.flags || [])]);
|
||||
|
||||
// Take the max severity
|
||||
const severityOrder = ["none", "low", "medium", "high", "critical"] as const;
|
||||
const l1Idx = severityOrder.indexOf(layer1.severity);
|
||||
const l2Idx = severityOrder.indexOf(
|
||||
(llmResult.severity ?? "none") as (typeof severityOrder)[number],
|
||||
);
|
||||
const finalSeverity = severityOrder[Math.max(l1Idx, l2Idx)];
|
||||
|
||||
// Combined confidence: weighted average favoring LLM when available
|
||||
const combinedConfidence =
|
||||
0.3 * layer1.confidence + 0.7 * (llmResult.confidence ?? 0.5);
|
||||
|
||||
// Combine scores (take max per dimension)
|
||||
const toxicityScore = Math.max(
|
||||
layer1.toxicityScore,
|
||||
llmResult.toxicityScore ?? 0,
|
||||
);
|
||||
const harmScore = Math.max(layer1.harmScore, llmResult.harmScore ?? 0);
|
||||
|
||||
return {
|
||||
messageId: llmResult.messageId,
|
||||
status: llmResult.status === "error" ? "error" as const : llmResult.status ?? "clean" as const,
|
||||
flags: Array.from(flagSet),
|
||||
categories: [
|
||||
...new Set([
|
||||
...layer1.flags,
|
||||
...(llmResult.categories ?? []),
|
||||
]),
|
||||
],
|
||||
severity: finalSeverity,
|
||||
confidence: Math.min(combinedConfidence, 1),
|
||||
recommendedAction: llmResult.recommendedAction ?? mapSeverityToAction(finalSeverity),
|
||||
toxicityScore,
|
||||
harmScore,
|
||||
jailbreakScore: llmResult.jailbreakScore ?? 0,
|
||||
safetyScore: llmResult.safetyScore ?? 0,
|
||||
explanation: llmResult.explanation ?? layer1.explanation,
|
||||
};
|
||||
}
|
||||
|
||||
function mapSeverityToAction(
|
||||
severity: "none" | "low" | "medium" | "high" | "critical",
|
||||
): AnalysisResult["recommendedAction"] {
|
||||
switch (severity) {
|
||||
case "none":
|
||||
return "none";
|
||||
case "low":
|
||||
return "monitor";
|
||||
case "medium":
|
||||
return "review";
|
||||
case "high":
|
||||
return "delete";
|
||||
case "critical":
|
||||
return "escalate";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Batch handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function processBatch(job: {
|
||||
type: "batch";
|
||||
conversationKey: string;
|
||||
messages: MessageRecord[];
|
||||
}): Promise<BatchOkResponse | BatchErrorResponse> {
|
||||
const { conversationKey, messages } = job;
|
||||
const firstMessage = messages[0];
|
||||
if (!firstMessage) return { ok: true, conversationKey, rows: [] };
|
||||
|
||||
// Fetch context
|
||||
const contextBefore = await messageStore.getConversationContextBefore({
|
||||
channelId: firstMessage.channel_id,
|
||||
threadId: firstMessage.thread_id,
|
||||
beforeCreatedAt: firstMessage.created_at,
|
||||
limit: config.AI_ANALYSIS_CONTEXT_MESSAGE_LIMIT,
|
||||
});
|
||||
|
||||
const contextLines = buildConversationContext({
|
||||
contextBefore,
|
||||
targets: messages,
|
||||
maxTokens: config.AI_ANALYSIS_MAX_CONTEXT_TOKENS,
|
||||
});
|
||||
const contextText = contextLines.join("\n");
|
||||
|
||||
// Fetch attachments
|
||||
const targetIds = messages.map((m) => m.id);
|
||||
const contextIds = contextBefore.map((m) => m.id);
|
||||
const allMessageIds = [...targetIds, ...contextIds];
|
||||
const attachments =
|
||||
await messageStore.getAttachmentsForMessages(allMessageIds);
|
||||
|
||||
// Run two-pass pipeline for each message
|
||||
const analysisResults = await Promise.all(
|
||||
messages.map(async (msg) => {
|
||||
try {
|
||||
return await runTwoPassPipeline(msg, contextText, attachments);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
logger.error(
|
||||
{ messageId: msg.id, error: errorMsg },
|
||||
"Two-pass pipeline failed for message",
|
||||
);
|
||||
return buildFallbackResult(msg.id, errorMsg);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Save results to DB
|
||||
const updates = analysisResults.map((result) => ({
|
||||
messageId: result.messageId,
|
||||
result: {
|
||||
status: result.status,
|
||||
flags: JSON.stringify(result.flags),
|
||||
score: result.toxicityScore,
|
||||
analysis: result.explanation,
|
||||
categories: result.categories,
|
||||
severity: result.severity,
|
||||
confidence: result.confidence,
|
||||
recommendedAction: result.recommendedAction,
|
||||
analyzedAt: Date.now(),
|
||||
error: result.status === "error" ? result.explanation : null,
|
||||
},
|
||||
}));
|
||||
|
||||
let allRows: MessageRecord[] = [];
|
||||
if (updates.length > 0) {
|
||||
allRows = await messageStore.updateMessagesAIAnalysisBulk(updates);
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
total: messages.length,
|
||||
saved: allRows.length,
|
||||
conversationKey,
|
||||
},
|
||||
"Two-pass batch analysis complete",
|
||||
);
|
||||
|
||||
return { ok: true, conversationKey, rows: allRows };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Individual fallback handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function processIndividual(job: {
|
||||
type: "individual";
|
||||
message: MessageRecord;
|
||||
skipNormalAnalysis: boolean;
|
||||
}): Promise<IndividualOkResponse | IndividualErrorResponse> {
|
||||
const { message, skipNormalAnalysis } = job;
|
||||
|
||||
if (skipNormalAnalysis) {
|
||||
// Use Layer 1 only (fast)
|
||||
const layer1Result = classifyMessage(message);
|
||||
|
||||
if (!layer1Result.cascadeToLayer2) {
|
||||
// Layer 1 is sufficient
|
||||
return {
|
||||
ok: true,
|
||||
results: [buildResultFromLayer1(message.id, layer1Result)],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Full analysis (context + two-pass)
|
||||
const contextBefore = await messageStore.getConversationContextBefore({
|
||||
channelId: message.channel_id,
|
||||
threadId: message.thread_id,
|
||||
beforeCreatedAt: message.created_at,
|
||||
limit: config.AI_ANALYSIS_CONTEXT_MESSAGE_LIMIT,
|
||||
});
|
||||
|
||||
const contextLines = buildConversationContext({
|
||||
contextBefore,
|
||||
targets: [message],
|
||||
maxTokens: config.AI_ANALYSIS_MAX_CONTEXT_TOKENS,
|
||||
});
|
||||
const contextText = contextLines.join("\n");
|
||||
|
||||
const contextIds = contextBefore.map((m) => m.id);
|
||||
const attachments = await messageStore.getAttachmentsForMessages([
|
||||
message.id,
|
||||
...contextIds,
|
||||
]);
|
||||
|
||||
try {
|
||||
const result = await runTwoPassPipeline(message, contextText, attachments);
|
||||
return { ok: true, results: [result] };
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
logger.error(
|
||||
{ messageId: message.id, error: errorMsg },
|
||||
"Individual two-pass analysis failed",
|
||||
);
|
||||
return { ok: true, results: [buildFallbackResult(message.id, errorMsg)] };
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import type { MessageRecord } from "../message-capture/types.js";
|
||||
|
||||
function getAnalysisWorkerUrl(): URL {
|
||||
const candidates = [
|
||||
new URL("./aiAnalysisWorker.js", import.meta.url),
|
||||
new URL("../aiAnalysisWorker.js", import.meta.url),
|
||||
new URL("./aiAnalysisWorker.ts", import.meta.url),
|
||||
new URL("./ai-analysis-worker.js", import.meta.url),
|
||||
new URL("../ai-analysis-worker.js", import.meta.url),
|
||||
new URL("./ai-analysis-worker.ts", import.meta.url),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* fastClassifier.ts
|
||||
*
|
||||
* Layer 1 — Synchronous heuristic classifier for the two-pass moderation pipeline.
|
||||
* Runs BEFORE any LLM call. Catches obvious spam, NSFW patterns, repeated characters,
|
||||
* and other low-hanging fruit with zero network cost.
|
||||
*
|
||||
* When a strong heuristic match is found, `cascadeToLayer2` is `false` and the
|
||||
* result is used as the final verdict. Otherwise the message proceeds to the LLM.
|
||||
*/
|
||||
|
||||
import type { MessageRecord } from "../message-capture/types.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface Layer1Result {
|
||||
flags: string[];
|
||||
severity: "none" | "low" | "medium" | "high";
|
||||
toxicityScore: number;
|
||||
harmScore: number;
|
||||
cascadeToLayer2: boolean;
|
||||
confidence: number;
|
||||
explanation: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pattern definitions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Pattern {
|
||||
name: string;
|
||||
test: (content: string, mentions: number) => boolean;
|
||||
severity: "low" | "medium" | "high";
|
||||
score: number; // contribution to toxicity/harm score
|
||||
category: "toxicity" | "harm" | "spam" | "safety";
|
||||
}
|
||||
|
||||
// ── Zalgo / zero-width detection ─────────────────────────────────────────
|
||||
|
||||
const ZALGO_RE =
|
||||
/[̀-ͯ҃-҉ؐ-ًؚ-ٰٟۖ-ۜ۟-ۤۧ-۪ۨ-ܑۭܰ-݊ަ-ްँ-ः़ा-्॑-॔ॢ-ॣঁ-ঃ়া-ৄে-ৈো-্ৗৢ-ৣ৾ਁ-ਃ਼ਾ-ੂੇ-ੈੋ-੍ੑੰ-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣૺ-૿ଁ-ଃ଼ା-ୄେ-ୈୋ-୍ୖ-ୗୢ-ୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕ-ౖౢ-ౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕ-ೖೢ-ೣഀ-ഃ഻-഼ാ-ൄെ-ൈൊ-്ൗൢ-ൣඁ-ඃ්ා-ුූෘ-ෟෲ-ෳัิ-ฺ็-๎ັິ-ູົ-ຼ່-ໍ༘-༹༙༵༷༾-༿ཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒ-ᝓᝲ-ᝳ឴-៓៝᠋-᠍ᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪾ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮁᮢ-ᮥᮨ-ᮩ᮫-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷿-
- -⃐-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙〯-゚꙯-꙲ꙴ-꙽ꚞ-ꚟ꛰-꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀ-ꢁꢴ-ꣅ꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꥠ-ꥼꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷ-ꪸꪾ-꪿꫁ꫫ-ꫯꫵ-꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯-]||͏|ᅟᅠ឴឵ - --ㅤᅠ-\U000e0001\U000e0020-\U000e007f/;
|
||||
|
||||
const ZERO_WIDTH_RE = /[-]/;
|
||||
|
||||
// ── URL / invite / phone / email / crypto patterns ─────────────────────
|
||||
|
||||
const URL_RE = /https?:\/\/[^\s"]+/gi;
|
||||
const INVITE_RE = /(?:discord\.(?:gg|com\/invite)|dsc\.gg)\/[a-zA-Z0-9_-]+/gi;
|
||||
const INVITE_CODE_RE = /(?:^|\s)([a-zA-Z0-9_-]{6,12})(?:\s|$)/g;
|
||||
const PHONE_RE =
|
||||
/(?:\+?\d{1,3}[-.\s]?)?\(?\d{2,4}\)?[-.\s]?\d{3,4}[-.\s]?\d{3,4}/g;
|
||||
const EMAIL_RE = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gi;
|
||||
const CRYPTO_RE =
|
||||
/(?:0x[a-fA-F0-9]{40}|bc1[a-z0-9]{39,59}|1[a-km-zA-HJ-NP-Z1-9]{25,34}|3[a-km-zA-HJ-NP-Z1-9]{25,34})/g;
|
||||
const IP_RE = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g;
|
||||
|
||||
// ── Spam / low-quality patterns ─────────────────────────────────────────
|
||||
|
||||
const REPEATED_CHAR_RE = /(.)\1{8,}/; // 9+ repeated chars
|
||||
const REPEATED_WORD_RE = /\b(\w{3,})\b\s*\b\1\b\s*\b\1\b/; // same word 3x
|
||||
const EXCESSIVE_CAPS_RE = /[A-Z]{6,}/;
|
||||
const EXCESSIVE_EMOJI_RE =
|
||||
/[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu;
|
||||
const BASE64_RE =
|
||||
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
||||
const PHISHING_RE =
|
||||
/(?:free\s*(?:nitro|gift|prime|steam|vbucks?)|click\s*(?:here|this)\s*(?:to|for)\s*(?:claim|win|verify)|login\s*:\s*\w+\s*password\s*:\s*\w+)/gi;
|
||||
|
||||
// ── Toxicity patterns ───────────────────────────────────────────────────
|
||||
|
||||
const HARASSMENT_RE =
|
||||
/\b(?:fuck|shit|asshole|bitch|dickhead|cunt|motherfucker|bastard|piss\s*off|screw\s*you|go\s*(?:to\s*)?hell|kys|kill\s*(?:yourself| urself))\b/i;
|
||||
const HATE_SPEECH_RE =
|
||||
/\b(?:nazi|white\s*supremacy|heil|racial\s*purity|race\s*war)\b/i;
|
||||
|
||||
// ── Harm patterns ───────────────────────────────────────────────────────
|
||||
|
||||
const SELF_HARM_RE =
|
||||
/\b(?:kill\s*(?:myself|me)|end\s*(?:my|the)\s*(?:life|own)|suicide|want\s*(?:to\s*)?die|cut\s*(?:myself|my\s*wrists)|harm\s*myself)\b/i;
|
||||
const VIOLENCE_RE =
|
||||
/\b(?:shoot|stab|bomb|massacre|terrorist|behead|torture|murder)\b/i;
|
||||
|
||||
// ── Safety patterns ─────────────────────────────────────────────────────
|
||||
|
||||
const PERSONAL_INFO_RE =
|
||||
/\b(?:\d{3}-\d{2}-\d{4}|(?:\d{3}\s?){2}\d{4})\b/; // SSN / IDs
|
||||
const SEXTORTION_RE =
|
||||
/\b(?:nudes?\s*(?:pic|photo|video|send|trade)|cp\s*(?:content|link|loli|shotacon)|underage|minor\s*(?:girl|boy|content))\b/i;
|
||||
const GROOMING_RE =
|
||||
/\b(?:how\s*old\s*are\s*you|are\s*you\s*(?:alone|home\s*alone)|dm\s*me\s*(?:baby|honey|sweetie|cutie)|send\s*(?:nudes|pics))\b/i;
|
||||
|
||||
// ── Mass-mention patterns ───────────────────────────────────────────────
|
||||
|
||||
const EVERYONE_MENTION = /@everyone/g;
|
||||
const HERE_MENTION = /@here/g;
|
||||
const ROLE_MENTION = /<@&(\d+)>/g;
|
||||
|
||||
// ── Pattern registry (ordered roughly by specificity) ───────────────────
|
||||
|
||||
const PATTERNS: Pattern[] = [
|
||||
// ── High severity ─────────────────────────────────────────────────
|
||||
{
|
||||
name: "self_harm",
|
||||
test: (c) => SELF_HARM_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.9,
|
||||
category: "harm",
|
||||
},
|
||||
{
|
||||
name: "violence_threat",
|
||||
test: (c) => VIOLENCE_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.85,
|
||||
category: "harm",
|
||||
},
|
||||
{
|
||||
name: "sextortion",
|
||||
test: (c) => SEXTORTION_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.95,
|
||||
category: "safety",
|
||||
},
|
||||
{
|
||||
name: "grooming",
|
||||
test: (c) => GROOMING_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.9,
|
||||
category: "safety",
|
||||
},
|
||||
{
|
||||
name: "hate_speech",
|
||||
test: (c) => HATE_SPEECH_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.85,
|
||||
category: "toxicity",
|
||||
},
|
||||
{
|
||||
name: "harassment",
|
||||
test: (c) => HARASSMENT_RE.test(c),
|
||||
severity: "medium",
|
||||
score: 0.6,
|
||||
category: "toxicity",
|
||||
},
|
||||
{
|
||||
name: "phishing",
|
||||
test: (c) => PHISHING_RE.test(c),
|
||||
severity: "high",
|
||||
score: 0.85,
|
||||
category: "harm",
|
||||
},
|
||||
// ── Spam / low quality ────────────────────────────────────────────
|
||||
{
|
||||
name: "mass_everyone_mention",
|
||||
test: (_c, mentions) => mentions >= 3,
|
||||
severity: "medium",
|
||||
score: 0.65,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "excessive_caps",
|
||||
test: (c) => {
|
||||
const caps = (c.match(EXCESSIVE_CAPS_RE) || []).join("");
|
||||
return caps.length > 0 && caps.length / Math.max(c.length, 1) > 0.5;
|
||||
},
|
||||
severity: "low",
|
||||
score: 0.3,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "repeated_characters",
|
||||
test: (c) => REPEATED_CHAR_RE.test(c),
|
||||
severity: "low",
|
||||
score: 0.25,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "repeated_words",
|
||||
test: (c) => REPEATED_WORD_RE.test(c),
|
||||
severity: "low",
|
||||
score: 0.25,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "zalgo_text",
|
||||
test: (c) => ZALGO_RE.test(c) || ZERO_WIDTH_RE.test(c),
|
||||
severity: "medium",
|
||||
score: 0.6,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "excessive_emojis",
|
||||
test: (c) => {
|
||||
const emojiCount = (c.match(EXCESSIVE_EMOJI_RE) || []).length;
|
||||
const textLen = c.replace(EXCESSIVE_EMOJI_RE, "").trim().length;
|
||||
return emojiCount >= 5 && textLen < emojiCount;
|
||||
},
|
||||
severity: "low",
|
||||
score: 0.2,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "base64_gibberish",
|
||||
test: (c) => c.length >= 20 && BASE64_RE.test(c.trim()),
|
||||
severity: "low",
|
||||
score: 0.2,
|
||||
category: "spam",
|
||||
},
|
||||
// ── Medium severity ───────────────────────────────────────────────
|
||||
{
|
||||
name: "personal_info",
|
||||
test: (c) => PERSONAL_INFO_RE.test(c),
|
||||
severity: "medium",
|
||||
score: 0.6,
|
||||
category: "safety",
|
||||
},
|
||||
{
|
||||
name: "discord_invite",
|
||||
test: (c) => INVITE_RE.test(c),
|
||||
severity: "low",
|
||||
score: 0.2,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "url_only",
|
||||
test: (c) => {
|
||||
const urls = c.match(URL_RE);
|
||||
if (!urls) return false;
|
||||
const textWithoutUrls = c.replace(URL_RE, "").trim();
|
||||
return urls.length >= 3 && textWithoutUrls.length === 0;
|
||||
},
|
||||
severity: "low",
|
||||
score: 0.25,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "phone_number",
|
||||
test: (c) => PHONE_RE.test(c),
|
||||
severity: "medium",
|
||||
score: 0.5,
|
||||
category: "safety",
|
||||
},
|
||||
{
|
||||
name: "email_address",
|
||||
test: (c) => EMAIL_RE.test(c),
|
||||
severity: "low",
|
||||
score: 0.3,
|
||||
category: "safety",
|
||||
},
|
||||
{
|
||||
name: "crypto_address",
|
||||
test: (c) => CRYPTO_RE.test(c),
|
||||
severity: "medium",
|
||||
score: 0.5,
|
||||
category: "spam",
|
||||
},
|
||||
{
|
||||
name: "ip_address_sharing",
|
||||
test: (c) => IP_RE.test(c),
|
||||
severity: "low",
|
||||
score: 0.3,
|
||||
category: "safety",
|
||||
},
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pattern matcher — count mentions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function countMentions(content: string): number {
|
||||
let count = 0;
|
||||
const everyoneMatches = content.match(EVERYONE_MENTION);
|
||||
if (everyoneMatches) count += everyoneMatches.length;
|
||||
const hereMatches = content.match(HERE_MENTION);
|
||||
if (hereMatches) count += hereMatches.length;
|
||||
const roleMatches = content.match(ROLE_MENTION);
|
||||
if (roleMatches) count += roleMatches.length;
|
||||
return count;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main classifier
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Runs Layer 1 heuristic classification on a message.
|
||||
* Returns a `Layer1Result` with matched flags and a decision on
|
||||
* whether to cascade to Layer 2 (LLM).
|
||||
*/
|
||||
export function classifyMessage(message: MessageRecord): Layer1Result {
|
||||
const content = message.edited_content ?? message.content;
|
||||
if (!content || content.trim().length === 0) {
|
||||
return {
|
||||
flags: [],
|
||||
severity: "none",
|
||||
toxicityScore: 0,
|
||||
harmScore: 0,
|
||||
cascadeToLayer2: true, // empty content still needs metadata check
|
||||
confidence: 0,
|
||||
explanation: "No text content to classify",
|
||||
};
|
||||
}
|
||||
|
||||
const mentions = countMentions(content);
|
||||
const matchedFlags: string[] = [];
|
||||
const severityWeights: Record<string, number> = {
|
||||
low: 1,
|
||||
medium: 2,
|
||||
high: 3,
|
||||
};
|
||||
|
||||
let maxSeverityWeight = 0;
|
||||
let totalToxicityScore = 0;
|
||||
let totalHarmScore = 0;
|
||||
let totalSafetyScore = 0;
|
||||
let totalSpamScore = 0;
|
||||
const matchedPatternDetails: string[] = [];
|
||||
|
||||
for (const pattern of PATTERNS) {
|
||||
if (pattern.test(content, mentions)) {
|
||||
matchedFlags.push(pattern.name);
|
||||
matchedPatternDetails.push(pattern.name);
|
||||
|
||||
const weight = severityWeights[pattern.severity] || 1;
|
||||
maxSeverityWeight = Math.max(maxSeverityWeight, weight);
|
||||
|
||||
switch (pattern.category) {
|
||||
case "toxicity":
|
||||
totalToxicityScore += pattern.score;
|
||||
break;
|
||||
case "harm":
|
||||
totalHarmScore += pattern.score;
|
||||
break;
|
||||
case "safety":
|
||||
totalSafetyScore += pattern.score;
|
||||
break;
|
||||
case "spam":
|
||||
totalSpamScore += pattern.score;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Determine final severity ───────────────────────────────────────
|
||||
|
||||
let finalSeverity: "none" | "low" | "medium" | "high" = "none";
|
||||
if (maxSeverityWeight >= 3) finalSeverity = "high";
|
||||
else if (maxSeverityWeight >= 2) finalSeverity = "medium";
|
||||
else if (maxSeverityWeight >= 1) finalSeverity = "low";
|
||||
|
||||
// ── Determine if we should cascade ─────────────────────────────────
|
||||
// Cascade to Layer 2 whenever:
|
||||
// 1. No high-severity match was found, OR
|
||||
// 2. Only spam/low-quality patterns matched (need LLM for nuance)
|
||||
// Do NOT cascade when a clear high-severity harm/safety/toxicity match
|
||||
// was found — the heuristic is sufficient.
|
||||
|
||||
const hasHighSeverityPattern = matchedFlags.some((f) => {
|
||||
const p = PATTERNS.find((p) => p.name === f);
|
||||
return p && p.severity === "high";
|
||||
});
|
||||
const hasOnlyLowSeveritySpam = matchedFlags.every((f) => {
|
||||
const p = PATTERNS.find((p) => p.name === f);
|
||||
return p && p.category === "spam" && p.severity !== "high";
|
||||
});
|
||||
|
||||
// Cascade if no matches, only spam, or low/medium severity toxicity/safety
|
||||
const cascadeToLayer2 =
|
||||
matchedFlags.length === 0 ||
|
||||
hasOnlyLowSeveritySpam ||
|
||||
(finalSeverity !== "high" && hasHighSeverityPattern === false);
|
||||
|
||||
// ── Compute final scores (clamped 0-1) ─────────────────────────────
|
||||
|
||||
const toxicityScore = Math.min(totalToxicityScore, 1);
|
||||
const harmScore = Math.min(totalHarmScore, 1);
|
||||
|
||||
// ── Confidence ─────────────────────────────────────────────────────
|
||||
|
||||
const confidence = cascadeToLayer2
|
||||
? 0.4 + 0.1 * matchedFlags.length // low confidence when punting to LLM
|
||||
: 0.6 + 0.4 * (1 - matchedFlags.length / PATTERNS.length);
|
||||
|
||||
const explanation =
|
||||
matchedFlags.length > 0
|
||||
? `Layer 1 matched: ${matchedPatternDetails.join(", ")}`
|
||||
: "No heuristic patterns matched";
|
||||
|
||||
return {
|
||||
flags: matchedFlags,
|
||||
severity: finalSeverity,
|
||||
toxicityScore,
|
||||
harmScore,
|
||||
cascadeToLayer2,
|
||||
confidence: Math.min(confidence, 0.99),
|
||||
explanation,
|
||||
};
|
||||
}
|
||||
@@ -2,3 +2,8 @@ export { startPendingAIAnalysisWorker } from "./aiAnalyzer.js";
|
||||
export { runModerationAnalysis } from "./moderationOrchestrator.js";
|
||||
export { buildSystemPrompt } from "./moderationPrompt.js";
|
||||
export { runSimpleTextFallback } from "./simpleFallback.js";
|
||||
|
||||
// ── New two-pass pipeline exports ──────────────────────────────────────────
|
||||
export { classifyMessage } from "./fastClassifier.js";
|
||||
export type { Layer1Result } from "./fastClassifier.js";
|
||||
export type { AnalysisInput, AnalysisResult, WorkerConfig, MessageBatch } from "./ai-analysis-worker.js";
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
useGuilds,
|
||||
useImages,
|
||||
useLoadMore,
|
||||
useMessageDetail,
|
||||
@@ -56,8 +55,16 @@ export default function MessagesPage() {
|
||||
|
||||
const ws = useWebSocket();
|
||||
const { data: channels = [] } = useTextChannels(guildId);
|
||||
const { data: messages, isLoading, error, refetch } = useMessages(guildId, selectedChannel || undefined);
|
||||
const { data: cursorData } = useMessagesHasMore(guildId, selectedChannel || undefined);
|
||||
const {
|
||||
data: messages,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useMessages(guildId, selectedChannel || undefined);
|
||||
const { data: cursorData } = useMessagesHasMore(
|
||||
guildId,
|
||||
selectedChannel || undefined,
|
||||
);
|
||||
const loadMoreMut = useLoadMore();
|
||||
const { data: images } = useImages(guildId);
|
||||
const { data: reviews } = useReview(selectedChannel || undefined);
|
||||
@@ -132,8 +139,10 @@ export default function MessagesPage() {
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="">All channels</SelectItem>
|
||||
{channels.map((ch: any) => (
|
||||
<SelectItem key={ch.id} value={ch.id}># {ch.name}</SelectItem>
|
||||
{channels.map((ch) => (
|
||||
<SelectItem key={ch.id} value={ch.id}>
|
||||
# {ch.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
@@ -10,8 +10,6 @@ import type { VoiceRecording } from "@/lib/types";
|
||||
|
||||
type RecordingsTab = "library" | "stats";
|
||||
|
||||
type RecordingsTab = "library" | "stats";
|
||||
|
||||
export default function RecordingsPage() {
|
||||
const { data: recordings, isLoading, error, refetch } = useRecordings();
|
||||
const [playingId, setPlayingId] = useState<string | null>(null);
|
||||
|
||||
@@ -64,8 +64,8 @@ export function SearchPanel() {
|
||||
</p>
|
||||
{results.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No messages found"
|
||||
description="Try a different search query."
|
||||
icon={Search}
|
||||
title="No messages found matching your query."
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeft, Clock, Hash, Sparkles } from "lucide-react";
|
||||
|
||||
import { DetailStat, ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useChannelDetail } from "@/hooks";
|
||||
|
||||
export function ChannelDetailSection({
|
||||
channelId,
|
||||
onBack,
|
||||
}: {
|
||||
channelId: string;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const { data: channel, isLoading } = useChannelDetail(channelId);
|
||||
if (isLoading) return <LoadingSkeleton count={1} height="h-64" />;
|
||||
if (!channel) return <ErrorState message="Channel not found." />;
|
||||
|
||||
return (
|
||||
<div className="space-y-5 animate-fade-in-up">
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="size-4 mr-1" /> Back
|
||||
</Button>
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-5">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold flex items-center gap-2">
|
||||
<Hash className="size-5 text-muted-foreground" />
|
||||
{channel.channel_name ?? channel.channel_id.slice(0, 8)}
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{channel.channel_id}
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<DetailStat label="Messages" value={channel.total_messages} />
|
||||
<DetailStat
|
||||
label="Flagged"
|
||||
value={channel.flagged_count}
|
||||
variant="danger"
|
||||
/>
|
||||
<DetailStat
|
||||
label="Clean"
|
||||
value={channel.clean_count}
|
||||
variant="success"
|
||||
/>
|
||||
</div>
|
||||
{channel.culture_summary && (
|
||||
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
|
||||
Channel Culture
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed italic">
|
||||
“{channel.culture_summary}”
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{channel.recent_messages.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold flex items-center gap-2">
|
||||
<Clock className="size-4 text-muted-foreground" /> Recent
|
||||
Messages
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
{channel.recent_messages.slice(0, 5).map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm font-medium">
|
||||
{msg.username}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm">{msg.content}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronRight, Hash, Search } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { EmptyState, LoadingSkeleton } from "@/components/shared";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useChannels } from "@/hooks";
|
||||
|
||||
export function ChannelsSection({
|
||||
guildId,
|
||||
onSelect,
|
||||
}: {
|
||||
guildId: string;
|
||||
onSelect: (id: string) => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const {
|
||||
data: channels,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useChannels(guildId, search || undefined);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 animate-fade-in-up">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search channels…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<LoadingSkeleton count={6} height="h-20" />
|
||||
) : !channels || channels.length === 0 ? (
|
||||
<EmptyState icon={Hash} title="No channels found." />
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{channels.map((ch) => (
|
||||
<Card
|
||||
key={ch.channel_id}
|
||||
className="cursor-pointer hover:bg-accent/5 transition-colors"
|
||||
onClick={() => onSelect(ch.channel_id)}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Hash className="size-3.5 text-muted-foreground shrink-0" />
|
||||
<p className="text-sm font-medium truncate">
|
||||
{ch.channel_name ?? ch.channel_id.slice(0, 8)}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{ch.total_messages} messages
|
||||
{ch.flagged_count > 0
|
||||
? ` · ${ch.flagged_count} flagged`
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="size-4 text-muted-foreground shrink-0 ml-2" />
|
||||
</div>
|
||||
{ch.culture_summary && (
|
||||
<p className="text-xs text-muted-foreground/70 mt-2 italic line-clamp-2 border-t border-border/50 pt-2">
|
||||
“{ch.culture_summary}”
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { ChannelDetailSection } from "./channel-detail-section";
|
||||
export { ChannelsSection } from "./channels-section";
|
||||
export { StatsSection } from "./stats-section";
|
||||
export { UserDetailSection } from "./user-detail-section";
|
||||
export { UsersSection } from "./users-section";
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AlertCircle,
|
||||
Clock,
|
||||
Hash,
|
||||
Shield,
|
||||
Sparkles,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
|
||||
import { ErrorState, LoadingSkeleton, StatCard } from "@/components/shared";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { useStats } from "@/hooks";
|
||||
import { formatNumber } from "@/lib/format";
|
||||
|
||||
export function StatsSection() {
|
||||
const { data: stats, isLoading, error, refetch } = useStats();
|
||||
if (error) return <ErrorState message={error.message} onRetry={refetch} />;
|
||||
if (isLoading || !stats)
|
||||
return (
|
||||
<div className="space-y-5 animate-fade-in-up">
|
||||
<LoadingSkeleton count={8} height="h-28" columns={4} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-5 animate-fade-in-up">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<StatCard
|
||||
label="Total Messages"
|
||||
value={stats.total_messages}
|
||||
icon={Hash}
|
||||
/>
|
||||
<StatCard label="Today" value={stats.today_messages} icon={Clock} />
|
||||
<StatCard label="Users" value={stats.total_users} icon={Users} />
|
||||
<StatCard
|
||||
label="Active 24h"
|
||||
value={stats.active_users_24h}
|
||||
icon={Sparkles}
|
||||
/>
|
||||
<StatCard
|
||||
label="Flagged"
|
||||
value={stats.total_flagged}
|
||||
icon={AlertCircle}
|
||||
variant="danger"
|
||||
/>
|
||||
<StatCard
|
||||
label="Clean"
|
||||
value={stats.total_clean}
|
||||
icon={Shield}
|
||||
variant="success"
|
||||
/>
|
||||
<StatCard
|
||||
label="Voice Recordings"
|
||||
value={stats.total_voice_recordings}
|
||||
icon={Hash}
|
||||
/>
|
||||
<StatCard
|
||||
label="AI Profiles"
|
||||
value={stats.total_profiles}
|
||||
icon={Sparkles}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
|
||||
<Hash className="size-4 text-muted-foreground" /> Top Channels
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{stats.top_channels.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-6 text-center">
|
||||
No channel data yet.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stats.top_channels.map((ch) => {
|
||||
const max = stats.top_channels[0].message_count;
|
||||
const pct = max > 0 ? (ch.message_count / max) * 100 : 0;
|
||||
return (
|
||||
<div key={ch.channel_id} className="space-y-1">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="truncate font-medium">
|
||||
#{ch.channel_name ?? ch.channel_id.slice(0, 8)}
|
||||
</span>
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
{formatNumber(ch.message_count)}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={pct} className="h-1.5" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
|
||||
<Shield className="size-4 text-muted-foreground" /> Moderation
|
||||
Queue
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{[
|
||||
{
|
||||
label: "Pending",
|
||||
value: stats.moderation_overview.pending,
|
||||
cls: "bg-muted/50",
|
||||
},
|
||||
{
|
||||
label: "Processing",
|
||||
value: stats.moderation_overview.processing,
|
||||
cls: "bg-yellow-500/10 text-yellow-500",
|
||||
},
|
||||
{
|
||||
label: "Errors",
|
||||
value: stats.moderation_overview.error,
|
||||
cls: "bg-destructive/10 text-destructive",
|
||||
},
|
||||
].map(({ label, value, cls }) => (
|
||||
<div
|
||||
key={label}
|
||||
className={`rounded-lg p-3 text-center space-y-1.5 ${cls}`}
|
||||
>
|
||||
<div
|
||||
className={`text-2xl font-bold tabular-nums ${cls.includes("yellow") ? "text-yellow-500" : cls.includes("destructive") ? "text-destructive" : ""}`}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">{label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeft, Clock, Sparkles } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
|
||||
import { DetailStat, ErrorState, LoadingSkeleton } from "@/components/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useUserDetail } from "@/hooks";
|
||||
|
||||
export function UserDetailSection({
|
||||
userId,
|
||||
onBack,
|
||||
}: {
|
||||
userId: string;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const { data: user, isLoading } = useUserDetail(userId);
|
||||
if (isLoading) return <LoadingSkeleton count={1} height="h-64" />;
|
||||
if (!user) return <ErrorState message="User not found." />;
|
||||
|
||||
return (
|
||||
<div className="space-y-5 animate-fade-in-up">
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="size-4 mr-1" /> Back
|
||||
</Button>
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-5">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="size-14 shrink-0 rounded-full bg-muted flex items-center justify-center text-xl font-medium overflow-hidden ring-2 ring-border">
|
||||
{user.avatar_url ? (
|
||||
<Image
|
||||
src={user.avatar_url}
|
||||
alt=""
|
||||
width={56}
|
||||
height={56}
|
||||
className="size-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
(user.username ?? "?").charAt(0).toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-lg font-semibold">
|
||||
{user.username ?? "Unknown"}
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{user.user_id}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<DetailStat label="Messages" value={user.total_messages} />
|
||||
<DetailStat
|
||||
label="Flagged"
|
||||
value={user.flagged_count}
|
||||
variant="danger"
|
||||
/>
|
||||
<DetailStat
|
||||
label="Clean Streak"
|
||||
value={user.clean_message_streak ?? 0}
|
||||
/>
|
||||
<DetailStat
|
||||
label="Trust Score"
|
||||
value={user.trust_score ?? 0}
|
||||
suffix="%"
|
||||
/>
|
||||
</div>
|
||||
{user.profile_summary && (
|
||||
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
|
||||
AI Profile
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed">{user.profile_summary}</p>
|
||||
</div>
|
||||
)}
|
||||
{user.recent_messages.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold flex items-center gap-2">
|
||||
<Clock className="size-4 text-muted-foreground" /> Recent
|
||||
Messages
|
||||
</h3>
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto">
|
||||
{user.recent_messages.slice(0, 5).map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
|
||||
>
|
||||
<p className="text-xs text-muted-foreground mb-1 flex items-center gap-2">
|
||||
<Clock className="size-3" />
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</p>
|
||||
<p className="text-sm">{msg.content}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronRight, Search, Users } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { useState } from "react";
|
||||
|
||||
import { EmptyState, LoadingSkeleton } from "@/components/shared";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useUsers } from "@/hooks";
|
||||
|
||||
export function UsersSection({ onSelect }: { onSelect: (id: string) => void }) {
|
||||
const [search, setSearch] = useState("");
|
||||
const { data: users, isLoading } = useUsers(search || undefined);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 animate-fade-in-up">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search users…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<LoadingSkeleton count={6} height="h-20" columns={2} />
|
||||
) : !users || users.length === 0 ? (
|
||||
<EmptyState icon={Users} title="No users found." />
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{users.map((u) => (
|
||||
<Card
|
||||
key={u.user_id}
|
||||
className="cursor-pointer hover:bg-accent/5 transition-colors"
|
||||
onClick={() => onSelect(u.user_id)}
|
||||
>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden ring-1 ring-border">
|
||||
{u.avatar_url ? (
|
||||
<Image
|
||||
src={u.avatar_url}
|
||||
alt=""
|
||||
width={40}
|
||||
height={40}
|
||||
className="size-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
(u.username ?? "?").charAt(0).toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{u.username ?? "Unknown"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground flex items-center gap-2">
|
||||
<span>{u.total_messages} messages</span>
|
||||
{u.flagged_count > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="text-[10px] px-1.5 py-0 h-4"
|
||||
>
|
||||
{u.flagged_count} flagged
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="size-4 text-muted-foreground shrink-0" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { mobileNavItems, isActivePath } from "@/lib/navigation";
|
||||
|
||||
import { isActivePath, mobileNavItems } from "@/lib/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function MobileNav() {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { ImageIcon } from "lucide-react";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { extractFirstImage } from "./message-card";
|
||||
|
||||
export function ImagesGrid({
|
||||
images,
|
||||
onSelect,
|
||||
}: {
|
||||
images: MessageRecord[];
|
||||
onSelect: (id: string) => void;
|
||||
}) {
|
||||
if (!images || images.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 text-center">
|
||||
<ImageIcon
|
||||
className="size-10 text-muted-foreground/40 mb-3"
|
||||
aria-label="No images"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">No images yet.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 animate-fade-in-up">
|
||||
{images.map((msg) => {
|
||||
const imgUrl = extractFirstImage(msg.metadata);
|
||||
return (
|
||||
<Card
|
||||
key={msg.id}
|
||||
className="group relative overflow-hidden cursor-pointer"
|
||||
onClick={() => onSelect(msg.id)}
|
||||
>
|
||||
<div className="aspect-square relative bg-muted">
|
||||
{imgUrl ? (
|
||||
<img
|
||||
src={imgUrl}
|
||||
alt={msg.content || "Image"}
|
||||
className="absolute inset-0 size-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center size-full text-muted-foreground text-xs">
|
||||
No image
|
||||
</div>
|
||||
)}
|
||||
{msg.content && (
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-end p-3">
|
||||
<p className="text-xs text-white/90 line-clamp-2">
|
||||
{msg.username}: {msg.content}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,87 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Hash, RefreshCw } from "lucide-react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { safeParseJsonArray } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AiStatusBadge } from "./ai-status-badge";
|
||||
|
||||
interface MessageCardProps {
|
||||
export function MessageCard({
|
||||
message: msg,
|
||||
onClick,
|
||||
onReanalyze,
|
||||
}: {
|
||||
message: MessageRecord;
|
||||
selected?: boolean;
|
||||
onClick?: (id: string) => void;
|
||||
}
|
||||
|
||||
const severityDot: Record<string, string> = {
|
||||
clean: "bg-emerald-500 shadow-[0_0_6px] shadow-emerald-500/60",
|
||||
pending: "bg-text-secondary/30",
|
||||
warn: "bg-accent-amber shadow-[0_0_6px] shadow-accent-amber/60",
|
||||
flagged: "bg-accent-purple shadow-[0_0_6px] shadow-accent-purple/60",
|
||||
error: "bg-destructive/60",
|
||||
};
|
||||
|
||||
function formatRelativeTime(timestamp: number): string {
|
||||
const diff = Date.now() - timestamp;
|
||||
const mins = Math.floor(diff / 60000);
|
||||
if (mins < 1) return "just now";
|
||||
if (mins < 60) return `${mins}m`;
|
||||
const hours = Math.floor(mins / 60);
|
||||
if (hours < 24) return `${hours}h`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}d`;
|
||||
}
|
||||
|
||||
export function MessageCard({ message, selected, onClick }: MessageCardProps) {
|
||||
const status = message.ai_status || "pending";
|
||||
onClick: (id: string) => void;
|
||||
onReanalyze: (id: string) => void;
|
||||
}) {
|
||||
const severity = (
|
||||
{
|
||||
low: "border-l-cyan-500/40",
|
||||
medium: "border-l-amber-500/60",
|
||||
high: "border-l-orange-500/70",
|
||||
critical: "border-l-red-500/80",
|
||||
} as Record<string, string>
|
||||
)[msg.ai_severity ?? ""];
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onClick?.(message.id)}
|
||||
<Card
|
||||
className={cn(
|
||||
"w-full text-left px-4 py-3 rounded-[var(--radius-panel)] transition-all duration-150 border",
|
||||
selected
|
||||
? "glass-elevated border-border-glow"
|
||||
: "glass border-glass-border hover:border-border-glow/50 hover:scale-[1.002]",
|
||||
"cursor-pointer transition-all duration-200 hover:shadow-[0_0_16px_oklch(0.62_0.17_215_/_0.08)] hover:border-cyan-500/20",
|
||||
severity && "border-l-2",
|
||||
severity,
|
||||
)}
|
||||
onClick={() => onClick(msg.id)}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Severity dot */}
|
||||
<span className={cn("mt-1.5 size-2 rounded-full shrink-0", severityDot[status] || severityDot.pending)} />
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm font-semibold text-text-primary truncate">{message.username}</span>
|
||||
<span className="text-[10px] font-mono text-text-secondary/50">{message.channel_id?.slice(0, 8)}</span>
|
||||
<span className="ml-auto text-[10px] text-text-secondary/40 shrink-0">
|
||||
{message.created_at ? formatRelativeTime(message.created_at) : ""}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<p className="text-sm text-text-secondary/80 line-clamp-2 leading-relaxed">
|
||||
{message.content || "(no text content)"}
|
||||
</p>
|
||||
|
||||
{/* AI status badge */}
|
||||
{status !== "pending" && (
|
||||
<div className="flex items-center gap-2 mt-1.5">
|
||||
<span className={cn(
|
||||
"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium font-mono",
|
||||
status === "clean" && "bg-emerald-500/10 text-emerald-500",
|
||||
status === "warn" && "bg-accent-amber/10 text-accent-amber",
|
||||
status === "flagged" && "bg-accent-purple/10 text-accent-purple",
|
||||
status === "error" && "bg-destructive/10 text-destructive",
|
||||
)}>
|
||||
{status}
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Avatar className="size-8 shrink-0 mt-0.5">
|
||||
<AvatarImage src={msg.avatar_url ?? undefined} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{msg.username.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-medium">{msg.username}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</span>
|
||||
{message.ai_moderation_flags && message.ai_moderation_flags.length > 0 && (
|
||||
<span className="text-[10px] text-text-secondary/50 font-mono">
|
||||
{message.ai_moderation_flags}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<Hash className="size-3 inline mr-0.5" />
|
||||
{msg.channel_id.slice(0, 8)}
|
||||
</span>
|
||||
<AiStatusBadge status={msg.ai_status} />
|
||||
{msg.ai_severity && msg.ai_severity !== "none" && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="text-[10px] px-1.5 py-0 h-4"
|
||||
>
|
||||
{msg.ai_severity}
|
||||
</Badge>
|
||||
)}
|
||||
{msg.type === "deleted" && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="text-[10px] px-1.5 py-0 h-4"
|
||||
>
|
||||
deleted
|
||||
</Badge>
|
||||
)}
|
||||
{msg.type === "edited" && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 h-4"
|
||||
>
|
||||
edited
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm leading-relaxed",
|
||||
msg.type === "deleted" &&
|
||||
"italic text-muted-foreground line-through",
|
||||
)}
|
||||
>
|
||||
{msg.content}
|
||||
</p>
|
||||
{(() => {
|
||||
const u = extractFirstImage(msg.metadata);
|
||||
if (!u) return null;
|
||||
return (
|
||||
<img
|
||||
src={u}
|
||||
alt=""
|
||||
className="mt-2 max-h-48 rounded-lg border border-border/50 object-cover"
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
{msg.ai_moderation_flags && msg.ai_moderation_flags !== "[]" && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{safeParseJsonArray(msg.ai_moderation_flags).map((f) => (
|
||||
<Badge
|
||||
key={f}
|
||||
variant="destructive"
|
||||
className="text-[10px] px-1.5 py-0 h-4"
|
||||
>
|
||||
{f}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{msg.ai_analysis && (
|
||||
<p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
|
||||
{msg.ai_analysis}
|
||||
</p>
|
||||
)}
|
||||
{msg.ai_confidence != null && (
|
||||
<div className="flex items-center gap-2 max-w-40">
|
||||
<Progress value={msg.ai_confidence * 100} className="h-1.5" />
|
||||
<span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
|
||||
{(msg.ai_confidence * 100).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onReanalyze(msg.id);
|
||||
}}
|
||||
>
|
||||
<RefreshCw className="size-3 mr-1" /> Reanalyze
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function extractFirstImage(
|
||||
metadata: string | null | undefined,
|
||||
): string | null {
|
||||
if (!metadata) return null;
|
||||
try {
|
||||
const m = JSON.parse(metadata);
|
||||
const atts: Array<{ url: string; contentType?: string }> =
|
||||
m.attachments ?? [];
|
||||
return atts.find((a) => a.contentType?.startsWith("image/"))?.url ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLink, Sparkles } from "lucide-react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { formatBytes, safeParseJsonArray } from "@/lib/format";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function MiniStat({
|
||||
label,
|
||||
value,
|
||||
destructive,
|
||||
capitalize,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
destructive?: boolean;
|
||||
capitalize?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-3">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm font-medium mt-0.5",
|
||||
capitalize && "capitalize",
|
||||
destructive && "text-destructive",
|
||||
)}
|
||||
>
|
||||
{value}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageDetailView({
|
||||
message,
|
||||
attachments,
|
||||
}: {
|
||||
message: MessageRecord;
|
||||
attachments: {
|
||||
id: string;
|
||||
filename: string;
|
||||
type: string;
|
||||
size: number;
|
||||
uploaded_url?: string | null;
|
||||
discord_url?: string | null;
|
||||
}[];
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-start gap-3">
|
||||
<Avatar className="size-10">
|
||||
<AvatarImage src={message.avatar_url ?? undefined} />
|
||||
<AvatarFallback>
|
||||
{message.username.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-medium">{message.username}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(message.created_at).toLocaleString()}
|
||||
</span>
|
||||
{message.type === "deleted" && (
|
||||
<Badge variant="destructive" className="text-[10px]">
|
||||
deleted
|
||||
</Badge>
|
||||
)}
|
||||
{message.type === "edited" && (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
edited
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm mt-2 whitespace-pre-wrap break-words leading-relaxed">
|
||||
{message.content}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{message.ai_analysis && (
|
||||
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
AI Analysis
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed">{message.ai_analysis}</p>
|
||||
</div>
|
||||
)}
|
||||
{message.ai_moderation_flags && message.ai_moderation_flags !== "[]" && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
Moderation Flags
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{safeParseJsonArray(message.ai_moderation_flags).map((f) => (
|
||||
<Badge key={f} variant="destructive" className="text-[11px]">
|
||||
{f}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{message.ai_status && (
|
||||
<MiniStat label="Status" value={message.ai_status} capitalize />
|
||||
)}
|
||||
{message.ai_severity && message.ai_severity !== "none" && (
|
||||
<MiniStat
|
||||
label="Severity"
|
||||
value={message.ai_severity}
|
||||
destructive
|
||||
capitalize
|
||||
/>
|
||||
)}
|
||||
{message.ai_confidence != null && (
|
||||
<MiniStat
|
||||
label="Confidence"
|
||||
value={`${(message.ai_confidence * 100).toFixed(0)}%`}
|
||||
/>
|
||||
)}
|
||||
{message.ai_recommended_action &&
|
||||
message.ai_recommended_action !== "none" && (
|
||||
<MiniStat
|
||||
label="Action"
|
||||
value={message.ai_recommended_action}
|
||||
capitalize
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{attachments.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
Attachments ({attachments.length})
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{attachments.map((a) => (
|
||||
<a
|
||||
key={a.id}
|
||||
href={a.uploaded_url ?? a.discord_url ?? "#"}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-2 rounded-lg border border-border/50 p-2 hover:bg-muted transition-colors group"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium truncate">{a.filename}</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
{a.type} · {formatBytes(a.size)}
|
||||
</p>
|
||||
</div>
|
||||
<ExternalLink className="size-3 shrink-0 text-muted-foreground/50 group-hover:text-muted-foreground transition-colors" />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { Flag } from "lucide-react";
|
||||
import type { MessageRecord } from "@/lib/types";
|
||||
import { MessageCard } from "./message-card";
|
||||
|
||||
export function ReviewList({
|
||||
reviews,
|
||||
onSelect,
|
||||
onReanalyze,
|
||||
}: {
|
||||
reviews: MessageRecord[];
|
||||
onSelect: (id: string) => void;
|
||||
onReanalyze: (id: string) => void;
|
||||
}) {
|
||||
if (!reviews || reviews.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 text-center">
|
||||
<Flag className="size-10 text-muted-foreground/40 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No flagged messages to review.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 animate-fade-in-up">
|
||||
{reviews.map((msg) => (
|
||||
<MessageCard
|
||||
key={msg.id}
|
||||
message={msg}
|
||||
onClick={onSelect}
|
||||
onReanalyze={onReanalyze}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { Download, Headphones, Trash2 } from "lucide-react";
|
||||
|
||||
import { EmptyState, LoadingSkeleton } from "@/components/shared";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
useDeleteRecording,
|
||||
useRecordings,
|
||||
useRecordingsWsSync,
|
||||
} from "@/hooks";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import type { WsHook } from "@/lib/ws-hook";
|
||||
|
||||
interface RecordingListProps {
|
||||
ws: WsHook;
|
||||
}
|
||||
|
||||
export function RecordingList({ ws }: RecordingListProps) {
|
||||
const { data: recordings, isLoading } = useRecordings();
|
||||
const deleteMut = useDeleteRecording();
|
||||
|
||||
useRecordingsWsSync(ws);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
|
||||
<Headphones className="size-4 text-primary" />
|
||||
Voice Recordings
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<LoadingSkeleton count={5} height="h-16" />
|
||||
) : !recordings || recordings.length === 0 ? (
|
||||
<EmptyState icon={Headphones} title="No recordings yet." />
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{recordings.map((rec) => (
|
||||
<div
|
||||
key={rec.id}
|
||||
className="flex items-center gap-3 rounded-lg border border-border/50 p-3 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<Avatar className="size-8">
|
||||
<AvatarImage src={rec.avatar_url ?? undefined} />
|
||||
<AvatarFallback>
|
||||
{(rec.username ?? "?").charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{rec.username}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{rec.channel_name ?? rec.channel_id ?? "Unknown channel"} —{" "}
|
||||
{new Date(rec.created_at).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] font-mono shrink-0"
|
||||
>
|
||||
{formatBytes(rec.size_bytes)}
|
||||
</Badge>
|
||||
{rec.download_url && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
if (rec.download_url)
|
||||
window.open(rec.download_url, "_blank");
|
||||
}}
|
||||
>
|
||||
<Download className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => deleteMut.mutate(rec.id)}
|
||||
className="hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { formatNumber } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface DetailStatProps {
|
||||
label: string;
|
||||
value: number;
|
||||
variant?: "default" | "danger" | "success";
|
||||
suffix?: string;
|
||||
}
|
||||
|
||||
const valueColor = {
|
||||
default: "",
|
||||
danger: "text-red-400",
|
||||
success: "text-emerald-400",
|
||||
};
|
||||
|
||||
/**
|
||||
* Small stat label used inside detail views.
|
||||
*/
|
||||
export function DetailStat({
|
||||
label,
|
||||
value,
|
||||
variant = "default",
|
||||
suffix,
|
||||
}: DetailStatProps) {
|
||||
return (
|
||||
<Card className="bg-gradient-to-br from-cyan-500/5 to-transparent border-cyan-500/10">
|
||||
<CardContent className="p-3">
|
||||
<p className="text-xs text-muted-foreground/70 tracking-wide">
|
||||
{label}
|
||||
</p>
|
||||
<p
|
||||
className={cn("text-lg font-bold tabular-nums", valueColor[variant])}
|
||||
>
|
||||
{formatNumber(value)}
|
||||
{suffix}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
export { DetailStat } from "./detail-stat";
|
||||
export { EmptyState } from "./empty-state";
|
||||
export { ErrorBoundary } from "./error-boundary";
|
||||
export { ErrorState } from "./error-state";
|
||||
export { LoadingSkeleton } from "./loading-skeleton";
|
||||
export { StatCard } from "./stat-card";
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { formatNumber } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
value: number;
|
||||
icon: LucideIcon;
|
||||
variant?: "default" | "danger" | "success" | "warning";
|
||||
}
|
||||
|
||||
const variantStyles = {
|
||||
default: "from-cyan-500/10 to-teal-500/5 border-cyan-500/20",
|
||||
danger: "from-red-500/10 to-rose-500/5 border-red-500/20",
|
||||
success: "from-emerald-500/10 to-green-500/5 border-emerald-500/20",
|
||||
warning: "from-amber-500/10 to-yellow-500/5 border-amber-500/20",
|
||||
};
|
||||
|
||||
const iconBg = {
|
||||
default: "bg-cyan-500/15 text-cyan-400",
|
||||
danger: "bg-red-500/15 text-red-400",
|
||||
success: "bg-emerald-500/15 text-emerald-400",
|
||||
warning: "bg-amber-500/15 text-amber-400",
|
||||
};
|
||||
|
||||
const valueColor = {
|
||||
default: "",
|
||||
danger: "text-red-400",
|
||||
success: "text-emerald-400",
|
||||
warning: "text-amber-400",
|
||||
};
|
||||
|
||||
/**
|
||||
* Metric card used across dashboard and landing pages.
|
||||
*/
|
||||
export function StatCard({
|
||||
label,
|
||||
value,
|
||||
icon: Icon,
|
||||
variant = "default",
|
||||
}: StatCardProps) {
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
"border bg-gradient-to-br backdrop-blur-sm",
|
||||
variantStyles[variant],
|
||||
)}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs text-muted-foreground/80 tracking-wide">
|
||||
{label}
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-2xl font-bold tabular-nums tracking-tight",
|
||||
valueColor[variant],
|
||||
)}
|
||||
>
|
||||
{formatNumber(value)}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-9 shrink-0 items-center justify-center rounded-lg",
|
||||
iconBg[variant],
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +1,26 @@
|
||||
import {
|
||||
Headphones,
|
||||
LayoutDashboard,
|
||||
type LucideIcon,
|
||||
MessageSquare,
|
||||
Mic,
|
||||
Headphones,
|
||||
Music,
|
||||
Search,
|
||||
Settings,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
export interface NavItem {
|
||||
href: string;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
}
|
||||
|
||||
export interface NavItemWithMatch extends NavItem {
|
||||
/** The pathname prefix that indicates this item is active */
|
||||
matchPrefix: string;
|
||||
}
|
||||
|
||||
export const navItems: NavItemWithMatch[] = [
|
||||
/**
|
||||
* Primary navigation items shown in the sidebar.
|
||||
*/
|
||||
export const navItems: NavItem[] = [
|
||||
{
|
||||
href: "/dashboard",
|
||||
label: "Dashboard",
|
||||
@@ -36,12 +39,24 @@ export const navItems: NavItemWithMatch[] = [
|
||||
icon: Mic,
|
||||
matchPrefix: "/voice",
|
||||
},
|
||||
{
|
||||
href: "/media",
|
||||
label: "Media",
|
||||
icon: Music,
|
||||
matchPrefix: "/media",
|
||||
},
|
||||
{
|
||||
href: "/recordings",
|
||||
label: "Recordings",
|
||||
icon: Headphones,
|
||||
matchPrefix: "/recordings",
|
||||
},
|
||||
{
|
||||
href: "/analysis",
|
||||
label: "Search",
|
||||
icon: Search,
|
||||
matchPrefix: "/analysis",
|
||||
},
|
||||
{
|
||||
href: "/settings",
|
||||
label: "Settings",
|
||||
@@ -50,14 +65,16 @@ export const navItems: NavItemWithMatch[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export const mobileNavItems: NavItemWithMatch[] = navItems.filter((item) =>
|
||||
["/dashboard", "/messages", "/voice", "/recordings"].includes(item.href),
|
||||
/**
|
||||
* Mobile bottom bar items (subset of primary nav).
|
||||
*/
|
||||
export const mobileNavItems: NavItem[] = navItems.filter((item) =>
|
||||
["/dashboard", "/messages", "/voice", "/media"].includes(item.href),
|
||||
);
|
||||
|
||||
export function isActivePath(
|
||||
pathname: string,
|
||||
matchPrefix: string,
|
||||
): boolean {
|
||||
export type NavItemId = (typeof navItems)[number]["href"];
|
||||
|
||||
export function isActivePath(pathname: string, matchPrefix: string): boolean {
|
||||
if (matchPrefix === "/dashboard") return pathname === "/dashboard";
|
||||
return pathname.startsWith(matchPrefix);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user