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(replay-vision): send base_version when saving scout instructions (#101288)

posthog[bot]25749374342b
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts
index ac92b322a8cc..d16f9c0b952e 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts
@@ -2,11 +2,16 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { hogFunctionsPartialUpdate, hogFunctionsRetrieve } from 'products/cdp/frontend/generated/api'
+import {
+ hogFunctionsCreate,
+ hogFunctionsPartialUpdate,
+ hogFunctionsRetrieve,
+} from 'products/cdp/frontend/generated/api'
import { signalsScoutConfigDestroy, signalsScoutConfigUpdate } from 'products/signals/frontend/generated/api'
import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'
import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'
-import { llmSkillsNamePartialUpdate } from 'products/skills/frontend/generated/api'
+import { scoutDisplayName } from 'products/signals/frontend/inbox/utils/scoutRunsWindow'
+import { llmSkillsNamePartialUpdate, llmSkillsNameRetrieve } from 'products/skills/frontend/generated/api'
import {
visionScannersScoutReportsList,
@@ -30,6 +35,8 @@ const mockScoutConfigDestroy = signalsScoutConfigDestroy as jest.MockedFunction<
const mockScoutsCreate = visionScannersScoutsCreate as jest.MockedFunction<typeof visionScannersScoutsCreate>
const mockHogFunctionsRetrieve = hogFunctionsRetrieve as jest.MockedFunction<typeof hogFunctionsRetrieve>
const mockHogFunctionsPartialUpdate = hogFunctionsPartialUpdate as jest.MockedFunction<typeof hogFunctionsPartialUpdate>
+const mockSkillRetrieve = llmSkillsNameRetrieve as jest.MockedFunction<typeof llmSkillsNameRetrieve>
+const mockHogFunctionsCreate = hogFunctionsCreate as jest.MockedFunction<typeof hogFunctionsCreate>
const SCANNER_ID = '01a014ea-854f-72b5-8192-bb6ac9f212a5'
const SKILL_NAME = 'signals-scout-daily-digest'
@@ -101,7 +108,7 @@ describe('scannerScoutLogic', () => {
scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
logic.actions.openScoutSettings(SKILL_NAME)
await expectLogic(logic).toFinishAllListeners()
- logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.' })
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
jest.mocked(signalsScoutConfigUpdate).mockResolvedValue({ ...config, display_name: 'Checkout / daily digest' })
logic.actions.saveScoutSettings({
@@ -121,6 +128,376 @@ describe('scannerScoutLogic', () => {
expect(logic.values.settingsSkillName).toBeNull()
})
+ it('publishes edited instructions against the version the form was loaded at', async () => {
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: {} })
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
+ jest.mocked(llmSkillsNamePartialUpdate).mockResolvedValue({ body: 'Watch checkout.', version: 4 } as any)
+
+ logic.actions.saveScoutSettings({
+ name: scoutDisplayName(config),
+ body: 'Watch checkout.',
+ cron: config.run_cron_schedule!,
+ outputDestinations: {},
+ webhookUrl: '',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(llmSkillsNamePartialUpdate).toHaveBeenCalledWith(expect.any(String), SKILL_NAME, {
+ body: 'Watch checkout.',
+ base_version: 3,
+ })
+ expect(logic.values.skillPrompt).toEqual({ skillName: SKILL_NAME, body: 'Watch checkout.', latestVersion: 4 })
+ })
+
+ it('keeps the rename and the delivery when the instructions fail to publish', async () => {
+ // The instructions PATCH is the only call here a concurrent edit can reject. Running it
+ // before the others hands the rejection every other edit made in the same modal.
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: {} })
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
+ jest.mocked(signalsScoutConfigUpdate).mockResolvedValue({ ...config, display_name: 'Checkout / daily digest' })
+ mockHogFunctionsCreate.mockResolvedValue({ id: 'hog-new' } as any)
+ jest.mocked(llmSkillsNamePartialUpdate).mockRejectedValue({ status: 409 })
+ mockSkillRetrieve.mockResolvedValue({
+ body: 'Watch this scanner.',
+ body_total_length: 'Watch this scanner.'.length,
+ body_next_offset: null,
+ version: 4,
+ latest_version: 4,
+ } as any)
+
+ logic.actions.saveScoutSettings({
+ name: 'Checkout / daily digest',
+ body: 'Watch checkout.',
+ cron: config.run_cron_schedule!,
+ outputDestinations: {},
+ webhookUrl: 'https://example.com/hooks/scout',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(signalsScoutConfigUpdate).toHaveBeenCalledWith(expect.any(String), config.id, {
+ display_name: 'Checkout / daily digest',
+ })
+ expect(mockHogFunctionsCreate).toHaveBeenCalled()
+ expect(logic.values.settingsSkillName).toBe(SKILL_NAME)
+ })
+
+ it('keeps the draft and moves to the current version when the instructions conflict', async () => {
+ // The retry publishes against the version that rejected the first save.
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: { webhook: null } })
+ const revised = 'Watch this scanner, revised elsewhere.'
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
+ jest.mocked(signalsScoutConfigUpdate).mockResolvedValue({
+ ...config,
+ display_name: 'Checkout / daily digest',
+ run_cron_schedule: '0 7 * * *',
+ })
+ jest.mocked(llmSkillsNamePartialUpdate).mockRejectedValue({ status: 409 })
+ mockSkillRetrieve.mockResolvedValue({
+ body: revised,
+ body_total_length: revised.length,
+ body_next_offset: null,
+ version: 5,
+ latest_version: 5,
+ } as any)
+
+ logic.actions.saveScoutSettings({
+ name: 'Checkout / daily digest',
+ body: 'Watch checkout.',
+ cron: '0 7 * * *',
+ outputDestinations: { webhook: null },
+ webhookUrl: '',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.settingsSkillName).toBe(SKILL_NAME)
+ expect(logic.values.skillPrompt).toEqual({ skillName: SKILL_NAME, body: revised, latestVersion: 5 })
+ const saved = logic.values.scoutConfigsForScanner[0]
+ expect(scoutDisplayName(saved)).toBe('Checkout / daily digest')
+ expect(saved.run_cron_schedule).toBe('0 7 * * *')
+
+ jest.mocked(signalsScoutConfigUpdate).mockClear()
+ jest.mocked(llmSkillsNamePartialUpdate).mockResolvedValue({ body: 'Watch checkout.', version: 6 } as any)
+ logic.actions.saveScoutSettings({
+ name: scoutDisplayName(saved),
+ body: 'Watch checkout.',
+ cron: saved.run_cron_schedule!,
+ outputDestinations: saved.output_destinations ?? {},
+ webhookUrl: '',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(llmSkillsNamePartialUpdate).toHaveBeenLastCalledWith(expect.any(String), SKILL_NAME, {
+ body: 'Watch checkout.',
+ base_version: 5,
+ })
+ expect(signalsScoutConfigUpdate).not.toHaveBeenCalled()
+ })
+
+ it('publishes the instructions even when the delivery cannot be reconciled', async () => {
+ // A scout that already delivers pays a destination read and write on every save, whether or
+ // not the delivery changed. Data pipelines failing there must not hold back an edit that
+ // only touched the instructions, or an outage on that destination blocks them all.
+ await mountWithReports([])
+ const config = makeConfig()
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ mockHogFunctionsRetrieve.mockResolvedValue({
+ id: WEBHOOK_ID,
+ name: 'Replay Vision · Rage clicks on checkout',
+ deleted: false,
+ template: { id: 'template-webhook' },
+ filters: {
+ events: [{ id: '$scout_report_emitted' }],
+ properties: [{ key: 'skill_name', value: SKILL_NAME }],
+ },
+ inputs: { url: { value: 'https://example.com/hooks/scout' } },
+ } as any)
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
+ mockHogFunctionsPartialUpdate.mockRejectedValue({ status: 503 })
+ jest.mocked(llmSkillsNamePartialUpdate).mockResolvedValue({ body: 'Watch checkout.', version: 4 } as any)
+
+ // Only the instructions changed; every other field is what the scout already holds.
+ logic.actions.saveScoutSettings({
+ name: scoutDisplayName(config),
+ body: 'Watch checkout.',
+ cron: config.run_cron_schedule!,
+ outputDestinations: config.output_destinations ?? {},
+ webhookUrl: 'https://example.com/hooks/scout',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(llmSkillsNamePartialUpdate).toHaveBeenCalledWith(expect.any(String), SKILL_NAME, {
+ body: 'Watch checkout.',
+ base_version: 3,
+ })
+ expect(logic.values.skillPrompt).toEqual({ skillName: SKILL_NAME, body: 'Watch checkout.', latestVersion: 4 })
+ // The delivery failure is still the user's to deal with, so the form stays open.
+ expect(logic.values.settingsSkillName).toBe(SKILL_NAME)
+ })
+
+ it('refuses the save when the loaded instructions belong to another scout', async () => {
+ // Nothing here can tell an edited body from an unchanged one without this scout's own
+ // prompt. Saving the rest anyway drops the instruction edit and still reports success.
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: {} })
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({
+ skillName: 'signals-scout-weekly-digest',
+ body: 'Watch another scanner.',
+ latestVersion: 7,
+ })
+
+ logic.actions.saveScoutSettings({
+ name: 'Checkout / daily digest',
+ body: 'Watch checkout.',
+ cron: config.run_cron_schedule!,
+ outputDestinations: {},
+ webhookUrl: '',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(signalsScoutConfigUpdate).not.toHaveBeenCalled()
+ expect(llmSkillsNamePartialUpdate).not.toHaveBeenCalled()
+ expect(logic.values.settingsSkillName).toBe(SKILL_NAME)
+ })
+
+ it('drops a slow read the user has already moved on from', async () => {
+ // Two opens in a row leave two reads in flight. Without a breakpoint the slower one lands
+ // last and puts the scout the user left behind under the form they are now looking at.
+ await mountWithReports([])
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([makeConfig()])
+ let resolveFirst: (skill: unknown) => void = () => {}
+ mockSkillRetrieve
+ .mockReturnValueOnce(new Promise((resolve) => (resolveFirst = resolve)) as any)
+ .mockResolvedValueOnce({
+ body: 'Watch the other scanner.',
+ body_total_length: 24,
+ body_next_offset: null,
+ version: 9,
+ latest_version: 9,
+ } as any)
+
+ logic.actions.openScoutSettings(SKILL_NAME)
+ logic.actions.openScoutSettings('signals-scout-weekly-digest')
+ resolveFirst({
+ body: 'Watch this scanner.',
+ body_total_length: 19,
+ body_next_offset: null,
+ version: 3,
+ latest_version: 3,
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.skillPrompt?.skillName).toBe('signals-scout-weekly-digest')
+ })
+
+ it('waits for a fresh read instead of reseeding the instructions a previous open left behind', async () => {
+ // The form seeds from whatever the loader holds for this scout. Reopening after a conflict
+ // with the stale body still in place seeds the losing text and the version it was read at,
+ // so the next save publishes over the edit that caused the conflict.
+ await mountWithReports([])
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([makeConfig()])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({ skillName: SKILL_NAME, body: 'Watch this scanner.', latestVersion: 3 })
+
+ logic.actions.openScoutSettings(SKILL_NAME)
+
+ expect(logic.values.skillPrompt).toBeNull()
+ expect(logic.values.scoutDelivery).toBeNull()
+ })
+
+ it.each<[string, string, string, number]>([
+ ['another scout', 'signals-scout-trend-watch', 'Watch trends.', 9],
+ ['the same scout', SKILL_NAME, 'Watch this scanner.', 3],
+ ])(
+ 'publishes against the scout it started on and leaves %s alone when it is opened mid-save',
+ async (_case, reopenedSkillName, reopenedBody, reopenedVersion) => {
+ // Every request in the save can outlive its own modal, and nothing stops the user
+ // opening a scout meanwhile. Reading the prompt after those requests anchors the publish
+ // to the newly opened form's version and files this scout's body under it. Closing on
+ // the way out throws away the draft that form holds. The scout name does not separate
+ // the two forms, because the user can reopen the scout the save started on.
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: { webhook: null } })
+ const other = makeConfig({
+ id: 'config-2',
+ skill_name: 'signals-scout-trend-watch',
+ output_destinations: { webhook: null },
+ })
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config, other])
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadSkillPromptSuccess({
+ skillName: SKILL_NAME,
+ body: 'Watch this scanner.',
+ latestVersion: 3,
+ })
+
+ let releaseRename: () => void = () => {}
+ jest.mocked(signalsScoutConfigUpdate).mockReturnValue(
+ new Promise((resolve) => (releaseRename = () => resolve({ ...config, display_name: 'Renamed' })))
+ )
+ jest.mocked(llmSkillsNamePartialUpdate).mockResolvedValue({ body: 'Watch checkout.', version: 4 } as any)
+ mockSkillRetrieve.mockResolvedValue({
+ body: reopenedBody,
+ body_total_length: reopenedBody.length,
+ body_next_offset: null,
+ version: reopenedVersion,
+ latest_version: reopenedVersion,
+ } as any)
+
+ logic.actions.saveScoutSettings({
+ name: 'Renamed',
+ body: 'Watch checkout.',
+ cron: config.run_cron_schedule!,
+ outputDestinations: { webhook: null },
+ webhookUrl: '',
+ })
+ // The rename is still in flight when the user gives up on it and opens a scout again.
+ logic.actions.closeScoutSettings()
+ logic.actions.openScoutSettings(reopenedSkillName)
+ logic.actions.loadSkillPromptSuccess({
+ skillName: reopenedSkillName,
+ body: reopenedBody,
+ latestVersion: reopenedVersion,
+ })
+ releaseRename()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(llmSkillsNamePartialUpdate).toHaveBeenCalledWith(expect.any(String), SKILL_NAME, {
+ body: 'Watch checkout.',
+ base_version: 3,
+ })
+ expect(logic.values.skillPrompt).toEqual({
+ skillName: reopenedSkillName,
+ body: reopenedBody,
+ latestVersion: reopenedVersion,
+ })
+ expect(logic.values.settingsSkillName).toBe(reopenedSkillName)
+ }
+ )
+
+ it('publishes the whole body when the instructions arrive over more than one page', async () => {
+ await mountWithReports([])
+ const config = makeConfig({ output_destinations: {} })
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([config])
+ const head = 'x'.repeat(8000)
+ const tail = '\n\nFile the digest as one report.'
+ mockSkillRetrieve
+ .mockResolvedValueOnce({
+ body: head,
+ body_total_length: head.length + tail.length,
+ body_next_offset: head.length,
+ version: 3,
+ latest_version: 3,
+ } as any)
+ .mockResolvedValueOnce({
+ body: head + tail,
+ body_total_length: head.length + tail.length,
+ body_next_offset: null,
+ version: 3,
+ latest_version: 3,
+ } as any)
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+ const edited = `${head}${tail} Watch checkout.`
+ jest.mocked(llmSkillsNamePartialUpdate).mockResolvedValue({ body: edited, version: 4 } as any)
+
+ expect(mockSkillRetrieve).toHaveBeenLastCalledWith(expect.any(String), SKILL_NAME, {
+ body_offset: 0,
+ body_length: head.length + tail.length,
+ version: 3,
+ })
+ expect(logic.values.skillPrompt).toEqual({ skillName: SKILL_NAME, body: head + tail, latestVersion: 3 })
+
+ logic.actions.saveScoutSettings({
+ name: scoutDisplayName(config),
+ body: edited,
+ cron: config.run_cron_schedule!,
+ outputDestinations: {},
+ webhookUrl: '',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(llmSkillsNamePartialUpdate).toHaveBeenCalledWith(expect.any(String), SKILL_NAME, {
+ body: edited,
+ base_version: 3,
+ })
+ })
+
+ it('loads nothing when the instructions come back short', async () => {
+ await mountWithReports([])
+ scoutFleetLogic.findMounted()!.actions.loadScoutConfigsSuccess([makeConfig({ output_destinations: {} })])
+ mockSkillRetrieve.mockResolvedValue({
+ body: 'Watch this scanner.',
+ body_total_length: 900,
+ body_next_offset: null,
+ version: 3,
+ latest_version: 3,
+ } as any)
+
+ logic.actions.openScoutSettings(SKILL_NAME)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.skillPrompt).toBeNull()
+ })
+
it('resolves the latest report without waiting for the scout roster', async () => {
// The card reads `latestReportRow` on a cold load, before the fleet logic has answered with
// this scanner's configs. Deriving reports from the fleet's runs window instead of this
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
index 66f990493596..2972a5404ded 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
@@ -1,4 +1,5 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import type { BreakPointFunction } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
@@ -60,6 +61,8 @@ export interface ScoutDelivery {
export interface ScoutPrompt {
skillName: string
body: string
+ /** The version the body was read at. The skills API needs it as `base_version` to publish an edit. */
+ latestVersion: number
}
function inputValue(inputs: unknown, key: string): unknown {
@@ -131,6 +134,7 @@ export interface scannerScoutLogicValues {
scoutReports: ScoutReportApi[]
scoutReportsFailed: boolean
scoutReportsLoading: boolean
+ settingsFormId: number
settingsSaving: boolean
settingsSkillName: string | null
skillPrompt: ScoutPrompt | null
@@ -155,6 +159,17 @@ export interface scannerScoutLogicActions {
loadScoutConfigs: (_?: void | undefined) => void // scoutFleetLogic
loadScoutMetadata: () => any // scoutFleetLogic
loadScoutRuns: (_?: void | undefined) => void // scoutFleetLogic
+ patchScoutConfigLocally: (
+ configId: string,
+ updates:
+ | Partial<SignalScoutConfigApi>
+ | import('products/signals/frontend/generated/api.schemas').PatchedSignalScoutConfigUpdateApi
+ ) => {
+ configId: string
+ updates:
+ | Partial<SignalScoutConfigApi>
+ | import('products/signals/frontend/generated/api.schemas').PatchedSignalScoutConfigUpdateApi
+ } // scoutFleetLogic
runScoutNow: (configId: string) => {
configId: string
} // scoutFleetLogic
@@ -255,7 +270,7 @@ export interface scannerScoutLogicActions {
scoutReports: ScoutReportApi[]
payload?: any
}
- loadSkillPrompt: () => any
+ loadSkillPrompt: (_: void) => void
loadSkillPromptFailure: (
error: string,
errorObject?: any
@@ -266,15 +281,17 @@ export interface scannerScoutLogicActions {
loadSkillPromptSuccess: (
skillPrompt: {
body: string
+ latestVersion: number
skillName: string
} | null,
- payload?: any
+ payload?: void
) => {
skillPrompt: {
body: string
+ latestVersion: number
skillName: string
} | null
- payload?: any
+ payload?: void
}
openCreateModal: (templateKey: ScannerScoutTemplateKey) => {
templateKey: ScannerScoutTemplateKey
@@ -371,6 +388,7 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
scoutFleetLogic,
[
'loadScoutConfigs',
+ 'patchScoutConfigLocally',
'updateScoutConfig',
'loadScoutRuns',
'loadScoutMetadata',
@@ -402,14 +420,42 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
skillPrompt: [
null as ScoutPrompt | null,
{
- loadSkillPrompt: async () => {
+ loadSkillPrompt: async (_: void, breakpoint: BreakPointFunction) => {
const projectId = teamLogic.values.currentProjectId
const skillName = values.settingsSkillName
if (!projectId || !skillName) {
return null
}
const skill = await llmSkillsNameRetrieve(String(projectId), skillName)
- return { skillName, body: skill.body ?? '' }
+ // Drop a read the user has already moved on from. Without this a slow read for
+ // one scout can land after a fast read for the next and leave that scout's body
+ // and version under the open form.
+ breakpoint()
+ // A fetch that sends no paging params caps the body at one page and reports the
+ // rest through body_next_offset. The form seeds from this value and a save
+ // replaces the whole body, so seeding a capped read would publish over every
+ // instruction past the first page. Read the rest in one request, pinned to the
+ // version the first response came from so a publish landing in between cannot
+ // splice two bodies together.
+ const full =
+ skill.body_next_offset === null
+ ? skill
+ : await llmSkillsNameRetrieve(String(projectId), skillName, {
+ body_offset: 0,
+ body_length: skill.body_total_length,
+ version: skill.version,
+ })
+ breakpoint()
+ const body = full.body ?? ''
+ if (body.length < full.body_total_length) {
+ // Fail the load instead of handing the form a short body. The modal blocks
+ // saving on a failed load, so this costs the user an edit; seeding what
+ // arrived would delete the instructions that did not.
+ throw new Error('The scout instructions did not load in full.')
+ }
+ // latest_version comes from the first response, so it is the version this body
+ // was read at even if another publish landed while the rest was in flight.
+ return { skillName, body, latestVersion: skill.latest_version }
},
},
],
@@ -539,6 +585,16 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
closeScoutSettings: () => null,
},
],
+ // Identifies the settings form on screen. The scout name cannot, because the user can
+ // close the form and open the same scout again while a save is still in flight. Both the
+ // open and the close move the count on, so no later form can carry an earlier form's id.
+ settingsFormId: [
+ 0,
+ {
+ openScoutSettings: (state) => state + 1,
+ closeScoutSettings: (state) => state + 1,
+ },
+ ],
settingsSaving: [
false,
{
@@ -818,6 +874,12 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
actions.loadOpenedReport()
},
openScoutSettings: () => {
+ // Both loaders keep their last value while the next read is in flight, and the form
+ // seeds from whatever is already there for this scout. Clearing them first makes the
+ // form wait for this open's read, so reopening after a conflict cannot seed the body
+ // and the version that the conflict already made stale.
+ actions.loadSkillPromptSuccess(null)
+ actions.loadScoutDeliverySuccess(null)
actions.loadSkillPrompt()
actions.loadScoutDelivery()
},
@@ -855,14 +917,26 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
const config = values.scoutConfigsForScanner.find(
(candidate) => candidate.skill_name === values.settingsSkillName
)
+ // Read with the config, before the first await. Every request below can outlive the
+ // modal that started it, and the user can open another scout meanwhile, so a later
+ // read would return that scout's instructions and version instead of this one's.
+ const prompt = values.skillPrompt
+ const formId = values.settingsFormId
if (!teamId || !projectId || !config || !form.body.trim()) {
actions.saveScoutSettingsFinished()
return
}
+ // Without this scout's own instructions there is no version to publish against, and
+ // no way to tell an edited body from an unchanged one. Saving the rest would drop
+ // the instruction edit and still report the whole save as done.
+ if (!prompt || prompt.skillName !== config.skill_name) {
+ lemonToast.error(
+ "Couldn't read this scout's current instructions. Close the settings and open them again."
+ )
+ actions.saveScoutSettingsFinished()
+ return
+ }
try {
- if (form.body !== values.skillPrompt?.body) {
- await llmSkillsNamePartialUpdate(String(projectId), config.skill_name, { body: form.body })
- }
const configUpdates: Record<string, unknown> = {}
if (form.name.trim() !== scoutDisplayName(config)) {
configUpdates.display_name = form.name.trim()
@@ -877,20 +951,63 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
configUpdates.output_destinations = form.outputDestinations ?? {}
}
if (Object.keys(configUpdates).length > 0) {
- await signalsScoutConfigUpdate(String(teamId), config.id, configUpdates)
+ const updated = await signalsScoutConfigUpdate(String(teamId), config.id, configUpdates)
+ // A retry after a conflict reads from the store before loadScoutConfigs
+ // lands, so the store has to hold this save already.
+ actions.patchScoutConfigLocally(config.id, updated)
actions.loadScoutConfigs()
}
// Reads the destination from the id the config records, so a retry after a
// partial failure patches what exists instead of provisioning a second one.
- if (!(await reconcileDelivery(config, form))) {
+ // A failure here must not hold the instructions back: the destination lives in
+ // Data pipelines, and a scout that already delivers pays a read and a write on
+ // every save, so an unrelated outage there would block every instruction edit.
+ const delivered = await reconcileDelivery(config, form)
+ // A body edit publishes a new skill version, so the API rejects it without the
+ // version the form was read at. It runs last because it is the only call here a
+ // concurrent edit can reject, and the rename, the schedule and the delivery must
+ // not go down with it.
+ if (form.body !== prompt.body) {
+ const published = await llmSkillsNamePartialUpdate(String(projectId), config.skill_name, {
+ body: form.body,
+ base_version: prompt.latestVersion,
+ })
+ // A second save from the same open modal must not send the version this one
+ // already replaced. Only while that same form is on screen: a save that
+ // outlives its own modal would leave this body under whatever form is open
+ // now, which can be another scout or the same scout opened again.
+ if (values.settingsFormId === formId) {
+ actions.loadSkillPromptSuccess({
+ skillName: config.skill_name,
+ body: published.body,
+ latestVersion: published.version,
+ })
+ }
+ }
+ if (!delivered) {
// reconcileDelivery already said what failed. Leaving the form open keeps the
// user's delivery edits in front of them instead of closing over the failure.
+ // Everything else is saved by now, so a retry repeats only the delivery.
return
}
lemonToast.success('Scout updated. Changes take effect on its next run.')
- actions.closeScoutSettings()
+ // Same reason: closing whatever is open now would discard a draft the user
+ // started after abandoning this save.
+ if (values.settingsFormId === formId) {
+ actions.closeScoutSettings()
+ }
} catch (error: any) {
- lemonToast.error(`Couldn't save the scout${error?.detail ? `: ${error.detail}` : ''}`)
+ if (error?.status !== 409) {
+ lemonToast.error(`Couldn't save the scout${error?.detail ? `: ${error.detail}` : ''}`)
+ return
+ }
+ // Re-read so latestVersion advances. The modal seeds once, so the edit stays.
+ if (values.settingsFormId === formId) {
+ actions.loadSkillPrompt()
+ }
+ lemonToast.error(
+ 'These instructions changed somewhere else while you were editing. Your edits are still here. Save again to publish them over the current version.'
+ )
} finally {
actions.saveScoutSettingsFinished()
}