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): log inbox PR-generation setting changes (#84657)

Andrew Maguirec218261e34a1
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index b374d42aa78a..7ac5d5de86ee 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6113,6 +6113,7 @@ export enum ActivityScope {
TICKET = 'Ticket',
INSTANCE_SETTING = 'InstanceSetting',
SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
+ SIGNAL_TEAM_CONFIG = 'SignalTeamConfig',
}
export type CommentType = {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 054ad9e15e37..5f45d2d682ee 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -99,6 +99,7 @@ ActivityScope = Literal[
"InstanceSetting",
"SignalReport",
"SignalScoutConfig",
+ "SignalTeamConfig",
"StreamlitApp",
"Metric",
"TableCertification",
@@ -357,6 +358,13 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
"pause_reason": "pause reason",
"auto_pause_exempt": "never pause for inactivity",
},
+ # Match the labels the inbox settings show, so an entry reads the way the setting was flipped.
+ "SignalTeamConfig": {
+ "autostart_enabled": "PR generation",
+ "default_autostart_priority": "project PR threshold",
+ "default_slack_notification_channel": "team Slack channel",
+ "autostart_base_branches": "base branch overrides",
+ },
"OAuthApplication": {
"_provisioning_config": "provisioning config",
},
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index a96d91a67105..c433cd5dcadb 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -42,6 +42,7 @@ model_activity:products.logs.backend.activity_logging.handle_logs_retention_rule
model_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_activity
model_activity:products.managed_migrations.backend.activity_logging.handle_batch_import_change
model_activity:products.signals.backend.activity_logging.handle_signal_scout_config_change
+model_activity:products.signals.backend.activity_logging.handle_signal_team_config_change
model_activity:products.tasks.backend.activity_logging.handle_loop_change
model_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_schema_change
model_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_source_change
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index a7689f7fc71c..a15a2d538125 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1173,6 +1173,7 @@ export type ActivityLogListParams = {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `SignalTeamConfig` - SignalTeamConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
@@ -1268,6 +1269,7 @@ export const ActivityLogListScope = {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ SignalTeamConfig: 'SignalTeamConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
@@ -1350,6 +1352,7 @@ export const ActivityLogListScope = {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `SignalTeamConfig` - SignalTeamConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
@@ -1433,6 +1436,7 @@ export const ActivityLogListScopesItem = {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ SignalTeamConfig: 'SignalTeamConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
diff --git a/products/signals/backend/activity_logging.py b/products/signals/backend/activity_logging.py
index 4a6868896852..a3a43c39ef2f 100644
--- a/products/signals/backend/activity_logging.py
+++ b/products/signals/backend/activity_logging.py
@@ -1,9 +1,9 @@
-"""Activity-log hook for SignalScoutConfig create/update/delete.
+"""Activity-log hooks for SignalScoutConfig and SignalTeamConfig changes.
`ModelActivityMixin.save()` only *emits* `model_activity_signal` — it does not persist
-anything. This receiver is the consumer that turns the emitted signal into a stored
-`ActivityLog` row. Without it, nothing about SignalScoutConfig would ever appear in the
-activity log. Imported from `SignalsConfig.ready()` so it registers at startup.
+anything. These receivers are the consumers that turn the emitted signal into a stored
+`ActivityLog` row. Without them, nothing about either model would ever appear in the
+activity log. Imported from `SignalsConfig.ready()` so they register at startup.
"""
import dataclasses
@@ -22,7 +22,7 @@ from posthog.models.activity_logging.model_activity import get_current_trigger
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
-from .models import SignalScoutConfig
+from .models import SignalScoutConfig, SignalTeamConfig
logger = structlog.get_logger(__name__)
@@ -64,3 +64,47 @@ def handle_signal_scout_config_change(
context=SignalScoutConfigContext(skill_name=instance.skill_name),
),
)
+
+
+@mutable_receiver(model_activity_signal, sender=SignalTeamConfig)
+def handle_signal_team_config_change(
+ sender: type[SignalTeamConfig],
+ scope: ActivityScope,
+ before_update: SignalTeamConfig | None,
+ after_update: SignalTeamConfig | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance: SignalTeamConfig | None = after_update or before_update
+ if instance is None:
+ return
+
+ # On create, diff against a fresh default row rather than None. `changes_between` yields
+ # nothing when `previous` is None, which would drop the create branch of update_or_create() —
+ # the path Slack onboarding takes to set a channel on a team whose row was never materialized.
+ # Diffing against defaults keeps an all-default create (team creation, lazy read) silent while
+ # still auditing a create that carries a non-default value.
+ previous = before_update if before_update is not None else SignalTeamConfig()
+ changes = changes_between(scope, previous=previous, current=after_update)
+ # Only persist saves that moved a field, which also keeps idempotent re-saves out of the log.
+ if not changes:
+ return
+
+ log_activity(
+ organization_id=None,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ changes=changes,
+ # Singleton per team, so there's no per-row name to show; label it where a reader
+ # would go to find the setting instead of exposing the model name.
+ name="Inbox settings",
+ trigger=get_current_trigger(),
+ ),
+ )
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.py
index a63ce20dd96d..2a56ea96690c 100644
--- a/products/signals/backend/apps.py
+++ b/products/signals/backend/apps.py
@@ -7,8 +7,9 @@ class SignalsConfig(AppConfig):
label = "signals"
def ready(self) -> None:
- # activity_logging: consumes model_activity_signal to persist SignalScoutConfig audit-log
- # entries (ModelActivityMixin only emits the signal; this is the consumer).
+ # activity_logging: consumes model_activity_signal to persist SignalScoutConfig and
+ # SignalTeamConfig audit-log entries (ModelActivityMixin only emits the signal; this
+ # is the consumer).
# receivers: post_save receiver that closes a report's implementation PR on suppression/snooze.
from . import (
activity_logging, # noqa: F401
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index e546feb79403..5d62ab78b834 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -125,7 +125,7 @@ class AutonomyPriority(models.TextChoices):
P4 = "P4", "P4"
-class SignalTeamConfig(UUIDModel):
+class SignalTeamConfig(ModelActivityMixin, UUIDModel):
team = models.OneToOneField(
"posthog.Team",
on_delete=models.CASCADE,
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 3a362dc86e6b..04dc70b9017b 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -173,6 +173,12 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
return super().create(validated_data)
+# A team overrides the base branch for a handful of its repos; a map larger than this is abuse,
+# not use. Bounding it caps the per-write activity-log row (which stores the full before/after map)
+# and the request body a caller can push through this field.
+MAX_AUTOSTART_BASE_BRANCH_ENTRIES = 500
+
+
class SignalTeamConfigSerializer(serializers.ModelSerializer):
autostart_base_branches = serializers.DictField(
child=serializers.CharField(max_length=255, allow_blank=True),
@@ -264,9 +270,18 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
}
def validate_autostart_base_branches(self, value: dict) -> dict:
+ if len(value) > MAX_AUTOSTART_BASE_BRANCH_ENTRIES:
+ raise serializers.ValidationError(
+ f"Too many repository overrides ({len(value)}); the maximum is {MAX_AUTOSTART_BASE_BRANCH_ENTRIES}."
+ )
cleaned: dict[str, str] = {}
for repo, branch in value.items():
repo_key = (repo or "").strip()
+ # Bound the key too — the DictField child only caps the branch value, so an
+ # oversized key would otherwise slip a large string into the stored map and its
+ # activity-log copy.
+ if len(repo_key) > 255:
+ raise serializers.ValidationError("Repository keys must be at most 255 characters.")
if repo_key.count("/") != 1 or any(not part for part in repo_key.split("/")):
raise serializers.ValidationError(
f"Repository keys must be in 'organization/repository' form, got '{repo}'."
diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.py
index c69972e308de..ba9b81810cb3 100644
--- a/products/signals/backend/test/test_signal_team_config_api.py
+++ b/products/signals/backend/test/test_signal_team_config_api.py
@@ -2,10 +2,16 @@ from datetime import UTC, datetime
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from rest_framework import status
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.signals.backend.facade.api import set_default_slack_notification_channel
from products.signals.backend.models import SignalReport, SignalTeamConfig
+from products.signals.backend.serializers import MAX_AUTOSTART_BASE_BRANCH_ENTRIES, SignalTeamConfigSerializer
class TestSignalTeamConfigAPI(APIBaseTest):
@@ -17,6 +23,9 @@ class TestSignalTeamConfigAPI(APIBaseTest):
def _url(self) -> str:
return f"/api/projects/{self.team.id}/signals/config/"
+ def _activity(self) -> list[ActivityLog]:
+ return list(ActivityLog.objects.filter(team_id=self.team.pk, scope="SignalTeamConfig").order_by("created_at"))
+
def test_get_config_includes_default_slack_notification_channel(self):
response = self.client.get(self._url())
data = response.json()
@@ -210,3 +219,100 @@ class TestSignalTeamConfigAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.json()
self.config.refresh_from_db()
assert self.config.autostart_enabled is False
+
+ # Each case starts from the model default, so the POST is the only change on the row.
+ @parameterized.expand(
+ [
+ ("threshold", "default_autostart_priority", "P1", "project PR threshold", "changed", "P4", "P1"),
+ ("pr_generation", "autostart_enabled", False, "PR generation", "created", None, False),
+ (
+ "slack_channel",
+ "default_slack_notification_channel",
+ "C123|#posthog-signals",
+ "team Slack channel",
+ "created",
+ None,
+ "C123|#posthog-signals",
+ ),
+ (
+ "base_branches",
+ "autostart_base_branches",
+ {"acme/web": "staging"},
+ "base branch overrides",
+ "created",
+ None,
+ {"acme/web": "staging"},
+ ),
+ ]
+ )
+ def test_update_is_recorded_in_the_activity_log(self, _name, field, sent, label, action, before, after):
+ response = self.client.post(self._url(), data={field: sent}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ entries = self._activity()
+ assert len(entries) == 1
+ entry = entries[0]
+ assert entry.activity == "updated"
+ assert entry.item_id == str(self.config.id)
+ assert entry.user == self.user
+ assert entry.detail is not None
+ assert entry.detail["changes"] == [
+ {"type": "SignalTeamConfig", "action": action, "field": label, "before": before, "after": after}
+ ]
+
+ def test_reading_config_does_not_record_activity(self):
+ # The viewset materializes a missing row on read. That is bookkeeping, so it must not
+ # show up as whoever opened the settings having changed something.
+ self.config.delete()
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert SignalTeamConfig.objects.filter(team=self.team).exists()
+ assert self._activity() == []
+
+ def test_create_carrying_a_nondefault_value_is_recorded_in_the_activity_log(self):
+ # Slack onboarding sets a channel via update_or_create for teams whose row was never
+ # 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")
+
+ entries = self._activity()
+ assert len(entries) == 1
+ assert entries[0].detail is not None
+ assert entries[0].detail["changes"] == [
+ {
+ "type": "SignalTeamConfig",
+ "action": "created",
+ "field": "team Slack channel",
+ "before": None,
+ "after": "C123|#posthog-signals",
+ }
+ ]
+
+ def test_resending_the_same_values_does_not_record_activity(self):
+ self.client.post(self._url(), data={"default_autostart_priority": "P1"}, format="json")
+ assert len(self._activity()) == 1
+
+ response = self.client.post(self._url(), data={"default_autostart_priority": "P1"}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert len(self._activity()) == 1
+
+
+class TestSignalTeamConfigSerializerValidation(SimpleTestCase):
+ # No DB needed: these are field-level rejections that short-circuit in to_internal_value.
+ # The endpoint wiring guard lives in TestSignalTeamConfigAPI.
+ @parameterized.expand(
+ [
+ (
+ "too_many_entries",
+ {f"acme/repo{i}": "staging" for i in range(MAX_AUTOSTART_BASE_BRANCH_ENTRIES + 1)},
+ ),
+ ("oversized_repo_key", {"acme/" + "r" * 300: "staging"}),
+ ]
+ )
+ def test_autostart_base_branches_rejects_oversized_input(self, _name, value):
+ # Both cap the stored map and its full-copy activity-log row; without the bound a caller
+ # with write access could append arbitrarily large rows by re-saving a huge map.
+ serializer = SignalTeamConfigSerializer(data={"autostart_base_branches": value}, partial=True)
+ assert not serializer.is_valid()
+ assert "autostart_base_branches" in serializer.errors
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8282af6d4f2a..129bd196b009 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -85078,6 +85078,7 @@ export namespace Schemas {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `SignalTeamConfig` - SignalTeamConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
@@ -85174,6 +85175,7 @@ export namespace Schemas {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ SignalTeamConfig: 'SignalTeamConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
@@ -85256,6 +85258,7 @@ export namespace Schemas {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `SignalTeamConfig` - SignalTeamConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
@@ -85340,6 +85343,7 @@ export namespace Schemas {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ SignalTeamConfig: 'SignalTeamConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',