: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(phai): default to auto mode and gate exec sub-tools server-side (#72257)
Georgiy Tarasov23df2e91f8fd
diff --git a/products/posthog_ai/frontend/components/Approval.test.tsx b/products/posthog_ai/frontend/components/Approval.test.tsxindex 7bfd31a69571..868546691602 100644--- a/products/posthog_ai/frontend/components/Approval.test.tsx+++ b/products/posthog_ai/frontend/components/Approval.test.tsx@@ -31,6 +31,18 @@ jest.mock('lib/components/CodeSnippet', () => ({Language: { JSON: 'json', Text: 'text' },}))+// Monaco can't render in jsdom — stand it in for a marker that echoes the diff props we care about.+jest.mock('lib/components/MonacoDiffEditor', () => ({+ __esModule: true,+ default: ({ original, modified }: { original?: string; modified?: string }) => (+ <div data-attr="monaco-diff" data-original={original} data-modified={modified} />+ ),+}))++jest.mock('react-intersection-observer', () => ({+ useInView: () => ({ ref: () => {}, inView: true }),+}))+const rawToolCall: ToolInvocation = {toolCallId: 'tc-1',rawServerName: 'posthog',@@ -72,14 +84,25 @@ describe('Sandbox approval input area', () => {})describe('PermissionInput', () => {- it('renders the approval prompt with the same two permission options', () => {+ it('renders the one-voice card: headline sentence, tool identity, option rows', () => {render(<PermissionInput streamKey="conv-1" request={makeRequest()} />)- expect(screen.getByText('Approval required')).toBeInTheDocument()+ expect(screen.getByText('The agent wants to create an insight.')).toBeInTheDocument()expect(screen.getByText('posthog - insight-create (MCP)')).toBeInTheDocument()expect(screen.getByText('Approve')).toBeInTheDocument()expect(screen.getByText('Decline')).toBeInTheDocument()- expect(screen.queryByText("Explain what you'd like instead.")).not.toBeInTheDocument()+ // The redundant category rows are gone — the headline sentence carries the ask.+ expect(screen.queryByText('Approval required')).not.toBeInTheDocument()+ })++ it('states the tool identity exactly once when the request has a title but no description', () => {+ render(<PermissionInput streamKey="conv-1" request={makeRequest({ description: undefined })} />)++ // getByText throws on multiple matches, so this also asserts the identity isn't duplicated+ // between the headline and the evidence label.+ expect(screen.getByText('posthog - insight-create (MCP)')).toBeInTheDocument()+ // The raw adapter title must not ride in as a second statement of the same identity.+ expect(screen.queryByText('Create insight')).not.toBeInTheDocument()})it('renders the unwrapped PostHog exec payload like PostHog Code', () => {@@ -126,7 +149,7 @@ describe('Sandbox approval input area', () => {expect(respondToPermission).not.toHaveBeenCalled()})- it('sends feedback text through the reject_with_feedback option when it is the decline path', () => {+ it('sends feedback text through the reject_with_feedback option, ignoring an empty submit', () => {render(<PermissionInputstreamKey="conv-1"@@ -139,10 +162,15 @@ describe('Sandbox approval input area', () => {/>)- fireEvent.click(screen.getByText("Explain what you'd like instead."))- const input = screen.getByPlaceholderText('Type your answer...')+ fireEvent.click(screen.getByText('Decline with feedback'))+ const input = screen.getByPlaceholderText('Tell the agent what to do differently')++ // The legacy feedback-only decline needs text — an empty Enter is a no-op.+ fireEvent.keyDown(input, { key: 'Enter' })+ expect(respondToPermission).not.toHaveBeenCalled()+fireEvent.change(input, { target: { value: 'Use a funnel instead' } })- fireEvent.click(screen.getByText('Send'))+ fireEvent.keyDown(input, { key: 'Enter' })expect(respondToPermission).toHaveBeenCalledWith({requestId: 'req-1',@@ -151,28 +179,113 @@ describe('Sandbox approval input area', () => {})})- it('renders reject_once as a one-click decline with no feedback toggle', () => {+ it('opens the note for a reject_once decline that supports feedback, declining plain on empty submit', () => {const request = makeRequest({options: [{ optionId: 'opt-allow', name: 'Yes', kind: 'allow_once' },- { optionId: 'opt-reject', name: 'No', kind: 'reject_once', customInput: true },+ {+ optionId: 'opt-reject',+ name: 'Type here to tell the agent what to do differently',+ kind: 'reject_once',+ customInput: true,+ },],})render(<PermissionInput streamKey="conv-1" request={request} />)- // No optional-feedback affordance — the decline is a plain one-click button.- expect(screen.queryByText('Add feedback…')).not.toBeInTheDocument()- fireEvent.click(screen.getByText('No'))+ // The interaction-describing wire name becomes a named choice; the note is opened, not sent.+ fireEvent.click(screen.getByText('Do it differently…'))+ const input = screen.getByPlaceholderText('Tell the agent what to do differently')+ expect(respondToPermission).not.toHaveBeenCalled()++ // An empty submit is the plain one-click decline.+ fireEvent.keyDown(input, { key: 'Enter' })+ expect(respondToPermission).toHaveBeenCalledWith({ requestId: 'req-1', optionId: 'opt-reject' })++ // A typed note rides along as feedback.+ respondToPermission.mockClear()+ fireEvent.change(input, { target: { value: 'Try a different query' } })+ fireEvent.keyDown(input, { key: 'Enter' })expect(respondToPermission).toHaveBeenCalledWith({requestId: 'req-1',optionId: 'opt-reject',+ customInput: 'Try a different query',+ })+ })++ it('activates rows with digit shortcuts but never while typing a note', () => {+ const request = makeRequest({+ options: [+ { optionId: 'opt-allow', name: 'Approve', kind: 'allow_once' },+ { optionId: 'opt-reject', name: 'No', kind: 'reject_once', customInput: true },+ ],})+ render(<PermissionInput streamKey="conv-1" request={request} />)++ // '2' opens the feedback note; digits typed inside it must not activate rows.+ fireEvent.keyDown(document.body, { key: '2' })+ const input = screen.getByPlaceholderText('Tell the agent what to do differently')+ fireEvent.keyDown(input, { key: '1' })+ expect(respondToPermission).not.toHaveBeenCalled()++ // Escape leaves the note; '1' back on the body approves.+ fireEvent.keyDown(input, { key: 'Escape' })+ fireEvent.keyDown(document.body, { key: '1' })+ expect(respondToPermission).toHaveBeenCalledWith({ requestId: 'req-1', optionId: 'opt-allow' })+ })++ it('caps a long payload behind a Show all expander', () => {+ const bigArgs = JSON.stringify({ query: 'select 1', cols: Array.from({ length: 20 }, (_, i) => `c${i}`) })+ render(+ <PermissionInput+ streamKey="conv-1"+ request={makeRequest({+ rawToolCall: { ...rawToolCall, input: { command: `call execute-sql ${bigArgs}` } },+ })}+ />+ )++ const snippet = (): HTMLElement =>+ screen.getByText((_content, element) => element?.getAttribute('data-attr') === 'code-snippet')+ expect(snippet().textContent).toContain('"c0"')+ expect(snippet().textContent).not.toContain('"c19"')++ fireEvent.click(screen.getByText(/^Show all \d+ lines$/))+ expect(snippet().textContent).toContain('"c19"')+ })++ it('renders diff evidence instead of the raw payload when the tool call carries a diff', () => {+ render(+ <PermissionInput+ streamKey="conv-1"+ request={makeRequest({+ rawToolCall: {+ ...rawToolCall,+ contentBlocks: [+ { type: 'diff', path: 'source.hog', oldText: 'let a := 1', newText: 'let a := 2' },+ ],+ },+ })}+ />+ )++ const diff = document.querySelector('[data-attr="monaco-diff"]')+ expect(diff).not.toBeNull()+ expect(diff?.getAttribute('data-original')).toBe('let a := 1')+ expect(diff?.getAttribute('data-modified')).toBe('let a := 2')+ expect(screen.getByText('+1')).toBeInTheDocument()+ expect(screen.getByText('-1')).toBeInTheDocument()+ expect(+ screen.queryByText((_content, element) => element?.getAttribute('data-attr') === 'code-snippet')+ ).not.toBeInTheDocument()})- // Plan approval keeps only the product's Auto and Accept edits continuation modes. Plan and the- // agent server's raw default mode are deliberately ignored even if the wire offers them.+ // Plan approval keeps only the product's Auto and Full auto continuation modes. Plan, the retired+ // acceptEdits mode, and the agent server's raw default mode are deliberately ignored even if the+ // wire offers them.const planWireOptions = [{ optionId: 'bypassPermissions', name: 'Yes, and bypass permissions', kind: 'allow_always' },+ { optionId: 'auto', name: 'Yes, and use "auto" mode', kind: 'allow_always' },{ optionId: 'acceptEdits', name: 'Yes, and auto-accept edits', kind: 'allow_always' },{ optionId: 'plan', name: 'Stay in plan mode', kind: 'allow_always' },{ optionId: 'default', name: 'Yes, and manually approve edits', kind: 'allow_once' },@@ -213,34 +326,43 @@ describe('Sandbox approval input area', () => {expect(screen.getByText('Approve this plan to proceed?')).toBeInTheDocument()})- it('keeps the supported plan modes and approves with Auto as bypassPermissions', () => {+ it('keeps the supported plan modes and approves with the default Auto as the auto wire option', () => {render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)- // Auto is the user-facing label for the bypassPermissions wire option.expect(screen.getByText('Auto')).toBeInTheDocument()fireEvent.click(screen.getByText('Approve and proceed'))expect(respondToPermission).toHaveBeenCalledWith({requestId: 'req-1',- optionId: 'bypassPermissions',+ optionId: 'auto',})})it('pre-selects the remembered last-approved mode over Auto', () => {+ window.localStorage.setItem('posthog-ai.lastPlanApprovalMode', 'bypassPermissions')+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ fireEvent.click(screen.getByText('Approve and proceed'))++ expect(respondToPermission).toHaveBeenCalledWith({ requestId: 'req-1', optionId: 'bypassPermissions' })+ })++ it('falls back to Auto when the remembered mode is retired', () => {window.localStorage.setItem('posthog-ai.lastPlanApprovalMode', 'acceptEdits')render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)fireEvent.click(screen.getByText('Approve and proceed'))- expect(respondToPermission).toHaveBeenCalledWith({ requestId: 'req-1', optionId: 'acceptEdits' })+ expect(respondToPermission).toHaveBeenCalledWith({ requestId: 'req-1', optionId: 'auto' })})- it('opens the mode picker with only Auto and Accept edits', () => {+ it('opens the mode picker with only Auto and Full auto', () => {render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)fireEvent.click(screen.getByLabelText('Mode'))- expect(screen.getByText('Accept edits')).toBeInTheDocument()+ expect(screen.getByText('Full auto')).toBeInTheDocument()+ expect(screen.queryByText('Accept edits')).not.toBeInTheDocument()expect(screen.queryByText('Default')).not.toBeInTheDocument()expect(screen.queryByText('Plan')).not.toBeInTheDocument()expect(screen.queryByText('Bypass permissions')).not.toBeInTheDocument()@@ -276,7 +398,7 @@ describe('Sandbox approval input area', () => {fireEvent.keyDown(document.body, { key: '1' })expect(respondToPermission).toHaveBeenCalledWith({requestId: 'req-1',- optionId: 'bypassPermissions',+ optionId: 'auto',})})@@ -337,7 +459,8 @@ describe('Sandbox approval input area', () => {<PermissionInput streamKey="conv-1" request={makeRequest({ title: 'Create a data retention plan' })} />)- expect(screen.getByText('Approval required')).toBeInTheDocument()+ expect(screen.queryByText('Implementation Plan')).not.toBeInTheDocument()+ expect(screen.getByText('Approve')).toBeInTheDocument()})it('falls back to showing every option when filtering would leave none', () => {diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsxindex 46dd4835f9e1..d9bc1da275f5 100644--- a/products/posthog_ai/frontend/components/PermissionInput.tsx+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx@@ -1,49 +1,307 @@import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'import { IconWarning } from '@posthog/icons'-import { LemonTag, Spinner } from '@posthog/lemon-ui'+import { Button, Spinner } from '@posthog/quill-primitives'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'--import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'+import { cn } from 'lib/utils/css-classes'import { runStreamLogic } from '../logics/runStreamLogic'import { MarkdownMessage } from '../messages/MarkdownMessage'import { getPermissionDisplay } from '../policy/permissionDisplayUtils'import { isPlanPermissionRequest, mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'import type { PermissionRequestRecord } from '../types/streamTypes'-import { isPlanApprovalModeOptionId, PlanApprovalSelector } from './PlanApprovalActions'-import { QuestionField } from './QuestionField'+import { isPlanApprovalModeOptionId, InlineEditableText, PlanApprovalSelector } from './PlanApprovalActions'+import { DiffEditor, DiffStats } from './tool/EditDiffRenderer'+import { FilePath } from './tool/FilePath'+import { findAllDiffContent, getDiffStats } from './tool/toolDiffContent'interface PermissionInputProps {streamKey: stringrequest: PermissionRequestRecord}-const ignoreMultiSelectChange = (_value: string[]): void => undefined-const ignoreMultiSelectSubmit = (): void => undefined--function toPermissionQuestion(- prompt: string,- options: ApprovalCardOption[],- allowCustomAnswer: boolean-): MultiQuestionFormQuestion {- return {- id: 'permission',- title: 'Approval',- question: prompt,- type: 'select',- options: options.map((option) => ({ value: option.label })),- allow_custom_answer: allowCustomAnswer,+/** Collapsed height of the payload preview, in lines — enough to scan, never enough to bury the choices. */+const PAYLOAD_COLLAPSED_LINES = 12++const FEEDBACK_PLACEHOLDER = 'Tell the agent what to do differently'++interface PermissionEvidenceProps {+ request: PermissionRequestRecord+ /** Tool identity for the evidence header; omitted when the headline sentence already carries it. */+ label?: string+ payload?: string+}++/**+ * The card's evidence block. A request whose tool call streamed `type: "diff"` content (Edit/Write, or+ * any adapter that reports a change to existing content) renders each diff with a path + stats header+ * and a side-by-side editor that collapses to unified when the container is narrow. Everything else+ * renders the payload preview capped at {@link PAYLOAD_COLLAPSED_LINES} with a "Show all" expander.+ */+function PermissionEvidence({ request, label, payload }: PermissionEvidenceProps): JSX.Element | null {+ const [showAll, setShowAll] = useState(false)+ const diffs = findAllDiffContent(request.rawToolCall.contentBlocks)++ if (diffs.length > 0) {+ return (+ <div className="flex flex-col gap-2 min-w-0">+ {diffs.map((diff, index) => {+ const stats = getDiffStats(diff.oldText, diff.newText)+ return (+ <div key={index} className="flex flex-col gap-1 min-w-0">+ <div className="flex items-center gap-2 min-w-0 text-xs text-secondary">+ {diff.path ? (+ <FilePath path={diff.path} />+ ) : (+ label && <span className="font-medium">{label}</span>+ )}+ <DiffStats added={stats.added} removed={stats.removed} />+ </div>+ <DiffEditor diff={diff} path={diff.path} sideBySide />+ </div>+ )+ })}+ </div>+ )+ }++ if (!payload) {+ return label ? <div className="text-xs text-secondary">{label}</div> : null+ }++ const language = payload.trim().match(/^[{[]/) ? Language.JSON : Language.Text+ const lines = payload.split('\n')+ const overflowing = lines.length > PAYLOAD_COLLAPSED_LINES+ const visible = showAll || !overflowing ? payload : lines.slice(0, PAYLOAD_COLLAPSED_LINES).join('\n')++ return (+ <div className="flex flex-col gap-1 min-w-0">+ {label && <div className="text-xs text-secondary font-medium">{label}</div>}+ <div className={cn(showAll && 'max-h-96 overflow-y-auto')}>+ <CodeSnippet language={language} className="text-xs" compact>+ {visible}+ </CodeSnippet>+ </div>+ {overflowing && (+ <Button variant="link-muted" size="xs" className="self-start" onClick={() => setShowAll(!showAll)}>+ {showAll ? 'Show less' : `Show all ${lines.length} lines`}+ </Button>+ )}+ </div>+ )+}++/** A decline that relays feedback is answered through its inline textarea, not a plain click. */+function isFeedbackOption(option: ApprovalCardOption): boolean {+ return option.requiresFeedback || option.supportsFeedback+}++function optionRowLabel(option: ApprovalCardOption): string {+ // The wire's feedback option describes the interaction ("Type here to tell the agent…") instead of+ // naming the choice; the textarea placeholder carries that instruction, the row just needs a name.+ if (isFeedbackOption(option) && /^type here\b/i.test(option.label)) {+ return 'Do it differently…'+ }+ return option.label+}++function optionSublabel(option: ApprovalCardOption): string | null {+ if (option.requiresFeedback) {+ return 'The agent adjusts and continues instead of stopping this turn.'+ }+ if (option.supportsFeedback) {+ return 'With a note the agent adjusts and continues. Without one, declining stops this turn.'+ }+ if (option.decision === 'declined') {+ return 'Stops this turn. Send a follow-up to redirect the agent.'+ }+ return null+}++interface PermissionOptionRowsProps {+ options: ApprovalCardOption[]+ responding: boolean+ onRespond: (optionId: string, customInput?: string) => void+}++/**+ * The generic approval's option rows, in the same CLI-like grammar as `PlanApprovalSelector`: caret ++ * numbered rows, window-level ↑↓/Enter/digit shortcuts, and an inline feedback textarea for a decline+ * that relays a note. Activating an approve or plain-decline row answers immediately; activating a+ * feedback-capable decline opens its textarea (Enter sends; for the optional-feedback kind an empty+ * Enter is the plain decline, for the legacy feedback-only kind it is a no-op). Consequence copy is a+ * sublabel on the row it applies to, shown while that row is selected or hovered.+ */+function PermissionOptionRows({ options, responding, onRespond }: PermissionOptionRowsProps): JSX.Element {+ const [selectedIndex, setSelectedIndex] = useState(0)+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)+ const [feedback, setFeedback] = useState('')+ const containerRef = useRef<HTMLDivElement>(null)++ const selectRow = (index: number): void => {+ setHoveredIndex(null)+ setSelectedIndex(index)+ }++ const activate = (index: number): void => {+ const option = options[index]+ if (!option || responding) {+ return+ }+ if (isFeedbackOption(option)) {+ selectRow(index)+ return+ }+ onRespond(option.optionId)}++ const submitFeedback = (option: ApprovalCardOption): void => {+ if (responding) {+ return+ }+ const text = feedback.trim()+ // The legacy feedback-only decline needs text on the wire; an empty Enter is a no-op. The+ // optional-feedback decline stays answerable without a note — that IS the plain decline.+ if (option.requiresFeedback && !text) {+ return+ }+ onRespond(option.optionId, text || undefined)+ }++ // Window-level shortcuts mirroring PlanApprovalSelector's guards: the feedback textarea owns the+ // keyboard while its row is selected, form fields and open menus are left alone, and focus resting+ // on an element outside the card keeps its native keys.+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent): void => {+ if (e.defaultPrevented || responding) {+ return+ }+ const target = e.target+ if (+ target instanceof HTMLElement &&+ (target.tagName === 'INPUT' ||+ target.tagName === 'TEXTAREA' ||+ target.tagName === 'SELECT' ||+ target.isContentEditable ||+ target.closest('[role="menu"]') !== null)+ ) {+ return+ }+ if (target instanceof HTMLElement && target !== document.body && !containerRef.current?.contains(target)) {+ return+ }+ switch (e.key) {+ case 'ArrowUp':+ e.preventDefault()+ selectRow((selectedIndex - 1 + options.length) % options.length)+ break+ case 'ArrowDown':+ e.preventDefault()+ selectRow((selectedIndex + 1) % options.length)+ break+ case 'Enter':+ e.preventDefault()+ activate(selectedIndex)+ break+ default:+ if (/^[1-9]$/.test(e.key) && !e.metaKey && !e.ctrlKey) {+ const idx = Number.parseInt(e.key, 10) - 1+ if (idx < options.length) {+ e.preventDefault()+ activate(idx)+ }+ }+ }+ }++ window.addEventListener('keydown', handleKeyDown)+ return () => window.removeEventListener('keydown', handleKeyDown)+ })++ return (+ <div ref={containerRef} className="flex flex-col gap-1 px-2">+ {options.map((option, index) => {+ const active = selectedIndex === index || hoveredIndex === index+ const editing = isFeedbackOption(option) && selectedIndex === index+ const sublabel = optionSublabel(option)+ const showSublabel = sublabel && (editing || active)+ return (+ <div+ key={option.optionId}+ onClick={() => activate(index)}+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ className={cn(+ '-mx-3 cursor-pointer select-none rounded px-3 py-1',+ selectedIndex === index+ ? 'bg-accent-highlight-secondary'+ : hoveredIndex === index+ ? 'bg-fill-button-tertiary-hover'+ : 'bg-transparent'+ )}+ >+ <div className="flex items-center gap-2 leading-4">+ <span+ className={cn(+ 'w-[1ch] shrink-0 text-[13px] leading-4',+ selectedIndex === index ? 'text-accent' : 'text-muted'+ )}+ >+ {selectedIndex === index ? '›' : ''}+ </span>+ <span+ className={cn(+ 'min-w-4 shrink-0 whitespace-nowrap text-right text-[13px] leading-4',+ active ? 'text-accent' : 'text-muted'+ )}+ >+ {index + 1}.+ </span>+ <div className="min-w-0 flex-1 leading-4">+ {editing ? (+ <InlineEditableText+ value={feedback}+ placeholder={FEEDBACK_PLACEHOLDER}+ active={editing}+ disabled={responding}+ onChange={setFeedback}+ onNavigateUp={() => selectRow((index - 1 + options.length) % options.length)}+ onNavigateDown={() => selectRow((index + 1) % options.length)}+ onEscape={() => {+ setFeedback('')+ selectRow(0)+ }}+ onSubmit={() => submitFeedback(option)}+ />+ ) : (+ <span+ className={cn(+ 'whitespace-pre-wrap font-medium text-[13px] leading-4',+ active ? 'text-accent' : 'text-primary'+ )}+ >+ {optionRowLabel(option)}+ </span>+ )}+ </div>+ </div>+ {showSublabel && <p className="mt-0.5 mb-0 pl-10 text-xs text-muted">{sublabel}</p>}+ </div>+ )+ })}+ </div>+ )}/*** Self-contained input-area renderer for an ACP `permission_request` on a sandbox conversation.* A plan approval (`ExitPlanMode`) renders `/code`'s plan-approval selector (the plan itself is the- * document card in the thread); every other request reuses the `QuestionField` surface as sandbox- * questions do, preserving the ACP option ids sent back to the runtime. `allow_always` stays hidden- * unless filtering would leave no choices.+ * document card in the thread); every other request renders the one-voice approval card: a single+ * headline sentence (the request's description) with the warning icon inline, the evidence block+ * (diff or capped payload preview), and the option rows. `allow_always` stays hidden unless filtering+ * would leave no choices.** Submitting POSTs through `runStreamLogic.respondToPermission`; the logic's* `respondingToPermission` drives the loading/double-submit guard and re-enables the controls when the@@ -54,7 +312,7 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): Jconst { respondToPermission, cancelRun } = useActions(boundLogic)const { respondingToPermission } = useValues(boundLogic)- // A plan approval keeps the product's Auto and Accept edits wire options. If neither is offered,+ // A plan approval keeps the product's Auto and Full auto wire options. If neither is offered,// fall through to the generic card so the request stays actionable.const planOptions = isPlanPermissionRequest(request) ? mapPermissionOptions(request.options, true) : []const planApproveOptions = planOptions.filter(@@ -83,89 +341,43 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): J// and the default filtering would leave a decline-only card.const defaultOptions = planOptions.length > 0 ? planOptions : mapPermissionOptions(request.options)const mappedOptions = defaultOptions.length > 0 ? defaultOptions : mapPermissionOptions(request.options, true)- // Only the legacy `reject_with_feedback` kind is feedback-only — reachable solely through the- // text field. A `reject_once` decline is a plain one-click button with no optional-feedback toggle.- const feedbackOption = mappedOptions.find((o) => o.requiresFeedback)- // Every option except the legacy feedback-only one renders as a one-click button.- const buttonOptions = mappedOptions.filter((o) => !o.requiresFeedback)- const hasOneClickDecline = buttonOptions.some((option) => option.decision === 'declined')- const allowFeedback = !!feedbackOption && !hasOneClickDecline-- const prompt = 'Approval required'+const display = getPermissionDisplay(request)- const payloadLanguage = display.payload?.trim().match(/^[{[]/) ? Language.JSON : Language.Text- // The description often just repeats the tool title — render the body only when it adds anything- // beyond the title line.- const requestBody = request.description ?? request.title- const showRequestBody = !!requestBody && requestBody !== display.title-- const handleAnswer = (value: string | string[] | null): void => {- if (respondingToPermission || value === null || Array.isArray(value)) {- return- }- const selectedOption = buttonOptions.find((option) => option.label === value)- if (selectedOption) {- respondToPermission({ requestId: request.requestId, optionId: selectedOption.optionId })- return- }- if (allowFeedback && feedbackOption) {- respondToPermission({- requestId: request.requestId,- optionId: feedbackOption.optionId,- customInput: value,- })- }- }+ // Only a genuine wire-level description that says more than the tool title becomes the+ // headline; a title-only request keeps the derived tool title as its headline (and the+ // evidence block skips its label) so the tool identity is stated exactly once.+ const headlineBody = request.description && request.description !== display.title ? request.description : undefinedreturn (- <div className="flex flex-col gap-2 p-3">- {showRequestBody && (- <div className="max-h-60 overflow-y-auto text-sm">- <MarkdownMessage content={requestBody ?? ''} id={`permission-${request.requestId}`} />- </div>- )}-- <div className="flex items-center gap-2 text-sm">- <IconWarning className="text-warning size-4" />- <LemonTag size="small" type="warning">- Approval- </LemonTag>+ <div className="flex flex-col gap-2.5 p-3">+ <div className="flex items-start gap-2 text-sm font-medium">+ <IconWarning className="text-warning size-4 mt-0.5 shrink-0" />+ {headlineBody ? (+ <div className="max-h-60 overflow-y-auto min-w-0 flex-1">+ <MarkdownMessage content={headlineBody} id={`permission-${request.requestId}`} />+ </div>+ ) : (+ <span>{display.title ?? 'Approval required'}</span>+ )}</div>- <div className="font-medium text-sm">{prompt}</div>- {display.title && <div className="text-xs text-secondary">{display.title}</div>}- {display.payload && (- <div className="max-h-60 overflow-y-auto">- <CodeSnippet language={payloadLanguage} className="text-xs" compact>- {display.payload}- </CodeSnippet>- </div>- )}+ <PermissionEvidence+ request={request}+ label={headlineBody ? display.title : undefined}+ payload={display.payload}+ />{respondingToPermission ? (<div className="flex items-center gap-2 text-muted pt-1"><Spinner className="size-4" /><span>Sending response…</span></div>) : (- <>- <QuestionField- question={toPermissionQuestion(prompt, buttonOptions, allowFeedback)}- value={undefined}- onAnswer={handleAnswer}- onChange={ignoreMultiSelectChange}- onSubmit={ignoreMultiSelectSubmit}- submitLabel="Send"- />- {allowFeedback ? (- <p className="text-xs text-secondary m-0">- Add a note when declining so the agent can adjust and continue, instead of stopping this- turn.- </p>- ) : hasOneClickDecline ? (- <p className="text-xs text-secondary m-0">- Declining stops this turn. Send a follow-up message to redirect the agent.- </p>- ) : null}- </>+ <PermissionOptionRows+ options={mappedOptions}+ responding={respondingToPermission}+ onRespond={(optionId, customInput) =>+ respondToPermission({ requestId: request.requestId, optionId, customInput })+ }+ />)}</div>)diff --git a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx b/products/posthog_ai/frontend/components/PlanApprovalActions.tsxindex 2696c72d2e54..70411ae1577f 100644--- a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx+++ b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx@@ -12,7 +12,7 @@ import { ComposerModePicker } from './composer/ComposerModePicker'const PLAN_APPROVAL_MODES: PermissionMode[] = [InitialPermissionModeEnumApi.BypassPermissions,- InitialPermissionModeEnumApi.AcceptEdits,+ InitialPermissionModeEnumApi.Auto,]export function isPlanApprovalModeOptionId(optionId: string): optionId is PermissionMode {@@ -62,7 +62,7 @@ interface InlineEditableTextProps {}/** Port of `/code`'s `InlineEditableText` — the borderless autosizing textarea that IS the reject row. */-function InlineEditableText({+export function InlineEditableText({value,placeholder,active,@@ -184,15 +184,13 @@ export function PlanApprovalSelector({return PLAN_APPROVAL_MODES.filter((mode) => offeredModeIds.has(mode))}, [approveOptions])- // Prefer the remembered offered mode, then Auto, then Accept edits.+ // Prefer the remembered offered mode, then Auto (the product default), then Full auto.const initialMode = useMemo(() => {const has = (id: string): boolean => modes.includes(id as PermissionMode)const remembered = readLastApprovalMode()return ((remembered && has(remembered) ? (remembered as PermissionMode) : undefined) ??- (has(InitialPermissionModeEnumApi.BypassPermissions)- ? InitialPermissionModeEnumApi.BypassPermissions- : undefined) ??+ (has(InitialPermissionModeEnumApi.Auto) ? InitialPermissionModeEnumApi.Auto : undefined) ??modes[0])}, [modes])diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsxindex 3cb5c019af6c..b89880426a0b 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx@@ -13,23 +13,18 @@ describe('ComposerModePicker', () => {it('shows the three product modes with their safety guidance and emits their server values', () => {const onModeChange = jest.fn()- render(- <ComposerModePicker- selectedMode={InitialPermissionModeEnumApi.BypassPermissions}- onModeChange={onModeChange}- />- )+ render(<ComposerModePicker selectedMode={InitialPermissionModeEnumApi.Auto} onModeChange={onModeChange} />)fireEvent.click(screen.getByLabelText('Mode'))expect(screen.getByText(- 'Bypasses all permissions. Safe in the sandbox, but the agent can modify or delete data without asking.'+ 'Accepts file edits and shell commands automatically. Always asks before PostHog tools that change live data. Creating or publishing content asks only while you watch the run.')).toBeInTheDocument()expect(screen.getByText(- 'Accepts file edits automatically. Bash commands and PostHog MCP tools that update or delete data still require approval.'+ 'Bypasses all permissions. Safe in the sandbox, but the agent can modify or delete data without asking.')).toBeInTheDocument()expect(@@ -38,13 +33,13 @@ describe('ComposerModePicker', () => {)).toBeInTheDocument()expect(screen.queryByText('Default')).not.toBeInTheDocument()- expect(screen.queryByText('Bypass permissions')).not.toBeInTheDocument()+ expect(screen.queryByText('Accept edits')).not.toBeInTheDocument()- const acceptEditsOption = screen.getByText('Accept edits').closest('[role="option"]')- expect(acceptEditsOption).not.toBeNull()- fireEvent.pointerDown(acceptEditsOption!, { pointerType: 'mouse' })- fireEvent.click(acceptEditsOption!)+ const fullAutoOption = screen.getByText('Full auto').closest('[role="option"]')+ expect(fullAutoOption).not.toBeNull()+ fireEvent.pointerDown(fullAutoOption!, { pointerType: 'mouse' })+ fireEvent.click(fullAutoOption!)- expect(onModeChange).toHaveBeenCalledWith(InitialPermissionModeEnumApi.AcceptEdits)+ expect(onModeChange).toHaveBeenCalledWith(InitialPermissionModeEnumApi.BypassPermissions)})})diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsxindex e4ed522539da..ff5ebff867cd 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx@@ -20,10 +20,9 @@ interface ModeStyle {className: string}-// Auto keeps the former bypass-permissions treatment so its risk is visible even though it is the default.const MODE_STYLES: Record<PermissionMode, ModeStyle> = {+ [InitialPermissionModeEnumApi.Auto]: { icon: <IconShield />, className: 'text-success' },[InitialPermissionModeEnumApi.BypassPermissions]: { icon: <IconUnlock />, className: 'text-danger' },- [InitialPermissionModeEnumApi.AcceptEdits]: { icon: <IconShield />, className: 'text-success' },[InitialPermissionModeEnumApi.Plan]: { icon: <IconPause />, className: 'text-warning' },}diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsxindex 3512391442cf..9d1fe8e278c9 100644--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx@@ -45,7 +45,25 @@ const DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions = {scrollbar: { alwaysConsumeMouseWheel: false, vertical: 'auto', horizontal: 'auto' },}-function DiffEditor({ diff, path }: { diff: ToolCallDiffContent; path?: string }): JSX.Element {+// The permission card's variant: side-by-side when the container affords it, with Monaco's own+// space-limited fallback collapsing back to the unified view in narrow embeds. Module-level for the+// same `updateOptions` identity reason as above.+const SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions = {+ ...DIFF_EDITOR_OPTIONS,+ renderSideBySide: true,+ useInlineViewWhenSpaceIsLimited: true,+ renderSideBySideInlineBreakpoint: 560,+}++export function DiffEditor({+ diff,+ path,+ sideBySide,+}: {+ diff: ToolCallDiffContent+ path?: string+ sideBySide?: boolean+}): JSX.Element {// Lazy-mount: only instantiate the Monaco diff editor once the card scrolls near the viewport.const { ref, inView } = useInView({ rootMargin: '500px', triggerOnce: true })// Match the surrounding app theme — without this Monaco falls back to its default `vs` (white) theme.@@ -60,7 +78,7 @@ function DiffEditor({ diff, path }: { diff: ToolCallDiffContent; path?: string }modified={diff.newText ?? ''}language={languageFromPath(path)}theme={isDarkModeOn ? 'vs-dark' : 'vs'}- options={DIFF_EDITOR_OPTIONS}+ options={sideBySide ? SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS : DIFF_EDITOR_OPTIONS}loading={<EditorSkeleton />}/>) : (@@ -71,7 +89,7 @@ function DiffEditor({ diff, path }: { diff: ToolCallDiffContent; path?: string }}/** +added / -removed mono stat chip for a diff. */-function DiffStats({ added, removed }: { added: number; removed: number }): JSX.Element {+export function DiffStats({ added, removed }: { added: number; removed: number }): JSX.Element {return (<span className="font-mono text-xs shrink-0"><span className="text-success">+{added}</span> <span className="text-danger">-{removed}</span>diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex afb2bdfc1577..c3728838bf61 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -233,8 +233,8 @@ describe('runInteractionLogic', () => {// The agent transitions autonomously (e.g. a plan approval leaves Plan mode) and confirms via a// `current_mode_update` frame — the live mode replaces the earlier pick.- stream.actions.setCurrentMode('acceptEdits')- expect(logic.values.selectedMode).toBe('acceptEdits')+ stream.actions.setCurrentMode('auto')+ expect(logic.values.selectedMode).toBe('auto')logic.actions.setComposerFormValues({ draft: 'go on' })await expectLogic(logic, () => {@@ -255,13 +255,14 @@ describe('runInteractionLogic', () => {stream.actions.setCurrentMode('full-access')expect(logic.values.selectedMode).toBe('plan')+ // The retired acceptEdits wire mode (older runs, resumed snapshots) normalizes to auto.stream.actions.setCurrentMode('acceptEdits')- expect(logic.values.selectedMode).toBe('acceptEdits')+ expect(logic.values.selectedMode).toBe('auto')})it('seeds a fresh run with the picked permission mode when the run is terminal', async () => {setStatus('completed')- logic.actions.setMode('acceptEdits')+ logic.actions.setMode('bypassPermissions')logic.actions.setComposerFormValues({ draft: 'continue from here' })await expectLogic(logic, () => {@@ -271,7 +272,7 @@ describe('runInteractionLogic', () => {expect(tasksRunCreate).toHaveBeenCalledWith('997',TASK_ID,- expect.objectContaining({ initial_permission_mode: 'acceptEdits' })+ expect.objectContaining({ initial_permission_mode: 'bypassPermissions' }))})@@ -350,7 +351,7 @@ describe('runInteractionLogic', () => {runtime_adapter: 'claude',model: 'claude-sonnet-5',reasoning_effort: 'high',- initial_permission_mode: 'bypassPermissions',+ initial_permission_mode: 'auto',resume_from_run_id: RUN_ID,pending_user_message: 'continue from here',})diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex affa70a001f9..cfc585502a1c 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -3170,6 +3170,63 @@ describe('runStreamLogic', () => {})})+ describe('full-auto mode', () => {+ // A `bypassPermissions` run opted out of tool approvals: a destructive exec sub-tool (which+ // otherwise always prompts) must auto-approve even on a foreground stream. The mode arrives+ // only on the session/new meta, so this also guards that seed parsing.+ it('auto-approves a destructive exec sub-tool once session/new seeds bypassPermissions', async () => {+ foregroundStreamLogic.actions.setForegroundStream('test-conversation', 'p-full-auto')+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ const source = MockStream.latest()++ await source.emitMessage(+ notification('session/new', { _meta: { permissionMode: 'bypassPermissions' } })+ )+ await source.emitMessage({+ ...permissionFrame,+ requestId: 'req-destructive-fa',+ toolCall: {+ ...permissionFrame.toolCall,+ rawInput: { command: 'call cdp-functions-partial-update {"id":"abc"}' },+ },+ })+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-destructive-fa', optionId: 'allow_once' },+ })+ })++ it('still surfaces a question in full-auto instead of picking an answer', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ const source = MockStream.latest()++ await source.emitMessage(+ notification('session/new', { _meta: { permissionMode: 'bypassPermissions' } })+ )+ await source.emitMessage({+ ...permissionFrame,+ requestId: 'req-question-fa',+ toolCall: {+ ...permissionFrame.toolCall,+ _meta: {+ codeToolKind: 'question',+ questions: [{ question: 'Which goal?', options: [{ label: 'A' }, { label: 'B' }] }],+ },+ rawInput: {},+ },+ })++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-question-fa')+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ })+ })+it('falls back to a manual card when the auto-approve POST fails', async () => {;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue({ status: 502 })jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex c9fbed78f717..779853be84d9 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -28,8 +28,9 @@ import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'import type { UserType } from '../../../../frontend/src/types'+import { isPlanPermissionRequest } from '../policy/permissionUtils'import { parseSandboxQuestions } from '../policy/questionUtils'-import { defaultPermissionDecision, findAllowOptionId, isPersistPromptTool } from '../policy/toolPolicy'+import { defaultPermissionDecision, findAllowOptionId, isFullAutoMode, isPersistPromptTool } from '../policy/toolPolicy'import type {ContextUsage,PermissionRequestRecord,@@ -2718,17 +2719,19 @@ export const runStreamLogic = kea<runStreamLogicType>([},routePermissionRequest: ({ record, replayedFromHistory }) => {// Replayed history is a read-only restore — never auto-approve (the run may be terminal).- // Persist/publish tools (dashboards, feature flags, surveys, hog functions, workflows)- // must still prompt when this run is a foreground stream (rendered in a surface the user- // is watching and can respond in), even though `defaultPermissionDecision` would+ // In full-auto (`bypassPermissions`) the user opted out of tool approvals entirely, so any+ // relayed tool request is answered with its allow option — but questions and plan approvals+ // still surface, since auto-answering those would pick an option on the user's behalf.+ // Otherwise: persist/publish tools (dashboards, feature flags, surveys, hog functions,+ // workflows) must still prompt when this run is a foreground stream (rendered in a surface+ // the user is watching and can respond in), even though `defaultPermissionDecision` would// auto-approve them as non-destructive. Background and headless runs keep auto-approving.+ const fullAuto =+ isFullAutoMode(values.currentMode) && !record.questions?.length && !isPlanPermissionRequest(record)const isForegroundStream = values.foregroundStreamKeys.has(props.streamKey)- const forcePromptForForeground = isForegroundStream && isPersistPromptTool(record)- if (- !replayedFromHistory &&- !forcePromptForForeground &&- defaultPermissionDecision(record) === 'auto_allow'- ) {+ const forcePromptForForeground = !fullAuto && isForegroundStream && isPersistPromptTool(record)+ const decision = fullAuto ? 'auto_allow' : defaultPermissionDecision(record)+ if (!replayedFromHistory && !forcePromptForForeground && decision === 'auto_allow') {const optionId = findAllowOptionId(record)if (optionId) {actions.autoApprovePermissionRequest(record, optionId)@@ -2745,8 +2748,8 @@ export const runStreamLogic = kea<runStreamLogicType>([// effect flushes). Yield one macrotask and re-check; if the stream became foreground,// surface the card instead of silently persisting. Plain `delay`, not a kea breakpoint —// a breakpoint would let a second rapid frame cancel this listener pre-POST and stall- // the agent.- if (isPersistPromptTool(record)) {+ // the agent. Full-auto runs skip the re-check — they never prompt for persist tools.+ if (!isFullAutoMode(values.currentMode) && isPersistPromptTool(record)) {await delay(0)if (values.foregroundStreamKeys.has(props.streamKey)) {actions.ingestPermissionRequest(record)@@ -3119,6 +3122,17 @@ export const runStreamLogic = kea<runStreamLogicType>([// sandbox_output, _posthog/git_checkpoint, … → no UI. No side effect either way.return}+ // The session/new request carries the run's starting permission mode in its meta. Seed the+ // mode fold from it so mode-aware permission routing (full-auto answering in+ // `bypassPermissions`) works before any `current_mode_update` arrives — the adapter only+ // emits those on changes.+ if (method === 'session/new') {+ const meta = (notification.params as { _meta?: { permissionMode?: unknown } } | undefined)?._meta+ if (typeof meta?.permissionMode === 'string' && meta.permissionMode) {+ actions.setCurrentMode(meta.permissionMode)+ }+ return+ }// session/prompt never renders and the resume-context filter is handled in the projection.if (method === 'session/prompt') {returndiff --git a/products/posthog_ai/frontend/policy/toolPolicy.test.ts b/products/posthog_ai/frontend/policy/toolPolicy.test.tsindex 58f2b72fe01f..eea2e34e1d46 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.test.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.test.ts@@ -63,6 +63,11 @@ describe('toolPolicy', () => {'delete','workflows-patch-graph','workflows-patch-email-template',+ // Destructive-annotated names with no verb segment come from the exact-name set.+ 'workflows-publish',+ 'experiment-ship-variant',+ 'skill-archive',+ 'error-tracking-issues-merge-create',])('%s is destructive', (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(true))it.each(['experiment-get',@@ -90,6 +95,9 @@ describe('toolPolicy', () => {['exec discovery verb', makeRecord({ input: { command: 'tools' } }), 'auto_allow'],['exec create', makeRecord({ input: { command: 'call insight-create {"name":"Signups"}' } }), 'auto_allow'],['exec update', makeRecord({ input: { command: 'call insight-update {"id":"abc"}' } }), 'prompt'],+ // A destructive-annotated name without a verb segment must resolve through the+ // exact-name set, not just the verb regex.+ ['exec publish', makeRecord({ input: { command: 'call workflows-publish {"id":"w1"}' } }), 'prompt'],['exec delete', makeRecord({ input: { command: 'call feature-flag-delete {"key":"new-nav"}' } }), 'prompt'],// A destructive sub-tool hidden behind --confirm/--json (in any order) must still prompt —// the inner tool name is resolved after the flags, not as the flag token.diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tsindex 3a489ac677d5..fc53a626d716 100644--- a/products/posthog_ai/frontend/policy/toolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -6,21 +6,56 @@ import { resolveToolCall } from '../utils/toolResolver'export { isPostHogExecTool } from '../components/tool/posthogExecDisplay'/**- * Default sandbox tool-permission policy, ported from Twig- * (`packages/agent/src/adapters/claude/permissions/posthog-exec-gate.ts`).+ * Client-side sandbox tool-permission policy.*- * The deployed agent-server runs in `default` mode and asks for approval on every PostHog `exec`- * call. We mirror Twig's policy on the client instead: auto-approve every built-in (default) tool- * and every PostHog `exec` operation EXCEPT the destructive ones (update/delete/destroy/- * partial-update), which still surface the approval card. Non-PostHog MCP tools fall outside the- * default-allow contract and also prompt.+ * The agent-server relays a permission request here in two cases: the exec sub-tool matched the+ * server's `--posthogExecPermissionRegex` (relayed in every non-background run regardless of+ * permission mode — see `POSTHOG_EXEC_PERMISSION_REGEX` in `products/tasks/backend/constants.py`,+ * which must stay in sync with the destructive verbs and persist tools below), or the run's+ * permission mode relays manual approvals and a client is connected. This policy decides which+ * relayed requests auto-approve and which surface the approval card: built-ins and read-only+ * PostHog `exec` auto-approve; destructive sub-tools prompt; persist/publish sub-tools prompt only+ * on foreground streams; full-auto (`bypassPermissions`) runs answer everything.*/+/** Full-auto modes answer every relayed tool request without prompting (questions and plan approvals still surface). */+export function isFullAutoMode(mode: string | null | undefined): boolean {+ return mode === 'bypassPermissions'+}+/** A sub-tool is destructive when one of these verbs appears as a whole `-`-bounded segment. */const POSTHOG_DESTRUCTIVE_SUBTOOL_RE = /(^|-)(partial-update|update|patch|delete|destroy)(-|$)/i+/**+ * Destructive-annotated sub-tools whose names carry no destructive verb segment (publish, ship,+ * merge, archive, …). Mirrors `POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS` in+ * `products/tasks/backend/constants.py`, which a backend test keeps complete against the+ * `annotations.destructive: true` tools in `products/*\/mcp/*.yaml` — update both together.+ */+const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([+ 'error-tracking-bypass-rules-create',+ 'error-tracking-issues-merge-create',+ 'error-tracking-issues-split-create',+ 'error-tracking-suppression-rules-create',+ 'experiment-ship-variant',+ 'external-data-schemas-resync',+ 'external-data-sources-repair-cdc-create',+ 'heatmaps-saved-regenerate',+ 'inbox-reports-bulk-set-state',+ 'inbox-reports-set-state',+ 'llma-prompt-label-set',+ 'scout-scratchpad-forget',+ 'signals-scout-scratchpad-forget',+ 'skill-archive',+ 'user-interview-topics-remove-interviewee',+ 'visual-review-runs-finalize-create',+ 'workflows-discard-draft',+ 'workflows-publish',+ 'workflows-test-run',+])+export function isPostHogDestructiveSubTool(subTool: string): boolean {- return POSTHOG_DESTRUCTIVE_SUBTOOL_RE.test(subTool)+ return POSTHOG_DESTRUCTIVE_SUBTOOL_RE.test(subTool) || POSTHOG_DESTRUCTIVE_SUB_TOOLS.has(subTool.toLowerCase())}export type PermissionDecision = 'auto_allow' | 'prompt'@@ -82,7 +117,10 @@ export function defaultPermissionDecision(record: PermissionRequestRecord): Perm* (background runs, headless runs, replays); the call site in `runStreamLogic`'s* `routePermissionRequest` forces the prompt path for foreground streams. Scoped to the product* families from the apply-back migration plan — every enabled tool that persists new content- * (create/copy/add) or publishes to end users (launch/stop); add a sub-tool name here to extend it.+ * (create/copy/add) or publishes to end users (launch/stop). To extend it, add the sub-tool name+ * here AND to `POSTHOG_EXEC_PERMISSION_REGEX` in `products/tasks/backend/constants.py` — the+ * server only relays sub-tools matching that regex, so a name missing there never reaches this+ * gate in modes that don't relay manual approvals.*/const PERSIST_PROMPT_SUB_TOOLS = new Set(['dashboard-create',diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex d042765d9c9b..486dd86ede83 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -96,7 +96,7 @@ describe('taskTrackerSceneLogic', () => {// state). Dropping either regresses follow-up streaming / loses the first prompt.expect(runBody).toMatchObject({mode: 'interactive',- initial_permission_mode: 'bypassPermissions',+ initial_permission_mode: 'auto',pending_user_message: 'do the thing',})const streamKey = logic.values.activeCreation?.streamKeydiff --git a/products/posthog_ai/frontend/utils/composerModes.test.ts b/products/posthog_ai/frontend/utils/composerModes.test.tsindex f4a585c50f4c..1e110be48443 100644--- a/products/posthog_ai/frontend/utils/composerModes.test.ts+++ b/products/posthog_ai/frontend/utils/composerModes.test.ts@@ -1,14 +1,14 @@import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'-import { cycleMode, DEFAULT_COMPOSER_MODE } from './composerModes'+import { cycleMode, DEFAULT_COMPOSER_MODE, getModeOption } from './composerModes'describe('composerModes', () => {// The `shift+tab` cycle: advances through every mode and wraps back to the first, so no mode is// unreachable and the last one loops around.it.each([- [InitialPermissionModeEnumApi.BypassPermissions, InitialPermissionModeEnumApi.AcceptEdits],- [InitialPermissionModeEnumApi.AcceptEdits, InitialPermissionModeEnumApi.Plan],- [InitialPermissionModeEnumApi.Plan, InitialPermissionModeEnumApi.BypassPermissions],+ [InitialPermissionModeEnumApi.Auto, InitialPermissionModeEnumApi.BypassPermissions],+ [InitialPermissionModeEnumApi.BypassPermissions, InitialPermissionModeEnumApi.Plan],+ [InitialPermissionModeEnumApi.Plan, InitialPermissionModeEnumApi.Auto],])('cycleMode(%s) → %s', (current, next) => {expect(cycleMode(current)).toBe(next)})@@ -16,4 +16,11 @@ describe('composerModes', () => {it.each([[null], [undefined], ['not-a-mode']])('cycleMode(%s) resets to the default', (current) => {expect(cycleMode(current)).toBe(DEFAULT_COMPOSER_MODE)})++ // Persisted selections and older runs still carry the retired acceptEdits mode — it must keep+ // resolving to a real option instead of falling back to the bare 'Mode' trigger.+ it('resolves legacy acceptEdits to the auto option', () => {+ expect(getModeOption(InitialPermissionModeEnumApi.AcceptEdits)?.value).toBe(InitialPermissionModeEnumApi.Auto)+ expect(cycleMode(InitialPermissionModeEnumApi.AcceptEdits)).toBe(InitialPermissionModeEnumApi.BypassPermissions)+ })})diff --git a/products/posthog_ai/frontend/utils/composerModes.ts b/products/posthog_ai/frontend/utils/composerModes.tsindex aa9d9c539f8a..c8a2580a5afc 100644--- a/products/posthog_ai/frontend/utils/composerModes.ts+++ b/products/posthog_ai/frontend/utils/composerModes.ts@@ -2,8 +2,8 @@ import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated//** The permission modes exposed by the PostHog AI composer. */export type PermissionMode =+ | typeof InitialPermissionModeEnumApi.Auto| typeof InitialPermissionModeEnumApi.BypassPermissions- | typeof InitialPermissionModeEnumApi.AcceptEdits| typeof InitialPermissionModeEnumApi.Planexport interface ComposerModeOption {@@ -12,21 +12,21 @@ export interface ComposerModeOption {description: string}-export const DEFAULT_COMPOSER_MODE: PermissionMode = InitialPermissionModeEnumApi.BypassPermissions+export const DEFAULT_COMPOSER_MODE: PermissionMode = InitialPermissionModeEnumApi.Auto// Ordered for the Shift+Tab cycle and the picker.export const MODE_OPTIONS: ComposerModeOption[] = [{- value: InitialPermissionModeEnumApi.BypassPermissions,+ value: InitialPermissionModeEnumApi.Auto,label: 'Auto',description:- 'Bypasses all permissions. Safe in the sandbox, but the agent can modify or delete data without asking.',+ 'Accepts file edits and shell commands automatically. Always asks before PostHog tools that change live data. Creating or publishing content asks only while you watch the run.',},{- value: InitialPermissionModeEnumApi.AcceptEdits,- label: 'Accept edits',+ value: InitialPermissionModeEnumApi.BypassPermissions,+ label: 'Full auto',description:- 'Accepts file edits automatically. Bash commands and PostHog MCP tools that update or delete data still require approval.',+ 'Bypasses all permissions. Safe in the sandbox, but the agent can modify or delete data without asking.',},{value: InitialPermissionModeEnumApi.Plan,@@ -36,8 +36,18 @@ export const MODE_OPTIONS: ComposerModeOption[] = [},]+// Modes retired from the picker resolve to their closest current equivalent, so persisted+// selections and runs started before the retirement keep resolving to a real option.+const LEGACY_MODE_ALIASES: Record<string, PermissionMode> = {+ [InitialPermissionModeEnumApi.AcceptEdits]: InitialPermissionModeEnumApi.Auto,+}+export function getModeOption(mode: string | null | undefined): ComposerModeOption | undefined {- return MODE_OPTIONS.find((option) => option.value === mode)+ if (mode == null) {+ return undefined+ }+ const normalized = LEGACY_MODE_ALIASES[mode] ?? mode+ return MODE_OPTIONS.find((option) => option.value === normalized)}export function getModeLabel(mode: string | null | undefined): string {@@ -48,7 +58,7 @@ export function getModeLabel(mode: string | null | undefined): string {// (null/undefined or a value not in the set) resets to the default so the cycle stays predictable.export function cycleMode(current: string | null | undefined): PermissionMode {const order = MODE_OPTIONS.map((option) => option.value)- const index = order.indexOf(current as PermissionMode)+ const index = order.indexOf((getModeOption(current)?.value ?? current) as PermissionMode)if (index === -1) {return DEFAULT_COMPOSER_MODE}diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex be3ea1c1a25e..ab3bc3bdc16a 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -65,6 +65,68 @@ ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissiCodexPermissionMode = Literal["plan", "auto", "read-only", "full-access"]InitialPermissionMode = ClaudePermissionMode | CodexPermissionMode+# PostHog `exec` sub-tools that must be approved by the user before they run, passed to the+# agent-server as `--posthogExecPermissionRegex`. A matching sub-tool is relayed to the connected+# client in every non-background run regardless of permission mode (the client then decides:+# destructive sub-tools always prompt, persist/publish sub-tools prompt only on foreground streams,+# full-auto runs answer everything). Three alternatives: destructive verbs as `-`-bounded segments,+# the exact names of `annotations.destructive: true` tools the verb regex misses, and the exact+# persist/publish tool names from the apply-back product families. Must stay in sync with+# `POSTHOG_DESTRUCTIVE_SUBTOOL_RE`, `POSTHOG_DESTRUCTIVE_SUB_TOOLS`, and `PERSIST_PROMPT_SUB_TOOLS`+# in `products/posthog_ai/frontend/policy/toolPolicy.ts`.+POSTHOG_EXEC_DESTRUCTIVE_VERB_REGEX = r"(^|-)(partial-update|update|patch|delete|destroy)(-|$)"++# Enabled tools annotated `destructive: true` in `products/*/mcp/*.yaml` whose names carry no+# destructive verb segment (publish, ship, merge, archive, …). Kept complete against those+# annotations by `test_exec_permission_regex_covers_destructive_annotated_tools`.+POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (+ "error-tracking-bypass-rules-create",+ "error-tracking-issues-merge-create",+ "error-tracking-issues-split-create",+ "error-tracking-suppression-rules-create",+ "experiment-ship-variant",+ "external-data-schemas-resync",+ "external-data-sources-repair-cdc-create",+ "heatmaps-saved-regenerate",+ "inbox-reports-bulk-set-state",+ "inbox-reports-set-state",+ "llma-prompt-label-set",+ "scout-scratchpad-forget",+ "signals-scout-scratchpad-forget",+ "skill-archive",+ "user-interview-topics-remove-interviewee",+ "visual-review-runs-finalize-create",+ "workflows-discard-draft",+ "workflows-publish",+ "workflows-test-run",+)++# Non-destructive tools that persist new content (create/copy/add) or publish to end users+# (launch/stop), from the apply-back product families — the client prompts for these only on+# foreground streams.+POSTHOG_EXEC_PERSIST_SUB_TOOLS: tuple[str, ...] = (+ "dashboard-create",+ "dashboard-create-text-tile",+ "dashboard-tile-copy",+ "dashboard-widgets-batch-add",+ "create-feature-flag",+ "feature-flags-copy-flags-create",+ "scheduled-changes-create",+ "survey-create",+ "survey-launch",+ "survey-stop",+ "cdp-functions-create",+ "workflows-create",+ "workflows-create-email-template",+)++POSTHOG_EXEC_PERMISSION_REGEX = (+ POSTHOG_EXEC_DESTRUCTIVE_VERB_REGEX+ + "|^("+ + "|".join(POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS + POSTHOG_EXEC_PERSIST_SUB_TOOLS)+ + ")$"+)+INITIAL_PERMISSION_MODE_CHOICES: list[str] = list(get_args(ClaudePermissionMode))CODEX_INITIAL_PERMISSION_MODE_CHOICES: list[str] = list(get_args(CodexPermissionMode))ALL_INITIAL_PERMISSION_MODE_CHOICES: list[str] = [diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex ac8ac638d115..e33ab3035573 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -20,7 +20,7 @@ from django.conf import settingsif TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig-from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS+from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARSfrom products.tasks.backend.exceptions import (ProcessTaskError,SandboxCleanupError,@@ -800,6 +800,7 @@ class DockerSandbox(SandboxBase):event_ingest_keep_stream_open: bool = False,repo_ready_file: str | None = None,rtk_enabled: bool = True,+ posthog_exec_permission_regex: str | None = None,) -> str:# The host proxy URL (e.g. localhost:8003) is unreachable from inside the container;# rewrite it the same way POSTHOG_API_URL is for Docker sandboxes.@@ -825,6 +826,11 @@ class DockerSandbox(SandboxBase):repo_flag = f" --repositoryPath {shlex.quote(repo_path)}" if repo_path else ""domains_flag = f" --allowedDomains {shlex.quote(','.join(allowed_domains))}" if allowed_domains else ""repo_ready_flag = f" --repoReadyFile {shlex.quote(repo_ready_file)}" if repo_ready_file else ""+ exec_permission_flag = (+ f" --posthogExecPermissionRegex {shlex.quote(posthog_exec_permission_regex)}"+ if posthog_exec_permission_regex+ else ""+ )# Scope BASH_ENV to the agent-server process (not the container env) so only the# agent's per-command tool shells re-source the refreshed token. Backend maintenance# execs (clone/checkout/token injection) must not source it — the script could be@@ -835,7 +841,7 @@ class DockerSandbox(SandboxBase):f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"- f"{domains_flag}{repo_ready_flag}"+ f"{domains_flag}{repo_ready_flag}{exec_permission_flag}")# agentsh injects HTTP_PROXY pointing at a per-session egress proxy port; undici@@ -931,6 +937,14 @@ class DockerSandbox(SandboxBase):logger.warning(f"Installed agent-server in sandbox {self.id} predates --autoPublish; starting review-first")auto_publish = False+ exec_permission_regex: str | None = POSTHOG_EXEC_PERMISSION_REGEX+ if not self.agent_server_supports_exec_permission_regex():+ logger.warning(+ f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "+ "exec sub-tools will not prompt"+ )+ exec_permission_regex = None+command = self._build_agent_server_command(repo_path,task_id,@@ -953,6 +967,7 @@ class DockerSandbox(SandboxBase):event_ingest_keep_stream_open=event_ingest_keep_stream_open,repo_ready_file=repo_ready_file,rtk_enabled=rtk_enabled,+ posthog_exec_permission_regex=exec_permission_regex,)logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")@@ -1003,6 +1018,7 @@ class DockerSandbox(SandboxBase):event_ingest_keep_stream_open=event_ingest_keep_stream_open,repo_ready_file=repo_ready_file,rtk_enabled=rtk_enabled,+ posthog_exec_permission_regex=exec_permission_regex,)if self._launch_and_check(command):logger.info(f"Agent-server started on port {self._host_port} (without --baseBranch)")diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex a91a0f8b43e9..73dc8767c185 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -36,6 +36,7 @@ from posthog.settings import CLOUD_DEPLOYMENTfrom products.tasks.backend.constants import (ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,+ POSTHOG_EXEC_PERMISSION_REGEX,SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS,SNAPSHOT_KIND_DIRECTORY,SNAPSHOT_KIND_FILESYSTEM,@@ -952,6 +953,7 @@ class ModalSandbox(SandboxBase):event_ingest_keep_stream_open: bool = False,repo_ready_file: str | None = None,rtk_enabled: bool = True,+ posthog_exec_permission_regex: str | None = None,) -> str:env_prefix = build_agent_runtime_env_prefix(interaction_origin=interaction_origin,@@ -973,6 +975,11 @@ class ModalSandbox(SandboxBase):branch_flag = f" --baseBranch {shlex.quote(branch)}" if branch else ""domains_flag = f" --allowedDomains {shlex.quote(','.join(allowed_domains))}" if allowed_domains else ""repo_ready_flag = f" --repoReadyFile {shlex.quote(repo_ready_file)}" if repo_ready_file else ""+ exec_permission_flag = (+ f" --posthogExecPermissionRegex {shlex.quote(posthog_exec_permission_regex)}"+ if posthog_exec_permission_regex+ else ""+ )# Scope BASH_ENV to the agent-server process (not the container env) so only the# agent's per-command tool shells re-source the refreshed token. Backend maintenance# execs (clone/checkout/token injection) must not source it — the script could be@@ -983,7 +990,7 @@ class ModalSandbox(SandboxBase):f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"- f"{domains_flag}{repo_ready_flag}"+ f"{domains_flag}{repo_ready_flag}{exec_permission_flag}")if repo_ready_file:@@ -1111,6 +1118,14 @@ class ModalSandbox(SandboxBase):logger.warning(f"Installed agent-server in sandbox {self.id} predates --autoPublish; starting review-first")auto_publish = False+ exec_permission_regex: str | None = POSTHOG_EXEC_PERMISSION_REGEX+ if not self.agent_server_supports_exec_permission_regex():+ logger.warning(+ f"Installed agent-server in sandbox {self.id} predates --posthogExecPermissionRegex; "+ "exec sub-tools will not prompt"+ )+ exec_permission_regex = None+command = self._build_agent_server_command(repo_path,task_id,@@ -1133,6 +1148,7 @@ class ModalSandbox(SandboxBase):event_ingest_keep_stream_open=event_ingest_keep_stream_open,repo_ready_file=repo_ready_file,rtk_enabled=rtk_enabled,+ posthog_exec_permission_regex=exec_permission_regex,)logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex b55e80aaf546..7503f439e97f 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -250,6 +250,15 @@ class SandboxBase(ABC):result = self.execute("grep -q autoPublish /scripts/node_modules/.bin/agent-server", timeout_seconds=10)return result.exit_code == 0+ def agent_server_supports_exec_permission_regex(self) -> bool:+ """Same probe as --autoPublish: check the installed binary before passing+ --posthogExecPermissionRegex; unsupported binaries degrade to server-side auto-approval of+ exec sub-tools instead of crashing at launch."""+ result = self.execute(+ "grep -q posthogExecPermissionRegex /scripts/node_modules/.bin/agent-server", timeout_seconds=10+ )+ return result.exit_code == 0+def clone_repository(self,repository: str,diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.pyindex 4c4bcd5f9615..8dc1de421144 100644--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py@@ -1,6 +1,12 @@+import re+import shlex+import pytestfrom unittest.mock import patch+from parameterized import parameterized++from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEXfrom products.tasks.backend.exceptions import SandboxExecutionErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig@@ -46,6 +52,36 @@ def test_start_agent_server_health_check_timeout_is_retryable_and_not_captured(scapture_exception.assert_not_called()+def test_build_agent_server_command_gates_exec_permission_regex(sandbox: DockerSandbox):+ with_flag = sandbox._build_agent_server_command(+ None, "t1", "r1", "interactive", True, posthog_exec_permission_regex=POSTHOG_EXEC_PERMISSION_REGEX+ )+ assert f"--posthogExecPermissionRegex {shlex.quote(POSTHOG_EXEC_PERMISSION_REGEX)}" in with_flag++ # An agent-server predating the flag rejects unknown options — the builder must omit it entirely.+ without_flag = sandbox._build_agent_server_command(None, "t1", "r1", "interactive", True)+ assert "--posthogExecPermissionRegex" not in without_flag+++ [+ ("cdp-functions-partial-update", True),+ ("insight-update", True),+ ("survey-delete", True),+ ("dashboard-create", True),+ ("survey-launch", True),+ ("workflows-create-email-template", True),+ ("insight-create", False),+ ("cdp-functions-list", False),+ ("dashboard-create-extra", False),+ ]+)+def test_exec_permission_regex_matches_gated_sub_tools(sub_tool: str, should_match: bool):+ # The constant is hand-concatenated; a broken anchor or alternation silently stops relaying+ # approvals for (or starts prompting on) the wrong sub-tools.+ assert bool(re.search(POSTHOG_EXEC_PERMISSION_REGEX, sub_tool, re.IGNORECASE)) is should_match++def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):failed = ExecutionResult(stdout="", stderr="boom", exit_code=1)with (diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 803c8b4a5f96..78ad1c937925 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -641,6 +641,7 @@ class TestModalSandboxAgentServer:mock_sandbox.execute = MagicMock(side_effect=[ExecutionResult(stdout="", stderr="", exit_code=0, error=None),+ ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # --posthogExecPermissionRegex probeExecutionResult(stdout="", stderr="", exit_code=1, error=None),ExecutionResult(stdout="some log output", stderr="", exit_code=0, error=None),]@@ -695,6 +696,7 @@ class TestModalSandboxAgentServer:mock_sandbox.execute = MagicMock(side_effect=[ExecutionResult(stdout="", stderr="", exit_code=0, error=None),+ ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # --posthogExecPermissionRegex probeExecutionResult(stdout="", stderr="", exit_code=0, error=None),ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),]diff --git a/products/tasks/backend/tests/test_constants.py b/products/tasks/backend/tests/test_constants.pynew file mode 100644index 000000000000..9c9dc50a7c08--- /dev/null+++ b/products/tasks/backend/tests/test_constants.py@@ -0,0 +1,37 @@+import re+from pathlib import Path++import yaml++from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX++PRODUCTS_DIR = Path(__file__).resolve().parents[3]+++def _enabled_destructive_tools() -> list[str]:+ tools: list[str] = []+ for config_path in sorted(PRODUCTS_DIR.glob("*/mcp/*.yaml")) + sorted(PRODUCTS_DIR.glob("*/mcp/*.yml")):+ config = yaml.safe_load(config_path.read_text())+ if not isinstance(config, dict):+ continue+ declared = config.get("tools") or {}+ entries = declared.items() if isinstance(declared, dict) else ((t.get("name"), t) for t in declared)+ for name, tool in entries:+ if not isinstance(tool, dict) or not isinstance(name, str) or not tool.get("enabled"):+ continue+ if (tool.get("annotations") or {}).get("destructive"):+ tools.append(name)+ return tools+++def test_exec_permission_regex_covers_destructive_annotated_tools():+ # A destructive-annotated tool the regex misses is never relayed for approval and executes+ # silently in `auto` mode — the exact gap this regex exists to close. When this fails, add the+ # tool name to `POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS` in `constants.py` AND to+ # `POSTHOG_DESTRUCTIVE_SUB_TOOLS` in `products/posthog_ai/frontend/policy/toolPolicy.ts`.+ destructive = _enabled_destructive_tools()+ assert len(destructive) > 0, f"no destructive-annotated MCP tools found under {PRODUCTS_DIR} — glob broken?"++ pattern = re.compile(POSTHOG_EXEC_PERMISSION_REGEX, re.IGNORECASE)+ ungated = sorted(name for name in destructive if not pattern.search(name))+ assert not ungated, f"destructive-annotated MCP tools not covered by POSTHOG_EXEC_PERMISSION_REGEX: {ungated}"