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): stop "Suggest a scout" starting a silent headless scan (#96368)

posthog[bot]f3939daee4b0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5bb2cf367a2c..368e62f7c488 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7871,15 +7871,23 @@ snapshots:
scenes-app-inbox-scoutsuggestionsstrip--never-generated--dark:
hash: v1.k794b7964.39e26f30989851080429efb281b4448ffc9039fee9bb5402186ed7fd2912dc26.3tfbUaa3WQw-wVGxNFvovrADZf_3m2_FkxluNoimVdc
scenes-app-inbox-scoutsuggestionsstrip--never-generated--light:
- hash: v1.k794b7964.7292410db6a6d174bc2a47f978e9a5ab116e81efad7c35373940e91c0fa03449.gvUgXCX89wlNP-GVito-ipUonxWW_O3iq41vunFAC4g
+ hash: v1.k794b7964.bda4b9761970b6db839d52bf095c11d998fb8ffa2f84d7d1238a6f9c163cf67a.lcKr8Ht7DMA4Bp8mxsEpQklK5iGtHrDEJrubiXQeTSk
scenes-app-inbox-scoutsuggestionsstrip--nothing-left--dark:
hash: v1.k794b7964.669e760714fe3acda90a90713fd40015a8eda10ee6aae7c7628d6820a18a520f.05GoZkCOgwfyr5N54RAer1SGyJIYQKB8D-7g_Cb5PD8
scenes-app-inbox-scoutsuggestionsstrip--nothing-left--light:
hash: v1.k794b7964.6132d08f6269e363d43e27e6908ce8c719099c00bcbf2dadd41516a2c474c85b.fzuFZjcwuJfMmZybduYCmSKdSu8nGl_udgCPRZcZobw
scenes-app-inbox-scoutsuggestionsstrip--scanning--dark:
- hash: v1.k794b7964.e849770feab5d46a037863d74c2ce37deca6fcec3677db1c434cc3406b22f8bc.rSRNUba302jNZkVQo0xYybhP4xAil1vHsS4ohtEJLrE
+ hash: v1.k794b7964.ea9137550bb6178ace0701c151ddbfb96995042a1fd2fee39b5e296f91aefff0.linffwBWJQGNxcbZoEEtTHjxBkAxvhRoZidzkx95dKQ
scenes-app-inbox-scoutsuggestionsstrip--scanning--light:
- hash: v1.k794b7964.d7c88ad16a6054b96d398ffd66af687768fed227ca65d1713474caa80db7d18e.rp4z_jMQ78IkiLAyyOp31jI3Rrh8AdwBVEOLH_2qaAc
+ hash: v1.k794b7964.4e32d9c94dab7dea8dc230f4849626be9c02492cbadc388f9f5e63402d25685a.0TgQOB_KdOjZNo_lB1Jz4JKCrHPX5FO1npJvQ_fIEQ0
+ scenes-app-inbox-scoutsuggestionsstrip--scanning-collapsed--dark:
+ hash: v1.k794b7964.2974c3ed95c84494b5c8747fbfcc7f715f81c6bce31911aa36315e3115fccf5b.602N2DaHAxZvPeNn7sTTYCu0GtWoNplWEMpbcuUcEMw
+ scenes-app-inbox-scoutsuggestionsstrip--scanning-collapsed--light:
+ hash: v1.k794b7964.a139550b807301e4832067850ad4527f7f0a25fc721995632b691454d6beb284.cwrpk5fZ1AaNGVJ6KV_U6-1MH77Jl6mrpuSpSc4phpo
+ scenes-app-inbox-scoutsuggestionsstrip--scanning-with-nothing-to-show--dark:
+ hash: v1.k794b7964.872fb6320825913b751e41be16585d7419b56498a04879bb676feb2d45956da7.C4BUY7TTxtlW3k1U-GrjmXwy2jZfou6hg_5EMSFFfa0
+ scenes-app-inbox-scoutsuggestionsstrip--scanning-with-nothing-to-show--light:
+ hash: v1.k794b7964.37e820ce174fc9fd70e27ccf6fc9b8654716abe4013f9e043372555e0ba9829b.XTmTK65QEbkaOkZUc5_2il2RqDeICc_p98_3qdRDBSA
scenes-app-inbox-scoutsuggestionsstrip--single-card--dark:
hash: v1.k794b7964.72c82855e6a294d35efdcb3651013f332876ca97d5669150a85ab591f5eed59a.aguVH00mJQ-54JxWvHdeMQle2S-qBC6CcpVy1bjyuBE
scenes-app-inbox-scoutsuggestionsstrip--single-card--light:
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx
index e41d88b4b668..81c26892e051 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.test.tsx
@@ -113,9 +113,34 @@ describe('scout creation buttons', () => {
logic.unmount()
})
+ // Reopening is local, so it must not wait on whatever else the header is starting. A separate
+ // test because the setup differs: this one needs a sibling task in flight.
+ it('reopens the closed strip while another header task is starting', async () => {
+ setSuggestionsFlag(true)
+ const logic = scoutSuggestionsLogic()
+ logic.mount()
+ await waitFor(() => expect(logic.values.hasPicks).toBe(true))
+ const { container, findByText, getByText } = render(<ScoutsRosterActions />)
+ logic.actions.hideStrip()
+ await findByText('Suggest a scout')
+
+ fireEvent.click(getByText('Ask'))
+ fireEvent.click(getByText('How is my scout troop performing?'))
+
+ // Read before the task resolves and clears the state, the same window the spinner lives in.
+ const reopen = container.querySelector<HTMLButtonElement>('[data-attr="scout-suggestions-show"]')
+ expect(reopen?.getAttribute('aria-disabled')).not.toBe('true')
+ expect(reopen?.querySelector('.Spinner')).toBeNull()
+ fireEvent.click(reopen!)
+
+ expect(logic.values.stripHidden).toBe(false)
+ await waitFor(() => expect(startedChatTypes).toEqual(['fleet_overview']))
+ logic.unmount()
+ })
+
// A project with no picks has no strip to reopen, so the header button is the only entry point
- // there. It has to be present, and it has to pay for a scan rather than open a chat.
- it('starts a scan from the header on a project with no picks', async () => {
+ // there. A headless scan would spend minutes with nothing on screen, so it opens the chat.
+ it('opens the authoring chat from the header on a project with no picks', async () => {
setSuggestionsFlag(true)
useMocks({
get: { '/api/projects/:team/signals/scout/suggestions/': mockScoutSuggestionSet({ items: [] }) },
@@ -129,14 +154,13 @@ describe('scout creation buttons', () => {
const logic = scoutSuggestionsLogic()
logic.mount()
const { findByText } = render(<ScoutsRosterActions />)
- // The button is busy until the batch is known, so a press before then costs no scan.
+ // The button is busy until the batch is known, so a press before then does nothing.
await waitFor(() => expect(logic.values.suggestionSet).not.toBeNull())
fireEvent.click(await findByText('Suggest a scout'))
- await waitFor(() => expect(refreshRequests).toBe(1))
- expect(logic.values.stripVisible).toBe(true)
- expect(startedChatTypes).toEqual([])
+ await waitFor(() => expect(startedChatTypes).toEqual(['author_scout']))
+ expect(refreshRequests).toBe(0)
logic.unmount()
})
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
index 3dd3ae85738b..2d5dd8678b5a 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
@@ -35,8 +35,14 @@ function StripState({
logic.actions.showStrip()
logic.actions.setCollapsed(collapsed)
if (refreshing) {
- logic.actions.requestRefresh()
+ const baseline = mockScoutSuggestionSet()
+ logic.actions.startRefreshPolling({
+ startedAt: Date.now(),
+ baselineGeneratedAt: baseline.generated_at,
+ baselineStatus: baseline.status,
+ })
}
+ return () => logic.actions.refreshFinished()
}, [logic, collapsed, refreshing])
return <>{children}</>
}
@@ -150,8 +156,21 @@ export const NothingLeft: Story = {
],
}
-// What the header button opens on a project with nothing to suggest: skeletons until the scan lands.
+// A scan over a batch that already has picks: they stay readable until it replaces them.
export const Scanning: Story = {
+ parameters: { stripRefreshing: true },
+ decorators: [mswDecorator({ get: { [SUGGESTIONS_URL]: () => [200, mockScoutSuggestionSet()] } })],
+}
+
+// The strip opens collapsed, so this is where most Refresh presses land: the picks stay named and
+// the scan says how long it has been going.
+export const ScanningCollapsed: Story = {
+ parameters: { stripCollapsed: true, stripRefreshing: true },
+ decorators: [mswDecorator({ get: { [SUGGESTIONS_URL]: () => [200, mockScoutSuggestionSet()] } })],
+}
+
+// The one case skeletons are left for: every pick was acted on while the scan ran.
+export const ScanningWithNothingToShow: Story = {
parameters: { stripRefreshing: true },
decorators: [
mswDecorator({
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.test.tsx
new file mode 100644
index 000000000000..89c87ee4a89b
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.test.tsx
@@ -0,0 +1,59 @@
+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { mockScoutSuggestionSet, mockScoutSuggestions } from '../../../__mocks__/scoutConfigs'
+import { scoutSuggestionsLogic } from '../../../logics/scoutSuggestionsLogic'
+import { ScoutSuggestionsStrip } from './ScoutSuggestionsStrip'
+
+describe('ScoutSuggestionsStrip', () => {
+ afterEach(cleanup)
+
+ function useSetupMocks(items: typeof mockScoutSuggestions): void {
+ useMocks({
+ get: {
+ '/api/projects/:team/signals/scout/configs/': [],
+ '/api/projects/:team/signals/scout/suggestions/': mockScoutSuggestionSet({ items }),
+ },
+ post: {
+ '/api/projects/:team/signals/scout/suggestions/refresh/': [200, { workflow_id: 'workflow-1' }],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SCOUTS_SUGGESTIONS_UI], {
+ [FEATURE_FLAGS.SCOUTS_SUGGESTIONS_UI]: true,
+ })
+ }
+
+ // The strip opens collapsed, so a press from the collapsed line is the common path for Refresh,
+ // not an edge case.
+ it('shows how the scan is going when Refresh is pressed from the collapsed line', async () => {
+ useSetupMocks(mockScoutSuggestions)
+ const { findByText, getByText } = render(<ScoutSuggestionsStrip />)
+ await findByText(/Watch signup drop-off by plan/)
+
+ fireEvent.click(getByText('Refresh'))
+
+ expect(await findByText(/less than a minute so far/)).toBeTruthy()
+ expect(getByText(/You can leave this page/)).toBeTruthy()
+ expect(getByText(/Watch signup drop-off by plan/)).toBeTruthy()
+ })
+
+ it('still says a scan is running when there are no picks left to name', async () => {
+ useSetupMocks([])
+ const logic = scoutSuggestionsLogic()
+ logic.mount()
+ await waitFor(() => expect(logic.values.suggestionSet).not.toBeNull())
+
+ const { findByText } = render(<ScoutSuggestionsStrip />)
+ act(() => logic.actions.requestRefresh('strip'))
+
+ expect(await findByText(/Scanning the project for new picks/)).toBeTruthy()
+ logic.unmount()
+ })
+})
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
index 3e732da2ceeb..25bb2b83db7d 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useEffect, useRef } from 'react'
import { IconChevronDown, IconRefresh, IconSparkles, IconX } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonSkeleton, Link, Spinner } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { cn } from 'lib/utils/css-classes'
@@ -61,7 +61,7 @@ export function ScoutSuggestionsStrip(): JSX.Element | null {
icon={<IconRefresh />}
loading={isRefreshing}
disabledReason={isRefreshing ? 'Scanning the project…' : undefined}
- onClick={() => requestRefresh()}
+ onClick={() => requestRefresh('strip')}
data-attr="scout-suggestions-refresh"
>
Refresh
@@ -90,19 +90,32 @@ export function ScoutSuggestionsStrip(): JSX.Element | null {
)
}
-/** Whichever of the strip's three states applies: collapsed, scanning, or the cards. */
+/** Whichever of the strip's states applies: collapsed, placeholders with nothing yet to read, or the cards. */
function StripBody(): JSX.Element {
const { suggestions, collapsed, batchStatus, isRefreshing, suggestionSetLoading } = useValues(scoutSuggestionsLogic)
if (collapsed) {
- return <CollapsedLine titles={suggestions.map((item) => item.title)} />
+ // The strip opens collapsed, so most Refresh presses land here. Without titles the strip is
+ // only up because a scan is running, so the note is all there is to show.
+ return (
+ <>
+ {suggestions.length > 0 && <CollapsedLine titles={suggestions.map((item) => item.title)} />}
+ {isRefreshing && <ScanningNote />}
+ </>
+ )
}
- if (isRefreshing || (suggestionSetLoading && suggestions.length === 0)) {
- return <SuggestionsSkeleton />
+ if (suggestions.length === 0 && (isRefreshing || suggestionSetLoading)) {
+ return (
+ <>
+ <SuggestionsSkeleton />
+ {isRefreshing && <ScanningNote />}
+ </>
+ )
}
return (
<>
<SuggestionGrid surface="strip" />
+ {isRefreshing && <ScanningNote />}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
{batchStatus === 'stale' && (
<span>
@@ -157,11 +170,21 @@ function SuggestionGrid({ surface, columns = 3 }: { surface: ScoutSuggestionSurf
)
}
+/** The picks a scan will replace are still on screen, so without this line a press looks ignored. */
+function ScanningNote(): JSX.Element {
+ const { refreshElapsedLabel } = useValues(scoutSuggestionsLogic)
+ return (
+ <div className="flex items-start gap-1.5 text-xs text-muted">
+ <Spinner className="mt-0.5 shrink-0" />
+ <span>
+ Scanning the project for new picks{refreshElapsedLabel ? `: ${refreshElapsedLabel}` : ''}. It usually
+ takes 2 to 5 minutes. You can leave this page. The new picks will be here when you come back.
+ </span>
+ </div>
+ )
+}
+
function CollapsedLine({ titles }: { titles: string[] }): JSX.Element {
- // The strip only stays up without titles while a scan runs, so that is what this line means.
- if (titles.length === 0) {
- return <span className="text-xs text-muted">Scanning the project…</span>
- }
const named = titles.slice(0, COLLAPSED_TITLE_PREVIEW).join(', ')
const rest = titles.length - COLLAPSED_TITLE_PREVIEW
return (
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx
index 53c909b8ef26..5133f458939c 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx
@@ -30,33 +30,28 @@ export function ScoutsRosterActions(): JSX.Element {
}
/**
- * Takes the "Suggest a scout" spot whenever the strip has no picks to show: it reopens a closed
- * strip, and on a project with none it starts a scan rather than opening a chat. It stays put while
- * that scan runs, because the empty-fleet state renders no strip whose skeletons could report it.
+ * Takes the "Suggest a scout" spot whenever the strip has no picks to show. With picks waiting it
+ * reopens the closed strip; with none it opens the authoring chat.
*/
function ShowSuggestionsButton(): JSX.Element | null {
const { suggestButtonVisible, hasPicks, isRefreshing, suggestionSetLoading, aiConsentDisabledReason } =
useValues(scoutSuggestionsLogic)
+ const { runningChatType } = useValues(scoutFleetLogic)
const { askForSuggestions } = useActions(scoutSuggestionsLogic)
+ // Opening the chat ends in a skill write, so it carries the editor gate. Reopening needs neither.
+ const creationDisabledReason = useScoutCreateDisabledReason()
if (!suggestButtonVisible) {
return null
}
- // Reopening a closed strip needs no scan, so the AI gate only applies when a press would pay
- // for one. The refresh endpoint refuses without consent, and a refusal reads as a failure.
- const busyReason = isRefreshing
- ? 'Scanning the project…'
- : suggestionSetLoading
- ? 'Reading the suggestions…'
- : hasPicks
- ? null
- : aiConsentDisabledReason
+ const busyReason = showSuggestionsBusyReason({ hasPicks, isRefreshing, suggestionSetLoading, runningChatType })
+ const gateReason = hasPicks ? null : (creationDisabledReason ?? aiConsentDisabledReason)
return (
<LemonButton
type="secondary"
size="small"
icon={<IconSparkles />}
loading={!!busyReason}
- disabledReason={busyReason ?? undefined}
+ disabledReason={busyReason ?? gateReason ?? undefined}
onClick={() => askForSuggestions()}
data-attr="scout-suggestions-show"
>
@@ -65,6 +60,38 @@ function ShowSuggestionsButton(): JSX.Element | null {
)
}
+function showSuggestionsBusyReason({
+ hasPicks,
+ isRefreshing,
+ suggestionSetLoading,
+ runningChatType,
+}: {
+ hasPicks: boolean
+ isRefreshing: boolean
+ suggestionSetLoading: boolean
+ runningChatType: ScoutChatType | null
+}): string | null {
+ // With picks waiting, the press only reopens the strip: no read, no task. Nothing else the
+ // header is doing holds that up, and every reason below would name work it never starts.
+ if (hasPicks) {
+ return null
+ }
+ if (suggestionSetLoading) {
+ return 'Reading the suggestions…'
+ }
+ // A scan already running is the answer to the press, so say so instead of opening a chat on top.
+ if (isRefreshing) {
+ return 'Scanning the project…'
+ }
+ if (runningChatType === 'author_scout') {
+ return 'Starting a task…'
+ }
+ if (runningChatType !== null) {
+ return 'Starting another task…'
+ }
+ return null
+}
+
/**
* The templated chat kickoffs, behind one button. As peers of "Create scout" they read as primary
* actions, which they aren't — each one navigates away to a task rather than changing anything here.
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index d5041b97068f..8a673272f84a 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -56,6 +56,7 @@ export const INBOX_EVENTS = {
SCOUT_SUGGESTION_CREATED: 'Scout suggestion created',
SCOUT_SUGGESTION_DISMISSED: 'Scout suggestion dismissed',
SCOUT_SUGGESTIONS_REFRESHED: 'Scout suggestions refreshed',
+ SCOUT_SUGGESTIONS_CHAT_OPENED: 'Scout suggestions chat opened',
RUN_OPENED: 'Inbox run opened',
ONBOARDING_DECIDED: 'Inbox onboarding decided',
} as const
@@ -828,8 +829,11 @@ export type ScoutSuggestionClickVia = 'button' | 'card'
/** How a suggestion became a scout: the create API in place, or a chat the person drove. */
export type ScoutSuggestionCreatedVia = 'api' | 'chat'
-/** How a refresh request ended, from the endpoint's answer. */
-export type ScoutSuggestionsRefreshOutcome = 'accepted' | 'running' | 'capped' | 'failed'
+/** How a refresh ended. All but `resumed` come from the endpoint; a resume sends no request at all. */
+export type ScoutSuggestionsRefreshOutcome = 'accepted' | 'running' | 'capped' | 'failed' | 'resumed'
+
+/** What put the scan on screen. Without it, a client resuming a paid scan reads as a refused duplicate. */
+export type ScoutSuggestionsRefreshSource = 'strip' | 'reload'
/**
* The suggestion batch as it was first rendered this visit. Without it a batch nobody acts on is
@@ -898,6 +902,17 @@ export function captureScoutSuggestionDismissed(params: {
}
/** A refresh was asked for, and what the endpoint said. Refreshes cost a scan, so the cap matters. */
-export function captureScoutSuggestionsRefreshed(params: { outcome: ScoutSuggestionsRefreshOutcome }): void {
- captureInboxEvent(INBOX_EVENTS.SCOUT_SUGGESTIONS_REFRESHED, { outcome: params.outcome })
+export function captureScoutSuggestionsRefreshed(params: {
+ outcome: ScoutSuggestionsRefreshOutcome
+ source: ScoutSuggestionsRefreshSource
+}): void {
+ captureInboxEvent(INBOX_EVENTS.SCOUT_SUGGESTIONS_REFRESHED, {
+ outcome: params.outcome,
+ source: params.source,
+ })
+}
+
+/** "Suggest a scout" opened the chat, having no picks to reopen. Separates cold start from refresh. */
+export function captureScoutSuggestionsChatOpened(params: { batchStatus: string }): void {
+ captureInboxEvent(INBOX_EVENTS.SCOUT_SUGGESTIONS_CHAT_OPENED, { batch_status: params.batchStatus })
}
diff --git a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
index adaae69a4497..f3743f43e6c0 100644
--- a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
@@ -201,22 +201,27 @@ describe('scoutSuggestionsLogic', () => {
expect(logic.values.stripVisible).toBe(false)
})
- // The header button is the entry point whenever the strip is off screen, so it has to cover
- // both reasons it can be: closed by the person, and empty because the project has no picks.
- it.each([
- ['pays for a scan when there is nothing to reopen', [] as ScoutSuggestionItemApi[], 1],
- ['only reopens the strip when picks are waiting', [CANONICAL_ITEM, CUSTOM_ITEM], 0],
- ])('the header button %s', async (_name, items, refreshCalls) => {
- await mountWithBatch(suggestionSet({ items }))
+ it('reopens the closed strip when picks are waiting, without paying for a scan', async () => {
+ await mountWithBatch()
logic.actions.hideStrip()
expect(logic.values.stripVisible).toBe(false)
logic.actions.askForSuggestions()
await expectLogic(logic).toFinishAllListeners()
- // Either way the strip is back on screen: with the picks, or with the scan's skeletons.
expect(logic.values.stripVisible).toBe(true)
- expect(mockRefresh).toHaveBeenCalledTimes(refreshCalls)
+ expect(mockRefresh).not.toHaveBeenCalled()
+ })
+
+ // A scan would take minutes with nothing on screen, so a project with no batch gets the chat.
+ it('opens the authoring chat instead of scanning when there is nothing to reopen', async () => {
+ await mountWithBatch(suggestionSet({ items: [] }))
+
+ await expectLogic(logic, () => logic.actions.askForSuggestions()).toDispatchActions([
+ scoutFleetLogic.actionTypes.startScoutChatTask,
+ ])
+
+ expect(mockRefresh).not.toHaveBeenCalled()
})
it('re-reads the batch instead of paying for a scan when the read never landed', async () => {
@@ -242,7 +247,7 @@ describe('scoutSuggestionsLogic', () => {
const toast = jest.spyOn(lemonToast, level as 'info' | 'error').mockReturnValue('toast-1')
await mountWithBatch()
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
await expectLogic(logic).toFinishAllListeners()
mockList.mockResolvedValue(suggestionSet({ ...(outcome as Partial<ScoutSuggestionSetApi>), items: [] }))
logic.actions.loadSuggestions()
@@ -331,8 +336,8 @@ describe('scoutSuggestionsLogic', () => {
it('sends one refresh request however often the button is pressed while it is out', async () => {
await mountWithBatch()
- logic.actions.requestRefresh()
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
+ logic.actions.requestRefresh('strip')
expect(logic.values.isRefreshing).toBe(true)
await expectLogic(logic).toFinishAllListeners()
@@ -344,17 +349,41 @@ describe('scoutSuggestionsLogic', () => {
await mountWithBatch()
mockRefresh.mockRejectedValueOnce(new ApiError('A refresh is already running for this project.', 409))
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.isRefreshing).toBe(true)
})
+ // A list request already out when the press lands can bring back the finished batch before the
+ // 409 does. The scan it waits on would then be measured against its own result.
+ it('measures the scan against the batch as of the press, not one that landed during the request', async () => {
+ await mountWithBatch()
+ let refuse: (error: ApiError) => void = () => {}
+ mockRefresh.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ refuse = reject
+ })
+ )
+
+ logic.actions.requestRefresh('strip')
+ mockList.mockResolvedValue(suggestionSet({ generated_at: '2026-09-03T00:00:00Z' }))
+ logic.actions.loadSuggestions()
+ await expectLogic(logic).toDispatchActions(['loadSuggestionsSuccess'])
+ refuse(new ApiError('A refresh is already running for this project.', 409))
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.loadSuggestions()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.isRefreshing).toBe(false)
+ })
+
it('does not wait for a scan the daily cap refused', async () => {
await mountWithBatch()
mockRefresh.mockRejectedValueOnce(new ApiError("You've reached today's limit.", 429))
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.isRefreshing).toBe(false)
@@ -363,7 +392,7 @@ describe('scoutSuggestionsLogic', () => {
it('keeps waiting when the row was already failed before the refresh', async () => {
await mountWithBatch(suggestionSet({ status: 'failed' }))
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
await expectLogic(logic).toFinishAllListeners()
logic.actions.loadSuggestions()
await expectLogic(logic).toFinishAllListeners()
@@ -375,7 +404,7 @@ describe('scoutSuggestionsLogic', () => {
it('stops waiting once the scan produces a newer batch', async () => {
await mountWithBatch()
- logic.actions.requestRefresh()
+ logic.actions.requestRefresh('strip')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.isRefreshing).toBe(true)
@@ -386,6 +415,40 @@ describe('scoutSuggestionsLogic', () => {
expect(logic.values.isRefreshing).toBe(false)
})
+ it('keeps the current picks readable while a scan runs, and says how long it has been going', async () => {
+ await mountWithBatch()
+
+ logic.actions.requestRefresh('strip')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.suggestions).toHaveLength(2)
+ expect(logic.values.refreshElapsedLabel).toEqual('less than a minute so far')
+
+ logic.actions.refreshTick(3 * 60_000)
+ expect(logic.values.refreshElapsedLabel).toEqual('3 min so far')
+ })
+
+ // The scan runs on the server for minutes, so a reload lands back here with it still going.
+ it('resumes a scan after a reload instead of sending a second request', async () => {
+ await mountWithBatch()
+ logic.actions.requestRefresh('strip')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockRefresh).toHaveBeenCalledTimes(1)
+
+ logic.unmount()
+ logic = scoutSuggestionsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.isRefreshing).toBe(true)
+ expect(mockRefresh).toHaveBeenCalledTimes(1)
+
+ mockList.mockResolvedValue(suggestionSet({ generated_at: '2026-09-03T00:00:00Z' }))
+ logic.actions.loadSuggestions()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.isRefreshing).toBe(false)
+ })
+
it('opens collapsed, closes with the cross, and comes back open', async () => {
await mountWithBatch()
expect(logic.values.collapsed).toBe(true)
diff --git a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.ts b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.ts
index 58b01ffa5f23..fcbf65f5a57e 100644
--- a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.ts
@@ -23,12 +23,13 @@ import {
captureScoutSuggestionClicked,
captureScoutSuggestionCreated,
captureScoutSuggestionDismissed,
+ captureScoutSuggestionsChatOpened,
captureScoutSuggestionsRefreshed,
captureScoutSuggestionsShown,
ScoutSuggestionKind,
ScoutSuggestionSurface,
} from '../inboxAnalytics'
-import type { ScoutChatType, ScoutSuggestionClickVia } from '../inboxAnalytics'
+import type { ScoutChatType, ScoutSuggestionClickVia, ScoutSuggestionsRefreshSource } from '../inboxAnalytics'
import type { ExistingScoutForSuggestion } from '../utils/scoutSuggestions'
import { scoutFleetLogic } from './scoutFleetLogic'
import type { SignalScoutConfig } from './scoutFleetLogic'
@@ -41,10 +42,29 @@ const REFRESH_POLL_INTERVAL_MS = 15_000
* both rather than giving up while the workflow is still allowed to finish.
*/
const REFRESH_POLL_TIMEOUT_MS = 60 * 60_000
+/** How often the elapsed line is redrawn. Minutes are the unit, so seconds-precision buys nothing. */
+const REFRESH_ELAPSED_TICK_MS = 10_000
+
+/**
+ * A scan this client is waiting on, persisted because the scan outlives the tab. The baseline is
+ * part of it: settling means the batch is no longer the one the scan started from, so a resumed
+ * wait needs the row as it was before the press, not as the first read after the reload finds it.
+ */
+export interface ScoutSuggestionsRefreshScan {
+ startedAt: number
+ baselineGeneratedAt: string | null
+ baselineStatus: string | null
+}
const suggestionKind = (item: ScoutSuggestionItemApi): ScoutSuggestionKind =>
item.kind === 'canonical' ? 'canonical' : 'custom'
+const scanFromBatch = (suggestionSet: ScoutSuggestionSetApi | null): ScoutSuggestionsRefreshScan => ({
+ startedAt: Date.now(),
+ baselineGeneratedAt: suggestionSet?.generated_at ?? null,
+ baselineStatus: suggestionSet?.status ?? null,
+})
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutSuggestionsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
@@ -62,9 +82,13 @@ export interface scoutSuggestionsLogicValues {
existing: ExistingScoutForSuggestion | null
item: ScoutSuggestionItemApi
} | null
+ expandedSuggestionId: string | null
hasPicks: boolean
hiddenSuggestionIds: string[]
isRefreshing: boolean
+ refreshElapsedLabel: string | null
+ refreshElapsedMs: number
+ refreshScan: ScoutSuggestionsRefreshScan | null
stripHidden: boolean
stripVisible: boolean
suggestButtonVisible: boolean
@@ -166,11 +190,14 @@ export interface scoutSuggestionsLogicActions {
refreshRequestRefused: () => {
value: true
}
+ refreshTick: (elapsedMs: number) => {
+ elapsedMs: number
+ }
reportSuggestionsShown: (surface: ScoutSuggestionSurface) => {
surface: ScoutSuggestionSurface
}
- requestRefresh: () => {
- value: true
+ requestRefresh: (source: ScoutSuggestionsRefreshSource) => {
+ source: ScoutSuggestionsRefreshSource
}
restoreSuggestion: (suggestionId: string) => {
suggestionId: string
@@ -181,8 +208,8 @@ export interface scoutSuggestionsLogicActions {
showStrip: () => {
value: true
}
- startRefreshPolling: () => {
- value: true
+ startRefreshPolling: (scan: ScoutSuggestionsRefreshScan) => {
+ scan: ScoutSuggestionsRefreshScan
}
suggestionActionFinished: (suggestionId: string) => {
suggestionId: string
@@ -215,6 +242,7 @@ export interface scoutSuggestionsLogicMeta {
isRefreshing: boolean
) => boolean
suggestButtonVisible: (hasPicks: boolean, suggestionsEnabled: boolean, stripHidden: boolean) => boolean
+ refreshElapsedLabel: (isRefreshing: boolean, refreshElapsedMs: number) => string | null
collapsed: (collapsedOverride: boolean | null) => boolean
}
}
@@ -228,8 +256,11 @@ export type scoutSuggestionsLogicType = MakeLogicType<
/**
* The pre-computed "Suggested for this project" batch: read it, act on one pick, or pay for a new
- * scan. A scheduled headless run writes the batch ahead of time, so unlike the "Suggest a scout"
- * chat there is nothing to wait for here.
+ * scan. A scheduled headless run writes the batch ahead of time, so reading the picks costs no wait.
+ *
+ * A scan does cost a wait, of minutes, so only the strip's Refresh starts one: the strip is where
+ * an existing batch stays readable while it runs. With no batch to refresh, "Suggest a scout"
+ * opens the authoring chat instead.
*
* The batch shrinks on its own — the read hides picks whose scout has since been turned on or
* created — so every surface has to look right with one card, and `stale` is the steady state
@@ -277,10 +308,11 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
closeCreateFromSuggestion: true,
askForSuggestions: true,
suggestionCreated: (item: ScoutSuggestionItemApi, surface: ScoutSuggestionSurface) => ({ item, surface }),
- requestRefresh: true,
+ requestRefresh: (source: ScoutSuggestionsRefreshSource) => ({ source }),
refreshRequestRefused: true,
refreshFinished: true,
- startRefreshPolling: true,
+ startRefreshPolling: (scan: ScoutSuggestionsRefreshScan) => ({ scan }),
+ refreshTick: (elapsedMs: number) => ({ elapsedMs }),
setCollapsed: (collapsed: boolean) => ({ collapsed }),
hideStrip: true,
showStrip: true,
@@ -347,6 +379,28 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
refreshFinished: () => false,
},
],
+ // Survives a reload, so the wait resumes instead of the request being sent a second time.
+ refreshScan: [
+ null as ScoutSuggestionsRefreshScan | null,
+ buildUserScopedPersistenceConfig(),
+ {
+ startRefreshPolling: (_, { scan }) => scan,
+ refreshFinished: () => null,
+ },
+ ],
+ refreshElapsedMs: [
+ 0,
+ {
+ refreshTick: (_, { elapsedMs }) => elapsedMs,
+ refreshFinished: () => 0,
+ },
+ ],
+ expandedSuggestionId: [
+ null as string | null,
+ {
+ toggleSuggestionExpanded: (state, { item }) => (state === item.id ? null : item.id),
+ },
+ ],
createFromSuggestion: [
null as { item: ScoutSuggestionItemApi; existing: ExistingScoutForSuggestion | null } | null,
{
@@ -435,6 +489,17 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
(hasPicks: boolean, suggestionsEnabled: boolean, stripHidden: boolean): boolean =>
suggestionsEnabled && (!hasPicks || stripHidden),
],
+ // Minutes, not seconds: a stopwatch on a five-minute wait nobody can hurry reads badly.
+ refreshElapsedLabel: [
+ (s) => [s.isRefreshing, s.refreshElapsedMs],
+ (isRefreshing: boolean, refreshElapsedMs: number): string | null => {
+ if (!isRefreshing) {
+ return null
+ }
+ const minutes = Math.floor(refreshElapsedMs / 60_000)
+ return minutes < 1 ? 'less than a minute so far' : `${minutes} min so far`
+ },
+ ],
collapsed: [
(s) => [s.collapsedOverride],
(collapsedOverride: boolean | null): boolean => collapsedOverride ?? true,
@@ -562,32 +627,41 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
actions.loadSuggestions()
return
}
- // With no picks on offer there is nothing to reopen, so the button pays for a scan.
- if (values.suggestions.length === 0) {
- actions.requestRefresh()
+ if (values.suggestions.length > 0) {
+ return
}
+ // Nothing to reopen, and a scan would take minutes with nothing on screen to read, so
+ // the press opens the chat. The scan stays behind Refresh, where picks fill the wait.
+ captureScoutSuggestionsChatOpened({ batchStatus: values.batchStatus })
+ actions.startScoutChatTask('author_scout', 'scout authoring task')
},
- requestRefresh: async () => {
+ requestRefresh: async ({ source }) => {
const teamId = values.currentTeamId
// The reducer already shows the button as busy; this non-reactive flag is what keeps a
- // second press, or a press during a running poll, from sending a second request.
- if (!teamId || cache.refreshInFlight || cache.refreshPolling) {
+ // second press from sending a second request. `refreshScan` covers a resumed scan too.
+ if (!teamId || cache.refreshInFlight || values.refreshScan) {
return
}
cache.refreshInFlight = true
+ // The baseline is the batch as of the press: a list response that lands during the
+ // request would otherwise become it, and a scan never settles against its own batch.
+ const scan = scanFromBatch(values.suggestionSet)
try {
await signalsScoutSuggestionsRefresh(String(teamId))
- captureScoutSuggestionsRefreshed({ outcome: 'accepted' })
- actions.startRefreshPolling()
+ captureScoutSuggestionsRefreshed({ outcome: 'accepted', source })
+ actions.startRefreshPolling(scan)
} catch (error) {
const apiError = error instanceof ApiError ? error : null
if (apiError?.status === 409) {
- // A scan is already running, which is the state the skeletons describe anyway.
- captureScoutSuggestionsRefreshed({ outcome: 'running' })
- actions.startRefreshPolling()
+ // A scan is already running, so wait on it rather than reporting a failure.
+ captureScoutSuggestionsRefreshed({ outcome: 'running', source })
+ actions.startRefreshPolling(scan)
return
}
- captureScoutSuggestionsRefreshed({ outcome: apiError?.status === 429 ? 'capped' : 'failed' })
+ captureScoutSuggestionsRefreshed({
+ outcome: apiError?.status === 429 ? 'capped' : 'failed',
+ source,
+ })
actions.refreshRequestRefused()
// The endpoint refuses for ordinary reasons — the daily cap, the org's AI setting,
// a quota — so its own message is the one worth showing.
@@ -596,13 +670,16 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
cache.refreshInFlight = false
}
},
- startRefreshPolling: () => {
- const generatedAtBefore = values.suggestionSet?.generated_at ?? null
- const statusBefore = values.suggestionSet?.status ?? null
- const startedAt = Date.now()
+ startRefreshPolling: ({ scan }) => {
+ cache.disposables.add(() => {
+ const tick = (): void => actions.refreshTick(Math.max(0, Date.now() - scan.startedAt))
+ tick()
+ const id = setInterval(tick, REFRESH_ELAPSED_TICK_MS)
+ return () => clearInterval(id)
+ }, 'suggestionsRefreshElapsed')
cache.disposables.add(() => {
const id = setInterval(() => {
- if (Date.now() - startedAt >= REFRESH_POLL_TIMEOUT_MS) {
+ if (Date.now() - scan.startedAt >= REFRESH_POLL_TIMEOUT_MS) {
// One last read, so a scan that landed while the tab was hidden shows up
// now rather than on the next visit.
actions.refreshFinished()
@@ -613,9 +690,6 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
}, REFRESH_POLL_INTERVAL_MS)
return () => clearInterval(id)
}, 'suggestionsRefreshPoll')
- cache.refreshBaselineGeneratedAt = generatedAtBefore
- cache.refreshBaselineStatus = statusBefore
- cache.refreshPolling = true
},
loadSuggestionsSuccess: ({ suggestionSet }) => {
if (!values.isRefreshing) {
@@ -625,8 +699,8 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
// the end of the wait rather than watching only for new items. A row that was already
// `failed` before the refresh is the old failure, not the new scan settling.
const settled =
- (suggestionSet?.generated_at ?? null) !== cache.refreshBaselineGeneratedAt ||
- (suggestionSet?.status === 'failed' && cache.refreshBaselineStatus !== 'failed')
+ (suggestionSet?.generated_at ?? null) !== (values.refreshScan?.baselineGeneratedAt ?? null) ||
+ (suggestionSet?.status === 'failed' && values.refreshScan?.baselineStatus !== 'failed')
if (!settled) {
return
}
@@ -645,8 +719,8 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
}
},
refreshFinished: () => {
- cache.refreshPolling = false
cache.disposables.dispose('suggestionsRefreshPoll')
+ cache.disposables.dispose('suggestionsRefreshElapsed')
},
setFeatureFlags: () => {
// Flags often resolve after the tab mounts, so the read is retried once the answer is
@@ -657,7 +731,19 @@ export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
},
})),
- afterMount(({ actions }) => {
+ afterMount(({ actions, values }) => {
actions.loadSuggestions()
+ const scan = values.refreshScan
+ if (!scan) {
+ return
+ }
+ // Resume from the persisted baseline. Pressing Refresh again would only earn a 409, which
+ // tells the person a scan is running through an error rather than through the strip.
+ if (Date.now() - scan.startedAt >= REFRESH_POLL_TIMEOUT_MS) {
+ actions.refreshFinished()
+ return
+ }
+ captureScoutSuggestionsRefreshed({ outcome: 'resumed', source: 'reload' })
+ actions.startRefreshPolling(scan)
}),
])