:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): bind the team slack channel to the workspace that owns it (#125187)
Dylan Martin8d85d0f99ecb
diff --git a/posthog/integrations/model_access_baseline.txt b/posthog/integrations/model_access_baseline.txtindex fd2a2c6cf77d..4639e7b5dc04 100644--- a/posthog/integrations/model_access_baseline.txt+++ b/posthog/integrations/model_access_baseline.txt@@ -88,7 +88,7 @@ products/signals/backend/scout_harness/profile/builders.py 2products/signals/backend/scout_harness/serializers.py 2products/signals/backend/scout_harness/slack_delivery.py 2products/signals/backend/serializers.py 2-products/signals/backend/slack_inbox_notifications.py 4+products/signals/backend/slack_inbox_notifications.py 2products/signals/backend/slack_notification_targets.py 2products/signals/backend/temporal/agentic/select_repository.py 2products/signals/backend/tracker_issues.py 4diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex e8d1e19d29af..1f01d100a025 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -24,6 +24,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.event_usage import groupsfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model+from posthog.integrations import IntegrationManagerfrom posthog.models import Team, Userfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connect@@ -458,15 +459,37 @@ def get_default_slack_notification_channel(team_id: int) -> str | None:return value or None-def set_default_slack_notification_channel(team_id: int, value: str | None) -> None:- """Idempotently set the team-default Slack channel for signal notifications."""+def get_default_slack_notification_integration_id(team_id: int) -> int | None:+ """The Slack integration that owns the team-default channel.++ None for an unbound legacy channel, and for a binding to a workspace that is no longer connected.+ """+ from products.signals.backend.models import (+ SignalTeamConfig, # noqa: PLC0415 — avoids importing model layer at facade import time+ )++ bound_id = (+ SignalTeamConfig.objects.filter(team_id=team_id)+ .values_list("default_slack_notification_integration_id", flat=True)+ .first()+ )+ if bound_id is None or not IntegrationManager.slack.any.get_many(team_id, [bound_id]):+ return None+ return bound_id+++def set_default_slack_notification_channel(team_id: int, value: str | None, *, integration_id: int | None) -> None:+ """Idempotently set the team-default Slack channel for signal notifications, and the workspace that owns it."""from products.signals.backend.models import (SignalTeamConfig, # noqa: PLC0415 — avoids importing model layer at facade import time)SignalTeamConfig.objects.update_or_create(team_id=team_id,- defaults={"default_slack_notification_channel": value or None},+ defaults={+ "default_slack_notification_channel": value or None,+ "default_slack_notification_integration_id": integration_id if value else None,+ },)diff --git a/products/signals/backend/migrations/0220_signalteamconfig_default_slack_notification_integration.py b/products/signals/backend/migrations/0220_signalteamconfig_default_slack_notification_integration.pynew file mode 100644index 000000000000..51ab65ce9687--- /dev/null+++ b/products/signals/backend/migrations/0220_signalteamconfig_default_slack_notification_integration.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.18 on 2026-10-28 22:34++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0219_signalteamconfig_implementation_repositories"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalteamconfig",+ name="default_slack_notification_integration_id",+ field=models.BigIntegerField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex e2390b6e0b86..b24eb9cdc9b1 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0219_signalteamconfig_implementation_repositories+0220_signalteamconfig_default_slack_notification_integrationdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 2ed3c505664d..f53c72a60266 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -239,6 +239,10 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):onboarding = models.JSONField(null=True, blank=True)default_autostart_priority = models.CharField(max_length=2, choices=AutonomyPriority, default=AutonomyPriority.P4)default_slack_notification_channel = models.CharField(max_length=255, null=True, blank=True)+ # The workspace that owns the channel. A team can connect several Slack workspaces, and a channel+ # id from one of them fails in every other. Null on rows saved before the binding existed.+ # A plain id rather than a foreign key, so readers treat an id of a deleted workspace as unbound.+ default_slack_notification_integration_id = models.BigIntegerField(null=True, blank=True)autostart_base_branches = models.JSONField(default=dict, blank=True)scout_instructions = models.TextField(null=True, blank=True)research_instructions = models.TextField(null=True, blank=True)diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 501b33754df4..aa9462a2d0c2 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -20,6 +20,8 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.auth import is_mcp_requestfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception+from posthog.integrations import IntegrationRecord+from posthog.integrations.fields import IntegrationReferenceFieldfrom posthog.models import Team, Userfrom posthog.models.integration import Integration, is_supported_external_issue_provider@@ -442,6 +444,18 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"default."),)+ default_slack_notification_integration = IntegrationReferenceField(+ kinds=["slack"],+ auth_types="any",+ source="default_slack_notification_integration_id",+ required=False,+ allow_null=True,+ help_text=(+ "Connected Slack integration that owns `default_slack_notification_channel`. Send it together "+ "with the channel. A channel saved without it is routed through the team's oldest Slack "+ "integration, and clearing the channel clears this too."+ ),+ )issue_tracking_config = serializers.DictField(child=serializers.CharField(max_length=255, allow_blank=True),required=False,@@ -609,6 +623,7 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):"autostart_enabled","default_autostart_priority","default_slack_notification_channel",+ "default_slack_notification_integration","autostart_base_branches","scout_instructions","research_instructions",@@ -653,6 +668,9 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):},}+ def validate_default_slack_notification_integration(self, value: IntegrationRecord | None) -> int | None:+ return value.id if value is not None else None+def validate_issue_tracking_integration(self, value: Integration | None) -> Integration | None:if value is None:return None@@ -664,6 +682,12 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):def validate(self, attrs: dict) -> dict:attrs = super().validate(attrs)+ # A new channel without its workspace must not keep the old binding, which may name a+ # workspace that cannot see the new channel.+ if "default_slack_notification_channel" in attrs and (+ not attrs["default_slack_notification_channel"] or "default_slack_notification_integration_id" not in attrs+ ):+ attrs["default_slack_notification_integration_id"] = None# The target only makes sense against an integration, and the two can arrive in either the# same PATCH or separate ones, so fall back to what is already stored.integration = (diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 83a400c48df1..397fc397d138 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -2,14 +2,11 @@Mirrors the inbox Reports tab's actionability gate: a report notifies only if it's actionable(its latest actionability judgment is immediately_actionable or requires_human_input) — READY is-enforced upstream — and has at least one suggested reviewer that resolves to a destination.-Each reviewer is routed to one destination: their own configured target if set (filtered by-their min-priority), otherwise the team-default channel. A personal target is either a channel or-the reviewer's own Slack account, which Slack delivers as a direct message. Reviewers sharing a-destination get a single post mentioning only the reviewers routed there. When no suggested-reviewer resolves, the report is still delivered to the team-default channel (if one is-configured) with no mentions, so a team is notified even when none of its members are linked to a-resolvable GitHub identity.+enforced upstream. The team-default channel (if configured) receives every such report. Each+suggested reviewer is also routed to one destination: their own configured target if set (filtered+by their min-priority), otherwise the team-default channel. A personal target is either a channel+or the reviewer's own Slack account, which Slack delivers as a direct message. Reviewers sharing a+destination get a single post mentioning only the reviewers routed there.All sends are best-effort."""@@ -27,8 +24,9 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups+from posthog.integrations import IntegrationManager, IntegrationRecordfrom posthog.models import User-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SlackIntegrationfrom posthog.ph_client import ph_scoped_capturefrom posthog.slack.formatting import (channel_id_from_target as _channel_id_from_target,@@ -245,17 +243,25 @@ def _own_target_configs_by_user(team_id: int, user_ids: set[int]) -> dict[int, Sreturn {config.user_id: config for config in configs}-def _get_team_slack_integration(team_id: int) -> Integration | None:- # Standard `slack` kind (not `slack-posthog-code`), matching the per-user path.- return Integration.objects.filter(team_id=team_id, kind="slack").first()---def _team_notification_channel(team_id: int) -> str | None:- config = SignalTeamConfig.objects.filter(team_id=team_id).only("default_slack_notification_channel").first()- if config is None:+def _team_notification_target(team_id: int) -> tuple[IntegrationRecord, str] | None:+ """The team-default channel and the Slack workspace that owns it."""+ config = (+ SignalTeamConfig.objects.filter(team_id=team_id)+ .only("default_slack_notification_channel", "default_slack_notification_integration_id")+ .first()+ )+ channel = ((config.default_slack_notification_channel if config else None) or "").strip()+ if config is None or not channel:return None- channel = (config.default_slack_notification_channel or "").strip()- return channel or None+ # Standard `slack` kind (not `slack-posthog-code`), matching the per-user path.+ slack_rows = IntegrationManager.slack.any+ bound_id = config.default_slack_notification_integration_id+ if bound_id is not None and (integration := slack_rows.get_many(team_id, [bound_id]).get(bound_id)):+ return integration, channel+ # A channel saved before the binding existed, or bound to a removed workspace, keeps the old+ # routing through the oldest workspace.+ legacy = slack_rows.find(team_id)+ return (legacy, channel) if legacy is not None else Nonedef _channel_display_name(value: str) -> str:@@ -387,7 +393,7 @@ class _ChannelRoute:The destination is a channel, or a member whose id Slack turns into a direct message."""- def __init__(self, integration: Integration, channel: str, *, is_team_channel: bool) -> None:+ def __init__(self, integration: IntegrationRecord, channel: str, *, is_team_channel: bool) -> None:self.integration = integrationself.channel = channelself.is_team_channel = is_team_channel@@ -397,7 +403,7 @@ class _ChannelRoute:@frozenclass _Destination:- integration: Integration+ integration: IntegrationRecordchannel: stris_team_channel: bool@@ -433,7 +439,7 @@ def _reviewer_destination(*,own_config: SignalUserAutonomyConfig | None,priority: str | None,- team_integration: Integration | None,+ team_integration: IntegrationRecord | None,team_channel: str | None,) -> _Destination | None:"""Where one suggested reviewer is notified: their own target if set, else the team default.@@ -443,7 +449,7 @@ def _reviewer_destination(if own_config is not None:if not _meets_min_priority(priority, own_config.slack_notification_min_priority):return None- integration = own_config.slack_notification_integration+ integration: IntegrationRecord | None = own_config.slack_notification_integrationchannel = own_config.slack_notification_channelis_team_channel = Falseelif team_integration is not None and team_channel:@@ -460,17 +466,16 @@ def _build_reviewer_routes(report: SignalReport,*,priority: str | None,- team_integration: Integration | None,+ team_integration: IntegrationRecord | None,team_channel: str | None,) -> list[_ChannelRoute]:"""Route resolvable suggested reviewers to a destination, mentioning them there.Own target (filtered by the reviewer's min-priority) if set, else the team default. A reviewer- filtered out of their own target does not fall back to the team channel — that was their choice.+ filtered out of their own target is not mentioned in the team channel — that was their choice.Reviewers sharing a destination are grouped so each channel is posted to once, mentioning only- its own reviewers. When no suggested reviewer resolves, the report is still delivered to the- team-default channel (if configured) with no mentions, so a team is notified even when none of- its members are linked to a resolvable GitHub identity.+ its own reviewers. The team-default channel (if configured) receives every report, with no+ mentions when no reviewer is routed there."""reviewer_user_ids = resolve_suggested_reviewer_user_ids(report)reviewer_users = {user.id: user for user in User.objects.filter(id__in=reviewer_user_ids)}@@ -491,11 +496,9 @@ def _build_reviewer_routes(continuetable.add(destination, user=user)- # No suggested reviewer resolved to a PostHog user: deliver to the team-default channel (if- # configured) so the team is still notified, without @-mentions — the message omits the- # suggested-reviewers section when there is nobody to tag. Per-user own channels are reviewer- # notifications, so they are not used here.- if not reviewer_user_ids and team_integration is not None and team_channel:+ # The team channel gets every report. It mentions only the reviewers routed there, so a reviewer+ # with their own target is not pinged twice.+ if team_integration is not None and team_channel:table.add(_Destination(integration=team_integration, channel=team_channel, is_team_channel=True))return table.routes()@@ -545,9 +548,9 @@ def _deliver_route_notification(# A member target opens a direct message, so the conversation Slack posted into is not the# id we sent. An inbound mention names the conversation, so that is what the link records.posted_channel = response.get("channel") if hasattr(response, "get") else None- if thread_ts:+ if thread_ts and (slack_workspace_id := route.integration.integration_id):record_report_slack_thread(- slack_workspace_id=route.integration.integration_id,+ slack_workspace_id=slack_workspace_id,team_id=report.team_id,report_id=str(report.id),integration_id=route.integration.id,@@ -645,8 +648,8 @@ def dispatch_inbox_item_notifications(report_id: str, team_id: int) -> int:return 0priority = _latest_priority(report)- team_integration = _get_team_slack_integration(team_id)- team_channel = _team_notification_channel(team_id) if team_integration is not None else None+ team_target = _team_notification_target(team_id)+ team_integration, team_channel = team_target if team_target is not None else (None, None)routes = _build_reviewer_routes(report,diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.pyindex 569ea984a5b5..7f719efc7311 100644--- a/products/signals/backend/test/test_signal_team_config_api.py+++ b/products/signals/backend/test/test_signal_team_config_api.py@@ -128,24 +128,32 @@ class TestSignalTeamConfigAPI(APIBaseTest):@parameterized.expand([- ("set", None, "C123|#posthog-signals", "C123|#posthog-signals"),- ("clear", "C123|#posthog-signals", None, None),+ ("set", None, "C123|#posthog-signals", False, "C123|#posthog-signals", False),+ ("set_with_workspace", None, "C123|#posthog-signals", True, "C123|#posthog-signals", True),+ ("change_without_workspace", "C999|#old", "C123|#posthog-signals", False, "C123|#posthog-signals", False),+ ("clear", "C123|#posthog-signals", None, False, None, False),])- def test_update_default_slack_notification_channel(self, _name, initial, sent, expected):+ def test_update_default_slack_notification_channel(+ self, _name, initial, sent, send_workspace, expected, expect_bound+ ):+ workspace = Integration.objects.create(team=self.team, kind="slack", integration_id="T123", config={})if initial is not None:self.config.default_slack_notification_channel = initial- self.config.save(update_fields=["default_slack_notification_channel"])- response = self.client.post(- self._url(),- data={"default_slack_notification_channel": sent},- format="json",- )+ self.config.default_slack_notification_integration_id = workspace.id+ self.config.save(+ update_fields=["default_slack_notification_channel", "default_slack_notification_integration_id"]+ )+ payload: dict = {"default_slack_notification_channel": sent}+ if send_workspace:+ payload["default_slack_notification_integration"] = workspace.id+ response = self.client.post(self._url(), data=payload, format="json")data = response.json()assert response.status_code == status.HTTP_200_OK, dataassert data["default_slack_notification_channel"] == expectedself.config.refresh_from_db()assert self.config.default_slack_notification_channel == expected+ assert self.config.default_slack_notification_integration_id == (workspace.id if expect_bound else None)def test_partial_update_preserves_default_autostart_priority(self):self.config.default_autostart_priority = "P2"@@ -367,7 +375,7 @@ class TestSignalTeamConfigAPI(APIBaseTest):# materialized, so the row is created with the channel already set. That first choice# must still be audited even though it arrives as a create rather than an update.self.config.delete()- set_default_slack_notification_channel(self.team.pk, "C123|#posthog-signals")+ set_default_slack_notification_channel(self.team.pk, "C123|#posthog-signals", integration_id=None)entries = self._activity()assert len(entries) == 1diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex 214f9d2faae8..b3bd4edfae66 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -237,8 +237,8 @@ def org_and_team():org.delete()-def _set_team_channel(team: Team, channel: str) -> None:- set_default_slack_notification_channel(team.id, channel)+def _set_team_channel(team: Team, channel: str, integration: Integration | None = None) -> None:+ set_default_slack_notification_channel(team.id, channel, integration_id=integration.id if integration else None)def _make_reviewer_user(org: Organization, email: str, login: str) -> User:@@ -444,6 +444,31 @@ def test_dispatch_posts_to_team_channel_without_per_user_config(org_and_team, aiassert ("@PostHog" in call_kwargs["blocks"][-1]["elements"][0]["text"]) is ai_approved[email protected]("binding", ["bound", "unbound", "removed"])+def test_dispatch_posts_team_channel_through_the_workspace_that_owns_it(org_and_team, binding):+ org, team = org_and_team+ reviewer = _make_reviewer_user(org, "[email protected]", "workspace-bot")+ oldest = _make_slack_integration(team, reviewer)+ newer = Integration.objects.create(+ team=team, kind="slack", integration_id="T456", config={}, sensitive_config={"access_token": "xoxb-other"}+ )+ removed = Integration.objects.create(team=team, kind="slack", integration_id="T789", config={})+ _set_team_channel(team, "CTEAM|#posthog-signals", {"bound": newer, "unbound": None, "removed": removed}[binding])+ removed.delete()+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["workspace-bot"])++ with (+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,+ patch("products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email", return_value=None),+ ):+ slack_cls.return_value.client = MagicMock()+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)++ assert sent == 1+ assert slack_cls.call_args.args[0] == (newer if binding == "bound" else oldest)++@pytest.mark.parametrize(("target", "posted_channel"),[@@ -655,9 +680,9 @@ def test_dispatch_groups_own_and_fallback_reviewers_sharing_a_channel(org_and_te@pytest.mark.django_db-def test_dispatch_skips_team_channel_when_reviewer_has_own_channel(org_and_team):- # The only reviewer has their own channel → they are routed there and nobody falls- # back to the team default, so the team channel is not posted to at all.+def test_dispatch_posts_team_channel_when_reviewer_has_own_channel(org_and_team):+ # The only reviewer has their own channel. The team channel still gets the report, without+ # mentioning that reviewer a second time.org, team = org_and_teamuser = _make_reviewer_user(org, "[email protected]", "own-only-bot")integration = _make_slack_integration(team, user)@@ -680,9 +705,10 @@ def test_dispatch_skips_team_channel_when_reviewer_has_own_channel(org_and_team)slack_cls.return_value.client = fake_clientsent = dispatch_inbox_item_notifications(str(report.id), team.id)- assert sent == 1- channels = {c.kwargs["channel"] for c in fake_client.chat_postMessage.call_args_list}- assert channels == {"CUSER"}+ assert sent == 2+ posts = {c.kwargs["channel"]: c.kwargs["blocks"] for c in fake_client.chat_postMessage.call_args_list}+ assert set(posts) == {"CUSER", "CTEAM"}+ assert "Suggested" not in json.dumps(posts["CTEAM"])@pytest.mark.django_db@@ -749,9 +775,9 @@ def test_dispatch_respects_per_user_min_priority_filter(org_and_team):@pytest.mark.django_db-def test_dispatch_filtered_own_channel_reviewer_does_not_fall_back_to_team(org_and_team):+def test_dispatch_filtered_own_channel_reviewer_is_not_mentioned_in_team_channel(org_and_team):# A reviewer whose own channel is filtered out by their min-priority chose that- # threshold — they are not silently rerouted to the team default channel.+ # threshold, so the team channel gets the report without mentioning them.org, team = org_and_teamuser = _make_reviewer_user(org, "[email protected]", "low-bot")integration = _make_slack_integration(team, user)@@ -762,7 +788,7 @@ def test_dispatch_filtered_own_channel_reviewer_does_not_fall_back_to_team(org_aslack_notification_min_priority=AutonomyPriority.P1,)_set_team_channel(team, "CTEAM|#posthog-signals")- # P3 is below the user's P1 threshold → no own-channel post and no team fallback.+ # P3 is below the user's P1 threshold → no own-channel post.report = _make_ready_report(team, priority=AutonomyPriority.P3, suggested_logins=["low-bot"])fake_client = MagicMock()@@ -776,8 +802,10 @@ def test_dispatch_filtered_own_channel_reviewer_does_not_fall_back_to_team(org_aslack_cls.return_value.client = fake_clientsent = dispatch_inbox_item_notifications(str(report.id), team.id)- assert sent == 0- assert fake_client.chat_postMessage.call_count == 0+ assert sent == 1+ call_kwargs = fake_client.chat_postMessage.call_args.kwargs+ assert call_kwargs["channel"] == "CTEAM"+ assert "Suggested" not in json.dumps(call_kwargs["blocks"])@pytest.mark.django_dbdiff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 61d308451e1e..e2b1b06eb0c2 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -681,6 +681,11 @@ export interface SignalTeamConfigApi {* @nullable*/default_slack_notification_channel?: string | null+ /**+ * Connected Slack integration that owns `default_slack_notification_channel`. Send it together with the channel. A channel saved without it is routed through the team's oldest Slack integration, and clearing the channel clears this too.+ * @nullable+ */+ default_slack_notification_integration?: number | null/** Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch. */autostart_base_branches?: SignalTeamConfigApiAutostartBaseBranches/**diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 90b9ed48063c..1cf4d753c348 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -51,6 +51,12 @@ export const SignalsConfigCreateBody = /* @__PURE__ */ zod.object({.describe("Default Slack channel for this team's signal inbox notifications, in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null means no team-level default; per-user channels still apply."),+ default_slack_notification_integration: zod+ .number()+ .nullish()+ .describe(+ "Connected Slack integration that owns `default_slack_notification_channel`. Send it together with the channel. A channel saved without it is routed through the team's oldest Slack integration, and clearing the channel clears this too."+ ),autostart_base_branches: zod.record(zod.string(), zod.string().max(signalsConfigCreateBodyAutostartBaseBranchesMaxOne)).optional()diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsxindex 9a7781700b9b..9cc613a377c4 100644--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx@@ -72,13 +72,14 @@ function ConnectSlackPrompt(): JSX.Element {/*** Team-wide channel where every actionable report is posted regardless of the suggested reviewer,* backed by `default_slack_notification_channel` on `signalTeamConfigLogic`. Toggling off (or- * clearing the channel) disables the team default. The backend routes the team channel through the- * team's first Slack integration (`_get_team_slack_integration`), so we target `integrations[0]`- * here too.+ * clearing the channel) disables the team default. The channel is saved with the workspace it came+ * from, because a channel id from one Slack workspace fails in every other.*/-function TeamChannelCard({ integration }: { integration: IntegrationType }): JSX.Element {+function TeamChannelCard({ integrations }: { integrations: IntegrationType[] }): JSX.Element {const { teamConfig, teamConfigLoading } = useValues(signalTeamConfigLogic)const { patchTeamConfig } = useActions(signalTeamConfigLogic)+ const savedIntegrationId = teamConfig?.default_slack_notification_integration ?? null+ const integration = integrations.find((i) => i.id === savedIntegrationId) ?? integrations[0]// Local view state: the toggle is on but no channel has been picked yet. A saved// channel implies enabled on its own, so this only bridges the picking moment.const [pickerExpanded, setPickerExpanded] = useState(false)@@ -119,7 +120,12 @@ function TeamChannelCard({ integration }: { integration: IntegrationType }): JSX<SlackChannelPickerintegration={integration}value={channel ?? undefined}- onChange={(next) => patchTeamConfig({ default_slack_notification_channel: next })}+ onChange={(next) =>+ patchTeamConfig({+ default_slack_notification_channel: next,+ default_slack_notification_integration: next ? integration.id : null,+ })+ }/></div>)}@@ -420,7 +426,7 @@ export function SlackNotificationsSection(): JSX.Element {return (<div className="flex flex-col gap-3">- <TeamChannelCard integration={integrations[0]} />+ <TeamChannelCard integrations={integrations} /><PerUserNotificationCard integrations={integrations} /></div>)diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex 2eb11d774900..79655071115f 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -398,6 +398,8 @@ export interface SignalTeamConfig {default_autostart_priority: SignalReportPriority | null/** Default Slack channel for this team's inbox notifications. */default_slack_notification_channel?: string | null+ /** Slack integration that owns the team channel. Send it together with the channel. */+ default_slack_notification_integration?: number | null/** Per-repo base-branch overrides for auto-started PRs, keyed by 'org/repo'. */autostart_base_branches?: Record<string, string>/** Integration self-driving opens a tracker issue in for each PR it makes. Null turns tracker issues off. */diff --git a/products/slack_app/backend/inbox_channel.py b/products/slack_app/backend/inbox_channel.pyindex 193ddde0e350..4da031ca0cd5 100644--- a/products/slack_app/backend/inbox_channel.py+++ b/products/slack_app/backend/inbox_channel.py@@ -7,6 +7,7 @@ from django.core.cache import cacheimport structlogfrom slack_sdk.errors import SlackApiError+from posthog.integrations import IntegrationManagerfrom posthog.models.integration import SlackIntegrationfrom posthog.slack.formatting import channel_id_from_target@@ -41,12 +42,24 @@ def _get_team_channel(team_id: int) -> str | None:return get_default_slack_notification_channel(team_id)-def _set_team_channel(team_id: int, value: str) -> None:+def _get_team_channel_integration_id(team_id: int) -> int | None:+ from products.signals.backend.facade.api import (+ get_default_slack_notification_integration_id, # noqa: PLC0415 — keeps the signals temporal stack off the slack import path+ )++ return get_default_slack_notification_integration_id(team_id)+++def _set_team_channel(integration: WorkspaceIntegration, value: str) -> None:from products.signals.backend.facade.api import (set_default_slack_notification_channel, # noqa: PLC0415 — keeps the signals temporal stack off the slack import path)- set_default_slack_notification_channel(team_id, value)+ set_default_slack_notification_channel(integration.team_id, value, integration_id=integration.id)+++def _team_has_other_slack_workspace(integration: WorkspaceIntegration) -> bool:+ return any(row.id != integration.id for row in IntegrationManager.slack.any.list(integration.team_id))def _channel_target(channel_id: str, channel_name: str) -> str:@@ -105,7 +118,8 @@ def _claim_channel_creation(slack_team_id: str) -> bool: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 the- install lacks ``channels:manage`` — callers fall back to manual instructions.+ install lacks ``channels:manage``, or when another connected workspace owns the team channel —+ callers fall back to manual instructions.Idempotent: reuses the configured channel, then any existing #posthog-inbox, before creating."""@@ -114,15 +128,22 @@ def ensure_inbox_channel(integration: WorkspaceIntegration) -> tuple[str, str] |configured = _get_team_channel(team_id)if configured:+ owner_id = _get_team_channel_integration_id(team_id)+ # This workspace cannot see a channel that another workspace owns, so replacing it would move+ # the team's notifications to this workspace without anyone choosing that.+ if owner_id is not None and owner_id != integration.id:+ return Nonechannel_id = channel_id_from_target(configured)if _channel_exists(slack, channel_id):return channel_id, channel_name_from_target(configured)+ if owner_id is None and _team_has_other_slack_workspace(integration):+ return None# Without channels:manage we can't create, so the only option is to find an already-created channel.if slack.missing_scopes(INBOX_CHANNEL_REQUIRED_SCOPES):existing = _find_inbox_channel(slack)if existing:- _set_team_channel(team_id, _channel_target(*existing))+ _set_team_channel(integration, _channel_target(*existing))return existingreturn None@@ -131,7 +152,7 @@ def ensure_inbox_channel(integration: WorkspaceIntegration) -> tuple[str, str] |# than racing a second create — the claim holder will finish and persist it.existing = _find_inbox_channel(slack)if existing:- _set_team_channel(team_id, _channel_target(*existing))+ _set_team_channel(integration, _channel_target(*existing))return existingreturn None@@ -151,7 +172,7 @@ def ensure_inbox_channel(integration: WorkspaceIntegration) -> tuple[str, str] |return Noneresult = found- _set_team_channel(team_id, _channel_target(*result))+ _set_team_channel(integration, _channel_target(*result))return resultdiff --git a/products/slack_app/backend/tests/services/test_slack_welcome_messages.py b/products/slack_app/backend/tests/services/test_slack_welcome_messages.pyindex 53e3f51684ba..e821decdcd9e 100644--- a/products/slack_app/backend/tests/services/test_slack_welcome_messages.py+++ b/products/slack_app/backend/tests/services/test_slack_welcome_messages.py@@ -142,7 +142,7 @@ class TestOnboardingDm:@patch("posthog.models.integration.slack.WebClient")def test_dm_join_button_when_channel_exists_with_scope(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}_, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))@@ -154,7 +154,7 @@ class TestOnboardingDm:client = self._client(mock_webclient_class)self.integration.config = {"scope": "chat:write"}self.integration.save()- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}_, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))@@ -196,7 +196,7 @@ class TestOnboardingDm:@patch("posthog.models.integration.slack.WebClient")def test_build_dm_omits_join_when_already_member(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}_, blocks = build_onboarding_dm(@@ -209,7 +209,7 @@ class TestOnboardingDm:@patch("posthog.models.integration.slack.WebClient")def test_build_dm_already_member_shows_only_github(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}_, blocks = build_onboarding_dm(diff --git a/products/slack_app/backend/tests/test_inbox_channel.py b/products/slack_app/backend/tests/test_inbox_channel.pyindex 0c8e040c2866..beea2efc699f 100644--- a/products/slack_app/backend/tests/test_inbox_channel.py+++ b/products/slack_app/backend/tests/test_inbox_channel.py@@ -54,7 +54,7 @@ class TestInboxChannel:@patch("posthog.models.integration.slack.WebClient")def test_reuses_configured_channel(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C777|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C777|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C777"}}result = inbox_channel.ensure_inbox_channel(self.integration)@@ -123,7 +123,7 @@ class TestInboxChannel:@patch("posthog.models.integration.slack.WebClient")def test_is_inbox_channel_by_configured_id(self, mock_webclient_class):self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C222|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C222|#posthog-inbox", integration_id=self.integration.id)assert inbox_channel.is_inbox_channel(self.integration, "C222") is True@@ -185,7 +185,7 @@ class TestInboxChannel:@patch("posthog.models.integration.slack.WebClient")def test_configured_channel_preserved_on_transient_error(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C_CUSTOM|#alerts")+ set_default_slack_notification_channel(self.team.id, "C_CUSTOM|#alerts", integration_id=self.integration.id)client.conversations_info.side_effect = SlackApiError("ratelimited", {"error": "ratelimited"})result = inbox_channel.ensure_inbox_channel(self.integration)@@ -198,7 +198,7 @@ class TestInboxChannel:@patch("posthog.models.integration.slack.WebClient")def test_configured_channel_replaced_when_definitely_gone(self, mock_webclient_class):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C_OLD|#alerts")+ set_default_slack_notification_channel(self.team.id, "C_OLD|#alerts", integration_id=self.integration.id)client.conversations_info.side_effect = SlackApiError("channel_not_found", {"error": "channel_not_found"})client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}client.conversations_create.return_value = {"channel": {"id": "C_NEW"}}@@ -208,6 +208,26 @@ class TestInboxChannel:assert result == ("C_NEW", "#posthog-inbox")assert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"+ @pytest.mark.parametrize("bound", [True, False])+ @patch("posthog.models.integration.slack.WebClient")+ def test_second_workspace_leaves_the_team_channel_alone(self, mock_webclient_class, bound):+ client = self._client(mock_webclient_class)+ other = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_OTHER",+ config={},+ sensitive_config={"access_token": "xoxb-other"},+ )+ set_default_slack_notification_channel(+ self.team.id, "C_OTHER|#posthog-inbox", integration_id=self.integration.id if bound else None+ )+ client.conversations_info.side_effect = SlackApiError("channel_not_found", {"error": "channel_not_found"})++ assert inbox_channel.ensure_inbox_channel(other) is None+ client.conversations_create.assert_not_called()+ assert get_default_slack_notification_channel(self.team.id) == "C_OTHER|#posthog-inbox"+@patch("posthog.models.integration.slack.WebClient")def test_ensure_returns_none_when_create_claimed_by_other(self, mock_webclient_class):client = self._client(mock_webclient_class)diff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.pyindex 36aa92c88bba..56d340539498 100644--- a/products/slack_app/backend/tests/test_onboarding.py+++ b/products/slack_app/backend/tests/test_onboarding.py@@ -109,7 +109,7 @@ class TestOnboarding:):# Install-only delivery: always post, even if every step is already done (shown as '✅').client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}@@ -203,7 +203,7 @@ class TestOnboarding:self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}self.organization.is_ai_data_processing_approved = False@@ -224,7 +224,7 @@ class TestOnboarding:self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin):client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox", integration_id=self.integration.id)client.conversations_info.return_value = {"channel": {"id": "C1"}}client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}self.organization.is_ai_data_processing_approved = Falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 409cc43befe2..309306552c96 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -111978,6 +111978,11 @@ export namespace Schemas {* @nullable*/default_slack_notification_channel?: string | null;+ /**+ * Connected Slack integration that owns `default_slack_notification_channel`. Send it together with the channel. A channel saved without it is routed through the team's oldest Slack integration, and clearing the channel clears this too.+ * @nullable+ */+ default_slack_notification_integration?: number | null;/** Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch. */autostart_base_branches?: SignalTeamConfigAutostartBaseBranches;/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex b8f8b8ec0c8f..c8d75a38bd76 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -215,6 +215,12 @@ export const SignalsConfigCreateBody = () => zod.object({.describe("Default Slack channel for this team's signal inbox notifications, in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null means no team-level default; per-user channels still apply."),+ default_slack_notification_integration: zod+ .number()+ .nullish()+ .describe(+ "Connected Slack integration that owns `default_slack_notification_channel`. Send it together with the channel. A channel saved without it is routed through the team's oldest Slack integration, and clearing the channel clears this too."+ ),autostart_base_branches: zod.record(zod.string(), zod.string().max(signalsConfigCreateBodyAutostartBaseBranchesMaxOne)).optional()diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 95f5b52783e4..f9940568b3df 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -1242,6 +1242,7 @@ const InboxSteeringInstructionsUpdateSchema = () => {autostart_enabled: true,default_autostart_priority: true,default_slack_notification_channel: true,+ default_slack_notification_integration: true,autostart_base_branches: true,issue_tracking_integration: true,issue_tracking_config: true,