: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
fix(tasks): show pull request titles in the space feed (#110030)
Shy Alter298a3047ba41
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 387e82cfc10f..941657157737 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -6244,6 +6244,14 @@ def task_review(team_id: int, task_id: str, user_id: int, page: int) -> dict:return build_task_review(team_id, task_id, user_id, page)+def get_pull_request_titles(team_id: int, user_id: int, task_ids: list[UUID]) -> dict[str, str]:+ from products.tasks.backend.logic.pull_request_titles import ( # noqa: PLC0415 — keep GitHub integration deps off the api import path+ pull_request_titles,+ )++ return pull_request_titles(team_id, user_id, task_ids)++def get_task_detail(task_id: str | UUID, team_id: int, user_id: int | None, *, bypass_visibility: bool = False) -> contracts.TaskDetailDTO | None:diff --git a/products/tasks/backend/logic/pull_request_titles.py b/products/tasks/backend/logic/pull_request_titles.pynew file mode 100644index 000000000000..f43743b53971--- /dev/null+++ b/products/tasks/backend/logic/pull_request_titles.py@@ -0,0 +1,124 @@+from uuid import UUID++from django.core.cache import cache++import structlog++from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.models.github_integration_base import GitHubIntegrationError, PullRequestRef+from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.user_integration import UserGitHubIntegration++from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.pr_urls import read_pr_urls+from products.tasks.backend.visibility import task_visibility_q++logger = structlog.get_logger(__name__)++_MAX_PULL_REQUESTS = 50+_CACHE_TTL_SECONDS = 60 * 60+++def _cache_key(team_id: int, url: str) -> str:+ return f"tasks:pr_title:{team_id}:{url}"+++def _pull_request_url(ref: PullRequestRef) -> str:+ return f"https://github.com/{ref.repository}/pull/{ref.number}"+++def _fetch_titles(github: GitHubIntegration | UserGitHubIntegration, refs: list[PullRequestRef]) -> dict[str, str]:+ declarations: list[str] = []+ fields: list[str] = []+ variables: dict[str, str | int] = {}+ for index, ref in enumerate(refs):+ declarations.append(f"$owner{index}: String!, $repo{index}: String!, $number{index}: Int!")+ fields.append(+ f"pr{index}: repository(owner: $owner{index}, name: $repo{index}) "+ f"{{ pullRequest(number: $number{index}) {{ title }} }}"+ )+ variables.update({f"owner{index}": ref.owner, f"repo{index}": ref.repo, f"number{index}": ref.number})+ query = f"query({', '.join(declarations)}) {{ {' '.join(fields)} }}"+ data = github._gh_graphql(query, variables, endpoint="/graphql:pullRequestTitles")+ titles: dict[str, str] = {}+ for index, ref in enumerate(refs):+ pull_request = (data.get(f"pr{index}") or {}).get("pullRequest") or {}+ titles[_pull_request_url(ref)] = pull_request.get("title") or ""+ return titles+++def _integration_key(task: Task, user_id: int) -> tuple[str, int | str]:+ user_integration = task.github_user_integration+ if user_integration is not None and user_integration.user_id == user_id:+ return ("user", str(user_integration.id))+ return ("team", task.github_integration_id or 0)+++def _github_for_task(task: Task, team_id: int, user_id: int) -> GitHubIntegration | UserGitHubIntegration | None:+ user_integration = task.github_user_integration+ if user_integration is not None and user_integration.user_id == user_id:+ return UserGitHubIntegration(user_integration)+ if not task.github_integration_id:+ return None+ integration = Integration.objects.filter(team_id=team_id, kind="github", id=task.github_integration_id).first()+ if integration is None:+ return None+ github = GitHubIntegration(integration)+ if github.access_token_expired():+ github.refresh_access_token()+ return github+++def pull_request_titles(team_id: int, user_id: int, task_ids: list[UUID]) -> dict[str, str]:+ tasks = {+ str(task.id): task+ for task in Task.objects.filter(team_id=team_id, deleted=False, id__in=task_ids)+ .filter(task_visibility_q(user_id))+ .select_related("github_user_integration")+ }+ latest_outputs = (+ TaskRun.objects.filter(team_id=team_id, task_id__in=tasks.keys())+ .order_by("task_id", "-created_at", "-id")+ .distinct("task_id")+ .values_list("task_id", "output")+ )+ refs_by_task: dict[str, list[PullRequestRef]] = {}+ for task_id, output in latest_outputs:+ task = tasks[str(task_id)]+ repositories = {repo.lower() for repo in [task.repository, *(task.repositories or [])] if repo}+ for url in read_pr_urls(output):+ ref = GitHubIntegration.parse_pull_request_url(url)+ if ref is not None and ref.repository.lower() in repositories:+ refs_by_task.setdefault(str(task_id), []).append(ref)++ urls = list(dict.fromkeys(_pull_request_url(ref) for refs in refs_by_task.values() for ref in refs))+ cached = cache.get_many([_cache_key(team_id, url) for url in urls])+ titles = {url: cached[_cache_key(team_id, url)] for url in urls if _cache_key(team_id, url) in cached}++ missing_by_integration: dict[tuple[str, int | str], list[PullRequestRef]] = {}+ tasks_by_integration: dict[tuple[str, int | str], Task] = {}+ queued: set[str] = set()+ for task_key, refs in refs_by_task.items():+ task = tasks[task_key]+ integration_key = _integration_key(task, user_id)+ for ref in refs:+ url = _pull_request_url(ref)+ if url in titles or url in queued or len(queued) >= _MAX_PULL_REQUESTS:+ continue+ queued.add(url)+ missing_by_integration.setdefault(integration_key, []).append(ref)+ tasks_by_integration.setdefault(integration_key, task)++ for integration_key, refs in missing_by_integration.items():+ try:+ github = _github_for_task(tasks_by_integration[integration_key], team_id, user_id)+ if github is None:+ continue+ fetched = _fetch_titles(github, refs)+ except (GitHubIntegrationError, GitHubRateLimitError, GitHubEgressBudgetExhausted):+ logger.warning("tasks_pull_request_titles_fetch_failed", team_id=team_id, exc_info=True)+ continue+ cache.set_many({_cache_key(team_id, url): title for url, title in fetched.items()}, _CACHE_TTL_SECONDS)+ titles.update(fetched)++ return {url: title for url, title in titles.items() if title}diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 52d92e3b87d6..391812a85d50 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -2198,6 +2198,28 @@ class TaskSummariesRequestSerializer(serializers.Serializer):)+TASK_PULL_REQUEST_TITLES_MAX_IDS = 30+++class TaskPullRequestTitlesRequestSerializer(serializers.Serializer):+ ids = serializers.ListField(+ child=serializers.UUIDField(),+ allow_empty=False,+ max_length=TASK_PULL_REQUEST_TITLES_MAX_IDS,+ help_text=f"Task IDs whose latest run's pull request titles to fetch (max {TASK_PULL_REQUEST_TITLES_MAX_IDS}).",+ )+++class TaskPullRequestTitlesSerializer(serializers.Serializer):+ titles = serializers.DictField(+ child=serializers.CharField(),+ help_text=(+ "Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub "+ "could not return its title."+ ),+ )++class TaskRunSummarySerializer(serializers.Serializer):id = serializers.UUIDField(help_text="ID of the latest run.")status = serializers.ChoiceField(choices=tasks_facade.TaskRunStatus.choices, allow_null=True)diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex a7005a7ee26f..360152bcd8b1 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -154,6 +154,8 @@ from products.tasks.backend.presentation.serializers import (TaskPinRequestSerializer,TaskPinResponseSerializer,TaskPresenceBeaconRequestSerializer,+ TaskPullRequestTitlesRequestSerializer,+ TaskPullRequestTitlesSerializer,TaskRepositoriesResponseSerializer,TaskRunAnalysisActivityRequestSerializer,TaskRunAnalysisActivityResponseSerializer,@@ -1108,6 +1110,24 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return self.get_paginated_response(TaskSummarySerializer(page, many=True).data)return Response(TaskSummarySerializer(summaries, many=True).data)+ @validated_request(+ request_serializer=TaskPullRequestTitlesRequestSerializer,+ responses={200: OpenApiResponse(response=TaskPullRequestTitlesSerializer)},+ summary="Fetch pull request titles for tasks",+ description="Returns the GitHub titles of the pull requests that the latest run of each task opened.",+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="pull_request_titles",+ pagination_class=None,+ required_scopes=["task:read"],+ filter_backends=[],+ )+ def pull_request_titles(self, request, **kwargs):+ titles = tasks_facade.get_pull_request_titles(self.team_id, request.user.id, request.validated_data["ids"])+ return Response(TaskPullRequestTitlesSerializer({"titles": titles}).data)+@validated_request(query_serializer=RepositoryReadinessQuerySerializer,responses={diff --git a/products/tasks/backend/tests/test_pull_request_titles.py b/products/tasks/backend/tests/test_pull_request_titles.pynew file mode 100644index 000000000000..e340d05d1786--- /dev/null+++ b/products/tasks/backend/tests/test_pull_request_titles.py@@ -0,0 +1,48 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cache++from posthog.models import Integration++from products.tasks.backend.logic.pull_request_titles import pull_request_titles+from products.tasks.backend.models import Task, TaskRun+++class TestPullRequestTitles(APIBaseTest):+ def setUp(self):+ super().setUp()+ cache.clear()+ integration = Integration.objects.create(team=self.team, kind="github", config={})+ self.task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Example change",+ repository="example/repo",+ github_integration=integration,+ )+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status="completed",+ output={+ "pr_url": "https://github.com/example/repo/pull/1/files",+ "pr_urls": ["https://github.com/example/other/pull/2"],+ },+ )++ @patch(+ "products.tasks.backend.logic.pull_request_titles.GitHubIntegration.access_token_expired", return_value=False+ )+ @patch("products.tasks.backend.logic.pull_request_titles.GitHubIntegration._gh_graphql")+ def test_fetches_in_repository_titles_once(self, graphql, _expired):+ graphql.return_value = {"pr0": {"pullRequest": {"title": "Fix the example"}}}++ first = pull_request_titles(self.team.id, self.user.id, [self.task.id])+ second = pull_request_titles(self.team.id, self.user.id, [self.task.id])++ expected = {"https://github.com/example/repo/pull/1": "Fix the example"}+ self.assertEqual(first, expected)+ self.assertEqual(second, expected)+ graphql.assert_called_once()+ self.assertEqual(graphql.call_args.args[1], {"owner0": "example", "repo0": "repo", "number0": 1})diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 6eec084c91dd..6a580ac67488 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4957,6 +4957,24 @@ export interface PinnedTaskIdsResponseApi {task_ids: string[]}+export interface TaskPullRequestTitlesRequestApi {+ /**+ * Task IDs whose latest run's pull request titles to fetch (max 30).+ * @maxItems 30+ */+ ids: string[]+}++/**+ * Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub could not return its title.+ */+export type TaskPullRequestTitlesApiTitles = { [key: string]: string }++export interface TaskPullRequestTitlesApi {+ /** Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub could not return its title. */+ titles: TaskPullRequestTitlesApiTitles+}+/*** * `engineering` - Engineering* * `data` - Datadiff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex fb6b5843268b..dbe60ccb82f2 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -92,6 +92,8 @@ import type {TaskPinRequestApi,TaskPinResponseApi,TaskPresenceBeaconRequestApi,+ TaskPullRequestTitlesApi,+ TaskPullRequestTitlesRequestApi,TaskRepositoriesResponseApi,TaskReviewApi,TaskRunAnalysisActivityRequestApi,@@ -2940,6 +2942,27 @@ export const tasksPinnedRetrieve = async (})}+export const getTasksPullRequestTitlesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tasks/pull_request_titles/`+}++/**+ * Returns the GitHub titles of the pull requests that the latest run of each task opened.+ * @summary Fetch pull request titles for tasks+ */+export const tasksPullRequestTitlesCreate = async (+ projectId: string,+ taskPullRequestTitlesRequestApi: TaskPullRequestTitlesRequestApi,+ options?: RequestInit+): Promise<TaskPullRequestTitlesApi> => {+ return apiMutator<TaskPullRequestTitlesApi>(getTasksPullRequestTitlesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(taskPullRequestTitlesRequestApi),+ })+}+export const getTasksRepoRoutingRulesListUrl = (projectId: string) => {return `/api/projects/${projectId}/tasks/repo_routing_rules/`}diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 618d826db2e6..d381d3ec55d0 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -3770,6 +3770,19 @@ export const TasksConfigCreateBody = /* @__PURE__ */ zod'The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.')+/**+ * Returns the GitHub titles of the pull requests that the latest run of each task opened.+ * @summary Fetch pull request titles for tasks+ */+export const tasksPullRequestTitlesCreateBodyIdsMax = 30++export const TasksPullRequestTitlesCreateBody = /* @__PURE__ */ zod.object({+ ids: zod+ .array(zod.uuid())+ .max(tasksPullRequestTitlesCreateBodyIdsMax)+ .describe("Task IDs whose latest run's pull request titles to fetch (max 30)."),+})+/*** Team routing rules that steer agent repo selection (`RepoRoutingRule`).*diff --git a/products/tasks/frontend/spaces/SpaceFeed.tsx b/products/tasks/frontend/spaces/SpaceFeed.tsxindex 04ca2959ea9e..5a05eb600eb0 100644--- a/products/tasks/frontend/spaces/SpaceFeed.tsx+++ b/products/tasks/frontend/spaces/SpaceFeed.tsx@@ -35,6 +35,7 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {feedSourceOptions,feedRepositories,feedStatus,+ pullRequestTitles,sessionsById,sessionsLoading,} = useValues(spaceSceneLogic({ id }))@@ -157,6 +158,7 @@ export function SpaceFeed({ id }: { id: string }): JSX.Element {<SpaceFeedPullRequestRowkey={entry.key}pullRequest={entry.pullRequest}+ pullRequestTitle={pullRequestTitles[entry.pullRequest.url]}session={entry.item}author={task.created_by ?? null}listRow={listRows}diff --git a/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx b/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsxindex c04fe536deda..8cb7de2597b6 100644--- a/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx+++ b/products/tasks/frontend/spaces/SpaceFeedPullRequestRow.tsx@@ -23,6 +23,7 @@ function IconGitMerge(props: IconProps): JSX.Element {interface SpaceFeedPullRequestRowProps {pullRequest: TaskPullRequest+ pullRequestTitle: string | undefined/** The session that opened the pull request. */session: TodayWorkItemauthor: TaskUserBasicInfoApi | null@@ -32,6 +33,7 @@ interface SpaceFeedPullRequestRowProps {/** A pull request in the feed's PRs view, as a card or a list row, like PostHog Desktop's. It opens on GitHub. */export function SpaceFeedPullRequestRow({pullRequest,+ pullRequestTitle,session,author,listRow,@@ -39,8 +41,7 @@ export function SpaceFeedPullRequestRow({const { pullRequestStates } = useValues(todaySpacesLogic)const state = pullRequestStates[pullRequest.url]const known = pullRequestStateMeta(state)- // GitHub reports no title to the web, so the row names the session that opened the pull request.- const title = session.title || 'Untitled session'+ const title = pullRequestTitle || session.title || 'Untitled session'const Icon = state === 'merged' ? IconGitMerge : IconPullRequestconst icon = <Icon className={cn('size-3.5 shrink-0', known ? known.iconClassName : 'opacity-50')} />const number = (diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.ts b/products/tasks/frontend/spaces/spaceSceneLogic.tsindex ea09ab82c5b4..78dc7e5a3eb8 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.ts@@ -29,6 +29,7 @@ import {taskChannelsRetrieve,taskChannelsStarCreate,tasksList,+ tasksPullRequestTitlesCreate,} from '../generated/api'import { ChannelDTOApi, PatchedChannelUpdateApi, TaskListItemApi, TaskUserBasicInfoApi } from '../generated/api.schemas'import {@@ -41,7 +42,7 @@ import {spaceFeedSections,} from './spaceFeedEntries'import { spaceFeedViewLogic } from './spaceFeedViewLogic'-import { sessionIdsWithPullRequests } from './taskPullRequests'+import { sessionIdsWithPullRequests, spacePullRequests } from './taskPullRequests'const SPACE_FEED_LIMIT = 50@@ -130,6 +131,8 @@ export interface spaceSceneLogicValues {nameDraft: string | nullnameError: string | nullpendingName: string | null+ pullRequestTitles: Record<string, string>+ pullRequestTitlesLoading: booleanrenameDisabledReason: string | nullsavingSpace: booleansessions: TaskListItemApi[]@@ -205,6 +208,21 @@ export interface spaceSceneLogicActions {members: TaskUserBasicInfoApi[]payload?: any}+ loadPullRequestTitles: () => any+ loadPullRequestTitlesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPullRequestTitlesSuccess: (+ pullRequestTitles: Record<string, string>,+ payload?: any+ ) => {+ pullRequestTitles: Record<string, string>+ payload?: any+ }loadSessions: () => anyloadSessionsFailure: (error: string,@@ -425,6 +443,31 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([},},],+ pullRequestTitles: [+ {} as Record<string, string>,+ {+ loadPullRequestTitles: async () => {+ const sessionIds = [+ ...new Set(+ spacePullRequests(values.feedItems)+ .filter(({ pullRequest }) => !(pullRequest.url in values.pullRequestTitles))+ .map(({ session }) => session.id)+ ),+ ]+ if (!values.types.includes('pr') || !sessionIds.length || !values.currentTeamId) {+ return values.pullRequestTitles+ }+ try {+ const { titles } = await tasksPullRequestTitlesCreate(String(values.currentTeamId), {+ ids: sessionIds,+ })+ return { ...values.pullRequestTitles, ...titles }+ } catch {+ return values.pullRequestTitles+ }+ },+ },+ ],// `null` until the first load, which waits until the Canvases type shows.canvases: [null as CanvasApi[] | null,@@ -691,12 +734,14 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([},loadSessionsSuccess: ({ sessions }) => {actions.loadPullRequestStates(sessionIdsWithPullRequests(sessions))+ actions.loadPullRequestTitles()},sessionUpdated: () => {actions.loadSessions()},setTypes: () => {actions.ensureCanvases()+ actions.loadPullRequestTitles()},// A failed load leaves `null`, so showing the type again retries it.ensureCanvases: () => {diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 31e5d94f3cfb..4207a6cf25f8 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -668,6 +668,9 @@ tools:tasks-presence-destroy:operation: tasks_presence_destroyenabled: false+ tasks-pull-request-titles-create:+ operation: tasks_pull_request_titles_create+ enabled: falsetasks-repo-routing-rules-create:operation: tasks_repo_routing_rules_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 48605e6a9eb8..c5d2de15bd14 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101881,6 +101881,24 @@ export namespace Schemas {device_id: string;}+ /**+ * Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub could not return its title.+ */+ export type TaskPullRequestTitlesTitles = {[key: string]: string};++ export interface TaskPullRequestTitles {+ /** Pull request titles keyed by normalized GitHub URL. A pull request is missing when GitHub could not return its title. */+ titles: TaskPullRequestTitlesTitles;+ }++ export interface TaskPullRequestTitlesRequest {+ /**+ * Task IDs whose latest run's pull request titles to fetch (max 30).+ * @maxItems 30+ */+ ids: string[];+ }+export interface TaskRepositoriesResponse {/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */repositories: string[];