: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(activity-log): retain intent from desktop oauth edits (#101677)
Paul D'Ambra9f55d65eecce
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex afbd37d493e4..291ea8894195 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -123,13 +123,19 @@ A receiver can also read one from `get_current_trigger()` when the job wrapped i### Agent writes-`OAuthAccessTokenAuthentication` records two things for an agent running in a sandbox: the task the token is bound to, and the agent's stated reason from the `x-posthog-intent` header.-When a row would otherwise have no trigger, `log_activity` fills it with `Trigger(job_type="agent", job_id=<task id>, payload={"intent": ...})`.+`OAuthAccessTokenAuthentication` records the agent's stated reason from the `x-posthog-intent` header for applications in the Desktop OAuth allowlist.+Other OAuth applications need a server-set sandbox task binding before they can record agent attribution.+The authentication also records the task id when the server has bound the token to a sandbox task.+Desktop uses the signed-in user's OAuth token, so an allowlisted token does not require a sandbox task binding.+When a row would otherwise have no trigger, `log_activity` fills it with `Trigger(job_type="agent", job_id=<task id or empty string>, payload={"intent": ...})`.A product that passes its own trigger keeps it, so this only fills the gap.-The task id is what makes the row an agent write, and it is not self-reported: the sandbox provisioning binds it to the token it mints.-The intent is the agent's own claim and nothing verifies it, so it is read only from a request whose token carries that binding, and every surface that shows it says where it came from.-Without that rule, any caller could put the header on a write of its own and have the audit trail present the write as automation.+The intent is the caller's own claim and nothing verifies it.+Both activity views display intent without a task link and identify it as self-reported in the tooltip.+A task link appears only when the token has a server-set task binding.+The `X-PostHog-Task-Id` header cannot supply that binding, and the authenticated user remains the actor on the audit row.+Session authentication and personal API keys do not use this OAuth attribution path.+This applies to new activity rows; it does not recover intent that was discarded before the change.A model with a fail-closed manager (`TeamScopedRootMixin`, `ProductTeamModel`) raises `TeamScopeError` on any query without team context.The mixin's before-update read is by primary key without a team filter (`unscoped()`), so a `save()` outside a request works.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2921f329f377..4437ab308715 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -116,6 +116,10 @@ snapshots:hash: v1.k794b7964.0d80c815b27006d88f038af4b2d689f510f8bdf583d7fc830eb68942821b56e4.vFLLhu562dwroQu8TA_dLSIrYC3SgtRpKdZTB8ufS84components-agentattribution--intent-and-task--light:hash: v1.k794b7964.24895d9480ddd6f87009e5b1b25baf6e886cac9cd9880903e339bff843033fd8.KzV5k8F-3EZNmgX3eF2rV0oiWATstdKagopl-HYlEfQ+ components-agentattribution--intent-only--dark:+ hash: v1.k794b7964.f8bf9ca0845659ac7663e8b7e345a8d093a752c1f562497bdad3d1f87f77366c.uPzI-KBozuElBjF8Hdlict0N4JMDU55i5YgPHtms8BU+ components-agentattribution--intent-only--light:+ hash: v1.k794b7964.ff34426525e6649ce8bce821f536aea21b43bd8878cefb5448209e6fd107c6a1.6Wo_irGPe6Xr4WKCYXA0XYpna9TiT0NuTNfewqR0uv0components-agentattribution--task-only--dark:hash: v1.k794b7964.5b5f3178c99673ba0bf03dddb8a88cf889e51cf1d89039743d51c3bb056172cc.nuzeiVXJiHurkyu1JOKm6DOspFpAqjrJKgmUZzfj0d0components-agentattribution--task-only--light:diff --git a/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx b/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsxindex 6295695ccd13..39ef34db8fdd 100644--- a/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx+++ b/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx@@ -47,3 +47,15 @@ export const TaskOnly: Story = {logItem: logItem({ trigger: { job_type: 'agent', job_id: AGENT_TASK_ID, payload: {} } }),},}++export const IntentOnly: Story = {+ args: {+ logItem: logItem({+ trigger: {+ job_type: 'agent',+ job_id: '',+ payload: { intent: 'Renaming the dashboard for the weekly review' },+ },+ }),+ },+}diff --git a/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsxindex ce79624db14a..4f7542e9d3c3 100644--- a/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx+++ b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx@@ -24,12 +24,14 @@ export function AgentAttribution({ logItem }: { logItem: HumanizedActivityLogIte<span className="text-default">{attribution.intent}</span></div>)}- <div>- Agent task{' '}- <Link to={urls.codeTaskLink(attribution.taskId)} target="_blank" targetBlankIcon>- {attribution.taskId.slice(0, 8)}- </Link>- </div>+ {attribution.taskId && (+ <div>+ Agent task{' '}+ <Link to={urls.codeTaskLink(attribution.taskId)} target="_blank" targetBlankIcon>+ {attribution.taskId.slice(0, 8)}+ </Link>+ </div>+ )}</div>)}diff --git a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.tsindex 19be6da81732..537b7d786b6d 100644--- a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts+++ b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts@@ -31,9 +31,9 @@ describe('parseAgentAttribution', () => {{ intent: 'Repairing a broken tile', taskId: AGENT_TASK_ID },],[- 'an agent trigger with no task id, which the server cannot write and readers must not trust',+ 'an agent trigger with intent but no verified task id',{ job_type: 'agent', job_id: '', payload: { intent: 'Disabling the flag per an incident runbook' } },- null,+ { intent: 'Disabling the flag per an incident runbook', taskId: null },],['an agent trigger whose intent is not a string',diff --git a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.tsindex 034e93f696f3..c9029dd015e0 100644--- a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts+++ b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts@@ -7,18 +7,21 @@ const AGENT_TRIGGER_JOB_TYPE = 'agent'export interface AgentAttribution {/** Self-reported by the agent, never verified. */intent: string | null- /** Bound to the agent's token by the server, so a row without it is not an agent write. */- taskId: string+ /** Bound to the agent's token by the server. Intent alone cannot verify a task. */+ taskId: string | null}export function parseAgentAttribution(logItem: HumanizedActivityLogItem): AgentAttribution | null {const trigger = logItem.unprocessed?.detail?.trigger- if (trigger?.job_type !== AGENT_TRIGGER_JOB_TYPE || !trigger.job_id) {+ if (trigger?.job_type !== AGENT_TRIGGER_JOB_TYPE) {return null}- return {- intent: typeof trigger.payload?.intent === 'string' ? trigger.payload.intent : null,- taskId: trigger.job_id,+ const intent = typeof trigger.payload?.intent === 'string' ? trigger.payload.intent : null+ const taskId = trigger.job_id || null+ if (!intent && !taskId) {+ return null}++ return { intent, taskId }}diff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsxindex 5f5ed6f23280..8fb52eff3949 100644--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx@@ -210,7 +210,7 @@ function ExpandedRowContent({ logItem }: { logItem: HumanizedActivityLogItem }):<div className="text-[13px] text-default">{agent.intent}</div></div>)}- {agent && (+ {agent?.taskId && (<div><div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">Agent taskdiff --git a/posthog/auth.py b/posthog/auth.pyindex cc6dbe59f72f..fe98ac963a42 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -59,6 +59,7 @@ from posthog.models.utils import (hash_key_value,)from posthog.models.webauthn_credential import WebauthnCredential+from posthog.oauth_provenance import is_interactive_desktop_grantfrom posthog.passkey import verify_passkey_authentication_responsefrom posthog.scoped_service_jwt import ScopedServiceJwtPurposefrom posthog.shared_link_user import SharedLinkUser@@ -900,15 +901,16 @@ class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):def _record_agent_attribution(request: Union[HttpRequest, Request], access_token: OAuthAccessToken) -> None:- """Record the sandbox task bound to the token, and the intent the agent claims.+ """Record a trusted task binding, or intent from a Desktop OAuth application.- Any caller can send the intent header, so it is read only behind the token binding.+ Intent is self-reported. Only the token binding can supply a verified task id.Attribution is extra detail on an audit row, so an error here must not fail the request."""try:- if access_token.sandbox_task_id is None:+ if access_token.sandbox_task_id is None and not is_interactive_desktop_grant(request, access_token):return- activity_storage.set_agent_task_id(str(access_token.sandbox_task_id))+ if access_token.sandbox_task_id is not None:+ activity_storage.set_agent_task_id(str(access_token.sandbox_task_id))intent = request.headers.get(ACTIVITY_LOG_INTENT_HEADER, "").strip()[:ACTIVITY_LOG_INTENT_MAX_LENGTH]if intent:activity_storage.set_agent_intent(intent)diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 5bd4c7dad616..e6cd00c92775 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -1188,17 +1188,17 @@ AGENT_TRIGGER_JOB_TYPE = "agent"def agent_trigger() -> Optional[Trigger]:- """The agent attribution for this request, or None when no token-bound task reached it.+ """The agent attribution for this request, or None when neither field reached it.- The task id is required because it is the only server-set part. The intent is the agent's claim.+ The task id is the only server-set part. The intent is the agent's claim."""task_id = activity_storage.get_agent_task_id()- if not task_id:- return Noneintent = activity_storage.get_agent_intent()+ if not task_id and not intent:+ return Nonereturn Trigger(job_type=AGENT_TRIGGER_JOB_TYPE,- job_id=task_id,+ job_id=task_id or "",payload={"intent": intent} if intent else {},)diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.pyindex c1456f10798a..549460bfe84a 100644--- a/posthog/models/activity_logging/utils.py+++ b/posthog/models/activity_logging/utils.py@@ -17,7 +17,7 @@ logger = structlog.get_logger(__name__)ACTIVITY_LOG_CLIENT_HEADER = "x-posthog-client"ACTIVITY_LOG_CLIENT_MAX_LENGTH = 32# The MCP server forwards the same intent it sends to analytics as `$mcp_intent`. It is the-# caller's own claim, so it is read only from a request whose token is bound to a sandbox task.+# caller's own claim and does not establish a verified sandbox task binding.ACTIVITY_LOG_INTENT_HEADER = "x-posthog-intent"ACTIVITY_LOG_INTENT_MAX_LENGTH = 500diff --git a/posthog/oauth_provenance.py b/posthog/oauth_provenance.pyindex a0bfca678fa5..2e0f979ea899 100644--- a/posthog/oauth_provenance.py+++ b/posthog/oauth_provenance.py@@ -61,7 +61,7 @@ def is_first_party_oauth_client(request) -> bool:return get_oauth_client_id(request) in POSTHOG_DESKTOP_OAUTH_CLIENT_IDS-def is_interactive_desktop_grant(request) -> bool:+def is_interactive_desktop_grant(request, access_token: object | None = None) -> bool:"""Whether this request carries a PostHog Desktop token a person consented to.The Electron app, the cloud coding agent, and the Slack app all authenticate against the@@ -69,7 +69,8 @@ def is_interactive_desktop_grant(request) -> bool:the server-minted `internal_run:read` marker, and refresh-token lineage proving a consentflow happened. Sandbox tokens fail the second check before the third does any query."""- access_token = get_oauth_access_token(request)+ if access_token is None:+ access_token = get_oauth_access_token(request)if access_token is None or not is_first_party_oauth_client(request):return Falsescopes = set((getattr(access_token, "scope", "") or "").split())diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 4a236eba0c2d..bbda8bef5cd6 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -15,7 +15,7 @@ from posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activityfrom posthog.models.activity_logging.model_activity import ActivityTriggerContextfrom posthog.models.activity_logging.utils import activity_storage, activity_visibility_manager-from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom posthog.models.scoping import team_scopefrom posthog.models.utils import UUIDTfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV@@ -173,7 +173,7 @@ class TestActivityLogModel(BaseTest):assert log.detail is not Noneself.assertEqual(log.detail["trigger"]["job_type"], "hog_flow")- def test_an_intent_without_a_task_binding_writes_no_trigger(self) -> None:+ def test_an_intent_without_a_task_binding_writes_no_task_id(self) -> None:activity_storage.set_agent_intent("Disabling the flag per an incident runbook")try:log_activity(@@ -191,7 +191,14 @@ class TestActivityLogModel(BaseTest):log: ActivityLog = ActivityLog.objects.latest("id")assert log.detail is not None- self.assertIsNone(log.detail["trigger"])+ self.assertEqual(+ log.detail["trigger"],+ {+ "job_type": "agent",+ "job_id": "",+ "payload": {"intent": "Disabling the flag per an incident runbook"},+ },+ )def test_a_failing_agent_trigger_still_writes_the_row(self) -> None:with patch(@@ -553,10 +560,12 @@ class TestActivityTriggerContext(BaseTest):class TestAgentAttributionOnApiWrites(APIBaseTest):"""The intent header, the OAuth token binding and the audit row only meet on a real request."""- def _authenticate_as_sandbox_agent(self, task_id: UUID | None, delegated: bool = False) -> None:+ def _authenticate_as_oauth_agent(+ self, client_id: str, task_id: UUID | None, delegated: bool = False+ ) -> OAuthAccessToken:application = OAuthApplication.objects.create(- name="Sandbox",- client_id=ARRAY_APP_CLIENT_ID_DEV,+ name="OAuth application",+ client_id=client_id,client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://example.com/callback",@@ -582,13 +591,16 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):PosthogJwtAudience.DELEGATED_USER,)self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token_value}")+ return token@parameterized.expand([(- "records the intent of a token bound to a sandbox task",+ "records an allowlisted token bound to a sandbox task",+ ARRAY_APP_CLIENT_ID_DEV,UUID("019f4c2a-0000-7000-8000-0000000000aa"),False,+ "Repairing a tile that hit the query row limit",{"job_type": "agent","job_id": "019f4c2a-0000-7000-8000-0000000000aa",@@ -596,37 +608,118 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):},),(- "records the intent of a delegated token bound to a sandbox task",+ "records a third-party delegated token bound to a sandbox task",+ "third-party-client",UUID("019f4c2a-0000-7000-8000-0000000000aa"),True,+ "Repairing a tile that hit the query row limit",{"job_type": "agent","job_id": "019f4c2a-0000-7000-8000-0000000000aa","payload": {"intent": "Repairing a tile that hit the query row limit"},},),- ("ignores the header on a token with no task", None, False, None),+ (+ "ignores unbound Array intent without consent lineage",+ ARRAY_APP_CLIENT_ID_DEV,+ None,+ False,+ "Repairing a tile that hit the query row limit",+ None,+ ),+ (+ "ignores unbound delegated Array intent without consent lineage",+ ARRAY_APP_CLIENT_ID_DEV,+ None,+ True,+ "Repairing a tile that hit the query row limit",+ None,+ ),+ (+ "ignores third-party intent without a task binding",+ "third-party-client",+ None,+ False,+ "Repairing a tile that hit the query row limit",+ None,+ ),+ (+ "ignores third-party delegated intent without a task binding",+ "third-party-client",+ None,+ True,+ "Repairing a tile that hit the query row limit",+ None,+ ),+ ("ignores an empty allowlisted intent", ARRAY_APP_CLIENT_ID_DEV, None, False, None, None),+ (+ "records an allowlisted task binding without intent",+ ARRAY_APP_CLIENT_ID_DEV,+ UUID("019f4c2a-0000-7000-8000-0000000000aa"),+ False,+ None,+ {+ "job_type": "agent",+ "job_id": "019f4c2a-0000-7000-8000-0000000000aa",+ "payload": {},+ },+ ),])def test_agent_write(- self, _name: str, task_id: UUID | None, delegated: bool, expected_trigger: dict | None+ self,+ _name: str,+ client_id: str,+ task_id: UUID | None,+ delegated: bool,+ intent: str | None,+ expected_trigger: dict | None,) -> None:- self._authenticate_as_sandbox_agent(task_id, delegated)+ self._authenticate_as_oauth_agent(client_id, task_id, delegated)response = self.client.post(f"/api/projects/{self.team.id}/dashboards/",{"name": "Weekly signups"},- HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",+ HTTP_X_POSTHOG_CLIENT="mcp",+ HTTP_X_POSTHOG_TASK_ID="019f4c2a-0000-7000-8000-0000000000bb",+ HTTP_X_POSTHOG_INTENT=intent or "",)self.assertEqual(response.status_code, 201, response.content)log = ActivityLog.objects.filter(scope="Dashboard").latest("id")assert log.detail is not Noneself.assertEqual(log.detail["trigger"], expected_trigger)+ self.assertEqual(log.user_id, self.user.id)+ self.assertEqual(log.client, "mcp")++ def test_records_intent_from_an_interactive_desktop_grant(self) -> None:+ token = self._authenticate_as_oauth_agent(ARRAY_APP_CLIENT_ID_DEV, None)+ OAuthRefreshToken.objects.create(+ user=self.user,+ application=token.application,+ token="refresh-token",+ access_token=token,+ scoped_teams=[self.team.id],+ scoped_organizations=[],+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/",+ {"name": "Weekly signups"},+ HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",+ )++ self.assertEqual(response.status_code, 201, response.content)+ log = ActivityLog.objects.filter(scope="Dashboard").latest("id")+ assert log.detail is not None+ self.assertEqual(+ log.detail["trigger"],+ {"job_type": "agent", "job_id": "", "payload": {"intent": "Repairing a tile that hit the query row limit"}},+ )def test_a_failing_attribution_loses_the_intent_and_nothing_else(self) -> None:task_id = UUID("019f4c2a-0000-7000-8000-0000000000aa")- self._authenticate_as_sandbox_agent(task_id)+ self._authenticate_as_oauth_agent(ARRAY_APP_CLIENT_ID_DEV, task_id)with patch("posthog.auth.activity_storage.set_agent_intent", side_effect=RuntimeError("storage is broken")):response = self.client.post(