:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): hold source switches until the source list loads (#114302)
posthog[bot]1b58019b3378
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 226a2c300b69..8fc28c509892 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11801,9 +11801,9 @@ snapshots:scenes-app-inbox-signalsourcespanel--server-side-exceptions-only--light:hash: v1.k794b7964.13df8c7b214cfd00e7eba5fea6da33f833ac202b7d3a2ebbadd331440bb9f97a.SL1Tzb4sMCHF1TQHfGCWGJYsBO88sT0dkLTlU88JrvQscenes-app-inbox-signalsourcespanel--source-configs-unavailable--dark:- hash: v1.k794b7964.b0af9348cf4a495b517dd863dca45310eb45c83964c8136eec37e6e7ada42ab3.mZK2q6HoW8jDn2n8yA9u1fqH22TvClzd8UgGiwfeRfc+ hash: v1.k794b7964.08032096bb8a223986a3a5b0f60f0966440a197906aafb84a0efbc3c7b1bd9e2.i7VYjJUGbfOhOXv9CPQinRTRT6qlb_EzTi5-cuV1eZoscenes-app-inbox-signalsourcespanel--source-configs-unavailable--light:- hash: v1.k794b7964.0a6cf287cde55b6cccce78b2603b9b736dacebd2ab6547f541df49845d6d3fdc.ry1SP43RXFgAvURyGogdG_ZZLfNuzaxCK0to6orM04A+ hash: v1.k794b7964.8bb3be64379113a1efe705deafff367381f509fbcd63f758e1870a558df0460f.1XVDXtWTy01V5cjltbWNM3EAe4BKpUDnjnrXCDBlEDsscenes-app-inbox-slacknotificationssection--awaiting-target--dark:hash: v1.k794b7964.8ea3584f9e8ba12a10845825520e5297ebf2c60282422cec693b0bd291ceee47.UdwureshdgpAitm-HeIekB6baljLm5XiV93vEw4z3-Ascenes-app-inbox-slacknotificationssection--awaiting-target--light:diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsxindex e3f38379cd3f..625f7227c16a 100644--- a/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx@@ -60,4 +60,20 @@ describe('AgentsRoster', () => {await userEvent.click(await screen.findByText('Show 2 more scanners'))expect(await screen.findByText('Scanner 9')).toBeInTheDocument()})++ // A failed load leaves every switch reading off and every import source reading unconnected.+ // A click then creates a row that may already exist, so the switches have to stay shut.+ it('holds the source switches shut while the source list has failed to load', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/signals/source_configs/': () => [500, { detail: 'Server error' }],+ },+ })+ render(<AgentsRoster />)++ expect(await screen.findByText(/Couldn't load your signal sources/)).toBeInTheDocument()+ expect(screen.getByLabelText('Arm Support')).toBeDisabled()+ expect(screen.getByLabelText('Arm GitHub issues')).toBeDisabled()+ expect(screen.queryByText('Connect')).not.toBeInTheDocument()+ })})diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsxindex 680136761900..16625daff74e 100644--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx@@ -120,8 +120,19 @@ interface AgentSourceState {* of them, so a source with a row per signal type is steered from its one card.*/steeringConfigs: SignalSourceConfig[]+ /** Why the switches cannot be used right now. Set while the source list is missing. */+ blockedReason?: string}+/**+ * Sources whose switch reads nothing from the source list: Replay vision reads its scanners and+ * GitHub CI reads its own config.+ */+const SOURCES_WITHOUT_CONFIG_ROWS: ReadonlySet<AgentRosterSource> = new Set(['replay_vision', 'engineering_analytics'])++const SOURCE_CONFIGS_LOADING_REASON = 'Loading your signal sources'+const SOURCE_CONFIGS_FAILED_REASON = "Couldn't load your signal sources. Select Retry above to try again."+function AgentIcon({ source }: { source: AgentRosterDefinition }): JSX.Element | null {const meta = getSourceProductMeta(source.sourceProduct)if (!meta?.Icon) {@@ -436,11 +447,12 @@ function Expansion({entity={entity}onToggle={() => onToggleEntity(entity.id)}disabledReason={- state.loading+ state.blockedReason ??+ (state.loading? 'Saving': productOff && !entity.enabled? `Turn on ${product?.productName} first. This source reads its data.`- : undefined+ : undefined)}/>))@@ -575,9 +587,10 @@ const AgentRow = memo(function AgentRow({checked={armed}onChange={() => onToggle(agent.source)}disabledReason={- armingBlocked+ state.blockedReason ??+ (armingBlocked? `Turn on ${product?.productName} first. This source reads its data.`- : undefined+ : undefined)}aria-label={`Arm ${agent.label}`}/>@@ -670,6 +683,7 @@ export function AgentsRoster(): JSX.Element {isCiSignalsToggling,productStatusBySource,enablingProduct,+ sourceConfigs,sourceConfigsLoadFailed,sourceConfigsLoading,linearTeamsPicker,@@ -718,7 +732,7 @@ export function AgentsRoster(): JSX.Element {[errorTrackingTypeStates])- const stateFor = useCallback(+ const sourceStateFor = useCallback((source: AgentRosterSource): AgentSourceState => {const base = {entities: [] as RosterEntity[],@@ -841,6 +855,25 @@ export function AgentsRoster(): JSX.Element {])+ // Without the source list every switch reads off and every data-import source reads as never+ // connected, so a click would try to create a row that may already exist. Hold the switches+ // until the list is in.+ const stateFor = useCallback(+ (source: AgentRosterSource): AgentSourceState => {+ const state = sourceStateFor(source)+ if (sourceConfigs !== null || SOURCES_WITHOUT_CONFIG_ROWS.has(source)) {+ return state+ }+ return {+ ...state,+ loading: state.loading || sourceConfigsLoading,+ requiresSetup: false,+ blockedReason: sourceConfigsLoading ? SOURCE_CONFIGS_LOADING_REASON : SOURCE_CONFIGS_FAILED_REASON,+ }+ },+ [sourceStateFor, sourceConfigs, sourceConfigsLoading]+ )+const handleToggle = useCallback((source: AgentRosterSource) => {switch (source) {@@ -917,7 +950,9 @@ export function AgentsRoster(): JSX.Element {'data-attr': 'signals-retry-source-configs',}}>- Couldn't load your signal sources, so the switches below may not match what's on.+ {sourceConfigs === null+ ? "Couldn't load your signal sources, so you can't turn them on or off yet. Retry to load them."+ : "Couldn't refresh your signal sources, so the switches below may not match what's on."}</LemonBanner>)}diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex ee56373b473f..8ab43cdeeef9 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -49,6 +49,8 @@ export const INBOX_EVENTS = {SETTINGS_CHANGED: 'Inbox settings changed',SOURCE_CONNECTED: 'Signal source connected',SOURCE_DISABLED: 'Signal source disabled',+ SOURCE_TOGGLE_FAILED: 'Signal source toggle failed',+ SOURCE_CONFIGS_LOAD_FAILED: 'Signal source configs load failed',SOURCE_INTEREST: 'signals source interest',SOURCE_STEERING_CHANGED: 'Signal source steering changed',SOURCE_FILTERS_CHANGED: 'Signal source filters changed',@@ -703,6 +705,34 @@ export function captureSignalSourceDisabled(params: { sourceProduct: string; sou})}+/**+ * Why a source switch did not save. `configs_unavailable` means the source list never loaded, so the+ * switch could not tell an existing row from a new one and refused to write.+ */+export type SignalSourceToggleFailureReason = 'configs_unavailable' | 'request_failed'++/** A source switch that did not save. Without it, a lost toggle leaves no trace next to the connections. */+export function captureSignalSourceToggleFailed(params: {+ sourceProduct: string+ sourceType: string+ enabled: boolean+ reason: SignalSourceToggleFailureReason+ errorMessage: string+}): void {+ captureInboxEvent(INBOX_EVENTS.SOURCE_TOGGLE_FAILED, {+ source_product: params.sourceProduct,+ source_type: params.sourceType,+ enabled: params.enabled,+ reason: params.reason,+ error_message: params.errorMessage,+ })+}++/** The source list failed to load, which blocks every switch that reads it. */+export function captureSignalSourceConfigsLoadFailed(errorMessage: string): void {+ captureInboxEvent(INBOX_EVENTS.SOURCE_CONFIGS_LOAD_FAILED, { error_message: errorMessage })+}+export function captureSignalSourceInterest(source: string): void {captureInboxEvent(INBOX_EVENTS.SOURCE_INTEREST, { source })}diff --git a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.tsindex 3f9676e0a432..6b58bb15a83e 100644--- a/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts+++ b/products/signals/frontend/inbox/logics/linearTeamsModalLogic.test.ts@@ -173,6 +173,7 @@ describe('linearTeamsModalLogic', () => {it('creates the row when Linear was never turned on before', async () => {const logic = linearTeamsModalLogic({ config: null, enableOnSave: true, viaSetupWizard: true, onClose })logic.mount()+ signalSourcesLogic.actions.loadSourceConfigsSuccess([])expect(logic.values.linearTeams).toEqual({ scope: 'all', teamIds: [] })await expectLogic(logic, () => logic.actions.submitLinearTeams()).toDispatchActions([diff --git a/products/signals/frontend/inbox/signalSourcesLogic.test.ts b/products/signals/frontend/inbox/signalSourcesLogic.test.tsindex 2d125494c265..16c2109c07e0 100644--- a/products/signals/frontend/inbox/signalSourcesLogic.test.ts+++ b/products/signals/frontend/inbox/signalSourcesLogic.test.ts@@ -2,6 +2,8 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import { lemonToast } from '@posthog/lemon-ui'+import api from 'lib/api'import { teamLogic } from 'scenes/teamLogic'@@ -210,6 +212,67 @@ describe('signalSourcesLogic', () => {expect(logic.values.isGithubIssuesToggling).toBe(false)})+ // Before the list loads, an existing row looks new. Creating it again fails on the unique+ // constraint, so the toggle has to refuse and let go of its spinner instead.+ it.each([+ {+ name: 'Support',+ toggle: (mountedLogic: typeof logic) => mountedLogic.actions.toggleConversations(),+ isToggling: (mountedLogic: typeof logic) => mountedLogic.values.isConversationsToggling,+ },+ {+ name: 'Error tracking',+ toggle: (mountedLogic: typeof logic) => mountedLogic.actions.toggleErrorTracking(),+ isToggling: (mountedLogic: typeof logic) => mountedLogic.values.isErrorTrackingToggling,+ },+ {+ name: 'an Error tracking signal type',+ toggle: (mountedLogic: typeof logic) =>+ mountedLogic.actions.toggleErrorTrackingType(SignalSourceType.IssueSpiking),+ 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)+ expect(logic.values.sourceConfigs).toBeNull()++ toggle(logic)+ await expectLogic(logic).toFinishAllListeners()++ expect(createSourceConfig).not.toHaveBeenCalled()+ expect(isToggling(logic)).toBe(false)+ createSourceConfig.mockRestore()+ })++ it('reports a failed toggle when another source is toggled while it saves', async () => {+ let rejectUpdate!: (error: unknown) => void+ 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 toastError = jest.spyOn(lemonToast, 'error')+ logic.actions.loadSourceConfigsSuccess([+ {+ ...githubIssuesConfig,+ id: 'config-conversations',+ source_product: SignalSourceProduct.Conversations,+ source_type: SignalSourceType.Ticket,+ enabled: false,+ },+ ])++ logic.actions.toggleConversations()+ logic.actions.toggleEvalReports()+ rejectUpdate({ detail: 'Support is not set up for this project.' })+ await expectLogic(logic).toFinishAllListeners()++ expect(toastError).toHaveBeenCalledWith('Support is not set up for this project.')+ expect(logic.values.isConversationsToggling).toBe(false)+ updateSourceConfig.mockRestore()+ createSourceConfig.mockRestore()+ toastError.mockRestore()+ })+it('uses only eval reports for the AI observability signal source', async () => {const createSourceConfig = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue({id: 'config-evaluation-reports',diff --git a/products/signals/frontend/inbox/signalSourcesLogic.ts b/products/signals/frontend/inbox/signalSourcesLogic.tsindex be7b32a5d685..3605c47b98f5 100644--- a/products/signals/frontend/inbox/signalSourcesLogic.ts+++ b/products/signals/frontend/inbox/signalSourcesLogic.ts@@ -28,7 +28,13 @@ import { ExternalDataSourceTypeEnumApi } from 'products/warehouse_sources/fronteimport type { SignalSourceTypeApi } from '../generated/api.schemas'import type { AgentRosterSource } from './components/config/agentRosterMeta'-import { captureSignalSourceConnected, captureSignalSourceDisabled } from './inboxAnalytics'+import {+ SignalSourceToggleFailureReason,+ captureSignalSourceConfigsLoadFailed,+ captureSignalSourceConnected,+ captureSignalSourceDisabled,+ captureSignalSourceToggleFailed,+} from './inboxAnalytics'import { SOURCE_STEERING_KEY, SignalSourceConfig, ToggleSignalSourceParams } from './types'/** product_enablement recipe names for products that back a signal source. */@@ -149,6 +155,12 @@ export const WAREHOUSE_SOURCE_SETUP: Record<},}+/**+ * Shown when a toggle runs before the source list has loaded. Without the list an existing source+ * looks new, and creating it again fails on the unique constraint with a message nobody can act on.+ */+const SOURCE_CONFIGS_UNAVAILABLE_MESSAGE = "Couldn't load your signal sources. Reload them and try again."+/** Values subset used by data-warehouse source helpers */interface SignalSourcesLogicValuesForDw {sourceConfigs: SignalSourceConfig[] | null@@ -1056,7 +1068,22 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([)}+ function failSignalSourceToggle(+ sourceProduct: SignalSourceProduct,+ sourceType: SignalSourceType,+ enabled: boolean,+ errorMessage: string,+ reason: SignalSourceToggleFailureReason+ ): void {+ captureSignalSourceToggleFailed({ sourceProduct, sourceType, enabled, reason, errorMessage })+ lemonToast.error(errorMessage)+ actions.loadSourceConfigs()+ }+return {+ loadSourceConfigsFailure: ({ error, errorObject }) => {+ captureSignalSourceConfigsLoadFailed(errorObject?.detail || error || 'Failed to load signal sources')+ },loadCiSignalsConfigFailure: ({ error, errorObject }) => {// Silent failure would leave the card claiming setup is required for an armed source.lemonToast.error(errorObject?.detail || error || 'Failed to load CI signals status')@@ -1132,10 +1159,23 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([viaSetupWizard: true,})},- toggleSignalSource: async ({ params }, breakpoint) => {+ // 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+ if (values.sourceConfigs === null) {+ actions.toggleSignalSourceFailure(params, SOURCE_CONFIGS_UNAVAILABLE_MESSAGE)+ failSignalSourceToggle(+ sourceProduct,+ sourceType,+ enabled,+ SOURCE_CONFIGS_UNAVAILABLE_MESSAGE,+ 'configs_unavailable'+ )+ return+ }try {- const configs = values.sourceConfigs ?? []+ const configs = values.sourceConfigsconst existing = configs.find((c: SignalSourceConfig) => c.source_product === sourceProduct && c.source_type === sourceType)@@ -1154,7 +1194,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([config: config ?? {},})}- breakpoint()actions.toggleSignalSourceSuccess(params)if (sourceProduct === SignalSourceProduct.LlmAnalytics &&@@ -1181,18 +1220,27 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([}actions.loadSourceConfigs()} catch (error: any) {- breakpoint()const errorMessage = error?.detail || error?.message || 'Failed to toggle signal source'actions.toggleSignalSourceFailure(params, errorMessage)- actions.loadSourceConfigs()- lemonToast.error(errorMessage)+ failSignalSourceToggle(sourceProduct, sourceType, enabled, errorMessage, 'request_failed')}},toggleErrorTracking: async (_, breakpoint) => {// The row switch reads "on" as soon as one type is armed, so turning it off has to// stand every type down rather than arm the remaining ones.const desiredEnabled = !values.errorTrackingTypeStates.some(({ enabled }) => enabled)- const configs = values.sourceConfigs ?? []+ if (values.sourceConfigs === null) {+ actions.toggleErrorTrackingComplete()+ failSignalSourceToggle(+ SignalSourceProduct.ErrorTracking,+ SignalSourceType.IssueCreated,+ desiredEnabled,+ SOURCE_CONFIGS_UNAVAILABLE_MESSAGE,+ 'configs_unavailable'+ )+ return+ }+ const configs = values.sourceConfigsconst inheritedConfig = inheritedErrorTrackingConfig(values.errorTrackingConfigs)// First connection when no persisted error-tracking config existed before this enable.const wasConnected = configs.some(@@ -1235,12 +1283,29 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([breakpoint() // re-throws if superseded, skipping the lines belowactions.toggleErrorTrackingComplete()const errorMessage = error?.detail || error?.message || 'Failed to toggle Error tracking signals'- lemonToast.error(errorMessage)- actions.loadSourceConfigs()+ failSignalSourceToggle(+ SignalSourceProduct.ErrorTracking,+ SignalSourceType.IssueCreated,+ desiredEnabled,+ errorMessage,+ 'request_failed'+ )}},- toggleErrorTrackingType: async ({ sourceType }, breakpoint) => {- const configs = values.sourceConfigs ?? []+ // No breakpoint here either: each signal type is its own row, so a click on another type+ // must not cancel this one or swallow its error.+ toggleErrorTrackingType: async ({ sourceType }) => {+ const configs = values.sourceConfigs+ if (configs === null) {+ failSignalSourceToggle(+ SignalSourceProduct.ErrorTracking,+ sourceType,+ true,+ SOURCE_CONFIGS_UNAVAILABLE_MESSAGE,+ 'configs_unavailable'+ )+ return+ }const inheritedConfig = inheritedErrorTrackingConfig(values.errorTrackingConfigs)const existing = configs.find((c) => c.source_product === SignalSourceProduct.ErrorTracking && c.source_type === sourceType@@ -1257,10 +1322,15 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([config: inheritedConfig,})}- breakpoint()} catch (error: any) {- breakpoint()- lemonToast.error(error?.detail || error?.message || 'Failed to toggle this signal type')+ failSignalSourceToggle(+ SignalSourceProduct.ErrorTracking,+ sourceType,+ desiredEnabled,+ error?.detail || error?.message || 'Failed to toggle this signal type',+ 'request_failed'+ )+ return}actions.loadSourceConfigs()},