: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(signals): edit a scout's structured output schema in settings (#105681)
posthog[bot]1e9d8c9f0270
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 75bf44bbadb5..0797c8c1932a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10223,29 +10223,33 @@ snapshots:scenes-app-inbox-scene--triage--light:hash: v1.k794b7964.ea1f0a1a3cd9c029a33e39277a276be15a04555ba2addee17df2aacb108316dc.CFYN_7EjRWTlSCsBQMuZ6Bq_ViTyRy7_RqqtqKfg05wscenes-app-inbox-scoutconfigform--custom-cron-schedule--dark:- hash: v1.k794b7964.26c4efd9ad29f1d204068bb7c0ab6487dc2156ea97bbf319b582ecdc00783f9f.lvx3Mqz8JFEv9Nf6P-QX_q_LCHHbn3xb_-ZS6MkmzZQ+ hash: v1.k794b7964.ab3f7494ddcba983ce8fa85f9bd0af8b28d6d562506795e0da265111e639f08f.M2nWzd5IXAX-0IBWrnYcHKxzMHdEx9sPYBaOpwGC6ugscenes-app-inbox-scoutconfigform--custom-cron-schedule--light:- hash: v1.k794b7964.77c921a7bf324fba11e12ae400aa7d1c0653551165b5278baa8c79121c241725.DlpiC0nCRR1MFR8iOQXdumFTXRyYZ2v-GlbrEnvU6Rw+ hash: v1.k794b7964.35ad471badfaf551e64ed3a29f59c39ee4f603071ed85b834c553257772c896c.IpmDODICE3hfY6uGLDOJ4uSrtZBpUKfugh4-TZrs4sAscenes-app-inbox-scoutconfigform--disabled--dark:- hash: v1.k794b7964.2c349d555bcf06832d48817b6d032fc113223b1544706492a8fc876af77601f4.zVzm7ItVQ4NM-vbMrDQ3GMIvmRTNvSGZPdKLXjd5dno+ hash: v1.k794b7964.d476592dfe48521d83c78056e6f5e44dd9834d435244251a60b16512c7c558ab.AP0aSzZ2NfvCvD4y9STmgkZDF6990u_uqfIvahDUxFgscenes-app-inbox-scoutconfigform--disabled--light:- hash: v1.k794b7964.8ba97f9f07711c421e80bebc6bd6720f10a3218f7011718f4ef1ad2923af654e.98uWAkH4QqAbMS9omWWxldhaXpgUhjc8QgoFXThzc0U+ hash: v1.k794b7964.c8d5c2be6aafeb5cb3a6855a23bd2c228689419f269a1e0c087646b4fcd4ad56.hFSJBS4WcfxWTXkzEvE0gwYP-frlke5WjXubZ1v4-aAscenes-app-inbox-scoutconfigform--dry-run--dark:- hash: v1.k794b7964.8c5411748833cd6b6c86345b86a1f38faa7b48dee776660eaaad1689fdbf87b3.GCLLchJ37jEg1VGH1_hRgfNk5e8Y7hVRgYhxcgpyb7M+ hash: v1.k794b7964.c18945886af43aeab5d10edb47bbb0539287388adba6a9e687284175bc1680b8.uEKjsHUynj5Q8CszhxE8xYOPC09tTSscOUzztGJyWrUscenes-app-inbox-scoutconfigform--dry-run--light:- hash: v1.k794b7964.bac76f1671995a47b9036c82cefdd9dbe93088b96a6695f4e730c66ccf93a709.fqrzO9wEFXuLdgHFiX1zyRoInMRmlXXxN8rr9LZDRts+ hash: v1.k794b7964.e1fbf749c58c5da186f85e360c573184ef1a22a6554985676be1539b5157a868.vEJ5eWEzDFh-MebvKEdhqUhVIVfA2B_DO0UW4NJSx_Yscenes-app-inbox-scoutconfigform--live--dark:- hash: v1.k794b7964.a80db416dc10ec13be6bb5ead0551a925133245f37b764a3e59357fb70e6c400.avfmsE2p8UtRZ2xX2gdPq3HmVQRl29h86kmdr15cb64+ hash: v1.k794b7964.ce68b3b3f8153c3354f10a93ddfba752b4878bfdd601dcf464b7b29686c2cf62.GRDUSgrlQfd_zE3EOncvLpTjPoYyD57EhbsOSkkhJQYscenes-app-inbox-scoutconfigform--live--light:- hash: v1.k794b7964.7875cd5e37b2641919b5f79d9cda301d0c1af178359315d42921f817d82dbe23.m-dFQT8IfRXJqdo3DakPSnPdWHb1rlr1nis5a_xVKFg+ hash: v1.k794b7964.324a750319e93297c10c9702087b804118f42fc4aaac49eab7dec6e7916cb9cb.lgjOHq03pb3aWwaMXGU5mXnkFWCPS7jEG1Yy6WobV7Yscenes-app-inbox-scoutconfigform--slack-channel-destination--dark:- hash: v1.k794b7964.4465b6466aad7aea2ab75e0d8fa6985bd72e9112ee5f6d874302a16f2c425673.nqhV_LA4xGc3KfLEG2-sJ7YYQermNBpEJwKa4tJABAQ+ hash: v1.k794b7964.501849958aba23ee74fc31fc55ef64487a04d21edde1a016a4874996ca113d9d.8ysgIdI7MznI26_BvWfQDUxa0y8wlZW4IZ98CFa0k04scenes-app-inbox-scoutconfigform--slack-channel-destination--light:- hash: v1.k794b7964.9879721a5c34c7a9d308848b690bd402a42093182f83ff539268f658071c885c.tZyALXreGXcW2nGZYiFce0rXwHWaoSMdHbMnTY0M1-8+ hash: v1.k794b7964.209e7a64caf9c1d92dfffbe6d5a40b341773ed7d11497016ca0f150a460c2cab.aYOtIcBt3WkoVzuHpV2Mp4dkNRA3dHxhq7t9W8Pv2p4+ scenes-app-inbox-scoutconfigform--structured-output--dark:+ hash: v1.k794b7964.a93a2720478eb53493d559c56823b6f8aff4ad664193718d082798a126d1dc41.GKQxYjrYDo5NHBUELfUd4bYl2MMmS798-S-lk2ytJIk+ scenes-app-inbox-scoutconfigform--structured-output--light:+ hash: v1.k794b7964.5425d38bc69b3bee0ce0ecd3699d9f8d572636f7bccee404d65281b681b72118.8SrWlOoByk1CUeYw9GEEdLJs-eebXKwtuZVnPTyueIAscenes-app-inbox-scoutconfigform--weekly-schedule--dark:- hash: v1.k794b7964.1b7901753edf904daf7ec8267356a571f11dd0f52e7a19ecad747b36998c276d.GiCVjpe90JKDpURDut6yR_aBxy8c-zAWNEb2W5xoP8s+ hash: v1.k794b7964.fa1801a0181ef8935e9982d7c19e73f637c4fc4258f32fc3592374ade35bc055.gBTGuqpe7zj7lvtMhMSDzF1lHgrmDTuc1FiF6tuX42Ascenes-app-inbox-scoutconfigform--weekly-schedule--light:- hash: v1.k794b7964.0c7c83f66a13080a80cf2414cec3125cf745d387fb7f946fab1063f1615e99cc.0wwNw7fJKvPjX00GJrMkTjtp_mW1A8k_u0q-Sep2pQk+ hash: v1.k794b7964.fbfb3c3846b1de0b08195046499e8fa469ee22c120e7076430316bddf367673d.YOCg2GpEsuT0bSiL57V1OD-gUp4mR1Zud2DOaE6YbJUscenes-app-inbox-scoutdetailview--scout-page--dark:hash: v1.k794b7964.7994cd307f5adb384df6008caa4d535248e8e10ba5505840e7b2661704cfa054.HD73lbCqzK0mXr4mcQ7lZJdj5J5aGTd_5LtbP3TDbLUscenes-app-inbox-scoutdetailview--scout-page--light:diff --git a/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx b/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsxindex 6deb03c98b65..15aead876b5f 100644--- a/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx+++ b/frontend/src/lib/lemon-ui/LemonTextArea/LemonTextArea.tsx@@ -7,7 +7,7 @@ import { cn } from 'lib/utils/css-classes'interface LemonTextAreaPropsBase extends Pick<React.TextareaHTMLAttributes<HTMLTextAreaElement>,- 'onFocus' | 'onBlur' | 'maxLength' | 'onKeyDown' | 'aria-label'+ 'onFocus' | 'onBlur' | 'maxLength' | 'onKeyDown' | 'aria-label' | 'aria-invalid' | 'aria-describedby'> {id?: stringvalue?: stringdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsxindex 88fe1d492d06..0946ec504639 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx@@ -87,3 +87,23 @@ export const SlackChannelDestination: Story = {/>),}++// A scout that measures something on a schedule: the collapsed section names the fields of the+// record it writes, so what the scout produces is readable without opening it.+export const StructuredOutput: Story = {+ render: () => (+ <EditableConfigForm+ initialConfig={{+ ...mockScoutConfigs[0],+ structured_output_schema: {+ type: 'object',+ properties: {+ verdict: { enum: ['good', 'bad', 'unsure'] },+ reason: { type: 'string' },+ },+ required: ['verdict', 'reason'],+ },+ }}+ />+ ),+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsxindex fb691e397586..3aedc249dc1c 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx@@ -242,4 +242,26 @@ describe('ScoutConfigForm', () => {expect(onUpdate).toHaveBeenCalledWith('config-1', { tags: ['on-call', 'revenue'] })unmount()})++ // The scout page keeps the form mounted when the URL moves to another scout, so a draft left on+ // one scout would otherwise sit in the next scout's editor, ready to save there.+ it('drops an unsaved schema draft when the form moves to another scout', () => {+ const onUpdate = jest.fn()+ const draft = '{"type": "object", "properties": {"verdict": {"type": "string"}}}'+ const { getByText, getByLabelText, queryByDisplayValue, rerender, unmount } = render(+ <ScoutConfigForm config={config} onUpdate={onUpdate} />+ )+ fireEvent.click(getByText('Structured output'))+ fireEvent.change(getByLabelText(`${config.skill_name} record schema`), { target: { value: draft } })++ rerender(+ <ScoutConfigForm+ config={{ ...config, id: 'config-2', skill_name: 'signals-scout-other' }}+ onUpdate={onUpdate}+ />+ )++ expect(queryByDisplayValue(draft)).toBeNull()+ unmount()+ })})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsxindex 80e4926e811f..8e6788f4edcc 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx@@ -36,6 +36,7 @@ import {import { ScoutMcpServersPicker } from './ScoutMcpServersPicker'import { ScoutRepositoriesPicker } from './ScoutRepositoriesPicker'import { ScoutSlackDestination } from './ScoutSlackDestination'+import { ScoutStructuredOutputSection } from './ScoutStructuredOutputSection'import { ScoutTagsEditor } from './ScoutTagsEditor'import { ScoutWriteAccessSection } from './ScoutWriteAccessSection'@@ -68,6 +69,8 @@ interface ScoutConfigFormProps extends ScoutConfigControlsProps {deleting?: boolean/** True while this scout's config update request is in flight. */updating?: boolean+ /** Called when a staged edit (the record schema) gains or loses unsaved changes. */+ onUnsavedChange?: (unsaved: boolean) => void}/** Enable/disable toggle for a scout. Lives on the row, not in the settings form. */@@ -98,6 +101,7 @@ export function ScoutConfigForm({onDelete,deleting,updating = false,+ onUnsavedChange,}: ScoutConfigFormProps): JSX.Element {const { timezone: projectTimezone } = useValues(teamLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -331,6 +335,15 @@ export function ScoutConfigForm({// Editable while the scout is disabled, for the same reason as the MCP selection.disabledReason={updating ? 'Saving scout settings' : undefined}/>+ {/* Keyed by scout because the scout page keeps this form mounted when the URL moves to another+ scout, and an unsaved schema draft must not become the next scout's save. */}+ <ScoutStructuredOutputSection+ key={config.id}+ config={config}+ onUpdate={onUpdate}+ updating={updating}+ onUnsavedChange={onUnsavedChange}+ /><ScoutWriteAccessSection config={config} onUpdate={onUpdate} updating={updating} />{/* Only custom scouts are deletable. A canonical scout would be re-seeded from disk afterdeletion (and couldn't be re-added from the UI), so its terminal action stays disable. */}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsxindex 7d89903361ba..6f5476c8c64f 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx@@ -31,6 +31,7 @@ export function ScoutSettingsModal({}): JSX.Element {const { updatingScoutIds, deletingScoutIds } = useValues(scoutFleetLogic)const { updateScoutConfig, deleteScout } = useActions(scoutFleetLogic)+ const [hasUnsavedInput, setHasUnsavedInput] = useState(false)return (<LemonModal@@ -39,6 +40,7 @@ export function ScoutSettingsModal({title={`${scoutDisplayName(config)} settings`}description="Changes take effect on this scout's next run."width={560}+ hasUnsavedInput={hasUnsavedInput}><ScoutConfigFormconfig={config}@@ -46,6 +48,7 @@ export function ScoutSettingsModal({onDelete={(configId) => deleteScout(configId, surface)}deleting={deletingScoutIds.includes(config.id)}updating={updatingScoutIds.includes(config.id)}+ onUnsavedChange={setHasUnsavedInput}/></LemonModal>)diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.test.tsxnew file mode 100644index 000000000000..3a4ba5e23605--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.test.tsx@@ -0,0 +1,170 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'++import { LemonDialog } from '@posthog/lemon-ui'++import { initKeaTests } from '~/test/init'++import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'++import { mockScoutConfigs } from '../../../__mocks__/scoutConfigs'+import { ScoutStructuredOutputSection } from './ScoutStructuredOutputSection'++const SCHEMA = {+ type: 'object',+ properties: { verdict: { enum: ['good', 'bad'] }, reason: { type: 'string' } },+ required: ['verdict'],+}++// Built from the shared mock so a new required config field only needs adding in one place.+const CONFIG: SignalScoutConfigApi = {+ ...mockScoutConfigs[0],+ id: 'config-1',+ skill_name: 'signals-scout-hygiene',+ scout_origin: 'custom',+ enabled: true,+ emit: true,+ structured_output_schema: null,+}++describe('ScoutStructuredOutputSection', () => {+ beforeEach(() => {+ initKeaTests()+ })+ afterEach(cleanup)++ const openSection = (config: SignalScoutConfigApi): jest.Mock => {+ const onUpdate = jest.fn()+ render(<ScoutStructuredOutputSection config={config} onUpdate={onUpdate} />)+ fireEvent.click(screen.getByText('Structured output'))+ return onUpdate+ }++ it.each([+ ['a live scout', true],+ // A dry-run scout records nothing, so a header that reads the same as a live scout's would+ // promise records the next run cannot write.+ ['a dry-run scout', false],+ ])('shows what the scout records without opening the section, for %s', (_name, emit) => {+ render(+ <ScoutStructuredOutputSection+ config={{ ...CONFIG, emit, structured_output_schema: SCHEMA }}+ onUpdate={jest.fn()}+ />+ )++ expect(screen.getByText('verdict')).toBeInTheDocument()+ expect(screen.queryByText('Off')).not.toBeInTheDocument()+ expect(screen.queryByText('Inactive during dry run') !== null).toBe(!emit)+ })++ it('stages an edit and saves the parsed schema only on the save button', () => {+ // The whole reason this section has a save button: the scout reads the schema verbatim in+ // its prompt, so a half-typed schema must not reach the next run.+ const onUpdate = openSection(CONFIG)+ const editor = screen.getByLabelText('signals-scout-hygiene record schema')++ fireEvent.change(editor, { target: { value: JSON.stringify(SCHEMA) } })+ expect(onUpdate).not.toHaveBeenCalled()++ fireEvent.click(screen.getByText('Save schema'))+ expect(onUpdate).toHaveBeenCalledWith('config-1', { structured_output_schema: SCHEMA })+ })++ it.each([+ // The typed JSON is the only copy of the edit, so a refused save must leave it to correct.+ ['refuses', null, JSON.stringify(SCHEMA)],+ ['accepts', SCHEMA, JSON.stringify(SCHEMA, null, 2)],+ ])('keeps the right text in the editor when the API %s the save', (_outcome, stored, expectedText) => {+ // Like scoutFleetLogic, the save patches the config and marks the scout as updating before the+ // request settles, and the settled config replaces the patch.+ let rerender: (ui: JSX.Element) => void = () => {}+ const onUpdate = (_configId: string, updates: Partial<SignalScoutConfigApi>): void =>+ rerender(<ScoutStructuredOutputSection config={{ ...CONFIG, ...updates }} onUpdate={jest.fn()} updating />)+ ;({ rerender } = render(<ScoutStructuredOutputSection config={CONFIG} onUpdate={onUpdate} />))+ fireEvent.click(screen.getByText('Structured output'))+ const editor = screen.getByLabelText('signals-scout-hygiene record schema')++ fireEvent.change(editor, { target: { value: JSON.stringify(SCHEMA) } })+ fireEvent.click(screen.getByText('Save schema'))+ rerender(+ <ScoutStructuredOutputSection+ config={{ ...CONFIG, structured_output_schema: stored }}+ onUpdate={jest.fn()}+ />+ )++ expect(editor).toHaveValue(expectedText)+ })++ it.each([+ ['refuses', SCHEMA, '{"type": "object", "properties": {"score": {"type": "integer"}}}'],+ ['accepts', null, ''],+ ])('keeps the right text in the editor when the API %s the turn-off', (_outcome, stored, expectedText) => {+ const edit = '{"type": "object", "properties": {"score": {"type": "integer"}}}'+ const open = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const withSchema = { ...CONFIG, structured_output_schema: SCHEMA }+ let rerender: (ui: JSX.Element) => void = () => {}+ const onUpdate = (_configId: string, updates: Partial<SignalScoutConfigApi>): void =>+ rerender(+ <ScoutStructuredOutputSection config={{ ...withSchema, ...updates }} onUpdate={jest.fn()} updating />+ )+ ;({ rerender } = render(<ScoutStructuredOutputSection config={withSchema} onUpdate={onUpdate} />))+ fireEvent.click(screen.getByText('Structured output'))+ const editor = screen.getByLabelText('signals-scout-hygiene record schema')++ fireEvent.change(editor, { target: { value: edit } })+ fireEvent.click(screen.getByText('Turn off'))+ act(() => open.mock.calls[0][0].primaryButton?.onClick?.({} as React.MouseEvent<HTMLElement>))+ rerender(+ <ScoutStructuredOutputSection+ config={{ ...CONFIG, structured_output_schema: stored }}+ onUpdate={jest.fn()}+ />+ )++ expect(editor).toHaveValue(expectedText)+ open.mockRestore()+ })++ it.each([+ // Half-typed JSON parses to no schema, which must not read as matching "no schema saved".+ ['a draft that does not parse yet', '{'],+ ['a valid draft', JSON.stringify(SCHEMA)],+ ])('reports %s as unsaved so the modal keeps it', (_name, text) => {+ const onUnsavedChange = jest.fn()+ render(<ScoutStructuredOutputSection config={CONFIG} onUpdate={jest.fn()} onUnsavedChange={onUnsavedChange} />)+ fireEvent.click(screen.getByText('Structured output'))++ fireEvent.change(screen.getByLabelText('signals-scout-hygiene record schema'), { target: { value: text } })++ expect(onUnsavedChange).toHaveBeenLastCalledWith(true)+ })++ it('refuses to save a schema the API would reject', () => {+ const onUpdate = openSection(CONFIG)++ fireEvent.change(screen.getByLabelText('signals-scout-hygiene record schema'), {+ target: { value: '{"type": "string"}' },+ })++ expect(screen.getByText('The schema must set "type": "object" at its root.')).toBeInTheDocument()+ expect(screen.getByLabelText('signals-scout-hygiene record schema')).toHaveAttribute('aria-invalid', 'true')+ fireEvent.click(screen.getByText('Save schema'))+ expect(onUpdate).not.toHaveBeenCalled()+ })++ it('turns the channel off only after the dialog is confirmed', () => {+ // A stray click must not delete a schema the scout records against.+ const open = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const onUpdate = openSection({ ...CONFIG, structured_output_schema: SCHEMA })++ fireEvent.click(screen.getByText('Turn off'))+ expect(onUpdate).not.toHaveBeenCalled()++ open.mock.calls[0][0].primaryButton?.onClick?.({} as React.MouseEvent<HTMLElement>)+ expect(onUpdate).toHaveBeenCalledWith('config-1', { structured_output_schema: null })+ open.mockRestore()+ })+})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.tsxnew file mode 100644index 000000000000..a146d11d21df--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutStructuredOutputSection.tsx@@ -0,0 +1,226 @@+import { useEffect, useState } from 'react'++import { LemonButton, LemonCollapse, LemonDialog, LemonTag, LemonTextArea, Tooltip } from '@posthog/lemon-ui'++import { objectsEqual } from 'lib/utils/objects'++import type {+ PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,+ SignalScoutConfigApi as SignalScoutConfig,+} from 'products/signals/frontend/generated/api.schemas'++import { parseScoutStructuredOutputSchema, scoutStructuredOutputFieldNames } from './scoutStructuredOutput'++const HEADER_FIELD_LIMIT = 3++const SCHEMA_PLACEHOLDER = `{+ "type": "object",+ "properties": {+ "verdict": { "enum": ["good", "bad", "unsure"] },+ "reason": { "type": "string" }+ },+ "required": ["verdict", "reason"]+}`++/**+ * The record schema for one scout in its settings form: collapsed by default, with the record's+ * field names in the header so a scout that records nothing costs one line.+ *+ * Like write access, this does not save on change. The scout reads the schema verbatim in its run+ * prompt, and a half-typed schema would rewrite what the next run is asked to produce, so the+ * editor stages a draft and the save button commits it.+ *+ * The editor stays live for everyone. Only a person who may edit skills can set a schema, and the+ * client cannot resolve that, so the API refuses and its message names what is missing.+ */+export function ScoutStructuredOutputSection({+ config,+ onUpdate,+ updating = false,+ onUnsavedChange,+}: {+ config: SignalScoutConfig+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void+ updating?: boolean+ /** Called when the editor gains or loses an unsaved edit, so a host modal can guard its backdrop. */+ onUnsavedChange?: (unsaved: boolean) => void+}): JSX.Element {+ const saved = config.structured_output_schema ?? null+ const savedText = saved ? JSON.stringify(saved, null, 2) : ''+ // Null until something is typed, so an untouched editor follows the saved schema.+ const [draft, setDraft] = useState<string | null>(null)+ // The schema the last save or turn-off sent (null for a turn-off), held until the request settles.+ // The draft clears only if the stored schema then matches it. A rejected request reverts the+ // config, so the typed JSON stays on screen to correct and try again.+ const [submitted, setSubmitted] = useState<{ schema: Record<string, unknown> | null } | null>(null)+ useEffect(() => {+ if (updating || !submitted) {+ return+ }+ if (objectsEqual(saved, submitted.schema)) {+ setDraft(null)+ }+ setSubmitted(null)+ }, [updating, submitted, saved])+ const text = draft ?? savedText+ const { schema, error } = parseScoutStructuredOutputSchema(text)+ const changed = JSON.stringify(schema) !== JSON.stringify(saved)+ // A draft that does not parse yet, or one whose save is still in flight, is still unsaved work.+ const unsaved = draft !== null && (changed || error !== null || submitted !== null)+ useEffect(() => {+ onUnsavedChange?.(unsaved)+ return () => onUnsavedChange?.(false)+ }, [unsaved, onUnsavedChange])+ const errorId = `${config.id}-structured-output-error`+ const fieldNames = scoutStructuredOutputFieldNames(saved)+ const headerFields = fieldNames.slice(0, HEADER_FIELD_LIMIT)+ const tagType = config.emit ? 'option' : 'muted'+ const disabledReason = updating ? 'Saving scout settings' : undefined+ const saveDisabledReason =+ disabledReason ??+ error ??+ (schema && changed ? undefined : !schema && saved ? 'To remove the schema, use Turn off' : 'No changes to save')++ return (+ <div className="border-t border-primary pt-2">+ <LemonCollapse+ embedded+ size="small"+ panels={[+ {+ key: 'structured-output',+ dataAttr: 'scout-structured-output',+ header: (+ <div className="flex min-w-0 flex-1 items-center justify-between gap-2">+ <span className="shrink-0 text-xs text-default">Structured output</span>+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">+ {saved ? (+ <>+ {headerFields.map((name) => (+ <Tooltip key={name} title={name}>+ <LemonTag size="small" type={tagType} className="max-w-40">+ <span className="truncate" translate="no">+ {name}+ </span>+ </LemonTag>+ </Tooltip>+ ))}+ {fieldNames.length > headerFields.length ? (+ <LemonTag size="small" type={tagType}>+ {`+${fieldNames.length - headerFields.length}`}+ </LemonTag>+ ) : null}+ {fieldNames.length === 0 ? (+ <LemonTag size="small" type={tagType}>+ Schema set+ </LemonTag>+ ) : null}+ {!config.emit && (+ <span className="text-[11.5px] text-muted">+ Inactive during dry run+ </span>+ )}+ </>+ ) : (+ <span className="text-[11.5px] text-muted">Off</span>+ )}+ </div>+ </div>+ ),+ content: (+ <div className="flex flex-col gap-2">+ <span className="text-[11.5px] text-muted">+ A JSON Schema for one record this scout measures, such as a verdict and a reason.+ The scout sees it in its prompt, and every record it submits is checked against it+ and saved as a $scout_structured_output event you can chart. Only a person who can+ edit skills may set a schema.+ </span>+ <LemonTextArea+ value={text}+ placeholder={SCHEMA_PLACEHOLDER}+ minRows={6}+ maxRows={16}+ className="font-mono text-[11.5px]"+ disabled={updating}+ onChange={setDraft}+ aria-label={`${config.skill_name} record schema`}+ aria-invalid={!!error}+ aria-describedby={error ? errorId : undefined}+ />+ {error ? (+ <span id={errorId} role="alert" className="text-[11.5px] text-danger">+ {error}+ </span>+ ) : null}+ {!config.emit ? (+ <span className="text-[11.5px] text-warning">+ This scout is in a dry run, so it records nothing. Turn on "Write signals to the+ inbox" to use the schema.+ </span>+ ) : null}+ <div className="flex flex-wrap items-center justify-end gap-2">+ {saved ? (+ <LemonButton+ size="small"+ type="secondary"+ status="danger"+ className="mr-auto"+ disabledReason={disabledReason}+ onClick={() =>+ LemonDialog.open({+ title: 'Turn off structured output?',+ description:+ 'The scout stops producing records. You can add a schema again later.',+ primaryButton: {+ children: 'Turn off',+ status: 'danger',+ onClick: () => {+ onUpdate(config.id, { structured_output_schema: null })+ setSubmitted({ schema: null })+ },+ 'data-attr': 'scout-structured-output-clear',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ data-attr="scout-structured-output-turn-off"+ >+ Turn off+ </LemonButton>+ ) : null}+ {unsaved ? (+ <LemonButton+ size="small"+ type="tertiary"+ disabledReason={disabledReason}+ onClick={() => setDraft(null)}+ data-attr="scout-structured-output-discard"+ >+ Discard+ </LemonButton>+ ) : null}+ <LemonButton+ size="small"+ type="secondary"+ loading={updating}+ disabledReason={saveDisabledReason}+ onClick={() => {+ if (!schema) {+ return+ }+ onUpdate(config.id, { structured_output_schema: schema })+ setSubmitted({ schema })+ }}+ data-attr="scout-structured-output-save"+ >+ Save schema+ </LemonButton>+ </div>+ </div>+ ),+ },+ ]}+ />+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.test.ts b/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.test.tsnew file mode 100644index 000000000000..2a2ba4670c1d--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.test.ts@@ -0,0 +1,66 @@+import { parseScoutStructuredOutputSchema, scoutStructuredOutputFieldNames } from './scoutStructuredOutput'++describe('scoutStructuredOutput', () => {+ const verdictSchema = {+ type: 'object',+ properties: { verdict: { enum: ['good', 'bad'] }, reason: { type: 'string' } },+ required: ['verdict'],+ }++ it.each([+ ['blank text', ' ', null],+ ['invalid JSON', '{"type":', 'This is not valid JSON.'],+ ['an empty object', '{}', 'The schema must be a JSON object with at least one key.'],+ ['an array', '[{"type": "object"}]', 'The schema must be a JSON object with at least one key.'],+ ['a non-object root', '{"type": "string"}', 'The schema must set "type": "object" at its root.'],+ [+ 'nesting that parses but is too deep to serialize',+ `{"type": "object", "default": ${'['.repeat(100000)}${']'.repeat(100000)}}`,+ 'The schema is nested too deeply. Use fewer nested levels.',+ ],+ ])('names what is wrong with %s', (_name, text, error) => {+ expect(parseScoutStructuredOutputSchema(text)).toEqual({ schema: null, error })+ })++ it.each([+ ['a record schema', JSON.stringify(verdictSchema), verdictSchema],+ // The API refuses regex keywords and references to other documents. Reading those rules+ // here as well could only refuse a schema the API accepts, so the save carries them.+ [+ 'a schema the API judges, such as one with a regex keyword',+ '{"type": "object", "properties": {"a": {"type": "string", "pattern": "^a+$"}}}',+ { type: 'object', properties: { a: { type: 'string', pattern: '^a+$' } } },+ ],+ ])('accepts %s', (_name, text, schema) => {+ expect(parseScoutStructuredOutputSchema(text)).toEqual({ schema, error: null })+ })++ const stringFields = (count: number): Record<string, unknown> => ({+ type: 'object',+ properties: Object.fromEntries(+ Array.from({ length: count }, (_value, index) => [`field_${index}`, { type: 'string' }])+ ),+ })++ // Each pair sits on the API's limit: the byte counts are what Python's json.dumps gives, and+ // compact UTF-8 counts both schemas in a pair well under the limit.+ it.each([+ ['608 fields, 19988 bytes to the API', stringFields(608), false],+ ['609 fields, 20021 bytes to the API', stringFields(609), true],+ ['3327 accented letters, 19999 bytes to the API', { type: 'object', description: 'é'.repeat(3327) }, false],+ ['3328 accented letters, 20005 bytes to the API', { type: 'object', description: 'é'.repeat(3328) }, true],+ ])('measures the size the way the API does, for %s', (_name, input, refused) => {+ const { schema, error } = parseScoutStructuredOutputSchema(JSON.stringify(input))++ expect(schema).toEqual(refused ? null : input)+ expect(error).toEqual(refused ? 'The schema is over the 20000 byte limit. Describe fewer fields.' : null)+ })++ it.each([+ ['a schema with properties', verdictSchema, ['verdict', 'reason']],+ ['a schema without properties', { type: 'object' }, []],+ ['no schema', null, []],+ ])('reads the record fields from %s', (_name, schema, fieldNames) => {+ expect(scoutStructuredOutputFieldNames(schema)).toEqual(fieldNames)+ })+})diff --git a/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.ts b/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.tsnew file mode 100644index 000000000000..c80182e55d64--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/scoutStructuredOutput.ts@@ -0,0 +1,92 @@+/** Serialized size cap the config API applies to a scout's record schema. */+export const SCOUT_STRUCTURED_OUTPUT_SCHEMA_MAX_BYTES = 20000++export interface ScoutStructuredOutputSchemaParse {+ /** The parsed schema, or null when the text is blank or invalid. */+ schema: Record<string, unknown> | null+ /** What is wrong with the text, in the words shown under the editor. */+ error: string | null+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++/**+ * The byte count the API compares with the cap. The API measures Python's default `json.dumps`,+ * which puts a space after every `,` and `:` and writes each UTF-16 code unit outside printable+ * ASCII as a 6-byte `\uXXXX` escape. Compact UTF-8 counts fewer bytes, so it lets through schemas+ * the API refuses.+ */+function apiSerializedByteLength(value: unknown): number {+ const json = JSON.stringify(value)+ let bytes = json.length+ let inString = false+ for (let index = 0; index < json.length; index++) {+ const char = json[index]+ if (inString) {+ if (char === '\\') {+ // Every escape JSON.stringify writes is ASCII, and Python writes one of the same length.+ index+++ } else if (char === '"') {+ inString = false+ } else if (char > '~') {+ bytes += 5+ }+ } else if (char === '"') {+ inString = true+ } else if (char === ',' || char === ':') {+ bytes += 1+ }+ }+ return bytes+}++/**+ * Read the editor text as a record schema, applying the shape rules the config API applies, so a+ * malformed schema is named under the field rather than coming back as a rejected save. The API+ * also refuses schema constructs that would attack the worker, such as a reference to another+ * document or a regex keyword. Those rules stay on the server alone, because a copy here can only+ * drift, and a copy that drifts toward strict refuses a schema the API accepts. The save surfaces+ * the API's own message for them.+ * Blank text is a half-finished edit, not a clear: it parses to no schema and no error.+ */+export function parseScoutStructuredOutputSchema(text: string): ScoutStructuredOutputSchemaParse {+ const trimmed = text.trim()+ if (!trimmed) {+ return { schema: null, error: null }+ }+ let parsed: unknown+ try {+ parsed = JSON.parse(trimmed)+ } catch {+ return { schema: null, error: 'This is not valid JSON.' }+ }+ if (!isPlainObject(parsed) || Object.keys(parsed).length === 0) {+ return { schema: null, error: 'The schema must be a JSON object with at least one key.' }+ }+ if (parsed.type !== 'object') {+ return { schema: null, error: 'The schema must set "type": "object" at its root.' }+ }+ let bytes: number+ try {+ bytes = apiSerializedByteLength(parsed)+ } catch {+ // JSON.parse reads nesting deeper than JSON.stringify can write, and the RangeError it+ // throws would crash the settings form during render.+ return { schema: null, error: 'The schema is nested too deeply. Use fewer nested levels.' }+ }+ if (bytes > SCOUT_STRUCTURED_OUTPUT_SCHEMA_MAX_BYTES) {+ return {+ schema: null,+ error: `The schema is over the ${SCOUT_STRUCTURED_OUTPUT_SCHEMA_MAX_BYTES} byte limit. Describe fewer fields.`,+ }+ }+ return { schema: parsed, error: null }+}++/** The record's field names, for the collapsed header. Empty when the schema names none. */+export function scoutStructuredOutputFieldNames(schema: Record<string, unknown> | null | undefined): string[] {+ const properties = schema?.properties+ return isPlainObject(properties) ? Object.keys(properties) : []+}