: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): add permission-mode selector with plan preview (#67451)
Georgiy Tarasov5864b663cf79
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c3db053a2cef..eaf84d3a7cbe 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7087,9 +7087,9 @@ snapshots:scenes-app-tasks--mobile-list--light:hash: v1.k794b7964.9fd49300ca0d02ce3fe8cf6ea7eb850af2f42332d19a821ac73a6108f33fd651.aHbvQ9EqCKA43njPMkK_xgXEq4rToiJ0U8zAsxjwEWAscenes-app-tasks--mobile-new-task--dark:- hash: v1.k794b7964.9b9c40cac551da8e7671c94761af2c1fea8d734127642b41daf0aaf83c21b95c.4GYGN5u7XrKtcu792itWe5FYthARxKS9Zj-7apPTv3A+ hash: v1.k794b7964.c659bc768ad6ece501075207672466dd3a7f3401fd9fbffbef400d552cfd3007.Nm4GPHMsfybaB-1wJbcZ5Gr8oUCY0qiTPRujpHMpl0gscenes-app-tasks--mobile-new-task--light:- hash: v1.k794b7964.dcf36750497b33932f1ab4b6881c04136827a801b777e1907244a31ecf301f65.1obDifj36R2bZNd4c2YID4coIqim-oVjc6lMHJR3NGk+ hash: v1.k794b7964.7d4307cef0f64137bd0278b3e9ca94c620ecbc63a726096ca6bdbc9570073ab5.p-KShlBQ8CPGw75SWnLVHxKGeUOnzvX3tACb5usDH9cscenes-app-tasks--mobile-task-selected--dark:hash: v1.k794b7964.db0156b3fd83b5c3494116788236075e0bc2c5ace019e4c1d9947d2b21fa70fb.4HfTdy-PBBkgEn0HFlUkrJm0D6GCiujf_ljrGGrLrscscenes-app-tasks--mobile-task-selected--light:diff --git a/products/posthog_ai/frontend/components/Approval.test.tsx b/products/posthog_ai/frontend/components/Approval.test.tsxindex 7606c2a598c9..7bfd31a69571 100644--- a/products/posthog_ai/frontend/components/Approval.test.tsx+++ b/products/posthog_ai/frontend/components/Approval.test.tsx@@ -58,11 +58,13 @@ function makeRequest(overrides: Partial<PermissionRequestRecord> = {}): Permissidescribe('Sandbox approval input area', () => {const respondToPermission = jest.fn()+ const cancelRun = jest.fn()beforeEach(() => {jest.clearAllMocks()- ;(useActions as jest.Mock).mockReturnValue({ respondToPermission })- ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false, currentMode: null })+ window.localStorage.removeItem('posthog-ai.lastPlanApprovalMode')+ ;(useActions as jest.Mock).mockReturnValue({ respondToPermission, cancelRun })+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })})afterEach(() => {@@ -167,24 +169,167 @@ describe('Sandbox approval input area', () => {})})- it.each([- [- 'the agent is in plan mode',- (): void => {- ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false, currentMode: 'plan' })+ // 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.+ const planWireOptions = [+ { optionId: 'bypassPermissions', name: 'Yes, and bypass permissions', 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' },+ {+ optionId: 'reject_with_feedback',+ name: 'No, and tell the agent what to do differently',+ kind: 'reject_once',+ customInput: true,+ },+ ]++ function makePlanRequest(overrides: Partial<PermissionRequestRecord> = {}): PermissionRequestRecord {+ return makeRequest({+ toolName: '',+ title: 'Ready to code?',+ description: undefined,+ options: planWireOptions,+ rawToolCall: {+ ...rawToolCall,+ kind: 'switch_mode',+ title: 'Ready to code?',+ input: { plan: '# The plan', planFilePath: '/tmp/plan.md', toolName: 'ExitPlanMode' },},- makeRequest(),- ],- [- 'the tool call is tagged as a plan',- (): void => {},- makeRequest({ rawToolCall: { ...rawToolCall, kind: 'plan' } }),- ],- ])('shows plan copy when %s', (_case, arrange, request) => {- arrange()+ ...overrides,+ })+ }++ it.each([+ ['the request is for ExitPlanMode', makePlanRequest({ toolName: 'ExitPlanMode', rawToolCall })],+ ['the tool call is tagged as a plan', makePlanRequest({ rawToolCall: { ...rawToolCall, kind: 'plan' } })],+ // The real agent-server wire shape: no top-level tool name, `kind: 'switch_mode'`, and the+ // tool name embedded in the input payload alongside the plan.+ ['the tool input carries the ExitPlanMode tool name', makePlanRequest()],+ ])('shows the plan-approval selector when %s', (_case, request) => {render(<PermissionInput streamKey="conv-1" request={request} />)- expect(screen.getByText('Approve this plan?')).toBeInTheDocument()+ expect(screen.getByText('Implementation Plan')).toBeInTheDocument()+ expect(screen.getByText('Approve this plan to proceed?')).toBeInTheDocument()+ })++ it('keeps the supported plan modes and approves with Auto as bypassPermissions', () => {+ 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',+ })+ })++ it('pre-selects the remembered last-approved mode over Auto', () => {+ 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' })+ })++ it('opens the mode picker with only Auto and Accept edits', () => {+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ fireEvent.click(screen.getByLabelText('Mode'))++ expect(screen.getByText('Accept edits')).toBeInTheDocument()+ expect(screen.queryByText('Default')).not.toBeInTheDocument()+ expect(screen.queryByText('Plan')).not.toBeInTheDocument()+ expect(screen.queryByText('Bypass permissions')).not.toBeInTheDocument()+ })++ it('sends plan rejection feedback through the reject row, ignoring an empty submit', () => {+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ // Select the reject row, then submit with Enter — empty feedback is a no-op.+ fireEvent.click(screen.getByText('2.'))+ const input = screen.getByPlaceholderText('Type here to tell the agent what to do differently')+ fireEvent.keyDown(input, { key: 'Enter' })+ expect(respondToPermission).not.toHaveBeenCalled()++ fireEvent.change(input, { target: { value: 'Use a different approach' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'reject_with_feedback',+ customInput: 'Use a different approach',+ })+ })++ it('handles the digit and Escape shortcuts without the selector being focused', () => {+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ // Shortcuts are window-level — fired on the page body, not on the selector.+ fireEvent.keyDown(document.body, { key: 'Escape' })+ expect(cancelRun).toHaveBeenCalled()+ expect(respondToPermission).not.toHaveBeenCalled()++ fireEvent.keyDown(document.body, { key: '1' })+ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'bypassPermissions',+ })+ })++ it('leaves keys alone when focus sits on an element outside the card', () => {+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ // Focus parked on unrelated page chrome (a nav button) — Enter must keep activating that+ // element and Tab must keep moving focus, never approve the plan or cycle its mode.+ const outsideButton = document.createElement('button')+ document.body.appendChild(outsideButton)+ outsideButton.focus()++ const tabNotPrevented = fireEvent.keyDown(outsideButton, { key: 'Tab' })+ fireEvent.keyDown(outsideButton, { key: 'Enter' })+ fireEvent.keyDown(outsideButton, { key: '1' })+ outsideButton.remove()++ // Tab was not prevented — the browser's native focus traversal still happens.+ expect(tabNotPrevented).toBe(true)+ expect(respondToPermission).not.toHaveBeenCalled()+ expect(cancelRun).not.toHaveBeenCalled()+ })++ it('blocks plan approval while the response POST is in flight', () => {+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })+ render(<PermissionInput streamKey="conv-1" request={makePlanRequest()} />)++ fireEvent.click(screen.getByText('Approve and proceed'))++ expect(respondToPermission).not.toHaveBeenCalled()+ })++ it('keeps the approve options on the fallback card when no plan mode id is recognized', () => {+ // Version-skew shape: a plan request whose approve ids all predate/postdate the known mode+ // enum. The fallback card must keep the `allow_always` approve options, not go decline-only.+ render(+ <PermissionInput+ streamKey="conv-1"+ request={makePlanRequest({+ options: [+ { optionId: 'future-mode', name: 'Yes, use future mode', kind: 'allow_always' },+ {+ optionId: 'reject_with_feedback',+ name: 'No, tell the agent what to do differently',+ kind: 'reject_once',+ },+ ],+ })}+ />+ )++ expect(screen.getByText('Yes, use future mode')).toBeInTheDocument()+ expect(screen.getByText('No, tell the agent what to do differently')).toBeInTheDocument()})it('does not show plan copy just because the title mentions a plan', () => {diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsxindex d928ecd12dc5..9d45e9ce50e4 100644--- a/products/posthog_ai/frontend/components/PermissionInput.tsx+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx@@ -10,8 +10,9 @@ import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistanimport { runStreamLogic } from '../logics/runStreamLogic'import { MarkdownMessage } from '../messages/MarkdownMessage'import { getPermissionDisplay } from '../policy/permissionDisplayUtils'-import { mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'+import { isPlanPermissionRequest, mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'import type { PermissionRequestRecord } from '../types/streamTypes'+import { isPlanApprovalModeOptionId, PlanApprovalSelector } from './PlanApprovalActions'import { QuestionField } from './QuestionField'interface PermissionInputProps {@@ -39,8 +40,10 @@ function toPermissionQuestion(/*** Self-contained input-area renderer for an ACP `permission_request` on a sandbox conversation.- * Reuses the same `QuestionField` surface as sandbox questions while preserving the ACP option ids- * sent back to the runtime. `allow_always` stays hidden unless filtering would leave no choices.+ * 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.** Submitting POSTs through `runStreamLogic.respondToPermission`; the logic's* `respondingToPermission` drives the loading/double-submit guard and re-enables the controls when the@@ -48,12 +51,37 @@ function toPermissionQuestion(*/export function PermissionInput({ streamKey, request }: PermissionInputProps): JSX.Element {const boundLogic = runStreamLogic({ streamKey })- const { respondToPermission } = useActions(boundLogic)- const { respondingToPermission, currentMode } = useValues(boundLogic)+ const { 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,+ // fall through to the generic card so the request stays actionable.+ const planOptions = isPlanPermissionRequest(request) ? mapPermissionOptions(request.options, true) : []+ const planApproveOptions = planOptions.filter(+ (option) => option.decision === 'approved' && isPlanApprovalModeOptionId(option.optionId)+ )+ if (planApproveOptions.length > 0) {+ return (+ <div className="p-3">+ <PlanApprovalSelector+ approveOptions={planApproveOptions}+ rejectOption={planOptions.find((option) => option.decision === 'declined')}+ responding={respondingToPermission}+ onApprove={(optionId) => respondToPermission({ requestId: request.requestId, optionId })}+ onReject={(optionId, feedback) =>+ respondToPermission({ requestId: request.requestId, optionId, customInput: feedback })+ }+ onCancel={() => cancelRun()}+ />+ </div>+ )+ }// A request whose every option was filtered out (e.g. only `allow_always` without a rememberable- // preview) must still be answerable — fall back to showing everything.- const defaultOptions = mapPermissionOptions(request.options)+ // preview) must still be answerable — fall back to showing everything. A plan that fell through+ // (unrecognized mode ids) keeps its unfiltered options: its approve choices are `allow_always`-kind+ // 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.@@ -63,19 +91,13 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): Jconst hasOneClickDecline = buttonOptions.some((option) => option.decision === 'declined')const allowFeedback = !!feedbackOption && !hasOneClickDecline- // Plan approvals are raised while the agent is in plan mode — the mode is the grounded signal;- // `toolCall.kind === 'plan'` covers adapters that tag the request directly.- const isPlan = currentMode === 'plan' || request.rawToolCall.kind === 'plan'- const prompt = isPlan ? 'Approve this plan?' : 'Approval required'+ const prompt = 'Approval required'const display = getPermissionDisplay(request)const payloadLanguage = display.payload?.trim().match(/^[{[]/) ? Language.JSON : Language.Text-- const respond = (optionId: string): void => {- if (respondingToPermission) {- return- }- respondToPermission({ requestId: request.requestId, optionId })- }+ // 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.titleconst handleAnswer = (value: string | string[] | null): void => {if (respondingToPermission || value === null || Array.isArray(value)) {@@ -83,7 +105,7 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): J}const selectedOption = buttonOptions.find((option) => option.label === value)if (selectedOption) {- respond(selectedOption.optionId)+ respondToPermission({ requestId: request.requestId, optionId: selectedOption.optionId })return}if (allowFeedback && feedbackOption) {@@ -97,22 +119,20 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): Jreturn (<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">- {isPlan ? 'Plan approval' : 'Approval'}+ Approval</LemonTag></div><div className="font-medium text-sm">{prompt}</div>{display.title && <div className="text-xs text-secondary">{display.title}</div>}- {(request.title || request.description) && (- <div className="max-h-60 overflow-y-auto text-sm">- <MarkdownMessage- content={request.description ?? request.title ?? ''}- id={`permission-${request.requestId}`}- />- </div>- )}{display.payload && (<div className="max-h-60 overflow-y-auto"><CodeSnippet language={payloadLanguage} className="text-xs" compact>diff --git a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx b/products/posthog_ai/frontend/components/PlanApprovalActions.tsxnew file mode 100644index 000000000000..2696c72d2e54--- /dev/null+++ b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx@@ -0,0 +1,438 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'++import { Spinner } from '@posthog/quill-primitives'++import { cn } from 'lib/utils/css-classes'++import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++import type { ApprovalCardOption } from '../policy/permissionUtils'+import type { PermissionMode } from '../utils/composerModes'+import { ComposerModePicker } from './composer/ComposerModePicker'++const PLAN_APPROVAL_MODES: PermissionMode[] = [+ InitialPermissionModeEnumApi.BypassPermissions,+ InitialPermissionModeEnumApi.AcceptEdits,+]++export function isPlanApprovalModeOptionId(optionId: string): optionId is PermissionMode {+ return PLAN_APPROVAL_MODES.includes(optionId as PermissionMode)+}++// The mode last used to approve a plan, remembered across runs — `/code`'s `lastPlanApprovalMode` setting.+const LAST_APPROVAL_MODE_KEY = 'posthog-ai.lastPlanApprovalMode'++function readLastApprovalMode(): string | null {+ try {+ return window.localStorage.getItem(LAST_APPROVAL_MODE_KEY)+ } catch {+ return null+ }+}++function writeLastApprovalMode(mode: string): void {+ try {+ window.localStorage.setItem(LAST_APPROVAL_MODE_KEY, mode)+ } catch {+ // Storage unavailable (private mode / quota) — the pre-selection just won't persist.+ }+}++const MAX_FEEDBACK_HEIGHT = 200++function autosize(el: HTMLTextAreaElement): void {+ el.style.height = 'auto'+ const next = Math.min(el.scrollHeight, MAX_FEEDBACK_HEIGHT)+ el.style.height = `${next}px`+ // Only enable scrolling when content actually exceeds the cap — "auto" surfaces a track on macOS+ // when "Always show scrollbars" is set.+ el.style.overflowY = el.scrollHeight > MAX_FEEDBACK_HEIGHT ? 'auto' : 'hidden'+}++interface InlineEditableTextProps {+ value: string+ placeholder: string+ active: boolean+ disabled?: boolean+ onChange: (value: string) => void+ onNavigateUp: () => void+ onNavigateDown: () => void+ onEscape: () => void+ onSubmit: () => void+}++/** Port of `/code`'s `InlineEditableText` — the borderless autosizing textarea that IS the reject row. */+function InlineEditableText({+ value,+ placeholder,+ active,+ disabled,+ onChange,+ onNavigateUp,+ onNavigateDown,+ onEscape,+ onSubmit,+}: InlineEditableTextProps): JSX.Element {+ const textareaRef = useRef<HTMLTextAreaElement>(null)++ useEffect(() => {+ const el = textareaRef.current+ if (!el) {+ return+ }+ if (active) {+ el.focus()+ } else if (document.activeElement === el) {+ // Leaving the row must also drop focus, or the still-focused textarea would keep+ // swallowing the selector's global keyboard shortcuts.+ el.blur()+ }+ }, [active])++ // Track parent-driven value changes (e.g. clearing after submit) through the rendered DOM.+ useEffect(() => {+ const el = textareaRef.current+ if (el) {+ autosize(el)+ }+ }, [value])++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.key === 'Escape') {+ e.preventDefault()+ onEscape()+ } else if (e.key === 'ArrowUp') {+ const el = e.currentTarget+ if (el.selectionStart === 0 && el.selectionEnd === 0) {+ e.preventDefault()+ onNavigateUp()+ }+ } else if (e.key === 'ArrowDown') {+ const el = e.currentTarget+ if (el.selectionStart === el.value.length && el.selectionEnd === el.value.length) {+ e.preventDefault()+ onNavigateDown()+ }+ } else if (e.key === 'Tab') {+ e.preventDefault()+ onNavigateDown()+ } else if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault()+ onSubmit()+ }+ },+ [onNavigateUp, onNavigateDown, onEscape, onSubmit]+ )++ return (+ <textarea+ ref={textareaRef}+ value={value}+ placeholder={placeholder}+ disabled={disabled}+ onChange={(e) => {+ onChange(e.target.value)+ autosize(e.target)+ }}+ onKeyDown={handleKeyDown}+ onClick={(e) => e.stopPropagation()}+ rows={1}+ className="block w-full cursor-text resize-none overflow-y-hidden break-words border-0 bg-transparent p-0 font-medium text-[13px] leading-4 outline-none placeholder:text-muted focus:outline-none"+ style={{+ userSelect: active ? 'auto' : 'none',+ pointerEvents: active ? 'auto' : 'none',+ }}+ />+ )+}++export interface PlanApprovalSelectorProps {+ /** Supported wire approve options whose optionIds are permission modes. */+ approveOptions: ApprovalCardOption[]+ /** The wire's reject option (reject-with-feedback), driving the inline feedback row. */+ rejectOption?: ApprovalCardOption+ /** True while the permission response POST is in flight — blocks approve/reject re-submission. */+ responding: boolean+ onApprove: (optionId: string) => void+ onReject: (optionId: string, feedback: string) => void+ /** Esc — cancels the permission and interrupts the turn, like `/code`'s `cancelPermissionAndPrompt`. */+ onCancel: () => void+}++/**+ * Plan-approval selector — a port of `/code`'s `PlanApprovalSelector`: an "Approve and proceed" line+ * with the per-mode "Yes, and…" wire options collapsed into the shared mode dropdown beside it, and+ * the inline reject-with-feedback line below. Window-level keyboard nav (no focus required — works+ * while focus rests on the page body or inside the card, without hijacking keys from elements+ * elsewhere on the page): ↑↓ move between the two rows, Enter approves, Tab/Shift+Tab cycles the+ * permission mode, digits act on rows, Esc cancels. Approve+ * → `onApprove(<modeOptionId>)`; reject requires+ * feedback text → `onReject(<rejectOptionId>, feedback)` (empty Enter is a no-op). The approved mode+ * is remembered and pre-selected on the next plan.+ */+export function PlanApprovalSelector({+ approveOptions,+ rejectOption,+ responding,+ onApprove,+ onReject,+ onCancel,+}: PlanApprovalSelectorProps): JSX.Element {+ const modes = useMemo(() => {+ const offeredModeIds = new Set(approveOptions.map((option) => option.optionId))+ return PLAN_APPROVAL_MODES.filter((mode) => offeredModeIds.has(mode))+ }, [approveOptions])++ // Prefer the remembered offered mode, then Auto, then Accept edits.+ 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) ??+ modes[0]+ )+ }, [modes])++ const [selectedMode, setSelectedMode] = useState<PermissionMode | undefined>(initialMode)+ const [selectedIndex, setSelectedIndex] = useState(0)+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)+ const [feedback, setFeedback] = useState('')+ const containerRef = useRef<HTMLDivElement>(null)++ const rejectIndex = rejectOption ? 1 : -1+ const rowCount = rejectOption ? 2 : 1+ // The reject row is the inline feedback textarea, so "on the reject row" and "editing feedback"+ // are the same state — derive it, don't duplicate it.+ const rejectSelected = selectedIndex === rejectIndex++ // The approve row needs no focus management — the shortcuts are window-level; the reject row's+ // textarea focuses itself via its `active` prop.+ const selectRow = (index: number): void => {+ setHoveredIndex(null)+ setSelectedIndex(index)+ }++ const approve = (): void => {+ if (!selectedMode || responding) {+ return+ }+ // Remember this choice so the next plan approval pre-selects it.+ writeLastApprovalMode(selectedMode)+ onApprove(selectedMode)+ }++ const submitReject = (): void => {+ const text = feedback.trim()+ // Reject requires feedback text; empty Enter is a no-op (use Esc to cancel instead).+ if (!rejectOption || !text || responding) {+ return+ }+ onReject(rejectOption.optionId, text)+ }++ const moveSelection = (delta: number): void => {+ selectRow((selectedIndex + delta + rowCount) % rowCount)+ }++ // Tab cycles the permission mode in place (`/code` parity) — no focus juggling with the dropdown.+ const cycleMode = (delta: number): void => {+ if (!selectedMode || modes.length < 2) {+ return+ }+ const idx = modes.indexOf(selectedMode)+ setSelectedMode(modes[(idx + delta + modes.length) % modes.length])+ }++ // Window-level shortcuts, so keyboard nav works without the selector being focused (the CLI-like+ // default is focus parked on the page body). Everything else keeps its keys: the reject textarea+ // owns the keyboard while its row is selected, form fields are left alone, and focus resting on+ // any element outside the card keeps native Tab/Enter behavior.+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent): void => {+ if (rejectSelected || e.defaultPrevented) {+ return+ }+ const target = e.target+ if (+ target instanceof HTMLElement &&+ (target.tagName === 'INPUT' ||+ target.tagName === 'TEXTAREA' ||+ target.tagName === 'SELECT' ||+ target.isContentEditable ||+ // While the mode dropdown is open its menu owns the keyboard — Enter there picks a+ // mode, it must not approve the plan.+ target.closest('[role="menu"]') !== null)+ ) {+ return+ }+ // A key pressed while focus sits on some other element (a nav link, a button in another+ // panel) keeps its native behavior — Tab must keep moving focus and Enter must keep+ // activating that element. The selector owns the keyboard only while focus rests on the+ // page body (the CLI-like default) or within its own subtree.+ if (target instanceof HTMLElement && target !== document.body && !containerRef.current?.contains(target)) {+ return+ }+ switch (e.key) {+ case 'ArrowUp':+ e.preventDefault()+ moveSelection(-1)+ break+ case 'ArrowDown':+ e.preventDefault()+ moveSelection(1)+ break+ case 'Tab':+ e.preventDefault()+ cycleMode(e.shiftKey ? -1 : 1)+ break+ case 'Enter':+ e.preventDefault()+ approve()+ break+ case 'Escape':+ e.preventDefault()+ e.stopPropagation()+ onCancel()+ break+ default:+ if (/^[1-9]$/.test(e.key) && !e.metaKey && !e.ctrlKey) {+ const idx = Number.parseInt(e.key, 10) - 1+ if (idx < rowCount) {+ e.preventDefault()+ if (idx === 0) {+ approve()+ } else {+ selectRow(idx)+ }+ }+ }+ }+ }++ window.addEventListener('keydown', handleKeyDown)+ return () => window.removeEventListener('keydown', handleKeyDown)+ })++ const rowClass = (index: number): string =>+ 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'+ )++ const caret = (index: number): JSX.Element => (+ <span+ className={cn(+ 'w-[1ch] shrink-0 text-[13px] leading-4',+ selectedIndex === index ? 'text-accent' : 'text-muted'+ )}+ >+ {selectedIndex === index ? '›' : ''}+ </span>+ )++ const number = (index: number): JSX.Element => (+ <span+ className={cn(+ 'min-w-4 shrink-0 whitespace-nowrap text-right text-[13px] leading-4',+ selectedIndex === index || hoveredIndex === index ? 'text-accent' : 'text-muted'+ )}+ >+ {index + 1}.+ </span>+ )++ const approveActive = selectedIndex === 0 || hoveredIndex === 0++ return (+ <div ref={containerRef} className="rounded border bg-surface-primary p-3">+ <div className="flex flex-col gap-2">+ <span className="font-medium text-[13px] text-accent">Implementation Plan</span>++ <div>+ <p className="mb-2 text-[13px]">Approve this plan to proceed?</p>++ <div className="flex flex-col gap-1 px-2">+ {/* Approve line — mode dropdown (shared ComposerModePicker) beside it. */}+ <div+ onClick={approve}+ onMouseEnter={() => setHoveredIndex(0)}+ onMouseLeave={() => setHoveredIndex(null)}+ className={rowClass(0)}+ >+ <div className="flex items-center gap-2 leading-4">+ {caret(0)}+ {number(0)}+ <div className="flex min-w-0 flex-1 items-center justify-between gap-2 leading-4">+ <span+ className={cn(+ 'whitespace-pre-wrap font-medium text-[13px] leading-4',+ approveActive ? 'text-accent' : 'text-primary'+ )}+ >+ Approve and proceed+ </span>+ {responding ? (+ <Spinner className="size-4" />+ ) : (+ selectedMode && (+ <div onClick={(e) => e.stopPropagation()}>+ <ComposerModePicker+ selectedMode={selectedMode}+ onModeChange={setSelectedMode}+ modes={modes}+ />+ </div>+ )+ )}+ </div>+ </div>+ </div>++ {/* Reject line — the inline feedback textarea. */}+ {rejectOption && (+ <div+ onClick={() => selectRow(1)}+ onMouseEnter={() => setHoveredIndex(1)}+ onMouseLeave={() => setHoveredIndex(null)}+ className={rowClass(1)}+ >+ <div className="flex items-center gap-2 leading-4">+ {caret(1)}+ {number(1)}+ <div className="min-w-0 flex-1 leading-4">+ <InlineEditableText+ value={feedback}+ placeholder="Type here to tell the agent what to do differently"+ active={rejectSelected}+ disabled={responding}+ onChange={setFeedback}+ onNavigateUp={() => selectRow(0)}+ onNavigateDown={() => selectRow(0)}+ onEscape={() => {+ setFeedback('')+ selectRow(0)+ }}+ onSubmit={submitReject}+ />+ </div>+ </div>+ </div>+ )}+ </div>++ <p className="mt-2 mb-0 text-[13px] text-muted">+ Enter to select · Tab to change mode · ↑↓ to navigate · Esc to cancel+ </p>+ </div>+ </div>+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/PlanCard.tsx b/products/posthog_ai/frontend/components/PlanCard.tsxnew file mode 100644index 000000000000..fd2475fcc52f--- /dev/null+++ b/products/posthog_ai/frontend/components/PlanCard.tsx@@ -0,0 +1,137 @@+import { useEffect, useRef, useState } from 'react'++import { IconCopy, IconExpand45, IconListCheck, IconX } from '@posthog/icons'+import { LemonButton, LemonModal } from '@posthog/lemon-ui'++import { copyToClipboard } from 'lib/utils/copyToClipboard'++import { MarkdownMessage } from '../messages/MarkdownMessage'++export interface PlanPayload {+ plan?: string+ planFilePath?: string+}++/**+ * Pull the plan markdown + plan file path out of an `ExitPlanMode` tool input. The agent-server sends+ * `rawInput: { plan, planFilePath, toolName }` — `plan` matching `/code`'s `toolCall.rawInput.plan`.+ */+export function getPlanPayload(input: Record<string, unknown> | undefined): PlanPayload {+ const plan = input?.plan+ const planFilePath = input?.planFilePath+ return {+ plan: typeof plan === 'string' && plan.trim() ? plan : undefined,+ planFilePath: typeof planFilePath === 'string' && planFilePath.trim() ? planFilePath : undefined,+ }+}++// Scroll offsets survive the card unmounting (collapse/expand, thread virtualization) — `/code` parity.+const planScrollPosition = new Map<string, number>()++export interface PlanCardProps {+ plan: string+ /** Stable id for the memoized markdown blocks and the preserved scroll offset. */+ id: string+}++/**+ * The agent's plan (the `ExitPlanMode` payload) as it appears in the thread — a port of `/code`'s+ * `PlanContent`: an accent-tinted document card capped at half the viewport with a "Final plan"+ * header bar (copy + fullscreen controls), and an expand-to-fullscreen view (a `LemonModal`) whose+ * header and content share the thread's centered max-width column. Esc exits fullscreen via the+ * modal's own close handling.+ */+export function PlanCard({ plan, id }: PlanCardProps): JSX.Element {+ const scrollRef = useRef<HTMLDivElement>(null)+ const [isFullscreen, setIsFullscreen] = useState(false)++ // Restore + track the scroll offset of whichever container is active (inline card or fullscreen body).+ useEffect(() => {+ const el = scrollRef.current+ if (!el) {+ return+ }++ const position = planScrollPosition.get(id)+ if (position !== undefined) {+ el.scrollTop = position+ }++ const handleScroll = (): void => {+ planScrollPosition.set(id, el.scrollTop)+ }+ el.addEventListener('scroll', handleScroll, { passive: true })+ return () => el.removeEventListener('scroll', handleScroll)+ }, [id, isFullscreen])++ const copyButton = (+ <LemonButton+ size="xsmall"+ icon={<IconCopy />}+ tooltip="Copy plan to clipboard"+ onClick={() => void copyToClipboard(plan, 'plan')}+ />+ )++ if (isFullscreen) {+ return (+ <LemonModal+ isOpen+ onClose={() => setIsFullscreen(false)}+ fullScreen+ simple+ hideCloseButton+ className="overflow-hidden"+ >+ <div className="flex h-full min-h-0 flex-col">+ <div className="border-b px-4 py-2">+ <div className="mx-auto flex w-full max-w-180 items-center justify-between">+ <div className="flex items-center gap-2 text-accent">+ <IconListCheck className="size-4" />+ <span className="text-sm">Plan</span>+ </div>+ <div className="flex items-center gap-1">+ {copyButton}+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ tooltip="Exit fullscreen (Escape)"+ onClick={() => setIsFullscreen(false)}+ />+ </div>+ </div>+ </div>+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto p-6">+ <div className="mx-auto w-full max-w-180">+ <MarkdownMessage content={plan} id={id} />+ </div>+ </div>+ </div>+ </LemonModal>+ )+ }++ // Mobile-first height cap: small screens get most of the viewport, `sm+` keeps /code's half-viewport cap.+ return (+ <div className="flex max-h-[75vh] max-w-[750px] flex-col overflow-hidden rounded-lg border-2 border-accent bg-accent-highlight-secondary sm:max-h-[50vh]">+ <div className="flex items-center justify-between gap-2 border-b border-accent px-3 py-1.5">+ <div className="flex min-w-0 items-center gap-2 text-accent">+ <IconListCheck className="size-4 shrink-0" />+ <span className="text-sm font-medium">Final plan</span>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {copyButton}+ <LemonButton+ size="xsmall"+ icon={<IconExpand45 />}+ tooltip="Expand to fullscreen"+ onClick={() => setIsFullscreen(true)}+ />+ </div>+ </div>+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto p-4">+ <MarkdownMessage content={plan} id={id} />+ </div>+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsxindex ab3d99d69606..5ca74e65f218 100644--- a/products/posthog_ai/frontend/components/composer/Composer.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx@@ -2,6 +2,7 @@ import {createContext,forwardRef,type HTMLAttributes,+ type KeyboardEventHandler,type ReactNode,type RefObject,useCallback,@@ -289,18 +290,26 @@ export interface ComposerTextareaProps {autoFocus?: booleanminRows?: numbermaxRows?: number+ /** `'enter'` submits on Enter (PostHog AI), `'cmd-enter'` on Cmd/Ctrl+Enter (tasks composer). */+ submitShortcut?: 'enter' | 'cmd-enter'+ /** Extra key handling (e.g. the mode picker's `shift+tab` cycle); runs after the submit shortcut. */+ onKeyDown?: KeyboardEventHandler<HTMLTextAreaElement>'data-attr'?: string}-/** The textarea itself, wired to the context value/submit. Submits on Enter, Shift+Enter for a newline. */+/** The textarea itself, wired to the context value/submit. */function ComposerTextarea({className,autoFocus,minRows = 1,maxRows = 10,+ submitShortcut = 'enter',...rest}: ComposerTextareaProps): JSX.Element {const { value, onChange, submit, textAreaRef, disabled, id } = useComposerContext()+ // onPressEnter / onPressCmdEnter are mutually exclusive in LemonTextArea's type — pick one.+ const submitProps =+ submitShortcut === 'cmd-enter' ? { onPressCmdEnter: () => submit() } : { onPressEnter: () => submit() }return (<LemonTextAreaid={id}@@ -314,7 +323,7 @@ function ComposerTextarea({autoFocus={autoFocus}className={cn('!border-none !bg-transparent min-h-16 py-2 pl-2 pr-12 resize-none', className)}hideFocus- onPressEnter={() => submit()}+ {...submitProps}{...rest}/>)diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsxnew file mode 100644index 000000000000..3cb5c019af6c--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx@@ -0,0 +1,50 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++import { ComposerModePicker } from './ComposerModePicker'++describe('ComposerModePicker', () => {+ afterEach(() => {+ cleanup()+ })++ 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}+ />+ )++ 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.'+ )+ ).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Accepts file edits automatically. Bash commands and PostHog MCP tools that update or delete data still require approval.'+ )+ ).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Recommended for complex work such as research or implementation. Create a plan now, then execute it later.'+ )+ ).toBeInTheDocument()+ expect(screen.queryByText('Default')).not.toBeInTheDocument()+ expect(screen.queryByText('Bypass permissions')).not.toBeInTheDocument()++ const acceptEditsOption = screen.getByText('Accept edits').closest('[role="option"]')+ expect(acceptEditsOption).not.toBeNull()+ fireEvent.pointerDown(acceptEditsOption!, { pointerType: 'mouse' })+ fireEvent.click(acceptEditsOption!)++ expect(onModeChange).toHaveBeenCalledWith(InitialPermissionModeEnumApi.AcceptEdits)+ })+})diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsxnew file mode 100644index 000000000000..e4ed522539da--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx@@ -0,0 +1,80 @@+import { IconPause, IconShield, IconUnlock } from '@posthog/icons'+import {+ ItemContent,+ ItemDescription,+ ItemTitle,+ Select,+ SelectContent,+ SelectGroup,+ SelectGroupLabel,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@posthog/quill-primitives'++import { getModeOption, MODE_OPTIONS, type PermissionMode } from 'products/posthog_ai/frontend/utils/composerModes'+import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++interface ModeStyle {+ icon: JSX.Element+ 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.BypassPermissions]: { icon: <IconUnlock />, className: 'text-danger' },+ [InitialPermissionModeEnumApi.AcceptEdits]: { icon: <IconShield />, className: 'text-success' },+ [InitialPermissionModeEnumApi.Plan]: { icon: <IconPause />, className: 'text-warning' },+}++export interface ComposerModePickerProps {+ selectedMode: PermissionMode+ onModeChange: (mode: PermissionMode) => void+ /** Restrict the picker to a subset of modes, such as the modes a plan approval offers. */+ modes?: PermissionMode[]+}++/**+ * Controlled, logic-free permission-mode picker for a composer footer, styled to match the adjacent+ * model/effort pickers. The caller owns the selection and its side effects. Also reused by the plan-approval+ * card, where `modes` narrows the menu to the wire-offered modes.+ */+export function ComposerModePicker({ selectedMode, onModeChange, modes }: ComposerModePickerProps): JSX.Element {+ const options = modes ? MODE_OPTIONS.filter((option) => modes.includes(option.value)) : MODE_OPTIONS+ const selectedOption = getModeOption(selectedMode)++ return (+ <Select value={selectedMode} onValueChange={(mode: PermissionMode | null) => mode && onModeChange(mode)}>+ <SelectTrigger size="sm" aria-label="Mode">+ <SelectValue>+ {selectedOption ? (+ <>+ <span className={MODE_STYLES[selectedOption.value].className}>+ {MODE_STYLES[selectedOption.value].icon}+ </span>+ {selectedOption.label}+ </>+ ) : (+ 'Mode'+ )}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start" alignItemWithTrigger={false} className="max-w-96">+ <SelectGroup>+ <SelectGroupLabel>Mode</SelectGroupLabel>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <span className={MODE_STYLES[option.value].className}>+ {MODE_STYLES[option.value].icon}+ </span>+ <ItemContent variant="menuItem">+ <ItemTitle>{option.label}</ItemTitle>+ <ItemDescription>{option.description}</ItemDescription>+ </ItemContent>+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ )+}diff --git a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsxnew file mode 100644index 000000000000..4054d0ddd117--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx@@ -0,0 +1,49 @@+import { fireEvent, render } from '@testing-library/react'++import { ComposerModeShortcut } from './ComposerModeShortcut'++describe('ComposerModeShortcut', () => {+ it('cycles on Shift+Tab regardless of where focus sits', () => {+ const onCycle = jest.fn()+ render(<ComposerModeShortcut onCycle={onCycle} />)++ fireEvent.keyDown(document.body, { key: 'Tab', shiftKey: true })++ expect(onCycle).toHaveBeenCalledTimes(1)+ })++ it('ignores plain Tab, so normal focus navigation is untouched', () => {+ const onCycle = jest.fn()+ render(<ComposerModeShortcut onCycle={onCycle} />)++ fireEvent.keyDown(document.body, { key: 'Tab', shiftKey: false })++ expect(onCycle).not.toHaveBeenCalled()+ })++ it('yields to a handler that already consumed the key', () => {+ const onCycle = jest.fn()+ render(<ComposerModeShortcut onCycle={onCycle} />)+ window.addEventListener('keydown', (e) => e.preventDefault(), { capture: true, once: true })++ fireEvent.keyDown(document.body, { key: 'Tab', shiftKey: true })++ expect(onCycle).not.toHaveBeenCalled()+ })++ it('yields to open menus, which own Tab for their focus order', () => {+ const onCycle = jest.fn()+ const { getByText } = render(+ <>+ <ComposerModeShortcut onCycle={onCycle} />+ <div role="menu">+ <button>Item</button>+ </div>+ </>+ )++ fireEvent.keyDown(getByText('Item'), { key: 'Tab', shiftKey: true })++ expect(onCycle).not.toHaveBeenCalled()+ })+})diff --git a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsxnew file mode 100644index 000000000000..1dfea11e430e--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx@@ -0,0 +1,33 @@+import { useEffect } from 'react'++export interface ComposerModeShortcutProps {+ /** Fired on Shift+Tab — cycle to the next permission mode. */+ onCycle: () => void+}++/**+ * Renderless window-level Shift+Tab shortcut for cycling the composer's permission mode, matching `/code`+ * where the shortcut is global. Mount it inside the composer subtree so it detaches with the composer —+ * e.g. while a pending plan approval replaces the composer slot, whose selector owns Tab itself. Yields to+ * anything that already handled the key (`defaultPrevented`) and to open menus/dialogs, which own Tab for+ * their internal focus order.+ */+export function ComposerModeShortcut({ onCycle }: ComposerModeShortcutProps): null {+ // No dep array on purpose: re-attaching keeps the listener's `onCycle` closure current (callers pass+ // inline arrows over the selected mode) — same pattern as the plan-approval selector's shortcuts.+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent): void => {+ if (e.key !== 'Tab' || !e.shiftKey || e.defaultPrevented) {+ return+ }+ if (e.target instanceof HTMLElement && e.target.closest('[role="menu"],[role="dialog"]')) {+ return+ }+ e.preventDefault()+ onCycle()+ }+ window.addEventListener('keydown', handleKeyDown)+ return () => window.removeEventListener('keydown', handleKeyDown)+ })+ return null+}diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsxindex 56be6dc567be..b549ed39f7f0 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx@@ -43,7 +43,7 @@ export function ComposerModelEffortPickers({const [effortOpen, setEffortOpen] = useState(false)return (- <div className="flex items-center gap-1 pl-2">+ <div className="flex items-center gap-1"><DropdownMenu open={modelOpen} onOpenChange={setModelOpen}><DropdownMenuTriggerrender={diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsxindex ab4103d99e03..d0e7848ff50b 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx@@ -7,6 +7,10 @@ import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypimport { BuiltinToolRenderer } from './builtinToolRenderers'import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'+jest.mock('../../messages/MarkdownMessage', () => ({+ MarkdownMessage: ({ content }: { content: string }) => <div data-attr="markdown">{content}</div>,+}))+function textBlock(text: string): unknown {return { type: 'content', content: { type: 'text', text } }}@@ -172,6 +176,63 @@ describe('builtin tool renderers', () => {expect(screen.getByText('funnel')).toBeInTheDocument()})+ it('renders a pending plan as the document card with the plan visible', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'ExitPlanMode',+ resolvedKey: 'ExitPlanMode',+ status: 'pending',+ rawInput: { plan: '# The plan' },+ })}+ />+ )++ // The plan markdown shows immediately under the card's header — no accordion to expand+ // while approval is pending.+ expect(screen.getByText('Final plan')).toBeInTheDocument()+ expect(screen.getByText('# The plan')).toBeInTheDocument()+ expect(screen.queryByText('Ready to code?')).not.toBeInTheDocument()+ })++ it('collapses an approved plan to the status row, revealing the plan on "show plan"', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'ExitPlanMode',+ resolvedKey: 'ExitPlanMode',+ status: 'completed',+ rawInput: { plan: '# The plan' },+ })}+ />+ )++ expect(screen.getByText('Plan approved — proceeding with implementation')).toBeInTheDocument()+ expect(screen.queryByText('# The plan')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('· show plan'))+ expect(screen.getByText('# The plan')).toBeInTheDocument()+ })++ it('marks a failed plan approval as rejected', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'ExitPlanMode',+ resolvedKey: 'ExitPlanMode',+ status: 'failed',+ rawInput: { plan: '# The plan' },+ })}+ />+ )++ expect(screen.getByText('(Plan rejected)')).toBeInTheDocument()+ expect(screen.queryByText('# The plan')).not.toBeInTheDocument()+ })+it('renders an unmapped MCP tool with a Call server – tool (MCP) header', () => {render(<GenericMcpToolRendererdiff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsxindex f735e2bf9ba7..2aad989a50a9 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx@@ -1,11 +1,21 @@-import { Suspense, memo } from 'react'+import { Suspense, memo, useState } from 'react'-import { IconDocument, IconGlobe, IconMagicWand, IconSearch, IconTerminal, IconWrench } from '@posthog/icons'+import {+ IconCheckCircle,+ IconChevronRight,+ IconDocument,+ IconGlobe,+ IconMagicWand,+ IconSearch,+ IconTerminal,+ IconWrench,+} from '@posthog/icons'// IconRobot is not exported from @posthog/icons — it lives only in the legacy lib icon set.import { IconRobot } from 'lib/lemon-ui/icons'import { lazyWithRetry } from 'lib/utils/retryImport'+import { getPlanPayload, PlanCard } from '../PlanCard'import { EditorSkeleton } from './EditorSkeleton'import { FilePath } from './FilePath'import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'@@ -110,6 +120,67 @@ const ReadToolRenderer = memo(function ReadToolRenderer(props: ToolRendererProps)})+/**+ * ExitPlanMode — `/code`'s `PlanApprovalView`: while the approval is pending the plan renders as the+ * tinted document card directly in the thread (the approval actions live in the composer slot); once+ * resolved it collapses to a status row ("Plan approved…" / "(Plan rejected)") with a show/hide toggle.+ */+const ExitPlanModeRenderer = memo(function ExitPlanModeRenderer(props: ToolRendererProps): JSX.Element | null {+ const { message, turnComplete, turnCancelled } = props+ const [isPlanExpanded, setIsPlanExpanded] = useState(false)+ const { plan: planFromInput } = getPlanPayload(message.rawInput)+ const plan = planFromInput ?? getContentText(message.content)++ const isComplete = message.status === 'completed'+ const isIncomplete = message.status === 'pending' || message.status === 'in_progress'+ // A denied plan surfaces as a failed tool call; a cancelled/finished turn leaves it incomplete forever.+ const wasRejected = message.status === 'failed' || (isIncomplete && !!(turnCancelled || turnComplete))+ const showResult = isComplete || wasRejected++ if (!plan && !showResult) {+ return null+ }++ if (!showResult) {+ return <div className="my-2">{plan && <PlanCard plan={plan} id={`plan-${message.id}`} />}</div>+ }++ const statusContent = isComplete ? (+ <>+ <IconCheckCircle className="size-4 shrink-0 text-success" />+ <span className="text-[13px] text-success">Plan approved — proceeding with implementation</span>+ </>+ ) : (+ <span className="text-[13px] text-muted">(Plan rejected)</span>+ )++ return (+ <div className="my-2">+ {plan ? (+ <button+ type="button"+ onClick={() => setIsPlanExpanded((expanded) => !expanded)}+ aria-expanded={isPlanExpanded}+ className="flex items-center gap-2 rounded px-1 text-left hover:bg-fill-button-tertiary-hover"+ >+ <IconChevronRight+ className={`size-3 shrink-0 text-muted transition-transform ${isPlanExpanded ? 'rotate-90' : ''}`}+ />+ {statusContent}+ <span className="text-[13px] text-muted">· {isPlanExpanded ? 'hide plan' : 'show plan'}</span>+ </button>+ ) : (+ <div className="flex items-center gap-2 px-1">{statusContent}</div>+ )}+ {plan && isPlanExpanded && (+ <div className="mt-2">+ <PlanCard plan={plan} id={`plan-${message.id}`} />+ </div>+ )}+ </div>+ )+})+/** Grep / Glob / LS — result count on line 2, matched lines in the body. */const SearchToolRenderer = memo(function SearchToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = props@@ -347,6 +418,8 @@ export const BuiltinToolRenderer = memo(function BuiltinToolRenderer(props: Toolreturn <SkillToolRenderer {...props} />case 'ToolSearch':return <ToolSearchRenderer {...props} />+ case 'ExitPlanMode':+ return <ExitPlanModeRenderer {...props} />default:return <GenericMcpToolRenderer {...props} />}diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 1e6c850144f1..6bdc50618b2c 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -26,6 +26,7 @@ jest.mock('./runStreamLogic', () => {respondToPermission: (payload: unknown) => ({ payload }),cancelRun: (run?: unknown) => ({ run }),markTurnComplete: true,+ setCurrentMode: (mode: string) => ({ mode }),setStubStatus: (status: string | null) => ({ status }),setStubThinking: (thinking: boolean) => ({ thinking }),}),@@ -44,6 +45,12 @@ jest.mock('./runStreamLogic', () => {],pendingPermissionRequest: [null, {}],respondingToPermission: [false, {}],+ currentMode: [+ null,+ {+ setCurrentMode: (_: string | null, { mode }: { mode: string }) => mode,+ },+ ],}),])return {@@ -143,20 +150,20 @@ describe('runInteractionLogic', () => {it('does not send any command when the model or effort is picked', async () => {setThinking(false)- logic.actions.setModel('claude-sonnet-4-6')+ logic.actions.setModel('claude-opus-4-8')logic.actions.setEffort('low')await expectLogic(logic).toFinishAllListeners()// Picking is client-side only now — nothing is synced until the message is sent.expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- expect(logic.values.selectedModel).toBe('claude-sonnet-4-6')+ expect(logic.values.selectedModel).toBe('claude-opus-4-8')expect(logic.values.selectedEffort).toBe('low')})it('syncs a changed model to the agent right before the message, and only when it changed', async () => {setThinking(false)- logic.actions.setModel('claude-sonnet-4-6')+ logic.actions.setModel('claude-opus-4-8')logic.actions.setComposerFormValues({ draft: 'ship it' })await expectLogic(logic, () => {@@ -165,7 +172,7 @@ describe('runInteractionLogic', () => {// The config sync lands before the message, never inside it.expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([- setConfigCommand('model', 'claude-sonnet-4-6'),+ setConfigCommand('model', 'claude-opus-4-8'),userMessageCommand('ship it'),])@@ -180,6 +187,81 @@ describe('runInteractionLogic', () => {expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('again')])})+ it('syncs a changed permission mode to the agent right before the message, and only when it changed', async () => {+ setThinking(false)+ logic.actions.setMode('plan')+ logic.actions.setComposerFormValues({ draft: 'ship it' })++ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ // The mode sync is a `set_config_option { configId: 'mode' }` command that lands before the message.+ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([+ setConfigCommand('mode', 'plan'),+ userMessageCommand('ship it'),+ ])++ // A follow-up with the same mode re-syncs nothing — just the message.+ ;(tasksRunsCommandCreate as jest.Mock).mockClear()+ logic.actions.setComposerFormValues({ draft: 'again' })++ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('again')])+ })++ it('adopts the agent-confirmed mode over a stale manual pick and stays in sync at send time', async () => {+ setThinking(false)+ logic.actions.setMode('plan')+ expect(logic.values.selectedMode).toBe('plan')++ // 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')++ logic.actions.setComposerFormValues({ draft: 'go on' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ // Already in sync with the agent — only the message goes out, no stale mode re-sync.+ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('go on')])+ })++ it('seeds the picker from the stored launch mode and ignores unrecognized wire modes', () => {+ // No live `current_mode_update` yet — the run's REST-stored launch mode drives the display.+ logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted, currentMode: 'plan' })+ expect(logic.values.selectedMode).toBe('plan')++ // An unrecognized wire mode (a future mode, another runtime's vocabulary) must not leak out as a+ // fake PermissionMode — it degrades to the stored launch mode.+ stream.actions.setCurrentMode('full-access')+ expect(logic.values.selectedMode).toBe('plan')++ stream.actions.setCurrentMode('acceptEdits')+ expect(logic.values.selectedMode).toBe('acceptEdits')+ })++ it('seeds a fresh run with the picked permission mode when the run is terminal', async () => {+ setStatus('completed')+ logic.actions.setMode('acceptEdits')+ logic.actions.setComposerFormValues({ draft: 'continue from here' })++ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect(tasksRunCreate).toHaveBeenCalledWith(+ '997',+ TASK_ID,+ expect.objectContaining({ initial_permission_mode: 'acceptEdits' })+ )+ })+it('stages the message in the queue while the agent is busy', async () => {setThinking(true)logic.actions.setComposerFormValues({ draft: 'follow up' })@@ -252,8 +334,9 @@ describe('runInteractionLogic', () => {expect(tasksRunsCommandCreate).not.toHaveBeenCalled()expect(tasksRunCreate).toHaveBeenCalledWith('997', TASK_ID, {runtime_adapter: 'claude',- model: 'claude-opus-4-8',+ model: 'claude-sonnet-5',reasoning_effort: 'high',+ initial_permission_mode: 'bypassPermissions',resume_from_run_id: RUN_ID,pending_user_message: 'continue from here',})diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex b6bf5429b103..53c548286612 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -11,6 +11,11 @@ import {DEFAULT_COMPOSER_MODEL,resolveEffortForModel,} from 'products/posthog_ai/frontend/utils/composerModels'+import {+ DEFAULT_COMPOSER_MODE,+ getModeOption,+ type PermissionMode,+} from 'products/posthog_ai/frontend/utils/composerModes'import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'import {ClaudeRuntimeAdapterEnumApi,@@ -35,10 +40,11 @@ export interface RunInteractionLogicProps {* `RunSurface` binds, never diverging from it. API calls still use the real `runId`.*/streamKey?: string- /** The run's stored model / reasoning effort, injected by the consumer. They seed the picker's display and- * the config a terminal-run send launches the next run with (override ?? this ?? default). */+ /** The run's stored model / reasoning effort / launch mode, injected by the consumer. They seed the picker's+ * display and the config a terminal-run send launches the next run with (override ?? this ?? default). */currentModel?: string | nullcurrentEffort?: string | null+ currentMode?: string | null/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can* re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */onRunStarted?: (runId: string) => void@@ -57,6 +63,9 @@ const QUEUED_MESSAGE_ID = 'queued'// option's id is `model`; the effort option's id is `effort` (its category is `thought_level`).const MODEL_CONFIG_ID = 'model'const EFFORT_CONFIG_ID = 'effort'+// The agent-server's permission-mode config option (`/code`'s "mode" preset). Sending+// `set_config_option { configId: 'mode' }` is how `/code` applies a live shift+tab mode change.+const MODE_CONFIG_ID = 'mode'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface runInteractionLogicValues {@@ -64,6 +73,7 @@ export interface runInteractionLogicValues {contextItems: AttachedContextItem[] // attachedContextLogicsentContextKeysByTask: Record<string, string[]> // attachedContextLogiccurrentProjectId: number | null // projectLogic+ currentMode: string | null // runStreamLogiccurrentRunStatus: RunStatus | null // runStreamLogicisThinking: boolean // runStreamLogicpendingPermissionRequest: PermissionRequestRecord | null // runStreamLogic@@ -97,13 +107,16 @@ export interface runInteractionLogicValues {isComposerFormValid: booleanisSubmitting: booleanisTerminal: boolean+ modeOverride: PermissionMode | nullmodelOverride: string | nullpendingContextItems: AttachedContextItem[]queuedMessages: QueuedMessage[]selectedEffort: ReasoningEffortEnumApi+ selectedMode: PermissionModeselectedModel: stringsending: booleansentEffort: string | null+ sentMode: PermissionMode | nullsentModel: string | nullshowComposerFormErrors: booleanstartingRun: boolean@@ -150,6 +163,9 @@ export interface runInteractionLogicActions {optionId: stringrequestId: string} // runStreamLogic+ setCurrentMode: (mode: string) => {+ mode: string+ } // runStreamLogicblockOnConsent: () => {value: true}@@ -205,6 +221,9 @@ export interface runInteractionLogicActions {setEffort: (effort: string) => {effort: string}+ setMode: (mode: PermissionMode) => {+ mode: PermissionMode+ }setModel: (model: string) => {model: string}@@ -214,6 +233,9 @@ export interface runInteractionLogicActions {setSentEffort: (effort: string) => {effort: string}+ setSentMode: (mode: PermissionMode) => {+ mode: PermissionMode+ }setSentModel: (model: string) => {model: string}@@ -262,6 +284,7 @@ export interface runInteractionLogicMeta {isTerminal: (currentRunStatus: RunStatus | null) => booleanselectedModel: (modelOverride: string | null, arg: any) => stringselectedEffort: (effortOverride: string | null, arg: any, selectedModel: string) => ReasoningEffortEnumApi+ selectedMode: (modeOverride: PermissionMode | null, currentMode: string | null, arg: any) => PermissionModeisBusy: (isThinking: boolean) => booleancanSend: (sending: boolean, isTerminal: boolean, currentProjectId: number | null) => booleanisSubmitting: (sending: boolean, startingRun: boolean) => boolean@@ -303,7 +326,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([projectLogic,['currentProjectId'],runStreamLogic({ streamKey: props.streamKey ?? props.runId }),- ['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],+ ['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking', 'currentMode'],attachedContextLogic,['contextItems', 'sentContextKeysByTask'],aiConsentLogic,@@ -311,7 +334,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([],actions: [runStreamLogic({ streamKey: props.streamKey ?? props.runId }),- ['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete'],+ ['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete', 'setCurrentMode'],attachedContextLogic,['markContextSent'],],@@ -342,10 +365,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// doesn't persist live changes back to the run state, so the override is the source of truth.setModel: (model: string) => ({ model }),setEffort: (effort: string) => ({ effort }),- // Internal: record the model / effort last synced to the agent session, so a send only fires a+ // Pick the permission mode for the run. Like model/effort, selection is held client-side and synced to+ // the running agent (via `set_config_option { configId: 'mode' }`) at send time, or seeds the next run.+ setMode: (mode: PermissionMode) => ({ mode }),+ // Internal: record the model / effort / mode last synced to the agent session, so a send only fires a// `set_config_option` when the pick actually differs from what the session is already running.setSentModel: (model: string) => ({ model }),setSentEffort: (effort: string) => ({ effort }),+ setSentMode: (mode: PermissionMode) => ({ mode }),}),reducers({@@ -403,6 +430,16 @@ export const runInteractionLogic = kea<runInteractionLogicType>([setEffort: (_, { effort }) => effort,},],+ modeOverride: [+ null as PermissionMode | null,+ {+ setMode: (_, { mode }) => mode,+ // Unlike model/effort, the mode genuinely changes server-side (e.g. a plan approval moves the+ // session out of Plan mode) — the agent's confirmed mode is authoritative, so a stale manual+ // pick must not keep shadowing the stream's `current_mode_update`.+ setCurrentMode: () => null,+ },+ ],// The model/effort last synced to the agent session via `set_config_option`. null means "not synced// yet this session" — the active config is then the run's stored value (or the default).sentModel: [@@ -417,6 +454,15 @@ export const runInteractionLogic = kea<runInteractionLogicType>([setSentEffort: (_, { effort }) => effort,},],+ sentMode: [+ null as PermissionMode | null,+ {+ setSentMode: (_, { mode }) => mode,+ // Cleared alongside `modeOverride` so the send-time sync check compares against the agent's+ // live mode, not a marker the agent has since moved past.+ setCurrentMode: () => null,+ },+ ],}),forms(({ actions, values }) => ({@@ -475,6 +521,16 @@ export const runInteractionLogic = kea<runInteractionLogicType>([(override: string | null, current, model: string): ReasoningEffortEnumApi =>resolveEffortForModel(override ?? current ?? DEFAULT_COMPOSER_EFFORT, model),],+ // The permission mode to display and launch with: the client-side override, else the session's live+ // mode (from the stream's `current_mode_update` frames), else the run's stored launch mode, else the+ // default. The wire values are narrowed via `getModeOption` — an unrecognized mode string (a future+ // mode, another runtime's vocabulary) degrades to the next fallback instead of leaking out as a+ // fake `PermissionMode`.+ selectedMode: [+ (s) => [s.modeOverride, s.currentMode, (_, p) => p.currentMode],+ (override: PermissionMode | null, current: string | null, initial): PermissionMode =>+ override ?? getModeOption(current)?.value ?? getModeOption(initial)?.value ?? DEFAULT_COMPOSER_MODE,+ ],// The agent is actively working a turn — a follow-up typed now should stage rather than send.isBusy: [(s) => [s.isThinking], (isThinking: boolean): boolean => isThinking],canSend: [@@ -574,6 +630,19 @@ export const runInteractionLogic = kea<runInteractionLogicType>([})actions.setSentEffort(values.selectedEffort)}+ const activeMode =+ values.sentMode ??+ getModeOption(values.currentMode)?.value ??+ getModeOption(props.currentMode)?.value ??+ DEFAULT_COMPOSER_MODE+ if (values.selectedMode !== activeMode) {+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {+ jsonrpc: '2.0',+ method: 'set_config_option',+ params: { configId: MODE_CONFIG_ID, value: values.selectedMode },+ })+ actions.setSentMode(values.selectedMode)+ }// Wrap the outgoing content with the on-screen context block (invisible to the user —// `runStreamLogic.unwrapUserMessageContent` strips it on replay, and the echo below is raw).const pendingContext = values.pendingContextItems@@ -631,6 +700,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,model: values.selectedModel,reasoning_effort: values.selectedEffort,+ initial_permission_mode: values.selectedMode,resume_from_run_id: props.runId,pending_user_message: wrapWithPosthogContext(content, pendingContext),}diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex a984d53c88f0..a23a3b349b1c 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -68,6 +68,25 @@ import { debugLogsLogic } from './debugLogsLogic'import { hasReplayListener, toolStreamEventsLogic } from './toolStreamEventsLogic'import type { ToolStreamSubscription } from './toolStreamEventsLogic'+interface LiveStreamRegistryHost {+ __posthogAiLiveStreamControllers?: Set<AbortController>+}++// Dev-only guard against orphaned SSE readers: an HMR swap re-evaluates this module in the same page,+// and the old build's logic gets discarded with a fresh kea `cache` — its 'event-source' disposable+// never runs teardown, so its reader keeps the connection open (pinning a granian dev worker) until+// the tab closes. A fresh evaluation finding controllers in the page-global registry therefore means+// an HMR swap just replaced their build — abort them (an aborted signal is the silent teardown path,+// so the old logic won't schedule a reconnect). On first load the registry is empty, and a full page+// load needs none of this: the browser aborts in-flight fetches itself. `import.meta.hot.dispose`+// would be the idiomatic hook, but `import.meta` is a parse error in Jest's CJS transform.+const liveStreamControllers = new Set<AbortController>()+if (process.env.NODE_ENV === 'development') {+ const registryHost = globalThis as LiveStreamRegistryHost+ registryHost.__posthogAiLiveStreamControllers?.forEach((controller) => controller.abort())+ registryHost.__posthogAiLiveStreamControllers = liveStreamControllers+}+export type RunSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'export type RunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'@@ -2495,17 +2514,21 @@ export const runStreamLogic = kea<runStreamLogicType>([}// Replace any prior connection. A hot reload can orphan the previous build's reader (its- // `cache`, and thus this disposable, is discarded before teardown runs), but the keyed- // log store makes duplicate ingestion idempotent — a lingering orphan can no longer- // double the thread, so the old `EventSource` registry is gone.+ // `cache`, and thus this disposable, is discarded before teardown runs) — the keyed+ // log store makes duplicate ingestion idempotent, and the module-level+ // `liveStreamControllers` HMR hook aborts the orphan's connection itself.cache.disposables.dispose('event-source')// pauseOnPageHidden: false — a live stream must survive tab hides; re-running setup on// show would reopen the stream and re-fold thread state.cache.disposables.add((): (() => void) => {const controller = new AbortController()+ liveStreamControllers.add(controller)void streamRun(controller.signal)- return () => controller.abort()+ return () => {+ liveStreamControllers.delete(controller)+ controller.abort()+ }},'event-source',{ pauseOnPageHidden: false }diff --git a/products/posthog_ai/frontend/policy/permissionUtils.ts b/products/posthog_ai/frontend/policy/permissionUtils.tsindex e07dcf931f7b..6e47991bd54e 100644--- a/products/posthog_ai/frontend/policy/permissionUtils.ts+++ b/products/posthog_ai/frontend/policy/permissionUtils.ts@@ -1,5 +1,20 @@+import type { PermissionRequestRecord } from '../types/streamTypes'import type { PermissionOption } from '../types/wireTypes'+/**+ * An `ExitPlanMode` approval — the plan-review card, not a generic tool approval. On the wire the+ * agent-server's plan request carries no top-level tool name and `kind: 'switch_mode'`; the reliable+ * signal is the `toolName` it embeds in the tool input (`rawInput: { plan, planFilePath, toolName }`).+ * The top-level name and `kind === 'plan'` cover adapters that tag the request directly.+ */+export function isPlanPermissionRequest(request: PermissionRequestRecord): boolean {+ return (+ request.toolName === 'ExitPlanMode' ||+ request.rawToolCall.input?.toolName === 'ExitPlanMode' ||+ request.rawToolCall.kind === 'plan'+ )+}+/*** The card-facing decision a user can take on a sandbox ACP `permission_request` option. The* sandbox runtime surfaces richer ACP option kinds that all map down onto approve / decline.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex c5fbe8e6c6ba..069cc2eefb25 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -12,9 +12,12 @@ import {Welcome,} from 'products/posthog_ai/frontend/api/primitives'import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'+import { cycleMode } from 'products/posthog_ai/frontend/utils/composerModes'import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'+import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'+import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { RepositorySelector } from './RepositorySelector'@@ -56,6 +59,9 @@ export function TaskComposer(): JSX.Element {value={newTaskData.repositoryConfig}onChange={(config) => setNewTaskData({ repositoryConfig: config })}/>+ <ComposerModeShortcut+ onCycle={() => setNewTaskData({ permissionMode: cycleMode(newTaskData.permissionMode) })}+ /><Composer.Rootvalue={draft.value}onChange={draft.onChange}@@ -69,9 +75,17 @@ export function TaskComposer(): JSX.Element {</Composer.Header><Composer.Field><Composer.Placeholder>Describe the task in detail…</Composer.Placeholder>- <Composer.Textarea autoFocus data-attr="task-composer-input" />+ <Composer.Textarea+ submitShortcut="cmd-enter"+ autoFocus+ data-attr="task-composer-input"+ /></Composer.Field>- <Composer.Footer>+ <Composer.Footer className="flex items-center gap-1 pl-2">+ <ComposerModePicker+ selectedMode={newTaskData.permissionMode}+ onModeChange={(permissionMode) => setNewTaskData({ permissionMode })}+ /><ComposerModelEffortPickersselectedModel={newTaskData.model}selectedEffort={newTaskData.reasoningEffort}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex 14391477f42a..454a4974c5c1 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -9,9 +9,12 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr// surface is its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'+import { cycleMode } from 'products/posthog_ai/frontend/utils/composerModes'import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'+import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'+import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'@@ -49,6 +52,7 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunCstreamKey,currentModel: selectedRun?.state?.model,currentEffort: selectedRun?.state?.reasoning_effort,+ currentMode: selectedRun?.state?.initial_permission_mode,onRunStarted: (newRunId) => {setSelectedRunId(newRunId, taskId)loadTaskRuns()@@ -108,6 +112,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):selectedModel,selectedEffort,consentBlocked,+ selectedMode,} = useValues(runInteractionLogic(logicProps))const {setComposerFormValues,@@ -118,60 +123,66 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):setModel,setEffort,clearConsentBlock,+ setMode,} = useActions(runInteractionLogic(logicProps))const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))return (- <Composer.Root- value={draft.value}- onChange={draft.onChange}- onSubmit={() => draft.submit(submitComposerForm)}- loading={isSubmitting}- isTurnActive={isBusy}- onStop={() => cancelRun()}- >- {queuedMessages.length > 0 && (- <Composer.Banner>- <QueuedMessageList- messages={queuedMessages}- onUpdate={updateQueuedMessage}- onRemove={removeQueuedMessage}- />- </Composer.Banner>- )}- <Composer.Frame>- <Composer.Header>- <AttachedContextBar />- </Composer.Header>- <Composer.Field>- <Composer.Placeholder>- {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}- </Composer.Placeholder>- <Composer.Textarea data-attr="sandbox-composer-input" />- </Composer.Field>- <Composer.Footer>- {/* Model/effort picker: selection lives in the bound runInteractionLogic and is- applied when the message is sent — synced to the running agent on a follow-up,- or used to seed the next run once terminal. */}- <ComposerModelEffortPickers- selectedModel={selectedModel}- selectedEffort={selectedEffort}- onModelChange={setModel}- onEffortChange={setEffort}- />- </Composer.Footer>- </Composer.Frame>- <AIConsentPopoverWrapper- placement="top-end"- showArrow- ignoreDismissal- hidden={!consentBlocked}- onApprove={() => submitComposerForm()}- onDismiss={() => clearConsentBlock()}+ <>+ {/* Inside the slot children: detaches while a pending approval replaces the composer. */}+ <ComposerModeShortcut onCycle={() => setMode(cycleMode(selectedMode))} />+ <Composer.Root+ value={draft.value}+ onChange={draft.onChange}+ onSubmit={() => draft.submit(submitComposerForm)}+ loading={isSubmitting}+ isTurnActive={isBusy}+ onStop={() => cancelRun()}>- <Composer.Submit data-attr="sandbox-composer-send" />- </AIConsentPopoverWrapper>- </Composer.Root>+ {queuedMessages.length > 0 && (+ <Composer.Banner>+ <QueuedMessageList+ messages={queuedMessages}+ onUpdate={updateQueuedMessage}+ onRemove={removeQueuedMessage}+ />+ </Composer.Banner>+ )}+ <Composer.Frame>+ <Composer.Header>+ <AttachedContextBar />+ </Composer.Header>+ <Composer.Field>+ <Composer.Placeholder>+ {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}+ </Composer.Placeholder>+ <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />+ </Composer.Field>+ <Composer.Footer className="flex items-center gap-1 pl-2">+ {/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is+ applied when the message is sent — synced to the running agent on a follow-up,+ or used to seed the next run once terminal. */}+ <ComposerModePicker selectedMode={selectedMode} onModeChange={setMode} />+ <ComposerModelEffortPickers+ selectedModel={selectedModel}+ selectedEffort={selectedEffort}+ onModelChange={setModel}+ onEffortChange={setEffort}+ />+ </Composer.Footer>+ </Composer.Frame>+ <AIConsentPopoverWrapper+ placement="top-end"+ showArrow+ ignoreDismissal+ hidden={!consentBlocked}+ onApprove={() => submitComposerForm()}+ onDismiss={() => clearConsentBlock()}+ >+ <Composer.Submit data-attr="sandbox-composer-send" />+ </AIConsentPopoverWrapper>+ </Composer.Root>+ </>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 66482e6d9fc6..c019c9027976 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -86,6 +86,7 @@ describe('taskTrackerSceneLogic', () => {// state). Dropping either regresses follow-up streaming / loses the first prompt.expect(runBody).toMatchObject({mode: 'interactive',+ initial_permission_mode: 'bypassPermissions',pending_user_message: 'do the thing',})expect(router.values.location.pathname).toContain('/tasks/new-task')diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 690b70b6394a..2d7c8568e38e 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -28,6 +28,7 @@ import type { RepositoryConfig, Task } from '../../types/taskTypes'import { OriginProduct, TaskUpsertProps } from '../../types/taskTypes'import type { TaskListParams } from '../../types/taskTypes'import { DEFAULT_COMPOSER_EFFORT, DEFAULT_COMPOSER_MODEL, resolveEffortForModel } from '../../utils/composerModels'+import { DEFAULT_COMPOSER_MODE, type PermissionMode } from '../../utils/composerModes'import { wrapWithPosthogContext } from '../../utils/posthogContextBlock'export type { ActiveCreation } from '../../logics/runnerPanelLogic'@@ -37,6 +38,7 @@ export interface TaskCreateForm {repositoryConfig: RepositoryConfigmodel: stringreasoningEffort: ReasoningEffortEnumApi+ permissionMode: PermissionMode}// The slice of the repo picker we remember across visits. Branch is deliberately excluded — on restore we@@ -61,6 +63,7 @@ const EMPTY_TASK_FORM: TaskCreateForm = {},model: DEFAULT_COMPOSER_MODEL,reasoningEffort: DEFAULT_COMPOSER_EFFORT,+ permissionMode: DEFAULT_COMPOSER_MODE,}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -445,7 +448,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([return}- const { description, repositoryConfig, model, reasoningEffort } = values.newTaskData+ const { description, repositoryConfig, model, reasoningEffort, permissionMode } = values.newTaskDataif (!description.trim()) {lemonToast.error('Description is required')@@ -488,6 +491,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,model,reasoning_effort: resolveEffortForModel(reasoningEffort, model),+ initial_permission_mode: permissionMode,// Interactive keeps the sandbox agent-server's event stream open across turns, so// follow-up messages stream their reply over the same SSE (background runs seal the// stream after the first turn). Interactive runs boot with the agent-server pullingdiff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.tsindex ca39fa2f14c3..fb3e7ec5f8ce 100644--- a/products/posthog_ai/frontend/utils/composerModels.ts+++ b/products/posthog_ai/frontend/utils/composerModels.ts@@ -13,11 +13,11 @@ export interface ComposerEffortOption {// Claude-only lineup — the task tracker always launches the `claude` runtime adapter, so Codex/GPT models are// intentionally absent. Add new Claude models here as they ship.export const COMPOSER_MODELS: ComposerModelOption[] = [+ { value: 'claude-sonnet-5', label: 'Claude Sonnet 5' },{ value: 'claude-opus-4-8', label: 'Claude Opus 4.8' },- { value: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },]-export const DEFAULT_COMPOSER_MODEL = 'claude-opus-4-8'+export const DEFAULT_COMPOSER_MODEL = 'claude-sonnet-5'export const DEFAULT_COMPOSER_EFFORT: ReasoningEffortEnumApi = ReasoningEffortEnumApi.Highconst EFFORT_LABELS: Record<ReasoningEffortEnumApi, string> = {@@ -38,7 +38,7 @@ const EFFORTS_BY_MODEL: Record<string, ReasoningEffortEnumApi[]> = {ReasoningEffortEnumApi.Xhigh,ReasoningEffortEnumApi.Max,],- 'claude-sonnet-4-6': [ReasoningEffortEnumApi.Low, ReasoningEffortEnumApi.Medium, ReasoningEffortEnumApi.High],+ 'claude-sonnet-5': [ReasoningEffortEnumApi.Low, ReasoningEffortEnumApi.Medium, ReasoningEffortEnumApi.High],}const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = [diff --git a/products/posthog_ai/frontend/utils/composerModes.test.ts b/products/posthog_ai/frontend/utils/composerModes.test.tsnew file mode 100644index 000000000000..f4a585c50f4c--- /dev/null+++ b/products/posthog_ai/frontend/utils/composerModes.test.ts@@ -0,0 +1,19 @@+import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++import { cycleMode, DEFAULT_COMPOSER_MODE } 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],+ ])('cycleMode(%s) → %s', (current, next) => {+ expect(cycleMode(current)).toBe(next)+ })++ it.each([[null], [undefined], ['not-a-mode']])('cycleMode(%s) resets to the default', (current) => {+ expect(cycleMode(current)).toBe(DEFAULT_COMPOSER_MODE)+ })+})diff --git a/products/posthog_ai/frontend/utils/composerModes.ts b/products/posthog_ai/frontend/utils/composerModes.tsnew file mode 100644index 000000000000..aa9d9c539f8a--- /dev/null+++ b/products/posthog_ai/frontend/utils/composerModes.ts@@ -0,0 +1,56 @@+import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++/** The permission modes exposed by the PostHog AI composer. */+export type PermissionMode =+ | typeof InitialPermissionModeEnumApi.BypassPermissions+ | typeof InitialPermissionModeEnumApi.AcceptEdits+ | typeof InitialPermissionModeEnumApi.Plan++export interface ComposerModeOption {+ value: PermissionMode+ label: string+ description: string+}++export const DEFAULT_COMPOSER_MODE: PermissionMode = InitialPermissionModeEnumApi.BypassPermissions++// Ordered for the Shift+Tab cycle and the picker.+export const MODE_OPTIONS: ComposerModeOption[] = [+ {+ value: InitialPermissionModeEnumApi.BypassPermissions,+ label: 'Auto',+ description:+ 'Bypasses all permissions. Safe in the sandbox, but the agent can modify or delete data without asking.',+ },+ {+ value: InitialPermissionModeEnumApi.AcceptEdits,+ label: 'Accept edits',+ description:+ 'Accepts file edits automatically. Bash commands and PostHog MCP tools that update or delete data still require approval.',+ },+ {+ value: InitialPermissionModeEnumApi.Plan,+ label: 'Plan',+ description:+ 'Recommended for complex work such as research or implementation. Create a plan now, then execute it later.',+ },+]++export function getModeOption(mode: string | null | undefined): ComposerModeOption | undefined {+ return MODE_OPTIONS.find((option) => option.value === mode)+}++export function getModeLabel(mode: string | null | undefined): string {+ return getModeOption(mode)?.label ?? 'Mode'+}++// Advance to the next mode, wrapping around. Port of `/code`'s `cycleModeOption`. An unknown `current`+// (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)+ if (index === -1) {+ return DEFAULT_COMPOSER_MODE+ }+ return order[(index + 1) % order.length]+}