: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): stop cutting a new scout's name at 45 characters (#99419)
coryslater76c45e6071f7
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e8972d768dd2..ebd6c1dab20c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4479,6 +4479,9 @@ importers:'@testing-library/react':specifier: ^14.3.1+ '@testing-library/user-event':+ specifier: ^14.6.1+ version: 14.6.1(@testing-library/[email protected])kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutFormModal.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutFormModal.tsxindex 98a7a5715603..472ac17a9674 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutFormModal.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutFormModal.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useEffect, useMemo, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import { LemonButton, LemonInput, LemonModal, LemonSelect, LemonSkeleton, Link } from '@posthog/lemon-ui'@@ -12,7 +12,7 @@ import { scoutDisplayName } from 'products/signals/frontend/inbox/utils/scoutRunimport { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { replayScannerLogic } from '../replayScannerLogic'-import { scannerScoutTemplate, scoutBodyPlaceholders } from '../scannerScout'+import { SCOUT_DISPLAY_NAME_MAX_LENGTH, scannerScoutTemplate, scoutBodyPlaceholders } from '../scannerScout'import { SCOUT_REPORT_EMITTED_EVENT, webhookUrlError } from '../scannerScoutDelivery'import type { ScannerScoutForm } from '../scannerScoutLogic'import { scannerScoutLogic } from '../scannerScoutLogic'@@ -112,8 +112,11 @@ export function ScannerScoutFormModal({const { scanner } = useValues(replayScannerLogic({ id: scannerId }))// Rebuilding the templates on every keystroke would regenerate three multi-KB prompts.const template = useMemo(- () => (createTemplateKey ? scannerScoutTemplate(createTemplateKey, scannerId, scanner?.scanner_type) : null),- [createTemplateKey, scannerId, scanner?.scanner_type]+ () =>+ createTemplateKey+ ? scannerScoutTemplate(createTemplateKey, scannerId, scanner?.scanner_type, scannerName)+ : null,+ [createTemplateKey, scannerId, scanner?.scanner_type, scannerName])const config = scoutConfigsForScanner.find((candidate) => candidate.skill_name === settingsSkillName)const [activeTab, setActiveTab] = useState<ScoutFormTab>('instructions')@@ -144,6 +147,20 @@ export function ScannerScoutFormModal({}}, [template, seeded, loadedForThisScout, skillPrompt, scoutDelivery])+ // The scanner's name can arrive after the modal opens (the scanner and the scouts list load in+ // parallel), and the default name leads with it. Until it answers, the scanner logic holds a+ // team-named placeholder, so a name seeded before it reads wrong. Follow a changed default+ // until the person edits the name.+ const nameTouchedRef = useRef(false)+ useEffect(() => {+ if (!template || nameTouchedRef.current) {+ return+ }+ setForm((current) =>+ current.name === template.defaultName ? current : { ...current, name: template.defaultName }+ )+ }, [template])+if (!template && !config) {return null}@@ -167,11 +184,20 @@ export function ScannerScoutFormModal({JSON.stringify(form.outputDestinations ?? {}) === JSON.stringify(config.output_destinations ?? {}) &&form.webhookUrl.trim() === (scoutDelivery?.webhook?.url ?? '')+ // The skill name is derived from the scanner name when the scout is created and never changes+ // afterwards (it is the load key, shown nowhere). Creating before the scanner loads would bake in+ // the team-named placeholder, so the create action waits for the real scanner. Settings mode edits+ // an existing scout and derives no skill name, so it is unaffected.+ const scannerLoaded = scanner?.id?.toLowerCase() === scannerId.toLowerCase()+const submitDisabledReason = (): string | undefined => {const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)if (editDisabledReason) {return editDisabledReason}+ if (template && !scannerLoaded) {+ return 'Loading the scanner'+ }if (loadFailed) {return "Couldn't load this scout's current settings"}@@ -223,9 +249,12 @@ export function ScannerScoutFormModal({<span className="text-xs text-default">Name</span><LemonInputvalue={form.name}- onChange={(name) => patch({ name })}+ onChange={(name) => {+ nameTouchedRef.current = true+ patch({ name })+ }}placeholder={template?.defaultName}- maxLength={template ? 45 : 200}+ maxLength={SCOUT_DISPLAY_NAME_MAX_LENGTH}data-attr="vision-scout-form-name"/></div>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.test.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.test.tsxnew file mode 100644index 000000000000..38bbe5c9e2dc--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.test.tsx@@ -0,0 +1,113 @@+import { render, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, type AppContext } from '~/types'++import { ScannerScoutsTab } from './ScannerScoutsTab'++const SCANNER_ID = '01a014ea-854f-72b5-8192-bb6ac9f212a5'++// The scouts list and the scanner load in parallel, so the create form can open before the scanner+// answers and the default name it seeds from is still the nameless fallback. These tests hold the+// scanner response back until after the form is open, which is the real timing, not a simulated one.+describe('ScannerScoutsTab', () => {+ let resolveScanner: (body: Record<string, unknown>) => void++ const scanner = {+ id: SCANNER_ID,+ name: 'Rage clicks on checkout',+ scanner_type: 'monitor',+ user_access_level: AccessControlLevel.Editor,+ }++ const nameInput = (): HTMLInputElement =>+ document.querySelector('[data-attr="vision-scout-form-name"]') as HTMLInputElement++ beforeEach(() => {+ initKeaTests()+ resolveScanner = () => {}+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.ReplayScanner]: AccessControlLevel.Editor,+ [AccessControlResourceType.SessionRecording]: AccessControlLevel.Viewer,+ [AccessControlResourceType.LlmSkill]: AccessControlLevel.Editor,+ },+ } as AppContext+ useMocks({+ get: {+ '/api/projects/:team/vision/scanners/:id/': () =>+ new Promise((resolve) => {+ resolveScanner = (body) => resolve([200, body])+ }),+ '/api/projects/:team/vision/scanners/:id/observations/stats/': [+ 200,+ {+ status_counts: {},+ coverage: {},+ labels: {},+ available_tags: [],+ monitor: null,+ classifier: null,+ },+ ],+ '/api/projects/:team/signals/scout/configs/': [200, []],+ '/api/projects/:team/signals/scout/runs/recent-per-scout/': [200, []],+ '/api/projects/:team/signals/scout/metadata/current/': [200, { enrolled: true }],+ '/api/projects/:team/vision/scanners/:id/scout_reports/': [200, []],+ },+ })+ })++ afterEach(() => {+ delete (window as { POSTHOG_APP_CONTEXT?: AppContext }).POSTHOG_APP_CONTEXT+ })++ async function openDailyDigestForm(): Promise<void> {+ render(<ScannerScoutsTab scannerId={SCANNER_ID} />)++ const useTemplate = await waitFor(+ () => {+ const button = document.querySelector('[data-attr="vision-scout-template-daily-digest"]')+ expect(button).not.toBeNull()+ return button as HTMLElement+ },+ // The button must be there while the scanner is still pending, or the race isn't real.+ { interval: 10 }+ )+ await userEvent.click(useTemplate)+ await waitFor(() => expect(nameInput()).toBeTruthy())+ }++ it('blocks create and shows a placeholder name until the scanner loads, then follows it', async () => {+ await openDailyDigestForm()+ const submit = (): HTMLElement =>+ document.querySelector('[data-attr="vision-scout-form-submit"]') as HTMLElement+ // Until the scanner answers, the logic holds a team-named placeholder. The display name seeds+ // from it, but create has to wait: the skill name is derived from the scanner name at creation+ // and never changes, so creating now would bake the placeholder into it.+ expect(nameInput().value).toBe('MockHog App + Marketing monitor daily digest')+ expect(submit().getAttribute('aria-disabled')).toBe('true')++ resolveScanner(scanner)+ await waitFor(() => expect(nameInput().value).toBe('Rage clicks on checkout daily digest'))+ expect(submit().getAttribute('aria-disabled')).not.toBe('true')+ })++ it('keeps a name the person typed once the scanner answers', async () => {+ await openDailyDigestForm()++ const user = userEvent.setup()+ await user.clear(nameInput())+ await user.type(nameInput(), 'My own name')++ resolveScanner(scanner)+ // The placeholder tracks the template's default, so it proves the loaded name reached the+ // form; the value then proves the typed name survived it.+ await waitFor(() => expect(nameInput().placeholder).toBe('Rage clicks on checkout daily digest'))+ expect(nameInput().value).toBe('My own name')+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsxindex 9a728d7ebf09..1c7448911b78 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx@@ -97,8 +97,8 @@ export function ScannerScoutsTab({ scannerId }: { scannerId: string }): JSX.Elem} = useValues(logic)const { openCreateModal, loadScoutConfigs } = useActions(logic)const templates = useMemo(- () => scannerScoutTemplates(scannerId, scanner?.scanner_type),- [scannerId, scanner?.scanner_type]+ () => scannerScoutTemplates(scannerId, scanner?.scanner_type, scannerName),+ [scannerId, scanner?.scanner_type, scannerName])if (scoutConfigs === null && scoutConfigsLoading) {diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.test.tsindex edd164e9a35f..424b64864ac6 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts@@ -1,41 +1,80 @@import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'+import { validateSkillName } from 'products/skills/frontend/skillConstants'import type { ScannerScoutTemplate } from './scannerScout'import {- scoutNameToSkillName,+ SCOUT_DISPLAY_NAME_MAX_LENGTH,isScannerScoutConfig,scannerScoutCreatePayload,scannerScoutTemplates,scoutBodyPlaceholders,+ scoutSkillName,} from './scannerScout'describe('scannerScout', () => {const scannerId = '0198B7C4-1111-2222-3333-444455556666'- it('slugifies user names into valid, unique skill names and humanizes them back', () => {- const name = scoutNameToSkillName('Checkout friction (weekly)', 'Rage clicks', [])- expect(name).toBe('signals-scout-rage-clicks-checkout-friction-weekly')- expect(name).toMatch(/^signals-scout-[a-z0-9-]+$/)- expect(scoutNameToSkillName('Checkout friction (weekly)', 'Rage clicks', [name])).toBe(`${name}-2`)- expect(scoutNameToSkillName('', 'Rage clicks', [])).toBe('signals-scout-rage-clicks-digest')- expect(scoutNameToSkillName('x'.repeat(100), 'Rage clicks', []).length).toBeLessThanOrEqual(64)+ it('derives the skill name from the scanner and the template, never from the typed name', () => {+ // The skill name is an id: unique per team, fixed at creation, capped at 64 characters.+ // Because the derivation takes no name at all, no typed name can overrun the cap.+ const name = scoutSkillName('Rage clicks on checkout', 'daily-digest', [])+ expect(name).toBe('signals-scout-rage-clicks-on-checkout-daily-digest')+ expect(validateSkillName(name)).toBeUndefined()+ expect(scoutSkillName('Rage clicks on checkout', 'daily-digest', [name])).toBe(`${name}-2`)})it('numbers a scout per scanner rather than across the team', () => {- // Skill names are unique per team, so deriving one from the label alone made the second+ // Skill names are unique per team, so leaving the scanner out of the slug made the second// scanner's first daily digest `signals-scout-daily-digest-2`, and the number climbed with// every scanner the team set up.- const first = scoutNameToSkillName('Daily digest', 'Checkout rage clicks', [])- const second = scoutNameToSkillName('Daily digest', 'Signup drop-off', [first])+ const first = scoutSkillName('Checkout rage clicks', 'daily-digest', [])+ const second = scoutSkillName('Signup drop-off', 'daily-digest', [first])expect(first).toBe('signals-scout-checkout-rage-clicks-daily-digest')expect(second).toBe('signals-scout-signup-drop-off-daily-digest')})- it('keeps the label whole when the scanner name would overrun the cap', () => {- // The label is what tells two scouts on one scanner apart; the scanner name is context.- const name = scoutNameToSkillName('new issue watch', 'x'.repeat(80), [])- expect(name.length).toBeLessThanOrEqual(64)- expect(name.endsWith('-new-issue-watch')).toBe(true)+ it('keeps the template key whole when the scanner name would overrun the cap', () => {+ // Only the scanner gives way to the cap, and only inside the id. A scanner named past the+ // cap must still leave a valid skill name that says which template the scout came from:+ // cut mid-word, a slug ends in a hyphen, which fails skill name validation. The keys come+ // from the templates themselves, so a new template joins the invariant without a change here.+ for (const { key } of scannerScoutTemplates(scannerId, 'monitor', '')) {+ const name = scoutSkillName('x'.repeat(SCOUT_DISPLAY_NAME_MAX_LENGTH), key, [])+ expect(name.length).toBeLessThanOrEqual(64)+ expect(validateSkillName(name)).toBeUndefined()+ expect(name.endsWith(`-${key}`)).toBe(true)+ }+ })++ it('fits the cap when a template key alone leaves no room for the scanner', () => {+ // No current key is this long, but the clamp must subtract the 14-char prefix, not just the+ // collision suffix: a 60-char key plus the prefix would otherwise reach 75 against a 64 cap.+ const longKey = 'x'.repeat(60) as ScannerScoutTemplate['key']+ expect(scoutSkillName('Rage clicks on checkout', longKey, []).length).toBeLessThanOrEqual(64)+ })++ it('leads the default name with the scanner, since the id is not shown', () => {+ // The scout lands in the Signals fleet beside every other product's, where four scanners'+ // "Daily digest" is four rows of the same name.+ const templates = scannerScoutTemplates(scannerId, 'monitor', 'Rage clicks on checkout')+ expect(templates.map((template) => template.defaultName)).toEqual([+ 'Rage clicks on checkout daily digest',+ 'Rage clicks on checkout trend watch',+ 'Rage clicks on checkout new issue watch',+ 'Rage clicks on checkout custom scout',+ ])+ // A scanner can be unnamed, and " daily digest" is not a name.+ expect(scannerScoutTemplates(scannerId, 'monitor', '')[0].defaultName).toBe('Daily digest')+ // A name with no letters or numbers is noise next to the phrase; a non-Latin one is still a+ // name, which is why the check is unicode-aware rather than a word-character test.+ expect(scannerScoutTemplates(scannerId, 'monitor', '!!!')[0].defaultName).toBe('Daily digest')+ expect(scannerScoutTemplates(scannerId, 'monitor', '!!! 42')[0].defaultName).toBe('!!! 42 daily digest')+ expect(scannerScoutTemplates(scannerId, 'monitor', '日本語')[0].defaultName).toBe('日本語 daily digest')+ // The scanner's name field allows 255, the display name only 200, so the default is clamped+ // rather than sent oversized and rejected.+ expect(scannerScoutTemplates(scannerId, 'monitor', 'x'.repeat(255))[0].defaultName.length).toBe(+ SCOUT_DISPLAY_NAME_MAX_LENGTH+ )})it('claims only the scouts recorded as belonging to this scanner', () => {@@ -50,7 +89,7 @@ describe('scannerScout', () => {})it('gives every template a distinct key, its own cron, and a body scoped to the scanner', () => {- const templates = scannerScoutTemplates(scannerId, 'monitor')+ const templates = scannerScoutTemplates(scannerId, 'monitor', 'Rage clicks')expect(templates).toHaveLength(4)const keys = templates.map((template) => template.key)expect(new Set(keys).size).toBe(keys.length)@@ -79,7 +118,7 @@ describe('scannerScout', () => {it('writes the trend template for the one output the scanner actually emits', () => {const trendFor = (type: 'monitor' | 'scorer' | 'classifier' | 'summarizer'): ScannerScoutTemplate =>- scannerScoutTemplates(scannerId, type).find((template) => template.key === 'trend-watch')!+ scannerScoutTemplates(scannerId, type, 'Rage clicks').find((template) => template.key === 'trend-watch')!expect(trendFor('monitor').description).toContain('yes-rate')expect(trendFor('monitor').body).toContain('scanner_output_verdict')@@ -88,11 +127,13 @@ describe('scannerScout', () => {expect(trendFor('classifier').description).toContain('tag mix')expect(trendFor('summarizer').description).toContain('themes')// A scanner whose type hasn't loaded still gets a usable template rather than nothing.- expect(scannerScoutTemplates(scannerId, undefined)).toHaveLength(4)+ expect(scannerScoutTemplates(scannerId, undefined, 'Rage clicks')).toHaveLength(4)})it('gives the new-issue template a catalog to diff against, so "new" means something', () => {- const newIssues = scannerScoutTemplates(scannerId, 'monitor').find((template) => template.key === 'new-issues')!+ const newIssues = scannerScoutTemplates(scannerId, 'monitor', 'Rage clicks').find(+ (template) => template.key === 'new-issues'+ )!// Novelty needs remembered history: without the catalog every run reports everything.// The key is scanner-scoped so it matches what the first move searches on.expect(newIssues.body).toContain(`${scannerId}:pattern:known-issues`)@@ -103,7 +144,7 @@ describe('scannerScout', () => {it('stamps both tags and the reviewed name, prompt, and cron on the create payload', () => {const payload = scannerScoutCreatePayload('Checkout friction', {name: 'signals-scout-daily-digest',- body: scannerScoutTemplates(scannerId, 'monitor')[0].body,+ body: scannerScoutTemplates(scannerId, 'monitor', 'Rage clicks')[0].body,cron: '30 7 * * *',})expect(payload.name).toBe('signals-scout-daily-digest')diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.tsindex 4491369eda07..889cac61e783 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScout.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.ts@@ -1,9 +1,12 @@+import { capitalizeFirstLetter } from 'lib/utils/strings'+import type { ScannerTypeEnumApi } from 'products/replay_vision/frontend/generated/api.schemas'import type { ScannerScoutCreateApi } from 'products/replay_vision/frontend/generated/api.schemas'import type {SignalScoutConfigApi,SignalScoutOutputDestinationsApi,} from 'products/signals/frontend/generated/api.schemas'+import { SIGNALS_SCOUT_SKILL_PREFIX } from 'products/signals/frontend/inbox/utils/scoutRunsWindow'// pinned: what a scout's config records as its owner, alongside the scanner id in `source_id`.// Signals stores the pair; the backend has the same constant in `scout_source.py`, and the two must@@ -19,8 +22,12 @@ export function isScannerScoutConfig(config: SignalScoutConfigApi, scannerId: st// Every morning at 9:00 in the project timezone: the default cadence for every template.export const SCANNER_SCOUT_CRON = '0 9 * * *'+/** What the name field accepts, and the only bound on it: the typed name is recorded as the scout+ * config's `display_name` and nothing else is derived from it. Kept in sync with the `display_name`+ * maxLength on the Signals scout config API. */+export const SCOUT_DISPLAY_NAME_MAX_LENGTH = 200+const SKILL_NAME_MAX_LENGTH = 64-const SKILL_NAME_PREFIX = 'signals-scout-'// Room for the `-2`..`-99` a collision appends.const COLLISION_SUFFIX_LENGTH = 3@@ -33,22 +40,30 @@ function slugify(value: string): string {.replace(/^-|-$/g, '')}-/** Turns the name a person typed into a valid, unique `signals-scout-*` skill name, suffixing- * while taken.+/** The scout's skill name, which is its id: fixed at creation, unique per team, and what the+ * runtime loads the scout's prompt by. Derived from the scanner and the template the person picked,+ * never from the name they typed, so nothing has to bound that name and the form can take one of+ * any length. Suffixes while taken.*- * The scanner's name goes in the slug because skill names are unique per team, not per scanner.- * Without it the second scanner's "Daily digest" becomes `signals-scout-daily-digest-2`, which- * reads as a second digest on that scanner rather than the first, and the numbering climbs with- * every scanner a team sets up. */-export function scoutNameToSkillName(label: string, scannerName: string, takenNames: string[]): string {- const labelSlug = slugify(label) || 'digest'- // The label is what tells two scouts on one scanner apart, so it keeps its full length and the- // scanner name gives way when the two together would overrun the cap.- const room = SKILL_NAME_MAX_LENGTH - SKILL_NAME_PREFIX.length - COLLISION_SUFFIX_LENGTH - labelSlug.length - 1- const scannerSlug = slugify(scannerName).slice(0, Math.max(0, room)).replace(/-$/, '')- const base = `${SKILL_NAME_PREFIX}${[scannerSlug, labelSlug].filter(Boolean).join('-')}`- .slice(0, SKILL_NAME_MAX_LENGTH - COLLISION_SUFFIX_LENGTH)+ * The scanner is in the slug because skill names are unique per team, not per scanner. Without it+ * the second scanner's daily digest becomes `signals-scout-daily-digest-2`, which reads as a second+ * digest on that scanner rather than the first, and the numbering climbs with every scanner a team+ * sets up. Template keys are already valid slugs and short, so only the scanner gives way to the+ * cap, and shortening it shortens the id alone, never a name anyone reads. */+export function scoutSkillName(+ scannerName: string,+ templateKey: ScannerScoutTemplateKey,+ takenNames: string[]+): string {+ const budget = SKILL_NAME_MAX_LENGTH - SIGNALS_SCOUT_SKILL_PREFIX.length - COLLISION_SUFFIX_LENGTH+ // Reserve the join dash and the whole template key, so only the scanner slug is trimmed.+ const scannerSlug = slugify(scannerName)+ .slice(0, Math.max(0, budget - templateKey.length - 1)).replace(/-$/, '')+ // Re-clamp the joined part to the same budget, so the cap holds even if the reservation above is+ // wrong for some future template key.+ const suffix = [scannerSlug, templateKey].filter(Boolean).join('-').slice(0, budget).replace(/-$/, '')+ const base = SIGNALS_SCOUT_SKILL_PREFIX + suffixconst taken = new Set(takenNames)if (!taken.has(base)) {return base@@ -67,7 +82,6 @@ export interface ScannerScoutTemplate {key: ScannerScoutTemplateKeytitle: stringdescription: string- /** Human-readable cadence for the template card, e.g. "Daily at 8:00". *//** The name the create form starts with; the user can rename before creating. */defaultName: stringcron: string@@ -233,9 +247,23 @@ const TREND_LENSES: Record<ScannerTypeEnumApi, TrendLens> = {},}+/** The name the create form starts with. It leads with the scanner because the scout also lands in+ * the Signals fleet beside every other product's, where "Daily digest" on its own doesn't say which+ * scanner files it. The displayed name is the person's own, so the default is where the scanner+ * belongs. Editable like any other. */+function scoutDefaultName(scannerName: string, phrase: string): string {+ const scanner = scannerName.trim()+ const named = scanner && /[\p{L}\p{N}]/u.test(scanner)+ const name = named ? `${scanner} ${phrase}` : capitalizeFirstLetter(phrase)+ // The scanner's name field allows 255; the display name only 200. A default seeded past the+ // bound would be rejected on save, so it is clamped here.+ return name.slice(0, SCOUT_DISPLAY_NAME_MAX_LENGTH)+}+export function scannerScoutTemplates(scannerId: string,- scannerType: ScannerTypeEnumApi | undefined+ scannerType: ScannerTypeEnumApi | undefined,+ scannerName: string): ScannerScoutTemplate[] {const lens = TREND_LENSES[scannerType ?? 'monitor'] ?? TREND_LENSES.monitorreturn [@@ -243,7 +271,7 @@ export function scannerScoutTemplates(key: 'daily-digest',title: 'Daily digest',description: 'A daily summary of what this scanner found, and the sessions worth watching.',- defaultName: 'Daily digest',+ defaultName: scoutDefaultName(scannerName, 'daily digest'),cron: SCANNER_SCOUT_CRON,body: buildScoutBody(scannerId, {heading: 'Replay Vision scanner digest',@@ -277,7 +305,7 @@ Lead the summary with whatever the window is actually about, and lean on:key: 'trend-watch',title: 'Trend watch',description: lens.description,- defaultName: 'Trend watch',+ defaultName: scoutDefaultName(scannerName, 'trend watch'),cron: SCANNER_SCOUT_CRON,body: buildScoutBody(scannerId, {heading: 'Replay Vision scanner trend watch',@@ -297,7 +325,7 @@ ${lens.skip}`,key: 'new-issues',title: 'New issue watch',description: 'Reports problems this scanner has never seen before, dated to what changed.',- defaultName: 'New issue watch',+ defaultName: scoutDefaultName(scannerName, 'new issue watch'),cron: SCANNER_SCOUT_CRON,body: buildScoutBody(scannerId, {heading: 'Replay Vision new issue watch',@@ -324,7 +352,7 @@ ${lens.skip}`,key: 'scratch',title: 'Start from scratch',description: 'A working skeleton. You fill in what to watch for and what counts as notable.',- defaultName: 'Custom scout',+ defaultName: scoutDefaultName(scannerName, 'custom scout'),cron: SCANNER_SCOUT_CRON,// Ships the mechanics that make a scout run (which tools to call, how to file exactly one// digest) and leaves the judgment to the user. `<ALL CAPS>` marks what has to be replaced;@@ -358,9 +386,10 @@ export function scoutBodyPlaceholders(body: string): string[] {export function scannerScoutTemplate(key: ScannerScoutTemplateKey,scannerId: string,- scannerType: ScannerTypeEnumApi | undefined+ scannerType: ScannerTypeEnumApi | undefined,+ scannerName: string): ScannerScoutTemplate {- const templates = scannerScoutTemplates(scannerId, scannerType)+ const templates = scannerScoutTemplates(scannerId, scannerType, scannerName)return templates.find((template) => template.key === key) ?? templates[0]}diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.tsindex d16f9c0b952e..2deaa820fcea 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.test.ts@@ -1,5 +1,7 @@import { expectLogic } from 'kea-test-utils'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { initKeaTests } from '~/test/init'import {@@ -585,6 +587,59 @@ describe('scannerScoutLogic', () => {})})+ it('records the typed name and gives the scout an id that does not depend on it', async () => {+ // Because nothing is slugified from the typed name, a name of any length survives whole,+ // and the id stays the scanner's and the template's, which is what keeps it readable and+ // unique per team.+ await mountWithReports([])+ const typed = 'Robot: Replay Vision intent and friction report, every weekday morning'+ const config = makeConfig({ output_destinations: {} })+ mockScoutsCreate.mockResolvedValueOnce({ created: true, config } as any)+ jest.mocked(signalsScoutConfigUpdate).mockResolvedValue({ ...config, display_name: typed })++ logic.actions.openCreateModal('daily-digest')+ logic.actions.createScout({+ name: typed,+ body: 'Watch this scanner.',+ cron: '0 9 * * *',+ outputDestinations: {},+ webhookUrl: '',+ })+ await expectLogic(logic).toFinishAllListeners()++ expect((mockScoutsCreate.mock.calls[0][2] as any).name).toBe(+ 'signals-scout-rage-clicks-on-checkout-daily-digest'+ )+ expect(signalsScoutConfigUpdate).toHaveBeenCalledWith(expect.any(String), config.id, {+ display_name: typed,+ })+ })++ it('creates the scout even when its display name cannot be recorded', async () => {+ // The scout is already created by then, so a failed rename must not read as a failed+ // create, but the toast must not claim an unqualified success either.+ await mountWithReports([])+ mockScoutsCreate.mockResolvedValueOnce({+ created: true,+ config: makeConfig({ output_destinations: {} }),+ } as any)+ jest.mocked(signalsScoutConfigUpdate).mockRejectedValue(new Error('boom'))+ const success = jest.spyOn(lemonToast, 'success')++ logic.actions.openCreateModal('daily-digest')+ logic.actions.createScout({+ name: 'Robot: Replay Vision intent and friction report, every weekday morning',+ body: 'Watch this scanner.',+ cron: '0 9 * * *',+ outputDestinations: {},+ webhookUrl: '',+ })+ await expectLogic(logic).toFinishAllListeners()++ expect(mockScoutsCreate).toHaveBeenCalledTimes(1)+ expect(success).toHaveBeenCalledWith(expect.stringContaining("its name wasn't saved"))+ })+it('renames and retries when another tab already took the name', async () => {// Skill names are unique per team, so a scout created in one tab leaves this tab's roster// stale and its derived name already taken.@@ -593,6 +648,7 @@ describe('scannerScoutLogic', () => {.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 })).mockResolvedValueOnce({ created: true, config: makeConfig() } as any)+ logic.actions.openCreateModal('daily-digest')logic.actions.createScout({name: 'Daily digest',body: 'Watch this scanner.',diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.tsindex 2972a5404ded..ab1af92a0c91 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts@@ -35,7 +35,7 @@ import {} from '../generated/api'import type { ScoutReportApi } from '../generated/api.schemas'import type { ScannerScoutTemplateKey } from './scannerScout'-import { isScannerScoutConfig, scannerScoutCreatePayload, scoutNameToSkillName } from './scannerScout'+import { isScannerScoutConfig, scannerScoutCreatePayload, scoutSkillName } from './scannerScout'import { isScoutDestination, scoutWebhookDestinationPayload } from './scannerScoutDelivery'/** Everything the scout form edits, in both create and settings mode. */@@ -765,6 +765,25 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([}}+ /** Records the name the person typed. Nothing else keeps it (the skill name is derived from+ * the scanner and the template), so this runs for every scout rather than only the ones with+ * a name too long to slug. Best-effort: the scout is already created by this point, so a+ * failure here leaves it named after its skill rather than unsaved. Returns whether the name+ * was recorded, so the create toast can say when it was not. */+ const applyDisplayName = async (config: SignalScoutConfigApi, name: string): Promise<boolean> => {+ const teamId = teamLogic.values.currentTeamId+ const displayName = name.trim()+ if (!teamId || !displayName) {+ return true+ }+ try {+ await signalsScoutConfigUpdate(String(teamId), config.id, { display_name: displayName })+ return true+ } catch {+ return false+ }+ }+/** Soft-deletes a scout's webhook destination without touching its config, for the delete* path where the config is already gone. */const clearScoutWebhook = async (@@ -807,7 +826,10 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([[scoutFleetLogic.actionTypes.loadScoutRunsSuccess]: refetchReportsIfChanged,createScout: async ({ form }) => {const teamId = teamLogic.values.currentTeamId- if (!teamId || !form.body.trim()) {+ // The template the form was opened from, which the skill name is derived from+ // instead of the typed name. Held until `createScoutFinished` clears it.+ const templateKey = values.createTemplateKey+ if (!teamId || !templateKey || !form.body.trim()) {actions.createScoutFinished()return}@@ -822,7 +844,7 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([// of asking the person to refresh.const burnedNames: string[] = []const create = async (): Promise<SignalScoutConfigApi> => {- const skillName = scoutNameToSkillName(form.name, props.scannerName, [+ const skillName = scoutSkillName(props.scannerName, templateKey, [...(values.scoutConfigs ?? []).map((config) => config.skill_name),...burnedNames,])@@ -850,12 +872,13 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([}}}- const created = { config: config! }- const delivered = await reconcileDelivery(created.config, form)+ const created = config!+ const named = await applyDisplayName(created, form.name)+ const delivered = await reconcileDelivery(created, form)lemonToast.success(- delivered+ delivered && named? 'Scout created. Its first report arrives after the next scheduled run.'- : "Scout created, but its delivery wasn't set up. Open its settings to try again."+ : `Scout created, but ${!named ? "its name wasn't saved" : "its delivery wasn't set up"}. Open its settings to try again.`)actions.loadScoutConfigs()} catch (error: any) {diff --git a/products/replay_vision/package.json b/products/replay_vision/package.jsonindex 6d9d45d6e42a..428620709e03 100644--- a/products/replay_vision/package.json+++ b/products/replay_vision/package.json@@ -15,6 +15,7 @@},"devDependencies": {"@testing-library/react": "^14.3.1",+ "@testing-library/user-event": "^14.6.1","kea-test-utils": "catalog:"},"peerDependencies": {