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(activity-logs): add organization-wide activity logs view (#57965)

Yasend7eb3c0529d5
diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
index a58e7892d279..06c75d11ce8e 100644
--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
@@ -43,6 +43,8 @@ export type ActivityLogItem = {
scope: ActivityScope | string
item_id?: string
detail: ActivityLogDetail
+ /** Team (project) the activity belongs to; null for organization-scoped activities. */
+ team_id?: number | null
/** Present if the log is used as a notification. Whether the notification is unread. */
unread?: boolean
/** Whether the activity was initiated by a PostHog staff member impersonating a user. */
diff --git a/frontend/src/scenes/audit-logs/AdvancedActivityLogFiltersPanel.tsx b/frontend/src/scenes/audit-logs/AdvancedActivityLogFiltersPanel.tsx
index b84b9a898bb5..5de65f03932d 100644
--- a/frontend/src/scenes/audit-logs/AdvancedActivityLogFiltersPanel.tsx
+++ b/frontend/src/scenes/audit-logs/AdvancedActivityLogFiltersPanel.tsx
@@ -12,7 +12,7 @@ import { advancedActivityLogsLogic } from './advancedActivityLogsLogic'
import { BasicFiltersTab } from './BasicFiltersTab'
export function AdvancedActivityLogFiltersPanel(): JSX.Element {
- const { hasActiveFilters, exportsLoading, filters } = useValues(advancedActivityLogsLogic)
+ const { hasActiveFilters, exportsLoading, filters, isOrganizationView } = useValues(advancedActivityLogsLogic)
const { clearAllFilters, exportLogs } = useActions(advancedActivityLogsLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -22,42 +22,44 @@ export function AdvancedActivityLogFiltersPanel(): JSX.Element {
<div className="border rounded-md p-4 bg-bg-light">
<div className="flex items-center justify-end">
<div className="flex gap-2">
- <LemonDropdown
- overlay={
- <div className="space-y-1 p-1">
- <LemonButton
- size="small"
- fullWidth
- onClick={() => exportLogs('csv')}
- loading={exportsLoading}
- data-attr="audit-logs-export-csv"
- >
- Export as CSV
- </LemonButton>
- <LemonButton
- size="small"
- fullWidth
- onClick={() => exportLogs('xlsx')}
- loading={exportsLoading}
- data-attr="audit-logs-export-xlsx"
- >
- Export as Excel
- </LemonButton>
- </div>
- }
- placement="bottom-end"
- data-attr="audit-logs-export-dropdown"
- >
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconDownload />}
- data-attr="audit-logs-export-button"
+ {!isOrganizationView && (
+ <LemonDropdown
+ overlay={
+ <div className="space-y-1 p-1">
+ <LemonButton
+ size="small"
+ fullWidth
+ onClick={() => exportLogs('csv')}
+ loading={exportsLoading}
+ data-attr="audit-logs-export-csv"
+ >
+ Export as CSV
+ </LemonButton>
+ <LemonButton
+ size="small"
+ fullWidth
+ onClick={() => exportLogs('xlsx')}
+ loading={exportsLoading}
+ data-attr="audit-logs-export-xlsx"
+ >
+ Export as Excel
+ </LemonButton>
+ </div>
+ }
+ placement="bottom-end"
+ data-attr="audit-logs-export-dropdown"
>
- Export
- </LemonButton>
- </LemonDropdown>
- {featureFlags[FEATURE_FLAGS.CDP_ACTIVITY_LOG_NOTIFICATIONS] && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconDownload />}
+ data-attr="audit-logs-export-button"
+ >
+ Export
+ </LemonButton>
+ </LemonDropdown>
+ )}
+ {!isOrganizationView && featureFlags[FEATURE_FLAGS.CDP_ACTIVITY_LOG_NOTIFICATIONS] && (
<ActivityLogSubscribeMenu
properties={subscribeProperties}
data-attr="audit-logs-subscribe-button"
diff --git a/frontend/src/scenes/audit-logs/AdvancedActivityLogsList.tsx b/frontend/src/scenes/audit-logs/AdvancedActivityLogsList.tsx
index c240cae24285..1282f347b95c 100644
--- a/frontend/src/scenes/audit-logs/AdvancedActivityLogsList.tsx
+++ b/frontend/src/scenes/audit-logs/AdvancedActivityLogsList.tsx
@@ -9,7 +9,8 @@ import { advancedActivityLogsLogic } from './advancedActivityLogsLogic'
import { AuditLogTable } from './AuditLogTable'
export function AdvancedActivityLogsList(): JSX.Element {
- const { advancedActivityLogs, advancedActivityLogsLoading, pagination } = useValues(advancedActivityLogsLogic)
+ const { advancedActivityLogs, advancedActivityLogsLoading, pagination, isOrganizationView, teamsById } =
+ useValues(advancedActivityLogsLogic)
const humanizedLogs = advancedActivityLogs?.results ? humanize(advancedActivityLogs.results, describerFor) : []
@@ -21,7 +22,13 @@ export function AdvancedActivityLogsList(): JSX.Element {
return <AdvancedActivityLogsEmptyState />
}
- return <AuditLogTable logItems={humanizedLogs} pagination={pagination} />
+ return (
+ <AuditLogTable
+ logItems={humanizedLogs}
+ pagination={pagination}
+ teamsById={isOrganizationView ? teamsById : undefined}
+ />
+ )
}
const AdvancedActivityLogsListSkeleton = (): JSX.Element => (
diff --git a/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx b/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx
index a57404966ff7..c87ba5c4f09f 100644
--- a/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx
+++ b/frontend/src/scenes/audit-logs/AdvancedActivityLogsScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconInfo, IconNotification } from '@posthog/icons'
-import { LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonSegmentedButton, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
import { AccessDenied } from 'lib/components/AccessDenied'
import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
@@ -18,6 +18,7 @@ import { AccessControlLevel, AccessControlResourceType, AvailableFeature } from
import { AdvancedActivityLogFiltersPanel } from './AdvancedActivityLogFiltersPanel'
import { AdvancedActivityLogsList } from './AdvancedActivityLogsList'
import { advancedActivityLogsLogic } from './advancedActivityLogsLogic'
+import type { ActivityLogsView } from './advancedActivityLogsLogic'
import { ExportsList } from './ExportsList'
export const scene: SceneExport = {
@@ -26,8 +27,8 @@ export const scene: SceneExport = {
}
export function AdvancedActivityLogsScene(): JSX.Element | null {
- const { activeTab } = useValues(advancedActivityLogsLogic)
- const { setActiveTab } = useActions(advancedActivityLogsLogic)
+ const { activeTab, view, canViewOrganization, isOrganizationView } = useValues(advancedActivityLogsLogic)
+ const { setActiveTab, setView } = useActions(advancedActivityLogsLogic)
const { currentTeam } = useValues(teamLogic)
const { user } = useValues(userLogic)
@@ -45,11 +46,16 @@ export function AdvancedActivityLogsScene(): JSX.Element | null {
</div>
),
},
- {
- key: 'exports',
- label: 'Exports',
- content: <ExportsList />,
- },
+ // Exports is project-scoped only — org view doesn't yet have an export path
+ ...(isOrganizationView
+ ? []
+ : [
+ {
+ key: 'exports',
+ label: 'Exports',
+ content: <ExportsList />,
+ },
+ ]),
]
if (!hasAccess) {
@@ -60,6 +66,18 @@ export function AdvancedActivityLogsScene(): JSX.Element | null {
)
}
+ const projectViewTooltip = (
+ <>
+ {includesOrgLevelLogs
+ ? 'This project view also includes organization-level changes (such as organization settings, domains, and members).'
+ : 'This project view only shows activity from this project. Organization-level changes are not shown.'}
+ <br />
+ <Link to={urls.settings('environment-activity-logs', 'activity-log-org-level-settings')}>
+ Change in settings
+ </Link>
+ </>
+ )
+
return (
<SceneContent>
<SceneTitleSection
@@ -71,34 +89,46 @@ export function AdvancedActivityLogsScene(): JSX.Element | null {
/>
<PayGateMini feature={AvailableFeature.AUDIT_LOGS} overrideShouldShowGate={user?.is_impersonated}>
<LemonTabs
- activeKey={activeTab}
+ activeKey={isOrganizationView ? 'logs' : activeTab}
onChange={(key) => setActiveTab(key as 'logs' | 'exports')}
tabs={tabs}
sceneInset
rightSlot={
- <Tooltip
- title={
- <>
- {includesOrgLevelLogs
- ? 'This view includes activity from both this project and organization-level changes (such as organization settings, domains, and members).'
- : 'This view only includes activity from this project. Organization-level changes are not shown.'}
- <br />
- <Link
- to={urls.settings(
- 'environment-activity-logs',
- 'activity-log-org-level-settings'
- )}
- >
- Change in settings
- </Link>
- </>
- }
- >
- <span className="flex items-center gap-1 text-sm text-secondary whitespace-nowrap cursor-pointer">
- {includesOrgLevelLogs ? 'Project and organization logs' : 'Project logs only'}
- <IconInfo className="text-base" />
- </span>
- </Tooltip>
+ <div className="flex items-center gap-3">
+ {canViewOrganization ? (
+ <LemonSegmentedButton
+ size="small"
+ value={view}
+ onChange={(value) => setView(value as ActivityLogsView)}
+ options={[
+ {
+ value: 'project',
+ label: (
+ <span className="flex items-center gap-1">
+ Project
+ <IconInfo className="text-base" />
+ </span>
+ ),
+ tooltip: projectViewTooltip,
+ },
+ {
+ value: 'organization',
+ label: 'Organization',
+ tooltip: 'Activity across all projects in the organization.',
+ },
+ ]}
+ data-attr="audit-logs-view-toggle"
+ />
+ ) : (
+ // No toggle for non-admins — keep the contextual indicator inline.
+ <Tooltip title={projectViewTooltip}>
+ <span className="flex items-center gap-1 text-sm text-secondary whitespace-nowrap cursor-pointer">
+ {includesOrgLevelLogs ? 'Project and organization logs' : 'Project logs only'}
+ <IconInfo className="text-base" />
+ </span>
+ </Tooltip>
+ )}
+ </div>
}
/>
</PayGateMini>
diff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
index 1eefc71c8e54..809cc2bdfb66 100644
--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx
+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
@@ -12,9 +12,11 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
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 columns: LemonTableColumns<HumanizedActivityLogItem> = [
+const baseColumns: LemonTableColumns<HumanizedActivityLogItem> = [
{
title: 'Description',
dataIndex: 'description',
@@ -29,7 +31,7 @@ const columns: LemonTableColumns<HumanizedActivityLogItem> = [
: (description as React.ReactNode) || 'No description'}
</span>
),
- width: '40%',
+ width: '35%',
},
{
title: 'User',
@@ -60,7 +62,7 @@ const columns: LemonTableColumns<HumanizedActivityLogItem> = [
title: 'Activity',
key: 'action',
render: (_, logItem) => <span>{humanizeActivity(logItem.unprocessed?.activity || 'unknown')}</span>,
- width: '20%',
+ width: '15%',
},
{
title: 'Scope',
@@ -70,17 +72,41 @@ const columns: LemonTableColumns<HumanizedActivityLogItem> = [
{logItem.unprocessed?.scope ? humanizeScope(logItem.unprocessed.scope, true) : 'Unknown'}
</span>
),
- width: '20%',
+ width: '15%',
},
{
title: 'Time',
key: 'time',
render: (_, logItem) => <TZLabel time={logItem.created_at} />,
- width: '10%',
+ width: '15%',
},
]
-export function AuditLogTable({ logItems, pagination }: AuditLogTableProps): JSX.Element {
+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 => {
diff --git a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
index c13bc206a8ff..a98970ab1a0a 100644
--- a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
+++ b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
@@ -14,9 +14,19 @@ import { advancedActivityLogsLogic } from './advancedActivityLogsLogic'
import { DetailFilters } from './DetailFilters'
export const BasicFiltersTab = (): JSX.Element => {
- const { filters, availableFilters, availableFiltersLoading, showMoreFilters, activeAdvancedFiltersCount } =
- useValues(advancedActivityLogsLogic)
+ const {
+ filters,
+ availableFilters,
+ availableFiltersLoading,
+ showMoreFilters,
+ activeAdvancedFiltersCount,
+ isOrganizationView,
+ teamsById,
+ } = useValues(advancedActivityLogsLogic)
const { setFilters, setShowMoreFilters } = useActions(advancedActivityLogsLogic)
+ const projectOptions = Object.entries(teamsById)
+ .map(([id, name]) => ({ key: id, label: name as string }))
+ .sort((a, b) => a.label.localeCompare(b.label))
return (
<div className="flex flex-col gap-4 pt-4">
@@ -35,6 +45,29 @@ export const BasicFiltersTab = (): JSX.Element => {
/>
</div>
+ {isOrganizationView && (
+ <div className="flex flex-col gap-1">
+ <label className="block text-sm font-medium mb-1">Project</label>
+ <LemonInputSelect
+ mode="multiple"
+ displayMode="count"
+ bulkActions="select-and-clear-all"
+ value={(filters.team_ids ?? []).map(String)}
+ onChange={(values) =>
+ setFilters({
+ team_ids: values.map((v) => parseInt(v, 10)).filter((v) => !Number.isNaN(v)),
+ })
+ }
+ options={projectOptions}
+ placeholder="All projects"
+ allowCustomValues={false}
+ data-attr="audit-logs-project-filter"
+ size="small"
+ className="min-w-50"
+ />
+ </div>
+ )}
+
<div className="flex flex-col gap-1">
<label className="block text-sm font-medium mb-1">User</label>
<LemonInputSelect
diff --git a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
index 4572a1256f2f..15d93584dacb 100644
--- a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
+++ b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
@@ -4,18 +4,21 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import api, { CountedPaginatedResponse } from 'lib/api'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
-import { ADVANCED_ACTIVITY_PAGE_SIZE } from 'lib/constants'
+import { ADVANCED_ACTIVITY_PAGE_SIZE, OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { dateStringToDayJs, objectClean } from 'lib/utils'
+import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
-import { ActivityScope } from '~/types'
+import { ActivityScope, OrganizationType, TeamBasicType } from '~/types'
import { userLogic } from '../userLogic'
import type { advancedActivityLogsLogicType } from './advancedActivityLogsLogicType'
+export type ActivityLogsView = 'project' | 'organization'
+
export interface DetailFilter {
operation: 'exact' | 'contains' | 'in'
value: string | string[]
@@ -34,6 +37,7 @@ export interface AdvancedActivityLogFilters {
scopes?: ActivityScope[]
activities?: string[]
clients?: string[]
+ team_ids?: number[]
detail_filters?: Record<string, DetailFilter>
was_impersonated?: boolean
is_system?: boolean
@@ -80,6 +84,7 @@ const DEFAULT_FILTERS: AdvancedActivityLogFilters = {
scopes: [],
activities: [],
clients: [],
+ team_ids: [],
detail_filters: {},
item_ids: [],
page: 1,
@@ -87,6 +92,29 @@ const DEFAULT_FILTERS: AdvancedActivityLogFilters = {
const ADVANCED_FILTERS = ['was_impersonated', 'is_system', 'item_ids', 'clients', 'detail_filters'] as const
+function parseListSearchParam(raw: unknown): string[] {
+ if (raw === undefined || raw === null || raw === '') {
+ return []
+ }
+ if (Array.isArray(raw)) {
+ return raw.map(String)
+ }
+ if (typeof raw === 'string') {
+ return raw.split(',').filter((v) => v.length > 0)
+ }
+ return [String(raw)]
+}
+
+function parseBooleanSearchParam(raw: unknown): boolean | undefined {
+ if (raw === 'true') {
+ return true
+ }
+ if (raw === 'false') {
+ return false
+ }
+ return undefined
+}
+
export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
path(['scenes', 'audit-logs', 'advancedActivityLogsLogic']),
connect(() => ({
@@ -97,6 +125,8 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
['hasAvailableFeature'],
teamLogic,
['currentTeamIdStrict', 'currentProjectId'],
+ organizationLogic,
+ ['currentOrganization', 'currentOrganizationId'],
],
})),
@@ -106,6 +136,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
clearAllFilters: true,
setActiveTab: (tab: 'logs' | 'exports') => ({ tab }),
setShowMoreFilters: (show: boolean) => ({ show }),
+ setView: (view: ActivityLogsView) => ({ view }),
// Detail filters
addActiveFilter: (fieldPath: string, isCustom: boolean = false) => ({ fieldPath, isCustom }),
@@ -153,6 +184,12 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
setActiveTab: (_, { tab }) => tab,
},
],
+ view: [
+ 'project' as ActivityLogsView,
+ {
+ setView: (_, { view }) => view,
+ },
+ ],
showMoreFilters: [
false,
{
@@ -198,6 +235,11 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
values.filters.activities?.forEach((activity) => params.append('activities', activity))
values.filters.clients?.forEach((client) => params.append('clients', client))
values.filters.item_ids?.forEach((item_id) => params.append('item_ids', item_id))
+ if (values.isOrganizationView) {
+ values.filters.team_ids?.forEach((team_id: number) =>
+ params.append('team_ids', String(team_id))
+ )
+ }
if (values.filters.was_impersonated !== undefined) {
params.append('was_impersonated', values.filters.was_impersonated.toString())
@@ -212,9 +254,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
params.append('page', (values.filters.page || 1).toString())
params.append('page_size', ADVANCED_ACTIVITY_PAGE_SIZE.toString())
- const response = await api.get(
- `api/projects/${values.currentProjectId}/advanced_activity_logs/?${params}`
- )
+ const response = await api.get(`${values.advancedActivityLogsBaseUrl}/?${params}`)
return response
},
},
@@ -224,9 +264,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
null as AvailableFilters | null,
{
loadAvailableFilters: async () => {
- const response = await api.get(
- `api/projects/${values.currentProjectId}/advanced_activity_logs/available_filters/`
- )
+ const response = await api.get(`${values.advancedActivityLogsBaseUrl}/available_filters/`)
return response
},
},
@@ -246,9 +284,34 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
})),
selectors({
+ isOrganizationView: [(s) => [s.view], (view: ActivityLogsView): boolean => view === 'organization'],
+
+ advancedActivityLogsBaseUrl: [
+ (s) => [s.isOrganizationView, s.currentProjectId, s.currentOrganizationId],
+ (isOrganizationView: boolean, currentProjectId: number | string, currentOrganizationId: string): string =>
+ isOrganizationView
+ ? `api/organizations/${currentOrganizationId}/advanced_activity_logs`
+ : `api/projects/${currentProjectId}/advanced_activity_logs`,
+ ],
+
+ canViewOrganization: [
+ (s) => [s.currentOrganization],
+ (currentOrganization: OrganizationType | null): boolean =>
+ !!currentOrganization?.membership_level &&
+ currentOrganization.membership_level >= OrganizationMembershipLevel.Admin,
+ ],
+
+ teamsById: [
+ (s) => [s.currentOrganization],
+ (currentOrganization: OrganizationType | null): Record<number, string> =>
+ Object.fromEntries(
+ (currentOrganization?.teams ?? []).map((team: TeamBasicType) => [team.id, team.name])
+ ),
+ ],
+
hasActiveFilters: [
- (s) => [s.filters],
- (filters: AdvancedActivityLogFilters): boolean => {
+ (s) => [s.filters, s.isOrganizationView],
+ (filters: AdvancedActivityLogFilters, isOrganizationView: boolean): boolean => {
return Boolean(
filters.start_date ||
filters.end_date ||
@@ -257,6 +320,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
filters.activities?.length ||
filters.clients?.length ||
filters.item_ids?.length ||
+ (isOrganizationView && filters.team_ids?.length) ||
filters.was_impersonated !== undefined ||
filters.is_system !== undefined ||
(filters.detail_filters && Object.keys(filters.detail_filters).length > 0)
@@ -302,16 +366,18 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
],
urlSearchParams: [
- (s) => [s.filters],
- (filters: AdvancedActivityLogFilters) => {
+ (s) => [s.filters, s.isOrganizationView],
+ (filters: AdvancedActivityLogFilters, isOrganizationView: boolean) => {
return objectClean({
...router.values.searchParams,
+ view: isOrganizationView ? 'organization' : undefined,
start_date: filters.start_date,
end_date: filters.end_date,
users: filters.users?.length ? filters.users.join(',') : undefined,
scopes: filters.scopes?.length ? filters.scopes.join(',') : undefined,
activities: filters.activities?.length ? filters.activities.join(',') : undefined,
clients: filters.clients?.length ? filters.clients.join(',') : undefined,
+ team_ids: isOrganizationView && filters.team_ids?.length ? filters.team_ids.join(',') : undefined,
item_ids: filters.item_ids?.length ? filters.item_ids.join(',') : undefined,
was_impersonated: filters.was_impersonated?.toString(),
is_system: filters.is_system?.toString(),
@@ -346,10 +412,19 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
actions.setShowMoreFilters(false)
actions.loadAdvancedActivityLogs({})
},
+ setView: () => {
+ // Switching view changes the endpoint and the meaning of project filters.
+ // Reset team_ids and rebuild the static filter options. The setFilters
+ // dispatch above runs through its own debounced listener which drives the
+ // log fetch — calling loadAdvancedActivityLogs here too races with deep-link
+ // navigation that follows up with another setFilters carrying real team_ids.
+ actions.setFilters({ team_ids: [], page: 1 })
+ actions.loadAvailableFilters()
+ },
setActiveTab: ({ tab }) => {
- if (tab === 'exports') {
- // Start polling when switching to exports tab
+ if (tab === 'exports' && !values.isOrganizationView) {
+ // Start polling when switching to exports tab (project view only)
actions.loadExports()
cache.disposables.add(() => {
const intervalId = setInterval(() => {
@@ -358,7 +433,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
return () => clearInterval(intervalId)
}, 'exportPollingInterval')
} else {
- // Stop polling when switching away from exports tab
+ // Stop polling when switching away from exports tab (or in organization view)
cache.disposables.dispose('exportPollingInterval')
}
},
@@ -457,6 +532,10 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
},
exportLogs: async ({ format }) => {
+ if (values.isOrganizationView) {
+ lemonToast.info('Export is not yet available for organization-wide activity logs.')
+ return
+ }
try {
const startDate = values.filters.start_date
? dateStringToDayJs(values.filters.start_date)?.toISOString()
@@ -492,25 +571,31 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
},
})),
- actionToUrl(({ values }) => ({
- setFilters: () => [
- router.values.location.pathname,
- values.urlSearchParams,
- router.values.hashParams,
- { replace: true },
- ],
- setPage: () => [
+ actionToUrl(({ values }) => {
+ const replaceUrl = (): [string, Record<string, any>, Record<string, any>, { replace: true }] => [
router.values.location.pathname,
values.urlSearchParams,
router.values.hashParams,
{ replace: true },
- ],
- })),
+ ]
+ return {
+ setFilters: replaceUrl,
+ setPage: replaceUrl,
+ setView: replaceUrl,
+ clearAllFilters: replaceUrl,
+ }
+ }),
- urlToAction(({ actions }) => ({
+ urlToAction(({ actions, values }) => ({
'/activity-logs': (_, searchParams) => {
const hasUrlParams = Object.keys(searchParams).length > 0
+ const desiredView: ActivityLogsView =
+ searchParams.view === 'organization' && values.canViewOrganization ? 'organization' : 'project'
+ if (desiredView !== values.view) {
+ actions.setView(desiredView)
+ }
+
// If just visiting the page, we want to clear all filters in case the page was previously mounted with filters
if (!hasUrlParams) {
actions.clearAllFilters()
@@ -525,36 +610,45 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
if (searchParams.end_date) {
urlFilters.end_date = searchParams.end_date
}
- if (searchParams.users) {
- urlFilters.users = Array.isArray(searchParams.users)
- ? searchParams.users
- : searchParams.users?.split(',') || []
+
+ const users = parseListSearchParam(searchParams.users)
+ if (users.length) {
+ urlFilters.users = users
}
- if (searchParams.scopes) {
- urlFilters.scopes = (
- Array.isArray(searchParams.scopes) ? searchParams.scopes : searchParams.scopes?.split(',') || []
- ) as ActivityScope[]
+ const scopes = parseListSearchParam(searchParams.scopes)
+ if (scopes.length) {
+ urlFilters.scopes = scopes as ActivityScope[]
}
- if (searchParams.activities) {
- urlFilters.activities = Array.isArray(searchParams.activities)
- ? searchParams.activities
- : searchParams.activities?.split(',') || []
+ const activities = parseListSearchParam(searchParams.activities)
+ if (activities.length) {
+ urlFilters.activities = activities
}
- if (searchParams.clients) {
- urlFilters.clients = Array.isArray(searchParams.clients)
- ? searchParams.clients
- : searchParams.clients?.split(',') || []
+ const clients = parseListSearchParam(searchParams.clients)
+ if (clients.length) {
+ urlFilters.clients = clients
}
- if (searchParams.item_ids) {
- urlFilters.item_ids = searchParams.item_ids.split?.(',') || [searchParams.item_ids]
+ const itemIds = parseListSearchParam(searchParams.item_ids)
+ if (itemIds.length) {
+ urlFilters.item_ids = itemIds
}
- if (searchParams.was_impersonated !== undefined) {
- urlFilters.was_impersonated =
- searchParams.was_impersonated === 'true' || searchParams.was_impersonated === true
+ if (desiredView === 'organization') {
+ const teamIds = parseListSearchParam(searchParams.team_ids)
+ .map((v) => parseInt(v, 10))
+ .filter((v) => !Number.isNaN(v))
+ if (teamIds.length) {
+ urlFilters.team_ids = teamIds
+ }
}
- if (searchParams.is_system !== undefined) {
- urlFilters.is_system = searchParams.is_system === 'true' || searchParams.is_system === true
+
+ const wasImpersonated = parseBooleanSearchParam(searchParams.was_impersonated)
+ if (wasImpersonated !== undefined) {
+ urlFilters.was_impersonated = wasImpersonated
}
+ const isSystem = parseBooleanSearchParam(searchParams.is_system)
+ if (isSystem !== undefined) {
+ urlFilters.is_system = isSystem
+ }
+
if (searchParams.detail_filters) {
try {
urlFilters.detail_filters = JSON.parse(searchParams.detail_filters)
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 926348da215c..81c2cc4a45f4 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -721,6 +721,12 @@ organizations_router.register(
"organization_welcome",
["organization_id"],
)
+organizations_router.register(
+ r"advanced_activity_logs",
+ advanced_activity_logs.OrganizationAdvancedActivityLogsViewSet,
+ "organization_advanced_activity_logs",
+ ["organization_id"],
+)
# General endpoints (shared across CH & PG)
router.register(r"login", authentication.LoginViewSet, "login")
diff --git a/posthog/api/advanced_activity_logs/__init__.py b/posthog/api/advanced_activity_logs/__init__.py
index 136fd871bac4..42198abfd5a6 100644
--- a/posthog/api/advanced_activity_logs/__init__.py
+++ b/posthog/api/advanced_activity_logs/__init__.py
@@ -6,6 +6,7 @@ from .viewset import (
ActivityLogViewSet,
AdvancedActivityLogFiltersSerializer,
AdvancedActivityLogsViewSet,
+ OrganizationAdvancedActivityLogsViewSet,
)
__all__ = [
@@ -13,6 +14,7 @@ __all__ = [
"ActivityLogSerializer",
"ActivityLogViewSet",
"AdvancedActivityLogsViewSet",
+ "OrganizationAdvancedActivityLogsViewSet",
"AdvancedActivityLogFiltersSerializer",
"AdvancedActivityLogFilterManager",
"AdvancedActivityLogFieldDiscovery",
diff --git a/posthog/api/advanced_activity_logs/filters.py b/posthog/api/advanced_activity_logs/filters.py
index e96202c2e6b4..a7c02ec0186a 100644
--- a/posthog/api/advanced_activity_logs/filters.py
+++ b/posthog/api/advanced_activity_logs/filters.py
@@ -20,6 +20,7 @@ class AdvancedActivityLogFilterManager:
queryset = self._apply_is_system_filter(queryset, filters)
queryset = self._apply_item_ids_filter(queryset, filters)
queryset = self._apply_clients_filter(queryset, filters)
+ queryset = self._apply_team_ids_filter(queryset, filters)
return queryset
def _apply_date_filters(self, queryset: QuerySet[ActivityLog], filters: dict[str, Any]) -> QuerySet[ActivityLog]:
@@ -188,6 +189,11 @@ class AdvancedActivityLogFilterManager:
queryset = queryset.filter(client__in=filters["clients"])
return queryset
+ def _apply_team_ids_filter(self, queryset: QuerySet[ActivityLog], filters: dict[str, Any]) -> QuerySet[ActivityLog]:
+ if filters.get("team_ids"):
+ queryset = queryset.filter(team_id__in=filters["team_ids"])
+ return queryset
+
def _get_type_variants(self, value: Any) -> list[Any]:
"""
Convert a value to its possible type variants for type-insensitive matching.
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index af21ddf879b7..2d0371fe88de 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -2,7 +2,7 @@ import json
import hashlib
import logging
from datetime import datetime
-from typing import Any, Optional, get_args
+from typing import Any, Optional, cast, get_args
from urllib.parse import urlencode
from django.db.models import Q, QuerySet
@@ -11,6 +11,8 @@ from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import mixins, serializers, viewsets
from rest_framework.decorators import action
from rest_framework.pagination import BasePagination, CursorPagination, PageNumberPagination
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -24,6 +26,8 @@ from posthog.models.activity_logging.activity_log import (
apply_activity_visibility_restrictions,
)
from posthog.models.exported_asset import ExportedAsset
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
from posthog.permissions import PremiumFeaturePermission
from posthog.tasks import exporter
@@ -56,7 +60,7 @@ class ActivityLogSerializer(serializers.ModelSerializer):
class Meta:
model = ActivityLog
- exclude = ["team_id"]
+ fields = "__all__"
def get_unread(self, obj: ActivityLog) -> bool:
"""is the date of this log item newer than the user's bookmark"""
@@ -207,18 +211,78 @@ class JSONStringFilterField(serializers.JSONField):
class AdvancedActivityLogFiltersSerializer(serializers.Serializer):
- start_date = serializers.DateTimeField(required=False)
- end_date = serializers.DateTimeField(required=False)
- users = serializers.ListField(child=serializers.UUIDField(), required=False, default=[])
- scopes = serializers.ListField(child=serializers.CharField(), required=False, default=[])
- activities = serializers.ListField(child=serializers.CharField(), required=False, default=[])
- clients = serializers.ListField(child=serializers.CharField(), required=False, default=[])
- search_text = serializers.CharField(required=False, allow_blank=True)
- detail_filters = JSONStringFilterField(required=False)
- hogql_filter = serializers.CharField(required=False, allow_blank=True)
- was_impersonated = OptionalBooleanField(required=False)
- is_system = OptionalBooleanField(required=False)
- item_ids = serializers.ListField(child=serializers.CharField(), required=False, default=[])
+ start_date = serializers.DateTimeField(
+ required=False,
+ help_text="Lower bound on `created_at` (inclusive), ISO-8601.",
+ )
+ end_date = serializers.DateTimeField(
+ required=False,
+ help_text="Upper bound on `created_at` (inclusive), ISO-8601.",
+ )
+ users = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ default=[],
+ help_text="Filter by users who performed the activity (user UUIDs).",
+ )
+ scopes = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=[],
+ help_text='Filter by activity scopes (e.g. "FeatureFlag", "Insight").',
+ )
+ activities = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=[],
+ help_text='Filter by activity types (e.g. "created", "updated", "deleted").',
+ )
+ clients = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=[],
+ help_text="Filter by API clients that generated the activity (from x-posthog-client header).",
+ )
+ team_ids = serializers.ListField(
+ child=serializers.IntegerField(),
+ required=False,
+ default=[],
+ help_text=(
+ "Filter by project (team) IDs. Only honored on the organization-scoped endpoint; "
+ "ignored on the project-scoped endpoint."
+ ),
+ )
+ search_text = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Free-text search across the `detail` JSON column.",
+ )
+ detail_filters = JSONStringFilterField(
+ required=False,
+ help_text=(
+ "JSON-encoded map of `detail` field paths to {operation, value} filters. "
+ "Allowed operations: exact, contains, in."
+ ),
+ )
+ hogql_filter = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Reserved for future HogQL-based filtering.",
+ )
+ was_impersonated = OptionalBooleanField(
+ required=False,
+ help_text="When set, filters rows where the actor was impersonating another user.",
+ )
+ is_system = OptionalBooleanField(
+ required=False,
+ help_text="When set, filters rows authored by the system (no user).",
+ )
+ item_ids = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=[],
+ help_text="Filter by the `item_id` of the affected resource(s).",
+ )
page = serializers.IntegerField(
required=False,
min_value=1,
@@ -447,3 +511,68 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
self.logger.exception(f"Failed to create export: {e}")
capture_exception(e)
return Response({"error": "Failed to create export"}, status=500)
+
+
+class OrganizationActivityLogPermission(BasePermission):
+ """
+ Restrict the organization-scoped activity logs endpoint to organization admins and owners.
+
+ Used in addition to OrganizationMemberPermissions, which TeamAndOrgViewSetMixin adds for
+ org-nested viewsets (so we already know the user is in the organization).
+ """
+
+ message = "Only organization admins and owners can view organization-wide activity logs."
+
+ def has_permission(self, request: Request, view) -> bool:
+ try:
+ organization = view.organization
+ except (Organization.DoesNotExist, ValueError):
+ return False
+
+ try:
+ membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
+ except OrganizationMembership.DoesNotExist:
+ return False
+
+ return membership.level >= OrganizationMembership.Level.ADMIN
+
+
+@extend_schema(tags=["activity_logs", "platform_features"])
+class OrganizationAdvancedActivityLogsViewSet(AdvancedActivityLogsViewSet):
+ """
+ Organization-wide view of activity logs across every project in the organization.
+
+ Mounted at /api/organizations/<organization_id>/advanced_activity_logs/.
+ Restricted to organization admins and owners.
+ """
+
+ permission_classes = [PremiumFeaturePermission, OrganizationActivityLogPermission]
+ # The parent declares {"project_id": "team_id"} but our nested route only carries
+ # organization_id, so the rewrite would KeyError on missing "project_id". Reset it.
+ filter_rewrite_rules: dict[str, str] = {}
+
+ def _should_skip_parents_filter(self) -> bool:
+ # parents_query_dict is {"organization_id": <uuid>} on this nested route, so let
+ # TeamAndOrgViewSetMixin filter the queryset by organization_id automatically.
+ return False
+
+ def safely_get_queryset(self, queryset) -> QuerySet:
+ queryset = queryset.select_related("user")
+
+ lookback_date = get_activity_log_lookback_restriction(self.organization)
+ if lookback_date:
+ queryset = queryset.filter(created_at__gte=lookback_date)
+
+ queryset = apply_activity_visibility_restrictions(queryset, self.request.user)
+
+ return queryset.order_by("-created_at")
+
+ @action(detail=False, methods=["POST"])
+ def export(self, request, **kwargs): # type: ignore[override]
+ # Override the parent's export action: it depends on self.team (for ExportedAsset.team)
+ # which is not available on org-nested routes. Defer export support until we have an
+ # org-aware ExportedAsset story.
+ return Response(
+ {"error": "Export is not yet supported on the organization-scoped activity logs endpoint."},
+ status=400,
+ )
diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.py
index 02c01a834d4a..e0b74d5e5dfc 100644
--- a/posthog/api/test/test_activity_log.py
+++ b/posthog/api/test/test_activity_log.py
@@ -1,5 +1,6 @@
from datetime import timedelta
from typing import Any, Optional
+from uuid import uuid4
from freezegun import freeze_time
from freezegun.api import FrozenDateTimeFactory, StepTickTimeFactory, TickingDateTimeFactory
@@ -10,7 +11,8 @@ from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
-from posthog.models import User
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.activity_logging.activity_log import Detail, log_activity
def _feature_flag_json_payload(key: str) -> dict:
@@ -236,3 +238,186 @@ class TestActivityLogAuditLogsGate(APIBaseTest):
res = self.client.get(f"/api/projects/{self.team.id}/{endpoint}/")
assert res.status_code == status.HTTP_200_OK
+
+
+class TestOrganizationAdvancedActivityLogsViewSet(APIBaseTest):
+ """Tests for the org-scoped activity logs viewset at /api/organizations/<id>/advanced_activity_logs/."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = False
+ self.user.save()
+ # Promote the seeded user to admin for the happy-path tests; downgrade per-test as needed.
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+ # Audit logs feature must be unlocked for the org so the cloud paywall doesn't pre-empt the
+ # access-control checks under test.
+ self.organization.available_product_features = [{"key": AvailableFeature.AUDIT_LOGS, "name": "Activity logs"}]
+ self.organization.save()
+
+ self.other_team_in_org = Team.objects.create(organization=self.organization, name="Other team in org")
+
+ self.outside_organization = Organization.objects.create(name="Outside org")
+ self.outside_team = Team.objects.create(organization=self.outside_organization, name="Outside team")
+
+ self._seed_activity_rows()
+
+ def _seed_activity_rows(self) -> None:
+ # Project-scoped row in primary team (both team_id and organization_id populated)
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id="flag-1",
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+ # Project-scoped row in the second team of the same org
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.other_team_in_org.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id="insight-1",
+ scope="Insight",
+ activity="created",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+ # Org-scoped row (team_id is null)
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=None,
+ user=self.user,
+ was_impersonated=False,
+ item_id=str(uuid4()),
+ scope="Organization",
+ activity="updated",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+ # Row in a completely different organization — must NOT be visible
+ log_activity(
+ organization_id=self.outside_organization.id,
+ team_id=self.outside_team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id="flag-outside",
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+
+ def _list(self, **query) -> Any:
+ url = f"/api/organizations/{self.organization.id}/advanced_activity_logs/"
+ return self.client.get(url, data=query)
+
+ def test_admin_sees_all_org_rows(self) -> None:
+ # Spot-check that the endpoint returns org-wide content (not just an empty 200)
+ # when the requester is allowed in. Permission gating itself is covered below.
+ res = self._list()
+
+ assert res.status_code == status.HTTP_200_OK
+ results = res.json()["results"]
+ item_ids = {row["item_id"] for row in results}
+ assert "flag-1" in item_ids
+ assert "insight-1" in item_ids
+ # Org-scoped row appears
+ assert any(row["scope"] == "Organization" for row in results)
+ # Cross-org row does NOT appear
+ assert "flag-outside" not in item_ids
+
+ @parameterized.expand(
+ [
+ ("owner", OrganizationMembership.Level.OWNER, status.HTTP_200_OK),
+ ("admin", OrganizationMembership.Level.ADMIN, status.HTTP_200_OK),
+ ("member", OrganizationMembership.Level.MEMBER, status.HTTP_403_FORBIDDEN),
+ ("non_member", None, status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_access_control_by_membership_level(self, _name: str, level: Optional[int], expected_status: int) -> None:
+ if level is None:
+ outsider = User.objects.create_and_join(
+ organization=self.outside_organization, email="[email protected]", password=""
+ )
+ self.client.force_login(outsider)
+ else:
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(level=level)
+
+ res = self._list()
+
+ assert res.status_code == expected_status
+
+ def test_team_ids_filter_narrows_to_selected_projects(self) -> None:
+ res = self._list(team_ids=self.team.id)
+
+ assert res.status_code == status.HTTP_200_OK
+ item_ids = {row["item_id"] for row in res.json()["results"]}
+ assert item_ids == {"flag-1"}
+
+ def test_audit_logs_feature_required_on_cloud(self) -> None:
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ with self.is_cloud(True):
+ res = self._list()
+
+ assert res.status_code == status.HTTP_402_PAYMENT_REQUIRED
+
+ def test_export_endpoint_is_disabled_on_organization_route(self) -> None:
+ url = f"/api/organizations/{self.organization.id}/advanced_activity_logs/export/"
+ res = self.client.post(url, data={"format": "csv"}, format="json")
+
+ assert res.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestOrganizationAdvancedActivityLogsAvailableFilters(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+ self.organization.available_product_features = [{"key": AvailableFeature.AUDIT_LOGS, "name": "Activity logs"}]
+ self.organization.save()
+
+ self.other_team = Team.objects.create(organization=self.organization, name="Other team")
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id="flag-1",
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.other_team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id="insight-1",
+ scope="Insight",
+ activity="updated",
+ detail=Detail(name="seed"),
+ force_save=True,
+ )
+
+ def test_available_filters_returns_org_wide_static_filters(self) -> None:
+ # Small-org branch (live computation path) — covered by default in tests.
+ url = f"/api/organizations/{self.organization.id}/advanced_activity_logs/available_filters/"
+ res = self.client.get(url)
+
+ assert res.status_code == status.HTTP_200_OK
+ body = res.json()
+ scopes = {entry["value"] for entry in body["static_filters"]["scopes"]}
+ # Both project-level scopes appear because the queryset is org-wide
+ assert {"FeatureFlag", "Insight"}.issubset(scopes)
+ activities = {entry["value"] for entry in body["static_filters"]["activities"]}
+ assert {"created", "updated"}.issubset(activities)
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index a4e53d998931..d926ef89ce1a 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -539,6 +539,12 @@ export interface ActivityLogApi {
user: UserBasicApi
/** is the date of this log item newer than the user's bookmark */
readonly unread: boolean
+ /**
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ team_id?: number | null
/** @nullable */
organization_id?: string | null
/** @nullable */
@@ -1085,15 +1091,34 @@ export const ActivityLogListScopesItem = {
} as const
export type AdvancedActivityLogsListParams = {
+ /**
+ * Filter by activity types (e.g. "created", "updated", "deleted").
+ */
activities?: string[]
+ /**
+ * Filter by API clients that generated the activity (from x-posthog-client header).
+ */
clients?: string[]
+ /**
+ * JSON-encoded map of `detail` field paths to {operation, value} filters. Allowed operations: exact, contains, in.
+ */
detail_filters?: string
+ /**
+ * Upper bound on `created_at` (inclusive), ISO-8601.
+ */
end_date?: string
+ /**
+ * Reserved for future HogQL-based filtering.
+ */
hogql_filter?: string
/**
+ * When set, filters rows authored by the system (no user).
* @nullable
*/
is_system?: boolean | null
+ /**
+ * Filter by the `item_id` of the affected resource(s).
+ */
item_ids?: string[]
/**
* Page number for pagination. When provided, uses page-based pagination ordered by most recent first.
@@ -1106,11 +1131,28 @@ export type AdvancedActivityLogsListParams = {
* @maximum 1000
*/
page_size?: number
+ /**
+ * Filter by activity scopes (e.g. "FeatureFlag", "Insight").
+ */
scopes?: string[]
+ /**
+ * Free-text search across the `detail` JSON column.
+ */
search_text?: string
+ /**
+ * Lower bound on `created_at` (inclusive), ISO-8601.
+ */
start_date?: string
+ /**
+ * Filter by project (team) IDs. Only honored on the organization-scoped endpoint; ignored on the project-scoped endpoint.
+ */
+ team_ids?: number[]
+ /**
+ * Filter by users who performed the activity (user UUIDs).
+ */
users?: string[]
/**
+ * When set, filters rows where the actor was impersonating another user.
* @nullable
*/
was_impersonated?: boolean | null
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 1efe1f41dd16..1d8572d47681 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -199,6 +199,9 @@ export const advancedActivityLogsExportCreateBodyUserLastNameMax = 150
export const advancedActivityLogsExportCreateBodyUserEmailMax = 254
+export const advancedActivityLogsExportCreateBodyTeamIdMin = 0
+export const advancedActivityLogsExportCreateBodyTeamIdMax = 2147483647
+
export const advancedActivityLogsExportCreateBodyClientMax = 32
export const advancedActivityLogsExportCreateBodyActivityMax = 79
@@ -229,6 +232,11 @@ export const AdvancedActivityLogsExportCreateBody = /* @__PURE__ */ zod.object({
])
.nullish(),
}),
+ team_id: zod
+ .number()
+ .min(advancedActivityLogsExportCreateBodyTeamIdMin)
+ .max(advancedActivityLogsExportCreateBodyTeamIdMax)
+ .nullish(),
organization_id: zod.uuid().nullish(),
was_impersonated: zod.boolean().nullish(),
is_system: zod.boolean().nullish(),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d0b0401873f6..139b84d3fb38 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1412,6 +1412,12 @@ export namespace Schemas {
user: UserBasic;
/** is the date of this log item newer than the user's bookmark */
readonly unread: boolean;
+ /**
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ team_id?: number | null;
/** @nullable */
organization_id?: string | null;
/** @nullable */
@@ -43508,6 +43514,74 @@ export namespace Schemas {
offset?: number;
};
+ export type OrgOrganizationsAdvancedActivityLogsListParams = {
+ /**
+ * Filter by activity types (e.g. "created", "updated", "deleted").
+ */
+ activities?: string[];
+ /**
+ * Filter by API clients that generated the activity (from x-posthog-client header).
+ */
+ clients?: string[];
+ /**
+ * JSON-encoded map of `detail` field paths to {operation, value} filters. Allowed operations: exact, contains, in.
+ */
+ detail_filters?: string;
+ /**
+ * Upper bound on `created_at` (inclusive), ISO-8601.
+ */
+ end_date?: string;
+ /**
+ * Reserved for future HogQL-based filtering.
+ */
+ hogql_filter?: string;
+ /**
+ * When set, filters rows authored by the system (no user).
+ * @nullable
+ */
+ is_system?: boolean | null;
+ /**
+ * Filter by the `item_id` of the affected resource(s).
+ */
+ item_ids?: string[];
+ /**
+ * Page number for pagination. When provided, uses page-based pagination ordered by most recent first.
+ * @minimum 1
+ */
+ page?: number;
+ /**
+ * Number of results per page (default: 100, max: 1000). Only used with page-based pagination.
+ * @minimum 1
+ * @maximum 1000
+ */
+ page_size?: number;
+ /**
+ * Filter by activity scopes (e.g. "FeatureFlag", "Insight").
+ */
+ scopes?: string[];
+ /**
+ * Free-text search across the `detail` JSON column.
+ */
+ search_text?: string;
+ /**
+ * Lower bound on `created_at` (inclusive), ISO-8601.
+ */
+ start_date?: string;
+ /**
+ * Filter by project (team) IDs. Only honored on the organization-scoped endpoint; ignored on the project-scoped endpoint.
+ */
+ team_ids?: number[];
+ /**
+ * Filter by users who performed the activity (user UUIDs).
+ */
+ users?: string[];
+ /**
+ * When set, filters rows where the actor was impersonating another user.
+ * @nullable
+ */
+ was_impersonated?: boolean | null;
+ };
+
export type OrgOrganizationsBatchExportsListParams = {
/**
* Number of results to return per page.
@@ -44091,15 +44165,34 @@ export namespace Schemas {
} as const;
export type AdvancedActivityLogsListParams = {
+ /**
+ * Filter by activity types (e.g. "created", "updated", "deleted").
+ */
activities?: string[];
+ /**
+ * Filter by API clients that generated the activity (from x-posthog-client header).
+ */
clients?: string[];
+ /**
+ * JSON-encoded map of `detail` field paths to {operation, value} filters. Allowed operations: exact, contains, in.
+ */
detail_filters?: string;
+ /**
+ * Upper bound on `created_at` (inclusive), ISO-8601.
+ */
end_date?: string;
+ /**
+ * Reserved for future HogQL-based filtering.
+ */
hogql_filter?: string;
/**
+ * When set, filters rows authored by the system (no user).
* @nullable
*/
is_system?: boolean | null;
+ /**
+ * Filter by the `item_id` of the affected resource(s).
+ */
item_ids?: string[];
/**
* Page number for pagination. When provided, uses page-based pagination ordered by most recent first.
@@ -44112,11 +44205,28 @@ export namespace Schemas {
* @maximum 1000
*/
page_size?: number;
+ /**
+ * Filter by activity scopes (e.g. "FeatureFlag", "Insight").
+ */
scopes?: string[];
+ /**
+ * Free-text search across the `detail` JSON column.
+ */
search_text?: string;
+ /**
+ * Lower bound on `created_at` (inclusive), ISO-8601.
+ */
start_date?: string;
+ /**
+ * Filter by project (team) IDs. Only honored on the organization-scoped endpoint; ignored on the project-scoped endpoint.
+ */
+ team_ids?: number[];
+ /**
+ * Filter by users who performed the activity (user UUIDs).
+ */
users?: string[];
/**
+ * When set, filters rows where the actor was impersonating another user.
* @nullable
*/
was_impersonated?: boolean | null;
diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.ts
index 2570f119e0cf..07af213852cc 100644
--- a/services/mcp/src/generated/platform_features/api.ts
+++ b/services/mcp/src/generated/platform_features/api.ts
@@ -302,16 +302,31 @@ export const advancedActivityLogsListQueryPageSizeDefault = 100
export const advancedActivityLogsListQueryPageSizeMax = 1000
export const advancedActivityLogsListQueryScopesDefault = []
+export const advancedActivityLogsListQueryTeamIdsDefault = []
export const advancedActivityLogsListQueryUsersDefault = []
export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({
- activities: zod.array(zod.string()).default(advancedActivityLogsListQueryActivitiesDefault),
- clients: zod.array(zod.string()).default(advancedActivityLogsListQueryClientsDefault),
- detail_filters: zod.string().optional(),
- end_date: zod.iso.datetime({}).optional(),
- hogql_filter: zod.string().optional(),
- is_system: zod.boolean().nullish(),
- item_ids: zod.array(zod.string()).default(advancedActivityLogsListQueryItemIdsDefault),
+ activities: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryActivitiesDefault)
+ .describe('Filter by activity types (e.g. "created", "updated", "deleted").'),
+ clients: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryClientsDefault)
+ .describe('Filter by API clients that generated the activity (from x-posthog-client header).'),
+ detail_filters: zod
+ .string()
+ .optional()
+ .describe(
+ 'JSON-encoded map of `detail` field paths to {operation, value} filters. Allowed operations: exact, contains, in.'
+ ),
+ end_date: zod.iso.datetime({}).optional().describe('Upper bound on `created_at` (inclusive), ISO-8601.'),
+ hogql_filter: zod.string().optional().describe('Reserved for future HogQL-based filtering.'),
+ is_system: zod.boolean().nullish().describe('When set, filters rows authored by the system (no user).'),
+ item_ids: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryItemIdsDefault)
+ .describe('Filter by the `item_id` of the affected resource(s).'),
page: zod
.number()
.min(1)
@@ -325,11 +340,26 @@ export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({
.max(advancedActivityLogsListQueryPageSizeMax)
.default(advancedActivityLogsListQueryPageSizeDefault)
.describe('Number of results per page (default: 100, max: 1000). Only used with page-based pagination.'),
- scopes: zod.array(zod.string()).default(advancedActivityLogsListQueryScopesDefault),
- search_text: zod.string().optional(),
- start_date: zod.iso.datetime({}).optional(),
- users: zod.array(zod.string()).default(advancedActivityLogsListQueryUsersDefault),
- was_impersonated: zod.boolean().nullish(),
+ scopes: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryScopesDefault)
+ .describe('Filter by activity scopes (e.g. "FeatureFlag", "Insight").'),
+ search_text: zod.string().optional().describe('Free-text search across the `detail` JSON column.'),
+ start_date: zod.iso.datetime({}).optional().describe('Lower bound on `created_at` (inclusive), ISO-8601.'),
+ team_ids: zod
+ .array(zod.number())
+ .default(advancedActivityLogsListQueryTeamIdsDefault)
+ .describe(
+ 'Filter by project (team) IDs. Only honored on the organization-scoped endpoint; ignored on the project-scoped endpoint.'
+ ),
+ users: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryUsersDefault)
+ .describe('Filter by users who performed the activity (user UUIDs).'),
+ was_impersonated: zod
+ .boolean()
+ .nullish()
+ .describe('When set, filters rows where the actor was impersonating another user.'),
})
export const AdvancedActivityLogsAvailableFiltersRetrieveParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.ts
index dcda8b9f94dc..3974b97f4331 100644
--- a/services/mcp/src/tools/generated/platform_features.ts
+++ b/services/mcp/src/tools/generated/platform_features.ts
@@ -120,6 +120,7 @@ const advancedActivityLogsList = (): ToolBase<
scopes: params.scopes,
search_text: params.search_text,
start_date: params.start_date,
+ team_ids: params.team_ids,
users: params.users,
was_impersonated: params.was_impersonated,
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
index c001e0c09ac1..98d36dd51ae9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
@@ -3,6 +3,7 @@
"properties": {
"activities": {
"default": [],
+ "description": "Filter by activity types (e.g. \"created\", \"updated\", \"deleted\").",
"items": {
"type": "string"
},
@@ -10,20 +11,24 @@
},
"clients": {
"default": [],
+ "description": "Filter by API clients that generated the activity (from x-posthog-client header).",
"items": {
"type": "string"
},
"type": "array"
},
"detail_filters": {
+ "description": "JSON-encoded map of `detail` field paths to {operation, value} filters. Allowed operations: exact, contains, in.",
"type": "string"
},
"end_date": {
+ "description": "Upper bound on `created_at` (inclusive), ISO-8601.",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"type": "string"
},
"hogql_filter": {
+ "description": "Reserved for future HogQL-based filtering.",
"type": "string"
},
"is_system": {
@@ -34,10 +39,12 @@
{
"type": "null"
}
- ]
+ ],
+ "description": "When set, filters rows authored by the system (no user)."
},
"item_ids": {
"default": [],
+ "description": "Filter by the `item_id` of the affected resource(s).",
"items": {
"type": "string"
},
@@ -57,21 +64,33 @@
},
"scopes": {
"default": [],
+ "description": "Filter by activity scopes (e.g. \"FeatureFlag\", \"Insight\").",
"items": {
"type": "string"
},
"type": "array"
},
"search_text": {
+ "description": "Free-text search across the `detail` JSON column.",
"type": "string"
},
"start_date": {
+ "description": "Lower bound on `created_at` (inclusive), ISO-8601.",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"type": "string"
},
+ "team_ids": {
+ "default": [],
+ "description": "Filter by project (team) IDs. Only honored on the organization-scoped endpoint; ignored on the project-scoped endpoint.",
+ "items": {
+ "type": "number"
+ },
+ "type": "array"
+ },
"users": {
"default": [],
+ "description": "Filter by users who performed the activity (user UUIDs).",
"items": {
"type": "string"
},
@@ -85,7 +104,8 @@
{
"type": "null"
}
- ]
+ ],
+ "description": "When set, filters rows where the actor was impersonating another user."
}
},
"type": "object"