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.

33.4 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
import { teamLogic } from 'scenes/teamLogic'

import {
    signalsScoutSuggestionsDismiss,
    signalsScoutSuggestionsList,
    signalsScoutSuggestionsRefresh,
} from 'products/signals/frontend/generated/api'
import type { ScoutSuggestionItemApi, ScoutSuggestionSetApi } from 'products/signals/frontend/generated/api.schemas'
import { llmSkillsNameRetrieve } from 'products/skills/frontend/generated/api'

import type { SignalScoutConfigApi } from '../../generated/api.schemas'
import {
    captureScoutSuggestionClicked,
    captureScoutSuggestionCreated,
    captureScoutSuggestionDismissed,
    captureScoutSuggestionsChatOpened,
    captureScoutSuggestionsRefreshed,
    captureScoutSuggestionsShown,
    captureScoutSuggestionsStripClicked,
    ScoutSuggestionKind,
    ScoutSuggestionSurface,
} from '../inboxAnalytics'
import type { ScoutChatType, ScoutSuggestionClickVia, ScoutSuggestionsRefreshSource } from '../inboxAnalytics'
import type { ExistingScoutForSuggestion } from '../utils/scoutSuggestions'
import { scoutFleetLogic } from './scoutFleetLogic'
import type { ScoutChatRequest, SignalScoutConfig } from './scoutFleetLogic'

/** How often the list is re-read while a refresh scan runs. The scan takes minutes, not seconds. */
const REFRESH_POLL_INTERVAL_MS = 15_000
/**
 * When a scan has not landed by here, stop polling. The next visit reads whatever it produced. The
 * scan itself may run for up to 30 minutes and wait as long again for a worker, so this sits past
 * both rather than giving up while the workflow is still allowed to finish.
 */
