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.

fix(signals): update source config keys atomically (#125653)

Mikayla Thompsond191cccfce19
diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
index ae7de89f3ebf..4afab2c44626 100644
--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
@@ -31,6 +31,7 @@ jest.mock('products/alerts/frontend/generated/api', () => ({
jest.mock('lib/utils/newInternalTab')
jest.mock('products/signals/frontend/generated/api', () => ({
+ ...jest.requireActual('products/signals/frontend/generated/api'),
signalsScoutConfigList: jest.fn(() => new Promise(() => {})),
signalsScoutMetadataGet: jest.fn(() => new Promise(() => {})),
}))
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index c600b1278c5c..96998a534e79 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -225,6 +225,17 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
),
)
config = _SourceConfigField(required=False, help_text=_SOURCE_CONFIG_HELP_TEXT)
+ config_set = _SourceConfigField(
+ required=False,
+ write_only=True,
+ help_text="Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.",
+ )
+ config_remove = serializers.ListField(
+ child=serializers.CharField(trim_whitespace=False, allow_blank=False),
+ required=False,
+ write_only=True,
+ help_text="Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.",
+ )
class Meta:
model = SignalSourceConfig
@@ -234,6 +245,8 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
"source_type",
"enabled",
"config",
+ "config_set",
+ "config_remove",
"created_at",
"updated_at",
"status",
@@ -289,6 +302,21 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
source_product = attrs.get("source_product", getattr(self.instance, "source_product", None))
source_type = attrs.get("source_type", getattr(self.instance, "source_type", None))
enabled = attrs.get("enabled", getattr(self.instance, "enabled", False))
+ if "config_set" in attrs or "config_remove" in attrs:
+ if self.instance is None:
+ raise serializers.ValidationError("config_set and config_remove are only supported on update.")
+ if "config" in attrs:
+ raise serializers.ValidationError("Use either config or config_set/config_remove.")
+ config_set = attrs.pop("config_set", {})
+ config_remove = attrs.pop("config_remove", [])
+ if not isinstance(config_set, dict):
+ raise serializers.ValidationError({"config_set": "config_set must be a JSON object"})
+ if set(config_set).intersection(config_remove):
+ raise serializers.ValidationError("A config key cannot be both set and removed.")
+ merged_config = {**self.instance.config, **config_set}
+ for key in config_remove:
+ merged_config.pop(key, None)
+ attrs["config"] = merged_config
config = attrs.get("config")
# `is not None` rather than truthiness: falsy non-dict values ([], "", 0, false) must be
# rejected, not silently persisted.
diff --git a/products/signals/backend/test/test_signal_source_config_api.py b/products/signals/backend/test/test_signal_source_config_api.py
index bed4e3a74e97..02938d13e7ff 100644
--- a/products/signals/backend/test/test_signal_source_config_api.py
+++ b/products/signals/backend/test/test_signal_source_config_api.py
@@ -1,16 +1,28 @@
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
+from typing import TYPE_CHECKING
+
+import pytest
from posthog.test.base import APIBaseTest
+from django.db import connection, connections
from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
+from rest_framework.test import APIClient
+from posthog.models import Organization, User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.signals.backend.models import SignalSourceConfig
from products.signals.backend.serializers import SignalSourceConfigSerializer
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
class TestSignalSourceConfigAPI(APIBaseTest):
@@ -287,7 +299,8 @@ class TestSignalSourceConfigAPI(APIBaseTest):
response = self.client.get(self._url(str(config.id)))
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_update_other_teams_config_forbidden(self):
+ @parameterized.expand([({"enabled": False},), ({"config_set": {"steering": "Example"}},)])
+ def test_update_other_teams_config_forbidden(self, body: dict[str, object]) -> None:
other_team = Team.objects.create(organization=self.organization, name="Other Team")
config = SignalSourceConfig.objects.create(
team=other_team,
@@ -297,7 +310,7 @@ class TestSignalSourceConfigAPI(APIBaseTest):
)
response = self.client.patch(
self._url(str(config.id)),
- data={"enabled": False},
+ data=body,
format="json",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
@@ -327,7 +340,7 @@ class TestSignalSourceConfigAPI(APIBaseTest):
team=self.team,
source_product="session_replay",
source_type="session_analysis_cluster",
- config={},
+ config={"steering": "Original guidance", "hogql_filter": "false"},
created_by=self.user,
)
response = self.client.patch(
@@ -338,6 +351,87 @@ class TestSignalSourceConfigAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["config"] == {"recording_filters": {"duration_min": 30}}
+ def test_config_key_updates_preserve_unrelated_settings(self) -> None:
+ config = SignalSourceConfig.objects.create(
+ team=self.team,
+ source_product="linear",
+ source_type="issue",
+ config={"hogql_filter": "false", "default_not_actionable": True, "nested": {"keep": True}},
+ )
+ response = self.client.patch(
+ self._url(str(config.id)),
+ {
+ "config_set": {"steering": "Prioritize documentation tasks"},
+ "config_remove": ["default_not_actionable", "missing"],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ response = self.client.patch(
+ self._url(str(config.id)),
+ {"config_set": {"linear_team_ids": [" team-example "], "nested": {"replace": True}, "nullable": None}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ config.refresh_from_db()
+ assert config.config == {
+ "hogql_filter": "false",
+ "nested": {"replace": True},
+ "nullable": None,
+ "steering": "Prioritize documentation tasks",
+ "linear_team_ids": ["team-example"],
+ }
+ assert response.json()["config"] == config.config
+ assert "config_set" not in response.json()
+ assert "config_remove" not in response.json()
+
+ def test_invalid_merged_config_does_not_write_other_fields(self) -> None:
+ config = SignalSourceConfig.objects.create(
+ team=self.team,
+ source_product="linear",
+ source_type="issue",
+ enabled=False,
+ config={"linear_team_ids": "invalid", "default_not_actionable": True},
+ )
+ updated_at = config.updated_at
+ response = self.client.patch(
+ self._url(str(config.id)),
+ {
+ "enabled": True,
+ "config_set": {"steering": "Review API documentation"},
+ "config_remove": ["default_not_actionable"],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ config.refresh_from_db()
+ assert config.enabled is False
+ assert config.config == {"linear_team_ids": "invalid", "default_not_actionable": True}
+ assert config.updated_at == updated_at
+ response = self.client.patch(self._url(str(config.id)), {"config_remove": ["linear_team_ids"]}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["config"] == {"default_not_actionable": True}
+
+ def test_config_keys_require_write_scope(self) -> None:
+ config = SignalSourceConfig.objects.create(team=self.team, source_product="linear", source_type="issue")
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["task:read"],
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ response = self.client.patch(
+ self._url(str(config.id)),
+ {"config_set": {"steering": "Review API documentation"}},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {raw}",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ config.refresh_from_db()
+ assert config.config == {}
+
def test_update_config_recording_filters_not_dict_rejected(self):
config = SignalSourceConfig.objects.create(
team=self.team,
@@ -417,6 +511,30 @@ class TestSignalSourceConfigAPI(APIBaseTest):
class TestSignalSourceConfigSerializerValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ({"config_set": []},),
+ ({"config_set": None},),
+ ({"config_remove": "steering"},),
+ ({"config_set": {"steering": "new"}, "config_remove": ["steering"]},),
+ ({"config": {}, "config_set": {}},),
+ ({"config": {}, "config_remove": []},),
+ ({"config_set": {"steering": None}},),
+ ({"config_set": {"linear_team_ids": "invalid"}},),
+ ]
+ )
+ def test_invalid_config_key_updates(self, data: dict[str, object]) -> None:
+ instance = SignalSourceConfig(source_product="linear", source_type="issue", config={"steering": "original"})
+ serializer = SignalSourceConfigSerializer(instance, data=data, partial=True)
+ assert not serializer.is_valid()
+ assert instance.config == {"steering": "original"}
+
+ def test_config_key_updates_are_rejected_on_create(self) -> None:
+ serializer = SignalSourceConfigSerializer(
+ data={"source_product": "linear", "source_type": "issue", "config_set": {}}
+ )
+ assert not serializer.is_valid()
+
@parameterized.expand(
[
("valid", {"linear_team_ids": ["team-1", "team-2"]}, True),
@@ -655,3 +773,60 @@ class TestIsSourceEnabledGating(APIBaseTest):
)
assert SignalSourceConfig.is_source_enabled(self.team.id, "signals_scout", "cross_source_issue") is expected
+
+
[email protected]_db(transaction=True)
[email protected]("status_lookup_fails", [False, True])
+def test_concurrent_config_key_updates_preserve_both_edits(status_lookup_fails: bool) -> None:
+ organization = Organization.objects.create(name="Config concurrency test")
+ team = Team.objects.create(organization=organization)
+ user = User.objects.create(email="[email protected]")
+ organization.members.add(user)
+ config = SignalSourceConfig.objects.create(
+ team=team,
+ source_product="linear",
+ source_type="issue",
+ enabled=False,
+ config={"hogql_filter": "false", "default_not_actionable": True},
+ )
+ barrier = Barrier(2)
+
+ def update_config(body: dict[str, object]) -> int:
+ failed_status_reads: list[str] = []
+
+ def fail_status_read(
+ execute: Callable[..., object], sql: str, params: object, many: bool, context: dict[str, object]
+ ) -> object:
+ if status_lookup_fails and ExternalDataSchema._meta.db_table in sql:
+ failed_status_reads.append(sql)
+ return execute("SELECT 1 / 0", None, many, context)
+ return execute(sql, params, many, context)
+
+ try:
+ client = APIClient()
+ client.force_authenticate(user)
+ barrier.wait(timeout=10)
+ with connection.execute_wrapper(fail_status_read):
+ response = client.patch(
+ f"/api/projects/{team.id}/signals/source_configs/{config.id}/", body, format="json"
+ )
+ assert bool(failed_status_reads) is status_lookup_fails
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.status_code
+ finally:
+ connections.close_all()
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ updates: list[dict[str, object]] = [
+ {"config_set": {"steering": "Prioritize documentation tasks"}, "config_remove": ["default_not_actionable"]},
+ {"config_set": {"linear_team_ids": ["team-example"]}},
+ ]
+ futures = [pool.submit(update_config, body) for body in updates]
+ for future in futures:
+ future.result(timeout=20)
+ config.refresh_from_db()
+ assert config.config == {
+ "hogql_filter": "false",
+ "steering": "Prioritize documentation tasks",
+ "linear_team_ids": ["team-example"],
+ }
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 159669663034..8023ea0611ea 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -597,6 +597,19 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
except Exception:
logger.exception(f"Failed to start error tracking backfill workflow for team {self.team_id}")
+ def update(self, request: Request, *args: object, **kwargs: object) -> Response:
+ partial = kwargs.pop("partial", False)
+ with transaction.atomic():
+ # Read after locking so validation and merging use the last committed configuration.
+ self.queryset = self.queryset.select_for_update()
+ instance = self.get_object()
+ serializer = self.get_serializer(instance, data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+
+ # A best-effort status query must not roll back the configuration write if it fails.
+ return Response(serializer.data)
+
def perform_update(self, serializer):
instance = cast(SignalSourceConfig, serializer.instance)
was_enabled = instance.enabled
@@ -619,7 +632,7 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if instance.enabled and not was_enabled:
- self._trigger_data_import_sync(instance)
+ transaction.on_commit(partial(self._trigger_data_import_sync, instance))
# Maps source_product to ExternalDataSourceType value for data import sources
_DATA_IMPORT_SOURCE_TYPE_MAP: dict[str, str] = {
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index a1686ff95876..7783d6f8ed6b 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -10403,6 +10403,11 @@ export const SignalSourceSyncStatusEnumApi = {
*/
export type SignalSourceConfigApiConfig = { [key: string]: unknown }
+/**
+ * Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.
+ */
+export type SignalSourceConfigApiConfigSet = { [key: string]: unknown }
+
export interface SignalSourceConfigApi {
readonly id: string
source_product: SignalSourceProductEnumApi
@@ -10410,6 +10415,10 @@ export interface SignalSourceConfigApi {
enabled?: boolean
/** Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint. */
config?: SignalSourceConfigApiConfig
+ /** Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config. */
+ config_set?: SignalSourceConfigApiConfigSet
+ /** Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config. */
+ config_remove?: string[]
readonly created_at: string
readonly updated_at: string
/** Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read. */
@@ -10430,6 +10439,11 @@ export interface PaginatedSignalSourceConfigListApi {
*/
export type PatchedSignalSourceConfigApiConfig = { [key: string]: unknown }
+/**
+ * Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.
+ */
+export type PatchedSignalSourceConfigApiConfigSet = { [key: string]: unknown }
+
export interface PatchedSignalSourceConfigApi {
readonly id?: string
source_product?: SignalSourceProductEnumApi
@@ -10437,6 +10451,10 @@ export interface PatchedSignalSourceConfigApi {
enabled?: boolean
/** Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint. */
config?: PatchedSignalSourceConfigApiConfig
+ /** Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config. */
+ config_set?: PatchedSignalSourceConfigApiConfigSet
+ /** Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config. */
+ config_remove?: string[]
readonly created_at?: string
readonly updated_at?: string
/** Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read. */
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 117a8ec9c308..eb6f777ba411 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -4117,6 +4117,18 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({
@@ -4272,6 +4284,18 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object({
@@ -4429,6 +4453,18 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object(
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
/**
diff --git a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts
index 6b58bb15a83e..5b715fdcdeea 100644
--- a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts
@@ -1,4 +1,7 @@
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { lemonToast } from '@posthog/lemon-ui'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
@@ -7,6 +10,7 @@ import { initKeaTests } from '~/test/init'
import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'
+import { INBOX_EVENTS } from '../inboxAnalytics'
import { signalSourcesLogic } from '../signalSourcesLogic'
import { SignalSourceConfig, SignalSourceProduct, SignalSourceType } from '../types'
import { linearTeamsModalLogic } from './linearTeamsModalLogic'
@@ -26,9 +30,15 @@ const existingConfig: SignalSourceConfig = {
describe('linearTeamsModalLogic', () => {
let requests: { method: string; body: Record<string, any> }[]
let onClose: jest.Mock
+ let saveFails: boolean
+ let captureSpy: jest.SpyInstance
+ let toastSpy: jest.SpyInstance
beforeEach(() => {
requests = []
+ saveFails = false
+ captureSpy = jest.spyOn(posthog, 'capture')
+ toastSpy = jest.spyOn(lemonToast, 'success')
useMocks({
get: {
'/api/projects/:team_id/signals/source_configs/': () => [
@@ -47,7 +57,9 @@ describe('linearTeamsModalLogic', () => {
'/api/projects/:team_id/signals/source_configs/:id/': async ({ request }) => {
const body = (await request.json()) as Record<string, any>
requests.push({ method: 'PATCH', body })
- return [200, { ...existingConfig, ...body }]
+ return saveFails
+ ? [500, { detail: 'Unable to save source settings.' }]
+ : [200, { ...existingConfig, ...body }]
},
},
})
@@ -59,37 +71,54 @@ describe('linearTeamsModalLogic', () => {
// The modal logic mounts integrationsLogic, whose mount-time load must settle here, or its
// response lands in the next test's context.
await expectLogic(integrationsLogic).toFinishAllListeners()
+ captureSpy.mockRestore()
+ toastSpy.mockRestore()
})
it.each([
{
name: 'a pick from Filters keeps the other keys and leaves enabled alone',
+ message: 'Linear reads 2 teams from the next sync.',
props: { config: existingConfig, enableOnSave: false },
form: { scope: 'selected' as const, teamIds: ['team-1', 'team-2'] },
expected: {
method: 'PATCH',
- body: { enabled: false, config: { steering: 'Skip chores', linear_team_ids: ['team-1', 'team-2'] } },
+ body: { enabled: false, config_set: { linear_team_ids: ['team-1', 'team-2'] } },
},
},
{
name: 'reading all teams writes an empty list',
+ message: 'Linear reads all teams from the next sync.',
props: { config: existingConfig, enableOnSave: false },
form: { scope: 'all' as const, teamIds: ['team-1'] },
expected: {
method: 'PATCH',
- body: { enabled: false, config: { steering: 'Skip chores', linear_team_ids: [] } },
+ body: { enabled: false, config_set: { linear_team_ids: [] } },
},
},
{
name: 'the enable flow turns the source on with the pick',
+ message: 'Linear reads 1 team from the next sync.',
props: { config: existingConfig, enableOnSave: true },
form: { scope: 'selected' as const, teamIds: ['team-2'] },
expected: {
method: 'PATCH',
- body: { enabled: true, config: { steering: 'Skip chores', linear_team_ids: ['team-2'] } },
+ body: { enabled: true, config_set: { linear_team_ids: ['team-2'] } },
},
},
- ])('$name', async ({ props, form, expected }) => {
+ {
+ name: 'a failed save records the attempted team selection',
+ message: null,
+ succeeds: false,
+ props: { config: existingConfig, enableOnSave: false },
+ form: { scope: 'selected' as const, teamIds: ['team-1', 'team-2'] },
+ expected: {
+ method: 'PATCH',
+ body: { enabled: false, config_set: { linear_team_ids: ['team-1', 'team-2'] } },
+ },
+ },
+ ])('$name', async ({ props, form, expected, message, succeeds = true }) => {
+ saveFails = !succeeds
const sourcesLogic = signalSourcesLogic()
sourcesLogic.mount()
await expectLogic(sourcesLogic, () => sourcesLogic.actions.loadSourceConfigs()).toDispatchActions([
@@ -101,11 +130,23 @@ describe('linearTeamsModalLogic', () => {
logic.actions.setLinearTeamsValues(form)
await expectLogic(logic, () => logic.actions.submitLinearTeams()).toDispatchActions([
'submitLinearTeamsSuccess',
- 'toggleSignalSourceSuccess',
+ succeeds ? 'toggleSignalSourceSuccess' : 'toggleSignalSourceFailure',
])
expect(requests).toEqual([expected])
- expect(onClose).toHaveBeenCalledTimes(1)
+ expect(onClose).toHaveBeenCalledTimes(succeeds ? 1 : 0)
+ if (succeeds) {
+ expect(toastSpy).toHaveBeenCalledWith(message)
+ }
+ expect(captureSpy).toHaveBeenCalledWith(
+ INBOX_EVENTS.SOURCE_FILTERS_CHANGED,
+ expect.objectContaining({
+ selected_count: form.scope === 'all' ? 0 : form.teamIds.length,
+ reads_everything: form.scope === 'all',
+ success: succeeds,
+ }),
+ undefined
+ )
})
it.each([
diff --git a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.ts b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.ts
index f7b1264364d8..3e604f091d1c 100644
--- a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.ts
+++ b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.ts
@@ -174,7 +174,7 @@ export const linearTeamsModalLogic: LogicWrapper<linearTeamsModalLogicType> = ke
],
actions: [signalSourcesLogic, ['toggleSignalSource', 'toggleSignalSourceSuccess', 'toggleSignalSourceFailure']],
})),
- forms(({ props: logicProps, actions, values }) => ({
+ forms(({ props: logicProps, actions }) => ({
linearTeams: {
defaults: formDefaults(logicProps.config),
// The message hangs off `scope` (a string field) because kea-forms types an array
@@ -186,20 +186,11 @@ export const linearTeamsModalLogic: LogicWrapper<linearTeamsModalLogicType> = ke
: undefined,
}),
submit: ({ scope, teamIds }: LinearTeamsFormValues) => {
- // The endpoint replaces the config object wholesale, so the whole blob goes back with
- // the team list merged in; a partial object would clobber the steering text. The merge
- // base is the freshest cached row rather than the open-time prop snapshot.
- const baseConfig =
- (logicProps.config &&
- values.sourceConfigs?.find((c: SignalSourceConfig) => c.id === logicProps.config?.id)
- ?.config) ??
- logicProps.config?.config ??
- {}
actions.toggleSignalSource({
sourceProduct: SignalSourceProduct.Linear,
sourceType: SignalSourceType.Issue,
enabled: logicProps.enableOnSave ? true : (logicProps.config?.enabled ?? true),
- config: { ...baseConfig, [SOURCE_LINEAR_TEAM_IDS_KEY]: scope === 'all' ? [] : teamIds },
+ configSet: { [SOURCE_LINEAR_TEAM_IDS_KEY]: scope === 'all' ? [] : teamIds },
viaSetupWizard: logicProps.viaSetupWizard,
})
},
@@ -237,7 +228,7 @@ export const linearTeamsModalLogic: LogicWrapper<linearTeamsModalLogicType> = ke
return
}
actions.saveSettled()
- const teamCount = linearTeamIdsFromConfig(params.config).length
+ const teamCount = linearTeamIdsFromConfig(params.configSet).length
captureSignalSourceFiltersChanged({
sourceProduct: params.sourceProduct,
sourceType: params.sourceType,
@@ -262,7 +253,7 @@ export const linearTeamsModalLogic: LogicWrapper<linearTeamsModalLogicType> = ke
sourceProduct: params.sourceProduct,
sourceType: params.sourceType,
filter: SOURCE_LINEAR_TEAM_IDS_KEY,
- selectedCount: linearTeamIdsFromConfig(params.config).length,
+ selectedCount: linearTeamIdsFromConfig(params.configSet).length,
success: false,
})
},
diff --git a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
index 06fedb122ad2..9c59e6134a33 100644
--- a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
@@ -48,7 +48,11 @@ describe('sourceSteeringModalLogic', () => {
patchBodies.push(body)
patchedIds.push(String(params.id))
// The serializer recomputes the sync status on every response.
- return [200, { ...sourceConfig, ...body, status: 'completed' }]
+ const config = { ...sourceConfig.config, ...body.config_set }
+ for (const key of body.config_remove ?? []) {
+ delete config[key]
+ }
+ return [200, { ...sourceConfig, config, status: 'completed' }]
},
},
})
@@ -62,7 +66,7 @@ describe('sourceSteeringModalLogic', () => {
logic?.unmount()
})
- it('saves the whole config with trimmed steering merged in, keeping keys it does not own and dropping the retired posture flag', async () => {
+ it('sends only trimmed guidance and explicitly removes the retired posture flag', async () => {
expect(logic.values.sourceSteering).toEqual({ steering: 'old rules' })
logic.actions.setSourceSteeringValue('steering', ' skip chores ')
@@ -72,10 +76,8 @@ describe('sourceSteeringModalLogic', () => {
expect(patchBodies).toEqual([
{
- config: {
- recording_filters: { events: [] },
- steering: 'skip chores',
- },
+ config_set: { steering: 'skip chores' },
+ config_remove: ['default_not_actionable'],
},
])
expect(onClose).toHaveBeenCalled()
@@ -109,7 +111,12 @@ describe('sourceSteeringModalLogic', () => {
SignalSourceType.IssueReopened,
SignalSourceType.IssueSpiking,
])
- expect(patchBodies).toEqual(rows.map(() => ({ config: { steering: 'Ignore errors from localhost.' } })))
+ expect(patchBodies).toEqual(
+ rows.map(() => ({
+ config_set: { steering: 'Ignore errors from localhost.' },
+ config_remove: ['default_not_actionable'],
+ }))
+ )
})
it('keeps writing the remaining rows when one fails, and stays open to be retried', async () => {
@@ -140,7 +147,7 @@ describe('sourceSteeringModalLogic', () => {
expect(onClose).not.toHaveBeenCalled()
})
- it('merges onto the freshest cached config, not the open-time snapshot', async () => {
+ it('does not send unrelated cached settings when saving guidance', async () => {
// A reload landed while the modal was open and changed a key steering does not own.
signalSourcesLogic.actions.loadSourceConfigsSuccess([
{ ...sourceConfig, config: { ...sourceConfig.config, recording_filters: { events: ['$pageview'] } } },
@@ -151,7 +158,10 @@ describe('sourceSteeringModalLogic', () => {
logic.actions.submitSourceSteering()
}).toDispatchActions(['submitSourceSteeringSuccess'])
- expect(patchBodies[0].config.recording_filters).toEqual({ events: ['$pageview'] })
+ expect(patchBodies[0]).toEqual({
+ config_set: { steering: 'new rules' },
+ config_remove: ['default_not_actionable'],
+ })
})
it('caches the saved config from the response even when the list reload fails', async () => {
diff --git a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
index 3b572c7da5db..c6a0973a0c24 100644
--- a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
+++ b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
@@ -194,26 +194,15 @@ export const sourceSteeringModalLogic: LogicWrapper<sourceSteeringModalLogicType
// behind. Retrying writes the same text to all of them, so a partial save heals.
let firstError: unknown = null
for (const sourceConfig of logicProps.sourceConfigs) {
- // The endpoint replaces the config object wholesale, so the whole blob goes back
- // with the steering keys merged in; a partial object would clobber source-specific
- // keys like recording_filters. The merge base is the freshest cached row rather
- // than the open-time prop snapshot, so a config change that landed while the
- // modal was open (another card's toggle, an earlier save) survives. A concurrent
- // write from another client can still be lost until the endpoint merges
- // server-side.
- const baseConfig =
- values.sourceConfigs?.find((c: SignalSourceConfig) => c.id === sourceConfig.id)?.config ??
- sourceConfig.config
- // The posture flag has no UI any more; dropping it on save keeps the free text the
- // only thing steering the gate, so what a user sees here is all that applies.
- const { [SOURCE_DEFAULT_NOT_ACTIONABLE_KEY]: _droppedPosture, ...restConfig } = baseConfig
- const config = { ...restConfig, [SOURCE_STEERING_KEY]: steering }
let updated: SignalSourceConfigApi
try {
updated = await signalsSourceConfigsPartialUpdate(
String(values.currentTeamId),
sourceConfig.id,
- { config }
+ {
+ config_set: { [SOURCE_STEERING_KEY]: steering },
+ config_remove: [SOURCE_DEFAULT_NOT_ACTIONABLE_KEY],
+ }
)
} catch (error) {
firstError = firstError ?? error
@@ -225,7 +214,7 @@ export const sourceSteeringModalLogic: LogicWrapper<sourceSteeringModalLogicType
actions.replaceSourceConfig({
...sourceConfig,
enabled: updated.enabled ?? sourceConfig.enabled,
- config: updated.config ?? config,
+ config: updated.config ?? sourceConfig.config,
updated_at: updated.updated_at,
// The generated type widens the serializer's sync status to string | null.
status: (updated.status ?? null) as SignalSourceConfig['status'],
diff --git a/products/signals/frontend/inbox/signalSourcesLogic.test.ts b/products/signals/frontend/inbox/signalSourcesLogic.test.ts
index c1f95a8b4433..a9beefe58e0f 100644
--- a/products/signals/frontend/inbox/signalSourcesLogic.test.ts
+++ b/products/signals/frontend/inbox/signalSourcesLogic.test.ts
@@ -23,7 +23,8 @@ import {
import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'
-import type { InboxOnboardingDraftApi, InboxOnboardingStateApi } from '../generated/api.schemas'
+import * as signalsApi from '../generated/api'
+import type { InboxOnboardingDraftApi, InboxOnboardingStateApi, SignalSourceConfigApi } from '../generated/api.schemas'
import { signalSourcesLogic } from './signalSourcesLogic'
import { SignalSourceProduct, SignalSourceType } from './types'
@@ -242,7 +243,7 @@ describe('signalSourcesLogic', () => {
['image-only connection', 'search_analytics_by_query_page_image'],
['connection without schemas', null],
])('does not enable Search Console signals with an %s', async (_name, schemaName) => {
- const createConfig = jest.spyOn(api.signalSourceConfigs, 'create')
+ const createConfig = jest.spyOn(signalsApi, 'signalsSourceConfigsCreate')
const toastError = jest.spyOn(lemonToast, 'error')
warehouseSources = [
{
@@ -281,7 +282,7 @@ describe('signalSourcesLogic', () => {
source_type: SignalSourceType.Ticket,
}
let saved = false
- const createConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockImplementation(async () => {
+ const createConfig = jest.spyOn(signalsApi, 'signalsSourceConfigsCreate').mockImplementation(async () => {
saved = true
return intercomConfig
})
@@ -305,7 +306,7 @@ describe('signalSourcesLogic', () => {
await expectLogic(logic, () => logic.actions.onDataSourceSetupComplete()).toFinishAllListeners()
- expect(createConfig).toHaveBeenCalledWith({
+ expect(createConfig).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {
source_product: 'intercom',
source_type: 'ticket',
enabled: true,
@@ -555,7 +556,9 @@ describe('signalSourcesLogic', () => {
resolveSources = resolve
})
const listSources = jest.spyOn(api.externalDataSources, 'list').mockReturnValue(sourcesPromise)
- const createSourceConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue(githubIssuesConfig)
+ const createSourceConfig = jest
+ .spyOn(signalsApi, 'signalsSourceConfigsCreate')
+ .mockResolvedValue(githubIssuesConfig as SignalSourceConfigApi)
logic.actions.loadSourceConfigsSuccess([])
logic.actions.initiateDataWarehouseSourceToggle('github')
@@ -595,13 +598,18 @@ describe('signalSourcesLogic', () => {
isToggling: () => false,
},
])('creates no row for $name while the source list has not loaded', async ({ toggle, isToggling }) => {
- const createSourceConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue(githubIssuesConfig)
+ const createSourceConfig = jest
+ .spyOn(signalsApi, 'signalsSourceConfigsCreate')
+ .mockResolvedValue(githubIssuesConfig as SignalSourceConfigApi)
+ const legacyCreate = jest.spyOn(api.signalSourceConfigs, 'create')
expect(logic.values.sourceConfigs).toBeNull()
toggle(logic)
await expectLogic(logic).toFinishAllListeners()
expect(createSourceConfig).not.toHaveBeenCalled()
+ expect(legacyCreate).not.toHaveBeenCalled()
+ legacyCreate.mockRestore()
expect(isToggling(logic)).toBe(false)
createSourceConfig.mockRestore()
})
@@ -611,8 +619,12 @@ describe('signalSourcesLogic', () => {
const updatePromise = new Promise<never>((_, reject) => {
rejectUpdate = reject
})
- const updateSourceConfig = jest.spyOn(api.signalSourceConfigs, 'update').mockReturnValue(updatePromise)
- const createSourceConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue(githubIssuesConfig)
+ const updateSourceConfig = jest
+ .spyOn(signalsApi, 'signalsSourceConfigsPartialUpdate')
+ .mockReturnValue(updatePromise)
+ const createSourceConfig = jest
+ .spyOn(signalsApi, 'signalsSourceConfigsCreate')
+ .mockResolvedValue(githubIssuesConfig as SignalSourceConfigApi)
const toastError = jest.spyOn(lemonToast, 'error')
logic.actions.loadSourceConfigsSuccess([
{
@@ -637,7 +649,7 @@ describe('signalSourcesLogic', () => {
})
it('uses only eval reports for the AI observability signal source', async () => {
- const createSourceConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue({
+ const createSourceConfig = jest.spyOn(signalsApi, 'signalsSourceConfigsCreate').mockResolvedValue({
id: 'config-evaluation-reports',
source_product: SignalSourceProduct.LlmAnalytics,
source_type: SignalSourceType.EvaluationReport,
@@ -665,7 +677,7 @@ describe('signalSourcesLogic', () => {
logic.actions.toggleEvalReports()
await expectLogic(logic).toFinishAllListeners()
- expect(createSourceConfig).toHaveBeenCalledWith({
+ expect(createSourceConfig).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {
source_product: SignalSourceProduct.LlmAnalytics,
source_type: SignalSourceType.EvaluationReport,
enabled: true,
diff --git a/products/signals/frontend/inbox/signalSourcesLogic.ts b/products/signals/frontend/inbox/signalSourcesLogic.ts
index bbd3dce098d2..5009b01c1497 100644
--- a/products/signals/frontend/inbox/signalSourcesLogic.ts
+++ b/products/signals/frontend/inbox/signalSourcesLogic.ts
@@ -31,9 +31,10 @@ import { SignalSourceProduct, SignalSourceType } from 'products/signals/frontend
import { externalDataSchemasPartialUpdate } from 'products/warehouse_sources/frontend/generated/api'
import { ExternalDataSourceTypeEnumApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
-import { signalsOnboardingList } from '../generated/api'
+import { signalsOnboardingList, signalsSourceConfigsCreate, signalsSourceConfigsPartialUpdate } from '../generated/api'
import type {
InboxOnboardingStateApi,
+ PatchedSignalSourceConfigApi,
SignalSourceTypeApi,
SignalSourceConfigSourceTypeEnumApi,
} from '../generated/api.schemas'
@@ -2013,7 +2014,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
// No breakpoint here: every call settles its own source, and a breakpoint would let a
// toggle on another source cancel this one, leaving its spinner up and its error unshown.
toggleSignalSource: async ({ params }) => {
- const { sourceProduct, sourceType, enabled, config } = params
+ const { sourceProduct, sourceType, enabled, config, configSet } = params
if (values.sourceConfigs === null) {
actions.toggleSignalSourceFailure(params, SOURCE_CONFIGS_UNAVAILABLE_MESSAGE)
failSignalSourceToggle(
@@ -2032,17 +2033,24 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
)
if (existing && !existing.id.startsWith('new_')) {
- const updateData: Partial<SignalSourceConfig> = { enabled }
+ const updateData: PatchedSignalSourceConfigApi = { enabled }
if (config !== undefined) {
updateData.config = config
}
- await api.signalSourceConfigs.update(existing.id, updateData)
+ if (configSet !== undefined) {
+ updateData.config_set = configSet
+ }
+ await signalsSourceConfigsPartialUpdate(
+ String(ApiConfig.getCurrentProjectId()),
+ existing.id,
+ updateData
+ )
} else if (enabled) {
- await api.signalSourceConfigs.create({
+ await signalsSourceConfigsCreate(String(ApiConfig.getCurrentProjectId()), {
source_product: sourceProduct,
- source_type: sourceType,
+ source_type: sourceType as SignalSourceConfigSourceTypeEnumApi,
enabled,
- config: config ?? {},
+ config: config ?? configSet ?? {},
})
}
actions.toggleSignalSourceSuccess(params)
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index a1e01af8a088..8838b9dc6766 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -2,6 +2,7 @@ import type { UserBasicType } from '~/types'
import {
type SignalReportApi,
+ type PatchedSignalSourceConfigApi,
type ReportChartApi,
type ReportMetricApi,
type ReportPlanApi,
@@ -219,6 +220,7 @@ export interface ToggleSignalSourceParams {
sourceType: SignalSourceType
enabled: boolean
config?: Record<string, any>
+ configSet?: PatchedSignalSourceConfigApi['config_set']
/** True when the enable came through the data-warehouse setup wizard, for `Signal source connected`. */
viaSetupWizard?: boolean
}
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index f7ab33867bf0..13182d3495d6 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -790,9 +790,12 @@ tools:
description: >
Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or
to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a
- project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. `config` is replaced as a
- whole, so include the existing keys (such as `steering`) when changing one of them, for example the Linear
- source's `linear_team_ids` allowlist.
+ project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Use `config_set` to set
+ individual top-level settings and `config_remove` to delete keys atomically, preserving unrelated settings.
+ For guidance, set `config_set.steering` and remove `default_not_actionable` with `config_remove`. For Linear
+ teams, set `config_set.linear_team_ids`. The resulting full configuration is validated before saving.
+ `config` still replaces the whole object; use it only for an intentional replacement. Do not combine
+ `config` with `config_set` or `config_remove`, or set and remove the same key.
inbox-source-configs-retrieve:
operation: signals_source_configs_retrieve
enabled: true
diff --git a/products/signals/skills/inbox-exploration/SKILL.md b/products/signals/skills/inbox-exploration/SKILL.md
index d9835811c81a..5917a2aae750 100644
--- a/products/signals/skills/inbox-exploration/SKILL.md
+++ b/products/signals/skills/inbox-exploration/SKILL.md
@@ -704,6 +704,12 @@ inbox-source-configs-partial-update
{ "id": "<source_config_uuid>", "enabled": false }
```
+To edit individual source settings, send only the top-level keys to change in `config_set` and keys to delete in `config_remove`.
+These edits preserve unrelated settings even when another editor saves at the same time.
+For guidance, set `config_set.steering` and include `default_not_actionable` in `config_remove`.
+Use `config_set.linear_team_ids` for Linear team selection.
+Reserve `config` for an intentional whole-object replacement; do not combine it with key edits.
+
## Tips
- **Check setup before assuming the inbox is empty.** If `inbox-reports-list` returns `count: 0`,
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4c402fc4639c..50098313b5f7 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8183,7 +8183,7 @@
}
},
"inbox-source-configs-partial-update": {
- "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. `config` is replaced as a whole, so include the existing keys (such as `steering`) when changing one of them, for example the Linear source's `linear_team_ids` allowlist.",
+ "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Use `config_set` to set individual top-level settings and `config_remove` to delete keys atomically, preserving unrelated settings. For guidance, set `config_set.steering` and remove `default_not_actionable` with `config_remove`. For Linear teams, set `config_set.linear_team_ids`. The resulting full configuration is validated before saving. `config` still replaces the whole object; use it only for an intentional replacement. Do not combine `config` with `config_set` or `config_remove`, or set and remove the same key.",
"category": "Signals",
"feature": "signals",
"summary": "Update signal source config",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 0e09f763ef92..48e127e05679 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8415,7 +8415,7 @@
}
},
"inbox-source-configs-partial-update": {
- "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. `config` is replaced as a whole, so include the existing keys (such as `steering`) when changing one of them, for example the Linear source's `linear_team_ids` allowlist.",
+ "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Use `config_set` to set individual top-level settings and `config_remove` to delete keys atomically, preserving unrelated settings. For guidance, set `config_set.steering` and remove `default_not_actionable` with `config_remove`. For Linear teams, set `config_set.linear_team_ids`. The resulting full configuration is validated before saving. `config` still replaces the whole object; use it only for an intentional replacement. Do not combine `config` with `config_set` or `config_remove`, or set and remove the same key.",
"category": "Signals",
"feature": "signals",
"summary": "Update signal source config",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 14ff30054b22..ce3621392fe1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -81113,6 +81113,11 @@ export namespace Schemas {
*/
export type SignalSourceConfigConfig = { [key: string]: unknown };
+ /**
+ * Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.
+ */
+ export type SignalSourceConfigConfigSet = { [key: string]: unknown };
+
export interface SignalSourceConfig {
readonly id: string;
source_product: SignalSourceProductEnum;
@@ -81120,6 +81125,10 @@ export namespace Schemas {
enabled?: boolean;
/** Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint. */
config?: SignalSourceConfigConfig;
+ /** Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config. */
+ config_set?: SignalSourceConfigConfigSet;
+ /** Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config. */
+ config_remove?: string[];
readonly created_at: string;
readonly updated_at: string;
/** Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read. */
@@ -92786,6 +92795,11 @@ export namespace Schemas {
*/
export type PatchedSignalSourceConfigConfig = { [key: string]: unknown };
+ /**
+ * Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.
+ */
+ export type PatchedSignalSourceConfigConfigSet = { [key: string]: unknown };
+
export interface PatchedSignalSourceConfig {
readonly id?: string;
source_product?: SignalSourceProductEnum;
@@ -92793,6 +92807,10 @@ export namespace Schemas {
enabled?: boolean;
/** Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint. */
config?: PatchedSignalSourceConfigConfig;
+ /** Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config. */
+ config_set?: PatchedSignalSourceConfigConfigSet;
+ /** Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config. */
+ config_remove?: string[];
readonly created_at?: string;
readonly updated_at?: string;
/** Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read. */
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index dd9f4760659a..d0d196b8c77f 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -4732,6 +4732,18 @@ export const SignalsSourceConfigsCreateBody = () => zod.object({
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
export const SignalsSourceConfigsRetrieveParams = () => zod.object({
@@ -4905,6 +4917,18 @@ export const SignalsSourceConfigsUpdateBody = () => zod.object({
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
export const SignalsSourceConfigsPartialUpdateParams = () => zod.object({
@@ -5071,4 +5095,16 @@ export const SignalsSourceConfigsPartialUpdateBody = () => zod.object({
.describe(
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources that define one (most data warehouse imports, and Conversations): `steering` (string, max 2000 characters) holds the team's preferences about this source's records in plain language: what matters, what to skip, what's out of scope. The emission actionability gate applies it when deciding which records become signals; rules apply from the next sync and nothing already emitted is retracted. `default_not_actionable` (boolean, default false) flips the gate's default: instead of keeping every record the steering rules don't exclude, only records that clearly match the team's preferences are kept. Other sources store these keys without reading them yet; future pipeline stages will consume the same steering text. Some sources read additional keys, for example `recording_filters` and `sample_rate` for session analysis. The Linear issue source (`source_product=linear`, `source_type=issue`) reads `linear_team_ids` (list of Linear team id strings, max 100): the warehouse still syncs the whole Linear workspace, but only issues from those teams become signals. Omit the key or pass an empty list to use every team. Get the ids from the Linear integration's teams endpoint."
),
+ config_set: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.'
+ ),
+ config_remove: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.'
+ ),
})
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 37fed2383436..2aff930a69e1 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -1052,6 +1052,12 @@ const inboxSourceConfigsCreate = (): ToolBase<
if (params.config !== undefined) {
body['config'] = params.config
}
+ if (params.config_set !== undefined) {
+ body['config_set'] = params.config_set
+ }
+ if (params.config_remove !== undefined) {
+ body['config_remove'] = params.config_remove
+ }
const result = await context.api.request<Schemas.SignalSourceConfig>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/source_configs/`,
@@ -1129,6 +1135,12 @@ const inboxSourceConfigsPartialUpdate = (): ToolBase<
if (params.config !== undefined) {
body['config'] = params.config
}
+ if (params.config_set !== undefined) {
+ body['config_set'] = params.config_set
+ }
+ if (params.config_remove !== undefined) {
+ body['config_remove'] = params.config_remove
+ }
const result = await context.api.request<Schemas.SignalSourceConfig>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/source_configs/${encodeURIComponent(String(params.id))}/`,
@@ -1186,6 +1198,12 @@ const inboxSourceConfigsUpdate = (): ToolBase<
if (params.config !== undefined) {
body['config'] = params.config
}
+ if (params.config_set !== undefined) {
+ body['config_set'] = params.config_set
+ }
+ if (params.config_remove !== undefined) {
+ body['config_remove'] = params.config_remove
+ }
const result = await context.api.request<Schemas.SignalSourceConfig>({
method: 'PUT',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/source_configs/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
index 6c95e511ea9e..ff0ee8880085 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
@@ -9,6 +9,21 @@
},
"type": "object"
},
+ "config_remove": {
+ "description": "Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "config_set": {
+ "additionalProperties": {},
+ "description": "Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
"enabled": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
index 79313c665e80..04c1bc79502e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
@@ -9,6 +9,21 @@
},
"type": "object"
},
+ "config_remove": {
+ "description": "Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "config_set": {
+ "additionalProperties": {},
+ "description": "Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
"enabled": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
index 77f1272a95b4..f6374fb160a3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
@@ -9,6 +9,21 @@
},
"type": "object"
},
+ "config_remove": {
+ "description": "Top-level config keys to remove atomically on update. Missing keys are ignored. Cannot overlap config_set or be combined with config.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "config_set": {
+ "additionalProperties": {},
+ "description": "Top-level config keys to set atomically on update. Unspecified keys are preserved. Cannot be combined with config.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
"enabled": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/signals-steering-generated.test.ts b/services/mcp/tests/unit/signals-steering-generated.test.ts
index dcec71f9902b..fb83a4b79f39 100644
--- a/services/mcp/tests/unit/signals-steering-generated.test.ts
+++ b/services/mcp/tests/unit/signals-steering-generated.test.ts
@@ -4,6 +4,26 @@ import { GENERATED_TOOLS } from '@/tools/generated/signals'
import type { Context } from '@/tools/types'
describe('Self-driving steering tools', () => {
+ it('passes atomic source config key edits through without stripping source-specific keys', async () => {
+ const request = vi.fn().mockResolvedValue({ id: 'source-example', config: {} })
+ const context = {
+ api: { request },
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+ const tool = GENERATED_TOOLS['inbox-source-configs-partial-update']!()
+ const input = {
+ id: 'source-example',
+ config_set: { steering: 'Prioritize documentation tasks', hogql_filter: 'false', nested: { keep: true } },
+ config_remove: ['default_not_actionable'],
+ }
+ await tool.handler(context, tool.schema.parse(input))
+ expect(request).toHaveBeenCalledWith({
+ method: 'PATCH',
+ path: '/api/projects/42/signals/source_configs/source-example/',
+ body: { config_set: input.config_set, config_remove: input.config_remove },
+ })
+ })
+
it.each(['inbox-steering-instructions-get', 'inbox-steering-instructions-update'])(
'%s uses the current project and returns only steering fields',
async (name) => {