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(tasks): attribute run artifact uploads to their uploader (#79721)

Shy Altera8083de434dc
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2e5bdb2433b0..7aa2732c2296 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2830,10 +2830,18 @@ def prepare_task_run_artifact_uploads(
def finalize_task_run_artifact_uploads(
- run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifacts: list[dict]
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ artifacts: list[dict],
+ uploaded_by: Literal["agent", "user"],
+ uploaded_by_user_id: int | None,
) -> tuple[list[dict] | None, str | None]:
"""Verify directly-uploaded S3 objects and attach them to the run manifest.
+ ``uploaded_by`` is server-derived and authoritative. ``source`` remains a client-declared organizational hint.
+
Returns ``(finalized_entries, error)``: ``(None, None)`` when the run isn't found,
``(None, error_message)`` on a validation failure, else ``(finalized_entries, None)``.
"""
@@ -2894,6 +2902,9 @@ def finalize_task_run_artifact_uploads(
uploaded_at=django_timezone.now().isoformat(),
metadata=artifact.get("metadata"),
)
+ entry["uploaded_by"] = uploaded_by
+ if uploaded_by == "user" and uploaded_by_user_id is not None:
+ entry["uploaded_by_user_id"] = uploaded_by_user_id
manifest.append(entry)
new_entries.append(entry)
finalized_entries.append(entry)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index d25635e78848..9c5e5b1ced31 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -280,6 +280,15 @@ class TaskRunArtifactResponseSerializer(serializers.Serializer):
)
storage_path = serializers.CharField(help_text="S3 object key for the artifact")
uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded")
+ uploaded_by = serializers.ChoiceField(
+ choices=["agent", "user"],
+ required=False,
+ help_text="Whether the artifact version was uploaded by the task agent or an interactive user.",
+ )
+ uploaded_by_user_id = serializers.IntegerField(
+ required=False,
+ help_text="User id for an interactive user upload. Absent for agent uploads and legacy entries.",
+ )
dismissed_at = serializers.CharField(
required=False,
help_text="Timestamp when a user dismissed the artifact. Absent while the artifact is shown.",
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index fe6ebecea04a..29b24ef0375c 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -45,7 +45,7 @@ from posthog.permissions import (
from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.schema_migrations.upgrade import upgrade
-from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS
+from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS, SANDBOX_OAUTH_APP_CLIENT_IDS
from posthog.utils import absolute_uri
from products.exports.backend.facade.api import render_png_export
@@ -1055,6 +1055,18 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def _user_id(self) -> int | None:
return getattr(self.request.user, "id", None)
+ def _is_sandbox_agent_request(self, task_id: str) -> bool:
+ authenticator = self.request.successful_authenticator
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return False
+ access_token = authenticator.access_token
+ application = access_token.application
+ if application is None or application.client_id not in SANDBOX_OAUTH_APP_CLIENT_IDS:
+ return False
+ return access_token.sandbox_task_id == UUID(task_id) or "internal_run:read" in (
+ get_authenticator_scopes(authenticator) or []
+ )
+
# Actions that only read run state. Everything else mutates or drives the
# run, so it requires task control (not just visibility): public-channel
# visibility lets teammates watch a run, never command it. connection_token
@@ -1621,8 +1633,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def artifacts_finalize_upload(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
+ is_agent_upload = self._is_sandbox_agent_request(task_id)
finalized_entries, error = tasks_facade.finalize_task_run_artifact_uploads(
- pk, task_id, self.team_id, artifacts=request.validated_data["artifacts"]
+ pk,
+ task_id,
+ self.team_id,
+ artifacts=request.validated_data["artifacts"],
+ uploaded_by="agent" if is_agent_upload else "user",
+ uploaded_by_user_id=None if is_agent_upload else self._user_id(),
)
if finalized_entries is None and error is None:
raise NotFound()
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index e77f69ce9a25..0f8954055114 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -31,7 +31,7 @@ from posthog.models.user_integration import UserIntegration
from posthog.models.utils import generate_random_token_personal
from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
from posthog.storage import object_storage
-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
from posthog.utils import absolute_uri
from products.slack_app.backend.models import SlackThreadTaskMapping
@@ -4705,6 +4705,37 @@ _OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"
class TestTaskRunAPI(BaseTaskAPITest):
+ def _sandbox_oauth_client(
+ self,
+ task_id: uuid.UUID,
+ *,
+ client_id: str = ARRAY_APP_CLIENT_ID_DEV,
+ bound: bool = True,
+ internal_scope: bool = False,
+ ) -> APIClient:
+ application = OAuthApplication.objects.create(
+ name="Task artifact uploader",
+ client_id=client_id,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ algorithm="RS256",
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ user=self.user,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token=f"pha_task_agent_{uuid.uuid4().hex}",
+ expires=django_timezone.now() + timedelta(hours=1),
+ scope=f"task:read task:write{' internal_run:read' if internal_scope else ''}",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task_id if bound else None,
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
+ return client
+
def _create_run_for_origin(self, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:
task = Task.objects.create(
team=self.team,
@@ -6607,6 +6638,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
"source": "user_attachment",
"storage_path": storage_path,
"content_type": "application/pdf",
+ "uploaded_by": "agent",
+ "uploaded_by_user_id": 999999,
}
]
},
@@ -6635,6 +6668,94 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(artifact["size"], 4096)
self.assertEqual(artifact["content_type"], "application/pdf")
self.assertEqual(artifact["storage_path"], storage_path)
+ self.assertEqual(artifact["uploaded_by"], "user")
+ self.assertEqual(artifact["uploaded_by_user_id"], self.user.id)
+
+ @parameterized.expand(
+ [
+ ("bound_code_sandbox", ARRAY_APP_CLIENT_ID_DEV, True, False, "agent"),
+ ("legacy_code_sandbox", ARRAY_APP_CLIENT_ID_DEV, False, True, "agent"),
+ ("posthog_ai_sandbox", POSTHOG_AI_APP_CLIENT_ID_DEV, True, False, "agent"),
+ ("interactive_code_oauth", ARRAY_APP_CLIENT_ID_DEV, False, False, "user"),
+ ("third_party_oauth", "artifact-client", False, False, "user"),
+ ]
+ )
+ @patch("posthog.storage.object_storage.head_object")
+ @patch("posthog.storage.object_storage.tag")
+ def test_finalize_artifact_uploads_attributes_oauth_from_server_provenance(
+ self,
+ _name: str,
+ client_id: str,
+ bound: bool,
+ internal_scope: bool,
+ expected_uploader: str,
+ mock_tag,
+ mock_head_object,
+ ) -> None:
+ mock_head_object.return_value = {"ContentLength": 4096, "ContentType": "text/markdown"}
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ artifact_id = uuid.uuid4().hex
+ storage_path = f"{run.get_artifact_s3_prefix()}/{artifact_id[:8]}_report.md"
+ client = self._sandbox_oauth_client(
+ task.id,
+ client_id=client_id,
+ bound=bound,
+ internal_scope=internal_scope,
+ )
+
+ response = client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/finalize_upload/",
+ {
+ "artifacts": [
+ {
+ "id": artifact_id,
+ "name": "report.md",
+ "type": "output",
+ "source": "agent_output",
+ "storage_path": storage_path,
+ "content_type": "text/markdown",
+ }
+ ]
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_head_object.assert_called_once_with(storage_path)
+ mock_tag.assert_called_once()
+ run.refresh_from_db()
+ artifact = run.artifacts[0]
+ self.assertEqual(artifact["uploaded_by"], expected_uploader)
+ if expected_uploader == "agent":
+ self.assertNotIn("uploaded_by_user_id", artifact)
+ else:
+ self.assertEqual(artifact["uploaded_by_user_id"], self.user.id)
+
+ def test_retrieve_run_accepts_legacy_artifacts_without_upload_attribution(self):
+ task = self.create_task()
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ artifacts=[
+ {
+ "id": "legacy-artifact",
+ "name": "report.md",
+ "type": "output",
+ "storage_path": "tasks/artifacts/legacy/report.md",
+ "uploaded_at": "2026-01-01T00:00:00+00:00",
+ }
+ ],
+ )
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ artifact = response.json()["artifacts"][0]
+ self.assertEqual(artifact["id"], "legacy-artifact")
+ self.assertNotIn("uploaded_by", artifact)
+ self.assertNotIn("uploaded_by_user_id", artifact)
@patch("posthog.storage.object_storage.head_object")
def test_finalize_artifact_uploads_rejects_invalid_storage_path(self, mock_head_object):
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 933edc52cbe7..e15c42c77194 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1415,6 +1415,17 @@ export interface TaskRunArtifactMetadataApi {
schema_version: number
}
+/**
+ * * `agent` - agent
+ * * `user` - user
+ */
+export type UploadedByEnumApi = (typeof UploadedByEnumApi)[keyof typeof UploadedByEnumApi]
+
+export const UploadedByEnumApi = {
+ Agent: 'agent',
+ User: 'user',
+} as const
+
export interface TaskRunArtifactResponseApi {
/** Stable identifier for the artifact within this run */
id?: string
@@ -1434,6 +1445,13 @@ export interface TaskRunArtifactResponseApi {
storage_path: string
/** Timestamp when the artifact was uploaded */
uploaded_at: string
+ /** Whether the artifact version was uploaded by the task agent or an interactive user.
+ *
+ * * `agent` - agent
+ * * `user` - user */
+ uploaded_by?: UploadedByEnumApi
+ /** User id for an interactive user upload. Absent for agent uploads and legacy entries. */
+ uploaded_by_user_id?: number
/** Timestamp when a user dismissed the artifact. Absent while the artifact is shown. */
dismissed_at?: string
/** Stable download URL for the artifact. Populated on the finalize-upload response so the caller can link to the file; it redirects to a fresh presigned URL on each request and is not persisted on the manifest. */
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index b780edb46a93..25102ecf9363 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -456,6 +456,9 @@ tools:
tasks-runs-artifacts-finalize-upload-create:
operation: tasks_runs_artifacts_finalize_upload_create
enabled: false
+ description: >
+ Finalize a task run artifact uploaded through a prepared form. Before revising a file under the same name,
+ read its latest version because an interactive user may have edited it since the agent's last upload.
tasks-runs-artifacts-prepare-upload-create:
operation: tasks_runs_artifacts_prepare_upload_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c280f83decd5..3cf527c1ad99 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50105,6 +50105,18 @@ export namespace Schemas {
schema_version: number;
}
+ /**
+ * * `agent` - agent
+ * * `user` - user
+ */
+ export type UploadedByEnum = typeof UploadedByEnum[keyof typeof UploadedByEnum];
+
+
+ export const UploadedByEnum = {
+ Agent: 'agent',
+ User: 'user',
+ } as const;
+
export interface TaskRunArtifactResponse {
/** Stable identifier for the artifact within this run */
id?: string;
@@ -50124,6 +50136,13 @@ export namespace Schemas {
storage_path: string;
/** Timestamp when the artifact was uploaded */
uploaded_at: string;
+ /** Whether the artifact version was uploaded by the task agent or an interactive user.
+ *
+ * * `agent` - agent
+ * * `user` - user */
+ uploaded_by?: UploadedByEnum;
+ /** User id for an interactive user upload. Absent for agent uploads and legacy entries. */
+ uploaded_by_user_id?: number;
/** Timestamp when a user dismissed the artifact. Absent while the artifact is shown. */
dismissed_at?: string;
/** Stable download URL for the artifact. Populated on the finalize-upload response so the caller can link to the file; it redirects to a fresh presigned URL on each request and is not persisted on the manifest. */