: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
feat(tasks): replace turn_complete thread writeback with pr_created artifact messages (#72857)
Peter Kirkham1e83c408142a
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 3c13fee43ab4..807288bbc911 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -25,7 +25,7 @@ from urllib.parse import urlparsefrom uuid import UUID, uuid4from django.conf import settings-from django.db import IntegrityError, close_old_connections, transaction+from django.db import IntegrityError, transactionfrom django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, QuerySet, Subqueryfrom django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone as django_timezone@@ -49,7 +49,7 @@ from products.tasks.backend.logic.services.image_builder import (is_custom_images_enabled,read_spec_from_builder_sandbox,)-from products.tasks.backend.mentions import format_mention_token, resolve_mentioned_user_ids+from products.tasks.backend.mentions import resolve_mentioned_user_idsfrom products.tasks.backend.models import (Channel,ChannelFeedMessage,@@ -2112,6 +2112,7 @@ def update_task_run(if new_pr_url and new_pr_url != old_pr_url:_post_slack_update_for_pr(run)_send_wizard_pr_ready_email_for_pr(run)+ post_pr_created_thread_update(run, new_pr_url)# Surface the PR in the run's progress timeline the moment the agent reports it, so the install# UI advances past "Started agent" instead of waiting on the 15-min CI follow-up loop to emit# these. Steps coalesce by id with the workflow's own pr/ci emissions (frontend mergeProgressStep),@@ -2162,6 +2163,8 @@ def set_task_run_output(run.publish_stream_state_event()_post_slack_update_for_pr(run)_send_wizard_pr_ready_email_for_pr(run)+ if merged.get("pr_url"):+ post_pr_created_thread_update(run, merged["pr_url"])return _task_run_detail_to_dto(run)@@ -5109,6 +5112,9 @@ def list_thread_messages(return Nonemessages = (TaskThreadMessage.objects.filter(task_id=task_id, team_id=team_id)+ # The thread is human-to-human plus artifact announcements; rows written+ # back when the agent finished a turn (a since-removed behavior) stay out.+ .exclude(event="turn_complete").select_related("author", "forwarded_by").order_by("created_at", "id"))@@ -5166,7 +5172,9 @@ def list_mentions(mentioned_user_id=user_id,# task__in keeps the visibility rules single-sourced in _visible_task_qs.task__in=_visible_task_qs(team_id, user_id),- )+ # Legacy turn_complete rows are hidden from threads (see list_thread_messages),+ # so their indexed mentions must not surface notifications pointing at them.+ ).exclude(message__event="turn_complete")if since is not None:qs = qs.filter(created_at__gt=since)mentions = qs.select_related("message__author", "task__channel").order_by("-created_at")[:limit]@@ -5248,13 +5256,6 @@ def forward_thread_message(# updates are gated on the same flag — evaluated for the task creator.AGENT_THREAD_UPDATES_FLAG = "project-bluebird"-# One turn-complete post per run within the window, so an SSE relay reconnect-# replaying the tail of the stream can't double-post the same end-of-turn.-_TURN_COMPLETE_COOLDOWN_SECONDS = 30--# Cap the relayed final message so one agent essay can't dwarf the thread.-_TURN_MESSAGE_MAX_CHARS = 4000-def _create_agent_thread_message(task: Task, content: str, *, event: str, payload: dict | None = None) -> None:"""Write an agent-authored thread message and index its mentions.@@ -5326,42 +5327,79 @@ def post_canvas_created_thread_update(logger.exception("Failed to post canvas-created thread update", extra={"task_id": str(task_id)})-def post_turn_complete_thread_update(- run_id: str | UUID, task_id: str | UUID, team_id: int, *, message: str | None = None-) -> None:- """Post the agent's final turn message into the task's thread, @-mentioning the task creator.+_GITHUB_PR_PATH_PATTERN = re.compile(r"/([^/]+)/([^/]+)/pull/(\d+)/?", re.IGNORECASE)++# Characters that could break out of a markdown [label](url) token or smuggle+# extra markdown into the rendered thread message.+_PR_URL_UNSAFE_CHARS = set(" \t\n\r()[]<>\"'`\\")++_PR_URL_MAX_LENGTH = 2048+- Fires from the sandbox event relay on every end-of-turn of a channel task's- background run, so the update lands even with no client open. ``message`` is- the agent's closing prose for the turn; when the relay captured none, a plain- "Turn complete." stands in. Best-effort and never raises — a failed post must- not disturb the relay.+def _is_safe_pr_url(pr_url: str) -> bool:+ """Whether ``pr_url`` is a plain http(s) URL safe to embed in a markdown link.++ ``pr_url`` originates from task-run output APIs, so it is caller-controlled.+ Real PR URLs never contain whitespace, quotes, brackets, or parentheses;+ anything that does is rejected rather than escaped.+ """+ if not pr_url or len(pr_url) > _PR_URL_MAX_LENGTH or any(char in _PR_URL_UNSAFE_CHARS for char in pr_url):+ return False+ parsed = urlparse(pr_url)+ return parsed.scheme in ("http", "https") and bool(parsed.netloc)+++def _pr_display_label(pr_url: str) -> str:+ parsed = urlparse(pr_url)+ if parsed.hostname is None or parsed.hostname.lower() != "github.com":+ return pr_url+ match = _GITHUB_PR_PATH_PATTERN.fullmatch(parsed.path)+ if match:+ owner, repo, number = match.groups()+ return f"{owner}/{repo}#{number}"+ return pr_url+++def post_pr_created_thread_update(run: TaskRun, pr_url: str) -> None:+ """Announce a run's freshly opened pull request in its task's thread.++ Posts "[owner/repo#N](url) has been opened" as an agent artifact message+ (``event="pr_created"``). Both the agent-output path and the GitHub webhook+ backstop can observe the same PR, so the announcement dedupes on the task's+ existing ``pr_created`` rows for this URL. Best-effort and never raises —+ recording the PR must not fail because its announcement couldn't be written."""try:- if not settings.TEST:- close_old_connections()- task = Task.objects.select_related("created_by").filter(id=task_id, team_id=team_id).first()- # Threads hang off a task's channel feed; a channel-less task has no audience.- if task is None or task.channel_id is None:+ if not _is_safe_pr_url(pr_url):+ logger.info("pr_created thread update skipped", extra={"task_id": str(run.task_id), "reason": "unsafe_url"})return- creator = task.created_by- if creator is None or not _agent_thread_updates_enabled(creator):+ # Unlike turn_complete's old channel guard, artifact rows post for+ # channel-less tasks too: every task has a thread panel.+ task = Task.objects.select_related("created_by").filter(id=run.task_id, team_id=run.team_id).first()+ if task is None:return- from products.tasks.backend.redis import get_tasks_cache # noqa: PLC0415 — keep redis off the api import path-- if not get_tasks_cache().add(f"thread_update:{run_id}:turn_complete", True, _TURN_COMPLETE_COOLDOWN_SECONDS):+ if task.created_by is None or not _agent_thread_updates_enabled(task.created_by):+ logger.info(+ "pr_created thread update skipped",+ extra={"task_id": str(task.id), "reason": "no_creator" if task.created_by is None else "flag_off"},+ )return- body = (message or "").strip() or "Turn complete."- if len(body) > _TURN_MESSAGE_MAX_CHARS:- body = body[: _TURN_MESSAGE_MAX_CHARS - 1] + "…"- mention = format_mention_token(creator.get_full_name() or creator.email, creator.email)- # payload.run_id is the dedupe key: a client already rendering this run's- # live agent turns can suppress the durable row (or vice versa).- _create_agent_thread_message(- task,- f"{mention} {body}",- event="turn_complete",- payload={"run_id": str(run_id)},- )+ # The agent-output path and the webhook backstop can race on the same PR;+ # locking the task row makes the dedupe check-and-create atomic across them.+ 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="pr_created", payload__pr_url=pr_url)+ .exists()+ ):+ return+ label = _pr_display_label(pr_url)+ _create_agent_thread_message(+ task,+ f"[{label}]({pr_url}) has been opened",+ event="pr_created",+ payload={"pr_url": pr_url},+ )except Exception:- logger.exception("Failed to post turn-complete thread update", extra={"task_id": str(task_id)})+ logger.exception("Failed to post pr-created thread update", extra={"task_id": str(run.task_id)})diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 1c508a428ffd..7f83fb51a35d 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -19,7 +19,6 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connections-from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.logic.services.agent_command import validate_sandbox_urlfrom products.tasks.backend.logic.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.logic.services.permission_broker import (@@ -331,10 +330,6 @@ async def _relay_loop(last_audit_ts_ns: list[int] = [0] # track last agentsh audit timestamp# Brackets turn_started / turn_completed signals to the parent.slack_turn_active: list[bool] = [False]- # The agent's in-progress closing message for the current turn. Chunks- # accumulate; a new tool call or user message resets it, so at end-of-turn- # it holds the prose after the last tool call — what the thread update posts.- final_message_parts: list[str] = []# ACP emits one tool_call + N tool_call_update per id; only render the start.emitted_tool_call_ids: set[str] = set()# Buffered prose + last flush time (monotonic); see TEXT_DELTA_FLUSH_INTERVAL_SECONDS.@@ -409,22 +404,6 @@ async def _relay_loop(# does sync Redis (cache.add) and a potential network call to# the feature-flag service.asyncio.create_task(asyncio.to_thread(_safe_dispatch_awaiting_input, task_run))- if task_run is not None and task_run.mode != "interactive":- # Background run finished a turn — post its closing message- # into the task's thread so teammates following it see the- # outcome without a client open. Guards (flag, channel,- # cooldown) live in the facade; same thread hop as above- # for its sync I/O.- asyncio.create_task(- asyncio.to_thread(- tasks_facade.post_turn_complete_thread_update,- str(task_run.id),- str(task_run.task_id),- task_run.team_id,- message="".join(final_message_parts).strip() or None,- )- )- final_message_parts.clear()if is_agent_design_enabled and slack_turn_active[0] and workflow_handle is not None:slack_turn_active[0] = False# Awaited in order: the final prose must be recorded before@@ -435,9 +414,6 @@ async def _relay_loop(elif not agent_active[0] and _is_active_agent_update(event_data):agent_active[0] = True- if task_run is not None and task_run.mode != "interactive":- _track_final_message(event_data, final_message_parts)-# Agent-design signal fan-out: first session/update opens the# child relay; tool_call → step, agent_message_chunk → markdown.if is_agent_design_enabled and workflow_handle is not None:@@ -500,7 +476,6 @@ async def _relay_loop(reconnect_count += 1# May have missed an end_of_turn on the dropped stream — assume idle until re-confirmed.agent_active[0] = False- final_message_parts.clear()# Drop un-flushed partial prose — the agent replays events on reconnect.pending_text_parts.clear()logger.warning(@@ -524,7 +499,6 @@ async def _relay_loop(# 5xx — transient server error, worth retryingreconnect_count += 1agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)- final_message_parts.clear()# Drop un-flushed partial prose — the agent replays events on reconnect.pending_text_parts.clear()logger.warning(@@ -539,7 +513,6 @@ async def _relay_loop(except (httpx.TransportError, httpx_sse.SSEError) as e:reconnect_count += 1agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)- final_message_parts.clear()# Drop un-flushed partial prose — the agent replays events on reconnect.pending_text_parts.clear()logger.warning(@@ -671,20 +644,6 @@ def _tool_args_preview(raw_input: Any) -> str | None:return one_line-def _track_final_message(event_data: dict, parts: list[str]) -> None:- """Accumulate agent_message_chunk text; a new tool call or user message resets,- so `parts` ends the turn holding only the agent's closing prose."""- text = _extract_agent_message_text(event_data)- if text:- parts.append(text)- return- if not _is_session_update(event_data):- return- update = (event_data.get("notification", {}).get("params") or {}).get("update") or {}- if update.get("sessionUpdate") in ("tool_call", "user_message", "user_message_chunk"):- parts.clear()--def _extract_agent_message_text(event_data: dict) -> str | None:"""Text delta from an ACP agent_message_chunk session/update, else None."""notification = event_data.get("notification", {})diff --git a/products/tasks/backend/tests/test_thread_updates.py b/products/tasks/backend/tests/test_thread_updates.pyindex 2e7f71b270ca..79de4d75874c 100644--- a/products/tasks/backend/tests/test_thread_updates.py+++ b/products/tasks/backend/tests/test_thread_updates.py@@ -1,15 +1,22 @@from unittest.mock import patchfrom django.core.cache import cache-from django.test import SimpleTestCase, TestCase+from django.test import TestCasefrom parameterized import parameterizedfrom posthog.models import Organization, OrganizationMembership, Team, User--from products.tasks.backend.facade.api import post_canvas_created_thread_update, post_turn_complete_thread_update+from posthog.models.scoping import team_scope++from products.tasks.backend.facade.api import (+ list_mentions,+ list_thread_messages,+ post_canvas_created_thread_update,+ post_pr_created_thread_update,+ set_task_run_output,+ update_task_run,+)from products.tasks.backend.models import Channel, Task, TaskRun, TaskThreadMessage, TaskThreadMessageMention-from products.tasks.backend.temporal.process_task.activities.relay_sandbox_events import _track_final_message_FLAG_TARGET = "products.tasks.backend.facade.api.posthoganalytics.feature_enabled"@@ -40,60 +47,79 @@ class TestAgentThreadUpdates(TestCase):def _messages(self, task: Task) -> list[TaskThreadMessage]:return list(TaskThreadMessage.objects.for_team(self.team.id).filter(task=task).order_by("created_at"))+ @patch(_FLAG_TARGET, return_value=True)+ def test_pr_created_posts_authorless_artifact_message(self, _flag) -> None:+ post_pr_created_thread_update(self.task_run, "https://github.com/posthog/posthog/pull/123")++ messages = self._messages(self.task)+ self.assertEqual(len(messages), 1)+ self.assertIsNone(messages[0].author_id)+ self.assertEqual(messages[0].author_kind, TaskThreadMessage.AuthorKind.AGENT)+ self.assertEqual(messages[0].event, "pr_created")+ self.assertEqual(messages[0].payload, {"pr_url": "https://github.com/posthog/posthog/pull/123"})+ self.assertEqual(+ messages[0].content,+ "[posthog/posthog#123](https://github.com/posthog/posthog/pull/123) has been opened",+ )+@parameterized.expand([- (- "relays_final_message",- "Shipped the canvas with three charts.",- "@[Casey Creator]([email protected]) Shipped the canvas with three charts.",- ),- ("falls_back_without_message", None, "@[Casey Creator]([email protected]) Turn complete."),+ ("non_github", "https://example.com/pr/9"),+ ("github_in_path", "https://evil.example/github.com/posthog/posthog/pull/123"),])@patch(_FLAG_TARGET, return_value=True)- def test_turn_complete_posts_authorless_message_mentioning_creator(self, _name, message, expected, _flag) -> None:- post_turn_complete_thread_update(str(self.task_run.id), str(self.task.id), self.team.id, message=message)+ def test_pr_created_falls_back_to_url_label_for_non_github_urls(self, _name, pr_url, _flag) -> None:+ post_pr_created_thread_update(self.task_run, pr_url)messages = self._messages(self.task)self.assertEqual(len(messages), 1)- self.assertIsNone(messages[0].author_id)- self.assertEqual(messages[0].author_kind, TaskThreadMessage.AuthorKind.AGENT)- self.assertEqual(messages[0].event, "turn_complete")- # run_id is the client's key for deduping this durable row against- # live session-derived agent turns.- self.assertEqual(messages[0].payload, {"run_id": str(self.task_run.id)})- self.assertEqual(messages[0].content, expected)- # The creator's mention is indexed so it lands in their mentions feed.- self.assertTrue(- TaskThreadMessageMention.objects.for_team(self.team.id)- .filter(message=messages[0], mentioned_user=self.user)- .exists()+ self.assertEqual(+ messages[0].content,+ f"[{pr_url}]({pr_url}) has been opened",)@patch(_FLAG_TARGET, return_value=True)- def test_turn_complete_truncates_oversized_message(self, _flag) -> None:- post_turn_complete_thread_update(str(self.task_run.id), str(self.task.id), self.team.id, message="x" * 5000)+ def test_pr_created_dedupes_per_pr_url(self, _flag) -> None:+ # Both the agent-output path and the GitHub webhook backstop can announce+ # the same PR; only one artifact row must land in the thread.+ post_pr_created_thread_update(self.task_run, "https://github.com/posthog/posthog/pull/123")+ post_pr_created_thread_update(self.task_run, "https://github.com/posthog/posthog/pull/123")++ self.assertEqual(len(self._messages(self.task)), 1)++ @patch(_FLAG_TARGET, return_value=True)+ def test_pr_created_posts_separate_messages_for_distinct_prs(self, _flag) -> None:+ post_pr_created_thread_update(self.task_run, "https://github.com/posthog/posthog/pull/1")+ post_pr_created_thread_update(self.task_run, "https://github.com/posthog/posthog/pull/2")- content = self._messages(self.task)[0].content- self.assertTrue(content.endswith("…"))- self.assertLess(len(content), 4100)+ self.assertEqual(len(self._messages(self.task)), 2)+ @parameterized.expand(+ [+ ("javascript_scheme", "javascript:alert(1)"),+ ("markdown_breakout_paren", "https://example.com/pr)+[click](https://evil.example)"),+ ("embedded_newline", "https://example.com/pr\n"),+ ("embedded_bracket", "https://github.com/own]er/repo/pull/1"),+ ("no_host", "https:///pull/1"),+ ]+ )@patch(_FLAG_TARGET, return_value=True)- def test_turn_complete_cooldown_collapses_duplicate_end_of_turn_events(self, _flag) -> None:- post_turn_complete_thread_update(str(self.task_run.id), str(self.task.id), self.team.id)- post_turn_complete_thread_update(str(self.task_run.id), str(self.task.id), self.team.id)+ def test_pr_created_skips_unsafe_urls(self, _name, pr_url, _flag) -> None:+ # pr_url flows from task-run output into a markdown [label](url) token in a+ # shared thread; anything that can't be a plain http(s) URL is dropped.+ post_pr_created_thread_update(self.task_run, pr_url)- self.assertEqual(len(self._messages(self.task)), 1)+ self.assertEqual(self._messages(self.task), [])@parameterized.expand([- ("flag_off", False, True, True),- ("no_channel", True, False, True),- ("no_creator", True, True, False),+ ("flag_off", False, True),+ ("no_creator", True, False),])@patch(_FLAG_TARGET)- def test_turn_complete_skips(self, _name, flag_on, has_channel, has_creator, flag_mock) -> None:+ def test_pr_created_skips(self, _name, flag_on, has_creator, flag_mock) -> None:flag_mock.return_value = flag_ontask = Task.objects.create(team=self.team,@@ -101,14 +127,64 @@ class TestAgentThreadUpdates(TestCase):description="",origin_product=Task.OriginProduct.USER_CREATED,created_by=self.user if has_creator else None,- channel=self.channel if has_channel else None,+ channel=self.channel,)run = TaskRun.objects.create(task=task, team=self.team)- post_turn_complete_thread_update(str(run.id), str(task.id), self.team.id)+ post_pr_created_thread_update(run, "https://github.com/posthog/posthog/pull/123")self.assertEqual(self._messages(task), [])+ @patch(_FLAG_TARGET, return_value=True)+ def test_pr_created_posts_when_run_patch_records_pr_url(self, _flag) -> None:+ # The agent attaches a PR by PATCHing the run's output — the path the+ # desktop/cloud agent actually uses (attachPullRequestToTask).+ with team_scope(self.team.id):+ update_task_run(+ self.task_run.id,+ self.task.id,+ self.team.id,+ validated_data={"output": {"pr_url": "https://github.com/posthog/posthog/pull/321"}},+ )++ messages = self._messages(self.task)+ 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_pr_created_posts_when_set_output_records_pr_url(self, _flag) -> None:+ with team_scope(self.team.id):+ set_task_run_output(+ self.task_run.id,+ self.task.id,+ self.team.id,+ output={"pr_url": "https://github.com/posthog/posthog/pull/654"},+ )++ messages = self._messages(self.task)+ self.assertEqual([message.event for message in messages], ["pr_created"])++ @patch(_FLAG_TARGET, return_value=True)+ def test_pr_created_posts_for_channel_less_tasks(self, _flag) -> None:+ # Threads exist per-task, not only per-channel: a task filed outside a+ # channel still has a thread panel, and its PR artifact must land there+ # (canvas_created behaves the same way).+ task = Task.objects.create(+ team=self.team,+ title="Channel-less task",+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ created_by=self.user,+ channel=None,+ )+ run = TaskRun.objects.create(task=task, team=self.team)++ post_pr_created_thread_update(run, "https://github.com/posthog/posthog/pull/123")++ messages = self._messages(task)+ self.assertEqual(len(messages), 1)+ self.assertEqual(messages[0].event, "pr_created")+@parameterized.expand([(@@ -157,33 +233,64 @@ class TestAgentThreadUpdates(TestCase):self.assertEqual(self._messages(self.task), [])+ def test_list_thread_messages_excludes_legacy_turn_complete_rows(self) -> None:+ # The thread is human-to-human plus artifacts: rows written back when the+ # agent finished a turn (before that writeback was removed) must not+ # resurface in the listing.+ TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team, task=self.task, author=self.user, content="Kicking this off"+ )+ TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=self.task,+ author_kind=TaskThreadMessage.AuthorKind.AGENT,+ event="turn_complete",+ payload={"run_id": str(self.task_run.id)},+ content="@[Casey Creator]([email protected]) Turn complete.",+ )+ TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=self.task,+ author_kind=TaskThreadMessage.AuthorKind.AGENT,+ event="canvas_created",+ payload={"canvas_name": "Signups", "canvas_url": None},+ content="Signups has been created",+ )-def _session_update(update: dict) -> dict:- return {"type": "notification", "notification": {"method": "session/update", "params": {"update": update}}}---def _chunk(text: str) -> dict:- return _session_update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})---class TestTrackFinalMessage(SimpleTestCase):- def test_holds_only_prose_after_last_tool_call(self) -> None:- parts: list[str] = []- for event in [- _chunk("Let me look at the data first. "),- _session_update({"sessionUpdate": "tool_call", "toolCallId": "t1"}),- _session_update({"sessionUpdate": "tool_call_update", "toolCallId": "t1"}),- _chunk("Done. The canvas "),- _chunk("shows signups by week."),- ]:- _track_final_message(event, parts)-- self.assertEqual("".join(parts), "Done. The canvas shows signups by week.")-- @parameterized.expand([("user_message",), ("user_message_chunk",), ("tool_call",)])- def test_resets_on(self, session_update: str) -> None:- parts = ["stale narration"]+ with team_scope(self.team.id):+ messages = list_thread_messages(self.task.id, self.team.id, self.user.id)- _track_final_message(_session_update({"sessionUpdate": session_update}), parts)+ assert messages is not None+ self.assertEqual([message.event for message in messages], ["", "canvas_created"])- self.assertEqual(parts, [])+ def test_list_mentions_excludes_legacy_turn_complete_mentions(self) -> None:+ # turn_complete messages @-mentioned the task creator and indexed that+ # mention; with the messages hidden from threads, their mention rows must+ # not surface notifications pointing at rows the thread no longer shows.+ human_message = TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=self.task,+ author=self.user,+ content="@[Casey Creator]([email protected]) thoughts?",+ )+ turn_message = TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=self.task,+ author_kind=TaskThreadMessage.AuthorKind.AGENT,+ event="turn_complete",+ payload={"run_id": str(self.task_run.id)},+ content="@[Casey Creator]([email protected]) Turn complete.",+ )+ for message in (human_message, turn_message):+ TaskThreadMessageMention.objects.for_team(self.team.id).create(+ team=self.team,+ message=message,+ task=self.task,+ mentioned_user=self.user,+ created_at=message.created_at,+ )++ with team_scope(self.team.id):+ mentions = list_mentions(self.team.id, self.user.id)++ self.assertEqual([mention.message_id for mention in mentions], [human_message.id])diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 90e5e3a1743b..d33ab3af3567 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -18,7 +18,7 @@ from posthog.models.user import Userfrom products.signals.backend.models import SignalReportfrom products.signals.backend.task_run_artefacts import append_task_run_artefact-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Task, TaskRun, TaskThreadMessagefrom products.tasks.backend.webhooks import _account_type, find_task_run@@ -445,6 +445,38 @@ class TestGitHubPRWebhook(TestCase):assert run.output is not Noneself.assertEqual(run.output["pr_url"], pr_url)+ @patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_opened_repairs_missing_artifact_for_existing_pr_url(+ self, mock_capture, mock_get_secret, mock_feature_enabled+ ) -> None:+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/780"+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ branch="feature/missing-artifact",+ output={"pr_url": pr_url},+ )+ payload = {+ "action": "opened",+ "pull_request": {+ "html_url": pr_url,+ "merged": False,+ "head": {"ref": "feature/missing-artifact", "repo": {"full_name": "posthog/posthog"}},+ },+ "repository": {"full_name": "posthog/posthog"},+ }++ response = self._make_webhook_request(payload)++ self.assertEqual(response.status_code, 200)+ self.assertTrue(+ TaskThreadMessage.objects.for_team(self.team.id).filter(task=self.task, payload__pr_url=pr_url).exists()+ )+@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@patch("products.tasks.backend.models.posthoganalytics.capture")def test_pr_opened_backfills_pr_url_on_wizard_head_branch_match(self, mock_capture, mock_get_secret):diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex b4d69b90a496..b6b34dfaf16d 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -15,7 +15,7 @@ from posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom products.signals.backend.models import InvalidStatusTransition, SignalReport-from products.tasks.backend.facade.api import signal_workflow_completion+from products.tasks.backend.facade.api import post_pr_created_thread_update, signal_workflow_completionfrom products.tasks.backend.facade.cancellation import cancel_task_runfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX@@ -216,7 +216,11 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:``output.pr_url`` stays empty, so inbox notifications, the CI follow-up loop,and later webhook lookups never resolve the PR."""- if not _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed"):+ recorded = _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed")+ if not recorded and not TaskRun.objects.filter(id=task_run.id, output__pr_url=pr_url).exists():+ return+ post_pr_created_thread_update(task_run, pr_url)+ if not recorded:return# Publish-only (no append_log): the S3 run log has a live writer — the agent is streaming# log batches at exactly this moment — and append_log's read-modify-write would race it.