: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(slack-app): use mentioner's GitHub install for repo picker (#60675)
Vojta Bartoš3e89a5792dc3
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex d52b8498dd5c..7f7c1bfaf84b 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -183,10 +183,13 @@ class PostHogCodeRepoCascadeOutcome:`auto` → use `repository` directly. `no_repo` → create a task with no repo(e.g. team has no GitHub integration connected). `agent_needed` → there are- multiple candidates and no explicit mention.+ multiple candidates and no explicit mention. `needs_user_github` → the team+ has a GitHub install but the mentioning user has not connected their personal+ GitHub yet, so the workflow should fire the connect-GitHub prompt rather than+ silently creating a no-repo task."""- mode: Literal["auto", "no_repo", "agent_needed"]+ mode: Literal["auto", "no_repo", "agent_needed", "needs_user_github"]repository: str | Nonereason: str@@ -318,17 +321,35 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):if rules_result.status == "handled":returnif rules_result.status == "needs_picker":- await _execute_posthog_code_activity(- post_posthog_code_repo_picker_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event,- workflow.info().workflow_id,- POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,- False,- )+ # Picker activity gained a trailing `user_id`. Gate the new call+ # shape so in-flight workflows that recorded the pre-`user_id`+ # 8-arg list keep matching their history on replay; new workflows+ # record the 9-arg shape from the start.+ if workflow.patched("posthog-code-slack-user-github-2026-06"):+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,+ user_id,+ )+ else:+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,+ )try:await workflow.wait_condition(lambda: self._repo_selection_resolved,@@ -374,16 +395,43 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):repo_research_task_id: str | None = Nonerepo_research_run_id: str | None = Noneif workflow.patched("posthog-code-repo-discovery-agent-2026-05"):- cascade = await _execute_posthog_code_activity(- cascade_posthog_code_repository_activity,- inputs,- event.get("text", ""),- )+ # The cascade activity gained `user_id` and a new `needs_user_github`+ # outcome. Gate the new shape so in-flight workflows that recorded+ # the 2-arg cascade command keep matching history on replay; new+ # workflows record the 3-arg shape and can take the new branch.+ if workflow.patched("posthog-code-slack-user-github-2026-06"):+ cascade = await _execute_posthog_code_activity(+ cascade_posthog_code_repository_activity,+ inputs,+ event.get("text", ""),+ user_id,+ )+ else:+ cascade = await _execute_posthog_code_activity(+ cascade_posthog_code_repository_activity,+ inputs,+ event.get("text", ""),+ )if cascade.mode == "auto":repository = cascade.repositoryelif cascade.mode == "no_repo":repository = None+ elif cascade.mode == "needs_user_github":+ # Team has GitHub, but the mentioning user hasn't connected their+ # personal install. Fire the gate so they get the Connect button+ # instead of a silently no-repo task. Only reachable on the patched+ # path — the cascade activity never emits this outcome when called+ # without `user_id`, so pre-patch workflows on replay don't see a+ # new activity command appear in history.+ await _execute_posthog_code_activity(+ block_posthog_code_task_if_no_personal_github_activity,+ inputs,+ channel,+ thread_ts,+ user_id,+ )+ returnelse:# Multiple candidates and no explicit mention. Cheap Haiku# check first to skip the agent entirely for analytics/config@@ -415,17 +463,31 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):# Agent crashed/timed out/hallucinated — italicize its reason# above the picker guidance so the user sees why.picker_guidance = f"_{outcome.reason}_\n\n{POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE}"- await _execute_posthog_code_activity(- post_posthog_code_repo_picker_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event,- workflow.info().workflow_id,- picker_guidance,- True,- )+ if workflow.patched("posthog-code-slack-user-github-2026-06"):+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ picker_guidance,+ True,+ user_id,+ )+ else:+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ picker_guidance,+ True,+ )try:await workflow.wait_condition(lambda: self._repo_selection_resolved,@@ -482,17 +544,31 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):None,)return- await _execute_posthog_code_activity(- post_posthog_code_repo_picker_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event,- workflow.info().workflow_id,- POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,- True,- )+ if workflow.patched("posthog-code-slack-user-github-2026-06"):+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,+ True,+ user_id,+ )+ else:+ await _execute_posthog_code_activity(+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,+ True,+ )try:await workflow.wait_condition(lambda: self._repo_selection_resolved,@@ -682,14 +758,30 @@ def collect_posthog_code_thread_messages_activity(def cascade_posthog_code_repository_activity(inputs: PostHogCodeSlackMentionWorkflowInputs,event_text: str,+ user_id: int | None = None,) -> PostHogCodeRepoCascadeOutcome:"""Synchronous fast-path before the discovery agent.- Resolves the trivial cases — no GitHub repos connected, exactly one- connected, or an explicit `org/repo` mentioned in the message — without- paying for the sandbox-backed agent. Anything else returns+ Resolves the trivial cases — no GitHub repos connected to the mentioning user's+ personal install, exactly one connected, or an explicit `org/repo` mentioned in the+ message — without paying for the sandbox-backed agent. Anything else returns`mode='agent_needed'` and the workflow takes over.++ ``user_id`` defaults to ``None`` for backwards compatibility with the pre-2026-06+ call shape: if a worker drains an activity task that was scheduled by an older+ workflow (recorded with two positional args), the call still binds. In that case+ the activity short-circuits to ``no_repo`` since the pre-2026-06 workflow code on+ the receiving end does not understand the ``needs_user_github`` outcome and would+ drop into the discovery agent flow with an empty repo list anyway."""+ if user_id is None:+ logger.warning(+ "posthog_code_cascade_legacy_call",+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ )+ return PostHogCodeRepoCascadeOutcome(mode="no_repo", repository=None, reason="legacy_no_user_id")+from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_namesintegration = Integration.objects.select_related("team", "team__organization").get(@@ -697,9 +789,16 @@ def cascade_posthog_code_repository_activity(kind="slack",integration_id=inputs.slack_team_id,)- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=user_id)if not all_repos:+ # A connected team install with no personal install is recoverable via the gate prompt;+ # a team with no install at all is genuinely no-op.+ team_has_github = Integration.objects.filter(+ team=integration.team, kind=Integration.IntegrationKind.GITHUB+ ).exists()+ if team_has_github:+ return PostHogCodeRepoCascadeOutcome(mode="needs_user_github", repository=None, reason="no_user_repos")return PostHogCodeRepoCascadeOutcome(mode="no_repo", repository=None, reason="no_repos")if len(all_repos) == 1:@@ -734,7 +833,7 @@ def select_posthog_code_repository_activity(kind="slack",integration_id=inputs.slack_team_id,)- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=user_id)return PostHogCodeSlackRepoDecisionData(mode="picker",repository=None,@@ -928,7 +1027,26 @@ def post_posthog_code_repo_picker_activity(workflow_id: str,guidance: str,allow_no_repo: bool,+ user_id: int | None = None,) -> None:+ """Post the repository picker block in the Slack thread.++ ``user_id`` is appended last and defaults to ``None`` so a worker draining an+ activity task scheduled by a pre-2026-06 workflow (recorded with 8 positional+ args) still binds: the eight legacy slots align by position and ``user_id``+ falls through to the default. The body short-circuits in that case rather than+ posting a picker with a missing ``mentioning_user_id``, which would break the+ downstream external-select handler. New workflows go through the patched call+ site at the workflow body and pass ``user_id`` as the final positional arg.+ """+ if user_id is None:+ logger.warning(+ "posthog_code_picker_legacy_call_skipped",+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ )+ return+from products.slack_app.backend.api import _post_repo_picker_messageintegration = Integration.objects.select_related("team", "team__organization").get(@@ -944,6 +1062,7 @@ def post_posthog_code_repo_picker_activity(channel=channel,thread_ts=thread_ts,slack_user_id=slack_user_id,+ user_id=user_id,event_text=event.get("text", ""),user_message_ts=event.get("ts"),guidance=guidance,@@ -1193,14 +1312,19 @@ def create_posthog_code_routing_rule_activity()slack = SlackIntegration(integration)- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=user_id)matched_repo = _extract_explicit_repo(repository, all_repos)if not matched_repo:- logger.warning("posthog_code_rules_add_repo_no_longer_connected", repo=repository, team_id=integration.team_id)+ logger.warning(+ "posthog_code_rules_add_repo_no_longer_connected",+ repo=repository,+ team_id=integration.team_id,+ user_id=user_id,+ )slack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text=f"Repository `{repository}` is no longer connected to this project.",+ text=f"Repository `{repository}` is no longer connected to your account.",)returndiff --git a/posthog/temporal/ai/posthog_code_slack_mention_command.py b/posthog/temporal/ai/posthog_code_slack_mention_command.pyindex 17ff052f955b..d892db0bb68c 100644--- a/posthog/temporal/ai/posthog_code_slack_mention_command.py+++ b/posthog/temporal/ai/posthog_code_slack_mention_command.py@@ -69,6 +69,7 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):from posthog.temporal.ai.posthog_code_slack_mention import (POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,PostHogCodeSlackMentionWorkflowInputs,+ block_posthog_code_task_if_no_personal_github_activity,create_posthog_code_routing_rule_activity,post_posthog_code_picker_timeout_activity,post_posthog_code_repo_picker_activity,@@ -115,21 +116,54 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):slack_team_id=inputs.slack_team_id,)- await workflow.execute_activity(- post_posthog_code_repo_picker_activity,- args=[- picker_inputs,- channel,- thread_ts,- slack_user_id,- inputs.event,- workflow.info().workflow_id,- POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,- False,- ],- start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ # Pre-patch command workflows skip the gate entirely and behave as before,+ # so in-flight replays don't trip nondeterminism on the new activity command.+ if workflow.patched("posthog-code-command-block-no-personal-github-2026-06"):+ blocked = await workflow.execute_activity(+ block_posthog_code_task_if_no_personal_github_activity,+ args=[picker_inputs, channel, thread_ts, user_id],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if blocked:+ return++ # Pre-patch command workflows replay through the 8-arg call shape so the+ # recorded picker command matches history; new workflows append `user_id`+ # as the final positional arg, matching the picker activity's signature.+ if workflow.patched("posthog-code-command-user-id-2026-06"):+ await workflow.execute_activity(+ post_posthog_code_repo_picker_activity,+ args=[+ picker_inputs,+ channel,+ thread_ts,+ slack_user_id,+ inputs.event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,+ user_id,+ ],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ else:+ await workflow.execute_activity(+ post_posthog_code_repo_picker_activity,+ args=[+ picker_inputs,+ channel,+ thread_ts,+ slack_user_id,+ inputs.event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,+ ],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )try:await workflow.wait_condition(diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex dd29321f419c..24b3aedb6135 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -24,7 +24,6 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.llm.gateway_client import get_llm_clientfrom posthog.models.integration import (SLACK_INTEGRATION_KINDS,- GitHubIntegration,Integration,SlackIntegration,SlackIntegrationError,@@ -33,6 +32,7 @@ from posthog.models.integration import ()from posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User+from posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.ai.posthog_code_slack_interactivity import (PostHogCodeSlackInteractivityInputs,PostHogCodeSlackTerminateTaskWorkflow,@@ -91,12 +91,12 @@ REPO_LIST_CACHE_TTL_SECONDS = 300PENDING_REPO_PICKER_TTL_SECONDS = PICKER_TOKEN_MAX_AGE_SECONDS-def _repo_list_cache_key(team_id: int) -> str:- return f"posthog_code:repo_list:v1:{team_id}"+def _user_repo_list_cache_key(user_id: int) -> str:+ return f"posthog_code:user_repo_list:v1:{user_id}"-def _invalidate_repo_list_cache(team_id: int) -> None:- cache.delete(_repo_list_cache_key(team_id))+def _invalidate_user_repo_list_cache(user_id: int) -> None:+ cache.delete(_user_repo_list_cache_key(user_id))def _pending_repo_picker_cache_key(integration_id: int, channel: str, thread_ts: str, slack_user_id: str) -> str:@@ -110,6 +110,7 @@ def _set_pending_repo_picker(channel: str,thread_ts: str,slack_user_id: str,+ user_id: int,workflow_id: str,context_token: str,message_ts: str | None,@@ -120,6 +121,7 @@ def _set_pending_repo_picker("workflow_id": workflow_id,"context_token": context_token,"message_ts": message_ts,+ "mentioning_user_id": user_id,},timeout=PENDING_REPO_PICKER_TTL_SECONDS,)@@ -787,6 +789,7 @@ def _post_repo_picker_message(channel: str,thread_ts: str,slack_user_id: str,+ user_id: int,event_text: str,user_message_ts: str | None,guidance: str,@@ -800,6 +803,7 @@ def _post_repo_picker_message("thread_ts": thread_ts,"user_message_ts": user_message_ts,"mentioning_slack_user_id": slack_user_id,+ "mentioning_user_id": user_id,"event_text": event_text,"created_at": int(time.time()),"workflow_id": workflow_id,@@ -857,6 +861,7 @@ def _post_repo_picker_message(channel=channel,thread_ts=thread_ts,slack_user_id=slack_user_id,+ user_id=user_id,workflow_id=workflow_id,context_token=context_token,message_ts=message_ts,@@ -866,9 +871,9 @@ def _post_repo_picker_message(# is served from cache rather than hitting the GitHub API inline.# Non-fatal: the dropdown will still work, it will just fetch on demand.try:- _get_full_repo_names(integration)+ _get_full_repo_names(integration, user_id=user_id)except Exception:- logger.warning("repo_list_prewarm_failed", team_id=integration.team_id, exc_info=True)+ logger.warning("repo_list_prewarm_failed", user_id=user_id, exc_info=True)def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:@@ -1018,28 +1023,40 @@ def _collect_thread_messages(return messages-def _get_full_repo_names(integration: Integration) -> list[str]:- """Return canonical org/repo names across all GitHub integrations for the team, or [] if unavailable."""- cache_key = _repo_list_cache_key(integration.team_id)+def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:+ """Return canonical org/repo names from the mentioning user's GitHub install, or [] if unavailable.++ Repos are scoped to the user's personal GitHub integration so the picker matches the+ identity that will author the resulting pull request. Users without a personal install+ see an empty list; the downstream personal-GitHub gate posts the connect-GitHub prompt.+ A `None` user_id (e.g. a workflow replay predating per-user scoping) also returns [].+ """+ if user_id is None:+ return []+ cache_key = _user_repo_list_cache_key(user_id)cached = cache.get(cache_key)if cached is not None:return cached- github_records = Integration.objects.filter(team=integration.team, kind="github")- if not github_records.exists():+ user_records = UserIntegration.objects.filter(+ user_id=user_id,+ kind=UserIntegration.IntegrationKind.GITHUB,+ )+ if not user_records.exists():cache.set(cache_key, [], timeout=REPO_LIST_CACHE_TTL_SECONDS)return []all_repos: set[str] = set()- for record in github_records:- github = GitHubIntegration(record)+ for record in user_records:+ github = UserGitHubIntegration(record)repo_entries = github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS)for repo in repo_entries:all_repos.add(repo["full_name"])if len(all_repos) >= _MAX_GITHUB_REPOS:logger.warning("github_repo_list_capped",+ user_id=user_id,team_id=integration.team_id,cap=_MAX_GITHUB_REPOS,)@@ -1148,8 +1165,14 @@ def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integratio)return False+ mentioning_user_id = pending_picker.get("mentioning_user_id")+ if not isinstance(mentioning_user_id, int):+ # Without a known PostHog user we can't scope the picker to a personal install;+ # let the message fall through to the standard flow, which will re-resolve and re-post.+ return False+try:- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=mentioning_user_id)except Exception:logger.exception("posthog_code_pending_picker_repo_fetch_failed", integration_id=integration.id)return False@@ -1845,8 +1868,15 @@ def _handle_repo_picker_options(payload: dict) -> JsonResponse:logger.info("posthog_code_repo_picker_options_no_integration", context_token=context_token)return JsonResponse({"options": []})+ mentioning_user_id = ctx.get("mentioning_user_id") if ctx else None+ if not isinstance(mentioning_user_id, int):+ # Without a known PostHog user we can't scope the options to a personal install;+ # return empty rather than falling back to the team install — the user can re-mention.+ logger.info("posthog_code_repo_picker_options_missing_user_id", context_token=context_token)+ return JsonResponse({"options": []})+try:- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=mentioning_user_id)except Exception:logger.exception("twig_repo_picker_options_repo_fetch_error", integration_id=integration.id)return JsonResponse({"options": []})diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex 1d14e2bd38a0..b9794694fb7f 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -59,12 +59,12 @@ def _handle_rules_add(from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names- all_repos = _get_full_repo_names(integration)+ all_repos = _get_full_repo_names(integration, user_id=user_id)if not all_repos:slack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text="No connected GitHub repositories found for this project.",+ text="No connected GitHub repositories found for your account.",)returndiff --git a/products/slack_app/backend/signals.py b/products/slack_app/backend/signals.pyindex c50e21b41138..c83bb81d72a0 100644--- a/products/slack_app/backend/signals.py+++ b/products/slack_app/backend/signals.py@@ -3,13 +3,13 @@ from typing import Anyfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver-from posthog.models.integration import Integration+from posthog.models.user_integration import UserIntegration-from products.slack_app.backend.api import _invalidate_repo_list_cache+from products.slack_app.backend.api import _invalidate_user_repo_list_cache-@receiver(post_save, sender=Integration)-@receiver(post_delete, sender=Integration)-def invalidate_repo_list_on_github_change(sender: Any, instance: Integration, **kwargs) -> None:- if instance.kind == "github":- _invalidate_repo_list_cache(instance.team_id)+@receiver(post_save, sender=UserIntegration)+@receiver(post_delete, sender=UserIntegration)+def invalidate_repo_list_on_user_github_change(sender: Any, instance: UserIntegration, **kwargs) -> None:+ if instance.kind == UserIntegration.IntegrationKind.GITHUB:+ _invalidate_user_repo_list_cache(instance.user_id)diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.pyindex a47b559123e4..bdce6c42193a 100644--- a/products/slack_app/backend/tests/test_guess_repository.py+++ b/products/slack_app/backend/tests/test_guess_repository.py@@ -12,14 +12,15 @@ from posthog.models.organization import Organizationfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.models.user_integration import UserIntegrationfrom products.slack_app.backend.api import (RulesCommand,_extract_explicit_repo,_get_full_repo_names,- _invalidate_repo_list_cache,+ _invalidate_user_repo_list_cache,_parse_rules_command,- _repo_list_cache_key,+ _user_repo_list_cache_key,classify_task_needs_repo,)@@ -28,12 +29,25 @@ def _repo_dict(org: str, name: str, repo_id: int = 1) -> dict:return {"id": repo_id, "name": name, "full_name": f"{org}/{name}"}-@patch("products.slack_app.backend.api.GitHubIntegration")+def _create_user_github_integration(+ user: User, *, integration_id: str = "gh-1", name: str = "posthog"+) -> UserIntegration:+ return UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id=integration_id,+ config={"account": {"name": name}},+ sensitive_config={"access_token": "ghp-test"},+ )+++@patch("products.slack_app.backend.api.UserGitHubIntegration")class TestGetFullRepoNames:@pytest.fixture(autouse=True)def setup(self, db):self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-1")self.slack_integration = Integration.objects.create(team=self.team,@@ -42,18 +56,13 @@ class TestGetFullRepoNames:sensitive_config={"access_token": "xoxb-test"},)- def test_no_github_integration_returns_empty(self, mock_github_class):- result = _get_full_repo_names(self.slack_integration)+ def test_no_user_github_integration_returns_empty(self, mock_github_class):+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == []mock_github_class.assert_not_called()def test_single_integration_single_page(self, mock_github_class):- Integration.objects.create(- team=self.team,- kind="github",- config={"account": {"name": "posthog"}},- sensitive_config={"access_token": "ghp-test"},- )+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [@@ -63,16 +72,11 @@ class TestGetFullRepoNames:]mock_github_class.return_value = mock_github- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["posthog/plugin-server", "posthog/posthog", "posthog/posthog-js"]def test_pagination_across_pages(self, mock_github_class):- Integration.objects.create(- team=self.team,- kind="github",- config={"account": {"name": "org"}},- sensitive_config={"access_token": "ghp-test"},- )+ _create_user_github_integration(self.user, name="org")page1 = [_repo_dict("org", f"repo-{i}", i) for i in range(100)]page2 = [_repo_dict("org", f"repo-{i}", i) for i in range(100, 120)]@@ -81,25 +85,13 @@ class TestGetFullRepoNames:mock_github.list_all_cached_repositories.return_value = page1 + page2mock_github_class.return_value = mock_github- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert len(result) == 120assert result == sorted(f"org/repo-{i}" for i in range(120))def test_multiple_integrations_aggregated(self, mock_github_class):- Integration.objects.create(- team=self.team,- kind="github",- integration_id="gh-1",- config={"account": {"name": "orgA"}},- sensitive_config={"access_token": "ghp-a"},- )- Integration.objects.create(- team=self.team,- kind="github",- integration_id="gh-2",- config={"account": {"name": "orgB"}},- sensitive_config={"access_token": "ghp-b"},- )+ _create_user_github_integration(self.user, integration_id="gh-1", name="orgA")+ _create_user_github_integration(self.user, integration_id="gh-2", name="orgB")gh_a = MagicMock()gh_a.list_all_cached_repositories.return_value = [_repo_dict("orgA", "repo-1", 1)]@@ -109,35 +101,25 @@ class TestGetFullRepoNames:mock_github_class.side_effect = [gh_a, gh_b]- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["orgA/repo-1", "orgB/repo-2"]@patch("products.slack_app.backend.api._MAX_GITHUB_REPOS", 5)def test_cap_reached_truncates_and_warns(self, mock_github_class, caplog):- Integration.objects.create(- team=self.team,- kind="github",- config={"account": {"name": "org"}},- sensitive_config={"access_token": "ghp-test"},- )+ _create_user_github_integration(self.user, name="org")mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("org", f"repo-{i}", i) for i in range(10)]mock_github_class.return_value = mock_githubwith caplog.at_level(logging.WARNING):- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert len(result) == 5assert any("github_repo_list_capped" in r.message for r in caplog.records)def test_results_are_sorted(self, mock_github_class):- Integration.objects.create(- team=self.team,- kind="github",- config={"account": {"name": "posthog"}},- sensitive_config={"access_token": "ghp-test"},- )+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [@@ -147,17 +129,18 @@ class TestGetFullRepoNames:]mock_github_class.return_value = mock_github- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["posthog/alpha", "posthog/middle", "posthog/zebra"]-@patch("products.slack_app.backend.api.GitHubIntegration")+@patch("products.slack_app.backend.api.UserGitHubIntegration")class TestGetFullRepoNamesCache:@pytest.fixture(autouse=True)def setup(self, db):cache.clear()self.organization = Organization.objects.create(name="Cache Org")self.team = Team.objects.create(organization=self.organization, name="Cache Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-cache")self.slack_integration = Integration.objects.create(team=self.team,kind="slack",@@ -165,50 +148,35 @@ class TestGetFullRepoNamesCache:sensitive_config={"access_token": "xoxb-cache"},)- def _create_github_integration(self, team=None, name="posthog"):- return Integration.objects.create(- team=team or self.team,- kind="github",- config={"account": {"name": name}},- sensitive_config={"access_token": "ghp-test"},- )-def test_cache_miss_populates_cache(self, mock_github_class):- self._create_github_integration()+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["posthog/repo-a"]- assert cache.get(_repo_list_cache_key(self.team.id)) == ["posthog/repo-a"]+ assert cache.get(_user_repo_list_cache_key(self.user.id)) == ["posthog/repo-a"]def test_cache_hit_avoids_github_api(self, mock_github_class):- self._create_github_integration()+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- _get_full_repo_names(self.slack_integration)+ _get_full_repo_names(self.slack_integration, user_id=self.user.id)mock_github_class.reset_mock()- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["posthog/repo-a"]mock_github_class.assert_not_called()- def test_team_isolation(self, mock_github_class):- org_b = Organization.objects.create(name="Other Org")- team_b = Team.objects.create(organization=org_b, name="Other Team")- slack_b = Integration.objects.create(- team=team_b,- kind="slack",- integration_id="T_OTHER",- sensitive_config={"access_token": "xoxb-other"},- )- self._create_github_integration(team=self.team, name="orgA")- self._create_github_integration(team=team_b, name="orgB")+ def test_user_isolation(self, mock_github_class):+ user_b = User.objects.create(email="[email protected]", distinct_id="user-b")+ _create_user_github_integration(self.user, integration_id="gh-a", name="orgA")+ _create_user_github_integration(user_b, integration_id="gh-b", name="orgB")gh_a = MagicMock()gh_a.list_all_cached_repositories.return_value = [_repo_dict("orgA", "repo-a")]@@ -218,106 +186,104 @@ class TestGetFullRepoNamesCache:mock_github_class.side_effect = [gh_a, gh_b]- result_a = _get_full_repo_names(self.slack_integration)- result_b = _get_full_repo_names(slack_b)+ result_a = _get_full_repo_names(self.slack_integration, user_id=self.user.id)+ result_b = _get_full_repo_names(self.slack_integration, user_id=user_b.id)assert result_a == ["orgA/repo-a"]assert result_b == ["orgB/repo-b"]def test_invalidation_forces_refetch(self, mock_github_class):- self._create_github_integration()+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- _get_full_repo_names(self.slack_integration)- _invalidate_repo_list_cache(self.team.id)+ _get_full_repo_names(self.slack_integration, user_id=self.user.id)+ _invalidate_user_repo_list_cache(self.user.id)- assert cache.get(_repo_list_cache_key(self.team.id)) is None+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is Nonemock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a"),_repo_dict("posthog", "repo-b", 2),]- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == ["posthog/repo-a", "posthog/repo-b"]def test_no_github_integrations_caches_empty(self, mock_github_class):- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == []- assert cache.get(_repo_list_cache_key(self.team.id)) == []+ assert cache.get(_user_repo_list_cache_key(self.user.id)) == []mock_github_class.assert_not_called()def test_empty_result_with_github_integrations_not_cached(self, mock_github_class):- self._create_github_integration()+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = []mock_github_class.return_value = mock_github- result = _get_full_repo_names(self.slack_integration)+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)assert result == []- assert cache.get(_repo_list_cache_key(self.team.id)) is None+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is None- def test_signal_invalidates_on_github_save(self, mock_github_class):- self._create_github_integration()+ def test_signal_invalidates_on_user_github_save(self, mock_github_class):+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- _get_full_repo_names(self.slack_integration)- assert cache.get(_repo_list_cache_key(self.team.id)) is not None+ _get_full_repo_names(self.slack_integration, user_id=self.user.id)+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is not None- Integration.objects.create(- team=self.team,- kind="github",+ UserIntegration.objects.create(+ user=self.user,+ kind=UserIntegration.IntegrationKind.GITHUB,integration_id="gh-new",config={"account": {"name": "new-org"}},sensitive_config={"access_token": "ghp-new"},)- assert cache.get(_repo_list_cache_key(self.team.id)) is None+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is None- def test_signal_invalidates_on_github_delete(self, mock_github_class):- gh_record = self._create_github_integration()+ def test_signal_invalidates_on_user_github_delete(self, mock_github_class):+ gh_record = _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- _get_full_repo_names(self.slack_integration)- assert cache.get(_repo_list_cache_key(self.team.id)) is not None+ _get_full_repo_names(self.slack_integration, user_id=self.user.id)+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is not Nonegh_record.delete()- assert cache.get(_repo_list_cache_key(self.team.id)) is None+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is None- def test_signal_ignores_non_github_integration(self, mock_github_class):- self._create_github_integration()+ def test_signal_isolated_to_user(self, mock_github_class):+ """A different user's GitHub install must not invalidate this user's cache."""+ other_user = User.objects.create(email="[email protected]", distinct_id="user-other-signal")+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github- _get_full_repo_names(self.slack_integration)- assert cache.get(_repo_list_cache_key(self.team.id)) is not None+ _get_full_repo_names(self.slack_integration, user_id=self.user.id)+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is not None- Integration.objects.create(- team=self.team,- kind="slack",- integration_id="S99",- sensitive_config={"access_token": "xoxb-other"},- )+ _create_user_github_integration(other_user, integration_id="gh-other", name="other-org")- assert cache.get(_repo_list_cache_key(self.team.id)) is not None+ assert cache.get(_user_repo_list_cache_key(self.user.id)) is not None-@patch("products.slack_app.backend.api.GitHubIntegration")+@patch("products.slack_app.backend.api.UserGitHubIntegration")class TestPostRepoPickerPrewarm:@pytest.fixture(autouse=True)def setup(self, db):cache.clear()self.organization = Organization.objects.create(name="Prewarm Org")self.team = Team.objects.create(organization=self.organization, name="Prewarm Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-prewarm")self.slack_integration = Integration.objects.create(team=self.team,kind="slack",@@ -332,12 +298,7 @@ class TestPostRepoPickerPrewarm:mock_slack = MagicMock()mock_slack_cls.return_value = mock_slack- Integration.objects.create(- team=self.team,- kind="github",- config={"account": {"name": "posthog"}},- sensitive_config={"access_token": "ghp-test"},- )+ _create_user_github_integration(self.user)mock_github = MagicMock()mock_github.list_all_cached_repositories.return_value = [_repo_dict("posthog", "repo-a")]mock_github_class.return_value = mock_github@@ -348,13 +309,14 @@ class TestPostRepoPickerPrewarm:channel="C001",thread_ts="123.456",slack_user_id="U001",+ user_id=self.user.id,event_text="fix bug",user_message_ts=None,guidance="Pick a repo",action_id="posthog_code_repo_select",)- assert cache.get(_repo_list_cache_key(self.team.id)) == ["posthog/repo-a"]+ assert cache.get(_user_repo_list_cache_key(self.user.id)) == ["posthog/repo-a"]class TestExtractExplicitRepo:diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex afdc55afc021..0747ad064fb0 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -13,6 +13,7 @@ from rest_framework.test import APIClientfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom products.slack_app.backend.tests.helpers import sign_slack_request@@ -107,6 +108,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):self.factory = RequestFactory()self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-1")self.posthog_code_integration = Integration.objects.create(team=self.team,kind="slack",@@ -197,6 +199,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):channel="C001",thread_ts="1234.5678",slack_user_id="U123",+ user_id=self.user.id,workflow_id="posthog-code-mention-T12345:pending",context_token="ctx-1",message_ts="1234.7777",@@ -591,6 +594,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):channel="C001",thread_ts="1234.5678",slack_user_id="U123",+ user_id=self.user.id,workflow_id="posthog-code-mention-T12345:pending",context_token="ctx-1",message_ts="1234.7777",diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.pyindex 04a5980ba1d3..dee4eb023651 100644--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py@@ -78,6 +78,7 @@ class TestRepoPickerOptions(TestCase):"thread_ts": "1234.5678","user_message_ts": "1234.5678","mentioning_slack_user_id": "U123",+ "mentioning_user_id": self.user.id,"event_text": "fix the bug","created_at": int(time.time()),}