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.

fix(tasks): improve home workstream grouping and tag quick actions (#62941)

Peter Kirkham5216a0c097c1
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 495f8747be5d..42cbfd3c594e 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -703,7 +703,7 @@ class GitHubIntegrationBase:
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
- number title url state isDraft mergeable updatedAt
+ number title url state isDraft mergeable updatedAt headRefName
author { login }
reviewDecision
reviewRequests(first: 50) {
@@ -857,6 +857,7 @@ class GitHubIntegrationBase:
"unresolved_threads": unresolved_threads,
"mergeable": self._map_mergeable(pr.get("mergeable")),
"author_login": author,
+ "head_branch": pr.get("headRefName"),
"requested_reviewer_logins": reviewer_logins,
"updated_at": pr.get("updatedAt"),
}
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 3d704c3e3e93..23d9dbfc2d36 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -1300,6 +1300,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
reasoning_effort = request.validated_data.get("reasoning_effort")
github_user_token = request.validated_data.get("github_user_token")
initial_permission_mode = request.validated_data.get("initial_permission_mode")
+ home_quick_action = request.validated_data.get("home_quick_action")
if run_source == RunSource.SIGNAL_REPORT:
pr_authorship_mode = PrAuthorshipMode.BOT
@@ -1317,6 +1318,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"provider": provider,
"model": model,
"reasoning_effort": reasoning_effort,
+ "home_quick_action": home_quick_action,
}.items():
if value is not None:
extra_state = extra_state or {}
diff --git a/products/tasks/backend/code_home_api.py b/products/tasks/backend/code_home_api.py
index 586f75025dc7..5edb815b3e51 100644
--- a/products/tasks/backend/code_home_api.py
+++ b/products/tasks/backend/code_home_api.py
@@ -133,6 +133,7 @@ class CodeHomeViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"status": t.get("status"),
"isGenerating": False,
"needsPermission": False,
+ "quickAction": t.get("quick_action"),
}
for t in (ws.tasks or [])
],
diff --git a/products/tasks/backend/code_workstreams/grouping.py b/products/tasks/backend/code_workstreams/grouping.py
index a1ce8e3d1bf4..56f0f26f4560 100644
--- a/products/tasks/backend/code_workstreams/grouping.py
+++ b/products/tasks/backend/code_workstreams/grouping.py
@@ -9,6 +9,12 @@ RUNNING_STATUSES = frozenset({"queued", "in_progress"})
RUNNING_STALE_THRESHOLD_MS = 30 * 60 * 1000
+# A normal PR is never headed from a repo's default branch, so these are always treated as base
+# branches when resolving a run to a PR by branch (see build_workstreams). If this ever needs to
+# cover non-standard defaults, derive the branch from the GitHub integration rather than growing
+# this set.
+DEFAULT_BASE_BRANCHES = frozenset({"master", "main"})
+
@dataclass
class TaskInput:
@@ -19,8 +25,10 @@ class TaskInput:
repo_name: Optional[str] = None
repo_full_path: Optional[str] = None
branch: Optional[str] = None
+ base_branch: Optional[str] = None
cloud_pr_url: Optional[str] = None
folder_path: Optional[str] = None
+ quick_action: Optional[str] = None
@dataclass
@@ -37,6 +45,7 @@ class PrInput:
is_current_user_author: bool
author: Optional[str]
last_updated_at: int
+ head_branch: Optional[str] = None
@dataclass
@@ -44,6 +53,7 @@ class WorkstreamTask:
id: str
title: str
status: Optional[str]
+ quick_action: Optional[str] = None
@dataclass
@@ -77,11 +87,21 @@ def _is_actively_running(task: TaskInput, now: int, has_pr: bool) -> bool:
return now - task.last_activity_at <= RUNNING_STALE_THRESHOLD_MS
+def _feature_branch(task: TaskInput) -> Optional[str]:
+ # `TaskRun.branch` starts as the run's base branch (e.g. "master") and is only synced to a
+ # real feature branch once the agent pushes one. Grouping on the base branch would collapse
+ # every no-PR run that never pushed into one blob, so only treat a distinct branch as real.
+ branch = task.branch
+ if branch and branch != task.base_branch:
+ return branch
+ return None
+
+
def workstream_key(task: TaskInput, pr_url: Optional[str]) -> Optional[str]:
if pr_url:
return f"pr:{pr_url}"
repo = task.repo_full_path or task.repo_name
- branch = task.branch
+ branch = _feature_branch(task)
if repo and branch:
return f"branch:{repo}#{branch}"
if task.folder_path:
@@ -89,13 +109,39 @@ def workstream_key(task: TaskInput, pr_url: Optional[str]) -> Optional[str]:
return None
+def branch_lookup_key(repo: Optional[str], branch: Optional[str]) -> Optional[tuple[str, str]]:
+ if repo and branch:
+ return (repo.casefold(), branch)
+ return None
+
+
def build_workstreams(
tasks: list[TaskInput],
pr_by_task: Mapping[str, PrInput],
now: int,
+ pr_by_branch: Optional[Mapping[tuple[str, str], PrInput]] = None,
) -> WorkstreamsResult:
+ # A run sitting on a base branch must not resolve to whatever PR is headed from it. A branch is
+ # a base branch if some sibling task uses it as a base while on a *different* branch, or if it's
+ # a conventional default (folded in so a *lone* base-branch run, with no sibling to mark it, is
+ # still caught). A feature-branch follow-up has branch == base_branch, so it is never flagged
+ # and still resolves — real feature branches are never named like the defaults.
+ base_branches = {
+ t.base_branch for t in tasks if t.base_branch and t.base_branch != t.branch
+ } | DEFAULT_BASE_BRANCHES
+
def pr_of(task: TaskInput) -> Optional[PrInput]:
- return pr_by_task.get(task.id)
+ # A task's own PR wins; otherwise resolve via the branch it ran on so a
+ # follow-up run (e.g. "Fix CI") that pushed to an open PR's branch but
+ # never recorded a pr_url still groups under that PR's workstream.
+ own = pr_by_task.get(task.id)
+ if own is not None:
+ return own
+ if pr_by_branch and task.branch not in base_branches:
+ key = branch_lookup_key(task.repo_full_path or task.repo_name, task.branch)
+ if key is not None:
+ return pr_by_branch.get(key)
+ return None
def pr_url_of(task: TaskInput) -> Optional[str]:
snap = pr_of(task)
@@ -131,7 +177,7 @@ def build_workstreams(
pr_url = url
break
- branch = head.branch
+ branch = _feature_branch(head)
last_activity_at = head.last_activity_at
situations = sorted(
@@ -153,7 +199,10 @@ def build_workstreams(
branch=branch,
pr_url=pr_url,
pr=pr,
- tasks=[WorkstreamTask(id=t.id, title=t.title, status=t.status) for t in group_tasks],
+ tasks=[
+ WorkstreamTask(id=t.id, title=t.title, status=t.status, quick_action=t.quick_action)
+ for t in group_tasks
+ ],
situations=situations,
last_activity_at=last_activity_at,
)
diff --git a/products/tasks/backend/code_workstreams/test_grouping.py b/products/tasks/backend/code_workstreams/test_grouping.py
index ac83f2ca3c16..c1221ad3653c 100644
--- a/products/tasks/backend/code_workstreams/test_grouping.py
+++ b/products/tasks/backend/code_workstreams/test_grouping.py
@@ -63,6 +63,12 @@ def _pr(**overrides) -> PrInput:
(_task(branch="b", repo_name="r", repo_full_path=None, folder_path="/p"), None, "branch:r#b"),
(_task(branch=None, repo_name=None, repo_full_path=None, folder_path="/p"), None, "path:/p"),
(_task(branch=None, repo_name=None, repo_full_path=None, folder_path=None), None, None),
+ # Branch equal to the base branch is not a real feature branch: don't group on it.
+ (_task(branch="master", base_branch="master", folder_path=None), None, None),
+ (_task(branch="master", base_branch="master", folder_path="/p"), None, "path:/p"),
+ (_task(branch="master", base_branch="master"), "https://x/pull/9", "pr:https://x/pull/9"),
+ # A branch distinct from the base branch still groups.
+ (_task(branch="feat/x", base_branch="master", repo_full_path="org/r"), None, "branch:org/r#feat/x"),
],
)
def test_workstream_key_precedence(task, pr_url, expected):
@@ -128,3 +134,113 @@ def test_task_without_grouping_key_is_skipped():
result = build_workstreams([task], {}, NOW)
assert not result.needs_attention
assert not result.in_progress
+
+
+def test_base_branch_no_pr_tasks_do_not_collapse_and_are_dropped():
+ # Tasks that ran on the base branch and never pushed a feature branch or PR left no real
+ # work to track, so they must neither collapse into one blob nor surface as workstreams.
+ t1 = _task(id="a", branch="master", base_branch="master", cloud_pr_url=None)
+ t2 = _task(id="b", branch="master", base_branch="master", cloud_pr_url=None)
+ result = build_workstreams([t1, t2], {}, NOW)
+ assert not result.needs_attention
+ assert not result.in_progress
+
+
+def test_tasks_group_by_shared_feature_branch():
+ t1 = _task(id="a", branch="feat/x", base_branch="master", last_activity_at=NOW)
+ t2 = _task(id="b", branch="feat/x", base_branch="master", last_activity_at=NOW - 1000)
+ result = build_workstreams([t1, t2], {}, NOW)
+ workstreams = result.needs_attention + result.in_progress
+ assert len(workstreams) == 1
+ assert {t.id for t in workstreams[0].tasks} == {"a", "b"}
+ assert workstreams[0].branch == "feat/x"
+
+
+def test_feature_branch_and_base_branch_tasks_do_not_merge():
+ feature = _task(id="a", branch="feat/x", base_branch="master", cloud_pr_url=None)
+ base = _task(id="b", branch="master", base_branch="master", cloud_pr_url=None)
+ result = build_workstreams([feature, base], {}, NOW)
+ workstreams = result.needs_attention + result.in_progress
+ assert len(workstreams) == 1
+ assert {t.id for t in workstreams[0].tasks} == {"a"}
+
+
+def test_follow_up_task_resolves_to_pr_by_branch():
+ # A follow-up run pushed to the PR's branch (branch == base, no own pr_url); it should still
+ # group under the PR workstream via the branch→PR map and inherit its situation.
+ url = "https://github.com/posthog/posthog/pull/7"
+ follow_up = _task(
+ id="b",
+ repo_full_path="posthog/posthog",
+ branch="feat/x",
+ base_branch="feat/x",
+ cloud_pr_url=None,
+ )
+ pr_by_branch = {("posthog/posthog", "feat/x"): _pr(url=url, ci_status="failing", head_branch="feat/x")}
+ result = build_workstreams([follow_up], {}, NOW, pr_by_branch)
+ assert len(result.needs_attention) == 1
+ ws = result.needs_attention[0]
+ assert ws.id == f"pr:{url}"
+ assert "ci_failing" in ws.situations
+
+
+def test_follow_up_task_groups_with_original_pr_task():
+ url = "https://github.com/posthog/posthog/pull/7"
+ original = _task(id="a", repo_full_path="posthog/posthog", branch="feat/x", cloud_pr_url=url)
+ follow_up = _task(
+ id="b",
+ repo_full_path="posthog/posthog",
+ branch="feat/x",
+ base_branch="feat/x",
+ cloud_pr_url=None,
+ )
+ pr_by_branch = {("posthog/posthog", "feat/x"): _pr(url=url, head_branch="feat/x")}
+ result = build_workstreams([original, follow_up], {original.id: _pr(url=url)}, NOW, pr_by_branch)
+ workstreams = result.needs_attention + result.in_progress
+ assert len(workstreams) == 1
+ assert {t.id for t in workstreams[0].tasks} == {"a", "b"}
+
+
+def test_branch_resolution_is_repo_scoped():
+ # A branch named "main" in one repo must not pull in a PR for "main" in another repo.
+ url = "https://github.com/posthog/other/pull/1"
+ task = _task(id="a", repo_full_path="posthog/posthog", branch="main", base_branch="main", cloud_pr_url=None)
+ pr_by_branch = {("posthog/other", "main"): _pr(url=url, head_branch="main")}
+ result = build_workstreams([task], {}, NOW, pr_by_branch)
+ workstreams = result.needs_attention + result.in_progress
+ assert not workstreams
+
+
+def test_base_branch_task_does_not_resolve_to_base_headed_pr():
+ # A no-op run on the base branch must not collapse into a PR that happens to be headed from
+ # that base branch, while a real feature-branch follow-up still resolves.
+ feature = _task(id="a", repo_full_path="posthog/posthog", branch="feat/x", base_branch="master", cloud_pr_url=None)
+ base = _task(id="b", repo_full_path="posthog/posthog", branch="master", base_branch="master", cloud_pr_url=None)
+ pr_by_branch = {
+ ("posthog/posthog", "feat/x"): _pr(url="https://github.com/posthog/posthog/pull/1", head_branch="feat/x"),
+ ("posthog/posthog", "master"): _pr(url="https://github.com/posthog/posthog/pull/2", head_branch="master"),
+ }
+ result = build_workstreams([feature, base], {}, NOW, pr_by_branch)
+ workstreams = result.needs_attention + result.in_progress
+ assert len(workstreams) == 1
+ assert workstreams[0].id == "pr:https://github.com/posthog/posthog/pull/1"
+ assert {t.id for t in workstreams[0].tasks} == {"a"}
+
+
+def test_lone_base_branch_task_does_not_resolve_to_base_headed_pr():
+ # Even with no sibling feature task to mark "master" a base branch, a lone run on the default
+ # branch must not collapse into a PR that happens to be headed from "master".
+ task = _task(id="a", repo_full_path="posthog/posthog", branch="master", base_branch="master", cloud_pr_url=None)
+ pr_by_branch = {
+ ("posthog/posthog", "master"): _pr(url="https://github.com/posthog/posthog/pull/2", head_branch="master")
+ }
+ result = build_workstreams([task], {}, NOW, pr_by_branch)
+ workstreams = result.needs_attention + result.in_progress
+ assert not workstreams
+
+
+def test_quick_action_is_carried_onto_workstream_task():
+ task = _task(id="a", quick_action="Fix CI")
+ result = build_workstreams([task], {task.id: _pr(ci_status="failing")}, NOW)
+ ws = result.needs_attention[0]
+ assert ws.tasks[0].quick_action == "Fix CI"
diff --git a/products/tasks/backend/migrations/0039_codeprsnapshot_head_branch.py b/products/tasks/backend/migrations/0039_codeprsnapshot_head_branch.py
new file mode 100644
index 000000000000..942f948cc2d1
--- /dev/null
+++ b/products/tasks/backend/migrations/0039_codeprsnapshot_head_branch.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0038_task_origin_product_conversations_support"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="codeprsnapshot",
+ name="head_branch",
+ field=models.CharField(
+ blank=True,
+ null=True,
+ max_length=255,
+ help_text="PR head (source) branch, used to group follow-up task runs under this PR's workstream",
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index b71f7634fd25..fc8df184e26c 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0038_task_origin_product_conversations_support
+0039_codeprsnapshot_head_branch
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 48b92f2e9740..02dd3eb3b44e 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1501,6 +1501,12 @@ class CodePrSnapshot(TeamScopedRootMixin):
unresolved_threads = models.PositiveIntegerField(default=0)
mergeable = models.BooleanField(null=True, blank=True)
author_login = models.CharField(max_length=255, null=True, blank=True)
+ head_branch = models.CharField(
+ max_length=255,
+ null=True,
+ blank=True,
+ help_text="PR head (source) branch, used to group follow-up task runs under this PR's workstream",
+ )
requested_reviewer_logins = models.JSONField(default=list, help_text="GitHub logins requested as reviewers")
pr_updated_at = models.DateTimeField(null=True, blank=True, help_text="PR's last-updated time on GitHub")
fingerprint = models.CharField(max_length=64, blank=True, default="", help_text="Change-detection hash")
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.py
index 60c6330ebe72..e2e7a8b8031c 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -1198,6 +1198,13 @@ class TaskRunBootstrapCreateRequestSerializer(serializers.Serializer):
"'read-only'."
),
)
+ home_quick_action = serializers.CharField(
+ required=False,
+ default=None,
+ allow_blank=False,
+ max_length=120,
+ help_text="Label of the Home-tab quick action that started this run (e.g. 'Fix CI'), surfaced on the workstream.",
+ )
def validate(self, attrs):
errors: dict[str, str] = {}
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
index 63a1e86575af..debe36715439 100644
--- a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
+++ b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
@@ -129,6 +129,7 @@ def poll_pull_requests_for_team(
"unresolved_threads": snap.get("unresolved_threads") or 0,
"mergeable": snap.get("mergeable"),
"author_login": snap.get("author_login"),
+ "head_branch": snap.get("head_branch"),
"requested_reviewer_logins": snap.get("requested_reviewer_logins") or [],
"pr_updated_at": parse_datetime(snap["updated_at"]) if snap.get("updated_at") else None,
"fingerprint": fingerprint,
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
index 1cf82f2dc144..252037c0d395 100644
--- a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
+++ b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
@@ -3,7 +3,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Optional
-from django.db.models import Max
+from django.db.models import Max, Q
from django.utils import timezone
from temporalio import activity
@@ -13,9 +13,16 @@ from posthog.models.user_integration import UserIntegration
from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.code_workstreams.classify import pick_primary_situation
-from products.tasks.backend.code_workstreams.grouping import PrInput, TaskInput, Workstream, build_workstreams
+from products.tasks.backend.code_workstreams.grouping import (
+ PrInput,
+ TaskInput,
+ Workstream,
+ branch_lookup_key,
+ build_workstreams,
+)
from products.tasks.backend.models import CodePrSnapshot, CodeWorkstream, Task, TaskRun
from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOW, MAX_TASKS_PER_TEAM
+from products.tasks.backend.temporal.process_task.utils import parse_run_state
@dataclass
@@ -52,6 +59,7 @@ def _task_to_input(task: Task) -> tuple[TaskInput, Optional[str]]:
run: Optional[TaskRun] = task.latest_run
last_activity = run.updated_at if run else task.updated_at
cloud_pr_url = _pr_url_from_run(run)
+ state = parse_run_state(run.state if run else None)
return (
TaskInput(
id=str(task.id),
@@ -61,8 +69,10 @@ def _task_to_input(task: Task) -> tuple[TaskInput, Optional[str]]:
repo_name=_repo_name(task.repository),
repo_full_path=task.repository,
branch=run.branch if run else None,
+ base_branch=state.pr_base_branch,
cloud_pr_url=cloud_pr_url,
folder_path=None,
+ quick_action=state.home_quick_action,
),
cloud_pr_url,
)
@@ -101,9 +111,31 @@ def _build_pr_input(snapshot: CodePrSnapshot, user_github_logins: set[str]) -> P
is_current_user_author=bool(author and author in user_github_logins),
author=author,
last_updated_at=_epoch_ms(snapshot.pr_updated_at) if snapshot.pr_updated_at else 0,
+ head_branch=snapshot.head_branch,
)
+def _branch_resolution_pref(snapshot: CodePrSnapshot) -> tuple[int, float, str]:
+ # Order so the best snapshot for a (repo, head_branch) collision is written last (last wins):
+ # prefer still-open PRs over merged/closed (a reused branch's new PR beats the stale one),
+ # then the most recently updated, with pr_url as a stable final tiebreaker.
+ open_score = 1 if snapshot.state in ("open", "draft") else 0
+ updated = snapshot.pr_updated_at.timestamp() if snapshot.pr_updated_at else 0.0
+ return (open_score, updated, snapshot.pr_url)
+
+
+def _repo_from_pr_url(pr_url: str) -> Optional[str]:
+ # https://<host>/<owner>/<repo>/pull/<n> -> "<owner>/<repo>" (host-agnostic, covers enterprise).
+ idx = pr_url.find("/pull/")
+ if idx == -1:
+ return None
+ segments = [s for s in pr_url[:idx].split("/") if s]
+ if len(segments) < 2:
+ return None
+ owner, repo = segments[-2], segments[-1]
+ return f"{owner}/{repo}"
+
+
def _github_logins_by_user(user_ids: list[int]) -> dict[int, set[str]]:
logins: dict[int, set[str]] = defaultdict(set)
for user_id, config in UserIntegration.objects.filter(user_id__in=user_ids, kind="github").values_list(
@@ -139,13 +171,19 @@ def rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamW
by_user: dict[int, list[Task]] = defaultdict(list)
needed_pr_urls: set[str] = set()
+ needed_branches: set[str] = set()
for task in tasks:
if task.created_by_id is None:
continue
by_user[task.created_by_id].append(task)
- pr_url = _pr_url_from_run(task.latest_run)
+ run = task.latest_run
+ pr_url = _pr_url_from_run(run)
if pr_url:
needed_pr_urls.add(pr_url)
+ # The branch a run actually worked on lets us link follow-up runs (no pr_url of
+ # their own) to the open PR for that branch.
+ if run and run.branch:
+ needed_branches.add(run.branch)
github_logins_by_user = _github_logins_by_user(list(by_user.keys()))
@@ -154,15 +192,22 @@ def rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamW
with team_scope(input.team_id):
# Only load snapshots we will actually look up, so memory stays bounded by recent tasks
- # rather than the team's all-time snapshot count.
- snapshots_by_url = {
- s.pr_url: s for s in CodePrSnapshot.objects.filter(team_id=input.team_id, pr_url__in=needed_pr_urls)
- }
+ # rather than the team's all-time snapshot count. We also pull snapshots whose head
+ # branch matches a run's branch so branch-resolved grouping can find them.
+ snapshots = list(
+ CodePrSnapshot.objects.filter(team_id=input.team_id).filter(
+ Q(pr_url__in=needed_pr_urls) | Q(head_branch__in=needed_branches)
+ )
+ )
+ snapshots_by_url = {s.pr_url: s for s in snapshots}
+ # Sorted so a (repo, head_branch) collision resolves deterministically (best wins last).
+ snapshots_by_branch = sorted((s for s in snapshots if s.head_branch), key=_branch_resolution_pref)
for user_id, user_tasks in by_user.items():
user_github_logins = github_logins_by_user.get(user_id, set())
task_inputs: list[TaskInput] = []
pr_by_task: dict[str, PrInput] = {}
+ pr_by_branch: dict[tuple[str, str], PrInput] = {}
snapshot_id_by_url: dict[str, str] = {}
for task in user_tasks:
task_input, pr_url = _task_to_input(task)
@@ -172,7 +217,16 @@ def rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamW
pr_by_task[task_input.id] = _build_pr_input(snapshot, user_github_logins)
snapshot_id_by_url[pr_url] = str(snapshot.id)
- result = build_workstreams(task_inputs, pr_by_task, now_ms)
+ # is_current_user_author depends on the user, so the branch map is built per user.
+ for snapshot in snapshots_by_branch:
+ repo = _repo_from_pr_url(snapshot.pr_url)
+ key = branch_lookup_key(repo, snapshot.head_branch)
+ if key is None:
+ continue
+ pr_by_branch[key] = _build_pr_input(snapshot, user_github_logins)
+ snapshot_id_by_url[snapshot.pr_url] = str(snapshot.id)
+
+ result = build_workstreams(task_inputs, pr_by_task, now_ms, pr_by_branch)
live_keys: set[str] = set()
for state, workstreams in (
(CodeWorkstream.WorkstreamState.ATTENTION, result.needs_attention),
@@ -219,7 +273,9 @@ def _persist_workstream(
"situations": list(ws.situations),
"primary_situation": pick_primary_situation(ws.situations),
"state": state,
- "tasks": [{"id": t.id, "title": t.title, "status": t.status} for t in ws.tasks],
+ "tasks": [
+ {"id": t.id, "title": t.title, "status": t.status, "quick_action": t.quick_action} for t in ws.tasks
+ ],
"last_activity_at": _from_epoch_ms(ws.last_activity_at),
"generated_at": generated_at,
},
diff --git a/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py
index 7408ce7276df..b7f23e009c20 100644
--- a/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py
+++ b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py
@@ -1,7 +1,14 @@
+from datetime import UTC, datetime
+
import pytest
from products.tasks.backend.models import CodePrSnapshot
-from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import _build_pr_input
+from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import (
+ _branch_resolution_pref,
+ _build_pr_input,
+ _repo_from_pr_url,
+)
+from products.tasks.backend.temporal.process_task.utils import parse_run_state
def _snapshot(**overrides) -> CodePrSnapshot:
@@ -22,6 +29,62 @@ def _snapshot(**overrides) -> CodePrSnapshot:
return CodePrSnapshot(**defaults)
+ "state,expected",
+ [
+ ({"pr_base_branch": "master"}, "master"),
+ ({"pr_base_branch": "main", "mode": "background"}, "main"),
+ ({"mode": "background"}, None),
+ ({}, None),
+ (None, None),
+ ],
+)
+def test_parse_run_state_reads_pr_base_branch(state, expected):
+ assert parse_run_state(state).pr_base_branch == expected
+
+
+ "pr_url,expected",
+ [
+ ("https://github.com/posthog/posthog/pull/123", "posthog/posthog"),
+ ("https://github.com/owner/repo/pull/1", "owner/repo"),
+ ("https://github.enterprise.com/posthog/posthog/pull/9", "posthog/posthog"),
+ ("not-a-url", None),
+ ("https://github.com/onlyowner", None),
+ ],
+)
+def test_repo_from_pr_url(pr_url, expected):
+ assert _repo_from_pr_url(pr_url) == expected
+
+
+def test_build_pr_input_carries_head_branch():
+ pr = _build_pr_input(_snapshot(head_branch="feat/x"), set())
+ assert pr.head_branch == "feat/x"
+
+
+def test_branch_resolution_pref_prefers_open_then_recent():
+ old = datetime(2026, 1, 1, tzinfo=UTC)
+ new = datetime(2026, 6, 1, tzinfo=UTC)
+ closed_new = _snapshot(pr_url="c", state="closed", pr_updated_at=new)
+ open_old = _snapshot(pr_url="a", state="open", pr_updated_at=old)
+ open_new = _snapshot(pr_url="b", state="open", pr_updated_at=new)
+ # Sorting ascending puts the winner last (last-wins when building the map).
+ winner = sorted([closed_new, open_old, open_new], key=_branch_resolution_pref)[-1]
+ assert winner.pr_url == "b"
+
+
+ "state,expected",
+ [
+ ({"home_quick_action": "Fix CI"}, "Fix CI"),
+ ({"mode": "background"}, None),
+ (None, None),
+ ],
+)
+def test_parse_run_state_reads_home_quick_action(state, expected):
+ assert parse_run_state(state).home_quick_action == expected
+
+
@pytest.mark.parametrize(
"author_login,user_github_logins,expected",
[
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index a2edb51b861d..3114a2512330 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -185,6 +185,7 @@ class RunState(BaseModel, extra="allow"):
pr_authorship_mode: PrAuthorshipMode | None = None
github_credential_source: GitHubCredentialSource | None = None
pr_base_branch: str | None = None
+ home_quick_action: str | None = None
run_source: RunSource | None = None
signal_report_id: str | None = None
runtime_adapter: RuntimeAdapter | None = None
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index b9efe62f49cf..c7b9875dc59a 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1129,6 +1129,11 @@ export interface TaskRunBootstrapCreateRequestApi {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi
+ /**
+ * Label of the Home-tab quick action that started this run (e.g. 'Fix CI'), surfaced on the workstream.
+ * @maxLength 120
+ */
+ home_quick_action?: string
}
/**
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 7d090faf20ba..d6c3082caeea 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -735,6 +735,8 @@ export const tasksRunsCreateBodyEnvironmentDefault = `local`
export const tasksRunsCreateBodyModeDefault = `background`
export const tasksRunsCreateBodyBranchMax = 255
+export const tasksRunsCreateBodyHomeQuickActionMax = 120
+
export const TasksRunsCreateBody = /* @__PURE__ */ zod
.object({
environment: zod
@@ -806,6 +808,13 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod
.describe(
"Initial permission mode for the agent session. Claude runtimes accept PostHog permission presets like 'plan'. Codex runtimes accept native Codex modes like 'auto' and 'read-only'.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access"
),
+ home_quick_action: zod
+ .string()
+ .max(tasksRunsCreateBodyHomeQuickActionMax)
+ .optional()
+ .describe(
+ "Label of the Home-tab quick action that started this run (e.g. 'Fix CI'), surfaced on the workstream."
+ ),
})
.describe('Request body for creating a task run without starting execution yet.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e889958ee878..721830aed0a4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -48367,6 +48367,11 @@ export namespace Schemas {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum;
+ /**
+ * Label of the Home-tab quick action that started this run (e.g. 'Fix CI'), surfaced on the workstream.
+ * @maxLength 120
+ */
+ home_quick_action?: string;
}
/**