Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(activity-log): keep agent intent on any authenticated write (#103869)

posthog[bot]69b1969116ef
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index 98ebb5375cc4..eccc191ad111 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -150,18 +150,16 @@ A receiver can also read one from `get_current_trigger()` when the job wrapped i
### Agent writes
-`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.
+`record_agent_intent` stores the agent's stated reason from the `x-posthog-intent` header for any authenticated request.
+A session, a personal API key and an OAuth token all reach it: the middleware calls it for a session, and the authentication class calls it for a bearer credential.
+`OAuthAccessTokenAuthentication` also records the task id when the server has bound the token to a sandbox task.
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 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.
+A task link appears only when the token has a server-set task binding, so intent never implies a verified run.
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.
diff --git a/posthog/auth.py b/posthog/auth.py
index c72763df5db6..ecb195e4061c 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -36,11 +36,7 @@ from posthog.helpers.verified_domain_enforcement import enforce_verified_domain
from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_match
from posthog.internal_api_secret import usable_internal_api_secrets
from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keys
-from posthog.models.activity_logging.utils import (
- ACTIVITY_LOG_INTENT_HEADER,
- ACTIVITY_LOG_INTENT_MAX_LENGTH,
- activity_storage,
-)
+from posthog.models.activity_logging.utils import activity_storage, record_agent_intent
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrand
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import (
@@ -60,7 +56,6 @@ from posthog.models.utils import (
hash_key_value,
)
from posthog.models.webauthn_credential import WebauthnCredential
-from posthog.oauth_provenance import is_interactive_desktop_grant
from posthog.passkey import verify_passkey_authentication_response
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from posthog.shared_link_user import SharedLinkUser
@@ -346,6 +341,7 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
# request cycle (e.g. authenticate() called directly) the thread-local would leak.
if activity_storage.is_request_scoped():
activity_storage.set_user(personal_api_key_object.user)
+ record_agent_intent(request)
self.personal_api_key = personal_api_key_object
self.personal_api_key_source = source
@@ -903,21 +899,18 @@ class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):
def _record_agent_attribution(request: Union[HttpRequest, Request], access_token: OAuthAccessToken) -> None:
- """Record a trusted task binding, or intent from a Desktop OAuth application.
+ """Record the intent the caller states, and a task binding when the token carries one.
- 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.
+ Only the token binding can supply a verified task id, so a token without one records the
+ intent alone. 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 and not is_interactive_desktop_grant(request, access_token):
- return
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)
except Exception as e:
capture_exception(e)
+ record_agent_intent(request)
class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
@@ -1117,6 +1110,7 @@ class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):
)
if activity_storage.is_request_scoped():
activity_storage.set_user(personal_api_key.user)
+ record_agent_intent(request)
return personal_api_key.user, None
diff --git a/posthog/middleware.py b/posthog/middleware.py
index eb1fbef5f563..0dcff6f5ece5 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -50,7 +50,12 @@ from posthog.helpers.sso import sso_failure_redirect_url
from posthog.helpers.user_devices import set_known_device_cookie
from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_match
from posthog.models import Organization, Team, User
-from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_HEADER, activity_storage, client_from_header
+from posthog.models.activity_logging.utils import (
+ ACTIVITY_LOG_CLIENT_HEADER,
+ activity_storage,
+ client_from_header,
+ record_agent_intent,
+)
from posthog.models.utils import generate_random_token
from posthog.ph_client import PH_US_API_KEY, PH_US_HOST
from posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URL
@@ -1254,6 +1259,7 @@ class ActivityLoggingMiddleware:
if request.user.is_authenticated:
activity_storage.set_user(request.user)
activity_storage.set_was_impersonated(is_impersonated_session(request))
+ record_agent_intent(request)
client_header = request.headers.get(ACTIVITY_LOG_CLIENT_HEADER)
if client_header:
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index e3cfc9890291..f9418cb5548f 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -48,6 +48,23 @@ def client_from_header(value: str) -> Optional[str]:
return client
+def record_agent_intent(request: Any) -> None:
+ """Store the reason an authenticated caller states for the writes it is about to make.
+
+ The intent is the caller's own claim, so it never supplies a task id: only a token binding
+ the server wrote can do that. Attribution is extra detail on an audit row, so a failure here
+ must not fail the request.
+ """
+ try:
+ if not activity_storage.is_request_scoped():
+ return
+ intent = request.headers.get(ACTIVITY_LOG_INTENT_HEADER, "").strip()[:ACTIVITY_LOG_INTENT_MAX_LENGTH]
+ if intent:
+ activity_storage.set_agent_intent(intent)
+ except Exception:
+ logger.warning("activity_log.agent_intent_failed", exc_info=True)
+
+
@frozen
class CreatedByInfo:
user_id: str | None
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index 1604b9b95772..a72e5ab33176 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -15,10 +15,15 @@ from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity
from posthog.models.activity_logging.model_activity import ActivityTriggerContext
-from posthog.models.activity_logging.utils import activity_storage, activity_visibility_manager
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.activity_logging.utils import (
+ ACTIVITY_LOG_INTENT_MAX_LENGTH,
+ activity_storage,
+ activity_visibility_manager,
+)
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.scoping import team_scope
-from posthog.models.utils import UUIDT
+from posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_value
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
@@ -621,36 +626,52 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):
},
),
(
- "ignores unbound Array intent without consent lineage",
+ "records unbound Array intent with no task id",
ARRAY_APP_CLIENT_ID_DEV,
None,
False,
"Repairing a tile that hit the query row limit",
- None,
+ {
+ "job_type": "agent",
+ "job_id": "",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
),
(
- "ignores unbound delegated Array intent without consent lineage",
+ "records unbound delegated Array intent with no task id",
ARRAY_APP_CLIENT_ID_DEV,
None,
True,
"Repairing a tile that hit the query row limit",
- None,
+ {
+ "job_type": "agent",
+ "job_id": "",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
),
(
- "ignores third-party intent without a task binding",
+ "records third-party intent with no task id",
"third-party-client",
None,
False,
"Repairing a tile that hit the query row limit",
- None,
+ {
+ "job_type": "agent",
+ "job_id": "",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
),
(
- "ignores third-party delegated intent without a task binding",
+ "records third-party delegated intent with no task id",
"third-party-client",
None,
True,
"Repairing a tile that hit the query row limit",
- None,
+ {
+ "job_type": "agent",
+ "job_id": "",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
),
("ignores an empty allowlisted intent", ARRAY_APP_CLIENT_ID_DEV, None, False, None, None),
(
@@ -693,16 +714,8 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):
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=[],
- )
+ def test_recording_intent_does_not_re_enter_authentication(self) -> None:
+ self._authenticate_as_oauth_agent(ARRAY_APP_CLIENT_ID_DEV, None)
with (
patch.object(
@@ -729,6 +742,65 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):
{"job_type": "agent", "job_id": "", "payload": {"intent": "Repairing a tile that hit the query row limit"}},
)
+ def _authenticate_with_a_personal_api_key(self) -> None:
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="MCP",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["dashboard:read", "dashboard:write"],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")
+
+ def test_records_intent_from_a_personal_api_key(self) -> None:
+ self._authenticate_with_a_personal_api_key()
+
+ 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_TASK_ID="019f4c2a-0000-7000-8000-0000000000bb",
+ )
+
+ 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"}},
+ )
+ self.assertEqual(log.user_id, self.user.id)
+
+ def test_records_intent_from_a_session(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/",
+ {"name": "Weekly signups"},
+ HTTP_X_POSTHOG_INTENT="Disabling the flag per an incident runbook",
+ )
+
+ 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": "Disabling the flag per an incident runbook"}},
+ )
+
+ def test_an_intent_longer_than_the_cap_is_cut_to_it(self) -> None:
+ self._authenticate_with_a_personal_api_key()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/",
+ {"name": "Weekly signups"},
+ HTTP_X_POSTHOG_INTENT="w" * (ACTIVITY_LOG_INTENT_MAX_LENGTH + 20),
+ )
+
+ 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"]["payload"]["intent"], "w" * ACTIVITY_LOG_INTENT_MAX_LENGTH)
+
def test_a_failing_attribution_loses_the_intent_and_nothing_else(self) -> None:
task_id = UUID("019f4c2a-0000-7000-8000-0000000000aa")
self._authenticate_as_oauth_agent(ARRAY_APP_CLIENT_ID_DEV, task_id)