feat: surface AI analysis duration across gateway, backend, and FE

Adds per-message AI moderation analysis time (ai_analysis_duration_ms)
so operators can see how long the LLM took to moderate each message.

Gateway:
- messagesTable: new ai_analysis_duration_ms (bigint) column.
- AIAnalysisUpdate + buildAIAnalysisSet: carry analysisDurationMs through
  both single and bulk update paths.
- ai-analysis-worker: measure wall-clock time around runModerationAnalysis
  and attach it to every result in the batch.

Backend:
- Mirror schema column; messageMapper maps ai_analysis_duration_ms;
  moderation-types + MappedMessage expose it.

Frontend:
- message.ts type gains ai_analysis_duration_ms.
- AiBadge (messages view) shows 'status · 1.2s' when duration is present;
  analysis view badge mirrors the same formatting.

DB:
- scripts/add-ai-analysis-duration.sql (idempotent ADD COLUMN IF NOT EXISTS).

No behavior change for moderation logic; null until new gateway build
records values.
This commit is contained in:
asepharyana
2026-08-16 00:11:00 +07:00
parent 2d7c7f2c35
commit 6244e307a3
10 changed files with 64 additions and 5 deletions
@@ -316,11 +316,13 @@ async function processBatch(job: {
// The orchestrator handles text/media split + caching + parallel paths
// internally, so a 20-message batch = 1 text LLM call (+1 media call
// when media is present), not N per-message calls.
const analysisStart = Date.now();
const moderationResult = await runModerationAnalysis({
targets: readyMessages,
contextBlock,
attachments,
});
const analysisDurationMs = Date.now() - analysisStart;
const results = moderationResult.results.map((r) =>
normalizeResult(
@@ -342,6 +344,7 @@ async function processBatch(job: {
confidence: result.confidence,
recommendedAction: result.recommendedAction,
analyzedAt: Date.now(),
analysisDurationMs,
error: result.status === "error" ? result.analysis : null,
},
}));
@@ -26,6 +26,8 @@ export interface AIAnalysisUpdate {
confidence?: number | null;
recommendedAction?: MessageRecord["ai_recommended_action"] | null;
analyzedAt?: number | null;
/** Wall-clock time the AI analysis (LLM call) took, in milliseconds. */
analysisDurationMs?: number | null;
error?: string | null;
}
@@ -42,6 +44,7 @@ function buildAIAnalysisSet(result: AIAnalysisUpdate, now?: number) {
ai_confidence: result.confidence ?? result.score ?? null,
ai_recommended_action: result.recommendedAction ?? null,
ai_analyzed_at: result.analyzedAt ?? now ?? Date.now(),
ai_analysis_duration_ms: result.analysisDurationMs ?? null,
ai_error: result.error ?? null,
};
}
@@ -62,6 +62,9 @@ export const pgMessagesTable = pgTable(
enum: ["none", "monitor", "warn", "review", "delete", "escalate"],
}),
ai_analyzed_at: pgBigint("ai_analyzed_at", { mode: "number" }),
ai_analysis_duration_ms: pgBigint("ai_analysis_duration_ms", {
mode: "number",
}),
ai_error: pgText("ai_error"),
},
(table) => ({