import { useEffect, useState } from "react"; import { AlertTriangle, Flame, FlaskConical, Layers, Loader2, Play, Scissors, ShieldAlert, Sparkles, Wand2, } from "lucide-react"; import { fetchQueryAblationApi, fetchTokenSaliency, runStressTest, runWhatIfDocApi, } from "../../api/client"; import { useShallow } from "zustand/react/shallow"; import { useOstraStore } from "../../store/useOstraStore"; import type { DocForensicProfile, QueryAblationResponse, StressTestResponse, TokenSaliencyResponse, WhatIfDocResponse, } from "../../types/ostra"; export function ForensicDiffPanel() { const { activeRun, searchParams, searchResult, forensicDocA, forensicDocB, forensicDiff, loadingForensic, openForensicDiff, applyFixPatch, executeSearch, } = useOstraStore( useShallow((s) => ({ activeRun: s.activeRun, searchParams: s.searchParams, searchResult: s.searchResult, forensicDocA: s.forensicDocA, forensicDocB: s.forensicDocB, forensicDiff: s.forensicDiff, loadingForensic: s.loadingForensic, openForensicDiff: s.openForensicDiff, applyFixPatch: s.applyFixPatch, executeSearch: s.executeSearch, })) ); const [saliencyByDoc, setSaliencyByDoc] = useState< Record >({}); const [loadingSalDoc, setLoadingSalDoc] = useState(null); const [stressResult, setStressResult] = useState( null ); const [loadingStress, setLoadingStress] = useState(false); const [ablationRes, setAblationRes] = useState( null ); const [loadingAblation, setLoadingAblation] = useState(false); const candidates = searchResult?.waterfall_rows || []; const defaultA = forensicDocA ?? candidates[0]?.doc_id ?? null; const defaultB = forensicDocB ?? searchParams.pinned_doc_id ?? candidates[1]?.doc_id ?? null; const handleLoadDefaultDiff = () => { if (defaultA !== null && defaultB !== null) { void openForensicDiff(defaultA, defaultB); } }; const handleComputeSaliency = async (docId: number) => { if (!activeRun || !searchParams.query.trim()) return; setLoadingSalDoc(docId); try { const res = await fetchTokenSaliency(activeRun.run_id, { query: searchParams.query, doc_id: docId, query_prefix_override: searchParams.query_prefix_override, abtt_d: searchParams.abtt_d, mean_center: searchParams.mean_center, }); setSaliencyByDoc((prev) => ({ ...prev, [docId]: res })); } catch (err) { console.error("Saliency error:", err); } finally { setLoadingSalDoc(null); } }; const handleStressTest = async () => { if (!activeRun || !searchParams.query.trim()) return; setLoadingStress(true); try { const res = await runStressTest(activeRun.run_id, searchParams); setStressResult(res); } catch (err) { console.error("Stress test failed:", err); } finally { setLoadingStress(false); } }; const handleQueryAblation = async (docId: number) => { if (!activeRun || !searchParams.query.trim()) return; setLoadingAblation(true); try { const res = await fetchQueryAblationApi( activeRun.run_id, searchParams, docId ); setAblationRes(res); } catch (err) { console.error("Query ablation failed:", err); } finally { setLoadingAblation(false); } }; return (
{/* Top Pair Selector & 1-Click Stress Test Button */}
Why Did Beat
{defaultB !== null && ( )}
{/* Query-Side Token Ablation Results */} {ablationRes && (
Query Token Impact on Doc #{ablationRes.doc_id} (Leave-One-Out ·{" "} {ablationRes.elapsed_ms.toFixed(0)}ms)

Shows how much each query word actually helped (green) vs. was ignored (slate) vs. hurt (red) Doc #{ablationRes.doc_id}. Click any chip to test removing that word.

{ablationRes.tokens.map((t) => { const cls = t.impact === "critical" ? "bg-emerald-50 border-emerald-700 text-emerald-950" : t.impact === "helpful" ? "bg-sky-50 border-sky-700 text-sky-950" : t.impact === "harmful" ? "bg-red-50 border-red-700 text-red-950" : "bg-[#f1f4f8] border-[#cbd5e1] text-[#475569]"; return ( ); })}
)} {/* 1-Click Query Stress-Test Results */} {stressResult && (
Query Robustness Probe (4 Micro-Mutations)
{stressResult.cases.map((tc) => (
{tc.label} Jaccard@10: {(tc.jaccard_at_10 * 100).toFixed(0)}%
“{tc.mutated_query}”
{tc.warning && (
{tc.warning}
)}
))}
)} {/* Forensic Diff Body */} {!forensicDiff ? (

Select two documents (e.g. Wrong Winner #1 vs. Pinned Expected Doc) and click{" "} Compare to inspect exact score math, per-field dilution, BM25 term contributions, and Dense semantic token saliency.

{defaultA !== null && defaultB !== null && ( )}
) : ( <> {/* Verdict Summary */} {forensicDiff.verdict_bullets.length > 0 && (
Forensic Verdict
{forensicDiff.verdict_bullets.map((b, i) => (
▸ {b}
))}
)} {/* Side-by-Side Doc A vs Doc B Columns */}
void handleComputeSaliency(forensicDiff.doc_a.doc_id) } onApplyPatch={(patch, label) => void applyFixPatch(patch, label)} /> void handleComputeSaliency(forensicDiff.doc_b.doc_id) } onApplyPatch={(patch, label) => void applyFixPatch(patch, label)} />
)}
); } function ForensicDocCard({ role, accent, profile, runId, searchParams, saliency, loadingSaliency, onComputeSaliency, onApplyPatch, }: { role: string; accent: "emerald" | "pink"; profile: DocForensicProfile; runId: string; searchParams: import("../../types/ostra").SearchRequest; saliency?: TokenSaliencyResponse; loadingSaliency: boolean; onComputeSaliency: () => void; onApplyPatch: ( patch: Partial, label: string ) => void; }) { const [highlightMode, setHighlightMode] = useState<"bm25" | "dense" | "whatif">("bm25"); const [showTrace, setShowTrace] = useState(true); const [whatIfText, setWhatIfText] = useState(profile.indexed_text); const [simChunking, setSimChunking] = useState(profile.is_truncated); const [chunkWords, setChunkWords] = useState(120); const [whatIfLoading, setWhatIfLoading] = useState(false); const [whatIfResult, setWhatIfResult] = useState(null); useEffect(() => { setWhatIfText(profile.indexed_text); setSimChunking(profile.is_truncated); setWhatIfResult(null); }, [profile.doc_id, profile.indexed_text, profile.is_truncated]); const handleRunWhatIf = async () => { if (!runId || !searchParams.query.trim()) return; setWhatIfLoading(true); try { const res = await runWhatIfDocApi(runId, { search: searchParams, doc_id: profile.doc_id, edited_text: whatIfText, simulate_chunking: simChunking, chunk_words: chunkWords, chunk_overlap: Math.min(30, Math.floor(chunkWords / 4)), }); setWhatIfResult(res); } catch (err) { console.error("What-If doc failed:", err); } finally { setWhatIfLoading(false); } }; const borderCls = accent === "emerald" ? "!border-emerald-800" : "!border-pink-800"; const badgeCls = accent === "emerald" ? "bg-emerald-100 border border-emerald-700 text-emerald-950" : "bg-pink-100 border border-pink-700 text-pink-950"; const renderHighlightedText = () => { const text = profile.indexed_text; const cutoff = profile.truncated_char_offset; if (highlightMode === "dense" && saliency && saliency.spans.length > 0) { return (
{saliency.spans.map((sp, i) => { const w = sp.normalized_weight; const bg = w > 0.15 ? `rgba(5, 150, 105, ${Math.min(0.35, w * 0.35)})` : w < -0.15 ? `rgba(220, 38, 38, ${Math.min(0.32, Math.abs(w) * 0.32)})` : "transparent"; return ( = 0 ? "+" : ""}${sp.delta_cosine.toFixed(4)}`} style={{ backgroundColor: bg }} className="px-0.5 mr-1 inline-block" > {sp.text} ); })} {cutoff !== null && ( <>
✂ TOKEN {profile.max_seq_len} CUTOFF — DROPPED BY EMBEDDING MODEL
{text.slice(cutoff)} )}
); } // Default: BM25 span highlighting + truncation cutoff line const spans = [...profile.bm25_highlight_spans].sort( (a, b) => a.start - b.start ); const renderSlice = (sliceStart: number, sliceEnd: number, dimmed: boolean) => { const nodes: React.ReactNode[] = []; let cursor = sliceStart; for (const sp of spans) { if (sp.end <= sliceStart || sp.start >= sliceEnd) continue; const s = Math.max(sp.start, sliceStart); const e = Math.min(sp.end, sliceEnd); if (s > cursor) { nodes.push( {text.slice(cursor, s)} ); } nodes.push( {text.slice(s, e)} ); cursor = e; } if (cursor < sliceEnd) { nodes.push({text.slice(cursor, sliceEnd)}); } return ( {nodes} ); }; if (cutoff !== null) { return (
{renderSlice(0, cutoff, false)}
✂ TOKEN {profile.max_seq_len} CUTOFF — INVISIBLE TO DENSE EMBEDDING
{renderSlice(cutoff, text.length, true)}
); } return (
{renderSlice(0, text.length, false)}
); }; return (
{/* Header */}
{role} Doc #{profile.doc_id} · Hybrid{" "} {profile.hybrid_rank ? `#${profile.hybrid_rank}` : "OUT"}
{profile.title_preview}
{profile.is_truncated && ( {profile.token_count}/{profile.max_seq_len}t )}
{/* Exact Formula Math & Stage-by-Stage Score Trace */}
{profile.formula_text}
{profile.score_trace && profile.score_trace.length > 0 && ( )}
{showTrace && profile.score_trace && profile.score_trace.length > 0 && (
{profile.score_trace.map((st, idx) => (
{idx + 1}. {st.label}
{st.delta !== null && ( 0 ? "text-emerald-700 font-semibold" : st.delta < 0 ? "text-red-700 font-semibold" : "text-[#64748b]" } > {st.delta >= 0 ? "+" : ""} {st.delta.toFixed(4)} )} {st.value.toFixed(4)}
{st.detail && (
{st.detail}
)}
))}
)}
{/* BM25 Length Normalization (b) & Saturation Diagnostics */} {profile.bm25_field_diagnostics && profile.bm25_field_diagnostics.length > 0 && (
BM25 Length Penalty (dl / avgdl) {profile.bm25_field_diagnostics.some( (fd) => fd.length_penalty_pct <= -15 && fd.raw_score > 0 ) && ( )}
{profile.bm25_field_diagnostics.map((fd) => (
{fd.field}{" "} ({fd.doc_len}/{fd.avg_dl.toFixed(0)}w · {fd.length_ratio.toFixed(1)}×) = 10 ? "text-emerald-700 font-bold" : "text-[#475569]" } > {fd.length_penalty_pct >= 0 ? "+" : ""} {fd.length_penalty_pct.toFixed(0)}% len
))}
)} {/* Per-Field Dilution & BM25 Breakdown */} {Object.keys(profile.per_field_dense_cos).length > 0 && (
Per-Field Signal & Dilution Check {profile.field_dilution_delta !== null && profile.field_dilution_delta > 0.05 && ( Dilution −{profile.field_dilution_delta.toFixed(3)} )}
{Object.entries(profile.per_field_dense_cos).map(([f, cosVal]) => (
{f}
cos {cosVal.toFixed(3)} bm25 {(profile.per_field_bm25[f] ?? 0).toFixed(2)}
))}
)} {/* BM25 Per-Term TF x IDF Breakdown */}
BM25 Term Contributions
{profile.bm25_term_breakdown.map((t) => ( {t.raw_term} ×{t.tf}{" "} +{t.score.toFixed(2)} {t.term_weight !== undefined && Math.abs(t.term_weight - 1.0) > 0.01 && ( [w×{t.term_weight.toFixed(2)}] )} {t.tf_saturation_pct !== undefined && t.tf_saturation_pct > 0 && ( ({t.tf_saturation_pct.toFixed(0)}% sat) )} ))} {profile.unmatched_query_terms.map((u, i) => ( {u} ))}
{profile.unmatched_morph_hints && profile.unmatched_morph_hints.length > 0 && (
{profile.unmatched_morph_hints.map((hint, idx) => (
⚠ {hint}
))}
)}
{/* Dual Word Highlight Viewer (BM25 vs On-Click Dense Saliency) */}
{saliency && highlightMode === "dense" && ( Green = +cos · Red = −cos ({saliency.elapsed_ms.toFixed(0)}ms) )}
{highlightMode === "whatif" ? (