Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): Notify suggested reviewers in Slack (#58774)

Michael Matlokac066578c416a
diff --git a/frontend/src/scenes/authentication/AccountConnected.tsx b/frontend/src/scenes/authentication/AccountConnected.tsx
index 83a1e370faed..8adf8c6057f2 100644
--- a/frontend/src/scenes/authentication/AccountConnected.tsx
+++ b/frontend/src/scenes/authentication/AccountConnected.tsx
@@ -10,15 +10,30 @@ import { SceneExport } from 'scenes/sceneTypes'
import type { SSOProvider } from '~/types'
-const POSTHOG_CODE_DEEP_LINK = 'posthog-code://integration'
+/** Path segment under {@link urls.accountConnected} — SSO link, GitHub integration, or Slack integration. */
+export type AccountConnectedKind = 'github-login' | 'github-integration' | 'slack-integration' | 'invalid'
-function posthogCodeDeepUrl(searchParams: Record<string, unknown>): string {
- const url = new URL(POSTHOG_CODE_DEEP_LINK)
+// Per-kind deep link host. GitHub already uses `posthog-code://integration`;
+// Slack uses its own host so each provider's main-process handler stays isolated
+// (the deep-link service registers one handler per host).
+const DEEP_LINK_HOSTS: Record<Exclude<AccountConnectedKind, 'invalid'>, string> = {
+ 'github-login': 'posthog-code://integration',
+ 'github-integration': 'posthog-code://integration',
+ 'slack-integration': 'posthog-code://slack-integration',
+}
+
+function posthogCodeDeepUrl(
+ kind: Exclude<AccountConnectedKind, 'invalid'>,
+ searchParams: Record<string, unknown>
+): string {
+ const url = new URL(DEEP_LINK_HOSTS[kind])
const provider = typeof searchParams.provider === 'string' ? searchParams.provider : ''
if (provider) {
url.searchParams.set('provider', provider)
}
- for (const key of ['project_id', 'installation_id'] as const) {
+ // `integration_id` (Slack and most kinds) and `installation_id` (GitHub) are both
+ // forwarded so the desktop handler can act on whichever its provider uses.
+ for (const key of ['project_id', 'installation_id', 'integration_id'] as const) {
const value = searchParams[key]
if (value !== undefined && value !== null && value !== '') {
url.searchParams.set(key, String(value))
@@ -36,38 +51,49 @@ function posthogCodeDeepUrl(searchParams: Record<string, unknown>): string {
return url.toString()
}
-/** Path segment under {@link urls.accountConnected} — SSO link vs GitHub user integration. */
-export type AccountConnectedKind = 'github-login' | 'github-integration' | 'invalid'
-
export interface AccountConnectedProps {
kind: AccountConnectedKind
}
+// Integration providers that aren't SSO providers, but render on the same page.
+const INTEGRATION_LABELS: Record<string, string> = {
+ slack: 'Slack',
+}
+
function providerLabel(provider: string | undefined): string {
if (!provider) {
return 'Account'
}
- return SSO_PROVIDER_NAMES[provider as SSOProvider] ?? provider
+ return SSO_PROVIDER_NAMES[provider as SSOProvider] ?? INTEGRATION_LABELS[provider] ?? provider
}
-function headline(kind: 'github-login' | 'github-integration', label: string, isError: boolean): string {
- if (kind === 'github-integration') {
+function headline(kind: Exclude<AccountConnectedKind, 'invalid'>, label: string, isError: boolean): string {
+ if (kind === 'github-integration' || kind === 'slack-integration') {
return isError ? `${label} connection failed` : `${label} connected`
}
return isError ? `${label} linking failed` : `${label} linked to account`
}
+const VALID_KINDS: ReadonlyArray<Exclude<AccountConnectedKind, 'invalid'>> = [
+ 'github-login',
+ 'github-integration',
+ 'slack-integration',
+]
+
export const scene: SceneExport<AccountConnectedProps> = {
component: AccountConnected,
paramsToProps: ({ params: { kind: raw } }) => {
- const kind: AccountConnectedKind = raw === 'github-login' || raw === 'github-integration' ? raw : 'invalid'
+ const kind: AccountConnectedKind = (VALID_KINDS as readonly string[]).includes(raw ?? '')
+ ? (raw as AccountConnectedKind)
+ : 'invalid'
return { kind }
},
}
/**
- * Unified return page for PostHog Code / web: social SSO link (`github-login`) or
- * personal GitHub integration (`github-integration`). Navigates to `posthog-code://integration?…` for the desktop app.
+ * Unified return page for PostHog Code / web: social SSO link (`github-login`), personal GitHub
+ * integration (`github-integration`), or team Slack integration (`slack-integration`). Navigates
+ * to the matching `posthog-code://…` deep link so the desktop app refreshes its integrations.
*/
export function AccountConnected({ kind }: AccountConnectedProps): JSX.Element {
const { searchParams } = useValues(router)
@@ -77,7 +103,7 @@ export function AccountConnected({ kind }: AccountConnectedProps): JSX.Element {
useEffect(() => {
if (kind !== 'invalid') {
- window.location.href = posthogCodeDeepUrl(searchParams)
+ window.location.href = posthogCodeDeepUrl(kind, searchParams)
}
}, [kind, searchParams])
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 0247bb629f4a..8175208643a1 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -147,8 +147,9 @@ export const urls = {
/** After linking a social provider to an existing session (OAuth `next`; see posthog/api/authentication.py sso_login). */
accountSocialConnected: (): string => '/account/social-connected',
/**
- * PostHog Code / web return page after connecting an account. Use `github-login` (social SSO) or
- * `github-integration` (user GitHub App integration); see `AccountConnected` and `posthog/api/authentication.py` / `user_integration.py`.
+ * PostHog Code / web return page after connecting an account. Use `github-login` (social SSO),
+ * `github-integration` (user GitHub App integration), or `slack-integration` (team Slack integration);
+ * see `AccountConnected` and `posthog/api/authentication.py` / `user_integration.py`.
*/
accountConnected: (kind: string = ':kind'): string =>
kind === ':kind' ? '/account-connected/:kind' : `/account-connected/${kind}`,
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 66b30443da1e..24e29c52ee4e 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -278,6 +278,28 @@ class SlackChannelSerializer(serializers.Serializer):
)
+class SlackChannelsQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text="Optional case-insensitive channel name or ID search query.",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=50,
+ min_value=1,
+ max_value=200,
+ help_text="Maximum number of channels to return per request (max 200).",
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ help_text="Number of channels to skip before returning results.",
+ )
+
+
class SlackChannelsResponseSerializer(serializers.Serializer):
channels = SlackChannelSerializer(many=True, help_text="Slack channels visible to the PostHog Slack app.")
lastRefreshedAt = serializers.CharField(
@@ -285,6 +307,10 @@ class SlackChannelsResponseSerializer(serializers.Serializer):
allow_null=True,
help_text="ISO 8601 timestamp of the last full Slack API refresh (only set on full lists, not single-channel lookups).",
)
+ has_more = serializers.BooleanField(
+ required=False,
+ help_text="Whether more channels match the current search beyond this page.",
+ )
@extend_schema_serializer(component_name="IntegrationConfig")
@@ -726,7 +752,29 @@ class IntegrationViewSet(
raise ValidationError("Kind not supported")
- @extend_schema(responses={200: SlackChannelsResponseSerializer})
+ @staticmethod
+ def _serialize_slack_channel(channel: dict) -> dict:
+ return {
+ "id": channel["id"],
+ "name": channel["name"],
+ "is_private": channel["is_private"],
+ "is_member": channel.get("is_member", True),
+ "is_ext_shared": channel["is_ext_shared"],
+ "is_private_without_access": channel.get("is_private_without_access", False),
+ }
+
+ @staticmethod
+ def _filter_slack_channels_for_search(channels: list[dict], search: str) -> list[dict]:
+ visible = [channel for channel in channels if not channel.get("is_private_without_access")]
+ query = search.strip().lower()
+ if not query:
+ return visible
+ return [channel for channel in visible if query in channel["name"].lower() or query in channel["id"].lower()]
+
+ @extend_schema(
+ parameters=[SlackChannelsQuerySerializer],
+ responses={200: SlackChannelsResponseSerializer},
+ )
@action(methods=["GET"], detail=True, url_path="channels")
def channels(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance = self.get_object()
@@ -742,53 +790,52 @@ class IntegrationViewSet(
if not authed_user:
raise ValidationError("SlackIntegration: Missing authed_user_id in integration config")
+ # Key on the Integration row PK (unique per PostHog team × Slack workspace), not
+ # integration_id (the Slack workspace id, shared across teams). Two teams that
+ # install the same workspace must not share cached private-channel lists.
+ key = f"slack/{instance.id}/{should_include_private_channels}/channels"
+
channel_id = request.query_params.get("channel_id")
if channel_id:
+ data = cache.get(key)
+ if data is not None:
+ for channel in data["channels"]:
+ if channel["id"] == channel_id:
+ return Response({"channels": [channel]})
channel = slack.get_channel_by_id(channel_id, should_include_private_channels, authed_user)
if channel:
- return Response(
- {
- "channels": [
- {
- "id": channel["id"],
- "name": channel["name"],
- "is_private": channel["is_private"],
- "is_member": channel.get("is_member", True),
- "is_ext_shared": channel["is_ext_shared"],
- "is_private_without_access": channel["is_private_without_access"],
- }
- ]
- }
- )
- else:
- return Response({"channels": []})
+ return Response({"channels": [self._serialize_slack_channel(channel)]})
+ return Response({"channels": []})
+
+ query_serializer = SlackChannelsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ search = query_serializer.validated_data["search"]
+ limit = query_serializer.validated_data["limit"]
+ offset = query_serializer.validated_data["offset"]
- # Key on the Integration row PK (unique per PostHog team × Slack workspace), not
- # integration_id (the Slack workspace id, shared across teams). Two teams that
- # install the same workspace must not share cached private-channel lists.
- key = f"slack/{instance.id}/{should_include_private_channels}/channels"
data = cache.get(key)
- if data is not None and not force_refresh:
- return Response(data)
+ if data is None or force_refresh:
+ data = {
+ "channels": [
+ self._serialize_slack_channel(channel)
+ for channel in slack.list_channels(should_include_private_channels, authed_user)
+ ],
+ "lastRefreshedAt": timezone.now().isoformat(),
+ }
+ cache.set(key, data, 60 * 60) # one hour
- response = {
- "channels": [
- {
- "id": channel["id"],
- "name": channel["name"],
- "is_private": channel["is_private"],
- "is_member": channel.get("is_member", True),
- "is_ext_shared": channel["is_ext_shared"],
- "is_private_without_access": channel.get("is_private_without_access", False),
- }
- for channel in slack.list_channels(should_include_private_channels, authed_user)
- ],
- "lastRefreshedAt": timezone.now().isoformat(),
- }
+ filtered_channels = self._filter_slack_channels_for_search(data["channels"], search)
+ page = filtered_channels[offset : offset + limit]
+ has_more = offset + limit < len(filtered_channels)
- cache.set(key, response, 60 * 60) # one hour
- return Response(response)
+ return Response(
+ {
+ "channels": page,
+ "lastRefreshedAt": data.get("lastRefreshedAt"),
+ "has_more": has_more,
+ }
+ )
@action(methods=["GET"], detail=True, url_path="twilio_phone_numbers")
def twilio_phone_numbers(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index dcf8f6c4760e..54d8b83d51fb 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -1058,6 +1058,93 @@ class TestIntegrationAPIKeyAccess:
elif expected_detail_substring is not None:
assert expected_detail_substring in response.json()["detail"]
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_channels_action_search_and_pagination(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_SEARCH",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.list_channels.return_value = [
+ {
+ "id": "C1",
+ "name": "general",
+ "is_private": False,
+ "is_member": True,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ },
+ {
+ "id": "C2",
+ "name": "random",
+ "is_private": False,
+ "is_member": True,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ },
+ {
+ "id": "C3",
+ "name": "engineering",
+ "is_private": False,
+ "is_member": True,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ },
+ {
+ "id": "CPRIVATE",
+ "name": PRIVATE_CHANNEL_WITHOUT_ACCESS,
+ "is_private": True,
+ "is_member": False,
+ "is_ext_shared": False,
+ "is_private_without_access": True,
+ },
+ ]
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_search"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+
+ base_url = f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/channels/"
+
+ response = client.get(
+ f"{base_url}?search=eng&limit=10",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["channels"] == [
+ {
+ "id": "C3",
+ "name": "engineering",
+ "is_private": False,
+ "is_member": True,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ }
+ ]
+ assert data["has_more"] is False
+
+ response = client.get(
+ f"{base_url}?limit=1&offset=1",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert len(data["channels"]) == 1
+ assert data["channels"][0]["id"] == "C2"
+ assert data["has_more"] is True
+
+ mock_slack_instance.list_channels.assert_called_once()
+
def test_channels_action_with_missing_authed_user_returns_400(self, client: HttpClient):
slack_integration = Integration.objects.create(
team=self.team,
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index a4f5900838a8..6008d2fe804b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -467,6 +467,7 @@ SPECTACULAR_SETTINGS = {
"LensProviderEnum": "products.replay_vision.backend.models.replay_lens.LensProvider",
"ObservationStatusEnum": "products.replay_vision.backend.models.replay_observation.ObservationStatus",
"ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger",
+ "AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority",
"UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"PropertyGroupOperator": ["AND", "OR"],
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 4a3862e201cd..5fe12db867ce 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -252,6 +252,7 @@ class TestSignalsProductModuleIntegrity:
def test_activities_remain_unchanged(self):
"""Ensure all expected signals product activities are present."""
expected_activities = [
+ "dispatch_inbox_slack_notifications_activity",
"emit_backfill_signal_activity",
"fetch_error_tracking_issues_activity",
"assign_and_emit_signal_activity",
diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_workflow.py
index 1e6978826031..e3e0a48c7f06 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_workflow.py
@@ -58,6 +58,7 @@ async def workflows_batch_export(ateam, interval, exclude_events, temporal_clien
@pytest.mark.parametrize("interval", ["hour", "day"], indirect=True)
@pytest.mark.parametrize("exclude_events", [None, ["test-exclude"]], indirect=True)
async def test_workflows_export_workflow(
clickhouse_client,
workflows_batch_export,
@@ -102,6 +103,7 @@ async def test_workflows_export_workflow(
finish_batch_export_run,
],
workflow_runner=UnsandboxedWorkflowRunner(),
+ build_id="test-workflows-batch-export",
):
await activity_environment.client.execute_workflow(
WorkflowsBatchExportWorkflow.run,
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index f0c4eecf8e61..50c86d5c41f8 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -270,6 +270,8 @@ export interface SlackChannelsResponseApi {
* @nullable
*/
lastRefreshedAt?: string | null
+ /** Whether more channels match the current search beyond this page. */
+ has_more?: boolean
}
/**
@@ -517,6 +519,24 @@ export const IntegrationsListKind = {
Vercel: 'vercel',
} as const
+export type IntegrationsChannelsRetrieveParams = {
+ /**
+ * Maximum number of channels to return per request (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number
+ /**
+ * Number of channels to skip before returning results.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Optional case-insensitive channel name or ID search query.
+ */
+ search?: string
+}
+
export type IntegrationsGithubBranchesRetrieveParams = {
/**
* Maximum number of branches to return
diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.ts
index efb0fdabb68e..daa093c55af7 100644
--- a/products/integrations/frontend/generated/api.ts
+++ b/products/integrations/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
GitHubReposResponseApi,
GitHubTeamsResponseApi,
IntegrationConfigApi,
+ IntegrationsChannelsRetrieveParams,
IntegrationsGithubBranchesRetrieveParams,
IntegrationsGithubReposRetrieveParams,
IntegrationsGithubTeamsRetrieveParams,
@@ -288,16 +289,33 @@ export const integrationsAnthropicManagedAgentsRetrieve = async (
})
}
-export const getIntegrationsChannelsRetrieveUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/integrations/${id}/channels/`
+export const getIntegrationsChannelsRetrieveUrl = (
+ projectId: string,
+ id: number,
+ params?: IntegrationsChannelsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/integrations/${id}/channels/?${stringifiedParams}`
+ : `/api/projects/${projectId}/integrations/${id}/channels/`
}
export const integrationsChannelsRetrieve = async (
projectId: string,
id: number,
+ params?: IntegrationsChannelsRetrieveParams,
options?: RequestInit
): Promise<SlackChannelsResponseApi> => {
- return apiMutator<SlackChannelsResponseApi>(getIntegrationsChannelsRetrieveUrl(projectId, id), {
+ return apiMutator<SlackChannelsResponseApi>(getIntegrationsChannelsRetrieveUrl(projectId, id, params), {
...options,
method: 'GET',
})
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
new file mode 100644
index 000000000000..62bf70831e98
--- /dev/null
+++ b/products/signals/backend/implementation_pr.py
@@ -0,0 +1,31 @@
+"""Resolve implementation PR URLs linked to signal reports."""
+
+from django.db.models.fields.json import KeyTextTransform
+
+from products.signals.backend.models import SignalReportTask
+from products.tasks.backend.models import TaskRun
+
+
+def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
+ """PR URL from the latest implementation task run for each report, when available."""
+ if not report_ids:
+ return {}
+
+ latest_runs = (
+ TaskRun.objects.filter(
+ task__signal_report_tasks__report_id__in=report_ids,
+ task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ output__pr_url__isnull=False,
+ )
+ .exclude(output__pr_url="")
+ .order_by("task__signal_report_tasks__report_id", "-created_at", "-id")
+ .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
+ .values("task__signal_report_tasks__report_id", "output_pr_url_text")
+ .distinct("task__signal_report_tasks__report_id")
+ )
+
+ return {
+ str(row["task__signal_report_tasks__report_id"]): row["output_pr_url_text"]
+ for row in latest_runs
+ if row["task__signal_report_tasks__report_id"] and row["output_pr_url_text"]
+ }
diff --git a/products/signals/backend/migrations/0020_signaluserautonomyconfig_slack_notification_fields.py b/products/signals/backend/migrations/0020_signaluserautonomyconfig_slack_notification_fields.py
new file mode 100644
index 000000000000..c2ae4b2cce99
--- /dev/null
+++ b/products/signals/backend/migrations/0020_signaluserautonomyconfig_slack_notification_fields.py
@@ -0,0 +1,46 @@
+# Generated for Signals Slack notification configuration
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1155_sharingconfiguration_interviewee_context"),
+ ("signals", "0019_alter_signalsourceconfig_source_product_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signaluserautonomyconfig",
+ name="slack_notification_integration",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.integration",
+ ),
+ ),
+ migrations.AddField(
+ model_name="signaluserautonomyconfig",
+ name="slack_notification_channel",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ migrations.AddField(
+ model_name="signaluserautonomyconfig",
+ name="slack_notification_min_priority",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("P0", "P0"),
+ ("P1", "P1"),
+ ("P2", "P2"),
+ ("P3", "P3"),
+ ("P4", "P4"),
+ ],
+ max_length=2,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 2bf59ebf84a5..c4e79a2cd9dc 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0019_alter_signalsourceconfig_source_product_and_more
+0020_signaluserautonomyconfig_slack_notification_fields
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index b4d1cb6de224..25d64ed1facc 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -100,6 +100,21 @@ register_team_extension_signal(SignalTeamConfig, logger=logger)
class SignalUserAutonomyConfig(UUIDModel):
user = models.OneToOneField("posthog.User", on_delete=models.CASCADE, related_name="signal_autonomy_config")
autostart_priority = models.CharField(max_length=2, choices=AutonomyPriority, null=True, blank=True)
+ # Slack notifications for new inbox items where the user is a suggested reviewer.
+ # All three fields are required together; a config row with any of them null
+ # disables notifications. Integration is team-scoped, so notifications are
+ # scoped to a single team via the integration's team.
+ slack_notification_integration = models.ForeignKey(
+ "posthog.Integration",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ )
+ slack_notification_channel = models.CharField(max_length=255, null=True, blank=True)
+ # When null, all priorities (including reports with no priority) notify.
+ # When set, only reports with a priority at or above this value (P0 highest) notify.
+ slack_notification_min_priority = models.CharField(max_length=2, choices=AutonomyPriority, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 3da6cfcb4db1..642dfdbfd0f4 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -159,11 +159,39 @@ class _UserSerializer(serializers.ModelSerializer):
class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
user = _UserSerializer(read_only=True)
+ slack_notification_integration_id = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="ID of the Slack Integration to deliver inbox-item notifications through, or null when notifications are disabled.",
+ )
class Meta:
model = SignalUserAutonomyConfig
- fields = ["id", "user", "autostart_priority", "created_at", "updated_at"]
+ fields = [
+ "id",
+ "user",
+ "autostart_priority",
+ "slack_notification_integration_id",
+ "slack_notification_channel",
+ "slack_notification_min_priority",
+ "created_at",
+ "updated_at",
+ ]
read_only_fields = ["id", "user", "created_at", "updated_at"]
+ extra_kwargs = {
+ "slack_notification_channel": {
+ "help_text": (
+ "Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere "
+ "(only the channel id is required). Null disables Slack notifications."
+ )
+ },
+ "slack_notification_min_priority": {
+ "help_text": (
+ "Minimum report priority that triggers a Slack notification. P0 is highest. "
+ "Null means notify on every priority (and reports without a priority judgment)."
+ )
+ },
+ }
class SignalReportTaskSerializer(serializers.ModelSerializer):
@@ -175,6 +203,27 @@ class SignalReportTaskSerializer(serializers.ModelSerializer):
class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
autostart_priority = serializers.ChoiceField(choices=AutonomyPriority.choices, required=False, allow_null=True)
+ slack_notification_integration_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Primary key of a Slack `Integration` row in one of the caller's teams. Pair with "
+ "`slack_notification_channel` to enable notifications; pass null on either to disable them."
+ ),
+ )
+ slack_notification_channel = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ max_length=255,
+ help_text="`channel_id|#channel-name` target — same convention used by Insight Alerts.",
+ )
+ slack_notification_min_priority = serializers.ChoiceField(
+ choices=AutonomyPriority.choices,
+ required=False,
+ allow_null=True,
+ help_text="P0 is highest. Null = notify for every priority.",
+ )
class SignalReportSerializer(serializers.ModelSerializer):
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
new file mode 100644
index 000000000000..675362d2c63c
--- /dev/null
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -0,0 +1,386 @@
+"""Slack notifications for signals inbox items.
+
+When a report transitions to READY (a new inbox item lands), we look up the
+suggested reviewers from its `suggested_reviewers` artefact, resolve them to
+PostHog users, and dispatch a Slack message to each user that has configured a
+Slack channel and integration in their `SignalUserAutonomyConfig`.
+
+Each user's `slack_notification_min_priority` filters out reports below the
+configured threshold (P0 is highest). When the report has no priority
+judgement, we notify regardless of the user's threshold — the inbox should
+not silently swallow these.
+
+Messages are framed for public channels: each post names the suggested reviewer
+(Slack @mention when email matches the workspace, otherwise their PostHog name).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+
+from django.conf import settings
+from django.db.models import Q
+
+from slack_sdk.errors import SlackApiError
+
+from posthog.models import User
+from posthog.models.integration import Integration, SlackIntegration
+
+from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
+from products.signals.backend.models import (
+ AutonomyPriority,
+ SignalReport,
+ SignalReportArtefact,
+ SignalSourceConfig,
+ SignalUserAutonomyConfig,
+)
+from products.signals.backend.report_generation.resolve_reviewers import (
+ enrich_reviewer_dicts_with_org_members,
+ normalized_github_logins_from_suggested_reviewer_artefacts,
+ resolve_org_github_login_to_users,
+)
+
+logger = logging.getLogger(__name__)
+
+_SUMMARY_EXCERPT_MAX_LEN = 600
+_SLACK_HEADER_MAX_LEN = 150
+
+# Deep link opened by the PostHog Code desktop app. Override via env for prod (`posthog-code`).
+POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME = getattr(settings, "POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME", "posthog-code-dev")
+
+# Priority ranking — lower index is higher priority. Index used for threshold comparison.
+_PRIORITY_ORDER: tuple[str, ...] = (
+ AutonomyPriority.P0,
+ AutonomyPriority.P1,
+ AutonomyPriority.P2,
+ AutonomyPriority.P3,
+ AutonomyPriority.P4,
+)
+
+_SOURCE_PRODUCT_LABELS: dict[str, str] = {
+ choice.value: str(choice.label) for choice in SignalSourceConfig.SourceProduct
+}
+
+
+def _priority_rank(value: str | None) -> int | None:
+ if value is None:
+ return None
+ try:
+ return _PRIORITY_ORDER.index(value)
+ except ValueError:
+ return None
+
+
+def _meets_min_priority(report_priority: str | None, min_priority: str | None) -> bool:
+ """Whether a report with the given priority meets the user's min-priority threshold.
+
+ `min_priority=None` notifies for every report. When the report has no priority
+ (no priority_judgment artefact yet, or unrecognised value), we still notify —
+ suppression would silently drop new inbox items, which the user did not opt into.
+ """
+ if min_priority is None:
+ return True
+ report_rank = _priority_rank(report_priority)
+ if report_rank is None:
+ return True
+ min_rank = _priority_rank(min_priority)
+ if min_rank is None:
+ return True
+ # Lower index = higher priority (P0 < P4).
+ return report_rank <= min_rank
+
+
+def _latest_priority(report: SignalReport) -> str | None:
+ art = (
+ report.artefacts.filter(type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT)
+ .order_by("-created_at")
+ .first()
+ )
+ if art is None:
+ return None
+ try:
+ data = json.loads(art.content)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ value = data.get("priority")
+ return value if isinstance(value, str) else None
+
+
+@dataclass(frozen=True)
+class _RecipientPresentation:
+ header_label: str # `<@U…>` mention or display name for the header
+ plain_name: str
+
+
+def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
+ """Resolve the suggested-reviewer GitHub logins on the report to PostHog user IDs.
+
+ Uses the same enrichment path the API uses so a user that connected their
+ GitHub account after the report was generated is still picked up.
+ """
+ artefacts = list(
+ report.artefacts.filter(
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ ).order_by("-created_at")
+ )
+ if not artefacts:
+ return set()
+
+ logins = normalized_github_logins_from_suggested_reviewer_artefacts(artefacts)
+ if not logins:
+ return set()
+ login_map = resolve_org_github_login_to_users(report.team_id, logins)
+ if not login_map:
+ return set()
+
+ # Enrich each artefact's payload to drop reviewers that didn't resolve to a user.
+ resolved_user_ids: set[int] = set()
+ for art in artefacts:
+ try:
+ parsed = json.loads(art.content)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ continue
+ if not isinstance(parsed, list):
+ continue
+ enriched = enrich_reviewer_dicts_with_org_members(report.team_id, parsed, login_to_user=login_map)
+ for entry in enriched:
+ user = entry.get("user") if isinstance(entry, dict) else None
+ if isinstance(user, dict) and user.get("id"):
+ resolved_user_ids.add(int(user["id"]))
+ return resolved_user_ids
+
+
+def _notification_targets_for_report(report: SignalReport) -> list[SignalUserAutonomyConfig]:
+ user_ids = _resolve_suggested_reviewer_user_ids(report)
+ if not user_ids:
+ return []
+
+ return list(
+ SignalUserAutonomyConfig.objects.filter(user_id__in=user_ids)
+ .filter(slack_notification_integration__team_id=report.team_id)
+ .exclude(Q(slack_notification_integration__isnull=True) | Q(slack_notification_channel__isnull=True))
+ .exclude(slack_notification_channel="")
+ .select_related("slack_notification_integration")
+ )
+
+
+def _channel_id_from_target(value: str) -> str:
+ """Mirror `getSlackChannelIdFromTargetValue` in the frontend."""
+ return value.split("|", 1)[0].strip()
+
+
+def _channel_display_name(value: str) -> str:
+ pipe = value.find("|")
+ if pipe == -1:
+ return value
+ return value[pipe + 1 :].strip() or value[:pipe].strip()
+
+
+def _posthog_user_display_name(user: User) -> str:
+ parts = [user.first_name or "", user.last_name or ""]
+ name = " ".join(part for part in parts if part).strip()
+ if name:
+ return name
+ email = (user.email or "").strip()
+ if "@" in email:
+ return email.split("@", 1)[0]
+ return email or "Unknown user"
+
+
+def lookup_slack_user_id_by_email(slack: SlackIntegration, email: str) -> str | None:
+ normalized_email = email.strip().lower()
+ if not normalized_email:
+ return None
+
+ try:
+ response = slack.client.users_lookupByEmail(email=normalized_email)
+ except SlackApiError as exc:
+ error_code = exc.response.get("error") if exc.response else None
+ if error_code != "users_not_found":
+ logger.warning(
+ "signals_inbox_slack_user_email_lookup_failed",
+ extra={"email": normalized_email, "error": error_code},
+ )
+ return None
+
+ data = response.data if hasattr(response, "data") and isinstance(response.data, dict) else response
+ if not isinstance(data, dict) or not data.get("ok"):
+ return None
+
+ slack_user = data.get("user")
+ if not isinstance(slack_user, dict) or not slack_user.get("id"):
+ return None
+ return str(slack_user["id"])
+
+
+def _recipient_presentation(
+ user: User,
+ slack: SlackIntegration,
+ integration: Integration,
+) -> _RecipientPresentation:
+ plain_name = _posthog_user_display_name(user)
+ slack_user_id = lookup_slack_user_id_by_email(slack, user.email) if user.email else None
+ header_label = f"<@{slack_user_id}>" if slack_user_id else plain_name
+ return _RecipientPresentation(header_label=header_label, plain_name=plain_name)
+
+
+def _format_source_product_labels(source_products: list[str]) -> str:
+ if not source_products:
+ return ""
+ labels = [_SOURCE_PRODUCT_LABELS.get(product, product.replace("_", " ").title()) for product in source_products]
+ return ", ".join(labels)
+
+
+def _summary_excerpt(summary: str) -> str:
+ """First line of the report description only, capped at 600 characters."""
+ text = summary.strip()
+ if not text:
+ return ""
+ first_line = text.splitlines()[0].strip()
+ if not first_line:
+ return ""
+ if len(first_line) <= _SUMMARY_EXCERPT_MAX_LEN:
+ return first_line
+ return first_line[: _SUMMARY_EXCERPT_MAX_LEN - 3].rstrip() + "..."
+
+
+def _build_message_blocks(
+ report: SignalReport,
+ *,
+ priority: str | None,
+ source_products: list[str],
+ recipient: _RecipientPresentation,
+ implementation_pr_url: str | None = None,
+) -> tuple[list[dict], str]:
+ title_line = report.title or "New signals inbox item"
+ header_text = f"Inbox for {recipient.header_label}"
+ if priority:
+ header_text = f"{header_text} · {priority}"
+ if len(header_text) > _SLACK_HEADER_MAX_LEN:
+ header_text = header_text[: _SLACK_HEADER_MAX_LEN - 3] + "..."
+
+ body_parts = [f"*{title_line}*"]
+ summary_text = _summary_excerpt(report.summary or "")
+ if summary_text:
+ body_parts.append(summary_text)
+
+ blocks: list[dict] = [
+ {"type": "header", "text": {"type": "plain_text", "text": header_text}},
+ {"type": "section", "text": {"type": "mrkdwn", "text": "\n\n".join(body_parts)}},
+ ]
+
+ context_parts: list[str] = []
+ if report.signal_count:
+ signal_label = "signal" if report.signal_count == 1 else "signals"
+ context_parts.append(f"{report.signal_count} {signal_label}")
+ sources_line = _format_source_product_labels(source_products)
+ if sources_line:
+ context_parts.append(sources_line)
+ context_parts.append("Inbox")
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts)}],
+ }
+ )
+
+ action_elements: list[dict] = [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Open in PostHog Code", "emoji": True},
+ "url": f"{POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME}://inbox/{report.id}",
+ }
+ ]
+ if implementation_pr_url:
+ action_elements.append(
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Review PR in GitHub", "emoji": True},
+ "url": implementation_pr_url,
+ }
+ )
+ blocks.append({"type": "actions", "elements": action_elements})
+
+ priority_suffix = f" ({priority})" if priority else ""
+ fallback_text = f"Inbox for {recipient.plain_name}{priority_suffix}: {title_line}"
+ return blocks, fallback_text
+
+
+def dispatch_inbox_item_notifications(
+ report_id: str,
+ team_id: int,
+ source_products: list[str] | None = None,
+) -> int:
+ """Send Slack notifications for a newly-ready report. Returns count of messages sent.
+
+ Best-effort: per-target Slack errors are logged but do not raise. We only raise
+ on programmer error (missing report). The caller is the temporal summary workflow,
+ which already swallows notification exceptions.
+ """
+ try:
+ report = SignalReport.objects.get(id=report_id, team_id=team_id)
+ except SignalReport.DoesNotExist:
+ logger.warning(
+ "dispatch_inbox_item_notifications: report not found",
+ extra={"report_id": report_id, "team_id": team_id},
+ )
+ return 0
+
+ targets = _notification_targets_for_report(report)
+ if not targets:
+ return 0
+
+ priority = _latest_priority(report)
+ sources = source_products or []
+ implementation_pr_url = fetch_implementation_pr_urls_for_reports([str(report.id)]).get(str(report.id))
+ users_by_id = {user.id: user for user in User.objects.filter(id__in=[config.user_id for config in targets])}
+
+ sent = 0
+ for config in targets:
+ if not _meets_min_priority(priority, config.slack_notification_min_priority):
+ continue
+
+ user = users_by_id.get(config.user_id)
+ if user is None:
+ logger.warning(
+ "signals_inbox_slack_notification_missing_user",
+ extra={"report_id": report_id, "team_id": team_id, "user_id": config.user_id},
+ )
+ continue
+
+ integration = config.slack_notification_integration
+ channel = config.slack_notification_channel
+ if integration is None or not channel:
+ continue
+
+ try:
+ slack = SlackIntegration(integration)
+ recipient = _recipient_presentation(user, slack, integration)
+ blocks, text = _build_message_blocks(
+ report,
+ priority=priority,
+ source_products=sources,
+ recipient=recipient,
+ implementation_pr_url=implementation_pr_url,
+ )
+ slack.client.chat_postMessage(
+ channel=_channel_id_from_target(channel),
+ blocks=blocks,
+ text=text,
+ )
+ sent += 1
+ except Exception:
+ logger.exception(
+ "Failed to deliver signals inbox-item Slack notification",
+ extra={
+ "report_id": report_id,
+ "team_id": team_id,
+ "user_id": config.user_id,
+ "channel": _channel_display_name(channel),
+ },
+ )
+ return sent
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index 6997bb7c18d4..944835237d34 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -46,6 +46,7 @@ from products.signals.backend.temporal.signal_queries import (
)
from products.signals.backend.temporal.summary import (
SignalReportSummaryWorkflow,
+ dispatch_inbox_slack_notifications_activity,
mark_report_failed_activity,
mark_report_in_progress_activity,
mark_report_pending_input_activity,
@@ -68,6 +69,7 @@ WORKFLOWS = [
]
ACTIVITIES = [
+ dispatch_inbox_slack_notifications_activity,
emit_backfill_signal_activity,
fetch_error_tracking_issues_activity,
assign_and_emit_signal_activity,
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index 4dbebc69a547..6ca9556f47c1 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -327,6 +327,24 @@ class SignalReportSummaryWorkflow:
workflow.logger.exception(
f"Failed to publish report_completed notification for {inputs.report_id}",
)
+ # Slack notifications to suggested reviewers — separate from the Kafka
+ # publish above so a Slack outage doesn't suppress the inbox event,
+ # and a Kafka outage doesn't suppress Slack delivery.
+ try:
+ await workflow.execute_activity(
+ dispatch_inbox_slack_notifications_activity,
+ DispatchInboxSlackNotificationsInput(
+ team_id=inputs.team_id,
+ report_id=inputs.report_id,
+ source_products=source_products,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except Exception:
+ workflow.logger.exception(
+ f"Failed to dispatch inbox Slack notifications for {inputs.report_id}",
+ )
return has_new_signals
except Exception as e:
await workflow.execute_activity(
@@ -603,6 +621,33 @@ async def reset_report_to_potential_activity(input: ResetReportToPotentialInput)
)
+@dataclass
+class DispatchInboxSlackNotificationsInput:
+ team_id: int
+ report_id: str
+ source_products: list[str] = field(default_factory=list)
+
+
+@scoped_temporal()
+async def dispatch_inbox_slack_notifications_activity(
+ input: DispatchInboxSlackNotificationsInput,
+) -> int:
+ """Send Slack notifications for a newly-READY report to suggested reviewers
+ who have configured Slack notifications in their signal autonomy config.
+
+ Returns the number of messages dispatched (informational; failures are
+ swallowed inside the dispatcher and logged).
+ """
+ from products.signals.backend.slack_inbox_notifications import dispatch_inbox_item_notifications
+
+ return await database_sync_to_async(dispatch_inbox_item_notifications, thread_sensitive=False)(
+ report_id=input.report_id,
+ team_id=input.team_id,
+ source_products=input.source_products,
+ )
+
+
@dataclass
class PublishReportCompletedInput:
team_id: int
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 482d1073e5d1..1caecda6d673 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -12,8 +12,8 @@ from social_django.models import UserSocialAuth
from posthog.models.team.team import Team
+from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
-from products.signals.backend.views import SignalReportViewSet
from products.tasks.backend.models import Task, TaskRun
@@ -510,9 +510,7 @@ class TestSignalReportListAPI(APIBaseTest):
self._create_implementation_task_with_run(report_with_pr, pr_url="https://github.com/org/repo/pull/42")
self._create_implementation_task_with_run(report_without_pr, output={"commit_sha": "abc123"})
- viewset = SignalReportViewSet()
- viewset.team = self.team
- result = viewset._fetch_implementation_pr_urls_for_reports([str(report_with_pr.id), str(report_without_pr.id)])
+ result = fetch_implementation_pr_urls_for_reports([str(report_with_pr.id), str(report_without_pr.id)])
assert result == {
str(report_with_pr.id): "https://github.com/org/repo/pull/42",
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
new file mode 100644
index 000000000000..39bc9df0082b
--- /dev/null
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -0,0 +1,398 @@
+import json
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from social_django.models import UserSocialAuth
+
+from posthog.models import Organization, Team, User
+from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+
+from products.signals.backend.models import (
+ AutonomyPriority,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportTask,
+ SignalUserAutonomyConfig,
+)
+from products.signals.backend.slack_inbox_notifications import (
+ _build_message_blocks,
+ _meets_min_priority,
+ _recipient_presentation,
+ _RecipientPresentation,
+ _summary_excerpt,
+ dispatch_inbox_item_notifications,
+)
+from products.tasks.backend.models import Task, TaskRun
+
+
+ ("report_priority", "min_priority", "expected"),
+ [
+ # No threshold → always notify
+ ("P0", None, True),
+ ("P4", None, True),
+ (None, None, True),
+ # Report without a priority always notifies (we don't silently swallow)
+ (None, AutonomyPriority.P0, True),
+ # P0 is highest — P1 with min P0 should NOT notify
+ ("P1", AutonomyPriority.P0, False),
+ # P0 with min P2 notifies
+ ("P0", AutonomyPriority.P2, True),
+ # P2 with min P2 notifies (at threshold)
+ ("P2", AutonomyPriority.P2, True),
+ # P3 with min P2 does not
+ ("P3", AutonomyPriority.P2, False),
+ # Unknown priority value → notify (fallback to "no judgement")
+ ("XX", AutonomyPriority.P1, True),
+ ],
+)
+def test_meets_min_priority(report_priority: str | None, min_priority: str | None, expected: bool) -> None:
+ assert _meets_min_priority(report_priority, min_priority) is expected
+
+
+def test_summary_excerpt_uses_first_line_only() -> None:
+ assert _summary_excerpt("First line.\nSecond line should not appear.") == "First line."
+
+
+def test_summary_excerpt_truncates_first_line_at_600_chars() -> None:
+ long_line = "x" * 650
+ assert len(_summary_excerpt(long_line)) == 600
+ assert _summary_excerpt(long_line).endswith("...")
+
+
+def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> None:
+ report = SignalReport(
+ id="report-uuid",
+ title="Checkout errors spiked",
+ summary="Error rate rose after deploy.\nIgnored second line.",
+ signal_count=12,
+ )
+ recipient = _RecipientPresentation(header_label="<@U123>", plain_name="Marcus Twix")
+ blocks, text = _build_message_blocks(
+ report,
+ priority="P1",
+ source_products=["error_tracking"],
+ recipient=recipient,
+ )
+
+ assert blocks[0]["text"]["text"] == "Inbox for <@U123> · P1"
+ section_text = blocks[1]["text"]["text"]
+ assert "Suggested for" not in section_text
+ assert "*Checkout errors spiked*" in section_text
+ assert "Error rate rose after deploy." in section_text
+ assert "Ignored second line." not in section_text
+ context_text = blocks[2]["elements"][0]["text"]
+ assert "12 signals" in context_text
+ assert "Error tracking" in context_text
+ assert "Inbox" in context_text
+ button = blocks[3]["elements"][0]
+ assert button["text"]["text"] == "Open in PostHog Code"
+ assert button["url"] == "posthog-code-dev://inbox/report-uuid"
+ assert text == "Inbox for Marcus Twix (P1): Checkout errors spiked"
+
+
+def test_build_message_blocks_includes_github_pr_button_when_pr_url_provided() -> None:
+ report = SignalReport(
+ id="report-uuid",
+ title="Checkout errors spiked",
+ summary="Error rate rose after deploy.",
+ signal_count=12,
+ )
+ recipient = _RecipientPresentation(header_label="<@U123>", plain_name="Marcus Twix")
+ pr_url = "https://github.com/org/repo/pull/42"
+ blocks, _ = _build_message_blocks(
+ report,
+ priority="P1",
+ source_products=["error_tracking"],
+ recipient=recipient,
+ implementation_pr_url=pr_url,
+ )
+
+ buttons = blocks[3]["elements"]
+ assert len(buttons) == 2
+ assert buttons[0]["text"]["text"] == "Open in PostHog Code"
+ assert buttons[1]["text"]["text"] == "Review PR in GitHub"
+ assert buttons[1]["url"] == pr_url
+
+
+def test_build_message_blocks_omits_github_pr_button_without_pr_url() -> None:
+ report = SignalReport(id="report-uuid", title="No PR yet")
+ recipient = _RecipientPresentation(header_label="Marcus Twix", plain_name="Marcus Twix")
+ blocks, _ = _build_message_blocks(
+ report,
+ priority=None,
+ source_products=[],
+ recipient=recipient,
+ implementation_pr_url=None,
+ )
+
+ assert len(blocks[3]["elements"]) == 1
+
+
+def test_recipient_presentation_uses_slack_mention_when_lookup_succeeds() -> None:
+ user = User(first_name="Marcus", last_name="Twix", email="[email protected]")
+ slack = MagicMock()
+ integration = MagicMock()
+
+ with patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value="U_SLACK",
+ ):
+ presentation = _recipient_presentation(user, slack, integration)
+
+ assert presentation.header_label == "<@U_SLACK>"
+ assert presentation.plain_name == "Marcus Twix"
+
+
+def test_recipient_presentation_falls_back_to_name_when_slack_user_not_found() -> None:
+ user = User(first_name="Marcus", last_name="Twix", email="[email protected]")
+ slack = MagicMock()
+ integration = MagicMock()
+
+ with patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value=None,
+ ):
+ presentation = _recipient_presentation(user, slack, integration)
+
+ assert presentation.header_label == "Marcus Twix"
+
+
+def org_and_team():
+ org = Organization.objects.create(name="slack-notif-org")
+ team = Team.objects.create(organization=org, name="slack-notif-team")
+ yield org, team
+ team.delete()
+ org.delete()
+
+
+def _make_reviewer_user(org: Organization, email: str, login: str) -> User:
+ user = User.objects.create(email=email, first_name="Reviewer", last_name="Bot")
+ OrganizationMembership.objects.create(user=user, organization=org)
+ UserSocialAuth.objects.create(user=user, provider="github", uid=f"gh-{login}", extra_data={"login": login})
+ return user
+
+
+def _make_slack_integration(team: Team, created_by: User) -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id="T123",
+ config={"team": {"id": "T123"}, "authed_user": {"id": "U999"}},
+ sensitive_config={"access_token": "xoxb-test"},
+ created_by=created_by,
+ )
+
+
+def _make_ready_report(
+ team: Team,
+ *,
+ title: str = "Test report",
+ summary: str = "Summary text",
+ priority: str | None = None,
+ suggested_logins: list[str] | None = None,
+) -> SignalReport:
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title=title, summary=summary, signal_count=3, total_weight=1.0
+ )
+ if priority:
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content=json.dumps({"priority": priority}),
+ )
+ if suggested_logins:
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": login} for login in suggested_logins]),
+ )
+ return report
+
+
+def _create_implementation_task_with_run(
+ team: Team,
+ report: SignalReport,
+ *,
+ pr_url: str | None = None,
+) -> None:
+ task = Task.objects.create(
+ team=team,
+ title="Implementation task",
+ description="Fix the bug",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+ SignalReportTask.objects.create(
+ team=team,
+ report=report,
+ task=task,
+ relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ )
+ TaskRun.objects.create(
+ team=team,
+ task=task,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": pr_url},
+ )
+
+
+def test_dispatch_no_notification_when_user_has_no_slack_config(org_and_team):
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "review-bot")
+ SignalUserAutonomyConfig.objects.create(user=user) # no slack config
+ report = _make_ready_report(team, suggested_logins=["review-bot"])
+
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 0
+ assert slack_cls.call_count == 0
+
+
+def test_dispatch_sends_to_configured_reviewer(org_and_team):
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "another-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="C123|#inbox",
+ )
+ report = _make_ready_report(team, priority=AutonomyPriority.P1, suggested_logins=["another-bot"])
+
+ fake_client = MagicMock()
+ 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="U_REVIEWER",
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id, source_products=["error_tracking"])
+
+ assert sent == 1
+ assert fake_client.chat_postMessage.call_count == 1
+ call_kwargs = fake_client.chat_postMessage.call_args.kwargs
+ assert call_kwargs["channel"] == "C123"
+ assert "Inbox for Reviewer Bot (P1)" in call_kwargs["text"]
+ blocks = call_kwargs["blocks"]
+ assert blocks[0]["text"]["text"] == "Inbox for <@U_REVIEWER> · P1"
+ assert blocks[3]["elements"][0]["url"] == f"posthog-code-dev://inbox/{report.id}"
+
+
+def test_dispatch_includes_github_pr_button_when_implementation_task_has_pr(org_and_team):
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "pr-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="C123|#inbox",
+ )
+ report = _make_ready_report(team, suggested_logins=["pr-bot"])
+ _create_implementation_task_with_run(team, report, pr_url="https://github.com/org/repo/pull/99")
+
+ fake_client = MagicMock()
+ 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 = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ buttons = fake_client.chat_postMessage.call_args.kwargs["blocks"][3]["elements"]
+ assert len(buttons) == 2
+ assert buttons[1]["text"]["text"] == "Review PR in GitHub"
+ assert buttons[1]["url"] == "https://github.com/org/repo/pull/99"
+
+
+def test_dispatch_respects_min_priority_filter(org_and_team):
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "skip-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="C123|#inbox",
+ slack_notification_min_priority=AutonomyPriority.P1,
+ )
+ # P3 < P1 threshold so this should be filtered out
+ report = _make_ready_report(team, priority=AutonomyPriority.P3, suggested_logins=["skip-bot"])
+
+ fake_client = MagicMock()
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 0
+ assert fake_client.chat_postMessage.call_count == 0
+
+
+def test_dispatch_ignores_slack_config_from_another_team(org_and_team):
+ org, report_team = org_and_team
+ other_team = Team.objects.create(organization=org, name="other-slack-team")
+ user = _make_reviewer_user(org, "[email protected]", "other-team-bot")
+ integration = _make_slack_integration(other_team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="C123|#inbox",
+ )
+ report = _make_ready_report(report_team, suggested_logins=["other-team-bot"])
+
+ fake_client = MagicMock()
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), report_team.id)
+
+ assert sent == 0
+ assert fake_client.chat_postMessage.call_count == 0
+
+
+def test_dispatch_continues_after_per_user_failure(org_and_team):
+ org, team = org_and_team
+ user1 = _make_reviewer_user(org, "[email protected]", "alpha-login")
+ user2 = _make_reviewer_user(org, "[email protected]", "beta-login")
+ integration = _make_slack_integration(team, user1)
+ SignalUserAutonomyConfig.objects.create(
+ user=user1,
+ slack_notification_integration=integration,
+ slack_notification_channel="C1|#a",
+ )
+ SignalUserAutonomyConfig.objects.create(
+ user=user2,
+ slack_notification_integration=integration,
+ slack_notification_channel="C2|#b",
+ )
+ report = _make_ready_report(team, suggested_logins=["alpha-login", "beta-login"])
+
+ fake_client = MagicMock()
+ fake_client.chat_postMessage.side_effect = [Exception("slack down"), {"ok": True}]
+ 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 = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ assert fake_client.chat_postMessage.call_count == 2
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 69c6b1bd2b5b..65e418d2071b 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -43,12 +43,15 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import InternalAPIAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
-from posthog.models import Team
+from posthog.models import Team, User
+from posthog.models.integration import Integration
from posthog.permissions import APIScopePermission
from posthog.temporal.common.client import sync_connect
+from posthog.user_permissions import UserPermissions
from products.data_warehouse.backend.data_load.service import trigger_external_data_workflow
from products.signals.backend.api import emit_signal
+from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import (
InvalidStatusTransition,
SignalReport,
@@ -70,6 +73,7 @@ from products.signals.backend.serializers import (
SignalReportTaskSerializer,
SignalSourceConfigSerializer,
SignalTeamConfigSerializer,
+ SignalUserAutonomyConfigCreateSerializer,
SignalUserAutonomyConfigSerializer,
)
from products.signals.backend.temporal.backfill_error_tracking import (
@@ -567,30 +571,6 @@ class SignalReportViewSet(
)
return queryset.annotate(implementation_pr_url=latest_impl_pr_url)
- def _fetch_implementation_pr_urls_for_reports(self, report_ids: list[str]) -> dict[str, str]:
- if not report_ids:
- return {}
-
- # Batch this after pagination so the hot list queryset avoids a per-row correlated TaskRun subquery.
- latest_runs = (
- TaskRun.objects.filter(
- task__signal_report_tasks__report_id__in=report_ids,
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- output__pr_url__isnull=False,
- )
- .exclude(output__pr_url="")
- .order_by("task__signal_report_tasks__report_id", "-created_at", "-id")
- .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
- .values("task__signal_report_tasks__report_id", "output_pr_url_text")
- .distinct("task__signal_report_tasks__report_id")
- )
-
- return {
- str(row["task__signal_report_tasks__report_id"]): row["output_pr_url_text"]
- for row in latest_runs
- if row["task__signal_report_tasks__report_id"] and row["output_pr_url_text"]
- }
-
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
return self._apply_signal_report_ordering(queryset)
@@ -694,7 +674,7 @@ class SignalReportViewSet(
report_ids = [str(r.id) for r in reports]
source_products_map = fetch_source_products_for_reports(self.team, report_ids) if report_ids else {}
- implementation_pr_url_map = self._fetch_implementation_pr_urls_for_reports(report_ids)
+ implementation_pr_url_map = fetch_implementation_pr_urls_for_reports(report_ids)
context = {
**self.get_serializer_context(),
@@ -960,7 +940,6 @@ class SignalUserAutonomyConfigView(APIView):
return request.user
if not request.user.is_staff:
raise exceptions.PermissionDenied("Only staff can access other users' autonomy config.")
- from posthog.models import User
try:
return User.objects.get(pk=user_id)
@@ -977,14 +956,43 @@ class SignalUserAutonomyConfigView(APIView):
@extend_schema(responses={200: SignalUserAutonomyConfigSerializer})
def post(self, request, user_id, **kwargs):
- from products.signals.backend.serializers import SignalUserAutonomyConfigCreateSerializer
-
user = self._resolve_user(request, user_id)
serializer = SignalUserAutonomyConfigCreateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
+ validated = serializer.validated_data
+ # Partial update: only touch fields the client explicitly sent. This lets the
+ # auto-start setting and the Slack notification settings be edited
+ # independently from separate UI surfaces without one wiping the other.
+ defaults: dict = {}
+ if "autostart_priority" in serializer.initial_data:
+ defaults["autostart_priority"] = validated.get("autostart_priority")
+ if "slack_notification_min_priority" in serializer.initial_data:
+ defaults["slack_notification_min_priority"] = validated.get("slack_notification_min_priority")
+ if "slack_notification_channel" in serializer.initial_data:
+ defaults["slack_notification_channel"] = validated.get("slack_notification_channel") or None
+ if "slack_notification_integration_id" in serializer.initial_data:
+ integration_id = validated.get("slack_notification_integration_id")
+ integration = None
+ if integration_id is not None:
+ current_team_id = request.user.current_team_id
+ if current_team_id is None or current_team_id not in UserPermissions(user).team_ids_visible_for_user:
+ raise serializers.ValidationError(
+ {"slack_notification_integration_id": "Unknown Slack integration for this user."}
+ )
+ candidate = Integration.objects.filter(
+ pk=integration_id,
+ kind="slack",
+ team_id=current_team_id,
+ ).first()
+ if candidate is None:
+ raise serializers.ValidationError(
+ {"slack_notification_integration_id": "Unknown Slack integration for this user."}
+ )
+ integration = candidate
+ defaults["slack_notification_integration"] = integration
config, _created = SignalUserAutonomyConfig.objects.update_or_create(
user=user,
- defaults={"autostart_priority": serializer.validated_data.get("autostart_priority")},
+ defaults=defaults,
)
return Response(SignalUserAutonomyConfigSerializer(config).data)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 28c83e7f82f2..80dfc18c279f 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -201,9 +201,9 @@ export interface _UserApi {
* `P3` - P3
* `P4` - P4
*/
-export type AutostartPriorityEnumApi = (typeof AutostartPriorityEnumApi)[keyof typeof AutostartPriorityEnumApi]
+export type AutonomyPriorityEnumApi = (typeof AutonomyPriorityEnumApi)[keyof typeof AutonomyPriorityEnumApi]
-export const AutostartPriorityEnumApi = {
+export const AutonomyPriorityEnumApi = {
P0: 'P0',
P1: 'P1',
P2: 'P2',
@@ -220,7 +220,26 @@ export const BlankEnumApi = {
export interface SignalUserAutonomyConfigApi {
readonly id: string
readonly user: _UserApi
- autostart_priority?: AutostartPriorityEnumApi | BlankEnumApi | null
+ autostart_priority?: AutonomyPriorityEnumApi | BlankEnumApi | null
+ /**
+ * ID of the Slack Integration to deliver inbox-item notifications through, or null when notifications are disabled.
+ * @nullable
+ */
+ readonly slack_notification_integration_id: number | null
+ /**
+ * Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.
+ * @maxLength 255
+ * @nullable
+ */
+ slack_notification_channel?: string | null
+ /** Minimum report priority that triggers a Slack notification. P0 is highest. Null means notify on every priority (and reports without a priority judgment).
+
+ * `P0` - P0
+ * `P1` - P1
+ * `P2` - P2
+ * `P3` - P3
+ * `P4` - P4 */
+ slack_notification_min_priority?: AutonomyPriorityEnumApi | BlankEnumApi | null
readonly created_at: string
readonly updated_at: string
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 63b5ddfeba18..a7a1e3cbbc3a 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -123,6 +123,8 @@ GET /api/users/<id>/signal_autonomy/ → current config (or 404)
POST /api/users/<id>/signal_autonomy/ → create or update
DELETE /api/users/<id>/signal_autonomy/ → remove (opt out)
*/
+export const usersSignalAutonomyCreateBodySlackNotificationChannelMax = 255
+
export const UsersSignalAutonomyCreateBody = /* @__PURE__ */ zod.object({
autostart_priority: zod
.union([
@@ -133,4 +135,23 @@ export const UsersSignalAutonomyCreateBody = /* @__PURE__ */ zod.object({
zod.null(),
])
.optional(),
+ slack_notification_channel: zod
+ .string()
+ .max(usersSignalAutonomyCreateBodySlackNotificationChannelMax)
+ .nullish()
+ .describe(
+ 'Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.'
+ ),
+ slack_notification_min_priority: zod
+ .union([
+ zod
+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])
+ .describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Minimum report priority that triggers a Slack notification. P0 is highest. Null means notify on every priority (and reports without a priority judgment).\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'
+ ),
})
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 6e8a04d8213a..26fb6b381280 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -18,6 +18,7 @@ from django.views.decorators.csrf import csrf_exempt
import requests
import structlog
import posthoganalytics
+from slack_sdk.errors import SlackApiError
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from posthog.llm.gateway_client import get_llm_client
@@ -135,6 +136,10 @@ def _slack_user_info_cache_key(integration_id: int, slack_user_id: str) -> str:
return f"posthog_code_slack_user_info:{integration_id}:{slack_user_id}"
+def _slack_user_id_by_email_cache_key(integration_id: int, normalized_email: str) -> str:
+ return f"posthog_code_slack_user_id_by_email:{integration_id}:{normalized_email}"
+
+
def _format_slack_user_info_payload(*, email: str | None, display_name: str, real_name: str) -> dict[str, Any]:
return {
"user": {
@@ -215,6 +220,78 @@ def _get_slack_user_info(slack: SlackIntegration, integration: Integration, slac
return {}
+def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:
+ from products.slack_app.backend.models import SlackUserProfileCache
+
+ try:
+ profile = SlackUserProfileCache.objects.filter(
+ integration_id=integration.id,
+ email__iexact=normalized_email,
+ ).first()
+ except DatabaseError:
+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)
+ return None
+ return profile.slack_user_id if profile else None
+
+
+def lookup_slack_user_id_by_email(
+ slack: SlackIntegration,
+ integration: Integration,
+ email: str,
+) -> str | None:
+ """Resolve a Slack user ID from a PostHog user email.
+
+ Uses ``SlackUserProfileCache`` (populated by ``resolve_slack_user`` and prior lookups),
+ then ``users.lookupByEmail``. Results are cached per integration + email.
+ """
+ normalized_email = email.strip().lower()
+ if not normalized_email:
+ return None
+
+ cache_key = _slack_user_id_by_email_cache_key(integration.id, normalized_email)
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached or None
+
+ slack_user_id = _get_slack_user_id_by_email_from_db(integration, normalized_email)
+ if slack_user_id:
+ cache.set(cache_key, slack_user_id, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)
+ return slack_user_id
+
+ try:
+ user_info = _normalize_slack_response(slack.client.users_lookupByEmail(email=email))
+ except SlackApiError as exc:
+ error_code = exc.response.get("error") if exc.response else None
+ if error_code != "users_not_found":
+ logger.warning(
+ "slack_user_id_by_email_lookup_failed",
+ integration_id=integration.id,
+ email=email,
+ error=error_code,
+ )
+ cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)
+ return None
+
+ if not user_info.get("ok"):
+ cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)
+ return None
+
+ user = user_info.get("user")
+ if not isinstance(user, dict) or not user.get("id"):
+ cache.set(cache_key, "", timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)
+ return None
+
+ slack_user_id = str(user["id"])
+ _persist_slack_user_info(integration, slack_user_id, user_info)
+ cache.set(
+ _slack_user_info_cache_key(integration.id, slack_user_id),
+ user_info,
+ timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS,
+ )
+ cache.set(cache_key, slack_user_id, timeout=SLACK_USER_INFO_CACHE_TTL_SECONDS)
+ return slack_user_id
+
+
def _post_slack_user_feedback(
slack: SlackIntegration,
channel: str,
diff --git a/products/slack_app/backend/tests/test_resolve_slack_user.py b/products/slack_app/backend/tests/test_resolve_slack_user.py
index e726c3611926..5e6ffaeb69fd 100644
--- a/products/slack_app/backend/tests/test_resolve_slack_user.py
+++ b/products/slack_app/backend/tests/test_resolve_slack_user.py
@@ -8,7 +8,7 @@ from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.slack_app.backend.api import resolve_slack_user
+from products.slack_app.backend.api import lookup_slack_user_id_by_email, resolve_slack_user
from products.slack_app.backend.models import SlackUserProfileCache
@@ -129,3 +129,53 @@ class TestResolveSlackUser:
assert profile.email == "[email protected]"
assert profile.display_name == "Dev"
assert profile.real_name == "Developer"
+
+
+class TestLookupSlackUserIdByEmail:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ cache.clear()
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack-posthog-code",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ @patch("posthog.models.integration.WebClient")
+ def test_uses_db_cached_profile(self, mock_webclient_class):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id="U123",
+ )
+
+ slack = SlackIntegration(self.integration)
+ slack_user_id = lookup_slack_user_id_by_email(slack, self.integration, "[email protected]")
+
+ assert slack_user_id == "U123"
+ mock_client.users_lookupByEmail.assert_not_called()
+
+ @patch("posthog.models.integration.WebClient")
+ def test_lookup_by_email_api(self, mock_webclient_class):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_lookupByEmail.return_value = {
+ "ok": True,
+ "user": {
+ "id": "U456",
+ "profile": {"email": "[email protected]", "display_name": "New", "real_name": "User"},
+ },
+ }
+
+ slack = SlackIntegration(self.integration)
+ slack_user_id = lookup_slack_user_id_by_email(slack, self.integration, "[email protected]")
+
+ assert slack_user_id == "U456"
+ profile = SlackUserProfileCache.objects.get(integration=self.integration, slack_user_id="U456")
+ assert profile.email == "[email protected]"
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 04342a2e2443..1050aa66fd50 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4475,10 +4475,10 @@ export namespace Schemas {
* `P3` - P3
* `P4` - P4
*/
- export type AutostartPriorityEnum = typeof AutostartPriorityEnum[keyof typeof AutostartPriorityEnum];
+ export type AutonomyPriorityEnum = typeof AutonomyPriorityEnum[keyof typeof AutonomyPriorityEnum];
- export const AutostartPriorityEnum = {
+ export const AutonomyPriorityEnum = {
P0: 'P0',
P1: 'P1',
P2: 'P2',
@@ -35143,7 +35143,26 @@ export namespace Schemas {
export interface SignalUserAutonomyConfig {
readonly id: string;
readonly user: _User;
- autostart_priority?: AutostartPriorityEnum | BlankEnum | null;
+ autostart_priority?: AutonomyPriorityEnum | BlankEnum | null;
+ /**
+ * ID of the Slack Integration to deliver inbox-item notifications through, or null when notifications are disabled.
+ * @nullable
+ */
+ readonly slack_notification_integration_id: number | null;
+ /**
+ * Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.
+ * @maxLength 255
+ * @nullable
+ */
+ slack_notification_channel?: string | null;
+ /** Minimum report priority that triggers a Slack notification. P0 is highest. Null means notify on every priority (and reports without a priority judgment).
+
+ * `P0` - P0
+ * `P1` - P1
+ * `P2` - P2
+ * `P3` - P3
+ * `P4` - P4 */
+ slack_notification_min_priority?: AutonomyPriorityEnum | BlankEnum | null;
readonly created_at: string;
readonly updated_at: string;
}
@@ -35171,6 +35190,8 @@ export namespace Schemas {
* @nullable
*/
lastRefreshedAt?: string | null;
+ /** Whether more channels match the current search beyond this page. */
+ has_more?: boolean;
}
/**
@@ -39389,6 +39410,24 @@ export namespace Schemas {
Vercel: 'vercel',
} as const;
+ export type EnvironmentsIntegrationsChannelsRetrieveParams = {
+ /**
+ * Maximum number of channels to return per request (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number;
+ /**
+ * Number of channels to skip before returning results.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Optional case-insensitive channel name or ID search query.
+ */
+ search?: string;
+ };
+
export type EnvironmentsIntegrationsGithubBranchesRetrieveParams = {
/**
* Maximum number of branches to return
@@ -44642,6 +44681,24 @@ export namespace Schemas {
Vercel: 'vercel',
} as const;
+ export type IntegrationsChannelsRetrieveParams = {
+ /**
+ * Maximum number of channels to return per request (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number;
+ /**
+ * Number of channels to skip before returning results.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Optional case-insensitive channel name or ID search query.
+ */
+ search?: string;
+ };
+
export type IntegrationsGithubBranchesRetrieveParams = {
/**
* Maximum number of branches to return
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index 63ed1595778d..e60543612ddd 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -89,3 +89,29 @@ export const IntegrationsChannelsRetrieveParams = /* @__PURE__ */ zod.object({
"Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
),
})
+
+export const integrationsChannelsRetrieveQueryLimitDefault = 50
+export const integrationsChannelsRetrieveQueryLimitMax = 200
+
+export const integrationsChannelsRetrieveQueryOffsetDefault = 0
+export const integrationsChannelsRetrieveQueryOffsetMin = 0
+
+export const integrationsChannelsRetrieveQuerySearchDefault = ``
+
+export const IntegrationsChannelsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod
+ .number()
+ .min(1)
+ .max(integrationsChannelsRetrieveQueryLimitMax)
+ .default(integrationsChannelsRetrieveQueryLimitDefault)
+ .describe('Maximum number of channels to return per request (max 200).'),
+ offset: zod
+ .number()
+ .min(integrationsChannelsRetrieveQueryOffsetMin)
+ .default(integrationsChannelsRetrieveQueryOffsetDefault)
+ .describe('Number of channels to skip before returning results.'),
+ search: zod
+ .string()
+ .default(integrationsChannelsRetrieveQuerySearchDefault)
+ .describe('Optional case-insensitive channel name or ID search query.'),
+})
diff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.ts
index 0ace0730ea5e..1299cec9dfe0 100644
--- a/services/mcp/src/tools/generated/integrations.ts
+++ b/services/mcp/src/tools/generated/integrations.ts
@@ -4,6 +4,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
IntegrationsChannelsRetrieveParams,
+ IntegrationsChannelsRetrieveQueryParams,
IntegrationsDestroyParams,
IntegrationsListQueryParams,
IntegrationsRetrieveParams,
@@ -49,7 +50,9 @@ const integrationGet = (): ToolBase<typeof IntegrationGetSchema, Schemas.Integra
},
})
-const IntegrationsChannelsRetrieveSchema = IntegrationsChannelsRetrieveParams.omit({ project_id: true })
+const IntegrationsChannelsRetrieveSchema = IntegrationsChannelsRetrieveParams.omit({ project_id: true }).extend(
+ IntegrationsChannelsRetrieveQueryParams.shape
+)
const integrationsChannelsRetrieve = (): ToolBase<
typeof IntegrationsChannelsRetrieveSchema,
@@ -62,6 +65,11 @@ const integrationsChannelsRetrieve = (): ToolBase<
const result = await context.api.request<Schemas.SlackChannelsResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/channels/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ search: params.search,
+ },
})
return result
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/integrations-channels-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/integrations-channels-retrieve.json
index 34da2ca90cc2..66c741cfea69 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/integrations-channels-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/integrations-channels-retrieve.json
@@ -4,6 +4,24 @@
"id": {
"description": "A unique integer value identifying this integration.",
"type": "number"
+ },
+ "limit": {
+ "default": 50,
+ "description": "Maximum number of channels to return per request (max 200).",
+ "maximum": 200,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "default": 0,
+ "description": "Number of channels to skip before returning results.",
+ "minimum": 0,
+ "type": "number"
+ },
+ "search": {
+ "default": "",
+ "description": "Optional case-insensitive channel name or ID search query.",
+ "type": "string"
}
},
"required": ["id"],