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): add run only when settings to the scout settings form (#114387)

posthog[bot]f390805cceba
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d928e323b4aa..fe7f0d5c9ee4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11455,33 +11455,33 @@ snapshots:
scenes-app-inbox-scout-trials-setup--unsaved-rubric--light:
hash: v1.k794b7964.64c0d8ac04bb10ab54ff05a9c7d2efd237b622b116771aee794fa1c7af421bcc.XeqOuTw49vlR0b-89jf7K-rnc7FjBV6h-EJZoDc8Su8
scenes-app-inbox-scoutconfigform--custom-cron-schedule--dark:
- hash: v1.k794b7964.5f16b2a4d04e486778e91d4eb789a1bd3319e5294eab554ea710100988486d8c._Dc-7uDt2LVj8PfUYrbi-vTgD2vyGpcUPlNLMrk93pI
+ hash: v1.k794b7964.6378a9596309fa4fd12a964073a13246e6af771163b2e74fc68e61c1db4292d7.RhdRT5KWraixvvTHP_y3dVuIW8J0SL5igyirjcewljk
scenes-app-inbox-scoutconfigform--custom-cron-schedule--light:
- hash: v1.k794b7964.e02082db90ce9a28a66d8705e886039e49702371189084bcc1cbcc62e3f5271e.T1si3RYLe1SVK7BoeeAp5H8-zIjDmwM_0UYiYhY7PFw
+ hash: v1.k794b7964.c51eebe91da2aeb28af4f6802d59c5dceab7007829c18a1c59649789e95e6a5c.Ze3mbrtkpUrYDjhEgGbG4RAgefvaPF2O5zbIRe3aWjw
scenes-app-inbox-scoutconfigform--disabled--dark:
- hash: v1.k794b7964.776b29163ec6e8ca08cfbd11e0d522ec3f5acbd0d311f6ce80b22cb7031989ca.4WKzemD9Lqb-USdSgAGO-7z-NkM9to10Esw5URgNbWE
+ hash: v1.k794b7964.ec7ef2256997314be550c838d3850710ada229040515da4ad6bc85d9a13425bb.z1WoHpY-gF9ZkDjQA7oUCo5g1AGcQcc3YxSbGRzLfYo
scenes-app-inbox-scoutconfigform--disabled--light:
- hash: v1.k794b7964.c1cb396fd505a988a78a3d995f8daae80575130eefe03490f1098f65ff3a83b3.lSMVMwfMCT_jtzaOVv6Hr8pM5mzCjU3D8OKHie_Ho7k
+ hash: v1.k794b7964.596758660f7fdf9a8f1ab581681c25df603bc176d67e5ea252b43159027acf80.CNYZsuIe7fRU07w3HllIPtvyHf2oZnSzJHoQg8LBHGo
scenes-app-inbox-scoutconfigform--dry-run--dark:
- hash: v1.k794b7964.e6d52e09d6ffd72d86c84d8032cf8ab47c87e1a3b81e8a518db40195be1174c9.gIoJfjKmsFzEyu2P2ReCtcGOUr5Ig4RySSO4mKA3d_E
+ hash: v1.k794b7964.85bd04d313a2246719a978813f5d8fcaa469c2d7ed16204149059287a86939b5.qdlsrpAcHCZ-4f7ENoKhuyZTuhNd32Ye64gltyx6Epk
scenes-app-inbox-scoutconfigform--dry-run--light:
- hash: v1.k794b7964.db15686714921ee32dcd9777565cbd1b692eadc5b48b3fb6852a7bf881fa7a54.1gwqOVvQefzSHxW1RQnf6NVMZqiKt5kXn831FWW4Q0g
+ hash: v1.k794b7964.215350b36bf14f21836f445d13adff456921786f52802da0f98f0b2ebead11c7.0H_WI7L82A1TPFC1tK9dgdmtKX6f9Ow03DdSc9YC2ro
scenes-app-inbox-scoutconfigform--live--dark:
- hash: v1.k794b7964.d1222c0d9dce2ceea9df8b0cd8bb81be32948f107c9f10157d02edfb059ab738.RyMXcVNaZwb8Qne2Xy7viSaIWjbcOAnFjLzW3C0YQ20
+ hash: v1.k794b7964.22844e997fdf12c3b3a39012a3e09c61bc1dfae1c8fe3af7195662dd168994d4.RxkaFU88ZioRIWXQIsENqd0Tr7cgwqRsJZO9NjEInX0
scenes-app-inbox-scoutconfigform--live--light:
- hash: v1.k794b7964.0cb359a23c3fcbbd4cdcdaa8dc139d2d9501c4d14287ec209bb213ad0eb3a07a.H4gWFstRwwMf7dttwqfKJzPkK_njc7U77S_5yATThf4
+ hash: v1.k794b7964.3438cb4bf321db1086dd10eabbaceb30f09530872427303742ad3d3907a1b23f.oGx_AuCL0y8v-S7odhR7Lbp-2vT7pjerHN9QZNJ-g9s
scenes-app-inbox-scoutconfigform--slack-channel-destination--dark:
- hash: v1.k794b7964.f9997ddd1d470ef8fb91af92eaa17de675014831ca6046aa90628dbe89351799.3IIPPxVLzyynVQcdm1eRkB7SDMtTtzqb67aCkqUwQ-o
+ hash: v1.k794b7964.7d472808fd14a8663ab8ac4f1b894547b055f1babcac80dc5b803d5fe2428706.pRsthoDdjt9hjwjoLTHRcAnXw7M1TATeQgcBgSZCxSk
scenes-app-inbox-scoutconfigform--slack-channel-destination--light:
- hash: v1.k794b7964.9f6140ccbbc8b55bd07afafbf7735f77370ec35479af55c530e85a622d150141.sB6puQ6eggmTME--95tzVd1naeEOVWEGMbnaS-m1hTU
+ hash: v1.k794b7964.7a5fdbdd6b03b474e9ac2c698d678c828fca0e4dbbc5d89121292153d4be5a31.j294iEwXC5J9schhlogtSwB1rocD1l_Zd0I73yaqS1U
scenes-app-inbox-scoutconfigform--structured-output--dark:
- hash: v1.k794b7964.1a197c92ab09bf0a19f35564d683fa1cc81d993451c99af1bea01a229a927b20.lfxIe4U4zVEsZr2iBXA0KYeIQwmTm3o97hUa1m7M4dA
+ hash: v1.k794b7964.c34f609a1d1034e4b8ee91c8c44fb02641b0107ffbaee4ee5ab78443aba0f58b.58MUI3Jrc2lRSHzvOaF1rWyQ8OmW1_P0myra_v2g_ow
scenes-app-inbox-scoutconfigform--structured-output--light:
- hash: v1.k794b7964.ed3286cfb9dcd72b546458c178750237966b54b073e4ff8a5c752c208a1271b8.T-mnEkll4xTFPB8X2P9D31UcBjUxzFjnd3g3lTo8KNc
+ hash: v1.k794b7964.8fd03bb1e0bcf6bfd12d4e1998b5c748a628d77305ed3ecd4f65c06dfb912859.47heuQ1PD7usF5OCbISOMs8eLB0VYyCdqi4LsN8OUb4
scenes-app-inbox-scoutconfigform--weekly-schedule--dark:
- hash: v1.k794b7964.9b976054979f9537937ff8d76c4a9bbeaae6e35130155b092c176adc3dd759b5.XhNq5OvOC09jhiXQ2YVEj-7weqIJ2cgxrKgVoXBemf4
+ hash: v1.k794b7964.19a81863734b43a19a43c3377dfcaaefdc267077a1a047305d99d81a693a5c7f.Lxu9-YhxbDgAogm9XF5HAxAE8gbU8obJT6GmnW70Yys
scenes-app-inbox-scoutconfigform--weekly-schedule--light:
- hash: v1.k794b7964.d02dc7a4dcd70d3a59ae10c83a68703bcb63c94b9cb0e74fdec82797c1ef6ba2.oUca34huG-Mr0y45QaNPzlxIcIDR1kAqxGKwyWv2lMg
+ hash: v1.k794b7964.df6a52c606df65aff4b0739de4647dea8f2d85ca10c2809eb623c0bde7dcf3aa.HIt7xQ0EWAkyBron_PV0TJUam5y6sO0_oF07KM0lnTQ
scenes-app-inbox-scoutdetailview--scout-page--dark:
hash: v1.k794b7964.7994cd307f5adb384df6008caa4d535248e8e10ba5505840e7b2661704cfa054.HD73lbCqzK0mXr4mcQ7lZJdj5J5aGTd_5LtbP3TDbLU
scenes-app-inbox-scoutdetailview--scout-page--light:
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx
index 29d66a19b465..abfaa4bb6e04 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx
@@ -1,5 +1,5 @@
import { useValues } from 'kea'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { IconTrash } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'
@@ -16,6 +16,7 @@ import type {
import { SignalScoutConfigNetworkAccessEnumApi } from 'products/signals/frontend/generated/api.schemas'
import { MODELS } from 'products/tasks/frontend/modelCatalog.generated'
+import type { ScoutSurface } from '../../../inboxAnalytics'
import {
dailyCronToTime,
dayTimeToWeeklyCron,
@@ -34,6 +35,7 @@ import {
weeklyCronToDayTime,
} from '../../../utils/scoutRunsWindow'
import { ScoutMcpServersPicker } from './ScoutMcpServersPicker'
+import { ScoutPrecheckSection } from './ScoutPrecheckSection'
import { ScoutRepositoriesPicker } from './ScoutRepositoriesPicker'
import { ScoutSlackDestination } from './ScoutSlackDestination'
import { ScoutStructuredOutputSection } from './ScoutStructuredOutputSection'
@@ -71,8 +73,9 @@ interface ScoutConfigFormProps extends ScoutConfigControlsProps {
deleting?: boolean
/** True while this scout's config update request is in flight. */
updating?: boolean
- /** Called when a staged edit (the record schema) gains or loses unsaved changes. */
+ /** Called when a staged edit (the pre-check query or the record schema) gains or loses unsaved changes. */
onUnsavedChange?: (unsaved: boolean) => void
+ surface?: ScoutSurface
}
/** Enable/disable toggle for a scout. Lives on the row, not in the settings form. */
@@ -104,6 +107,7 @@ export function ScoutConfigForm({
deleting,
updating = false,
onUnsavedChange,
+ surface = 'scout_detail',
}: ScoutConfigFormProps): JSX.Element {
const { timezone: projectTimezone } = useValues(teamLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -116,6 +120,12 @@ export function ScoutConfigForm({
// config stays the truth for them, including when a failed write rolls it back.
const [customModePicked, setCustomModePicked] = useState(false)
const scheduleMode = customModePicked ? SCOUT_CUSTOM_CRON_SCHEDULE_MODE : savedScheduleMode
+ // Two sections stage edits, and either one alone must keep the host modal guarded.
+ const [precheckUnsaved, setPrecheckUnsaved] = useState(false)
+ const [schemaUnsaved, setSchemaUnsaved] = useState(false)
+ useEffect(() => {
+ onUnsavedChange?.(precheckUnsaved || schemaUnsaved)
+ }, [precheckUnsaved, schemaUnsaved, onUnsavedChange])
const controlsDisabledReason = updating
? 'Saving scout settings'
: config.enabled
@@ -357,13 +367,21 @@ export function ScoutConfigForm({
disabledReason={updating ? 'Saving scout settings' : undefined}
/>
{/* Keyed by scout because the scout page keeps this form mounted when the URL moves to another
- scout, and an unsaved schema draft must not become the next scout's save. */}
+ scout, and an unsaved draft must not become the next scout's save. */}
+ <ScoutPrecheckSection
+ key={`precheck-${config.id}`}
+ config={config}
+ onUpdate={onUpdate}
+ updating={updating}
+ surface={surface}
+ onUnsavedChange={setPrecheckUnsaved}
+ />
<ScoutStructuredOutputSection
key={config.id}
config={config}
onUpdate={onUpdate}
updating={updating}
- onUnsavedChange={onUnsavedChange}
+ onUnsavedChange={setSchemaUnsaved}
/>
<ScoutWriteAccessSection config={config} onUpdate={onUpdate} updating={updating} />
{/* Only custom scouts are deletable. A canonical scout would be re-seeded from disk after
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx
new file mode 100644
index 000000000000..29307cbb630c
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx
@@ -0,0 +1,236 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonButton, LemonCollapse, LemonDialog, LemonTag, LemonTextArea } from '@posthog/lemon-ui'
+
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+
+import type {
+ PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,
+ SignalScoutConfigApi as SignalScoutConfig,
+ SignalScoutPrecheckTestApi,
+} from 'products/signals/frontend/generated/api.schemas'
+
+import type { ScoutSurface } from '../../../inboxAnalytics'
+import { scoutPrecheckLogic } from '../../../logics/scoutPrecheckLogic'
+
+const QUERY_PLACEHOLDER = `SELECT count()
+FROM events
+WHERE event = '$exception' AND timestamp > {since}`
+
+function testVerdict(result: SignalScoutPrecheckTestApi): string {
+ switch (result.reason) {
+ case 'no_rows':
+ return 'The next scheduled run skips. The query found no rows.'
+ case 'rows':
+ return `The next scheduled run starts. The query found ${result.row_count} ${result.row_count === 1 ? 'row' : 'rows'}.`
+ case 'false_value':
+ return 'The next scheduled run skips. The query returned a single false value, such as a count of 0.'
+ case 'query_error':
+ return 'The next scheduled run starts, because a query that fails never skips a run.'
+ }
+}
+
+/**
+ * The pre-check of one scout in its settings form: a HogQL query that a scheduled run checks
+ * before it starts. No rows, or a single false value, skips the run, so a scout that watches a quiet
+ * surface costs nothing between bursts.
+ *
+ * The query does not save on change, like the record schema. A half-typed query would fail on the
+ * next tick, so the editor stages a draft, the test button tries it, and the save button commits it.
+ */
+export function ScoutPrecheckSection({
+ config,
+ onUpdate,
+ updating = false,
+ surface,
+ onUnsavedChange,
+}: {
+ config: SignalScoutConfig
+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void
+ updating?: boolean
+ surface: ScoutSurface
+ /** Called when the editor gains or loses an unsaved edit, so a host modal can guard its backdrop. */
+ onUnsavedChange?: (unsaved: boolean) => void
+}): JSX.Element {
+ const logic = scoutPrecheckLogic({ configId: config.id, skillName: config.skill_name, surface })
+ const { testRun, testRunLoading, testRunFailed } = useValues(logic)
+ const { testPrecheck } = useActions(logic)
+ const saved = config.precheck_query ?? null
+ // Null until something is typed, so an untouched editor follows the saved query.
+ const [draft, setDraft] = useState<string | null>(null)
+ // The query the last save or turn-off sent, held until the request settles. The draft clears
+ // only if the stored query then matches it, so a query the API rejects stays on screen to fix.
+ const [submitted, setSubmitted] = useState<{ query: string | null } | null>(null)
+ useEffect(() => {
+ if (updating || !submitted) {
+ return
+ }
+ if (saved === submitted.query) {
+ setDraft(null)
+ }
+ setSubmitted(null)
+ }, [updating, submitted, saved])
+ const text = draft ?? saved ?? ''
+ const query = text.trim()
+ const changed = query !== (saved ?? '')
+ const unsaved = draft !== null && (changed || submitted !== null)
+ useEffect(() => {
+ onUnsavedChange?.(unsaved)
+ return () => onUnsavedChange?.(false)
+ }, [unsaved, onUnsavedChange])
+ // A result describes the query it ran. Once the query changes, or a newer test is running or
+ // failed, it no longer applies.
+ const result = testRun && testRun.query === query && !testRunLoading && !testRunFailed ? testRun.result : null
+ const disabledReason = updating ? 'Saving scout settings' : undefined
+ const saveDisabledReason =
+ disabledReason ??
+ (query && changed ? undefined : !query && saved ? 'To remove the query, use Turn off' : 'No changes to save')
+
+ return (
+ <div className="border-t border-primary pt-2">
+ <LemonCollapse
+ embedded
+ size="small"
+ panels={[
+ {
+ key: 'precheck',
+ dataAttr: 'scout-precheck',
+ header: (
+ <div className="flex min-w-0 flex-1 items-center justify-between gap-2">
+ <span className="shrink-0 text-xs text-default">Run only when</span>
+ {saved ? (
+ <LemonTag size="small" type="option">
+ Query set
+ </LemonTag>
+ ) : (
+ <span className="text-[11.5px] text-muted">Always run</span>
+ )}
+ </div>
+ ),
+ content: (
+ <div className="flex flex-col gap-2">
+ <span className="text-[11.5px] text-muted">
+ A HogQL query that each scheduled run checks first. When it returns no rows, or a
+ single false value such as a count of 0, the scout skips the run, so a quiet scout
+ costs nothing. Otherwise the run starts with the rows the query found. Use{' '}
+ {'{since}'} for the start of the last run and {'{now}'} for the current time. To run
+ at least once a week, add {'OR {since} < {now} - INTERVAL 7 DAY'}. A manual run
+ always starts.
+ </span>
+ <LemonTextArea
+ value={text}
+ placeholder={QUERY_PLACEHOLDER}
+ minRows={4}
+ maxRows={12}
+ className="font-mono text-[11.5px]"
+ disabled={updating}
+ onChange={setDraft}
+ aria-label={`${config.skill_name} pre-check query`}
+ />
+ {testRunFailed ? (
+ <span role="alert" className="text-[11.5px] text-danger">
+ The test could not run. Try again.
+ </span>
+ ) : null}
+ {result ? (
+ <div
+ className="flex flex-col gap-1 ph-no-capture ph-replay-block"
+ data-attr="scout-precheck-result"
+ >
+ <span
+ className={`text-[11.5px] ${result.would_run ? 'text-default' : 'text-success'}`}
+ >
+ {testVerdict(result)}
+ </span>
+ {result.error ? (
+ <span className="text-[11.5px] text-danger">{result.error}</span>
+ ) : null}
+ <span className="text-[11.5px] text-muted">
+ {'{since}'} is {humanFriendlyDetailedTime(result.since)}.
+ </span>
+ {result.rows_text ? (
+ <pre className="m-0 max-h-40 overflow-auto rounded border border-primary bg-surface-secondary p-2 font-mono text-[11px] whitespace-pre-wrap break-all">
+ {result.rows_text}
+ </pre>
+ ) : null}
+ </div>
+ ) : null}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {saved ? (
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ className="mr-auto"
+ disabledReason={disabledReason}
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Remove the pre-check?',
+ description:
+ 'Every scheduled run starts again. You can add a query again later.',
+ primaryButton: {
+ children: 'Turn off',
+ status: 'danger',
+ onClick: () => {
+ onUpdate(config.id, { precheck_query: null })
+ setSubmitted({ query: null })
+ },
+ 'data-attr': 'scout-precheck-clear',
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ data-attr="scout-precheck-turn-off"
+ >
+ Turn off
+ </LemonButton>
+ ) : null}
+ {unsaved ? (
+ <LemonButton
+ size="small"
+ type="tertiary"
+ disabledReason={disabledReason}
+ onClick={() => setDraft(null)}
+ data-attr="scout-precheck-discard"
+ >
+ Discard
+ </LemonButton>
+ ) : null}
+ <LemonButton
+ size="small"
+ type="secondary"
+ loading={testRunLoading}
+ // The test reads the stored settings, so it waits for a save to finish.
+ disabledReason={
+ testRunLoading
+ ? 'Testing the query'
+ : (disabledReason ?? (query ? undefined : 'Write a query first'))
+ }
+ onClick={() => testPrecheck({ query })}
+ data-attr="scout-precheck-test"
+ >
+ Test query
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="secondary"
+ loading={updating}
+ disabledReason={saveDisabledReason}
+ onClick={() => {
+ onUpdate(config.id, { precheck_query: query })
+ setSubmitted({ query })
+ }}
+ data-attr="scout-precheck-save"
+ >
+ Save query
+ </LemonButton>
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx
index 6f5476c8c64f..33ae223afd83 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx
@@ -49,6 +49,7 @@ export function ScoutSettingsModal({
deleting={deletingScoutIds.includes(config.id)}
updating={updatingScoutIds.includes(config.id)}
onUnsavedChange={setHasUnsavedInput}
+ surface={surface}
/>
</LemonModal>
)
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 8ab43cdeeef9..ef4ae9c2d684 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -230,6 +230,7 @@ export type ScoutActionType =
| 'sort_roster'
| 'choose_create_path'
| 'switch_create_path'
+ | 'test_precheck'
/** What a scout chat CTA was asking for. Matches the desktop values. */
export type ScoutChatType = 'author_scout' | 'fleet_overview' | 'recent_signals'
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index 82d11a317694..ce1338486eee 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -126,12 +126,15 @@ function captureScoutConfigUpdates(
success: boolean
): void {
for (const [setting, newValue] of Object.entries(updates)) {
+ const oldValue = config ? (config as unknown as Record<string, unknown>)[setting] : null
+ // A pre-check query can name values from the team's own data, so only whether it is set is sent.
+ const masked = setting === 'precheck_query'
captureScoutConfigChanged({
skillName: config?.skill_name ?? '',
scoutOrigin: config?.scout_origin ?? null,
setting,
- oldValue: config ? (config as unknown as Record<string, unknown>)[setting] : null,
- newValue,
+ oldValue: masked ? Boolean(oldValue) : oldValue,
+ newValue: masked ? Boolean(newValue) : newValue,
success,
})
}
diff --git a/products/signals/frontend/inbox/logics/scoutPrecheckLogic.ts b/products/signals/frontend/inbox/logics/scoutPrecheckLogic.ts
new file mode 100644
index 000000000000..aae5c2d3c3a7
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/scoutPrecheckLogic.ts
@@ -0,0 +1,144 @@
+import { MakeLogicType, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { signalsScoutConfigPrecheckTest } from 'products/signals/frontend/generated/api'
+import type { SignalScoutPrecheckTestApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { captureScoutAction, type ScoutSurface } from '../inboxAnalytics'
+
+export interface ScoutPrecheckLogicProps {
+ configId: string
+ skillName: string
+ surface: ScoutSurface
+}
+
+export interface ScoutPrecheckTestRequest {
+ query: string
+}
+
+export interface ScoutPrecheckTestRun extends ScoutPrecheckTestRequest {
+ result: SignalScoutPrecheckTestApi
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutPrecheckLogicValues {
+ testRun: ScoutPrecheckTestRun | null
+ testRunFailed: boolean
+ testRunLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutPrecheckLogicActions {
+ clearTestRun: () => any
+ clearTestRunFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ clearTestRunSuccess: (
+ testRun: null,
+ payload?: any
+ ) => {
+ testRun: null
+ payload?: any
+ }
+ testPrecheck: ({ query }: ScoutPrecheckTestRequest) => ScoutPrecheckTestRequest
+ testPrecheckFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ testPrecheckSuccess: (
+ testRun: {
+ query: string
+ result: SignalScoutPrecheckTestApi
+ } | null,
+ payload?: ScoutPrecheckTestRequest
+ ) => {
+ testRun: {
+ query: string
+ result: SignalScoutPrecheckTestApi
+ } | null
+ payload?: ScoutPrecheckTestRequest
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutPrecheckLogicMeta {
+ key: string
+}
+
+export type scoutPrecheckLogicType = MakeLogicType<
+ scoutPrecheckLogicValues,
+ scoutPrecheckLogicActions,
+ ScoutPrecheckLogicProps,
+ scoutPrecheckLogicMeta
+>
+
+/**
+ * The "Test query" button of one scout's pre-check. It runs the query once with the `{since}` and
+ * `{now}` values of the next scheduled run, and starts no run and saves nothing.
+ */
+export const scoutPrecheckLogic = kea<scoutPrecheckLogicType>([
+ path((key) => ['scenes', 'inbox', 'logics', 'scoutPrecheckLogic', key]),
+ props({} as ScoutPrecheckLogicProps),
+ key((props) => props.configId),
+
+ loaders(({ props }) => ({
+ testRun: [
+ null as ScoutPrecheckTestRun | null,
+ {
+ testPrecheck: async ({ query }: ScoutPrecheckTestRequest, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return null
+ }
+ const result = await signalsScoutConfigPrecheckTest(String(teamId), props.configId, {
+ precheck_query: query,
+ })
+ // A second test can start while the first is in flight. Only the newest answers.
+ breakpoint()
+ return { query, result }
+ },
+ clearTestRun: () => null,
+ },
+ ],
+ })),
+
+ reducers({
+ testRunFailed: [
+ false,
+ {
+ testPrecheck: () => false,
+ testPrecheckSuccess: () => false,
+ testPrecheckFailure: () => true,
+ clearTestRun: () => false,
+ },
+ ],
+ }),
+
+ listeners(({ props }) => ({
+ testPrecheckSuccess: ({ testRun }) => {
+ if (!testRun) {
+ return
+ }
+ captureScoutAction({
+ actionType: 'test_precheck',
+ surface: props.surface,
+ skillName: props.skillName,
+ extra: {
+ would_run: testRun.result.would_run,
+ reason: testRun.result.reason,
+ row_count: testRun.result.row_count,
+ has_error: testRun.result.error !== null,
+ },
+ })
+ },
+ })),
+])