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.

15.1 KB
Raw Blame
import { useState } from 'react'

import { IconInfo } from '@posthog/icons'
import { LemonTabs, LemonTag } from '@posthog/lemon-ui'

import { ActivityClientTag } from 'lib/components/ActivityLog/ActivityClientTag'
import { AGENT_INTENT_TOOLTIP } from 'lib/components/ActivityLog/AgentAttribution'
import { HumanizedActivityLogItem, humanizeActivity, humanizeScope } from 'lib/components/ActivityLog/humanizeActivity'
import { parseAgentAttribution } from 'lib/components/ActivityLog/parseAgentAttribution'
import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { Link } from 'lib/lemon-ui/Link'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { urls } from 'scenes/urls'

import { credentialTypeLabel } from './credentialTypeLabel'
import { sandboxChange } from './sandboxChange'

export interface AuditLogTableProps {
    logItems: HumanizedActivityLogItem[]
    pagination?: PaginationManual
    /** When provided, renders a Project column resolving each row's team_id via this map. */
    teamsById?: Record<number, string>
}

const SANDBOX_IP_TOOLTIP = 'This change used a token that PostHog issued for a sandbox task.'
const SANDBOX_TAG_TOOLTIP =
    'This change used a token that PostHog issued for a sandbox task. PostHog records this, so it is not self-reported.'

const baseColumns: LemonTableColumns<HumanizedActivityLogItem> = [
    {
        title: 'Description',
        dataIndex: 'description',
        key: 'description',
        className: 'max-w-80',
        render: (description) => (
            <span className="[&_*]:inline whitespace-nowrap overflow-hidden text-ellipsis">
                {typeof description === 'string'
                    ? description
                    : typeof description === 'object' && description !== null && 'format' in description
                      ? (description as { format: (s: string) => string }).format('YYYY-MM-DD HH:mm:ss')
                      : (description as React.ReactNode) || 'No description'}
            </span>
        ),
        width: '30%',
    },
    {
        title: 'User',
        key: 'user',
        render: (_, logItem) => (
            <div className="flex items-center gap-1.5">
                <ProfilePicture
                    showName={true}
                    user={{
                        first_name: logItem.isSystem ? 'PostHog' : logItem.name,
                        email: logItem.email ?? undefined,
                    }}
                    type={logItem.isSystem ? 'system' : 'person'}
                    size="md"
                />
                {logItem.unprocessed?.client && <ActivityClientTag client={logItem.unprocessed.client} />}
                {sandboxChange(logItem)?.needsSandboxTag && (
                    <Tooltip title={SANDBOX_TAG_TOOLTIP}>
                        <LemonTag size="small" type="muted">
                            via sandbox
                        </LemonTag>
                    </Tooltip>
                )}
            </div>
        ),
        width: '20%',
    },
    {
        title: 'Activity',
        key: 'action',
        render: (_, logItem) => <span>{humanizeActivity(logItem.unprocessed?.activity || 'unknown')}</span>,
        width: '15%',
    },
    {
        title: 'Scope',
        key: 'scope',
        render: (_, logItem) => (
            <span className="inline-block">
                {logItem.unprocessed?.scope ? humanizeScope(logItem.unprocessed.scope, true) : 'Unknown'}
            </span>
        ),
        width: '15%',
    },
    {
        title: 'Time',
        key: 'time',
        render: (_, logItem) => <TZLabel time={logItem.created_at} />,
        width: '15%',
    },
    {
        title: 'Credential',
        key: 'credential_type',
        render: (_, logItem) => {
            const credentialType = logItem.unprocessed?.credential_type
            return credentialType ? (
                <span className="whitespace-nowrap">{credentialTypeLabel(credentialType)}</span>
            ) : (
                <span className="text-muted">—</span>
            )
        },
        width: '10%',
    },
    {
        title: 'IP address',
        key: 'ip_address',
        render: (_, logItem) => {
            const ipAddress = logItem.unprocessed?.ip_address
            if (sandboxChange(logItem)) {
                return (
                    <Tooltip title={ipAddress ? `${SANDBOX_IP_TOOLTIP} Request IP: ${ipAddress}` : SANDBOX_IP_TOOLTIP}>
                        <span className="inline-flex items-center gap-1 text-muted">
                            — <IconInfo />
                        </span>
                    </Tooltip>
                )
            }
            return ipAddress ? (
                <span className="font-mono text-xs">{ipAddress}</span>
            ) : (
                <span className="text-muted">—</span>
            )
        },
        width: '10%',
    },
]

