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): keep the create-scout draft when leaving the modal (#91895)

posthog[bot]bd37e871f0ba
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx
index 5376b04599fe..7ec925f05e0b 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx
@@ -1,6 +1,5 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { useId } from 'react'
import {
LemonButton,
@@ -23,6 +22,7 @@ import {
ScoutCreateInitialValues,
ScoutCreateModalLogicProps,
scoutCreateModalLogic,
+ scoutCreateModalLogicKey,
} from '../../../logics/scoutCreateModalLogic'
import {
getScoutScheduleMode,
@@ -44,7 +44,7 @@ export interface ScoutCreateModalProps {
export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }: ScoutCreateModalProps): JSX.Element {
const redesign = useFeatureFlag('INBOX_REDESIGN')
- const logicKey = useId()
+ const logicKey = scoutCreateModalLogicKey(initialValues)
const formId = `scout-create-form-${logicKey}`
const logicProps: ScoutCreateModalLogicProps = { logicKey, initialValues, onClose, onCreated }
const logic = scoutCreateModalLogic(logicProps)
@@ -56,7 +56,8 @@ export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }:
scoutCreateFormTouches,
showScoutCreateFormErrors,
} = useValues(logic)
- const { resetScoutCreateForm, setScoutCreateDailyTime, setScoutCreateScheduleMode } = useActions(logic)
+ const { resetScoutCreateForm, resetMcpServersDefaulted, setScoutCreateDailyTime, setScoutCreateScheduleMode } =
+ useActions(logic)
const { timezone: projectTimezone } = useValues(teamLogic)
const scheduleMode = getScoutScheduleMode(scoutCreateForm.config)
@@ -65,6 +66,9 @@ export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }:
return
}
resetScoutCreateForm()
+ // Leaving the modal on purpose discards the draft, so clear the "servers defaulted" marker too.
+ // Otherwise its persisted `true` would make the next open skip the all-servers default.
+ resetMcpServersDefaulted()
onClose()
}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx
index 35369f6cf20b..9f80c2e0a901 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx
@@ -1,4 +1,4 @@
-import React from 'react'
+import React, { useEffect } from 'react'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
@@ -38,6 +38,15 @@ export function ScoutCreateModalHost({
onClose,
onCreated,
}: ScoutCreateModalHostProps): JSX.Element | null {
+ const isOpen = initialValues !== null
+ // Open is the top of the create funnel. Without it only a successful create was captured, so an
+ // abandoned draft was invisible and the abandonment could not be sized.
+ useEffect(() => {
+ if (isOpen) {
+ captureScoutAction({ actionType: 'open_create_modal', surface: 'fleet_list' })
+ }
+ }, [isOpen])
+
if (!initialValues) {
return null
}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx
index f19508ae8420..bfb44c070591 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx
@@ -113,8 +113,10 @@ function FullPicker(props: ScoutMcpServersPickerProps): JSX.Element {
<div className="min-w-0">
<div className="font-medium text-sm text-default">No MCP servers shared with the team yet</div>
<p className="text-xs text-secondary mt-0.5 mb-0">
- <Link to={urls.mcpGateway()}>Share an MCP server with the team</Link> to give scouts external
- tools.
+ <Link to={urls.mcpGateway()} target="_blank">
+ Share an MCP server with the team
+ </Link>{' '}
+ to give scouts external tools.
</p>
</div>
</div>
@@ -164,6 +166,7 @@ function FullPicker(props: ScoutMcpServersPickerProps): JSX.Element {
)}
<Link
to={urls.mcpGateway()}
+ target="_blank"
className="group flex items-center justify-between gap-3 border-t border-primary px-3 py-2 text-xs no-underline transition-colors hover:bg-bg-3000"
>
<span className="text-secondary group-hover:text-default">Share more MCP servers</span>
@@ -196,7 +199,9 @@ function CompactPicker(props: ScoutMcpServersPickerProps): JSX.Element {
<span className="text-xs text-default">MCP servers</span>
<span className="text-[11.5px] text-muted">
Choose which of the team's shared MCP servers this scout can use.{' '}
- <Link to={urls.mcpGateway()}>Manage MCP servers</Link>
+ <Link to={urls.mcpGateway()} target="_blank">
+ Manage MCP servers
+ </Link>
</span>
</div>
{state.initialLoading ? (
@@ -205,7 +210,10 @@ function CompactPicker(props: ScoutMcpServersPickerProps): JSX.Element {
</span>
) : state.visibleServers.length === 0 ? (
<span className="text-[11.5px] text-muted">
- <Link to={urls.mcpGateway()}>Share an MCP server with the team</Link> to give scouts external tools.
+ <Link to={urls.mcpGateway()} target="_blank">
+ Share an MCP server with the team
+ </Link>{' '}
+ to give scouts external tools.
</span>
) : (
<div className="flex flex-col gap-1.5">
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 1d5714bccaef..75e5bf4bea90 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -173,6 +173,7 @@ export type ScoutActionType =
| 'copy_finding_link'
| 'open_task_run'
| 'open_linked_report'
+ | 'open_create_modal'
| 'create_scout'
| 'delete_scout'
| 'open_memory'
diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
index 969a84117f77..3a6d81d077a2 100644
--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
@@ -17,7 +17,7 @@ import { signalsScoutCreate } from 'products/signals/frontend/generated/api'
import type { SignalScoutCreateResponseApi } from 'products/signals/frontend/generated/api.schemas'
import { SCOUT_DAILY_AT_SCHEDULE_MODE } from '../utils/scoutRunsWindow'
-import { ScoutCreateModalLogicProps, scoutCreateModalLogic } from './scoutCreateModalLogic'
+import { ScoutCreateModalLogicProps, scoutCreateModalLogic, scoutCreateModalLogicKey } from './scoutCreateModalLogic'
jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutCreate: jest.fn(),
@@ -111,6 +111,8 @@ describe('scoutCreateModalLogic', () => {
let onCreated: jest.MockedFunction<NonNullable<ScoutCreateModalLogicProps['onCreated']>>
beforeEach(() => {
+ // The draft is persisted to localStorage; clear it so one test's draft can't leak into another.
+ localStorage.clear()
initKeaTests()
// The prefix-in-the-field form is part of the inbox redesign; the legacy contract is pinned below.
setRedesignFlag(true)
@@ -223,6 +225,43 @@ describe('scoutCreateModalLogic', () => {
prefilled.unmount()
})
+ it('clears the servers-defaulted marker on create so the next open re-applies the default', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () =>
+ scoutAccountResponse([teamServer('github-id', 'GitHub'), teamServer('linear-id', 'Linear')]),
+ },
+ })
+ mockSignalsScoutCreate.mockResolvedValue(CREATED_SCOUT)
+
+ const logicKey = scoutCreateModalLogicKey(undefined)
+ logic = scoutCreateModalLogic({ logicKey, onClose, onCreated })
+ logic.mount()
+ // The team's servers load, so the default is applied and the marker is set.
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.mcpServersDefaulted).toBe(true)
+ expect(logic.values.scoutCreateForm.config.mcp_gateway_server_ids).toEqual(['github-id', 'linear-id'])
+
+ logic.actions.setScoutCreateFormValue('name', 'checkout-failures')
+ logic.actions.setScoutCreateFormValue('description', 'Investigates recurring checkout failures.')
+ logic.actions.setScoutCreateFormValue(
+ 'body',
+ 'Inspect checkout failure signals and report meaningful regressions.'
+ )
+ await expectLogic(logic, () => logic.actions.submitScoutCreateForm()).toFinishAllListeners()
+ // A successful create discards the draft, so the marker resets to its initial value.
+ expect(logic.values.mcpServersDefaulted).toBe(false)
+ logic.unmount()
+
+ // The next blank open re-applies the all-servers default instead of opening with every server off.
+ const reopened = scoutCreateModalLogic({ logicKey, onClose })
+ reopened.mount()
+ await expectLogic(reopened).toFinishAllListeners()
+ expect(reopened.values.mcpServersDefaulted).toBe(true)
+ expect(reopened.values.scoutCreateForm.config.mcp_gateway_server_ids).toEqual(['github-id', 'linear-id'])
+ reopened.unmount()
+ })
+
it('submits a daily run time as a project-timezone cron schedule', async () => {
mockSignalsScoutCreate.mockResolvedValue(CREATED_SCOUT)
logic = scoutCreateModalLogic({
@@ -367,6 +406,74 @@ describe('scoutCreateModalLogic', () => {
)
})
+ it('restores a persisted draft when reopened under the same key', async () => {
+ logic = scoutCreateModalLogic({ logicKey: scoutCreateModalLogicKey(undefined), onClose })
+ logic.mount()
+ logic.actions.setScoutCreateFormValue('body', 'Watch checkout latency and report spikes.')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.scoutCreateFormChanged).toBe(true)
+ logic.unmount()
+
+ // A fresh instance under the same key is what a remount after navigating away looks like.
+ const reopened = scoutCreateModalLogic({ logicKey: scoutCreateModalLogicKey(undefined), onClose })
+ reopened.mount()
+ expect(reopened.values.scoutCreateForm.body).toBe('Watch checkout latency and report spikes.')
+ // The changed flag must restore with the draft, or the modal's unsaved-input guard would be
+ // off and one backdrop click would silently discard the restored draft.
+ expect(reopened.values.scoutCreateFormChanged).toBe(true)
+ reopened.unmount()
+ })
+
+ it('does not restore a persisted draft after switching to another project', async () => {
+ const logicKey = scoutCreateModalLogicKey(undefined)
+ const first = scoutCreateModalLogic({ logicKey, onClose })
+ first.mount()
+ first.actions.setScoutCreateFormValue('body', 'Watch checkout latency and report spikes.')
+ await expectLogic(first).toFinishAllListeners()
+ first.unmount()
+
+ // Switching project reloads the app under a different team. localStorage is not cleared here,
+ // unlike in beforeEach, so the first project's draft is still stored. The draft is scoped to
+ // the project it was written in, so it must not restore under another project.
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, id: MOCK_TEAM_ID + 1 })
+ logic = scoutCreateModalLogic({ logicKey, onClose })
+ logic.mount()
+ expect(logic.values.scoutCreateForm.body).toBe('')
+ })
+
+ it.each([
+ [undefined, 'new'],
+ [{}, 'new'],
+ [{ name: 'signals-scout-ai-observability-daily-digest' }, 'signals-scout-ai-observability-daily-digest'],
+ ])('keys the draft per opening context: %p', (initialValues, expectedKey) => {
+ expect(scoutCreateModalLogicKey(initialValues)).toBe(expectedKey)
+ })
+
+ it('keys a name-less template draft apart from the blank create form', () => {
+ // A deep-link template can prefill a description and body but carry no valid name. Keying on
+ // name alone would put it in the blank form's 'new' slot, so a restored draft from one context
+ // would clobber the other. Each context must get its own key.
+ const blankKey = scoutCreateModalLogicKey({})
+ const templateKey = scoutCreateModalLogicKey({
+ description: 'Investigates recurring checkout failures.',
+ body: 'Inspect checkout failure signals and report meaningful regressions.',
+ })
+ const otherTemplateKey = scoutCreateModalLogicKey({
+ description: 'Watches signup latency.',
+ body: 'Report signup latency spikes.',
+ })
+
+ expect(templateKey).not.toBe(blankKey)
+ expect(templateKey).not.toBe(otherTemplateKey)
+ // The same payload keys the same slot, so a template keeps its own draft across a remount.
+ expect(
+ scoutCreateModalLogicKey({
+ description: 'Investigates recurring checkout failures.',
+ body: 'Inspect checkout failure signals and report meaningful regressions.',
+ })
+ ).toBe(templateKey)
+ })
+
// With the redesign flag off the field holds the whole skill name, so the prefix must be typed.
describe('with the redesign flag off', () => {
beforeEach(() => setRedesignFlag(false))
diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts
index 618894e315a8..3b99cf80ed8e 100644
--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts
@@ -8,6 +8,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api-error'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
+import { hashCodeForString } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import type { MCPServiceAccountServerApi } from 'products/mcp_store/frontend/generated/api.schemas'
@@ -95,6 +97,29 @@ export function getScoutCreateFormValues(
}
}
+/**
+ * A stable logic key per opening context. The blank create form gets one draft; each prefilled
+ * template keeps its own. The draft is persisted keyed by this, so it must not change between mounts
+ * of the same context — `useId()` would mint a new key each mount and lose the draft.
+ */
+export function scoutCreateModalLogicKey(initialValues: ScoutCreateInitialValues | undefined): string {
+ const name = initialValues?.name?.trim()
+ if (name) {
+ return name
+ }
+ const description = initialValues?.description?.trim()
+ const body = initialValues?.body?.trim()
+ if (description || body) {
+ // A prefilled template can omit a valid name, because the deep-link decoder drops an invalid
+ // one. Keying on name alone then returns 'new' for that template, the same key the blank
+ // create form uses, so their persisted drafts share one slot and each overwrites the other.
+ // Key a name-less prefill by a stable hash of its content instead, so every opening context
+ // keeps its own draft. Hash the two fields apart so a description/body split cannot collide.
+ return `template-${hashCodeForString(description ?? '')}-${hashCodeForString(body ?? '')}`
+ }
+ return 'new'
+}
+
/**
* The skill name a form entry produces: the fixed prefix plus what was typed. A pasted full name
* (`signals-scout-foo`) is not doubled up.
@@ -166,6 +191,9 @@ export interface scoutCreateModalLogicActions {
markMcpServersDefaulted: () => {
value: true
}
+ resetMcpServersDefaulted: () => {
+ value: true
+ }
resetScoutCreateForm: (values?: ScoutCreateFormValues) => {
values?: ScoutCreateFormValues
}
@@ -239,13 +267,22 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = ke
setScoutCreateScheduleMode: (scheduleMode: string) => ({ scheduleMode }),
setScoutCreateDailyTime: (dailyTime: string) => ({ dailyTime }),
markMcpServersDefaulted: true,
+ resetMcpServersDefaulted: true,
}),
reducers(({ props: logicProps }) => ({
- // A caller that passes explicit server ids opts out of the "all servers" default.
+ // A caller that passes explicit server ids opts out of the "all servers" default. Persisted
+ // alongside the draft so a restored draft keeps the user's server selection, rather than the
+ // "all servers" default re-applying on the next open. Scoped to the user and project so the
+ // marker cannot suppress another project's default selection. Discarding the draft resets it
+ // to the initial value, so the next open re-applies the default rather than opening with every
+ // server switched off. The defaulting subscription calls `resetScoutCreateForm`, so the reset
+ // is a separate action rather than tied to the form reset.
mcpServersDefaulted: [
logicProps.initialValues?.config?.mcp_gateway_server_ids !== undefined,
+ buildUserScopedPersistenceConfig(),
{
markMcpServersDefaulted: () => true,
+ resetMcpServersDefaulted: () => logicProps.initialValues?.config?.mcp_gateway_server_ids !== undefined,
},
],
})),
@@ -296,6 +333,7 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = ke
})
actions.resetScoutCreateForm()
+ actions.resetMcpServersDefaulted()
lemonToast.success(
scout.created ? 'Scout created' : 'Scout already exists. Its settings were updated.'
)
@@ -315,6 +353,19 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = ke
},
},
})),
+ // Persist the draft so it survives navigating away or reloading. kea-localstorage keys it by the
+ // logic path plus the logic key, so each opening context keeps its own draft (see
+ // `scoutCreateModalLogicKey`). Scope the key to the user and project so a draft from one project
+ // cannot restore in another and submit that project's server or integration ids to the wrong one.
+ // The default and handlers already come from the form above; this only attaches the persistence
+ // option to those same reducers. Persist the changed flag alongside the draft, and with the same
+ // scope, so a restored draft keeps the unsaved-input guard. kea-forms resets the flag to false on
+ // a fresh mount, so without this a restored draft would open unguarded and one backdrop click
+ // would discard it.
+ reducers(() => ({
+ scoutCreateForm: [DEFAULT_SCOUT_CREATE_FORM_VALUES, buildUserScopedPersistenceConfig(), {}],
+ scoutCreateFormChanged: [false, buildUserScopedPersistenceConfig(), {}],
+ })),
// The team's servers load asynchronously, so the default is applied once they arrive
// rather than in the form defaults. Applying it once keeps a later reload from
// re-selecting servers the user switched off.