feat(lens): add live run layout with queue, reading trace and conclusions

This commit is contained in:
Ishaan Jaff 2026-10-03 16:36:38 -07:00
parent 5a68f71bfa
commit 97225a7143
No known key found for this signature in database
6 changed files with 535 additions and 0 deletions

View file

@ -0,0 +1,97 @@
import { useEffect, useRef, type RefObject } from "react";
import { cn } from "@/lib/cva.config";
import { type Conclusion } from "../../model/live";
export interface Arrival {
key: string;
checkId: string;
text: string;
}
const FLY_MS = 550;
function fly(from: DOMRect, to: DOMRect, text: string) {
const node = document.createElement("div");
node.textContent = text;
node.setAttribute("aria-hidden", "true");
node.className =
"pointer-events-none fixed z-floating truncate rounded-lg border border-[#e5484d]/30 bg-background px-3 py-2 text-xs font-semibold text-[#e5484d] shadow-lg";
Object.assign(node.style, { left: `${from.left}px`, top: `${from.top}px`, width: `${from.width}px` });
document.body.appendChild(node);
const animation = node.animate(
[
{ transform: "translate(0, 0)", width: `${from.width}px`, opacity: 1 },
{
transform: `translate(${to.left - from.left}px, ${to.top - from.top}px)`,
width: `${Math.max(200, to.width)}px`,
opacity: 0.2,
},
],
{ duration: FLY_MS, easing: "cubic-bezier(.3,.7,.2,1)" },
);
animation.onfinish = () => node.remove();
return () => node.remove();
}
function useFlyIn(arrival: Arrival | null, from: RefObject<HTMLElement | null>, list: RefObject<HTMLElement | null>) {
useEffect(() => {
const source = from.current;
const box = list.current;
if (!arrival || !source || !box || typeof HTMLElement.prototype.animate !== "function") return;
if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
const target = box.querySelector<HTMLElement>(`[data-check="${CSS.escape(arrival.checkId)}"]`) ?? box;
return fly(source.getBoundingClientRect(), target.getBoundingClientRect(), arrival.text);
}, [arrival, from, list]);
}
export function ConclusionsPanel({
groups,
reviewed,
arrival,
verdictRef,
}: {
groups: readonly Conclusion[];
reviewed: number;
arrival: Arrival | null;
verdictRef: RefObject<HTMLElement | null>;
}) {
const list = useRef<HTMLOListElement>(null);
useFlyIn(arrival, verdictRef, list);
return (
<ol ref={list} aria-label="Conclusions" className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 py-2.5">
{groups.map((group) => (
<li
key={group.checkId}
data-check={group.checkId}
data-hit={arrival?.checkId === group.checkId || undefined}
className={cn(
"rounded-lg border bg-background px-3 py-2 transition-shadow duration-500 motion-safe:animate-in motion-safe:fade-in",
"data-hit:border-[#e5484d]/30 data-hit:ring-3 data-hit:ring-[#e5484d]/10",
)}
>
<p className="flex items-start gap-1.5 text-[12.5px] font-semibold">
<span
aria-hidden="true"
className={cn("mt-1.5 size-1.5 shrink-0 rounded-full", group.issue ? "bg-[#e5484d]" : "bg-muted-foreground/50")}
/>
<span className="line-clamp-2">{group.label}</span>
</p>
<p className="mt-1 flex justify-between gap-3 font-mono text-[11px] text-muted-foreground">
<span>
{group.count} {group.count === 1 ? "trace" : "traces"}
</span>
<span>{Math.round((group.count / Math.max(1, reviewed)) * 100)}% of reviewed</span>
</p>
{group.latest !== group.label && (
<p className="mt-1 line-clamp-1 text-[11px] text-muted-foreground" title={group.latest}>
latest: {group.latest}
</p>
)}
</li>
))}
{!groups.length && <li className="py-4 text-xs text-muted-foreground">Nothing flagged yet.</li>}
</ol>
);
}

View file

