Skip to content

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

feat(sessions): add trace detail peek view and clean up layout (#9042)

Leo Weigand729c2132af1c
diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.ts
index 8840180bdb..8f013a82fa 100644
--- a/packages/shared/scripts/seeder/seed-postgres.ts
+++ b/packages/shared/scripts/seeder/seed-postgres.ts
@@ -110,6 +110,9 @@ async function main() {
},
});
+ // Realistic support chat scenario
+ await createSupportChatSession(project1);
+
await prisma.organizationMembership.upsert({
where: {
orgId_userId: {
@@ -771,6 +774,24 @@ async function createTraceSessions(project1: Project, project2: Project) {
}
}
+async function createSupportChatSession(project: Project) {
+ const sessionId = "support-chat-session";
+ await prisma.traceSession.upsert({
+ where: {
+ id_projectId: {
+ id: sessionId,
+ projectId: project.id,
+ },
+ },
+ create: {
+ id: sessionId,
+ projectId: project.id,
+ environment: "default",
+ },
+ update: {},
+ });
+}
+
async function generateConfigs(project: Project) {
const configNameAndId: {
name: string;
diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.ts
index 3881b18052..0d4d36242f 100644
--- a/packages/shared/scripts/seeder/utils/data-generators.ts
+++ b/packages/shared/scripts/seeder/utils/data-generators.ts
@@ -952,6 +952,310 @@ export class DataGenerator {
: JSON.stringify(this.fileContent.chatMlJson);
}
+ /**
+ * Creates realistic support chat session data with conversational flow.
+ * Use for: Demonstrating session-based conversations with tool calls and scoring.
+ */
+ generateSupportChatSessionData(projectId: string): {
+ traces: TraceRecordInsertType[];
+ observations: ObservationRecordInsertType[];
+ scores: ScoreRecordInsertType[];
+ } {
+ // Domain: Art museum membership support (non-tech)
+ const dialogues = [
+ {
+ user: "Hi—my family membership at the City Art Museum was charged twice this month.",
+ assistant:
+ "Sorry about that. I can help. Could you share your membership ID and the last 4 digits of the card?",
+ },
+ {
+ user: "Membership ID is CAM-48291, card ending 4417.",
+ assistant: "Thanks. I'll check your billing records now.",
+ tool: {
+ name: "billing.lookup",
+ input: { membershipId: "CAM-48291", last4: "4417" },
+ output: {
+ duplicateCharge: true,
+ amounts: [95.0, 95.0],
+ date: "2025-08-28",
+ },
+ },
+ },
+ {
+ user: "Okay.",
+ assistant:
+ "I found a duplicate charge on 2025-08-28 for $95. I can issue a refund to the original payment method. Shall I proceed?",
+ },
+ {
+ user: "Yes, please issue the refund.",
+ assistant: "Processing your refund now. One moment.",
+ tool: {
+ name: "billing.refund",
+ input: { membershipId: "CAM-48291", amount: 95.0 },
+ output: { status: "success", refundId: "RFND-20931" },
+ },
+ },
+ {
+ user: "Thank you!",
+ assistant:
+ "Refund RFND-20931 has been issued. You'll see it on your statement within 3–5 business days.",
+ },
+ {
+ user: "No, that's all. Appreciate the quick help!",
+ assistant: "Happy to help. Enjoy your next visit to the museum!",
+ },
+ // a couple more lightweight turns for scrolling realism
+ {
+ user: "Oh, and do members get early access to exhibitions?",
+ assistant:
+ "Yes—members get a 48-hour early booking window and a preview evening invite.",
+ },
+ {
+ user: "Perfect.",
+ assistant: "You're all set. Have a great day!",
+ },
+ ];
+
+ const now = Date.now();
+ const traces: TraceRecordInsertType[] = dialogues.map((d, index) => ({
+ id: `support-chat-${index}-${projectId.slice(-8)}`,
+ timestamp: now + index * 1000,
+ name: "SupportChatSession",
+ user_id: null,
+ metadata: { scenario: "support-chat" },
+ release: null,
+ version: null,
+ project_id: projectId,
+ environment: "default",
+ public: false,
+ bookmarked: false,
+ tags: ["support", "chat", "session"],
+ input: JSON.stringify(
+ d.tool
+ ? {
+ messages: [
+ { role: "user", content: d.user },
+ { role: "assistant", content: d.assistant },
+ {
+ role: "tool",
+ name: d.tool.name,
+ content: d.tool.output,
+ },
+ ],
+ }
+ : { messages: [{ role: "user", content: d.user }] },
+ ),
+ output: JSON.stringify({ role: "assistant", content: d.assistant }),
+ session_id: "support-chat-session",
+ created_at: now + index * 1000,
+ updated_at: now + index * 1000 + 500,
+ event_ts: now + index * 1000,
+ is_deleted: 0,
+ }));
+
+ // Create one GENERATION observation per trace
+ const observations: ObservationRecordInsertType[] = dialogues
+ .map((d, index) => {
+ const start = now + index * 1000 + 50;
+ const end = start + 400 + Math.floor(Math.random() * 400);
+ const inputTokens = 80 + Math.floor(Math.random() * 60);
+ const outputTokens = 60 + Math.floor(Math.random() * 60);
+ const totalTokens = inputTokens + outputTokens;
+
+ const baseGen: ObservationRecordInsertType = {
+ id: `support-chat-${index}-${projectId.slice(-8)}-gen`,
+ trace_id: `support-chat-${index}-${projectId.slice(-8)}`,
+ project_id: projectId,
+ type: "GENERATION",
+ parent_observation_id: null,
+ environment: "default",
+ start_time: start,
+ end_time: end,
+ name: "llm-generation",
+ metadata: {},
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: JSON.stringify({
+ messages: [
+ { role: "user", content: d.user },
+ d.tool
+ ? {
+ role: "tool",
+ name: d.tool.name,
+ content: d.tool.output,
+ }
+ : undefined,
+ ].filter(Boolean),
+ }),
+ output: JSON.stringify({ role: "assistant", content: d.assistant }),
+ provided_model_name: "gpt-4o",
+ internal_model_id: null,
+ model_parameters: JSON.stringify({ temperature: 0.2 }),
+ provided_usage_details: {
+ input: inputTokens,
+ output: outputTokens,
+ total: totalTokens,
+ },
+ usage_details: {
+ input: inputTokens,
+ output: outputTokens,
+ total: totalTokens,
+ },
+ provided_cost_details: {
+ input: Math.round(inputTokens * 2) / 1_000_000,
+ output: Math.round(outputTokens * 3) / 1_000_000,
+ total: Math.round(totalTokens * 5) / 1_000_000,
+ },
+ cost_details: {
+ input: Math.round(inputTokens * 2) / 1_000_000,
+ output: Math.round(outputTokens * 3) / 1_000_000,
+ total: Math.round(totalTokens * 5) / 1_000_000,
+ },
+ total_cost: Math.round(totalTokens * 5) / 1_000_000,
+ completion_start_time: start + 120,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: start,
+ updated_at: end,
+ event_ts: start,
+ is_deleted: 0,
+ };
+
+ if (!d.tool) return [baseGen];
+
+ const toolObs: ObservationRecordInsertType = {
+ id: `support-chat-${index}-${projectId.slice(-8)}-tool`,
+ trace_id: `support-chat-${index}-${projectId.slice(-8)}`,
+ project_id: projectId,
+ type: "TOOL",
+ parent_observation_id: null,
+ environment: "default",
+ start_time: start - 40,
+ end_time: start - 5,
+ name: d.tool.name,
+ metadata: {},
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ input: JSON.stringify(d.tool.input),
+ output: JSON.stringify(d.tool.output),
+ provided_model_name: null,
+ internal_model_id: null,
+ model_parameters: null,
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ total_cost: null,
+ completion_start_time: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: start - 40,
+ updated_at: start - 5,
+ event_ts: start - 40,
+ is_deleted: 0,
+ };
+
+ return [toolObs, baseGen];
+ })
+ .flat();
+
+ // Create a couple of scores per trace
+ const scores: ScoreRecordInsertType[] = dialogues
+ .map((_, index) => {
+ const baseTs = now + index * 1000 + 600;
+ const helpfulness: ScoreRecordInsertType = {
+ id: `support-chat-${index}-${projectId.slice(-8)}-score-helpfulness`,
+ project_id: projectId,
+ trace_id: `support-chat-${index}-${projectId.slice(-8)}`,
+ session_id: null,
+ dataset_run_id: null,
+ observation_id: null,
+ environment: "default",
+ name: "helpfulness",
+ value: 70 + Math.random() * 25,
+ source: "API",
+ comment: "Heuristic helpfulness score",
+ metadata: {},
+ author_user_id: null,
+ config_id: null,
+ data_type: "NUMERIC",
+ string_value: null,
+ queue_id: null,
+ created_at: baseTs,
+ updated_at: baseTs,
+ timestamp: baseTs,
+ event_ts: baseTs,
+ is_deleted: 0,
+ };
+
+ const safeVal = Math.random() > 0.1 ? 1 : 0;
+ const safety: ScoreRecordInsertType = {
+ id: `support-chat-${index}-${projectId.slice(-8)}-score-safety`,
+ project_id: projectId,
+ trace_id: `support-chat-${index}-${projectId.slice(-8)}`,
+ session_id: null,
+ dataset_run_id: null,
+ observation_id: null,
+ environment: "default",
+ name: "safe",
+ value: safeVal,
+ source: "API",
+ comment: "Content safety",
+ metadata: {},
+ author_user_id: null,
+ config_id: null,
+ data_type: "BOOLEAN",
+ string_value: safeVal === 1 ? "true" : "false",
+ queue_id: null,
+ created_at: baseTs + 10,
+ updated_at: baseTs + 10,
+ timestamp: baseTs + 10,
+ event_ts: baseTs + 10,
+ is_deleted: 0,
+ };
+
+ // Optional: resolution score on last turn
+ const isFinal = index === dialogues.length - 1;
+ const resolved: ScoreRecordInsertType | null = isFinal
+ ? {
+ id: `support-chat-${index}-${projectId.slice(-8)}-score-resolved`,
+ project_id: projectId,
+ trace_id: `support-chat-${index}-${projectId.slice(-8)}`,
+ session_id: null,
+ dataset_run_id: null,
+ observation_id: null,
+ environment: "default",
+ name: "resolved",
+ value: 1,
+ source: "API",
+ comment: "Conversation resolved",
+ metadata: {},
+ author_user_id: null,
+ config_id: null,
+ data_type: "BOOLEAN",
+ string_value: "true",
+ queue_id: null,
+ created_at: baseTs + 20,
+ updated_at: baseTs + 20,
+ timestamp: baseTs + 20,
+ event_ts: baseTs + 20,
+ is_deleted: 0,
+ }
+ : null;
+
+ return [helpfulness, safety, resolved].filter(
+ Boolean,
+ ) as ScoreRecordInsertType[];
+ })
+ .flat();
+
+ return { traces, observations, scores };
+ }
+
/**
* Creates exactly one score per evaluation trace with prefixed IDs.
* Use for: Evaluation traces that need score validation, evaluator testing.
diff --git a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
index f47a52fb10..8f58b18111 100644
--- a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
+++ b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
@@ -321,6 +321,9 @@ export class SeederOrchestrator {
// Create synthetic data
await this.createSyntheticData(projectIds, opts);
+ // Create traces for a realistic chat session
+ await this.createSupportChatSessionTraces(projectIds);
+
// Log completion statistics (commented out to reduce terminal noise)
await this.logStatistics();
@@ -378,4 +381,27 @@ export class SeederOrchestrator {
}
}
}
+
+ async createSupportChatSessionTraces(projectIds: string[]): Promise<void> {
+ logger.info(
+ `Creating support chat session data for ${projectIds.length} projects.`,
+ );
+
+ for (const projectId of projectIds) {
+ logger.info(`Processing support chat session for project ${projectId}`);
+
+ // Generate data using the data generator
+ const { traces, observations, scores } =
+ this.dataGenerator.generateSupportChatSessionData(projectId);
+
+ try {
+ await this.queryBuilder.executeTracesInsert(traces);
+ await this.queryBuilder.executeObservationsInsert(observations);
+ await this.queryBuilder.executeScoresInsert(scores);
+ } catch (error) {
+ logger.error(`✗ Support chat session insert failed:`, error);
+ throw error;
+ }
+ }
+ }
}
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 49b4c22b27..0cac33ed3d 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -28,6 +28,11 @@ import { ScrollArea } from "@/src/components/ui/scroll-area";
import { Label } from "@/src/components/ui/label";
import { AnnotationQueueObjectType, type APIScoreV2 } from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
+import { TablePeekView } from "@/src/components/table/peek";
+import { PeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
+import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";
+import { ItemBadge } from "@/src/components/ItemBadge";
// some projects have thousands of traces in a sessions, paginate to avoid rendering all at once
const PAGE_SIZE = 50;
@@ -153,11 +158,27 @@ export const SessionPage: React.FC<{
},
},
);
+
+ const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
+ usePeekNavigation({
+ expandConfig: {
+ // Expand peeked traces to the trace detail route; sessions list traces
+ basePath: `/project/${projectId}/traces`,
+ },
+ queryParams: ["timestamp"],
+ extractParamsValuesFromRow: (row: any) => ({
+ timestamp: row.timestamp.toISOString(),
+ }),
+ });
+
useEffect(() => {
if (session.isSuccess) {
setDetailPageList(
"traces",
- session.data.traces.map((t) => ({ id: t.id })),
+ session.data.traces.map((t) => ({
+ id: t.id,
+ params: { timestamp: t.timestamp.toISOString() },
+ })),
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -202,8 +223,6 @@ export const SessionPage: React.FC<{
return (
<Page
- withPadding
- scrollable
headerProps={{
title: sessionId,
itemType: "SESSION",
@@ -280,90 +299,136 @@ export const SessionPage: React.FC<{
),
}}
>
- <div className="flex flex-wrap items-end gap-2">
- <SessionUsers projectId={projectId} users={session.data?.users} />
- <Badge variant="outline">Traces: {session.data?.traces.length}</Badge>
- {session.data && (
+ <div className="flex h-full flex-col overflow-auto">
+ <div className="sticky top-0 z-40 flex flex-wrap gap-2 border-b bg-background p-4">
+ {session.data?.users?.length ? (
+ <SessionUsers projectId={projectId} users={session.data.users} />
+ ) : null}
<Badge variant="outline">
- Total cost: {usdFormatter(session.data.totalCost, 2)}
+ Total traces: {session.data?.traces.length}
</Badge>
- )}
- <SessionScores
- scores={
- session.data?.scores?.map((score) => ({
- ...score,
- timestamp: new Date(score.timestamp),
- createdAt: new Date(score.createdAt),
- updatedAt: new Date(score.updatedAt),
- })) ?? []
- }
- />
- </div>
- <div className="mt-5 flex flex-col gap-2 border-t pt-5">
- {session.data?.traces.slice(0, visibleTraces).map((trace) => (
- <Card
- className="group grid gap-3 border-border p-2 shadow-none hover:border-ring md:grid-cols-3"
- key={trace.id}
- >
- <div className="col-span-2 overflow-hidden">
- <SessionIO
- traceId={trace.id}
- projectId={projectId}
- timestamp={new Date(trace.timestamp)}
- />
- </div>
- <div className="-mt-1 p-1 opacity-50 transition-opacity group-hover:opacity-100">
- <Link
- href={`/project/${projectId}/traces/${trace.id}`}
- className="text-xs hover:underline"
- >
- Trace: {trace.name} ({trace.id})&nbsp;↗
- </Link>
- <div className="text-xs text-muted-foreground">
- {trace.timestamp.toLocaleString()}
- </div>
- <div className="mb-1 mt-2 text-xs text-muted-foreground">
- Scores
- </div>
- <div className="mb-1 flex flex-wrap content-start items-start gap-1">
- <GroupedScoreBadges scores={trace.scores} />
- </div>
- <div className="flex items-center gap-1">
- <AnnotateDrawer
- projectId={projectId}
- scoreTarget={{
- type: "trace",
- traceId: trace.id,
- }}
- scores={trace.scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- variant="badge"
- analyticsData={{ type: "trace", source: "SessionDetail" }}
- key={"annotation-drawer" + trace.id}
- environment={trace.environment}
- />
- <CommentDrawerButton
- projectId={projectId}
- objectId={trace.id}
- objectType="TRACE"
- count={getNumberFromMap(traceCommentCounts.data, trace.id)}
- className="h-6 rounded-full text-xs"
- />
+ {session.data && (
+ <Badge variant="outline">
+ Total cost: {usdFormatter(session.data.totalCost, 2)}
+ </Badge>
+ )}
+ <SessionScores
+ scores={
+ session.data?.scores?.map((score) => ({
+ ...score,
+ timestamp: new Date(score.timestamp),
+ createdAt: new Date(score.createdAt),
+ updatedAt: new Date(score.updatedAt),
+ })) ?? []
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-4 p-4">
+ {session.data?.traces.slice(0, visibleTraces).map((trace) => (
+ <Card className="border-border shadow-none" key={trace.id}>
+ <div className="grid md:grid-cols-[1fr_1px_358px] lg:grid-cols-[1fr_1px_28rem]">
+ <div className="overflow-hidden py-4 pl-4 pr-4">
+ <SessionIO
+ traceId={trace.id}
+ projectId={projectId}
+ timestamp={new Date(trace.timestamp)}
+ />
+ </div>
+ <div className="hidden bg-border md:block"></div>
+ <div className="flex flex-col border-t py-4 pl-4 pr-4 md:border-0">
+ <div className="mb-4 flex flex-col gap-2">
+ <Link
+ href={`/project/${projectId}/traces/${trace.id}`}
+ className="flex items-start gap-2 rounded-lg border p-2 transition-colors hover:bg-accent"
+ onClick={(e) => {
+ // Only prevent default for normal clicks, allow modifier key clicks through
+ if (!e.metaKey && !e.ctrlKey && !e.shiftKey) {
+ e.preventDefault();
+ openPeek(trace.id, trace);
+ }
+ }}
+ >
+ <ItemBadge type="TRACE" isSmall />
+ <div className="flex flex-col">
+ <span className="text-xs font-medium">
+ {trace.name} ({trace.id})&nbsp;↗
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {trace.timestamp.toLocaleString()}
+ </span>
+ </div>
+ </Link>
+ <div className="flex flex-wrap gap-2">
+ <NewDatasetItemFromTraceId
+ projectId={projectId}
+ traceId={trace.id}
+ timestamp={new Date(trace.timestamp)}
+ buttonVariant="outline"
+ />
+ <AnnotateDrawer
+ projectId={projectId}
+ scoreTarget={{
+ type: "trace",
+ traceId: trace.id,
+ }}
+ scores={trace.scores}
+ emptySelectedConfigIds={emptySelectedConfigIds}
+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}
+ variant="button"
+ buttonVariant="outline"
+ analyticsData={{
+ type: "trace",
+ source: "SessionDetail",
+ }}
+ key={"annotation-drawer" + trace.id}
+ environment={trace.environment}
+ />
+ <CommentDrawerButton
+ projectId={projectId}
+ variant="outline"
+ objectId={trace.id}
+ objectType="TRACE"
+ count={getNumberFromMap(
+ traceCommentCounts.data,
+ trace.id,
+ )}
+ />
+ </div>
+ </div>
+ <div className="flex-1">
+ <p className="mb-1 font-medium">Scores</p>
+ <div className="flex flex-wrap content-start items-start gap-1">
+ <GroupedScoreBadges scores={trace.scores} />
+ </div>
+ </div>
+ </div>
</div>
- </div>
- </Card>
- ))}
- {session.data?.traces && session.data.traces.length > visibleTraces && (
- <Button
- onClick={() => setVisibleTraces((prev) => prev + PAGE_SIZE)}
- variant="ghost"
- className="self-center"
- >
- {`Load ${Math.min(session.data.traces.length - visibleTraces, PAGE_SIZE)} More`}
- </Button>
- )}
+ </Card>
+ ))}
+ {session.data?.traces &&
+ session.data.traces.length > visibleTraces && (
+ <Button
+ onClick={() => setVisibleTraces((prev) => prev + PAGE_SIZE)}
+ variant="ghost"
+ className="self-center"
+ >
+ {`Load ${Math.min(session.data.traces.length - visibleTraces, PAGE_SIZE)} More`}
+ </Button>
+ )}
+ </div>
</div>
+ <TablePeekView
+ peekView={{
+ itemType: "TRACE",
+ detailNavigationKey: "traces",
+ openPeek,
+ closePeek,
+ expandPeek,
+ resolveDetailNavigationPath,
+ children: <PeekViewTraceDetail projectId={projectId} />,
+ tableDataUpdatedAt: session.dataUpdatedAt,
+ }}
+ />
</Page>
);
};
@@ -411,3 +476,41 @@ export const SessionIO = ({
</div>
);
};
+
+const NewDatasetItemFromTraceId = (props: {
+ projectId: string;
+ traceId: string;
+ timestamp: Date;
+ buttonVariant?: "outline" | "secondary";
+}) => {
+ // SessionIO already fetches the trace, so this doesn't add an extra request
+ const trace = api.traces.byId.useQuery(
+ {
+ traceId: props.traceId,
+ projectId: props.projectId,
+ timestamp: props.timestamp,
+ },
+ {
+ enabled: typeof props.traceId === "string",
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ },
+ );
+
+ if (!trace.data) return null;
+
+ return (
+ <NewDatasetItemFromExistingObject
+ projectId={props.projectId}
+ traceId={props.traceId}
+ input={trace.data.input ?? null}
+ output={trace.data.output ?? null}
+ metadata={trace.data.metadata ?? null}
+ buttonVariant={props.buttonVariant}
+ />
+ );
+};
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index 323a4a0c1b..90aadcb9f3 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -16,6 +16,7 @@ import { SubHeaderLabel } from "@/src/components/layouts/header";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import useLocalStorage from "@/src/components/useLocalStorage";
+import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";
export const IOPreview: React.FC<{
input?: Prisma.JsonValue;
@@ -55,6 +56,8 @@ export const IOPreview: React.FC<{
const capture = usePostHogClientCapture();
const input = deepParseJson(props.input);
const output = deepParseJson(props.output);
+ const [compensateScrollRef, startPreserveScroll] =
+ usePreserveRelativeScroll<HTMLDivElement>([selectedView]);
// parse old completions: { completion: string } -> string
const outLegacyCompletionSchema = z
@@ -118,14 +121,16 @@ export const IOPreview: React.FC<{
{isPrettyViewAvailable && !currentView ? (
<div className="flex w-full flex-row justify-start">
<Tabs
+ ref={compensateScrollRef}
className="h-fit py-0.5"
value={selectedView}
onValueChange={(value) => {
+ startPreserveScroll();
capture("trace_detail:io_mode_switch", { view: value });
setLocalCurrentView(value as "pretty" | "json");
}}
>
- <TabsList className="h-fit py-0.5">
+ <TabsList className="h-fit p-0.5">
<TabsTrigger value="pretty" className="h-fit px-1 text-xs">
Formatted
</TabsTrigger>
diff --git a/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx b/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
index 02a7bf14d4..0880a62364 100644
--- a/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
@@ -43,6 +43,7 @@ export const NewDatasetItemFromExistingObject = (props: {
output: string | null;
metadata: Prisma.JsonValue;
isCopyItem?: boolean;
+ buttonVariant?: "outline" | "secondary";
}) => {
const parsedInput =
props.input && typeof props.input === "string"
@@ -74,6 +75,7 @@ export const NewDatasetItemFromExistingObject = (props: {
scope: "datasets:CUD",
});
const capture = usePostHogClientCapture();
+ const buttonVariant = props.buttonVariant || "secondary";
return (
<>
@@ -137,7 +139,7 @@ export const NewDatasetItemFromExistingObject = (props: {
object: props.observationId ? "observation" : "trace",
});
}}
- variant="secondary"
+ variant={buttonVariant}
disabled={!hasAccess}
>
{hasAccess ? (
diff --git a/web/src/hooks/usePreserveRelativeScroll.ts b/web/src/hooks/usePreserveRelativeScroll.ts
new file mode 100644
index 0000000000..aade60aea3
--- /dev/null
+++ b/web/src/hooks/usePreserveRelativeScroll.ts
@@ -0,0 +1,171 @@
+import { useCallback, useLayoutEffect, useRef } from "react";
+
+type ScrollTarget = Window | Element;
+
+function isWindow(target: ScrollTarget): target is Window {
+ return (
+ (target as Window).scrollBy !== undefined &&
+ (target as Window).document !== undefined
+ );
+}
+
+function getComputedOverflowY(node: Element): string {
+ const style = window.getComputedStyle(node);
+ return style.overflowY;
+}
+
+function isScrollable(node: Element): boolean {
+ const overflowY = getComputedOverflowY(node);
+ if (overflowY !== "auto" && overflowY !== "scroll") return false;
+ return node.scrollHeight > node.clientHeight;
+}
+
+function findNearestScrollContainer(start: Element): ScrollTarget {
+ let node: Element | null = start;
+ while (node && node !== document.body) {
+ if (isScrollable(node)) return node;
+ node = node.parentElement;
+ }
+ return window;
+}
+
+export interface UsePreserveRelativeScrollOptions {
+ getScrollTarget?: (clickedElement: Element) => ScrollTarget;
+ enabled?: boolean;
+}
+
+/**
+ * Preserves the referenced element's relative scroll position when content size changes.
+ *
+ * @param options - Optional configuration for scroll target detection and enabling the behavior.
+ * @param layoutDeps - Values that change when the layout will reflow due to your interaction
+ * (for example, the selected tab value). Provide stable, memoized values; avoid passing
+ * freshly created objects or inline functions.
+ */
+export function usePreserveRelativeScroll<T extends Element = Element>(
+ layoutDeps: ReadonlyArray<unknown> = [],
+ options?: UsePreserveRelativeScrollOptions,
+): [React.RefObject<T | null>, () => void] {
+ const enabled = options?.enabled ?? true;
+ const beforeTopRef = useRef<number | null>(null);
+ const targetRef = useRef<ScrollTarget | null>(null);
+ const didUserScrollRef = useRef<boolean>(false);
+ const elementRef = useRef<T | null>(null);
+ const compensatedRef = useRef<boolean>(false);
+
+ const attachScrollListener = useCallback(() => {
+ const target = targetRef.current;
+ const cancel = () => {
+ didUserScrollRef.current = true;
+ };
+ const keydownHandler = (e: KeyboardEvent) => {
+ const keys = [
+ "ArrowUp",
+ "ArrowDown",
+ "PageUp",
+ "PageDown",
+ "Home",
+ "End",
+ " ",
+ ];
+ if (keys.includes(e.key)) cancel();
+ };
+ window.addEventListener("wheel", cancel, { passive: true, once: true });
+ window.addEventListener("touchmove", cancel, { passive: true, once: true });
+ window.addEventListener(
+ "keydown",
+ keydownHandler as EventListener,
+ {
+ once: true,
+ } as AddEventListenerOptions,
+ );
+ if (target && !isWindow(target)) {
+ target.addEventListener(
+ "wheel",
+ cancel as EventListener,
+ {
+ passive: true,
+ once: true,
+ } as AddEventListenerOptions,
+ );
+ target.addEventListener(
+ "touchmove",
+ cancel as EventListener,
+ {
+ passive: true,
+ once: true,
+ } as AddEventListenerOptions,
+ );
+ target.addEventListener(
+ "keydown",
+ keydownHandler as EventListener,
+ {
+ once: true,
+ } as AddEventListenerOptions,
+ );
+ }
+ }, []);
+
+ const removeRefs = useCallback(() => {
+ beforeTopRef.current = null;
+ targetRef.current = null;
+ didUserScrollRef.current = false;
+ compensatedRef.current = false;
+ }, []);
+
+ const performCompensation = useCallback(
+ (element: T) => {
+ if (compensatedRef.current) return;
+ const beforeTop = beforeTopRef.current;
+ const target = targetRef.current;
+ if (beforeTop == null || !target) return;
+ if (didUserScrollRef.current) {
+ removeRefs();
+ return;
+ }
+ const afterTop = element.getBoundingClientRect().top;
+ const delta = afterTop - beforeTop;
+ if (Math.abs(delta) < 1) {
+ removeRefs();
+ return;
+ }
+ if (isWindow(target)) {
+ window.scrollBy({ top: delta, left: 0 });
+ } else {
+ (target as Element).scrollTop += delta;
+ }
+ compensatedRef.current = true;
+ removeRefs();
+ },
+ [removeRefs],
+ );
+
+ const startPreserveScroll = useCallback(() => {
+ if (!enabled) return;
+ const element = elementRef.current;
+ if (!element || !element.getBoundingClientRect) return;
+ const rect = element.getBoundingClientRect();
+ beforeTopRef.current = rect.top;
+ targetRef.current =
+ options?.getScrollTarget?.(element) ??
+ findNearestScrollContainer(element);
+ didUserScrollRef.current = false;
+ attachScrollListener();
+ }, [attachScrollListener, enabled, options]);
+
+ const compensateInLayout = useCallback(() => {
+ if (!enabled) return;
+ const element = elementRef.current;
+ if (!element) return;
+ performCompensation(element);
+ }, [enabled, performCompensation]);
+
+ useLayoutEffect(() => {
+ compensateInLayout();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, layoutDeps);
+
+ return [elementRef, startPreserveScroll];
+}
+
+export default usePreserveRelativeScroll;