function buildColumns(teamsById?: Record<number, string>): LemonTableColumns<HumanizedActivityLogItem> {
    if (!teamsById) {
        return baseColumns
    }

    const projectColumn: LemonTableColumns<HumanizedActivityLogItem>[number] = {
        title: 'Project',
        key: 'project',
        render: (_, logItem) => {
            const teamId = (logItem.unprocessed as { team_id?: number | null } | undefined)?.team_id
            if (teamId == null) {
                return <span className="text-muted">Organization-wide</span>
            }
            const teamName = teamsById[teamId]
            return <span>{teamName ?? `Project #${teamId}`}</span>
        },
        width: '15%',
    }

    // Insert Project as the second column (after Description, before User).
    return [baseColumns[0], projectColumn, ...baseColumns.slice(1)]
}

export function AuditLogTable({ logItems, pagination, teamsById }: AuditLogTableProps): JSX.Element {
    const columns = buildColumns(teamsById)
    const [expandedRows, setExpandedRows] = useState<Set<number>>(new Set())

    const toggleRowExpansion = (_: HumanizedActivityLogItem, index: number): void => {
        setExpandedRows((prev) => {
            const newSet = new Set(prev)
            if (newSet.has(index)) {
                newSet.delete(index)
            } else {
                newSet.add(index)
            }
            return newSet
        })
    }

    const isRowExpanded = (_: HumanizedActivityLogItem, index: number): boolean => {
        return expandedRows.has(index)
    }

    return (
        <LemonTable
            columns={columns}
            dataSource={logItems}
            expandable={{
                expandedRowRender: (logItem) => <ExpandedRowContent logItem={logItem} />,
                rowExpandable: () => true,
                isRowExpanded: (logItem, index) => (isRowExpanded(logItem, index) ? 1 : 0),
                onRowExpand: (logItem, index) => toggleRowExpansion(logItem, index),
                onRowCollapse: (logItem, index) => toggleRowExpansion(logItem, index),
            }}
            onRow={(logItem, index) => ({
                onClick: (e) => {
                    if ((e.target as HTMLElement).closest('.LemonTable__toggle')) {
                        return
                    }
                    toggleRowExpansion(logItem, index)
                },
                style: { cursor: 'pointer' },
            })}
            pagination={pagination}
            data-attr="audit-log-table"
        />
    )
}