@ -0,0 +1,173 @@
"use client";
import { useMemo, useRef, useState, type CSSProperties } from "react";
import { Button } from "@/components/ui/button";
import { useNow } from "@/hooks/useNow";
import { cn } from "@/lib/cva.config";
import { sampleBatch } from "../../__fixtures__/reviews";
import { durationText, money } from "../../model/format";
import { modelsUsed } from "../../model/inbox";
import {
analysisModel,
conclusions,
isCompact,
liveStats,
outcome,
providerAccent,
providerOf,
rateLabel,
reviewKey,
shownCount,
tokenLabel,
verdictLine,
} from "../../model/live";
import { analysisProgress } from "../../model/progress";
import type { Job, Review } from "../../model/types";
import { ConclusionsPanel, type Arrival } from "./ConclusionsPanel";
import { ProviderBadge } from "./ProviderBadge";
import { ReadingPanel } from "./ReadingPanel";
import { ReviewQueue } from "./ReviewQueue";
import { useReviewPlayback } from "./useReviewPlayback";
const NEUTRAL_ACCENT = "var(--foreground)";
const SAMPLE_POLL_MS = 2000;
const SAMPLE_TOTAL = 60;
const COLUMN_HEAD =
"flex h-9 shrink-0 items-center justify-between gap-2 border-b px-3.5 text-[10px] tracking-[0.08em] text-muted-foreground uppercase";
function useArrival(review: Review | null, verdict: boolean, compact: boolean): Arrival | null {
const issue = review && verdict && !compact ? review.verdicts.find((v) => v.kind === "issue") : undefined;
const key = review && issue ? reviewKey(review) : "";
const checkId = issue?.check_id ?? "";
const text = review ? verdictLine(review) : "";
return useMemo(() => (key ? { key, checkId, text } : null), [key, checkId, text]);
}
function Status({ job }: { job: Job }) {
if (job.status === "queued") return <span className="text-xs text-muted-foreground">Queued</span>;
if (job.status === "running")
return (
<span className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground">
<span aria-hidden="true">●</span> Running
</span>
);
if (job.status === "completed")
return (
<span className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2.5 py-1 text-xs font-medium">
<span aria-hidden="true">✓</span> Done
</span>
);
return <span className="text-xs text-muted-foreground capitalize">{job.status}</span>;
}
function useSampleReviews(enabled: boolean): readonly Review[] {
const now = useNow(SAMPLE_POLL_MS);
const [startedAt] = useState(now);
return useMemo(() => {
if (!enabled) return [];
const polls = Math.floor((now - startedAt) / SAMPLE_POLL_MS);
return Array.from({ length: polls + 1 }, (_, poll) => sampleBatch(poll, poll < 3 ? 1 : 3))
.flat()
.slice(0, SAMPLE_TOTAL);
}, [enabled, now, startedAt]);
}
export function LiveRun({ job, onCancel }: { job: Job; onCancel?: () => void }) {
const live = job.status === "queued" || job.status === "running";
const sample = live && job.reviews.length === 0;
const sampled = useSampleReviews(sample);
const reviews = sample ? sampled : job.reviews;
const playback = useReviewPlayback(reviews, live);
const { current, played, pending, phase, duration } = playback;
const now = useNow(1000);
const verdictRef = useRef<HTMLDivElement>(null);
const model = analysisModel([current?.model ?? "", ...reviews.map((r) => r.model), ...modelsUsed(job.steps)]);
const accent = providerAccent(providerOf(model)) ?? NEUTRAL_ACCENT;
const decided = phase.verdict && current ? [...played, current] : played;
const groups = conclusions(decided, job.settings.checks);
const arrival = useArrival(current, phase.verdict, isCompact(duration));
const stats = liveStats(job, now);
const reviewed = sample ? decided.length : shownCount(job.reviewed, playback);
const selected = sample ? SAMPLE_TOTAL : job.coverage.selected;
const percent = live ? Math.min(100, Math.round((reviewed / Math.max(1, selected)) * 100)) : 100;
const issues = decided.filter((r) => outcome(r) === "issue").length;
const progress = analysisProgress(job);
return (
<section
aria-label="Live review"
style={{ "--provider": accent } as CSSProperties}
className="flex flex-col overflow-hidden rounded-xl border bg-background"
>
<header className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 px-4 py-2.5">
<div className="flex min-w-0 items-center gap-3">
<Status job={job} />
<span className="truncate text-xs text-muted-foreground">
{live ? progress.title : `Reviewed ${reviewed} ${reviewed === 1 ? "trace" : "traces"}`}
{sample && " · preview data until the worker reports reviews"}
</span>
</div>
<div className="flex min-w-0 items-center gap-2">
<ProviderBadge model={model} />
{live && onCancel && (
<Button variant="ghost" size="xs" onClick={onCancel}>
Cancel
</Button>
)}
</div>
</header>
<div
role="progressbar"
aria-label="Traces reviewed"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percent}
aria-valuetext={`${reviewed} of ${selected} traces reviewed`}
className="h-[3px] bg-muted"
>
<div
className="h-full bg-(--provider) transition-[width] duration-300 motion-reduce:transition-none"
style={{ width: `${percent}%` }}
/>
</div>
<div className="grid min-h-0 grid-cols-1 md:h-[440px] md:grid-cols-[minmax(0,15rem)_minmax(0,1fr)] xl:grid-cols-[17rem_minmax(0,1fr)_20rem]">
<div className="flex min-h-0 flex-col border-b md:border-r md:border-b-0">
<div className={COLUMN_HEAD}>
<span>Traces</span>
<span className="font-mono tracking-normal normal-case">
{reviewed} / {selected}
</span>
</div>
<ReviewQueue played={played} current={current} pending={pending} live={live} />
</div>
<div className="flex min-h-0 flex-col border-b xl:border-r xl:border-b-0">
<div className={COLUMN_HEAD}>
<span>{live ? "Reading trace" : "Last trace"}</span>
<span className="font-mono tracking-normal normal-case">{rateLabel(stats.perSecond)}</span>
</div>
<ReadingPanel review={current} phase={phase} tokens={tokenLabel(stats.tokens)} verdictRef={verdictRef} />
</div>
<div className="flex min-h-0 flex-col bg-muted/30 md:col-span-2 xl:col-span-1">
<div className={COLUMN_HEAD}>
<span>Conclusions</span>
<span className={cn("font-mono tracking-normal normal-case", issues > 0 && "text-[#e5484d]")}>
{issues} {issues === 1 ? "problem" : "problems"}
</span>
</div>
<ConclusionsPanel groups={groups} reviewed={decided.length} arrival={arrival} verdictRef={verdictRef} />
<footer
aria-label="Run stats"
className="flex shrink-0 flex-wrap justify-between gap-x-4 gap-y-1 border-t bg-background px-3.5 py-2 font-mono text-[11px] text-muted-foreground"
>
<span>{rateLabel(stats.perSecond)}</span>
<span>{tokenLabel(stats.tokens)}</span>
<span>{money(stats.cost)}</span>
<span>{durationText(stats.elapsedSeconds)}</span>
</footer>
</div>
</div>
</section>
);
}

