Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llma): Adding export button to Trace Reviews + tests (#56797)

Sean Malliafd0d12b043e8
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8958e9d3c15e..fbf96132636b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2736,6 +2736,9 @@ importers:
'@testing-library/user-event':
specifier: '*'
version: 13.5.0(@testing-library/[email protected])
+ '@types/papaparse':
+ specifier: '*'
+ version: 5.3.8
'@types/react':
specifier: 18.3.27
version: 18.3.27
@@ -2763,6 +2766,9 @@ importers:
kea-subscriptions:
specifier: 'catalog:'
+ papaparse:
+ specifier: '*'
+ version: 5.4.1
partial-json:
specifier: ^0.1.7
version: 0.1.7
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
index cada6a45d5be..8d1db09c35d3 100644
--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
+++ b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
@@ -515,25 +515,6 @@
events.properties,
events.timestamp
FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', '')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT events__session.`$entry_pathname` AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
LEFT JOIN
(SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
@@ -543,7 +524,7 @@
FROM raw_sessions
WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1))
GROUP BY session_id,
breakdown_value)
GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
diff --git a/products/llm_analytics/backend/api/test/test_trace_reviews.py b/products/llm_analytics/backend/api/test/test_trace_reviews.py
index 13e20b8948d2..31bfd4450438 100644
--- a/products/llm_analytics/backend/api/test/test_trace_reviews.py
+++ b/products/llm_analytics/backend/api/test/test_trace_reviews.py
@@ -1,6 +1,8 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.test import override_settings
+
from parameterized import parameterized
from rest_framework import status
@@ -101,6 +103,20 @@ class TestTraceReviewsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_list_response_includes_absolute_trace_url(self):
+ self._create_review(trace_id="trace_link_check")
+
+ response = self.client.get(self._endpoint())
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(
+ results[0]["trace_url"],
+ f"https://us.posthog.com/project/{self.team.id}/llm-analytics/traces/trace_link_check",
+ )
+
def test_can_create_review_without_score_or_comment(self):
response = self.client.post(self._endpoint(), {"trace_id": "trace_123"}, format="json")
diff --git a/products/llm_analytics/backend/api/trace_reviews.py b/products/llm_analytics/backend/api/trace_reviews.py
index f52535bd77ee..1cc9164787df 100644
--- a/products/llm_analytics/backend/api/trace_reviews.py
+++ b/products/llm_analytics/backend/api/trace_reviews.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any, cast
+from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import Prefetch, Q, QuerySet
from django.utils import timezone
@@ -11,7 +12,7 @@ import django_filters
import posthoganalytics
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse
+from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema_field
from rest_framework import serializers, status
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
@@ -128,6 +129,9 @@ class TraceReviewSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Trace ID for the review.",
)
+ trace_url = serializers.SerializerMethodField(
+ help_text="Absolute URL to the trace this review is attached to.",
+ )
comment = serializers.CharField(
read_only=True,
allow_null=True,
@@ -141,11 +145,16 @@ class TraceReviewSerializer(serializers.ModelSerializer):
help_text="Saved scorer values for this review.",
)
+ @extend_schema_field(OpenApiTypes.URI)
+ def get_trace_url(self, obj: TraceReview) -> str:
+ return f"{settings.SITE_URL}/project/{obj.team_id}/llm-analytics/traces/{obj.trace_id}"
+
class Meta:
model = TraceReview
fields = [
"id",
"trace_id",
+ "trace_url",
"comment",
"created_at",
"updated_at",
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index 38c4f228163d..da72774b5e37 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -1476,6 +1476,8 @@ export interface TraceReviewApi {
readonly id: string
/** Trace ID for the review. */
readonly trace_id: string
+ /** Absolute URL to the trace this review is attached to. */
+ readonly trace_url: string
/**
* Optional comment or reasoning for the review.
* @nullable
diff --git a/products/llm_analytics/frontend/traceReviews/LLMAnalyticsReviews.tsx b/products/llm_analytics/frontend/traceReviews/LLMAnalyticsReviews.tsx
index 8b41c1d6d2af..fe53d8d24ca0 100644
--- a/products/llm_analytics/frontend/traceReviews/LLMAnalyticsReviews.tsx
+++ b/products/llm_analytics/frontend/traceReviews/LLMAnalyticsReviews.tsx
@@ -1,13 +1,24 @@
import { useActions, useMountedLogic, useValues } from 'kea'
-import { LemonInput, LemonSelect, LemonTable, LemonTableColumn, LemonTableColumns } from '@posthog/lemon-ui'
+import { IconDownload } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonInput,
+ LemonMenu,
+ LemonSelect,
+ LemonTable,
+ LemonTableColumn,
+ LemonTableColumns,
+} from '@posthog/lemon-ui'
+import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { Link } from 'lib/lemon-ui/Link'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { updatedAtColumn } from '~/lib/lemon-ui/LemonTable/columnUtils'
import { urls } from '~/scenes/urls'
+import { ExporterFormat } from '~/types'
import { llmAnalyticsReviewsLogic, TRACE_REVIEWS_PER_PAGE } from './llmAnalyticsReviewsLogic'
import { TraceReviewValue } from './TraceReviewValue'
@@ -19,7 +30,8 @@ function formatTraceId(traceId: string): string {
export function LLMAnalyticsReviews({ tabId }: { tabId?: string }): JSX.Element {
const logic = useMountedLogic(llmAnalyticsReviewsLogic({ tabId }))
- const { setFilters } = useActions(logic)
+ const { setFilters, copyReviewsToClipboard } = useActions(logic)
+ const { startExport } = useActions(exportsLogic)
const {
reviews,
reviewsLoading,
@@ -27,10 +39,28 @@ export function LLMAnalyticsReviews({ tabId }: { tabId?: string }): JSX.Element
pagination,
filters,
reviewCountLabel,
+ exportPath,
scoreDefinitionOptions,
scoreDefinitionOptionsLoading,
} = useValues(logic)
+ const triggerFileExport = (format: ExporterFormat, extension: 'csv' | 'xlsx'): void => {
+ startExport({
+ export_format: format,
+ export_context: {
+ path: exportPath,
+ method: 'GET',
+ filename: `trace_reviews.${extension}`,
+ },
+ })
+ }
+
+ const hasLoadedReviews = reviews.results.length > 0
+ let exportDisabledReason: string | undefined
+ if (!hasLoadedReviews) {
+ exportDisabledReason = reviewsLoading ? 'Loading reviews...' : 'No reviews to export'
+ }
+
const columns: LemonTableColumns<TraceReview> = [
{
title: 'Trace',
@@ -125,7 +155,56 @@ export function LLMAnalyticsReviews({ tabId }: { tabId?: string }): JSX.Element
data-attr="llma-trace-reviews-definition-filter"
/>
</div>
- <div className="text-muted-alt">{reviewCountLabel}</div>
+ <div className="flex gap-2 items-center">
+ <span className="text-muted-alt">{reviewCountLabel}</span>
+ <LemonMenu
+ items={[
+ {
+ label: 'Export current columns',
+ items: [
+ {
+ label: 'CSV',
+ onClick: () => triggerFileExport(ExporterFormat.CSV, 'csv'),
+ },
+ {
+ label: 'XLSX',
+ onClick: () => triggerFileExport(ExporterFormat.XLSX, 'xlsx'),
+ },
+ ],
+ },
+ {
+ label: 'Copy to clipboard',
+ items: [
+ {
+ label: 'CSV',
+ onClick: () => copyReviewsToClipboard('csv'),
+ 'data-attr': 'copy-csv-to-clipboard',
+ },
+ {
+ label: 'JSON',
+ onClick: () => copyReviewsToClipboard('json'),
+ 'data-attr': 'copy-json-to-clipboard',
+ },
+ {
+ label: 'Excel',
+ onClick: () => copyReviewsToClipboard('tsv'),
+ 'data-attr': 'copy-excel-to-clipboard',
+ },
+ ],
+ },
+ ]}
+ >
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ size="small"
+ disabledReason={exportDisabledReason}
+ data-attr="llma-trace-reviews-export-menu"
+ >
+ Export
+ </LemonButton>
+ </LemonMenu>
+ </div>
</div>
<LemonTable
diff --git a/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.test.ts b/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.test.ts
new file mode 100644
index 000000000000..9a6e65297d6e
--- /dev/null
+++ b/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.test.ts
@@ -0,0 +1,148 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { initKeaTests } from '~/test/init'
+
+import { llmAnalyticsReviewsLogic } from './llmAnalyticsReviewsLogic'
+import { traceReviewsApi } from './traceReviewsApi'
+import { CLIPBOARD_ROW_LIMIT } from './traceReviewsExport'
+import type { TraceReview } from './types'
+
+jest.mock('lib/utils/copyToClipboard')
+jest.mock('@posthog/lemon-ui', () => ({
+ ...jest.requireActual('@posthog/lemon-ui'),
+ lemonToast: {
+ error: jest.fn(),
+ warning: jest.fn(),
+ },
+}))
+jest.mock('./traceReviewsApi', () => ({
+ ...jest.requireActual('./traceReviewsApi'),
+ traceReviewsApi: {
+ list: jest.fn(),
+ },
+}))
+jest.mock('../generated/api', () => ({
+ llmAnalyticsScoreDefinitionsList: jest
+ .fn()
+ .mockResolvedValue({ results: [], count: 0, next: null, previous: null }),
+}))
+
+const mockTraceReviewsList = traceReviewsApi.list as jest.MockedFunction<typeof traceReviewsApi.list>
+const mockCopyToClipboard = copyToClipboard as jest.MockedFunction<typeof copyToClipboard>
+const mockLemonToastError = lemonToast.error as jest.MockedFunction<typeof lemonToast.error>
+const mockLemonToastWarning = lemonToast.warning as jest.MockedFunction<typeof lemonToast.warning>
+
+const baseReview: TraceReview = {
+ id: 'review-1',
+ trace_id: 'trace-abc',
+ trace_url: 'https://us.posthog.com/project/1/llm-analytics/traces/trace-abc',
+ comment: 'Looks good',
+ created_at: '2026-03-12T00:00:00Z',
+ updated_at: '2026-03-12T01:00:00Z',
+ created_by: null,
+ reviewed_by: null,
+ scores: [],
+ team: 1,
+}
+
+describe('llmAnalyticsReviewsLogic.copyReviewsToClipboard', () => {
+ let logic: ReturnType<typeof llmAnalyticsReviewsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ logic = llmAnalyticsReviewsLogic({ tabId: 'test-tab' })
+ // Stub the initial mount load so afterMount doesn't interfere with our test mocks.
+ mockTraceReviewsList.mockResolvedValue({ results: [], count: 0 })
+ logic.mount()
+ })
+
+ it('copies the formatted payload to the clipboard on the happy path', async () => {
+ mockTraceReviewsList.mockReset()
+ mockTraceReviewsList.mockResolvedValueOnce({ results: [baseReview], count: 1 })
+
+ await expectLogic(logic, () => {
+ logic.actions.copyReviewsToClipboard('csv')
+ }).toFinishAllListeners()
+
+ expect(mockCopyToClipboard).toHaveBeenCalledTimes(1)
+ expect(mockCopyToClipboard.mock.calls[0][1]).toBe('reviews')
+ })
+
+ it('shows an error toast and skips the clipboard write when there are no reviews', async () => {
+ mockTraceReviewsList.mockReset()
+ mockTraceReviewsList.mockResolvedValueOnce({ results: [], count: 0 })
+
+ await expectLogic(logic, () => {
+ logic.actions.copyReviewsToClipboard('csv')
+ }).toFinishAllListeners()
+
+ expect(mockLemonToastError).toHaveBeenCalledWith('No reviews to copy!')
+ expect(mockCopyToClipboard).not.toHaveBeenCalled()
+ })
+
+ it('shows a warning pointing at the file export when the dataset exceeds the cap', async () => {
+ mockTraceReviewsList.mockReset()
+ mockTraceReviewsList.mockResolvedValueOnce({
+ results: [baseReview],
+ count: CLIPBOARD_ROW_LIMIT + 1,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.copyReviewsToClipboard('csv')
+ }).toFinishAllListeners()
+
+ expect(mockLemonToastWarning).toHaveBeenCalledTimes(1)
+ const message = mockLemonToastWarning.mock.calls[0][0] as string
+ expect(message).toContain(String(CLIPBOARD_ROW_LIMIT + 1))
+ expect(message).toContain('Export current columns')
+ expect(mockCopyToClipboard).not.toHaveBeenCalled()
+ })
+
+ it('falls back to an error toast when the fetch fails', async () => {
+ mockTraceReviewsList.mockReset()
+ mockTraceReviewsList.mockRejectedValueOnce(new Error('network down'))
+
+ await expectLogic(logic, () => {
+ logic.actions.copyReviewsToClipboard('csv')
+ }).toFinishAllListeners()
+
+ expect(mockLemonToastError).toHaveBeenCalledWith('Copy failed!')
+ })
+
+ it('cancels an earlier invocation when called twice in quick succession', async () => {
+ mockTraceReviewsList.mockReset()
+ let resolveFirst: ((value: { results: TraceReview[]; count: number }) => void) | undefined
+ mockTraceReviewsList
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFirst = resolve
+ })
+ )
+ .mockResolvedValueOnce({ results: [baseReview], count: 1 })
+
+ // Click 1 hangs on the API; click 2 resolves immediately and should win.
+ logic.actions.copyReviewsToClipboard('csv')
+ logic.actions.copyReviewsToClipboard('csv')
+
+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
+ await flush()
+ await flush()
+
+ // Click 2 has finished and written to the clipboard.
+ expect(mockCopyToClipboard).toHaveBeenCalledTimes(1)
+
+ // Now unblock click 1: when it resumes, breakpoint() should detect the newer
+ // invocation and throw, so no second clipboard write happens.
+ resolveFirst?.({ results: [baseReview], count: 1 })
+ await flush()
+ await flush()
+
+ expect(mockCopyToClipboard).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.ts b/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.ts
index 8b2dcd98a922..daa8fc8bfb4a 100644
--- a/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.ts
+++ b/products/llm_analytics/frontend/traceReviews/llmAnalyticsReviewsLogic.ts
@@ -1,8 +1,11 @@
-import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import { lemonToast } from '@posthog/lemon-ui'
+
import { Sorting } from 'lib/lemon-ui/LemonTable'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { CountedPaginatedResponse } from '~/lib/api'
import { ApiConfig } from '~/lib/api'
@@ -15,7 +18,8 @@ import { urls } from '~/scenes/urls'
import { llmAnalyticsScoreDefinitionsList } from '../generated/api'
import type { ScoreDefinitionApi } from '../generated/api.schemas'
import type { llmAnalyticsReviewsLogicType } from './llmAnalyticsReviewsLogicType'
-import { traceReviewsApi } from './traceReviewsApi'
+import { buildTraceReviewsListUrl, traceReviewListParamsFromFilters, traceReviewsApi } from './traceReviewsApi'
+import { fetchAllReviewsForExport, formatReviewsForClipboard, type ReviewClipboardFormat } from './traceReviewsExport'
import type { TraceReview } from './types'
export const TRACE_REVIEWS_PER_PAGE = 30
@@ -71,6 +75,7 @@ export const llmAnalyticsReviewsLogic = kea<llmAnalyticsReviewsLogicType>([
}),
loadReviews: (debounce: boolean = true) => ({ debounce }),
loadScoreDefinitionOptions: true,
+ copyReviewsToClipboard: (format: ReviewClipboardFormat) => ({ format }),
}),
reducers({
@@ -99,9 +104,7 @@ export const llmAnalyticsReviewsLogic = kea<llmAnalyticsReviewsLogicType>([
const { filters } = values
return traceReviewsApi.list({
- search: filters.search || undefined,
- definition_id: filters.definition_id || undefined,
- order_by: filters.order_by,
+ ...traceReviewListParamsFromFilters(filters),
offset: Math.max(0, (filters.page - 1) * TRACE_REVIEWS_PER_PAGE),
limit: TRACE_REVIEWS_PER_PAGE,
})
@@ -160,6 +163,12 @@ export const llmAnalyticsReviewsLogic = kea<llmAnalyticsReviewsLogicType>([
return count === 0 ? '0 reviews' : `${start}-${end} of ${pluralize(count, 'review')}`
},
],
+
+ exportPath: [
+ (s) => [s.filters],
+ (filters: TraceReviewFilters): string =>
+ buildTraceReviewsListUrl(undefined, traceReviewListParamsFromFilters(filters)),
+ ],
}),
listeners(({ asyncActions, values, selectors }) => ({
@@ -170,6 +179,33 @@ export const llmAnalyticsReviewsLogic = kea<llmAnalyticsReviewsLogicType>([
await asyncActions.loadReviews(debounce)
}
},
+ copyReviewsToClipboard: async ({ format }, breakpoint) => {
+ try {
+ const { reviews, total, truncated } = await fetchAllReviewsForExport(values.filters)
+ breakpoint()
+
+ if (total === 0) {
+ lemonToast.error('No reviews to copy!')
+ return
+ }
+
+ if (truncated) {
+ lemonToast.warning(
+ `Too many reviews to copy to clipboard (${total}). Use "Export current columns" to download a file instead.`
+ )
+ return
+ }
+
+ const payload = formatReviewsForClipboard(reviews, format)
+ await copyToClipboard(payload, 'reviews')
+ breakpoint()
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ return
+ }
+ lemonToast.error('Copy failed!')
+ }
+ },
})),
tabAwareActionToUrl(({ values }) => ({
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
index 94367faf85b9..e6c2047e5b60 100644
--- a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
@@ -73,6 +73,7 @@ describe('traceReviewModalLogic', () => {
const existingReview: TraceReview = {
id: 'review_1',
trace_id: 'trace_1',
+ trace_url: `https://us.posthog.com/project/${MOCK_DEFAULT_TEAM.id}/llm-analytics/traces/trace_1`,
comment: 'Needs investigation',
created_at: '2026-03-12T00:00:00Z',
updated_at: '2026-03-12T00:00:00Z',
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewsApi.ts b/products/llm_analytics/frontend/traceReviews/traceReviewsApi.ts
index bc4a61455423..c14bab1af4b0 100644
--- a/products/llm_analytics/frontend/traceReviews/traceReviewsApi.ts
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewsApi.ts
@@ -35,7 +35,23 @@ function getTraceReviewsBaseUrl(teamId: number = ApiConfig.getCurrentTeamId()):
return `/api/environments/${teamId}/llm_analytics/trace_reviews/`
}
-function buildTraceReviewsListUrl(
+export interface TraceReviewListFilters {
+ search: string
+ definition_id: string
+ order_by: string
+}
+
+export function traceReviewListParamsFromFilters(
+ filters: TraceReviewListFilters
+): Pick<TraceReviewListParams, 'search' | 'definition_id' | 'order_by'> {
+ return {
+ search: filters.search || undefined,
+ definition_id: filters.definition_id || undefined,
+ order_by: filters.order_by,
+ }
+}
+
+export function buildTraceReviewsListUrl(
teamId: number = ApiConfig.getCurrentTeamId(),
params?: TraceReviewListParams
): string {
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewsExport.test.ts b/products/llm_analytics/frontend/traceReviews/traceReviewsExport.test.ts
new file mode 100644
index 000000000000..874c784603c2
--- /dev/null
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewsExport.test.ts
@@ -0,0 +1,244 @@
+import Papa from 'papaparse'
+
+import { traceReviewsApi, type TraceReviewListFilters } from './traceReviewsApi'
+import {
+ CLIPBOARD_ROW_LIMIT,
+ fetchAllReviewsForExport,
+ formatReviewsForClipboard,
+ getReviewClipboardRows,
+} from './traceReviewsExport'
+import type { TraceReview, TraceReviewScore } from './types'
+
+jest.mock('papaparse', () => ({
+ unparse: jest.fn((data: unknown, options: { delimiter?: string } = {}) => {
+ const delimiter = options.delimiter || ','
+ return `mock-papa-unparse:${delimiter}:${JSON.stringify(data)}`
+ }),
+}))
+jest.mock('./traceReviewsApi', () => ({
+ ...jest.requireActual('./traceReviewsApi'),
+ traceReviewsApi: {
+ list: jest.fn(),
+ },
+}))
+
+const mockPapaUnparse = Papa.unparse as jest.MockedFunction<typeof Papa.unparse>
+const mockTraceReviewsList = traceReviewsApi.list as jest.MockedFunction<typeof traceReviewsApi.list>
+
+const filters: TraceReviewListFilters = {
+ search: 'auth',
+ definition_id: 'def-1',
+ order_by: '-updated_at',
+}
+
+const baseScore: TraceReviewScore = {
+ id: 'score-1',
+ definition_id: 'definition-1',
+ definition_name: 'Helpfulness',
+ definition_kind: 'categorical',
+ definition_archived: false,
+ definition_version_id: 'version-1',
+ definition_version: 1,
+ definition_config: {
+ options: [{ key: 'good', label: 'Good' }],
+ selection_mode: 'single',
+ },
+ categorical_values: ['good'],
+ numeric_value: null,
+ boolean_value: null,
+ created_at: '2026-03-12T00:00:00Z',
+ updated_at: null,
+}
+
+const baseReview: TraceReview = {
+ id: 'review-1',
+ trace_id: 'trace-abc',
+ trace_url: 'https://us.posthog.com/project/1/llm-analytics/traces/trace-abc',
+ comment: 'Looks good',
+ created_at: '2026-03-12T00:00:00Z',
+ updated_at: '2026-03-12T01:00:00Z',
+ created_by: {
+ id: 7,
+ uuid: 'user-uuid-7',
+ distinct_id: 'distinct-7',
+ first_name: 'Ada',
+ last_name: 'Lovelace',
+ email: '[email protected]',
+ },
+ reviewed_by: {
+ id: 8,
+ uuid: 'user-uuid-8',
+ distinct_id: 'distinct-8',
+ first_name: 'Grace',
+ last_name: 'Hopper',
+ email: '[email protected]',
+ },
+ scores: [baseScore],
+ team: 1,
+}
+
+describe('traceReviewsExport', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ describe('getReviewClipboardRows', () => {
+ it('returns an empty array when no reviews are passed', () => {
+ expect(getReviewClipboardRows([])).toEqual([])
+ })
+
+ it('flattens nested user objects with column-prefixed keys', () => {
+ const [row] = getReviewClipboardRows([baseReview])
+
+ expect(row['reviewed_by.email']).toBe('[email protected]')
+ expect(row['reviewed_by.first_name']).toBe('Grace')
+ expect(row['created_by.email']).toBe('[email protected]')
+ expect(row).not.toHaveProperty('reviewed_by')
+ expect(row).not.toHaveProperty('created_by')
+ })
+
+ it('expands score arrays into indexed dotted keys mirroring rest_framework_csv', () => {
+ const [row] = getReviewClipboardRows([baseReview])
+
+ expect(row['scores.0.id']).toBe('score-1')
+ expect(row['scores.0.definition_id']).toBe('definition-1')
+ expect(row['scores.0.definition_name']).toBe('Helpfulness')
+ expect(row['scores.0.categorical_values.0']).toBe('good')
+ expect(row['scores.0.definition_config.selection_mode']).toBe('single')
+ expect(row['scores.0.definition_config.options.0.key']).toBe('good')
+ expect(row['scores.0.definition_config.options.0.label']).toBe('Good')
+ expect(row).not.toHaveProperty('scores')
+ })
+
+ it('produces ragged columns when reviews have different score counts (matches server-side)', () => {
+ const reviewWithTwoScores: TraceReview = {
+ ...baseReview,
+ id: 'review-2',
+ scores: [baseScore, { ...baseScore, id: 'score-2', definition_name: 'Accuracy' }],
+ }
+ const [single, double] = getReviewClipboardRows([baseReview, reviewWithTwoScores])
+
+ expect(single['scores.0.id']).toBe('score-1')
+ expect(single).not.toHaveProperty('scores.1.id')
+
+ expect(double['scores.0.id']).toBe('score-1')
+ expect(double['scores.1.id']).toBe('score-2')
+ expect(double['scores.1.definition_name']).toBe('Accuracy')
+ })
+
+ it('copies primitive review fields as-is', () => {
+ const [row] = getReviewClipboardRows([baseReview])
+
+ expect(row.trace_id).toBe('trace-abc')
+ expect(row.comment).toBe('Looks good')
+ expect(row.created_at).toBe('2026-03-12T00:00:00Z')
+ expect(row.updated_at).toBe('2026-03-12T01:00:00Z')
+ })
+
+ it('includes the absolute trace URL alongside the trace_id', () => {
+ const [row] = getReviewClipboardRows([baseReview])
+
+ expect(row.trace_url).toBe('https://us.posthog.com/project/1/llm-analytics/traces/trace-abc')
+ })
+
+ it('preserves null user fields without throwing', () => {
+ const review: TraceReview = {
+ ...baseReview,
+ created_by: null,
+ reviewed_by: null,
+ }
+
+ const [row] = getReviewClipboardRows([review])
+
+ expect(row.reviewed_by).toBeNull()
+ expect(row.created_by).toBeNull()
+ })
+
+ it('mirrors the file-export shape by including every serializer field (id, team, ...)', () => {
+ const [row] = getReviewClipboardRows([baseReview])
+
+ expect(row.id).toBe('review-1')
+ expect(row.team).toBe(1)
+ })
+ })
+
+ describe('fetchAllReviewsForExport', () => {
+ it('paginates until the full dataset is fetched', async () => {
+ const reviewA = { ...baseReview, id: 'a' }
+ const reviewB = { ...baseReview, id: 'b' }
+ const reviewC = { ...baseReview, id: 'c' }
+ mockTraceReviewsList
+ .mockResolvedValueOnce({ results: [reviewA, reviewB], count: 3 })
+ .mockResolvedValueOnce({ results: [reviewC], count: 3 })
+
+ const result = await fetchAllReviewsForExport(filters)
+
+ expect(mockTraceReviewsList).toHaveBeenCalledTimes(2)
+ expect(mockTraceReviewsList.mock.calls[0][0]).toMatchObject({
+ search: 'auth',
+ definition_id: 'def-1',
+ order_by: '-updated_at',
+ offset: 0,
+ })
+ expect(mockTraceReviewsList.mock.calls[1][0]).toMatchObject({ offset: 2 })
+ expect(result.reviews.map((r) => r.id)).toEqual(['a', 'b', 'c'])
+ expect(result.total).toBe(3)
+ expect(result.truncated).toBe(false)
+ })
+
+ it('flags the result as truncated when count exceeds the cap and skips further pages', async () => {
+ mockTraceReviewsList.mockResolvedValueOnce({
+ results: [baseReview],
+ count: CLIPBOARD_ROW_LIMIT + 1,
+ })
+
+ const result = await fetchAllReviewsForExport(filters)
+
+ expect(mockTraceReviewsList).toHaveBeenCalledTimes(1)
+ expect(result.truncated).toBe(true)
+ expect(result.total).toBe(CLIPBOARD_ROW_LIMIT + 1)
+ })
+
+ it('treats blank filter values as undefined when calling the API', async () => {
+ mockTraceReviewsList.mockResolvedValueOnce({ results: [], count: 0 })
+
+ await fetchAllReviewsForExport({ search: '', definition_id: '', order_by: '-updated_at' })
+
+ expect(mockTraceReviewsList.mock.calls[0][0]).toMatchObject({
+ search: undefined,
+ definition_id: undefined,
+ order_by: '-updated_at',
+ })
+ })
+ })
+
+ describe('formatReviewsForClipboard', () => {
+ it.each([
+ ['csv', undefined, 'mock-papa-unparse:,:'],
+ ['tsv', { delimiter: '\t' }, 'mock-papa-unparse:\t:'],
+ ] as const)(
+ 'formats %s via Papa.unparse with the matching options',
+ (format, expectedOptions, expectedPrefix) => {
+ const payload = formatReviewsForClipboard([baseReview], format)
+
+ expect(mockPapaUnparse).toHaveBeenCalledTimes(1)
+ const [rowsArg, optionsArg] = mockPapaUnparse.mock.calls[0]
+ expect(rowsArg).toHaveLength(1)
+ expect(optionsArg).toEqual(expectedOptions)
+ expect(payload).toContain(expectedPrefix)
+ }
+ )
+
+ it('formats JSON as the nested API shape, not the flattened CSV shape', () => {
+ const payload = formatReviewsForClipboard([baseReview], 'json')
+
+ expect(mockPapaUnparse).not.toHaveBeenCalled()
+ const parsed = JSON.parse(payload)
+ expect(Array.isArray(parsed)).toBe(true)
+ expect(parsed[0]).toEqual(baseReview)
+ expect(parsed[0].scores[0].id).toBe('score-1')
+ expect(parsed[0].created_by.email).toBe('[email protected]')
+ expect(payload).toContain('\n ')
+ })
+ })
+})
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewsExport.ts b/products/llm_analytics/frontend/traceReviews/traceReviewsExport.ts
new file mode 100644
index 000000000000..188ac758e938
--- /dev/null
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewsExport.ts
@@ -0,0 +1,83 @@
+import Papa from 'papaparse'
+
+import { traceReviewListParamsFromFilters, traceReviewsApi, type TraceReviewListFilters } from './traceReviewsApi'
+import type { TraceReview } from './types'
+
+export type ReviewClipboardFormat = 'csv' | 'json' | 'tsv'
+
+export const CLIPBOARD_ROW_LIMIT = 5000
+const CLIPBOARD_PAGE_SIZE = 500
+const LEVEL_SEP = '.'
+
+// Mirrors rest_framework_csv.CSVRenderer.flatten_item so client-side clipboard
+// output matches the server-side file export shape exactly: nested dicts produce
+// dotted keys (created_by.email), and lists expand by index (scores.0.id, scores.1.id).
+function nestFlatItem(flat: Record<string, unknown>, prefix: string): Record<string, unknown> {
+ const nested: Record<string, unknown> = {}
+ for (const [header, val] of Object.entries(flat)) {
+ nested[header ? `${prefix}${LEVEL_SEP}${header}` : prefix] = val
+ }
+ return nested
+}
+
+function flattenItem(item: unknown): Record<string, unknown> {
+ if (Array.isArray(item)) {
+ const flat: Record<string, unknown> = {}
+ item.forEach((value, index) => {
+ Object.assign(flat, nestFlatItem(flattenItem(value), String(index)))
+ })
+ return flat
+ }
+ if (item !== null && typeof item === 'object') {
+ const flat: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(item as Record<string, unknown>)) {
+ Object.assign(flat, nestFlatItem(flattenItem(value), key))
+ }
+ return flat
+ }
+ return { '': item }
+}
+
+export function getReviewClipboardRows(reviews: TraceReview[]): Record<string, unknown>[] {
+ return reviews.map((review) => flattenItem(review))
+}
+
+export async function fetchAllReviewsForExport(
+ filters: TraceReviewListFilters,
+ maxRows: number = CLIPBOARD_ROW_LIMIT
+): Promise<{ reviews: TraceReview[]; total: number; truncated: boolean }> {
+ const baseParams = traceReviewListParamsFromFilters(filters)
+
+ const first = await traceReviewsApi.list({
+ ...baseParams,
+ offset: 0,
+ limit: CLIPBOARD_PAGE_SIZE,
+ })
+
+ if (first.count > maxRows) {
+ return { reviews: first.results, total: first.count, truncated: true }
+ }
+
+ const reviews = [...first.results]
+ while (reviews.length < first.count) {
+ const page = await traceReviewsApi.list({
+ ...baseParams,
+ offset: reviews.length,
+ limit: CLIPBOARD_PAGE_SIZE,
+ })
+ if (page.results.length === 0) {
+ break
+ }
+ reviews.push(...page.results)
+ }
+
+ return { reviews, total: first.count, truncated: false }
+}
+
+export function formatReviewsForClipboard(reviews: TraceReview[], format: ReviewClipboardFormat): string {
+ // JSON keeps the nested API shape; CSV/TSV flatten to mirror rest_framework_csv on the server.
+ if (format === 'json') {
+ return JSON.stringify(reviews, null, 4)
+ }
+ return Papa.unparse(getReviewClipboardRows(reviews), format === 'tsv' ? { delimiter: '\t' } : undefined)
+}
diff --git a/products/llm_analytics/frontend/traceReviews/types.ts b/products/llm_analytics/frontend/traceReviews/types.ts
index 5f664ced716a..cada050d159a 100644
--- a/products/llm_analytics/frontend/traceReviews/types.ts
+++ b/products/llm_analytics/frontend/traceReviews/types.ts
@@ -26,6 +26,7 @@ export interface TraceReviewScore {
export interface TraceReview {
id: string
trace_id: string
+ trace_url: string
comment: string | null
created_at: string
updated_at: string | null
diff --git a/products/llm_analytics/frontend/traceReviews/utils.test.ts b/products/llm_analytics/frontend/traceReviews/utils.test.ts
index 60551f5261c5..afe789f54379 100644
--- a/products/llm_analytics/frontend/traceReviews/utils.test.ts
+++ b/products/llm_analytics/frontend/traceReviews/utils.test.ts
@@ -31,6 +31,7 @@ describe('traceReviews utils', () => {
const baseReview: TraceReview = {
id: 'review-1',
trace_id: 'trace-1',
+ trace_url: 'https://us.posthog.com/project/1/llm-analytics/traces/trace-1',
comment: null,
created_at: '2026-03-12T00:00:00Z',
updated_at: null,
diff --git a/products/llm_analytics/package.json b/products/llm_analytics/package.json
index 1cabcbeaf52d..6ed1a25cd96c 100644
--- a/products/llm_analytics/package.json
+++ b/products/llm_analytics/package.json
@@ -22,10 +22,12 @@
"@testing-library/jest-dom": "*",
"@testing-library/react": "*",
"@testing-library/user-event": "*",
+ "@types/papaparse": "*",
"@types/react": "*",
"clsx": "*",
"eslint": "*",
"jest": "*",
+ "papaparse": "*",
"react": "*",
"stylelint": "*",
"typescript": "*",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7e4662df6314..156f99b3504a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23756,6 +23756,8 @@ export namespace Schemas {
readonly id: string;
/** Trace ID for the review. */
readonly trace_id: string;
+ /** Absolute URL to the trace this review is attached to. */
+ readonly trace_url: string;
/**
* Optional comment or reasoning for the review.
* @nullable