Skip to content

The platform for continuously improving AI agents.

Make trace scores, payloads and errors inspectable (#274)

Tyler-Edwards50b268936d1d
diff --git a/DESIGN.md b/DESIGN.md
index b706f22e..e9c32fe9 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -1022,6 +1022,9 @@ they name a symbol or quote a wire value.
## Don't
+- Add floating or inset decorative dividers between content sections. Use spacing
+ and aligned labels. Borders belong to container edges, table rows or data-tree
+ guides, not freestanding rules inside padded content.
- Write a hex, `hsl()`, `rgb()` or a raw Tailwind palette class
(`bg-blue-500`, `text-zinc-400`) anywhere in app code.
- Use the brand copper outside `overmind-eye-copper.svg`. Orange in the UI
diff --git a/frontend/src/components/traces/SpanDetailView.tsx b/frontend/src/components/traces/SpanDetailView.tsx
index bcf178ce..f02d8f04 100644
--- a/frontend/src/components/traces/SpanDetailView.tsx
+++ b/frontend/src/components/traces/SpanDetailView.tsx
@@ -1,16 +1,32 @@
import type React from "react";
-import { Fragment, useMemo, useState } from "react";
+import { Fragment, useId, useMemo, useState } from "react";
import { EvaluationMethodBadge } from "@/components/evaluations/evaluation-method-badge";
-import { metricResults } from "@/components/evaluations/metric-list";
+import { type MetricResult, metricResults } from "@/components/evaluations/metric-list";
import { ScoreChip } from "@/components/evaluations/run-comparison";
import { FinetuningModelChip } from "@/components/finetuning/finetuning-model-chip";
import { useTraceData } from "@/components/traces/contexts/TraceDataContext";
+import { useTraceSelection } from "@/components/traces/contexts/TraceSelectionContext";
+import {
+ CodeTokens,
+ ExpandableContent,
+ InspectorSection as Section,
+ StackTraceContent,
+} from "@/components/traces/inspector-section";
+import { TraceErrorDetailsView } from "@/components/traces/trace-error-details";
import { Badge } from "@/components/ui/badge";
import { BlockActions } from "@/components/ui/block-actions";
+import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { isLikelyMarkdown, MarkdownContent } from "@/components/ui/markdown";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import {
Table,
TableBody,
@@ -20,7 +36,7 @@ import {
TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import type { SpanEvent, SpanRow } from "@/hooks/use-traces";
+import type { SpanRow } from "@/hooks/use-traces";
import { spanStatusLabel } from "@/hooks/use-traces";
import { formatCost, formatDuration, formatNumber } from "@/lib/formatters";
import { PROSE } from "@/lib/typography";
@@ -29,6 +45,12 @@ import type { ToolCallItem, TranscriptMessage } from "@/types/chat";
const NOOP = () => undefined;
+function eventDate(timeUnixNano: unknown): Date | null {
+ if (!timeUnixNano) return null;
+ const date = new Date(Number(timeUnixNano) / 1_000_000);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
function formatAttributeValue(value: unknown): string {
if (value === null || value === undefined) return "—";
if (typeof value === "object") return JSON.stringify(value, null, 2);
@@ -46,46 +68,48 @@ function formatAttributeValue(value: unknown): string {
return String(value);
}
-function Section({
- actions,
- badge,
- children,
- id,
- label,
-}: {
- actions?: React.ReactNode;
- badge?: React.ReactNode;
- children: React.ReactNode;
- id?: string;
- label: string;
-}) {
- return (
- <section className="px-4 py-3" id={id}>
- <div className="mb-2 flex min-h-5 items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <span className="text-xs font-medium text-muted-foreground">{label}</span>
- {badge}
- </div>
- {actions}
- </div>
- {children}
- </section>
- );
-}
-
function KeyValueRows({ entries }: { entries: Array<[string, unknown]> }) {
+ const { projectId } = useTraceData();
if (entries.length === 0) return null;
return (
- <dl className="grid grid-cols-[minmax(0,2fr)_minmax(0,3fr)] gap-x-4 gap-y-1.5 text-xs">
- {entries.map(([key, value]) => (
- <Fragment key={key}>
- <dt className="max-w-[20rem] break-all font-mono text-muted-foreground">
- {/* Older spans still carry PromptId; show it under the current name. */}
- {key === "PromptId" ? "CapabilityId" : key}
- </dt>
- <dd className="whitespace-pre-wrap break-all font-mono">{formatAttributeValue(value)}</dd>
- </Fragment>
- ))}
+ <dl className="grid grid-cols-[minmax(0,1fr)_minmax(0,3fr)] gap-x-4 gap-y-2 text-xs">
+ {entries.map(([key, value]) =>
+ key.toLowerCase().includes("stacktrace") && typeof value === "string" ? (
+ <Fragment key={key}>
+ <dt className="sr-only">{key}</dt>
+ <dd className="col-span-2 min-w-0">
+ <StackTraceContent label={key} text={value} />
+ </dd>
+ </Fragment>
+ ) : (
+ <Fragment key={key}>
+ <dt className="max-w-[20rem] break-all font-mono text-muted-foreground">
+ {/* Older spans still carry PromptId; show it under the current name. */}
+ {key === "PromptId" ? "CapabilityId" : key}
+ </dt>
+ <dd className="min-w-0">
+ {[
+ "Model",
+ "Response model",
+ "gen_ai.request.model",
+ "gen_ai.response.model",
+ ].includes(key) &&
+ typeof value === "string" &&
+ value.trim() ? (
+ <FinetuningModelChip compact model={value} projectId={projectId} />
+ ) : value !== null && typeof value === "object" ? (
+ <FormattedValue value={value} />
+ ) : (
+ <ExpandableContent label={key} text={formatAttributeValue(value)}>
+ <pre className="whitespace-pre-wrap break-words font-mono leading-5">
+ {formatAttributeValue(value)}
+ </pre>
+ </ExpandableContent>
+ )}
+ </dd>
+ </Fragment>
+ )
+ )}
</dl>
);
}
@@ -156,7 +180,10 @@ function collectFieldEntries(
return entries;
}
-function groupSpanAttributes(attributes: Record<string, unknown> | undefined): {
+function groupSpanAttributes(
+ attributes: Record<string, unknown> | undefined,
+ previewKeys: ReadonlyArray<string | null>
+): {
groups: Array<{ title: string; entries: Array<[string, unknown]> }>;
rest: Array<[string, unknown]>;
} {
@@ -166,7 +193,7 @@ function groupSpanAttributes(attributes: Record<string, unknown> | undefined): {
if (attributes && typeof attributes === "object") {
for (const [key, value] of Object.entries(attributes)) {
- if (HIDDEN_ATTRIBUTE_KEYS.has(key)) continue;
+ if (HIDDEN_ATTRIBUTE_KEYS.has(key) || previewKeys.includes(key)) continue;
const match = OVERMIND_GROUPS.find((g) => key.startsWith(g.prefix));
if (match) {
const stripped = key.slice(match.prefix.length);
@@ -236,9 +263,14 @@ function ToolCallBlock({ tc }: { tc: ToolCallItem }) {
<div className="mt-1 rounded-sm border border-border/60 bg-wash-raised px-2 py-1.5">
<span className="font-semibold text-cat-2">{tc.function?.name ?? tc.name ?? "tool"}</span>
{prettyArgs && (
- <pre className="mt-1 whitespace-pre-wrap break-words text-muted-foreground">
- {prettyArgs}
- </pre>
+ <ExpandableContent
+ label={`${tc.function?.name ?? tc.name ?? "Tool"} arguments`}
+ text={prettyArgs}
+ >
+ <pre className="mt-1 whitespace-pre-wrap break-words text-muted-foreground">
+ {prettyArgs}
+ </pre>
+ </ExpandableContent>
)}
</div>
);
@@ -398,33 +430,43 @@ function MessageRow({ msg }: { msg: TranscriptMessage }) {
return (
<div>
- <div className="mb-1.5 flex items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <span className="font-semibold text-muted-foreground">{roleLabel}</span>
- {hasToolCalls && (
- <span className="chip-label inline-flex items-center rounded-sm border border-cat-2/30 bg-cat-2/10 px-2 py-0.5 text-xs font-semibold text-cat-2">
- Tool call
- </span>
- )}
- </div>
- {text.length > 0 && (
- <BlockActions
- mode={mode}
- onToggleMode={() => setMode((m) => (m === "raw" ? "markdown" : "raw"))}
- showToggle={canMarkdown}
- text={text}
- />
+ <ExpandableContent
+ label={`${roleLabel} content`}
+ render={(content, toggle) => (
+ <>
+ <div className="mb-1.5 flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold text-muted-foreground">{roleLabel}</span>
+ {hasToolCalls && (
+ <span className="chip-label inline-flex items-center rounded-sm border border-cat-2/30 bg-cat-2/10 px-2 py-0.5 text-xs font-semibold text-cat-2">
+ Tool call
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ {toggle}
+ {text.length > 0 && (
+ <BlockActions
+ mode={mode}
+ onToggleMode={() => setMode((m) => (m === "raw" ? "markdown" : "raw"))}
+ showToggle={canMarkdown}
+ text={text}
+ />
+ )}
+ </div>
+ </div>
+ {content}
+ </>
)}
- </div>
- {text !== "" && (
- <div className="break-words">
- {mode === "markdown" && canMarkdown ? (
+ text={text}
+ >
+ {text !== "" &&
+ (mode === "markdown" && canMarkdown ? (
<MarkdownContent compact>{text}</MarkdownContent>
) : (
<div className={cn(PROSE, "whitespace-pre-wrap text-xs")}>{text}</div>
- )}
- </div>
- )}
+ ))}
+ </ExpandableContent>
{toolCalls.map((tc, tcIdx) => (
<ToolCallBlock key={tcIdx} tc={tc} />
))}
@@ -432,7 +474,65 @@ function MessageRow({ msg }: { msg: TranscriptMessage }) {
);
}
-type JsonView = "formatted" | "json";
+type JsonView = "formatted" | "tree";
+
+function JsonValue({
+ value,
+ depth = 0,
+ label,
+}: {
+ value: unknown;
+ depth?: number;
+ label?: string;
+}) {
+ if (value === null || typeof value !== "object") {
+ const text = JSON.stringify(value) ?? "null";
+ return (
+ <div className="flex min-w-0 items-baseline gap-2 py-0.5">
+ {label !== undefined && <span className="shrink-0 text-muted-foreground">{label}:</span>}
+ <div className="min-w-0 flex-1">
+ <ExpandableContent label={label ?? "JSON value"} text={text}>
+ <span className="whitespace-pre-wrap break-words">
+ <CodeTokens text={text} />
+ </span>
+ </ExpandableContent>
+ </div>
+ </div>
+ );
+ }
+ const array = Array.isArray(value);
+ const entries = Object.entries(value);
+ if (entries.length === 0)
+ return (
+ <span>
+ {label !== undefined ? `${label}: ` : ""}
+ {array ? "[]" : "{}"}
+ </span>
+ );
+ const singleRecord =
+ array &&
+ value.length === 1 &&
+ value[0] !== null &&
+ typeof value[0] === "object" &&
+ !Array.isArray(value[0]);
+ const children = singleRecord ? Object.entries(value[0]) : entries;
+ const opening = singleRecord ? "[{" : array ? "[" : "{";
+ const closing = singleRecord ? "}]" : array ? "]" : "}";
+ return (
+ <details className="py-0.5" open={depth < 2 || entries.length <= 3}>
+ <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
+ {label !== undefined && <span className="text-foreground">{label}: </span>}
+ {opening}
+ </summary>
+ <div className="ml-2 border-l border-border/70 pl-4">
+ {children.map(([key, item]) => (
+ <JsonValue depth={depth + 1} key={key} label={key} value={item} />
+ ))}
+ </div>
+ <span className="pl-4 text-muted-foreground">{closing}</span>
+ </details>
+ );
+}
function isMessageLike(value: unknown): value is TranscriptMessage {
return (
@@ -477,14 +577,13 @@ function FormattedValue({ value }: { value: unknown }) {
}
if (Array.isArray(value)) {
if (value.length === 0) return <span className="text-muted-foreground">[]</span>;
+ if (value.length === 1) return <FormattedValue value={value[0]} />;
return (
- <div className="space-y-1.5">
+ <div className="divide-y divide-border/70">
{value.map((item, idx) => (
- <div className="flex gap-2" key={idx}>
- <span className="select-none font-mono text-muted-foreground">{idx}</span>
- <div className="min-w-0 flex-1">
- <FormattedValue value={item} />
- </div>
+ <div className="py-3 first:pt-0" key={idx}>
+ <p className="mb-2 text-xs text-muted-foreground">[{idx}]</p>
+ <FormattedValue value={item} />
</div>
))}
</div>
@@ -493,15 +592,18 @@ function FormattedValue({ value }: { value: unknown }) {
const entries = Object.entries(value as Record<string, unknown>);
if (entries.length === 0) return <span className="text-muted-foreground">{"{}"}</span>;
return (
- <div className="space-y-2">
+ <div className="space-y-3">
{entries.map(([key, val]) => {
const inline =
isPlainScalar(val) &&
!(typeof val === "string" && (val.includes("\n") || val.length > 60));
if (inline) {
return (
- <div className="flex flex-wrap items-baseline gap-x-2" key={key}>
- <span className="font-mono text-muted-foreground">{key}</span>
+ <div
+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-baseline gap-x-4"
+ key={key}
+ >
+ <span className="min-w-0 break-words font-mono text-muted-foreground">{key}</span>
<span className="min-w-0 break-all font-mono">
{val === "" ? (
<span className="text-muted-foreground">""</span>
@@ -516,15 +618,22 @@ function FormattedValue({ value }: { value: unknown }) {
}
if (val !== null && typeof val === "object") {
const count = Array.isArray(val) ? val.length : Object.keys(val).length;
+ if (count <= 3)
+ return (
+ <div className="space-y-2" key={key}>
+ <p className="font-mono text-muted-foreground">{key}</p>
+ <FormattedValue value={val} />
+ </div>
+ );
return (
- <details className="border-b border-border/60 py-1 last:border-0" key={key}>
+ <details className="py-1" key={key}>
<summary className="cursor-pointer break-all font-mono text-muted-foreground hover:text-foreground">
- {key}{" "}
+ <span>{key}</span>{" "}
<span className="ml-2 text-xs">
{count} {Array.isArray(val) ? "items" : "fields"}
</span>
</summary>
- <div className="mt-2 pl-3">
+ <div className="mt-3">
<FormattedValue value={val} />
</div>
</details>
@@ -532,9 +641,11 @@ function FormattedValue({ value }: { value: unknown }) {
}
return (
<div key={key}>
- <span className="font-mono text-muted-foreground">{key}</span>
- <div className="mt-0.5 pl-3">
- <FormattedValue value={val} />
+ <span className="min-w-0 break-words font-mono text-muted-foreground">{key}</span>
+ <div className="mt-1">
+ <ExpandableContent label={key} text={formatAttributeValue(val)}>
+ <FormattedValue value={val} />
+ </ExpandableContent>
</div>
</div>
);
@@ -545,28 +656,19 @@ function FormattedValue({ value }: { value: unknown }) {
function ViewToggle({ onChange, value }: { onChange: (next: JsonView) => void; value: JsonView }) {
return (
- <div
- aria-label="Toggle view format"
- className="inline-flex items-center gap-0.5 rounded-sm border border-border/60 p-0.5"
- role="group"
- >
- {(["formatted", "json"] as const).map((option) => (
- <button
- aria-pressed={value === option}
- className={cn(
- "rounded-md px-1.5 py-0.5 text-xs font-medium capitalize transition-colors",
- value === option
- ? "bg-muted text-foreground"
- : "text-muted-foreground hover:text-foreground"
- )}
- key={option}
- onClick={() => onChange(option)}
- type="button"
- >
- {option === "json" ? "JSON" : option}
- </button>
- ))}
- </div>
+ <Select onValueChange={(next) => onChange(next as JsonView)} value={value}>
+ <SelectTrigger
+ aria-label="View format"
+ className="bg-transparent text-muted-foreground hover:bg-muted"
+ size="xs"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="formatted">Formatted</SelectItem>
+ <SelectItem value="tree">Tree</SelectItem>
+ </SelectContent>
+ </Select>
);
}
@@ -603,27 +705,34 @@ function JsonBlock({
const showToggle = Boolean(
messageList || messageObject || canMarkdown || !isStringValue || stringNeedsToggle
);
- const [view, setView] = useState<JsonView>("formatted");
+ const [view, setView] = useState<JsonView>(
+ messageList || messageObject || isStringValue ? "formatted" : "tree"
+ );
if (value === null || value === undefined) {
return (
<Section label={title}>
- <p className="text-xs text-muted-foreground">Not captured</p>
+ <Card className="bg-wash-subtle px-3 py-2">
+ <p className="text-xs text-muted-foreground">Not captured</p>
+ </Card>
</Section>
);
}
- const surface = "bg-wash-subtle";
- const jsonPre = `whitespace-pre-wrap break-words p-3 font-mono text-xs ${surface}`;
+ const jsonPre = "whitespace-pre-wrap break-words font-mono text-xs leading-5";
let content: React.ReactNode;
- if (view === "json") {
- content = <pre className={jsonPre}>{prettyJson}</pre>;
+ if (view === "tree") {
+ content = (
+ <div className="font-mono text-xs leading-5">
+ <JsonValue value={parsedValue} />
+ </div>
+ );
} else if (messageList) {
content = (
- <div className={`divide-y divide-border/70 font-mono text-xs ${surface}`}>
+ <div className="space-y-4 font-mono text-xs">
{messageList.map((msg, idx) => (
- <div className="px-3 py-3" key={idx}>
+ <div className="py-3 first:pt-0 last:pb-0" key={idx}>
<MessageRow msg={msg} />
</div>
))}
@@ -631,13 +740,13 @@ function JsonBlock({
);
} else if (messageObject) {
content = (
- <div className={`p-3 font-mono text-xs ${surface}`}>
+ <div className="font-mono text-xs">
<MessageRow msg={messageObject} />
</div>
);
} else if (isStringValue) {
content = canMarkdown ? (
- <div className={`p-3 ${surface}`}>
+ <div className="min-w-0">
<MarkdownContent compact>{parsedValue}</MarkdownContent>
</div>
) : (
@@ -645,36 +754,170 @@ function JsonBlock({
);
} else {
content = (
- <div className={`p-3 text-xs ${surface}`}>
+ <div className="text-xs leading-5">
<FormattedValue value={parsedValue} />
</div>
);
}
return (
- <Section
- actions={
- <div className="flex items-center gap-1.5">
- {showToggle && <ViewToggle onChange={setView} value={view} />}
- <BlockActions
- mode="raw"
- onToggleMode={NOOP}
- showToggle={false}
- text={isStringValue ? parsedValue : prettyJson}
- />
- </div>
- }
- badge={badge}
- id={id}
- label={title}
+ <ExpandableContent
+ label={`${title} content`}
+ render={(body, toggle) => (
+ <Section
+ actions={
+ <div className="flex items-center gap-1.5">
+ {showToggle && <ViewToggle onChange={setView} value={view} />}
+ {toggle}
+ <BlockActions
+ mode="raw"
+ onToggleMode={NOOP}
+ showToggle={false}
+ text={isStringValue ? parsedValue : prettyJson}
+ />
+ </div>
+ }
+ badge={badge}
+ id={id}
+ label={title}
+ >
+ <Card className="min-w-0 bg-wash-subtle px-3 py-2">{body}</Card>
+ </Section>
+ )}
+ text={isStringValue && view !== "tree" ? parsedValue : ""}
>
{content}
- </Section>
+ </ExpandableContent>
+ );
+}
+
+function MetricScore({ metric }: { metric: MetricResult }) {
+ if (metric.error)
+ return (
+ <Badge size="chip" variant="error">
+ Error
+ </Badge>
+ );
+ if (metric.verdict === "abstain")
+ return (
+ <Badge size="chip" variant="neutral">
+ Abstained
+ </Badge>
+ );
+ if (metric.score == null)
+ return (
+ <Badge size="chip" variant="neutral">
+ Not scored
+ </Badge>
+ );
+ return <ScoreChip value={metric.score} />;
+}
+
+function MetricExplanation({ metric }: { metric: MetricResult }) {
+ return (
+ <dl className="grid grid-cols-[7rem_minmax(0,1fr)] items-baseline gap-x-4 gap-y-3 text-xs">
+ {metric.expectation && (
+ <>
+ <dt className="text-muted-foreground">Expectation</dt>
+ <dd className="min-w-0 whitespace-pre-wrap break-words leading-6">
+ {metric.expectation}
+ </dd>
+ </>
+ )}
+ {metric.verdict && (
+ <>
+ <dt className="text-muted-foreground">Verdict</dt>
+ <dd>{metric.verdict}</dd>
+ </>
+ )}
+ <dt className="text-muted-foreground">{metric.error ? "Evaluation error" : "Explanation"}</dt>
+ <dd className="min-w-0">
+ <ExpandableContent label="score explanation" text={metric.error || metric.reason || ""}>
+ <p
+ className={cn(
+ "whitespace-pre-wrap break-words leading-6",
+ metric.error && "text-destructive"
+ )}
+ >
+ {metric.error || metric.reason || "No explanation recorded"}
+ </p>
+ </ExpandableContent>
+ </dd>
+ </dl>
+ );
+}
+
+function ScoreRow({
+ name,
+ metric,
+ children,
+ aggregate = false,
+}: {
+ name: string;
+ metric: MetricResult;
+ children: React.ReactNode;
+ aggregate?: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const id = useId();
+ return (
+ <Fragment>
+ <TableRow className={open ? "bg-wash-raised" : undefined}>
+ <TableCell className="p-0" colSpan={3}>
+ <button
+ aria-controls={id}
+ aria-describedby={`${id}-result`}
+ aria-expanded={open}
+ aria-label={`Inspect score: ${name}`}
+ className="grid w-full grid-cols-[minmax(0,1fr)_8rem_6rem] items-center gap-0 p-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ onClick={() => setOpen(!open)}
+ type="button"
+ >
+ <span className="flex min-w-0 items-start gap-2 pr-3 whitespace-normal break-words">
+ <Icon.chevronRight
+ aria-hidden
+ className={cn(
+ "mt-0.5 size-3.5 shrink-0 text-muted-foreground",
+ open && "rotate-90"
+ )}
+ />
+ <span>{name}</span>
+ </span>
+ <span>
+ {aggregate ? (
+ <span className="text-muted-foreground">Aggregate</span>
+ ) : metric.type === "llm" || metric.type === "deterministic" ? (
+ <EvaluationMethodBadge type={metric.type} />
+ ) : (
+ <span className="text-muted-foreground">{metric.type || "Not recorded"}</span>
+ )}
+ </span>
+ <span className="text-right" id={`${id}-result`}>
+ <MetricScore metric={metric} />
+ </span>
+ </button>
+ </TableCell>
+ </TableRow>
+ {open && (
+ <TableRow className="hover:bg-transparent">
+ <TableCell className="whitespace-normal p-4" colSpan={3}>
+ <div className="min-w-0 space-y-4" id={id}>
+ {children}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </Fragment>
);
}
function TraceScoresSection({ span }: { span: SpanRow }) {
+ const { spans } = useTraceData();
+ const { setSelectedSpanId } = useTraceSelection();
const entries = metricResults(span.evalMetrics);
+ const referenceKey = ["overmind.expected", "expected_output", "expected"].find(
+ (key) => span.spanAttributes[key] != null
+ );
return (
<Table
aria-label="Evaluation scores"
@@ -683,49 +926,70 @@ function TraceScoresSection({ span }: { span: SpanRow }) {
>
<TableHeader>
<TableRow>
- <TableHead>Eval name</TableHead>
- <TableHead className="w-32">Type</TableHead>
- <TableHead className="w-24 text-right">Score</TableHead>
+ <TableHead className="pl-8">Evaluation</TableHead>
+ <TableHead className="w-32">Method</TableHead>
+ <TableHead className="w-28 pr-3 text-right">Score</TableHead>
</TableRow>
</TableHeader>
<TableBody>
- {span.trajectoryScore != null && (
- <TableRow>
- <TableCell>Trajectory</TableCell>
- <TableCell className="text-muted-foreground">Aggregate</TableCell>
- <TableCell className="text-right">
- <ScoreChip value={span.trajectoryScore} />
- </TableCell>
- </TableRow>
- )}
- {entries.map(([name, metric]) => (
- <TableRow key={name}>
- <TableCell className="whitespace-normal break-words">{name}</TableCell>
- <TableCell>
- {metric.type === "llm" || metric.type === "deterministic" ? (
- <EvaluationMethodBadge type={metric.type} />
- ) : (
- <span className="text-muted-foreground">{metric.type || "Not recorded"}</span>
+ {span.trajectory && (
+ <ScoreRow aggregate metric={{ score: span.trajectoryScore }} name="Trajectory">
+ <div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
+ <span>Trace-level result</span>
+ {span.trajectory.span_count != null && (
+ <span>{span.trajectory.span_count} spans evaluated</span>
)}
- </TableCell>
- <TableCell className="text-right">
- {metric.verdict === "abstain" ? (
- <Badge size="chip" variant="neutral">
- Abstained
- </Badge>
- ) : metric.error ? (
- <Badge size="chip" variant="error">
- Error
+ {span.trajectory.passed != null && (
+ <Badge size="chip" variant={span.trajectory.passed ? "success" : "warning"}>
+ {span.trajectory.passed ? "Passed" : "Did not pass"}
</Badge>
- ) : metric.score == null ? (
- <Badge size="chip" variant="neutral">
- Not scored
- </Badge>
- ) : (
- <ScoreChip value={metric.score} />
)}
- </TableCell>
- </TableRow>
+ </div>
+ {metricResults(span.trajectory.metrics).length ? (
+ metricResults(span.trajectory.metrics).map(([name, metric]) => (
+ <Section badge={<MetricScore metric={metric} />} key={name} label={name}>
+ <MetricExplanation metric={metric} />
+ </Section>
+ ))
+ ) : (
+ <p className="text-xs text-muted-foreground">No component results recorded</p>
+ )}
+ <Section defaultOpen={false} label="Trace spans">
+ <div className="divide-y divide-border/70">
+ {spans.map((source) => (
+ <button
+ className="flex w-full items-center justify-between gap-3 px-2 py-2 text-left text-xs hover:bg-wash-raised focus-visible:ring-2 focus-visible:ring-ring"
+ key={source.spanId}
+ onClick={() => setSelectedSpanId(source.spanId)}
+ type="button"
+ >
+ <span className="min-w-0">
+ <span className="block break-words">
+ {source.name || source.scopeName || "Unnamed span"}
+ </span>
+ <span className="font-mono text-muted-foreground">{source.spanId}</span>
+ </span>
+ <Icon.chevronRight className="size-3 shrink-0" />
+ </button>
+ ))}
+ </div>
+ </Section>
+ </ScoreRow>
+ )}
+ {entries.map(([name, metric]) => (
+ <ScoreRow key={name} metric={metric} name={name}>
+ <MetricExplanation metric={metric} />
+ {span.evalIntent && (
+ <Section label="Intent">
+ <p className="whitespace-pre-wrap text-xs leading-5">{span.evalIntent}</p>
+ </Section>
+ )}
+ <JsonBlock title="Output" value={span.outputs} />
+ <JsonBlock title="Input" value={span.inputs} />
+ {referenceKey && (
+ <JsonBlock title="Reference" value={span.spanAttributes[referenceKey]} />
+ )}
+ </ScoreRow>
))}
</TableBody>
</Table>
@@ -736,49 +1000,11 @@ interface SpanDetailViewProps {
span: SpanRow;
}
-function ExceptionEventsSection({ events }: { events: SpanEvent[] }) {
- const exceptionEvents = events.filter((e) => e.name === "exception");
- if (exceptionEvents.length === 0) return null;
- return (
- <Section label="Exceptions">
- <div className="space-y-3">
- {exceptionEvents.map((ev, idx) => {
- const attrs = ev.attributes ?? {};
- const type = attrs["exception.type"] as string | undefined;
- const message = attrs["exception.message"] as string | undefined;
- const stacktrace = attrs["exception.stacktrace"] as string | undefined;
- return (
- <div className="rounded-md border border-destructive/40 bg-destructive/5 p-3" key={idx}>
- {type && (
- <p className="mb-1 font-mono text-xs font-semibold text-destructive">{type}</p>
- )}
- {message && (
- <p className="whitespace-pre-wrap break-words font-mono text-xs text-destructive/80">
- {message}
- </p>
- )}
- {stacktrace && (
- <details className="mt-2">
- <summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground">
- Stack trace
- </summary>
- <pre className="mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground">
- {stacktrace}
- </pre>
- </details>
- )}
- </div>
- );
- })}
- </div>
- </Section>
- );
-}
-
export function SpanDetailView({ span }: SpanDetailViewProps) {
const { projectId } = useTraceData();
const { groups: overmindGroups, rest: spanAttributeEntries } = groupSpanAttributes(
- span.spanAttributes
+ span.spanAttributes,
+ [span.inputAttribute, span.outputAttribute]
);
const modelUsageEntries = collectFieldEntries(span.spanAttributes, MODEL_USAGE_FIELDS);
@@ -795,18 +1021,78 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
["Status", spanStatusLabel(span.statusCode)],
];
- const scoreCount = Object.keys(span.traceScores).length + (span.trajectoryScore != null ? 1 : 0);
+ const scoreCount = metricResults(span.evalMetrics).length + (span.trajectory ? 1 : 0);
+ const TypeIcon =
+ span.spanType === "llm_call"
+ ? Icon.model
+ : span.spanType === "tool_call"
+ ? Icon.tool
+ : Icon.code;
+
+ const eventSections = span.events.map((event, index) => {
+ const time = eventDate(event.timeUnixNano);
+ return (
+ <Section
+ actions={
+ <BlockActions
+ mode="raw"
+ onToggleMode={NOOP}
+ showToggle={false}
+ text={JSON.stringify(event, null, 2)}
+ />
+ }
+ badge={
+ <>
+ <Badge size="chip" variant="neutral">
+ Event
+ </Badge>
+ {time ? (
+ <time
+ className="font-mono text-xs text-muted-foreground"
+ dateTime={time.toISOString()}
+ >
+ {time.toLocaleString()}
+ </time>
+ ) : null}
+ </>
+ }
+ key={index}
+ label={event.name}
+ >
+ <KeyValueRows
+ entries={[
+ ...(time ? [["Time", time.toISOString()] as [string, unknown]] : []),
+ ...Object.entries(event.attributes ?? {}),
+ ]}
+ />
+ </Section>
+ );
+ });
return (
<div className="flex h-full min-w-0 flex-col overflow-hidden bg-card text-card-foreground">
- <div className="shrink-0 px-4 pt-3 pb-2">
+ <div className="shrink-0 px-3 py-2">
<div className="flex flex-wrap items-start justify-between gap-2">
- <h3 className="min-w-0 break-words text-sm font-medium">
- {span.name || span.scopeName || "Unnamed span"}
- </h3>
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ "flex size-5 shrink-0 items-center justify-center rounded-sm",
+ span.spanType === "llm_call"
+ ? "bg-cat-1/10 text-cat-1"
+ : span.spanType === "tool_call"
+ ? "bg-cat-2/10 text-cat-2"
+ : "bg-muted text-muted-foreground"
+ )}
+ >
+ <TypeIcon className="size-3.5" />
+ </span>
+ <h3 className="min-w-0 break-words text-sm font-medium">
+ {span.name || span.scopeName || "Unnamed span"}
+ </h3>
+ </div>
{span.model && <FinetuningModelChip compact model={span.model} projectId={projectId} />}
</div>
- <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-xs tabular-nums text-muted-foreground">
+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-xs tabular-nums text-muted-foreground">
<span className={isError ? "text-destructive" : undefined}>
{spanStatusLabel(span.statusCode)}
</span>
@@ -824,32 +1110,37 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
{span.totalCost != null && <span>{formatCost(span.totalCost)}</span>}
</div>
</div>
- {isError && span.statusMessage && (
- <div className="shrink-0 border-y border-destructive/40 bg-destructive/5 px-4 py-2">
- <p className="break-words text-xs text-destructive">{span.statusMessage}</p>
- </div>
- )}
+ {span.errorDetails && <TraceErrorDetailsView details={span.errorDetails} />}
<Tabs className="flex min-h-0 flex-1 flex-col" defaultValue="preview">
<TabsList
aria-label="Span details"
- className="h-10 w-full shrink-0 justify-start gap-3 overflow-x-auto rounded-none border-b border-border/70 bg-transparent px-4 py-0"
+ className="mx-3 my-1 h-8 max-w-[calc(100%-1.5rem)] shrink-0 self-start justify-start gap-0.5 overflow-x-auto border border-border bg-background p-0.5"
>
{[
- ["preview", "Preview"],
- ["attributes", "Attributes"],
- ["scores", `Scores (${scoreCount})`],
- ["events", `Events (${span.events.length})`],
- ].map(([value, label]) => (
+ { label: "Preview", value: "preview" },
+ { label: "Attributes", value: "attributes" },
+ { count: scoreCount, label: "Scores", value: "scores" },
+ { count: span.events.length, label: "Events", value: "events" },
+ ].map(({ value, label, count }) => (
<TabsTrigger
- className="h-10 rounded-none border-b-2 border-transparent px-0 text-xs data-[state=active]:border-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:hover:text-foreground"
+ aria-label={count === undefined ? label : `${label} (${count})`}
+ className="h-6 gap-1.5 px-2 text-xs data-[state=active]:bg-control data-[state=active]:text-foreground data-[state=active]:hover:text-foreground"
key={value}
value={value}
>
{label}
+ {count !== undefined && (
+ <span
+ aria-hidden
+ className="rounded-sm bg-muted px-1 text-xs tabular-nums text-muted-foreground"
+ >
+ {count}
+ </span>
+ )}
</TabsTrigger>
))}
</TabsList>
- <TabsContent className="mt-0 min-h-0 flex-1 overflow-auto" value="preview">
+ <TabsContent className="mt-0 min-h-0 flex-1 overflow-auto px-3 py-2" value="preview">
<JsonBlock title="Input" value={span.inputs} />
<JsonBlock
badge={
@@ -858,9 +1149,15 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
title="Output"
value={span.outputs}
/>
+ {(spanAttributeEntries.length > 0 || modelUsageEntries.length > 0) && (
+ <Section label="Attributes">
+ <KeyValueRows entries={[...modelUsageEntries, ...spanAttributeEntries]} />
+ </Section>
+ )}
+ {eventSections}
{Array.isArray(span.spanAttributes?.available_tools) &&
span.spanAttributes.available_tools.length > 0 && (
- <details className="mx-4 mb-3 border-t border-border/70 pt-3">
+ <details className="py-2">
<summary className="cursor-pointer text-xs text-muted-foreground">
Available tools ({span.spanAttributes.available_tools.length})
</summary>
@@ -870,10 +1167,7 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
</details>
)}
</TabsContent>
- <TabsContent
- className="mt-0 min-h-0 flex-1 divide-y divide-border/70 overflow-auto"
- value="attributes"
- >
+ <TabsContent className="mt-0 min-h-0 flex-1 overflow-auto px-3 py-2" value="attributes">
<Section label="Span">
<KeyValueRows entries={spanInfoEntries} />
</Section>
@@ -910,7 +1204,7 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
/>
)}
</TabsContent>
- <TabsContent className="mt-0 min-h-0 flex-1 overflow-auto" value="events">
+ <TabsContent className="mt-0 min-h-0 flex-1 overflow-auto px-3 py-2" value="events">
{span.events.length === 0 ? (
<EmptyState
description="This span has no captured events."
@@ -919,28 +1213,7 @@ export function SpanDetailView({ span }: SpanDetailViewProps) {
title="No recorded events"
/>
) : (
- <>
- <ExceptionEventsSection events={span.events} />
- {span.events
- .filter((event) => event.name !== "exception")
- .map((event, index) => (
- <Section key={index} label={event.name}>
- <KeyValueRows
- entries={[
- ...(event.timeUnixNano
- ? [
- ["Time", new Date(event.timeUnixNano / 1_000_000).toISOString()] as [
- string,
- unknown,
- ],
- ]
- : []),
- ...Object.entries(event.attributes ?? {}),
- ]}
- />
- </Section>
- ))}
- </>
+ eventSections
)}
</TabsContent>
</Tabs>
diff --git a/frontend/src/components/traces/SpanTree.tsx b/frontend/src/components/traces/SpanTree.tsx
index 82627203..35752305 100644
--- a/frontend/src/components/traces/SpanTree.tsx
+++ b/frontend/src/components/traces/SpanTree.tsx
@@ -93,17 +93,18 @@ function SpanTreeNodeRow({
type="button"
>
<span className="flex items-center gap-2 text-xs">
- <TypeIcon
- aria-hidden
+ <span
className={cn(
- "size-3.5 shrink-0",
+ "flex size-5 shrink-0 items-center justify-center rounded-sm",
node.span.spanType === "tool_call"
- ? "text-cat-2"
+ ? "bg-cat-2/10 text-cat-2"
: node.span.spanType === "llm_call"
- ? "text-cat-1"
- : "text-muted-foreground"
+ ? "bg-cat-1/10 text-cat-1"
+ : "bg-muted text-muted-foreground"
)}
- />
+ >
+ <TypeIcon aria-hidden className="size-3.5" />
+ </span>
<span
className={cn("truncate", isSelected && "font-medium text-foreground")}
title={name}
diff --git a/frontend/src/components/traces/TraceLayoutDesktop.tsx b/frontend/src/components/traces/TraceLayoutDesktop.tsx
index 72dec449..a34c2c5a 100644
--- a/frontend/src/components/traces/TraceLayoutDesktop.tsx
+++ b/frontend/src/components/traces/TraceLayoutDesktop.tsx
@@ -11,8 +11,8 @@ const HANDLE_ID = "trace-layout-handle";
const NAV_PANEL_ID = "trace-layout-nav";
const DETAIL_PANEL_ID = "trace-layout-detail";
-const NAV_DEFAULT_PCT = 35;
-const NAV_MIN_PCT = 25;
+const NAV_DEFAULT_PCT = 28;
+const NAV_MIN_PCT = 20;
const NAV_COLLAPSED_PCT = 5;
interface TraceLayoutDesktopContextValue {
@@ -97,7 +97,7 @@ TraceLayoutDesktop.ResizeHandle = function ResizeHandle() {
TraceLayoutDesktop.DetailPanel = function DetailPanel({ children }: { children: ReactNode }) {
return (
- <Panel defaultSize={65} id={DETAIL_PANEL_ID} minSize={40}>
+ <Panel defaultSize={72} id={DETAIL_PANEL_ID} minSize={40}>
{children}
</Panel>
);
diff --git a/frontend/src/components/traces/TracePanelNavigation.tsx b/frontend/src/components/traces/TracePanelNavigation.tsx
index fa47ebca..a05ad0a1 100644
--- a/frontend/src/components/traces/TracePanelNavigation.tsx
+++ b/frontend/src/components/traces/TracePanelNavigation.tsx
@@ -2,6 +2,7 @@ import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
+import { ListToolbar } from "@/components/ui/list-toolbar";
import { SearchInput } from "@/components/ui/search-input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -24,6 +25,7 @@ export function TracePanelNavigation() {
} = useTraceSelection();
const [search, setSearch] = useState("");
const roots = useMemo(() => buildSpanTree(spans), [spans]);
+ const failedSpans = spans.filter((span) => span.statusCode === 2);
const collapsed = roots.length > 0 && roots.every((root) => collapsedNodes.has(root.id));
return (
<div className="flex h-full min-w-0 flex-col bg-wash-subtle">
@@ -61,16 +63,27 @@ export function TracePanelNavigation() {
</Tooltip>
)}
</div>
+ {failedSpans.length > 0 && (
+ <div className="flex shrink-0 items-center justify-between gap-2 border-b border-border/70 px-3 py-1.5 text-xs">
+ <span className="text-destructive">
+ {failedSpans.length} failed {failedSpans.length === 1 ? "span" : "spans"}
+ </span>
+ </div>
+ )}
{viewMode === "tree" && (
- <div className="shrink-0 border-b border-border/70 px-2 py-1.5">
- <SearchInput
- label="Search spans"
- onChange={(e) => setSearch(e.target.value)}
- onClear={() => setSearch("")}
- placeholder="Search spans…"
- size="sm"
- value={search}
- variant="subtle"
+ <div className="shrink-0 border-b border-border/70 px-2 py-2">
+ <ListToolbar
+ search={
+ <SearchInput
+ aria-keyshortcuts="/"
+ className="min-w-0 flex-1"
+ label="Search spans"
+ onChange={(e) => setSearch(e.target.value)}
+ onClear={() => setSearch("")}
+ placeholder="Search spans…"
+ value={search}
+ />
+ }
/>
</div>
)}
diff --git a/frontend/src/components/traces/TracePanelNavigationHeader.tsx b/frontend/src/components/traces/TracePanelNavigationHeader.tsx
index 78b0fb0f..aecb3081 100644
--- a/frontend/src/components/traces/TracePanelNavigationHeader.tsx
+++ b/frontend/src/components/traces/TracePanelNavigationHeader.tsx
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { formatCost, formatNumber } from "@/lib/formatters";
+import { formatCost, formatDuration, formatNumber } from "@/lib/formatters";
import { useTraceData } from "./contexts/TraceDataContext";
import { buildSpanTree } from "./lib/tree-building";
@@ -19,42 +19,79 @@ export function TracePanelNavigationHeader() {
const { traceId } = traceRouteApi.useParams();
const { detailExpanded } = traceRouteApi.useSearch();
const roots = useMemo(() => buildSpanTree(spans), [spans]);
- const rootName = roots[0]?.span.name?.trim() || "Trace";
+ const root = roots[0]?.span;
+ const rootName = root?.name?.trim() || "Trace";
return (
- <header className="flex shrink-0 items-center gap-3 border-b border-border/70 bg-card px-3 py-3">
+ <header className="flex shrink-0 items-center gap-2 border-b border-border/70 bg-card px-3 py-2">
<Tooltip>
<TooltipTrigger asChild>
<Button asChild size="icon-sm" variant="ghost">
<Link aria-label="Close trace" resetScroll={false} search={(prev) => prev} to="..">
- <Icon.panelLeftOpen />
+ <Icon.close />
</Link>
</Button>
</TooltipTrigger>
<TooltipContent>Close trace</TooltipContent>
</Tooltip>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2">
+ <div className="flex min-w-0 items-center gap-2">
{isLoading ? (
- <Skeleton aria-label="Loading trace name" className="h-4 w-48 max-w-full" />
+ <Skeleton aria-label="Loading trace name" className="h-4 w-40 max-w-full" />
) : (
- <h2 className="truncate text-sm font-medium" title={rootName}>
+ <h2 className="max-w-64 truncate text-sm font-medium" title={rootName}>
{rootName}
</h2>
)}
- {traceStatus === "live" && <Badge variant="info">Live</Badge>}
- {traceStatus === "interrupted" && <Badge variant="warning">Interrupted</Badge>}
- </div>
- <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs tabular-nums text-muted-foreground">
- <span className="font-mono" title={traceId}>
- {traceId.slice(0, 8)}…
+ <span
+ className="max-w-32 truncate font-mono text-xs text-muted-foreground"
+ title={traceId}
+ >
+ {traceId}
</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5 tabular-nums">
{isLoading ? (
- <Skeleton aria-label="Loading span count" className="h-3 w-16" />
+ <Skeleton aria-label="Loading span count" className="h-6 w-20" />
) : (
- <span>{spans.length} spans</span>
+ <>
+ {root?.parentSpanId === null && root.durationNano > 0 && (
+ <Badge
+ aria-label="Root duration"
+ className="gap-1.5"
+ size="chip"
+ variant="secondary"
+ >
+ <Icon.history aria-hidden className="size-3.5 text-muted-foreground" />
+ {formatDuration(root.durationNano / 1_000_000)}
+ </Badge>
+ )}
+ <Badge className="gap-1.5" size="chip" variant="secondary">
+ <Icon.gitBranch aria-hidden className="size-3.5 text-muted-foreground" />
+ {spans.length} {spans.length === 1 ? "span" : "spans"}
+ </Badge>
+ </>
+ )}
+ {usage?.totalTokens != null && (
+ <Badge size="chip" variant="secondary">
+ {formatNumber(usage.totalTokens)} tokens
+ </Badge>
+ )}
+ {usage?.totalCost != null && (
+ <Badge aria-label="Total cost" className="gap-1.5" size="chip" variant="secondary">
+ <Icon.cost aria-hidden className="size-3.5 text-muted-foreground" />
+ {formatCost(usage.totalCost)}
+ </Badge>
+ )}
+ {traceStatus === "live" && (
+ <Badge size="chip" variant="info">
+ Live
+ </Badge>
+ )}
+ {traceStatus === "interrupted" && (
+ <Badge size="chip" variant="warning">
+ Interrupted
+ </Badge>
)}
- {usage?.totalTokens != null && <span>{formatNumber(usage.totalTokens)} tokens</span>}
- {usage?.totalCost != null && <span>{formatCost(usage.totalCost)}</span>}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
@@ -73,16 +110,6 @@ export function TracePanelNavigationHeader() {
</TooltipTrigger>
<TooltipContent>{detailExpanded ? "Exit full screen" : "Full screen"}</TooltipContent>
</Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button asChild size="icon-sm" variant="ghost">
- <Link aria-label="Close" resetScroll={false} search={(prev) => prev} to="..">
- <Icon.close />
- </Link>
- </Button>
- </TooltipTrigger>
- <TooltipContent>Close trace</TooltipContent>
- </Tooltip>
</div>
</header>
);
diff --git a/frontend/src/components/traces/inspector-section.tsx b/frontend/src/components/traces/inspector-section.tsx
new file mode 100644
index 00000000..fb595db3
--- /dev/null
+++ b/frontend/src/components/traces/inspector-section.tsx
@@ -0,0 +1,181 @@
+import { type ReactNode, useId, useState } from "react";
+
+import { BlockActions } from "@/components/ui/block-actions";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Icon } from "@/components/ui/icons";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+
+export function InspectorSection({
+ actions,
+ badge,
+ children,
+ id,
+ label,
+ defaultOpen = true,
+}: {
+ actions?: ReactNode;
+ badge?: ReactNode;
+ children: ReactNode;
+ id?: string;
+ label: string;
+ defaultOpen?: boolean;
+}) {
+ const [open, setOpen] = useState(defaultOpen);
+ const SectionIcon =
+ label === "Input"
+ ? Icon.forward
+ : label === "Output"
+ ? Icon.back
+ : label === "Attributes"
+ ? Icon.code
+ : Icon.list;
+ return (
+ <Collapsible asChild onOpenChange={setOpen} open={open}>
+ <section className="min-w-0 py-1" id={id}>
+ <div className="flex min-h-8 items-center gap-2">
+ <CollapsibleTrigger asChild>
+ <button
+ aria-label={`${open ? "Collapse" : "Expand"} ${label}`}
+ className="flex min-w-0 flex-1 items-center gap-2 py-1 text-left text-xs font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ type="button"
+ >
+ <span className="flex size-5 shrink-0 items-center justify-center rounded-sm bg-muted text-muted-foreground">
+ <SectionIcon className="size-3.5" />
+ </span>
+ <span className="break-words">{label}</span>
+ {badge}
+ <Icon.chevronRight
+ aria-hidden
+ className={cn(
+ "ml-auto size-3.5 shrink-0 text-muted-foreground",
+ open && "rotate-90"
+ )}
+ />
+ </button>
+ </CollapsibleTrigger>
+ {open && actions}
+ </div>
+ <CollapsibleContent className="mt-1 min-w-0 pb-2">{children}</CollapsibleContent>
+ </section>
+ </Collapsible>
+ );
+}
+
+export function CodeTokens({ text }: { text: string }) {
+ return text
+ .split(
+ /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b(?:true|false|null|True|False|None|await|raise|return|async|def|in)\b|\b\d+(?:\.\d+)?\b)/g
+ )
+ .map((part, index) => (
+ <span
+ className={
+ /^['"]/.test(part)
+ ? "text-cat-2"
+ : /^(true|false|null|True|False|None|await|raise|return|async|def|in)$/.test(part)
+ ? "text-cat-1"
+ : /^\d/.test(part)
+ ? "text-cat-4"
+ : undefined
+ }
+ key={index}
+ >
+ {part}
+ </span>
+ ));
+}
+
+export function StackTraceContent({ label, text }: { label: string; text: string }) {
+ const lines = text.split("\n");
+ const isPython = text.includes("Traceback (most recent call last):");
+ const LanguageIcon = isPython ? Icon.python : Icon.code;
+ return (
+ <ExpandableContent
+ label={label}
+ render={(content, toggle) => (
+ <Card className="min-w-0 overflow-hidden bg-wash-subtle">
+ <div className="flex items-center justify-between gap-2 border-b border-border bg-background px-4 py-2">
+ <span className="flex items-center gap-2 font-mono text-xs text-muted-foreground">
+ <LanguageIcon className="size-4" />
+ {isPython ? "python" : "Stack trace"}
+ </span>
+ <div className="flex items-center gap-1">
+ {toggle}
+ <BlockActions
+ mode="raw"
+ onToggleMode={() => undefined}
+ showToggle={false}
+ text={text}
+ />
+ </div>
+ </div>
+ <div className="p-3">{content}</div>
+ </Card>
+ )}
+ text={text}
+ >
+ <pre className="whitespace-pre-wrap break-words font-mono text-xs leading-5 [counter-reset:line]">
+ <code>
+ {lines.map((line, index) => (
+ <span
+ className="relative block pl-9 [counter-increment:line] before:absolute before:left-0 before:w-6 before:select-none before:text-right before:text-muted-foreground before:content-[counter(line)]"
+ key={index}
+ >
+ <CodeTokens text={line} />
+ {index < lines.length - 1 ? "\n" : ""}
+ </span>
+ ))}
+ </code>
+ </pre>
+ </ExpandableContent>
+ );
+}
+
+export function ExpandableContent({
+ children,
+ text,
+ label,
+ render,
+}: {
+ children: ReactNode;
+ text: string;
+ label: string;
+ render?: (content: ReactNode, toggle: ReactNode) => ReactNode;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const id = useId();
+ const long = text.length > 900 || text.split("\n").length > 12;
+ const toggle = long ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-controls={id}
+ aria-expanded={expanded}
+ aria-label={`${expanded ? "Collapse" : "Expand"} ${label}`}
+ onClick={() => setExpanded(!expanded)}
+ size="icon-xs"
+ variant="ghost"
+ >
+ {expanded ? <Icon.collapse /> : <Icon.expand />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {expanded ? "Collapse" : "Expand"} {label}
+ </TooltipContent>
+ </Tooltip>
+ ) : null;
+ const content = (
+ <div className={cn("min-w-0", long && !expanded && "max-h-56 overflow-hidden")} id={id}>
+ {children}
+ </div>
+ );
+ if (render) return render(content, toggle);
+ return (
+ <div className="min-w-0">
+ {toggle && <div className="mb-1 flex justify-end">{toggle}</div>}
+ {content}
+ </div>
+ );
+}
diff --git a/frontend/src/components/traces/trace-error-details.tsx b/frontend/src/components/traces/trace-error-details.tsx
new file mode 100644
index 00000000..48f745be
--- /dev/null
+++ b/frontend/src/components/traces/trace-error-details.tsx
@@ -0,0 +1,102 @@
+import { Alert } from "@/components/ui/alert";
+import { useCopy } from "@/components/ui/block-actions";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import type { TraceErrorDetails } from "@/openapi";
+
+export function TraceErrorDetailsView({ details }: { details: TraceErrorDetails }) {
+ const types = [...new Set(details.records.map((record) => record.type).filter(Boolean))];
+ const messages = [
+ ...new Set(details.records.map((record) => record.message).filter(Boolean)),
+ ].map((message) => {
+ const type = details.records.find((record) => record.message === message && record.type)?.type;
+ return type && !message.startsWith(type) ? `${type}: ${message}` : message;
+ });
+ const stacks = [...new Set(details.records.map((record) => record.stacktrace).filter(Boolean))];
+ const text = [
+ ...types,
+ ...Object.entries(details.context).map(([key, value]) => `${key}: ${value}`),
+ ...messages,
+ ...stacks,
+ ].join("\n\n");
+ const { copied, copy } = useCopy(text || "No error message captured");
+ return (
+ <section aria-label="Error details" className="max-h-[40vh] shrink-0 overflow-auto px-3 py-1">
+ <Alert className="gap-2 border-0 bg-destructive/5 px-3 py-2 text-xs" variant="destructive">
+ <span className="flex size-5 shrink-0 items-center justify-center rounded-sm bg-destructive/10">
+ <Icon.warning className="size-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ {messages.length === 0 && (
+ <>
+ {details.summary !== "No error message captured" && (
+ <p className="whitespace-pre-wrap break-words font-mono text-xs leading-5">
+ {details.summary}
+ </p>
+ )}
+ <p className="text-xs">No error message captured</p>
+ </>
+ )}
+ {messages.map((message) =>
+ message.length > 300 ? (
+ <details className="group font-mono text-xs leading-5" key={message}>
+ <summary className="cursor-pointer break-words">
+ <span className="group-open:hidden">{message.slice(0, 300)}… </span>
+ <span className="underline underline-offset-4">Full message</span>
+ </summary>
+ <p className="mt-2 whitespace-pre-wrap break-words">{message}</p>
+ </details>
+ ) : (
+ <p
+ className="whitespace-pre-wrap break-words font-mono text-xs leading-5"
+ key={message}
+ >
+ {message}
+ </p>
+ )
+ )}
+ <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
+ {(Object.keys(details.context).length > 0 || types.length > 0) && (
+ <details className="text-xs text-foreground open:w-full">
+ <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
+ Technical details
+ </summary>
+ <dl className="mt-2 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">
+ {types.length > 0 && (
+ <>
+ <dt className="text-muted-foreground">Error type</dt>
+ <dd className="break-words font-mono">{types.join(" · ")}</dd>
+ </>
+ )}
+ {Object.entries(details.context).map(([key, value]) => (
+ <div className="contents" key={key}>
+ <dt className="break-all text-muted-foreground">{key}</dt>
+ <dd className="whitespace-pre-wrap break-all font-mono">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ </details>
+ )}
+ {stacks.map((stack, index) => (
+ <details className="text-xs text-foreground open:w-full" key={stack}>
+ <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
+ Stack trace{stacks.length > 1 ? ` ${index + 1}` : ""}
+ </summary>
+ <pre className="mt-2 whitespace-pre-wrap break-words font-mono">{stack}</pre>
+ </details>
+ ))}
+ </div>
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button aria-label="Copy error details" onClick={copy} size="icon-sm" variant="ghost">
+ {copied ? <Icon.success /> : <Icon.clipboard />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{copied ? "Copied" : "Copy error details"}</TooltipContent>
+ </Tooltip>
+ </Alert>
+ </section>
+ );
+}
diff --git a/frontend/src/components/traces/trace-inspector.test.tsx b/frontend/src/components/traces/trace-inspector.test.tsx
index 98dfa9ae..53d948c4 100644
--- a/frontend/src/components/traces/trace-inspector.test.tsx
+++ b/frontend/src/components/traces/trace-inspector.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { SpanRow } from "@/hooks/use-traces";
@@ -16,9 +16,11 @@ const root: SpanRow = {
evalMetrics: {},
evalScore: null,
events: [],
+ inputAttribute: null,
inputs: null,
model: null,
name: "Agent",
+ outputAttribute: null,
outputs: null,
parentSpanId: null,
policyOutcome: null,
@@ -55,7 +57,38 @@ describe("Trace inspector", () => {
</Fixture>
);
expect(screen.getAllByText("Not captured")).toHaveLength(1);
- expect(screen.getByText(value === "" ? '""' : JSON.stringify(value))).toBeTruthy();
+ const input = screen.getByRole("button", { name: "Collapse Input" }).closest("section");
+ expect(within(input!).getByText(value === "" ? '""' : JSON.stringify(value))).toBeTruthy();
+ });
+ it("lists payload attributes that Preview does not render as input or output", () => {
+ render(
+ <Fixture>
+ <SpanDetailView
+ span={{
+ ...root,
+ inputAttribute: "overmind.input",
+ inputs: "Rendered input",
+ spanAttributes: {
+ "gen_ai.input.messages": "Unrendered messages",
+ "overmind.input": "Rendered input",
+ },
+ }}
+ />
+ </Fixture>
+ );
+ expect(screen.getByText("gen_ai.input.messages")).toBeTruthy();
+ expect(screen.queryByText("overmind.input")).toBeNull();
+ });
+ it("renders events whose timestamp is not a valid time", () => {
+ render(
+ <Fixture>
+ <SpanDetailView
+ span={{ ...root, events: [{ name: "provider.retry", timeUnixNano: Number.MAX_VALUE }] }}
+ />
+ </Fixture>
+ );
+ expect(screen.getByText("provider.retry")).toBeTruthy();
+ expect(screen.queryByText("Time")).toBeNull();
});
it("shows content-block messages as text, with non-text blocks as JSON", () => {
const request = {
diff --git a/frontend/src/components/ui/icons/index.ts b/frontend/src/components/ui/icons/index.ts
index a31f5f89..4643e5d9 100644
--- a/frontend/src/components/ui/icons/index.ts
+++ b/frontend/src/components/ui/icons/index.ts
@@ -14,6 +14,7 @@ import {
OvermindEyeMono,
Chart as TitleChart,
} from "./page-title";
+import { PythonIcon } from "./python";
export const Icon = {
add: glyph("plus"),
@@ -105,6 +106,7 @@ export const Icon = {
play: glyph("play"),
project: glyph("box"),
projectAdd: glyph("box-plus"),
+ python: PythonIcon,
refresh: glyph("reload"),
search: glyph("search"),
send: glyph("send"),
diff --git a/frontend/src/components/ui/icons/python.tsx b/frontend/src/components/ui/icons/python.tsx
new file mode 100644
index 00000000..3cc66e6b
--- /dev/null
+++ b/frontend/src/components/ui/icons/python.tsx
@@ -0,0 +1,14 @@
+// Python mark from Simple Icons (CC0): https://github.com/simple-icons/simple-icons/blob/develop/icons/python.svg
+export function PythonIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ aria-hidden="true"
+ className={className}
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path d="M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02 1.27.05zm-6.3 1.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09 3.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14 1.04.05 1.23-.06 1.23-.16 1.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01 2.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01zm-6.47 14.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z" />
+ </svg>
+ );
+}
diff --git a/frontend/src/components/ui/list-toolbar.tsx b/frontend/src/components/ui/list-toolbar.tsx
index ef1e34e6..f5e6e4f8 100644
--- a/frontend/src/components/ui/list-toolbar.tsx
+++ b/frontend/src/components/ui/list-toolbar.tsx
@@ -34,17 +34,19 @@ export function useListShortcuts({
useEffect(() => {
const handler = (e: KeyboardEvent) => {
- if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (e.defaultPrevented || e.isComposing || e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key !== "/" && e.key !== "r" && e.key !== "c") return;
- // Never steal a keystroke from a field, or act on the list behind an open dialog.
+ // Only the active dialog's search may handle shortcuts over a covered list.
const target = e.target as HTMLElement | null;
if (target?.isContentEditable) return;
const tag = target?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
- if (document.querySelector('[role="dialog"][data-state="open"]')) return;
-
const current = latest.current;
+ const dialog = Array.from(document.querySelectorAll('[role="dialog"][data-state="open"]')).at(
+ -1
+ );
+ if (dialog && !dialog.contains(current.searchRef?.current ?? null)) return;
if (e.key === "/") {
const el = current.searchRef?.current;
if (!el) return;
diff --git a/frontend/src/hooks/use-traces.ts b/frontend/src/hooks/use-traces.ts
index 0d76ae2c..75b84d8f 100644
--- a/frontend/src/hooks/use-traces.ts
+++ b/frontend/src/hooks/use-traces.ts
@@ -2,7 +2,7 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query";
import apiClient from "@/client";
import { backoffPolling } from "@/lib/poll";
-import type { Span, TraceDetail, TracesListRequest } from "@/openapi";
+import type { Span, TraceDetail, TraceErrorDetails, TracesListRequest } from "@/openapi";
export function spanStatusLabel(statusCode: number): string {
if (statusCode === 2) return "error";
@@ -30,10 +30,13 @@ export interface SpanRow {
scopeName: string;
statusCode: number;
statusMessage: string;
+ errorDetails?: TraceErrorDetails | null;
durationNano: number;
startTimeUnixNano: number;
endTimeUnixNano: number;
spanAttributes: Record<string, unknown>;
+ inputAttribute: string | null;
+ outputAttribute: string | null;
inputs: unknown | null;
outputs: unknown | null;
events: SpanEvent[];
@@ -54,6 +57,13 @@ export interface SpanRow {
evalMetrics: unknown;
evalScore: number | null;
trajectoryScore: number | null;
+ trajectory?: {
+ score?: number | null;
+ span_count?: number;
+ passed?: boolean | null;
+ metrics?: unknown;
+ };
+ evalIntent?: string;
}
function evalBlock(evalAttributes: unknown): Record<string, unknown> {
@@ -164,12 +174,24 @@ const transformSpan = (span: Span): SpanRow => {
capabilityName,
durationNano,
endTimeUnixNano: endNano,
+ errorDetails: span.errorDetails,
+ evalIntent:
+ typeof evalBlock(span.evalAttributes).intent === "string"
+ ? (evalBlock(span.evalAttributes).intent as string)
+ : undefined,
evalMetrics: evalBlock(span.evalAttributes).metrics ?? null,
evalScore: finiteOrNull(evalBlock(span.evalAttributes).score),
- events: Array.isArray(span.events) ? (span.events as SpanEvent[]) : [],
+ events: Array.isArray(span.events)
+ ? span.events.map((event: SpanEvent & { time_unix_nano?: number }) => ({
+ ...event,
+ timeUnixNano: event.time_unix_nano ?? event.timeUnixNano,
+ }))
+ : [],
+ inputAttribute: span.inputAttribute,
inputs: span.inputAttribute ? (attrs[span.inputAttribute] ?? null) : null,
model: pickModel(attrs),
name: span.name ?? "",
+ outputAttribute: span.outputAttribute,
outputs: span.outputAttribute ? (attrs[span.outputAttribute] ?? null) : null,
parentSpanId: span.parentSpanId || null,
policyOutcome: (attrs.policy_outcome as string) ?? null,
@@ -194,6 +216,7 @@ const transformSpan = (span: Span): SpanRow => {
(promptTokens != null && completionTokens != null ? promptTokens + completionTokens : null),
traceId: span.traceId ?? "",
traceScores: extractTraceScores(span.evalAttributes),
+ trajectory: evalBlock(span.evalAttributes).trajectory as SpanRow["trajectory"],
trajectoryScore: extractTrajectoryScore(span.evalAttributes),
};
};
@@ -308,6 +331,7 @@ function mapTraceListRow(row: {
receivedAt?: Date | null;
startTimeNs?: number | null;
statusMessage?: string | null;
+ errorSummary?: string | null;
statusCode?: number | null;
capability?: string | null;
capabilityName?: string | null;
@@ -335,7 +359,10 @@ function mapTraceListRow(row: {
capabilityName: row.capabilityName ?? null,
createdAt,
durationNs: row.durationNs ?? undefined,
- error: row.statusCode === 2 ? statusMessage || "error" : null,
+ error:
+ row.statusCode === 2
+ ? row.errorSummary || statusMessage || "No error message captured"
+ : null,
evaluations: Object.keys(extractTraceScores(row.evalAttributes)).length,
model: row.model ?? null,
operation: row.operation ?? undefined,
diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILES
index 7ae266a3..724daf5b 100644
--- a/frontend/src/openapi/.openapi-generator/FILES
+++ b/frontend/src/openapi/.openapi-generator/FILES
@@ -82,6 +82,7 @@ models/CapabilityList.ts
models/CapabilityProposalMethodEnum.ts
models/CapabilityRequest.ts
models/CapabilityStatusEnum.ts
+models/CapturedError.ts
models/CatalogModel.ts
models/Cell.ts
models/CellStateEnum.ts
@@ -413,6 +414,7 @@ models/TiersEnum.ts
models/TokenObtainPair.ts
models/TokenObtainPairRequest.ts
models/TraceDetail.ts
+models/TraceErrorDetails.ts
models/TraceProviderEnum.ts
models/TraceStatusEnum.ts
models/TraceUsage.ts
diff --git a/frontend/src/openapi/models/CapturedError.ts b/frontend/src/openapi/models/CapturedError.ts
new file mode 100644
index 00000000..02f7ca28
--- /dev/null
+++ b/frontend/src/openapi/models/CapturedError.ts
@@ -0,0 +1,92 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+/**
+ *
+ * @export
+ * @interface CapturedError
+ */
+export interface CapturedError {
+ /**
+ *
+ * @type {string}
+ * @memberof CapturedError
+ */
+ source: string;
+ /**
+ *
+ * @type {string}
+ * @memberof CapturedError
+ */
+ type: string;
+ /**
+ *
+ * @type {string}
+ * @memberof CapturedError
+ */
+ message: string;
+ /**
+ *
+ * @type {string}
+ * @memberof CapturedError
+ */
+ stacktrace: string;
+}
+
+/**
+ * Check if a given object implements the CapturedError interface.
+ */
+export function instanceOfCapturedError(value: object): value is CapturedError {
+ if (!('source' in value) || value['source'] === undefined) return false;
+ if (!('type' in value) || value['type'] === undefined) return false;
+ if (!('message' in value) || value['message'] === undefined) return false;
+ if (!('stacktrace' in value) || value['stacktrace'] === undefined) return false;
+ return true;
+}
+
+export function CapturedErrorFromJSON(json: any): CapturedError {
+ return CapturedErrorFromJSONTyped(json, false);
+}
+
+export function CapturedErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): CapturedError {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'source': json['source'],
+ 'type': json['type'],
+ 'message': json['message'],
+ 'stacktrace': json['stacktrace'],
+ };
+}
+
+export function CapturedErrorToJSON(json: any): CapturedError {
+ return CapturedErrorToJSONTyped(json, false);
+}
+
+export function CapturedErrorToJSONTyped(value?: CapturedError | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'source': value['source'],
+ 'type': value['type'],
+ 'message': value['message'],
+ 'stacktrace': value['stacktrace'],
+ };
+}
diff --git a/frontend/src/openapi/models/RootSpanList.ts b/frontend/src/openapi/models/RootSpanList.ts
index 949b6ea1..32170e67 100644
--- a/frontend/src/openapi/models/RootSpanList.ts
+++ b/frontend/src/openapi/models/RootSpanList.ts
@@ -100,6 +100,12 @@ export interface RootSpanList {
* @memberof RootSpanList
*/
readonly statusMessage: string;
+ /**
+ *
+ * @type {string}
+ * @memberof RootSpanList
+ */
+ readonly errorSummary: string | null;
/**
*
* @type {number}
@@ -198,6 +204,7 @@ export function instanceOfRootSpanList(value: object): value is RootSpanList {
if (!('kind' in value) || value['kind'] === undefined) return false;
if (!('statusCode' in value) || value['statusCode'] === undefined) return false;
if (!('statusMessage' in value) || value['statusMessage'] === undefined) return false;
+ if (!('errorSummary' in value) || value['errorSummary'] === undefined) return false;
if (!('startTimeNs' in value) || value['startTimeNs'] === undefined) return false;
if (!('endTimeNs' in value) || value['endTimeNs'] === undefined) return false;
if (!('durationNs' in value) || value['durationNs'] === undefined) return false;
@@ -236,6 +243,7 @@ export function RootSpanListFromJSONTyped(json: any, ignoreDiscriminator: boolea
'kind': json['kind'],
'statusCode': json['status_code'],
'statusMessage': json['status_message'],
+ 'errorSummary': json['error_summary'],
'startTimeNs': json['start_time_ns'],
'endTimeNs': json['end_time_ns'],
'durationNs': json['duration_ns'],
@@ -256,7 +264,7 @@ export function RootSpanListToJSON(json: any): RootSpanList {
return RootSpanListToJSONTyped(json, false);
}
-export function RootSpanListToJSONTyped(value?: Omit<RootSpanList, 'trace_id'|'span_id'|'project'|'capability'|'capability_name'|'span_type'|'operation'|'name'|'service_name'|'kind'|'status_code'|'status_message'|'start_time_ns'|'end_time_ns'|'duration_ns'|'total_tokens'|'total_cost'|'cache_read_tokens'|'model'|'conversation'|'feedback_score'|'received_at'|'source'|'eval_attributes'|'trace_status'> | null, ignoreDiscriminator: boolean = false): any {
+export function RootSpanListToJSONTyped(value?: Omit<RootSpanList, 'trace_id'|'span_id'|'project'|'capability'|'capability_name'|'span_type'|'operation'|'name'|'service_name'|'kind'|'status_code'|'status_message'|'error_summary'|'start_time_ns'|'end_time_ns'|'duration_ns'|'total_tokens'|'total_cost'|'cache_read_tokens'|'model'|'conversation'|'feedback_score'|'received_at'|'source'|'eval_attributes'|'trace_status'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/Span.ts b/frontend/src/openapi/models/Span.ts
index e7c4cab2..6f00f306 100644
--- a/frontend/src/openapi/models/Span.ts
+++ b/frontend/src/openapi/models/Span.ts
@@ -13,6 +13,14 @@
*/
import { mapValues } from '../runtime';
+import type { TraceErrorDetails } from './TraceErrorDetails';
+import {
+ TraceErrorDetailsFromJSON,
+ TraceErrorDetailsFromJSONTyped,
+ TraceErrorDetailsToJSON,
+ TraceErrorDetailsToJSONTyped,
+} from './TraceErrorDetails';
+
/**
* Full span — used both for ``/api/traces/{trace_id}/`` (one span row in
* the per-trace list) and as the per-row representation for any span query.
@@ -104,6 +112,12 @@ export interface Span {
* @memberof Span
*/
readonly statusMessage: string;
+ /**
+ *
+ * @type {TraceErrorDetails}
+ * @memberof Span
+ */
+ readonly errorDetails: TraceErrorDetails | null;
/**
*
* @type {string}
@@ -208,6 +222,7 @@ export function instanceOfSpan(value: object): value is Span {
if (!('durationNs' in value) || value['durationNs'] === undefined) return false;
if (!('statusCode' in value) || value['statusCode'] === undefined) return false;
if (!('statusMessage' in value) || value['statusMessage'] === undefined) return false;
+ if (!('errorDetails' in value) || value['errorDetails'] === undefined) return false;
if (!('serviceName' in value) || value['serviceName'] === undefined) return false;
if (!('resourceAttrs' in value) || value['resourceAttrs'] === undefined) return false;
if (!('scopeName' in value) || value['scopeName'] === undefined) return false;
@@ -249,6 +264,7 @@ export function SpanFromJSONTyped(json: any, ignoreDiscriminator: boolean): Span
'durationNs': json['duration_ns'],
'statusCode': json['status_code'],
'statusMessage': json['status_message'],
+ 'errorDetails': TraceErrorDetailsFromJSON(json['error_details']),
'serviceName': json['service_name'],
'resourceAttrs': json['resource_attrs'],
'scopeName': json['scope_name'],
@@ -270,7 +286,7 @@ export function SpanToJSON(json: any): Span {
return SpanToJSONTyped(json, false);
}
-export function SpanToJSONTyped(value?: Omit<Span, 'span_id'|'trace_id'|'parent_span_id'|'is_root'|'project'|'span_type'|'operation'|'name'|'kind'|'start_time_ns'|'end_time_ns'|'duration_ns'|'status_code'|'status_message'|'service_name'|'resource_attrs'|'scope_name'|'scope_version'|'attributes'|'input_attribute'|'output_attribute'|'events'|'links'|'capability'|'conversation'|'feedback_score'|'eval_attributes'|'received_at'> | null, ignoreDiscriminator: boolean = false): any {
+export function SpanToJSONTyped(value?: Omit<Span, 'span_id'|'trace_id'|'parent_span_id'|'is_root'|'project'|'span_type'|'operation'|'name'|'kind'|'start_time_ns'|'end_time_ns'|'duration_ns'|'status_code'|'status_message'|'error_details'|'service_name'|'resource_attrs'|'scope_name'|'scope_version'|'attributes'|'input_attribute'|'output_attribute'|'events'|'links'|'capability'|'conversation'|'feedback_score'|'eval_attributes'|'received_at'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/TraceErrorDetails.ts b/frontend/src/openapi/models/TraceErrorDetails.ts
new file mode 100644
index 00000000..45dd73d7
--- /dev/null
+++ b/frontend/src/openapi/models/TraceErrorDetails.ts
@@ -0,0 +1,91 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+import type { CapturedError } from './CapturedError';
+import {
+ CapturedErrorFromJSON,
+ CapturedErrorFromJSONTyped,
+ CapturedErrorToJSON,
+ CapturedErrorToJSONTyped,
+} from './CapturedError';
+
+/**
+ *
+ * @export
+ * @interface TraceErrorDetails
+ */
+export interface TraceErrorDetails {
+ /**
+ *
+ * @type {string}
+ * @memberof TraceErrorDetails
+ */
+ summary: string;
+ /**
+ *
+ * @type {Array<CapturedError>}
+ * @memberof TraceErrorDetails
+ */
+ records: Array<CapturedError>;
+ /**
+ *
+ * @type {{ [key: string]: string; }}
+ * @memberof TraceErrorDetails
+ */
+ context: { [key: string]: string; };
+}
+
+/**
+ * Check if a given object implements the TraceErrorDetails interface.
+ */
+export function instanceOfTraceErrorDetails(value: object): value is TraceErrorDetails {
+ if (!('summary' in value) || value['summary'] === undefined) return false;
+ if (!('records' in value) || value['records'] === undefined) return false;
+ if (!('context' in value) || value['context'] === undefined) return false;
+ return true;
+}
+
+export function TraceErrorDetailsFromJSON(json: any): TraceErrorDetails {
+ return TraceErrorDetailsFromJSONTyped(json, false);
+}
+
+export function TraceErrorDetailsFromJSONTyped(json: any, ignoreDiscriminator: boolean): TraceErrorDetails {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'summary': json['summary'],
+ 'records': ((json['records'] as Array<any>).map(CapturedErrorFromJSON)),
+ 'context': json['context'],
+ };
+}
+
+export function TraceErrorDetailsToJSON(json: any): TraceErrorDetails {
+ return TraceErrorDetailsToJSONTyped(json, false);
+}
+
+export function TraceErrorDetailsToJSONTyped(value?: TraceErrorDetails | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'summary': value['summary'],
+ 'records': ((value['records'] as Array<any>).map(CapturedErrorToJSON)),
+ 'context': value['context'],
+ };
+}
diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.ts
index 95aee6d8..6065a267 100644
--- a/frontend/src/openapi/models/index.ts
+++ b/frontend/src/openapi/models/index.ts
@@ -40,6 +40,7 @@ export * from './CapabilityList';
export * from './CapabilityProposalMethodEnum';
export * from './CapabilityRequest';
export * from './CapabilityStatusEnum';
+export * from './CapturedError';
export * from './CatalogModel';
export * from './Cell';
export * from './CellStateEnum';
@@ -371,6 +372,7 @@ export * from './TiersEnum';
export * from './TokenObtainPair';
export * from './TokenObtainPairRequest';
export * from './TraceDetail';
+export * from './TraceErrorDetails';
export * from './TraceProviderEnum';
export * from './TraceStatusEnum';
export * from './TraceUsage';
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index 316481b7..0defd35c 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -52,6 +52,7 @@ from overbae.services.datasets.lifecycle import DatasetError
from overbae.services.deployment import deployment_progress
from overbae.services.model_activation import start_activation
from overbae.services.serving_context import evaluation_budget, serving_plan
+from overbae.services.trace_errors import captured_errors
from overbae.services.training_contract import (
baseline_evaluation_enabled,
contract,
@@ -757,6 +758,19 @@ class CapabilitySerializer(serializers.ModelSerializer):
return attrs
+class CapturedErrorSerializer(serializers.Serializer):
+ source = serializers.CharField()
+ type = serializers.CharField(allow_blank=True)
+ message = serializers.CharField(allow_blank=True)
+ stacktrace = serializers.CharField(allow_blank=True)
+
+
+class TraceErrorDetailsSerializer(serializers.Serializer):
+ summary = serializers.CharField()
+ records = CapturedErrorSerializer(many=True)
+ context = serializers.DictField(child=serializers.CharField())
+
+
class SpanSerializer(serializers.ModelSerializer):
"""Full span — used both for ``/api/traces/{trace_id}/`` (one span row in
the per-trace list) and as the per-row representation for any span query."""
@@ -764,6 +778,11 @@ class SpanSerializer(serializers.ModelSerializer):
is_root = serializers.BooleanField(read_only=True)
input_attribute = serializers.SerializerMethodField()
output_attribute = serializers.SerializerMethodField()
+ error_details = serializers.SerializerMethodField()
+
+ @extend_schema_field(TraceErrorDetailsSerializer(allow_null=True))
+ def get_error_details(self, obj):
+ return captured_errors(obj)
@extend_schema_field(serializers.CharField(allow_null=True))
def get_input_attribute(self, obj):
@@ -790,6 +809,7 @@ class SpanSerializer(serializers.ModelSerializer):
"duration_ns",
"status_code",
"status_message",
+ "error_details",
"service_name",
"resource_attrs",
"scope_name",
@@ -867,6 +887,12 @@ class RootSpanListSerializer(serializers.ModelSerializer):
)
source = serializers.SerializerMethodField()
trace_status = serializers.SerializerMethodField()
+ error_summary = serializers.SerializerMethodField()
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_error_summary(self, obj):
+ details = captured_errors(obj)
+ return details["summary"] if details else None
class Meta:
model = Span
@@ -883,6 +909,7 @@ class RootSpanListSerializer(serializers.ModelSerializer):
"kind",
"status_code",
"status_message",
+ "error_summary",
"start_time_ns",
"end_time_ns",
"duration_ns",
diff --git a/overbae/services/trace_errors.py b/overbae/services/trace_errors.py
new file mode 100644
index 00000000..9c7eea48
--- /dev/null
+++ b/overbae/services/trace_errors.py
@@ -0,0 +1,83 @@
+from overbae.models import Span
+
+
+def captured_errors(span: Span) -> dict | None:
+ if span.status_code != 2:
+ return None
+ attrs = span.attributes or {}
+ records = []
+
+ def text(value):
+ return value if isinstance(value, str) and value.strip() else ""
+
+ def first(*keys):
+ for key in keys:
+ value = attrs.get(key)
+ if isinstance(value, int) and not isinstance(value, bool):
+ return str(value)
+ if text(value):
+ return text(value)
+ return ""
+
+ def add(source, error_type="", message="", stacktrace=""):
+ record = {
+ "source": source,
+ "type": text(error_type),
+ "message": text(message),
+ "stacktrace": text(stacktrace),
+ }
+ if any(record[key] for key in ("type", "message", "stacktrace")):
+ records.append(record)
+
+ # Most specific first: the summary takes the first type and message it finds.
+ for prefix in ("error", "overmind.error", "exception"):
+ add(
+ "Attributes" if prefix == "error" else prefix,
+ attrs.get(f"{prefix}.type"),
+ attrs.get(f"{prefix}.message"),
+ attrs.get(f"{prefix}.stacktrace"),
+ )
+ for event in span.events or []:
+ if not isinstance(event, dict) or event.get("name") != "exception":
+ continue
+ event_attrs = event.get("attributes")
+ if not isinstance(event_attrs, dict):
+ continue
+ add(
+ "Exception event",
+ event_attrs.get("exception.type"),
+ event_attrs.get("exception.message"),
+ event_attrs.get("exception.stacktrace"),
+ )
+ add("Status", message=span.status_message)
+
+ context = {}
+ provider = first("gen_ai.provider.name", "genai.provider", "gen_ai.system")
+ if provider:
+ context["Provider"] = provider
+ http_status = first("http.response.status_code", "http.status_code")
+ if http_status:
+ context["HTTP status"] = http_status
+ for key in (
+ "http.request.method",
+ "url.full",
+ "http.url",
+ "server.address",
+ "anthropic.request.id",
+ "openai.request.id",
+ "gen_ai.response.id",
+ "http.response.request_id",
+ "request.id",
+ ):
+ if value := first(key):
+ context[key] = value
+
+ error_type = next((r["type"] for r in records if r["type"]), "")
+ message = next((r["message"] for r in records if r["message"]), "")
+ parts = [error_type]
+ if "HTTP status" in context:
+ parts.append(f"HTTP {context['HTTP status']}")
+ if message and message != error_type:
+ parts.append(message.splitlines()[0])
+ summary = " · ".join(part for part in parts if part) or "No error message captured"
+ return {"summary": summary, "records": records, "context": context}
diff --git a/tests/journeys/console/test_trace_errors.py b/tests/journeys/console/test_trace_errors.py
new file mode 100644
index 00000000..6205648f
--- /dev/null
+++ b/tests/journeys/console/test_trace_errors.py
@@ -0,0 +1,117 @@
+import uuid
+
+from django.utils import timezone
+from factories import make_span
+
+from overbae.models import Project
+
+
+def test_trace_errors_expose_captured_context_and_failed_children(console, workshop):
+ project = Project.objects.get(pk=workshop.project()["id"])
+ now = int(timezone.now().timestamp() * 1_000_000_000)
+ trace_id = uuid.uuid4().hex
+ root = make_span(
+ project,
+ trace_id=trace_id,
+ name="Recovered navigation",
+ start_ns=now,
+ end_time_ns=now + 3_000_000_000,
+ duration_ns=3_000_000_000,
+ eval_attributes={"score": None, "trajectory": {"score": None}},
+ )
+ message = "The requested model is unavailable"
+ stack = "Traceback (most recent call last):\n request()\nNotFoundError: unavailable"
+ make_span(
+ project,
+ trace_id=trace_id,
+ parent_span_id=root.span_id,
+ name="Provider request",
+ status_code=2,
+ start_ns=now + 1_000_000,
+ end_time_ns=now + 1_000_000_000,
+ duration_ns=999_000_000,
+ attributes={
+ "error.type": "not_found_error",
+ "http.response.status_code": 404,
+ "anthropic.request.id": "req_browser_fixture",
+ },
+ events=[
+ {
+ "name": "exception",
+ "attributes": {
+ "exception.type": "NotFoundError",
+ "exception.message": message,
+ "exception.stacktrace": stack,
+ },
+ }
+ ],
+ eval_attributes={"score": None},
+ )
+ console.goto(f"/observability/{trace_id}?projectId={project.pk}&view=roots&timeRange=all")
+ console.sees("1 failed span")
+ console._browser.call(lambda: console._page.get_by_role("tab", name="Tree", exact=True).click())
+ console._browser.call(lambda: console._page.keyboard.press("/"))
+ console.wait_until(
+ "() => document.activeElement?.getAttribute('aria-label') === 'Search spans'"
+ )
+ console.fill('input[aria-label="Search spans"]', "Provider")
+ console._browser.call(lambda: console._page.keyboard.press("/"))
+ assert (
+ console._browser.call(
+ lambda: console._page.get_by_role("searchbox", name="Search spans").input_value()
+ )
+ == "Provider/"
+ )
+ console.press("Clear search")
+ console.click("Provider request")
+ console.sees(message, exact=False)
+ console.click("Technical details")
+ console.sees("req_browser_fixture")
+ console.click("Stack trace")
+ console.sees(stack)
+ console._browser.call(
+ lambda: console._page.context.grant_permissions(["clipboard-read", "clipboard-write"])
+ )
+ console.press("Copy error details")
+ copied = console._browser.call(lambda: console._page.evaluate("navigator.clipboard.readText()"))
+ assert message in copied and stack in copied and "req_browser_fixture" in copied
+ console.save_evidence("trace-error-captured-details")
+
+ for label, attrs in [
+ (
+ "Attribute-only failure",
+ {"error.type": "not_found_error", "http.response.status_code": 404},
+ ),
+ ("Failure without details", {}),
+ ]:
+ trace_id = uuid.uuid4().hex
+ make_span(
+ project,
+ trace_id=trace_id,
+ name=label,
+ status_code=2,
+ start_ns=now,
+ attributes=attrs,
+ eval_attributes={"score": None, "trajectory": {"score": None}},
+ )
+ console.goto(f"/observability?projectId={project.pk}&view=roots&timeRange=all")
+ console.click(label)
+ console.sees("No error message captured")
+ console.save_evidence(f"trace-error-{label.lower().replace(' ', '-')}")
+ trace_id = uuid.uuid4().hex
+ long_message = "Navigation failed: " + "The previous frame was detached. " * 50
+ make_span(
+ project,
+ trace_id=trace_id,
+ name="Long captured error",
+ status_code=2,
+ start_ns=now,
+ attributes={"error.message": long_message},
+ eval_attributes={"score": None, "trajectory": {"score": None}},
+ )
+ console.goto(f"/observability/{trace_id}?projectId={project.pk}&view=roots&timeRange=all")
+ console.click("Full message")
+ console.sees(long_message, exact=False)
+ console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")
+ console.save_evidence("trace-error-long-message")
+ console.healthy()
diff --git a/tests/journeys/console/test_trace_inspection.py b/tests/journeys/console/test_trace_inspection.py
new file mode 100644
index 00000000..ada74c53
--- /dev/null
+++ b/tests/journeys/console/test_trace_inspection.py
@@ -0,0 +1,166 @@
+import uuid
+
+from django.utils import timezone
+from factories import make_span
+
+from overbae.models import Project
+
+from ..stack import drain
+
+
+def test_trace_scores_reveal_the_recorded_reason_and_span_context(console, workshop, worker):
+ project = Project.objects.get(pk=workshop.project()["id"])
+ trace_id = uuid.uuid4().hex
+ now = int(timezone.now().timestamp() * 1_000_000_000)
+ root = make_span(
+ project,
+ trace_id=trace_id,
+ name="Answer with sources",
+ start_ns=now,
+ attributes={"input": "Which cities are served?", "output": "San Francisco and Chicago."},
+ eval_attributes={
+ "score": 0.5,
+ "metrics": {
+ "Cites sources": {
+ "type": "llm",
+ "expectation": "Every city is supported by a source.",
+ "score": 0.5,
+ "verdict": "partial",
+ "reason": "Chicago has no supporting citation.",
+ },
+ "Tool selection": {
+ "type": "deterministic",
+ "score": None,
+ "verdict": "abstain",
+ "reason": "No tool calls were captured.",
+ },
+ "Provider check": {"type": "llm", "score": None, "error": "Judge unavailable"},
+ },
+ "trajectory": {
+ "score": 0.5,
+ "span_count": 2,
+ "passed": False,
+ "metrics": {
+ "outcome": {
+ "score": 0.5,
+ "expectation": "The agent achieves the intent.",
+ "reason": "The final answer is incomplete.",
+ }
+ },
+ },
+ },
+ )
+ make_span(
+ project,
+ trace_id=trace_id,
+ parent_span_id=root.span_id,
+ name="Uncaptured answer",
+ start_ns=now + 1_000,
+ eval_attributes={
+ "score": 0,
+ "metrics": {"Empty result": {"type": "deterministic", "score": 0}},
+ },
+ )
+ drain(worker)
+ console.goto(f"/observability/{trace_id}?projectId={project.pk}&timeRange=all")
+ console._browser.call(lambda: console._page.get_by_role("tab", name="Scores (4)").click())
+ console._browser.call(
+ lambda: console._page.get_by_role("button", name="Inspect score: Cites sources").press(
+ "Enter"
+ )
+ )
+ console.sees("Chicago has no supporting citation.")
+ console.sees("Every city is supported by a source.")
+ console.sees("San Francisco and Chicago.")
+ console.sees("Which cities are served?")
+ console.save_evidence("trace-score-evidence")
+ console.press("Inspect score: Cites sources")
+ console._browser.call(
+ lambda: console._page.get_by_text("Chicago has no supporting citation.").wait_for(
+ state="hidden"
+ )
+ )
+ console.press("Inspect score: Trajectory")
+ console.sees("The final answer is incomplete.")
+ console.press("Inspect score: Tool selection")
+ console.sees("No tool calls were captured.")
+ console.press("Inspect score: Provider check")
+ console.sees("Judge unavailable")
+ console.press("Expand Trace spans")
+ console.press("Uncaptured answer")
+ console._browser.call(lambda: console._page.get_by_role("tab", name="Scores (1)").click())
+ console.press("Inspect score: Empty result")
+ console.sees("0%")
+ console.sees("No explanation recorded")
+ console.sees("Not captured")
+ console.healthy()
+
+
+def test_trace_payloads_and_events_expand_without_losing_content(console, workshop, worker):
+ project = Project.objects.get(pk=workshop.project()["id"])
+ trace_id = uuid.uuid4().hex
+ now = int(timezone.now().timestamp() * 1_000_000_000)
+ long_text = "Keep the full instruction.\n" * 80 + "Final instruction marker"
+ stack = (
+ "Traceback (most recent call last):\n"
+ + " provider_request()\n" * 60
+ + "Final stack marker"
+ )
+ make_span(
+ project,
+ trace_id=trace_id,
+ name="Inspect structured evidence",
+ start_ns=now,
+ attributes={
+ "input": [{"role": "system", "content": long_text}],
+ "output": {"answer": False, "count": 0, "results": [{"city": "Chicago"}]},
+ },
+ events=[{"name": "provider.debug", "attributes": {"stacktrace": stack, "escaped": False}}],
+ eval_attributes={"score": None},
+ )
+ drain(worker)
+ console._browser.call(
+ lambda: console._page.add_init_script("localStorage.setItem('vite-ui-theme', 'light')")
+ )
+ console.goto(f"/observability/{trace_id}?projectId={project.pk}&timeRange=all")
+ console.press("Collapse Input")
+ console._browser.call(
+ lambda: console._page.get_by_text("Final instruction marker", exact=False).wait_for(
+ state="hidden"
+ )
+ )
+ console.press("Expand Input")
+ console.press("Expand System content")
+ console.sees(long_text)
+ assert console._browser.call(
+ lambda: console._page.get_by_role("button", name="Collapse System content").evaluate(
+ "button => button.getBoundingClientRect().bottom <= "
+ "document.getElementById(button.getAttribute('aria-controls')).getBoundingClientRect().top"
+ )
+ )
+ console.press("Collapse System content")
+ console.press("Expand System content")
+ console.sees("false")
+ console.sees("0")
+ console.sees('"Chicago"')
+ console._browser.call(
+ lambda: console._page.get_by_role("combobox", name="View format").nth(1).click()
+ )
+ console._browser.call(
+ lambda: console._page.get_by_role("option", name="Formatted", exact=True).click()
+ )
+ console.sees("Chicago")
+ assert (
+ console._browser.call(lambda: console._page.get_by_text("Item 1", exact=True).count()) == 0
+ )
+ console._browser.call(lambda: console._page.get_by_role("tab", name="Events (1)").click())
+ console.press("Expand stacktrace")
+ console.sees("Final stack marker")
+ console.press("Collapse provider.debug")
+ console._browser.call(
+ lambda: console._page.get_by_text("Final stack marker").wait_for(state="hidden")
+ )
+ console.press("Expand provider.debug")
+ console.press("Expand stacktrace")
+ console.save_evidence("trace-expandable-event")
+ console.healthy()
diff --git a/tests/test_trace_errors.py b/tests/test_trace_errors.py
new file mode 100644
index 00000000..0e34f4ca
--- /dev/null
+++ b/tests/test_trace_errors.py
@@ -0,0 +1,156 @@
+import base64
+import json
+import uuid
+
+import pytest
+from factories import api_key_client, make_member, make_project, make_span, make_user
+from google.protobuf.json_format import ParseDict
+from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
+
+pytestmark = pytest.mark.django_db
+
+
[email protected]("wire_format", ["json", "protobuf"])
+def test_captured_errors_survive_ingest_and_reach_trace_list_and_detail(wire_format):
+ project, user = make_project(), make_user()
+ make_member(user, project)
+ client = api_key_client(user, project)
+ trace_id, span_id = uuid.uuid4().hex, uuid.uuid4().hex[:16]
+ message = "Model unavailable\n" + "provider detail " * 100
+ stack = "Traceback (most recent call last):\n request()\nNotFoundError: model unavailable"
+ attrs = {
+ "error.type": "not_found_error",
+ "error.message": message,
+ "http.response.status_code": 404,
+ "gen_ai.provider.name": "anthropic",
+ "anthropic.request.id": "req_fixture",
+ }
+
+ def attributes(values):
+ return [
+ {"key": key, "value": {"intValue" if isinstance(value, int) else "stringValue": value}}
+ for key, value in values.items()
+ ]
+
+ export = {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": trace_id,
+ "spanId": span_id,
+ "name": "anthropic.messages.create",
+ "startTimeUnixNano": "1000",
+ "endTimeUnixNano": "2000",
+ "status": {"code": 2, "message": "Provider request failed"},
+ "attributes": attributes(attrs),
+ "events": [
+ {
+ "name": "exception",
+ "timeUnixNano": "1900",
+ "attributes": attributes(
+ {
+ "exception.type": "NotFoundError",
+ "exception.message": "The requested model is unavailable",
+ "exception.stacktrace": stack,
+ }
+ ),
+ }
+ ],
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ if wire_format == "protobuf":
+ # Protobuf JSON uses base64 IDs; OTLP JSON uses hex IDs.
+ span = export["resourceSpans"][0]["scopeSpans"][0]["spans"][0]
+ span["traceId"] = base64.b64encode(bytes.fromhex(trace_id)).decode()
+ span["spanId"] = base64.b64encode(bytes.fromhex(span_id)).decode()
+ body = ParseDict(export, ExportTraceServiceRequest()).SerializeToString()
+ content_type = "application/x-protobuf"
+ else:
+ body, content_type = json.dumps(export), "application/json"
+ response = client.post("/api/v1/traces", data=body, content_type=content_type)
+ assert response.status_code == 200, response.content
+ detail = client.get(f"/api/traces/{trace_id}/", {"project": str(project.pk)}).json()
+ [span] = detail["spans"]
+ assert span["status_message"] == "Provider request failed"
+ assert span["attributes"]["error.message"] == message
+ assert span["events"][0]["attributes"]["exception.stacktrace"] == stack
+ errors = span["error_details"]
+ assert errors["context"]["HTTP status"] == "404"
+ assert errors["context"]["anthropic.request.id"] == "req_fixture"
+ assert {record["message"] for record in errors["records"]} == {
+ message,
+ "Provider request failed",
+ "The requested model is unavailable",
+ }
+ assert any(record["stacktrace"] == stack for record in errors["records"])
+ [row] = client.get("/api/traces/", {"project": str(project.pk)}).json()["results"]
+ assert "404" in row["error_summary"]
+ assert "not_found_error" in row["error_summary"]
+ assert "Model unavailable" in row["error_summary"]
+
+
+ "attrs",
+ [
+ {"error.type": "not_found_error", "http.response.status_code": 404},
+ {
+ "error.type": "not_found_error",
+ "http.response.status_code": None,
+ "http.status_code": 404,
+ },
+ {},
+ ],
+)
+def test_errors_without_messages_use_captured_context_without_inventing_a_cause(attrs):
+ project, user = make_project(), make_user()
+ make_member(user, project)
+ trace_id = uuid.uuid4().hex
+ make_span(project, trace_id=trace_id, status_code=2, attributes=attrs)
+ client = api_key_client(user, project)
+ [span] = client.get(f"/api/traces/{trace_id}/").json()["spans"]
+ assert span["error_details"]["records"] == (
+ []
+ if not attrs
+ else [
+ {
+ "source": "Attributes",
+ "type": "not_found_error",
+ "message": "",
+ "stacktrace": "",
+ }
+ ]
+ )
+ assert span["error_details"]["summary"] == (
+ "not_found_error · HTTP 404" if attrs else "No error message captured"
+ )
+
+
+def test_spans_without_error_status_report_no_error_despite_http_status_or_exception_event():
+ project, user = make_project(), make_user()
+ make_member(user, project)
+ trace_id = uuid.uuid4().hex
+ make_span(
+ project,
+ trace_id=trace_id,
+ status_code=0,
+ attributes={"http.response.status_code": 404},
+ events=[
+ {
+ "name": "exception",
+ "attributes": {"exception.type": "NotFound", "exception.message": "No route"},
+ }
+ ],
+ )
+ client = api_key_client(user, project)
+ [span] = client.get(f"/api/traces/{trace_id}/").json()["spans"]
+ assert span["error_details"] is None
+ [row] = client.get("/api/traces/", {"project": str(project.pk)}).json()["results"]
+ assert row["error_summary"] is None