View file

@ -0,0 +1,38 @@
import { getProviderLogoAndName } from "@/components/provider_info_helpers";
import { cn } from "@/lib/cva.config";
import { modelName, providerOf } from "../../model/live";
const MARK_CROP: Readonly<Record<string, string>> = {
cerebras: "absolute top-[-8px] left-[-2.4px] h-[30px] w-[40px] max-w-none",
};
export function ProviderLogo({ model, className }: { model: string; className?: string }) {
const provider = providerOf(model);
const { logo, displayName } = getProviderLogoAndName(provider);
if (!provider || !logo) return null;
const crop = MARK_CROP[provider];
return (
<span className={cn("relative inline-block size-3.5 shrink-0 overflow-hidden", className)}>
{/* eslint-disable-next-line @next/next/no-img-element -- provider logos are static svgs from /assets/logos */}
<img src={logo} alt={displayName} className={crop ?? "size-full object-contain"} />
</span>
);
}
export function ProviderBadge({ model }: { model: string }) {
if (!model) return null;
const provider = providerOf(model);
const { displayName } = getProviderLogoAndName(provider);
return (
<span
data-testid="provider-badge"
className="inline-flex min-w-0 items-center gap-1.5 rounded-full border border-(--provider)/30 bg-(--provider)/5 px-2.5 py-1 text-xs font-medium text-(--provider)"
>
<ProviderLogo model={model} />
<span className="truncate">
{provider ? `Analyzed by ${displayName} · ${modelName(model)}` : `Analyzed by ${model}`}
</span>
</span>
);
}

