: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): retry message submission during warm-run startup (#95958)
Georgiy Tarasov14c844b27667
diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex cfe027b85168..acef9a9a1f64 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -106,6 +106,10 @@ Pass `isTurnActive` + `onStop` to make the send button a **Stop** button while tthe input is empty (clicking cancels the run); with drafted text it stays **Send** and queues the follow-up.Omit both for a send-only composer.+Task creation and resumption keep the submitted draft and unsent context while a warm run starts.+Web retries confirmed startup failures for up to 20 seconds, then leaves the message available to+submit again.+### Custom layout via the `RunSurface` compound`RunSurface.Root` (Tier 1, `api/runSurface`) binds the stream logic and bootstraps the run; the slotsdiff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 9a88cfc322e6..6360c4573bf2 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'+import { ApiError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'@@ -295,7 +296,8 @@ describe('runInteractionLogic', () => {expect(tasksRunCreate).toHaveBeenCalledWith('997',TASK_ID,- expect.objectContaining({ initial_permission_mode: 'bypassPermissions' })+ expect.objectContaining({ initial_permission_mode: 'bypassPermissions' }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }))})@@ -370,14 +372,19 @@ describe('runInteractionLogic', () => {// No live-run signal for a finished run — it resumes into a new run instead.expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- expect(tasksRunCreate).toHaveBeenCalledWith('997', TASK_ID, {- runtime_adapter: 'claude',- model: 'claude-sonnet-5',- reasoning_effort: 'high',- initial_permission_mode: 'auto',- resume_from_run_id: RUN_ID,- pending_user_message: 'continue from here',- })+ expect(tasksRunCreate).toHaveBeenCalledWith(+ '997',+ TASK_ID,+ {+ runtime_adapter: 'claude',+ model: 'claude-sonnet-5',+ reasoning_effort: 'high',+ initial_permission_mode: 'auto',+ resume_from_run_id: RUN_ID,+ pending_user_message: 'continue from here',+ },+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )expect(onRunStarted).toHaveBeenCalledWith('run-2')expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()expect(toolEvents.values.applyBackTargetClaims['run-2']).toEqual([@@ -410,7 +417,8 @@ describe('runInteractionLogic', () => {expect(tasksRunCreate).toHaveBeenCalledWith('997',TASK_ID,- expect.objectContaining({ resume_from_run_id: RUN_ID })+ expect.objectContaining({ resume_from_run_id: RUN_ID }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }))})@@ -471,21 +479,136 @@ describe('runInteractionLogic', () => {expect(tasksRunCreate).toHaveBeenCalled()})- it('keeps the draft and toasts when starting a new run fails', async () => {- ;(tasksRunCreate as jest.Mock).mockRejectedValue(new Error('boom'))+ test.each([+ [new Error('boom'), 'Failed to start a new run. Please try again.'],+ [+ new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable' }),+ "Couldn't start this run yet. Please try again.",+ ],+ ])('keeps the draft and unsent context when starting a run fails with %s', async (error, message) => {+ let rejectSend!: (error: unknown) => void+ ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(+ new Promise((_, reject) => {+ rejectSend = reject+ })+ )+ attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' }])setStatus('completed')logic.actions.setComposerFormValues({ draft: 'continue from here' })+ logic.actions.submitComposerForm()++ expect(logic.values.startingRun).toBe(true)+ expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()await expectLogic(logic, () => {- logic.actions.submitComposerForm()+ rejectSend(error)}).toFinishAllListeners()- expect(lemonToast.error).toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith(message)expect(onRunStarted).not.toHaveBeenCalled()+ expect(logic.values.startingRun).toBe(false)expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(logic.values.pendingContextItems).toEqual([{ type: 'insight', key: 'sig', label: 'Signups' }])expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()++ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()++ expect(tasksRunCreate).toHaveBeenCalledTimes(2)+ expect((tasksRunCreate as jest.Mock).mock.calls[1].slice(0, 3)).toEqual(+ (tasksRunCreate as jest.Mock).mock.calls[0].slice(0, 3)+ )+ expect(onRunStarted).toHaveBeenCalledWith('run-2')+ expect(logic.values.composerForm.draft).toBe('')+ expect(logic.values.startingRun).toBe(false)+ expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toEqual(['insight:sig'])})+ test.each(['recovered', 'exhausted', 'timeout', 'unmounted'])(+ 'keeps a resumed submission pending through bounded frontend retries: %s',+ async (outcome) => {+ jest.useFakeTimers()+ const error = new ApiError('starting', 503, undefined, {+ code: 'warm_run_activation_unavailable',+ retry_token: 'synthetic-retry-token',+ })+ let rejectFirst!: (error: unknown) => void+ let resolveRetry!: (value: unknown) => void+ let rejectRetry!: (error: unknown) => void+ ;(tasksRunCreate as jest.Mock)+ .mockReturnValueOnce(new Promise((_, reject) => (rejectFirst = reject)))+ .mockRejectedValueOnce(error)+ .mockRejectedValueOnce(error)+ .mockReturnValueOnce(+ new Promise((resolve, reject) => {+ resolveRetry = resolve+ rejectRetry = reject+ })+ )+ try {+ attachedContextLogic().actions.registerContext('scene', [+ { type: 'insight', key: 'sig', label: 'Signups' },+ ])+ setStatus('completed')+ logic.actions.setComposerFormValues({ draft: 'continue from here' })+ logic.actions.submitComposerForm()+ await jest.advanceTimersByTimeAsync(10_000)+ rejectFirst(error)+ await jest.advanceTimersByTimeAsync(1750)+ expect(tasksRunCreate).toHaveBeenCalledTimes(4)+ const calls = (tasksRunCreate as jest.Mock).mock.calls+ for (const call of calls.slice(1)) {+ expect(call.slice(0, 3)).toEqual(calls[0].slice(0, 3))+ expect(call[3].headers).toEqual({ 'X-PostHog-Warm-Retry': 'synthetic-retry-token' })+ }+ expect(logic.values.startingRun).toBe(true)+ expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()+ logic.actions.submitComposerForm()+ expect(tasksRunCreate).toHaveBeenCalledTimes(4)+ if (outcome === 'unmounted') {+ logic.unmount()+ resolveRetry({ latest_run: { id: 'warm-run' } })+ await jest.advanceTimersByTimeAsync(10_000)+ expect(calls[1][3].signal.aborted).toBe(true)+ expect(onRunStarted).not.toHaveBeenCalled()+ return+ }+ await jest.advanceTimersByTimeAsync(8_249)+ expect(logic.values.startingRun).toBe(true)+ await expectLogic(logic, async () => {+ if (outcome === 'recovered') {+ resolveRetry({ latest_run: { id: 'warm-run' } })+ } else if (outcome === 'exhausted') {+ rejectRetry(+ new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable' })+ )+ } else {+ await jest.advanceTimersByTimeAsync(1)+ }+ }).toFinishAllListeners()+ expect(tasksRunCreate).toHaveBeenCalledTimes(4)+ expect(logic.values.startingRun).toBe(false)+ if (outcome === 'recovered') {+ expect(onRunStarted).toHaveBeenCalledWith('warm-run')+ expect(logic.values.composerForm.draft).toBe('')+ } else {+ expect(onRunStarted).not.toHaveBeenCalled()+ expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(logic.values.pendingContextItems).toEqual([+ { type: 'insight', key: 'sig', label: 'Signups' },+ ])+ expect(lemonToast.error).toHaveBeenCalledWith("Couldn't start this run yet. Please try again.")+ resolveRetry({ latest_run: { id: 'late-run' } })+ await jest.advanceTimersByTimeAsync(0)+ expect(onRunStarted).not.toHaveBeenCalled()+ }+ } finally {+ jest.useRealTimers()+ }+ }+ )+it('wraps outgoing content with the attached-context block while echoing the raw text, and dedupes per task', async () => {attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' },diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex abf5db483fc6..8943f1f4d221 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reduimport { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { ApiError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'@@ -32,6 +33,7 @@ import {import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'import type { PermissionRequestRecord } from '../types/streamTypes'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'+import { submitWithWarmRunRetry } from '../utils/warmRunSubmission'import { attachedContextLogic } from './attachedContextLogic'import { modelCatalogueLogic } from './modelCatalogueLogic'import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'@@ -712,7 +714,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([],}),- listeners(({ actions, values, props }) => {+ listeners(({ actions, values, props, cache }) => {const noteTerminalDraft = (): void => {// Consent gates warming as it gates sending: a warm boots a cloud sandbox and restores// the task's repository snapshot, so typing must not start one before the organization@@ -876,6 +878,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([const streamKey = props.streamKey ?? props.runIdlet claimedStreamKey = streamKeyconst pendingContext = values.pendingContextItems+ const disposables = cache.disposables+ const projectId = String(values.currentProjectId)actions.claimApplyBackTargets(streamKey)try {// Same endpoint as the "Run again" button, but seeded with the user's message and chained@@ -893,7 +897,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([})actions.consumeWarm()- const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)+ const result = await submitWithWarmRunRetry(+ (options) => tasksRunCreate(projectId, props.taskId, createRequest, options),+ disposables+ )actions.resetComposerForm()markPendingContextSent(pendingContext)const latestRunId = result.latest_run?.id@@ -904,11 +911,20 @@ export const runInteractionLogic = kea<runInteractionLogicType>([} else {actions.releaseApplyBackTargets(streamKey)}- } catch {+ } catch (error) {+ if (disposables.isDisposed) {+ return+ }actions.releaseApplyBackTargets(claimedStreamKey)- lemonToast.error('Failed to start a new run. Please try again.')+ lemonToast.error(+ error instanceof ApiError && error.code === 'warm_run_activation_unavailable'+ ? "Couldn't start this run yet. Please try again."+ : 'Failed to start a new run. Please try again.'+ )} finally {- actions.setStartingRun(false)+ if (!disposables.isDisposed) {+ actions.setStartingRun(false)+ }}},diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 84d46a685cd3..dc55842c2d21 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -1,6 +1,7 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { useMocks } from '~/mocks/jest'@@ -166,6 +167,101 @@ describe('taskTrackerSceneLogic', () => {expect(logic.values.activeCreation?.runId).toBe('warm-run-1')})+ test.each([false, true])(+ 'keeps loading, the draft, and unsent context until warm activation succeeds (automatic retry: %s)',+ async (automaticRetry) => {+ const requests: { body: Record<string, unknown>; token: string | null }[] = []+ let finishActivation!: () => void+ let requestStarted!: () => void+ const started = new Promise<void>((resolve) => {+ requestStarted = resolve+ })+ const response = new Promise<void>((resolve) => {+ finishActivation = resolve+ })+ useMocks({+ post: {+ '/api/projects/:team/tasks/': async ({ request }) => {+ createBody = (await request.json()) as Record<string, unknown>+ requests.push({ body: createBody, token: request.headers.get('X-PostHog-Warm-Retry') })+ if (automaticRetry && requests.length === 4) {+ return [201, { id: 'warm-task', latest_run: { id: 'warm-run' } }]+ }+ requestStarted()+ await response+ return [+ 503,+ {+ code: 'warm_run_activation_unavailable',+ ...(automaticRetry ? { retry_token: 'synthetic-retry-token' } : {}),+ error: "Couldn't start this run yet. Please try again.",+ },+ ]+ },+ },+ })+ const toast = jest.spyOn(lemonToast, 'error')+ logic.mount()+ attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' }])+ logic.actions.setNewTaskData({ description: 'Inspect the example chart' })+ logic.actions.submitNewTask()+ await started++ expect(logic.values.isSubmittingTask).toBe(true)+ expect(logic.values.activeCreation).not.toBeNull()+ expect(logic.values.newTaskData.description).toBe('Inspect the example chart')+ expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({})+ logic.actions.submitNewTask()+ const firstBody = createBody++ jest.useFakeTimers({ advanceTimers: true })+ try {+ await expectLogic(logic, finishActivation).toFinishAllListeners()+ } finally {+ jest.useRealTimers()+ }++ if (automaticRetry) {+ expect(requests).toEqual([+ { body: firstBody, token: null },+ ...Array.from({ length: 3 }, () => ({ body: firstBody, token: 'synthetic-retry-token' })),+ ])+ expect(runBody).toBeNull()+ expect(logic.values.activeCreation?.runId).toBe('warm-run')+ expect(logic.values.isSubmittingTask).toBe(false)+ expect(logic.values.newTaskData.description).toBe('')+ expect(attachedContextLogic().values.sentContextKeysByTask['warm-task']).toEqual(['insight:sig'])+ expect(toast).not.toHaveBeenCalled()+ toast.mockRestore()+ return+ }++ expect(logic.values.isSubmittingTask).toBe(false)+ expect(logic.values.activeCreation).toBeNull()+ expect(logic.values.newTaskData.description).toBe('Inspect the example chart')+ expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({})+ expect(toast).toHaveBeenCalledWith("Couldn't start this run yet. Please try again.")++ useMocks({+ post: {+ '/api/projects/:team/tasks/': async ({ request }) => {+ createBody = (await request.json()) as Record<string, unknown>+ return [201, { id: 'warm-task', latest_run: { id: 'warm-run' } }]+ },+ },+ })+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()++ expect(createBody).toEqual(firstBody)+ expect(runBody).toBeNull()+ expect(logic.values.activeCreation?.runId).toBe('warm-run')+ expect(logic.values.isSubmittingTask).toBe(false)+ expect(logic.values.newTaskData.description).toBe('')+ expect(attachedContextLogic().values.sentContextKeysByTask['warm-task']).toEqual(['insight:sig'])+ toast.mockRestore()+ }+ )+// The seeded first message wraps the on-screen context, and the wrapped non-text refs must be marked// sent under the created task's id — otherwise the run's first follow-up (sent via// `runInteractionLogic`, which prunes against the task-scoped store) re-wraps the same refs.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 6838b2433089..905abfb95024 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -4,6 +4,7 @@ import { router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'+import { ApiError } from 'lib/api-error'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { uuid } from 'lib/utils/dom'import { projectLogic } from 'scenes/projectLogic'@@ -50,6 +51,7 @@ import {} from '../../utils/composerModels'import { DEFAULT_COMPOSER_MODE, type PermissionMode } from '../../utils/composerModes'import { wrapWithPosthogContext } from '../../utils/posthogContextBlock'+import { submitWithWarmRunRetry } from '../../utils/warmRunSubmission'export type { ActiveCreation } from '../../logics/runnerPanelLogic'@@ -704,6 +706,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}},submitNewTask: async () => {+ if (cache.submittingTask && !cache.submittingTask.isDisposed) {+ return+ }if (!values.dataProcessingAccepted) {actions.blockOnConsent()return@@ -720,6 +725,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([actions.submitNewTaskFailure('Project is required')return}+ const disposables = cache.disposables+ cache.submittingTask = disposables// Optimistically open the thread on send: a `runStreamLogic` keyed by a client `streamKey`, seeded// with the typed message + provisioning indicator, rendered by the pending `RunSurface` (the@@ -788,7 +795,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}const projectId = String(values.currentProjectId)- const newTask = await tasksCreate(projectId, taskData)+ const newTask = await submitWithWarmRunRetry(+ (options) => tasksCreate(projectId, taskData, options),+ disposables+ )// Whatever happened, this submit owns the warm now: drop the lease without cancelling it,// since the Run it points at is the one the create just activated.actions.consumeWarm()@@ -802,7 +812,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// and launches with the picked model / reasoning effort (clamped to one the model supports).let runId = newTask.latest_run?.idif (!runId) {- const runResponse = await tasksRunCreate(projectId, newTask.id, runRequest)+ const runResponse = await submitWithWarmRunRetry(+ (options) => tasksRunCreate(projectId, newTask.id, runRequest, options),+ disposables+ )runId = runResponse.latest_run?.id}@@ -826,15 +839,25 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// Reset before signaling success: the success listener applies any seed held during this// submission, and resetting afterwards would wipe that seed's prefill.actions.resetNewTaskData()+ cache.submittingTask = nullactions.submitNewTaskSuccess()actions.loadTasks(values.taskListParams)actions.loadRepositories()} catch (error) {+ if (disposables.isDisposed) {+ return+ }actions.releaseApplyBackTargets(streamKey)- // Return to the composer with the typed text intact, and no toast: the composer is- // still on screen, so a failure banner over it reads as a dead end.actions.clearActiveCreation()+ if (error instanceof ApiError && error.code === 'warm_run_activation_unavailable') {+ lemonToast.error("Couldn't start this run yet. Please try again.")+ }+ cache.submittingTask = nullactions.submitNewTaskFailure(error instanceof Error ? error.message : 'Unknown error')+ } finally {+ if (cache.submittingTask === disposables) {+ cache.submittingTask = null+ }}},openExistingTask: ({ task }) => {diff --git a/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts b/products/posthog_ai/frontend/utils/warmRunSubmission.test.tsnew file mode 100644index 000000000000..042bc77856bf--- /dev/null+++ b/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts@@ -0,0 +1,148 @@+import { kea, path, resetContext } from 'kea'++import { ApiError } from 'lib/api-error'++import { DisposablesManager, disposablesPlugin } from '~/kea-disposables'++import { submitWithWarmRunRetry } from './warmRunSubmission'++const starting = (token = 'synthetic-retry-token'): ApiError =>+ new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable', retry_token: token })++describe('submitWithWarmRunRetry', () => {+ let logic: ReturnType<typeof kea>+ let disposables: DisposablesManager++ beforeEach(() => {+ jest.useFakeTimers()+ resetContext({ plugins: [disposablesPlugin] })+ logic = kea([path(['test', 'warmRunSubmission'])])+ logic.mount()+ disposables = logic.cache.disposables+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ jest.useRealTimers()+ })++ it('backs off sequentially with the first token, including while the tab is hidden', async () => {+ let complete!: (value: string) => void+ const send = jest+ .fn()+ .mockRejectedValueOnce(starting())+ .mockRejectedValueOnce(starting('another-token'))+ .mockRejectedValueOnce(starting('another-token'))+ .mockReturnValueOnce(new Promise<string>((resolve) => (complete = resolve)))+ const result = submitWithWarmRunRetry(send, disposables)+ await jest.advanceTimersByTimeAsync(249)+ expect(send).toHaveBeenCalledTimes(1)+ await jest.advanceTimersByTimeAsync(1)+ expect(send).toHaveBeenCalledTimes(2)+ jest.spyOn(document, 'hidden', 'get').mockReturnValue(true)+ document.dispatchEvent(new Event('visibilitychange'))+ await jest.advanceTimersByTimeAsync(499)+ expect(send).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(1)+ expect(send).toHaveBeenCalledTimes(3)+ await jest.advanceTimersByTimeAsync(999)+ expect(send).toHaveBeenCalledTimes(3)+ await jest.advanceTimersByTimeAsync(1)+ expect(send).toHaveBeenCalledTimes(4)+ await jest.advanceTimersByTimeAsync(1000)+ expect(send).toHaveBeenCalledTimes(4)+ expect(send.mock.calls[0][0].headers).toBeUndefined()+ for (const [options] of send.mock.calls.slice(1)) {+ expect(options.headers).toEqual({ 'X-PostHog-Warm-Retry': 'synthetic-retry-token' })+ expect(options.signal).toBe(send.mock.calls[0][0].signal)+ }+ complete('accepted')+ await expect(result).resolves.toBe('accepted')+ expect(disposables.registry.size).toBe(0)+ expect(jest.getTimerCount()).toBe(0)+ })++ test.each([+ new Error('network failure'),+ new DOMException('request timed out', 'TimeoutError'),+ new ApiError('unavailable', 503),+ new ApiError('unavailable', 500, undefined, { code: 'warm_run_activation_unavailable', retry_token: 'token' }),+ new ApiError('unavailable', 503, undefined, { code: 'another_error', retry_token: 'token' }),+ starting(''),+ starting(' '),+ new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable', retry_token: 1 }),+ ])('stops without retrying an unconfirmed failure: %s', async (error) => {+ const send = jest.fn().mockRejectedValueOnce(starting()).mockRejectedValueOnce(error)+ const result = submitWithWarmRunRetry(send, disposables)+ const rejected = result.catch((error) => error)+ await jest.advanceTimersByTimeAsync(20_000)+ await expect(rejected).resolves.toBe(error)+ expect(send).toHaveBeenCalledTimes(2)+ expect(disposables.registry.size).toBe(0)+ })++ test.each(['backoff', 'request'])(+ 'expires at 20 seconds during %s, counting the initial request',+ async (phase) => {+ const error = starting()+ let rejectInitial!: (error: Error) => void+ let complete!: (value: string) => void+ const send = jest.fn().mockReturnValueOnce(new Promise((_, reject) => (rejectInitial = reject)))+ if (phase === 'backoff') {+ send.mockRejectedValue(error)+ } else {+ send.mockReturnValue(new Promise<string>((resolve) => (complete = resolve)))+ }+ const result = submitWithWarmRunRetry(send, disposables)+ const rejected = result.catch((error) => error)+ await jest.advanceTimersByTimeAsync(10_000)+ rejectInitial(error)+ await jest.advanceTimersByTimeAsync(9_999)+ expect(send.mock.calls[0][0].signal.aborted).toBe(false)+ const attempts = send.mock.calls.length+ await jest.advanceTimersByTimeAsync(1)+ await expect(rejected).resolves.toBe(error)+ expect(send.mock.calls[0][0].signal.aborted).toBe(true)+ complete?.('late acceptance')+ await jest.advanceTimersByTimeAsync(20_000)+ expect(send).toHaveBeenCalledTimes(attempts)+ expect(disposables.registry.size).toBe(0)+ expect(jest.getTimerCount()).toBe(0)+ }+ )++ test.each(['initial request', 'backoff', 'retry request'])('cancels on unmount during %s', async (phase) => {+ let complete!: (value: string) => void+ const pending = new Promise<string>((resolve) => (complete = resolve))+ const send = jest.fn().mockReturnValue(pending)+ if (phase !== 'initial request') {+ send.mockRejectedValueOnce(starting())+ }+ const result = submitWithWarmRunRetry(send, disposables)+ const rejected = result.catch((error) => error)+ await jest.advanceTimersByTimeAsync(phase === 'retry request' ? 250 : 0)+ logic.unmount()+ await expect(rejected).resolves.toMatchObject({ name: 'AbortError' })+ const attempts = send.mock.calls.length+ logic.mount()+ complete('obsolete acceptance')+ await jest.advanceTimersByTimeAsync(20_000)+ expect(send).toHaveBeenCalledTimes(attempts)+ expect(send.mock.calls[0][0].signal.aborted).toBe(true)+ expect(disposables.registry.size).toBe(0)+ await expect(submitWithWarmRunRetry(send, disposables)).rejects.toMatchObject({ name: 'AbortError' })+ expect(send).toHaveBeenCalledTimes(attempts)+ })++ it('does not impose the warm deadline on an ordinary cold submission', async () => {+ let complete!: (value: string) => void+ const send = jest.fn().mockReturnValue(new Promise<string>((resolve) => (complete = resolve)))+ const result = submitWithWarmRunRetry(send, disposables)+ await jest.advanceTimersByTimeAsync(30_000)+ expect(send.mock.calls[0][0].signal.aborted).toBe(false)+ complete('cold acceptance')+ await expect(result).resolves.toBe('cold acceptance')+ expect(send).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/posthog_ai/frontend/utils/warmRunSubmission.ts b/products/posthog_ai/frontend/utils/warmRunSubmission.tsnew file mode 100644index 000000000000..cbc473c04994--- /dev/null+++ b/products/posthog_ai/frontend/utils/warmRunSubmission.ts@@ -0,0 +1,115 @@+import { ApiError } from 'lib/api-error'+import { uuid } from 'lib/utils/dom'++import type { DisposablesManager } from '~/kea-disposables'++async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {+ let abort = (): void => {}+ try {+ return await new Promise((resolve, reject) => {+ abort = (): void => reject(signal.reason)+ signal.addEventListener('abort', abort, { once: true })+ if (signal.aborted) {+ abort()+ }+ promise.then(resolve, reject)+ })+ } finally {+ signal.removeEventListener('abort', abort)+ }+}++export async function submitWithWarmRunRetry<T>(+ send: (options: RequestInit) => Promise<T>,+ disposables: DisposablesManager+): Promise<T> {+ if (disposables.isDisposed) {+ throw new DOMException('Submission cancelled', 'AbortError')+ }+ const controller = new AbortController()+ const key = `warm-submission:${uuid()}`+ const deadlineKey = `${key}:deadline`+ const delayKey = `${key}:delay`+ const deadline = performance.now() + 20_000+ let retryToken: string | undefined+ let retryError: ApiError | undefined+ let delay = 250+ disposables.add(() => () => controller.abort(), key, { pauseOnPageHidden: false })+ try {+ while (true) {+ if (controller.signal.aborted) {+ throw controller.signal.reason+ }+ if (retryError && performance.now() >= deadline) {+ throw retryError+ }+ try {+ const result = await abortable(+ send({+ signal: controller.signal,+ ...(retryToken ? { headers: { 'X-PostHog-Warm-Retry': retryToken } } : {}),+ }),+ controller.signal+ )+ if (controller.signal.aborted) {+ throw controller.signal.reason+ }+ if (retryError && performance.now() >= deadline) {+ throw retryError+ }+ return result+ } catch (error) {+ const token = error instanceof ApiError ? error.data?.retry_token : undefined+ if (+ controller.signal.aborted ||+ !(error instanceof ApiError) ||+ error.status !== 503 ||+ error.code !== 'warm_run_activation_unavailable' ||+ typeof token !== 'string' ||+ !token.trim()+ ) {+ throw error+ }+ const remaining = deadline - performance.now()+ if (remaining <= 0) {+ throw error+ }+ retryError = error+ if (!retryToken) {+ // Only the server can confirm nondelivery and pin a create retry to the original run.+ retryToken = token+ disposables.add(+ () => {+ const timer = setTimeout(() => controller.abort(retryError), remaining)+ return () => clearTimeout(timer)+ },+ deadlineKey,+ { pauseOnPageHidden: false }+ )+ }+ }+ try {+ await abortable(+ new Promise<void>((resolve) => {+ disposables.add(+ () => {+ const timer = setTimeout(resolve, Math.min(delay, deadline - performance.now()))+ return () => clearTimeout(timer)+ },+ delayKey,+ { pauseOnPageHidden: false }+ )+ }),+ controller.signal+ )+ } finally {+ disposables.dispose(delayKey)+ }+ delay = Math.min(delay * 2, 1000)+ }+ } finally {+ disposables.dispose(deadlineKey)+ disposables.dispose(delayKey)+ disposables.dispose(key)+ }+}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 77f96c76b8ea..571c31bfe64d 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -12,6 +12,7 @@ from urllib.parse import urlparsefrom uuid import UUID, uuid4from django.conf import settings+from django.core import signingfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import IntegrityError, transactionfrom django.db.models import (@@ -166,6 +167,7 @@ __all__ = ["TaskRuntime","TaskRunEnvironment","TaskRunStatus",+ "WarmRunActivationUnavailable","append_task_run_log","apply_task_run_model_config","ensure_task_run_session",@@ -3933,6 +3935,8 @@ def signal_task_run_user_message(message_id: str | None = None,actor_slack_user_id: str | None = None,steer: bool = False,+ rpc_timeout: timedelta | None = None,+ workflow_id: str | None = None,) -> bool | None:"""Queue a user_message follow-up signal on the run's workflow.@@ -3961,13 +3965,14 @@ def signal_task_run_user_message(try:context = {"actor_slack_user_id": actor_slack_user_id} if actor_slack_user_id else Nonesignal_task_followup_message(- run.workflow_id,+ workflow_id or run.workflow_id,content,artifact_ids,message_id,actor_user_id,context,steer=steer,+ **({"rpc_timeout": rpc_timeout} if rpc_timeout is not None else {}),)except RPCError as e:if e.status == RPCStatusCode.NOT_FOUND:@@ -5708,6 +5713,7 @@ def create_task(validated_data: dict,client_provenance: TaskClientProvenance | None = None,code_access_allowed: bool = False,+ warm_retry_token: str | None = None,) -> contracts.TaskDetailDTO:"""Create a task, mirroring ``TaskSerializer.create`` byte-for-byte.@@ -5835,6 +5841,7 @@ def create_task()warm_run = Noneif warm_run is not None:+ _warm_retry_message_id(warm_retry_token, warm_run)warm_task = warm_run.taskshould_set_client_provenance = warm_task.client_provenance is None and client_provenance is not Noneif should_set_client_provenance:@@ -5878,9 +5885,13 @@ def create_task(artifact_ids=pending_user_artifact_ids,auto_publish=warm_auto_publish,reasoning_effort=warm_reasoning_effort,+ retry_token=warm_retry_token,)return _task_detail_to_dto(_task_detail_queryset().get(pk=warm_task.pk))+ if warm_retry_token is not None:+ raise WarmRunActivationUnavailable("target_unavailable")+# The relationship the client asserted (validated by the serializer, which rejects `research`).# Popped so it isn't forwarded to the model; the link itself is recorded by record_report_task below.signal_report_task_relationship = validated_data.pop("signal_report_task_relationship", None)@@ -6525,6 +6536,112 @@ def _attach_staged_artifacts_to_run()+class WarmRunActivationUnavailable(Exception):+ code = "warm_run_activation_unavailable"++ def __init__(self, reason: str) -> None:+ self.reason = reason+ self.retry_token: str | None = None+ super().__init__("Couldn't start this run yet. Please try again.")+++def _warm_retry_message_id(token: str | None, run: TaskRun) -> str | None:+ if token is None:+ return None+ try:+ run_id, workflow_id, message_id = signing.TimestampSigner(salt="warm-run-activation").unsign_object(+ token, max_age=60+ )+ except (signing.BadSignature, ValueError) as error:+ raise WarmRunActivationUnavailable("invalid_retry") from error+ if run_id != str(run.id) or workflow_id != run.workflow_id:+ raise WarmRunActivationUnavailable("target_unavailable")+ return str(message_id)+++def _deliver_warm_run_message(+ run: TaskRun, *, message: str | None, artifact_ids: list[str], message_id: str | None = None+) -> None:+ from temporalio.service import RPCError, RPCStatusCode++ started_at = time.monotonic()+ workflow_id = run.workflow_id+ frontend_retry = message_id is not None+ message_id = message_id or str(uuid4())+ eligible_runs = TaskRun.objects.filter(+ id=run.id,+ team_id=run.team_id,+ task_id=run.task_id,+ task__deleted=False,+ state__await_user_message=True,+ ).exclude(status__in=_TERMINAL_TASK_RUN_STATUSES)++ try:+ current_run = eligible_runs.first()+ if current_run is None or current_run.workflow_id != workflow_id:+ raise WarmRunActivationUnavailable("target_unavailable")+ try:+ delivered = signal_task_run_user_message(+ run.id,+ run.task_id,+ run.team_id,+ content=message,+ artifact_ids=artifact_ids,+ message_id=message_id,+ workflow_id=workflow_id,+ rpc_timeout=timedelta(seconds=10),+ )+ except RPCError as error:+ # NOT_FOUND proves the workflow did not receive this message. Other errors may follow delivery.+ if error.status != RPCStatusCode.NOT_FOUND:+ raise+ current_run = eligible_runs.first()+ if current_run is None or current_run.workflow_id != workflow_id:+ raise WarmRunActivationUnavailable("target_unavailable") from error+ unavailable = WarmRunActivationUnavailable("starting")+ unavailable.retry_token = signing.TimestampSigner(salt="warm-run-activation").sign_object(+ [str(run.id), workflow_id, message_id]+ )+ raise unavailable from error+ if delivered is not True:+ raise WarmRunActivationUnavailable("delivery_failed")++ with transaction.atomic():+ activated_run = eligible_runs.select_for_update(of=("self",)).first()+ if activated_run is None or activated_run.workflow_id != workflow_id:+ raise WarmRunActivationUnavailable("target_unavailable")+ activated_run.state.pop("await_user_message", None)+ activated_run.state["warm_activated"] = True+ activated_run.save(update_fields=["state", "updated_at"])+ except WarmRunActivationUnavailable as error:+ log = logger.info if error.retry_token else logger.warning+ log(+ "task_warm_activation_unavailable",+ extra={+ "run_id": str(run.id),+ "task_id": str(run.task_id),+ "team_id": run.team_id,+ "workflow_id": workflow_id,+ "elapsed_seconds": time.monotonic() - started_at,+ "reason": error.reason,+ "frontend_retry": frontend_retry,+ },+ )+ raise+ if frontend_retry:+ logger.info(+ "task_warm_activation_recovered",+ extra={+ "run_id": str(run.id),+ "task_id": str(run.task_id),+ "team_id": run.team_id,+ "workflow_id": workflow_id,+ "elapsed_seconds": time.monotonic() - started_at,+ "frontend_retry": frontend_retry,+ },+ )++def _activate_warm_run(run: TaskRun,task: Task,@@ -6535,6 +6652,7 @@ def _activate_warm_run(description: str | None = None,auto_publish: bool | None = None,reasoning_effort: str | None = None,+ retry_token: str | None = None,) -> None:"""Activate an idling warm Run: set the draft Task's visible description from raw task text,forward the first message to the already-running agent, and drop the ``await_user_message`` marker@@ -6551,11 +6669,7 @@ def _activate_warm_run(if description and not (task.description or "").strip():task.description = descriptiontask.save(update_fields=["description", "updated_at"])- # Claims the Run as activated before the signal goes out. `await_user_message` can only be cleared- # after the signal — clearing it first would drop a Run out of the warm pool that a failed signal- # never activated, stranding its sandbox. That leaves a window where the Run is being activated but- # still looks idle, so this marker is what the unused-warm metric reads to tell the two apart.- activation_state_updates: dict[str, object] = {"warm_activated": True}+ activation_state_updates: dict[str, object] = {}if auto_publish is not None:# Before the signal: the agent-server re-reads run state when the forwarded# first message arrives, so the choice must already be persisted by then.@@ -6567,8 +6681,9 @@ def _activate_warm_run(updates=activation_state_updates,remove_keys=["reasoning_effort"] if reasoning_effort is None else None,)- signal_task_run_user_message(run.id, task.id, team_id, content=message, artifact_ids=artifact_ids)- TaskRun.update_state_atomic(run.id, remove_keys=["await_user_message"])+ _deliver_warm_run_message(+ run, message=message, artifact_ids=artifact_ids, message_id=_warm_retry_message_id(retry_token, run)+ )# Only count activations of Runs that actually carry the prewarmed marker, so the activation# numerator stays consistent with the workflow_start{prewarmed="true"} denominator — otherwise# warm Runs provisioned before this ships (await_user_message set, prewarmed absent) would push@@ -6914,7 +7029,12 @@ def warm_task_resume_sandbox(def run_task(- task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict+ task_id: str | UUID,+ team_id: int,+ user_id: int | None,+ *,+ validated_data: dict,+ warm_retry_token: str | None = None,) -> contracts.TaskRunResult | None:"""Create a run for a task and kick off its workflow, mirroring ``TaskViewSet.run``.@@ -6925,7 +7045,10 @@ def run_task(from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product read kept off the api import pathenforce_report_implementation_rerun_cap,)- from products.tasks.backend.logic.services.staged_artifacts import get_task_staged_artifacts # noqa: PLC0415+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415+ get_task_run_artifacts_by_id,+ get_task_staged_artifacts,+ )from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import pathPrAuthorshipMode,RunSource,@@ -7001,6 +7124,7 @@ def run_task(warm_run = _idling_warm_run_for_task(task)if warm_run is not None:+ _warm_retry_message_id(warm_retry_token, warm_run)warm_state = warm_run.state or {}# Both directions. A request that states no resume source must not be handed a successor# warmed to resume an earlier run — its filesystem was restored from that run's snapshot, so@@ -7069,6 +7193,9 @@ def run_task(if pending_user_artifact_idselse ([], []))+ if warm_missing_artifact_ids:+ # A previous activation attempt may have moved these out of staging before delivery failed.+ _, warm_missing_artifact_ids = get_task_run_artifacts_by_id(warm_run, warm_missing_artifact_ids)if not warm_missing_artifact_ids:if warm_staged_artifacts:_attach_staged_artifacts_to_run(@@ -7086,8 +7213,11 @@ def run_task(artifact_ids=pending_user_artifact_ids,auto_publish=validated_data.get("auto_publish"),reasoning_effort=validated_data.get("reasoning_effort"),+ retry_token=warm_retry_token,)return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id))+ if warm_retry_token is not None:+ raise WarmRunActivationUnavailable("target_unavailable")sandbox_environment_id = validated_data.get("sandbox_environment_id")sandbox_environment_id_supplied_by_user = sandbox_environment_id is not Nonecustom_image_id = validated_data.get("custom_image_id")diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex b73698f1197e..3eb9d2f83053 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1029,6 +1029,10 @@ class TaskRunErrorResponseSerializer(serializers.Serializer):error = serializers.CharField(required=False, help_text="Human-readable error message")type = serializers.CharField(required=False, help_text="Machine-readable error type")code = serializers.CharField(required=False, help_text="Machine-readable error code")+ retry_token = serializers.CharField(+ required=False,+ help_text="After confirmed warm startup nondelivery, echo this token in X-PostHog-Warm-Retry to retry the same run and message within 60 seconds.",+ )reason = serializers.ChoiceField(choices=DESKTOP_ACCESS_REASON_CHOICES,required=False,diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 695208cc17e7..6d32d4e23106 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -613,6 +613,14 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(request=TaskCreateSerializer,+ parameters=[+ OpenApiParameter(+ "X-PostHog-Warm-Retry",+ str,+ OpenApiParameter.HEADER,+ description="Retry token from a warm_run_activation_unavailable response; prevents creating a replacement run.",+ )+ ],responses={201: TaskSerializer,403: OpenApiResponse(@@ -628,7 +636,11 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):),503: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="PostHog Desktop access could not be verified",+ description=(+ "PostHog Desktop access could not be verified, or warm run activation is unavailable "+ "(code `warm_run_activation_unavailable`). After confirmed nondelivery, a retry_token permits "+ "retrying the same run and message with X-PostHog-Warm-Retry. Web retries for up to 20 seconds."+ ),),},)@@ -681,14 +693,33 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):validated_data=validated_data,client_provenance=get_task_client_provenance(request),code_access_allowed=code_access_allowed,+ **(+ {"warm_retry_token": request.headers["X-PostHog-Warm-Retry"]}+ if "X-PostHog-Warm-Retry" in request.headers+ else {}+ ),)except ComputeBillingLimitExceeded as error:return compute_quota_limit_response(error.reason)except ReportTaskCapExceeded as error:return self._report_task_cap_response(error.detail)+ except tasks_facade.WarmRunActivationUnavailable as error:+ return self._warm_activation_unavailable_response(error)self._forward_signals_discussion_note(request, task, relationship, discussion_question)return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)+ def _warm_activation_unavailable_response(self, error: tasks_facade.WarmRunActivationUnavailable) -> Response:+ return Response(+ TaskRunErrorResponseSerializer(+ {+ "code": error.code,+ "error": str(error),+ **({"retry_token": error.retry_token} if error.retry_token else {}),+ }+ ).data,+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+def _one_shot_analysis_response(self, task_id: str) -> Response | None:"""Refuse to add runs to a server-created analysis task; see the facade reader."""if not tasks_facade.task_is_one_shot_analysis(task_id, self.team_id):@@ -1089,7 +1120,17 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = TaskStagedArtifactsFinalizeUploadResponseSerializer({"artifacts": result.artifacts})return Response(serializer.data)- @extend_schema(request=TaskRunCreateRequestSchemaSerializer)+ @extend_schema(+ request=TaskRunCreateRequestSchemaSerializer,+ parameters=[+ OpenApiParameter(+ "X-PostHog-Warm-Retry",+ str,+ OpenApiParameter.HEADER,+ description="Retry token from a warm_run_activation_unavailable response; prevents creating a replacement run.",+ )+ ],+ )@validated_request(request_serializer=TaskRunCreateRequestSerializer,responses={@@ -1102,7 +1143,11 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):404: OpenApiResponse(description="Task not found"),503: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="PostHog Desktop access could not be verified",+ description=(+ "PostHog Desktop access could not be verified, or warm run activation is unavailable "+ "(code `warm_run_activation_unavailable`). After confirmed nondelivery, a retry_token permits "+ "retrying the same run and message with X-PostHog-Warm-Retry. Web retries for up to 20 seconds."+ ),),429: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -1144,8 +1189,18 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):try:result = tasks_facade.run_task(- pk, self.team_id, self._user_id(), validated_data=dict(request.validated_data)+ pk,+ self.team_id,+ self._user_id(),+ validated_data=dict(request.validated_data),+ **(+ {"warm_retry_token": request.headers["X-PostHog-Warm-Retry"]}+ if "X-PostHog-Warm-Retry" in request.headers+ else {}+ ),)+ except tasks_facade.WarmRunActivationUnavailable as error:+ return self._warm_activation_unavailable_response(error)except ReportTaskCapExceeded as error:return self._report_task_cap_response(error.detail)if result is None:diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 43ac00b9f558..8c936dd2b0c5 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -1,6 +1,7 @@import uuidimport asyncioimport logging+from datetime import timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optionalfrom django.conf import settings@@ -593,6 +594,7 @@ def signal_task_followup_message(context: dict[str, Any] | None = None,*,steer: bool = False,+ rpc_timeout: timedelta | None = None,) -> None:"""Legacy positional signal args stay frozen for worker deploy compatibility."""client = sync_connect()@@ -616,7 +618,10 @@ def signal_task_followup_message(if isinstance(protocol_version, int) and protocol_version >= STEERING_PROTOCOL_VERSION:signal_name = SEND_STEER_SIGNALsignal_args = [message, artifact_ids, message_id, actor_user_id, context]- await handle.signal(signal_name, args=signal_args)+ if rpc_timeout is None:+ await handle.signal(signal_name, args=signal_args)+ else:+ await handle.signal(signal_name, args=signal_args, rpc_timeout=rpc_timeout)asyncio.run(signal())diff --git a/products/tasks/backend/temporal/tests/test_client.py b/products/tasks/backend/temporal/tests/test_client.pyindex 22a83370b505..ca1af11c9230 100644--- a/products/tasks/backend/temporal/tests/test_client.py+++ b/products/tasks/backend/temporal/tests/test_client.py@@ -1,3 +1,6 @@+from datetime import timedelta++import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom products.tasks.backend.temporal.client import (@@ -26,11 +29,18 @@ def test_relay_enqueue_constructs_workflow_input(mock_connect: MagicMock) -> Nonassert workflow_input.run_id == "run-1"[email protected]("rpc_timeout", [None, timedelta(seconds=0.25)])@patch("products.tasks.backend.temporal.client.sync_connect")-def test_followup_signal_sends_expected_args(mock_connect: MagicMock) -> None:+def test_followup_signal_sends_expected_args(mock_connect: MagicMock, rpc_timeout: timedelta | None) -> None:handle = MagicMock(signal=AsyncMock())mock_connect.return_value = MagicMock(get_workflow_handle=MagicMock(return_value=handle))- signal_task_followup_message("wf-1", "hi", ["artifact-1"], message_id="msg-1", actor_user_id=7)+ signal_task_followup_message(+ "wf-1", "hi", ["artifact-1"], message_id="msg-1", actor_user_id=7, rpc_timeout=rpc_timeout+ )- handle.signal.assert_awaited_once_with("send_followup_message", args=["hi", ["artifact-1"], "msg-1", 7, None])+ handle.signal.assert_awaited_once_with(+ "send_followup_message",+ args=["hi", ["artifact-1"], "msg-1", 7, None],+ **({"rpc_timeout": rpc_timeout} if rpc_timeout is not None else {}),+ )diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex f435161f1181..7481fcfb1802 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -158,11 +158,7 @@ class TestTaskRunMetrics(TestCase):assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before + 1- def test_activation_claims_the_run_before_signaling_the_first_message(self) -> None:- # Activation cannot clear `await_user_message` until the signal lands — a failed signal would- # otherwise drop a never-activated run out of the warm pool and strand its sandbox. So it- # claims the run first, and a terminal transition arriving mid-signal must read that claim- # rather than book the run as a miss it is also counting as activated.+ def test_failed_startup_during_activation_does_not_count_as_activated(self) -> None:from products.tasks.backend.facade import api as facadefrom products.tasks.backend.metrics import observe_prewarmed_unused_if_never_activated@@ -173,15 +169,22 @@ class TestTaskRunMetrics(TestCase):)labels = {"origin_product": "user_created", "reason": "other"}before = _sample_value("posthog_tasks_prewarmed_unused_total", labels)+ activation_labels = {"origin_product": "user_created"}+ activated_before = _sample_value("posthog_tasks_prewarmed_activated_total", activation_labels)def _terminalize_during_signal(*_args: object, **_kwargs: object) -> bool:+ TaskRun.objects.filter(id=run.id).update(status=TaskRun.Status.FAILED)observe_prewarmed_unused_if_never_activated(TaskRun.objects.get(id=run.id), reason="other")return True- with patch.object(facade, "signal_task_run_user_message", side_effect=_terminalize_during_signal):+ with (+ patch.object(facade, "signal_task_run_user_message", side_effect=_terminalize_during_signal),+ self.assertRaises(facade.WarmRunActivationUnavailable),+ ):facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])- assert _sample_value("posthog_tasks_prewarmed_unused_total", labels) == before+ assert _sample_value("posthog_tasks_prewarmed_unused_total", labels) == before + 1+ assert _sample_value("posthog_tasks_prewarmed_activated_total", activation_labels) == activated_beforedef test_direct_terminal_write_counts_a_released_warm(self) -> None:# The cancel fallback writes the terminal status itself when the workflow is already gone, sodiff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex c07f5cfb0c82..e3346ecc053b 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -1,13 +1,17 @@+from datetime import timedeltafrom typing import Any+from freezegun import freeze_timefrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, patch+from django.db import transactionfrom django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.exceptions import PermissionDenied, Throttled+from temporalio.service import RPCError, RPCStatusCodefrom posthog.exceptions import QuotaLimitExceededfrom posthog.models import Integration, User@@ -630,9 +634,11 @@ class TestCreateTaskWarmReuse(APIBaseTest):assert Task.objects.filter(team=self.team, deleted=False).count() == 2- def test_reuses_matching_warm_task_and_activates_it_in_place(self):+ def test_reuses_matching_warm_task_and_activates_it_in_place(self) -> None:warm_task, run = self._warm_run()- with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal:+ handle = MagicMock(signal=AsyncMock())+ with patch("products.tasks.backend.temporal.client.sync_connect") as connect:+ connect.return_value.get_workflow_handle.return_value = handledto = self._create(auto_publish=True)assert str(dto.id) == str(warm_task.id)@@ -641,14 +647,174 @@ class TestCreateTaskWarmReuse(APIBaseTest):run.refresh_from_db()assert warm_task.description == "fix the bug"assert warm_task.title- m_signal.assert_called_once()- _, kwargs = m_signal.call_args- assert kwargs["content"] == "fix the bug"+ assert handle.signal.await_count == 1+ payloads = [call.kwargs["args"] for call in handle.signal.await_args_list]+ assert payloads[0][0] == "fix the bug"+ assert payloads[0][2]+ assert all(payload == payloads[0] for payload in payloads)+ assert all(call.args == (run.workflow_id,) for call in connect.return_value.get_workflow_handle.call_args_list)assert "await_user_message" not in run.state+ assert run.state["warm_activated"] is True# The agent-server re-reads run state on the forwarded first message, so this# must be persisted for the warm run to honor the setting.assert run.state.get("auto_publish") is True+ @parameterized.expand(+ [+ (endpoint, outcome)+ for endpoint in ("create", "resume")+ for outcome in (+ "retry",+ "retry_cancelled",+ "retry_replaced",+ "retry_invalid",+ "retry_expired",+ "retry_workflow_changed",+ "cancelled",+ "failed",+ "deleted",+ "task_deleted",+ "not_awaiting",+ "workflow_changed",+ "cancelled_after_delivery",+ "workflow_changed_after_delivery",+ )+ ]+ )+ def test_warm_activation_startup_through_endpoints(self, endpoint: str, outcome: str) -> None:+ task, run = self._warm_run(extra_state={"initial_permission_mode": "default", "prewarmed": True})+ artifact = _artifact_entry("startup-attachment")+ payload: dict[str, Any] = {+ "branch": "main",+ "pending_user_message": "Inspect the example chart",+ "pending_user_artifact_ids": [artifact["id"]],+ }+ if endpoint == "create":+ url = "/api/projects/@current/tasks/"+ payload.update(description="Inspect the example chart", repository="posthog/posthog")+ run.artifacts = [artifact]+ run.save(update_fields=["artifacts"])+ else:+ previous = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"pr_base_branch": "main", "initial_permission_mode": "default"},+ )+ TaskRun.objects.filter(id=previous.id).update(created_at=run.created_at - timedelta(seconds=1))+ TaskRun.update_state_atomic(run.id, updates={"resume_from_run_id": str(previous.id)})+ payload.update(mode="interactive", resume_from_run_id=str(previous.id))+ url = f"/api/projects/@current/tasks/{task.id}/run/"+ get_tasks_cache().set(+ build_task_staged_artifact_cache_key(str(task.id), artifact["id"]), artifact, timeout=60+ )++ run_count = TaskRun.objects.filter(team=self.team).count()+ savepoints = list(transaction.get_connection().savepoint_ids)+ handle = MagicMock(signal=AsyncMock(side_effect=RPCError("workflow starting", RPCStatusCode.NOT_FOUND, b"")))++ def get_handle(workflow_id: str) -> MagicMock:+ assert workflow_id == run.workflow_id+ assert transaction.get_connection().savepoint_ids == savepoints+ if outcome in ("cancelled", "failed", "cancelled_after_delivery"):+ TaskRun.objects.filter(id=run.id).update(status="failed" if outcome == "failed" else "cancelled")+ elif outcome == "deleted":+ TaskRun.objects.filter(id=run.id).delete()+ elif outcome == "task_deleted":+ Task.objects.filter(id=task.id).update(deleted=True)+ elif outcome == "not_awaiting":+ TaskRun.update_state_atomic(run.id, remove_keys=["await_user_message"])+ elif outcome in ("workflow_changed", "workflow_changed_after_delivery"):+ TaskRun.update_state_atomic(run.id, updates={"workflow_id": "replacement-workflow"})+ if outcome.endswith("after_delivery"):+ handle.signal.side_effect = None+ return handle++ with (+ patch("products.tasks.backend.temporal.client.sync_connect") as connect,+ patch(f"{FACADE}.time.sleep") as sleep,+ patch("posthog.storage.object_storage.tag"),+ patch(+ "products.tasks.backend.logic.services.title_generator.generate_task_title",+ return_value="Example chart",+ ),+ ):+ connect.return_value.get_workflow_handle.side_effect = get_handle+ response = self.client.post(url, payload, format="json")++ assert Task.objects.filter(team=self.team).count() == 1+ assert TaskRun.objects.filter(team=self.team).count() == run_count - (outcome == "deleted")+ assert response.status_code == 503, response.content+ error_body = response.json()+ retry_token = error_body.pop("retry_token", None)+ assert bool(retry_token) is outcome.startswith("retry")+ assert error_body == {+ "code": "warm_run_activation_unavailable",+ "error": "Couldn't start this run yet. Please try again.",+ }+ handle.signal.assert_awaited_once()+ assert handle.signal.call_args.kwargs["rpc_timeout"] == timedelta(seconds=10)+ sleep.assert_not_called()++ if outcome != "deleted":+ run.refresh_from_db()+ assert not run.state.get("warm_activated")+ assert bool(run.state.get("await_user_message")) is (outcome != "not_awaiting")+ if outcome.startswith("retry"):+ first_message = handle.signal.call_args.kwargs["args"]+ if outcome in ("retry_cancelled", "retry_replaced"):+ TaskRun.objects.filter(id=run.id).update(status=TaskRun.Status.CANCELLED)+ if outcome == "retry_replaced":+ TaskRun.objects.create(task=task, team=self.team, state=run.state, branch=run.branch)+ run_count += 1+ if outcome == "retry_invalid":+ retry_token += "invalid"+ if outcome == "retry_workflow_changed":+ TaskRun.update_state_atomic(run.id, updates={"workflow_id": "replacement-workflow"})+ with freeze_time(django_timezone.now() + timedelta(seconds=61 if outcome == "retry_expired" else 0)):+ retry = self.client.post(url, payload, format="json", HTTP_X_POSTHOG_WARM_RETRY=retry_token)+ if outcome != "retry":+ assert retry.status_code == 503, retry.content+ assert "retry_token" not in retry.json()+ assert handle.signal.await_count == 1+ assert Task.objects.filter(team=self.team).count() == 1+ assert TaskRun.objects.filter(team=self.team).count() == run_count+ return+ assert retry.status_code == 503, retry.content+ assert retry.json()["retry_token"]+ assert handle.signal.await_count == 2+ handle.signal.side_effect = None+ retry = self.client.post(url, payload, format="json", HTTP_X_POSTHOG_WARM_RETRY=retry_token)+ assert retry.status_code == (201 if endpoint == "create" else 200), retry.content+ assert retry.json()["latest_run"]["id"] == str(run.id)+ assert handle.signal.await_count == 3+ assert all(call.kwargs["args"] == first_message for call in handle.signal.await_args_list)+ run.refresh_from_db()+ assert [entry["id"] for entry in run.artifacts] == [artifact["id"]]+ assert "await_user_message" not in run.state+ assert run.state["warm_activated"] is True+ assert Task.objects.filter(team=self.team).count() == 1+ assert TaskRun.objects.filter(team=self.team).count() == run_count+ sleep.assert_not_called()++ @parameterized.expand([(False,), (None,), (RPCStatusCode.UNAVAILABLE,), (RPCStatusCode.DEADLINE_EXCEEDED,)])+ def test_warm_activation_does_not_retry_unconfirmed_delivery(self, outcome: bool | None | RPCStatusCode) -> None:+ _, run = self._warm_run()+ expected_error: type[Exception]+ with patch(f"{FACADE}.signal_task_run_user_message") as signal:+ if isinstance(outcome, RPCStatusCode):+ signal.side_effect = RPCError("transport failure", outcome, b"")+ expected_error = RPCError+ else:+ signal.return_value = outcome+ expected_error = facade.WarmRunActivationUnavailable+ with self.assertRaises(expected_error):+ self._create()+ signal.assert_called_once()+ run.refresh_from_db()+ assert run.state["await_user_message"] is True+ assert not run.state.get("warm_activated")+def test_reuses_warm_task_with_new_reasoning_effort_and_attachments(self):warm_task, run = self._warm_run(extra_state={diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 192614d41a95..6d2fe5ee1f3d 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -45,6 +45,8 @@ export interface TaskRunErrorResponseApi {type?: string/** Machine-readable error code */code?: string+ /** After confirmed warm startup nondelivery, echo this token in X-PostHog-Warm-Retry to retry the same run and message within 60 seconds. */+ retry_token?: string/** Why PostHog Desktop access was denied, when applicable.** * `startup_plan` - startup_plandiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 35bdedd67ce4..cb9505dff196 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -86203,6 +86203,8 @@ export namespace Schemas {type?: string;/** Machine-readable error code */code?: string;+ /** After confirmed warm startup nondelivery, echo this token in X-PostHog-Warm-Retry to retry the same run and message within 60 seconds. */+ retry_token?: string;/** Why PostHog Desktop access was denied, when applicable.** * `startup_plan` - startup_plandiff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex b4eccfc350f6..e52df6cbc528 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -989,6 +989,13 @@ export const TasksCreateParams = () => zod.object({),})+export const TasksCreateHeader = () => zod.object({+ 'X-PostHog-Warm-Retry': zod+ .string()+ .optional()+ .describe('Retry token from a warm_run_activation_unavailable response; prevents creating a replacement run.'),+})+export const tasksCreateBodyTitleMax = 255export const tasksCreateBodyRepositoryMax = 255