function ExpandedRowContent({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {
    const unprocessed = logItem.unprocessed
    const agent = parseAgentAttribution(logItem)

    if (!unprocessed) {
        return <div className="p-4 text-muted">No additional details available</div>
    }

    return (
        <div className="p-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-3">
                    <div>
                        <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
                            Description
                        </div>
                        <div className="text-[13px] text-default">{logItem.description}</div>
                    </div>
                    {logItem.extendedDescription && (
                        <div>
                            <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
                                Extended Description
                            </div>
                            <div className="text-[13px] text-default">{logItem.extendedDescription}</div>
                        </div>
                    )}
                    {unprocessed.item_id && (
                        <div>
                            <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
                                Item ID
                            </div>
                            <div className="text-[13px] text-default">{unprocessed.item_id}</div>
                        </div>
                    )}
                    {unprocessed.credential_id && (
                        <div>
                            <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
                                Credential ID
                            </div>
                            <div className="text-[13px] text-default font-mono">{unprocessed.credential_id}</div>
                        </div>
                    )}
                    {agent?.intent && (
                        <div>
                            <Tooltip title={AGENT_INTENT_TOOLTIP}>
                                <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1 w-fit">
                                    Agent intent
                                </div>
                            </Tooltip>
                            <div className="text-[13px] text-default">{agent.intent}</div>
                        </div>
                    )}
                    {agent?.taskId && (
                        <div>
                            <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
                                Agent task
                            </div>
                            <div className="text-[13px]">
                                <Link to={urls.codeTaskLink(agent.taskId)} target="_blank" targetBlankIcon>
                                    {agent.taskId}
                                </Link>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            <ActivityDetailsSection logItem={logItem} />
        </div>
    )
}

type ActivityLogTabs = 'details' | 'extended description' | 'diff' | 'raw'

const ActivityDetailsSection = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {
    const [activeTab, setActiveTab] = useState<ActivityLogTabs>(logItem.expandedView ? 'details' : 'diff')

    return (
        <LemonTabs
            activeKey={activeTab}
            onChange={(key) => setActiveTab(key as ActivityLogTabs)}
            data-attr="audit-log-details-tabs"
            tabs={[
                logItem.expandedView
                    ? {
                          key: 'details',
                          label: logItem.expandedView.label,
                          content: logItem.expandedView.content,
                      }
                    : false,
                logItem.extendedDescription
                    ? {
                          key: 'extended description',
                          label: 'Extended description',
                          tooltip: 'Some activities have a more detailed description that is not shown when collapsed.',
                          content: <div>{logItem.extendedDescription}</div>,
                      }
                    : false,
                {
                    key: 'diff',
                    label: 'Diff',
                    tooltip:
                        'Show the diff of the changes made to the item. Each activity item could have more than one change.',
                    content: <ActivityLogDiff logItem={logItem} />,
                },
                {
                    key: 'raw',
                    label: 'Raw',
                    tooltip: 'Show the raw data of the activity item.',
                    content: (
                        <div className="bg-surface-primary p-2 rounded border border-border text-sm">
                            <pre>{JSON.stringify(logItem.unprocessed, null, 2)}</pre>
                        </div>
                    ),
                },
            ]}
        />
    )
}

const ActivityLogDiff = ({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element => {
    const changes = logItem.unprocessed?.detail.changes

    return (
        <div className="flex flex-col space-y-2 px-2 py-1">
            <div className="flex flex-col space-y-2">
                {changes?.length ? (
                    changes.map((change, i) => {
                        return (
                            <JsonDiffViewer
                                key={i}
                                field={change.field || ''}
                                before={change.before}
                                after={change.after}
                            />
                        )
                    })
                ) : (
                    <div className="text-muted">This item has no changes to compare</div>
                )}
            </div>
        </div>
    )
}

interface JsonDiffViewerProps {
    field: string
    before: any
    after: any
}

const JsonDiffViewer = ({ field, before, after }: JsonDiffViewerProps): JSX.Element => {
    const beforeStr = JSON.stringify(before, null, 2)
    const afterStr = JSON.stringify(after, null, 2)

    if (beforeStr === afterStr) {
        return (
            <div className="border rounded p-2 bg-surface-primary">
                <div className="font-medium text-sm mb-1">{field}</div>
                <div className="text-muted text-xs">No changes detected</div>
            </div>
        )
    }

    return (
        <div className="border rounded bg-surface-primary">
            <div className="font-medium text-sm p-2">{field}</div>
            <MonacoDiffEditor
                original={beforeStr}
                value={afterStr}
                modified={afterStr}
                language="json"
                options={{
                    readOnly: true,
                    minimap: { enabled: false },
                    scrollBeyondLastLine: false,
                    renderSideBySide: true,
                    hideUnchangedRegions: {
                        enabled: true,
                        contextLineCount: 3,
                        minimumLineCount: 3,
                        revealLineCount: 20,
                    },
                    diffAlgorithm: 'advanced',
                }}
            />
        </div>
    )
}