export 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 {
    aiConsentDisabledReason: string | null // scoutFleetLogic
    runningChatType: ScoutChatType | null // scoutFleetLogic
    scoutChatDisabledReason: string | null // scoutFleetLogic
    scoutConfigs: SignalScoutConfig[] | null // scoutFleetLogic
    currentProjectId: number | string // teamLogic
    currentTeamId: number | null // teamLogic
    batchAgeHours: number | null
    batchStatus: string
    busySuggestionIds: string[]
    collapsed: boolean
    collapsedOverride: boolean | null
    createFromSuggestion: {
        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
    suggestionSet: ScoutSuggestionSetApi | null
    suggestionSetLoading: boolean
    suggestions: ScoutSuggestionItemApi[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutSuggestionsLogicActions {
    loadScoutConfigs: (_?: void | undefined) => void // scoutFleetLogic
    startScoutChatTask: (
        chatType: ScoutChatType,
        taskLabel: string,
        suggestionId?: string | undefined,
        request?: ScoutChatRequest | undefined
    ) => {
        chatType: ScoutChatType
        request: ScoutChatRequest | undefined
        suggestionId: string | undefined
        taskLabel: string
    } // scoutFleetLogic
    startScoutChatTaskFailure: () => {
        value: true
    } // scoutFleetLogic
    startScoutChatTaskSuccess: () => {
        value: true
    } // scoutFleetLogic
    updateScoutConfig: (
        configId: string,
        updates: import('products/signals/frontend/generated/api.schemas').PatchedSignalScoutConfigUpdateApi
    ) => {
        configId: string
        updates: import('products/signals/frontend/generated/api.schemas').PatchedSignalScoutConfigUpdateApi
    } // scoutFleetLogic
    askForSuggestions: () => {
        value: true
    }
    closeCreateFromSuggestion: () => {
        value: true
    }
    createFromSuggestionReady: (
        item: ScoutSuggestionItemApi,
        existing: ExistingScoutForSuggestion | null
    ) => {
        existing: ExistingScoutForSuggestion | null
        item: ScoutSuggestionItemApi
    }
    dismissSuggestion: (
        item: ScoutSuggestionItemApi,
        surface: ScoutSuggestionSurface
    ) => {
        item: ScoutSuggestionItemApi
        surface: ScoutSuggestionSurface
    }
    hideStrip: () => {
        value: true
    }
    loadSuggestions: (_: void) => void
    loadSuggestionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSuggestionsSuccess: (
        suggestionSet: ScoutSuggestionSetApi | null,
        payload?: void
    ) => {
        suggestionSet: ScoutSuggestionSetApi | null
        payload?: void
    }
    openCreateFromSuggestion: (
        item: ScoutSuggestionItemApi,
        surface: ScoutSuggestionSurface,
        via?: ScoutSuggestionClickVia
    ) => {
        item: ScoutSuggestionItemApi
        surface: ScoutSuggestionSurface
        via: ScoutSuggestionClickVia
    }
    refineSuggestionWithAi: (
        item: ScoutSuggestionItemApi,
        surface: ScoutSuggestionSurface
    ) => {
        item: ScoutSuggestionItemApi
        surface: ScoutSuggestionSurface
    }
    refreshFinished: () => {
        value: true
    }
    refreshRequestRefused: () => {
        value: true
    }
    refreshTick: (elapsedMs: number) => {
        elapsedMs: number
    }
    reportSuggestionsShown: (surface: ScoutSuggestionSurface) => {
        surface: ScoutSuggestionSurface
    }
    requestRefresh: (source: ScoutSuggestionsRefreshSource) => {
        source: ScoutSuggestionsRefreshSource
    }
    restoreSuggestion: (suggestionId: string) => {
        suggestionId: string
    }
    setCollapsed: (collapsed: boolean) => {
        collapsed: boolean
    }
    showStrip: () => {
        value: true
    }
    startRefreshPolling: (scan: ScoutSuggestionsRefreshScan) => {
        scan: ScoutSuggestionsRefreshScan
    }
    suggestionActionFinished: (suggestionId: string) => {
        suggestionId: string
    }
    suggestionCreated: (
        item: ScoutSuggestionItemApi,
        surface: ScoutSuggestionSurface,
        config: SignalScoutConfig
    ) => {
        config: SignalScoutConfigApi
        item: ScoutSuggestionItemApi
        surface: ScoutSuggestionSurface
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutSuggestionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        suggestions: (
            suggestionSet: ScoutSuggestionSetApi | null,
            hiddenSuggestionIds: string[],
            scoutConfigs: SignalScoutConfigApi[] | null
        ) => ScoutSuggestionItemApi[]
        batchStatus: (suggestionSet: ScoutSuggestionSetApi | null) => string
        batchAgeHours: (suggestionSet: ScoutSuggestionSetApi | null) => number | null
        hasPicks: (suggestions: ScoutSuggestionItemApi[]) => boolean
        stripVisible: (hasPicks: boolean, stripHidden: boolean, isRefreshing: boolean) => boolean
        suggestButtonVisible: (hasPicks: boolean, stripHidden: boolean) => boolean
        refreshElapsedLabel: (isRefreshing: boolean, refreshElapsedMs: number) => string | null
        collapsed: (collapsedOverride: boolean | null) => boolean
    }
}

export type scoutSuggestionsLogicType = MakeLogicType<
    scoutSuggestionsLogicValues,
    scoutSuggestionsLogicActions,
    Record<string, any>,
    scoutSuggestionsLogicMeta
>

/**
 * 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 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
 * rather than an error: any fleet change flips it, and the picks stay valid.
 */
export const scoutSuggestionsLogic = kea<scoutSuggestionsLogicType>([
    path(['products', 'signals', 'frontend', 'inbox', 'logics', 'scoutSuggestionsLogic']),
    connect(() => ({
        values: [
            scoutFleetLogic,
            ['scoutConfigs', 'aiConsentDisabledReason', 'scoutChatDisabledReason', 'runningChatType'],
            teamLogic,
            ['currentTeamId', 'currentProjectId'],
        ],
        actions: [
            scoutFleetLogic,
            [
                'updateScoutConfig',
                'loadScoutConfigs',
                'startScoutChatTask',
                'startScoutChatTaskSuccess',
                'startScoutChatTaskFailure',
            ],
        ],
    })),

    actions({
        dismissSuggestion: (item: ScoutSuggestionItemApi, surface: ScoutSuggestionSurface) => ({ item, surface }),
        createFromSuggestionReady: (item: ScoutSuggestionItemApi, existing: ExistingScoutForSuggestion | null) => ({
            item,
            existing,
        }),
        refineSuggestionWithAi: (item: ScoutSuggestionItemApi, surface: ScoutSuggestionSurface) => ({ item, surface }),
        restoreSuggestion: (suggestionId: string) => ({ suggestionId }),
        suggestionActionFinished: (suggestionId: string) => ({ suggestionId }),
        openCreateFromSuggestion: (
            item: ScoutSuggestionItemApi,
            surface: ScoutSuggestionSurface,
            via: ScoutSuggestionClickVia = 'button'
        ) => ({ item, surface, via }),
        closeCreateFromSuggestion: true,
        askForSuggestions: true,
        suggestionCreated: (
            item: ScoutSuggestionItemApi,
            surface: ScoutSuggestionSurface,
            config: SignalScoutConfig
        ) => ({
            item,
            surface,
            config,
        }),
        requestRefresh: (source: ScoutSuggestionsRefreshSource) => ({ source }),
        refreshRequestRefused: true,
        refreshFinished: true,
        startRefreshPolling: (scan: ScoutSuggestionsRefreshScan) => ({ scan }),
        refreshTick: (elapsedMs: number) => ({ elapsedMs }),
        setCollapsed: (collapsed: boolean) => ({ collapsed }),
        hideStrip: true,
        showStrip: true,
        reportSuggestionsShown: (surface: ScoutSuggestionSurface) => ({ surface }),
    }),

    loaders(({ actions, values }) => ({
        suggestionSet: [
            null as ScoutSuggestionSetApi | null,
            {
                loadSuggestions: async (_: void, breakpoint) => {
                    const teamId = values.currentTeamId
                    if (!teamId) {
                        return values.suggestionSet
                    }
                    try {
                        const set = await signalsScoutSuggestionsList(String(teamId))
                        breakpoint()
                        return set
                    } catch (error) {
                        // A member without resource-level scout access, or a stale project id left
                        // by a project switch, are expected — degrade to the empty batch instead of
                        // reporting them. Keeping the picks an earlier read returned would leave a
                        // strip whose every button is refused. Anything else, notably a 5xx, still
                        // throws so a real backend failure reaches error tracking.
                        if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {
                            // The strip can unmount before the refusal lands, and a loader that
                            // resolves into a dead store is what reports next.
                            breakpoint()
                            // Without access the scan's batch can never be read. End the wait here,
                            // because the success listener would read the empty batch as the scan's
                            // result and show a false toast, or poll until the timeout.
                            if (values.isRefreshing) {
                                actions.refreshFinished()
                            }
                            return null
                        }
                        throw error
                    }
                },
            },
        ],
    })),

    // Built lazily so the persisted key reads the project the logic actually mounts in, not
    // whichever one was current when this module first loaded.
    reducers(() => ({
        // Optimistic removal. The next read excludes a dismissed pick server-side, so this only has
        // to cover the gap between the press and that read.
        hiddenSuggestionIds: [
            [] as string[],
            {
                dismissSuggestion: (state, { item }) => (state.includes(item.id) ? state : [...state, item.id]),
                // Custom only: a canonical pick disappears through the enabled-config filter
                // below instead, so a failed enable puts its card back rather than losing it.
                suggestionCreated: (state, { item }) =>
                    item.kind === 'canonical' || state.includes(item.id) ? state : [...state, item.id],
                restoreSuggestion: (state, { suggestionId }) => state.filter((id) => id !== suggestionId),
                // The server is the truth about what is still on offer, so an id it no longer
                // returns needs no local hiding and the list stays the length of one visit.
                loadSuggestionsSuccess: (state, { suggestionSet }) =>
                    state.filter((id) => (suggestionSet?.items ?? []).some((item) => item.id === id)),
            },
        ],
        busySuggestionIds: [
            [] as string[],
            {
                dismissSuggestion: (state, { item }) => [...state, item.id],
                // A canonical pick reads the existing scout before its form opens; a draft opens at once.
                openCreateFromSuggestion: (state, { item }) =>
                    item.kind === 'canonical' ? [...state, item.id] : state,
                refineSuggestionWithAi: (state, { item }) => [...state, item.id],
                suggestionActionFinished: (state, { suggestionId }) => state.filter((id) => id !== suggestionId),
            },
        ],
        // True from the press until the scan settles, so the button shows loading while the request
        // itself is still out, not only once the poll starts.
        isRefreshing: [
            false,
            {
                requestRefresh: () => true,
                refreshRequestRefused: () => false,
                startRefreshPolling: () => true,
                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,
            {
                createFromSuggestionReady: (_, { item, existing }) => ({ item, existing }),
                closeCreateFromSuggestion: () => null,
                suggestionCreated: () => null,
            },
        ],
        // Null until someone touches the chevron, so the strip opens collapsed until they have an
        // opinion. Scoped to the user and project, so opening it here does not open it elsewhere.
        collapsedOverride: [
            null as boolean | null,
            buildUserScopedPersistenceConfig(),
            {
                setCollapsed: (_, { collapsed }) => collapsed,
                // Someone asking for the picks back wants to read them, not a collapsed line.
                showStrip: () => false,
            },
        ],
        // Closed outright with the cross. The "Suggest a scout" header button brings it back.
        stripHidden: [
            false,
            buildUserScopedPersistenceConfig(),
            {
                hideStrip: () => true,
                showStrip: () => false,
            },
        ],
    })),

    selectors({
        suggestions: [
            (s) => [s.suggestionSet, s.hiddenSuggestionIds, s.scoutConfigs],
            (
                suggestionSet: ScoutSuggestionSetApi | null,
                hiddenSuggestionIds: string[],
                scoutConfigs: SignalScoutConfig[] | null
            ): ScoutSuggestionItemApi[] => {
                // The same rule the read applies, but against the roster's own optimistically
                // patched configs: a scout that is on is no longer something to suggest.
                const enabled = new Set(
                    (scoutConfigs ?? []).filter((config) => config.enabled).map((config) => config.skill_name)
                )
                return (suggestionSet?.items ?? []).filter(
                    (item) => !hiddenSuggestionIds.includes(item.id) && !enabled.has(item.skill_name)
                )
            },
        ],
        batchStatus: [
            (s) => [s.suggestionSet],
            (suggestionSet: ScoutSuggestionSetApi | null): string => suggestionSet?.status ?? 'empty',
        ],
        batchAgeHours: [
            (s) => [s.suggestionSet],
            (suggestionSet: ScoutSuggestionSetApi | null): number | null =>
                suggestionSet?.generated_at
                    ? Math.max(0, Math.round(dayjs().diff(dayjs(suggestionSet.generated_at), 'hour', true) * 10) / 10)
                    : null,
        ],
        // Every suggestions surface reads this instead of the batch row. A batch with no picks left
        // — a scan that found nothing, picks all acted on, a scan that failed — has nothing to
        // show, so it must not put an empty box on the roster.
        hasPicks: [(s) => [s.suggestions], (suggestions: ScoutSuggestionItemApi[]): boolean => suggestions.length > 0],
        // A running scan keeps the strip up with its skeletons, so the person who pressed for one
        // watches it arrive rather than looking at a roster that ignored the press.
        stripVisible: [
            (s) => [s.hasPicks, s.stripHidden, s.isRefreshing],
            (hasPicks: boolean, stripHidden: boolean, isRefreshing: boolean): boolean =>
                !stripHidden && (hasPicks || isRefreshing),
        ],
        // The header's own entry point, which stays put while a scan runs: the empty-fleet state
        // renders no strip at all, so a button that hid itself on press would be the only feedback
        // the person got, and it would be feedback that the press did nothing.
        suggestButtonVisible: [
            (s) => [s.hasPicks, s.stripHidden],
            (hasPicks: boolean, stripHidden: boolean): boolean => !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,
        ],
    }),

    listeners(({ actions, values, cache }) => ({
        dismissSuggestion: async ({ item, surface }) => {
            const teamId = values.currentTeamId
            if (!teamId) {
                actions.suggestionActionFinished(item.id)
                return
            }
            try {
                await signalsScoutSuggestionsDismiss(String(teamId), item.id)
                // Reported once the server holds it, so a failed dismissal is not counted as one.
                captureScoutSuggestionDismissed({
                    suggestionId: item.id,
                    kind: suggestionKind(item),
                    skillName: item.skill_name,
                    surface,
                })
            } catch (error) {
                // A dismissal has no undo, so a failed one has to come back rather than quietly
                // disappear until the next read tells the person it was never hidden.
                actions.restoreSuggestion(item.id)
                lemonToast.error(
                    (error instanceof ApiError ? error.detail : null) ?? 'Could not dismiss that suggestion'
                )
            } finally {
                actions.suggestionActionFinished(item.id)
            }
        },
        refineSuggestionWithAi: async ({ item, surface }) => {
            captureScoutSuggestionClicked({
                suggestionId: item.id,
                kind: suggestionKind(item),
                skillName: item.skill_name,
                target: 'refine_with_ai',
                via: 'button',
                surface,
            })
            // The server builds the primed first turn from the stored draft, so the chat opens on
            // this suggestion instead of re-scanning the project from scratch. The card stays busy
            // until the task request settles, so a slow request cannot mint a second task.
            cache.refiningSuggestionId = item.id
            actions.startScoutChatTask('author_scout', 'scout authoring task', item.id)
        },
        startScoutChatTaskSuccess: () => {
            if (cache.refiningSuggestionId) {
                actions.suggestionActionFinished(cache.refiningSuggestionId)
                cache.refiningSuggestionId = null
            }
        },
        startScoutChatTaskFailure: () => {
            if (cache.refiningSuggestionId) {
                actions.suggestionActionFinished(cache.refiningSuggestionId)
                cache.refiningSuggestionId = null
            }
        },
        openCreateFromSuggestion: async ({ item, surface, via }) => {
            captureScoutSuggestionClicked({
                suggestionId: item.id,
                kind: suggestionKind(item),
                skillName: item.skill_name,
                target: item.kind === 'canonical' ? 'turn_on' : 'create',
                via,
                surface,
            })
            if (item.kind !== 'canonical') {
                actions.createFromSuggestionReady(item, null)
                return
            }
            // The form opens on the scout as it exists, so the person reads what it does before it
            // runs. Submitting then writes only its config, through the same update the roster uses.
            const config = values.scoutConfigs?.find((candidate) => candidate.skill_name === item.skill_name)
            const projectId = values.currentProjectId
            if (!config || typeof projectId !== 'number') {
                // The roster materializes the canonical fleet on open, so a missing row means the
                // sync has not landed yet rather than that the scout does not exist.
                lemonToast.error('This scout is still being set up on your project. Try again in a moment.')
                actions.loadScoutConfigs()
                actions.suggestionActionFinished(item.id)
                return
            }
            try {
                const skill = await llmSkillsNameRetrieve(String(projectId), item.skill_name)
                actions.createFromSuggestionReady(item, {
                    config,
                    description: skill.description,
                    body: skill.body,
                })
            } catch (error) {
                lemonToast.error(
                    (error instanceof ApiError ? error.detail : null) ??
                        'Could not load this scout. Try again in a moment.'
                )
            } finally {
                actions.suggestionActionFinished(item.id)
            }
        },
        suggestionCreated: ({ item, surface, config }) => {
            // Both one-click paths land here — turning a canonical scout on, and a custom draft
            // coming back from the create modal. A refinement chat only opens on the draft, so it
            // is a click, not a creation.
            captureScoutSuggestionCreated({
                suggestionId: item.id,
                configId: config.id,
                kind: suggestionKind(item),
                skillName: config.skill_name,
                via: 'api',
                surface,
            })
            actions.loadSuggestions()
        },
        // Only the strip's own buttons dispatch these. A remembered state comes back through
        // persistence, which dispatches no action, so a reload reports nothing.
        setCollapsed: ({ collapsed }) => {
            captureScoutSuggestionsStripClicked({
                target: collapsed ? 'collapse' : 'expand',
                count: values.suggestions.length,
                status: values.batchStatus,
            })
        },
        hideStrip: () => {
            captureScoutSuggestionsStripClicked({
                target: 'close',
                count: values.suggestions.length,
                status: values.batchStatus,
            })
        },
        reportSuggestionsShown: ({ surface }) => {
            captureScoutSuggestionsShown({
                count: values.suggestions.length,
                status: values.batchStatus,
                ageHours: values.batchAgeHours,
                collapsed: values.collapsed,
                surface,
            })
        },
        askForSuggestions: () => {
            actions.showStrip()
            // A read that never landed is not an empty batch, and a scan is paid for and daily
            // capped, so an unknown batch is re-read rather than scanned.
            if (values.suggestionSet === null) {
                actions.loadSuggestions()
                return
            }
            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 ({ source }) => {
            const teamId = values.currentTeamId
            // The reducer already shows the button as busy; this non-reactive flag is what keeps a
            // 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', source })
                actions.startRefreshPolling(scan)
            } catch (error) {
                const apiError = error instanceof ApiError ? error : null
                if (apiError?.status === 409) {
                    // 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',
                    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.
                if (source !== 'onboarding' || apiError?.status !== 403) {
                    lemonToast.error(apiError?.detail ?? 'Could not start a new scan')
                }
            } finally {
                cache.refreshInFlight = false
            }
        },
        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() - 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()
                        actions.loadSuggestions()
                        return
                    }
                    actions.loadSuggestions()
                }, REFRESH_POLL_INTERVAL_MS)
                return () => clearInterval(id)
            }, 'suggestionsRefreshPoll')
        },
        loadSuggestionsSuccess: ({ suggestionSet }) => {
            if (!values.isRefreshing) {
                return
            }
            // A scan that produced nothing still lands as a `failed` row, so treat any conclusion as
            // 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) !== (values.refreshScan?.baselineGeneratedAt ?? null) ||
                (suggestionSet?.status === 'failed' && values.refreshScan?.baselineStatus !== 'failed')
            if (!settled) {
                return
            }
            actions.refreshFinished()
            // The strip closes on an empty batch, so a scan that produced nothing would otherwise
            // just take the skeletons away and leave the person guessing what the press did. The
            // two outcomes are not the same: `failed` means the scan never finished, so it is
            // worth another press, while `empty` means it ran and found nothing.
            if (values.suggestions.length > 0) {
                return
            }
            if (suggestionSet?.status === 'failed') {
                lemonToast.error("That scan didn't finish. Try again in a moment.")
            } else {
                lemonToast.info('That scan found nothing new to suggest.')
            }
        },
        refreshFinished: () => {
            cache.disposables.dispose('suggestionsRefreshPoll')
            cache.disposables.dispose('suggestionsRefreshElapsed')
        },
    })),

    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)
    }),
])