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(aio): add ai_events property category to access rules (#109241)

Radu Raicea1b29f3a16f51
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3ec8db75e566..afc22f2392ec 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13030,6 +13030,22 @@ snapshots:
hash: v1.k794b7964.7a6a02807240dbbe34017687603246e0d2a8cf3c5030a72489e9c91dbebbd7bf.wRFlnN8ieOdhMFH_nOuQP7jaRIAsHHzggG0_S_U6UBU
scenes-inbox-scout-tags--searched-filter--wide--light:
hash: v1.k794b7964.d2fc29b8d0d41c120300eb49eff2ef947cc30813d3491d915dfe4219a8c4326d.-JiZJOnlilAHmEGyfuIA5Uoerbf1c_XC6zVvzKjtduY
+ scenes-other-access-control-property-rules--ai-property-picker--dark:
+ hash: v1.k794b7964.44dd6391c243b1a12408ad42a34ec2c09333232bce5ffce5dae7e3c96c181d1e.46JF-BelKqooz5_oYr4tZrBqKPvWhbIYZ9NoSBAgEN8
+ scenes-other-access-control-property-rules--ai-property-picker--light:
+ hash: v1.k794b7964.709e7619c1aeb1044cb952b1f20e386ef63c3a4be0eddede5b8dd1f1b5215e60.kHSQ_4LbW2jlLeRGuM6GVzZGNT09G-XykcRt3HE6vew
+ scenes-other-access-control-property-rules--default--dark:
+ hash: v1.k794b7964.279fee58a8b64ecc4242914ea4c97d5e00819ff404e1ba537d62c33510a83fe7.oKTTgaqtpuXTZWDyf9Tw_e0kMyRj-H8aH34xAKxTZrY
+ scenes-other-access-control-property-rules--default--light:
+ hash: v1.k794b7964.dac6d38e89371044282bd486d2ced541cf2adf480da8212dc7529bd45320d10c.pkmFnxlnYymfAiaEcTWo9DgZEMQM4QvjSAAtKzGHvXw
+ scenes-other-access-control-property-rules--narrow--dark:
+ hash: v1.k794b7964.ca818f8306d183d36504c706b739304960f2136612b4602f3c78e812d158b419.MkKGWmT8YPBapYtHTIHH1jFGcFF5u6dgwGWSY-zC3qU
+ scenes-other-access-control-property-rules--narrow--light:
+ hash: v1.k794b7964.08f5461bdd27081088ced5cfc9b86a4bd8e8d3ec6869943336a4e52030c65d65.1vuTGVYghlXVGQ4xbJV9UJDAKFUXMhAWNfnokseJ_ic
+ scenes-other-access-control-property-rules--saving-ai-property-rule--dark:
+ hash: v1.k794b7964.610e843169d2964454392cc46da86f96b5ca1fd91f92dfab075efaf1c43661b7.S1lB60UBoWVJT8NpkCjs1CpoTjWTGzor-F-3nR11YRM
+ scenes-other-access-control-property-rules--saving-ai-property-rule--light:
+ hash: v1.k794b7964.f744b83a3b4cd755d46c352fdabb216ab0ab61227f5a27961d6ea7501a3ae57c.YZapjuaJVZzE1iuZjp9BdXY8XmjTxoMaVP8ANezY4Fg
scenes-other-account-connected--github-integration-connected--dark:
hash: v1.k794b7964.fcae9b65af8160ba40bf82664dd9b5a6b9f5a1ddbdedee05bf15ec453eb7aa64.3616s9KNJancKVe-j4dQsJdo3W1CVcwWxRMA24QgU6Q
scenes-other-account-connected--github-integration-connected--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.test.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.test.tsx
new file mode 100644
index 000000000000..b526527f9cd8
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.test.tsx
@@ -0,0 +1,81 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { accessDetailLogic } from './accessDetailLogic'
+import { addPropertyRestrictionModalLogic } from './addPropertyRestrictionModalLogic'
+import { AddPropertyRuleModal } from './AddPropertyRuleModal'
+
+describe('AddPropertyRuleModal', () => {
+ const props = { projectId: '997', scopeType: 'default' as const, subjectId: '' }
+ let logic: ReturnType<typeof addPropertyRestrictionModalLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:id/access_control_default_objects': { results: [] },
+ '/api/projects/:id/access_control_default_properties': { results: [] },
+ '/api/projects/:id/property_definitions/': { results: [] },
+ },
+ })
+ initKeaTests()
+ logic = addPropertyRestrictionModalLogic.build(props)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ })
+
+ it.each([200, 500])('prevents dismissal until a save completes with status %s', async (status) => {
+ let releaseSave: () => void = () => {}
+ const pendingSave = new Promise<void>((resolve) => {
+ releaseSave = resolve
+ })
+ useMocks({
+ post: {
+ '/api/projects/:id/property_access_controls/': async () => {
+ await pendingSave
+ return [status, status === 200 ? { id: 'new-rule', access_level: 'read' } : { detail: 'Try again' }]
+ },
+ },
+ })
+ const user = userEvent.setup()
+ render(<AddPropertyRuleModal {...props} />)
+ await act(async () => {
+ await expectLogic(logic, () => {
+ logic.actions.openModal()
+ logic.actions.setPropertyType('ai')
+ }).toDispatchActions(['loadPropertyOptionsSuccess'])
+ })
+ act(() => logic.actions.setPropertyId('$ai_output_choices'))
+ await user.click(screen.getByText('Add rule'))
+
+ const cancel = screen.getByText('Cancel').closest('button')!
+ const dialog = screen.getByRole('dialog')
+ expect(cancel).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.queryByLabelText('close')).not.toBeInTheDocument()
+ fireEvent.click(cancel)
+ fireEvent.keyDown(dialog, { key: 'Escape', code: 'Escape', keyCode: 27 })
+ fireEvent.click(dialog.parentElement!)
+ expect(dialog).toBeVisible()
+ expect(logic.values.isOpen).toBe(true)
+
+ await act(async () => {
+ await expectLogic(accessDetailLogic(props), releaseSave).toDispatchActions(['ruleSaveFinished'])
+ })
+ if (status === 500) {
+ expect(dialog).toBeVisible()
+ expect(cancel).not.toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByLabelText('close')).toBeVisible()
+ await user.click(cancel)
+ }
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ })
+})
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.tsx
new file mode 100644
index 000000000000..3c3f9b21d7fe
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AddPropertyRuleModal.tsx
@@ -0,0 +1,129 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonInputSelect, LemonLabel, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+
+import { PROPERTY_ACCESS_LEVEL_OPTIONS } from 'lib/utils/accessControlUtils'
+
+import { AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
+
+import { addPropertyRestrictionModalLogic } from './addPropertyRestrictionModalLogic'
+import type { ScopeType } from './types'
+
+function propertyLevelLabel(level: AccessLevelEnumApi): string | JSX.Element {
+ return PROPERTY_ACCESS_LEVEL_OPTIONS.find((o) => o.value === level)?.label ?? level
+}
+
+export function AddPropertyRuleModal({
+ projectId,
+ scopeType,
+ subjectId,
+}: {
+ projectId: string
+ scopeType: ScopeType
+ subjectId: string
+}): JSX.Element {
+ const logic = addPropertyRestrictionModalLogic({ projectId, scopeType, subjectId })
+ const {
+ isOpen,
+ propertyType,
+ propertyId,
+ level,
+ displayPropertyOptions,
+ propertyOptionsLoading,
+ existingRule,
+ ruleSaving,
+ } = useValues(logic)
+ const { closeModal, setPropertyType, setSearch, setPropertyId, setLevel, submitRule } = useActions(logic)
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={closeModal}
+ closable={!ruleSaving}
+ title="Add property rule"
+ description={
+ scopeType === 'default'
+ ? "Set everyone's access to a specific property."
+ : `Set this ${scopeType === 'role' ? 'role' : 'member'}'s access to a specific property.`
+ }
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeModal} disabled={ruleSaving}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ disabledReason={
+ propertyOptionsLoading
+ ? 'Loading properties'
+ : !propertyId
+ ? 'Select a property'
+ : existingRule?.access_level === level
+ ? 'The rule already has this level'
+ : undefined
+ }
+ loading={ruleSaving}
+ onClick={submitRule}
+ >
+ {existingRule ? 'Update rule' : 'Add rule'}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="space-y-3 min-w-[24rem]">
+ <div>
+ <LemonLabel>Type</LemonLabel>
+ <LemonSelect
+ value={propertyType}
+ onChange={setPropertyType}
+ disabled={ruleSaving}
+ data-attr="property-rule-type"
+ options={[
+ { value: 'person', label: 'Person property' },
+ { value: 'event', label: 'Event property' },
+ { value: 'ai', label: 'ai_events property' },
+ ]}
+ fullWidth
+ />
+ </div>
+ <div>
+ <LemonLabel>Property</LemonLabel>
+ <LemonInputSelect
+ mode="single"
+ value={propertyId ? [propertyId] : []}
+ onChange={(values) => setPropertyId(values[0] ?? null)}
+ onInputChange={setSearch}
+ loading={propertyOptionsLoading}
+ disabled={ruleSaving}
+ data-attr="property-rule-property"
+ options={displayPropertyOptions.map((o) => ({ key: o.id, label: o.name }))}
+ placeholder="Search by name…"
+ />
+ </div>
+ <div>
+ <LemonLabel>Access</LemonLabel>
+ <LemonSelect
+ value={level}
+ onChange={setLevel}
+ options={PROPERTY_ACCESS_LEVEL_OPTIONS}
+ disabled={ruleSaving}
+ fullWidth
+ />
+ </div>
+ {existingRule ? (
+ <LemonBanner type="warning">
+ "{existingRule.property}" already has a rule.{' '}
+ {existingRule.access_level === level ? (
+ <>It's already set to {propertyLevelLabel(level)}.</>
+ ) : (
+ <>
+ Saving updates it from {propertyLevelLabel(existingRule.access_level)} to{' '}
+ {propertyLevelLabel(level)}.
+ </>
+ )}
+ </LemonBanner>
+ ) : null}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.stories.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.stories.tsx
new file mode 100644
index 000000000000..2a9e3fcbbf3b
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.stories.tsx
@@ -0,0 +1,99 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor, within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { PropertyAccessRules } from './PropertyAccessRules'
+
+const meta: Meta<typeof PropertyAccessRules> = {
+ title: 'Scenes-Other/Access control/Property rules',
+ component: PropertyAccessRules,
+ parameters: { layout: 'padded' },
+ args: { projectId: '997', scopeType: 'default', subjectId: '', subjectNoun: 'project', canEdit: true },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:id/access_control_default_objects': { results: [] },
+ '/api/projects/:id/access_control_default_properties': {
+ results: [
+ {
+ property_definition_id: 'input-rule',
+ property: '$ai_input',
+ property_type: 'event',
+ access_level: 'none',
+ },
+ {
+ property_definition_id: 'output-rule',
+ property: '$ai_output_choices',
+ property_type: 'event',
+ access_level: 'none',
+ },
+ {
+ property_definition_id: 'person-rule',
+ property: 'email',
+ property_type: 'person',
+ access_level: 'read',
+ },
+ ],
+ },
+ '/api/projects/:id/property_definitions/': { results: [] },
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Default: Story = {}
+
+export const AIPropertyPicker: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByText('Add rule'))
+ const page = within(document.body)
+ await userEvent.click(
+ await page.findByText('Person property', { selector: '[data-attr="property-rule-type"] *' })
+ )
+ await userEvent.click(await page.findByRole('button', { name: 'Person property' }))
+ await userEvent.click(await page.findByRole('menuitem', { name: 'ai_events property' }))
+ await userEvent.type(await page.findByPlaceholderText('Search by name…'), 'output')
+ await page.findByRole('button', { name: 'output_choices ($ai_output_choices)' })
+ },
+}
+
+export const SavingAIPropertyRule: Story = {
+ parameters: {
+ testOptions: { waitForLoadersToDisappear: false },
+ msw: {
+ mocks: {
+ post: {
+ '/api/projects/:id/property_access_controls/': () => new Promise<never>(() => {}),
+ },
+ },
+ },
+ },
+ play: async (context) => {
+ await AIPropertyPicker.play?.(context)
+ const page = within(document.body)
+ await userEvent.click(await page.findByRole('button', { name: 'output ($ai_output)' }))
+ const dialog = within(page.getByRole('dialog'))
+ await waitFor(() => {
+ if (dialog.getByRole('button', { name: 'Add rule' }).getAttribute('aria-disabled') === 'true') {
+ throw new Error('Waiting for property selection')
+ }
+ })
+ await userEvent.click(dialog.getByRole('button', { name: 'Add rule' }))
+ },
+}
+
+export const Narrow: Story = {
+ decorators: [
+ (Story) => (
+ <div className="max-w-lg">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.tsx
index f27ac232c33e..db8ba9151755 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/PropertyAccessRules.tsx
@@ -1,29 +1,18 @@
import { useActions, useValues } from 'kea'
import { IconPlus, IconTrash } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonInputSelect,
- LemonLabel,
- LemonModal,
- LemonSelect,
- LemonTable,
-} from '@posthog/lemon-ui'
+import { LemonButton, LemonSelect, LemonTable } from '@posthog/lemon-ui'
import { PROPERTY_ACCESS_LEVEL_OPTIONS } from 'lib/utils/accessControlUtils'
-import { AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
+import { AIEventPropertyEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import { AccessPropertyRule, accessDetailLogic } from './accessDetailLogic'
import { AccessDetailSection } from './AccessDetailSection'
import { addPropertyRestrictionModalLogic } from './addPropertyRestrictionModalLogic'
+import { AddPropertyRuleModal } from './AddPropertyRuleModal'
import type { ScopeType } from './types'
-function propertyLevelLabel(level: AccessLevelEnumApi): string | JSX.Element {
- return PROPERTY_ACCESS_LEVEL_OPTIONS.find((o) => o.value === level)?.label ?? level
-}
-
export interface PropertyAccessRulesProps {
projectId: string
scopeType: ScopeType
@@ -72,14 +61,25 @@ export function PropertyAccessRules({
{
title: 'Property',
key: 'property',
- render: (_, p: AccessPropertyRule) => <span className="font-medium">{p.property}</span>,
+ render: (_, p: AccessPropertyRule) => (
+ <span className="font-medium">
+ {p.property_type === 'event' &&
+ Object.values(AIEventPropertyEnumApi).some((name) => name === p.property)
+ ? `${p.property.slice(4)} (${p.property})`
+ : p.property}
+ </span>
+ ),
},
{
title: 'Type',
key: 'type',
render: (_, p: AccessPropertyRule) => (
<span className="text-secondary">
- {p.property_type === 'person' ? 'Person property' : 'Event property'}
+ {p.property_type === 'person'
+ ? 'Person property'
+ : Object.values(AIEventPropertyEnumApi).some((name) => name === p.property)
+ ? 'ai_events property'
+ : 'Event property'}
</span>
),
},
@@ -138,95 +138,3 @@ export function PropertyAccessRules({
</AccessDetailSection>
)
}
-
-function AddPropertyRuleModal({
- projectId,
- scopeType,
- subjectId,
-}: {
- projectId: string
- scopeType: ScopeType
- subjectId: string
-}): JSX.Element {
- const logic = addPropertyRestrictionModalLogic({ projectId, scopeType, subjectId })
- const { isOpen, propertyType, propertyId, level, displayPropertyOptions, propertyOptionsLoading, existingRule } =
- useValues(logic)
- const { closeModal, setPropertyType, setSearch, setPropertyId, setLevel, submitRule } = useActions(logic)
-
- return (
- <LemonModal
- isOpen={isOpen}
- onClose={closeModal}
- title="Add property rule"
- description={
- scopeType === 'default'
- ? "Set everyone's access to a specific property."
- : `Set this ${scopeType === 'role' ? 'role' : 'member'}'s access to a specific property.`
- }
- footer={
- <>
- <LemonButton type="secondary" onClick={closeModal}>
- Cancel
- </LemonButton>
- <LemonButton
- type="primary"
- disabledReason={
- !propertyId
- ? 'Select a property'
- : existingRule?.access_level === level
- ? 'The rule already has this level'
- : undefined
- }
- onClick={submitRule}
- >
- {existingRule ? 'Update rule' : 'Add rule'}
- </LemonButton>
- </>
- }
- >
- <div className="space-y-3 min-w-[24rem]">
- <div>
- <LemonLabel>Type</LemonLabel>
- <LemonSelect
- value={propertyType}
- onChange={setPropertyType}
- options={[
- { value: 'person', label: 'Person property' },
- { value: 'event', label: 'Event property' },
- ]}
- fullWidth
- />
- </div>
- <div>
- <LemonLabel>Property</LemonLabel>
- <LemonInputSelect
- mode="single"
- value={propertyId ? [propertyId] : []}
- onChange={(values) => setPropertyId(values[0] ?? null)}
- onInputChange={setSearch}
- loading={propertyOptionsLoading}
- options={displayPropertyOptions.map((o) => ({ key: o.id, label: o.name }))}
- placeholder="Search by name…"
- />
- </div>
- <div>
- <LemonLabel>Access</LemonLabel>
- <LemonSelect value={level} onChange={setLevel} options={PROPERTY_ACCESS_LEVEL_OPTIONS} fullWidth />
- </div>
- {existingRule ? (
- <LemonBanner type="warning">
- "{existingRule.property}" already has a rule.{' '}
- {existingRule.access_level === level ? (
- <>It's already set to {propertyLevelLabel(level)}.</>
- ) : (
- <>
- Saving updates it from {propertyLevelLabel(existingRule.access_level)} to{' '}
- {propertyLevelLabel(level)}.
- </>
- )}
- </LemonBanner>
- ) : null}
- </div>
- </LemonModal>
- )
-}
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index 87fa3d7fb226..3cb630a6b556 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -12,7 +12,7 @@ import {
propertyAccessControlsCreate,
propertyAccessControlsDestroy,
} from 'products/access_control/frontend/generated/api'
-import type { ScopeObjectEnumApi } from 'products/access_control/frontend/generated/api.schemas'
+import type { AIEventPropertyEnumApi, ScopeObjectEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import { AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import type { ScopeType } from './types'
@@ -203,6 +203,9 @@ export interface accessDetailLogicActions {
properties: AccessPropertyRule[]
payload?: any
}
+ propertyRuleSaved: () => {
+ value: true
+ }
ruleSaveFinished: () => {
value: true
}
@@ -217,8 +220,10 @@ export interface accessDetailLogicActions {
}
setPropertyRule: (
propertyDefinitionId: string,
- level: AccessLevelEnumApi | null
+ level: AccessLevelEnumApi | null,
+ aiProperty?: AIEventPropertyEnumApi
) => {
+ aiProperty: AIEventPropertyEnumApi | undefined
level: AccessLevelEnumApi | null
propertyDefinitionId: string
}
@@ -247,10 +252,12 @@ export const accessDetailLogic = kea<accessDetailLogicType>([
resourceId,
level,
}),
- setPropertyRule: (propertyDefinitionId: string, level: AccessLevelEnumApi | null) => ({
- propertyDefinitionId,
- level,
- }),
+ setPropertyRule: (
+ propertyDefinitionId: string,
+ level: AccessLevelEnumApi | null,
+ aiProperty?: AIEventPropertyEnumApi
+ ) => ({ propertyDefinitionId, level, aiProperty }),
+ propertyRuleSaved: true,
ruleSaveFinished: true,
}),
@@ -306,7 +313,7 @@ export const accessDetailLogic = kea<accessDetailLogicType>([
actions.ruleSaveFinished()
}
},
- setPropertyRule: async ({ propertyDefinitionId, level }) => {
+ setPropertyRule: async ({ propertyDefinitionId, level, aiProperty }) => {
try {
if (level === null) {
await propertyAccessControlsDestroy(props.projectId, {
@@ -315,11 +322,14 @@ export const accessDetailLogic = kea<accessDetailLogicType>([
})
} else {
await propertyAccessControlsCreate(props.projectId, {
- property_definition_id: propertyDefinitionId,
+ ...(aiProperty
+ ? { ai_property: aiProperty }
+ : { property_definition_id: propertyDefinitionId }),
access_level: level,
...subjectBody(props),
})
}
+ actions.propertyRuleSaved()
lemonToast.success(level === null ? 'Rule removed' : 'Property rule saved')
actions.loadProperties()
} catch (e) {
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.test.ts
new file mode 100644
index 000000000000..2641e7cfc547
--- /dev/null
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.test.ts
@@ -0,0 +1,121 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
+
+import { accessDetailLogic } from './accessDetailLogic'
+import { addPropertyRestrictionModalLogic } from './addPropertyRestrictionModalLogic'
+
+describe('addPropertyRestrictionModalLogic', () => {
+ let logic: ReturnType<typeof addPropertyRestrictionModalLogic.build>
+ const props = { projectId: '997', scopeType: 'default' as const, subjectId: '' }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:id/access_control_default_objects': { results: [] },
+ '/api/projects/:id/access_control_default_properties': { results: [] },
+ '/api/projects/:id/property_definitions/': { results: [] },
+ },
+ })
+ initKeaTests()
+ logic = addPropertyRestrictionModalLogic.build(props)
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it('finds built-in AI properties without ingested definitions and matches canonical names', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.openModal()
+ logic.actions.setPropertyType('ai')
+ }).toDispatchActions(['loadPropertyOptionsSuccess'])
+ expect(logic.values.propertyOptions).toEqual(
+ expect.arrayContaining([
+ { id: '$ai_input', name: 'input ($ai_input)' },
+ { id: '$ai_output', name: 'output ($ai_output)' },
+ { id: '$ai_output_choices', name: 'output_choices ($ai_output_choices)' },
+ ])
+ )
+ await expectLogic(logic, () => logic.actions.setSearch('$ai_output_choices')).toDispatchActions([
+ 'loadPropertyOptionsSuccess',
+ ])
+ expect(logic.values.propertyOptions).toEqual([
+ { id: '$ai_output_choices', name: 'output_choices ($ai_output_choices)' },
+ ])
+ await expectLogic(logic, () => logic.actions.setPropertyType('event')).toDispatchActions([
+ 'loadPropertyOptionsSuccess',
+ ])
+ expect(logic.values.displayPropertyOptions).toEqual([])
+ })
+
+ it('recognizes an existing event rule when selecting its AI category entry', async () => {
+ const existing = {
+ property_definition_id: 'existing-input',
+ property: '$ai_input',
+ property_type: 'event' as const,
+ access_level: AccessLevelEnumApi.None,
+ }
+ useMocks({
+ get: { '/api/projects/:id/access_control_default_properties': { results: [existing] } },
+ })
+ const details = accessDetailLogic(props)
+ await expectLogic(details, () => details.actions.loadProperties()).toDispatchActions(['loadPropertiesSuccess'])
+ await expectLogic(logic, () => logic.actions.setPropertyType('ai')).toDispatchActions([
+ 'loadPropertyOptionsSuccess',
+ ])
+ logic.actions.setPropertyId('$ai_input')
+ expect(logic.values.existingRule).toEqual(existing)
+ })
+
+ it('saves the canonical AI property once and keeps the modal open until the save succeeds', async () => {
+ let releaseSave: () => void = () => {}
+ const pendingSave = new Promise<void>((resolve) => {
+ releaseSave = resolve
+ })
+ const bodies: unknown[] = []
+ useMocks({
+ post: {
+ '/api/projects/:id/property_access_controls/': async ({ request }) => {
+ bodies.push(await request.json())
+ await pendingSave
+ return [200, { id: 'new-rule', access_level: 'none' }]
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.openModal()
+ logic.actions.setPropertyType('ai')
+ }).toDispatchActions(['loadPropertyOptionsSuccess'])
+ logic.actions.setPropertyId('$ai_output_choices')
+ logic.actions.setLevel(AccessLevelEnumApi.None)
+ logic.actions.submitRule()
+ logic.actions.submitRule()
+ expect(logic.values.ruleSaving).toBe(true)
+ expect(logic.values.isOpen).toBe(true)
+ await expectLogic(accessDetailLogic(props), releaseSave).toDispatchActions([
+ 'propertyRuleSaved',
+ 'ruleSaveFinished',
+ ])
+ expect(bodies).toEqual([{ ai_property: '$ai_output_choices', access_level: 'none' }])
+ expect(logic.values.isOpen).toBe(false)
+ expect(logic.values.ruleSaving).toBe(false)
+ })
+
+ it('keeps the selection available for retry when saving fails', async () => {
+ useMocks({ post: { '/api/projects/:id/property_access_controls/': [500, { detail: 'Try again' }] } })
+ await expectLogic(logic, () => {
+ logic.actions.openModal()
+ logic.actions.setPropertyType('ai')
+ }).toDispatchActions(['loadPropertyOptionsSuccess'])
+ logic.actions.setPropertyId('$ai_input')
+ await expectLogic(accessDetailLogic(props), () => logic.actions.submitRule()).toDispatchActions([
+ 'ruleSaveFinished',
+ ])
+ expect(logic.values.isOpen).toBe(true)
+ expect(logic.values.propertyId).toBe('$ai_input')
+ expect(logic.values.ruleSaving).toBe(false)
+ })
+})
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.ts
index cad06e0c324a..95d98bff19f6 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addPropertyRestrictionModalLogic.ts
@@ -1,9 +1,9 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import api from 'lib/api'
+import { propertyDefinitionsList } from '~/generated/core/api'
-import { AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
+import { AIEventPropertyEnumApi, AccessLevelEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import { AccessPropertyRule, accessDetailLogic } from './accessDetailLogic'
import type { ScopeType } from './types'
@@ -22,6 +22,7 @@ export interface AddPropertyRestrictionModalLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addPropertyRestrictionModalLogicValues {
properties: AccessPropertyRule[] // accessDetailLogic
+ ruleSaving: boolean // accessDetailLogic
displayPropertyOptions: PropertyOption[]
existingRule: AccessPropertyRule | null
isOpen: boolean
@@ -29,17 +30,22 @@ export interface addPropertyRestrictionModalLogicValues {
propertyId: string | null
propertyOptions: PropertyOption[]
propertyOptionsLoading: boolean
- propertyType: 'event' | 'person'
+ propertyType: 'ai' | 'event' | 'person'
search: string
selectedProperty: PropertyOption | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addPropertyRestrictionModalLogicActions {
+ propertyRuleSaved: () => {
+ value: true
+ } // accessDetailLogic
setPropertyRule: (
propertyDefinitionId: string,
- level: AccessLevelEnumApi | null
+ level: AccessLevelEnumApi | null,
+ aiProperty?: AIEventPropertyEnumApi | undefined
) => {
+ aiProperty: AIEventPropertyEnumApi | undefined
level: AccessLevelEnumApi | null
propertyDefinitionId: string
} // accessDetailLogic
@@ -76,8 +82,8 @@ export interface addPropertyRestrictionModalLogicActions {
setPropertyId: (propertyId: string | null) => {
propertyId: string | null
}
- setPropertyType: (propertyType: 'event' | 'person') => {
- propertyType: 'event' | 'person'
+ setPropertyType: (propertyType: 'ai' | 'event' | 'person') => {
+ propertyType: 'ai' | 'event' | 'person'
}
setSearch: (search: string) => {
search: string
@@ -94,10 +100,15 @@ export interface addPropertyRestrictionModalLogicActions {
export interface addPropertyRestrictionModalLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- existingRule: (properties: AccessPropertyRule[], propertyId: string | null) => AccessPropertyRule | null
+ existingRule: (
+ properties: AccessPropertyRule[],
+ propertyId: string | null,
+ propertyType: 'ai' | 'event' | 'person'
+ ) => AccessPropertyRule | null
displayPropertyOptions: (
propertyOptions: PropertyOption[],
- selectedProperty: PropertyOption | null
+ selectedProperty: PropertyOption | null,
+ propertyOptionsLoading: boolean
) => PropertyOption[]
}
}
@@ -115,14 +126,14 @@ export const addPropertyRestrictionModalLogic = kea<addPropertyRestrictionModalL
key((props) => `${props.projectId}:${props.scopeType}:${props.subjectId}`),
connect((props: AddPropertyRestrictionModalLogicProps) => ({
- actions: [accessDetailLogic(props), ['setPropertyRule']],
- values: [accessDetailLogic(props), ['properties']],
+ actions: [accessDetailLogic(props), ['setPropertyRule', 'propertyRuleSaved']],
+ values: [accessDetailLogic(props), ['properties', 'ruleSaving']],
})),
actions({
openModal: true,
closeModal: true,
- setPropertyType: (propertyType: 'person' | 'event') => ({ propertyType }),
+ setPropertyType: (propertyType: 'person' | 'event' | 'ai') => ({ propertyType }),
setSearch: (search: string) => ({ search }),
setPropertyId: (propertyId: string | null) => ({ propertyId }),
setSelectedProperty: (option: PropertyOption | null) => ({ option }),
@@ -133,7 +144,7 @@ export const addPropertyRestrictionModalLogic = kea<addPropertyRestrictionModalL
reducers({
isOpen: [false, { openModal: () => true, closeModal: () => false }],
propertyType: [
- 'person' as 'person' | 'event',
+ 'person' as 'person' | 'event' | 'ai',
{ setPropertyType: (_, { propertyType }) => propertyType, closeModal: () => 'person' },
],
search: ['', { setSearch: (_, { search }) => search, setPropertyType: () => '', closeModal: () => '' }],
@@ -158,12 +169,22 @@ export const addPropertyRestrictionModalLogic = kea<addPropertyRestrictionModalL
{
loadPropertyOptions: async (_, breakpoint) => {
await breakpoint(300)
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use propertyDefinitionsList() from '~/generated/core/api' instead.
- const response = await api.get<{ results: { id: string; name: string }[] }>(
- `api/projects/${props.projectId}/property_definitions/?type=${values.propertyType}&limit=20&search=${encodeURIComponent(
- values.search
- )}`
- )
+ if (values.propertyType === 'ai') {
+ const words = values.search.trim().toLowerCase().split(/\s+/)
+ return Object.values(AIEventPropertyEnumApi)
+ .map((name) => ({
+ id: name,
+ name: `${name.slice(4)} (${name})`,
+ }))
+ .filter((option) => words.every((word) => option.name.toLowerCase().includes(word)))
+ .sort((a, b) => a.name.localeCompare(b.name))
+ }
+ const response = await propertyDefinitionsList(props.projectId, {
+ type: values.propertyType,
+ limit: 20,
+ search: values.search,
+ })
+ breakpoint()
return response.results.map((item) => ({ id: item.id, name: item.name }))
},
},
@@ -173,19 +194,35 @@ export const addPropertyRestrictionModalLogic = kea<addPropertyRestrictionModalL
selectors({
/** The rule already stored for the picked property, so the modal offers an update, not a silent overwrite. */
existingRule: [
- (s) => [s.properties, s.propertyId],
- (properties: AccessPropertyRule[], propertyId: string | null): AccessPropertyRule | null =>
- propertyId ? (properties.find((p) => p.property_definition_id === propertyId) ?? null) : null,
+ (s) => [s.properties, s.propertyId, s.propertyType],
+ (
+ properties: AccessPropertyRule[],
+ propertyId: string | null,
+ propertyType: 'ai' | 'event' | 'person'
+ ): AccessPropertyRule | null =>
+ propertyId
+ ? (properties.find((p) =>
+ propertyType === 'ai'
+ ? p.property_type === 'event' && p.property === propertyId
+ : p.property_definition_id === propertyId
+ ) ?? null)
+ : null,
],
// Selecting an option resets the search, which reloads the options; keep the picked one in
// the list so LemonInputSelect can render its name instead of the raw id
displayPropertyOptions: [
- (s) => [s.propertyOptions, s.selectedProperty],
- (propertyOptions: PropertyOption[], selectedProperty: PropertyOption | null): PropertyOption[] =>
- selectedProperty && !propertyOptions.some((o) => o.id === selectedProperty.id)
- ? [selectedProperty, ...propertyOptions]
- : propertyOptions,
+ (s) => [s.propertyOptions, s.selectedProperty, s.propertyOptionsLoading],
+ (
+ propertyOptions: PropertyOption[],
+ selectedProperty: PropertyOption | null,
+ loading: boolean
+ ): PropertyOption[] => {
+ const options = loading ? [] : propertyOptions
+ return selectedProperty && !options.some((o) => o.id === selectedProperty.id)
+ ? [selectedProperty, ...options]
+ : options
+ },
],
}),
@@ -198,13 +235,20 @@ export const addPropertyRestrictionModalLogic = kea<addPropertyRestrictionModalL
propertyId ? (values.propertyOptions.find((o) => o.id === propertyId) ?? null) : null
)
},
+ propertyRuleSaved: () => actions.closeModal(),
submitRule: () => {
- // isOpen guards a double click: the first submit closes the modal synchronously
- if (!values.isOpen || !values.propertyId) {
+ if (!values.isOpen || !values.propertyId || values.ruleSaving || values.propertyOptionsLoading) {
return
}
- actions.setPropertyRule(values.propertyId, values.level)
- actions.closeModal()
+ const aiProperty =
+ values.propertyType === 'ai'
+ ? Object.values(AIEventPropertyEnumApi).find((name) => name === values.propertyId)
+ : undefined
+ actions.setPropertyRule(
+ values.existingRule?.property_definition_id ?? values.propertyId,
+ values.level,
+ aiProperty
+ )
},
})),
])
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 13e53b1fa341..6c0e594cef47 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -639,6 +639,7 @@ SPECTACULAR_SETTINGS = {
# Every grantable scope object, from posthog/scopes.py. The frontend's APIScopeObject type
# derives from this enum, so the object list is never copied by hand.
"ScopeObjectEnum": "products.access_control.backend.facade.enums.SCOPE_OBJECT_CHOICES",
+ "AIEventPropertyEnum": "products.access_control.backend.facade.enums.AI_EVENT_PROPERTY_CHOICES",
"TaskArtifactStatusEnum": ["active", "failed"],
# signals maps a warehouse import's status down to these three. Same values as the
# warehouse's own SyncStatus, but that class carries different labels, so the two are
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index d507805382df..d8c51c62df11 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -21,6 +21,7 @@ from __future__ import annotations
from typing import cast
from uuid import UUID
+from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404
@@ -32,6 +33,7 @@ from posthog.models.user import User
from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
from products.access_control.backend.models.role import Role, RoleMembership
+from products.event_definitions.backend.models import effective_project_id_expr
from ..models.access_control import AccessControl
from ..models.property_access_control import PropertyAccessControl
@@ -41,6 +43,7 @@ from ..property_access_control import (
)
from . import contracts
from .contracts import PropertyAccessLevel
+from .enums import AI_EVENT_PROPERTY_CHOICES
from .user_access_control import (
RESOURCE_INHERITANCE_MAP,
RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS,
@@ -97,8 +100,13 @@ def _get_property_definition(property_definition_id: str, team_id: int) -> Prope
UUID(str(property_definition_id))
except ValueError as exc:
raise PropertyDefinitionNotFoundError(property_definition_id) from exc
+ project_id = Team.objects.values_list("project_id", flat=True).get(id=team_id)
try:
- return get_object_or_404(PropertyDefinition, id=property_definition_id, team_id=team_id)
+ return get_object_or_404(
+ PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()),
+ effective_project_id=project_id,
+ id=property_definition_id,
+ )
except Http404 as exc:
# Normalize 404 -> domain error so presentation can translate without leaking ORM concerns.
raise PropertyDefinitionNotFoundError(property_definition_id) from exc
@@ -316,6 +324,20 @@ def valid_role_member_user_ids(*, role_id: str | UUID) -> list[int]:
# --- Write API ---
+def _get_or_create_ai_property_definition(team_id: int, property_name: str) -> PropertyDefinition:
+ project_id = Team.objects.values_list("project_id", flat=True).get(id=team_id)
+ project_definitions = PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()).filter(
+ effective_project_id=project_id
+ )
+ definition, _ = project_definitions.get_or_create(
+ name=property_name,
+ type=PropertyDefinition.Type.EVENT,
+ group_type_index=None,
+ defaults={"team_id": team_id, "project_id": project_id},
+ )
+ return definition
+
+
def _validate_target_org(
*,
team_id: int,
@@ -359,29 +381,37 @@ def upsert_property_access_control(
input: contracts.UpsertPropertyAccessControlInput,
) -> contracts.PropertyAccessControlRule:
"""Create or update a single access control rule."""
- prop_def = _get_property_definition(input.property_definition_id, team_id)
+ if input.ai_property is not None and input.ai_property not in AI_EVENT_PROPERTY_CHOICES:
+ raise InvalidPropertyAccessControlTargetError("Unknown AI event property.")
_validate_target_org(
team_id=team_id,
organization_member_id=input.organization_member_id,
role_id=input.role_id,
)
- # `created_by_id` must only be set on creation — using `defaults` would
- # overwrite the original creator on every update. `create_defaults`
- # (Django 4.2+) is applied only when a new row is inserted.
- rule, _created = PropertyAccessControl.objects.update_or_create(
- team_id=team_id,
- property_definition=prop_def,
- organization_member_id=input.organization_member_id,
- role_id=input.role_id,
- defaults={
- "access_level": input.access_level.value,
- },
- create_defaults={
- "access_level": input.access_level.value,
- "created_by_id": created_by_id,
- },
- )
+ with transaction.atomic():
+ if input.ai_property is not None:
+ prop_def = _get_or_create_ai_property_definition(team_id, input.ai_property)
+ else:
+ assert input.property_definition_id is not None
+ prop_def = _get_property_definition(input.property_definition_id, team_id)
+
+ # `created_by_id` must only be set on creation — using `defaults` would
+ # overwrite the original creator on every update. `create_defaults`
+ # (Django 4.2+) is applied only when a new row is inserted.
+ rule, _created = PropertyAccessControl.objects.update_or_create(
+ team_id=team_id,
+ property_definition=prop_def,
+ organization_member_id=input.organization_member_id,
+ role_id=input.role_id,
+ defaults={
+ "access_level": input.access_level.value,
+ },
+ create_defaults={
+ "access_level": input.access_level.value,
+ "created_by_id": created_by_id,
+ },
+ )
return _to_rule(rule)
diff --git a/products/access_control/backend/facade/contracts.py b/products/access_control/backend/facade/contracts.py
index 474a142dccf4..5dcbcd5f91f0 100644
--- a/products/access_control/backend/facade/contracts.py
+++ b/products/access_control/backend/facade/contracts.py
@@ -10,6 +10,8 @@ from datetime import datetime
from enum import Enum
from uuid import UUID
+from posthog.dataclasses import frozen
+
class PropertyAccessLevel(str, Enum):
"""Effective access level for a property."""
@@ -60,15 +62,20 @@ class PropertyAccessControlState:
# --- Input DTOs ---
-@dataclass(frozen=True)
+@frozen
class UpsertPropertyAccessControlInput:
"""Input for creating or updating an access control rule."""
- property_definition_id: str
access_level: PropertyAccessLevel
+ property_definition_id: str | None = None
+ ai_property: str | None = None
organization_member_id: UUID | None = None
role_id: UUID | None = None
+ def __post_init__(self) -> None:
+ if (self.property_definition_id is None) == (self.ai_property is None):
+ raise ValueError("Provide exactly one of property_definition_id or ai_property.")
+
@dataclass(frozen=True)
class DeletePropertyAccessControlInput:
diff --git a/products/access_control/backend/facade/enums.py b/products/access_control/backend/facade/enums.py
index ede2bfa236ed..f9c3da3a9872 100644
--- a/products/access_control/backend/facade/enums.py
+++ b/products/access_control/backend/facade/enums.py
@@ -14,6 +14,8 @@ should stay in the implementation (logic.py, models.py).
from typing import Literal, get_args
+from posthog.hogql.database.schema.ai_events import AI_PROPERTY_TO_COLUMN
+
from posthog.scopes import GRANTABLE_API_SCOPE_OBJECTS
ResolvedAccessSourceValue = Literal[
@@ -38,3 +40,5 @@ RESOLVED_ACCESS_SOURCE_SUBJECT_CHOICES: list[str] = list(get_args(ResolvedAccess
# Keep every grantable scope object here. The scope pickers get their type from this enum, so a
# narrower list would remove objects from the OAuth consent screen and the key picker.
SCOPE_OBJECT_CHOICES: list[str] = list(GRANTABLE_API_SCOPE_OBJECTS)
+
+AI_EVENT_PROPERTY_CHOICES: list[str] = list(AI_PROPERTY_TO_COLUMN)
diff --git a/products/access_control/backend/presentation/serializers.py b/products/access_control/backend/presentation/serializers.py
index 0645a2d0ca8f..cbc97c146be6 100644
--- a/products/access_control/backend/presentation/serializers.py
+++ b/products/access_control/backend/presentation/serializers.py
@@ -12,7 +12,7 @@ from posthog.models.organization import OrganizationMembership
from ..facade import contracts
from ..facade.contracts import PropertyAccessLevel
-from ..facade.enums import SCOPE_OBJECT_CHOICES
+from ..facade.enums import AI_EVENT_PROPERTY_CHOICES, SCOPE_OBJECT_CHOICES
from ..facade.user_access_control import RULE_RESOURCE_CHOICES
from .access_control import ResolvedAccessSerializer
@@ -85,7 +85,13 @@ class PropertyAccessControlUpdateSerializer(serializers.Serializer):
"""Request body for upserting a rule (create or update)."""
property_definition_id = serializers.CharField(
- help_text="The property definition ID this rule applies to.",
+ required=False,
+ help_text="The existing property definition ID. Provide this or ai_property.",
+ )
+ ai_property = serializers.ChoiceField(
+ choices=AI_EVENT_PROPERTY_CHOICES,
+ required=False,
+ help_text="A built-in AI event property. Creates its definition if missing. Provide this or property_definition_id.",
)
access_level = serializers.ChoiceField(
choices=_ACCESS_LEVEL_CHOICES,
@@ -104,6 +110,11 @@ class PropertyAccessControlUpdateSerializer(serializers.Serializer):
help_text="The role UUID to set an override for.",
)
+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:
+ if ("property_definition_id" in attrs) == ("ai_property" in attrs):
+ raise serializers.ValidationError("Provide exactly one of property_definition_id or ai_property.")
+ return attrs
+
class PropertyAccessControlDeleteSerializer(serializers.Serializer):
"""Query parameters for deleting a rule.
diff --git a/products/access_control/backend/presentation/views.py b/products/access_control/backend/presentation/views.py
index bb1e5bd01925..4a2380bb3996 100644
--- a/products/access_control/backend/presentation/views.py
+++ b/products/access_control/backend/presentation/views.py
@@ -133,7 +133,8 @@ class PropertyAccessControlViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
team_id=self.team_id,
created_by_id=created_by_id,
input=UpsertPropertyAccessControlInput(
- property_definition_id=data["property_definition_id"],
+ property_definition_id=data.get("property_definition_id"),
+ ai_property=data.get("ai_property"),
access_level=PropertyAccessLevel(data["access_level"]),
organization_member_id=data.get("organization_member"),
role_id=data.get("role"),
diff --git a/products/access_control/backend/tests/test_property_access_control_viewset.py b/products/access_control/backend/tests/test_property_access_control_viewset.py
index c2f56c7c0316..c3c0ba6521eb 100644
--- a/products/access_control/backend/tests/test_property_access_control_viewset.py
+++ b/products/access_control/backend/tests/test_property_access_control_viewset.py
@@ -1,12 +1,19 @@
+from urllib.parse import urlencode
+
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership, PropertyDefinition, User
+from posthog.models import OrganizationMembership, PropertyDefinition, Team, User
from products.access_control.backend.models.property_access_control import PropertyAccessControl
-from products.access_control.backend.property_access_control import PropertyAccessLevel
+from products.access_control.backend.models.role import Role
+from products.access_control.backend.presentation.serializers import PropertyAccessControlUpdateSerializer
+from products.access_control.backend.property_access_control import PropertyAccessLevel, get_restricted_property_names
class TestPropertyAccessControlViewSet(APIBaseTest):
@@ -28,11 +35,12 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
property_type="String",
type=PropertyDefinition.Type.EVENT,
)
- self.url = f"/api/environments/{self.team.pk}/property_access_controls/"
+ self.url = f"/api/projects/{self.team.pk}/property_access_controls/"
self.list_url = f"{self.url}?property_definition_id={self.prop_def.id}"
- def _post(self, data: dict):
- payload = {"property_definition_id": str(self.prop_def.id), **data}
+ def _post(self, data: dict, *, ai_property: bool = False):
+ selector = {"ai_property": "$ai_input"} if ai_property else {"property_definition_id": str(self.prop_def.id)}
+ payload = {**selector, **data}
return self.client.post(self.url, payload, format="json")
def test_list_empty(self):
@@ -61,12 +69,121 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
assert list_response.json()["default_access_level"] == PropertyAccessLevel.NONE.value
assert len(list_response.json()["access_controls"]) == 1
- def test_create_member_override(self):
+ @parameterized.expand([("$ai_input",), ("$ai_output",), ("$ai_output_choices",)])
+ def test_create_ai_rule_before_ingestion(self, property_name: str) -> None:
+ response = self.client.post(self.url, {"ai_property": property_name, "access_level": "none"}, format="json")
+ assert response.status_code == status.HTTP_200_OK
+ definition = PropertyDefinition.objects.get(team=self.team, name=property_name)
+ assert definition.type == PropertyDefinition.Type.EVENT
+ assert definition.project_id == self.team.project_id
+ assert get_restricted_property_names(
+ team_id=self.team.id, user=None, property_type=PropertyDefinition.Type.EVENT
+ ) == {property_name}
+
+ repeated = self.client.post(self.url, {"ai_property": property_name, "access_level": "read"}, format="json")
+ assert repeated.status_code == status.HTTP_200_OK
+ assert repeated.json()["id"] == response.json()["id"]
+ assert (
+ self.client.get(f"{self.url}?property_definition_id={definition.id}").json()["default_access_level"]
+ == "read"
+ )
+ assert (
+ self.client.delete(f"{self.url}?property_definition_id={definition.id}").status_code
+ == status.HTTP_204_NO_CONTENT
+ )
+
+ @parameterized.expand([(False,), (True,)])
+ def test_ai_rule_reuses_existing_definition_and_preserves_other_rules(self, legacy_definition: bool) -> None:
+ definition = PropertyDefinition.objects.create(
+ team=self.team,
+ project_id=None if legacy_definition else self.team.project_id,
+ name="$ai_input",
+ type=PropertyDefinition.Type.EVENT,
+ property_type="String",
+ )
+ member_rule = PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ organization_member=self.organization_membership,
+ access_level="read",
+ )
+ PropertyAccessControl.objects.create(team=self.team, property_definition=definition, access_level="read")
+ response = self.client.post(self.url, {"ai_property": "$ai_input", "access_level": "none"}, format="json")
+ assert response.status_code == status.HTTP_200_OK
+ rule = PropertyAccessControl.objects.get(id=response.json()["id"])
+ assert rule.property_definition_id == definition.id
+ assert rule.team_id == self.team.id
+ assert (
+ self.client.get(f"{self.url}?property_definition_id={definition.id}").json()["default_access_level"]
+ == "none"
+ )
+ assert get_restricted_property_names(
+ team_id=self.team.id, user=None, property_type=PropertyDefinition.Type.EVENT
+ ) == {"$ai_input"}
+
+ updated = self.client.post(
+ self.url, {"property_definition_id": str(definition.id), "access_level": "read"}, format="json"
+ )
+ assert updated.status_code == status.HTTP_200_OK
+ assert updated.json()["id"] == response.json()["id"]
+ assert (
+ self.client.get(f"{self.url}?property_definition_id={definition.id}").json()["default_access_level"]
+ == "read"
+ )
+ assert (
+ self.client.delete(f"{self.url}?property_definition_id={definition.id}").status_code
+ == status.HTTP_204_NO_CONTENT
+ )
+ assert not PropertyAccessControl.objects.filter(id=rule.id).exists()
+ definition.refresh_from_db()
+ member_rule.refresh_from_db()
+ assert definition.property_type == "String"
+ assert member_rule.access_level == "read"
+ assert PropertyDefinition.objects.filter(team=self.team, name="$ai_input").count() == 1
+
+ @parameterized.expand([(True,), (False,)])
+ def test_property_rule_rejects_definition_from_another_project(self, legacy_definition: bool) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ definition = PropertyDefinition.objects.create(
+ team=other_team,
+ project_id=None if legacy_definition else other_team.project_id,
+ name="$ai_input",
+ type=PropertyDefinition.Type.EVENT,
+ )
+ rule = PropertyAccessControl.objects.create(
+ team=other_team, property_definition=definition, access_level="none"
+ )
+ assert (
+ self.client.get(f"{self.url}?property_definition_id={definition.id}").status_code
+ == status.HTTP_404_NOT_FOUND
+ )
+ assert (
+ self.client.post(
+ self.url, {"property_definition_id": str(definition.id), "access_level": "read"}, format="json"
+ ).status_code
+ == status.HTTP_404_NOT_FOUND
+ )
+ assert (
+ self.client.delete(f"{self.url}?property_definition_id={definition.id}").status_code
+ == status.HTTP_404_NOT_FOUND
+ )
+ rule.refresh_from_db()
+ assert rule.access_level == "none"
+ assert not PropertyAccessControl.objects.filter(team=self.team, property_definition=definition).exists()
+
+ def test_unknown_ai_property_does_not_create_definition(self) -> None:
+ response = self.client.post(self.url, {"ai_property": "input", "access_level": "none"}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not PropertyDefinition.objects.filter(team=self.team, name="input").exists()
+
+ @parameterized.expand([(False,), (True,)])
+ def test_create_member_override(self, ai_property: bool) -> None:
response = self._post(
{
"access_level": PropertyAccessLevel.READ_WRITE.value,
"organization_member": str(self.organization_membership.id),
- }
+ },
+ ai_property=ai_property,
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["access_level"] == PropertyAccessLevel.READ_WRITE.value
@@ -80,7 +197,8 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
]
self.organization.save()
- def test_create_role_override(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_create_role_override(self, ai_property: bool) -> None:
from products.access_control.backend.models.role import Role
self._grant_role_based_access()
@@ -89,12 +207,53 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
{
"access_level": PropertyAccessLevel.READ.value,
"role": str(role.id),
- }
+ },
+ ai_property=ai_property,
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["access_level"] == PropertyAccessLevel.READ.value
assert str(response.json()["role"]) == str(role.id)
+ @parameterized.expand([("default",), ("member",), ("role",)])
+ def test_ai_rule_remains_visible_in_settings(self, scope: str) -> None:
+ definition = PropertyDefinition.objects.create(
+ team=self.team,
+ project_id=self.team.project_id,
+ name="$ai_input",
+ type=PropertyDefinition.Type.EVENT,
+ )
+ subject: dict[str, str] = {}
+ query: dict[str, str] = {}
+ if scope == "member":
+ subject["organization_member"] = str(self.organization_membership.id)
+ query["member_id"] = str(self.organization_membership.id)
+ elif scope == "role":
+ self._grant_role_based_access()
+ role = Role.objects.create(name="Analyst", organization=self.organization)
+ subject["role"] = str(role.id)
+ query["role_id"] = str(role.id)
+
+ response = self.client.post(
+ self.url, {"ai_property": "$ai_input", "access_level": "none", **subject}, format="json"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ settings_url = f"/api/projects/{self.team.project_id}/access_control_{scope}_properties/"
+ listed = self.client.get(settings_url, query)
+ assert listed.status_code == status.HTTP_200_OK
+ assert listed.json()["results"] == [
+ {
+ "property_definition_id": str(definition.id),
+ "property": "$ai_input",
+ "property_type": "event",
+ "access_level": "none",
+ }
+ ]
+
+ delete_query = urlencode({"property_definition_id": str(definition.id), **subject})
+ deleted = self.client.delete(f"{self.url}?{delete_query}")
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert self.client.get(settings_url, query).json()["results"] == []
+
def test_update_existing_rule(self):
# create a rule
self._post({"access_level": PropertyAccessLevel.NONE.value})
@@ -195,7 +354,8 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
assert len(data["access_controls"]) == 3
assert data["default_access_level"] == PropertyAccessLevel.NONE.value
- def test_cross_org_role_rejected(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_cross_org_role_rejected(self, ai_property: bool) -> None:
from posthog.models import Organization
from products.access_control.backend.models.role import Role
@@ -208,12 +368,15 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
{
"access_level": PropertyAccessLevel.READ.value,
"role": str(other_role.id),
- }
+ },
+ ai_property=ai_property,
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert PropertyAccessControl.objects.filter(property_definition=self.prop_def).count() == 0
+ assert not PropertyDefinition.objects.filter(team=self.team, name="$ai_input").exists()
- def test_cross_org_organization_member_rejected(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_cross_org_organization_member_rejected(self, ai_property: bool) -> None:
from posthog.models import Organization, OrganizationMembership, User
other_org = Organization.objects.create(name="Other org")
@@ -226,10 +389,12 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
{
"access_level": PropertyAccessLevel.READ.value,
"organization_member": str(other_membership.id),
- }
+ },
+ ai_property=ai_property,
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert PropertyAccessControl.objects.filter(property_definition=self.prop_def).count() == 0
+ assert not PropertyDefinition.objects.filter(team=self.team, name="$ai_input").exists()
def test_delete_cross_org_role_rejected(self):
from posthog.models import Organization
@@ -243,7 +408,8 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
response = self.client.delete(f"{self.url}?property_definition_id={self.prop_def.id}&role={other_role.id}")
assert response.status_code == status.HTTP_400_BAD_REQUEST
- def test_member_with_implicit_project_admin_can_read_but_not_write(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_member_with_implicit_project_admin_can_read_but_not_write(self, ai_property: bool) -> None:
self.organization.available_product_features = [
{
"name": AvailableFeature.PROPERTY_ACCESS_CONTROL,
@@ -271,7 +437,7 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
response = self.client.get(self.list_url)
assert response.status_code == status.HTTP_200_OK
- response = self._post({"access_level": PropertyAccessLevel.READ_WRITE.value})
+ response = self._post({"access_level": PropertyAccessLevel.READ_WRITE.value}, ai_property=ai_property)
assert response.status_code == status.HTTP_403_FORBIDDEN
response = self.client.delete(
@@ -279,26 +445,33 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert PropertyAccessControl.objects.filter(id=rule.id).exists()
+ assert not PropertyDefinition.objects.filter(team=self.team, name="$ai_input").exists()
- def test_create_forbidden_without_property_access_control_feature(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_create_forbidden_without_property_access_control_feature(self, ai_property: bool) -> None:
# Org lost (or never had) the PROPERTY_ACCESS_CONTROL entitlement — writes must be blocked
# so rules cannot be added or modified. Existing rules continue to affect query behavior.
self.organization.available_product_features = []
self.organization.save()
- response = self._post({"access_level": PropertyAccessLevel.NONE.value})
+ response = self._post({"access_level": PropertyAccessLevel.NONE.value}, ai_property=ai_property)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert PropertyAccessControl.objects.filter(property_definition=self.prop_def).count() == 0
# The gate runs before the body is validated, so an invalid body is still a 403 and not a 400
assert self._post({}).status_code == status.HTTP_403_FORBIDDEN
+ assert not PropertyDefinition.objects.filter(team=self.team, name="$ai_input").exists()
- def test_role_rule_forbidden_without_role_based_access_feature(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_role_rule_forbidden_without_role_based_access_feature(self, ai_property: bool) -> None:
from products.access_control.backend.models.role import Role
role = Role.objects.create(name="Analyst", organization=self.organization)
- response = self._post({"access_level": PropertyAccessLevel.READ.value, "role": str(role.id)})
+ response = self._post(
+ {"access_level": PropertyAccessLevel.READ.value, "role": str(role.id)}, ai_property=ai_property
+ )
assert response.status_code == status.HTTP_403_FORBIDDEN
assert PropertyAccessControl.objects.filter(property_definition=self.prop_def).count() == 0
+ assert not PropertyDefinition.objects.filter(team=self.team, name="$ai_input").exists()
def test_delete_forbidden_without_property_access_control_feature(self):
# Create a rule while the feature is available
@@ -326,3 +499,17 @@ class TestPropertyAccessControlViewSet(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["default_access_level"] == PropertyAccessLevel.NONE.value
assert len(response.json()["access_controls"]) == 1
+
+
+class TestPropertyAccessControlUpdateSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ({},),
+ ({"property_definition_id": "existing", "ai_property": "$ai_input"},),
+ ({"ai_property": "input"},),
+ ({"ai_property": "$ai_unknown"},),
+ ]
+ )
+ def test_invalid_property_selector(self, selector: dict[str, str]) -> None:
+ serializer = PropertyAccessControlUpdateSerializer(data={**selector, "access_level": "none"})
+ assert not serializer.is_valid()
diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.ts
index 6436464762dd..cc04bca49811 100644
--- a/products/access_control/frontend/generated/api.schemas.ts
+++ b/products/access_control/frontend/generated/api.schemas.ts
@@ -1453,12 +1453,166 @@ export interface PropertyAccessControlStateApi {
default_access_level: string
}
+/**
+ * * `$ai_trace_id` - $ai_trace_id
+ * * `$ai_session_id` - $ai_session_id
+ * * `$ai_parent_id` - $ai_parent_id
+ * * `$ai_span_id` - $ai_span_id
+ * * `$ai_span_type` - $ai_span_type
+ * * `$ai_generation_id` - $ai_generation_id
+ * * `$ai_experiment_id` - $ai_experiment_id
+ * * `$ai_span_name` - $ai_span_name
+ * * `$ai_trace_name` - $ai_trace_name
+ * * `$ai_prompt_name` - $ai_prompt_name
+ * * `$ai_model` - $ai_model
+ * * `$ai_provider` - $ai_provider
+ * * `$ai_framework` - $ai_framework
+ * * `$ai_total_tokens` - $ai_total_tokens
+ * * `$ai_input_tokens` - $ai_input_tokens
+ * * `$ai_output_tokens` - $ai_output_tokens
+ * * `$ai_text_input_tokens` - $ai_text_input_tokens
+ * * `$ai_text_output_tokens` - $ai_text_output_tokens
+ * * `$ai_image_input_tokens` - $ai_image_input_tokens
+ * * `$ai_image_output_tokens` - $ai_image_output_tokens
+ * * `$ai_audio_input_tokens` - $ai_audio_input_tokens
+ * * `$ai_audio_output_tokens` - $ai_audio_output_tokens
+ * * `$ai_video_input_tokens` - $ai_video_input_tokens
+ * * `$ai_video_output_tokens` - $ai_video_output_tokens
+ * * `$ai_reasoning_tokens` - $ai_reasoning_tokens
+ * * `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens
+ * * `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens
+ * * `$ai_web_search_count` - $ai_web_search_count
+ * * `$ai_input_cost_usd` - $ai_input_cost_usd
+ * * `$ai_output_cost_usd` - $ai_output_cost_usd
+ * * `$ai_total_cost_usd` - $ai_total_cost_usd
+ * * `$ai_request_cost_usd` - $ai_request_cost_usd
+ * * `$ai_web_search_cost_usd` - $ai_web_search_cost_usd
+ * * `$ai_audio_cost_usd` - $ai_audio_cost_usd
+ * * `$ai_image_cost_usd` - $ai_image_cost_usd
+ * * `$ai_video_cost_usd` - $ai_video_cost_usd
+ * * `$ai_latency` - $ai_latency
+ * * `$ai_time_to_first_token` - $ai_time_to_first_token
+ * * `$ai_is_error` - $ai_is_error
+ * * `$ai_error` - $ai_error
+ * * `$ai_error_type` - $ai_error_type
+ * * `$ai_error_normalized` - $ai_error_normalized
+ * * `$ai_input` - $ai_input
+ * * `$ai_output` - $ai_output
+ * * `$ai_output_choices` - $ai_output_choices
+ * * `$ai_input_state` - $ai_input_state
+ * * `$ai_output_state` - $ai_output_state
+ * * `$ai_tools` - $ai_tools
+ */
+export type AIEventPropertyEnumApi = (typeof AIEventPropertyEnumApi)[keyof typeof AIEventPropertyEnumApi]
+
+export const AIEventPropertyEnumApi = {
+ AiTraceId: '$ai_trace_id',
+ AiSessionId: '$ai_session_id',
+ AiParentId: '$ai_parent_id',
+ AiSpanId: '$ai_span_id',
+ AiSpanType: '$ai_span_type',
+ AiGenerationId: '$ai_generation_id',
+ AiExperimentId: '$ai_experiment_id',
+ AiSpanName: '$ai_span_name',
+ AiTraceName: '$ai_trace_name',
+ AiPromptName: '$ai_prompt_name',
+ AiModel: '$ai_model',
+ AiProvider: '$ai_provider',
+ AiFramework: '$ai_framework',
+ AiTotalTokens: '$ai_total_tokens',
+ AiInputTokens: '$ai_input_tokens',
+ AiOutputTokens: '$ai_output_tokens',
+ AiTextInputTokens: '$ai_text_input_tokens',
+ AiTextOutputTokens: '$ai_text_output_tokens',
+ AiImageInputTokens: '$ai_image_input_tokens',
+ AiImageOutputTokens: '$ai_image_output_tokens',
+ AiAudioInputTokens: '$ai_audio_input_tokens',
+ AiAudioOutputTokens: '$ai_audio_output_tokens',
+ AiVideoInputTokens: '$ai_video_input_tokens',
+ AiVideoOutputTokens: '$ai_video_output_tokens',
+ AiReasoningTokens: '$ai_reasoning_tokens',
+ AiCacheReadInputTokens: '$ai_cache_read_input_tokens',
+ AiCacheCreationInputTokens: '$ai_cache_creation_input_tokens',
+ AiWebSearchCount: '$ai_web_search_count',
+ AiInputCostUsd: '$ai_input_cost_usd',
+ AiOutputCostUsd: '$ai_output_cost_usd',
+ AiTotalCostUsd: '$ai_total_cost_usd',
+ AiRequestCostUsd: '$ai_request_cost_usd',
+ AiWebSearchCostUsd: '$ai_web_search_cost_usd',
+ AiAudioCostUsd: '$ai_audio_cost_usd',
+ AiImageCostUsd: '$ai_image_cost_usd',
+ AiVideoCostUsd: '$ai_video_cost_usd',
+ AiLatency: '$ai_latency',
+ AiTimeToFirstToken: '$ai_time_to_first_token',
+ AiIsError: '$ai_is_error',
+ AiError: '$ai_error',
+ AiErrorType: '$ai_error_type',
+ AiErrorNormalized: '$ai_error_normalized',
+ AiInput: '$ai_input',
+ AiOutput: '$ai_output',
+ AiOutputChoices: '$ai_output_choices',
+ AiInputState: '$ai_input_state',
+ AiOutputState: '$ai_output_state',
+ AiTools: '$ai_tools',
+} as const
+
/**
* Request body for upserting a rule (create or update).
*/
export interface PropertyAccessControlUpdateApi {
- /** The property definition ID this rule applies to. */
- property_definition_id: string
+ /** The existing property definition ID. Provide this or ai_property. */
+ property_definition_id?: string
+ /** A built-in AI event property. Creates its definition if missing. Provide this or property_definition_id.
+ *
+ * * `$ai_trace_id` - $ai_trace_id
+ * * `$ai_session_id` - $ai_session_id
+ * * `$ai_parent_id` - $ai_parent_id
+ * * `$ai_span_id` - $ai_span_id
+ * * `$ai_span_type` - $ai_span_type
+ * * `$ai_generation_id` - $ai_generation_id
+ * * `$ai_experiment_id` - $ai_experiment_id
+ * * `$ai_span_name` - $ai_span_name
+ * * `$ai_trace_name` - $ai_trace_name
+ * * `$ai_prompt_name` - $ai_prompt_name
+ * * `$ai_model` - $ai_model
+ * * `$ai_provider` - $ai_provider
+ * * `$ai_framework` - $ai_framework
+ * * `$ai_total_tokens` - $ai_total_tokens
+ * * `$ai_input_tokens` - $ai_input_tokens
+ * * `$ai_output_tokens` - $ai_output_tokens
+ * * `$ai_text_input_tokens` - $ai_text_input_tokens
+ * * `$ai_text_output_tokens` - $ai_text_output_tokens
+ * * `$ai_image_input_tokens` - $ai_image_input_tokens
+ * * `$ai_image_output_tokens` - $ai_image_output_tokens
+ * * `$ai_audio_input_tokens` - $ai_audio_input_tokens
+ * * `$ai_audio_output_tokens` - $ai_audio_output_tokens
+ * * `$ai_video_input_tokens` - $ai_video_input_tokens
+ * * `$ai_video_output_tokens` - $ai_video_output_tokens
+ * * `$ai_reasoning_tokens` - $ai_reasoning_tokens
+ * * `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens
+ * * `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens
+ * * `$ai_web_search_count` - $ai_web_search_count
+ * * `$ai_input_cost_usd` - $ai_input_cost_usd
+ * * `$ai_output_cost_usd` - $ai_output_cost_usd
+ * * `$ai_total_cost_usd` - $ai_total_cost_usd
+ * * `$ai_request_cost_usd` - $ai_request_cost_usd
+ * * `$ai_web_search_cost_usd` - $ai_web_search_cost_usd
+ * * `$ai_audio_cost_usd` - $ai_audio_cost_usd
+ * * `$ai_image_cost_usd` - $ai_image_cost_usd
+ * * `$ai_video_cost_usd` - $ai_video_cost_usd
+ * * `$ai_latency` - $ai_latency
+ * * `$ai_time_to_first_token` - $ai_time_to_first_token
+ * * `$ai_is_error` - $ai_is_error
+ * * `$ai_error` - $ai_error
+ * * `$ai_error_type` - $ai_error_type
+ * * `$ai_error_normalized` - $ai_error_normalized
+ * * `$ai_input` - $ai_input
+ * * `$ai_output` - $ai_output
+ * * `$ai_output_choices` - $ai_output_choices
+ * * `$ai_input_state` - $ai_input_state
+ * * `$ai_output_state` - $ai_output_state
+ * * `$ai_tools` - $ai_tools */
+ ai_property?: AIEventPropertyEnumApi
/** The access level to set for this rule.
*
* * `read_write` - read_write
diff --git a/products/access_control/frontend/generated/api.zod.ts b/products/access_control/frontend/generated/api.zod.ts
index bebf009fa380..eba4d2d313dc 100644
--- a/products/access_control/frontend/generated/api.zod.ts
+++ b/products/access_control/frontend/generated/api.zod.ts
@@ -266,7 +266,68 @@ export const OrganizationsProjectsAccessControlRoleRulesUpdateBody = /* @__PURE_
*/
export const PropertyAccessControlsCreateBody = /* @__PURE__ */ zod
.object({
- property_definition_id: zod.string().describe('The property definition ID this rule applies to.'),
+ property_definition_id: zod
+ .string()
+ .optional()
+ .describe('The existing property definition ID. Provide this or ai_property.'),
+ ai_property: zod
+ .enum([
+ '$ai_trace_id',
+ '$ai_session_id',
+ '$ai_parent_id',
+ '$ai_span_id',
+ '$ai_span_type',
+ '$ai_generation_id',
+ '$ai_experiment_id',
+ '$ai_span_name',
+ '$ai_trace_name',
+ '$ai_prompt_name',
+ '$ai_model',
+ '$ai_provider',
+ '$ai_framework',
+ '$ai_total_tokens',
+ '$ai_input_tokens',
+ '$ai_output_tokens',
+ '$ai_text_input_tokens',
+ '$ai_text_output_tokens',
+ '$ai_image_input_tokens',
+ '$ai_image_output_tokens',
+ '$ai_audio_input_tokens',
+ '$ai_audio_output_tokens',
+ '$ai_video_input_tokens',
+ '$ai_video_output_tokens',
+ '$ai_reasoning_tokens',
+ '$ai_cache_read_input_tokens',
+ '$ai_cache_creation_input_tokens',
+ '$ai_web_search_count',
+ '$ai_input_cost_usd',
+ '$ai_output_cost_usd',
+ '$ai_total_cost_usd',
+ '$ai_request_cost_usd',
+ '$ai_web_search_cost_usd',
+ '$ai_audio_cost_usd',
+ '$ai_image_cost_usd',
+ '$ai_video_cost_usd',
+ '$ai_latency',
+ '$ai_time_to_first_token',
+ '$ai_is_error',
+ '$ai_error',
+ '$ai_error_type',
+ '$ai_error_normalized',
+ '$ai_input',
+ '$ai_output',
+ '$ai_output_choices',
+ '$ai_input_state',
+ '$ai_output_state',
+ '$ai_tools',
+ ])
+ .describe(
+ '\* `$ai_trace_id` - $ai_trace_id\n\* `$ai_session_id` - $ai_session_id\n\* `$ai_parent_id` - $ai_parent_id\n\* `$ai_span_id` - $ai_span_id\n\* `$ai_span_type` - $ai_span_type\n\* `$ai_generation_id` - $ai_generation_id\n\* `$ai_experiment_id` - $ai_experiment_id\n\* `$ai_span_name` - $ai_span_name\n\* `$ai_trace_name` - $ai_trace_name\n\* `$ai_prompt_name` - $ai_prompt_name\n\* `$ai_model` - $ai_model\n\* `$ai_provider` - $ai_provider\n\* `$ai_framework` - $ai_framework\n\* `$ai_total_tokens` - $ai_total_tokens\n\* `$ai_input_tokens` - $ai_input_tokens\n\* `$ai_output_tokens` - $ai_output_tokens\n\* `$ai_text_input_tokens` - $ai_text_input_tokens\n\* `$ai_text_output_tokens` - $ai_text_output_tokens\n\* `$ai_image_input_tokens` - $ai_image_input_tokens\n\* `$ai_image_output_tokens` - $ai_image_output_tokens\n\* `$ai_audio_input_tokens` - $ai_audio_input_tokens\n\* `$ai_audio_output_tokens` - $ai_audio_output_tokens\n\* `$ai_video_input_tokens` - $ai_video_input_tokens\n\* `$ai_video_output_tokens` - $ai_video_output_tokens\n\* `$ai_reasoning_tokens` - $ai_reasoning_tokens\n\* `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens\n\* `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens\n\* `$ai_web_search_count` - $ai_web_search_count\n\* `$ai_input_cost_usd` - $ai_input_cost_usd\n\* `$ai_output_cost_usd` - $ai_output_cost_usd\n\* `$ai_total_cost_usd` - $ai_total_cost_usd\n\* `$ai_request_cost_usd` - $ai_request_cost_usd\n\* `$ai_web_search_cost_usd` - $ai_web_search_cost_usd\n\* `$ai_audio_cost_usd` - $ai_audio_cost_usd\n\* `$ai_image_cost_usd` - $ai_image_cost_usd\n\* `$ai_video_cost_usd` - $ai_video_cost_usd\n\* `$ai_latency` - $ai_latency\n\* `$ai_time_to_first_token` - $ai_time_to_first_token\n\* `$ai_is_error` - $ai_is_error\n\* `$ai_error` - $ai_error\n\* `$ai_error_type` - $ai_error_type\n\* `$ai_error_normalized` - $ai_error_normalized\n\* `$ai_input` - $ai_input\n\* `$ai_output` - $ai_output\n\* `$ai_output_choices` - $ai_output_choices\n\* `$ai_input_state` - $ai_input_state\n\* `$ai_output_state` - $ai_output_state\n\* `$ai_tools` - $ai_tools'
+ )
+ .optional()
+ .describe(
+ 'A built-in AI event property. Creates its definition if missing. Provide this or property_definition_id.\n\n\* `$ai_trace_id` - $ai_trace_id\n\* `$ai_session_id` - $ai_session_id\n\* `$ai_parent_id` - $ai_parent_id\n\* `$ai_span_id` - $ai_span_id\n\* `$ai_span_type` - $ai_span_type\n\* `$ai_generation_id` - $ai_generation_id\n\* `$ai_experiment_id` - $ai_experiment_id\n\* `$ai_span_name` - $ai_span_name\n\* `$ai_trace_name` - $ai_trace_name\n\* `$ai_prompt_name` - $ai_prompt_name\n\* `$ai_model` - $ai_model\n\* `$ai_provider` - $ai_provider\n\* `$ai_framework` - $ai_framework\n\* `$ai_total_tokens` - $ai_total_tokens\n\* `$ai_input_tokens` - $ai_input_tokens\n\* `$ai_output_tokens` - $ai_output_tokens\n\* `$ai_text_input_tokens` - $ai_text_input_tokens\n\* `$ai_text_output_tokens` - $ai_text_output_tokens\n\* `$ai_image_input_tokens` - $ai_image_input_tokens\n\* `$ai_image_output_tokens` - $ai_image_output_tokens\n\* `$ai_audio_input_tokens` - $ai_audio_input_tokens\n\* `$ai_audio_output_tokens` - $ai_audio_output_tokens\n\* `$ai_video_input_tokens` - $ai_video_input_tokens\n\* `$ai_video_output_tokens` - $ai_video_output_tokens\n\* `$ai_reasoning_tokens` - $ai_reasoning_tokens\n\* `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens\n\* `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens\n\* `$ai_web_search_count` - $ai_web_search_count\n\* `$ai_input_cost_usd` - $ai_input_cost_usd\n\* `$ai_output_cost_usd` - $ai_output_cost_usd\n\* `$ai_total_cost_usd` - $ai_total_cost_usd\n\* `$ai_request_cost_usd` - $ai_request_cost_usd\n\* `$ai_web_search_cost_usd` - $ai_web_search_cost_usd\n\* `$ai_audio_cost_usd` - $ai_audio_cost_usd\n\* `$ai_image_cost_usd` - $ai_image_cost_usd\n\* `$ai_video_cost_usd` - $ai_video_cost_usd\n\* `$ai_latency` - $ai_latency\n\* `$ai_time_to_first_token` - $ai_time_to_first_token\n\* `$ai_is_error` - $ai_is_error\n\* `$ai_error` - $ai_error\n\* `$ai_error_type` - $ai_error_type\n\* `$ai_error_normalized` - $ai_error_normalized\n\* `$ai_input` - $ai_input\n\* `$ai_output` - $ai_output\n\* `$ai_output_choices` - $ai_output_choices\n\* `$ai_input_state` - $ai_input_state\n\* `$ai_output_state` - $ai_output_state\n\* `$ai_tools` - $ai_tools'
+ ),
access_level: zod
.enum(['read_write', 'read', 'none'])
.describe('\* `read_write` - read_write\n\* `read` - read\n\* `none` - none')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c9091ca0a394..c3750d4b8570 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20,6 +20,110 @@ export namespace Schemas {
name: string;
}
+ /**
+ * * `$ai_trace_id` - $ai_trace_id
+ * * `$ai_session_id` - $ai_session_id
+ * * `$ai_parent_id` - $ai_parent_id
+ * * `$ai_span_id` - $ai_span_id
+ * * `$ai_span_type` - $ai_span_type
+ * * `$ai_generation_id` - $ai_generation_id
+ * * `$ai_experiment_id` - $ai_experiment_id
+ * * `$ai_span_name` - $ai_span_name
+ * * `$ai_trace_name` - $ai_trace_name
+ * * `$ai_prompt_name` - $ai_prompt_name
+ * * `$ai_model` - $ai_model
+ * * `$ai_provider` - $ai_provider
+ * * `$ai_framework` - $ai_framework
+ * * `$ai_total_tokens` - $ai_total_tokens
+ * * `$ai_input_tokens` - $ai_input_tokens
+ * * `$ai_output_tokens` - $ai_output_tokens
+ * * `$ai_text_input_tokens` - $ai_text_input_tokens
+ * * `$ai_text_output_tokens` - $ai_text_output_tokens
+ * * `$ai_image_input_tokens` - $ai_image_input_tokens
+ * * `$ai_image_output_tokens` - $ai_image_output_tokens
+ * * `$ai_audio_input_tokens` - $ai_audio_input_tokens
+ * * `$ai_audio_output_tokens` - $ai_audio_output_tokens
+ * * `$ai_video_input_tokens` - $ai_video_input_tokens
+ * * `$ai_video_output_tokens` - $ai_video_output_tokens
+ * * `$ai_reasoning_tokens` - $ai_reasoning_tokens
+ * * `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens
+ * * `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens
+ * * `$ai_web_search_count` - $ai_web_search_count
+ * * `$ai_input_cost_usd` - $ai_input_cost_usd
+ * * `$ai_output_cost_usd` - $ai_output_cost_usd
+ * * `$ai_total_cost_usd` - $ai_total_cost_usd
+ * * `$ai_request_cost_usd` - $ai_request_cost_usd
+ * * `$ai_web_search_cost_usd` - $ai_web_search_cost_usd
+ * * `$ai_audio_cost_usd` - $ai_audio_cost_usd
+ * * `$ai_image_cost_usd` - $ai_image_cost_usd
+ * * `$ai_video_cost_usd` - $ai_video_cost_usd
+ * * `$ai_latency` - $ai_latency
+ * * `$ai_time_to_first_token` - $ai_time_to_first_token
+ * * `$ai_is_error` - $ai_is_error
+ * * `$ai_error` - $ai_error
+ * * `$ai_error_type` - $ai_error_type
+ * * `$ai_error_normalized` - $ai_error_normalized
+ * * `$ai_input` - $ai_input
+ * * `$ai_output` - $ai_output
+ * * `$ai_output_choices` - $ai_output_choices
+ * * `$ai_input_state` - $ai_input_state
+ * * `$ai_output_state` - $ai_output_state
+ * * `$ai_tools` - $ai_tools
+ */
+ export type AIEventPropertyEnum = typeof AIEventPropertyEnum[keyof typeof AIEventPropertyEnum];
+
+
+ export const AIEventPropertyEnum = {
+ AiTraceId: '$ai_trace_id',
+ AiSessionId: '$ai_session_id',
+ AiParentId: '$ai_parent_id',
+ AiSpanId: '$ai_span_id',
+ AiSpanType: '$ai_span_type',
+ AiGenerationId: '$ai_generation_id',
+ AiExperimentId: '$ai_experiment_id',
+ AiSpanName: '$ai_span_name',
+ AiTraceName: '$ai_trace_name',
+ AiPromptName: '$ai_prompt_name',
+ AiModel: '$ai_model',
+ AiProvider: '$ai_provider',
+ AiFramework: '$ai_framework',
+ AiTotalTokens: '$ai_total_tokens',
+ AiInputTokens: '$ai_input_tokens',
+ AiOutputTokens: '$ai_output_tokens',
+ AiTextInputTokens: '$ai_text_input_tokens',
+ AiTextOutputTokens: '$ai_text_output_tokens',
+ AiImageInputTokens: '$ai_image_input_tokens',
+ AiImageOutputTokens: '$ai_image_output_tokens',
+ AiAudioInputTokens: '$ai_audio_input_tokens',
+ AiAudioOutputTokens: '$ai_audio_output_tokens',
+ AiVideoInputTokens: '$ai_video_input_tokens',
+ AiVideoOutputTokens: '$ai_video_output_tokens',
+ AiReasoningTokens: '$ai_reasoning_tokens',
+ AiCacheReadInputTokens: '$ai_cache_read_input_tokens',
+ AiCacheCreationInputTokens: '$ai_cache_creation_input_tokens',
+ AiWebSearchCount: '$ai_web_search_count',
+ AiInputCostUsd: '$ai_input_cost_usd',
+ AiOutputCostUsd: '$ai_output_cost_usd',
+ AiTotalCostUsd: '$ai_total_cost_usd',
+ AiRequestCostUsd: '$ai_request_cost_usd',
+ AiWebSearchCostUsd: '$ai_web_search_cost_usd',
+ AiAudioCostUsd: '$ai_audio_cost_usd',
+ AiImageCostUsd: '$ai_image_cost_usd',
+ AiVideoCostUsd: '$ai_video_cost_usd',
+ AiLatency: '$ai_latency',
+ AiTimeToFirstToken: '$ai_time_to_first_token',
+ AiIsError: '$ai_is_error',
+ AiError: '$ai_error',
+ AiErrorType: '$ai_error_type',
+ AiErrorNormalized: '$ai_error_normalized',
+ AiInput: '$ai_input',
+ AiOutput: '$ai_output',
+ AiOutputChoices: '$ai_output_choices',
+ AiInputState: '$ai_input_state',
+ AiOutputState: '$ai_output_state',
+ AiTools: '$ai_tools',
+ } as const;
+
export type AIEventType = typeof AIEventType[keyof typeof AIEventType];
@@ -84537,8 +84641,59 @@ export namespace Schemas {
* Request body for upserting a rule (create or update).
*/
export interface PropertyAccessControlUpdate {
- /** The property definition ID this rule applies to. */
- property_definition_id: string;
+ /** The existing property definition ID. Provide this or ai_property. */
+ property_definition_id?: string;
+ /** A built-in AI event property. Creates its definition if missing. Provide this or property_definition_id.
+ *
+ * * `$ai_trace_id` - $ai_trace_id
+ * * `$ai_session_id` - $ai_session_id
+ * * `$ai_parent_id` - $ai_parent_id
+ * * `$ai_span_id` - $ai_span_id
+ * * `$ai_span_type` - $ai_span_type
+ * * `$ai_generation_id` - $ai_generation_id
+ * * `$ai_experiment_id` - $ai_experiment_id
+ * * `$ai_span_name` - $ai_span_name
+ * * `$ai_trace_name` - $ai_trace_name
+ * * `$ai_prompt_name` - $ai_prompt_name
+ * * `$ai_model` - $ai_model
+ * * `$ai_provider` - $ai_provider
+ * * `$ai_framework` - $ai_framework
+ * * `$ai_total_tokens` - $ai_total_tokens
+ * * `$ai_input_tokens` - $ai_input_tokens
+ * * `$ai_output_tokens` - $ai_output_tokens
+ * * `$ai_text_input_tokens` - $ai_text_input_tokens
+ * * `$ai_text_output_tokens` - $ai_text_output_tokens
+ * * `$ai_image_input_tokens` - $ai_image_input_tokens
+ * * `$ai_image_output_tokens` - $ai_image_output_tokens
+ * * `$ai_audio_input_tokens` - $ai_audio_input_tokens
+ * * `$ai_audio_output_tokens` - $ai_audio_output_tokens
+ * * `$ai_video_input_tokens` - $ai_video_input_tokens
+ * * `$ai_video_output_tokens` - $ai_video_output_tokens
+ * * `$ai_reasoning_tokens` - $ai_reasoning_tokens
+ * * `$ai_cache_read_input_tokens` - $ai_cache_read_input_tokens
+ * * `$ai_cache_creation_input_tokens` - $ai_cache_creation_input_tokens
+ * * `$ai_web_search_count` - $ai_web_search_count
+ * * `$ai_input_cost_usd` - $ai_input_cost_usd
+ * * `$ai_output_cost_usd` - $ai_output_cost_usd
+ * * `$ai_total_cost_usd` - $ai_total_cost_usd
+ * * `$ai_request_cost_usd` - $ai_request_cost_usd
+ * * `$ai_web_search_cost_usd` - $ai_web_search_cost_usd
+ * * `$ai_audio_cost_usd` - $ai_audio_cost_usd
+ * * `$ai_image_cost_usd` - $ai_image_cost_usd
+ * * `$ai_video_cost_usd` - $ai_video_cost_usd
+ * * `$ai_latency` - $ai_latency
+ * * `$ai_time_to_first_token` - $ai_time_to_first_token
+ * * `$ai_is_error` - $ai_is_error
+ * * `$ai_error` - $ai_error
+ * * `$ai_error_type` - $ai_error_type
+ * * `$ai_error_normalized` - $ai_error_normalized
+ * * `$ai_input` - $ai_input
+ * * `$ai_output` - $ai_output
+ * * `$ai_output_choices` - $ai_output_choices
+ * * `$ai_input_state` - $ai_input_state
+ * * `$ai_output_state` - $ai_output_state
+ * * `$ai_tools` - $ai_tools */
+ ai_property?: AIEventPropertyEnum;
/** The access level to set for this rule.
*
* * `read_write` - read_write
diff --git a/tach.toml b/tach.toml
index bd17803d2311..71545ff8c5f8 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1380,6 +1380,7 @@ path = "products.access_control"
depends_on = [
"posthog",
"ee",
+ "products.event_definitions",
]
layer = "modules"