: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
feat(aio): open a scout template from the self-driving URL (#83977)
Sarah Sanders008d1dccb98c
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex ae02b05a214b..e2478a7ad0e9 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -296,6 +296,7 @@ export const commonConfig = {'.mp3': 'file','.sql': 'text','.yaml': 'text',+ '.md': 'text',},metafile: true,}diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex cf86ba1d2236..6596d2e6a444 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -190,6 +190,7 @@ const config: Config = {devHmrStreamAbort$: '<rootDir>/src/test/mocks/emptyMock.js','^.+\\.sql\\?raw$': '<rootDir>/src/test/mocks/rawFileMock.js','^(.+)\\.yaml\\?raw$': '$1.yaml',+ '^(.+)\\.md\\?raw$': '$1.md','^~/(.*)$': '<rootDir>/src/$1','^@posthog/hogql-parser$': '<rootDir>/node_modules/@posthog/hogql-parser/dist/index.cjs',// @posthog/hogvm ships as ESM-only; map to the TS source so Jest (Sucrase) can handle it.@@ -334,7 +335,10 @@ const config: Config = {transform: {// Include .mjs/.cjs so ESM dependencies allowed through transformIgnorePatterns (e.g. MSW's) are transpiled.'\\.[cm]?[jt]sx?$': '@sucrase/jest-plugin',+ // The transformer just wraps file text as a string module, so it serves any raw+ // text import, not only YAML.'\\.yaml$': '<rootDir>/src/test/yamlRawTransformer.js',+ '\\.md$': '<rootDir>/src/test/yamlRawTransformer.js',},// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformationdiff --git a/frontend/src/custom.d.ts b/frontend/src/custom.d.tsindex 392a4bd5c38b..189de4964526 100644--- a/frontend/src/custom.d.ts+++ b/frontend/src/custom.d.ts@@ -46,6 +46,12 @@ declare module '*.yaml?raw' {export default content}+// This fixes TS errors when importing a .md file with ?raw suffix+declare module '*.md?raw' {+ const content: string+ export default content+}+// This fixes TS2882 errors when side-effect importing .scss filesdeclare module '*.scss'diff --git a/products/ai_observability/backend/scouts/signals-scout-ai-observability-costly-users.md b/products/ai_observability/backend/scouts/signals-scout-ai-observability-costly-users.mdnew file mode 100644index 000000000000..338da311d7f9--- /dev/null+++ b/products/ai_observability/backend/scouts/signals-scout-ai-observability-costly-users.md@@ -0,0 +1,55 @@+---+name: signals-scout-ai-observability-costly-users+description: >+ Finds extraordinary user-level AI spend or usage, validates the cause in traces, and reports only+ patterns with a controllable next action.+scout-tags:+ - ai-observability+---++# AI observability costly or unusual users++Find extraordinary user-level cost or usage patterns in the most recent complete 24 hours. Compare them with the preceding 24 hours, the recent 7-day baseline, and the same weekday when traffic is seasonal. Never compare a complete period with a partial one.++A user ranking highly by spend is not a finding. Look for a material departure in unit economics or behavior with a controllable cause, validated in real traces. High volume with normal cost per trace may be healthy usage.++## Use the packaged analysis skills++Load these preinstalled skills through the runtime's packaged-skill mechanism when relevant:++- `analyzing-expensive-users`+- `exploring-llm-costs`+- `exploring-llm-traces`+- `querying-posthog-data`++These are packaged runtime skills, not project skill-store entries. Do not use `skill-list` or `skill-get` to load them.++## Avoid duplicate work++Read this Scout's last 14 days of run summaries with `scout-runs-list`, filtered by its exact `skill_name` and current `skill_version`. Retrieve relevant details with `scout-runs-retrieve`.++Search the scratchpad and recent Inbox reports for the user, segment, workflow, and suspected cause. If a live report already covers the same pattern, add only materially new evidence with `scout-edit-report`. Skip unchanged issues. Never create a second report for an unchanged issue.++## Investigate a bounded set++1. Rank identified users by generated-call spend. Include both `$ai_generation` and `$ai_embedding` when calculating full cost totals. Exclude rows where `distinct_id = properties.$ai_trace_id` when treating `distinct_id` as a user.+2. Establish the population baseline for cost share, traces, cost per generation, tokens, cache behavior, errors, and retries.+3. Select at most three candidates whose behavior materially differs from both the population and their own baseline.+4. Break each candidate down by model, provider, span, workflow, feature, or another property that exists in the project. Use `read-data-schema` before grouping by custom dimensions.+5. Open representative traces before explaining the cause. Aggregates identify candidates. Traces establish whether the cause is a retry loop, context growth, output growth, model choice, missing caching, abuse, or a product bug.++Minimize personal data. Use the least identifying stable label available. Never include raw prompts, responses, or full person-property objects in a report.++Close without a report when the highest-spend users are consistent with expected volume and normal unit economics.++## Report only actionable patterns++A report-worthy finding must be extraordinary against a relevant baseline, material and recent, supported by representative traces, and actionable through code, prompts, model choice, caching, limits, configuration, or product behavior.++Group users with the same root cause into one report. Create no more than two reports per run. Search the Inbox again before writing. Edit a matching live report instead of creating a duplicate.++Title a new report `Unusual AI spend: <segment and cause>`. Include the comparison window, the minimum numbers needed to judge the change, the trace-backed cause or best next investigation, and one specific next action. Include direct trace links or IDs as evidence.++Do not report routine top spenders, expected launches or batch jobs, test traffic, one costly trace without a repeatable problem, or a known provider incident already covered elsewhere.++Finish with a short run summary covering what you checked, what you reported or updated, and what you ruled out.diff --git a/products/ai_observability/backend/scouts/signals-scout-ai-observability-daily-digest.md b/products/ai_observability/backend/scouts/signals-scout-ai-observability-daily-digest.mdnew file mode 100644index 000000000000..d040adf955ec--- /dev/null+++ b/products/ai_observability/backend/scouts/signals-scout-ai-observability-daily-digest.md@@ -0,0 +1,60 @@+---+name: signals-scout-ai-observability-daily-digest+description: >+ Creates a concise, low-noise daily digest from the AI observability dashboard, errors, costly+ users, and online evaluations.+scout-tags:+ - ai-observability+---++# AI observability daily digest++Create one concise, actionable AI observability digest for the previous complete 24 hours in the project's timezone. Compare it with the preceding 24 hours, the recent 7-day baseline, and the same weekday when traffic is seasonal. Never compare a complete period with a partial one.++## Use the packaged analysis skills++The following skills are preinstalled in the Scout runtime. Load them through the runtime's packaged-skill mechanism when their workflow is relevant:++- `exploring-ai-failures`+- `exploring-llm-traces`+- `analyzing-expensive-users`+- `exploring-llm-costs`+- `exploring-llm-evaluations`+- `querying-posthog-data`++These are packaged runtime skills, not project skill-store entries. Use the runtime's packaged-skill loader, not `skill-list` or `skill-get`, to read them, and do not browse the skill store. `skill-get` is only for loading this bound Scout skill as directed by the harness.++## Avoid noise++First read this Scout's last 14 days of run summaries with `scout-runs-list`. Always filter by both this Scout's exact `skill_name` and its current `skill_version`; never use runs from another Scout, even when its name is similar. Retrieve relevant details with `scout-runs-retrieve`.++Search prior baselines or known noise with `scout-scratchpad-search`. Use only entries whose `created_by_skill` exactly matches this Scout, plus fleetwide guidance written by a human. Ignore entries created by other Scouts. Use `inbox-reports-list` only to deduplicate reports, not as Scout run history.++Do not repeat an unchanged issue. Include a recurring issue only when it materially worsened, recovered, relapsed, gained useful new evidence, or now needs a different action. Avoiding noise suppresses issue bullets, not the daily digest itself.++## Review these surfaces++- **Dashboard:** The canonical dashboard is the product view at `/project/{team_id}/ai-observability/dashboard`. Review the same usage, cost, latency, error, and performance measures with the underlying AI observability trace, cost, evaluation, and HogQL MCP tools. Never substitute a saved dashboard selected by name, tag, or fuzzy match. `dashboards-get-all`, `dashboard-get`, and `dashboard-insights-run` operate on saved dashboards and must not be used for this surface. If the available tools cannot reproduce a canonical dashboard measure, mark the dashboard surface incomplete instead of using a lookalike.+- **Errors and traces:** Use `exploring-ai-failures` and `exploring-llm-traces`. Inspect errors for new or changed patterns. When errors exist, open at least one representative trace before drawing a conclusion. Exclude expected cancellations, test traffic, known provider incidents, and recorded noise.+- **Costly users:** Use `analyzing-expensive-users` and `exploring-llm-costs`. Inspect costly users and their workflows, not only model-level spend. Never report a user merely for ranking highly or spending a lot. Include a user-level pattern only when it is extraordinary against the project baseline and reveals a controllable cause, such as a retry loop, incorrect model choice, bloated context, missing caching, abuse, or a product bug. Minimize personal data.+- **Online evaluations:** Use `exploring-llm-evaluations`. Inspect enabled evaluation configs and recent `$ai_evaluation` results for material pass-rate regressions, failure or N/A surges, missing expected results, or broken configuration. Localize the cause before including it.+- **Code, when available:** Use read-only repository access only to validate a likely cause or identify the relevant code and owner. Cite the path or commit. Do not speculate or block the digest when code access is unavailable.++Use the project's real dimensions. Validate aggregates with representative traces, evaluation runs, or direct evidence. Every included item must lead to a concrete next action on code, configuration, prompts, evaluations, model choice, caching, limits, or further investigation.++## Produce one digest++Every successful run must leave exactly one report for the date. It is the daily digest, never one report per finding. Before emitting, use `inbox-reports-list` to search for today's title and compare returned titles exactly. If an exact match exists, update that report with `scout-edit-report`; otherwise create it with `scout-emit-report`. Never create two digests for the same date.++Title it `AI observability daily digest: YYYY-MM-DD`. When no actionable or extraordinary finding clears the bar, still produce the report with the verdict `No material regressions` and a concise coverage summary.++When there are findings, keep the summary under 180 words with one to three bullets, ordered by impact. Each bullet must state:++- what changed, with the comparison window and only the numbers needed to judge it;+- why it matters and which model, feature, workflow, evaluation, or user segment is affected;+- the evidence-backed cause or best next investigation;+- a specific next action, including the likely owner when known.++Include direct links or IDs for the best evidence. Do not include routine metrics, unchanged leaderboards, raw query output, or filler. Write for a reader with no prior context. End the report with the surfaces checked and explicitly list any incomplete surface and why it was incomplete.++Update the scratchpad with useful baselines, noise, and dedupe decisions so tomorrow's run can avoid repeating work. Finish the run with one short note about what you checked and whether you created or updated the digest.diff --git a/products/ai_observability/backend/scouts/signals-scout-ai-observability-error-patterns.md b/products/ai_observability/backend/scouts/signals-scout-ai-observability-error-patterns.mdnew file mode 100644index 000000000000..9e7530460705--- /dev/null+++ b/products/ai_observability/backend/scouts/signals-scout-ai-observability-error-patterns.md@@ -0,0 +1,62 @@+---+name: signals-scout-ai-observability-error-patterns+description: >+ Finds new or growing AI failure modes, including silent quality failures, and validates each+ pattern against real traces.+scout-tags:+ - ai-observability+---++# AI observability error patterns++Find new, growing, or recurring AI failure modes in the most recent complete 24 hours. Compare them with the preceding 24 hours and the recent 7-day baseline.++The main signal is a recurring failure mode within one use case, validated by real traces and tied to a concrete next action. Raw error counts are pointers to investigate, not findings. Important AI failures can return HTTP 200 with no exception.++## Use the packaged analysis skills++Load these preinstalled skills through the runtime's packaged-skill mechanism when relevant:++- `exploring-ai-failures`+- `exploring-llm-traces`+- `exploring-llm-clusters`+- `exploring-llm-evaluations`+- `querying-posthog-data`++These are packaged runtime skills, not project skill-store entries. Do not use `skill-list` or `skill-get` to load them.++## Avoid duplicate work++Read this Scout's last 14 days of run summaries with `scout-runs-list`, filtered by its exact `skill_name` and current `skill_version`. Retrieve relevant details with `scout-runs-retrieve`.++Search the scratchpad and recent Inbox reports for the use case, failure mode, error, evaluation, cluster, and suspected cause. If a live report already covers the same pattern, add only materially new evidence with `scout-edit-report`. Skip it when the evidence and impact are unchanged.++## Find and read failures++Work on one use case at a time because different trace types fail differently.++1. Discover the project's trace taxonomy from properties that actually exist, such as feature, workflow, model, or span name.+2. Choose the use case with the clearest recent change or the stalest prior coverage.+3. Select traces using the signals that fit the data: explicit errors, tool failures, retries, evaluation failures, negative feedback, latency or token outliers, semantic clusters, or a stratified sample.+4. Open and read real traces. Queries choose what to read but do not establish a failure mode.+5. Identify the first thing that went wrong in each failing trace and group traces by that root failure instead of downstream symptoms.+6. Continue until the common modes stabilize, with a maximum of 25 traces in one run.+7. Quantify each mode against the full use-case population. Keep sample counts and population estimates separate.++Look for loud errors and silent failures such as ignored instructions, wrong answers, missing context, tool misuse, loops, malformed output, or incomplete work. Do not infer a silent failure from text matching alone.++Minimize personal data. Summarize the relevant behavior and cite trace IDs or links without copying sensitive prompt or response content.++Close without a report when no repeated, materially changed, or actionable failure mode clears the bar.++## Report only actionable patterns++A report-worthy failure must appear across independent traces or have clear systemic impact, be new or materially worse than baseline, be validated by representative traces, and lead to a concrete action.++Create one report per root failure, not per trace or error string. Create no more than two reports per run. Search the Inbox again before writing. Edit a matching live report instead of creating a duplicate.++Title a new report `AI error pattern: <specific mode>`. Include the affected use case and comparison window, how often it appeared, what failed first, why it matters, and the best next action. Include one to three representative trace links or IDs.++Do not report expected cancellations, test or synthetic evaluation traffic presented as production impact, known provider incidents covered elsewhere, one-off traces without systemic impact, or error aggregates that were not validated by reading traces.++Finish with a short run summary covering what you reviewed, what you reported or updated, and what you ruled out.diff --git a/products/ai_observability/frontend/AIObservabilityDigestScoutButton.test.tsx b/products/ai_observability/frontend/AIObservabilityDigestScoutButton.test.tsxdeleted file mode 100644index 223848789793..000000000000--- a/products/ai_observability/frontend/AIObservabilityDigestScoutButton.test.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { getAIObservabilityDigestScoutInitialValues } from './AIObservabilityDigestScoutButton'--describe('AI observability daily digest scout template', () => {- it('prefills a daily 9 a.m. scout that reviews canonical AI observability data and always produces one digest', () => {- const initialValues = getAIObservabilityDigestScoutInitialValues()-- expect(initialValues).toMatchObject({- name: 'signals-scout-ai-observability-daily-digest',- config: {- enabled: true,- emit: true,- run_interval_minutes: 1440,- run_cron_schedule: '0 9 * * *',- tags: ['ai-observability'],- },- })- expect(initialValues.body).toEqual(expect.stringContaining('/project/{team_id}/ai-observability/dashboard'))- expect(initialValues.body).toEqual(expect.stringContaining('must not be used for this surface'))- expect(initialValues.body).toEqual(expect.stringContaining('preinstalled in the Scout runtime'))- for (const skillName of [- 'exploring-ai-failures',- 'exploring-llm-traces',- 'analyzing-expensive-users',- 'exploring-llm-costs',- 'exploring-llm-evaluations',- 'querying-posthog-data',- ]) {- expect(initialValues.body).toEqual(expect.stringContaining(`\`${skillName}\``))- }- expect(initialValues.body).toEqual(- expect.stringContaining('`skill-get` is only for loading this bound Scout skill')- )- expect(initialValues.body).toEqual(- expect.stringContaining("both this Scout's exact `skill_name` and its current `skill_version`")- )- expect(initialValues.body).toEqual(- expect.stringContaining('whose `created_by_skill` exactly matches this Scout')- )- expect(initialValues.body).toEqual(expect.stringContaining('Do not repeat an unchanged issue'))- expect(initialValues.body).toEqual(- expect.stringContaining('Every successful run must leave exactly one report')- )- expect(initialValues.body).toEqual(expect.stringContaining('No material regressions'))- expect(initialValues.body).toEqual(expect.stringContaining('list any incomplete surface'))- expect(initialValues.body).toEqual(- expect.stringContaining('Every included item must lead to a concrete next action')- )- })-})diff --git a/products/ai_observability/frontend/AIObservabilityDigestScoutButton.tsx b/products/ai_observability/frontend/AIObservabilityDigestScoutButton.tsxdeleted file mode 100644index fa3e5589c9c5..000000000000--- a/products/ai_observability/frontend/AIObservabilityDigestScoutButton.tsx+++ /dev/null@@ -1,69 +0,0 @@-import type { ScoutCreateInitialValues } from 'products/signals/frontend/inbox/logics/scoutCreateModalLogic'--const AI_OBSERVABILITY_DIGEST_SCOUT_NAME = 'signals-scout-ai-observability-daily-digest'--export function getAIObservabilityDigestScoutInitialValues(): ScoutCreateInitialValues {- return {- name: AI_OBSERVABILITY_DIGEST_SCOUT_NAME,- description:- 'Creates a concise, low-noise daily digest from the AI observability dashboard, errors, costly users, and online evaluations.',- body: `# AI observability daily digest--Create one concise, actionable AI observability digest for the previous complete 24 hours in the project's timezone. Compare it with the preceding 24 hours, the recent 7-day baseline, and the same weekday when traffic is seasonal. Never compare a complete period with a partial one.--## Use the packaged analysis skills--The following skills are preinstalled in the Scout runtime. Load them through the runtime's packaged-skill mechanism when their workflow is relevant:--- \`exploring-ai-failures\`-- \`exploring-llm-traces\`-- \`analyzing-expensive-users\`-- \`exploring-llm-costs\`-- \`exploring-llm-evaluations\`-- \`querying-posthog-data\`--These are packaged runtime skills, not project skill-store entries. Use the runtime's packaged-skill loader, not \`skill-list\` or \`skill-get\`, to read them, and do not browse the skill store. \`skill-get\` is only for loading this bound Scout skill as directed by the harness.--## Avoid noise--First read this Scout's last 14 days of run summaries with \`scout-runs-list\`. Always filter by both this Scout's exact \`skill_name\` and its current \`skill_version\`; never use runs from another Scout, even when its name is similar. Retrieve relevant details with \`scout-runs-retrieve\`.--Search prior baselines or known noise with \`scout-scratchpad-search\`. Use only entries whose \`created_by_skill\` exactly matches this Scout, plus fleetwide guidance written by a human. Ignore entries created by other Scouts. Use \`inbox-reports-list\` only to deduplicate reports, not as Scout run history.--Do not repeat an unchanged issue. Include a recurring issue only when it materially worsened, recovered, relapsed, gained useful new evidence, or now needs a different action. Avoiding noise suppresses issue bullets, not the daily digest itself.--## Review these surfaces--- **Dashboard:** The canonical dashboard is the product view at \`/project/{team_id}/ai-observability/dashboard\`. Review the same usage, cost, latency, error, and performance measures with the underlying AI observability trace, cost, evaluation, and HogQL MCP tools. Never substitute a saved dashboard selected by name, tag, or fuzzy match. \`dashboards-get-all\`, \`dashboard-get\`, and \`dashboard-insights-run\` operate on saved dashboards and must not be used for this surface. If the available tools cannot reproduce a canonical dashboard measure, mark the dashboard surface incomplete instead of using a lookalike.-- **Errors and traces:** Use \`exploring-ai-failures\` and \`exploring-llm-traces\`. Inspect errors for new or changed patterns. When errors exist, open at least one representative trace before drawing a conclusion. Exclude expected cancellations, test traffic, known provider incidents, and recorded noise.-- **Costly users:** Use \`analyzing-expensive-users\` and \`exploring-llm-costs\`. Inspect costly users and their workflows, not only model-level spend. Never report a user merely for ranking highly or spending a lot. Include a user-level pattern only when it is extraordinary against the project baseline and reveals a controllable cause, such as a retry loop, incorrect model choice, bloated context, missing caching, abuse, or a product bug. Minimize personal data.-- **Online evaluations:** Use \`exploring-llm-evaluations\`. Inspect enabled evaluation configs and recent \`$ai_evaluation\` results for material pass-rate regressions, failure or N/A surges, missing expected results, or broken configuration. Localize the cause before including it.-- **Code, when available:** Use read-only repository access only to validate a likely cause or identify the relevant code and owner. Cite the path or commit. Do not speculate or block the digest when code access is unavailable.--Use the project's real dimensions. Validate aggregates with representative traces, evaluation runs, or direct evidence. Every included item must lead to a concrete next action on code, configuration, prompts, evaluations, model choice, caching, limits, or further investigation.--## Produce one digest--Every successful run must leave exactly one report for the date. It is the daily digest, never one report per finding. Before emitting, use \`inbox-reports-list\` to search for today's title and compare returned titles exactly. If an exact match exists, update that report with \`scout-edit-report\`; otherwise create it with \`scout-emit-report\`. Never create two digests for the same date.--Title it \`AI observability daily digest: YYYY-MM-DD\`. When no actionable or extraordinary finding clears the bar, still produce the report with the verdict \`No material regressions\` and a concise coverage summary.--When there are findings, keep the summary under 180 words with one to three bullets, ordered by impact. Each bullet must state:--- what changed, with the comparison window and only the numbers needed to judge it;-- why it matters and which model, feature, workflow, evaluation, or user segment is affected;-- the evidence-backed cause or best next investigation;-- a specific next action, including the likely owner when known.--Include direct links or IDs for the best evidence. Do not include routine metrics, unchanged leaderboards, raw query output, or filler. Write for a reader with no prior context. End the report with the surfaces checked and explicitly list any incomplete surface and why it was incomplete.--Update the scratchpad with useful baselines, noise, and dedupe decisions so tomorrow's run can avoid repeating work. Finish the run with one short note about what you checked and whether you created or updated the digest.`,- config: {- enabled: true,- emit: true,- run_interval_minutes: 1440,- run_cron_schedule: '0 9 * * *',- tags: ['ai-observability'],- },- }-}diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsxindex e3a67fda6d8a..a980b5dad963 100644--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx@@ -3,7 +3,6 @@ import '@testing-library/jest-dom'import { cleanup, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'kea'-import type { ReactNode } from 'react'import { lemonToast } from '@posthog/lemon-ui'@@ -14,6 +13,7 @@ import { newInternalTab } from 'lib/utils/newInternalTab'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, type AppContext } from '~/types'import * as alertsApi from 'products/alerts/frontend/generated/api'@@ -37,10 +37,6 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutMetadataGet: jest.fn(() => new Promise(() => {})),}))-jest.mock('products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton', () => ({- ScoutCreateButton: ({ children }: { children: ReactNode }) => <button>{children}</button>,-}))-const EVAL_REPORTS_SOURCE_CONFIG = {id: 'source-config-eval-reports',source_product: 'llm_analytics',@@ -93,6 +89,13 @@ describe('AIObservabilitySelfDriving', () => {},},})+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.LlmSkill]: AccessControlLevel.Editor,+ },+ } as AppContextinitKeaTests()featureFlagLogic.mount()featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_START_WITH_AI], {@@ -259,6 +262,11 @@ describe('AIObservabilitySelfDriving', () => {expect(screen.getAllByText('Use template')).toHaveLength(3)+ // Counting the labels alone passes even when every button is disabled, which is what+ // happens if the scene stops granting scout-creation access. Prove one actually opens.+ await userEvent.click(screen.getByTestId('create-costly-users-scout'))+ expect(await screen.findByText('Create a scout')).toBeInTheDocument()+const tooltipTrigger = screen.getByText('What is this?')await userEvent.hover(tooltipTrigger)diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsxindex c8768eafde40..282cbfb9abe4 100644--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'import type { ReactNode } from 'react'-import { IconCalendar, IconQuestion, IconUser, IconWarning } from '@posthog/icons'+import { IconCalendar, IconPlus, IconQuestion, IconUser, IconWarning } from '@posthog/icons'import {LemonBanner,LemonButton,@@ -28,7 +28,10 @@ import { urls } from 'scenes/urls'import type { InsightShortId } from '~/types'import type { AlertApi } from 'products/alerts/frontend/generated/api.schemas'-import { ScoutCreateButton } from 'products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton'+import {+ ScoutCreateModalHost,+ useScoutCreateDisabledReason,+} from 'products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost'import { ScoutSummaryRow } from 'products/signals/frontend/inbox/components/config/scouts/ScoutSummaryRow'import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'import { signalSourcesLogic } from 'products/signals/frontend/inbox/signalSourcesLogic'@@ -39,6 +42,7 @@ import type { EvaluationReportApi } from '../generated/api.schemas'import {AI_OBSERVABILITY_SCOUT_TEMPLATES,AIObservabilityScoutTemplate,+ findAIObservabilityScoutTemplate,isAIObservabilityScout,} from './aiObservabilityScoutTemplates'import {@@ -158,9 +162,28 @@ const TEMPLATE_ICONS: Record<AIObservabilityScoutTemplate['key'], JSX.Element> ='error-patterns': <IconWarning />,}-function ScoutTemplateCard({ template }: { template: AIObservabilityScoutTemplate }): JSX.Element {+/**+ * The one create modal for this tab, so a card click and a `#template=` link land in the same+ * place. Hosted beside the cards rather than inside one, since the URL can open it for any of them.+ */+function ScoutTemplateModal(): JSX.Element | null {+ const { openScoutTemplateKey } = useValues(aiObservabilitySelfDrivingLogic)+ const { setOpenScoutTemplateKey } = useActions(aiObservabilitySelfDrivingLogic)const { loadScoutConfigs } = useActions(scoutFleetLogic)+ return (+ <ScoutCreateModalHost+ initialValues={findAIObservabilityScoutTemplate(openScoutTemplateKey)?.initialValues ?? null}+ onClose={() => setOpenScoutTemplateKey(null)}+ onCreated={() => loadScoutConfigs()}+ />+ )+}++function ScoutTemplateCard({ template }: { template: AIObservabilityScoutTemplate }): JSX.Element {+ const { setOpenScoutTemplateKey } = useActions(aiObservabilitySelfDrivingLogic)+ const creationDisabledReason = useScoutCreateDisabledReason()+return (<LemonCard hoverEffect={false} className="flex flex-col gap-3 p-3"><div className="flex min-w-0 items-start gap-2">@@ -174,13 +197,16 @@ function ScoutTemplateCard({ template }: { template: AIObservabilityScoutTemplat<LemonTag type="muted" size="small">{template.schedule}</LemonTag>- <ScoutCreateButton- initialValues={template.initialValues}- onCreated={() => loadScoutConfigs()}+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ disabledReason={creationDisabledReason ?? undefined}+ onClick={() => setOpenScoutTemplateKey(template.key)}data-attr={`create-${template.key}-scout`}>Use template- </ScoutCreateButton>+ </LemonButton></div></LemonCard>)@@ -332,6 +358,8 @@ export function AIObservabilitySelfDriving(): JSX.Element {return (<div className="flex flex-col gap-4">+ {/* Outside the collapse: a `#template=` link has to work even with Scouts collapsed. */}+ <ScoutTemplateModal /><LemonBanner type="info" className="text-sm"><p className="m-0">To power{' '}diff --git a/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.test.ts b/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.test.tsindex d87548b0e4e0..0f87dff47dd3 100644--- a/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.test.ts+++ b/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.test.ts@@ -17,8 +17,15 @@ describe('AI observability scout templates', () => {it.each(AI_OBSERVABILITY_SCOUT_TEMPLATES)('$title creates an enabled 9 a.m. daily scout with the product tag',({ initialValues, schedule }) => {+ // Every field comes out of a SKILL.md parsed at module scope, so a malformed file is a+ // commit away. These assertions are what stops one reaching the eager import in+ // AIObservabilityScene.expect(initialValues.name).toMatch(/^signals-scout-ai-observability-/)- expect(initialValues.body).toBeTruthy()+ expect(initialValues.description?.trim()).toBeTruthy()+ // The body is read out of a SKILL.md whose frontmatter carries name and description as+ // separate form fields. A broken strip would push `---\nname: ...` into Instructions.+ expect(initialValues.body).not.toMatch(/^---/)+ expect(initialValues.body).toMatch(/^# /)expect(schedule).toBe('Daily at 9:00 AM')expect(initialValues.config).toMatchObject({enabled: true,diff --git a/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.ts b/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.tsindex 9ea61e6f127c..cd2e3d9d3e5f 100644--- a/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.ts+++ b/products/ai_observability/frontend/selfDriving/aiObservabilityScoutTemplates.ts@@ -1,164 +1,107 @@+import { parse as parseYaml } from 'yaml'+import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'import type { ScoutCreateInitialValues } from 'products/signals/frontend/inbox/logics/scoutCreateModalLogic'import { scoutTags } from 'products/signals/frontend/inbox/utils/scoutTags'-import { getAIObservabilityDigestScoutInitialValues } from '../AIObservabilityDigestScoutButton'+import costlyUsersSkill from '../../backend/scouts/signals-scout-ai-observability-costly-users.md?raw'+import dailyDigestSkill from '../../backend/scouts/signals-scout-ai-observability-daily-digest.md?raw'+import errorPatternsSkill from '../../backend/scouts/signals-scout-ai-observability-error-patterns.md?raw'export const AI_OBSERVABILITY_SCOUT_TAG = 'ai-observability'+export type AIObservabilityScoutTemplateKey = 'daily-digest' | 'costly-users' | 'error-patterns'+export interface AIObservabilityScoutTemplate {- key: 'daily-digest' | 'costly-users' | 'error-patterns'+ key: AIObservabilityScoutTemplateKeytitle: stringdescription: stringschedule: stringinitialValues: ScoutCreateInitialValues}+const FRONTMATTER_BLOCK = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/++interface ScoutSkillFrontmatter {+ name?: string+ description?: string+ 'scout-tags'?: string[]+}++/** Every template runs daily at 9 a.m. and writes to the inbox. Tags come from the skill file. */+const DAILY_AT_9AM: Omit<NonNullable<ScoutCreateInitialValues['config']>, 'tags'> = {+ enabled: true,+ emit: true,+ run_interval_minutes: 1440,+ run_cron_schedule: '0 9 * * *',+}++/**+ * Splits a scout's `SKILL.md` into the fields the create form takes separately. The file is the+ * single source for the scout itself — posthog.com's pocket guides fetch the same one — so+ * everything here is read from it rather than restated.+ *+ * `source` names the file in any throw: all three parse at module scope, so without it a malformed+ * file gives an error nobody can trace back to a filename.+ */+function readScoutSkill(raw: string, source: string): ScoutCreateInitialValues {+ const match = raw.match(FRONTMATTER_BLOCK)+ if (!match) {+ throw new Error(`Scout skill file ${source} is missing its frontmatter`)+ }++ const frontmatter = (parseYaml(match[1]) ?? {}) as ScoutSkillFrontmatter+ const name = frontmatter.name?.trim()+ const description = frontmatter.description?.trim()+ // Explicit emptiness checks rather than `??`: a blank value parses fine and would otherwise+ // reach the create form as an empty name.+ if (!name) {+ throw new Error(`Scout skill file ${source} is missing a name`)+ }+ if (!description) {+ throw new Error(`Scout skill file ${source} is missing a description`)+ }++ return {+ name,+ description,+ body: raw.slice(match[0].length).trim(),+ // `scout-tags` is the canonical frontmatter field for a scout's config tags, so the file+ // carries them too and stays liftable into products/signals/skills/ unchanged.+ config: { ...DAILY_AT_9AM, tags: frontmatter['scout-tags'] ?? [] },+ }+}+export const AI_OBSERVABILITY_SCOUT_TEMPLATES: AIObservabilityScoutTemplate[] = [{key: 'daily-digest',title: 'Daily digest',description: 'Summarize meaningful changes in AI usage, cost, errors, costly users, and evaluations.',schedule: 'Daily at 9:00 AM',- initialValues: getAIObservabilityDigestScoutInitialValues(),+ initialValues: readScoutSkill(dailyDigestSkill, 'signals-scout-ai-observability-daily-digest.md'),},{key: 'costly-users',title: 'Costly or unusual users',description: 'Find unusual usage and very costly users, then trace the spend to a cause you can act on.',schedule: 'Daily at 9:00 AM',- initialValues: {- name: 'signals-scout-ai-observability-costly-users',- description:- 'Finds extraordinary user-level AI spend or usage, validates the cause in traces, and reports only patterns with a controllable next action.',- body: `# AI observability costly or unusual users--Find extraordinary user-level cost or usage patterns in the most recent complete 24 hours. Compare them with the preceding 24 hours, the recent 7-day baseline, and the same weekday when traffic is seasonal. Never compare a complete period with a partial one.--A user ranking highly by spend is not a finding. Look for a material departure in unit economics or behavior with a controllable cause, validated in real traces. High volume with normal cost per trace may be healthy usage.--## Use the packaged analysis skills--Load these preinstalled skills through the runtime's packaged-skill mechanism when relevant:--- \`analyzing-expensive-users\`-- \`exploring-llm-costs\`-- \`exploring-llm-traces\`-- \`querying-posthog-data\`--These are packaged runtime skills, not project skill-store entries. Do not use \`skill-list\` or \`skill-get\` to load them.--## Avoid duplicate work--Read this Scout's last 14 days of run summaries with \`scout-runs-list\`, filtered by its exact \`skill_name\` and current \`skill_version\`. Retrieve relevant details with \`scout-runs-retrieve\`.--Search the scratchpad and recent Inbox reports for the user, segment, workflow, and suspected cause. If a live report already covers the same pattern, add only materially new evidence with \`scout-edit-report\`. Skip unchanged issues. Never create a second report for an unchanged issue.--## Investigate a bounded set--1. Rank identified users by generated-call spend. Include both \`$ai_generation\` and \`$ai_embedding\` when calculating full cost totals. Exclude rows where \`distinct_id = properties.$ai_trace_id\` when treating \`distinct_id\` as a user.-2. Establish the population baseline for cost share, traces, cost per generation, tokens, cache behavior, errors, and retries.-3. Select at most three candidates whose behavior materially differs from both the population and their own baseline.-4. Break each candidate down by model, provider, span, workflow, feature, or another property that exists in the project. Use \`read-data-schema\` before grouping by custom dimensions.-5. Open representative traces before explaining the cause. Aggregates identify candidates. Traces establish whether the cause is a retry loop, context growth, output growth, model choice, missing caching, abuse, or a product bug.--Minimize personal data. Use the least identifying stable label available. Never include raw prompts, responses, or full person-property objects in a report.--Close without a report when the highest-spend users are consistent with expected volume and normal unit economics.--## Report only actionable patterns--A report-worthy finding must be extraordinary against a relevant baseline, material and recent, supported by representative traces, and actionable through code, prompts, model choice, caching, limits, configuration, or product behavior.--Group users with the same root cause into one report. Create no more than two reports per run. Search the Inbox again before writing. Edit a matching live report instead of creating a duplicate.--Title a new report \`Unusual AI spend: <segment and cause>\`. Include the comparison window, the minimum numbers needed to judge the change, the trace-backed cause or best next investigation, and one specific next action. Include direct trace links or IDs as evidence.--Do not report routine top spenders, expected launches or batch jobs, test traffic, one costly trace without a repeatable problem, or a known provider incident already covered elsewhere.--Finish with a short run summary covering what you checked, what you reported or updated, and what you ruled out.`,- config: {- enabled: true,- emit: true,- run_interval_minutes: 1440,- run_cron_schedule: '0 9 * * *',- tags: [AI_OBSERVABILITY_SCOUT_TAG],- },- },+ initialValues: readScoutSkill(costlyUsersSkill, 'signals-scout-ai-observability-costly-users.md'),},{key: 'error-patterns',title: 'Error patterns',description: 'Read real traces to find recurring errors and silent AI failures worth fixing.',schedule: 'Daily at 9:00 AM',- initialValues: {- name: 'signals-scout-ai-observability-error-patterns',- description:- 'Finds new or growing AI failure modes, including silent quality failures, and validates each pattern against real traces.',- body: `# AI observability error patterns--Find new, growing, or recurring AI failure modes in the most recent complete 24 hours. Compare them with the preceding 24 hours and the recent 7-day baseline.--The main signal is a recurring failure mode within one use case, validated by real traces and tied to a concrete next action. Raw error counts are pointers to investigate, not findings. Important AI failures can return HTTP 200 with no exception.--## Use the packaged analysis skills--Load these preinstalled skills through the runtime's packaged-skill mechanism when relevant:--- \`exploring-ai-failures\`-- \`exploring-llm-traces\`-- \`exploring-llm-clusters\`-- \`exploring-llm-evaluations\`-- \`querying-posthog-data\`--These are packaged runtime skills, not project skill-store entries. Do not use \`skill-list\` or \`skill-get\` to load them.--## Avoid duplicate work--Read this Scout's last 14 days of run summaries with \`scout-runs-list\`, filtered by its exact \`skill_name\` and current \`skill_version\`. Retrieve relevant details with \`scout-runs-retrieve\`.--Search the scratchpad and recent Inbox reports for the use case, failure mode, error, evaluation, cluster, and suspected cause. If a live report already covers the same pattern, add only materially new evidence with \`scout-edit-report\`. Skip it when the evidence and impact are unchanged.--## Find and read failures--Work on one use case at a time because different trace types fail differently.--1. Discover the project's trace taxonomy from properties that actually exist, such as feature, workflow, model, or span name.-2. Choose the use case with the clearest recent change or the stalest prior coverage.-3. Select traces using the signals that fit the data: explicit errors, tool failures, retries, evaluation failures, negative feedback, latency or token outliers, semantic clusters, or a stratified sample.-4. Open and read real traces. Queries choose what to read but do not establish a failure mode.-5. Identify the first thing that went wrong in each failing trace and group traces by that root failure instead of downstream symptoms.-6. Continue until the common modes stabilize, with a maximum of 25 traces in one run.-7. Quantify each mode against the full use-case population. Keep sample counts and population estimates separate.--Look for loud errors and silent failures such as ignored instructions, wrong answers, missing context, tool misuse, loops, malformed output, or incomplete work. Do not infer a silent failure from text matching alone.--Minimize personal data. Summarize the relevant behavior and cite trace IDs or links without copying sensitive prompt or response content.--Close without a report when no repeated, materially changed, or actionable failure mode clears the bar.--## Report only actionable patterns--A report-worthy failure must appear across independent traces or have clear systemic impact, be new or materially worse than baseline, be validated by representative traces, and lead to a concrete action.--Create one report per root failure, not per trace or error string. Create no more than two reports per run. Search the Inbox again before writing. Edit a matching live report instead of creating a duplicate.--Title a new report \`AI error pattern: <specific mode>\`. Include the affected use case and comparison window, how often it appeared, what failed first, why it matters, and the best next action. Include one to three representative trace links or IDs.--Do not report expected cancellations, test or synthetic evaluation traffic presented as production impact, known provider incidents covered elsewhere, one-off traces without systemic impact, or error aggregates that were not validated by reading traces.--Finish with a short run summary covering what you reviewed, what you reported or updated, and what you ruled out.`,- config: {- enabled: true,- emit: true,- run_interval_minutes: 1440,- run_cron_schedule: '0 9 * * *',- tags: [AI_OBSERVABILITY_SCOUT_TAG],- },- },+ initialValues: readScoutSkill(errorPatternsSkill, 'signals-scout-ai-observability-error-patterns.md'),},]+/** Looks a template up by key. Returns undefined for anything not in the list, so an untrusted+ * value (a URL fragment, say) can be resolved and validated in one step. */+export function findAIObservabilityScoutTemplate(key: unknown): AIObservabilityScoutTemplate | undefined {+ return AI_OBSERVABILITY_SCOUT_TEMPLATES.find((template) => template.key === key)+}+export function isAIObservabilityScout(config: SignalScoutConfigApi): boolean {return scoutTags(config).includes(AI_OBSERVABILITY_SCOUT_TAG)}diff --git a/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.test.ts b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.test.tsnew file mode 100644index 000000000000..d9e0d30f4e9e--- /dev/null+++ b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.test.ts@@ -0,0 +1,87 @@+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'++import * as alertsApi from 'products/alerts/frontend/generated/api'++import * as aiObservabilityApi from '../generated/api'+import { aiObservabilitySelfDrivingLogic } from './aiObservabilitySelfDrivingLogic'++jest.mock('../generated/api', () => ({+ llmAnalyticsEvaluationReportsList: jest.fn(),+}))++jest.mock('products/alerts/frontend/generated/api', () => ({+ alertsList: jest.fn(),+}))++jest.mock('products/signals/frontend/generated/api', () => ({+ signalsScoutConfigList: jest.fn(() => new Promise(() => {})),+ signalsScoutMetadataGet: jest.fn(() => new Promise(() => {})),+}))++const SELF_DRIVING_URL = '/ai-observability/self-driving'++describe('aiObservabilitySelfDrivingLogic', () => {+ let logic: ReturnType<typeof aiObservabilitySelfDrivingLogic.build>++ beforeEach(() => {+ silenceKeaLoadersErrors()+ initKeaTests()+ jest.mocked(alertsApi.alertsList).mockResolvedValue({+ results: [],+ count: 0,+ next: null,+ previous: null,+ } as any)+ jest.mocked(aiObservabilityApi.llmAnalyticsEvaluationReportsList).mockResolvedValue({+ results: [],+ count: 0,+ next: null,+ previous: null,+ } as any)+ })++ afterEach(() => {+ logic?.unmount()+ resumeKeaLoadersErrors()+ jest.clearAllMocks()+ })++ const mountAt = (hash: Record<string, string>): void => {+ router.actions.push(SELF_DRIVING_URL, {}, hash)+ logic = aiObservabilitySelfDrivingLogic()+ logic.mount()+ }++ it.each([+ ['a known template key', { template: 'costly-users' }, 'costly-users'],+ ['a second known template key', { template: 'error-patterns' }, 'error-patterns'],+ ['an unknown template key', { template: 'not-a-template' }, null],+ ['no template key at all', {}, null],+ ])('opens the template %s names, and nothing else', (_label, hash, expected) => {+ mountAt(hash)++ expect(logic.values.openScoutTemplateKey).toBe(expected)+ })++ it('tells the reader when a link names a template that does not exist', () => {+ // The fragment is stripped before the lookup, so without this the reader is left with a+ // page that silently ignored their link.+ const toastError = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as any)++ mountAt({ template: 'not-a-template' })++ expect(toastError).toHaveBeenCalledTimes(1)+ toastError.mockRestore()+ })++ it('strips the template fragment so a refresh does not reopen the modal', () => {+ mountAt({ template: 'daily-digest', other: 'kept' })++ expect(router.values.hashParams).toEqual({ other: 'kept' })+ })+})diff --git a/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.tsindex 74291a768594..bccbe65142d0 100644--- a/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts+++ b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts@@ -1,7 +1,11 @@import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import * as alertsApi from 'products/alerts/frontend/generated/api'import type { AlertApi } from 'products/alerts/frontend/generated/api.schemas'@@ -11,7 +15,11 @@ import type { SignalSourceConfig } from 'products/signals/frontend/inbox/types'import { listAllEvaluationReports } from '../evaluations/evaluationsApi'import type { EvaluationReportApi } from '../generated/api.schemas'import { listAllPages } from '../listAllPages'-import { AI_OBSERVABILITY_SCOUT_TAG } from './aiObservabilityScoutTemplates'+import {+ AI_OBSERVABILITY_SCOUT_TAG,+ type AIObservabilityScoutTemplateKey,+ findAIObservabilityScoutTemplate,+} from './aiObservabilityScoutTemplates'const ANOMALY_ALERTS_PAGE_SIZE = 100@@ -51,6 +59,7 @@ export interface aiObservabilitySelfDrivingLogicValues {evaluationReportsByEvaluationId: Record<string, EvaluationReportApi> | nullevaluationReportsLoading: booleanexpandedSections: AIObservabilitySelfDrivingSection[]+ openScoutTemplateKey: AIObservabilityScoutTemplateKey | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -89,6 +98,9 @@ export interface aiObservabilitySelfDrivingLogicActions {setExpandedSections: (expandedSections: AIObservabilitySelfDrivingSection[]) => {expandedSections: AIObservabilitySelfDrivingSection[]}+ setOpenScoutTemplateKey: (openScoutTemplateKey: AIObservabilityScoutTemplateKey | null) => {+ openScoutTemplateKey: AIObservabilityScoutTemplateKey | null+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -117,6 +129,9 @@ export const aiObservabilitySelfDrivingLogic = kea<aiObservabilitySelfDrivingLogactions({setExpandedSections: (expandedSections: AIObservabilitySelfDrivingSection[]) => ({ expandedSections }),+ setOpenScoutTemplateKey: (openScoutTemplateKey: AIObservabilityScoutTemplateKey | null) => ({+ openScoutTemplateKey,+ }),}),loaders({@@ -148,6 +163,12 @@ export const aiObservabilitySelfDrivingLogic = kea<aiObservabilitySelfDrivingLogsetExpandedSections: (_, { expandedSections }) => expandedSections,},],+ openScoutTemplateKey: [+ null as AIObservabilityScoutTemplateKey | null,+ {+ setOpenScoutTemplateKey: (_, { openScoutTemplateKey }) => openScoutTemplateKey,+ },+ ],}),selectors({@@ -162,6 +183,27 @@ export const aiObservabilitySelfDrivingLogic = kea<aiObservabilitySelfDrivingLog],}),+ // `#template=<key>` opens that template's create modal, so a posthog.com pocket guide can hand+ // someone straight into it. The fragment is stripped on arrival: it carries no config of its+ // own (the template does), and leaving it in the URL would reopen the modal on every refresh.+ urlToAction(({ actions }) => ({+ [urls.aiObservabilitySelfDriving()]: (_, __, hashParams) => {+ if (hashParams?.['template'] === undefined) {+ return+ }+ const { template, ...remainingHashParams } = hashParams+ router.actions.replace(router.values.location.pathname, router.values.searchParams, remainingHashParams)+ const matched = findAIObservabilityScoutTemplate(template)+ if (matched) {+ actions.setOpenScoutTemplateKey(matched.key)+ } else {+ // The fragment is already stripped, so staying silent would leave the reader with+ // nothing to look at and nothing to report. `inboxSceneLogic` toasts here too.+ lemonToast.error("That link points to a scout template that doesn't exist. Pick one below.")+ }+ },+ })),+afterMount(({ actions, values }) => {actions.loadAnomalyAlertInvestigations()actions.loadSelfDrivingEvaluationReports()diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.tsxindex df761553c5ad..e7a35f513691 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton.tsx@@ -3,19 +3,10 @@ import React, { useState } from 'react'import { IconPlus } from '@posthog/icons'import { LemonButton, type LemonButtonProps } from '@posthog/lemon-ui'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'--import { AccessControlLevel, AccessControlResourceType } from '~/types'-import type { SignalScoutCreateResponseApi } from 'products/signals/frontend/generated/api.schemas'-import { captureScoutAction } from '../../../inboxAnalytics'import type { ScoutCreateInitialValues } from '../../../logics/scoutCreateModalLogic'--const LazyScoutCreateModal = React.lazy(async () => {- const { ScoutCreateModal } = await import('./ScoutCreateModal')- return { default: ScoutCreateModal }-})+import { ScoutCreateModalHost, useScoutCreateDisabledReason } from './ScoutCreateModalHost'export interface ScoutCreateButtonProps {children?: React.ReactNode@@ -38,10 +29,7 @@ export function ScoutCreateButton({'data-attr': dataAttr,}: ScoutCreateButtonProps): JSX.Element {const [isModalOpen, setIsModalOpen] = useState(false)- const creationDisabledReason = getAccessControlDisabledReason(- AccessControlResourceType.LlmSkill,- AccessControlLevel.Editor- )+ const creationDisabledReason = useScoutCreateDisabledReason()return (<>@@ -56,23 +44,11 @@ export function ScoutCreateButton({>{children}</LemonButton>- {isModalOpen ? (- <React.Suspense fallback={null}>- <LazyScoutCreateModal- isOpen- initialValues={initialValues}- onCreated={(scout) => {- captureScoutAction({- actionType: 'create_scout',- surface: 'fleet_list',- skillName: scout.config.skill_name,- })- onCreated?.(scout)- }}- onClose={() => setIsModalOpen(false)}- />- </React.Suspense>- ) : null}+ <ScoutCreateModalHost+ initialValues={isModalOpen ? (initialValues ?? {}) : null}+ onClose={() => setIsModalOpen(false)}+ onCreated={onCreated}+ /></>)}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsxnew file mode 100644index 000000000000..35369f6cf20b--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModalHost.tsx@@ -0,0 +1,62 @@+import React from 'react'++import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import type { SignalScoutCreateResponseApi } from 'products/signals/frontend/generated/api.schemas'++import { captureScoutAction } from '../../../inboxAnalytics'+import type { ScoutCreateInitialValues } from '../../../logics/scoutCreateModalLogic'++const LazyScoutCreateModal = React.lazy(async () => {+ const { ScoutCreateModal } = await import('./ScoutCreateModal')+ return { default: ScoutCreateModal }+})++/** Why the current user can't create a scout, or null when they can. */+export function useScoutCreateDisabledReason(): string | null {+ return getAccessControlDisabledReason(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor)+}++export interface ScoutCreateModalHostProps {+ /** The scout to prefill, or null to render nothing. Doubles as the open state. */+ initialValues: ScoutCreateInitialValues | null+ onClose: () => void+ onCreated?: (scout: SignalScoutCreateResponseApi) => void+}++/**+ * The create-scout modal, lazily loaded and instrumented, with its open state owned by the caller.+ *+ * Split out of `ScoutCreateButton` because a caller that opens the modal from a URL can't host it+ * inside the button: on the AI observability tab the buttons sit in a `LemonCollapse` panel, whose+ * content unmounts while collapsed, so a link would open nothing.+ */+export function ScoutCreateModalHost({+ initialValues,+ onClose,+ onCreated,+}: ScoutCreateModalHostProps): JSX.Element | null {+ if (!initialValues) {+ return null+ }++ return (+ <React.Suspense fallback={null}>+ <LazyScoutCreateModal+ isOpen+ initialValues={initialValues}+ onCreated={(scout) => {+ captureScoutAction({+ actionType: 'create_scout',+ surface: 'fleet_list',+ skillName: scout.config.skill_name,+ })+ onCreated?.(scout)+ }}+ onClose={onClose}+ />+ </React.Suspense>+ )+}