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): emit commit, comment, and artifact events on the task timeline (#82160)

Shy Alterc0904127bf71
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index d3711b73d490..308fce532e1f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -94,6 +94,7 @@ from products.tasks.backend.models import (
SandboxSnapshot,
Task,
TaskActivity,
+ TaskArtifact,
TaskAutomation,
TaskClientProvenance,
TaskCommentActivity,
@@ -2435,6 +2436,7 @@ def update_task_run(
*,
validated_data: dict,
only_if_non_terminal: bool = False,
+ caller_is_agent: bool = False,
) -> contracts.TaskRunDetailDTO | None:
"""Apply a PATCH to a run: merge output/state, set completion, then dispatch side effects.
@@ -2479,6 +2481,7 @@ def update_task_run(
old_status = run.status
old_environment = run.environment
old_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else None
+ old_commit_head = _commit_push_head_sha(run.output)
for key, value in validated_data.items():
if key == "output" and isinstance(value, dict):
@@ -2571,6 +2574,10 @@ def update_task_run(
except Exception:
logger.warning("task_run.pr_progress_emit_failed", extra={"run_id": str(run.id)}, exc_info=True)
+ new_commit_head = _commit_push_head_sha(run.output)
+ if caller_is_agent and isinstance(run.output, dict) and new_commit_head and new_commit_head != old_commit_head:
+ post_commits_pushed_thread_update(run, run.output["commit_push"])
+
return _task_run_detail_to_dto(run)
@@ -2889,7 +2896,12 @@ def _save_artifact_manifest(run: TaskRun, manifest: list[dict]) -> None:
def upload_task_run_artifacts(
- 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"] | None = None,
) -> tuple[list[dict], list[dict]] | None:
"""Write artifact bytes to S3 and append them to the run manifest.
@@ -2953,6 +2965,9 @@ def upload_task_run_artifacts(
manifest.extend(uploaded)
_save_artifact_manifest(run, manifest)
+ if uploaded_by == "agent":
+ _announce_agent_artifact_uploads(run, uploaded, manifest)
+
# Same download URL the finalize-upload path returns, so a caller that reaches storage
# through this endpoint instead of a presigned POST still gets a link to surface. Built
# after the save so it stays off the persisted manifest.
@@ -3109,10 +3124,15 @@ def finalize_task_run_artifact_uploads(
merged = [entry for entry in (locked_run.artifacts or []) if entry.get("id") not in new_ids]
merged.extend(new_entries)
_save_artifact_manifest(locked_run, merged)
+ # Count versions from the locked merge, or a concurrent same-named finalize is missed.
+ manifest = merged
for storage_path in new_storage_paths:
_tag_artifact_object(run, storage_path)
+ if uploaded_by == "agent":
+ _announce_agent_artifact_uploads(run, new_entries, manifest)
+
# Attach a download URL per response entry so the caller (e.g. the upload_artifact
# tool) can surface a link to the file. The app URL redirects to a fresh presigned
# URL on each request, so unlike a raw presigned URL it stays short and works for
@@ -3166,6 +3186,7 @@ def create_task_run_living_artifact(
team_id: int,
*,
artifact: dict,
+ caller_is_agent: bool = False,
) -> tuple[dict | None, str | None]:
from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
create_living_artifact,
@@ -3180,7 +3201,10 @@ def create_task_run_living_artifact(
except Exception as exc:
logger.warning("Failed to create living artifact for task run %s: %s", run.id, exc)
return None, str(exc)
- return serialize_task_artifact(created), None
+ serialized = serialize_task_artifact(created)
+ if caller_is_agent:
+ post_artifact_thread_update(run, serialized, revised=False)
+ return serialized, None
def edit_task_run_living_artifact(
@@ -3188,6 +3212,7 @@ def edit_task_run_living_artifact(
task_id: str | UUID,
team_id: int,
*,
+ caller_is_agent: bool = False,
artifact_id: str | UUID,
content: str | None = None,
content_bytes: bytes | None = None,
@@ -3224,7 +3249,10 @@ def edit_task_run_living_artifact(
except Exception as exc:
logger.warning("Failed to edit living artifact %s for task run %s: %s", artifact_id, run.id, exc)
return None, str(exc)
- return serialize_task_artifact(updated), None
+ serialized = serialize_task_artifact(updated)
+ if caller_is_agent:
+ post_artifact_thread_update(run, serialized, revised=True)
+ return serialized, None
def presign_task_run_artifact(
@@ -6600,6 +6628,7 @@ def record_comment_activity(
target_owner_id=target_owner_id,
activity_at=activity_at,
)
+ post_comment_thread_update(team_id=team_id, comment_id=comment_id)
def enqueue_comment_activity_retry(
@@ -6978,7 +7007,13 @@ def _create_agent_thread_message(task: Task, content: str, *, event: str, payloa
payload=payload or {},
content=content,
)
- project_thread_message_activity(message)
+ try:
+ # A projection failure must not roll back the caller's dedup transaction with
+ # the announcement in it; the savepoint contains a database error.
+ with transaction.atomic():
+ project_thread_message_activity(message)
+ except Exception:
+ logger.exception("Failed to project thread message activity", extra={"message_id": str(message.id)})
try:
mentioned_user_ids = resolve_mentioned_user_ids(
User, message.content, team_id=message.team_id, author_id=message.author_id
@@ -7007,6 +7042,219 @@ def _agent_thread_updates_enabled(creator: User | None) -> bool:
return False
+def _commit_push_head_sha(output: object) -> str:
+ if not isinstance(output, dict) or not isinstance(output.get("commit_push"), dict):
+ return ""
+ commits = output["commit_push"].get("commits")
+ if not isinstance(commits, list) or not commits or not isinstance(commits[-1], dict):
+ return ""
+ sha = commits[-1].get("sha")
+ return sha[:64] if isinstance(sha, str) else ""
+
+
+def post_commits_pushed_thread_update(run: TaskRun, push: dict) -> None:
+ try:
+ head_sha = _commit_push_head_sha({"commit_push": push})
+ if not head_sha:
+ return
+ task = Task.objects.select_related("created_by").filter(id=run.task_id, team_id=run.team_id).first()
+ if task is None or not _agent_thread_updates_enabled(task.created_by):
+ return
+ raw_commits = push.get("commits")
+ if not isinstance(raw_commits, list):
+ return
+ commits = [
+ {
+ "sha": str(commit.get("sha") or "")[:64],
+ "subject": str(commit.get("subject") or "")[:120],
+ "url": str(commit.get("url") or "")[:2048],
+ }
+ for commit in raw_commits[-10:]
+ if isinstance(commit, dict) and commit.get("sha")
+ ]
+ if not commits:
+ return
+ with transaction.atomic():
+ Task.objects.select_for_update().filter(id=task.id).first()
+ if (
+ TaskThreadMessage.objects.for_team(task.team_id)
+ .filter(task_id=task.id, event="commits_pushed", payload__head_sha=head_sha)
+ .exists()
+ ):
+ return
+ # Branch is caller-controlled and flows into rendered markdown content
+ # and the server-side mention scanner. Strip the bracket and newline
+ # characters that would otherwise forge a [label](url) link, a
+ # ![alt](url) image, or an @[name](email) mention (the canvas-name and
+ # PR-URL guards below sanitize their equivalents for the same reason).
+ branch = re.sub(r"[\[\]\n]", " ", str(push.get("branch") or "")).strip()[:255]
+ count = len(raw_commits)
+ content = f"{count} commit{'s' if count != 1 else ''} pushed"
+ _create_agent_thread_message(
+ task,
+ f"{content} to {branch}" if branch else content,
+ event="commits_pushed",
+ payload={
+ "run_id": str(run.id),
+ "branch": branch,
+ "repository": str(push.get("repository") or "")[:255],
+ "commits": commits,
+ "total": count,
+ "head_sha": head_sha,
+ },
+ )
+ except Exception:
+ logger.exception("Failed to post commits-pushed thread update", extra={"task_id": str(run.task_id)})
+
+
+def _comment_target_name(task: Task, *, scope: str, item_id: str | None) -> str | None:
+ """The commented artifact's display name for the row label; None on the task's own scope."""
+ if scope != "task_artifact" or not item_id:
+ return None
+ try:
+ name = (
+ TaskArtifact.objects.for_team(task.team_id)
+ .filter(task_id=task.id, id=item_id)
+ .values_list("name", flat=True)
+ .first()
+ )
+ except (ValueError, DjangoValidationError):
+ name = None
+ if not name:
+ run = (
+ TaskRun.objects.filter(team_id=task.team_id, task_id=task.id, artifacts__contains=[{"id": item_id}])
+ .values_list("artifacts", flat=True)
+ .first()
+ )
+ name = next((entry.get("name") for entry in run or [] if entry.get("id") == item_id), None)
+ return str(name)[:255] if name else None
+
+
+def post_comment_thread_update(*, team_id: int, comment_id: UUID) -> None:
+ """Draw a comment on the task timeline: identity-only payload, the commenter as author.
+
+ Root comments and resolve/reopen replies each get a row; plain replies stay in the
+ Comments tab so a busy thread cannot flood the timeline.
+ """
+ from posthog.models.comment import Comment # noqa: PLC0415 — keeps the comments app off the api import path
+
+ from products.tasks.backend.logic.services.comment_activity import comment_task_id # noqa: PLC0415
+
+ try:
+ comment = Comment.objects.filter(team_id=team_id, id=comment_id, deleted=False).first()
+ if comment is None or comment.created_by_id is None:
+ return
+ context = comment.item_context if isinstance(comment.item_context, dict) else {}
+ thread_state = context.get("threadState")
+ if comment.source_comment_id and thread_state in ("resolved", "open"):
+ event = "comment_state_changed"
+ elif comment.source_comment_id:
+ return
+ else:
+ event = "comment_added"
+ task_id = comment_task_id(comment)
+ if task_id is None:
+ return
+ task = Task.objects.select_related("created_by").filter(id=task_id, team_id=team_id).first()
+ if task is None or not _agent_thread_updates_enabled(task.created_by):
+ return
+ payload: dict = {
+ "comment_id": str(comment.id),
+ "root_comment_id": str(comment.source_comment_id or comment.id),
+ "scope": comment.scope,
+ "item_id": str(comment.item_id) if comment.item_id else None,
+ "target_name": _comment_target_name(task, scope=comment.scope, item_id=comment.item_id),
+ }
+ if event == "comment_state_changed":
+ payload["state"] = thread_state
+ content = "Resolved a comment thread" if thread_state == "resolved" else "Reopened a comment thread"
+ else:
+ content = "Commented"
+ with transaction.atomic():
+ Task.objects.select_for_update().filter(id=task.id).first()
+ if (
+ TaskThreadMessage.objects.for_team(task.team_id)
+ .filter(task_id=task.id, event=event, payload__comment_id=str(comment.id))
+ .exists()
+ ):
+ return
+ # Not _create_agent_thread_message: the commenter is the author, and the
+ # comment path already projected activity and indexed mentions.
+ TaskThreadMessage.objects.for_team(task.team_id).create(
+ team_id=task.team_id,
+ task_id=task.id,
+ author_id=comment.created_by_id,
+ author_kind=TaskThreadMessage.AuthorKind.HUMAN,
+ event=event,
+ payload=payload,
+ content=content,
+ )
+ except Exception:
+ logger.exception("Failed to post comment thread update", extra={"comment_id": str(comment_id)})
+
+
+def _announce_agent_artifact_uploads(run: TaskRun, new_entries: list[dict], manifest: list[dict]) -> None:
+ """Manifest entries carry no version, so an announcement counts same-named entries:
+ re-uploading a file reads as a revision of it, the way the artifacts list groups
+ versions. The artifact_id dedup absorbs a retried upload."""
+ new_ids = {entry.get("id") for entry in new_entries}
+ announced_in_batch: dict[str, int] = {}
+ for entry in new_entries:
+ name = entry.get("name")
+ prior_versions = sum(
+ 1 for other in manifest if other.get("name") == name and other.get("id") not in new_ids
+ ) + announced_in_batch.get(name or "", 0)
+ announced_in_batch[name or ""] = announced_in_batch.get(name or "", 0) + 1
+ post_artifact_thread_update(
+ run,
+ {
+ "id": entry.get("id"),
+ "name": name,
+ "artifact_type": entry.get("type"),
+ "current_version": prior_versions + 1,
+ },
+ revised=prior_versions > 0,
+ )
+
+
+def post_artifact_thread_update(run: TaskRun, artifact: dict, *, revised: bool) -> None:
+ try:
+ artifact_id = str(artifact.get("id") or "")
+ # Caller-controlled, rendered as markdown, and scanned for mentions: strip
+ # link/mention syntax like the commits-pushed branch field.
+ name = re.sub(r"[\[\]\n]", " ", str(artifact.get("name") or "")).strip()[:255]
+ if not artifact_id or not name:
+ return
+ raw_version = artifact.get("current_version")
+ version = raw_version if isinstance(raw_version, int) else 1
+ task = Task.objects.select_related("created_by").filter(id=run.task_id, team_id=run.team_id).first()
+ if task is None or not _agent_thread_updates_enabled(task.created_by):
+ return
+ event = "artifact_revised" if revised else "artifact_created"
+ with transaction.atomic():
+ Task.objects.select_for_update().filter(id=task.id).first()
+ if (
+ TaskThreadMessage.objects.for_team(task.team_id)
+ .filter(task_id=task.id, event=event, payload__artifact_id=artifact_id, payload__version=version)
+ .exists()
+ ):
+ return
+ _create_agent_thread_message(
+ task,
+ f"{'Revised' if revised else 'Created'} {name}",
+ event=event,
+ payload={
+ "run_id": str(run.id),
+ "artifact_id": artifact_id,
+ "name": name,
+ "artifact_type": str(artifact.get("artifact_type") or "")[:64],
+ "version": version,
+ },
+ )
+ except Exception:
+ logger.exception("Failed to post artifact thread update", extra={"task_id": str(run.task_id)})
+
+
def post_canvas_created_thread_update(
task_id: str | UUID, team_id: int, *, acting_user_id: int | None, canvas_name: str, canvas_url: str | None
) -> None:
diff --git a/products/tasks/backend/logic/services/comment_activity.py b/products/tasks/backend/logic/services/comment_activity.py
index 613344ce69ba..47c8d45ea5b7 100644
--- a/products/tasks/backend/logic/services/comment_activity.py
+++ b/products/tasks/backend/logic/services/comment_activity.py
@@ -62,7 +62,7 @@ def notifications_allowed(*, team_id: int, task_id: str | UUID) -> bool:
return _notification_tasks(team_id).filter(id=parsed_task_id).exists()
-def _task_id(comment: Comment) -> UUID | None:
+def comment_task_id(comment: Comment) -> UUID | None:
if comment.scope not in COMMENT_ACTIVITY_SCOPES:
return None
raw_task_id = comment.item_id if comment.scope == "task" else (comment.item_context or {}).get("taskId")
@@ -86,7 +86,7 @@ def project_comment_activity(
comment = Comment.objects.filter(team_id=team_id, id=comment_id).first()
if comment is None or comment.created_by_id is None:
return
- task_id = _task_id(comment)
+ task_id = comment_task_id(comment)
if task_id is None:
return
task = _notification_tasks(team_id).filter(id=task_id).only("created_by_id").first()
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 3f66521bab40..83583ebc2ec6 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1080,6 +1080,18 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(tags=["task-runs", "tasks"])
+def is_sandbox_agent_request(request, task_id: str) -> bool:
+ """True only for the task-bound sandbox OAuth identity, never a human session or key."""
+ authenticator = 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)
+
+
class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
API for managing task runs. Each run represents an execution of a task.
@@ -1115,14 +1127,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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)
+ return is_sandbox_agent_request(self.request, task_id)
# Actions that only read run state. Everything else mutates or drives the
# run, so it requires task control (not just visibility): public-channel
@@ -1384,7 +1389,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# must not be resurrected to completed/failed by a stale in-flight agent PATCH. A terminal run
# is done, so a late PATCH is a no-op, not an overwrite.
run = tasks_facade.update_task_run(
- pk, task_id, self.team_id, validated_data=dict(request.validated_data), only_if_non_terminal=True
+ pk,
+ task_id,
+ self.team_id,
+ validated_data=dict(request.validated_data),
+ only_if_non_terminal=True,
+ caller_is_agent=self._is_sandbox_agent_request(task_id),
)
if run is None:
raise NotFound()
@@ -1618,7 +1628,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def artifacts(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
result = tasks_facade.upload_task_run_artifacts(
- 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 self._is_sandbox_agent_request(task_id) else "user",
)
if result is None:
raise NotFound()
@@ -2693,7 +2707,11 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
def create(self, request, *args, **kwargs):
task_id = self._ensure_task_accessible()
artifact, error = tasks_facade.create_task_run_living_artifact(
- self._run_id(), task_id, self.team_id, artifact=request.validated_data
+ self._run_id(),
+ task_id,
+ self.team_id,
+ artifact=request.validated_data,
+ caller_is_agent=is_sandbox_agent_request(request, task_id),
)
if artifact is None and error is None:
raise NotFound()
@@ -2819,6 +2837,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
run_id,
task_id,
self.team_id,
+ caller_is_agent=is_sandbox_agent_request(request, task_id),
artifact={
"name": self._with_png_extension(name),
"artifact_type": TaskArtifactType.FILE,
@@ -2900,6 +2919,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
self._run_id(),
task_id,
self.team_id,
+ caller_is_agent=is_sandbox_agent_request(request, task_id),
artifact_id=pk,
content=request.validated_data.get("content"),
content_bytes=request.validated_data.get("content_bytes"),
diff --git a/products/tasks/backend/tests/test_thread_updates.py b/products/tasks/backend/tests/test_thread_updates.py
index 79de4d75874c..0ab84aa0350d 100644
--- a/products/tasks/backend/tests/test_thread_updates.py
+++ b/products/tasks/backend/tests/test_thread_updates.py
@@ -5,14 +5,17 @@ from django.test import TestCase
from parameterized import parameterized
-from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models import Comment, Organization, OrganizationMembership, Team, User
from posthog.models.scoping import team_scope
from products.tasks.backend.facade.api import (
list_mentions,
list_thread_messages,
+ post_artifact_thread_update,
post_canvas_created_thread_update,
+ post_commits_pushed_thread_update,
post_pr_created_thread_update,
+ record_comment_activity,
set_task_run_output,
update_task_run,
)
@@ -151,6 +154,212 @@ class TestAgentThreadUpdates(TestCase):
self.assertEqual([message.event for message in messages], ["pr_created"])
self.assertEqual(messages[0].payload, {"pr_url": "https://github.com/posthog/posthog/pull/321"})
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_artifact_events_post_once_per_version(self, _flag) -> None:
+ artifact = {"id": "art-1", "name": "report.md", "artifact_type": "document", "current_version": 1}
+
+ post_artifact_thread_update(self.task_run, artifact, revised=False)
+ post_artifact_thread_update(self.task_run, artifact, revised=False)
+ post_artifact_thread_update(self.task_run, {**artifact, "current_version": 2}, revised=True)
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["artifact_created", "artifact_revised"])
+ self.assertEqual(
+ messages[0].payload,
+ {
+ "run_id": str(self.task_run.id),
+ "artifact_id": "art-1",
+ "name": "report.md",
+ "artifact_type": "document",
+ "version": 1,
+ },
+ )
+ self.assertEqual(messages[1].payload["version"], 2)
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_comment_events_draw_roots_and_state_changes_only(self, _flag) -> None:
+ def comment(**kwargs) -> Comment:
+ return Comment.objects.create(
+ team=self.team,
+ scope="task",
+ item_id=str(self.task.id),
+ created_by=self.user,
+ **kwargs,
+ )
+
+ root = comment(content="the header looks off")
+ record_comment_activity(team_id=self.team.id, comment_id=root.id, mentioned_user_ids=[])
+ record_comment_activity(team_id=self.team.id, comment_id=root.id, mentioned_user_ids=[])
+ reply = comment(content="agreed", source_comment=root)
+ record_comment_activity(team_id=self.team.id, comment_id=reply.id, mentioned_user_ids=[])
+ resolve = comment(content="", source_comment=root, item_context={"threadState": "resolved"})
+ record_comment_activity(team_id=self.team.id, comment_id=resolve.id, mentioned_user_ids=[])
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["comment_added", "comment_state_changed"])
+ added, state = messages
+ self.assertEqual(added.author_id, self.user.id)
+ self.assertEqual(added.author_kind, TaskThreadMessage.AuthorKind.HUMAN)
+ self.assertEqual(added.payload["comment_id"], str(root.id))
+ self.assertEqual(added.payload["root_comment_id"], str(root.id))
+ self.assertIsNone(added.payload["target_name"])
+ self.assertEqual(state.payload["state"], "resolved")
+ self.assertEqual(state.payload["root_comment_id"], str(root.id))
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_artifact_name_cannot_forge_markdown_or_mentions(self, _flag) -> None:
+ post_artifact_thread_update(
+ self.task_run,
+ {"id": "art-9", "name": "x [click](https://evil.example)\n@[Casey]([email protected])"},
+ revised=False,
+ )
+
+ messages = self._messages(self.task)
+ self.assertEqual(len(messages), 1)
+ for forged in ("[", "]", "\n"):
+ self.assertNotIn(forged, messages[0].content)
+ self.assertNotIn(forged, messages[0].payload["name"])
+ self.assertEqual(TaskThreadMessageMention.objects.for_team(self.team.id).count(), 0)
+
+ @patch("posthog.storage.object_storage.tag")
+ @patch("posthog.storage.object_storage.write")
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_inline_agent_upload_announces_created_then_revised(self, _flag, _write, _tag) -> None:
+ from products.tasks.backend.facade.api import upload_task_run_artifacts
+
+ artifact = {"name": "summary.md", "type": "output", "content_bytes": b"v1", "content_type": "text/markdown"}
+ with team_scope(self.team.id):
+ upload_task_run_artifacts(
+ self.task_run.id, self.task.id, self.team.id, artifacts=[artifact], uploaded_by="agent"
+ )
+ upload_task_run_artifacts(
+ self.task_run.id,
+ self.task.id,
+ self.team.id,
+ artifacts=[{**artifact, "content_bytes": b"v2"}],
+ uploaded_by="agent",
+ )
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["artifact_created", "artifact_revised"])
+ self.assertEqual(messages[1].payload["version"], 2)
+ self.assertEqual(messages[1].payload["name"], "summary.md")
+
+ @patch("products.tasks.backend.facade.api.project_thread_message_activity", side_effect=Exception("boom"))
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_announcement_survives_a_failed_activity_projection(self, _flag, _projection) -> None:
+ push = {
+ "branch": "posthog/x",
+ "repository": "posthog/posthog",
+ "commits": [{"sha": "fadedfacade", "subject": "feat: x", "url": "https://github.com/x"}],
+ }
+
+ post_commits_pushed_thread_update(self.task_run, push)
+
+ self.assertEqual([message.event for message in self._messages(self.task)], ["commits_pushed"])
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_artifact_comment_names_its_target(self, _flag) -> None:
+ self.task_run.artifacts = [{"id": "artifact-1", "name": "report.md", "type": "output"}]
+ self.task_run.save(update_fields=["artifacts"])
+ comment = Comment.objects.create(
+ team=self.team,
+ scope="task_artifact",
+ item_id="artifact-1",
+ item_context={"taskId": str(self.task.id)},
+ content="nice summary",
+ created_by=self.user,
+ )
+
+ record_comment_activity(team_id=self.team.id, comment_id=comment.id, mentioned_user_ids=[])
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["comment_added"])
+ self.assertEqual(messages[0].payload["target_name"], "report.md")
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_commit_push_posts_once_when_run_patch_is_retried(self, _flag) -> None:
+ output = {
+ "commit_push": {
+ "branch": "posthog/task-timeline-commits",
+ "repository": "posthog/posthog",
+ "commits": [
+ {
+ "sha": "abc123",
+ "subject": "feat(desktop): show commits",
+ "url": "https://github.com/posthog/posthog/commit/abc123",
+ }
+ ],
+ }
+ }
+ with team_scope(self.team.id):
+ update_task_run(
+ self.task_run.id,
+ self.task.id,
+ self.team.id,
+ validated_data={"output": output},
+ caller_is_agent=True,
+ )
+ update_task_run(
+ self.task_run.id,
+ self.task.id,
+ self.team.id,
+ validated_data={"output": output},
+ caller_is_agent=True,
+ )
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["commits_pushed"])
+ self.assertEqual(messages[0].payload["head_sha"], "abc123")
+ self.assertEqual(messages[0].payload["total"], 1)
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_commit_push_from_a_human_caller_does_not_forge_an_agent_row(self, _flag) -> None:
+ output = {
+ "commit_push": {
+ "branch": "posthog/x",
+ "repository": "posthog/posthog",
+ "commits": [{"sha": "beadedcafe", "subject": "feat: x", "url": "https://github.com/x"}],
+ }
+ }
+ with team_scope(self.team.id):
+ update_task_run(
+ self.task_run.id,
+ self.task.id,
+ self.team.id,
+ validated_data={"output": output},
+ )
+
+ self.assertEqual(self._messages(self.task), [])
+
+ @patch(_FLAG_TARGET, return_value=True)
+ def test_commit_push_sanitizes_untrusted_branch(self, _flag) -> None:
+ # The branch is caller-controlled and lands in rendered markdown content
+ # and the mention scanner. A crafted value must not forge a markdown link
+ # or an @[name](email) mention of a real org member in the agent row.
+ post_commits_pushed_thread_update(
+ self.task_run,
+ {
+ "branch": "@[Casey Creator]([email protected])",
+ "repository": "posthog/posthog",
+ "commits": [
+ {
+ "sha": "abc123",
+ "subject": "feat(desktop): show commits",
+ "url": "https://github.com/posthog/posthog/commit/abc123",
+ }
+ ],
+ },
+ )
+
+ messages = self._messages(self.task)
+ self.assertEqual([message.event for message in messages], ["commits_pushed"])
+ self.assertEqual(messages[0].content, "1 commit pushed to @ Casey Creator ([email protected])")
+ self.assertEqual(
+ list(TaskThreadMessageMention.objects.for_team(self.team.id).filter(task=self.task)),
+ [],
+ )
+
@patch(_FLAG_TARGET, return_value=True)
def test_pr_created_posts_when_set_output_records_pr_url(self, _flag) -> None:
with team_scope(self.team.id):