: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): add task list filters for PR, CI, and activity (#83735)
Shy Alterb98687c3b401
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 86c5fe04284c..5b297ffb1e2e 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -4,6 +4,12 @@ from typing import Literal, get_argsimport posthoganalytics+# Canonical PR/CI snapshot vocabulary, as produced by the GitHub integration's+# pull-request snapshot (`_map_pr_state` / `_map_ci_status`) and persisted on+# ``TaskRun.output`` (``pr_state`` / ``ci_status``) for the task list filters.+PR_STATES = ("open", "draft", "merged", "closed")+CI_STATUSES = ("passing", "failing", "pending", "none")+SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG = "tasks-agent-proxy-keep-stream-open"MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 81edf5f64231..9a79569c3ef2 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -61,9 +61,11 @@ from posthog.utils import absolute_urifrom products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,+ CI_STATUSES as CI_STATUSES, # re-exported for presentationMAX_CUSTOM_IMAGES_PER_TEAM,MAX_CUSTOM_IMAGES_PER_USER,PI_CLOUD_RUNTIME_FEATURE_FLAG,+ PR_STATES as PR_STATES, # re-exported for presentationRESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,TASK_SESSION_MAX_SIZE_BYTES,get_required_model_flag,@@ -4620,6 +4622,67 @@ def _list_tasks_queryset(latest_run_status = latest_run.values("status")[:1]qs = qs.annotate(_latest_run_status=Subquery(latest_run_status)).filter(_latest_run_status=status_filter)+ # PR/CI state filters read the snapshot the PR webhook and the CI follow-up+ # loop persist onto the latest run's output (same latest-run subquery shape+ # as the status filter, so "the task's PR" means what the API's latest_run+ # shows). KeyTextTransform, so the comparison is text = text.+ pr_state = filters.get("pr_state")+ if pr_state:+ latest_run_pr_state = latest_run.annotate(_pr_state=KeyTextTransform("pr_state", "output")).values("_pr_state")[+ :1+ ]+ qs = qs.annotate(_latest_run_pr_state=Subquery(latest_run_pr_state))+ if pr_state == "merged":+ # Runs merged before pr_state existed only carry the older+ # pr_merged flag; honor both spellings.+ latest_run_pr_merged = latest_run.annotate(_pr_merged=KeyTextTransform("pr_merged", "output")).values(+ "_pr_merged"+ )[:1]+ qs = qs.annotate(_latest_run_pr_merged=Subquery(latest_run_pr_merged)).filter(+ Q(_latest_run_pr_state="merged") | Q(_latest_run_pr_merged="true")+ )+ else:+ qs = qs.filter(_latest_run_pr_state=pr_state)++ ci_status = filters.get("ci_status")+ if ci_status:+ latest_run_ci_status = latest_run.annotate(_ci_status=KeyTextTransform("ci_status", "output")).values(+ "_ci_status"+ )[:1]+ qs = qs.annotate(_latest_run_ci_status=Subquery(latest_run_ci_status)).filter(_latest_run_ci_status=ci_status)++ # Pins are per-user, so "pinned" means the requesting user's pins — and+ # without a user (service callers) nothing is pinned.+ if str(filters.get("pinned")).lower() == "true":+ if user_id is None:+ qs = qs.none()+ else:+ qs = qs.filter(Exists(TaskPin.objects.filter(task=OuterRef("pk"), user_id=user_id)))++ commented_by = filters.get("commented_by")+ if commented_by:+ qs = qs.filter(+ Exists(+ TaskThreadMessage.objects.for_team(team_id).filter(+ task=OuterRef("pk"),+ author_id=commented_by,+ author_kind=TaskThreadMessage.AuthorKind.HUMAN,+ )+ )+ )++ mentions = filters.get("mentions")+ if mentions:+ qs = qs.filter(+ Exists(+ TaskThreadMessageMention.objects.for_team(team_id)+ .filter(task=OuterRef("pk"), mentioned_user_id=mentions)+ # Same rule as list_mentions: legacy turn_complete rows are hidden+ # from threads, so their indexed mentions must not match either.+ .exclude(message__event="turn_complete")+ )+ )+# `internal` controls default visibility, not access — task visibility (applied above) is the real# authorization boundary, open to any team member. `all` returns both, `true` returns only-internal,# and the default excludes internal tasks so the main task list stays clean.diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 321aad4764db..b0d0cd764920 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2123,6 +2123,30 @@ class TaskRun(models.Model):return cls.mutate_state_atomic(run_id, _mutator)+ @classmethod+ def update_output_atomic(+ cls,+ run_id: str | uuid.UUID,+ *,+ updates: dict[str, Any],+ ) -> dict[str, Any]:+ """Merge output updates against the latest persisted row output.++ Output is written from several independent places (the agent server, the+ PR webhook backstop, the CI follow-up snapshot), so an unlocked+ read-modify-write could resurrect keys another writer already changed.+ Skips the save when nothing changes, so pollers don't churn ``updated_at``.+ """+ with transaction.atomic():+ locked_task_run = cls.objects.select_for_update().get(id=run_id)+ output = dict(locked_task_run.output or {})+ merged = {**output, **updates}+ if merged == output:+ return output+ locked_task_run.output = merged+ locked_task_run.save(update_fields=["output", "updated_at"])+ return merged+@classmethoddef clear_sandbox_connection_state_atomic(cls,diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex b869620445f5..db433b2433fb 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1513,6 +1513,34 @@ class TaskListQuerySerializer(serializers.Serializer):choices=[choice.value for choice in tasks_facade.TaskRunStatus],help_text="Filter tasks by the status of their most recent run.",)+ pr_state = serializers.ChoiceField(+ required=False,+ choices=list(tasks_facade.PR_STATES),+ help_text=(+ "Filter tasks by the state of their most recent run's pull request, as last observed "+ "from GitHub (webhooks plus the CI follow-up snapshot)."+ ),+ )+ ci_status = serializers.ChoiceField(+ required=False,+ choices=list(tasks_facade.CI_STATUSES),+ help_text=(+ "Filter tasks by the CI check rollup on their most recent run's pull request, as last "+ "observed from GitHub. 'none' means the PR has no checks."+ ),+ )+ pinned = serializers.BooleanField(+ required=False,+ help_text="With true, only tasks the requesting user has pinned.",+ )+ commented_by = serializers.IntegerField(+ required=False,+ help_text="Filter to tasks carrying a thread comment written by this user ID.",+ )+ mentions = serializers.IntegerField(+ required=False,+ help_text="Filter to tasks whose thread mentions this user ID.",+ )internal = serializers.ChoiceField(required=False,choices=["true", "false", "all"],diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.pyindex e3794ab4a4e6..18a3985b907e 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py@@ -12,6 +12,7 @@ from posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.common.utils import close_db_connections+from products.tasks.backend.constants import CI_STATUSES, PR_STATESfrom products.tasks.backend.exceptions import GitHubRateLimitedError, ProcessTaskTransientErrorfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.observability import log_activity_execution@@ -167,6 +168,22 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:cause=e,)+ # Persist the snapshot the CI loop just paid for, so the task list's+ # pr:/ci: filters read live state off the run's output instead of+ # needing their own GitHub round trips. Only canonical values land in+ # output, and best-effort: the follow-up decision must not fail+ # because a row write did.+ updates: dict[str, Any] = {}+ if pull_request.get("state") in PR_STATES:+ updates["pr_state"] = pull_request["state"]+ if pull_request.get("ci_status") in CI_STATUSES:+ updates["ci_status"] = pull_request["ci_status"]+ if updates:+ try:+ TaskRun.update_output_atomic(ctx.run_id, updates=updates)+ except Exception:+ activity.logger.warning("get_pr_context_snapshot_persist_failed", exc_info=True)+return GetPrContextOutput(pr_url=pr_url,pr_state=pull_request.get("state", "unknown"),diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.pyindex 853b768049b7..4574dc365292 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py@@ -185,6 +185,46 @@ class TestGetPrContextActivity:assert result.unresolved_threads == 1integration.get_pull_request_snapshot.assert_called_once_with(pr_url)+ @pytest.mark.django_db+ def test_persists_snapshot_state_to_run_output(self, test_task_run):+ pr_url = "https://github.com/org/repo/pull/42"+ test_task_run.output = {"pr_url": pr_url}+ test_task_run.save(update_fields=["output"])++ integration = MagicMock()+ integration.get_pull_request_snapshot.return_value = {+ "success": True,+ "url": pr_url,+ "state": "open",+ "ci_status": "failing",+ }++ ctx = self._ctx(run_id=str(test_task_run.id))+ with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):+ self._run(ctx)++ test_task_run.refresh_from_db()+ assert test_task_run.output["pr_state"] == "open"+ assert test_task_run.output["ci_status"] == "failing"+ assert test_task_run.output["pr_url"] == pr_url++ @pytest.mark.django_db+ def test_does_not_persist_unrecognized_snapshot_state(self, test_task_run):+ pr_url = "https://github.com/org/repo/pull/42"+ test_task_run.output = {"pr_url": pr_url}+ test_task_run.save(update_fields=["output"])++ integration = MagicMock()+ integration.get_pull_request_snapshot.return_value = {"success": True, "url": pr_url}++ ctx = self._ctx(run_id=str(test_task_run.id))+ with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):+ self._run(ctx)++ test_task_run.refresh_from_db()+ assert "pr_state" not in test_task_run.output+ assert "ci_status" not in test_task_run.output+@pytest.mark.django_dbdef test_uses_user_github_integration_for_user_credentials(self, test_task_run):pr_url = "https://github.com/org/repo/pull/42"diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 03b0ca735ce4..29d579f3cbc7 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -78,6 +78,8 @@ from products.tasks.backend.models import (TaskPin,TaskRun,TaskSession,+ TaskThreadMessage,+ TaskThreadMessageMention,)from products.tasks.backend.presentation.serializers import (TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,@@ -4227,6 +4229,164 @@ class TestTaskAPI(BaseTaskAPITest):response = self.client.get("/api/projects/@current/tasks/?status=not_a_real_status")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_filter_by_pr_state(self):+ open_pr = self.create_task("Open PR task")+ TaskRun.objects.create(+ task=open_pr,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/1", "pr_state": "open"},+ )++ merged_pr = self.create_task("Merged PR task")+ TaskRun.objects.create(+ task=merged_pr,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/2", "pr_state": "merged"},+ )++ # A run merged before pr_state existed carries only the legacy flag.+ legacy_merged = self.create_task("Legacy merged task")+ TaskRun.objects.create(+ task=legacy_merged,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/3", "pr_merged": True},+ )++ no_pr = self.create_task("No PR task")+ TaskRun.objects.create(task=no_pr, team=self.team, status=TaskRun.Status.COMPLETED)++ response = self.client.get("/api/projects/@current/tasks/?pr_state=open")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual({t["id"] for t in response.json()["results"]}, {str(open_pr.id)})++ response = self.client.get("/api/projects/@current/tasks/?pr_state=merged")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ {t["id"] for t in response.json()["results"]},+ {str(merged_pr.id), str(legacy_merged.id)},+ )++ def test_filter_by_ci_status(self):+ failing = self.create_task("Failing CI task")+ TaskRun.objects.create(+ task=failing,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/1", "ci_status": "failing"},+ )++ passing = self.create_task("Passing CI task")+ TaskRun.objects.create(+ task=passing,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/2", "ci_status": "passing"},+ )++ no_ci = self.create_task("No CI task")+ TaskRun.objects.create(task=no_ci, team=self.team, status=TaskRun.Status.COMPLETED)++ response = self.client.get("/api/projects/@current/tasks/?ci_status=failing")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual({t["id"] for t in response.json()["results"]}, {str(failing.id)})++ @parameterized.expand([("pr_state",), ("ci_status",)])+ def test_filter_by_pr_ci_rejects_unknown_value(self, param):+ response = self.client.get(f"/api/projects/@current/tasks/?{param}=sideways")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_filter_by_pinned_returns_only_own_pins(self):+ other_user = User.objects.create_user(email="[email protected]", first_name="Pinner", password="password")+ self.organization.members.add(other_user)++ mine = self.create_task("My pinned task")+ TaskPin.objects.create(user=self.user, task=mine)++ theirs = self.create_task("Their pinned task")+ TaskPin.objects.create(user=other_user, task=theirs)++ self.create_task("Unpinned task")++ response = self.client.get("/api/projects/@current/tasks/?pinned=true")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual({t["id"] for t in response.json()["results"]}, {str(mine.id)})++ def test_filter_by_commented_by_counts_human_comments_only(self):+ commented = self.create_task("Commented task")+ TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team, task=commented, author=self.user, content="looks good"+ )++ agent_only = self.create_task("Agent-comment task")+ TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=agent_only,+ author=self.user,+ author_kind=TaskThreadMessage.AuthorKind.AGENT,+ content="turn complete",+ )++ self.create_task("Silent task")++ response = self.client.get(f"/api/projects/@current/tasks/?commented_by={self.user.id}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual({t["id"] for t in response.json()["results"]}, {str(commented.id)})++ def test_filter_by_mentions(self):+ mentioned = self.create_task("Mentioned task")+ message = TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team, task=mentioned, author=self.user, content="cc @me"+ )+ TaskThreadMessageMention.objects.for_team(self.team.id).create(+ team=self.team, message=message, task=mentioned, mentioned_user=self.user+ )++ # A legacy turn_complete mention row must not surface the task.+ legacy = self.create_task("Legacy mention task")+ legacy_message = TaskThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ task=legacy,+ author=self.user,+ author_kind=TaskThreadMessage.AuthorKind.AGENT,+ event="turn_complete",+ content="done",+ )+ TaskThreadMessageMention.objects.for_team(self.team.id).create(+ team=self.team, message=legacy_message, task=legacy, mentioned_user=self.user+ )++ self.create_task("Unmentioned task")++ response = self.client.get(f"/api/projects/@current/tasks/?mentions={self.user.id}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual({t["id"] for t in response.json()["results"]}, {str(mentioned.id)})++ def test_filter_by_pr_state_uses_latest_run_not_any_run(self):+ """A task whose latest run has no PR state must not match an older run's state."""+ base_time = django_timezone.now()++ task = self.create_task("Task with mixed PR runs")+ TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ created_at=base_time,+ output={"pr_url": "https://github.com/posthog/posthog/pull/1", "pr_state": "open"},+ )+ TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ created_at=base_time + timedelta(seconds=1),+ )++ response = self.client.get("/api/projects/@current/tasks/?pr_state=open")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"], [])+def test_filter_by_status_uses_latest_run_not_any_run(self):"""A task whose latest run is in_progress must not match status=completed, even if an older run completed."""base_time = django_timezone.now()diff --git a/products/tasks/backend/tests/test_filter_matrix.py b/products/tasks/backend/tests/test_filter_matrix.pynew file mode 100644index 000000000000..aeae1bce5cb0--- /dev/null+++ b/products/tasks/backend/tests/test_filter_matrix.py@@ -0,0 +1,267 @@+import json+from typing import ClassVar++from django.test import TestCase++from parameterized import parameterized+from rest_framework import status as http_status+from rest_framework.test import APIClient++from posthog.models.organization import Organization+from posthog.models.team import Team+from posthog.models.user import User++from products.tasks.backend.models import Channel, Task, TaskPin, TaskRun, TaskThreadMessage, TaskThreadMessageMention+++class TestTaskListFilterMatrix(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ me: ClassVar[User]+ peter: ClassVar[User]+ adam: ClassVar[User]+ tasks: ClassVar[dict[str, Task]]+ channel: ClassVar[Channel]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Matrix Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Matrix Team")+ cls.me = User.objects.create_user(email="[email protected]", first_name="Me", password="password")+ cls.peter = User.objects.create_user(email="[email protected]", first_name="Peter", password="password")+ cls.adam = User.objects.create_user(email="[email protected]", first_name="Adam", password="password")+ for user in (cls.me, cls.peter, cls.adam):+ cls.organization.members.add(user)++ # Public, so the tasks are team-visible. A personal channel would hide+ # everyone else's tasks from the requester before any filter runs.+ def public_channel(name: str) -> Channel:+ return Channel.objects.unscoped().create(+ team=cls.team, name=name, channel_type=Channel.ChannelType.PUBLIC, created_by=cls.me+ )++ shared = public_channel("engineering")+ channel = public_channel("mobile")++ def task(+ key: str,+ *,+ created_by: User,+ title: str,+ origin: str = Task.OriginProduct.USER_CREATED,+ repository: str = "posthog/posthog",+ archived: bool = False,+ in_channel: bool = False,+ run_status: str | None = None,+ output: dict | None = None,+ ) -> Task:+ t = Task.objects.create(+ team=cls.team,+ created_by=created_by,+ title=title,+ description=f"{key} description",+ origin_product=origin,+ repository=repository,+ archived=archived,+ channel=channel if in_channel else shared,+ )+ if run_status is not None:+ TaskRun.objects.create(task=t, team=cls.team, status=run_status, output=output)+ return t++ def comment(task: Task, author: User, *, mentions: User | None = None, event: str = "") -> None:+ message = TaskThreadMessage.objects.for_team(cls.team.id).create(+ team=cls.team,+ task=task,+ author=author,+ author_kind=TaskThreadMessage.AuthorKind.AGENT if event else TaskThreadMessage.AuthorKind.HUMAN,+ event=event,+ content="seeded",+ )+ if mentions is not None:+ TaskThreadMessageMention.objects.for_team(cls.team.id).create(+ team=cls.team, message=message, task=task, mentioned_user=mentions+ )++ cls.tasks = {+ "peter_mention_me": task(+ "peter_mention_me",+ created_by=cls.peter,+ title="Fix billing address validation",+ run_status=TaskRun.Status.FAILED,+ output={+ "pr_url": "https://github.com/posthog/posthog/pull/1",+ "pr_state": "open",+ "ci_status": "failing",+ },+ ),+ "peter_plain": task(+ "peter_plain",+ created_by=cls.peter,+ title="Add billing period picker",+ run_status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/posthog/posthog/pull/2", "pr_state": "merged"},+ ),+ "peter_slack_mention_me": task(+ "peter_slack_mention_me",+ created_by=cls.peter,+ title="Slack-reported crash",+ origin=Task.OriginProduct.SLACK,+ run_status=TaskRun.Status.IN_PROGRESS,+ ),+ "adam_mention_peter": task(+ "adam_mention_peter",+ created_by=cls.adam,+ title="Push notification opt-in",+ run_status=TaskRun.Status.IN_PROGRESS,+ ),+ "mine_peter_commented": task(+ "mine_peter_commented",+ created_by=cls.me,+ title="Skeleton loading for feeds",+ run_status=TaskRun.Status.IN_PROGRESS,+ output={+ "pr_url": "https://github.com/posthog/posthog/pull/3",+ "pr_state": "draft",+ "ci_status": "passing",+ },+ ),+ "mine_archived": task("mine_archived", created_by=cls.me, title="Old spike", archived=True),+ "scout_in_channel": task(+ "scout_in_channel",+ created_by=cls.adam,+ title="Weekly anomaly sweep",+ origin=Task.OriginProduct.SIGNALS_SCOUT,+ repository="posthog/posthog.com",+ in_channel=True,+ run_status=TaskRun.Status.QUEUED,+ ),+ "peter_i_commented": task(+ "peter_i_commented",+ created_by=cls.peter,+ title="Remove artifacts tab",+ run_status=TaskRun.Status.COMPLETED,+ # Legacy merge: pr_merged flag, no pr_state.+ output={"pr_url": "https://github.com/posthog/posthog/pull/4", "pr_merged": True},+ ),+ "adam_pinned_by_me": task(+ "adam_pinned_by_me",+ created_by=cls.adam,+ title="Growth funnel dashboard",+ run_status=TaskRun.Status.CANCELLED,+ ),+ # Mentions me from a turn_complete row, which must not count.+ "peter_legacy_mention": task(+ "peter_legacy_mention",+ created_by=cls.peter,+ title="Dark mode for settings",+ run_status=TaskRun.Status.COMPLETED,+ ),+ }++ comment(cls.tasks["peter_mention_me"], cls.peter, mentions=cls.me)+ comment(cls.tasks["peter_slack_mention_me"], cls.peter, mentions=cls.me)+ comment(cls.tasks["adam_mention_peter"], cls.adam, mentions=cls.peter)+ comment(cls.tasks["mine_peter_commented"], cls.peter)+ comment(cls.tasks["peter_i_commented"], cls.me)+ comment(cls.tasks["peter_legacy_mention"], cls.peter, mentions=cls.me, event="turn_complete")+ TaskPin.objects.create(user=cls.peter, task=cls.tasks["peter_i_commented"])+ TaskPin.objects.create(user=cls.me, task=cls.tasks["adam_pinned_by_me"])+ cls.channel = channel++ def setUp(self):+ self.client = APIClient()+ self.client.force_login(self.me)++ def _list(self, **params) -> set[str]:+ response = self.client.get("/api/projects/@current/tasks/", params)+ assert response.status_code == http_status.HTTP_200_OK, json.dumps(response.json())+ return {t["id"] for t in response.json()["results"]}++ def _ids(self, *keys: str) -> set[str]:+ return {str(self.tasks[key].id) for key in keys}++ def all_except(self, *keys: str) -> set[str]:+ universe = {str(t.id) for k, t in self.tasks.items() if k != "mine_archived"}+ return universe - self._ids(*keys)++ def test_created_by(self):+ assert self._list(created_by=self.peter.id) == self._ids(+ "peter_mention_me", "peter_plain", "peter_slack_mention_me", "peter_i_commented", "peter_legacy_mention"+ )++ def test_mentions_counts_only_real_thread_mentions(self):+ assert self._list(mentions=self.me.id) == self._ids("peter_mention_me", "peter_slack_mention_me")+ assert self._list(mentions=self.peter.id) == self._ids("adam_mention_peter")++ def test_commented_by(self):+ assert self._list(commented_by=self.peter.id) == self._ids(+ "peter_mention_me", "peter_slack_mention_me", "mine_peter_commented"+ )+ assert self._list(commented_by=self.me.id) == self._ids("peter_i_commented")++ def test_pinned_is_the_requesters_pins(self):+ assert self._list(pinned="true") == self._ids("adam_pinned_by_me")++ def test_origin_product(self):+ assert self._list(origin_product="signals_scout") == self._ids("scout_in_channel")+ assert self._list(origin_product="slack") == self._ids("peter_slack_mention_me")++ @parameterized.expand(+ [+ ("failed", ["peter_mention_me"]),+ ("in_progress", ["peter_slack_mention_me", "adam_mention_peter", "mine_peter_commented"]),+ ("queued", ["scout_in_channel"]),+ ("cancelled", ["adam_pinned_by_me"]),+ ]+ )+ def test_status(self, value, expected):+ assert self._list(status=value) == self._ids(*expected)++ @parameterized.expand(+ [+ ("open", ["peter_mention_me"]),+ ("draft", ["mine_peter_commented"]),+ # merged matches pr_state plus the legacy pr_merged flag.+ ("merged", ["peter_plain", "peter_i_commented"]),+ ]+ )+ def test_pr_state(self, value, expected):+ assert self._list(pr_state=value) == self._ids(*expected)++ @parameterized.expand([("failing", ["peter_mention_me"]), ("passing", ["mine_peter_commented"])])+ def test_ci_status(self, value, expected):+ assert self._list(ci_status=value) == self._ids(*expected)++ def test_archived(self):+ assert self._list(archived="true") == self._ids("mine_archived")+ assert "mine_archived" not in {k for k in self.tasks if str(self.tasks[k].id) in self._list()}++ def test_channel_and_repository(self):+ assert self._list(channel=str(self.channel.id)) == self._ids("scout_in_channel")+ assert self._list(repository="posthog.com") == self._ids("scout_in_channel")++ def test_search(self):+ assert self._list(search="billing") == self._ids("peter_mention_me", "peter_plain")++ def test_mentions_me_by_peter_user_created(self):+ # The feed query `mentions:@me origin:user_created created-by:peter`.+ assert self._list(mentions=self.me.id, created_by=self.peter.id, origin_product="user_created") == self._ids(+ "peter_mention_me"+ )++ def test_created_by_and_status(self):+ assert self._list(created_by=self.peter.id, status="failed") == self._ids("peter_mention_me")++ def test_pinned_and_created_by(self):+ assert self._list(pinned="true", created_by=self.adam.id) == self._ids("adam_pinned_by_me")+ assert self._list(pinned="true", created_by=self.peter.id) == set()++ def test_commented_by_and_pr_state(self):+ assert self._list(commented_by=self.peter.id, pr_state="open") == self._ids("peter_mention_me")++ def test_search_and_mentions(self):+ assert self._list(search="billing", mentions=self.me.id) == self._ids("peter_mention_me")++ def test_status_and_ci(self):+ assert self._list(status="in_progress", ci_status="passing") == self._ids("mine_peter_commented")diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 4cec49c210d9..32cf9791d62a 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -487,6 +487,84 @@ class TestGitHubPRWebhook(TestCase):call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "pr_created")+ # The pr: task-list filter reads output.pr_state, so each state-changing+ # webhook action must land the canonical state on the run that claims the PR.+ @parameterized.expand(+ [+ ("opened", {"draft": False, "merged": False}, "open"),+ ("opened_as_draft", {"draft": True, "merged": False}, "draft"),+ ("converted_to_draft", {"merged": False}, "draft"),+ ("ready_for_review", {"merged": False}, "open"),+ ("reopened", {"draft": False, "merged": False}, "open"),+ ("closed", {"merged": False}, "closed"),+ ("closed", {"merged": True}, "merged"),+ ]+ )+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_action_records_pr_state(self, action_name, pr_fields, expected_state, _mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ action = "opened" if action_name == "opened_as_draft" else action_name++ payload = {+ "action": action,+ "pull_request": {+ "html_url": "https://github.com/posthog/posthog/pull/123",+ **pr_fields,+ },+ }++ response = self._make_webhook_request(payload)++ self.assertEqual(response.status_code, 200)+ self.task_run.refresh_from_db()+ assert self.task_run.output is not None+ self.assertEqual(self.task_run.output.get("pr_state"), expected_state)++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_state_only_action_records_state_without_analytics(self, mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret++ payload = {+ "action": "converted_to_draft",+ "pull_request": {+ "html_url": "https://github.com/posthog/posthog/pull/123",+ "merged": False,+ },+ }++ response = self._make_webhook_request(payload)++ self.assertEqual(response.status_code, 200)+ mock_capture.assert_not_called()+ self.task_run.refresh_from_db()+ assert self.task_run.output is not None+ self.assertEqual(self.task_run.output.get("pr_state"), "draft")++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_state_not_recorded_for_unclaimed_pr(self, _mock_capture, mock_get_secret):+ """A same-branch webhook for a different PR must not restate this run's PR."""+ mock_get_secret.return_value = self.webhook_secret++ payload = {+ "action": "closed",+ "pull_request": {+ "html_url": "https://github.com/posthog/posthog/pull/999",+ "merged": True,+ "head": {"ref": "other-branch"},+ },+ "repository": {"full_name": "posthog/posthog"},+ }++ response = self._make_webhook_request(payload)++ self.assertEqual(response.status_code, 200)+ self.task_run.refresh_from_db()+ assert self.task_run.output is not None+ self.assertNotIn("pr_state", self.task_run.output)+@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_branch_match(self, mock_capture, mock_get_secret):@@ -739,7 +817,7 @@ class TestGitHubPRWebhook(TestCase):"""Test that PR actions other than opened/closed are acknowledged but ignored."""mock_get_secret.return_value = self.webhook_secret- for action in ["edited", "reopened", "synchronize", "labeled"]:+ for action in ["edited", "synchronize", "labeled"]:payload = {"action": action,"pull_request": {diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 8c4e6a89bb10..f277d7591f31 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -153,6 +153,21 @@ def get_github_webhook_secret() -> str | None:return secret if secret else None+def _pr_state_for_action(action: str | None, pull_request: dict) -> str | None:+ """The ``output.pr_state`` a webhook action moves a run's PR to, in the+ same open/draft/merged/closed vocabulary the GitHub snapshot uses. None+ for actions that don't change the state (comments, labels, pushes)."""+ if action in ("opened", "reopened"):+ return "draft" if pull_request.get("draft") else "open"+ if action == "ready_for_review":+ return "open"+ if action == "converted_to_draft":+ return "draft"+ if action == "closed":+ return "merged" if pull_request.get("merged") else "closed"+ return None++def handle_pull_request_event(payload: dict) -> HttpResponse:"""Process a pre-verified pull_request webhook event.@@ -167,6 +182,8 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:logger.warning("github_pr_webhook_no_pr_url", action=action)return HttpResponse(status=200)+ pr_state = _pr_state_for_action(action, pull_request)+ analytics_event: str | None = Noneif action == "opened":event_action = "created"analytics_event = "pr_created"@@ -177,6 +194,11 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:else:event_action = "closed"analytics_event = "pr_closed"+ elif pr_state is not None:+ # A state-only transition (reopened, ready_for_review, converted_to_draft):+ # worth recording on the matched run so the pr: list filters stay honest,+ # not worth an analytics event.+ event_action = action or ""else:logger.debug("github_pr_webhook_ignored_action", action=action, pr_url=pr_url)return HttpResponse(status=200)@@ -220,9 +242,22 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:# fingerprint skips generation._enqueue_report_canvas_refresh(task_run)- # Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.- event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))- _capture_pr_event(payload, task_run, analytics_event, event_uuid)+ # After the backstop on purpose: a just-backfilled pr_url means the run now+ # claims this PR. Gated on the run's *primary* PR — output.pr_state describes+ # the PR the task APIs surface as output.pr_url, so a same-branch webhook for+ # a secondary or unrelated PR must not restate it.+ if (+ task_run is not None+ and pr_state is not None+ and isinstance(task_run.output, dict)+ and task_run.output.get("pr_url") == pr_url+ ):+ _record_run_pr_state(task_run, pr_state)++ if analytics_event is not None:+ # Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.+ event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))+ _capture_pr_event(payload, task_run, analytics_event, event_uuid)if task_run and action == "closed" and merged:# Only trust the merge for the run that actually claims this PR URL. The pr_url backstop@@ -367,6 +402,19 @@ def _append_run_pr_url(task_run: TaskRun, pr_url: str) -> bool:return False+def _record_run_pr_state(task_run: TaskRun, pr_state: str) -> None:+ """Persist ``output.pr_state`` on a state-changing PR webhook.++ Overwrites (a PR moves open → draft → merged), unlike the write-once+ ``_record_run_output_field``. Tolerant: a failure here must not fail the+ webhook (GitHub retries 5xx, and the event is already handled).+ """+ try:+ task_run.output = TaskRun.update_output_atomic(task_run.id, updates={"pr_state": pr_state})+ except Exception:+ logger.warning("github_pr_webhook_record_pr_state_failed", run_id=str(task_run.id), exc_info=True)++def _record_run_pr_merged(task_run: TaskRun) -> None:"""Persist ``output.pr_merged`` when the run's PR is merged.diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex d8d5568d329f..f3618f62c93f 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4330,6 +4330,20 @@ export type TasksListParams = {* Filter tasks to a channel's feed.*/channel?: string+ /**+ * Filter tasks by the CI check rollup on their most recent run's pull request, as last observed from GitHub. 'none' means the PR has no checks.+ *+ * * `passing` - passing+ * * `failing` - failing+ * * `pending` - pending+ * * `none` - none+ * @minLength 1+ */+ ci_status?: TasksListCiStatus+ /**+ * Filter to tasks carrying a thread comment written by this user ID.+ */+ commented_by?: number/*** Filter by creator user ID*/@@ -4349,6 +4363,10 @@ export type TasksListParams = {* @maximum 100*/limit?: number+ /**+ * Filter to tasks whose thread mentions this user ID.+ */+ mentions?: number/*** The initial index from which to return the results.* @minimum 0@@ -4372,6 +4390,20 @@ export type TasksListParams = {* @minLength 1*/origin_product?: string+ /**+ * With true, only tasks the requesting user has pinned.+ */+ pinned?: boolean+ /**+ * Filter tasks by the state of their most recent run's pull request, as last observed from GitHub (webhooks plus the CI follow-up snapshot).+ *+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * @minLength 1+ */+ pr_state?: TasksListPrState/*** Filter by repository name (can include org/repo format)* @minLength 1@@ -4408,6 +4440,15 @@ export const TasksListArchived = {All: 'all',} as const+export type TasksListCiStatus = (typeof TasksListCiStatus)[keyof typeof TasksListCiStatus]++export const TasksListCiStatus = {+ Passing: 'passing',+ Failing: 'failing',+ Pending: 'pending',+ None: 'none',+} as const+export type TasksListInternal = (typeof TasksListInternal)[keyof typeof TasksListInternal]export const TasksListInternal = {@@ -4423,6 +4464,15 @@ export const TasksListOrdering = {LastActivityAt: '-last_activity_at',} as const+export type TasksListPrState = (typeof TasksListPrState)[keyof typeof TasksListPrState]++export const TasksListPrState = {+ Open: 'open',+ Draft: 'draft',+ Merged: 'merged',+ Closed: 'closed',+} as const+export type TasksListStatus = (typeof TasksListStatus)[keyof typeof TasksListStatus]export const TasksListStatus = {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4efc74218ae1..a3b5c1b7982e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -92486,6 +92486,20 @@ export namespace Schemas {* Filter tasks to a channel's feed.*/channel?: string;+ /**+ * Filter tasks by the CI check rollup on their most recent run's pull request, as last observed from GitHub. 'none' means the PR has no checks.+ *+ * * `passing` - passing+ * * `failing` - failing+ * * `pending` - pending+ * * `none` - none+ * @minLength 1+ */+ ci_status?: TasksListCiStatus;+ /**+ * Filter to tasks carrying a thread comment written by this user ID.+ */+ commented_by?: number;/*** Filter by creator user ID*/@@ -92505,6 +92519,10 @@ export namespace Schemas {* @maximum 100*/limit?: number;+ /**+ * Filter to tasks whose thread mentions this user ID.+ */+ mentions?: number;/*** The initial index from which to return the results.* @minimum 0@@ -92528,6 +92546,20 @@ export namespace Schemas {* @minLength 1*/origin_product?: string;+ /**+ * With true, only tasks the requesting user has pinned.+ */+ pinned?: boolean;+ /**+ * Filter tasks by the state of their most recent run's pull request, as last observed from GitHub (webhooks plus the CI follow-up snapshot).+ *+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * @minLength 1+ */+ pr_state?: TasksListPrState;/*** Filter by repository name (can include org/repo format)* @minLength 1@@ -92565,6 +92597,16 @@ export namespace Schemas {All: 'all',} as const;+ export type TasksListCiStatus = typeof TasksListCiStatus[keyof typeof TasksListCiStatus];+++ export const TasksListCiStatus = {+ Passing: 'passing',+ Failing: 'failing',+ Pending: 'pending',+ None: 'none',+ } as const;+export type TasksListInternal = typeof TasksListInternal[keyof typeof TasksListInternal];@@ -92582,6 +92624,16 @@ export namespace Schemas {LastActivityAt: '-last_activity_at',} as const;+ export type TasksListPrState = typeof TasksListPrState[keyof typeof TasksListPrState];+++ export const TasksListPrState = {+ Open: 'open',+ Draft: 'draft',+ Merged: 'merged',+ Closed: 'closed',+ } as const;+export type TasksListStatus = typeof TasksListStatus[keyof typeof TasksListStatus];diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 2370d0fa590a..421654c62f4a 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -876,6 +876,16 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({"Filter by archived state. Defaults to excluding archived tasks. Use 'true' to list only archived tasks, 'false' for the default, or 'all' to include both.\n\n\* `true` - true\n\* `false` - false\n\* `all` - all"),channel: zod.string().optional().describe("Filter tasks to a channel's feed."),+ ci_status: zod+ .enum(['passing', 'failing', 'pending', 'none'])+ .optional()+ .describe(+ "Filter tasks by the CI check rollup on their most recent run's pull request, as last observed from GitHub. 'none' means the PR has no checks.\n\n\* `passing` - passing\n\* `failing` - failing\n\* `pending` - pending\n\* `none` - none"+ ),+ commented_by: zod+ .number()+ .optional()+ .describe('Filter to tasks carrying a thread comment written by this user ID.'),created_by: zod.number().optional().describe('Filter by creator user ID'),internal: zod.enum(['true', 'false', 'all'])@@ -889,6 +899,7 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({.max(tasksListQueryLimitMax).default(tasksListQueryLimitDefault).describe('Number of results to return per page.'),+ mentions: zod.number().optional().describe('Filter to tasks whose thread mentions this user ID.'),offset: zod.number().min(tasksListQueryOffsetMin)@@ -902,6 +913,13 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({),organization: zod.string().min(1).optional().describe('Filter by repository organization'),origin_product: zod.string().min(1).optional().describe('Filter by origin product'),+ pinned: zod.boolean().optional().describe('With true, only tasks the requesting user has pinned.'),+ pr_state: zod+ .enum(['open', 'draft', 'merged', 'closed'])+ .optional()+ .describe(+ "Filter tasks by the state of their most recent run's pull request, as last observed from GitHub (webhooks plus the CI follow-up snapshot).\n\n\* `open` - open\n\* `draft` - draft\n\* `merged` - merged\n\* `closed` - closed"+ ),repository: zod.string().min(1).optional().describe('Filter by repository name (can include org\/repo format)'),search: zod.string()diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 9cf37ea16e9a..40a9dcc56732 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -528,13 +528,18 @@ const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.Paall_team_tasks: params.all_team_tasks,archived: params.archived,channel: params.channel,+ ci_status: params.ci_status,+ commented_by: params.commented_by,created_by: params.created_by,internal: params.internal,limit: params.limit,+ mentions: params.mentions,offset: params.offset,ordering: params.ordering,organization: params.organization,origin_product: params.origin_product,+ pinned: params.pinned,+ pr_state: params.pr_state,repository: params.repository,search: params.search,stage: params.stage,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.jsonindex 7c9b20913592..b641f02d39fb 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json@@ -15,6 +15,15 @@"description": "Filter tasks to a channel's feed.","type": "string"},+ "ci_status": {+ "description": "Filter tasks by the CI check rollup on their most recent run's pull request, as last observed from GitHub. 'none' means the PR has no checks.\n\n* `passing` - passing\n* `failing` - failing\n* `pending` - pending\n* `none` - none",+ "enum": ["passing", "failing", "pending", "none"],+ "type": "string"+ },+ "commented_by": {+ "description": "Filter to tasks carrying a thread comment written by this user ID.",+ "type": "number"+ },"created_by": {"description": "Filter by creator user ID","type": "number"@@ -31,6 +40,10 @@"minimum": 1,"type": "number"},+ "mentions": {+ "description": "Filter to tasks whose thread mentions this user ID.",+ "type": "number"+ },"offset": {"default": 0,"description": "The initial index from which to return the results.",@@ -52,6 +65,15 @@"minLength": 1,"type": "string"},+ "pinned": {+ "description": "With true, only tasks the requesting user has pinned.",+ "type": "boolean"+ },+ "pr_state": {+ "description": "Filter tasks by the state of their most recent run's pull request, as last observed from GitHub (webhooks plus the CI follow-up snapshot).\n\n* `open` - open\n* `draft` - draft\n* `merged` - merged\n* `closed` - closed",+ "enum": ["open", "draft", "merged", "closed"],+ "type": "string"+ },"repository": {"description": "Filter by repository name (can include org/repo format)","minLength": 1,