View file

@ -0,0 +1,115 @@
import type { Ref } from "react";
import { cn } from "@/lib/cva.config";
import { modelName, outcome, verdictLine, type Phase } from "../../model/live";
import type { Review } from "../../model/types";
import { ProviderLogo } from "./ProviderBadge";
const VERDICT_TONE = {
issue: "border-[#e5484d]/30 bg-[#e5484d]/5 text-[#e5484d]",
clear: "border-border bg-muted/60 text-foreground",
unknown: "border-border bg-muted/60 text-muted-foreground",
} as const;
const VERDICT_MARK = { issue: "●", clear: "✓", unknown: "?" } as const;
function Spans({ review, phase }: { review: Review; phase: Phase }) {
return (
<section aria-label="Trace" className="overflow-hidden rounded-xl border">
<header className="flex justify-between gap-3 border-b bg-muted/40 px-3 py-2 font-mono text-[11px] text-muted-foreground">
<span className="truncate">trace {review.trace_id.slice(0, 8)}</span>
<span className="truncate">{review.agent || review.name}</span>
</header>
<ol>
{review.spans.map((span, index) => {
const scanning = phase.span === index;
const cited = phase.verdict && span.cited;
return (
<li
key={span.span_id}
data-state={scanning ? "reading" : cited ? "cited" : "idle"}
className={cn(
"grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2.5 border-b border-dashed border-border/70 px-3 py-1.5 text-[12.5px] transition-colors duration-200 last:border-b-0 motion-reduce:transition-none",
scanning && "bg-(--provider)/8",
cited && "bg-[#e5484d]/5",
)}
>
<span className="truncate pt-px font-mono text-[10.5px] text-muted-foreground" title={span.name}>
{span.kind || span.name}
</span>
<span className={cn("line-clamp-2 break-words", cited && "text-[#e5484d]")}>
{span.preview || span.name}
</span>
</li>
);
})}
{!review.spans.length && <li className="px-3 py-2 text-xs text-muted-foreground">No trace parts shown</li>}
</ol>
</section>
);
}
function Reasoning({ review, phase, tokens }: { review: Review; phase: Phase; tokens: string }) {
const typing = phase.typed < review.reasoning.length;
return (
<section aria-label="Reasoning" className="rounded-xl border border-(--provider)/25 bg-(--provider)/3">
<header className="flex items-center justify-between gap-3 border-b border-(--provider)/20 px-3 py-2">
<span className="inline-flex min-w-0 items-center gap-1.5 text-xs font-semibold text-(--provider)">
<ProviderLogo model={review.model} />
<span className="truncate">{modelName(review.model) || "analysis model"} · reasoning</span>
</span>
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">{tokens}</span>
</header>
<p className="min-h-24 px-3 py-2.5 text-[12.5px] leading-relaxed whitespace-pre-wrap text-foreground/80">
{review.reasoning ? review.reasoning.slice(0, phase.typed) : !typing && "No reasoning was returned."}
{typing && (
<span
aria-hidden="true"
className="ml-px inline-block h-3.5 w-1.5 translate-y-0.5 bg-(--provider) motion-safe:animate-pulse"
/>
)}
</p>
</section>
);
}
export function ReadingPanel({
review,
phase,
tokens,
verdictRef,
}: {
review: Review | null;
phase: Phase;
tokens: string;
verdictRef: Ref<HTMLDivElement>;
}) {
if (!review) {
return (
<p className="px-4 py-6 text-sm text-muted-foreground">
Traces appear here as the worker reviews them.
</p>
);
}
const result = outcome(review);
return (
<div className="flex min-h-0 flex-col gap-3 overflow-hidden px-4 py-3.5">
<Spans review={review} phase={phase} />
<Reasoning review={review} phase={phase} tokens={tokens} />
<div
ref={verdictRef}
role="status"
aria-label="Verdict"
data-outcome={result}
className={cn(
"flex items-center gap-2.5 rounded-xl border px-3 py-2.5 text-sm font-semibold transition-all duration-200 motion-reduce:transition-none",
VERDICT_TONE[result],
phase.verdict ? "translate-y-0 opacity-100" : "translate-y-1 opacity-0",
)}
>
<span aria-hidden="true">{VERDICT_MARK[result]}</span>
<span className="min-w-0 truncate">{phase.verdict ? verdictLine(review) : ""}</span>
</div>
</div>
);
}

