: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
refactor(posthog-ai): simplify permission input (#98006)
Paul D'Ambra8dd2994f0a86
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsxindex c631d0bc0ab2..61c419099aa5 100644--- a/products/posthog_ai/frontend/components/PermissionInput.tsx+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx@@ -19,7 +19,7 @@ import { isPlanApprovalModeOptionId, InlineEditableText, PlanApprovalSelector }import { DiffStats } from './tool/DiffStats'import { FilePath } from './tool/FilePath'import { LazyDiffEditor } from './tool/LazyDiffEditor'-import { findAllDiffContent, getDiffStats } from './tool/toolDiffContent'+import { findAllDiffContent, getDiffStats, type ToolCallDiffContent } from './tool/toolDiffContent'import { lookupToolRenderer } from './tool/toolRegistry'interface PermissionInputProps {@@ -55,43 +55,38 @@ interface PermissionEvidenceProps {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)+interface DiffPermissionEvidenceProps {+ diffs: ToolCallDiffContent[]+ label?: string+}- 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>- <LazyDiffEditor diff={diff} path={diff.path} sideBySide />- </div>- )- })}- </div>- )- }+function DiffPermissionEvidence({ diffs, label }: DiffPermissionEvidenceProps): JSX.Element {+ return (+ <div className="flex flex-col gap-2 min-w-0">+ {diffs.map((diff, index) => (+ <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 {...getDiffStats(diff.oldText, diff.newText)} />+ </div>+ <LazyDiffEditor diff={diff} path={diff.path} sideBySide />+ </div>+ ))}+ </div>+ )+}- if (!payload) {- return label ? <div className="text-xs text-secondary">{label}</div> : null- }+interface PayloadPermissionEvidenceProps {+ label?: string+ payload: string+}+function PayloadPermissionEvidence({ label, payload }: PayloadPermissionEvidenceProps): JSX.Element {+ const [showAll, setShowAll] = useState(false)const language = payload.trim().match(/^[{[]/) ? Language.JSON : Language.Textconst lines = payload.split('\n')const overflowing = lines.length > PAYLOAD_COLLAPSED_LINES@@ -114,6 +109,26 @@ function PermissionEvidence({ request, label, payload }: PermissionEvidenceProps)}+/**+ * 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 diffs = findAllDiffContent(request.rawToolCall.contentBlocks)++ if (diffs.length > 0) {+ return <DiffPermissionEvidence diffs={diffs} label={label} />+ }++ if (!payload) {+ return label ? <div className="text-xs text-secondary">{label}</div> : null+ }++ return <PayloadPermissionEvidence label={label} payload={payload} />+}+/** 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@@ -147,6 +162,156 @@ interface PermissionOptionRowsProps {onRespond: (optionId: string, customInput?: string) => void}+function isEditableTarget(target: EventTarget | null): boolean {+ return (+ target instanceof HTMLElement &&+ (target.tagName === 'INPUT' ||+ target.tagName === 'TEXTAREA' ||+ target.tagName === 'SELECT' ||+ target.isContentEditable ||+ target.closest('[role="menu"]') !== null)+ )+}++function ignoresPermissionShortcut(+ event: KeyboardEvent,+ responding: boolean,+ container: HTMLDivElement | null+): boolean {+ const target = event.target+ return (+ event.defaultPrevented ||+ responding ||+ isEditableTarget(target) ||+ (target instanceof HTMLElement && target !== document.body && !container?.contains(target))+ )+}++interface PermissionShortcut {+ action: 'activate' | 'select'+ index: number+}++function numericShortcut(event: KeyboardEvent, optionsLength: number): PermissionShortcut | null {+ if (!/^[1-9]$/.test(event.key) || event.metaKey || event.ctrlKey) {+ return null+ }++ const index = Number.parseInt(event.key, 10) - 1+ return index < optionsLength ? { action: 'activate', index } : null+}++function permissionShortcut(+ event: KeyboardEvent,+ selectedIndex: number,+ optionsLength: number+): PermissionShortcut | null {+ switch (event.key) {+ case 'ArrowUp':+ return { action: 'select', index: (selectedIndex - 1 + optionsLength) % optionsLength }+ case 'ArrowDown':+ return { action: 'select', index: (selectedIndex + 1) % optionsLength }+ case 'Enter':+ return { action: 'activate', index: selectedIndex }+ default:+ return numericShortcut(event, optionsLength)+ }+}++interface PermissionOptionRowProps {+ feedback: string+ hovered: boolean+ index: number+ onActivate: (index: number) => void+ onFeedbackChange: (feedback: string) => void+ onResetFeedback: () => void+ onSelect: (index: number) => void+ option: ApprovalCardOption+ optionsLength: number+ responding: boolean+ selected: boolean+ onSubmitFeedback: (option: ApprovalCardOption) => void+ setHoveredIndex: (index: number | null) => void+}++function optionRowClass(selected: boolean, hovered: boolean): string {+ if (selected) {+ return 'bg-accent-highlight-secondary'+ }+ if (hovered) {+ return 'bg-fill-button-tertiary-hover'+ }+ return 'bg-transparent'+}++function PermissionOptionRow({+ feedback,+ hovered,+ index,+ onActivate,+ onFeedbackChange,+ onResetFeedback,+ onSelect,+ option,+ optionsLength,+ responding,+ selected,+ onSubmitFeedback,+ setHoveredIndex,+}: PermissionOptionRowProps): JSX.Element {+ const active = selected || hovered+ const editing = isFeedbackOption(option) && selected+ const sublabel = optionSublabel(option)++ return (+ <div+ onClick={() => onActivate(index)}+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ className={cn('-mx-3 cursor-pointer select-none rounded px-3 py-1', optionRowClass(selected, hovered))}+ >+ <div className="flex items-center gap-2 leading-4">+ <span className={cn('w-[1ch] shrink-0 text-[13px] leading-4', selected ? 'text-accent' : 'text-muted')}>+ {selected ? '›' : ''}+ </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={onFeedbackChange}+ onNavigateUp={() => onSelect((index - 1 + optionsLength) % optionsLength)}+ onNavigateDown={() => onSelect((index + 1) % optionsLength)}+ onEscape={onResetFeedback}+ onSubmit={() => onSubmitFeedback(option)}+ />+ ) : (+ <span+ className={cn(+ 'whitespace-pre-wrap font-medium text-[13px] leading-4',+ active ? 'text-accent' : 'text-primary'+ )}+ >+ {optionRowLabel(option)}+ </span>+ )}+ </div>+ </div>+ {sublabel && <p className="mt-0.5 mb-0 pl-10 text-xs text-muted">{sublabel}</p>}+ </div>+ )+}+/*** 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@@ -196,44 +361,19 @@ function PermissionOptionRows({ options, responding, onRespond }: PermissionOpti// on an element outside the card keeps its native keys.useEffect(() => {const handleKeyDown = (e: KeyboardEvent): void => {- if (e.defaultPrevented || responding) {+ if (ignoresPermissionShortcut(e, responding, containerRef.current)) {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)- ) {+ const shortcut = permissionShortcut(e, selectedIndex, options.length)+ if (!shortcut) {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)- }- }++ e.preventDefault()+ if (shortcut.action === 'select') {+ selectRow(shortcut.index)+ } else {+ activate(shortcut.index)}}@@ -243,118 +383,44 @@ function PermissionOptionRows({ options, responding, onRespond }: PermissionOptireturn (<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)- 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>- {sublabel && <p className="mt-0.5 mb-0 pl-10 text-xs text-muted">{sublabel}</p>}- </div>- )- })}+ {options.map((option, index) => (+ <PermissionOptionRow+ key={option.optionId}+ feedback={feedback}+ hovered={hoveredIndex === index}+ index={index}+ onActivate={activate}+ onFeedbackChange={setFeedback}+ onResetFeedback={() => {+ setFeedback('')+ selectRow(0)+ }}+ onSelect={selectRow}+ option={option}+ optionsLength={options.length}+ responding={responding}+ selected={selectedIndex === index}+ onSubmitFeedback={submitFeedback}+ setHoveredIndex={setHoveredIndex}+ />+ ))}</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 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- * POST fails (the pending request only clears on success).- */-export function PermissionInput({ streamKey, request, disabled = false }: PermissionInputProps): JSX.Element {- const boundLogic = runStreamLogic({ streamKey })- const { respondToPermission, cancelRun } = useActions(boundLogic)- const { respondingToPermission: delivering } = useValues(boundLogic)- const respondingToPermission = delivering || disabled+interface PermissionOptions {+ mappedOptions: ApprovalCardOption[]+ planApproveOptions: ApprovalCardOption[]+ planOptions: ApprovalCardOption[]+}+function getPermissionOptions(request: PermissionRequestRecord): PermissionOptions {// 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((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. A plan that fell through@@ -363,6 +429,46 @@ export function PermissionInput({ streamKey, request, disabled = false }: Permisconst defaultOptions = planOptions.length > 0 ? planOptions : mapPermissionOptions(request.options)const mappedOptions = defaultOptions.length > 0 ? defaultOptions : mapPermissionOptions(request.options, true)+ return { mappedOptions, planApproveOptions, planOptions }+}++interface PlanPermissionInputProps {+ approveOptions: ApprovalCardOption[]+ rejectOption?: ApprovalCardOption+ responding: boolean+ onCancel: () => void+ onRespond: (optionId: string, customInput?: string) => void+}++function PlanPermissionInput({+ approveOptions,+ rejectOption,+ responding,+ onCancel,+ onRespond,+}: PlanPermissionInputProps): JSX.Element {+ return (+ <div className="p-3">+ <PlanApprovalSelector+ approveOptions={approveOptions}+ rejectOption={rejectOption}+ responding={responding}+ onApprove={(optionId) => onRespond(optionId)}+ onReject={(optionId, feedback) => onRespond(optionId, feedback)}+ onCancel={onCancel}+ />+ </div>+ )+}++interface GenericPermissionInputProps {+ options: ApprovalCardOption[]+ request: PermissionRequestRecord+ responding: boolean+ onRespond: (optionId: string, customInput?: string) => void+}++function GenericPermissionInput({ options, request, responding, onRespond }: GenericPermissionInputProps): JSX.Element {const display = getPermissionDisplay(request)// 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@@ -395,13 +501,52 @@ export function PermissionInput({ streamKey, request, disabled = false }: Permispayload={display.payload}/>)}- <PermissionOptionRows- options={mappedOptions}+ <PermissionOptionRows options={options} responding={responding} onRespond={onRespond} />+ </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 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+ * POST fails (the pending request only clears on success).+ */+export function PermissionInput({ streamKey, request, disabled = false }: PermissionInputProps): JSX.Element {+ const boundLogic = runStreamLogic({ streamKey })+ const { respondToPermission, cancelRun } = useActions(boundLogic)+ const { respondingToPermission: delivering } = useValues(boundLogic)+ const respondingToPermission = delivering || disabled++ const { mappedOptions, planApproveOptions, planOptions } = getPermissionOptions(request)+ if (planApproveOptions.length > 0) {+ return (+ <PlanPermissionInput+ approveOptions={planApproveOptions}+ rejectOption={planOptions.find((option) => option.decision === 'declined')}responding={respondingToPermission}+ onCancel={cancelRun}onRespond={(optionId, customInput) =>respondToPermission({ requestId: request.requestId, optionId, customInput })}/>- </div>+ )+ }++ return (+ <GenericPermissionInput+ options={mappedOptions}+ request={request}+ responding={respondingToPermission}+ onRespond={(optionId, customInput) =>+ respondToPermission({ requestId: request.requestId, optionId, customInput })+ }+ />)}