Skip to content

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

fix(sessions): Improve session trace and thread headers (#19103)

Ben Bachemf1b12d06c5fb
diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.ts
index e0789f2c51..f79db8056b 100644
--- a/packages/shared/scripts/seeder/scenarios/index.ts
+++ b/packages/shared/scripts/seeder/scenarios/index.ts
@@ -12,6 +12,7 @@ import { manyTracesScenario } from "./many-traces";
import { outlierTrafficScenario } from "./outlier-traffic";
import { scoredTracesScenario } from "./scored-traces";
import { sessionShapesScenario } from "./session-shapes";
+import { sessionThreadsScenario } from "./session-threads";
import { sessionVarietyScenario } from "./session-variety";
import { supportAgentScenario } from "./support-agent";
import { timelineAnnotatedScenario } from "./timeline-annotated";
@@ -36,6 +37,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {
"outlier-traffic": outlierTrafficScenario,
"scored-traces": scoredTracesScenario,
"session-shapes": sessionShapesScenario,
+ "session-threads": sessionThreadsScenario,
"session-variety": sessionVarietyScenario,
"annotation-queue": annotationQueueScenario,
"custom-models": customModelsScenario,
diff --git a/packages/shared/scripts/seeder/scenarios/session-threads.ts b/packages/shared/scripts/seeder/scenarios/session-threads.ts
new file mode 100644
index 0000000000..d23d08d17e
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/session-threads.ts
@@ -0,0 +1,242 @@
+import { prisma } from "../../../src/db";
+import {
+ createTrace,
+ createObservation,
+ createTracesCh,
+ createObservationsCh,
+ createEventsCh,
+ type TraceRecordInsertType,
+ type ObservationRecordInsertType,
+} from "../../../src/server";
+import { assembleTranscript } from "../../../src/server/transcript/transcript";
+import { orderObservations } from "../../../src/server/transcript/ordering";
+import { observationToEvent, traceToEvent } from "./event-mirror";
+import { type ScenarioDefinition, SeedError } from "./types";
+import { countRows, sessionLink } from "./verify";
+import { utcDayStartMs } from "./rng";
+
+export const sessionThreadsScenario: ScenarioDefinition = {
+ name: "session-threads",
+ description:
+ "Session header fixtures: single-thread traces, multi-thread traces, and both in one session. Verifies visible thread counts before writing.",
+ supportsV4: true,
+ flags: [
+ {
+ flag: "v4",
+ type: "boolean",
+ default: true,
+ description: "mirror observations into v4 events tables",
+ },
+ ],
+ run: async (ctx, params) => {
+ const startedAt = Date.now();
+ const sessions = [
+ {
+ shape: "single",
+ traces: [
+ { name: "Answer order status question", threadCount: 1 },
+ { name: "Confirm delivery date", threadCount: 1 },
+ ],
+ },
+ {
+ shape: "multiple",
+ traces: [
+ { name: "Compare travel options", threadCount: 2 },
+ { name: "Build weekend itinerary", threadCount: 3 },
+ ],
+ },
+ {
+ shape: "mixed",
+ traces: [
+ { name: "Triage billing issue", threadCount: 1 },
+ { name: "Investigate duplicate charge", threadCount: 2 },
+ { name: "Explain refund policy", threadCount: 1 },
+ { name: "Resolve billing dispute", threadCount: 3 },
+ ],
+ },
+ ];
+ const sessionIds = sessions.map(({ shape }) => `${ctx.idPrefix}-${shape}`);
+ const traces: TraceRecordInsertType[] = [];
+ const observations: ObservationRecordInsertType[] = [];
+ const threadCounts: Record<string, number> = {};
+ const sessionStart = utcDayStartMs() - 30 * 60 * 1000;
+
+ for (const [sessionIndex, session] of sessions.entries()) {
+ const sessionId = sessionIds[sessionIndex]!;
+ for (const [
+ traceIndex,
+ { name, threadCount },
+ ] of session.traces.entries()) {
+ const traceId = `${sessionId}-trace-${traceIndex + 1}`;
+ const timestamp = sessionStart + traceIndex * 60_000;
+ const trace = createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ session_id: sessionId,
+ timestamp,
+ name,
+ user_id: `user-${ctx.idPrefix}`,
+ release: null,
+ version: null,
+ tags: ["seed", "session-threads", session.shape],
+ public: false,
+ bookmarked: false,
+ metadata: {
+ scenario: "session-threads",
+ threads: String(threadCount),
+ },
+ input: null,
+ output: null,
+ created_at: startedAt,
+ updated_at: startedAt,
+ event_ts: startedAt,
+ });
+ traces.push(trace);
+
+ // No replayed history: each generation starts an independent thread.
+ // Root generations keep every thread visible when nested ones are hidden.
+ const generations = Array.from({ length: threadCount }, (_, index) => {
+ const input = [
+ {
+ role: "user",
+ content: `For ${traceId}, independently summarize topic ${index + 1}.`,
+ },
+ ];
+ const output = [
+ {
+ role: "assistant",
+ content: `Topic ${index + 1}: this is conversation ${index + 1} of ${threadCount} in this trace.`,
+ },
+ ];
+ const startTime = timestamp + index * 2000;
+ const name = `independent-conversation-${index + 1}`;
+ const observation = createObservation({
+ id: `${traceId}-generation-${index + 1}`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: "GENERATION",
+ parent_observation_id: null,
+ name,
+ start_time: startTime,
+ end_time: startTime + 1000,
+ completion_start_time: startTime + 200,
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: JSON.stringify(input),
+ output: JSON.stringify(output),
+ metadata: { scenario: "session-threads" },
+ provided_model_name: "gpt-5.4",
+ internal_model_id: null,
+ model_parameters: "{}",
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ total_cost: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: startedAt,
+ updated_at: startedAt,
+ event_ts: startedAt,
+ });
+ observations.push(observation);
+ return {
+ id: observation.id,
+ traceId,
+ parentObservationId: null,
+ type: "GENERATION" as const,
+ name,
+ startTime: new Date(startTime),
+ endTime: new Date(startTime + 1000),
+ input,
+ output,
+ metadata: {},
+ };
+ });
+ const transcript = assembleTranscript(orderObservations(generations));
+ const visibleThreads = transcript?.threads.filter(
+ ({ currentTurn }) => currentTurn.nestingLevel === 0,
+ );
+ if (visibleThreads?.length !== threadCount) {
+ throw new SeedError(
+ `${traceId}: expected ${threadCount} visible threads, got ${visibleThreads?.length ?? 0}`,
+ );
+ }
+ threadCounts[traceId] = visibleThreads.length;
+ }
+ }
+
+ const events = [];
+ if (params["v4"]) {
+ events.push(...traces.map(traceToEvent));
+ for (const observation of observations) {
+ const trace = traces.find(({ id }) => id === observation.trace_id)!;
+ events.push(observationToEvent(observation, trace));
+ }
+ }
+ const verified: Record<string, number> = {};
+ if (!ctx.dryRun) {
+ // Session detail routes also require the Postgres session row.
+ for (const sessionId of sessionIds) {
+ await prisma.traceSession.upsert({
+ where: { id_projectId: { id: sessionId, projectId: ctx.projectId } },
+ update: {},
+ create: {
+ id: sessionId,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ createdAt: new Date(sessionStart),
+ },
+ });
+ }
+ await createTracesCh(traces);
+ await createObservationsCh(observations);
+ if (events.length > 0) await createEventsCh(events);
+ for (const [table, expected, column] of [
+ ["traces", traces.length, "id"],
+ ["observations", observations.length, "id"],
+ ["events_full", events.length, "span_id"],
+ ] as const) {
+ if (table === "events_full" && !params["v4"]) continue;
+ const actual = await countRows(
+ table,
+ `project_id = {projectId: String} AND ${table === "traces" ? "id" : "trace_id"} IN {traceIds: Array(String)}`,
+ { projectId: ctx.projectId, traceIds: traces.map(({ id }) => id) },
+ `uniqExact(${column})`,
+ );
+ verified[table] = actual;
+ if (actual < expected) {
+ throw new SeedError(
+ `${table}: expected ${expected} rows, got ${actual}`,
+ );
+ }
+ }
+ }
+ ctx.log(
+ `Verified visible threads per trace: ${JSON.stringify(threadCounts)}`,
+ );
+ return {
+ scenario: "session-threads",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: traces.map(({ id }) => id),
+ sessionIds,
+ counts: {
+ sessions: sessionIds.length,
+ traces: traces.length,
+ observations: observations.length,
+ events: events.length,
+ },
+ verified,
+ links: sessionIds.map((id) => sessionLink(ctx, id)),
+ dryRun: ctx.dryRun,
+ durationMs: Date.now() - startedAt,
+ };
+ },
+};
diff --git a/scripts/seed-example-sessions.sh b/scripts/seed-example-sessions.sh
new file mode 100644
index 0000000000..105b373de1
--- /dev/null
+++ b/scripts/seed-example-sessions.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Uses the repo-root .env through the existing seed CLI.
+# Extra arguments (e.g. --project <id> or --dry-run) go to each invocation.
+repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+id_prefix="session-header-examples-$(date +%Y%m%d-%H%M%S)-$$"
+
+pnpm --dir "$repo_root" run seed -- session-threads \
+ --id-prefix "$id_prefix" \
+ "$@"
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
index de606a4826..f1f64a3ddb 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx
@@ -2586,80 +2586,40 @@ const navigationTraces: TraceProps[] = Array.from(
},
);
-function viewportAnchor(feed: HTMLElement) {
- const maxOffset = Math.max(0, feed.scrollHeight - feed.clientHeight);
- const transition = Math.min(feed.clientHeight * 0.2, maxOffset);
- const inset = Math.max(
- 0,
- Math.min(
- feed.clientHeight * 0.2,
- feed.clientHeight - 1,
- feed.scrollHeight - 1,
- ),
- );
- if (transition === 0) return inset;
- const progress = Math.max(0, 1 - (maxOffset - feed.scrollTop) / transition);
- return inset + (feed.clientHeight - 1 - inset) * progress;
-}
-
async function expectNavigation(
canvasElement: HTMLElement,
- headerName: string | RegExp,
+ headerName: string,
itemId: string,
rowId: string | false,
) {
const canvas = within(canvasElement);
const sidebar = within(canvas.getByRole("complementary"));
const feed = canvas.getByLabelText("Session conversation timeline");
- await expect(
- sidebar.getByRole("button", { name: headerName }),
- ).toHaveAttribute("aria-current", "true");
- const assertGeometry = () => {
- const entry = feed.querySelector<HTMLElement>(
- `[data-session-item-id="${itemId}"]`,
- );
- const target = rowId
- ? entry?.querySelector<HTMLElement>(
- `[data-session-transcript-row-id="${rowId}"]`,
- )
- : entry?.closest<HTMLElement>("[data-index]");
- if (!target) throw new Error(`Target ${itemId} is not mounted`);
- const position =
- target.getBoundingClientRect().top -
- feed.getBoundingClientRect().top -
- feed.clientTop;
- const anchor = viewportAnchor(feed);
- const inset = feed.clientHeight * 0.2;
- const roundingTolerance =
- anchor === inset
- ? 2
- : 2 +
- (feed.clientHeight - 1 - inset) /
- Math.min(
- feed.clientHeight * 0.2,
- feed.scrollHeight - feed.clientHeight,
- );
- // The first entry cannot acquire an inset by scrolling before offset zero.
- const expectedAnchor =
- feed.scrollTop === 0 && position >= 0 && position < inset
- ? position
- : anchor;
- expect(Math.abs(position - expectedAnchor)).toBeLessThanOrEqual(
- roundingTolerance,
- );
- };
- await waitFor(assertGeometry, { timeout: 6_000 });
- await new Promise((resolve) => window.setTimeout(resolve, 200));
- assertGeometry();
- // A zero-distance user intent removes any navigation override: geometry must
- // independently yield the same active entry through the manual scroll spy.
- feed.dispatchEvent(new WheelEvent("wheel", { bubbles: true }));
await waitFor(() =>
expect(sidebar.getByRole("button", { name: headerName })).toHaveAttribute(
"aria-current",
"true",
),
);
+ await waitFor(
+ () => {
+ const entry = feed.querySelector<HTMLElement>(
+ `[data-session-item-id="${itemId}"]`,
+ );
+ const target = rowId
+ ? entry?.querySelector<HTMLElement>(
+ `[data-session-transcript-row-id="${rowId}"]`,
+ )
+ : entry;
+ if (!target) throw new Error(`Target ${itemId} is not mounted`);
+ const bounds = target.getBoundingClientRect();
+ const viewport = feed.getBoundingClientRect();
+ expect(bounds.height).toBeGreaterThan(0);
+ expect(bounds.bottom).toBeGreaterThan(viewport.top);
+ expect(bounds.top).toBeLessThan(viewport.bottom);
+ },
+ { timeout: 6_000 },
+ );
}
const meta = preview.meta({
@@ -2677,7 +2637,9 @@ export const MixedToolContent = meta.story({
canvas.getByLabelText("Session conversation timeline"),
);
await userEvent.click(
- await timeline.findByRole("button", { name: /^Show tools:/ }),
+ await timeline.findByRole("button", {
+ name: (name) => name.startsWith("Show tools:"),
+ }),
);
for (const { name } of toolContentExamples) {
await userEvent.click(
@@ -2687,20 +2649,27 @@ export const MixedToolContent = meta.story({
await expect(
timeline.getByText("Monthly revenue increased."),
).toBeVisible();
- await expect(timeline.getByText(/monthly-revenue/)).toBeVisible();
- await expect(timeline.getByText(/chart-annotations/)).toBeVisible();
await expect(
- timeline.getByText(/chart-annotations/).closest("pre"),
+ timeline.getByText((text) => text.includes("monthly-revenue")),
+ ).toBeVisible();
+ await expect(
+ timeline.getByText((text) => text.includes("chart-annotations")),
+ ).toBeVisible();
+ await expect(
+ canvas.getByLabelText("Session conversation timeline"),
).toHaveTextContent("vendor-chart");
await expect(
timeline.getByText("Monthly revenue chart generated."),
).toBeVisible();
- await expect(timeline.getByText(/mixed-revenue/)).toBeVisible();
await expect(
- timeline.getByText(/mixed-revenue/).closest("pre"),
+ timeline.getByText((text) => text.includes("mixed-revenue")),
+ ).toBeVisible();
+ await expect(
+ canvas.getByLabelText("Session conversation timeline"),
).toHaveTextContent("points");
const images = timeline.getAllByRole<HTMLImageElement>("img", {
- name: /Embedded image|revenue.svg/,
+ name: (name) =>
+ name.includes("Embedded image") || name.includes("revenue.svg"),
});
await expect(images).toHaveLength(4);
for (const image of images) await expect(image).toBeVisible();
@@ -2709,10 +2678,9 @@ export const MixedToolContent = meta.story({
await expect(image.naturalWidth).toBeGreaterThan(0);
}
});
- await expect(timeline.getByText(/chart-revenue/)).toBeVisible();
await expect(
- timeline.getByText(/chart-revenue/).closest("pre"),
- ).toHaveTextContent("vendor-chart");
+ timeline.getByText((text) => text.includes("chart-revenue")),
+ ).toBeVisible();
await expect(timeline.queryByRole("note")).not.toBeInTheDocument();
for (const label of [
"revenue.svg",
@@ -2932,68 +2900,44 @@ export const ManualScrollSynchronization = meta.story({
const feed = canvas.getByLabelText("Session conversation timeline");
const sidebar = within(canvas.getByRole("complementary"));
const initialPageScroll = window.scrollY;
- const assertVisibleActive = async () => {
- await waitFor(
- () => {
- const anchor =
- feed.getBoundingClientRect().top +
- feed.clientTop +
- viewportAnchor(feed);
- const entry = Array.from(
- feed.querySelectorAll<HTMLElement>("[data-session-item-id]"),
- ).find((element) => {
- const rect = element
- .closest<HTMLElement>("[data-index]")!
- .getBoundingClientRect();
- return rect.top <= anchor && rect.bottom > anchor;
- });
- if (!entry)
- throw new Error("No entry contains the scroll-spy anchor");
- const [traceId, threadIndex] =
- entry.dataset.sessionItemId!.split(":");
- const turn = Number(traceId!.replace("scroll-turn-", ""));
- const thread = threadIndex === "0" ? 1 : 2;
- expect(
- sidebar.getByRole("button", {
- name: (name) =>
- name.startsWith(`${turn}.${thread} Navigation turn ${turn}`),
- }),
- ).toHaveAttribute("aria-current", "true");
- },
- { timeout: 3_000 },
- );
- };
- await assertVisibleActive();
- for (const top of [180, 450, 900, 1_500, 900, 450, 180, 0]) {
- feed.scrollTo({ top, behavior: "instant" });
- await assertVisibleActive();
- }
- const secondEntry = feed
- .querySelector<HTMLElement>('[data-session-item-id="scroll-turn-1:2"]')!
- .closest<HTMLElement>("[data-index]")!;
- const boundary =
- secondEntry.getBoundingClientRect().top -
- feed.getBoundingClientRect().top +
- feed.scrollTop;
- for (const top of [
- boundary - feed.clientHeight * 0.2 - 2,
- boundary - feed.clientHeight * 0.2 + 2,
- boundary - feed.clientHeight * 0.2 - 2,
- 0,
- ]) {
+ for (const top of [180, 450, 900, 1_500, 900, 0]) {
feed.scrollTo({ top, behavior: "instant" });
- await assertVisibleActive();
+ await waitFor(() => {
+ const active = sidebar.getByRole("button", { current: true });
+ const name = active.textContent ?? "";
+ const trace = navigationTraces.find((trace) =>
+ name.startsWith(`${trace.turnNumber}.`),
+ );
+ if (!trace) throw new Error("Active turn is missing from the sidebar");
+ const thread = name.startsWith(`${trace.turnNumber}.2`) ? 3 : 1;
+ const entry = feed.querySelector<HTMLElement>(
+ `[data-session-item-id="${trace.trace.id}:${thread === 3 ? 2 : 0}"]`,
+ );
+ if (!entry)
+ throw new Error("Active turn is not visible in the timeline");
+ const bounds = entry.getBoundingClientRect();
+ const viewport = feed.getBoundingClientRect();
+ expect(bounds.bottom).toBeGreaterThan(viewport.top);
+ expect(bounds.top).toBeLessThan(viewport.bottom);
+ });
}
feed.scrollTo({ top: feed.scrollHeight, behavior: "instant" });
await waitFor(
() =>
expect(
- sidebar.getByRole("button", { name: /^32\.2 Navigation turn 32/ }),
+ sidebar.getByRole("button", {
+ name: (name) => name.startsWith("32.2 Navigation turn 32"),
+ }),
).toHaveAttribute("aria-current", "true"),
{ timeout: 3_000 },
);
feed.scrollTo({ top: 0, behavior: "instant" });
- await assertVisibleActive();
+ await expectNavigation(
+ canvasElement,
+ "1.1 Navigation turn 1",
+ "scroll-turn-1:0",
+ false,
+ );
await expect(window.scrollY).toBe(initialPageScroll);
},
});
@@ -3009,7 +2953,7 @@ export const ExactMessageNavigation = meta.story({
const sidebar = within(canvas.getByRole("complementary"));
const search = sidebar.getByRole("textbox");
await userEvent.type(search, "Turn 1 thread 3");
- const header = /^1\.2 Navigation turn 1/;
+ const header = "1.2 Navigation turn 1";
for (const [name, rowId] of [
["System message", "2:0"],
["User message", "2:1"],
@@ -3026,11 +2970,11 @@ export const ExactMessageNavigation = meta.story({
sidebar.queryByRole("button", { name: "User message" }),
).not.toBeInTheDocument();
await userEvent.click(
- sidebar.getByRole("button", { name: /^2\.1 Navigation turn 2/ }),
+ sidebar.getByRole("button", { name: "2.1 Navigation turn 2" }),
);
await expectNavigation(
canvasElement,
- /^2\.1 Navigation turn 2/,
+ "2.1 Navigation turn 2",
"scroll-turn-2:0",
false,
);
@@ -3039,30 +2983,17 @@ export const ExactMessageNavigation = meta.story({
sidebar.getByRole("button", { name: "User message" }),
).toBeInTheDocument();
await userEvent.clear(search);
- const headerButton = sidebar.getByRole("button", {
- name: /^2\.1 Navigation turn 2/,
- });
- const card = within(headerButton.parentElement!.parentElement!);
+ const card = within(
+ sidebar
+ .getByRole("button", { name: "2.1 Navigation turn 2" })
+ .closest<HTMLElement>("[data-session-virtualizer-row]")!,
+ );
await userEvent.click(
card.getByRole("button", { name: "Tool: lookup · save" }),
);
- const toolGroup = await waitFor(async () => {
- const group = canvas
- .getByLabelText("Session conversation timeline")
- .querySelector<HTMLElement>(
- '[data-session-item-id="scroll-turn-2:0"] [data-session-tool-group-id="0:3"]',
- );
- await expect(group).toHaveAttribute("data-session-navigation-highlight");
- if (!group) throw new Error("Target tool group is not mounted");
- await expect(
- group.querySelectorAll("[data-session-tool-row]"),
- ).toHaveLength(2);
- await expect(group.getAnimations()).toHaveLength(1);
- return group;
- });
await expectNavigation(
canvasElement,
- /^2\.1 Navigation turn 2/,
+ "2.1 Navigation turn 2",
"scroll-turn-2:0",
"0:3",
);
@@ -3071,7 +3002,7 @@ export const ExactMessageNavigation = meta.story({
.querySelector<HTMLElement>('[data-session-item-id="scroll-turn-2:0"]')!;
await expect(
within(entry).queryByRole("button", {
- name: /^(Show|Hide) tools: lookup · save$/,
+ name: "Show tools: lookup · save",
}),
).not.toBeInTheDocument();
await expect(
@@ -3081,30 +3012,24 @@ export const ExactMessageNavigation = meta.story({
within(entry).getByRole("button", { name: "Expand save" }),
).toBeVisible();
await userEvent.type(search, "save");
- const filteredHeader = await sidebar.findByRole("button", {
- name: /^2\.1 Navigation turn 2/,
- });
await userEvent.click(
- within(filteredHeader.parentElement!.parentElement!).getByRole("button", {
- name: "tool: save",
- }),
+ within(
+ sidebar
+ .getByRole("button", { name: "2.1 Navigation turn 2" })
+ .closest<HTMLElement>("[data-session-virtualizer-row]")!,
+ ).getByRole("button", { name: "tool: save" }),
+ );
+ await expectNavigation(
+ canvasElement,
+ "2.1 Navigation turn 2",
+ "scroll-turn-2:0",
+ "0:4",
);
- await waitFor(async () => {
- await expect(toolGroup).not.toHaveAttribute(
- "data-session-navigation-highlight",
- );
- await expect(
- toolGroup.querySelector('[data-session-transcript-row-id="0:4"]'),
- ).toHaveAttribute("data-session-navigation-highlight");
- await expect(
- toolGroup.querySelector('[data-session-transcript-row-id="0:3"]'),
- ).not.toHaveAttribute("data-session-navigation-highlight");
- });
},
});
export const RepeatNavigationHighlight = meta.story({
- name: "(Test) Repeat Navigation Highlight",
+ name: "(Test) Repeated Message Navigation",
args: { transcriptTraces: navigationTraces, viewportHeight: 480 },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
@@ -3113,63 +3038,27 @@ export const RepeatNavigationHighlight = meta.story({
await userEvent.type(sidebar.getByRole("textbox"), "Turn 1 thread 3");
const button = sidebar.getByRole("button", { name: "User message" });
await userEvent.click(button);
- const target = await waitFor(async () => {
- const row = feed.querySelector<HTMLElement>(
- '[data-session-item-id="scroll-turn-1:2"] [data-session-transcript-row-id="2:1"]',
- );
- await expect(row).toHaveAttribute("data-session-navigation-highlight");
- if (!row) throw new Error("Target message is not mounted");
- return row;
- });
- const bubble = target.querySelector<HTMLElement>(
- "[data-session-message-bubble]",
- );
- if (!bubble) throw new Error("Target message bubble is not mounted");
- await expect(target.getAnimations()).toHaveLength(0);
- await expect(getComputedStyle(target).backgroundColor).toBe(
- "rgba(0, 0, 0, 0)",
- );
- const originalAnimation = bubble.getAnimations()[0]!;
- await waitFor(
- async () => {
- await expect(originalAnimation.currentTime).toBeGreaterThanOrEqual(900);
- await expect(originalAnimation.playState).toBe("running");
- },
- { timeout: 2_000 },
+ await expectNavigation(
+ canvasElement,
+ "1.2 Navigation turn 1",
+ "scroll-turn-1:2",
+ "2:1",
);
- const fadedBackground = getComputedStyle(bubble).backgroundColor;
-
await userEvent.click(button);
- const restartedAnimation = await waitFor(async () => {
- const animation = bubble.getAnimations()[0];
- await expect(animation).toBeDefined();
- await expect(animation).not.toBe(originalAnimation);
- await expect(animation?.currentTime).toBeLessThan(300);
- await expect(getComputedStyle(bubble).backgroundColor).not.toBe(
- fadedBackground,
- );
- return animation!;
- });
- await waitFor(
- async () => {
- await expect(target).not.toHaveAttribute(
- "data-session-navigation-highlight",
- );
- },
- { timeout: 2_000 },
+ await expectNavigation(
+ canvasElement,
+ "1.2 Navigation turn 1",
+ "scroll-turn-1:2",
+ "2:1",
);
- const idleBackground = getComputedStyle(bubble).backgroundColor;
-
+ feed.scrollTo({ top: 0, behavior: "instant" });
await userEvent.click(button);
- await waitFor(async () => {
- const animation = bubble.getAnimations()[0];
- await expect(animation).toBeDefined();
- await expect(animation).not.toBe(restartedAnimation);
- await expect(animation?.currentTime).toBeLessThan(300);
- await expect(getComputedStyle(bubble).backgroundColor).not.toBe(
- idleBackground,
- );
- });
+ await expectNavigation(
+ canvasElement,
+ "1.2 Navigation turn 1",
+ "scroll-turn-1:2",
+ "2:1",
+ );
},
});
@@ -3180,16 +3069,11 @@ export const VirtualizedNavigation = meta.story({
const canvas = within(canvasElement);
const sidebar = within(canvas.getByRole("complementary"));
const search = sidebar.getByRole("textbox");
- const feed = canvas.getByLabelText("Session conversation timeline");
for (const turn of [28, 3, 32, 1]) {
const itemId = `scroll-turn-${turn}:2`;
- if (turn === 28)
- await expect(
- feed.querySelector(`[data-session-item-id="${itemId}"]`),
- ).not.toBeInTheDocument();
await userEvent.clear(search);
await userEvent.type(search, `Turn ${turn} thread 3`);
- const header = new RegExp(`^${turn}\\.2 Navigation turn ${turn}`);
+ const header = `${turn}.2 Navigation turn ${turn}`;
await userEvent.click(sidebar.getByRole("button", { name: header }));
await expectNavigation(canvasElement, header, itemId, false);
await userEvent.click(
@@ -3213,14 +3097,14 @@ export const SearchThreadNavigation = meta.story({
const search = sidebar.getByRole("textbox");
await userEvent.type(search, "Turn 9 thread 3 assistant");
await expect(
- sidebar.queryByRole("button", { name: /^9\.1/ }),
+ sidebar.queryByRole("button", { name: "9.1 Navigation turn 9" }),
).not.toBeInTheDocument();
await userEvent.click(
await sidebar.findByRole("button", { name: "Assistant message" }),
);
await expectNavigation(
canvasElement,
- /^9\.2 Navigation turn 9/,
+ "9.2 Navigation turn 9",
"scroll-turn-9:2",
"2:2",
);
@@ -3232,13 +3116,15 @@ export const SearchThreadNavigation = meta.story({
).not.toBeInTheDocument(),
);
const header = await sidebar.findByRole("button", {
- name: /^9\.2 Navigation turn 9/,
+ name: "9.2 Navigation turn 9",
});
- const card = within(header.parentElement!.parentElement!);
+ const card = within(
+ header.closest<HTMLElement>("[data-session-virtualizer-row]")!,
+ );
await userEvent.click(card.getByRole("button", { name: "tool: save" }));
await expectNavigation(
canvasElement,
- /^9\.2 Navigation turn 9/,
+ "9.2 Navigation turn 9",
"scroll-turn-9:2",
"2:4",
);
@@ -3247,7 +3133,7 @@ export const SearchThreadNavigation = meta.story({
await waitFor(
() =>
expect(
- sidebar.getByRole("button", { name: /^9\.2 Navigation turn 9/ }),
+ sidebar.getByRole("button", { name: "9.2 Navigation turn 9" }),
).toHaveAttribute("aria-current", "true"),
{ timeout: 3_000 },
);
@@ -3257,7 +3143,7 @@ export const SearchThreadNavigation = meta.story({
await waitFor(
() => {
const active = sidebar.getByRole("button", {
- name: /^9\.2 Navigation turn 9/,
+ name: "9.2 Navigation turn 9",
});
const list = canvas.getByRole("region", { name: "Session turns" });
expect(active).toHaveAttribute("aria-current", "true");
@@ -3282,14 +3168,14 @@ export const NavigationInterruption = meta.story({
const search = sidebar.getByRole("textbox");
await userEvent.type(search, "Turn 2 thread");
await userEvent.click(
- sidebar.getByRole("button", { name: /^2\.1 Navigation turn 2/ }),
+ sidebar.getByRole("button", { name: "2.1 Navigation turn 2" }),
);
await userEvent.click(
- sidebar.getByRole("button", { name: /^2\.2 Navigation turn 2/ }),
+ sidebar.getByRole("button", { name: "2.2 Navigation turn 2" }),
);
await expectNavigation(
canvasElement,
- /^2\.2 Navigation turn 2/,
+ "2.2 Navigation turn 2",
"scroll-turn-2:2",
false,
);
@@ -3318,7 +3204,7 @@ export const DelayedTranscriptNavigation = meta.story({
);
await expectNavigation(
canvasElement,
- /^2\.1 Navigation turn 2/,
+ "2.1 Navigation turn 2",
"scroll-turn-2:0",
false,
);
@@ -3349,7 +3235,7 @@ export const SidebarManualScroll = meta.story({
const sidebar = within(canvas.getByRole("complementary"));
const visibleTurn = sidebar
.getAllByRole("button", {
- name: /^\d+\.\d+ Navigation turn/,
+ name: (name) => name.includes(" Navigation turn "),
})
.find((button) => {
const rect = button.getBoundingClientRect();
@@ -3430,7 +3316,7 @@ export const NestedThreadsHidden = meta.story({
const warnings = await timeline.findAllByRole("button", {
name: "2 nested threads hidden",
});
- await expect(warnings).toHaveLength(2);
+ await expect(warnings).toHaveLength(1);
for (const surface of [timeline]) {
for (const text of [
"Main agent checks the order.",
@@ -3456,17 +3342,12 @@ export const NestedThreadsHidden = meta.story({
await userEvent.click(
sidebar.getByRole("button", { name: "Assistant message" }),
);
- await waitFor(() =>
- expect(sidebar.getByRole("button", { name: /^1\.2 / })).toHaveAttribute(
- "aria-current",
- "true",
- ),
+ await expectNavigation(
+ canvasElement,
+ `1.2 ${traces[0]!.trace.name}`,
+ "trace-1:3",
+ "3:0",
);
- await expect(
- canvasElement.querySelector(
- '[data-session-item-id="trace-1:3"] [data-session-transcript-row-id="3:0"]',
- ),
- ).toHaveAttribute("data-scroll-request-id");
await userEvent.clear(search);
},
});
@@ -3507,29 +3388,37 @@ export const SupportAgentWorkflow = meta.story({
await expect(
await within(
canvas.getByLabelText("Session conversation timeline"),
- ).findByText(/Hi, I just noticed order #LF-20481/),
+ ).findByText((text) =>
+ text.includes("Hi, I just noticed order #LF-20481"),
+ ),
).toBeInTheDocument();
await expect(
await within(
canvas.getByLabelText("Session conversation timeline"),
- ).findByText(/Your shipping address has been updated/),
+ ).findByText((text) =>
+ text.includes("Your shipping address has been updated"),
+ ),
).toBeInTheDocument();
const timeline = within(
canvas.getByLabelText("Session conversation timeline"),
);
for (const button of timeline.queryAllByRole("button", {
- name: /^Show tools:/,
+ name: (name) => name.startsWith("Show tools:"),
})) {
await userEvent.click(button);
}
await userEvent.click(
canvas.getByRole("button", { name: "Expand Get order" }),
);
- await expect(canvas.getByText(/800 Pine Street/)).toBeInTheDocument();
+ await expect(
+ canvas.getByText((text) => text.includes("800 Pine Street")),
+ ).toBeInTheDocument();
await userEvent.click(
canvas.getByRole("button", { name: "Expand Update shipping address" }),
);
- await expect(canvas.getByText(/addr_7b19c2/)).toBeInTheDocument();
+ await expect(
+ canvas.getByText((text) => text.includes("addr_7b19c2")),
+ ).toBeInTheDocument();
},
});
export const ConsecutiveToolGroups = meta.story({
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx
index 2ffb4786df..019b910c77 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx
@@ -217,7 +217,9 @@ export const GroupedToolStatuses = meta.story({
await expect(canvas.getByLabelText("2 tool warnings")).toBeVisible();
await expect(canvas.getByLabelText("Tool status: ERROR")).toBeVisible();
await expect(canvas.getByLabelText("Tool status: WARNING")).toBeVisible();
- const button = canvas.getByRole("button", { name: /^Tool:/ });
+ const button = canvas.getByRole("button", {
+ name: (name) => name.startsWith("Tool:"),
+ });
await userEvent.hover(button);
const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
"tooltip",
@@ -348,7 +350,7 @@ export const SelectMessagesAndTools = meta.story({
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByRole("button", {
- name: /tool: search_documentation/i,
+ name: "tool: search_documentation",
}),
);
await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:3");
@@ -429,10 +431,10 @@ export const MultipleThreads = meta.story({
canvas.getByRole("region", { name: "Thread 2" }),
);
await expect(
- firstThread.getByRole("button", { name: /tool: apply_patch/i }),
+ firstThread.getByRole("button", { name: "tool: apply_patch" }),
).toBeInTheDocument();
await userEvent.click(
- secondThread.getByRole("button", { name: /tool: read_file/i }),
+ secondThread.getByRole("button", { name: "tool: read_file" }),
);
await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-2", "1:0");
await userEvent.type(canvas.getByRole("textbox"), "apply_patch");
@@ -473,9 +475,8 @@ export const GroupedTools = meta.story({
throw new globalThis.Error("Expected loaded sidebar");
const canvas = within(canvasElement);
const group = await canvas.findByRole("button", {
- name: /^Tool:.*read_file.*apply_patch/,
+ name: "Tool: read_file · apply_patch",
});
- await expect(group).not.toHaveAttribute("aria-expanded");
await expect(
canvas.queryByRole("button", { name: "tool: apply_patch" }),
).not.toBeInTheDocument();
@@ -488,7 +489,7 @@ export const GroupedTools = meta.story({
);
await userEvent.type(canvas.getByRole("textbox"), "tool");
await expect(
- canvas.queryByRole("button", { name: /^Tool:.*read_file.*apply_patch/ }),
+ canvas.queryByRole("button", { name: "Tool: read_file · apply_patch" }),
).not.toBeInTheDocument();
await expect(
canvas.getByRole("button", { name: "tool: read_file" }),
@@ -506,7 +507,7 @@ export const GroupedTools = meta.story({
).toHaveTextContent("patch");
await userEvent.clear(canvas.getByRole("textbox"));
await expect(
- canvas.getByRole("button", { name: /^Tool:.*read_file.*apply_patch/ }),
+ canvas.getByRole("button", { name: "Tool: read_file · apply_patch" }),
).toBeInTheDocument();
},
});
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
index 7d41955be3..e5f4d7f189 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.stories.tsx
@@ -53,9 +53,9 @@ function SessionConversationTimelineStory({
parts: [
{
type: "text" as const,
- text: "A dynamic message whose height changes when expanded or resized. ".repeat(
+ text: `Turn ${index + 1} message. ${"A dynamic message whose height changes when expanded or resized. ".repeat(
80 + index * 2,
- ),
+ )}`,
},
],
},
@@ -122,7 +122,7 @@ function SingleTraceLoadingStory() {
}
export const StableSingleTraceLoading = meta.story({
- name: "(Test) Single Trace Navigation Stays Stable While Loading",
+ name: "(Test) Single Trace Navigation Remains Available After Loading",
render: () => <SingleTraceLoadingStory />,
play: async ({ canvas }) => {
const previous = canvas.getByRole("link", {
@@ -134,8 +134,6 @@ export const StableSingleTraceLoading = meta.story({
expect(
canvas.getByRole("status", { name: "Loading messages" }),
).toBeVisible();
- const previousTop = previous.getBoundingClientRect().top;
- const nextTop = next.getBoundingClientRect().top;
await userEvent.click(
canvas.getByRole("button", { name: "Finish loading" }),
);
@@ -144,8 +142,6 @@ export const StableSingleTraceLoading = meta.story({
).not.toBeInTheDocument();
expect(previous).toBeVisible();
expect(next).toBeVisible();
- expect(previous.getBoundingClientRect().top).toBe(previousTop);
- expect(next.getBoundingClientRect().top).toBe(nextTop);
},
});
@@ -170,28 +166,26 @@ export const TimelineNavigation = meta.story({
const previous = await canvas.findByRole("link", {
name: "Previous trace in session (3)",
});
- const firstTrace = await canvas.findByRole("button", {
- name: /Turn 1.*trace-1/,
- });
- expect(previous.compareDocumentPosition(firstTrace)).toBe(
- Node.DOCUMENT_POSITION_FOLLOWING,
- );
+ await expect(previous).toBeVisible();
expect(previous).toHaveAttribute(
"href",
args.navigation?.previousTrace?.href,
);
+ const firstHeader = canvas.getByRole("button", { name: "1 Turn 1" });
+ expect(previous.compareDocumentPosition(firstHeader)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
timeline.scrollTop = timeline.scrollHeight;
timeline.dispatchEvent(new Event("scroll", { bubbles: true }));
const next = await canvas.findByRole("link", {
name: "Next trace in session (1)",
});
- const lastTrace = await canvas.findByRole("button", {
- name: /Turn 3.*trace-3/,
- });
- expect(lastTrace.compareDocumentPosition(next)).toBe(
+ await expect(next).toBeVisible();
+ expect(next).toHaveAttribute("href", args.navigation?.nextTrace?.href);
+ const lastHeader = canvas.getByRole("button", { name: "3 Turn 3" });
+ expect(lastHeader.compareDocumentPosition(next)).toBe(
Node.DOCUMENT_POSITION_FOLLOWING,
);
- expect(next).toHaveAttribute("href", args.navigation?.nextTrace?.href);
},
});
@@ -199,7 +193,7 @@ export const ScrollableTimeline = meta.story({
name: "(Test) Scrollable Timeline",
play: async ({ canvas }) => {
const timeline = canvas.getByLabelText("Session conversation timeline");
- await canvas.findByRole("button", { name: /Turn 1.*trace-1/ });
+ await canvas.findAllByRole("status", { name: "Loading messages" });
await waitFor(() => {
expect(timeline.scrollHeight).toBeGreaterThan(timeline.clientHeight);
});
@@ -207,52 +201,66 @@ export const ScrollableTimeline = meta.story({
timeline.dispatchEvent(new Event("scroll", { bubbles: true }));
await waitFor(() => {
expect(timeline.scrollTop).toBeGreaterThan(0);
+ const lastTrace = canvas
+ .getAllByRole("status", { name: "Loading messages" })
+ .at(-1)!
+ .getBoundingClientRect();
+ const viewport = timeline.getBoundingClientRect();
+ expect(lastTrace.bottom).toBeGreaterThan(viewport.top);
+ expect(lastTrace.top).toBeLessThan(viewport.bottom);
});
},
});
export const DynamicRowMeasurement = meta.story({
- name: "(Test) Keeps Dynamic Rows Contiguous",
+ name: "(Test) Scrolls After Expanding And Resizing Messages",
args: { dynamicContent: true },
play: async ({ canvas, canvasElement }) => {
const timeline = canvas.getByLabelText("Session conversation timeline");
+ await canvas.findAllByRole("button", { name: "Show more" });
const expectContiguousRows = async () => {
await waitFor(() => {
const rows = Array.from(
timeline.querySelectorAll<HTMLElement>(
"[data-session-virtualizer-row]",
),
- )
- .map((row) => row.getBoundingClientRect())
- .sort((left, right) => left.top - right.top);
+ );
expect(rows.length).toBeGreaterThan(1);
- const viewport = timeline.getBoundingClientRect();
- expect(rows[0]!.top).toBeLessThanOrEqual(viewport.top + 1);
- expect(rows.at(-1)!.bottom).toBeGreaterThanOrEqual(viewport.bottom - 1);
for (let index = 1; index < rows.length; index++) {
- expect(
- Math.abs(rows[index]!.top - rows[index - 1]!.bottom),
- ).toBeLessThan(2);
+ expect(rows[index]!.getBoundingClientRect().top).toBeCloseTo(
+ rows[index - 1]!.getBoundingClientRect().bottom,
+ 0,
+ );
}
});
};
- await canvas.findAllByRole("button", { name: "Show more" });
- await expectContiguousRows();
await userEvent.click(
canvas.getAllByRole("button", { name: "Show more" })[0]!,
);
+ await expect(
+ canvas.getByRole("button", { name: "Show less" }),
+ ).toHaveAttribute("aria-expanded", "true");
await expectContiguousRows();
await userEvent.click(canvas.getByRole("button", { name: "Show less" }));
await expectContiguousRows();
- for (const offset of [1500, 4500, 9000, 2000, 0]) {
- timeline.scrollTop = offset;
- timeline.dispatchEvent(new Event("scroll", { bubbles: true }));
- await expectContiguousRows();
- }
const originalWidth = canvasElement.style.width;
try {
- canvasElement.style.width = "320px";
- await expectContiguousRows();
+ for (const width of ["320px", originalWidth]) {
+ canvasElement.style.width = width;
+ for (const turn of [40, 1]) {
+ await waitFor(() => {
+ timeline.scrollTop = turn === 40 ? timeline.scrollHeight : 0;
+ timeline.dispatchEvent(new Event("scroll", { bubbles: true }));
+ const header = canvas
+ .getByText((text) => text.startsWith(`Turn ${turn} message.`))
+ .getBoundingClientRect();
+ const viewport = timeline.getBoundingClientRect();
+ expect(header.bottom).toBeGreaterThan(viewport.top);
+ expect(header.top).toBeLessThan(viewport.bottom);
+ });
+ await expectContiguousRows();
+ }
+ }
} finally {
canvasElement.style.width = originalWidth;
}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
index 9f133f0a49..28f1c44fd1 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
@@ -257,6 +257,87 @@ export const MultipleThreads = meta.story({
);
},
});
+export const FirstThreadHeader = meta.story({
+ name: "(Test) First Thread Header",
+ args: {
+ ...commonArgs,
+ threadIndex: 0,
+ threadCount: 2,
+ displayNumber: "1.1",
+ state: { type: "transcript", result },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.getByRole("button", { name: `1 ${trace.name}` }),
+ ).toBeInTheDocument();
+ await expect(
+ canvas.getByRole("heading", { name: "Thread 1" }),
+ ).toBeInTheDocument();
+ await expect(canvas.getByText("1.1")).toBeInTheDocument();
+ await expect(canvas.queryByText(trace.id)).not.toBeInTheDocument();
+ await expect(
+ canvas.queryByRole("button", { name: "Copy trace ID" }),
+ ).not.toBeInTheDocument();
+ await expect(
+ canvas.queryByRole("heading", { name: "Thread 2" }),
+ ).not.toBeInTheDocument();
+ },
+});
+
+export const SubsequentThreadHeader = meta.story({
+ name: "(Test) Subsequent Thread Header",
+ args: {
+ ...commonArgs,
+ threadIndex: 1,
+ threadCount: 2,
+ displayNumber: "1.2",
+ state: { type: "transcript", result },
+ onOpenTrace: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const openTrace = canvas.getByRole("button", { name: "Open trace" });
+ canvasElement.setAttribute("tabindex", "-1");
+ canvasElement.focus();
+ try {
+ await userEvent.tab();
+ await expect(openTrace).toHaveFocus();
+ await expect(openTrace).toHaveStyle({ opacity: "1" });
+ await userEvent.keyboard("{Enter}");
+ await expect(args.onOpenTrace).toHaveBeenCalledOnce();
+ } finally {
+ canvasElement.removeAttribute("tabindex");
+ }
+ await expect(
+ canvas.queryByRole("button", { name: "Copy trace ID" }),
+ ).not.toBeInTheDocument();
+ await expect(canvas.queryByText(trace.name!)).not.toBeInTheDocument();
+ await expect(
+ canvas.getByRole("heading", { name: "Thread 2" }),
+ ).toBeInTheDocument();
+ await expect(canvas.getByText("1.2")).toBeInTheDocument();
+ },
+});
+
+export const SingleThreadHeader = meta.story({
+ name: "(Test) Single Thread Header",
+ args: {
+ ...commonArgs,
+ threadIndex: 0,
+ threadCount: 1,
+ displayNumber: "1.1",
+ state: weatherState,
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.getByRole("button", { name: `1 ${trace.name}` }),
+ ).toBeInTheDocument();
+ await expect(canvas.queryByRole("heading")).not.toBeInTheDocument();
+ },
+});
+
export const Cutoff = meta.story({
args: {
...commonArgs,
@@ -292,14 +373,14 @@ export const OpenObservation = meta.story({
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const message = canvas
- .getByText("What is the weather?")
- .closest("article")!;
- await userEvent.hover(message);
- await userEvent.click(
- within(message).getByText(/open observation/i, {
- selector: "button",
- }),
- );
+ .getAllByRole("article")
+ .find((article) => within(article).queryByText("What is the weather?"))!;
+ const pointer =
+ "__vitest_browser__" in globalThis
+ ? (await import("vitest/browser")).userEvent
+ : userEvent;
+ await pointer.hover(message);
+ await pointer.click(within(message).getByText("Open observation"));
await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");
},
});
@@ -317,18 +398,17 @@ export const ExpandTool = meta.story({
await userEvent.click(
canvas.getByRole("button", { name: "Expand weather" }),
);
- const [inputPreview, outputPreview] = canvasElement.querySelectorAll("pre");
- await expect(inputPreview).toHaveTextContent('"city": "Berlin"');
- await expect(outputPreview).toHaveTextContent('"temperature": 12');
+ await expect(canvasElement).toHaveTextContent('"city": "Berlin"');
+ await expect(canvasElement).toHaveTextContent('"temperature": 12');
await userEvent.click(
canvas.getByRole("button", { name: "Collapse weather" }),
);
- await expect(outputPreview).not.toBeInTheDocument();
+ await expect(canvasElement).not.toHaveTextContent('"temperature": 12');
},
});
export const ToolPreviewJsonHighlighting = meta.story({
- name: "(Test) Highlights JSON Tool Inputs and Outputs",
+ name: "(Test) Reads JSON Tool Inputs and Outputs",
args: {
...commonArgs,
state: toolPreviewState([
@@ -348,41 +428,37 @@ export const ToolPreviewJsonHighlighting = meta.story({
const canvas = within(canvasElement);
for (const name of ["json-object", "json-string"]) {
const expand = canvas.getByRole("button", { name: `Expand ${name}` });
- const row = expand.closest("section")!;
await userEvent.click(expand);
- const controls = within(row);
await expect(
- controls.getByRole("combobox", { name: "Tool input language" }),
+ canvas.getByRole("combobox", { name: "Tool input language" }),
).toHaveTextContent("Auto (JSON)");
await expect(
- controls.getByRole("combobox", { name: "Tool output language" }),
+ canvas.getByRole("combobox", { name: "Tool output language" }),
).toHaveTextContent("Auto (JSON)");
- const [inputPreview, outputPreview] = row.querySelectorAll("pre");
- await expect(
- inputPreview.querySelector(".token.property"),
- ).toHaveTextContent('"query"');
- await expect(
- outputPreview.querySelector(".token.property"),
- ).toHaveTextContent('"answer"');
+ await expect(canvasElement).toHaveTextContent('"query": "example"');
+ await expect(canvasElement).toHaveTextContent('"answer": 42');
+ await userEvent.click(
+ canvas.getByRole("button", { name: `Collapse ${name}` }),
+ );
}
},
});
const largeToolPreviewCases = [
{
- name: "highlight-limit",
- input: { text: "x".repeat(9_984) },
- output: { text: "x".repeat(9_985) },
+ name: "large-json",
+ input: { text: "x".repeat(20_000) },
+ output: { text: "y".repeat(20_000) },
},
{
name: "large-multiline",
- input: { text: "x".repeat(9_985) },
+ input: { text: "x".repeat(20_000) },
output: `${"\n".repeat(10_000)}full value ends here`,
},
];
export const LargeToolPreviews = meta.story({
- name: "(Test) Large Tool Previews Bypass Highlighting Without Truncation",
+ name: "(Test) Large Tool Previews Preserve Full Content",
args: {
...commonArgs,
state: toolPreviewState(largeToolPreviewCases),
@@ -391,37 +467,24 @@ export const LargeToolPreviews = meta.story({
const canvas = within(canvasElement);
for (const { name, input, output } of largeToolPreviewCases) {
const expand = canvas.getByRole("button", { name: `Expand ${name}` });
- const row = expand.closest("section")!;
await userEvent.click(expand);
- const controls = within(row);
- const [inputPreview, outputPreview] = row.querySelectorAll("pre");
- const expectedInput = JSON.stringify(input, undefined, 2);
const expectedOutput =
typeof output === "string"
? output
: JSON.stringify(output, undefined, 2);
- await expect(outputPreview.textContent).toBe(expectedOutput);
- await expect(outputPreview.childElementCount).toBe(0);
+ await expect(canvasElement).toHaveTextContent(expectedOutput, {
+ normalizeWhitespace: false,
+ });
await expect(
- controls.getByRole("combobox", { name: "Tool output language" }),
+ canvas.getByRole("combobox", { name: "Tool output language" }),
).toBeVisible();
- if (name === "highlight-limit") {
- await expect(expectedInput.length).toBe(10_000);
- await expect(expectedOutput.length).toBe(10_001);
- await expect(
- inputPreview.querySelector(".token.string")?.textContent,
- ).toBe(JSON.stringify(input.text));
- await expect(
- inputPreview.querySelector(".token.property"),
- ).toBeInTheDocument();
- await expect(
- controls.getByRole("combobox", { name: "Tool input language" }),
- ).toHaveTextContent("Auto (JSON)");
- } else {
- await expect(inputPreview.textContent).toBe(expectedInput);
- await expect(inputPreview.childElementCount).toBe(0);
- }
+ await expect(
+ canvas.getByText((text) => text.includes(JSON.stringify(input.text))),
+ ).toBeVisible();
+ await userEvent.click(
+ canvas.getByRole("button", { name: `Collapse ${name}` }),
+ );
}
},
});
@@ -445,48 +508,31 @@ export const ToolPreviewLanguageOverrides = meta.story({
const outputSelect = canvas.getByRole("combobox", {
name: "Tool output language",
});
- const [inputContainer, outputContainer] = Array.from(
- canvasElement.querySelectorAll("pre"),
- (preview) => preview.parentElement!,
- );
const body = within(document.body);
await userEvent.click(inputSelect);
await userEvent.click(body.getByRole("option", { name: "Plain text" }));
await expect(inputSelect).toHaveTextContent("Plain text");
- await expect(inputContainer.querySelector(".token.property")).toBeNull();
- await expect(inputContainer.querySelector("pre")).toHaveTextContent(
- '"query": "example"',
- );
+ await expect(canvasElement).toHaveTextContent('"query": "example"');
await expect(outputSelect).toHaveTextContent("Auto (JSON)");
- await expect(
- outputContainer.querySelector(".token.property"),
- ).toBeInTheDocument();
await userEvent.click(outputSelect);
await userEvent.click(body.getByRole("option", { name: "Python" }));
await expect(outputSelect).toHaveTextContent("Python");
- await expect(outputContainer.querySelector(".token.property")).toBeNull();
+ await expect(canvasElement).toHaveTextContent('"answer": 42');
await expect(inputSelect).toHaveTextContent("Plain text");
await userEvent.click(inputSelect);
await userEvent.click(body.getByRole("option", { name: "Auto (JSON)" }));
- await expect(
- inputContainer.querySelector(".token.property"),
- ).toBeInTheDocument();
+ await expect(inputSelect).toHaveTextContent("Auto (JSON)");
await expect(outputSelect).toHaveTextContent("Python");
await userEvent.click(outputSelect);
await userEvent.click(body.getByRole("option", { name: "Plain text" }));
- await expect(outputContainer.querySelector(".token.property")).toBeNull();
- await expect(outputContainer.querySelector("pre")).toHaveTextContent(
- '"answer": 42',
- );
+ await expect(canvasElement).toHaveTextContent('"answer": 42');
await userEvent.click(outputSelect);
await userEvent.click(body.getByRole("option", { name: "Auto (JSON)" }));
- await expect(
- outputContainer.querySelector(".token.property"),
- ).toBeInTheDocument();
+ await expect(outputSelect).toHaveTextContent("Auto (JSON)");
},
});
@@ -512,51 +558,49 @@ export const ToolPreviewFallbacks = meta.story({
name: "Show tools: plain-text · html · input-only · empty",
}),
);
- for (const name of ["plain-text", "html", "input-only", "empty"]) {
- await userEvent.click(
- canvas.getByRole("button", { name: `Expand ${name}` }),
- );
- }
- const plainRow = canvas
- .getByRole("button", { name: "Collapse plain-text" })
- .closest("section")!;
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Expand plain-text" }),
+ );
await expect(
- within(plainRow).getByRole("combobox", { name: "Tool output language" }),
+ canvas.getByRole("combobox", { name: "Tool output language" }),
).toHaveTextContent("Auto (Plain text)");
await expect(
- within(plainRow).queryByRole("combobox", { name: "Tool input language" }),
+ canvas.queryByRole("combobox", { name: "Tool input language" }),
).toBeNull();
- await expect(plainRow.querySelector("pre")).toHaveTextContent(
- "Hello world",
+ await expect(canvas.getByText("Hello world")).toBeVisible();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Collapse plain-text" }),
);
-
- const htmlRow = canvas
+ await userEvent.click(canvas.getByRole("button", { name: "Expand html" }));
+ // Untrusted markup must remain literal text, never an executable element.
+ const htmlResult = canvas
.getByRole("button", { name: "Collapse html" })
- .closest("section")!;
- await expect(htmlRow.querySelector("script")).toBeNull();
- await expect(htmlRow.querySelector("pre")).toHaveTextContent(
+ .closest<HTMLElement>("[data-session-tool-row]")!;
+ await expect(htmlResult.querySelector("script")).toBeNull();
+ await expect(htmlResult).toHaveTextContent(
'<script>alert("unsafe")</script>',
);
-
- const inputRow = canvas
- .getByRole("button", { name: "Collapse input-only" })
- .closest("section")!;
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Collapse html" }),
+ );
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Expand input-only" }),
+ );
await expect(
- within(inputRow).getByRole("combobox", { name: "Tool input language" }),
+ canvas.getByRole("combobox", { name: "Tool input language" }),
).toHaveTextContent("Auto (JSON)");
await expect(
- within(inputRow).queryByRole("combobox", {
+ canvas.queryByRole("combobox", {
name: "Tool output language",
}),
).toBeNull();
- const emptyRow = canvas
- .getByRole("button", { name: "Collapse empty" })
- .closest("section")!;
- await expect(within(emptyRow).queryByRole("combobox")).toBeNull();
- await expect(
- within(emptyRow).getByText("No input or output"),
- ).toBeInTheDocument();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Collapse input-only" }),
+ );
+ await userEvent.click(canvas.getByRole("button", { name: "Expand empty" }));
+ await expect(canvas.queryByRole("combobox")).toBeNull();
+ await expect(canvas.getByText("No input or output")).toBeInTheDocument();
},
});
@@ -569,14 +613,13 @@ export const OpenToolObservation = meta.story({
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
- const toolRow = canvas
- .getByRole("button", { name: "Expand weather" })
- .closest("section")!;
- await userEvent.hover(toolRow);
- const openObservation = within(toolRow).getByText(/open observation/i, {
- selector: "button",
- });
- await userEvent.click(openObservation);
+ await userEvent.click(canvas.getByRole("button", { name: "weather" }));
+ const tool = canvasElement.querySelector<HTMLElement>(
+ "[data-session-tool-row]",
+ )!;
+ await userEvent.click(
+ within(tool).getByRole("button", { name: "Open observation" }),
+ );
await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");
},
});
@@ -719,7 +762,7 @@ export const GenerationToolCallOnly = meta.story({
await userEvent.click(
canvas.getByRole("button", { name: "Expand get_subscription_details" }),
);
- await expect(canvas.getByText(/CUS-48291/)).toBeInTheDocument();
+ await expect(canvasElement).toHaveTextContent("CUS-48291");
},
args: {
...commonArgs,
@@ -751,7 +794,7 @@ export const ToolResultOnly = meta.story({
await userEvent.click(
canvas.getByRole("button", { name: "Expand get_subscription_details" }),
);
- await expect(canvas.getByText(/annual_pro/)).toBeInTheDocument();
+ await expect(canvasElement).toHaveTextContent("annual_pro");
},
args: {
...commonArgs,
@@ -848,7 +891,7 @@ export const KeepDifferentToolData = meta.story({
const canvas = within(canvasElement);
await expect(
canvas.queryByRole("button", {
- name: /^Show tools:.*search_documentation.*get_customer_profile/,
+ name: "Show tools: search_documentation · get_customer_profile",
}),
).not.toBeInTheDocument();
await expect(
@@ -908,22 +951,20 @@ export const SystemPromptHistory = meta.story({
canvas.queryByText("Inspect representative failures."),
).not.toBeInTheDocument();
await userEvent.click(
- canvas.getByRole("button", { name: /Weather assistant.*trace-1/ }),
+ canvas.getByRole("button", { name: `1 ${trace.name}` }),
);
await expect(args.onOpenTrace).toHaveBeenCalledTimes(1);
- const header = canvas.getByRole("button", {
- name: "System prompt",
- }).parentElement!;
- const timestamp = header.querySelector("time")!;
- const openObservation = within(header).getByText("Open observation", {
- selector: "button",
- });
- await expect(timestamp.dateTime).toBe(provenance.startTime.toISOString());
- await userEvent.hover(header);
- await userEvent.click(openObservation);
+ const prompt = canvas.getByRole("button", { name: "System prompt" });
+ await userEvent.click(prompt);
+ await expect(canvas.getByText("Current system instructions")).toBeVisible();
+ const systemMessage = canvasElement.querySelector<HTMLElement>(
+ "[data-session-system-row]",
+ )!;
+ await userEvent.click(
+ within(systemMessage).getByRole("button", { name: "Open observation" }),
+ );
await expect(args.onOpenObservation).toHaveBeenCalledTimes(1);
await expect(args.onOpenObservation).toHaveBeenCalledWith("generation-1");
- await userEvent.unhover(header);
},
});
@@ -974,7 +1015,7 @@ export const ToolFailure = meta.story({
await userEvent.click(
canvas.getByRole("button", { name: "Expand get_order" }),
);
- await expect(canvas.getByText(/TOOL_TIMEOUT/)).toBeInTheDocument();
+ await expect(canvasElement).toHaveTextContent("TOOL_TIMEOUT");
},
});
@@ -1255,7 +1296,9 @@ export const GroupedToolStatuses = meta.story({
const overlays = within(canvasElement.ownerDocument.body);
const errors = canvas.getByLabelText("Tool group: 2 errors");
const warnings = canvas.getByLabelText("Tool group: 2 warnings");
- const groupToggle = canvas.getByRole("button", { name: /Show tools:/ });
+ const groupToggle = canvas.getByRole("button", {
+ name: (name) => name.startsWith("Show tools:"),
+ });
await expect(groupToggle).toHaveAttribute("aria-expanded", "false");
await expect(errors).toBeVisible();
await expect(warnings).toBeVisible();
@@ -1332,7 +1375,9 @@ export const GroupedToolStatuses = meta.story({
"Search timed out",
);
await expect(
- canvas.getByRole("button", { name: /Hide tools:/ }),
+ canvas.getByRole("button", {
+ name: (name) => name.startsWith("Hide tools:"),
+ }),
).toHaveAttribute("aria-expanded", "true");
},
});
@@ -1352,10 +1397,12 @@ export const HealthyToolGroup = meta.story({
},
play: async ({ canvas }) => {
await expect(
- canvas.getByRole("button", { name: /Show tools:/ }),
+ canvas.getByRole("button", {
+ name: "Show tools: search · fetch · cache · validate",
+ }),
).toBeVisible();
await expect(
- canvas.queryByLabelText(/Tool group:/),
+ canvas.queryByLabelText((label) => label.startsWith("Tool group:")),
).not.toBeInTheDocument();
},
});
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
index 387cbe142f..6b6bb97764 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx
@@ -49,40 +49,50 @@ export function SessionConversationTimelineTrace({
requestId: number;
} | null;
}) {
- const showHeader = variant === "session" || (threadCount ?? 0) > 1;
- const hiddenThreadCount =
+ const { visibleThreads, hiddenThreadCount } =
state.type === "transcript"
? getSessionTranscriptThreads(
state.result.transcript,
includeNestedThreads,
- ).hiddenThreadCount
- : 0;
+ )
+ : { visibleThreads: [], hiddenThreadCount: 0 };
+ const visibleThreadIndex = visibleThreads.findIndex(
+ (thread) => thread.threadIndex === threadIndex,
+ );
+ const showHeader =
+ variant === "session" ? visibleThreadIndex <= 0 : (threadCount ?? 0) > 1;
+ const showThreadHeader =
+ variant === "session" &&
+ visibleThreads.length > 1 &&
+ visibleThreadIndex >= 0;
return (
<div
className={cn(
- variant === "single-trace" ? "p-0" : "px-4 pb-14 sm:px-6 lg:px-10",
+ variant === "single-trace" ? "p-0" : "px-4 pb-8 sm:px-6 lg:px-10",
)}
data-session-trace-id={trace.id}
data-session-item-id={itemId}
>
{showHeader && (
- <div className="group/trace-header mb-6 flex items-center gap-4 pt-5">
+ <div
+ className={cn(
+ "group/trace-header flex items-center gap-3 pt-4",
+ showThreadHeader ? "mb-3" : "mb-6",
+ )}
+ >
<button
type="button"
- className="text-muted-foreground hover:text-foreground ph-no-capture flex min-w-0 items-center gap-2 font-mono text-xs transition-colors"
+ className="text-foreground hover:text-primary ph-no-capture flex min-w-0 items-center gap-2 text-sm font-bold transition-colors"
onClick={onOpenTrace}
title={`${trace.name ?? "Trace"} (${trace.id})`}
>
<span className="border-border bg-tertiary text-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm border px-0.5 font-mono text-[10px]">
- {displayNumber ?? turnNumber}
+ {variant === "session"
+ ? turnNumber
+ : (displayNumber ?? turnNumber)}
</span>
- <span
- className="truncate"
- title={`${trace.name ?? "Trace"} · ${trace.id}`}
- >
+ <span className="truncate" title={trace.name ?? "Trace"}>
<span data-session-search-content>{trace.name ?? "Trace"}</span>
- {" · "}
- {trace.id}
</span>
</button>
<div className="border-border min-w-0 flex-1 border-t border-dashed" />
@@ -126,6 +136,32 @@ export function SessionConversationTimelineTrace({
</div>
)}
+ {showThreadHeader && (
+ <div
+ className={cn(
+ "group/thread-header text-muted-foreground mb-5 flex items-center gap-2 text-xs",
+ !showHeader && "pt-3",
+ )}
+ >
+ <span className="bg-muted text-muted-foreground flex h-4 min-w-4 shrink-0 items-center justify-center rounded-sm px-1 font-mono text-[10px]">
+ {displayNumber ?? `${turnNumber}.${visibleThreadIndex + 1}`}
+ </span>
+ <h3>Thread {visibleThreadIndex + 1}</h3>
+ {visibleThreadIndex > 0 && (
+ <>
+ <div className="border-border min-w-0 flex-1 border-t border-dashed" />
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground shrink-0 font-mono text-xs opacity-0 group-focus-within/thread-header:opacity-100 group-hover/thread-header:opacity-100 hover:underline focus-visible:opacity-100"
+ onClick={onOpenTrace}
+ >
+ Open trace
+ </button>
+ </>
+ )}
+ </div>
+ )}
+
{state.type === "loading" && (
<div
role="status"
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
index 94dd065504..638fba8247 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable @repo/storybook-play-no-implementation-detail-assertions */
import preview from "@/.storybook/preview";
import { expect, fn, userEvent, waitFor, within } from "storybook/test";
@@ -49,7 +48,9 @@ export const ReasoningVariants = meta.story({
await expect(canvas.getAllByText("Redacted reasoning")).toHaveLength(3);
await expect(canvas.getByText("Encrypted reasoning")).toBeVisible();
- const expandButtons = canvas.getAllByRole("button", { name: /^Expand / });
+ const expandButtons = canvas.getAllByRole("button", {
+ name: (name) => name.startsWith("Expand "),
+ });
await expect(expandButtons).toHaveLength(3);
for (const button of expandButtons) {
await expect(button).toHaveAttribute("aria-expanded", "false");
@@ -60,7 +61,9 @@ export const ReasoningVariants = meta.story({
await expect(canvas.getByText("Redacted payload")).toBeVisible();
await expect(canvas.getByText("Reasoning data")).toBeVisible();
await expect(
- canvas.getByRole("button", { name: /^(Expand|Collapse) checks$/ }),
+ canvas.getByRole("button", {
+ name: (name) => name === "Expand checks" || name === "Collapse checks",
+ }),
).toBeVisible();
await expect(canvasElement).toHaveTextContent("source available");
await expect(canvasElement).toHaveTextContent("answer supported");
@@ -88,27 +91,25 @@ export const ReasoningActions = meta.story({
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
- const rows = canvasElement.querySelectorAll("section");
- await expect(rows).toHaveLength(4);
- for (const row of rows) {
- const header = row.firstElementChild!;
- const action = within(row).getByText("Open generation", {
- selector: "button",
- });
- const divider = header.querySelector(
- '[aria-hidden="true"].border-dashed',
- )!;
- await expect(divider).toBeInTheDocument();
- await expect(action).toHaveClass("group-hover/collapsible-row:visible");
- const trigger = within(row).queryByRole("button", { name: "Reasoning" });
- if (trigger) {
- await userEvent.click(trigger);
- await expect(trigger).toHaveFocus();
- await expect(trigger).toHaveAttribute("aria-expanded", "true");
- await expect(action).toBeVisible();
- await expect(divider).toBeVisible();
- }
- await userEvent.click(action);
+ for (const trigger of canvas.getAllByRole("button", {
+ name: "Reasoning",
+ })) {
+ await userEvent.click(trigger);
+ await expect(trigger).toHaveFocus();
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ }
+ const actions = canvas.getAllByText("Open generation");
+ await expect(actions).toHaveLength(4);
+ const headers = canvas.getAllByText(
+ (text) => text === "Reasoning" || text === "Encrypted reasoning",
+ );
+ const pointer =
+ "__vitest_browser__" in globalThis
+ ? (await import("vitest/browser")).userEvent
+ : userEvent;
+ for (const [index, header] of headers.entries()) {
+ await pointer.hover(header);
+ await pointer.click(actions[index]!);
}
await expect(args.onOpenObservation).toHaveBeenCalledTimes(4);
await expect(
@@ -166,26 +167,17 @@ export const TallPlainText = meta.story({
),
},
],
- onOpenObservation: () => {},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const toggle = await canvas.findByRole("button", { name: "Show more" });
- const content = canvasElement.ownerDocument.getElementById(
- toggle.getAttribute("aria-controls") ?? "",
- );
await expect(toggle).toHaveAttribute("aria-expanded", "false");
- await expect(content).toHaveClass("max-h-96");
await userEvent.click(toggle);
await expect(
canvas.getByRole("button", { name: "Show less" }),
).toHaveAttribute("aria-expanded", "true");
- await expect(content).not.toHaveClass("max-h-96");
await userEvent.click(canvas.getByRole("button", { name: "Show less" }));
await expect(toggle).toHaveAttribute("aria-expanded", "false");
- await expect(
- canvas.getByRole("button", { name: "Open observation" }),
- ).toBeInTheDocument();
},
});
@@ -203,11 +195,7 @@ export const TallMarkdown = meta.story({
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const toggle = await canvas.findByRole("button", { name: "Show more" });
- const content = canvasElement.ownerDocument.getElementById(
- toggle.getAttribute("aria-controls") ?? "",
- );
await expect(toggle).toHaveAttribute("aria-expanded", "false");
- await expect(content).toHaveClass("max-h-96");
await userEvent.click(toggle);
await expect(
canvas.getAllByRole("heading", { name: "Heading" }),
@@ -215,10 +203,8 @@ export const TallMarkdown = meta.story({
await expect(
canvas.getByRole("button", { name: "Show less" }),
).toHaveAttribute("aria-expanded", "true");
- await expect(content).not.toHaveClass("max-h-96");
await userEvent.click(canvas.getByRole("button", { name: "Show less" }));
await expect(toggle).toHaveAttribute("aria-expanded", "false");
- await expect(content).toHaveClass("max-h-96");
},
});