View file

@ -0,0 +1,69 @@
import { cn } from "@/lib/cva.config";
import { outcome, reviewKey } from "../../model/live";
import type { Review } from "../../model/types";
const BEFORE = 6;
const AFTER = 12;
const MARK = { issue: "●", clear: "✓", unknown: "?" } as const;
type Row = { review: Review; state: "done" | "active" | "next" };
function rows(played: readonly Review[], current: Review | null, pending: readonly Review[], live: boolean): Row[] {
const tail = played.slice(live ? -BEFORE : -(BEFORE + AFTER));
return [
...tail.map((review): Row => ({ review, state: "done" })),
...(current ? [{ review: current, state: live ? "active" : "done" } as Row] : []),
...pending.slice(0, AFTER).map((review): Row => ({ review, state: "next" })),
];
}
export function ReviewQueue({
played,
current,
pending,
live,
}: {
played: readonly Review[];
current: Review | null;
pending: readonly Review[];
live: boolean;
}) {
return (
<ol aria-label="Reviewed traces" className="min-h-0 flex-1 overflow-hidden">
{rows(played, current, pending, live).map(({ review, state }) => {
const result = outcome(review);
return (
<li
key={reviewKey(review)}
data-state={state}
aria-current={state === "active" ? "step" : undefined}
className={cn(
"grid grid-cols-[0.875rem_minmax(0,1fr)_auto] items-center gap-2 border-b border-border/60 px-3.5 py-1.5 text-xs",
state === "active" && "bg-(--provider)/5 shadow-[inset_2px_0_0_var(--provider)]",
state === "next" && "text-muted-foreground",
)}
>
{state === "active" && (
<span
aria-label="Reviewing"
className="size-2.5 rounded-full border-[1.5px] border-(--provider)/25 border-t-(--provider) motion-safe:animate-spin"
/>
)}
{state === "done" && (
<span
aria-label={result}
className={cn("text-[11px]", result === "issue" ? "text-[#e5484d]" : "text-muted-foreground")}
>
{MARK[result]}
</span>
)}
{state === "next" && <span className="text-[11px] text-muted-foreground">·</span>}
<span className="truncate">{review.agent || review.name}</span>
<span className="font-mono text-[11px] text-muted-foreground">{review.trace_id.slice(0, 8)}</span>
</li>
);
})}
</ol>
);
}

View file

@ -0,0 +1,43 @@
"use client";
import { useEffect, useReducer, useState } from "react";
import { playbackPhase, playbackReducer, startPlayback, type Phase, type Playback } from "../../model/live";
import type { Review } from "../../model/types";
const FRAME_MS = 40;
function prefersReducedMotion(): boolean {
return typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
export function useReviewPlayback(reviews: readonly Review[], live: boolean): Playback & { phase: Phase } {
const [still] = useState(prefersReducedMotion);
const [state, dispatch] = useReducer(playbackReducer, undefined, () =>
playbackReducer(startPlayback(reviews, live), still ? { type: "settle" } : { type: "tick", now: Date.now() }),
);
const [now, setNow] = useState(Date.now);
useEffect(() => {
dispatch({ type: "enqueue", reviews });
if (still) dispatch({ type: "settle" });
}, [reviews, still]);
const busy = state.pending.length > 0 || now - state.startedAt < state.duration;
useEffect(() => {
if (!busy || still) return;
const timer = window.setInterval(() => {
const at = Date.now();
setNow(at);
dispatch({ type: "tick", now: at });
}, FRAME_MS);
return () => window.clearInterval(timer);
}, [busy, still]);
const current = state.current;
const phase =
still || !current
? { span: -1, typed: current?.reasoning.length ?? 0, verdict: true }
: playbackPhase(now - state.startedAt, state.duration, current.spans.length, current.reasoning.length);
return { ...state, phase };
}