Skip to content

: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.

fix(ai): prevent task creation from racing composer prewarming (#99369)

Georgiy Tarasovdfda1d13edfc
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 29681cd9bb22..fe4cfc14018b 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -491,6 +491,19 @@ The flow, driven from the PostHog Desktop Environments → Cloud tab:
falling back to the standard base if the image can't be loaded.
Repo-setup snapshots are skipped for custom-image runs; resume snapshots still apply.
+## Composer prewarming
+
+The task composer can warm a sandbox while the user types.
+Submission stops pending warm-up timers before creating a task or resuming a run, so a delayed warm-up cannot create an extra task after the backend has checked the warm pool.
+The submission takes ownership of held and pending warm-ups before sending, so closing the composer cannot cancel a run while its first message is being delivered.
+Each response reconciles only its own submission's warm-up, including one whose response arrives later.
+Once submission returns, the composer keeps the activated run and releases an unused warm-up if no later submission could have activated it.
+Overlapping submissions leave earlier warm-ups to the server reaper because either request might deliver to the same run.
+If the response is lost, the server reaper handles unused warm-ups because the composer cannot tell whether the message reached the run.
+Releases use `only_if_awaiting_first_message` and claim the run under the same row lock as activation.
+Activation claims the run before delivering its first message, so another composer or browser tab cannot cancel delivery in progress.
+A release that claims the run first prevents subsequent activation.
+
## Continuing after sandbox inactivity
When a sandbox expires, a new user message starts the next turn with the preserved
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index caf4c9e86e63..b41a73403154 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -921,32 +921,76 @@ describe('runInteractionLogic', () => {
}
)
- it('warms the resumed run while composing and consumes it before submit', async () => {
+ it.each([
+ ['submitted', false],
+ ['unmounted', false],
+ ['unmounted', true],
+ ['failed', false],
+ ['failed', true],
+ ] as const)('protects the submitted warm when %s (warm pending: %s)', async (outcome, warmPending) => {
+ let resolveWarm!: () => void
+ let resolveRun!: () => void
+ let rejectRun!: () => void
+ ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
+ })
+ )
+ ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(
+ new Promise((resolve, reject) => {
+ resolveRun = () => resolve({ latest_run: { id: 'warm-run' } })
+ rejectRun = () => reject(new Error('Connection lost'))
+ })
+ )
jest.useFakeTimers()
- setStatus('cancelled')
- logic.actions.setComposerFormValues({ draft: 'continue from the checkpoint' })
- jest.advanceTimersByTime(300)
- jest.useRealTimers()
-
- await expectLogic(logic).toFinishAllListeners()
- expect(tasksWarmResumeCreate).toHaveBeenCalledWith('997', TASK_ID, {
- resume_from_run_id: RUN_ID,
- runtime_adapter: 'claude',
- model: 'claude-sonnet-5',
- reasoning_effort: 'high',
- initial_permission_mode: 'auto',
- })
+ try {
+ setStatus('cancelled')
+ logic.actions.setComposerFormValues({ draft: 'continue from the checkpoint' })
+ await jest.advanceTimersByTimeAsync(300)
+ if (!warmPending) {
+ resolveWarm()
+ await jest.advanceTimersByTimeAsync(0)
+ }
+ expect(tasksWarmResumeCreate).toHaveBeenCalledWith('997', TASK_ID, {
+ resume_from_run_id: RUN_ID,
+ runtime_adapter: 'claude',
+ model: 'claude-sonnet-5',
+ reasoning_effort: 'high',
+ initial_permission_mode: 'auto',
+ })
- await expectLogic(logic, () => {
logic.actions.submitComposerForm()
- }).toFinishAllListeners()
+ expect(tasksRunCreate).toHaveBeenCalledWith(
+ '997',
+ TASK_ID,
+ expect.objectContaining({ resume_from_run_id: RUN_ID }),
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
+ expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
- expect(tasksRunCreate).toHaveBeenCalledWith(
- '997',
- TASK_ID,
- expect.objectContaining({ resume_from_run_id: RUN_ID }),
- expect.objectContaining({ signal: expect.any(AbortSignal) })
- )
+ if (outcome === 'failed') {
+ rejectRun()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.composerForm.draft).toBe('continue from the checkpoint')
+ }
+ if (outcome !== 'submitted') {
+ logic.unmount()
+ }
+ resolveRun()
+ resolveWarm()
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
+ if (outcome === 'submitted') {
+ expect(onRunStarted).toHaveBeenCalledWith('warm-run', expect.anything())
+ } else {
+ expect(onRunStarted).not.toHaveBeenCalled()
+ }
+ } finally {
+ resolveRun()
+ resolveWarm()
+ jest.useRealTimers()
+ }
})
it('records the boundary instead of starting a run when /clear is sent to a terminal run', async () => {
@@ -1521,4 +1565,109 @@ describe('runInteractionLogic', () => {
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
expect(logic.values.queuedMessages).toEqual([])
})
+ it('changing mode after a lost response preserves the first submitted warm', async () => {
+ let finishWarm!: () => void
+ ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
+ })
+ )
+ ;(tasksRunCreate as jest.Mock)
+ .mockRejectedValueOnce(new Error('Connection lost'))
+ .mockResolvedValueOnce({ latest_run: { id: 'retry-run' } })
+ jest.useFakeTimers()
+ try {
+ setStatus('completed')
+ logic.actions.setComposerFormValues({ draft: 'continue from the checkpoint' })
+ await jest.advanceTimersByTimeAsync(300)
+ expect(tasksWarmResumeCreate).toHaveBeenCalledTimes(1)
+ logic.actions.submitComposerForm()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.startingRun).toBe(false)
+ expect(logic.values.composerForm.draft).toBe('continue from the checkpoint')
+ logic.actions.setMode('plan')
+ logic.actions.submitComposerForm()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(tasksRunCreate).toHaveBeenCalledTimes(2)
+ expect(tasksRunCreate).toHaveBeenLastCalledWith(
+ '997',
+ TASK_ID,
+ expect.objectContaining({ initial_permission_mode: 'plan' }),
+ expect.anything()
+ )
+ expect(onRunStarted).toHaveBeenCalledWith('retry-run', expect.anything())
+ finishWarm()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
+ } finally {
+ finishWarm()
+ jest.useRealTimers()
+ }
+ })
+
+ it.each([false, true])(
+ 'preserves a submitted warm across composers (warm response ready: %s)',
+ async (warmReady) => {
+ let finishWarm!: () => void
+ let finishFirstRun!: () => void
+ let finishSecondRun!: () => void
+ ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
+ })
+ )
+ ;(tasksRunCreate as jest.Mock)
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishFirstRun = () => resolve({ latest_run: { id: 'warm-run' } })
+ })
+ )
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishSecondRun = () => resolve({ latest_run: { id: 'cold-run' } })
+ })
+ )
+ logic.unmount()
+ logic = runInteractionLogic({
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ interactionKey: 'optimistic-panel',
+ streamKey: 'panel-stream',
+ })
+ logic.mount()
+ const panelStream = runStreamLogic({ streamKey: 'panel-stream' })
+ ;(panelStream.actions as any).setStubStatus('cancelled')
+ const second = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID })
+ second.mount()
+ jest.useFakeTimers()
+ try {
+ setStatus('cancelled')
+ logic.actions.setComposerFormValues({ draft: 'first composer' })
+ await jest.advanceTimersByTimeAsync(300)
+ expect(tasksWarmResumeCreate).toHaveBeenCalledTimes(1)
+ if (warmReady) {
+ finishWarm()
+ await jest.advanceTimersByTimeAsync(0)
+ }
+ logic.actions.submitComposerForm()
+ second.actions.setMode('plan')
+ second.actions.setComposerFormValues({ draft: 'second composer' })
+ second.actions.submitComposerForm()
+ expect(tasksRunCreate).toHaveBeenCalledTimes(2)
+ finishSecondRun()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.startingRun).toBe(true)
+ finishWarm()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
+ } finally {
+ finishFirstRun()
+ finishSecondRun()
+ finishWarm()
+ await jest.advanceTimersByTimeAsync(0)
+ second.unmount()
+ jest.useRealTimers()
+ }
+ }
+ )
})
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 2a8f2a01671d..c0eab1b3dad2 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -57,7 +57,7 @@ import type { RunStatus } from './runStreamLogic'
import { taskDraftListeners } from './taskDraftListeners'
import type { DraftRecovery } from './taskDraftPersistence'
import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'
-import { taskWarmLogic } from './taskWarmLogic'
+import { taskWarmLogic, type WarmSubmission } from './taskWarmLogic'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
export interface RunInteractionLogicProps {
@@ -1053,6 +1053,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
!props.runId ||
!values.isTerminal ||
!values.dataProcessingAccepted ||
+ values.startingRun ||
values.draftRecovery ||
cache.restoringTaskDraft
) {
@@ -1391,7 +1392,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
pending_user_message: wrapWithPosthogContext(content, pendingContext),
}
)
- getWarmLogic()?.actions.consumeWarm()
+ const warmSubmission: WarmSubmission = { projectId, lease: null }
+ getWarmLogic()?.actions.prepareSubmit(warmSubmission)
actions.beginTaskDraftDelivery(content)
actions.resetComposerForm()
actions.startOptimisticResume(content)
@@ -1403,6 +1405,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
if (!isCurrent()) {
return
}
+ getWarmLogic()?.actions.consumeWarm(warmSubmission, result.latest_run?.id ?? null)
const run = result.latest_run
if (!run?.id) {
throw new Error('The run response did not include a run')
diff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts
index 6567e7bb2af5..1d6cfe4ba01c 100644
--- a/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts
@@ -10,7 +10,7 @@ import {
type WarmTaskRequestApi,
} from 'products/tasks/frontend/generated/api.schemas'
-import { taskWarmLogic } from './taskWarmLogic'
+import { taskWarmLogic, type WarmSubmission } from './taskWarmLogic'
const WARM_REQUEST: WarmTaskRequestApi = {
repository: 'posthog/posthog',
@@ -26,11 +26,13 @@ describe('taskWarmLogic', () => {
let logic: ReturnType<typeof taskWarmLogic.build>
let warmCalls: number
let cancelledRuns: string[]
+ let cancelBodies: unknown[]
let resolveWarm: ((value: unknown) => void) | null
beforeEach(() => {
warmCalls = 0
cancelledRuns = []
+ cancelBodies = []
resolveWarm = null
useMocks({
post: {
@@ -38,8 +40,9 @@ describe('taskWarmLogic', () => {
warmCalls += 1
return [200, { task_id: `warm-task-${warmCalls}`, run_id: `warm-run-${warmCalls}` }]
},
- '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params }) => {
+ '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params, request }) => {
cancelledRuns.push(params.runId as string)
+ cancelBodies.push(await request.json())
return [200, {}]
},
},
@@ -68,20 +71,31 @@ describe('taskWarmLogic', () => {
expect(logic.values.warmLease).toMatchObject({ taskId: 'warm-task-1', runId: 'warm-run-1' })
})
- it('consuming a warm on submit clears the lease without cancelling the run', async () => {
- jest.useFakeTimers()
- logic.actions.noteDraft(true, WARM_REQUEST)
- jest.advanceTimersByTime(300)
- jest.useRealTimers()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.consumeWarm()
- await expectLogic(logic).toFinishAllListeners()
-
- // The submit activates this very Run — cancelling it would kill the run out from under the message.
- expect(logic.values.warmLease).toBeNull()
- expect(cancelledRuns).toEqual([])
- })
+ it.each(['warm-run-1', 'cold-run'])(
+ 'consuming a warm after submit activates %s releases only the unused run',
+ async (runId) => {
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ jest.useFakeTimers()
+ logic.actions.noteDraft(false, WARM_REQUEST)
+ const submission: WarmSubmission = { projectId: '997', lease: null }
+ logic.actions.prepareSubmit(submission)
+ await jest.advanceTimersByTimeAsync(5000)
+ jest.useRealTimers()
+ expect(cancelledRuns).toEqual([])
+
+ logic.actions.consumeWarm(submission, runId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.warmLease).toBeNull()
+ expect(cancelledRuns).toEqual(runId === 'warm-run-1' ? [] : ['warm-run-1'])
+ expect(cancelBodies).toEqual(runId === 'warm-run-1' ? [] : [{ only_if_awaiting_first_message: true }])
+ }
+ )
it('warms again for the next draft after a submit consumed the previous warm', async () => {
jest.useFakeTimers()
@@ -91,7 +105,9 @@ describe('taskWarmLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(warmCalls).toBe(1)
- logic.actions.consumeWarm()
+ const submission: WarmSubmission = { projectId: '997', lease: null }
+ logic.actions.prepareSubmit(submission)
+ logic.actions.consumeWarm(submission, 'warm-run-1')
await expectLogic(logic).toFinishAllListeners()
jest.useFakeTimers()
@@ -323,44 +339,98 @@ describe('taskWarmLogic', () => {
expect(cancelledRuns).toEqual([])
})
- it('drops a warm that resolves after the submit consumed it mid-flight', async () => {
- // The scene consumes the warm only after its create resolves, so a create round trip that beats
- // the slower warm POST leaves the warm still in flight at consume time. Without a fence the
- // completing POST installs a lease on a Run the create may have already activated, and a later
- // selection change would then cancel that live Run.
- let resolveHeldWarm: () => void = () => {}
+ it.each([
+ ['warm-run-1', false],
+ ['warm-run-1', true],
+ ['cold-run', false],
+ ['cold-run', true],
+ ] as const)('reconciles a warm response when submit activates %s (warm first: %s)', async (runId, warmFirst) => {
+ let resolveHeldWarm!: () => void
+ let warmStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ warmStarted = resolve
+ })
useMocks({
post: {
'/api/projects/:team/tasks/warm/': async () => {
await new Promise<void>((resolve) => {
resolveHeldWarm = resolve
+ warmStarted()
})
return [200, { task_id: 'warm-task-1', run_id: 'warm-run-1' }]
},
- '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params }) => {
- cancelledRuns.push(params.runId as string)
- return [200, {}]
- },
},
})
logic.actions.prewarm(WARM_REQUEST)
- await expectLogic(logic).toMount()
- // The submit consumes the warm while the POST is still open.
- logic.actions.consumeWarm()
+ await started
+ const submission: WarmSubmission = { projectId: '997', lease: null }
+ logic.actions.prepareSubmit(submission)
+ if (warmFirst) {
+ resolveHeldWarm()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.releaseWarm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(cancelledRuns).toEqual([])
+ }
+ logic.actions.consumeWarm(submission, runId)
resolveHeldWarm()
await expectLogic(logic).toFinishAllListeners()
- // No lease is installed, so a later selection change (noteDraft only releases when a lease is
- // held) has nothing to cancel — the activated Run is safe. And the Run itself was not cancelled.
expect(logic.values.warmLease).toBeNull()
- expect(cancelledRuns).toEqual([])
+ expect(cancelledRuns).toEqual(runId === 'warm-run-1' ? [] : ['warm-run-1'])
+ expect(cancelBodies).toEqual(runId === 'warm-run-1' ? [] : [{ only_if_awaiting_first_message: true }])
})
- it('releases a held warm when the composer unmounts', async () => {
- // Navigating away is the common way to leave the composer. Without an unmount release, the warm
- // sandbox idles until the server reaper while holding a scarce per-user warm-pool slot.
+ it.each([false, true])(
+ 'preserves an earlier warm that a later submission may use (in flight: %s)',
+ async (inFlight) => {
+ let finishWarm!: () => void
+ let warmStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ warmStarted = resolve
+ })
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ await new Promise<void>((resolve) => {
+ finishWarm = resolve
+ warmStarted()
+ })
+ return [200, { task_id: 'warm-task-1', run_id: 'warm-run-1' }]
+ },
+ },
+ })
+
+ logic.actions.prewarm(WARM_REQUEST)
+ await started
+ if (!inFlight) {
+ finishWarm()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ const first: WarmSubmission = { projectId: '997', lease: null }
+ const second: WarmSubmission = { projectId: '997', lease: null }
+ logic.actions.prepareSubmit(first)
+ logic.actions.prepareSubmit(second)
+ logic.actions.consumeWarm(first, 'cold-run')
+ finishWarm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(cancelledRuns).toEqual([])
+ logic.actions.consumeWarm(second, 'warm-run-1')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(cancelledRuns).toEqual([])
+ expect(logic.values.warmLease).toBeNull()
+ }
+ )
+
+ it.each([false, true])('releases a warm when the composer unmounts (in flight: %s)', async (inFlight) => {
+ let finishWarm!: () => void
+ let warmStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ warmStarted = resolve
+ })
let cancelSeen: () => void = () => {}
const cancelled = new Promise<void>((resolve) => {
cancelSeen = resolve
@@ -369,27 +439,34 @@ describe('taskWarmLogic', () => {
post: {
'/api/projects/:team/tasks/warm/': async () => {
warmCalls += 1
+ await new Promise<void>((resolve) => {
+ finishWarm = resolve
+ warmStarted()
+ })
return [200, { task_id: 'warm-task-1', run_id: 'warm-run-1' }]
},
- '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params }) => {
+ '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params, request }) => {
cancelledRuns.push(params.runId as string)
+ cancelBodies.push(await request.json())
cancelSeen()
return [200, {}]
},
},
})
- jest.useFakeTimers()
- logic.actions.noteDraft(true, WARM_REQUEST)
- jest.advanceTimersByTime(300)
- jest.useRealTimers()
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-1' })
+ logic.actions.prewarm(WARM_REQUEST)
+ await started
+ if (!inFlight) {
+ finishWarm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-1' })
+ }
- // Leaving the composer unmounts the logic; the deferred promise resolves only if the cancel fires.
logic.unmount()
+ finishWarm()
await cancelled
expect(cancelledRuns).toEqual(['warm-run-1'])
+ expect(cancelBodies).toEqual([{ only_if_awaiting_first_message: true }])
})
})
diff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.ts
index 08226eafc313..e4a71a554ab3 100644
--- a/products/posthog_ai/frontend/logics/taskWarmLogic.ts
+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.ts
@@ -23,6 +23,13 @@ export interface WarmLease {
runId: string
}
+export interface WarmSubmission {
+ projectId: string
+ lease: WarmLease | null
+ runId?: string | null
+ superseded?: boolean
+}
+
export interface TaskWarmLogicProps {
/** Matches `taskTrackerSceneLogicProps.panelId` so each composer instance owns its own lease. */
panelId?: string
@@ -83,6 +90,18 @@ async function cancelWarmRun(projectId: string, lease: WarmLease): Promise<void>
}
}
+async function releaseUnusedWarm(submission: WarmSubmission): Promise<void> {
+ // A failed or aborted submission may still deliver its message. Leave uncertain warms to the reaper.
+ if (
+ !submission.superseded &&
+ submission.runId !== undefined &&
+ submission.lease &&
+ submission.lease.runId !== submission.runId
+ ) {
+ await cancelWarmRun(submission.projectId, submission.lease)
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskWarmLogicValues {
currentProjectId: number | null // projectLogic
@@ -91,8 +110,12 @@ export interface taskWarmLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskWarmLogicActions {
- consumeWarm: () => {
- value: true
+ consumeWarm: (
+ submission: WarmSubmission,
+ runId: string | null
+ ) => {
+ runId: string | null
+ submission: WarmSubmission
}
noteDraft: (
hasText: boolean,
@@ -101,6 +124,9 @@ export interface taskWarmLogicActions {
hasText: boolean
request: TaskWarmRequest
}
+ prepareSubmit: (submission: WarmSubmission) => {
+ submission: WarmSubmission
+ }
prewarm: (request: TaskWarmRequest) => {
request: TaskWarmRequest
}
@@ -146,8 +172,9 @@ export const taskWarmLogic = kea<taskWarmLogicType>([
actions({
noteDraft: (hasText: boolean, request: TaskWarmRequest) => ({ hasText, request }),
prewarm: (request: TaskWarmRequest) => ({ request }),
+ prepareSubmit: (submission: WarmSubmission) => ({ submission }),
releaseWarm: true,
- consumeWarm: true,
+ consumeWarm: (submission: WarmSubmission, runId: string | null) => ({ submission, runId }),
setWarmLease: (lease: WarmLease | null) => ({ lease }),
}),
@@ -242,27 +269,30 @@ export const taskWarmLogic = kea<taskWarmLogicType>([
cache.lastWarmRequestAt = Date.now()
cache.pendingRelease = false
cache.pendingWarmRequest = null
- cache.consumedWhileWarming = false
+ const warmRequest: { submission: WarmSubmission | null } = { submission: null }
+ cache.warmRequest = warmRequest
+ const projectId = String(values.currentProjectId)
+ const disposables = cache.disposables
try {
const warm = resumeRequest
- ? await tasksWarmResumeCreate(
- String(values.currentProjectId),
- props.taskId as string,
- resumeRequest
- )
- : await tasksWarmCreate(String(values.currentProjectId), request as WarmTaskRequestApi)
- if (cache.consumedWhileWarming) {
- // A submit consumed the warm while this POST was open. The backend's create may have
- // matched and activated this very Run for the submit, so installing a lease on it
- // would let a later selection change cancel a live run. Drop the response without a
- // lease. We can't tell an activated Run from an unactivated orphan here, so we never
- // cancel; an orphan falls to the server reaper. Partner of pendingRelease/pendingWarm.
+ ? await tasksWarmResumeCreate(projectId, props.taskId as string, resumeRequest)
+ : await tasksWarmCreate(projectId, request as WarmTaskRequestApi)
+ const lease = warm?.task_id && warm?.run_id ? { key, taskId: warm.task_id, runId: warm.run_id } : null
+ if (warmRequest.submission) {
+ warmRequest.submission.lease = lease
+ await releaseUnusedWarm(warmRequest.submission)
+ return
+ }
+ if (disposables.isDisposed) {
+ if (lease) {
+ await cancelWarmRun(projectId, lease)
+ }
return
}
// An empty body is the documented "not warmed" answer — the flag is off, the pool is
// full, or the integration didn't resolve. Not an error, just no speedup this time.
- if (warm?.task_id && warm?.run_id) {
- actions.setWarmLease({ key, taskId: warm.task_id, runId: warm.run_id })
+ if (lease) {
+ actions.setWarmLease(lease)
// The cooldown throttles repeated "not warmed" answers, which leave no lease. This
// warm produced one, so drop the stamp: once a submit consumes the lease or a
// release drops it, the next draft for the same selection must warm again instead
@@ -282,6 +312,7 @@ export const taskWarmLogic = kea<taskWarmLogicType>([
} finally {
cache.warming = false
cache.warmingKey = null
+ cache.warmRequest = null
}
// A newer selection arrived while the POST was open. Now that the slot is free, release the
// sandbox booted for the stale selection and warm for the latest one instead. A pending
@@ -316,36 +347,43 @@ export const taskWarmLogic = kea<taskWarmLogicType>([
await cancelWarmRun(String(values.currentProjectId), lease)
},
- consumeWarm: () => {
- // A submitted message consumes the warm: that Run is the one the submit activates, so drop
- // every timer and the lease WITHOUT cancelling it.
+ prepareSubmit: ({ submission }) => {
+ // A warm started after submission can miss the backend's pool lookup and create an extra task.
cache.disposables.dispose('warm-debounce')
cache.disposables.dispose('warm-release')
cache.pendingRelease = false
cache.pendingWarmRequest = null
- // A warm fenced below by consumedWhileWarming returns before it installs a lease, so it
- // never clears the cooldown stamp itself. Clear it here so the next draft in this composer
- // can warm rather than taking the cold path for the rest of the cooldown.
+ // A submission-owned warm never installs a lease to clear this stamp. Let the next draft warm.
cache.lastWarmRequestKey = null
cache.lastWarmRequestAt = null
- // The submit can beat an in-flight warm POST back to the client (the scene consumes only after
- // its create resolves). Fence that response so its completion drops rather than installs a
- // lease — otherwise a stale lease survives the submit and a later selection change cancels a
- // Run the create may have activated. prewarm resets this flag when it opens the next POST.
- if (cache.warming) {
- cache.consumedWhileWarming = true
+ if (values.currentProjectId == null) {
+ return
}
+ // Another submission can activate the same warm, so the earlier result cannot authorize cleanup.
+ if (cache.submission) {
+ cache.submission.superseded = true
+ }
+ submission.lease = values.warmLease
+ cache.submission = submission
+ if (cache.warmRequest && !cache.warmRequest.submission) {
+ cache.warmRequest.submission = submission
+ }
+ // Teardown must not cancel a run while its first message is being delivered.
actions.setWarmLease(null)
},
+
+ consumeWarm: async ({ submission, runId }) => {
+ submission.runId = runId
+ await releaseUnusedWarm(submission)
+ },
})),
// Leaving the composer (this logic is connected to the scene, so it unmounts when the scene or panel
// does) is the most common way to abandon a draft, more so than clearing the box and waiting out the
// release timer. Cancel the held warm here too, so navigating away reclaims the sandbox immediately
// instead of leaving it to idle until the server reaper. Cancel inline rather than dispatching
- // releaseWarm, because a listener dispatched during teardown does not run. A consumed warm is already
- // cleared by consumeWarm before the submit navigates, so no lease is found on that path. A warm still
- // mid-boot (no lease yet) has no Run id to cancel and falls back to the server reaper.
+ // releaseWarm, because a listener dispatched during teardown does not run. Submitted warms belong to
+ // their submission until its outcome is known. Unsubmitted warms still mid-boot are released on arrival.
beforeUnmount(({ values }) => {
const lease = values.warmLease
if (lease && values.currentProjectId != null) {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 4ad515c73770..4483d2170229 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -617,6 +617,7 @@ describe('taskTrackerSceneLogic', () => {
finishCreation = resolve
})
let createCount = 0
+ let warmCount = 0
useMocks({
post: {
'/api/projects/:team/tasks/': async ({ request }) => {
@@ -624,8 +625,13 @@ describe('taskTrackerSceneLogic', () => {
createBody = (await request.json()) as Record<string, unknown>
return creation
},
+ '/api/projects/:team/tasks/warm/': () => {
+ warmCount++
+ return [200, { task_id: 'unused-task', run_id: 'unused-run' }]
+ },
},
})
+ jest.useFakeTimers()
router.actions.push(urls.ai(undefined, 'analyze churn'))
const unmountBridge = phaiAiComposerSeedLogic().mount()
try {
@@ -634,6 +640,9 @@ describe('taskTrackerSceneLogic', () => {
expect(runStreamLogic({ streamKey }).values.threadItems).toEqual([
expect.objectContaining({ type: 'human_message', text: 'analyze churn' }),
])
+ await jest.advanceTimersByTimeAsync(300)
+ jest.useRealTimers()
+ expect(warmCount).toBe(0)
if (destination) {
router.actions.push(destination)
expect(logic.values.activeCreation).toBeNull()
@@ -652,6 +661,7 @@ describe('taskTrackerSceneLogic', () => {
expect(router.values.location.pathname).toContain('/tasks/new-task')
}
} finally {
+ jest.useRealTimers()
finishCreation([200, { id: 'new-task', latest_run: { id: 'run-1' } }])
unmountBridge()
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 20026fe2aa55..ed91b4f80028 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -38,7 +38,7 @@ import type { ActiveCreation } from '../../logics/runnerPanelLogic'
import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'
import { tasksLogic } from '../../logics/tasksLogic'
import { taskWarmLogic } from '../../logics/taskWarmLogic'
-import type { WarmLease } from '../../logics/taskWarmLogic'
+import type { WarmLease, WarmSubmission } from '../../logics/taskWarmLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import type { AttachedContextItem } from '../../types/contextTypes'
@@ -214,8 +214,12 @@ export interface taskTrackerSceneLogicActions {
toggleHistory: () => {
value: true
} // runnerPanelLogic
- consumeWarm: () => {
- value: true
+ consumeWarm: (
+ submission: WarmSubmission,
+ runId: string | null
+ ) => {
+ runId: string | null
+ submission: WarmSubmission
} // taskWarmLogic
noteDraft: (
hasText: boolean,
@@ -224,6 +228,9 @@ export interface taskTrackerSceneLogicActions {
hasText: boolean
request: import('../../logics/taskWarmLogic').TaskWarmRequest
} // taskWarmLogic
+ prepareSubmit: (submission: WarmSubmission) => {
+ submission: WarmSubmission
+ } // taskWarmLogic
releaseWarm: () => {
value: true
} // taskWarmLogic
@@ -384,7 +391,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
composerSeedLogic(props),
['consumeSeed', 'setSeed'],
taskWarmLogic({ panelId: props.panelId }),
- ['noteDraft', 'consumeWarm', 'releaseWarm'],
+ ['noteDraft', 'prepareSubmit', 'consumeWarm', 'releaseWarm'],
],
})),
@@ -619,6 +626,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
const disposables = cache.disposables
cache.submittingTask = disposables
+ const projectId = String(values.currentProjectId)
+ const warmSubmission: WarmSubmission = { projectId, lease: null }
+ actions.prepareSubmit(warmSubmission)
// 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
@@ -709,14 +719,11 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
pending_user_message: pendingUserMessage,
}
- const projectId = String(values.currentProjectId)
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()
+ actions.consumeWarm(warmSubmission, newTask.latest_run?.id ?? null)
if (!disposables.isDisposed && values.activeCreation?.streamKey === streamKey) {
interaction.props.flushDraft?.()
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 45ec00d1ba80..27f1889bda9a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -6680,6 +6680,8 @@ def _find_idling_warm_run(
)
for run in candidates:
state = run.state or {}
+ if state.get("cancel_requested_at"):
+ continue
have_repositories = [
repo.lower() for repo in (run.task.repositories or ([run.task.repository] if run.task.repository else []))
]
@@ -6805,9 +6807,17 @@ def _deliver_warm_run_message(
).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")
+ with transaction.atomic():
+ current_run = eligible_runs.select_for_update(of=("self",)).first()
+ if (
+ current_run is None
+ or current_run.workflow_id != workflow_id
+ or (current_run.state or {}).get("cancel_requested_at")
+ ):
+ raise WarmRunActivationUnavailable("target_unavailable")
+ # Claim before signaling so a different composer's release cannot cancel delivery in flight.
+ current_run.state["warm_activation_started"] = True
+ current_run.save(update_fields=["state", "updated_at"])
try:
delivered = signal_task_run_user_message(
run.id,
diff --git a/products/tasks/backend/facade/cancellation.py b/products/tasks/backend/facade/cancellation.py
index a46a2908bc78..82549fda56a3 100644
--- a/products/tasks/backend/facade/cancellation.py
+++ b/products/tasks/backend/facade/cancellation.py
@@ -3,6 +3,7 @@ import logging
from typing import Any, Literal
from uuid import UUID
+from django.db import transaction
from django.utils import timezone as django_timezone
from temporalio.service import RPCError, RPCStatusCode
@@ -133,9 +134,25 @@ def cancel_task_run(
if requested_by_user_id is not None:
marker["cancel_requested_by_user_id"] = requested_by_user_id
try:
- TaskRun.update_state_atomic(run.id, updates=marker)
+ if only_if_awaiting_first_message:
+ with transaction.atomic():
+ run = TaskRun.objects.select_for_update().get(id=run.id, task_id=task_id, team_id=team_id)
+ can_release = (
+ not run.is_terminal
+ and bool((run.state or {}).get("await_user_message"))
+ and not (run.state or {}).get("warm_activation_started")
+ )
+ if can_release:
+ run.state = {**(run.state or {}), **marker}
+ run.save(update_fields=["state", "updated_at"])
+ if not can_release:
+ return "already_activated", tasks_api._task_run_detail_to_dto(run)
+ else:
+ TaskRun.update_state_atomic(run.id, updates=marker)
except Exception:
logger.warning("Failed to record cancel request marker for task run %s", run.id, exc_info=True)
+ if only_if_awaiting_first_message:
+ return "unavailable", tasks_api._task_run_detail_to_dto(run)
_interrupt_agent_turn(run, requested_by_user_id, requested_by_distinct_id)
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 473fb9fe6a29..290bda274b7d 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -19,6 +19,7 @@ from posthog.models import Integration, User
from products.tasks.backend.facade import (
access as tasks_access,
api as facade,
+ cancellation as cancellation_facade,
contracts,
)
from products.tasks.backend.logic.services.staged_artifacts import (
@@ -634,6 +635,14 @@ class TestCreateTaskWarmReuse(APIBaseTest):
assert Task.objects.filter(team=self.team, deleted=False).count() == 2
+ def test_creates_a_cold_task_when_warm_release_is_still_pending(self) -> None:
+ warm_task, _ = self._warm_run(extra_state={"cancel_requested_at": "2026-01-01T00:00:00Z"})
+ with patch(f"{FACADE}.signal_task_run_user_message") as signal:
+ created = self._create()
+
+ assert str(created.id) != str(warm_task.id)
+ signal.assert_not_called()
+
def test_reuses_matching_warm_task_and_activates_it_in_place(self) -> None:
warm_task, run = self._warm_run()
handle = MagicMock(signal=AsyncMock())
@@ -816,6 +825,12 @@ class TestCreateTaskWarmReuse(APIBaseTest):
run.refresh_from_db()
assert run.state["await_user_message"] is True
assert not run.state.get("warm_activated")
+ with patch("products.tasks.backend.facade.cancellation._interrupt_agent_turn") as interrupt:
+ cancel_outcome, _ = cancellation_facade.cancel_task_run(
+ run.id, run.task_id, self.team.id, only_if_awaiting_first_message=True
+ )
+ assert cancel_outcome == "already_activated"
+ interrupt.assert_not_called()
def test_reuses_warm_task_with_new_reasoning_effort_and_attachments(self):
warm_task, run = self._warm_run(
@@ -1189,6 +1204,65 @@ class TestWarmRunRelease(APIBaseTest):
assert response.status_code == expected_status, response.content
assert m_signal.called is expect_signal
+ def test_release_during_first_message_delivery_does_not_cancel_the_run(self) -> None:
+ run = self._run(awaiting=True)
+
+ def release_during_delivery(*args: object, **kwargs: object) -> bool:
+ outcome, _ = cancellation_facade.cancel_task_run(
+ run.id, self.task.id, self.team.id, only_if_awaiting_first_message=True
+ )
+ assert outcome == "already_activated"
+ return True
+
+ with (
+ patch(f"{FACADE}.signal_task_run_user_message", side_effect=release_during_delivery),
+ patch("products.tasks.backend.facade.cancellation._interrupt_agent_turn") as interrupt,
+ patch("products.tasks.backend.facade.cancellation._signal_complete_task") as cancel_signal,
+ ):
+ facade._deliver_warm_run_message(run, message="Continue the example task", artifact_ids=[])
+
+ interrupt.assert_not_called()
+ cancel_signal.assert_not_called()
+ run.refresh_from_db()
+ assert run.state["warm_activated"] is True
+ assert "cancel_requested_at" not in run.state
+
+ def test_release_claim_prevents_activation_before_cancellation_finishes(self) -> None:
+ run = self._run(awaiting=True)
+
+ def activate_during_cancellation(*args: object, **kwargs: object) -> None:
+ with self.assertRaises(facade.WarmRunActivationUnavailable) as caught:
+ facade._deliver_warm_run_message(run, message="Continue the example task", artifact_ids=[])
+ assert caught.exception.reason == "target_unavailable"
+
+ with (
+ patch(
+ "products.tasks.backend.facade.cancellation._interrupt_agent_turn",
+ side_effect=activate_during_cancellation,
+ ),
+ patch("products.tasks.backend.facade.cancellation._signal_complete_task", return_value="signaled"),
+ patch(f"{FACADE}.signal_task_run_user_message") as deliver,
+ ):
+ response = self._release(run)
+
+ assert response.status_code == status.HTTP_202_ACCEPTED, response.content
+ deliver.assert_not_called()
+
+ def test_release_does_not_cancel_if_its_claim_cannot_be_saved(self) -> None:
+ run = self._run(awaiting=True)
+ with (
+ patch.object(TaskRun, "save", side_effect=RuntimeError("Cannot persist the claim")),
+ patch("products.tasks.backend.facade.cancellation._interrupt_agent_turn") as interrupt,
+ patch("products.tasks.backend.facade.cancellation._signal_complete_task") as cancel_signal,
+ ):
+ outcome, _ = cancellation_facade.cancel_task_run(
+ run.id, self.task.id, self.team.id, only_if_awaiting_first_message=True
+ )
+
+ assert outcome == "unavailable"
+ interrupt.assert_not_called()
+ cancel_signal.assert_not_called()
+
class TestWarmTaskResumeSandbox(APIBaseTest):
def test_warms_and_activates_a_successor_for_the_latest_terminal_run(self):