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.

10.6 KB
Raw Blame
import { useActions, useMountedLogic, useValues } from 'kea'

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 { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'

import { updatedAtColumn } from '~/lib/lemon-ui/LemonTable/columnUtils'
import { urls } from '~/scenes/urls'
import { AccessControlLevel, AccessControlResourceType, ExporterFormat } from '~/types'

import { TraceDrawerHost } from '../redesign/trace/TraceDrawerHost'
import { useTraceDrawerTable } from '../redesign/trace/TraceDrawerRowsHost'
import { TraceListRow } from '../redesign/trace/traceListRows'
import { aiObservabilityReviewsLogic, TRACE_REVIEWS_PER_PAGE } from './aiObservabilityReviewsLogic'
import { TraceReviewValue } from './TraceReviewValue'
import type { TraceReview } from './types'

const TRACE_DRAWER_LIST_ID = 'reviews'
const TRACE_LINK = '[data-attr="llma-trace-review-trace-link"]'

function formatTraceId(traceId: string): string {
    return traceId.length > 12 ? `${traceId.slice(0, 4)}...${traceId.slice(-4)}` : traceId
}

// `created_at` is when the review happened, which says nothing about when the trace did, so no timestamp.
function toTraceDrawerRow(review: TraceReview): TraceListRow | null {
    return review.trace_id ? { traceId: review.trace_id, timestamp: null, stepId: null } : null
}

export function AIObservabilityReviews(): JSX.Element {
    const logic = useMountedLogic(aiObservabilityReviewsLogic())
    const { setFilters, copyReviewsToClipboard } = useActions(logic)
    const { startExport } = useActions(exportsLogic)
    const {
        reviews,
        reviewsLoading,
        sorting,
        pagination,
        filters,
        reviewCountLabel,
        exportPath,
        scoreDefinitionOptions,
        scoreDefinitionOptionsLoading,
    } = useValues(logic)
    const drawerTableProps = useTraceDrawerTable(TRACE_DRAWER_LIST_ID, TRACE_LINK, toTraceDrawerRow)

    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'
    }

    // Creating an export requires editor access to the export resource.
    const exportAccessControlDisabledReason = getAccessControlDisabledReason(
        AccessControlResourceType.Export,
        AccessControlLevel.Editor
    )
    const fileExportDisabledReason = exportDisabledReason ?? exportAccessControlDisabledReason ?? undefined

    const columns: LemonTableColumns<TraceReview> = [
        {
            title: 'Trace',
            dataIndex: 'trace_id',
            key: 'trace_id',
            width: '22%',
            render: function renderTraceId(traceId) {
                const value = String(traceId || '')

                if (!value) {
                    return <span className="text-muted">–</span>
                }

                return (
                    <Tooltip title={value}>
                        <Link to={urls.aiObservabilityTrace(value)} data-attr="llma-trace-review-trace-link">
                            {formatTraceId(value)}
                        </Link>
                    </Tooltip>
                )
            },
        },
        {
            title: 'Review',
            key: 'review',
            width: '16%',
            render: function renderReview(_, review) {
                return <TraceReviewValue review={review} />
            },
        },
        {
            title: 'Comment',
            dataIndex: 'comment',
            key: 'comment',
            width: '34%',
            render: function renderComment(comment) {
                const value = String(comment || '')

                if (!value) {
                    return <span className="text-muted">–</span>
                }

                return (
                    <Tooltip title={value}>
                        <span className="block max-w-2xl truncate text-muted-alt">{value}</span>
                    </Tooltip>
                )
            },
        },
        {
            title: 'Reviewed by',
            dataIndex: 'reviewed_by',
            key: 'reviewed_by',
            render: function renderReviewedBy(_, review) {
                return review.reviewed_by ? (
                    <div className="flex flex-row items-center flex-nowrap">
                        <ProfilePicture user={review.reviewed_by} size="md" showName />
                    </div>
                ) : (
                    <span className="text-muted">–</span>
                )
            },
        },
        updatedAtColumn<TraceReview>() as LemonTableColumn<TraceReview, keyof TraceReview | undefined>,
    ]

    return (
        <>
            <div className="space-y-4">
                <div className="flex gap-x-4 gap-y-2 items-center flex-wrap py-4 -mt-4 mb-4 border-b justify-between">
                    <div className="flex gap-2 items-center flex-wrap">
                        <LemonInput
                            type="search"
                            placeholder="Search reviews..."
                            value={filters.search}
                            onChange={(value) => setFilters({ search: value })}
                            className="max-w-md"
                            data-attr="llma-trace-reviews-search-input"
                        />
                        <LemonSelect
                            value={filters.definition_id || undefined}
                            onChange={(value) => setFilters({ definition_id: value ? String(value) : '' })}
                            options={[
                                { label: 'All scorers', value: '' },
                                ...scoreDefinitionOptions.map((definition) => ({
                                    label: definition.name,
                                    value: definition.id,
                                })),
                            ]}
                            placeholder="Filter by scorer"
                            loading={scoreDefinitionOptionsLoading}
                            className="min-w-60"
                            data-attr="llma-trace-reviews-definition-filter"
                        />
                    </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'),
                                            disabledReason: fileExportDisabledReason,
                                        },
                                        {
                                            label: 'XLSX',
                                            onClick: () => triggerFileExport(ExporterFormat.XLSX, 'xlsx'),
                                            disabledReason: fileExportDisabledReason,
                                        },
                                    ],
                                },
                                {
                                    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
                    id="review"
                    loading={reviewsLoading}
                    columns={columns}
                    dataSource={reviews.results}
                    pagination={pagination}
                    noSortingCancellation
                    sorting={sorting}
                    useURLForSorting={false}
                    onSort={(newSorting) =>
                        setFilters({
                            order_by: newSorting
                                ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}`
                                : undefined,
                        })
                    }
                    rowKey="id"
                    loadingSkeletonRows={TRACE_REVIEWS_PER_PAGE}
                    nouns={['review', 'reviews']}
                    {...drawerTableProps}
                />
            </div>
            <TraceDrawerHost listId={TRACE_DRAWER_LIST_ID} />
        </>
    )
}