: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
fix(tasks): keep approvals pending during agent startup (#95980)
Georgiy Tarasove4d87f441b8e
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex fb1bd2a333ac..7d5d996896b4 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -40,7 +40,11 @@ jest.mock('products/tasks/frontend/generated/api', () => ({}))function notification(method: string, params: Record<string, unknown>): StoredLogEntry {- return { type: 'notification', notification: { method, params } }+ return {+ type: 'notification',+ notification: { method, params },+ ...(method.startsWith('_posthog/permission_') ? { source_run_id: 'run-1' } : {}),+ }}function sessionUpdate(update: Record<string, unknown>): StoredLogEntry {@@ -202,7 +206,9 @@ describe('runStreamLogic', () => {MockStream.install()projectLogic.mount()projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)- ;(tasksRunsCommandCreate as jest.Mock).mockReset().mockResolvedValue({ jsonrpc: '2.0' })+ ;(tasksRunsCommandCreate as jest.Mock)+ .mockReset()+ .mockResolvedValue({ jsonrpc: '2.0', result: { resolved: true } })logic = runStreamLogic({ streamKey: 'test-conversation', conversationId: 'test-conversation' })logic.mount()})@@ -2153,14 +2159,17 @@ describe('runStreamLogic', () => {).toEqual(['history', 'live tail'])})- it('drains the seam by content: a frame in both history and the buffered live tail renders once', async () => {+ test.each([false, true])('deduplicates history without run markers (resumed=%s)', async (resumed) => {// The exact keyless-`agent_message` duplication: the same finalized message is delivered// live during the fetch AND persisted in the snapshot. The multiset absorbs the live copy.let resolveLogs: (value: unknown) => void = () => {}jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(new Promise((resolve) => (resolveLogs = resolve)) as any)- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'in_progress',+ state: resumed ? { resume_from_run_id: 'ancestor-run' } : {},+ } as any)logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })await flushPromises()@@ -2169,7 +2178,7 @@ describe('runStreamLogic', () => {const overlap = sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'overlap' } })await MockStream.latest().emitMessage(overlap, '9-0')- resolveLogs([overlap as any])+ resolveLogs([overlap])await flushPromises()expect(@@ -2199,7 +2208,7 @@ describe('runStreamLogic', () => {await MockStream.latest().emitMessage(repeated, '1-0')await MockStream.latest().emitMessage(repeated, '2-0')- resolveLogs([repeated as any])+ resolveLogs([repeated])await flushPromises()expect(@@ -2919,6 +2928,14 @@ describe('runStreamLogic', () => {runId: 'run-1',traceId: 'trace-1',})+ logic.actions.ingestAcpFrame(+ notification('_posthog/permission_request', {+ requestId: 'req-1',+ toolCall: { toolCallId: 'tool-1', toolName: 'example_tool' },+ options: [{ optionId: 'allow_once', name: 'Allow', kind: 'allow_once' }],+ }),+ 'replay'+ )await expectLogic(logic, () => {logic.actions.respondToPermission({@@ -2927,12 +2944,17 @@ describe('runStreamLogic', () => {})}).toFinishAllListeners()- // "Command the latest run": the reply targets the (task, run) the renderer is streaming.- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-1',+ 'run-1',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },+ },+ { signal: expect.any(AbortSignal) }+ )})it('cancelRun cancels the streamed run via the tasks relay', async () => {@@ -3209,6 +3231,205 @@ describe('runStreamLogic', () => {],}+ describe.each([false, true])('approval delivery (automatic=%s)', (automatic) => {+ const readinessError = { status: 503, code: 'agent_session_not_ready' }+ const accepted = { jsonrpc: '2.0', result: { resolved: true } }+ const answers = { 'Which environment?': 'Example environment' }+ const submit = (): void => {+ const record = parsePermissionRequestFrame(permissionFrame, 'run-1')!+ if (automatic) {+ logic.actions.autoApprovePermissionRequest(record, 'allow_once')+ } else {+ logic.actions.ingestPermissionRequest(record)+ logic.actions.respondToPermission({ requestId: record.requestId, optionId: 'allow_once', answers })+ }+ }++ beforeEach(() => {+ jest.useFakeTimers()+ jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as never)+ jest.spyOn(lemonToast, 'error').mockImplementation(() => undefined as never)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ })++ afterEach(() => jest.useRealTimers())++ test('retries readiness rejections with one stable approval until confirmed', async () => {+ const command = jest.mocked(tasksRunsCommandCreate)+ let accept!: (value: typeof accepted) => void+ command+ .mockRejectedValueOnce(readinessError)+ .mockRejectedValueOnce(readinessError)+ .mockRejectedValueOnce(readinessError)+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ accept = resolve+ })+ )+ submit()+ await jest.advanceTimersByTimeAsync(0)+ expect(command).toHaveBeenCalledTimes(1)+ expect(logic.values.respondingToPermission).toBe(true)+ if (!automatic) {+ expect(logic.values.pendingPermissionRequest?.requestId).toBe('req-1')+ logic.actions.respondToPermission({ requestId: 'req-1', optionId: 'reject' })+ expect(command).toHaveBeenCalledTimes(1)+ }+ await jest.advanceTimersByTimeAsync(250)+ expect(command).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(500)+ expect(command).toHaveBeenCalledTimes(3)+ await jest.advanceTimersByTimeAsync(1000)+ expect(command).toHaveBeenCalledTimes(4)+ expect(logic.values.resolvedPermissionRequestIds.has('req-1')).toBe(false)+ accept(accepted)+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(logic.values.respondingToPermission).toBe(false)+ expect(logic.values.resolvedPermissionRequestIds.has('req-1')).toBe(true)+ const first = command.mock.calls[0].slice(0, 4)+ expect(first.slice(0, 3)).toEqual(['997', 'task-1', 'run-1'])+ for (const call of command.mock.calls) {+ expect(call.slice(0, 4)).toEqual(first)+ }+ })++ test.each(['exhausted', 'rpc_error', 'transport', 'request_timeout'])(+ 'preserves a manual card after %s and accepts a later manual retry',+ async (outcome) => {+ const command = jest.mocked(tasksRunsCommandCreate)+ if (outcome === 'exhausted') {+ command.mockRejectedValue(readinessError)+ } else if (outcome === 'rpc_error') {+ command.mockResolvedValue({+ jsonrpc: '2.0',+ error: { code: -32000, message: 'No pending permission request found for id: req-1' },+ })+ } else if (outcome === 'transport') {+ command.mockRejectedValue(new TypeError('Network request failed'))+ } else {+ command.mockImplementation(() => new Promise(() => {}))+ }+ submit()+ await jest.advanceTimersByTimeAsync(10_000)+ expect(command).toHaveBeenCalledTimes(outcome === 'exhausted' ? 12 : 1)+ expect(logic.values.pendingPermissionRequest?.requestId).toBe('req-1')+ expect(logic.values.respondingToPermission).toBe(false)+ expect(logic.values.resolvedPermissionRequestIds.has('req-1')).toBe(false)+ const failedAttempts = command.mock.calls.length+ await jest.advanceTimersByTimeAsync(10_000)+ expect(command).toHaveBeenCalledTimes(failedAttempts)+ command.mockResolvedValue(accepted)+ logic.actions.respondToPermission({ requestId: 'req-1', optionId: 'allow_once', answers })+ await jest.advanceTimersByTimeAsync(0)+ expect(command.mock.lastCall?.[3].params).toEqual({+ requestId: 'req-1',+ optionId: 'allow_once',+ customInput: undefined,+ answers,+ })+ expect(logic.values.pendingPermissionRequest).toBeNull()+ }+ )++ test.each(['replacement', 'terminal', 'resolved', 'unmount', 'reset'])(+ 'cancels an outstanding request on %s and ignores its completion',+ async (change) => {+ const command = jest.mocked(tasksRunsCommandCreate)+ let complete!: (value: typeof accepted) => void+ command.mockImplementation(+ () =>+ new Promise((resolve) => {+ complete = resolve+ })+ )+ submit()+ await jest.advanceTimersByTimeAsync(0)+ const signal = command.mock.calls[0][4]?.signal+ if (change === 'replacement') {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-2' })+ } else if (change === 'terminal') {+ logic.actions.handleTerminalStatus({ status: 'completed' })+ } else if (change === 'resolved') {+ logic.actions.ingestAcpFrame(+ notification('_posthog/permission_resolved', { requestId: 'req-1' })+ )+ } else if (change === 'reset') {+ logic.actions.reset()+ } else {+ logic.unmount()+ logic.mount()+ }+ expect(signal?.aborted).toBe(true)+ complete(accepted)+ await jest.advanceTimersByTimeAsync(20_000)+ expect(command).toHaveBeenCalledTimes(1)+ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(logic.values.respondingToPermission).toBe(false)+ expect(logic.values.resolvedPermissionRequestIds.has('req-1')).toBe(change === 'resolved')+ }+ )++ test('drops the card when the target run has already ended', async () => {+ const command = jest+ .mocked(tasksRunsCommandCreate)+ .mockRejectedValue({ status: 409, code: 'permission_target_ended' })+ submit()+ await jest.advanceTimersByTimeAsync(10_000)+ expect(command).toHaveBeenCalledTimes(1)+ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(logic.values.respondingToPermission).toBe(false)+ })++ test('cancels an outstanding request when the streamed run is canceled', async () => {+ const command = jest.mocked(tasksRunsCommandCreate)+ let complete!: (value: typeof accepted) => void+ command+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ complete = resolve+ })+ )+ .mockResolvedValue(accepted)+ submit()+ await jest.advanceTimersByTimeAsync(0)+ const signal = command.mock.calls[0][4]?.signal+ logic.actions.cancelRun()+ expect(signal?.aborted).toBe(true)+ complete(accepted)+ await jest.advanceTimersByTimeAsync(20_000)+ expect(command.mock.calls.filter((call) => call[3].method === 'permission_response')).toHaveLength(1)+ expect(logic.values.respondingToPermission).toBe(false)+ expect(logic.values.resolvedPermissionRequestIds.has('req-1')).toBe(false)+ })++ test('keeps the delivery alive when a warm run outside this stream is canceled', async () => {+ const command = jest.mocked(tasksRunsCommandCreate).mockRejectedValue(readinessError)+ submit()+ await jest.advanceTimersByTimeAsync(250)+ logic.actions.cancelRun({ taskId: 'warm-task', runId: 'warm-run' })+ await jest.advanceTimersByTimeAsync(500)+ expect(command.mock.calls.filter((call) => call[3].method === 'permission_response')).toHaveLength(3)+ })++ test('stops readiness retries when another client resolves this permission', async () => {+ const command = jest.mocked(tasksRunsCommandCreate).mockRejectedValue(readinessError)+ submit()+ await jest.advanceTimersByTimeAsync(250)+ logic.actions.ingestAcpFrame(+ notification('_posthog/permission_resolved', { requestId: 'different-request' })+ )+ await jest.advanceTimersByTimeAsync(500)+ expect(command).toHaveBeenCalledTimes(3)+ logic.actions.ingestAcpFrame(notification('_posthog/permission_resolved', { requestId: 'req-1' }))+ await jest.advanceTimersByTimeAsync(10_000)+ expect(command).toHaveBeenCalledTimes(3)+ expect(logic.values.pendingPermissionRequest).toBeNull()+ })+ })+it('parses a permission_request frame into a PermissionRequestRecord', () => {const record = parsePermissionRequestFrame(permissionFrame)expect(record).not.toBeNull()@@ -3304,11 +3525,17 @@ describe('runStreamLogic', () => {})expect(logic.values.pendingPermissionRequest).toBeNull()- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-auto', optionId: 'allow_once' },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-1',+ 'run-1',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-auto', optionId: 'allow_once' },+ },+ { signal: expect.any(AbortSignal) }+ )expect(captureSpy).toHaveBeenCalledWith('permission_auto_approved',expect.objectContaining({ request_id: 'req-auto', execution_type: 'sandbox' })@@ -3333,11 +3560,17 @@ describe('runStreamLogic', () => {})expect(logic.values.pendingPermissionRequest).toBeNull()- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-bash', optionId: 'allow' },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-1',+ 'run-1',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-bash', optionId: 'allow' },+ },+ { signal: expect.any(AbortSignal) }+ )})describe('full-auto mode', () => {@@ -3362,11 +3595,17 @@ describe('runStreamLogic', () => {await new Promise((resolve) => setTimeout(resolve, 0))expect(logic.values.pendingPermissionRequest).toBeNull()- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-destructive-fa', optionId: 'allow_once' },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-1',+ 'run-1',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-destructive-fa', optionId: 'allow_once' },+ },+ { signal: expect.any(AbortSignal) }+ )})it('still surfaces a connected-project operation', async () => {@@ -3451,16 +3690,27 @@ describe('runStreamLogic', () => {viewerLogic.mount()try {viewerLogic.actions.openSseForRun({ taskId: 'task-7', runId: 'run-7' })- viewerLogic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ viewerLogic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame, 'run-7')!)await expectLogic(viewerLogic, () => {viewerLogic.actions.respondToPermission({ requestId: 'req-1', optionId: 'allow_once' })}).toFinishAllListeners()- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-7', 'run-7', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-7',+ 'run-7',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: {+ requestId: 'req-1',+ optionId: 'allow_once',+ customInput: undefined,+ answers: undefined,+ },+ },+ { signal: expect.any(AbortSignal) }+ )const permRequested = captureSpy.mock.calls.find((c) => c[0] === 'permission_requested')expect(permRequested).not.toBeUndefined()if (!permRequested) {@@ -3476,7 +3726,7 @@ describe('runStreamLogic', () => {it('clears the pending request and commands the run on respondToPermission', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })- logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame, 'run-1')!)await expectLogic(logic, () => {logic.actions.respondToPermission({@@ -3487,11 +3737,17 @@ describe('runStreamLogic', () => {expect(logic.values.pendingPermissionRequest).toBeNull()expect(logic.values.respondingToPermission).toEqual(false)- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },- })+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(+ '997',+ 'task-1',+ 'run-1',+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },+ },+ { signal: expect.any(AbortSignal) }+ )})it('keeps the card pending and surfaces an error when the reply command fails', async () => {@@ -3499,7 +3755,7 @@ describe('runStreamLogic', () => {const exceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => undefined as any)logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })- logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame, 'run-1')!)await expectLogic(logic, () => {logic.actions.respondToPermission({@@ -3550,23 +3806,46 @@ describe('runStreamLogic', () => {expect(captureSpy).toHaveBeenCalledTimes(1)})- it('re-derives a pending approval from a logged _posthog/permission_request without telemetry', async () => {- const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)- jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([- notification('_posthog/permission_request', {- requestId: 'req-1',- toolCall: permissionFrame.toolCall,- options: permissionFrame.options,- }) as any,- ])- jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ test.each([+ ['_posthog/sdk_session', 'run-1', true, true],+ ['_posthog/run_started', 'run-1', true, true],+ ['_posthog/sdk_session', 'ancestor-run', true, false],+ ['_posthog/run_started', 'ancestor-run', true, false],+ [undefined, undefined, true, false],+ [undefined, undefined, false, true],+ ] as const)(+ 'restores approvals using run markers (%s, %s, resumed=%s)',+ async (method, sourceRunId, resumed, actionable) => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ ...(method+ ? [+ notification(method, {+ [method === '_posthog/sdk_session' ? 'taskRunId' : 'runId']: sourceRunId,+ }),+ ]+ : []),+ notification('_posthog/permission_request', {+ requestId: 'req-1',+ toolCall: permissionFrame.toolCall,+ options: permissionFrame.options,+ }),+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'in_progress',+ state: resumed ? { resume_from_run_id: 'ancestor-run' } : {},+ } as any)- logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })- await flushPromises()+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()- expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')- expect(captureSpy).not.toHaveBeenCalled()- })+ expect(logic.values.pendingPermissionRequest?.requestId).toEqual(actionable ? 'req-1' : undefined)+ expect(captureSpy).not.toHaveBeenCalled()+ logic.actions.respondToPermission({ requestId: 'req-1', optionId: 'allow_once' })+ await flushPromises()+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(actionable ? 1 : 0)+ }+ )it('drops a logged permission_request that has a matching permission_resolved entry', async () => {jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([@@ -3586,7 +3865,8 @@ describe('runStreamLogic', () => {})it('clears the pending card when another client resolves the request', async () => {- logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame, 'run-1')!)expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')await expectLogic(logic, () => {@@ -3597,7 +3877,7 @@ describe('runStreamLogic', () => {})it('drops the pending card when the run reaches a terminal status, but not before', () => {- logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame, 'run-1')!)logic.actions.handleTerminalStatus({ status: 'queued' })expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex d1170b4d42ea..cc9e042e4743 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -27,6 +27,7 @@ import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'import type { UserType } from '../../../../frontend/src/types'+import { deliverPermissionResponse, isPermissionTargetEnded } from '../policy/permissionDelivery'import { isPlanPermissionRequest } from '../policy/permissionUtils'import { parseSandboxQuestions } from '../policy/questionUtils'import {@@ -366,6 +367,7 @@ function normalizeNotificationEntry(entry: unknown): StoredLogEntry | null {return {type: 'notification',...(typeof entry.timestamp === 'string' ? { timestamp: entry.timestamp } : {}),+ ...(typeof entry.source_run_id === 'string' ? { source_run_id: entry.source_run_id } : {}),notification: entry.notification,} as StoredLogEntry}@@ -375,6 +377,29 @@ function isResumeRun(run: { state?: unknown }): boolean {return isRecord(state) && typeof state.resume_from_run_id === 'string' && state.resume_from_run_id !== ''}+function normalizeHistory(entries: unknown[], runId: string, resumed: boolean): StoredLogEntry[] {+ // Match Desktop's run-marker scoping without changing the shared log payload or its deduplication keys.+ // A resume chain without a marker has unknown ownership; a single-run history belongs to its requested run.+ let sourceRunId: string | undefined = resumed ? undefined : runId+ return entries.flatMap((raw) => {+ const entry = normalizeNotificationEntry(raw)+ if (!entry) {+ return []+ }+ const { method, params } = entry.notification+ const marker =+ method === '_posthog/sdk_session'+ ? params?.taskRunId+ : method === '_posthog/run_started'+ ? params?.runId+ : undefined+ if (typeof marker === 'string') {+ sourceRunId = marker+ }+ return [{ ...entry, source_run_id: sourceRunId }]+ })+}+/*** Union incoming resource products into the accumulated list by `id`, preserving first-seen order.* Pure — mirrors the reference `accumulateSessionResources`. Products without an `id` are skipped.@@ -694,7 +719,8 @@ function parsePermissionOption(raw: unknown): PermissionOption | null {* its runtime check.*/export function parsePermissionRequestFrame(- frame: PermissionRequestFrame | PosthogPermissionRequestParams+ frame: PermissionRequestFrame | PosthogPermissionRequestParams,+ sourceRunId?: string): PermissionRequestRecord | null {const requestId = frame.requestIdif (typeof requestId !== 'string') {@@ -731,6 +757,7 @@ export function parsePermissionRequestFrame(return {requestId,+ sourceRunId,toolCallId,toolName,options,@@ -908,7 +935,14 @@ function isResumeContextPrompt(text: string): boolean {* through. Steady-state live frames after the drain are appended directly and never deduped.*/function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: StoredLogEntry[]): StoredLogEntry[] {- const seamKey = (entry: StoredLogEntry): string => JSON.stringify(entry.notification)+ const seamKey = (entry: StoredLogEntry): string =>+ JSON.stringify([+ entry.notification.method === '_posthog/permission_request' ||+ entry.notification.method === '_posthog/permission_resolved'+ ? entry.source_run_id+ : undefined,+ entry.notification,+ ])const historicalCounts = new Map<string, number>()for (const entry of history) {const key = seamKey(entry)@@ -1412,6 +1446,7 @@ export interface runStreamLogicValues {log: RunLoglogBootstrapLoading: booleanpendingPermissionRequest: PermissionRequestRecord | null+ permissionResponseRequestIds: Set<string>reconnectAttempt: numberresolvedPermissionRequestIds: Set<string>resourcesUsed: ResourceProduct[]@@ -1472,6 +1507,9 @@ export interface runStreamLogicActions {taskId: stringtraceId?: string | undefined}+ cancelPermissionDelivery: () => {+ value: true+ }cancelRun: (run?: { runId: string; taskId: string }) => {run:| {@@ -1486,6 +1524,19 @@ export interface runStreamLogicActions {closeSse: () => {value: true}+ deliverPermission: (+ record: PermissionRequestRecord,+ optionId: string,+ customInput?: string,+ answers?: Record<string, string>,+ automatic?: boolean+ ) => {+ answers: Record<string, string> | undefined+ automatic: boolean+ customInput: string | undefined+ optionId: string+ record: PermissionRequestRecord+ }handleStreamError: (envelope: StreamErrorEnvelope) => StreamErrorEnvelopehandleTerminalStatus: (status: {errorMessage?: string | null@@ -1548,7 +1599,10 @@ export interface runStreamLogicActions {taskId: stringtraceId?: string | undefined}- permissionResponseFailed: () => {+ permissionResponseFailed: (requestId: string) => {+ requestId: string+ }+ permissionRunChanged: () => {value: true}pushConversationCleared: () => {@@ -1630,6 +1684,10 @@ export interface runStreamLogicActions {export interface runStreamLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ respondingToPermission: (+ permissionResponseRequestIds: Set<string>,+ pendingPermissionRequest: PermissionRequestRecord | null+ ) => booleanfoldedThread: (log: RunLog, isBootstrapResumeRun: boolean) => FoldedThreadlatestTurnTraceId: (threadItems: ThreadItem[]) => string | nullthreadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]@@ -1785,6 +1843,15 @@ export const runStreamLogic = kea<runStreamLogicType>([}),/** Silently POST `allow` for a request the default policy auto-approves (no card shown). */autoApprovePermissionRequest: (record: PermissionRequestRecord, optionId: string) => ({ record, optionId }),+ deliverPermission: (+ record: PermissionRequestRecord,+ optionId: string,+ customInput?: string,+ answers?: Record<string, string>,+ automatic: boolean = false+ ) => ({ record, optionId, customInput, answers, automatic }),+ cancelPermissionDelivery: true,+ permissionRunChanged: true,/** Pin a requestId as seen without surfacing a card, so a reconnect replay can't re-process it. */markPermissionRequestSeen: (requestId: string) => ({ requestId }),/**@@ -1816,7 +1883,7 @@ export const runStreamLogic = kea<runStreamLogicType>([* Internal: the reply POST failed. Resets the in-flight flag (so the surviving card's* buttons re-enable for retry) without coupling that reset to unrelated stream errors.*/- permissionResponseFailed: true,+ permissionResponseFailed: (requestId: string) => ({ requestId }),handleTerminalStatus: (status: {status: RunStatuserrorMessage?: string | null@@ -2034,6 +2101,7 @@ export const runStreamLogic = kea<runStreamLogicType>([markPermissionRequestResolved: (state, { requestId }) =>state?.requestId === requestId ? null : state,clearPermissionRequest: () => null,+ permissionRunChanged: () => null,// A terminal run can't accept approvals — drop a card re-derived from its history.handleTerminalStatus: (state, { status }) => (isTerminalRunStatus(status) ? null : state),reset: () => null,@@ -2054,6 +2122,7 @@ export const runStreamLogic = kea<runStreamLogicType>([next.add(requestId)return next},+ permissionRunChanged: () => new Set<string>(),reset: () => new Set<string>(),},],@@ -2067,20 +2136,24 @@ export const runStreamLogic = kea<runStreamLogicType>([next.add(requestId)return next},+ permissionRunChanged: () => new Set<string>(),reset: () => new Set<string>(),},],// In-flight state for the approval reply POST — drives the input card's loading/disabled// props. Cleared on resolution (success) and on the POST's own failure (the card stays// pending, so the buttons must re-enable for retry).- respondingToPermission: [- false,+ permissionResponseRequestIds: [+ new Set<string>(),{- respondToPermission: () => true,- markPermissionRequestResolved: () => false,- clearPermissionRequest: () => false,- permissionResponseFailed: () => false,- reset: () => false,+ deliverPermission: (state, { record }) => new Set([...state, record.requestId]),+ markPermissionRequestResolved: (state, { requestId }) =>+ new Set([...state].filter((id) => id !== requestId)),+ clearPermissionRequest: () => new Set<string>(),+ permissionResponseFailed: (state, { requestId }) =>+ new Set([...state].filter((id) => id !== requestId)),+ cancelPermissionDelivery: () => new Set<string>(),+ reset: () => new Set<string>(),},],currentMode: [@@ -2180,6 +2253,11 @@ export const runStreamLogic = kea<runStreamLogicType>([],}),selectors({+ respondingToPermission: [+ (s) => [s.permissionResponseRequestIds, s.pendingPermissionRequest],+ (ids: Set<string>, record: PermissionRequestRecord | null): boolean =>+ record ? ids.has(record.requestId) : ids.size > 0,+ ],/*** Pure projection of the ordered log into the rendered thread plus the tool-invocation map.* Memoized on `log` identity, so it recomputes only when a frame is actually appended.@@ -2381,6 +2459,11 @@ export const runStreamLogic = kea<runStreamLogicType>([}),listeners(({ values, actions, cache, props }) => ({bootstrapRun: async ({ taskId, runId, justCreatedRun }, breakpoint) => {+ if (cache.activeRun && (cache.activeRun.runId !== runId || cache.activeRun.taskId !== taskId)) {+ actions.cancelPermissionDelivery()+ actions.permissionRunChanged()+ cache.activeRun = undefined+ }const projectId = values.currentProjectIdif (projectId === null) {actions.handleStreamError({ errorTitle: 'No current project', retryable: false })@@ -2413,10 +2496,9 @@ export const runStreamLogic = kea<runStreamLogicType>([const replayEntries = replayResultbreakpoint()if (values.log.entries.length === 0) {- replayEntries- .map(normalizeNotificationEntry)- .filter((entry): entry is StoredLogEntry => entry !== null)- .forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))+ normalizeHistory(replayEntries, runId, isResumeRun(replayRun)).forEach((entry) =>+ actions.ingestAcpFrame(entry, 'replay')+ )}if (isTerminalRunStatus(replayRun.status ?? null)) {@@ -2494,9 +2576,7 @@ export const runStreamLogic = kea<runStreamLogicType>([// The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders// persisted human turns and side-effect telemetry stays suppressed for history.- const history = entries- .map(normalizeNotificationEntry)- .filter((entry): entry is StoredLogEntry => entry !== null)+ const history = normalizeHistory(entries, runId, isResumeRun(run))history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))if (terminal) {@@ -2536,7 +2616,14 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.streamEnded = falsecache.streamTokenRefreshes = 0const previousRun = cache.activeRun as { taskId: string; runId: string } | undefined- if (previousRun && previousRun.runId !== runId) {+ if (cache.permissionRunId && cache.permissionRunId !== runId) {+ actions.cancelPermissionDelivery()+ actions.permissionRunChanged()+ }+ cache.permissionRunId = runId+ if (previousRun && (previousRun.runId !== runId || previousRun.taskId !== taskId)) {+ actions.cancelPermissionDelivery()+ actions.permissionRunChanged()// The cursor is a Redis id from the previous run's stream — it addresses nothing in// this one, so resuming from it can skip this run's opening frames.cache.lastEventId = undefined@@ -2596,19 +2683,20 @@ export const runStreamLogic = kea<runStreamLogicType>([return}if (isNotificationFrame(parsed)) {+ const entry = { ...parsed, source_run_id: runId }// During the bootstrap window the SSE is connected before the S3 snapshot lands,// so buffer live notification frames instead of appending them; the drain// reconciles them against the snapshot once it loads (see `bootstrapRun`). Steady// state (and every send/reconnect open, which never buffers) appends directly.if (cache.bufferingLiveFrames) {- ;(cache.bufferedLiveFrames as StoredLogEntry[]).push(parsed)+ ;(cache.bufferedLiveFrames as StoredLogEntry[]).push(entry)} else {- actions.ingestAcpFrame(parsed, 'live')+ actions.ingestAcpFrame(entry, 'live')}} else if (isPermissionRequestFrame(parsed)) {// requestId-keyed dedup: this top-level envelope isn't a notification, so a// reconnect's resume could re-deliver it verbatim.- const record = parsePermissionRequestFrame(parsed)+ const record = parsePermissionRequestFrame(parsed, runId)if (record &&!values.seenPermissionRequestIds.has(record.requestId) &&@@ -2868,6 +2956,14 @@ export const runStreamLogic = kea<runStreamLogicType>([}},routePermissionRequest: ({ record, replayedFromHistory }) => {+ if (+ props.replayOnly ||+ !record.sourceRunId ||+ record.sourceRunId !== cache.activeRun?.runId ||+ isTerminalRunStatus(values.currentRunStatus)+ ) {+ return+ }// Replayed history is a read-only restore — never auto-approve (the run may be terminal).// Full-auto covers the task's selected project. Questions, plan approvals, and calls into// connected projects still surface because the task did not authorize them.@@ -2906,19 +3002,7 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.ingestPermissionRequest(record)return}- try {- await tasksRunsCommandCreate(String(values.currentProjectId), activeRun.taskId, activeRun.runId, {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId: record.requestId, optionId },- })- actions.markPermissionRequestResolved(record.requestId)- } catch (error) {- // The auto-approve command failed — don't leave the agent silently blocked. Fall back to- // the manual card so the user can respond.- posthog.captureException(error)- actions.ingestPermissionRequest(record)- }+ actions.deliverPermission(record, optionId, undefined, undefined, true)},ingestPermissionRequest: ({ record, replayedFromHistory }) => {if (replayedFromHistory) {@@ -2939,35 +3023,106 @@ export const runStreamLogic = kea<runStreamLogicType>([execution_type: 'sandbox',})},- respondToPermission: async ({ requestId, optionId, customInput, answers }) => {+ respondToPermission: ({ requestId, optionId, customInput, answers }) => {+ const record = values.pendingPermissionRequest+ if (record?.requestId === requestId) {+ actions.deliverPermission(record, optionId, customInput, answers)+ }+ },+ deliverPermission: async ({ record, optionId, customInput, answers, automatic }) => {const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined- if (!activeRun || values.currentProjectId == null) {- // No live run to command — keep the card so the user can retry once the stream resolves.- actions.permissionResponseFailed()- lemonToast.error('Failed to send approval. Please try again.')+ const projectId = values.currentProjectId+ if (+ !activeRun ||+ projectId == null ||+ record.sourceRunId !== activeRun.runId ||+ isTerminalRunStatus(values.currentRunStatus) ||+ props.replayOnly+ ) {+ actions.permissionResponseFailed(record.requestId)+ return+ }+ const deliveries = (cache.permissionDeliveries ??= new Map<string, AbortController>()) as Map<+ string,+ AbortController+ >+ const key = `permission-delivery:${activeRun.runId}:${record.requestId}`+ if (deliveries.has(key)) {+ return+ }+ if (values.resolvedPermissionRequestIds.has(record.requestId)) {+ actions.permissionResponseFailed(record.requestId)return}+ const controller = new AbortController()+ const disposables = cache.disposables+ deliveries.set(key, controller)+ disposables.add(+ () => () => {+ controller.abort()+ deliveries.delete(key)+ },+ key,+ { pauseOnPageHidden: false }+ )+ const params = {+ requestId: record.requestId,+ optionId,+ customInput,+ answers: answers ? { ...answers } : undefined,+ }try {- // PERMISSION_RESPONDED telemetry is emitted server-side by the tasks relay. The renderer- // commands the run it is streaming (`cache.activeRun`); on a persistent sandbox the run- // only advances when the old one dies and the successor takes over — which is exactly the- // run the renderer has re-resolved, so the reply lands where it belongs.- await tasksRunsCommandCreate(String(values.currentProjectId), activeRun.taskId, activeRun.runId, {- jsonrpc: '2.0',- method: 'permission_response',- params: { requestId, optionId, customInput, answers },- })- actions.markPermissionRequestResolved(requestId)+ await deliverPermissionResponse(+ (signal) =>+ tasksRunsCommandCreate(+ String(projectId),+ activeRun.taskId,+ activeRun.runId,+ {+ jsonrpc: '2.0',+ method: 'permission_response',+ params,+ },+ { signal }+ ),+ controller.signal+ )+ if (!controller.signal.aborted && !disposables.isDisposed) {+ actions.markPermissionRequestResolved(record.requestId)+ }} catch (error) {- // A failed reply POST does not mean the run died — the agent is still alive and- // blocked on this same approval. Keep the failure local to the card (re-enable its- // buttons for a retry) instead of tearing down the stream, which would release the- // chat lock and hide the still-pending request behind the normal input.+ if (controller.signal.aborted || disposables.isDisposed) {+ return+ }posthog.captureException(error)- actions.permissionResponseFailed()+ // The run ended before the approval arrived, so every further attempt gets the same+ // rejection. Drop the card instead of asking for a retry that cannot succeed.+ if (isPermissionTargetEnded(error)) {+ actions.clearPermissionRequest()+ lemonToast.error("This run has ended, so the approval wasn't sent. Send a new message to continue.")+ return+ }+ if (automatic) {+ actions.ingestPermissionRequest(record)+ }+ actions.permissionResponseFailed(record.requestId)lemonToast.error('Failed to send approval. Please try again.')+ } finally {+ disposables.dispose(key)}},+ cancelPermissionDelivery: () => {+ const deliveries = cache.permissionDeliveries as Map<string, AbortController> | undefined+ for (const key of deliveries?.keys() ?? []) {+ cache.disposables.dispose(key)+ }+ },+ markPermissionRequestResolved: ({ requestId }) => {+ cache.disposables.dispose(`permission-delivery:${cache.activeRun?.runId}:${requestId}`)+ },+ clearPermissionRequest: () => {+ actions.cancelPermissionDelivery()+ },cancelRun: async ({ run }) => {// Cancel a run through the generic tasks relay — the same command PostHog Desktop issues. The// SSE then receives a terminal task_run_state; cancellation telemetry is emitted server-side@@ -2977,6 +3132,12 @@ export const runStreamLogic = kea<runStreamLogicType>([if (!target || values.currentProjectId == null) {return}+ // An approval waiting on agent startup outlives this command — the terminal frame that stops+ // it is a round trip away, so the agent can still accept work the user just canceled. Drop+ // the delivery here. A warm Run is not the streamed run, so its deliveries are not ours.+ if (target.runId === (cache.activeRun as { runId: string } | undefined)?.runId) {+ actions.cancelPermissionDelivery()+ }try {await tasksRunsCommandCreate(String(values.currentProjectId), target.taskId, target.runId, {jsonrpc: '2.0',@@ -2992,6 +3153,7 @@ export const runStreamLogic = kea<runStreamLogicType>([if (!isTerminalRunStatus(status)) {return}+ actions.cancelPermissionDelivery()cache.disposables.dispose('reconnect-backoff')cache.disposables.dispose('event-source')@@ -3067,6 +3229,7 @@ export const runStreamLogic = kea<runStreamLogicType>([})},closeSse: () => {+ actions.cancelPermissionDelivery()cache.activeRun = undefinedcache.lastEventId = undefinedcache.disposables.dispose('reconnect-backoff')@@ -3075,9 +3238,11 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.disposables.dispose('event-source')},reset: () => {+ actions.cancelPermissionDelivery()// `log` clears via its own reducer on `reset`, so the projection empties with it. The// per-frame invocation tracker mirrors the log, so it must clear alongside it.cache.trackedToolInvocations = undefined+ cache.permissionRunId = undefinedcache.activeRun = undefinedcache.turnStartedAtMs = undefinedcache.isBootstrapping = false@@ -3244,7 +3409,7 @@ export const runStreamLogic = kea<runStreamLogicType>([// are re-derived on bootstrap (a reload mid-approval would otherwise lose the card while// the agent stays blocked), and a resolution observed here clears the local card.if (isPosthogNotification(notification, '_posthog/permission_request')) {- const record = parsePermissionRequestFrame(notification.params ?? {})+ const record = parsePermissionRequestFrame(notification.params ?? {}, entry.source_run_id)if (record &&!values.seenPermissionRequestIds.has(record.requestId) &&@@ -3256,7 +3421,12 @@ export const runStreamLogic = kea<runStreamLogicType>([}if (isPosthogNotification(notification, '_posthog/permission_resolved')) {const requestId = notification.params?.requestId- if (typeof requestId === 'string' && requestId) {+ if (+ typeof requestId === 'string' &&+ requestId &&+ entry.source_run_id === cache.activeRun?.runId &&+ entry.source_run_id+ ) {actions.markPermissionRequestResolved(requestId)}returndiff --git a/products/posthog_ai/frontend/policy/permissionDelivery.ts b/products/posthog_ai/frontend/policy/permissionDelivery.tsnew file mode 100644index 000000000000..b854d67e5508--- /dev/null+++ b/products/posthog_ai/frontend/policy/permissionDelivery.ts@@ -0,0 +1,78 @@+import type { TaskRunCommandResponseApi } from 'products/tasks/frontend/generated/api.schemas'++const STARTUP_WAIT_MS = 10_000+const REQUEST_TIMEOUT_MS = 5_000++function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {+ return new Promise((resolve, reject) => {+ const abort = (): void => reject(signal.reason ?? new Error('Approval delivery canceled'))+ signal.addEventListener('abort', abort, { once: true })+ if (signal.aborted) {+ abort()+ }+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort))+ })+}++async function waitForReadiness(ms: number, signal: AbortSignal): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ await abortable(new Promise<void>((resolve) => (timer = setTimeout(resolve, ms))), signal)+ } finally {+ clearTimeout(timer)+ }+}++export function isPermissionTargetEnded(error: unknown): boolean {+ const rejection = error as { status?: number; code?: string }+ return rejection?.status === 409 && rejection.code === 'permission_target_ended'+}++export async function deliverPermissionResponse(+ send: (signal: AbortSignal) => Promise<TaskRunCommandResponseApi>,+ signal: AbortSignal+): Promise<void> {+ const deadline = performance.now() + STARTUP_WAIT_MS+ let attempt = 0+ while (!signal.aborted) {+ const remaining = deadline - performance.now()+ if (remaining <= 0) {+ throw new Error('The agent is still starting. Please try again.')+ }+ const request = new AbortController()+ const abort = (): void => request.abort(signal.reason)+ signal.addEventListener('abort', abort, { once: true })+ const timer = setTimeout(+ () => request.abort(new Error('Approval delivery timed out')),+ Math.min(REQUEST_TIMEOUT_MS, remaining)+ )+ try {+ const response = await abortable(send(request.signal), request.signal)+ const result = response.result+ if (+ response.jsonrpc !== '2.0' ||+ 'error' in response ||+ typeof result !== 'object' ||+ result === null ||+ !('resolved' in result) ||+ result.resolved !== true+ ) {+ throw new Error('The agent did not confirm this approval.')+ }+ return+ } catch (error) {+ const rejection = error as { status?: number; code?: string }+ if (signal.aborted || rejection?.status !== 503 || rejection.code !== 'agent_session_not_ready') {+ throw error+ }+ } finally {+ clearTimeout(timer)+ signal.removeEventListener('abort', abort)+ }+ await waitForReadiness(+ Math.min(250 * 2 ** Math.min(attempt++, 2), Math.max(0, deadline - performance.now())),+ signal+ )+ }+ throw signal.reason ?? new Error('Approval delivery canceled')+}diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tsindex 3ddf416824c8..baf51d642a3f 100644--- a/products/posthog_ai/frontend/types/streamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -241,6 +241,7 @@ export interface RunArtifacts {*/export interface PermissionRequestRecord {requestId: string+ sourceRunId?: stringtoolCallId: string/** Canonical ACP tool name (`mcp__posthog__exec`, or a built-in like `Bash`) — drives the default permission policy. */toolName: stringdiff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.tsindex 5b8e0140baca..827a7afdc155 100644--- a/products/posthog_ai/frontend/types/wireTypes.ts+++ b/products/posthog_ai/frontend/types/wireTypes.ts@@ -28,6 +28,8 @@ export interface AcpNotification {*/export interface StoredLogEntry {type: 'notification'+ /** Client-side ownership; the shared backend log payload stays unchanged. */+ source_run_id?: stringtimestamp?: stringnotification: AcpNotification}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ad28c48d100f..2aa64b919cc6 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -232,6 +232,9 @@ __all__ = ["task_run_preview_ready","get_task_run_living_artifact","capture_relay_command_telemetry",+ "PermissionResponseUnavailable",+ "validate_permission_response_target",+ "classify_permission_response","get_task_run_stream_info","get_task_summaries","is_internal_debug_team",@@ -3917,6 +3920,33 @@ def resolve_stream_base_url(*, distinct_id: str, organization_id: str | UUID, fo# --- Task run commands (user_message signal + sandbox proxy) ---+class PermissionResponseUnavailable(Exception):+ def __init__(self, *, target_ended: bool) -> None:+ self.code = "permission_target_ended" if target_ended else "agent_session_not_ready"+ self.status_code = 409 if target_ended else 503+ super().__init__("This run has ended." if target_ended else "The agent is still starting. Please try again.")+++def validate_permission_response_target(run_id: str | UUID, task_id: str | UUID, team_id: int) -> None:+ run = _get_visible_run(run_id, task_id, team_id)+ if run is None or run.is_terminal:+ raise PermissionResponseUnavailable(target_ended=True)+++def classify_permission_response(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, status_code: int, data: object+) -> bool:+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415+ is_agent_session_not_ready,+ permission_response_succeeded,+ )++ validate_permission_response_target(run_id, task_id, team_id)+ if is_agent_session_not_ready(status_code, data):+ raise PermissionResponseUnavailable(target_ended=False)+ return 200 <= status_code < 300 and permission_response_succeeded(data)++def validate_task_run_artifact_ids(run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_ids: list[str]) -> tuple[list[str], bool]:diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.pyindex e58b9780baf7..a452d04086a6 100644--- a/products/tasks/backend/logic/services/agent_command.py+++ b/products/tasks/backend/logic/services/agent_command.py@@ -54,6 +54,17 @@ def is_retryable_agent_rpc_error(error: str) -> bool:return bool(CONTENT_BLOCK_ERROR.search(error)) or TURN_ENDED_WITHOUT_RESPONSE_ERROR in error+def is_agent_session_not_ready(status_code: int, data: object) -> bool:+ return status_code == 400 and isinstance(data, dict) and data.get("error") == NO_ACTIVE_SESSION_ERROR+++def permission_response_succeeded(data: object) -> bool:+ if not isinstance(data, dict) or data.get("jsonrpc") != "2.0" or "error" in data:+ return False+ result = data.get("result")+ return isinstance(result, dict) and result.get("resolved") is True++def user_facing_agent_error(error: str | None) -> str:if error and CONTENT_BLOCK_ERROR.search(error):return CONTENT_BLOCK_USER_ERRORdiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex f50f1c675425..974722f927cb 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -4025,8 +4025,12 @@ class TaskRunCommandResponseSerializer(serializers.Serializer):jsonrpc = serializers.CharField(help_text="JSON-RPC version")id = serializers.JSONField(required=False, default=None, help_text="Request ID echoed back (string or number)")- result = serializers.JSONField(required=False, help_text="Command result on success")- error = serializers.DictField(required=False, help_text="Error details on failure")+ result = serializers.JSONField(+ required=False, help_text="Command result. Permission responses confirm acceptance only with resolved=true."+ )+ error = serializers.DictField(+ required=False, help_text="JSON-RPC error details, including failures returned with HTTP 200"+ )class TaskRunSessionLogsQuerySerializer(serializers.Serializer):diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 0dacf6d6ee0b..0293ab6db3f9 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -2782,7 +2782,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):404: OpenApiResponse(description="Task run not found"),409: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="Task run workflow has ended",+ description="Task run workflow has ended; permission_target_ended for an ended approval target",),429: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -2791,13 +2791,17 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),503: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="PostHog Desktop access could not be verified",+ description="agent_session_not_ready: approval rejected before execution while the agent starts; "+ "or PostHog Desktop access could not be verified",),},summary="Send command to task run",description="Queue user_message JSON-RPC commands through the task workflow and forward sandbox control ""commands to the agent server. Supports user_message, cancel, close, permission_response, "- "set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations.",+ "set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. "+ "Permission responses return 503 agent_session_not_ready only when rejected before execution; "+ "clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; "+ "permission acceptance requires result.resolved=true.",strict_request_validation=True,)@action(@@ -2963,6 +2967,15 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if connection is None:raise NotFound()+ if method == "permission_response":+ try:+ tasks_facade.validate_permission_response_target(pk, task_id, self.team_id)+ except tasks_facade.PermissionResponseUnavailable as error:+ return Response(+ TaskRunErrorResponseSerializer({"code": error.code, "error": str(error)}).data,+ status=error.status_code,+ )+if not connection.sandbox_url:return Response(TaskRunErrorResponseSerializer(@@ -3002,17 +3015,25 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):sandbox_token_param=connection.sandbox_token_param,)+ try:+ response_data = agent_response.json()+ except ValueError:+ if agent_response.ok:+ raise+ response_data = {}+ success = agent_response.ok+ if method == "permission_response":+ success = tasks_facade.classify_permission_response(+ pk, task_id, self.team_id, status_code=agent_response.status_code, data=response_data+ )tasks_facade.capture_relay_command_telemetry(- pk, task_id, self.team_id, method=method, params=params, success=agent_response.ok+ pk, task_id, self.team_id, method=method, params=params, success=success)if agent_response.ok:tasks_facade.signal_task_run_client_activity(pk, task_id, self.team_id)- return Response(agent_response.json())+ return Response(response_data)- try:- error_body = agent_response.json()- except Exception:- error_body = {}+ error_body = response_data if isinstance(response_data, dict) else {}if agent_response.status_code == 401:error_msg = error_body.get("error", "Agent server authentication failed")@@ -3028,6 +3049,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):status=status.HTTP_502_BAD_GATEWAY,)+ except tasks_facade.PermissionResponseUnavailable as error:+ tasks_facade.capture_relay_command_telemetry(+ pk, task_id, self.team_id, method=method, params=params, success=False+ )+ return Response(+ TaskRunErrorResponseSerializer({"code": error.code, "error": str(error)}).data,+ status=error.status_code,+ )except http_requests.ConnectionError:logger.warning(f"Agent server unreachable for task run {pk}")tasks_facade.capture_relay_command_telemetry(diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex c262a927b2a6..deb0f7706310 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -8970,7 +8970,7 @@ class TestTaskRunSessionLogsAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()- self.assertEqual(len(data), 3)+ self.assertEqual(data, entries)self.assertEqual(response["X-Total-Count"], "3")self.assertEqual(response["X-Filtered-Count"], "3")@@ -11820,12 +11820,27 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):def _capture_calls_for_event(self, mock_capture, event):return [call for call in mock_capture.call_args_list if call.kwargs.get("event") == event]+ @parameterized.expand(+ [+ ("accepted", {"result": {"resolved": True}}, True),+ (+ "rpc_error",+ {"error": {"code": -32000, "message": "No pending permission request found for id: perm-1"}},+ False,+ ),+ ("unconfirmed", {"result": {"acknowledged": True}}, False),+ ("false", {"result": {"resolved": False}}, False),+ ]+ )@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.models.posthoganalytics.capture")@patch("products.tasks.backend.presentation.views.api.http_requests.post")- def test_command_emits_permission_responded_telemetry_for_posthog_ai(self, mock_post, mock_capture):+ def test_command_emits_permission_responded_telemetry_for_posthog_ai(+ self, _name, envelope, expected_success, mock_post, mock_capture+ ):reset_sandbox_jwt_key_cache()- self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-4", "result": {"acknowledged": True}})+ payload = {"jsonrpc": "2.0", "id": "req-4", **envelope}+ self._mock_agent_response(mock_post, payload)task = self._create_posthog_ai_task()run = self._create_run_with_sandbox(task)@@ -11848,7 +11863,8 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(props["run_id"], str(run.id))self.assertEqual(props["request_id"], "perm-1")self.assertEqual(props["option_id"], "allow")- self.assertTrue(props["success"])+ self.assertEqual(props["success"], expected_success)+ self.assertEqual(response.json(), payload)self.assertEqual(props["surface"], "relay")self.assertIsNone(props["conversation_id"])@@ -12226,27 +12242,116 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)self.assertIn("Missing authorization header", response.json()["error"])+ @parameterized.expand(+ [+ ("cancel", 400, "No active session for this run", TaskRun.Status.IN_PROGRESS, 502, None),+ (+ "permission_response",+ 400,+ "No active session for this run",+ TaskRun.Status.IN_PROGRESS,+ 503,+ "agent_session_not_ready",+ ),+ ("permission_response", 404, "No active session for this run", TaskRun.Status.IN_PROGRESS, 502, None),+ ("permission_response", 400, "Invalid command", TaskRun.Status.IN_PROGRESS, 502, None),+ (+ "permission_response",+ 400,+ "No active session for this run",+ TaskRun.Status.COMPLETED,+ 409,+ "permission_target_ended",+ ),+ (+ "permission_response",+ 400,+ "No active session for this run",+ TaskRun.Status.FAILED,+ 409,+ "permission_target_ended",+ ),+ (+ "permission_response",+ 400,+ "No active session for this run",+ TaskRun.Status.CANCELLED,+ 409,+ "permission_target_ended",+ ),+ ]+ )@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")- def test_command_forwards_agent_server_no_session_error(self, mock_post):+ def test_command_forwards_agent_server_no_session_error(+ self, method, upstream_status, error, run_status, expected_status, code, mock_post+ ):reset_sandbox_jwt_key_cache()self._mock_agent_response(mock_post,- {"error": "No active session for this run"},- status_code=400,+ {"error": error},+ status_code=upstream_status,)task = self.create_task()run = self._create_run_with_sandbox(task)+ run.status = run_status+ run.save(update_fields=["status"])response = self.client.post(self._command_url(task, run),- self._make_cancel(),+ {"jsonrpc": "2.0", "method": method, "params": {"requestId": "perm-1", "optionId": "allow"}}+ if method == "permission_response"+ else self._make_cancel(),format="json",)- self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)- self.assertIn("No active session", response.json()["error"])+ self.assertEqual(response.status_code, expected_status)+ self.assertEqual(response.json().get("code"), code)+ if run.is_terminal:+ mock_post.assert_not_called()+ elif expected_status == 503:+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {"resolved": True}})+ retry = self.client.post(+ self._command_url(task, run),+ {"jsonrpc": "2.0", "method": method, "params": {"requestId": "perm-1", "optionId": "allow"}},+ format="json",+ )+ self.assertEqual(retry.status_code, 200)+ self.assertEqual(mock_post.call_count, 2)+ self.assertEqual(mock_post.call_args_list[0].args, mock_post.call_args_list[1].args)+ self.assertEqual(mock_post.call_args_list[0].kwargs["json"], mock_post.call_args_list[1].kwargs["json"])++ @parameterized.expand(+ [+ ("rejected", 400, {"error": "No active session for this run"}),+ ("accepted", 200, {"jsonrpc": "2.0", "result": {"resolved": True}}),+ ]+ )+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_permission_target_ends_during_delivery(self, _name, upstream_status, body, mock_post, mock_capture):+ reset_sandbox_jwt_key_cache()+ task = self._create_posthog_ai_task()+ run = self._create_run_with_sandbox(task)+ self._mock_agent_response(mock_post, body, status_code=upstream_status)++ def end_run(*args, **kwargs):+ TaskRun.objects.filter(id=run.id).update(status=TaskRun.Status.CANCELLED)+ return mock_post.return_value++ mock_post.side_effect = end_run+ response = self.client.post(+ self._command_url(task, run),+ {"jsonrpc": "2.0", "method": "permission_response", "params": {"requestId": "perm-1", "optionId": "allow"}},+ format="json",+ )+ self.assertEqual(response.status_code, 409)+ self.assertEqual(response.json()["code"], "permission_target_ended")+ self.assertEqual(mock_post.call_count, 1)+ calls = self._capture_calls_for_event(mock_capture, "permission_responded")+ self.assertFalse(calls[0].kwargs["properties"]["success"])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")@@ -12375,9 +12480,10 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):call_kwargs = mock_post.call_args[1]self.assertEqual(call_kwargs["json"]["id"], 42)+ @parameterized.expand([("cancel", 600), ("permission_response", 600)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")- def test_command_uses_600s_timeout(self, mock_post):+ def test_command_uses_command_timeout(self, method, timeout, mock_post):reset_sandbox_jwt_key_cache()self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})@@ -12386,12 +12492,14 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.client.post(self._command_url(task, run),- self._make_cancel(),+ {"jsonrpc": "2.0", "method": method, "params": {"requestId": "perm-1", "optionId": "allow"}}+ if method == "permission_response"+ else self._make_cancel(),format="json",)call_kwargs = mock_post.call_args[1]- self.assertEqual(call_kwargs["timeout"], 600)+ self.assertEqual(call_kwargs["timeout"], timeout)@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex a3a0b1e9f5a9..09207078f93f 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3802,7 +3802,7 @@ export interface TaskRunCommandRequestApi {}/**- * Error details on failure+ * JSON-RPC error details, including failures returned with HTTP 200*/export type TaskRunCommandResponseApiError = { [key: string]: unknown }@@ -3814,9 +3814,9 @@ export interface TaskRunCommandResponseApi {jsonrpc: string/** Request ID echoed back (string or number) */id?: unknown- /** Command result on success */+ /** Command result. Permission responses confirm acceptance only with resolved=true. */result?: unknown- /** Error details on failure */+ /** JSON-RPC error details, including failures returned with HTTP 200 */error?: TaskRunCommandResponseApiError}diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 5fe1089e431b..7f0e3337c6a6 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -2061,7 +2061,7 @@ export const getTasksRunsCommandCreateUrl = (projectId: string, taskId: string,}/**- * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations.+ * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Permission responses return 503 agent_session_not_ready only when rejected before execution; clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.* @summary Send command to task run*/export const tasksRunsCommandCreate = async (diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 13773b95cab5..ae79ff4af092 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -3101,7 +3101,7 @@ export const TasksRunsCancelCreateBody = /* @__PURE__ */ zod.object({})/**- * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations.+ * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Permission responses return 503 agent_session_not_ready only when rejected before execution; clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.* @summary Send command to task run*/export const TasksRunsCommandCreateBody = /* @__PURE__ */ zoddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a4032ba759e9..5c2c0019bf19 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -85972,7 +85972,7 @@ export namespace Schemas {}/**- * Error details on failure+ * JSON-RPC error details, including failures returned with HTTP 200*/export type TaskRunCommandResponseError = { [key: string]: unknown };@@ -85984,9 +85984,9 @@ export namespace Schemas {jsonrpc: string;/** Request ID echoed back (string or number) */id?: unknown;- /** Command result on success */+ /** Command result. Permission responses confirm acceptance only with resolved=true. */result?: unknown;- /** Error details on failure */+ /** JSON-RPC error details, including failures returned with HTTP 200 */error?: TaskRunCommandResponseError;}