: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
refactor(slack-app): use the integrations SDK (#125018)
Tom Owers131c708aa66a
diff --git a/posthog/integrations/model_access_baseline.txt b/posthog/integrations/model_access_baseline.txtindex bfb79ce0daad..8dff37611275 100644--- a/posthog/integrations/model_access_baseline.txt+++ b/posthog/integrations/model_access_baseline.txt@@ -95,50 +95,17 @@ products/signals/backend/temporal/agentic/select_repository.py 2products/signals/backend/tracker_issues.py 4products/signals/backend/views.py 2products/skills/backend/api/community_publish_services.py 1-products/slack_app/backend/analytics.py 1-products/slack_app/backend/api.py 28-products/slack_app/backend/discussion_replies.py 1+products/slack_app/backend/api.py 1products/slack_app/backend/facade/api.py 3-products/slack_app/backend/inbox_channel.py 1-products/slack_app/backend/logic/feature_tips/catalog.py 3-products/slack_app/backend/logic/feature_tips/interactivity.py 2-products/slack_app/backend/logic/feature_tips/offer.py 1-products/slack_app/backend/logic/interview_recruitment.py 2-products/slack_app/backend/logic/link_unfurl_charts.py 2-products/slack_app/backend/logic/thread_join.py 1products/slack_app/backend/models.py 3-products/slack_app/backend/onboarding.py 2-products/slack_app/backend/services/commands.py 3-products/slack_app/backend/services/inbox_interactivity.py 2-products/slack_app/backend/services/integration_resolver.py 6-products/slack_app/backend/services/project_picker.py 1-products/slack_app/backend/services/slack_app_home.py 6+products/slack_app/backend/services/integration_resolver.py 3+products/slack_app/backend/services/slack_app_home.py 2products/slack_app/backend/services/slack_app_home_stats.py 1-products/slack_app/backend/services/slack_auth.py 1-products/slack_app/backend/services/slack_messages.py 2-products/slack_app/backend/services/slack_settings.py 1-products/slack_app/backend/services/slack_user_info.py 3-products/slack_app/backend/services/slack_welcome_messages.py 1-products/slack_app/backend/services/turn_feedback.py 2-products/slack_app/backend/signals.py 2-products/slack_app/backend/slack_link_unfurl.py 1+products/slack_app/backend/services/slack_user_info.py 2products/slack_app/backend/slack_thread.py 2-products/slack_app/backend/slack_workflow_events.py 2-products/slack_app/backend/tasks.py 2-products/slack_app/backend/temporal/activities/billing.py 2-products/slack_app/backend/temporal/activities/classifiers.py 6-products/slack_app/backend/temporal/activities/messaging.py 9-products/slack_app/backend/temporal/activities/model_router.py 2+products/slack_app/backend/temporal/activities/classifiers.py 1+products/slack_app/backend/temporal/activities/messaging.py 1products/slack_app/backend/temporal/activities/onboarding.py 2-products/slack_app/backend/temporal/activities/repo_selection.py 4-products/slack_app/backend/temporal/activities/rules.py 2-products/slack_app/backend/temporal/activities/task_creation.py 4-products/slack_app/backend/temporal/activities/thread.py 2-products/slack_app/backend/temporal/activities/untagged_question.py 2-products/slack_app/backend/temporal/activities/user_resolution.py 2-products/slack_app/backend/temporal/attachments.py 1-products/slack_app/backend/views/slack_user_link.py 2-products/slack_app/evals/eval_project_classifier.py 1products/stamphog/backend/logic/channel_resolution.py 2products/stamphog/backend/logic/slack_digest.py 3products/subscriptions/backend/logic/slack_subscriptions.py 2diff --git a/products/slack_app/backend/analytics.py b/products/slack_app/backend/analytics.pyindex 09df4f15d1a2..4589ea0e4326 100644--- a/products/slack_app/backend/analytics.py+++ b/products/slack_app/backend/analytics.py@@ -13,16 +13,17 @@ from typing import TYPE_CHECKINGimport structlogfrom posthog.event_usage import groups-from posthog.models.integration import Integrationfrom posthog.ph_client import ph_background_capture+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration+if TYPE_CHECKING:from posthog.models.user import Userlogger = structlog.get_logger(__name__)-def slack_event_props(integration: Integration, *, slack_user_id: str | None = None, **extra: object) -> dict:+def slack_event_props(integration: WorkspaceIntegration, *, slack_user_id: str | None = None, **extra: object) -> dict:"""The standard property bundle attached to every Slack app event, plus any ``extra`` props."""props: dict = {"integration_id": integration.id,@@ -41,13 +42,13 @@ def slack_session_id(slack_team_id: str, channel: str, thread_ts: str) -> str:return f"{slack_team_id}:{channel}:{thread_ts}"-def slack_distinct_id(integration: Integration, slack_user_id: str) -> str:+def slack_distinct_id(integration: WorkspaceIntegration, slack_user_id: str) -> str:"""The distinct id of a Slack user that no PostHog user has been resolved for yet."""return f"slack:{integration.integration_id}:{slack_user_id}"def capture_slack_event(- integration: Integration,+ integration: WorkspaceIntegration,event: str,*,slack_user_id: str | None = None,@@ -85,7 +86,7 @@ def capture_slack_event(logger.warning("slack_analytics_capture_failed", slack_event=event, exc_info=True)-def alias_slack_user(integration: Integration, slack_user_id: str, posthog_user: User) -> None:+def alias_slack_user(integration: WorkspaceIntegration, slack_user_id: str, posthog_user: User) -> None:"""Merge a Slack user's anonymous person into their PostHog user's person. Best-effort.Events captured before the Slack user was linked use ``slack_distinct_id``. After the merge,diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 3ba7d904dca6..4af780ddda3d 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -4,6 +4,7 @@ import timeimport uuidimport asyncioimport hashlib+from collections.abc import Sequencefrom dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal@@ -26,9 +27,9 @@ from posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.event_usage import groupsfrom posthog.git import extract_explicit_repo, extract_linked_repo, extract_repo_from_scopes+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.models.integration import (SLACK_INTEGRATION_KINDS,- Integration,SlackIntegration,SlackIntegrationError,sign_slack_request,@@ -131,6 +132,13 @@ from products.slack_app.backend.services.slack_welcome_messages import (build_channel_welcome,build_team_join_welcome,)+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ get_team_workspace_integration,+ get_workspace_integration,+ workspace_integration_exists,+ workspace_integrations,+)from products.slack_app.backend.slack_link_unfurl import (ADHOC_INSIGHT_KIND,handle_posthog_link_unfurl,@@ -328,7 +336,7 @@ QUOTA_EXHAUSTED_MESSAGE = (def post_quota_exhausted_denial(*,- integration: Integration,+ integration: WorkspaceIntegration,slack: SlackIntegration,channel: str,thread_ts: str,@@ -431,7 +439,7 @@ def _post_slack_user_ephemeral(def resolve_slack_user(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,channel: str,thread_ts: str,@@ -923,15 +931,12 @@ def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:if not filtered:return HttpResponse("No valid kinds", status=400)- claimed = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- kind__in=filtered,- integration_id=slack_team_id,- ).exists()+ claimed = IntegrationManager.slack.oauth.exists_by_external_id(slack_team_id)channel, thread_ts = data.get("channel"), data.get("thread_ts")if channel is not None or thread_ts is not None:if not isinstance(channel, str) or not channel or not isinstance(thread_ts, str) or not thread_ts:return HttpResponse("Invalid thread", status=400)- candidates = list(Integration.objects.filter(kind__in=filtered, integration_id=slack_team_id))+ candidates = workspace_integrations(slack_team_id)result = resolve_from_candidates(candidates, slack_team_id=slack_team_id, channel=channel, thread_ts=thread_ts)return JsonResponse({"claimed": claimed, "thread_claimed": result.source == "thread"})return JsonResponse({"claimed": claimed})@@ -1025,7 +1030,7 @@ def parse_rules_command(text: str) -> RulesCommand | None:def _post_repo_picker_message(*,slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,slack_user_id: str,@@ -1157,7 +1162,7 @@ def _repo_snapshot_needs_refresh(record: UserIntegration) -> bool:return (timezone.now() - updated_at).total_seconds() >= REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS-def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:+def _get_full_repo_names(integration: WorkspaceIntegration, *, user_id: int | None) -> list[str]:"""Repo names available to the mentioner, from their personal GitHub install. Cached per user."""if user_id is None:return []@@ -1214,10 +1219,9 @@ def _replace_repo_picker_message_with_selection(selected_repo: str,) -> None:try:- # nosemgrep: idor-lookup-without-team — Slack webhook: no team context; scoped by PK + kind + Slack team ID- integration = Integration.objects.get(- id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id- )+ integration = get_workspace_integration(integration_id, slack_team_id)+ if integration is None:+ raise IntegrationNotFoundslack = SlackIntegration(integration)text = f"Repository selected: `{selected_repo}`"slack.client.chat_update(@@ -1248,10 +1252,9 @@ def _replace_repo_picker_message_with_no_repo(message_ts: str,) -> None:try:- # nosemgrep: idor-lookup-without-team — Slack webhook: no team context; scoped by PK + kind + Slack team ID- integration = Integration.objects.get(- id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id- )+ integration = get_workspace_integration(integration_id, slack_team_id)+ if integration is None:+ raise IntegrationNotFoundslack = SlackIntegration(integration)text = "Continuing without a repository."slack.client.chat_update(@@ -1274,7 +1277,7 @@ def _replace_repo_picker_message_with_no_repo()-def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integration: Integration) -> bool:+def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integration: WorkspaceIntegration) -> bool:channel = event.get("channel")thread_ts = event.get("thread_ts") or event.get("ts")slack_user_id = event.get("user")@@ -1511,7 +1514,7 @@ def _edited_mention_ignore_cause(event: dict[str, Any], slack_team_id: str) -> sreturn None-def _awaits_request_from_author(event: dict[str, Any], slack_team_id: str, probe: Integration) -> bool:+def _awaits_request_from_author(event: dict[str, Any], slack_team_id: str, probe: WorkspaceIntegration) -> bool:"""Whether this threaded message is the request a bare mention in its thread asked for."""channel = event.get("channel")thread_ts = event.get("thread_ts")@@ -1533,7 +1536,7 @@ def _awaits_request_from_author(event: dict[str, Any], slack_team_id: str, probedef _answer_bare_mention(- event: dict[str, Any], integration: Integration, slack_team_id: str, *, posthog_user: User+ event: dict[str, Any], integration: WorkspaceIntegration, slack_team_id: str, *, posthog_user: User) -> str:channel = event.get("channel")message_ts = event.get("ts")@@ -1622,7 +1625,7 @@ def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:def _resolve_untagged_followup_mapping(*,- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],channel: str | None,thread_ts: str | None,) -> SlackThreadTaskMapping | None:@@ -1647,7 +1650,7 @@ def _resolve_untagged_followup_mapping(return mapping-def _message_tags_bot(event: dict[str, Any], integration: Integration) -> bool:+def _message_tags_bot(event: dict[str, Any], integration: WorkspaceIntegration) -> bool:"""Whether the message text mentions the app's own bot user.Slack delivers a thread reply that tags the bot twice — as ``app_mention``@@ -1674,7 +1677,7 @@ def _message_tags_bot(event: dict[str, Any], integration: Integration) -> bool:def _untagged_followups_switched_off(event: dict[str, Any],- integration: Integration,+ integration: WorkspaceIntegration,slack_team_id: str,*,mapping: SlackThreadTaskMapping,@@ -1746,7 +1749,7 @@ def _notify_missing_slack_scopes(return _post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)-def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str) -> str | None:+def get_slack_email_for_user(probe_integration: WorkspaceIntegration, slack_user_id: str) -> str | None:"""Best-effort lookup of the Slack user's email via ``users.info``, cache-first thena fresh hit on miss. Returns ``None`` when Slack doesn't expose an email for theuser (profile email hidden) or the lookup fails.@@ -1821,8 +1824,8 @@ def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str)def resolve_posthog_user_from_event(*,slack_user_id: str,- probe_integration: Integration,- candidate_integrations: list[Integration],+ probe_integration: WorkspaceIntegration,+ candidate_integrations: Sequence[WorkspaceIntegration],slack_email: str | None = None,) -> User | None:"""Resolve the acting Slack user to a PostHog ``User`` who is a member of@@ -1881,7 +1884,7 @@ def resolve_posthog_user_from_event(def _post_pick_a_project_hint(probe: SlackIntegration,- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],event: dict[str, Any],) -> bool:"""Tell the user that this workspace is connected to multiple PostHog@@ -1908,7 +1911,7 @@ def _post_pick_a_project_hint(def _post_project_picker(- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],event: dict[str, Any],event_id: str | None,*,@@ -1986,15 +1989,7 @@ def _handle_project_picker_pick(payload: dict) -> HttpResponse:)integration = Noneif rejection is None and integration_id is not None and slack_team_id:- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)# Access can change between the post and the click.posthog_user = _is_org_member(integration, clicker_slack_user_id) if integration is not None else Noneif (@@ -2029,7 +2024,7 @@ def _handle_project_picker_pick(payload: dict) -> HttpResponse:SlackSettings.objects.update_or_create(slack_workspace_id=slack_team_id,slack_user_id=clicker_slack_user_id,- defaults={"default_integration": integration},+ defaults={"default_integration_id": integration.id},)# The mention never reached the workflow, so its event id is still unused._dispatch_mention_to_target(@@ -2061,7 +2056,7 @@ def _handle_project_picker_pick(payload: dict) -> HttpResponse:def _post_user_resolution_failure_reply(*,- probe: Integration,+ probe: WorkspaceIntegration,channel: str | None,slack_user_id: str | None,thread_ts: str | None,@@ -2259,7 +2254,7 @@ def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, threaddef _handle_assistant_dm_message(event: dict,- integration: Integration,+ integration: WorkspaceIntegration,slack_team_id: str,event_id: str | None,channel_id: str,@@ -2348,7 +2343,11 @@ def _route_assistant_event(if region_route is not None:return region_route- probe = result.integration if result.integration in result.candidates else result.candidates[0]+ probe = (+ result.integration+ if result.integration is not None and result.integration in result.candidates+ else result.candidates[0]+ )# Share the mention path's user resolution + access filter, so the DM only ever sees and runs# against projects the resolved PostHog user can actually access (no cross-org metadata leak).@@ -2515,11 +2514,7 @@ def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:# A workspace linked to several projects matches several rows, but the uninstall is# one act: capture once per region so plain event counts stay honest, with# `linked_project_count` carrying how many links it severed.- linked_integrations = list(- Integration.objects.filter(kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id)- .select_related("team", "team__organization")- .order_by("id")- )+ linked_integrations = workspace_integrations(slack_team_id)if linked_integrations:capture_slack_event(linked_integrations[0],@@ -2619,7 +2614,7 @@ def _route_untagged_question(def _dispatch_mention_to_target(event: dict,- mention_target: Integration,+ mention_target: WorkspaceIntegration,slack_team_id: str,event_id: str | None,*,@@ -3308,7 +3303,7 @@ def resolve_region_or_terminal_route(def _redirect_mention_command(command: RulesCommand,event: dict[str, Any],- probe: Integration,+ probe: WorkspaceIntegration,slack_team_id: str,*,posthog_user: User,@@ -3353,7 +3348,7 @@ def _redirect_mention_command(return ROUTE_HANDLED_LOCALLY-def _connected_organization_ids(candidates: list[Integration]) -> tuple[str, ...]:+def _connected_organization_ids(candidates: Sequence[WorkspaceIntegration]) -> tuple[str, ...]:team_ids = {candidate.team_id for candidate in candidates}organization_ids = Team.objects.filter(id__in=team_ids).values_list("organization_id", flat=True).distinct()return tuple(str(organization_id) for organization_id in organization_ids)@@ -3361,10 +3356,10 @@ def _connected_organization_ids(candidates: list[Integration]) -> tuple[str, ...def _hand_off_command(event: dict[str, Any],- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],slack_team_id: str,*,- probe: Integration,+ probe: WorkspaceIntegration,posthog_user: User,is_ext_shared_channel: bool,) -> bool:@@ -3443,7 +3438,7 @@ def _hand_off_command(def _start_command_workflow(event: dict,- integrations: list[Integration],+ integrations: Sequence[WorkspaceIntegration],slack_team_id: str,event_id: str | None,*,@@ -3469,7 +3464,9 @@ def _start_command_workflow(return ROUTE_HANDLED_LOCALLY-def _count_session_thread_messages(integration: Integration, channel: str | None, thread_ts: str | None) -> int | None:+def _count_session_thread_messages(+ integration: WorkspaceIntegration, channel: str | None, thread_ts: str | None+) -> int | None:"""Best-effort count of messages in a Slack thread (the session). None if unavailable.Runs in the Slack webhook request path, so the client timeout is bounded: a slow or@@ -3606,7 +3603,7 @@ def _release_channel_onboarding_claim(slack_team_id: str, channel_id: str) -> Nodef _post_channel_onboarding_message(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel_id: str,*,only_to_user: str | None = None,@@ -3705,7 +3702,7 @@ def _team_join_onboarding_cache_key(slack_team_id: str, slack_user_id: str) -> sreturn f"slack_app:team_join_welcomed:v1:{slack_team_id}:{slack_user_id}"-def _post_team_join_welcome(integration: Integration, slack_user_id: str) -> bool:+def _post_team_join_welcome(integration: WorkspaceIntegration, slack_user_id: str) -> bool:text, blocks = build_team_join_welcome(integration)try:SlackIntegration(integration).client.chat_postMessage(@@ -3741,7 +3738,7 @@ def _channel_is_approved(slack_workspace_id: str, channel_id: str) -> bool:def _post_channel_approval_prompt(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,event: dict[str, Any],) -> bool:"""Post the approval prompt as an ephemeral message to the mentioner.@@ -3848,7 +3845,7 @@ def _post_channel_approval_prompt(def _post_untagged_followup_prompt(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,event: dict[str, Any],*,is_ext_shared_channel: bool,@@ -3960,7 +3957,9 @@ def _post_untagged_followup_prompt(return True-def _post_untagged_question_prompt(slack: SlackIntegration, integration: Integration, event: dict[str, Any]) -> bool:+def _post_untagged_question_prompt(+ slack: SlackIntegration, integration: WorkspaceIntegration, event: dict[str, Any]+) -> bool:"""Offer the author, privately, to answer the question they posted without tagging the app.Posted when the author's mode is ``ask``. The whole event is stashed behind a one-off@@ -4053,7 +4052,7 @@ def _post_untagged_question_prompt(slack: SlackIntegration, integration: Integraclass _UntaggedQuestionClick:context_token: strcontext: dict[str, Any]- integration: Integration+ integration: WorkspaceIntegrationdef _untagged_question_click(payload: dict) -> _UntaggedQuestionClick | None:@@ -4067,15 +4066,7 @@ def _untagged_question_click(payload: dict) -> _UntaggedQuestionClick | None:# The prompt is ephemeral, so only its recipient can click it, but the dispatch runs as the clicker.if not integration_id or not slack_team_id or payload.get("user", {}).get("id") != context.get("slack_user_id"):return None- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)if integration is None:return Nonereturn _UntaggedQuestionClick(context_token=context_token, context=context, integration=integration)@@ -4176,7 +4167,7 @@ def _thread_join_pending_key(integration_id: int, channel: str, thread_ts: str,def post_thread_join_prompt(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,inputs: PostHogCodeSlackMentionWorkflowInputs,*,channel: str,@@ -4331,15 +4322,7 @@ def _handle_thread_join_allow(payload: dict) -> HttpResponse:if not slack_team_id or not isinstance(integration_id, int):_close_thread_join_prompt(context_token, context, response_url)return HttpResponse(status=200)- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)joiner_slack_user_id = context.get("joiner_slack_user_id")event = context.get("event")if integration is None or not isinstance(joiner_slack_user_id, str) or not isinstance(event, dict):@@ -4403,11 +4386,7 @@ def _handle_thread_join_decline(payload: dict) -> HttpResponse:integration_id = context.get("integration_id")if not isinstance(integration_id, int):return HttpResponse(status=200)- integration = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=payload.get("team", {}).get("id", ""),- ).first()+ integration = get_workspace_integration(integration_id, payload.get("team", {}).get("id", ""))if integration is None:return HttpResponse(status=200)try:@@ -4423,7 +4402,7 @@ def _handle_thread_join_decline(payload: dict) -> HttpResponse:return HttpResponse(status=200)-def _can_access_team(posthog_user: User, integration: Integration) -> bool:+def _can_access_team(posthog_user: User, integration: WorkspaceIntegration) -> bool:"""Whether the user can reach the integration's project.Org membership alone is what ``_is_org_member`` answers, and it is not enough@@ -4441,7 +4420,7 @@ def _can_access_team(posthog_user: User, integration: Integration) -> bool:return False-def _untagged_followups_revoked_since_prompt(integration: Integration, context: dict[str, Any]) -> bool:+def _untagged_followups_revoked_since_prompt(integration: WorkspaceIntegration, context: dict[str, Any]) -> bool:"""Whether the thread creator switched follow-ups off while the prompt sat unanswered.The confirmed run skips the mode activity — its answer is what re-dispatched@@ -4493,15 +4472,7 @@ def _handle_untagged_followup_run(payload: dict) -> HttpResponse:_delete_ephemeral_via_response_url(response_url)return HttpResponse(status=200)- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)if integration is None:_delete_ephemeral_via_response_url(response_url)return HttpResponse(status=200)@@ -4569,15 +4540,7 @@ def _handle_untagged_followup_dismiss(payload: dict) -> HttpResponse:slack_team_id = payload.get("team", {}).get("id", "")integration_id = context.get("integration_id")dismissing_integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team", "team__organization")- .first()- if integration_id and slack_team_id- else None+ get_workspace_integration(integration_id, slack_team_id) if integration_id and slack_team_id else None)dismisser_slack_user_id = payload.get("user", {}).get("id")if dismissing_integration is not None:@@ -4622,15 +4585,7 @@ def _handle_reply_suggestion_click(payload: dict, clicked: reply_suggestions.Cliclaim_key = f"slack_app_reply_suggestion_claim:{clicked.integration_id}:{channel}:{message_ts}"if cache.get(claim_key):return HttpResponse(status=200)- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=clicked.integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(clicked.integration_id, slack_team_id)if integration is None:return HttpResponse(status=200)slack = SlackIntegration(integration)@@ -4734,7 +4689,7 @@ def _handle_reply_suggestion_click(payload: dict, clicked: reply_suggestions.Clidef _report_slack_mention_received(event: dict,- integration: Integration,+ integration: WorkspaceIntegration,slack_team_id: str,*,posthog_user: User | None = None,@@ -4832,7 +4787,7 @@ def _report_slack_mention_dropped(*,reason: str,replied: bool,- integration: Integration | None = None,+ integration: WorkspaceIntegration | None = None,posthog_user: User | None = None,**extra: object,) -> None:@@ -4890,7 +4845,7 @@ def _report_slack_mention_dropped(def _start_mention_workflow(event: dict,- integration: Integration,+ integration: WorkspaceIntegration,slack_team_id: str,event_id: str | None,*,@@ -5116,7 +5071,7 @@ def _link_shared_resource_refs(event: dict[str, Any]) -> list[dict[str, str]]:class LinkSharedTarget:"""The install that serves a ``link_shared`` event, and how it was chosen."""- integration: Integration | None+ integration: WorkspaceIntegration | Nonesource: str@@ -5171,7 +5126,7 @@ def _link_shared_url_team_ids(event: dict[str, Any]) -> set[int]:def _link_shared_target(- event: dict[str, Any], candidates: list[Integration], *, slack_team_id: str+ event: dict[str, Any], candidates: Sequence[WorkspaceIntegration], *, slack_team_id: str) -> LinkSharedTarget:"""Pick the install to unfurl with, preferring the project the link itself names."""team_ids = _link_shared_url_team_ids(event)@@ -5339,9 +5294,7 @@ def _handle_repo_picker_options(payload: dict) -> JsonResponse:if not ctx and not hinted_integration_id:team_id = payload.get("team", {}).get("id")if team_id:- fallback_integration = (- Integration.objects.filter(kind=SLACK_INTEGRATION_KIND, integration_id=team_id).order_by("id").first()- )+ fallback_integration = next(iter(workspace_integrations(team_id)), None)if fallback_integration:hinted_integration_id = fallback_integration.idlogger.info(@@ -5369,15 +5322,9 @@ def _handle_repo_picker_options(payload: dict) -> JsonResponse:if not expected_user:logger.info("slack_app_repo_picker_options_missing_expected_user", context_token=context_token)- try:- integration_id: int | None = ctx["integration_id"] if ctx else hinted_integration_id- if not integration_id:- raise Integration.DoesNotExist- # nosemgrep: idor-lookup-without-team — Slack webhook: no team context; scoped by PK + kind + Slack team ID- integration = Integration.objects.get(- id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id- )- except Integration.DoesNotExist:+ integration_id: int | None = ctx["integration_id"] if ctx else hinted_integration_id+ integration = get_workspace_integration(integration_id, slack_team_id) if integration_id else None+ if integration is None:logger.info("slack_app_repo_picker_options_no_integration", context_token=context_token)return JsonResponse({"options": []})@@ -5459,10 +5406,9 @@ def _handle_repo_picker_submit(payload: dict) -> HttpResponse:returntry:- # nosemgrep: idor-lookup-without-team — Slack webhook: no team context; scoped by PK + kind + Slack team ID- integration = Integration.objects.get(- id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id- )+ integration = get_workspace_integration(integration_id, slack_team_id)+ if integration is None:+ raise IntegrationNotFoundpost_slack_thread_reply(SlackIntegration(integration).client,channel=channel,@@ -5576,7 +5522,7 @@ def _delete_ephemeral_via_response_url(response_url: str) -> None:def _post_channel_approval_outcome(- integration: Integration,+ integration: WorkspaceIntegration,channel_id: str,thread_ts: str | None,text: str,@@ -5605,9 +5551,8 @@ def _post_channel_approval_outcome()-def _resolve_channel_approval_context(- payload: dict,-) -> tuple[Integration, dict, str, str] | None:+# nosemgrep: tuple-return-prefer-dataclass -- existing shape, only the record type changed+def _resolve_channel_approval_context(payload: dict) -> tuple[WorkspaceIntegration, dict, str, str] | None:"""Decode the click context and load the prompt's integration in one place.Returns ``(integration, context, channel_id, clicker_slack_user_id)`` on@@ -5630,15 +5575,7 @@ def _resolve_channel_approval_context(_delete_ephemeral_via_response_url(response_url)return None- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)if integration is None:_delete_ephemeral_via_response_url(response_url)return None@@ -5646,7 +5583,7 @@ def _resolve_channel_approval_context(return integration, context, channel_id, clicker_slack_user_id-def _is_org_member(integration: Integration, clicker_slack_user_id: str) -> User | None:+def _is_org_member(integration: WorkspaceIntegration, clicker_slack_user_id: str) -> User | None:"""Resolve the clicker to a PostHog ``User`` belonging to the integration'sorganization, or ``None`` if no such membership exists."""@@ -5657,7 +5594,7 @@ def _is_org_member(integration: Integration, clicker_slack_user_id: str) -> User)-def _org_label(integration: Integration) -> str:+def _org_label(integration: WorkspaceIntegration) -> str:try:org_name = integration.team.organization.nameexcept Exception:@@ -5666,7 +5603,7 @@ def _org_label(integration: Integration) -> str:def _reject_non_member_click(- integration: Integration,+ integration: WorkspaceIntegration,channel_id: str,thread_ts: str | None,response_url: str,@@ -5804,14 +5741,10 @@ def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:if not (isinstance(integration_id, int) and report_id and isinstance(report_team_id, int)):return HttpResponse(status=200)- try:- # Slack webhook: no team context; scoped by PK + kind + workspace ID. The team match below- # ensures the report belongs to the workspace's integration before we touch it.- # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get- integration = Integration.objects.get(- id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id- )- except Integration.DoesNotExist:+ # Slack webhook: no team context; scoped by PK + kind + workspace ID. The team match below+ # ensures the report belongs to the workspace's integration before we touch it.+ integration = get_workspace_integration(integration_id, slack_team_id)+ if integration is None:logger.info("signals_dismiss_report_no_integration", integration_id=integration_id)return HttpResponse(status=200)@@ -6027,13 +5960,9 @@ def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:logger.info("insight_alert_snooze_no_alert", alert_id=str(alert_uuid))return HttpResponse(status=200)- try:- # Proves the Slack workspace the click came from is connected to the alert's team.- # nosemgrep: idor-lookup-without-team- integration = Integration.objects.get(- kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id, team_id=alert_team_id- )- except Integration.DoesNotExist:+ # Proves the Slack workspace the click came from is connected to the alert's team.+ integration = get_team_workspace_integration(alert_team_id, slack_team_id)+ if integration is None:logger.info("insight_alert_snooze_no_integration", alert_id=str(alert_uuid), slack_team_id=slack_team_id)return HttpResponse(status=200)@@ -6127,7 +6056,7 @@ def _render_insight_alert_snooze_modal(private_metadata: str) -> dict:}-def _open_insight_alert_snooze_modal(integration: Integration, payload: dict, alert_uuid: uuid.UUID) -> None:+def _open_insight_alert_snooze_modal(integration: WorkspaceIntegration, payload: dict, alert_uuid: uuid.UUID) -> None:trigger_id = payload.get("trigger_id")if not trigger_id:return@@ -6186,12 +6115,8 @@ def _handle_insight_alert_snooze_modal_submit(payload: dict) -> HttpResponse:alert_team_id = get_alert_team_id(alert_uuid)if alert_team_id is None or not slack_team_id:return HttpResponse(status=200)- try:- # nosemgrep: idor-lookup-without-team- integration = Integration.objects.get(- kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id, team_id=alert_team_id- )- except Integration.DoesNotExist:+ integration = get_team_workspace_integration(alert_team_id, slack_team_id)+ if integration is None:return HttpResponse(status=200)org_member = _is_org_member(integration, slack_user_id)@@ -6212,7 +6137,7 @@ def _handle_insight_alert_snooze_modal_submit(payload: dict) -> HttpResponse:def _post_insight_alert_snooze_modal_confirmation(- integration: Integration, meta: dict, until: datetime, slack_user_id: str+ integration: WorkspaceIntegration, meta: dict, until: datetime, slack_user_id: str) -> None:channel = meta.get("channel")if not channel:@@ -6311,26 +6236,14 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:ctx_integration_id = context.get("integration_id") if context else None# Slack webhook endpoint: no team context available; queries are scoped by PK + kind + workspace IDif slack_team_id and ctx_integration_id:- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=ctx_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(ctx_integration_id, slack_team_id)elif slack_team_id and hinted_integration_id and hinted_user_id and requesting_user == hinted_user_id:- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=hinted_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(hinted_integration_id, slack_team_id)elif slack_team_id and dismiss_integration_id:# Routing/region-ownership only — this just claims the workspace's integration locally.# Authorization (report-team match + org-member gate) is enforced in _handle_signals_dismiss_report.# Intended trust boundary for dismiss is org membership (any org member can dismiss the org's reports).- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=dismiss_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(dismiss_integration_id, slack_team_id)elif slack_team_id and alert_snooze_uuid:# Alert UUIDs are globally unique per region (each region has its own DB), so a local# existence check alone settles region ownership — no need to consult Integration here.@@ -6345,39 +6258,24 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:elif slack_team_id and inbox_integration_id:# Inbox onboarding buttons (create/join) are DMed to a user; any clicker may act, so this# is gated only on owning the integration locally.- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=inbox_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(inbox_integration_id, slack_team_id)elif slack_team_id and project_picker_integration_id:# Reached once the context expired, so that the handler can tell the person.- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=project_picker_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(project_picker_integration_id, slack_team_id)elif slack_team_id and _is_ai_preferences_interactivity(payload, payload_type):# App Home AI-settings actions (Edit/Reset/Save) and the modal# re-render dispatched_actions carry no per-row hint — the button is# tied to the workspace, not a specific picker context. Claim locality# based on the workspace integration alone; if we own *any* Integration# for this Slack team, the click is ours to handle.- local = Integration.objects.filter(- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = bool(workspace_integrations(slack_team_id))elif slack_team_id and reply_control_integration_id:# The fork menu and the thumbs ride on a bot reply anyone in the thread can see, so# any reader may use them, and the same goes for the modal a thumbs-down opens.# Routing only claims the workspace; who the fork runs as, and whether they may, is# settled in the fork activity, and a rating is matched to its run in the feedback# handler.- local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=reply_control_integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).exists()+ local = workspace_integration_exists(reply_control_integration_id, slack_team_id)proxied = was_proxied(request)incoming_host = request.get_host()diff --git a/products/slack_app/backend/discussion_replies.py b/products/slack_app/backend/discussion_replies.pyindex 960f583d150e..af3fbf5d756a 100644--- a/products/slack_app/backend/discussion_replies.py+++ b/products/slack_app/backend/discussion_replies.py@@ -7,22 +7,23 @@ decision happens here, on the webhook request thread — the Slack profile lookuin a Celery task so the events endpoint can ack within Slack's deadline and failures get retries."""+from collections.abc import Sequencefrom typing import Anyimport structlogfrom posthog.models.comment import CommentSlackThread-from posthog.models.integration import Integrationfrom posthog.tasks.comment_slack_sync import ingest_slack_discussion_replyfrom products.slack_app.backend.models import SlackThreadTaskMapping+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationlogger = structlog.get_logger(__name__)def try_ingest_discussion_reply(event: dict[str, Any],- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],channel: str | None,thread_ts: str | None,slack_team_id: str,diff --git a/products/slack_app/backend/inbox_channel.py b/products/slack_app/backend/inbox_channel.pyindex b415fbab035c..193ddde0e350 100644--- a/products/slack_app/backend/inbox_channel.py+++ b/products/slack_app/backend/inbox_channel.py@@ -7,9 +7,11 @@ from django.core.cache import cacheimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.slack.formatting import channel_id_from_target+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration+logger = structlog.get_logger(__name__)INBOX_CHANNEL_NAME = "posthog-inbox"@@ -26,7 +28,7 @@ _CHANNEL_CLAIM_TTL_SECONDS = 60_MAX_CHANNEL_LIST_PAGES = 50-def has_inbox_scopes(integration: Integration) -> bool:+def has_inbox_scopes(integration: WorkspaceIntegration) -> bool:"""Whether the install granted the onboarding scopes. Gated on this rather than a feature flag."""return not SlackIntegration(integration).missing_scopes(INBOX_ONBOARDING_REQUIRED_SCOPES)@@ -99,7 +101,8 @@ def _claim_channel_creation(slack_team_id: str) -> bool:)-def ensure_inbox_channel(integration: Integration) -> tuple[str, str] | None:+# nosemgrep: tuple-return-prefer-dataclass -- existing shape, only the record type changed+def ensure_inbox_channel(integration: WorkspaceIntegration) -> tuple[str, str] | None:"""Find-or-create #posthog-inbox, persist it as the team's default notification channel,and return (channel_id, "#name"). Returns None when the channel must be created but theinstall lacks ``channels:manage`` — callers fall back to manual instructions.@@ -152,7 +155,7 @@ def ensure_inbox_channel(integration: Integration) -> tuple[str, str] | None:return result-def invite_user_to_inbox(integration: Integration, channel_id: str, slack_user_id: str) -> bool:+def invite_user_to_inbox(integration: WorkspaceIntegration, channel_id: str, slack_user_id: str) -> bool:"""Invite a Slack user into the inbox channel; existing membership counts as success.A bot isn't auto-added to a channel it creates and can't invite others to one it's not in, so on@@ -183,7 +186,7 @@ def invite_user_to_inbox(integration: Integration, channel_id: str, slack_user_ireturn False-def is_inbox_channel(integration: Integration, channel_id: str) -> bool:+def is_inbox_channel(integration: WorkspaceIntegration, channel_id: str) -> bool:"""True when ``channel_id`` is this team's inbox channel — by configured id, else by name(the name fallback covers the window before the team default is written)."""configured = _get_team_channel(integration.team_id)diff --git a/products/slack_app/backend/logic/feature_tips/catalog.py b/products/slack_app/backend/logic/feature_tips/catalog.pyindex 87fd9b6a836a..d6e2ee1b6172 100644--- a/products/slack_app/backend/logic/feature_tips/catalog.py+++ b/products/slack_app/backend/logic/feature_tips/catalog.py@@ -17,7 +17,8 @@ from __future__ import annotationsfrom functools import cached_propertyfrom posthog.dataclasses import frozen-from posthog.models.integration import Integration, SlackIntegration+from posthog.integrations import IntegrationManager+from posthog.models.integration import SlackIntegrationfrom posthog.models.user_integration import UserIntegrationfrom posthog.slack.formatting import channel_id_from_target@@ -40,12 +41,13 @@ from products.slack_app.backend.services.slack_settings import (set_untagged_followup_mode,set_untagged_question_mode,)+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, workspace_integrationsfrom products.subscriptions.backend.facade.api import user_has_slack_subscription@frozen(slots=False)class TipContext:- integration: Integration+ integration: WorkspaceIntegrationslack_user_id: strposthog_user_id: int | Nonechannel: str@@ -62,17 +64,12 @@ class TipContext:@cached_propertydef team_has_github(self) -> bool:- return Integration.objects.filter(team_id=self.team_id, kind="github").exists()+ return IntegrationManager.github.oauth.exists(self.team_id)@cached_propertydef workspace_has_several_projects(self) -> bool:# Every PostHog project connected to this Slack workspace has its own Slack integration row.- return (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- kind="slack", integration_id=self.integration.integration_id- ).count()- > 1- )+ return len(workspace_integrations(self.integration.integration_id)) > 1@cached_propertydef inbox_channel_target(self) -> str | None:@@ -90,7 +87,7 @@ class TipContext:return app_home_url(self.integration)-def _is_public_channel(integration: Integration, channel_id: str) -> bool:+def _is_public_channel(integration: WorkspaceIntegration, channel_id: str) -> bool:conversation_type = resolve_conversation_type(SlackIntegration(integration), {}, channel_id)return conversation_type == SlackThreadTaskMapping.ConversationType.PUBLIC_CHANNEL@@ -131,7 +128,7 @@ class TipFeature:def cta(self, ctx: TipContext) -> TipCta | None:return None- def apply_action(self, integration: Integration, slack_user_id: str) -> str:+ def apply_action(self, integration: WorkspaceIntegration, slack_user_id: str) -> str:raise NotImplementedError@@ -159,7 +156,7 @@ class ThreadFollowupTip(TipFeature):def cta(self, ctx: TipContext) -> TipCta | None:return TipCta(label="Always pick up my replies")- def apply_action(self, integration: Integration, slack_user_id: str) -> str:+ def apply_action(self, integration: WorkspaceIntegration, slack_user_id: str) -> str:set_untagged_followup_mode(integration.integration_id, slack_user_id, UntaggedFollowupMode.AUTO)return ("✅ Done. I'll pick up your replies in threads you start with me. "@@ -324,7 +321,7 @@ class InboxChannelTip(TipFeature):def cta(self, ctx: TipContext) -> TipCta | None:return TipCta(label="Join the channel")- def apply_action(self, integration: Integration, slack_user_id: str) -> str:+ def apply_action(self, integration: WorkspaceIntegration, slack_user_id: str) -> str:channel = ensure_inbox_channel(integration)# Checked again on click, because the channel can turn private after the tip was shown.if channel is None or not _is_public_channel(integration, channel[0]):@@ -405,7 +402,7 @@ class AutoModelChoiceTip(TipFeature):def cta(self, ctx: TipContext) -> TipCta | None:return TipCta(label="Turn it on")- def apply_action(self, integration: Integration, slack_user_id: str) -> str:+ def apply_action(self, integration: WorkspaceIntegration, slack_user_id: str) -> str:set_auto_model_choice(integration.integration_id, slack_user_id, True)return "✅ Done. I'll choose the model for each new task you start. You can change this in the PostHog app Home tab."@@ -476,7 +473,7 @@ class UnpromptedAnswersTip(TipFeature):def cta(self, ctx: TipContext) -> TipCta | None:return TipCta(label="Always answer my questions")- def apply_action(self, integration: Integration, slack_user_id: str) -> str:+ def apply_action(self, integration: WorkspaceIntegration, slack_user_id: str) -> str:set_untagged_question_mode(integration.integration_id, slack_user_id, UntaggedFollowupMode.AUTO)return ("✅ Done. I'll answer your questions about PostHog in channels, also when you don't tag me. "diff --git a/products/slack_app/backend/logic/feature_tips/interactivity.py b/products/slack_app/backend/logic/feature_tips/interactivity.pyindex 91fdf1e4d834..c1d1f81ad7c9 100644--- a/products/slack_app/backend/logic/feature_tips/interactivity.py+++ b/products/slack_app/backend/logic/feature_tips/interactivity.py@@ -11,7 +11,6 @@ from django.utils import timezoneimport structlogfrom posthog.dataclasses import frozen-from posthog.models.integration import Integrationfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.logic.feature_tips.catalog import CATALOG@@ -24,6 +23,7 @@ from products.slack_app.backend.logic.feature_tips.offer import ()from products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, TipRecord, update_statefrom products.slack_app.backend.services.inbox_interactivity import post_response_url+from products.slack_app.backend.services.workspace_integrations import get_workspace_integrationlogger = structlog.get_logger(__name__)@@ -73,11 +73,7 @@ def handle_feature_tip_action(payload: dict[str, Any]) -> HttpResponse:post_response_url(response_url, {"delete_original": True})return HttpResponse(status=200)value = found.value- integration = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind="slack",- integration_id=slack_team_id,- ).first()+ integration = get_workspace_integration(integration_id, slack_team_id)if integration is None or value.get("feature") not in SlackFeature:post_response_url(response_url, {"delete_original": True})return HttpResponse(status=200)diff --git a/products/slack_app/backend/logic/feature_tips/offer.py b/products/slack_app/backend/logic/feature_tips/offer.pyindex 3da492f9234a..5c074c61acf6 100644--- a/products/slack_app/backend/logic/feature_tips/offer.py+++ b/products/slack_app/backend/logic/feature_tips/offer.py@@ -22,7 +22,7 @@ from django.utils import timezoneimport structlogfrom posthog.dataclasses import frozen-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.analytics import capture_slack_event, slack_distinct_idfrom products.slack_app.backend.logic.feature_tips.catalog import CATALOG, TipContext, TipFeature@@ -31,6 +31,7 @@ from products.slack_app.backend.logic.feature_tips.picker import choose_tipfrom products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, mark_shown, parse_statefrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMappingfrom products.slack_app.backend.services.slack_messages import post_slack_ephemeral, section_block+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationif TYPE_CHECKING:from posthog.models.user import User@@ -51,7 +52,7 @@ FEATURE_TIP_ACTION_IDS = frozenset(@frozenclass TipRequest:- integration: Integration+ integration: WorkspaceIntegrationslack_user_id: strposthog_user: User | Nonechannel: strdiff --git a/products/slack_app/backend/logic/interview_recruitment.py b/products/slack_app/backend/logic/interview_recruitment.pyindex ea6d82e06a43..b03d2bb1bbb2 100644--- a/products/slack_app/backend/logic/interview_recruitment.py+++ b/products/slack_app/backend/logic/interview_recruitment.py@@ -29,7 +29,7 @@ from posthog.dataclasses import frozenfrom posthog.llm.managed_decision_model import DEFAULT_DECISION_MODELfrom posthog.llm.system_one import ChoiceAnswer, ChoiceQuestionfrom posthog.llm.system_one_client import build_system_one_client-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, get_state, update_state@@ -37,6 +37,7 @@ from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.services.inbox_interactivity import post_response_urlfrom products.slack_app.backend.services.slack_messages import post_slack_ephemeral, section_blockfrom products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, get_workspace_integrationfrom products.slack_app.backend.temporal.activities.classifiers import CLASSIFIER_PROPERTYif TYPE_CHECKING:@@ -108,7 +109,7 @@ class SentimentVerdict:return self.choice == UNHAPPY and self.confidence >= SENTIMENT_MIN_CONFIDENCE-def linked_posthog_user(integration: Integration, slack_user_id: str) -> User | None:+def linked_posthog_user(integration: WorkspaceIntegration, slack_user_id: str) -> User | None:"""The PostHog user behind this Slack identity. Best-effort, because the result only labels events and model calls."""try:return find_linked_posthog_user(@@ -140,7 +141,7 @@ def invite_section(text: str, button: dict[str, Any]) -> dict[str, Any]:@frozenclass FrustrationInviteRequest:- integration: Integration+ integration: WorkspaceIntegrationslack_user_id: strposthog_user: User | Nonechannel: str@@ -359,15 +360,7 @@ def handle_interview_action(payload: dict[str, Any]) -> HttpResponse:if clicked is None or integration_id is None or not slack_user_id or not slack_team_id:return HttpResponse(status=200)value = clicked.value- integration = (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind="slack",- integration_id=slack_team_id,- )- .select_related("team__organization")- .first()- )+ integration = get_workspace_integration(integration_id, slack_team_id)surface = value.get("surface")if integration is None or surface not in INTERVIEW_SURFACES:return HttpResponse(status=200)diff --git a/products/slack_app/backend/logic/link_unfurl_charts.py b/products/slack_app/backend/logic/link_unfurl_charts.pyindex 247390e525eb..ccdd77a047ea 100644--- a/products/slack_app/backend/logic/link_unfurl_charts.py+++ b/products/slack_app/backend/logic/link_unfurl_charts.py@@ -18,13 +18,15 @@ from slack_sdk.errors import SlackApiErrorfrom temporalio.exceptions import ApplicationErrorfrom posthog.dataclasses import frozen+from posthog.integrations import IntegrationManagerfrom posthog.models import Team, User-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.product_analytics.backend.facade.api import user_can_view_insightfrom products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.services.workspace_integrations import with_teamsif TYPE_CHECKING:# Runtime import would load the temporal package, whose activities import this module.@@ -128,9 +130,7 @@ def _raise_if_transient(error: SlackApiError) -> None:def post_unfurl_charts(post: SlackAppUnfurlChartsPostInput, *, image_urls_by_key: dict[str, str]) -> None:"""Post the rendered charts. ``image_urls_by_key`` holds a delivery url for each render key that rendered."""request = post.request- integration = Integration.objects.select_related("team__organization").get(- id=request.integration_id, team_id=request.team_id- )+ integration = with_teams([IntegrationManager.slack.oauth.get(request.team_id, request.integration_id)])[0]team = integration.teamuser = User.objects.filter(id=request.user_id).first()failure_reason: str | None = Nonediff --git a/products/slack_app/backend/logic/thread_join.py b/products/slack_app/backend/logic/thread_join.pyindex e5571cc60944..f921486573c7 100644--- a/products/slack_app/backend/logic/thread_join.py+++ b/products/slack_app/backend/logic/thread_join.py@@ -5,10 +5,9 @@ from typing import TYPE_CHECKINGfrom products.slack_app.backend.models import SlackThreadJoin, ThreadJoinModefrom products.slack_app.backend.services.slack_settings import resolve_thread_join_mode+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationif TYPE_CHECKING:- from posthog.models.integration import Integration-from products.slack_app.backend.models import SlackThreadTaskMapping@@ -22,7 +21,7 @@ class ThreadJoinDecision(StrEnum):def decide_thread_join(- integration: "Integration", mapping: "SlackThreadTaskMapping", slack_user_id: str+ integration: "WorkspaceIntegration", mapping: "SlackThreadTaskMapping", slack_user_id: str) -> ThreadJoinDecision:"""The creator's join mode applied to one person, given the approvals the thread already has.diff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.pyindex afeb709aefac..2a50a44ef2a5 100644--- a/products/slack_app/backend/onboarding.py+++ b/products/slack_app/backend/onboarding.py@@ -12,8 +12,9 @@ from enum import StrEnumimport structlogfrom slack_sdk.errors import SlackApiError+from posthog.integrations import IntegrationManagerfrom posthog.models import OrganizationMembership, Team-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.user_integration import UserIntegrationfrom posthog.slack.formatting import channel_id_from_target@@ -31,6 +32,7 @@ from products.slack_app.backend.services.slack_welcome_messages import (INBOX_JOIN_ACTION_ID,build_onboarding_dm,)+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationlogger = structlog.get_logger(__name__)@@ -69,7 +71,7 @@ def _replace_actions_with_context(blocks: list[dict], action_ids: set[str], textdef _has_team_github(team_id: int) -> bool:- return Integration.objects.filter(team_id=team_id, kind="github").exists()+ return IntegrationManager.github.oauth.exists(team_id)def _has_personal_github(user_id: int) -> bool:@@ -104,7 +106,9 @@ def _has_enabled_source(team_id: int) -> bool:return has_enabled_source(team_id)-def _resolve_onboarding_user(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> int | None:+def _resolve_onboarding_user(+ slack: SlackIntegration, integration: WorkspaceIntegration, slack_user_id: str+) -> int | None:"""Resolve the Slack user to a PostHog user id (org-member email match), or None."""from products.slack_app.backend.api import (resolve_slack_user, # noqa: PLC0415 — api.py imports this module; defer to break the cycle@@ -115,7 +119,7 @@ def _resolve_onboarding_user(slack: SlackIntegration, integration: Integration,def _onboarding_status(- integration: Integration, slack: SlackIntegration, slack_user_id: str, user_id: int | None = None+ integration: WorkspaceIntegration, slack: SlackIntegration, slack_user_id: str, user_id: int | None = None) -> tuple[int | None, dict[OnboardingStep, bool]]:"""Resolve the user and evaluate each step's done/not-done — the source of truth for what's left.Pass ``user_id`` when the caller already resolved it, to skip the repeat lookup."""@@ -134,7 +138,7 @@ def _onboarding_status(def _build_from_status(- integration: Integration, slack: SlackIntegration, user_id: int | None, status: dict[OnboardingStep, bool]+ integration: WorkspaceIntegration, slack: SlackIntegration, user_id: int | None, status: dict[OnboardingStep, bool]) -> tuple[str, list[dict]]:is_admin = user_id is not None and _is_org_admin(user_id, integration.team_id)return build_onboarding_dm(@@ -147,7 +151,7 @@ def _build_from_status()-def send_onboarding_dm(integration: Integration, slack_user_id: str) -> bool:+def send_onboarding_dm(integration: WorkspaceIntegration, slack_user_id: str) -> bool:"""DM a user the inbox onboarding. Returns True when sent, False when the post failed.Always posts (no dedupe, no all-done shortcut) — the install hook already fires only once.@@ -180,14 +184,14 @@ def send_onboarding_dm(integration: Integration, slack_user_id: str) -> bool:return True-def _maybe_complete(integration: Integration, slack_user_id: str, user_id: int | None = None) -> None:+def _maybe_complete(integration: WorkspaceIntegration, slack_user_id: str, user_id: int | None = None) -> None:"""Fire 'completed' once every required step is done. Pass ``user_id`` when already resolved."""_, status = _onboarding_status(integration, SlackIntegration(integration), slack_user_id, user_id)_capture_completed_if_done(integration, slack_user_id, status)def _capture_completed_if_done(- integration: Integration, slack_user_id: str, status: dict[OnboardingStep, bool]+ integration: WorkspaceIntegration, slack_user_id: str, status: dict[OnboardingStep, bool]) -> None:if all(status[step] for step in _REQUIRED_STEPS):capture_slack_event(integration, EVENT_COMPLETED, slack_user_id=slack_user_id)@@ -198,7 +202,9 @@ def _capture_completed_if_done(# =====================================================================-def _chat_update_blocks(integration: Integration, channel: str, message_ts: str, text: str, blocks: list[dict]) -> None:+def _chat_update_blocks(+ integration: WorkspaceIntegration, channel: str, message_ts: str, text: str, blocks: list[dict]+) -> None:try:SlackIntegration(integration).client.chat_update(channel=channel, ts=message_ts, text=text, blocks=blocks)except SlackApiError as e:@@ -208,7 +214,7 @@ def _chat_update_blocks(integration: Integration, channel: str, message_ts: str,def mark_channel_joined(- integration: Integration, slack_user_id: str, channel: str, message_ts: str, original_blocks: list[dict]+ integration: WorkspaceIntegration, slack_user_id: str, channel: str, message_ts: str, original_blocks: list[dict]) -> None:"""After create/join: flip just the channel block to a '✅' line in place, then record completion."""swapped = _replace_actions_with_context(@@ -223,7 +229,7 @@ def mark_channel_joined(_maybe_complete(integration, slack_user_id)-def apply_sources_selection(integration: Integration, slack_user_id: str, selected_keys: list[str]) -> None:+def apply_sources_selection(integration: WorkspaceIntegration, slack_user_id: str, selected_keys: list[str]) -> None:"""Sync the team's sources to the new selection."""from products.signals.backend.facade.api import (set_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path@@ -243,7 +249,7 @@ def apply_sources_selection(integration: Integration, slack_user_id: str, select_maybe_complete(integration, slack_user_id, user_id)-def approve_ai_data_processing(integration: Integration, slack_user_id: str) -> bool:+def approve_ai_data_processing(integration: WorkspaceIntegration, slack_user_id: str) -> bool:"""Admin-only approval: re-checks ADMIN+ server-side, sets org consent, records completion.Returns False if the clicker isn't an admin."""user_id = _resolve_onboarding_user(SlackIntegration(integration), integration, slack_user_id)@@ -268,11 +274,11 @@ def approve_ai_data_processing(integration: Integration, slack_user_id: str) ->return True-def installer_slack_user_id(integration: Integration) -> str | None:+def installer_slack_user_id(integration: WorkspaceIntegration) -> str | None:return ((integration.config or {}).get("authed_user") or {}).get("id")-def run_install_onboarding(integration: Integration) -> None:+def run_install_onboarding(integration: WorkspaceIntegration) -> None:"""On a fresh install: create the inbox channel, invite the installer, and DM them the onboarding.Gated on the install having ``channels:manage``; best-effort."""if not has_inbox_scopes(integration):diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex a82cff090662..9f577edcc989 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -1,9 +1,14 @@+from collections.abc import Sequencefrom typing import TYPE_CHECKING-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom products.slack_app.backend.services.slack_messages import app_home_url, post_slack_ephemeral+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ get_team_workspace_integration,+)if TYPE_CHECKING:from products.slack_app.backend.api import RulesCommand@@ -63,7 +68,7 @@ def reject_invalid_rule_text(team_id: int, rule_text: str) -> str | None:def _handle_help(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,slack_user_id: str,@@ -111,7 +116,7 @@ def _handle_help(def _handle_rules_list(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,*,@@ -146,7 +151,7 @@ def _handle_rules_list(def _handle_rules_add(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,user_id: int,@@ -215,7 +220,7 @@ def _handle_rules_add(def _handle_rules_remove(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,rule_numbers: list[int] | None,@@ -271,7 +276,7 @@ def _handle_project_show(slack_user_id: str,slack_workspace_id: str,user_id: int,- workspace_candidates: list[Integration] | None = None,+ workspace_candidates: Sequence[WorkspaceIntegration] | None = None,*,command_prefix: str,) -> None:@@ -346,7 +351,7 @@ def _handle_project_set(slack_workspace_id: str,user_id: int,target_team_id: int,- workspace_candidates: list[Integration] | None = None,+ workspace_candidates: Sequence[WorkspaceIntegration] | None = None,) -> None:from posthog.models.user import User@@ -366,15 +371,7 @@ def _handle_project_set(if workspace_candidates is not None:target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)else:- target = (- Integration.objects.filter(- kind="slack",- integration_id=slack_workspace_id,- team_id=target_team_id,- )- .select_related("team", "team__organization")- .first()- )+ target = get_team_workspace_integration(target_team_id, slack_workspace_id)if target is None:post_slack_ephemeral(slack.client,@@ -388,7 +385,7 @@ def _handle_project_set(SlackSettings.objects.update_or_create(slack_workspace_id=slack_workspace_id,slack_user_id=slack_user_id,- defaults={"default_integration": target},+ defaults={"default_integration_id": target.id},)post_slack_ephemeral(slack.client,@@ -405,14 +402,14 @@ def _handle_project_set(def _handle_project_set_workspace(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,slack_user_id: str,slack_workspace_id: str,user_id: int,target_team_id: int,- workspace_candidates: list[Integration] | None = None,+ workspace_candidates: Sequence[WorkspaceIntegration] | None = None,*,command_prefix: str,) -> None:@@ -449,15 +446,7 @@ def _handle_project_set_workspace(if workspace_candidates is not None:target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)else:- target = (- Integration.objects.filter(- kind="slack",- integration_id=slack_workspace_id,- team_id=target_team_id,- )- .select_related("team", "team__organization")- .first()- )+ target = get_team_workspace_integration(target_team_id, slack_workspace_id)if target is None:post_slack_ephemeral(slack.client,@@ -471,7 +460,7 @@ def _handle_project_set_workspace(SlackSettings.objects.update_or_create(slack_workspace_id=slack_workspace_id,slack_user_id=None,- defaults={"default_integration": target},+ defaults={"default_integration_id": target.id},)post_slack_ephemeral(slack.client,@@ -520,7 +509,7 @@ def _handle_welcome_show(def _handle_welcome_set(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,slack_user_id: str,@@ -558,7 +547,7 @@ def resolve_command_target(user_id: int,channel: str,thread_ts: str,-) -> tuple[list[Integration], "ResolutionResult"]:+) -> tuple[Sequence[WorkspaceIntegration], "ResolutionResult"]:"""Load workspace candidates and decide which one to dispatch against.Returns ``(workspace_candidates, result)``. ``result.integration`` is@@ -613,14 +602,14 @@ def resolve_command_target(def dispatch_rules_command(command: "RulesCommand",slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,*,channel: str,thread_ts: str,slack_user_id: str,slack_workspace_id: str,user_id: int,- workspace_candidates: list[Integration] | None = None,+ workspace_candidates: Sequence[WorkspaceIntegration] | None = None,command_prefix: str,) -> None:"""Run the right handler for a parsed ``RulesCommand``. Assumes the caller hasdiff --git a/products/slack_app/backend/services/inbox_interactivity.py b/products/slack_app/backend/services/inbox_interactivity.pyindex 0d1f0e104071..088779f1857c 100644--- a/products/slack_app/backend/services/inbox_interactivity.py+++ b/products/slack_app/backend/services/inbox_interactivity.py@@ -15,17 +15,14 @@ from django.http import HttpResponseimport requestsimport structlog-from posthog.models.integration import Integration-from products.slack_app.backend import inbox_channel, onboardingfrom products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_usedfrom products.slack_app.backend.services import slack_welcome_messages+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, get_workspace_integrationlogger = structlog.get_logger(__name__)-SLACK_INTEGRATION_KIND = "slack"-def extract_inbox_hints(payload: dict) -> int | None:"""Integration id carried by an inbox onboarding interaction, used for region-ownership routing.@@ -78,16 +75,12 @@ def _post_ephemeral_via_response_url(response_url: str, text: str) -> None:post_response_url(response_url, {"response_type": "ephemeral", "replace_original": False, "text": text})-def _inbox_integration_from_payload(payload: dict) -> Integration | None:+def _inbox_integration_from_payload(payload: dict) -> WorkspaceIntegration | None:integration_id = extract_inbox_hints(payload)slack_team_id = payload.get("team", {}).get("id")if not integration_id or not slack_team_id:return None- return Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- ).first()+ return get_workspace_integration(integration_id, slack_team_id)def _reconnect_hint() -> str:diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex d611f5f22c20..f8baab037758 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -1,4 +1,4 @@-from collections.abc import Iterable+from collections.abc import Iterable, Sequencefrom dataclasses import fieldfrom typing import Literal, TypedDict@@ -7,7 +7,7 @@ from django.db.models import Qimport structlogfrom posthog.dataclasses import frozen-from posthog.models.integration import Integration+from posthog.integrations import IntegrationManagerfrom posthog.models.user import Userfrom posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.user_permissions import UserPermissions@@ -18,9 +18,12 @@ from products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMappingfrom products.slack_app.backend.services.slack_fork_context import get_pending_forkfrom products.slack_app.backend.services.slack_scopes import bot_is_ready+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, workspace_integrationslogger = structlog.get_logger(__name__)+SLACK_INTEGRATION_KIND = "slack"+ResolutionSource = Literal["thread","user_default",@@ -90,7 +93,9 @@ def user_resolution_failure_reply(return None-def _resolved_or_oldest(integration: Integration | None, candidates: list[Integration]) -> Integration | None:+def _resolved_or_oldest(+ integration: WorkspaceIntegration | None, candidates: Sequence[WorkspaceIntegration]+) -> WorkspaceIntegration | None:"""The resolved integration, falling back to the oldest install in `candidates`.Surfaces that must act on *some* integration rather than prompt for one share this@@ -106,16 +111,16 @@ def _resolved_or_oldest(integration: Integration | None, candidates: list[Integr@frozenclass ResolutionResult:- integration: Integration | None+ integration: WorkspaceIntegration | Nonesource: ResolutionSource- candidates: list[Integration] = field(default_factory=list)+ candidates: Sequence[WorkspaceIntegration] = field(default_factory=list)- def resolved_or_first(self) -> Integration | None:+ def resolved_or_first(self) -> WorkspaceIntegration | None:"""The resolved integration, falling back to the workspace's oldest install."""return _resolved_or_oldest(self.integration, self.candidates)-def project_label(integration: Integration) -> str:+def project_label(integration: WorkspaceIntegration) -> str:"""One project named the way every Slack surface names it.Shared so a prompt that lists candidates and names a default in prose cannot spell@@ -124,7 +129,9 @@ def project_label(integration: Integration) -> str:return f"{integration.team.organization.name} · {integration.team.name}"-def format_project_candidate_list(candidates: list[Integration], *, first: Integration | None = None) -> str:+def format_project_candidate_list(+ candidates: Sequence[WorkspaceIntegration], *, first: WorkspaceIntegration | None = None+) -> str:"""One line per project, ``first`` at the head of the list.The order is otherwise ``check_integrations_auth_and_filter``'s, which sorts by@@ -145,7 +152,7 @@ def format_project_candidate_list(candidates: list[Integration], *, first: Integdef pick_a_project_message(intro: str,- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],*,set_command: str,home_tab_url: str | None,@@ -173,7 +180,7 @@ def pick_a_project_message(def resolve_from_candidates(- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],*,slack_team_id: str,slack_user_id: str = "",@@ -216,7 +223,7 @@ def resolve_from_candidates(# route through the canonical candidate for the same team in this# workspace so the mapping's ``task_run`` linkage stays intact.mapped = thread_match.integration- target: Integration | None = (+ target: WorkspaceIntegration | None = (mapped if mapped.id in candidate_ids else candidates_by_team_id.get(mapped.team_id))# Access check on the resolved target so a user whose access was@@ -288,11 +295,7 @@ def load_integrations("""from products.slack_app.backend.services.slack_auth import check_integrations_auth_and_filter- candidates = list(- Integration.objects.filter(kind__in=kinds, integration_id=slack_team_id)- .select_related("team", "team__organization", "created_by")- .order_by("id")- )+ candidates = workspace_integrations(slack_team_id) if SLACK_INTEGRATION_KIND in kinds else []candidates = check_integrations_auth_and_filter(candidates, slack_user_id=slack_user_id or None)return resolve_from_candidates(candidates,@@ -304,7 +307,7 @@ def load_integrations()-def accessible_candidates(candidates: Iterable[Integration], *, user: User) -> list[Integration]:+def accessible_candidates(candidates: Iterable[WorkspaceIntegration], *, user: User) -> list[WorkspaceIntegration]:"""The candidates whose project this user is a member of.Per-team ``effective_membership_level`` rather than ``user.teams``: the latter keys@@ -323,16 +326,13 @@ def multiple_accessible_projects(*, slack_team_id: str, user: User) -> bool:there is anything to tell apart should not pay an ``auth.test`` per candidate.``routable_projects`` asks the stricter question of where a run may actually be sent."""- installs = Integration.objects.filter(kind="slack", integration_id=slack_team_id)- # Accessible is a subset of installed, so one install settles it without the- # membership scan — on a count, which reads an index rather than hydrating and- # decrypting every row.- if installs.count() < 2:+ # Accessible is a subset of installed, so one install settles it without loading any row.+ if IntegrationManager.slack.oauth.count_by_external_id(slack_team_id) < 2:return False- return len(accessible_candidates(installs.select_related("team"), user=user)) > 1+ return len(accessible_candidates(workspace_integrations(slack_team_id), user=user)) > 1-def routable_projects(*, slack_team_id: str, slack_user_id: str, user: User) -> list[Integration]:+def routable_projects(*, slack_team_id: str, slack_user_id: str, user: User) -> list[WorkspaceIntegration]:"""The projects a message from this user may route itself to, in this workspace.Empty when there is nothing to choose between, which is the common answer. Installs@@ -368,13 +368,13 @@ class UserAndIntegrationsResolution:"""user: User | None = None- integration: Integration | None = None- candidates: list[Integration] = field(default_factory=list)+ integration: WorkspaceIntegration | None = None+ candidates: Sequence[WorkspaceIntegration] = field(default_factory=list)source: ResolutionSource = "needs_picker"failure_reason: UserResolutionFailure | None = Noneslack_email: str | None = None- def resolved_or_first(self) -> Integration | None:+ def resolved_or_first(self) -> WorkspaceIntegration | None:"""The integration this resolution picked, falling back to the oldest one the user can reach."""return _resolved_or_oldest(self.integration, self.candidates)@@ -397,7 +397,7 @@ class UnresolvedUserProperties(TypedDict):def unresolved_user_properties(- resolution: UserAndIntegrationsResolution, probe: Integration+ resolution: UserAndIntegrationsResolution, probe: WorkspaceIntegration) -> UnresolvedUserProperties:"""Analytics properties that tell apart the reasons a Slack user was not identified."""return {diff --git a/products/slack_app/backend/services/project_picker.py b/products/slack_app/backend/services/project_picker.pyindex 48847a4d96d4..4f64c5d789c8 100644--- a/products/slack_app/backend/services/project_picker.py+++ b/products/slack_app/backend/services/project_picker.py@@ -1,11 +1,12 @@import jsonimport time+from collections.abc import Sequencefrom typing import Any, Literal-from posthog.models.integration import Integrationfrom posthog.slack.formatting import escape_slack_mrkdwnfrom products.slack_app.backend.services.integration_resolver import project_label+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationPROJECT_PICKER_CONTEXT_KIND = "project_picker"PROJECT_PICKER_BLOCK_ID_PREFIX = "slack_app_project_picker"@@ -26,8 +27,8 @@ def build_project_picker_context(*,event: dict[str, Any],event_id: str | None,- probe: Integration,- candidates: list[Integration],+ probe: WorkspaceIntegration,+ candidates: Sequence[WorkspaceIntegration],slack_user_id: str,is_ext_shared_channel: bool,) -> dict[str, Any]:@@ -44,19 +45,19 @@ def build_project_picker_context(}-def _choice_text(integration: Integration) -> dict[str, Any]:+def _choice_text(integration: WorkspaceIntegration) -> dict[str, Any]:label = project_label(integration)if len(label) > _CHOICE_TEXT_MAX_LENGTH:label = f"{label[: _CHOICE_TEXT_MAX_LENGTH - 1]}…"return {"type": "plain_text", "text": label}-def _choice_value(integration: Integration, slack_user_id: str) -> str:+def _choice_value(integration: WorkspaceIntegration, slack_user_id: str) -> str:return json.dumps({"integration_id": integration.id, "mentioning_slack_user_id": slack_user_id})def build_project_picker_blocks(- candidates: list[Integration],+ candidates: Sequence[WorkspaceIntegration],*,context_token: str,slack_user_id: str,@@ -145,7 +146,7 @@ def pick_rejection(return None-def project_picked_message(integration: Integration, *, home_tab_url: str | None) -> str:+def project_picked_message(integration: WorkspaceIntegration, *, home_tab_url: str | None) -> str:home_tab = f"<{home_tab_url}|Home tab>" if home_tab_url else "Home tab"return (f"Using *{escape_slack_mrkdwn(project_label(integration))}* for this and your future mentions. "diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex ef76efaf683d..17635f2749e5 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -15,7 +15,7 @@ in `products/slack_app/backend/api.py` are the ones that actually callfrom __future__ import annotations-from collections.abc import Iterable, Mapping+from collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass, replacefrom datetime import datetime, timedeltafrom typing import Any, Literal@@ -26,7 +26,7 @@ from django.http import HttpResponse, JsonResponseimport structlog-from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegration+from posthog.models.integration import SLACK_INTEGRATION_KINDS, SlackIntegrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration@@ -87,6 +87,11 @@ from products.slack_app.backend.services.slack_settings import ()from products.slack_app.backend.services.slack_user_info import is_slack_workspace_adminfrom products.slack_app.backend.services.slack_user_oauth import build_invite_url, find_linked_posthog_user+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ get_team_workspace_integration,+ workspace_integrations,+)logger = structlog.get_logger(__name__)@@ -1718,7 +1723,7 @@ def _selected_value(state: dict, block_prefix: str, action_id: str) -> str | Non# here.-def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Integration) -> None:+def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: WorkspaceIntegration) -> None:"""Publish the Home tab for the user who just opened it.The caller resolves the integration through the shared region gate, so this@@ -1950,7 +1955,7 @@ def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonRespons# ----------------------------------------------------------------------------def _resolve_interaction_integration(slack_team_id: str, slack_user_id: str) -> Integration | None:+def _resolve_interaction_integration(slack_team_id: str, slack_user_id: str) -> WorkspaceIntegration | None:"""The integration the viewer's Home tab is rendered against.Same resolver the publish path runs, so a click is answered for the project the viewer@@ -1968,7 +1973,7 @@ def _resolve_interaction_integration(slack_team_id: str, slack_user_id: str) ->return result.resolved_or_first()-def _stored_personal_preferences(integration: Integration, slack_user_id: str) -> AIPreferences:+def _stored_personal_preferences(integration: WorkspaceIntegration, slack_user_id: str) -> AIPreferences:"""The viewer's stored central preference, for prefilling the edit modal.Deliberately the stored per-user value rather than the resolved default: the@@ -1992,7 +1997,7 @@ def _stored_personal_preferences(integration: Integration, slack_user_id: str) -)-def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:+def _is_admin(slack: SlackIntegration, integration: WorkspaceIntegration, slack_user_id: str) -> bool:try:return is_slack_workspace_admin(slack, integration, slack_user_id)except Exception:@@ -2004,7 +2009,7 @@ def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id:return False-def _open_edit_modal(integration: Integration, slack_user_id: str, *, trigger_id: str) -> None:+def _open_edit_modal(integration: WorkspaceIntegration, slack_user_id: str, *, trigger_id: str) -> None:current = _stored_personal_preferences(integration, slack_user_id)supported = _supported_efforts(current.runtime_adapter, current.model)slack = SlackIntegration(integration)@@ -2041,7 +2046,7 @@ def _render_unavailable_modal() -> dict:}-def _update_modal_after_input_change(payload: dict, integration: Integration) -> HttpResponse:+def _update_modal_after_input_change(payload: dict, integration: WorkspaceIntegration) -> HttpResponse:"""Re-render the modal in response to a runtime_adapter or model change.Reads the in-flight state from `payload["view"]`, drops whatever the change@@ -2094,8 +2099,8 @@ def _supported_efforts(runtime_adapter: str | None, model: str | None) -> list[sdef _routed_project_integration(- integration: Integration, slack_user_id: str, *, accessible: list[Integration] | None = None-) -> Integration | None:+ integration: WorkspaceIntegration, slack_user_id: str, *, accessible: Sequence[WorkspaceIntegration] | None = None+) -> WorkspaceIntegration | None:"""The integration of the project this viewer's mentions currently route to,restricted to projects the viewer can access. None when they can reach none.Pass `accessible` when the caller already resolved it, to skip the repeat@@ -2113,7 +2118,9 @@ def _routed_project_integration(return None-def _personal_preference_target(integration: Integration, slack_user_id: str) -> tuple[User, Integration]:+def _personal_preference_target(+ integration: WorkspaceIntegration, slack_user_id: str+) -> tuple[User, WorkspaceIntegration]:"""The PostHog user behind this viewer and the project whose central configthey edit — the one their mentions route to, restricted to this user's ownaccess via `resolve_from_candidates(user=...)`.@@ -2145,7 +2152,7 @@ def _personal_preference_target(integration: Integration, slack_user_id: str) ->def _apply_personal_preferences(- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,*,runtime_adapter: str | None,@@ -2184,7 +2191,7 @@ def _apply_personal_preferences()-def _reset_personal_preferences(integration: Integration, slack_user_id: str) -> None:+def _reset_personal_preferences(integration: WorkspaceIntegration, slack_user_id: str) -> None:"""Clear the viewer's central per-(user, project) preference, which resetsthem to the project default. The reset button only renders for viewers withsuch a preference, so an unmapped viewer is a no-op here."""@@ -2213,7 +2220,7 @@ def _picked_untagged_mode(action: dict) -> UntaggedFollowupMode | None:return UntaggedFollowupMode(picked) if picked in UntaggedFollowupMode.values else None-def _clear_project_personal(integration: Integration, slack_user_id: str) -> None:+def _clear_project_personal(integration: WorkspaceIntegration, slack_user_id: str) -> None:"""Clear the personal routing override; drop the row once it holds nothing else."""row = SlackSettings.objects.filter(@@ -2247,7 +2254,7 @@ class _HomeRender:def _build_home_view(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,*,view_state: HomeViewState | None = None,@@ -2311,7 +2318,7 @@ def _build_home_view(def _republish_home(- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,*,view_state: HomeViewState | None = None,@@ -2348,10 +2355,10 @@ _TASKS_RECENT_WINDOW = timedelta(days=14)def _resolve_tasks_state(- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,*,- accessible: list[Integration],+ accessible: Sequence[WorkspaceIntegration],selected_repo: str | None = None,selected_status: str | None = None,page: int = 0,@@ -2499,7 +2506,7 @@ def _format_relative(when: datetime | None, *, now: datetime) -> str:def _resolve_run_defaults_state(- integration: Integration, slack_user_id: str, *, accessible: list[Integration]+ integration: WorkspaceIntegration, slack_user_id: str, *, accessible: Sequence[WorkspaceIntegration]) -> RunDefaultsState:"""The PostHog default this person's Slack runs fall back to, plus where to change it.@@ -2546,7 +2553,11 @@ def _resolve_run_defaults_state(def _resolve_own_plan_state(- integration: Integration, slack_user_id: str, home_user: User | None, *, accessible: list[Integration]+ integration: WorkspaceIntegration,+ slack_user_id: str,+ home_user: User | None,+ *,+ accessible: Sequence[WorkspaceIntegration],) -> OwnPlanState | None:"""The ChatGPT plan card for this viewer, or `None` when the card is not offered."""from products.slack_app.backend.services.slack_messages import ai_subscriptions_url # noqa: PLC0415@@ -2568,11 +2579,11 @@ def _resolve_own_plan_state(return None-def _auto_model_choice_offered(integration: Integration, slack_user_id: str) -> bool:+def _auto_model_choice_offered(integration: WorkspaceIntegration, slack_user_id: str) -> bool:return _resolve_home_user(integration, slack_user_id) is not None-def _resolve_account_state(integration: Integration, slack_user_id: str) -> AccountState:+def _resolve_account_state(integration: WorkspaceIntegration, slack_user_id: str) -> AccountState:slack_team_id = integration.integration_idif not is_slack_app_oauth_enabled(integration):return AccountState(enabled=False)@@ -2604,7 +2615,7 @@ def _resolve_account_state(integration: Integration, slack_user_id: str) -> Accoreturn AccountState(enabled=True, linked_email=None, link_url=link_url)-def _resolve_home_user(integration: Integration, slack_user_id: str) -> User | None:+def _resolve_home_user(integration: WorkspaceIntegration, slack_user_id: str) -> User | None:"""Identify the PostHog user behind this Slack identity.Mirrors the event-path cascade in `resolve_posthog_user_from_event`: the@@ -2644,7 +2655,7 @@ def _resolve_home_user(integration: Integration, slack_user_id: str) -> User | Nreturn membership.user if membership else None-def _analytics_home_user(integration: Integration, slack_user_id: str) -> User | None:+def _analytics_home_user(integration: WorkspaceIntegration, slack_user_id: str) -> User | None:# Attribution is best-effort, so a failed lookup must not cost the reader the publish or the click.try:return _resolve_home_user(integration, slack_user_id)@@ -2653,7 +2664,7 @@ def _analytics_home_user(integration: Integration, slack_user_id: str) -> User |return None-def _resolve_github_state(integration: Integration, slack_user_id: str) -> GitHubState:+def _resolve_github_state(integration: WorkspaceIntegration, slack_user_id: str) -> GitHubState:"""List the personal GitHub installations of the user opening the Home tab.Usability comes from the tasks facade, the same judgment@@ -2704,16 +2715,12 @@ def _github_account_from_row(row: UserIntegration) -> GitHubAccount:)-def _workspace_integrations(slack_team_id: str) -> list[Integration]:+def _workspace_integrations(slack_team_id: str) -> list[WorkspaceIntegration]:"""Every PostHog project this Slack workspace is connected to."""- return list(- Integration.objects.filter(kind="slack", integration_id=slack_team_id)- .select_related("team", "team__organization")- .order_by("id")- )+ return workspace_integrations(slack_team_id)-def _accessible_integrations(integration: Integration, slack_user_id: str) -> list[Integration]:+def _accessible_integrations(integration: WorkspaceIntegration, slack_user_id: str) -> list[WorkspaceIntegration]:"""The workspace's projects this Slack user can actually reach in PostHog.Resolved once per publish and handed to every card: it costs a `UserPermissions`@@ -2730,9 +2737,9 @@ def _accessible_integrations(integration: Integration, slack_user_id: str) -> lidef _resolve_stats_state(- integration: Integration,+ integration: WorkspaceIntegration,*,- accessible: list[Integration],+ accessible: Sequence[WorkspaceIntegration],is_admin: bool,window_days: int = DEFAULT_STATS_WINDOW_DAYS,force_refresh: bool = False,@@ -2767,7 +2774,7 @@ def _resolve_stats_state(def _resolve_project_state(- integration: Integration, slack_user_id: str, *, accessible: list[Integration]+ integration: WorkspaceIntegration, slack_user_id: str, *, accessible: Sequence[WorkspaceIntegration]) -> ProjectState:candidates = _workspace_integrations(integration.integration_id)if not candidates:@@ -2790,7 +2797,7 @@ def _resolve_project_state(.first())- def project_label(c: Integration) -> str:+ def project_label(c: WorkspaceIntegration) -> str:return f"{c.team.organization.name} · {c.team.name}"# Look up the workspace default's label against the full candidate list,@@ -2814,8 +2821,8 @@ def _resolve_project_state(def _filter_accessible_integrations(- integration: Integration, slack_user_id: str, candidates: list[Integration]-) -> list[Integration]:+ integration: WorkspaceIntegration, slack_user_id: str, candidates: Sequence[WorkspaceIntegration]+) -> list[WorkspaceIntegration]:"""The candidates this Slack identity can reach.`views.publish` answers whoever opens the tab, including a Slack Connect guest with no@@ -2832,7 +2839,7 @@ def _filter_accessible_integrations(def _apply_project_pick(- integration: Integration,+ integration: WorkspaceIntegration,*,actor_slack_user_id: str,action: dict,@@ -2850,11 +2857,7 @@ def _apply_project_pick(team_id = int(selected)except (TypeError, ValueError):return- target = (- Integration.objects.filter(kind="slack", integration_id=integration.integration_id, team_id=team_id)- .select_related("team", "team__organization")- .first()- )+ target = get_team_workspace_integration(team_id, integration.integration_id)if target is None:return# The renderer hides options the clicker can't reach, but a hand-crafted@@ -2865,7 +2868,7 @@ def _apply_project_pick(SlackSettings.objects.update_or_create(slack_workspace_id=integration.integration_id,slack_user_id=actor_slack_user_id if scope == "personal" else None,- defaults={"default_integration": target},+ defaults={"default_integration_id": target.id},)logger.info("slack_app_home_project_default_set",@@ -2876,7 +2879,7 @@ def _apply_project_pick()-def _unlink_user_account(integration: Integration, slack_user_id: str) -> None:+def _unlink_user_account(integration: WorkspaceIntegration, slack_user_id: str) -> None:# Scope across every org connected to this Slack workspace, not just the# one for the integration the click happened to land on — for multi-org# workspaces, the linked row may live in any of them.@@ -2897,11 +2900,7 @@ def _unlink_user_account(integration: Integration, slack_user_id: str) -> None:def _workspace_org_ids(slack_team_id: str) -> set:- return set(- Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list(- "team__organization_id", flat=True- )- )+ return {row.team.organization_id for row in workspace_integrations(slack_team_id)}def _modal_error_response(message: str) -> JsonResponse:diff --git a/products/slack_app/backend/services/slack_auth.py b/products/slack_app/backend/services/slack_auth.pyindex 9adfa6b85e2d..a5e1ebcfe5fd 100644--- a/products/slack_app/backend/services/slack_auth.py+++ b/products/slack_app/backend/services/slack_auth.py@@ -32,11 +32,11 @@ from django.utils import timezoneimport structlog+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration+if TYPE_CHECKING:from slack_sdk.errors import SlackApiError- from posthog.models.integration import Integration-logger = structlog.get_logger(__name__)# Six hours matches the precedent set by the previous bot-user-id cache —@@ -127,7 +127,7 @@ def classify_slack_api_error(exc: "SlackApiError") -> tuple[str | None, bool]:def _resolve_one_candidate_state(- candidate: "Integration", slack_user_id: str | None+ candidate: "WorkspaceIntegration", slack_user_id: str | None) -> SlackIntegrationAuthState | None:"""Return the auth-state verdict for ``candidate``, populating the cache via``auth.test`` on miss. Returns ``None`` when the verdict is unknown@@ -200,10 +200,10 @@ def _resolve_one_candidate_state(def check_integrations_auth_and_filter(- candidates: list["Integration"],+ candidates: list["WorkspaceIntegration"],*,slack_user_id: str | None = None,-) -> list["Integration"]:+) -> list["WorkspaceIntegration"]:"""Check each candidate's bot-token health and return only the healthy ones,sorted with the freshest verdict first.@@ -260,9 +260,9 @@ def check_integrations_auth_and_filter(if not candidates:return candidates- healthy: list[tuple[Integration, datetime]] = []- unknown: list[Integration] = []- broken: list[Integration] = []+ healthy: list[tuple[WorkspaceIntegration, datetime]] = []+ unknown: list[WorkspaceIntegration] = []+ broken: list[WorkspaceIntegration] = []for candidate in candidates:state = _resolve_one_candidate_state(candidate, slack_user_id)if state is None:diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex bdf9851fbbab..22b0ee2cbfd0 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -35,13 +35,15 @@ from slack_sdk.errors import SlackApiErrorfrom slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandlerfrom posthog.dataclasses import frozen-from posthog.models.integration import Integration, SlackIntegration+from posthog.integrations import IntegrationManager, IntegrationNotFound+from posthog.models.integration import SlackIntegrationfrom posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.slack.markdown import opens_with_line_anchored_markdownfrom posthog.utils import absolute_urifrom products.slack_app.backend.services.model_catalogue import describe_run_modelfrom products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id, get_slack_user_info+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationlogger = structlog.get_logger(__name__)@@ -60,7 +62,7 @@ SLACK_WEBHOOK_TIMEOUT_SECONDS = 3def resolve_user_mentions_text(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,text: str,*,strip_bot_user_id: str | None = None,@@ -150,7 +152,7 @@ def unwrap_slack_links(text: str) -> str:def _resolve_and_decode(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,text: str,*,strip_bot_user_id: str | None = None,@@ -166,7 +168,7 @@ def _resolve_and_decode(return decode_slack_entities(resolved)-def decode_slack_event_text(slack: SlackIntegration, integration: Integration, text: str) -> str:+def decode_slack_event_text(slack: SlackIntegration, integration: WorkspaceIntegration, text: str) -> str:"""Strip the bot's own self-mention from a Slack event and label the rest for the agent.Trigger sites all want the same thing: drop the bot's self-ping (it's just@@ -545,7 +547,7 @@ def messages_at_or_before(messages: list[SlackThreadMessage], bound_ts: str) ->def collect_thread_messages(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,our_bot_id: str | None,@@ -626,7 +628,7 @@ def collect_thread_messages(def cached_collect_thread_messages(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,channel: str,thread_ts: str,our_bot_id: str | None,@@ -745,15 +747,14 @@ def _project_name(team_id: int, *, integration_id: int | None, created_by_id: in# The id is the install this reply posts through, read off stored thread state# rather than off the message, and all this reads from the row is the Slack# workspace it belongs to.- integration = (- Integration.objects.filter(pk=integration_id) # nosemgrep: idor-lookup-without-team- .only("integration_id")- .first()- )+ try:+ integration = IntegrationManager.slack.oauth.get(team_id, integration_id)+ except IntegrationNotFound:+ return Noneuser = User.objects.filter(pk=created_by_id).first()- if integration is None or user is None:+ if user is None:return None- if not multiple_accessible_projects(slack_team_id=integration.integration_id, user=user):+ if not multiple_accessible_projects(slack_team_id=integration.integration_id or "", user=user):return Noneteam = Team.objects.filter(pk=team_id).only("name").first()except Exception:@@ -1011,7 +1012,7 @@ def context_block(text: str) -> dict[str, Any]:return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}-def app_home_url(integration: Integration, *, tab: str = "home") -> str | None:+def app_home_url(integration: WorkspaceIntegration, *, tab: str = "home") -> str | None:"""Deep link to this install's Home tab, where the model picker lives.The native `slack://` form rather than the https `app_redirect` one: the reader is@@ -1061,7 +1062,7 @@ def _public_url(path: str) -> str:return absolute_uri(path)-def viewer_has_code_access(integration: Integration, slack_user_id: str | None) -> bool:+def viewer_has_code_access(integration: WorkspaceIntegration, slack_user_id: str | None) -> bool:"""Whether the Slack identity reading this can open a PostHog Code link.Asked about the reader rather than the task's creator: the two can differ, and a linkdiff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pyindex 0db524a53c98..f1e7ef192463 100644--- a/products/slack_app/backend/services/slack_settings.py+++ b/products/slack_app/backend/services/slack_settings.py@@ -12,14 +12,12 @@ layer with zero translation.from __future__ import annotationsfrom dataclasses import dataclass-from typing import TYPE_CHECKING, TypeVar+from typing import TypeVarfrom django.db import modelsfrom products.slack_app.backend.models import ChannelWelcomeMode, ThreadJoinMode, UntaggedFollowupMode--if TYPE_CHECKING:- from posthog.models.integration import Integration+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration_Mode = TypeVar("_Mode", bound=models.TextChoices)@@ -37,7 +35,9 @@ class AIPreferences:reasoning_effort: str | None = None-def resolve_untagged_followup_mode(integration: Integration, slack_user_id: str | None) -> UntaggedFollowupMode:+def resolve_untagged_followup_mode(+ integration: WorkspaceIntegration, slack_user_id: str | None+) -> UntaggedFollowupMode:"""Resolve how untagged replies in a thread this Slack user started are treated.Read from the thread creator's row, so one person's choice governs every@@ -113,7 +113,7 @@ def _set_untagged_mode(slack_workspace_id: str, slack_user_id: str, column: str,def resolve_thread_join_mode(- integration: Integration, slack_user_id: str | None, *, own_subscription: bool = False+ integration: WorkspaceIntegration, slack_user_id: str | None, *, own_subscription: bool = False) -> ThreadJoinMode:"""Resolve what happens when someone else tags PostHog in a thread this Slack user started.diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.pyindex 6c742f6dc83c..debf36ab335c 100644--- a/products/slack_app/backend/services/slack_user_info.py+++ b/products/slack_app/backend/services/slack_user_info.py@@ -28,7 +28,8 @@ from django.utils import timezoneimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegration+from posthog.integrations import IntegrationRecord+from posthog.models.integration import SLACK_INTEGRATION_KINDS, SlackIntegrationfrom products.slack_app.backend.models import SlackUserProfileCachefrom products.slack_app.backend.services.slack_auth import (@@ -78,7 +79,7 @@ def normalize_slack_response(payload: Any) -> dict[str, Any]:return {}-def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -> dict[str, Any] | None:+def _get_slack_user_info_from_db(integration: IntegrationRecord, slack_user_id: str) -> dict[str, Any] | None:try:profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id@@ -99,7 +100,7 @@ def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -)-def persist_slack_user_info(integration: Integration, slack_user_id: str, user_info: dict[str, Any]) -> None:+def persist_slack_user_info(integration: IntegrationRecord, slack_user_id: str, user_info: dict[str, Any]) -> None:user = user_info.get("user", {})profile = user.get("profile", {})try:@@ -120,7 +121,7 @@ def persist_slack_user_info(integration: Integration, slack_user_id: str, user_ilogger.warning("slack_app_slack_user_cache_db_unavailable", integration_id=integration.id)-def get_slack_user_info(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> dict[str, Any]:+def get_slack_user_info(slack: SlackIntegration, integration: IntegrationRecord, slack_user_id: str) -> dict[str, Any]:cached_db = _get_slack_user_info_from_db(integration, slack_user_id)if isinstance(cached_db, dict):return cached_db@@ -132,14 +133,14 @@ def get_slack_user_info(slack: SlackIntegration, integration: Integration, slackreturn {}-def is_slack_workspace_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:+def is_slack_workspace_admin(slack: SlackIntegration, integration: IntegrationRecord, slack_user_id: str) -> bool:"""Whether the Slack user is a workspace admin or owner."""user_info = get_slack_user_info(slack, integration, slack_user_id)slack_user = user_info.get("user", {}) if isinstance(user_info, dict) else {}return bool(slack_user.get("is_admin") or slack_user.get("is_owner"))-def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:+def _get_slack_user_id_by_email_from_db(integration: IntegrationRecord, normalized_email: str) -> str | None:try:profile = SlackUserProfileCache.objects.filter(integration_id=integration.id,@@ -155,7 +156,7 @@ def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_emadef lookup_slack_user_id_by_email(slack: SlackIntegration,- integration: Integration,+ integration: IntegrationRecord,email: str,) -> str | None:"""Resolve a Slack user ID from a PostHog user email.@@ -197,7 +198,7 @@ def lookup_slack_user_id_by_email(return slack_user_id-def _purge_stale_email_rows(integration: Integration, normalized_email: str, keep_slack_user_id: str) -> None:+def _purge_stale_email_rows(integration: IntegrationRecord, normalized_email: str, keep_slack_user_id: str) -> None:"""Drop rows that share an email with the authoritative Slack user ID we just resolved.Without this, an orphan row (same email, older Slack user ID) can outrank the fresh one@@ -278,7 +279,7 @@ def invalidate_workspace_bot_user_id(slack_team_id: str) -> None:logger.warning("slack_app_workspace_bot_user_cache_delete_failed", slack_team_id=slack_team_id)-def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:+def get_cached_bot_user_id(slack: SlackIntegration, integration: IntegrationRecord) -> str | None:"""Return the bot's Slack user id for ``integration``, populating theshared auth-state cache as a side effect.@@ -338,7 +339,7 @@ def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) ->_USER_MENTION_RE = re.compile(r"<@([A-Z0-9]+)(?:\|[^>]*)?>")-def find_addressed_bot_user_id(slack: SlackIntegration, integration: Integration, text: str) -> str | None:+def find_addressed_bot_user_id(slack: SlackIntegration, integration: IntegrationRecord, text: str) -> str | None:"""The user id of a bot other than ours that this message tags, or ``None``.Callers ask this to tell a message addressed to another app from one addressed to us.diff --git a/products/slack_app/backend/services/slack_welcome_messages.py b/products/slack_app/backend/services/slack_welcome_messages.pyindex 30c8fb65d4b0..cfdea8493ac8 100644--- a/products/slack_app/backend/services/slack_welcome_messages.py+++ b/products/slack_app/backend/services/slack_welcome_messages.py@@ -18,7 +18,7 @@ from typing import Anyfrom django.conf import settings-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.slack.formatting import channel_id_from_targetfrom posthog.utils import absolute_uri@@ -31,6 +31,7 @@ from products.slack_app.backend.inbox_channel import ()from products.slack_app.backend.services.followup_invite import BOT_SETUP_DOCS_URLfrom products.slack_app.backend.services.slack_messages import app_home_url, context_block, section_block+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration# Block Kit action ids for the onboarding DM, kept in sync with the interactivity router.INBOX_CREATE_ACTION_ID = "slack_inbox_create"@@ -74,7 +75,7 @@ def _feedback_block() -> dict[str, Any]:)-def _home_tab(integration: Integration, label: str = "my Home tab") -> str:+def _home_tab(integration: WorkspaceIntegration, label: str = "my Home tab") -> str:"""``label``, linked to this install's Home tab where there is one to link to.An install that predates the app id on its config has no deep link, and the tab is@@ -104,7 +105,7 @@ def build_assistant_pane_welcome() -> str:)-def build_channel_welcome(integration: Integration) -> tuple[str, list[dict[str, Any]]]:+def build_channel_welcome(integration: WorkspaceIntegration) -> tuple[str, list[dict[str, Any]]]:"""Posted in a channel the moment the app is added to it.Written for everyone in the channel rather than for whoever did the adding.@@ -146,7 +147,7 @@ def build_channel_welcome(integration: Integration) -> tuple[str, list[dict[str,return "Hey, I'm PostHog. Tag me with @PostHog to get started.", blocks-def build_team_join_welcome(integration: Integration) -> tuple[str, list[dict[str, Any]]]:+def build_team_join_welcome(integration: WorkspaceIntegration) -> tuple[str, list[dict[str, Any]]]:"""DM'd to someone who just joined a workspace that already has the app.They inherited a tool nobody introduced them to, so this says what it is before it@@ -214,7 +215,7 @@ def _github_connect_url(team_id: int) -> str:return _public_url(f"/integrations/connect/github/?project_id={team_id}&connect_from=slack")-def _github_blocks(integration: Integration, *, done: bool) -> list[dict]:+def _github_blocks(integration: WorkspaceIntegration, *, done: bool) -> list[dict]:blocks: list[dict] = [section_block("*1. Connect your codebase* :wrench:\nConnect GitHub so I can fix things, not just flag them - "@@ -236,7 +237,7 @@ def _github_blocks(integration: Integration, *, done: bool) -> list[dict]:return blocks-def _sources_blocks(integration: Integration) -> list[dict]:+def _sources_blocks(integration: WorkspaceIntegration) -> list[dict]:"""Inline checkboxes (current state pre-checked) — ticking sets a source up immediately, unticking turns it off."""from products.signals.backend.facade.api import (onboarding_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path@@ -267,7 +268,7 @@ def _sources_blocks(integration: Integration) -> list[dict]:return blocks-def _channel_blocks(integration: Integration, slack: SlackIntegration, *, done: bool) -> list[dict]:+def _channel_blocks(integration: WorkspaceIntegration, slack: SlackIntegration, *, done: bool) -> list[dict]:blocks: list[dict] = [section_block("*3. Where I report* :inbox_tray:\nEverything I find lands in one shared channel so the team stays in the loop."@@ -296,7 +297,7 @@ def _channel_blocks(integration: Integration, slack: SlackIntegration, *, done:return blocks-def _ai_approval_blocks(integration: Integration, *, is_admin: bool) -> list[dict]:+def _ai_approval_blocks(integration: WorkspaceIntegration, *, is_admin: bool) -> list[dict]:"""The approval prompt — only rendered when not yet approved. Admins tick a checkbox to approve;non-admins get an 'ask an admin' note, since only ADMIN+ can toggle org settings."""blocks: list[dict] = [@@ -329,7 +330,7 @@ def _ai_approval_blocks(integration: Integration, *, is_admin: bool) -> list[dicdef build_onboarding_dm(- integration: Integration,+ integration: WorkspaceIntegration,slack: SlackIntegration,*,needs_ai_approval: bool = False,diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.pyindex 89377c8eb303..5fe03c71bb2b 100644--- a/products/slack_app/backend/services/turn_feedback.py+++ b/products/slack_app/backend/services/turn_feedback.py@@ -29,7 +29,7 @@ import posthoganalyticsfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.analytics import slack_event_propsfrom products.slack_app.backend.logic.feature_tips.features import SlackFeature@@ -37,11 +37,10 @@ from products.slack_app.backend.logic.feature_tips.state import record_feature_ufrom products.slack_app.backend.logic.interview_recruitment import MODAL_INVITE_MESSAGE, book_button, invite_sectionfrom products.slack_app.backend.services.slack_messages import SLACK_WEBHOOK_TIMEOUT_SECONDS, TURN_FEEDBACK_ACTION_IDfrom products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, get_workspace_integrationlogger = structlog.get_logger(__name__)-SLACK_INTEGRATION_KIND = "slack"-TURN_FEEDBACK_MODAL_CALLBACK_ID = "slack_app_turn_feedback_modal"_MODAL_TEXT_BLOCK_ID = "feedback_text"_MODAL_TEXT_ACTION_ID = "text"@@ -91,7 +90,7 @@ class _FeedbackTarget:way; ``_trace_id`` says what stands behind it instead."""- integration: Integration+ integration: WorkspaceIntegrationrun_id: strtask_id: str | Noneturn_id: str | None@@ -140,7 +139,7 @@ def extract_modal_hint(payload: dict) -> int | None:return integration_id if isinstance(integration_id, int) else None-def _local_integration(integration_id: Any, slack_team_id: str | None) -> Integration | None:+def _local_integration(integration_id: Any, slack_team_id: str | None) -> WorkspaceIntegration | None:"""The integration a rating names, if this region owns it for that Slack team.Scoped to the Slack team the rating came from, so a forged id resolves to nothing@@ -149,23 +148,13 @@ def _local_integration(integration_id: Any, slack_team_id: str | None) -> Integr"""if not slack_team_id or not isinstance(integration_id, int):return None- return (- Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get- kind=SLACK_INTEGRATION_KIND,- integration_id=slack_team_id,- )- # The event properties and the capture's groups both read through to the team and- # its organization, and Slack gives the interaction three seconds.- .select_related("team__organization")- .first()- )+ return get_workspace_integration(integration_id, slack_team_id)def _resolve_target(value: dict[str, Any],*,- integration: Integration,+ integration: WorkspaceIntegration,slack_user_id: str,turn_id: str | None,) -> _FeedbackTarget | None:@@ -465,7 +454,9 @@ def reaction_sentiment(reaction: Any) -> str | None:return _REACTION_SENTIMENTS.get(_reaction_base(reaction))-def _fetch_reacted_message(workspace_integration: Integration, channel: str, message_ts: str) -> dict[str, Any] | None:+def _fetch_reacted_message(+ workspace_integration: WorkspaceIntegration, channel: str, message_ts: str+) -> dict[str, Any] | None:"""The reacted message, read back from Slack so its blocks can say which run it is.``conversations.replies`` accepts the ts of any message in a thread, and agent replies@@ -508,7 +499,9 @@ def _feedback_value_from_message(message: dict[str, Any]) -> dict[str, Any]:return {}-def handle_reaction_added(event: dict, slack_team_id: str, workspace_integration: Integration) -> ReactionOutcome:+def handle_reaction_added(+ event: dict, slack_team_id: str, workspace_integration: WorkspaceIntegration+) -> ReactionOutcome:"""Record a thumbs reaction on an agent reply as a rating.``workspace_integration`` is any of this region's integrations for the Slack team; itsdiff --git a/products/slack_app/backend/services/workspace_integrations.py b/products/slack_app/backend/services/workspace_integrations.pynew file mode 100644index 000000000000..c689154b8f7a--- /dev/null+++ b/products/slack_app/backend/services/workspace_integrations.py@@ -0,0 +1,70 @@+from collections.abc import Iterable+from typing import Protocol, cast++from django.db.models import Model, prefetch_related_objects++from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord+from posthog.models.team import Team++# Slack webhooks carry the workspace id and no team, so these reads scope rows by the workspace id.+++class WorkspaceIntegration(IntegrationRecord, Protocol):+ """A Slack row with its team and organization loaded. Only `with_teams` makes one."""++ @property+ def integration_id(self) -> str: ...++ @property+ def team(self) -> Team: ...+++def with_teams(rows: Iterable[IntegrationRecord]) -> list[WorkspaceIntegration]:+ """Load the team and organization of all rows in two queries, because callers read `row.team.organization`."""+ loaded = list(rows)+ prefetch_related_objects(cast(list[Model], loaded), "team__organization")+ # The prefetch above makes this true at runtime. A frozen record can replace it with a team lookup here.+ return cast(list[WorkspaceIntegration], loaded)+++def workspace_integrations(slack_team_id: str) -> list[WorkspaceIntegration]:+ """The Slack app rows of a workspace, one per linked project, oldest id first."""+ rows = IntegrationManager.slack.oauth.list_by_external_id(slack_team_id)+ return with_teams(sorted(rows, key=lambda row: row.id))+++def _fetch_workspace_integration(integration_id: object, slack_team_id: str) -> IntegrationRecord | None:+ if isinstance(integration_id, bool) or not isinstance(integration_id, int | str):+ return None+ try:+ wanted = int(integration_id)+ except ValueError:+ return None+ try:+ return IntegrationManager.slack.oauth.get_by_external_id(slack_team_id, wanted)+ except IntegrationNotFound:+ return None+++def get_workspace_integration(integration_id: object, slack_team_id: str) -> WorkspaceIntegration | None:+ """The Slack app row with this id in the workspace, or None when the id is unknown or invalid."""+ row = _fetch_workspace_integration(integration_id, slack_team_id)+ return None if row is None else with_teams([row])[0]+++def workspace_integration_exists(integration_id: object, slack_team_id: str) -> bool:+ return _fetch_workspace_integration(integration_id, slack_team_id) is not None+++def get_team_workspace_integration(team_id: int, slack_team_id: str) -> WorkspaceIntegration | None:+ """The Slack app row that links this workspace to this project, or None."""+ row = IntegrationManager.slack.oauth.find(team_id, external_id=slack_team_id)+ return None if row is None else with_teams([row])[0]+++def require_workspace_integration(integration_id: object, slack_team_id: str) -> WorkspaceIntegration:+ """Like `get_workspace_integration`, but raises `IntegrationNotFound` so a Temporal activity retries."""+ row = get_workspace_integration(integration_id, slack_team_id)+ if row is None:+ raise IntegrationNotFound(f"No Slack integration {integration_id!r} in workspace {slack_team_id!r}")+ return rowdiff --git a/products/slack_app/backend/signals.py b/products/slack_app/backend/signals.pyindex 8a021d58abf5..e6f7a7a983f0 100644--- a/products/slack_app/backend/signals.py+++ b/products/slack_app/backend/signals.py@@ -4,9 +4,11 @@ from django.db import transactionfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver-from posthog.models.integration import Integration+from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, workspace_integrations+@receiver(post_save, sender=UserIntegration)@receiver(post_delete, sender=UserIntegration)@@ -21,8 +23,8 @@ def invalidate_repo_list_on_user_github_change(sender: Any, instance: UserIntegr_invalidate_user_repo_list_cache(instance.user_id)-@receiver(post_save, sender=Integration)-def onboard_slack_inbox_on_install(sender: Any, instance: Integration, created: bool, **kwargs) -> None:+@receiver(post_save, sender="posthog.Integration")+def onboard_slack_inbox_on_install(sender: Any, instance: WorkspaceIntegration, created: bool, **kwargs) -> None:"""Fresh Slack install -> capture ``slack app installed`` and enqueue the #posthog-inbox onboardingTemporal workflow on commit (the enqueue runs inline; the workflow itself runs on a Temporalworker). Onboarding is gated on ``channels:manage``. Re-auth uses update_or_create@@ -43,7 +45,7 @@ def onboard_slack_inbox_on_install(sender: Any, instance: Integration, created:transaction.on_commit(lambda: _start_inbox_onboarding_workflow(integration_id))-def _capture_install(integration: Integration, *, has_inbox_scopes: bool) -> None:+def _capture_install(integration: WorkspaceIntegration, *, has_inbox_scopes: bool) -> None:from products.slack_app.backend.analytics import capture_slack_event # noqa: PLC0415from products.slack_app.backend.onboarding import installer_slack_user_id # noqa: PLC0415@@ -51,12 +53,12 @@ def _capture_install(integration: Integration, *, has_inbox_scopes: bool) -> Nonintegration,"slack app installed",slack_user_id=installer_slack_user_id(integration),- posthog_user=integration.created_by,+ posthog_user=User.objects.filter(id=integration.created_by_id).first(),has_inbox_scopes=has_inbox_scopes,# Only a workspace's first project connection is a new workspace adopting the app.- workspace_already_linked=Integration.objects.filter(kind="slack", integration_id=integration.integration_id)- .exclude(id=integration.id)- .exists(),+ workspace_already_linked=any(+ row.id != integration.id for row in workspace_integrations(integration.integration_id)+ ),)diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex 58f4c04f7a52..350f15b4d6d2 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -27,7 +27,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.dataclasses import frozenfrom posthog.models import Team, Userfrom posthog.models.comment import Comment-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.user_integration import UserIntegrationfrom posthog.object_tags.kinds import OBJECT_URL_TEMPLATES, ObjectRef, object_ref_for_urlfrom posthog.redis import get_client@@ -71,6 +71,7 @@ from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.services.followup_invite import build_followup_invitefrom products.slack_app.backend.services.slack_messages import UNFURL_OPT_OUT_PARAMfrom products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationfrom products.slack_app.backend.temporal.slack_app_unfurl_charts import (SLACK_APP_UNFURL_CHARTS_WORKFLOW_TIMEOUT,SlackAppUnfurlChartsWorkflow,@@ -508,7 +509,7 @@ def _claim_invite_slot(slack_team_id: str, channel: str) -> bool:return bool(claimed)-def _build_unfurl_invite(integration: Integration, kind: str, channel: str) -> dict | None:+def _build_unfurl_invite(integration: WorkspaceIntegration, kind: str, channel: str) -> dict | None:"""The invite block for the first resource we unfurled, or None when it should stay quiet.Consent is checked before the slot is claimed: the other way round, a workspace that never@@ -552,7 +553,7 @@ def _is_normal_public_channel(slack: SlackIntegration, channel: str, cache: dictdef _task_owner_can_view_public_slack_channel(slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,task: TaskSlackUnfurlDTO,cache: dict[str, bool],) -> bool:@@ -586,7 +587,7 @@ def _task_owner_can_view_public_slack_channel(def _attach_public_slack_thread_reference(*,slack: SlackIntegration,- integration: Integration,+ integration: WorkspaceIntegration,task: TaskSlackUnfurlDTO,event: dict,shared_by_slack_user_id: str,@@ -627,7 +628,7 @@ def _attach_public_slack_thread_reference(@frozenclass _UnfurlContext:slack: SlackIntegration- integration: Integration+ integration: WorkspaceIntegrationteam: Teamuser: Useruac: UserAccessControl@@ -1225,7 +1226,7 @@ def _post_unfurls(slack: SlackIntegration, event: dict, unfurls: dict[str, dict]def start_unfurl_charts(*,- integration: Integration,+ integration: WorkspaceIntegration,user: User,event: dict,unfurls: dict[str, dict],@@ -1273,7 +1274,7 @@ def start_unfurl_charts(def _queue_unfurl_charts(*,- integration: Integration,+ integration: WorkspaceIntegration,user: User,event: dict,unfurls: dict[str, dict],@@ -1300,7 +1301,7 @@ def _queue_unfurl_charts(def _queue_unfurl_artifact_image(- *, integration: Integration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str+ *, integration: WorkspaceIntegration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str) -> bool:"""Reading and storing the file is too slow for the webhook's ack budget, so it runs on Celery."""# noqa reason: the task module imports api, which imports this module at load time.@@ -1331,7 +1332,7 @@ class _ImageLink:failure: _ImageFailure | None = None-def _artifact_image_link(*, integration: Integration, user: User, url: str, title: str) -> _ImageLink:+def _artifact_image_link(*, integration: WorkspaceIntegration, user: User, url: str, title: str) -> _ImageLink:# The link opens without a PostHog login, so it follows the public sharing setting like chart images do.team = integration.teamif not team.organization.allow_publicly_shared_resources:@@ -1369,7 +1370,7 @@ def _artifact_image_link(*, integration: Integration, user: User, url: str, titldef add_artifact_image_to_unfurl(- *, integration: Integration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str+ *, integration: WorkspaceIntegration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str) -> None:"""Post a task artifact card again with its image. Best effort: a failure keeps the text card."""link = _artifact_image_link(integration=integration, user=user, url=url, title=title)@@ -1398,7 +1399,7 @@ def add_artifact_image_to_unfurl()-def _bot_reply_actor(integration: Integration, event: dict) -> str | None:+def _bot_reply_actor(integration: WorkspaceIntegration, event: dict) -> str | None:"""The Slack user steering the run in this thread, when that run was told to share chart links.Slack credits a message our app posts to our bot user, and some bot-posted messages to the@@ -1409,7 +1410,7 @@ def _bot_reply_actor(integration: Integration, event: dict) -> str | None:return Noneactors = (SlackThreadTaskMapping.objects.filter(- integration=integration,+ integration_id=integration.id,channel=event["channel"],thread_ts=event["thread_ts"],task_run__state__slack_chart_links=True,@@ -1422,7 +1423,7 @@ def _bot_reply_actor(integration: Integration, event: dict) -> str | None:return next((actor for actor in actors or () if actor), None)-def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:+def handle_posthog_link_unfurl(event: dict, integration: WorkspaceIntegration) -> None:"""Unfurl supported PostHog resource links with metadata.diff --git a/products/slack_app/backend/slack_workflow_events.py b/products/slack_app/backend/slack_workflow_events.pyindex c7ce46213439..93a168d1ed89 100644--- a/products/slack_app/backend/slack_workflow_events.py+++ b/products/slack_app/backend/slack_workflow_events.py@@ -10,7 +10,7 @@ from typing import Anyimport structlog-from posthog.models.integration import Integration+from posthog.integrations import IntegrationManagerfrom products.cdp.backend.internal_events import InternalEventEvent, produce_internal_event@@ -91,9 +91,9 @@ def emit_slack_message_event(# Integration is per team), and each configures its own workflows, so every one gets a copy.# Projects with nothing listening are discarded by the CDP consumer, which is cheaper than# asking Postgres here.- integrations = list(- Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list("team_id", "id")- )+ integrations = [+ (row.team_id, row.id) for row in IntegrationManager.slack.oauth.list_by_external_id(slack_team_id)+ ]except Exception:# Stay put on a lookup failure: handing the workspace over would turn a local database blip# into a cross-region hop for every message in every channel.diff --git a/products/slack_app/backend/tasks.py b/products/slack_app/backend/tasks.pyindex a72bbcc31e79..312a685c5017 100644--- a/products/slack_app/backend/tasks.py+++ b/products/slack_app/backend/tasks.py@@ -6,8 +6,8 @@ from celery import shared_taskfrom posthog.celery_queues import CeleryQueuefrom posthog.egress.limiter.policies import Priority+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.models import User-from posthog.models.integration import Integrationfrom posthog.models.scoping import with_team_scopefrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.scoping_audit import skip_team_scope_audit@@ -23,6 +23,7 @@ from products.slack_app.backend.logic.interview_recruitment import (linked_posthog_user,offer_frustration_invite,)+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, with_teamsfrom products.slack_app.backend.slack_link_unfurl import add_artifact_image_to_unfurl, start_unfurl_chartsfrom products.slack_app.backend.temporal.types import SlackUnfurlChartRequest@@ -66,8 +67,11 @@ def refresh_user_github_repository_cache(*, user_integration_id: str) -> None:github.sync_repository_cache(min_refresh_interval_seconds=REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS)-def _load_integration(integration_id: int, team_id: int) -> Integration | None:- return Integration.objects.select_related("team__organization").filter(id=integration_id, team_id=team_id).first()+def _load_integration(integration_id: int, team_id: int) -> WorkspaceIntegration | None:+ try:+ return with_teams([IntegrationManager.slack.oauth.get(team_id, integration_id)])[0]+ except IntegrationNotFound:+ return None@shared_task(ignore_result=True)diff --git a/products/slack_app/backend/temporal/activities/billing.py b/products/slack_app/backend/temporal/activities/billing.pyindex 94f52d6e32f4..925cb31e6f0e 100644--- a/products/slack_app/backend/temporal/activities/billing.py+++ b/products/slack_app/backend/temporal/activities/billing.py@@ -3,6 +3,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import close_db_connections+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.helpers import block_if_team_over_quotafrom products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputs@@ -24,13 +25,9 @@ def enforce_posthog_code_billing_quota_activity(Slack roundtrips, thread fetches, or billable LLM calls (the classifier,notably) for an over-quota team."""- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegration- integration = Integration.objects.select_related("team").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)# An untagged reply or an untagged channel question has asked PostHog for nothing# yet, because both the classifier and the confirmation prompt run after this gate.diff --git a/products/slack_app/backend/temporal/activities/classifiers.py b/products/slack_app/backend/temporal/activities/classifiers.pyindex 0b4db1c9d1f6..ce04d750dbe8 100644--- a/products/slack_app/backend/temporal/activities/classifiers.py+++ b/products/slack_app/backend/temporal/activities/classifiers.py@@ -1,4 +1,5 @@import re+from collections.abc import Sequencefrom pathlib import Pathimport structlog@@ -8,7 +9,7 @@ from temporalio import activityfrom posthog.llm.gateway_client import Product, build_anthropic_client, build_openai_client, trace_id_from_seedfrom posthog.llm.semantic_enrichment import extract_json_object-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom posthog.models.user import Userfrom posthog.temporal.common.utils import close_db_connections@@ -26,6 +27,11 @@ from products.slack_app.backend.prompt_templates import PromptTemplatesfrom products.slack_app.backend.services.integration_resolver import format_project_candidate_list, routable_projectsfrom products.slack_app.backend.services.slack_messages import SlackThreadMessagefrom products.slack_app.backend.services.slack_user_info import find_addressed_bot_user_id+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ require_workspace_integration,+ workspace_integrations,+)from products.slack_app.backend.temporal.types import (PostHogCodeSlackMentionWorkflowInputs,SlackAppModelOverride,@@ -280,11 +286,7 @@ def classify_posthog_code_task_needs_repo_activity(if inputs is None:return classify_task_needs_repo(event_text, thread_messages)- integration = Integration.objects.get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)# Filter rules to repos the mentioner can reach, matching what selection accepts for# this mention. An empty list means the lookup resolved nothing (the cascade would# have stopped such a mention already), so treat it as unknown rather than dropping@@ -601,11 +603,7 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInputif not input.event_text.strip():return None- integration = Integration.objects.select_related("team").get(- id=input.integration_id,- kind="slack",- integration_id=input.slack_team_id,- )+ integration = require_workspace_integration(input.integration_id, input.slack_team_id)choices = available_model_choices()if not choices:# The gateway is the source of truth for what can run; with no catalogue we@@ -632,7 +630,7 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInputreturn override-def _project_route_response_format(projects: list[Integration]) -> ResponseFormatJSONSchema:+def _project_route_response_format(projects: Sequence[WorkspaceIntegration]) -> ResponseFormatJSONSchema:"""A strict JSON schema pinning the reply to one id from ``projects``.The enum is what stops the classifier naming a project this mentioner cannot reach.@@ -662,11 +660,11 @@ class _ProjectRouteReply(BaseModel):def classify_slack_app_project_route(event_text: str,- projects: list[Integration],- default: Integration | None = None,+ projects: Sequence[WorkspaceIntegration],+ default: WorkspaceIntegration | None = None,trace_id: str | None = None,team_id: int | None = None,-) -> Integration | None:+) -> WorkspaceIntegration | None:"""Read the project a mention asked to be answered from, out of its text.``default`` is the project the run is already on. It heads the list the model is@@ -742,14 +740,10 @@ def classify_slack_app_project_route_activity(input: SlackAppProjectRouteInput)# Cheapest gate first, and the one that answers most workspaces. Everything below is# two queries and an access scan, and a workspace connected to one project has# nothing to route between however they come out.- if Integration.objects.filter(kind="slack", integration_id=input.slack_team_id).count() < 2:+ if len(workspace_integrations(input.slack_team_id)) < 2:return None- integration = Integration.objects.select_related("team", "team__organization").get(- id=input.integration_id,- kind="slack",- integration_id=input.slack_team_id,- )+ integration = require_workspace_integration(input.integration_id, input.slack_team_id)user = User.objects.filter(id=input.user_id).first()if user is None:return Nonediff --git a/products/slack_app/backend/temporal/activities/fork.py b/products/slack_app/backend/temporal/activities/fork.pyindex 5c6579de5037..f1645a50d78e 100644--- a/products/slack_app/backend/temporal/activities/fork.py+++ b/products/slack_app/backend/temporal/activities/fork.py@@ -185,7 +185,7 @@ def process_slack_app_fork_thread_payload(payload: dict[str, Any]) -> None:# mentioner could.source_task = (SlackThreadTaskMapping.objects.filter(- integration=integration,+ integration_id=integration.id,channel=source_channel,thread_ts=source_thread_ts,)diff --git a/products/slack_app/backend/temporal/activities/messaging.py b/products/slack_app/backend/temporal/activities/messaging.pyindex c3f5fa8bc9b7..384acd134b77 100644--- a/products/slack_app/backend/temporal/activities/messaging.py+++ b/products/slack_app/backend/temporal/activities/messaging.py@@ -3,10 +3,11 @@ from typing import Anyimport structlogfrom temporalio import activity-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.services.slack_messages import post_slack_thread_reply+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.helpers import safe_react, swap_reactionfrom products.slack_app.backend.temporal.types import (SLACK_APP_PROCESSING_REACTION,@@ -33,11 +34,7 @@ def post_posthog_code_no_repos_activity(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:inputs = coerce_mention_workflow_inputs(inputs)- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)post_slack_thread_reply(slack.client,@@ -68,11 +65,7 @@ def post_posthog_code_repo_picker_activity(from products.slack_app.backend.api import _post_repo_picker_message- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)_post_repo_picker_message(@@ -184,11 +177,7 @@ def block_posthog_code_task_if_no_personal_github_activity(if tasks_facade.user_has_usable_personal_github(user_id):return False- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)# A stale row (present but unusable) gets reconnect wording; a missing one gets setup wording.has_stale_github = UserIntegration.objects.filter(user_id=user_id,@@ -236,11 +225,7 @@ def post_posthog_code_picker_timeout_activity().exists():return- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)post_slack_thread_reply(slack.client,@@ -267,11 +252,7 @@ def post_posthog_code_internal_error_activity(slack_user_id=slack_user_id,)- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)post_slack_thread_reply(slack.client,@@ -291,11 +272,7 @@ def mark_slack_app_message_processing_activity(input: SlackAppMessageReactionInpthe conversation queue behind retries of a reaction."""try:- integration = Integration.objects.get(- id=input.integration_id,- kind="slack",- integration_id=input.slack_team_id,- )+ integration = require_workspace_integration(input.integration_id, input.slack_team_id)slack = SlackIntegration(integration)swap_reaction(slack.client, input.channel, input.message_ts, SLACK_APP_QUEUED_REACTION, SLACK_APP_PROCESSING_REACTION@@ -318,11 +295,7 @@ def mark_slack_app_message_queued_activity(input: SlackAppMessageReactionInput)Best-effort like the processing swap above: never raises."""try:- integration = Integration.objects.get(- id=input.integration_id,- kind="slack",- integration_id=input.slack_team_id,- )+ integration = require_workspace_integration(input.integration_id, input.slack_team_id)slack = SlackIntegration(integration)safe_react(slack.client, input.channel, input.message_ts, SLACK_APP_QUEUED_REACTION)except Exception as e:diff --git a/products/slack_app/backend/temporal/activities/model_router.py b/products/slack_app/backend/temporal/activities/model_router.pyindex 33d380fb17d3..492cbcbc1af8 100644--- a/products/slack_app/backend/temporal/activities/model_router.py+++ b/products/slack_app/backend/temporal/activities/model_router.py@@ -13,7 +13,6 @@ from posthog.dataclasses import frozenfrom posthog.llm.managed_decision_model import DEFAULT_DECISION_MODELfrom posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, JsonValuefrom posthog.llm.system_one_client import GATEWAY_MAX_CHOICE_OPTIONS, build_system_one_client-from posthog.models.integration import Integrationfrom posthog.models.user import Userfrom posthog.temporal.common.utils import close_db_connections@@ -24,6 +23,10 @@ from products.slack_app.backend.facade.run_preferences import (model_router_options,)from products.slack_app.backend.services.slack_settings import resolve_auto_model_choice+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ require_workspace_integration,+)from products.slack_app.backend.temporal.activities.classifiers import CLASSIFIER_PROPERTY, _thread_trace_idfrom products.slack_app.backend.temporal.types import SlackAppModelOverride, SlackAppModelRouterInput@@ -88,7 +91,7 @@ def classify_slack_app_model_router(def _capture_decision(- integration: Integration,+ integration: WorkspaceIntegration,input: SlackAppModelRouterInput,user: User,decision: ModelRouterDecision,@@ -139,11 +142,7 @@ def classify_slack_app_model_router_activity(input: SlackAppModelRouterInput) ->if not resolve_auto_model_choice(input.slack_team_id, input.slack_user_id):return override- integration = Integration.objects.select_related("team").get(- id=input.integration_id,- kind="slack",- integration_id=input.slack_team_id,- )+ integration = require_workspace_integration(input.integration_id, input.slack_team_id)user = User.objects.filter(id=input.user_id).first()if user is None:return overridediff --git a/products/slack_app/backend/temporal/activities/repo_selection.py b/products/slack_app/backend/temporal/activities/repo_selection.pyindex 4865574269b2..c140428dbf9e 100644--- a/products/slack_app/backend/temporal/activities/repo_selection.py+++ b/products/slack_app/backend/temporal/activities/repo_selection.py@@ -5,10 +5,12 @@ import structlogfrom temporalio import activityfrom posthog.egress.limiter.policies import Priority+from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.services.slack_messages import SlackThreadMessage+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.helpers import safe_reactfrom products.slack_app.backend.temporal.types import (PostHogCodeRepoCascadeOutcome,@@ -48,15 +50,10 @@ def cascade_posthog_code_repository_activity(an activity task scheduled by an older workflow, the call still binds and degradesto the mention-only behavior."""- from posthog.models.integration import Integrationfrom products.slack_app.backend.api import _get_full_repo_names- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)all_repos = _get_full_repo_names(integration, user_id=user_id)if not all_repos:@@ -126,7 +123,7 @@ async def discover_posthog_code_repository_via_agent_activity(The agent's legitimate "no plausible candidate" result becomes`status='no_match'`, which the workflow turns into a no-repo task."""- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.api import post_quota_exhausted_denialfrom products.tasks.backend.facade import api as tasks_facade@@ -139,10 +136,8 @@ async def discover_posthog_code_repository_via_agent_activity(user_message_ts = event.get("ts")- integration = await Integration.objects.select_related("team", "team__organization").aget(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,+ integration = await database_sync_to_async(require_workspace_integration)(+ inputs.integration_id, inputs.slack_team_id)# Best-effort searching reaction so the user sees we're working beforediff --git a/products/slack_app/backend/temporal/activities/rules.py b/products/slack_app/backend/temporal/activities/rules.pyindex 8b320496e976..660a688f0612 100644--- a/products/slack_app/backend/temporal/activities/rules.py+++ b/products/slack_app/backend/temporal/activities/rules.py@@ -4,6 +4,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.services.slack_messages import post_slack_ephemeral, post_slack_thread_reply+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.types import (PostHogCodeSlackMentionCommandResult,PostHogCodeSlackMentionCommandWorkflowInputs,@@ -23,17 +24,13 @@ def create_posthog_code_routing_rule_activity(rule_text: str,repository: str,) -> None:- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom posthog.models.repo_routing_rule import RepoRoutingRulefrom products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_namesfrom products.slack_app.backend.services.commands import reject_invalid_rule_text- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)rejection = reject_invalid_rule_text(integration.team_id, rule_text)diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.pyindex edcf7c709362..fde22c85693b 100644--- a/products/slack_app/backend/temporal/activities/task_creation.py+++ b/products/slack_app/backend/temporal/activities/task_creation.py@@ -22,6 +22,7 @@ from products.slack_app.backend.services.slack_messages import (post_slack_thread_reply,thread_permalink,)+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.attachments import (PreparedSlackAttachments,SlackAttachmentBudget,@@ -597,7 +598,7 @@ def create_posthog_code_task_for_repo_activity(repo_research_run_id: str | None = None,model_override: SlackAppModelOverride | None = None,) -> None:- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom posthog.models.user import Userfrom products.signals.backend.facade import api as signals_facade@@ -607,11 +608,7 @@ def create_posthog_code_task_for_repo_activity(from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.temporal import dispatch_task_processing_workflow- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)# A report notification invites the reader to reply in its thread, so a mention there is the@@ -863,7 +860,7 @@ def create_posthog_code_task_for_repo_activity(*(m.ts for m in thread_messages),)SlackThreadTaskMapping.objects.update_or_create(- integration=integration,+ integration_id=integration.id,channel=channel,thread_ts=thread_ts,defaults={@@ -976,7 +973,7 @@ def forward_posthog_code_followup_activity(the first attempt announced. It defaults to ``None`` for histories recorded beforethe workflow classified this early, which simply leave the run on its own model."""- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.api import resolve_slack_userfrom products.tasks.backend.facade import api as tasks_facade@@ -989,11 +986,7 @@ def forward_posthog_code_followup_activity(task_run = mapping.task_run- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)actor_user = mapping.task.created_bydiff --git a/products/slack_app/backend/temporal/activities/thread.py b/products/slack_app/backend/temporal/activities/thread.pyindex 5d0db0b4e5f9..e6538adf939a 100644--- a/products/slack_app/backend/temporal/activities/thread.py+++ b/products/slack_app/backend/temporal/activities/thread.py@@ -3,6 +3,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.services.slack_messages import SlackThreadMessage+from products.slack_app.backend.services.workspace_integrations import require_workspace_integrationfrom products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputs@@ -13,15 +14,11 @@ def collect_posthog_code_thread_messages_activity(channel: str,thread_ts: str,) -> list[SlackThreadMessage]:- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.services.slack_messages import collect_thread_messages- integration = Integration.objects.select_related("team", "team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+ integration = require_workspace_integration(inputs.integration_id, inputs.slack_team_id)slack = SlackIntegration(integration)auth_response = slack.client.auth_test()our_bot_id = auth_response.get("bot_id")diff --git a/products/slack_app/backend/temporal/activities/untagged_question.py b/products/slack_app/backend/temporal/activities/untagged_question.pyindex 8cfab392012e..55845dfb19c4 100644--- a/products/slack_app/backend/temporal/activities/untagged_question.py+++ b/products/slack_app/backend/temporal/activities/untagged_question.py@@ -13,7 +13,7 @@ from posthog.dataclasses import frozenfrom posthog.llm.managed_decision_model import DEFAULT_DECISION_MODELfrom posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfiguredfrom posthog.llm.system_one_client import build_system_one_client-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.user import Userfrom posthog.temporal.common.utils import close_db_connections@@ -21,6 +21,10 @@ from products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.models import UntaggedFollowupModefrom products.slack_app.backend.services.slack_conversations import channel_is_ext_sharedfrom products.slack_app.backend.services.slack_settings import resolve_untagged_question_mode+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ require_workspace_integration,+)from products.slack_app.backend.temporal.activities.classifiers import CLASSIFIER_PROPERTY, _thread_trace_idfrom products.slack_app.backend.temporal.types import (PostHogCodeSlackMentionWorkflowInputs,@@ -140,12 +144,8 @@ def classify_untagged_question(return UntaggedQuestionVerdict(asks_for_information=asks.probability, answerable_by_posthog=answerable.probability)-def _load_integration(inputs: PostHogCodeSlackMentionWorkflowInputs) -> Integration:- return Integration.objects.select_related("team__organization").get(- id=inputs.integration_id,- kind="slack",- integration_id=inputs.slack_team_id,- )+def _load_integration(inputs: PostHogCodeSlackMentionWorkflowInputs) -> WorkspaceIntegration:+ return require_workspace_integration(inputs.integration_id, inputs.slack_team_id)@activity.defndiff --git a/products/slack_app/backend/temporal/activities/user_resolution.py b/products/slack_app/backend/temporal/activities/user_resolution.pyindex 87fd2d8a4456..2541b69c3462 100644--- a/products/slack_app/backend/temporal/activities/user_resolution.py+++ b/products/slack_app/backend/temporal/activities/user_resolution.py@@ -2,6 +2,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import close_db_connections+from products.slack_app.backend.services.workspace_integrations import workspace_integrationsfrom products.slack_app.backend.temporal.types import PostHogCodeSlackMentionCommandWorkflowInputs@@ -10,7 +11,7 @@ from products.slack_app.backend.temporal.types import PostHogCodeSlackMentionComdef resolve_posthog_code_slack_command_user_activity(inputs: PostHogCodeSlackMentionCommandWorkflowInputs,) -> int | None:- from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.integration import SlackIntegrationfrom products.slack_app.backend.api import resolve_posthog_user_from_event@@ -22,13 +23,8 @@ def resolve_posthog_code_slack_command_user_activity(if not channel or not slack_user_id or not inputs.integration_ids:return None- candidates = list(- Integration.objects.filter(- id__in=inputs.integration_ids,- kind="slack",- integration_id=inputs.slack_team_id,- ).select_related("team", "team__organization")- )+ wanted_ids = set(inputs.integration_ids)+ candidates = [row for row in workspace_integrations(inputs.slack_team_id) if row.id in wanted_ids]if not candidates:return Nonediff --git a/products/slack_app/backend/temporal/attachments.py b/products/slack_app/backend/temporal/attachments.pyindex cf7ba7cf4b09..919d1f8d6d36 100644--- a/products/slack_app/backend/temporal/attachments.py+++ b/products/slack_app/backend/temporal/attachments.py@@ -10,10 +10,10 @@ from django.conf import settingsimport structlogfrom posthog.egress.slack.transport import slack_request-from posthog.models.integration import Integrationfrom products.slack_app.backend.services.slack_messages import SlackFileRef, SlackThreadMessagefrom products.slack_app.backend.services.slack_scopes import has_scopes+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationlogger = structlog.get_logger(__name__)@@ -102,7 +102,7 @@ class PreparedSlackAttachments:return self.requested_count > 0-def can_read_slack_files(integration: Integration) -> bool:+def can_read_slack_files(integration: WorkspaceIntegration) -> bool:return has_scopes(integration, {SLACK_FILE_READ_SCOPE})diff --git a/products/slack_app/backend/temporal/tests/activities/test_discover_repository_activity.py b/products/slack_app/backend/temporal/tests/activities/test_discover_repository_activity.pyindex 288a19961e91..ec48d4fcc836 100644--- a/products/slack_app/backend/temporal/tests/activities/test_discover_repository_activity.py+++ b/products/slack_app/backend/temporal/tests/activities/test_discover_repository_activity.py@@ -13,11 +13,9 @@ async def test_usage_limited_selection_posts_the_credits_message_instead_of_a_pievent = {"channel": "C1", "ts": "1.2", "thread_ts": "1.0", "user": "U1", "text": "fix the bug"}inputs = PostHogCodeSlackMentionWorkflowInputs(event=event, integration_id=1, slack_team_id="T1", user_id=42)integration = MagicMock(team_id=7)- objects = MagicMock()- objects.select_related.return_value.aget = AsyncMock(return_value=integration)with (- patch("posthog.models.integration.Integration.objects", objects),+ patch.object(repo_selection, "require_workspace_integration", return_value=integration),patch("posthog.models.integration.SlackIntegration"),patch.object(repo_selection, "Heartbeater", return_value=contextlib.nullcontext()),patch(diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex 2aa39464078e..0540685e60ea 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -1,3 +1,6 @@+from collections.abc import Sequence+from typing import Any+import pytestfrom django.apps import apps@@ -125,6 +128,12 @@ class TestResolveIntegration:mentioning_slack_user_id=SLACK_USER,)+ def test_load_integrations_for_user_does_not_query_per_candidate(self, django_assert_num_queries):+ with django_assert_num_queries(4):+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], user=self.user)++ assert {c.id for c in result.candidates} == {self.integration_a.id, self.integration_b.id}+@pytest.mark.parametrize("mapping_kind", ["task", "report", "fork"])@pytest.mark.parametrize("has_default", [False, True])def test_thread_mapping_wins_over_everything(self, mapping_kind, has_default):@@ -594,7 +603,7 @@ class TestLoadIntegrationsAuthStateFilter:sensitive_config={"access_token": "xoxb"},)- def _candidate_ids(self, result_candidates: list[Integration]) -> list[int]:+ def _candidate_ids(self, result_candidates: Sequence[Any]) -> list[int]:return [c.id for c in result_candidates]def test_cold_cache_runs_auth_test_per_candidate_and_caches_verdict(self):diff --git a/products/slack_app/backend/tests/test_workspace_integrations.py b/products/slack_app/backend/tests/test_workspace_integrations.pynew file mode 100644index 000000000000..036da918dfa8--- /dev/null+++ b/products/slack_app/backend/tests/test_workspace_integrations.py@@ -0,0 +1,104 @@+import pytest++from posthog.integrations import IntegrationManager, IntegrationNotFound+from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.services.workspace_integrations import (+ get_team_workspace_integration,+ get_workspace_integration,+ require_workspace_integration,+ workspace_integration_exists,+ workspace_integrations,+)++WORKSPACE = "T_WS"+OTHER_WORKSPACE = "T_OTHER"+++def _mk(team: Team, workspace: str = WORKSPACE, **extra) -> Integration:+ return Integration.objects.create(+ team=team, kind="slack", integration_id=workspace, sensitive_config={"access_token": "xoxb"}, **extra+ )+++class TestWorkspaceIntegrations:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ organization = Organization.objects.create(name="Org")+ self.team_a = Team.objects.create(organization=organization, name="A")+ self.team_b = Team.objects.create(organization=organization, name="B")+ self.row_a = _mk(self.team_a)+ self.row_b = _mk(self.team_b)+ self.row_other_workspace = _mk(self.team_a, OTHER_WORKSPACE)++ def test_two_teams_in_one_workspace_resolve_their_own_rows(self):+ assert get_workspace_integration(self.row_a.id, WORKSPACE) == self.row_a+ assert get_workspace_integration(self.row_b.id, WORKSPACE) == self.row_b+ assert get_team_workspace_integration(self.team_a.id, WORKSPACE) == self.row_a+ assert get_team_workspace_integration(self.team_b.id, WORKSPACE) == self.row_b+ assert [row.id for row in workspace_integrations(WORKSPACE)] == sorted([self.row_a.id, self.row_b.id])++ def test_id_from_another_workspace_returns_none(self):+ assert get_workspace_integration(self.row_other_workspace.id, WORKSPACE) is None+ assert not workspace_integration_exists(self.row_other_workspace.id, WORKSPACE)+ assert get_team_workspace_integration(self.team_b.id, OTHER_WORKSPACE) is None++ @pytest.mark.parametrize(+ "make_row",+ [+ pytest.param(+ lambda team: IntegrationManager.slack.token.create(+ team.id, external_id=WORKSPACE, config={}, sensitive_config={"access_token": "xoxb"}+ ),+ id="token_auth",+ ),+ pytest.param(+ lambda team: _mk(team, config={"warehouse_source_type": "Stripe"}),+ id="warehouse_source_marked",+ ),+ ],+ )+ def test_rows_outside_the_oauth_scope_are_excluded(self, make_row):+ organization = Organization.objects.create(name="Org2")+ team = Team.objects.create(organization=organization, name="C")+ row = make_row(team)++ assert get_workspace_integration(row.id, WORKSPACE) is None+ assert not workspace_integration_exists(row.id, WORKSPACE)+ assert get_team_workspace_integration(team.id, WORKSPACE) is None+ assert row.id not in [r.id for r in workspace_integrations(WORKSPACE)]++ @pytest.mark.parametrize(+ "make_id,found",+ [+ pytest.param(lambda row: row.id, True, id="int"),+ pytest.param(lambda row: str(row.id), True, id="numeric_string"),+ pytest.param(lambda row: True, False, id="bool"),+ pytest.param(lambda row: "abc", False, id="non_numeric_string"),+ pytest.param(lambda row: "", False, id="empty_string"),+ pytest.param(lambda row: None, False, id="none"),+ pytest.param(lambda row: 1.5, False, id="float"),+ pytest.param(lambda row: 10**30, False, id="out_of_range_int"),+ ],+ )+ def test_id_types(self, make_id, found):+ wanted = make_id(self.row_a)++ assert (get_workspace_integration(wanted, WORKSPACE) is not None) is found+ assert workspace_integration_exists(wanted, WORKSPACE) is found++ def test_require_raises_when_missing(self):+ assert require_workspace_integration(self.row_a.id, WORKSPACE) == self.row_a+ with pytest.raises(IntegrationNotFound):+ require_workspace_integration(self.row_other_workspace.id, WORKSPACE)++ def test_rows_come_with_team_and_organization_loaded(self, django_assert_num_queries):+ rows = workspace_integrations(WORKSPACE)+ with django_assert_num_queries(0):+ assert {row.team.organization.name for row in rows} == {"Org"}+ single = get_workspace_integration(self.row_a.id, WORKSPACE)+ assert single is not None+ with django_assert_num_queries(0):+ assert single.team.organization.name == "Org"diff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.pyindex b395085d9c78..d4c4efae0d62 100644--- a/products/slack_app/backend/views/slack_user_link.py+++ b/products/slack_app/backend/views/slack_user_link.py@@ -38,7 +38,7 @@ from django.views.decorators.http import require_GETimport structlogfrom posthog.api.github_callback.redirects import PERSONAL_INTEGRATIONS_SETTINGS_PATH-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.user_integration import user_slack_integration_from_identity@@ -53,6 +53,10 @@ from products.slack_app.backend.services.slack_user_oauth import (build_authorize_url,exchange_code,)+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ get_team_workspace_integration,+)logger = structlog.get_logger(__name__)@@ -79,7 +83,7 @@ def _settings_redirect(*, error: str | None = None) -> HttpResponseRedirect:def _link_failed(- integration: Integration,+ integration: WorkspaceIntegration,reason: str,*,slack_user_id: str | None = None,@@ -99,12 +103,8 @@ def _link_failed(return _settings_redirect(error=reason)-def _load_workspace_integration(posthog_team_id: int, slack_team_id: str) -> Integration | None:- return (- Integration.objects.filter(team_id=posthog_team_id, kind="slack", integration_id=slack_team_id)- .select_related("team", "team__organization")- .first()- )+def _load_workspace_integration(posthog_team_id: int, slack_team_id: str) -> WorkspaceIntegration | None:+ return get_team_workspace_integration(posthog_team_id, slack_team_id)@require_GET@@ -276,7 +276,7 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:def _post_link_success_followup(*,- workspace_integration: Integration,+ workspace_integration: WorkspaceIntegration,slack_user_id: str,channel: Any,thread_ts: Any,diff --git a/products/slack_app/evals/eval_project_classifier.py b/products/slack_app/evals/eval_project_classifier.pyindex f39c50b679db..939af53c7aca 100644--- a/products/slack_app/evals/eval_project_classifier.py+++ b/products/slack_app/evals/eval_project_classifier.py@@ -37,8 +37,9 @@ To run:from __future__ import annotationsimport asyncio+from types import SimpleNamespace+from typing import cast-from posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team@@ -46,6 +47,7 @@ from products.posthog_ai.eval_harness.config import BaseEvalCasefrom products.posthog_ai.eval_harness.harness.context import EvalContextfrom products.posthog_ai.eval_harness.harness.requirements import SuiteKindfrom products.posthog_ai.eval_harness.one_shot import OneShotEval+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationfrom products.slack_app.backend.temporal.activities import classifiersfrom products.slack_app.evals.offline_config import offline_suitefrom products.slack_app.evals.scorers import PROJECT_ROUTE_KEY, NoUnaskedProjectSwitch, ProjectRouteMatch@@ -53,12 +55,17 @@ from products.slack_app.evals.scorers import PROJECT_ROUTE_KEY, NoUnaskedProjectSUITE_KIND = SuiteKind.ONE_SHOT-def _project(*, team_id: int, integration_id: int, name: str) -> Integration:- """An unsaved `Integration` row, which is all the classifier reads."""- return Integration(- id=integration_id,- kind="slack",- team=Team(id=team_id, name=name, organization=Organization(name="Northwind")),+def _project(*, team_id: int, integration_id: int, name: str) -> WorkspaceIntegration:+ """A stand-in row with only what the classifier reads."""+ return cast(+ WorkspaceIntegration,+ SimpleNamespace(+ id=integration_id,+ team_id=team_id,+ kind="slack",+ integration_id="T_EVAL",+ team=Team(id=team_id, name=name, organization=Organization(name="Northwind")),+ ),)@@ -113,18 +120,18 @@ NORTHWIND = _project(team_id=53, integration_id=530, name="Northwind")SITE_DEV = _project(team_id=54, integration_id=540, name="northwind.io development")SITES = [NORTHWIND, SITE_DEV, STAGING, AGENT_PLATFORM, MOBILE]-WORKSPACES: dict[str, tuple[list[Integration], Integration]] = {+WORKSPACES: dict[str, tuple[list[WorkspaceIntegration], WorkspaceIntegration]] = {"simple": (PROJECTS, MAIN),"crowded": (CROWD, MAIN),"sites": (SITES, NORTHWIND),}-def _routes_to(project: Integration | None = None) -> dict:+def _routes_to(project: WorkspaceIntegration | None = None) -> dict:return {PROJECT_ROUTE_KEY: {"integration_id": project.id if project else None}}-def _stays_on(default: Integration) -> dict:+def _stays_on(default: WorkspaceIntegration) -> dict:"""The message names the project the run is already on, so its id and null both pass."""return {PROJECT_ROUTE_KEY: {"integration_id": default.id, "is_default": True}}