feat: comprehensive UX improvements — messages, analysis, moderation

Fix #1 (CRITICAL): Wire message_analyzed through Redis EventBroadcaster
- DG aiAnalyzer.ts: Add broadcastAnalysisCompleted() helper that publishes
  to both in-memory WS broadcaster AND Redis EventBroadcaster
- DG bootstrap.ts: Pass eventBroadcaster to startPendingAIAnalysisWorker()
- Fixes broken real-time chain so analysis results appear instantly

Fix #2: Collapsible AI Analysis with Rich Formatting
- MessageCard: AI analysis now collapsible with color-coded severity border
  (red/yellow/blue), summary line showing categories + confidence + severity
- Default collapsed for clean, expanded for warn/flagged

Fix #3: Toast Notifications for Flagged Content
- Wrap app in ToastProvider; ModerationAlertListener component listens for
  moderation_alert custom events and shows toast with emoji + details

Fix #4: Discord-style Message Grouping
- MessageFeed: Group consecutive messages from same user within 5 min
- MessageCard: Compact variant hides avatar, reduces padding for non-first

Fix #5: Moderation Action Buttons in UI
- BE: POST /api/messages/:id/moderate endpoint + publishCommand() for Redis
- FE: Delete/Warn buttons on flagged/warned cards with confirmation dialog

Fix #6: Search Results Include Full Data
- BE analysis.service.ts: SELECT all 26 message columns instead of just 11
- Search results now render with full MessageCard including images/analysis

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MythEclipse
2026-06-02 12:17:51 +07:00
co-authored by Claude Opus 4.8
parent 74400376a0
commit c5c667b147
11 changed files with 470 additions and 91 deletions
@@ -1,6 +1,6 @@
import { sql } from "drizzle-orm";
import { getDatabase } from "../../shared/database/index.js";
import { config } from "../../shared/config/index.js";
import { getDatabase } from "../../shared/database/index.js";
import { createChildLogger } from "../../shared/logger/index.js";
const logger = createChildLogger("analysis.service");
@@ -11,6 +11,17 @@ export interface AnalysisSearchQuery {
limit?: number;
}
/** Full message columns for search results — matches MessageRecord from client.ts */
const FULL_COLUMNS = sql.raw(`
id, guild_id, channel_id, thread_id,
user_id, username, avatar_url,
content, edited_content, created_at, edited_at, deleted_at,
type, metadata,
ai_status, ai_moderation_flags, ai_moderation_score,
ai_analysis, ai_categories, ai_severity, ai_confidence,
ai_recommended_action, ai_analyzed_at, ai_error
`);
export class AnalysisService {
async search(query: AnalysisSearchQuery) {
const db = getDatabase();
@@ -25,8 +36,7 @@ export class AnalysisService {
let sqlQuery;
if (channelId && guildId) {
sqlQuery = sql`
SELECT id, guild_id, channel_id, user_id, username, avatar_url,
content, type, created_at, ai_status, ai_severity, ai_confidence
SELECT ${FULL_COLUMNS}
FROM messages
WHERE guild_id = ${guildId}
AND channel_id = ${channelId}
@@ -36,8 +46,7 @@ export class AnalysisService {
`;
} else if (channelId) {
sqlQuery = sql`
SELECT id, guild_id, channel_id, user_id, username, avatar_url,
content, type, created_at, ai_status, ai_severity, ai_confidence
SELECT ${FULL_COLUMNS}
FROM messages
WHERE channel_id = ${channelId}
AND content ILIKE ${searchPattern}
@@ -46,8 +55,7 @@ export class AnalysisService {
`;
} else if (guildId) {
sqlQuery = sql`
SELECT id, guild_id, channel_id, user_id, username, avatar_url,
content, type, created_at, ai_status, ai_severity, ai_confidence
SELECT ${FULL_COLUMNS}
FROM messages
WHERE guild_id = ${guildId}
AND content ILIKE ${searchPattern}
@@ -56,8 +64,7 @@ export class AnalysisService {
`;
} else {
sqlQuery = sql`
SELECT id, guild_id, channel_id, user_id, username, avatar_url,
content, type, created_at, ai_status, ai_severity, ai_confidence
SELECT ${FULL_COLUMNS}
FROM messages
WHERE content ILIKE ${searchPattern}
ORDER BY created_at DESC
@@ -91,5 +91,72 @@ export function createMessagesRouter(): Router {
}),
);
// POST /api/messages/:id/moderate — Trigger moderation action via DG
router.post(
"/messages/:id/moderate",
asyncHandler(async (req: Request, res: Response) => {
const id = req.params.id;
if (!id) {
res.status(400).json({ error: "MISSING_ID" });
return;
}
const { actionType, reason } = (req.body ?? {}) as {
actionType?: string;
reason?: string;
};
const allowedActions = [
"delete_message",
"warn_user",
"kick_user",
"ban_user",
"mute_user",
];
if (!actionType || !allowedActions.includes(actionType)) {
res.status(400).json({
error: "INVALID_ACTION",
message: `actionType must be one of: ${allowedActions.join(", ")}`,
});
return;
}
// Fetch the message to get guild/user context
const pool = getPool();
const { rows } = await pool.query(
`SELECT id, guild_id, channel_id, thread_id, user_id, content
FROM messages WHERE id = $1`,
[id],
);
if (rows.length === 0) {
res.status(404).json({ error: "MESSAGE_NOT_FOUND" });
return;
}
const msg = rows[0] as Record<string, unknown>;
// Publish command to DG via Redis
const { publishCommand } = await import("../../ws/redis-bridge.js");
await publishCommand({
id: crypto.randomUUID(),
type: "moderation:action",
payload: {
messageId: id,
guildId: String(msg.guild_id ?? ""),
channelId: (msg.thread_id as string) || String(msg.channel_id ?? ""),
userId: String(msg.user_id ?? ""),
actionType,
reason: reason ?? "Manual moderation from dashboard",
requestedAt: Date.now(),
},
});
logger.info({ id, actionType, reason }, "Moderation action dispatched");
res.json({ ok: true, actionType, messageId: id });
}),
);
return router;
}
+31 -1
View File
@@ -27,8 +27,9 @@ const SUBSCRIPTIONS: ChannelMapping[] = [
];
let subscriber: Redis | null = null;
let publisher: Redis | null = null;
function createSubscriber(): Redis {
function createRedisInstance(): Redis {
if (config.REDIS_URL) {
return new Redis(config.REDIS_URL, { keyPrefix: "" });
}
@@ -39,6 +40,35 @@ function createSubscriber(): Redis {
});
}
function createSubscriber(): Redis {
return createRedisInstance();
}
function getPublisher(): Redis {
if (!publisher) {
publisher = createRedisInstance();
}
return publisher;
}
/**
* Publish a command to the Discord Gateway via Redis.
* The DG's commandHandler listens on "backend:command" channel.
*/
export async function publishCommand(
payload: Record<string, unknown>,
): Promise<void> {
const pub = getPublisher();
const envelope = {
type: "command",
data: payload,
timestamp: Date.now(),
source: "backend",
};
await pub.publish("backend:command", JSON.stringify(envelope));
logger.debug({ payload }, "Published command to DG");
}
function handleSubscriptionMessage(channel: string, message: string): void {
const mapping = SUBSCRIPTIONS.find((m) => m.channel === channel);
if (!mapping) {