Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(trace): resolve the peeked observation off the tree (LFE-14992) (#16030)

Nikita Kabardine21bb4e14bc9
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.md
index 8633ce6d26..0e0b1ccb26 100644
--- a/.agents/skills/seed-test-data/SKILL.md
+++ b/.agents/skills/seed-test-data/SKILL.md
@@ -34,6 +34,7 @@ this.
| A realistic agent flow over a timeline (graph view + scrubbable timeline) | `pnpm run seed -- agent-timeline --turns 6 --v4` (LangGraph refine loop planner→retriever→generator→critic→loop, staggered in time; add `--timing-only` for the pure timing fallback) |
| A demo-grade, real-looking agent trace (videos, screenshots, docs) | `pnpm run seed -- support-agent --v4 --id-prefix <hex>` (one fixed, fully handcrafted support-copilot refund run: guardrails, parallel context fan-out, 3-turn ReAct loop with real payloads/costs; deterministic — reseed with a FRESH prefix for a clean take; the prefix is the trace id, so a hex prefix reads like production) |
| A plain trace with no agentic types (collapsed-by-default graph panel) | add `--plain` to `trace-tree` (SPAN/GENERATION/EVENT only) |
+| A trace with MORE observations than the detail view loads (v4 caps the tree at 10k, `startTime ASC` — the chronological tail is missing) | `pnpm run seed -- trace-tree --observations 12000 --stride-ms 10 --v4` (`--stride-ms` starts each observation index × N ms in, so start times are unique and strictly increasing: observation index < 10000 loads, `-obs-10000` and up fall past the cap. Without it thousands of rows share one millisecond and the boundary is arbitrary. Re-runs that CHANGE timing flags need a fresh `--id-prefix`: `start_time` is an events ORDER BY key, so both versions persist in the same trace) |
| An extremely DEEP single-chain trace (tree depth = observation count; layout stress) | `pnpm run seed -- deep-chain --v4` (1401 sequential generations, each the sole child of the previous — the mis-parented-instrumentation shape from LFE-10959 that collapses tree/timeline layouts; `--observations N` to change depth) |
| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |
| Diverse v4 session shapes (chat / coding-agent / mixed / media) for the session-detail view | `pnpm run seed -- session-shapes --shape all` (the `agent` shape has I/O on AGENT/TOOL with no GENERATION — pre-LFE-10520 the "first generation" default rendered empty cards for it; the current "All observations with I/O" default renders it correctly; v4 on by default) |
diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.md
index 6a5ee210b2..cbd33e46cd 100644
--- a/packages/shared/scripts/seeder/AGENTS.md
+++ b/packages/shared/scripts/seeder/AGENTS.md
@@ -11,6 +11,7 @@ pnpm run seed -- list # scenarios and flags (--json for machines)
pnpm run seed -- trace-tree --observations 5000 --breadth 500 --v4
pnpm run seed -- trace-tree --observations 12 --plain --v4 # SPAN/GENERATION/EVENT only (collapsed-by-default graph panel)
pnpm run seed -- trace-tree --observations 12 --v4 --tags "Zebra,apple,Ärger" # extra trace tags (alphabetical tag filter ordering)
+pnpm run seed -- trace-tree --observations 12000 --stride-ms 10 --v4 # more observations than the detail view loads; --stride-ms makes the startTime-ordered cap boundary exact (index < 10000 loads)
pnpm run seed -- deep-chain --v4 # 1401 sequential generations in ONE parent chain (depth = count; LFE-10959 layout stress)
pnpm run seed -- agent-timeline --turns 6 --v4 # realistic agent flow-with-loop over a timeline (graph view)
pnpm run seed -- support-agent --v4 --id-prefix <hex> # demo-grade handcrafted support-copilot run (videos/screenshots)
diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.ts
index 7ad296a66e..82247c099d 100644
--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts
+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts
@@ -149,6 +149,7 @@ const run = async (
// validator below enforces the >= 2 lower bound on the requested value)
const depth = Math.min(requestedDepth, observationCount);
const payloadBytes = params["payload-bytes"] as number;
+ const strideMs = params["stride-ms"] as number;
const payloadStyle = params["payload-style"] as PayloadStyle;
const withV4 = params["v4"] as boolean;
const asyncParents = params["async-parents"] as boolean;
@@ -197,6 +198,12 @@ const run = async (
"larger payloads exceed V8 string limits during generation",
);
}
+ if (strideMs < 0 || strideMs > 60_000) {
+ throw new SeedError(
+ `--stride-ms must be between 0 and 60000, got ${strideMs}`,
+ "pass e.g. --stride-ms 10 to spread starts one per 10ms",
+ );
+ }
if (scoresPerNode < 0 || scoresPerNode > 100) {
throw new SeedError(
`--scores-per-node must be between 0 and 100, got ${scoresPerNode}`,
@@ -294,6 +301,18 @@ const run = async (
10 +
jitter(ctx.seed, node.index, 80);
}
+ // --stride-ms: flat strictly-increasing starts (start = index × stride) instead
+ // of the nested timing. Default nesting puts thousands of rows on the same
+ // millisecond, so which of them fall past a startTime-ordered row cap
+ // (MAX_OBSERVATIONS_PER_TRACE) is arbitrary; a stride makes chronological order
+ // equal index order, so the boundary is exact and reproducible.
+ // parentIndex < index keeps "child starts after its parent" intact.
+ if (strideMs > 0) {
+ for (const node of shape) {
+ startOffsets[node.index] = node.index * strideMs;
+ }
+ }
+
const endOffsets = new Array<number>(shape.length).fill(0);
for (let i = shape.length - 1; i >= 0; i--) {
const node = shape[i];
@@ -704,6 +723,13 @@ export const traceTreeScenario: ScenarioDefinition = {
default: 25_000,
description: "approx bytes for the root input payload (max 50 MB)",
},
+ {
+ flag: "stride-ms",
+ type: "number",
+ default: 0,
+ description:
+ "start each observation index × N ms after the trace start (unique, strictly increasing start times — makes a startTime-ordered observation cap boundary exact); 0 keeps the nested timing",
+ },
{
flag: "payload-style",
type: "string",
diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
index 7ffc5b5117..bdfd3498e3 100644
--- a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
@@ -112,7 +112,10 @@ export function ObservationDetailView({
// for v4:
// is this observation topmost in tree? we don't check for root observation here as this is not necessarily given.
- // Uses the tree's roots array which handles orphans correctly
+ // Uses the tree's roots array which handles orphans correctly.
+ // Both stay absent/false for an observation outside the loaded (capped) list:
+ // subtree metrics and root-only chrome are tree facts we genuinely don't have,
+ // so they are omitted rather than guessed.
const treeNode = nodeMap.get(observation.id);
const isRoot = roots.some((root) => root.id === observation.id);
diff --git a/web/src/features/traces/components/TracePanelDetail.clienttest.tsx b/web/src/features/traces/components/TracePanelDetail.clienttest.tsx
new file mode 100644
index 0000000000..c2ccb1cea2
--- /dev/null
+++ b/web/src/features/traces/components/TracePanelDetail.clienttest.tsx
@@ -0,0 +1,109 @@
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { TracePanelDetail } from "@/src/features/traces/components/TracePanelDetail";
+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
+
+const { mockUseSelection, mockUseTraceData, mockByIdQuery } = vi.hoisted(
+ () => ({
+ mockUseSelection: vi.fn(),
+ mockUseTraceData: vi.fn(),
+ mockByIdQuery: vi.fn(),
+ }),
+);
+
+vi.mock("@/src/features/traces/contexts/SelectionContext", () => ({
+ useSelection: () => mockUseSelection(),
+}));
+vi.mock("@/src/features/traces/contexts/TraceDataContext", () => ({
+ useTraceData: () => mockUseTraceData(),
+}));
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ observations: {
+ byId: {
+ useQuery: (input: unknown, options: unknown) =>
+ mockByIdQuery(input, options),
+ },
+ },
+ },
+}));
+// The two detail views pull in the whole trace-detail subtree; the panel's only
+// job is picking between them.
+vi.mock(
+ "@/src/features/traces/components/TraceDetailView/TraceDetailView",
+ () => ({ TraceDetailView: () => <div data-testid="trace-detail" /> }),
+);
+vi.mock(
+ "@/src/features/traces/components/ObservationDetailView/ObservationDetailView",
+ () => ({
+ ObservationDetailView: ({
+ observation,
+ }: {
+ observation: ObservationReturnTypeWithMetadata;
+ }) => <div data-testid="observation-detail">{observation.id}</div>,
+ }),
+);
+
+const observation = (id: string) =>
+ ({
+ id,
+ traceId: "t",
+ startTime: new Date("2026-08-12T00:00:00.000Z"),
+ type: "SPAN",
+ }) as unknown as ObservationReturnTypeWithMetadata;
+
+describe("TracePanelDetail", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockByIdQuery.mockReturnValue({ data: undefined, error: null });
+ // The loaded list is capped, so it holds only "in-list" — and the tree built
+ // from it knows only that node plus the synthetic TRACE node.
+ mockUseTraceData.mockReturnValue({
+ trace: { id: "t", projectId: "p" },
+ observations: [observation("in-list")],
+ nodeMap: new Map([
+ ["in-list", { id: "in-list", type: "SPAN" }],
+ ["trace-t", { id: "trace-t", type: "TRACE" }],
+ ]),
+ serverScores: [],
+ corrections: [],
+ });
+ });
+
+ it("shows the selected observation even when it is outside the loaded list", () => {
+ // Regression: the panel used to decide "is an observation selected" from the
+ // tree's nodeMap, so an observation past the 10k cap silently rendered the
+ // TRACE detail instead.
+ mockUseSelection.mockReturnValue({ selectedNodeId: "past-cap" });
+ mockByIdQuery.mockReturnValue({ data: observation("past-cap") });
+
+ render(<TracePanelDetail />);
+
+ expect(screen.getByTestId("observation-detail")).toHaveTextContent(
+ "past-cap",
+ );
+ expect(screen.queryByTestId("trace-detail")).not.toBeInTheDocument();
+ });
+
+ it("says so for an unknown observation id rather than falling back to the trace", () => {
+ mockUseSelection.mockReturnValue({ selectedNodeId: "bogus" });
+ mockByIdQuery.mockReturnValue({
+ data: undefined,
+ error: { data: { code: "NOT_FOUND" } },
+ });
+
+ render(<TracePanelDetail />);
+
+ expect(screen.getByText("Observation not found")).toBeInTheDocument();
+ expect(screen.queryByTestId("trace-detail")).not.toBeInTheDocument();
+ });
+
+ it("shows the trace detail when the trace node is selected", () => {
+ mockUseSelection.mockReturnValue({ selectedNodeId: "trace-t" });
+
+ render(<TracePanelDetail />);
+
+ expect(screen.getByTestId("trace-detail")).toBeInTheDocument();
+ });
+});
diff --git a/web/src/features/traces/components/TracePanelDetail.tsx b/web/src/features/traces/components/TracePanelDetail.tsx
index 3ca8d61138..d8692ed574 100644
--- a/web/src/features/traces/components/TracePanelDetail.tsx
+++ b/web/src/features/traces/components/TracePanelDetail.tsx
@@ -7,7 +7,8 @@
*
* Hooks:
* - useSelection() - for selected node state
- * - useTraceData() - for trace, nodeMap, observations, scores
+ * - useTraceData() - for trace, observations, scores
+ * - useSelectedObservation() - resolves the selected observation off the tree
*
* Re-renders when:
* - Selection changes (clicking nodes)
@@ -17,61 +18,79 @@
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
+import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";
+import { Skeleton } from "@/src/components/ui/skeleton";
import { TraceDetailView } from "./TraceDetailView/TraceDetailView";
import { ObservationDetailView } from "./ObservationDetailView/ObservationDetailView";
import { useMemo } from "react";
+function PanelMessage({ title, body }: { title: string; body: string }) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-1 p-4 text-center">
+ <p className="text-sm font-bold">{title}</p>
+ <p className="text-muted-foreground max-w-sm text-sm">{body}</p>
+ </div>
+ );
+}
+
export function TracePanelDetail() {
const { selectedNodeId } = useSelection();
const {
trace,
- nodeMap,
observations,
serverScores: scores,
corrections,
} = useTraceData();
+ // Resolved from the selected id, not from the tree: the observation list is
+ // capped, so a selected observation may be missing from the tree while its
+ // data is perfectly fetchable.
+ const selected = useSelectedObservation({
+ selectedNodeId,
+ traceId: trace.id,
+ projectId: trace.projectId,
+ observations,
+ });
+
// Memoize to prevent recreation when deps haven't changed
const content = useMemo(() => {
- const selectedNode = selectedNodeId ? nodeMap.get(selectedNodeId) : null;
- const isObservationSelected =
- selectedNodeId !== null && selectedNode?.type !== "TRACE";
-
- if (isObservationSelected && selectedNode) {
- // Find the full observation data from observations array
- const observationData = observations.find(
- (obs) => obs.id === selectedNode.id,
- );
-
- if (!observationData) {
+ switch (selected.kind) {
+ case "observation":
return (
- <div className="flex h-full w-full items-center justify-center p-4">
- <p className="text-muted-foreground text-sm">
- Observation not found
- </p>
- </div>
+ <ObservationDetailView
+ observation={selected.observation}
+ projectId={trace.projectId}
+ traceId={trace.id}
+ />
+ );
+ case "loading":
+ return <Skeleton className="h-full w-full rounded-none" />;
+ case "not-found":
+ return (
+ <PanelMessage
+ title="Observation not found"
+ body="This observation is not part of this trace. It may have been deleted."
+ />
+ );
+ case "error":
+ return (
+ <PanelMessage
+ title="Could not load observation"
+ body="Loading this observation failed. Reload the page to try again."
+ />
+ );
+ case "trace":
+ return (
+ <TraceDetailView
+ trace={trace}
+ observations={observations}
+ scores={scores}
+ corrections={corrections}
+ projectId={trace.projectId}
+ />
);
- }
-
- return (
- <ObservationDetailView
- observation={observationData}
- projectId={trace.projectId}
- traceId={trace.id}
- />
- );
}
-
- return (
- <TraceDetailView
- trace={trace}
- observations={observations}
- scores={scores}
- corrections={corrections}
- projectId={trace.projectId}
- />
- );
- }, [selectedNodeId, nodeMap, trace, observations, scores, corrections]);
+ }, [selected, trace, observations, scores, corrections]);
return (
<div className="bg-background h-full w-full overflow-y-auto">{content}</div>
diff --git a/web/src/features/traces/fns/treeBuilding.ts b/web/src/features/traces/fns/treeBuilding.ts
index 31f8918e18..1aa5e88766 100644
--- a/web/src/features/traces/fns/treeBuilding.ts
+++ b/web/src/features/traces/fns/treeBuilding.ts
@@ -58,6 +58,14 @@ interface ProcessingNode {
subtreeMaxEndMs?: number;
}
+/**
+ * Id of the synthetic TRACE node (v3 traces wrap their observations in one).
+ * Selection state travels as a plain node id, so consumers need to recognise the
+ * trace node from the id alone — without a nodeMap lookup that a capped
+ * observation list can fail.
+ */
+export const traceNodeId = (traceId: string) => `trace-${traceId}`;
+
/**
* Returns observation levels at or above the minimum level.
*/
@@ -421,7 +429,7 @@ function buildTraceTree(
// Traditional traces: return TRACE node with no children
const emptyTree: TreeNode = {
- id: `trace-${trace.id}`,
+ id: traceNodeId(trace.id),
type: "TRACE",
name: trace.name ?? "",
startTime: trace.timestamp,
@@ -499,7 +507,7 @@ function buildTraceTree(
// Create trace root node
const traceNode: TreeNode = {
- id: `trace-${trace.id}`,
+ id: traceNodeId(trace.id),
type: "TRACE",
name: trace.name ?? "",
startTime: trace.timestamp,
diff --git a/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx b/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx
new file mode 100644
index 0000000000..cf1bdf19f4
--- /dev/null
+++ b/web/src/features/traces/hooks/useSelectedObservation.clienttest.tsx
@@ -0,0 +1,129 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";
+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
+
+const { mockByIdQuery } = vi.hoisted(() => ({ mockByIdQuery: vi.fn() }));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ observations: {
+ byId: {
+ useQuery: (input: unknown, options: unknown) =>
+ mockByIdQuery(input, options),
+ },
+ },
+ },
+}));
+
+const observation = (id: string) =>
+ ({
+ id,
+ traceId: "t",
+ startTime: new Date("2026-08-12T00:00:00.000Z"),
+ type: "SPAN",
+ }) as unknown as ObservationReturnTypeWithMetadata;
+
+const loaded = [observation("in-list")];
+
+const render = (selectedNodeId: string | null) =>
+ renderHook(() =>
+ useSelectedObservation({
+ selectedNodeId,
+ traceId: "t",
+ projectId: "p",
+ observations: loaded,
+ }),
+ ).result.current;
+
+const queryEnabled = () => mockByIdQuery.mock.calls[0]?.[1]?.enabled;
+
+describe("useSelectedObservation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockByIdQuery.mockReturnValue({ data: undefined, error: null });
+ });
+
+ it("resolves an observation outside the loaded list by id instead of falling back to the trace", () => {
+ // The tree's observation list is capped, so nodeMap/observations miss the
+ // chronological tail — the panel must still show that observation.
+ mockByIdQuery.mockReturnValue({
+ data: { ...observation("past-cap"), traceId: null },
+ error: null,
+ });
+
+ const result = render("past-cap");
+
+ expect(result).toMatchObject({
+ kind: "observation",
+ isOutsideLoadedList: true,
+ });
+ expect(queryEnabled()).toBe(true);
+ // traceId is nullable on the by-id row; the fetch was scoped to this trace.
+ expect(
+ result.kind === "observation" ? result.observation.traceId : null,
+ ).toBe("t");
+ });
+
+ it("serves a loaded observation from the list without firing a request", () => {
+ const result = render("in-list");
+
+ expect(result).toEqual({
+ kind: "observation",
+ observation: loaded[0],
+ isOutsideLoadedList: false,
+ });
+ expect(queryEnabled()).toBe(false);
+ });
+
+ it.each([null, "trace-t"])(
+ "treats %s as the trace selection and fires no request",
+ (selectedNodeId) => {
+ expect(render(selectedNodeId)).toEqual({ kind: "trace" });
+ expect(queryEnabled()).toBe(false);
+ },
+ );
+
+ it("prefers a real observation over the trace-node id shape", () => {
+ // Observation ids are caller-supplied, so an observation can genuinely be
+ // named `trace-<traceId>`; a loaded row is the stronger evidence.
+ const collided = [observation("trace-t")];
+ const result = renderHook(() =>
+ useSelectedObservation({
+ selectedNodeId: "trace-t",
+ traceId: "t",
+ projectId: "p",
+ observations: collided,
+ }),
+ ).result.current;
+
+ expect(result).toMatchObject({ kind: "observation" });
+ });
+
+ it.each([
+ {
+ name: "NOT_FOUND",
+ error: { data: { code: "NOT_FOUND" } },
+ kind: "not-found",
+ },
+ // A transient failure must not be reported as a deleted observation.
+ {
+ name: "a server error",
+ error: { data: { code: "INTERNAL_SERVER_ERROR" } },
+ kind: "error",
+ },
+ // Transport-level failures carry no `data.code` at all; keying on the code
+ // alone left the panel waiting on a skeleton forever.
+ {
+ name: "a transport failure",
+ error: { message: "fetch failed" },
+ kind: "error",
+ },
+ { name: "an in-flight fetch", error: null, kind: "loading" },
+ ])("reports $name as $kind", ({ error, kind }) => {
+ mockByIdQuery.mockReturnValue({ data: undefined, error });
+
+ expect(render("past-cap")).toEqual({ kind, observationId: "past-cap" });
+ });
+});
diff --git a/web/src/features/traces/hooks/useSelectedObservation.ts b/web/src/features/traces/hooks/useSelectedObservation.ts
new file mode 100644
index 0000000000..2a519288fa
--- /dev/null
+++ b/web/src/features/traces/hooks/useSelectedObservation.ts
@@ -0,0 +1,118 @@
+/**
+ * useSelectedObservation - resolves the selected node WITHOUT the trace tree.
+ *
+ * The trace's observation list is capped (MAX_OBSERVATIONS_PER_TRACE), so an
+ * observation can be selectable (peek/deep link from the observations table)
+ * while being absent from the loaded list — and therefore from the tree and its
+ * nodeMap. Tree drawability must not decide what the data panel shows, so the
+ * row is resolved from the loaded list when present (fast path, no extra
+ * request) and fetched by id otherwise.
+ */
+
+import { useMemo } from "react";
+import { api } from "@/src/utils/api";
+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
+import { traceNodeId } from "@/src/features/traces/fns/treeBuilding";
+
+export type SelectedObservation =
+ | { kind: "trace" }
+ | { kind: "loading"; observationId: string }
+ | { kind: "not-found"; observationId: string }
+ | { kind: "error"; observationId: string }
+ | {
+ kind: "observation";
+ observation: ObservationReturnTypeWithMetadata;
+ /** Resolved by id: the row is outside the loaded (capped) list. */
+ isOutsideLoadedList: boolean;
+ };
+
+export function useSelectedObservation({
+ selectedNodeId,
+ traceId,
+ projectId,
+ observations,
+}: {
+ selectedNodeId: string | null;
+ traceId: string;
+ projectId: string;
+ observations: ObservationReturnTypeWithMetadata[];
+}): SelectedObservation {
+ // A loaded row wins over the synthetic trace-node id shape: observation ids
+ // are caller-supplied, so an observation really can be called
+ // `trace-<traceId>`, and a real row is the stronger evidence.
+ const loadedRow = useMemo(
+ () =>
+ selectedNodeId
+ ? observations.find((obs) => obs.id === selectedNodeId)
+ : undefined,
+ [observations, selectedNodeId],
+ );
+
+ // Otherwise derived from the id alone, never from a nodeMap hit: past the cap
+ // the lookup misses, and reading that as "the trace is selected" is the bug
+ // this hook fixes.
+ //
+ // The id shape stays the tiebreaker for an id NOT in the list, which trades
+ // two edge cases against each other: a v3-dialect URL (`observation=trace-<id>`)
+ // opened against a v4 trace, which has no TRACE node to match, still resolves
+ // to the trace — at the price of an observation deliberately NAMED
+ // `trace-<its own trace id>` and sitting past the cap showing the trace
+ // instead. Cross-dialect links are a real, documented case
+ // (resolvePeekTraceParams); that naming collision is not.
+ const observationId =
+ !selectedNodeId || (!loadedRow && selectedNodeId === traceNodeId(traceId))
+ ? null
+ : selectedNodeId;
+
+ // `compact` keeps this row lean — the detail view fetches full I/O separately
+ // (useParsedObservation) once it has the row.
+ const byId = api.observations.byId.useQuery(
+ {
+ observationId: observationId ?? "",
+ traceId,
+ projectId,
+ verbosity: "compact",
+ },
+ {
+ enabled: !!observationId && !loadedRow,
+ staleTime: 5 * 60 * 1000,
+ // The panel renders the missing-observation state itself; a global error
+ // toast on top of it would just be alarming noise.
+ meta: { silentHttpCodes: [404] },
+ },
+ );
+
+ // Transport-level failures (proxy error page, dropped connection, a body that
+ // is not JSON) carry no `data.code`, so the presence of an error — not its
+ // code — is what ends the wait. Keying on the code alone left the panel on a
+ // skeleton forever.
+ const hasError = !!byId.error;
+ const isNotFound = byId.error?.data?.code === "NOT_FOUND";
+
+ return useMemo(() => {
+ if (!observationId) return { kind: "trace" };
+ if (loadedRow)
+ return {
+ kind: "observation",
+ observation: loadedRow,
+ isOutsideLoadedList: false,
+ };
+ if (byId.data)
+ return {
+ kind: "observation",
+ // traceId is nullable on the by-id row; the fetch was scoped to this
+ // trace, so the selected observation belongs to it by construction.
+ observation: { ...byId.data, traceId: byId.data.traceId ?? traceId },
+ isOutsideLoadedList: true,
+ };
+ // A transient failure is not a missing observation — mislabeling it would
+ // repeat the class of bug this hook exists to fix.
+ if (hasError) {
+ return {
+ kind: isNotFound ? "not-found" : "error",
+ observationId,
+ };
+ }
+ return { kind: "loading", observationId };
+ }, [observationId, loadedRow, byId.data, hasError, isNotFound, traceId]);
+}