:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): prewarm resumed task sandboxes (#85445)
Georgiy Tarasov5ab3eef3a4bf
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 221019c1e8e7..9a88cfc322e6 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -8,8 +8,10 @@ import { initKeaTests } from '~/test/init'import {tasksRunCreate,+ tasksRunsCancelCreate,tasksRunsClearConversationCreate,tasksRunsCommandCreate,+ tasksWarmResumeCreate,} from 'products/tasks/frontend/generated/api'import { contextItemLine } from '../utils/posthogContextBlock'@@ -34,6 +36,7 @@ jest.mock('./runStreamLogic', () => {cancelRun: (run?: unknown) => ({ run }),markTurnComplete: true,setCurrentMode: (mode: string) => ({ mode }),+ handleTerminalStatus: (status: string) => ({ status }),setStubStatus: (status: string | null) => ({ status }),setStubThinking: (thinking: boolean) => ({ thinking }),setStubClearSupported: (supported: boolean) => ({ supported }),@@ -43,6 +46,7 @@ jest.mock('./runStreamLogic', () => {'in_progress',{setStubStatus: (_: string | null, { status }: { status: string | null }) => status,+ handleTerminalStatus: (_: string | null, { status }: { status: string }) => status,},],isThinking: [@@ -95,6 +99,8 @@ jest.mock('products/tasks/frontend/generated/api', () => ({tasksRunsCommandCreate: jest.fn(),tasksRunCreate: jest.fn(),tasksRunsClearConversationCreate: jest.fn(),+ tasksWarmResumeCreate: jest.fn(),+ tasksRunsCancelCreate: jest.fn(),}))jest.mock('lib/lemon-ui/LemonToast', () => ({@@ -136,6 +142,7 @@ describe('runInteractionLogic', () => {;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({});(tasksRunCreate as jest.Mock).mockResolvedValue({ latest_run: { id: 'run-2' } });(tasksRunsClearConversationCreate as jest.Mock).mockResolvedValue({})+ ;(tasksWarmResumeCreate as jest.Mock).mockResolvedValue({ task_id: TASK_ID, run_id: 'warm-run' })initKeaTests()project = projectLogic()project.mount()@@ -380,6 +387,33 @@ describe('runInteractionLogic', () => {expect(logic.values.composerForm.draft).toBe('')})+ it('warms the resumed run while composing and consumes it before submit', async () => {+ 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',+ })++ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect(tasksRunCreate).toHaveBeenCalledWith(+ '997',+ TASK_ID,+ expect.objectContaining({ resume_from_run_id: RUN_ID })+ )+ })+it('records the boundary instead of starting a run when /clear is sent to a terminal run', async () => {setStatus('completed')logic.actions.setComposerFormValues({ draft: '/clear' })@@ -399,6 +433,29 @@ describe('runInteractionLogic', () => {])})+ it('hands back a warmed successor when /clear succeeds', async () => {+ // The successor booted before the clear boundary was written, so its restored session still+ // holds the conversation /clear promises to remove. Keeping it would let the next message+ // resume the very thing the user just cleared.+ jest.useFakeTimers()+ setStatus('completed')+ logic.actions.setComposerFormValues({ draft: 'keep going' })+ jest.advanceTimersByTime(300)+ jest.useRealTimers()+ await expectLogic(logic).toFinishAllListeners()+ expect(tasksWarmResumeCreate).toHaveBeenCalled()++ logic.actions.setComposerFormValues({ draft: '/clear' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect(tasksRunsClearConversationCreate).toHaveBeenCalled()+ expect(tasksRunsCancelCreate).toHaveBeenCalledWith('997', TASK_ID, 'warm-run', {+ only_if_awaiting_first_message: true,+ })+ })+it('falls back to a new run when the chain agent cannot honour the clear boundary', async () => {// An older agent ignores the marker and resumes the conversation it was meant to retire,// so a divider here would claim a clear that never happens.@@ -711,11 +768,20 @@ describe('runInteractionLogic', () => {const blockedLogic = runInteractionLogic({ taskId: TASK_ID, runId: blockedRunId, onRunStarted })blockedLogic.mount()+ // Terminal, so typing would otherwise warm a successor — which boots a cloud sandbox and+ // restores the repository snapshot, before the organization has accepted anything.+ ;(blockedStream.actions as unknown as { setStubStatus: (status: string | null) => void }).setStubStatus(+ 'completed'+ )+ jest.useFakeTimers()blockedLogic.actions.setComposerFormValues({ draft: 'ship it' })+ jest.advanceTimersByTime(300)+ jest.useRealTimers()await expectLogic(blockedLogic, () => {blockedLogic.actions.submitComposerForm()}).toFinishAllListeners()+ expect(tasksWarmResumeCreate).not.toHaveBeenCalled()expect(tasksRunsCommandCreate).not.toHaveBeenCalled()expect(tasksRunCreate).not.toHaveBeenCalled()expect(blockedLogic.values.consentBlocked).toBe(true)diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 11849416900b..0672bae643ae 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -27,6 +27,7 @@ import {type ModelChoiceApi,type ReasoningEffortEnumApi,RuntimeAdapterEnumApi,+ type WarmTaskResumeRequestApi,} from 'products/tasks/frontend/generated/api.schemas'import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'@@ -36,6 +37,7 @@ import { attachedContextLogic } from './attachedContextLogic'import { modelCatalogueLogic } from './modelCatalogueLogic'import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'import type { RunStatus } from './runStreamLogic'+import { taskWarmLogic } from './taskWarmLogic'import { toolStreamEventsLogic } from './toolStreamEventsLogic'export interface RunInteractionLogicProps {@@ -165,6 +167,15 @@ export interface runInteractionLogicActions {}| undefined} // runStreamLogic+ handleTerminalStatus: (status: {+ errorMessage?: string | null+ replayedFromHistory?: boolean+ status: RunStatus+ }) => {+ errorMessage?: string | null | undefined+ replayedFromHistory?: boolean | undefined+ status: RunStatus+ } // runStreamLogicmarkTurnComplete: () => {value: true} // runStreamLogic@@ -188,6 +199,19 @@ export interface runInteractionLogicActions {setCurrentMode: (mode: string) => {mode: string} // runStreamLogic+ consumeWarm: () => {+ value: true+ } // taskWarmLogic+ noteDraft: (+ hasText: boolean,+ request: import('./taskWarmLogic').TaskWarmRequest+ ) => {+ hasText: boolean+ request: import('./taskWarmLogic').TaskWarmRequest+ } // taskWarmLogic+ releaseWarm: () => {+ value: true+ } // taskWarmLogicclaimApplyBackTargets: (streamKey: string) => {streamKey: string} // toolStreamEventsLogic@@ -402,11 +426,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>(['cancelRun','markTurnComplete','setCurrentMode',+ 'handleTerminalStatus',],attachedContextLogic,['markContextSent'],toolStreamEventsLogic,['claimApplyBackTargets', 'transferApplyBackTargets', 'releaseApplyBackTargets'],+ taskWarmLogic({ taskId: props.taskId, resumeFromRunId: props.runId }),+ ['noteDraft', 'consumeWarm', 'releaseWarm'],],})),@@ -679,6 +706,23 @@ export const runInteractionLogic = kea<runInteractionLogicType>([}),listeners(({ actions, values, props }) => {+ 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+ // accepts AI data processing.+ if (!values.isTerminal || !values.dataProcessingAccepted) {+ return+ }+ const createRequest = buildRunCreateRequest(+ values.catalogue,+ values.selectedModel,+ values.selectedEffort,+ values.selectedMode,+ { resume_from_run_id: props.runId }+ )+ actions.noteDraft(Boolean(values.composerForm.draft.trim()), createRequest as WarmTaskResumeRequestApi)+ }+// Record the non-text refs just wrapped into a send under the task, so no later send anywhere in// the task's resume chain (including the next run after a terminal-run send) re-inflates them.const markPendingContextSent = (pendingContext: AttachedContextItem[]): void => {@@ -807,8 +851,15 @@ export const runInteractionLogic = kea<runInteractionLogicType>([if (resolvedEffort !== currentEffort) {actions.setEffort(resolvedEffort)}+ noteTerminalDraft()},+ setEffort: noteTerminalDraft,+ setMode: noteTerminalDraft,+ setComposerFormValue: noteTerminalDraft,+ setComposerFormValues: noteTerminalDraft,+ handleTerminalStatus: noteTerminalDraft,+startNewRun: async ({ content }) => {if (values.startingRun || !content.trim() || values.currentProjectId == null) {return@@ -833,6 +884,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([pending_user_message: wrapWithPosthogContext(content, pendingContext),})+ actions.consumeWarm()const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)actions.resetComposerForm()markPendingContextSent(pendingContext)@@ -859,6 +911,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([actions.setClearing(true)try {await tasksRunsClearConversationCreate(String(values.currentProjectId), props.taskId, props.runId)+ // Any successor held right now was warmed before this boundary was written, so its+ // restored session still carries the conversation the clear just removed. Hand it+ // back; the next keystroke warms a fresh one on the cleared state.+ actions.releaseWarm()actions.resetComposerForm()// A finished run has no live stream to echo these back, so paint them from here.// They match what the backend persisted, so a later replay folds the same thread.diff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.test.tsindex eb0b2aca34e4..6567e7bb2af5 100644--- a/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts@@ -83,6 +83,27 @@ describe('taskWarmLogic', () => {expect(cancelledRuns).toEqual([])})+ it('warms again for the next draft after a submit consumed the previous warm', async () => {+ jest.useFakeTimers()+ logic.actions.noteDraft(true, WARM_REQUEST)+ jest.advanceTimersByTime(300)+ jest.useRealTimers()+ await expectLogic(logic).toFinishAllListeners()+ expect(warmCalls).toBe(1)++ logic.actions.consumeWarm()+ await expectLogic(logic).toFinishAllListeners()++ jest.useFakeTimers()+ logic.actions.noteDraft(true, WARM_REQUEST)+ jest.advanceTimersByTime(300)+ jest.useRealTimers()+ await expectLogic(logic).toFinishAllListeners()++ expect(warmCalls).toBe(2)+ expect(logic.values.warmLease).toMatchObject({ taskId: 'warm-task-2', runId: 'warm-run-2' })+ })+it('releases the warm when the draft is abandoned', async () => {jest.useFakeTimers()logic.actions.noteDraft(true, WARM_REQUEST)@@ -161,6 +182,38 @@ describe('taskWarmLogic', () => {expect(warmCalls).toBe(1)})+ it('warms a fresh task through the create endpoint even when mounted under the new-task route', async () => {+ // The scene passes the `/tasks/:taskId` route param down, so this logic can be keyed on the `new`+ // sentinel. Routing on that prop sent the fresh-task body to `tasks/new/warm/`, which the server+ // rejects for a missing `resume_from_run_id` — the composer then never warmed at all.+ let resumeCalls = 0+ useMocks({+ post: {+ '/api/projects/:team/tasks/warm/': async () => {+ warmCalls += 1+ return [200, { task_id: 'warm-task-1', run_id: 'warm-run-1' }]+ },+ '/api/projects/:team/tasks/:taskId/warm/': async () => {+ resumeCalls += 1+ return [400, { attr: 'resume_from_run_id', code: 'required' }]+ },+ },+ })+ logic.unmount()+ logic = taskWarmLogic({ panelId: 'new-route', taskId: 'new' })+ logic.mount()++ jest.useFakeTimers()+ logic.actions.noteDraft(true, WARM_REQUEST)+ jest.advanceTimersByTime(300)+ jest.useRealTimers()+ await expectLogic(logic).toFinishAllListeners()++ expect(resumeCalls).toBe(0)+ expect(warmCalls).toBe(1)+ expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-1' })+ })+it('asks once per selection when the server answers that it did not warm', async () => {// An empty body ("flag off", "pool full", "integration didn't resolve") installs no lease, so// the lease check can't stop the next typing pause from asking again. Before the cooldown thatdiff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.tsindex ccfed0417f09..08226eafc313 100644--- a/products/posthog_ai/frontend/logics/taskWarmLogic.ts+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.ts@@ -3,8 +3,8 @@ import posthog from 'posthog-js'import { projectLogic } from 'scenes/projectLogic'-import { tasksRunsCancelCreate, tasksWarmCreate } from 'products/tasks/frontend/generated/api'-import type { WarmTaskRequestApi } from 'products/tasks/frontend/generated/api.schemas'+import { tasksRunsCancelCreate, tasksWarmCreate, tasksWarmResumeCreate } from 'products/tasks/frontend/generated/api'+import type { WarmTaskRequestApi, WarmTaskResumeRequestApi } from 'products/tasks/frontend/generated/api.schemas'/** Debounce before warming, measured from the keystroke that first made the draft non-empty. */const WARM_DEBOUNCE_MS = 250@@ -26,14 +26,26 @@ export interface WarmLease {export interface TaskWarmLogicProps {/** Matches `taskTrackerSceneLogicProps.panelId` so each composer instance owns its own lease. */panelId?: string+ taskId?: string+ resumeFromRunId?: string}+export type TaskWarmRequest = WarmTaskRequestApi | WarmTaskResumeRequestApi+/*** Build the lease key from the fields the backend matches a warm Run on. Reasoning effort is* deliberately excluded: activation applies the final effort before the first turn, so changing it must* not throw the warm away (`_find_idling_warm_run` omits it from the match for the same reason).*/-export function warmLeaseKey(request: WarmTaskRequestApi): string {+export function warmLeaseKey(request: TaskWarmRequest): string {+ if ('resume_from_run_id' in request) {+ return [+ request.resume_from_run_id,+ request.runtime_adapter ?? '',+ request.model ?? '',+ request.initial_permission_mode ?? '',+ ].join('|')+ }return [request.repository ?? '',(request.repositories ?? []).join(','),@@ -84,13 +96,13 @@ export interface taskWarmLogicActions {}noteDraft: (hasText: boolean,- request: WarmTaskRequestApi+ request: TaskWarmRequest) => {hasText: boolean- request: WarmTaskRequestApi+ request: TaskWarmRequest}- prewarm: (request: WarmTaskRequestApi) => {- request: WarmTaskRequestApi+ prewarm: (request: TaskWarmRequest) => {+ request: TaskWarmRequest}releaseWarm: () => {value: true@@ -125,15 +137,15 @@ export type taskWarmLogicType = MakeLogicType<export const taskWarmLogic = kea<taskWarmLogicType>([path(['products', 'posthog_ai', 'frontend', 'logics', 'taskWarmLogic']),props({} as TaskWarmLogicProps),- key((props) => props.panelId ?? 'scene'),+ key((props) => props.panelId ?? ([props.taskId, props.resumeFromRunId].filter(Boolean).join(':') || 'scene')),connect({values: [projectLogic, ['currentProjectId']],}),actions({- noteDraft: (hasText: boolean, request: WarmTaskRequestApi) => ({ hasText, request }),- prewarm: (request: WarmTaskRequestApi) => ({ request }),+ noteDraft: (hasText: boolean, request: TaskWarmRequest) => ({ hasText, request }),+ prewarm: (request: TaskWarmRequest) => ({ request }),releaseWarm: true,consumeWarm: true,setWarmLease: (lease: WarmLease | null) => ({ lease }),@@ -148,7 +160,7 @@ export const taskWarmLogic = kea<taskWarmLogicType>([],}),- listeners(({ actions, values, cache }) => ({+ listeners(({ actions, values, cache, props }) => ({noteDraft: ({ hasText, request }) => {if (!hasText) {// Draft emptied — drop a pending warm and schedule a release, so a user who clears the@@ -202,6 +214,15 @@ export const taskWarmLogic = kea<taskWarmLogicType>([if (values.currentProjectId == null || values.warmLease?.key === key) {return}+ // Route on the payload, not on `props.taskId`: the request shape is what each endpoint+ // accepts, and only a resume request names a source run. The scene composer mounts this logic+ // under the `/tasks/:taskId` route param, so `props.taskId` can be the `new` sentinel — a+ // fresh-task body posted to `tasks/new/warm/` is rejected for the missing `resume_from_run_id`+ // and that composer never warms at all.+ const resumeRequest = 'resume_from_run_id' in request ? request : null+ if (resumeRequest && !props.taskId) {+ return+ }if (cache.warming) {// Only one warm POST runs at a time. A newer selection that arrives mid-flight must not// be dropped, or the completing POST installs a lease on the stale selection and the@@ -223,7 +244,13 @@ export const taskWarmLogic = kea<taskWarmLogicType>([cache.pendingWarmRequest = nullcache.consumedWhileWarming = falsetry {- const warm = await tasksWarmCreate(String(values.currentProjectId), request)+ 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@@ -236,6 +263,12 @@ export const taskWarmLogic = kea<taskWarmLogicType>([// 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 })+ // 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+ // of waiting out the cooldown.+ cache.lastWarmRequestKey = null+ cache.lastWarmRequestAt = null}// The user may have abandoned the draft while this POST was in flight, in which case the// release hit the early-exit below with nothing to release. Honor that intent now so the@@ -290,6 +323,11 @@ export const taskWarmLogic = kea<taskWarmLogicType>([cache.disposables.dispose('warm-release')cache.pendingRelease = falsecache.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.+ 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 adiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex f010911d137e..10093822af4c 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -290,10 +290,10 @@ export interface taskTrackerSceneLogicActions {} // taskWarmLogicnoteDraft: (hasText: boolean,- request: WarmTaskRequestApi+ request: import('../../logics/taskWarmLogic').TaskWarmRequest) => {hasText: boolean- request: WarmTaskRequestApi+ request: import('../../logics/taskWarmLogic').TaskWarmRequest} // taskWarmLogicreleaseWarm: () => {value: true@@ -399,7 +399,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['overrideHeadlines'],modelCatalogueLogic,['catalogue'],- taskWarmLogic(props),+ // Only `panelId`: the scene is mounted with the `/tasks/:taskId` route param in its props, and+ // this composer always creates a fresh task, so a forwarded `taskId` would point the warm at+ // the resume endpoint for a task that doesn't exist yet.+ taskWarmLogic({ panelId: props.panelId }),['warmLease'],],actions: [@@ -415,7 +418,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['claimApplyBackTargets', 'releaseApplyBackTargets'],composerSeedLogic(props),['consumeSeed', 'setSeed'],- taskWarmLogic(props),+ taskWarmLogic({ panelId: props.panelId }),['noteDraft', 'consumeWarm', 'releaseWarm'],],})),diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ab28301353a5..53ce712ad8e8 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -54,6 +54,7 @@ from django.utils.http import content_disposition_headerimport posthoganalytics+from posthog.dataclasses import frozenfrom posthog.event_usage import groupsfrom posthog.models import Team, Userfrom posthog.models.integration import Integration@@ -5003,6 +5004,35 @@ def task_runtime(task_id: str | UUID, team_id: int, user_id: int | None, *, for_)+@frozen+class ControlVisibleTask:+ runtime: str+ origin_product: str+++def task_control_runtime_and_origin(+ task_id: str | UUID, team_id: int, user_id: int | None+) -> ControlVisibleTask | None:+ """The runtime and origin product of a task the user may drive, or ``None`` when it is not+ control-visible.++ One narrow control-predicate query for the warm-resume gate. The control predicate is a subset+ of the read predicate, so a control-visible task is always read-visible. This covers the same+ 404 gate as a read query plus a separate control ``EXISTS`` check. It does not load the detail+ DTO, prefetch every run, or presign the latest run's log URL.+ """+ row = (+ _visible_task_qs(team_id, user_id, for_control=True)+ .filter(id=task_id)+ .values_list("runtime", "origin_product")+ .first()+ )+ if row is None:+ return None+ runtime, origin_product = row+ return ControlVisibleTask(runtime=runtime, origin_product=origin_product)++def task_visible(task_id: str | UUID, team_id: int, user_id: int | None, *, for_control: bool = False) -> bool:"""Whether a non-deleted task exists for the team and is visible to the user.@@ -6364,6 +6394,168 @@ def warm_task_sandbox(return contracts.WarmTaskDTO(task_id=task.id, run_id=result.run.id)+def warm_task_resume_sandbox(+ task_id: str | UUID,+ team_id: int,+ user_id: int,+ *,+ resume_from_run_id: str | UUID,+ runtime_adapter: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,+ initial_permission_mode: str | None = None,+) -> contracts.WarmTaskDTO | None:+ """Warm a successor for the task's current terminal run while its next message is composed."""+ from rest_framework.exceptions import ( # noqa: PLC0415 — keep DRF exception types off the api import path+ PermissionDenied,+ Throttled,+ )++ from posthog.exceptions import QuotaLimitExceeded # noqa: PLC0415 — keep billing deps off the api import path++ from products.tasks.backend.logic.services.warm import ( # noqa: PLC0415 — keep warming deps off the api import path+ SandboxWarmer,+ WarmSourceChanged,+ )+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path+ get_pr_authorship_mode,+ get_provider_for_runtime_adapter,+ get_reasoning_effort_error,+ parse_run_state,+ )++ task = _visible_task_qs(team_id, user_id, for_control=True).select_related("team").filter(id=task_id).first()+ if task is None:+ return None++ previous_run = task.runs.filter(id=resume_from_run_id).first()+ if previous_run is None or not previous_run.is_terminal:+ return None+ if not previous_run.matches_task_ownership(task):+ # A handed-off task keeps its old runs stamped with the previous owner, so create_run would+ # reject this resume source with TaskOwnershipChangedError. Skip warming; the cold resume path+ # reports the friendly error when the person submits.+ return None+ latest_run = task.latest_run+ latest_state = (latest_run.state or {}) if latest_run is not None else {}+ latest_is_expected_source = latest_run is not None and latest_run.id == previous_run.id+ latest_is_expected_warm = (+ latest_run is not None+ and not latest_run.is_terminal+ and latest_state.get("await_user_message") is True+ and latest_state.get("resume_from_run_id") == str(previous_run.id)+ )+ # A successor the composer handed back (or the reaper took) is terminal and sits in front of its+ # own source, so neither test above sees it. Without this the first release would leave the task+ # unable to warm again until it was submitted — and releases are routine: an emptied draft, a+ # changed model or mode, or leaving the composer. The source fence still holds, because the+ # released successor has to have been warmed for this same run.+ latest_is_released_warm = (+ latest_run is not None+ and latest_run.is_terminal+ and latest_state.get("prewarmed") is True+ and latest_state.get("await_user_message") is True+ and latest_state.get("resume_from_run_id") == str(previous_run.id)+ )+ if not latest_is_expected_source and not latest_is_expected_warm and not latest_is_released_warm:+ return None++ previous_state = parse_run_state(previous_run.state)+ resolved_runtime_adapter = runtime_adapter or previous_state.runtime_adapter+ resolved_model = model or previous_state.model+ resolved_reasoning_effort = reasoning_effort or previous_state.reasoning_effort+ resolved_permission_mode = initial_permission_mode or previous_state.initial_permission_mode or "default"+ reasoning_effort_error = get_reasoning_effort_error(+ runtime_adapter=resolved_runtime_adapter,+ model=resolved_model,+ reasoning_effort=resolved_reasoning_effort,+ )+ if reasoning_effort_error is not None:+ return None++ user = User.objects.get(pk=user_id)+ model_access_error = get_model_access_error(resolved_model, distinct_id=user.distinct_id)+ if model_access_error is not None:+ return None++ resolved_pr_authorship_mode, validation_error = _resolve_cloud_pr_authorship_mode(+ task,+ pr_authorship_mode=get_pr_authorship_mode(task, previous_run.state),+ request_user_id=user_id,+ github_user_token=None,+ )+ if validation_error is not None:+ return None++ branch = previous_state.pr_base_branch+ sandbox_environment_id = previous_state.sandbox_environment_id+ custom_image_id = (previous_run.state or {}).get("custom_image_id")+ if not _warm_sandbox_selection_is_accessible(+ team_id=team_id,+ task_created_by_id=task.created_by_id,+ sandbox_environment_id=sandbox_environment_id,+ custom_image_id=custom_image_id,+ ):+ return None++ def state_value(value: object | None) -> object | None:+ return value.value if hasattr(value, "value") else value++ extra_state: dict[str, Any] = {+ "branch": branch,+ "pr_base_branch": branch,+ "pr_authorship_mode": state_value(resolved_pr_authorship_mode),+ "auto_publish": previous_state.auto_publish,+ "run_source": state_value(previous_state.run_source),+ "signal_report_id": previous_state.signal_report_id,+ "runtime_adapter": state_value(resolved_runtime_adapter),+ "provider": state_value(get_provider_for_runtime_adapter(resolved_runtime_adapter)),+ "model": resolved_model,+ "reasoning_effort": state_value(resolved_reasoning_effort),+ "context_window": previous_state.context_window,+ "fast_mode": previous_state.fast_mode,+ "initial_permission_mode": state_value(resolved_permission_mode),+ "sandbox_environment_id": sandbox_environment_id,+ "custom_image_id": custom_image_id,+ }+ extra_state.update(_github_credential_source_extra_state(resolved_pr_authorship_mode, None))+ for protected_key in ("wizard_head_branch", "self_driving_head_branch", "github_read_access"):+ if protected_key in (previous_run.state or {}):+ extra_state[protected_key] = (previous_run.state or {})[protected_key]+ extra_state = {key: value for key, value in extra_state.items() if value is not None}+ stable_selection = {+ key: value+ for key, value in extra_state.items()+ if key+ in {+ "branch",+ "runtime_adapter",+ "model",+ "context_window",+ "fast_mode",+ "initial_permission_mode",+ "sandbox_environment_id",+ "custom_image_id",+ "pr_authorship_mode",+ "github_credential_source",+ }+ }++ try:+ result = SandboxWarmer(task, user=user).warm(+ mode="interactive",+ extra_state=extra_state,+ create_pr=True,+ expected_resume_from_run_id=previous_run.id,+ required_existing_state=stable_selection,+ )+ except (PermissionDenied, QuotaLimitExceeded, Throttled, WarmSourceChanged, TaskOwnershipChangedError):+ # TaskOwnershipChangedError guards a handoff that lands after the check above but before the+ # locked create_run, keeping this best-effort endpoint from returning a server error.+ return None+ return contracts.WarmTaskDTO(task_id=task.id, run_id=result.run.id)++# --- Task run (the ``run`` action) ---@@ -6412,6 +6604,22 @@ def run_task(pending_user_message = validated_data.get("pending_user_message")pending_user_artifact_ids = validated_data.get("pending_user_artifact_ids") or []is_pi_task = task.runtime == Task.Runtime.PI+ previous_run: TaskRun | None = None+ previous_state = None+ if resume_from_run_id:+ previous_run = task.runs.filter(id=resume_from_run_id).first()+ if previous_run is None:+ return contracts.TaskRunResult(+ error=contracts.TaskValidationError(kind="detail", detail="Invalid resume_from_run_id")+ )+ if not previous_run.matches_task_ownership(task):+ return contracts.TaskRunResult(+ error=contracts.TaskValidationError(+ kind="detail",+ detail="This run belongs to a previous task owner. Start a new run instead.",+ )+ )+ previous_state = parse_run_state(previous_run.state)if branch is None and not resume_from_run_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:# The inbox "Create PR" button sends no branch, so without this the run would target the@@ -6426,10 +6634,38 @@ def run_task(team_id, task.repositories[0] if task.repositories else task.repository)- if not resume_from_run_id:- warm_run = _idling_warm_run_for_task(task)- if warm_run is not None and (branch or None) == (warm_run.branch or None):- warm_state = warm_run.state or {}+ warm_run = _idling_warm_run_for_task(task)+ if warm_run is not None:+ 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+ # a run asked to start fresh would silently inherit it.+ warm_resume_matches = (warm_state.get("resume_from_run_id") or None) == (+ str(resume_from_run_id) if resume_from_run_id else None+ )+ effective_branch = branch+ if effective_branch is None and previous_state is not None:+ effective_branch = previous_state.pr_base_branch+ if warm_resume_matches and (effective_branch or None) == (warm_run.branch or None):+ desired_runtime_adapter = validated_data.get("runtime_adapter")+ desired_model = validated_data.get("model")+ desired_context_window = validated_data.get("context_window")+ desired_fast_mode = validated_data.get("fast_mode")+ desired_sandbox_environment_id = validated_data.get("sandbox_environment_id")+ desired_custom_image_id = validated_data.get("custom_image_id")+ if previous_state is not None:+ assert previous_run is not None+ desired_runtime_adapter = desired_runtime_adapter or previous_state.runtime_adapter+ desired_model = desired_model or previous_state.model+ desired_context_window = desired_context_window or previous_state.context_window+ if desired_fast_mode is None:+ desired_fast_mode = previous_state.fast_mode+ desired_sandbox_environment_id = desired_sandbox_environment_id or previous_state.sandbox_environment_id+ desired_custom_image_id = desired_custom_image_id or (previous_run.state or {}).get("custom_image_id")++ def state_value(value: object | None) -> object | None:+ return value.value if hasattr(value, "value") else value+warm_runtime_matches = (warm_state.get("runtime_adapter") or None,warm_state.get("model") or None,@@ -6438,18 +6674,30 @@ def run_task(warm_state.get("sandbox_environment_id") or None,warm_state.get("custom_image_id") or None,) == (- validated_data.get("runtime_adapter") or None,- validated_data.get("model") or None,- validated_data.get("context_window") or None,- validated_data.get("fast_mode") or None,- str(validated_data["sandbox_environment_id"]) if validated_data.get("sandbox_environment_id") else None,- str(validated_data["custom_image_id"]) if validated_data.get("custom_image_id") else None,+ state_value(desired_runtime_adapter) or None,+ desired_model or None,+ desired_context_window or None,+ desired_fast_mode or None,+ str(desired_sandbox_environment_id) if desired_sandbox_environment_id else None,+ str(desired_custom_image_id) if desired_custom_image_id else None,)- if warm_runtime_matches and _warm_sandbox_selection_is_accessible(- team_id=team_id,- task_created_by_id=task.created_by_id,- sandbox_environment_id=warm_state.get("sandbox_environment_id"),- custom_image_id=warm_state.get("custom_image_id"),+ requested_permission_mode = validated_data.get("initial_permission_mode")+ if previous_state is not None:+ requested_permission_mode = (+ requested_permission_mode or previous_state.initial_permission_mode or "default"+ )+ warm_permission_matches = requested_permission_mode is None or warm_state.get(+ "initial_permission_mode"+ ) == state_value(requested_permission_mode)+ if (+ warm_runtime_matches+ and warm_permission_matches+ and _warm_sandbox_selection_is_accessible(+ team_id=team_id,+ task_created_by_id=task.created_by_id,+ sandbox_environment_id=warm_state.get("sandbox_environment_id"),+ custom_image_id=warm_state.get("custom_image_id"),+ )):warm_staged_artifacts, warm_missing_artifact_ids = (get_task_staged_artifacts(task, pending_user_artifact_ids)@@ -6522,20 +6770,8 @@ def run_task(extra_state["rtk_enabled"] = rtk_enabledif resume_from_run_id:- previous_run = task.runs.filter(id=resume_from_run_id).first()- if not previous_run:- return contracts.TaskRunResult(- error=contracts.TaskValidationError(kind="detail", detail="Invalid resume_from_run_id")- )- if not previous_run.matches_task_ownership(task):- return contracts.TaskRunResult(- error=contracts.TaskValidationError(- kind="detail",- detail="This run belongs to a previous task owner. Start a new run instead.",- )- )-- prev_state = parse_run_state(previous_run.state)+ assert previous_run is not None and previous_state is not None+ prev_state = previous_stateextra_state = extra_state or {}if not is_pi_task:extra_state["resume_from_run_id"] = str(resume_from_run_id)@@ -6725,6 +6961,7 @@ def run_task(except TaskOwnershipChangedError:return Noneif is_pi_task and resume_from_run_id:+ assert previous_run is not Nonetask_run.active_task_session = previous_run.active_task_sessiontask_run.save(update_fields=["active_task_session", "updated_at"])diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 639df0113564..6ead2abe5ddf 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -432,6 +432,13 @@ class SandboxBase(ABC):)return result.exit_code == 0+ def agent_server_supports_prewarmed_resume_idle(self) -> bool:+ result = self.execute(+ "grep -q prewarmedResumeIdle /scripts/node_modules/.bin/agent-server",+ timeout_seconds=10,+ )+ return result.exit_code == 0+def clone_repository(self,repository: str,diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.pyindex e285c9695545..d0ed08d34688 100644--- a/products/tasks/backend/logic/services/tests/test_warm.py+++ b/products/tasks/backend/logic/services/tests/test_warm.py@@ -5,7 +5,7 @@ from rest_framework.exceptions import PermissionDenied, Throttledfrom posthog.exceptions import QuotaLimitExceeded-from products.tasks.backend.logic.services.warm import SandboxWarmer+from products.tasks.backend.logic.services.warm import SandboxWarmer, WarmSourceChangedfrom products.tasks.backend.models import Task, TaskRunWARM = "products.tasks.backend.logic.services.warm"@@ -93,6 +93,38 @@ class TestSandboxWarmerWarm(APIBaseTest):assert result.run.state["snapshot_external_id"] == "snap-1"m_workflow.assert_called_once()+ def test_expected_resume_source_is_idempotent_and_rejects_a_stale_selection(self):+ task = self._task()+ terminal = task.create_run(mode="interactive")+ terminal.status = TaskRun.Status.CANCELLED+ terminal.save(update_fields=["status"])++ with (+ patch(f"{WARM}.execute_task_processing_workflow"),+ patch(f"{WARM}.is_team_limited", return_value=False),+ self.captureOnCommitCallbacks(execute=True),+ ):+ first = SandboxWarmer(task, user=self.user).warm(+ extra_state={"model": "claude-sonnet-5"},+ expected_resume_from_run_id=terminal.id,+ required_existing_state={"model": "claude-sonnet-5"},+ )+ repeated = SandboxWarmer(task, user=self.user).warm(+ extra_state={"model": "claude-sonnet-5"},+ expected_resume_from_run_id=terminal.id,+ required_existing_state={"model": "claude-sonnet-5"},+ )++ with self.assertRaises(WarmSourceChanged):+ SandboxWarmer(task, user=self.user).warm(+ extra_state={"model": "claude-opus-5"},+ expected_resume_from_run_id=terminal.id,+ required_existing_state={"model": "claude-opus-5"},+ )++ assert repeated.run.id == first.run.id+ assert task.runs.count() == 2+def test_dispatch_is_deferred_to_commit(self):# No captureOnCommitCallbacks: the test transaction never commits, so the on_commit dispatch# must not fire — proving provisioning isn't done inside the atomic block.diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.pyindex 87c89f83ee1c..4757a9e98fd2 100644--- a/products/tasks/backend/logic/services/warm.py+++ b/products/tasks/backend/logic/services/warm.py@@ -15,6 +15,7 @@ quota gate before it can warm.from collections.abc import Callablefrom dataclasses import dataclassfrom typing import Any+from uuid import UUIDfrom django.db import transaction@@ -44,6 +45,10 @@ class WarmResult:just_created: bool+class WarmSourceChanged(Exception):+ pass++@dataclass(frozen=True)class WarmPoolCaps:per_user: int@@ -131,7 +136,13 @@ class SandboxWarmer:return warm_runs.filter(task__team__organization_id=team.organization_id).count() >= caps.per_orgdef warm(- self, *, mode: str = "interactive", extra_state: dict[str, Any] | None = None, create_pr: bool = False+ self,+ *,+ mode: str = "interactive",+ extra_state: dict[str, Any] | None = None,+ create_pr: bool = False,+ expected_resume_from_run_id: str | UUID | None = None,+ required_existing_state: dict[str, Any] | None = None,) -> WarmResult:"""Idempotently ensure the Task has a warm Run, then dispatch the processing workflow after commit.@@ -154,9 +165,43 @@ class SandboxWarmer:locked = Task.objects.select_for_update().get(id=self.task.id)existing = locked.latest_runif existing is not None and not existing.is_terminal:+ if expected_resume_from_run_id is not None:+ existing_state = existing.state or {}+ expected_resume_id = str(expected_resume_from_run_id)+ matches_resume_source = (+ existing_state.get("await_user_message") is True+ and existing_state.get("resume_from_run_id") == expected_resume_id+ )+ matches_required_state = all(+ existing_state.get(key) == value for key, value in (required_existing_state or {}).items()+ )+ if not matches_resume_source or not matches_required_state:+ raise WarmSourceChanged# A warm Run already idling, or an active Run in progress — either way, no double-provision.return WarmResult(run=existing, just_created=False)+ # The Run the successor resumes from. Normally the latest Run is the source itself, but a+ # successor the composer already handed back is terminal and sits in front of it — resume+ # from the source the caller named rather than from that dead successor, whose own+ # `resume_from_run_id` would otherwise be lost and leave the new warm unrecognizable as a+ # successor of the source.+ resume_source = existing+ if expected_resume_from_run_id is not None:+ if existing is None:+ raise WarmSourceChanged+ if str(existing.id) != str(expected_resume_from_run_id):+ existing_state = existing.state or {}+ released_successor = (+ existing_state.get("prewarmed") is True+ and existing_state.get("await_user_message") is True+ and existing_state.get("resume_from_run_id") == str(expected_resume_from_run_id)+ )+ if not released_successor:+ raise WarmSourceChanged+ resume_source = locked.runs.filter(id=expected_resume_from_run_id).first()+ if resume_source is None:+ raise WarmSourceChanged+if self.at_capacity(locked.origin_product, locked.team, self.user):raise Throttled(detail="Warm-pool capacity reached. Release an idle warm session and try again.")@@ -166,10 +211,10 @@ class SandboxWarmer:"initial_permission_mode": "default",**(extra_state or {}),}- if existing is not None:+ if resume_source is not None:# Latest Run is terminal — resume into a successor so the warm session reuses its filesystem.- run_state["resume_from_run_id"] = str(existing.id)- run_state.update(parse_run_state(existing.state).resume_snapshot_carry_state())+ run_state["resume_from_run_id"] = str(resume_source.id)+ run_state.update(parse_run_state(resume_source.state).resume_snapshot_carry_state())new_run = locked.create_run(mode=mode, extra_state=run_state, branch=run_state.get("branch"))diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex fc7205d1234f..dcdac445925a 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -3339,6 +3339,92 @@ class WarmTaskResponseSerializer(serializers.Serializer):)+class WarmTaskResumeRequestSerializer(serializers.Serializer):+ """Request body for warming a successor to an existing terminal task run."""++ resume_from_run_id = serializers.UUIDField(+ help_text="ID of the task's latest terminal run whose snapshot and conversation should be resumed.",+ )+ runtime_adapter = serializers.ChoiceField(+ choices=[adapter.value for adapter in RuntimeAdapter],+ required=False,+ default=None,+ help_text="Agent runtime adapter to start before the next message is submitted.",+ )+ model = serializers.CharField(+ required=False,+ default=None,+ allow_blank=False,+ help_text="LLM model to start before the next message is submitted.",+ )+ reasoning_effort = serializers.ChoiceField(+ choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS],+ required=False,+ default=None,+ help_text="Reasoning effort to apply when the warmed successor receives its first message.",+ )+ initial_permission_mode = serializers.ChoiceField(+ choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,+ required=False,+ default=None,+ help_text="Initial permission mode for the warmed successor's agent session.",+ )++ def validate(self, attrs):+ errors: dict[str, str] = {}+ runtime_adapter = attrs.get("runtime_adapter")+ model = attrs.get("model")+ if (runtime_adapter is None) != (model is None):+ missing_field = "runtime_adapter" if runtime_adapter is None else "model"+ errors[missing_field] = "This field is required when selecting a cloud runtime."++ initial_permission_mode = attrs.get("initial_permission_mode")+ if initial_permission_mode is not None:+ if runtime_adapter is None:+ errors["initial_permission_mode"] = "This field requires runtime_adapter to be set."+ else:+ allowed_permission_modes = (+ list(CODEX_INITIAL_PERMISSION_MODE_CHOICES)+ if runtime_adapter == RuntimeAdapter.CODEX.value+ else list(INITIAL_PERMISSION_MODE_CHOICES)+ )+ if initial_permission_mode not in allowed_permission_modes:+ allowed_values = ", ".join(f"'{value}'" for value in allowed_permission_modes)+ errors["initial_permission_mode"] = (+ f"Invalid choice '{initial_permission_mode}' for runtime_adapter "+ f"'{runtime_adapter}'. Supported values: {allowed_values}."+ )++ reasoning_effort_error = get_reasoning_effort_error(+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=attrs.get("reasoning_effort"),+ )+ if reasoning_effort_error is not None:+ errors["reasoning_effort"] = reasoning_effort_error+ _capture_rejected_reasoning_effort(+ self.context,+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=attrs.get("reasoning_effort"),+ error=reasoning_effort_error,+ )++ model_access_error = get_model_access_error(model, distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ errors["model"] = model_access_error+ if errors:+ raise serializers.ValidationError(errors)+ return attrs+++class WarmTaskResumeResponseSerializer(serializers.Serializer):+ """Response for a successfully warmed successor run on an existing task."""++ task_id = serializers.UUIDField(help_text="ID of the existing task being resumed.")+ run_id = serializers.UUIDField(help_text="ID of the idling successor run that submit will activate.")++class TaskRunStartRequestSerializer(serializers.Serializer):pending_user_message = serializers.CharField(required=False,diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 6f7f33766b56..ee523abc1d27 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -181,6 +181,8 @@ from products.tasks.backend.presentation.serializers import (TaskWriteSerializer,WarmTaskRequestSerializer,WarmTaskResponseSerializer,+ WarmTaskResumeRequestSerializer,+ WarmTaskResumeResponseSerializer,WizardCloudRunSerializer,)@@ -219,15 +221,20 @@ def _pi_cloud_runtime_disabled_response() -> Response:TASKS_PREWARM_SANDBOX_FLAG = "tasks-prewarm-sandbox"-POSTHOG_AI_PREWARM_SANDBOX_FLAG = "posthog-ai-prewarm-sandbox"-# One rollout per origin product — the Code app and PostHog AI reach different populations. An origin-# missing here cannot warm, which keeps the endpoint fail-closed for products that never opted in.+# One rollout per origin product — the Code app and PostHog AI reach different populations, so a shared+# flag would drag one to 100% while rolling out the other.WARM_SANDBOX_FLAGS_BY_ORIGIN_PRODUCT: dict[str, str] = {tasks_facade.TaskOriginProduct.USER_CREATED: TASKS_PREWARM_SANDBOX_FLAG,- tasks_facade.TaskOriginProduct.POSTHOG_AI: POSTHOG_AI_PREWARM_SANDBOX_FLAG,}+# Origins that warm for every user, with no flag left to evaluate.+WARM_SANDBOX_UNGATED_ORIGIN_PRODUCTS: frozenset[str] = frozenset(+ {+ tasks_facade.TaskOriginProduct.POSTHOG_AI,+ }+)+# Detail-route lookup pattern for viewsets keyed on a UUID primary key. Keeps the router from# matching an unknown collection path as a pk and passing a non-UUID string to the ORM.UUID_LOOKUP_REGEX = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"@@ -1088,9 +1095,11 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def _warm_enabled(self, origin_product: str) -> bool:"""Person + org level gate for the sandbox-warming feature. Fail-closed on any error.- One flag per origin product: the Code app and PostHog AI are disjoint populations, so a shared- flag would drag one to 100% while rolling out the other.+ An origin in neither the ungated set nor the flag map cannot warm, which keeps the endpoint+ fail-closed for products that never opted in."""+ if origin_product in WARM_SANDBOX_UNGATED_ORIGIN_PRODUCTS:+ return Trueflag = WARM_SANDBOX_FLAGS_BY_ORIGIN_PRODUCT.get(origin_product)if flag is None:return False@@ -1186,6 +1195,61 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return Response(status=status.HTTP_200_OK)return Response(WarmTaskResponseSerializer({"task_id": result.task_id, "run_id": result.run_id}).data)+ @extend_schema(operation_id="tasks_warm_resume_create")+ @validated_request(+ request_serializer=WarmTaskResumeRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=WarmTaskResumeResponseSerializer,+ description="Successor Run provisioned, or an empty body when warming is unavailable or the source run changed.",+ ),+ 403: OpenApiResponse(+ response=TaskRunErrorResponseSerializer, description="PostHog Desktop access is required"+ ),+ 404: OpenApiResponse(description="Task not found"),+ 429: OpenApiResponse(+ response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"+ ),+ },+ summary="Warm a resumed task sandbox",+ description=(+ "Warm an idling successor for the task's latest terminal Run while the user composes the next "+ "message. The successor restores the prior snapshot when compatible and waits for the normal "+ "run endpoint to activate it. Best-effort: returns an empty body when warming is disabled, capped, "+ "or the task advanced to another Run."+ ),+ include_serializer_context=True,+ )+ @action(detail=True, methods=["post"], url_path="warm", url_name="warm-resume", required_scopes=["task:write"])+ def warm_resume(self, request, pk=None, **kwargs):+ gate = tasks_facade.task_control_runtime_and_origin(pk, self.team_id, self._user_id())+ if gate is None:+ raise NotFound()+ if gate.runtime == tasks_facade.TaskRuntime.PI or not self._warm_enabled(gate.origin_product):+ return Response(status=status.HTTP_200_OK)+ if access_response := code_access_required_response(request, self.organization, task_id=pk):+ return access_response++ user_id = self._user_id()+ if user_id is None:+ return Response(status=status.HTTP_200_OK)+ if limit_response := usage_limit_response(request.user, self.team_id):+ return limit_response++ result = tasks_facade.warm_task_resume_sandbox(+ pk,+ self.team_id,+ user_id,+ resume_from_run_id=request.validated_data["resume_from_run_id"],+ runtime_adapter=request.validated_data.get("runtime_adapter"),+ model=request.validated_data.get("model"),+ reasoning_effort=request.validated_data.get("reasoning_effort"),+ initial_permission_mode=request.validated_data.get("initial_permission_mode"),+ )+ if result is None:+ return Response(status=status.HTTP_200_OK)+ return Response(WarmTaskResumeResponseSerializer({"task_id": result.task_id, "run_id": result.run_id}).data)+@staticmethoddef _task_error_response(error: tasks_contracts.TaskValidationError) -> Response:if error.kind == "error":diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.mdindex daa26f8b326b..93bfe53a455e 100644--- a/products/tasks/backend/temporal/process_task/README.md+++ b/products/tasks/backend/temporal/process_task/README.md@@ -52,7 +52,7 @@ User ─────────────────────────### PostHog API-`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming, checks server-side PostHog Desktop access before provisioning or activating a run. Composer prewarming carries the complete ordered repository selection, so single- and multi-repository submissions can reuse only a matching sandbox. Runtime, model, branch, and sandbox configuration must match; reasoning effort may change and is applied before the warmed agent's first turn. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.+`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming, checks server-side PostHog Desktop access before provisioning or activating a run. Composer prewarming carries the complete ordered repository selection, so single- and multi-repository submissions can reuse only a matching sandbox. A terminal task can also prewarm a successor through `POST .../tasks/{id}/warm/`; the source run must remain the task's latest terminal run, and the normal `run` request activates that successor with `resume_from_run_id`. Runtime, model, branch, permission mode, and sandbox configuration must match; reasoning effort may change and is applied before the warmed agent's first turn. Full-filesystem resume snapshots bundle their agent binary, so prewarming probes for the deferred-resume capability and falls back to a fresh sandbox when an old snapshot lacks it. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.### Temporal workflowdiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 2968651ad629..6c64044edaa5 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -20,6 +20,7 @@ from posthog.temporal.common.utils import asyncifyfrom products.context_layer.backend.facade import api as context_layer_facadefrom products.tasks.backend.constants import (DEV_STACK_IMAGE_NAME,+ SNAPSHOT_KIND_DIRECTORY,SNAPSHOT_KIND_FILESYSTEM,TASK_SIGNALS_CLONING_BLOBLESS_FEATURE_FLAG,filter_user_sandbox_env_vars,@@ -287,6 +288,29 @@ def _apply_modal_network_policy(config.network_policy_fingerprint = ctx.network_policy_fingerprint+def _prewarmed_resume_needs_fresh_agent(+ ctx: TaskProcessingContext,+ prepared: PrepareSandboxForRepositoryOutput,+ sandbox: SandboxBase,+ *,+ used_snapshot: bool,+) -> bool:+ """Whether a full resume snapshot bundled an agent that cannot idle before the resumed prompt."""+ if (+ not used_snapshot+ or prepared.snapshot_external_id is None+ or prepared.snapshot_kind == SNAPSHOT_KIND_DIRECTORY+ or not (ctx.state or {}).get("prewarmed")+ or not (ctx.state or {}).get("resume_from_run_id")+ ):+ return False+ try:+ return not sandbox.agent_server_supports_prewarmed_resume_idle()+ except Exception:+ logger.warning("prewarmed_resume_agent_capability_probe_failed", extra={"run_id": ctx.run_id})+ return True++def _is_blobless_signals_clone_enabled(ctx: TaskProcessingContext) -> bool:if ctx.origin_product != Task.OriginProduct.SIGNAL_REPORT:return False@@ -779,6 +803,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Crf"Requesting Modal network enforcement for {len(config.outbound_domain_allowlist)} domains",)+ sandbox_class = get_sandbox_class_for_run_backend(ctx.sandbox_backend)try:with StepTimer("sandbox_creation",@@ -787,13 +812,35 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Crruntime=runtime,sandbox_backend=sandbox_backend,) as sandbox_creation_timer:- sandbox = get_sandbox_class_for_run_backend(ctx.sandbox_backend).create(config)+ sandbox = sandbox_class.create(config)# The provider's TTL clock starts here — the usage ledger anchors its# kill deadline on this boundary, not on when the row is opened below.sandbox_created_at = timezone.now()actual_used_snapshot = bool((prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored)+ if _prewarmed_resume_needs_fresh_agent(+ ctx,+ prepared,+ sandbox,+ used_snapshot=actual_used_snapshot,+ ):+ emit_agent_log(+ ctx.run_id,+ "debug",+ "Resume snapshot uses an older agent; provisioning a fresh sandbox before prewarming",+ )+ sandbox.destroy()+ config.snapshot_id = None+ config.snapshot_external_id = None+ config.snapshot_kind = SNAPSHOT_KIND_FILESYSTEM+ config.snapshot_mount_path = None+ config.snapshot_source = "none"+ config.snapshot_restored = False+ config.image_fallback = None+ sandbox = sandbox_class.create(config)+ sandbox_created_at = timezone.now()+ actual_used_snapshot = Falsesandbox_creation_timer.set_used_snapshot(actual_used_snapshot)except Exception:if config.outbound_domain_allowlist is not None:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.pyindex c1f6ee6202dc..5518ebf4a8ea 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py@@ -9,6 +9,7 @@ from django.test import override_settingsfrom asgiref.sync import async_to_sync+from products.tasks.backend.constants import SNAPSHOT_KIND_DIRECTORY, SNAPSHOT_KIND_FILESYSTEMfrom products.tasks.backend.exceptions import RepositoryCloneErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, Sandbox@@ -22,6 +23,7 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox iCreateSandboxForRepositoryOutput,PrepareSandboxForRepositoryOutput,_prepare_posthog_desktop_cloud_task,+ _prewarmed_resume_needs_fresh_agent,_sandbox_image_kind,clone_repository_in_sandbox,create_sandbox_for_repository,@@ -132,6 +134,56 @@ def test_sandbox_image_kind(image_source: str, custom_image_name: str | None, exassert _sandbox_image_kind(image_source, custom_image_name) == expected+ "snapshot_kind, state, capability, expected",+ [+ (+ SNAPSHOT_KIND_FILESYSTEM,+ {"prewarmed": True, "resume_from_run_id": "previous-run"},+ False,+ True,+ ),+ (+ SNAPSHOT_KIND_FILESYSTEM,+ {"prewarmed": True, "resume_from_run_id": "previous-run"},+ True,+ False,+ ),+ (+ SNAPSHOT_KIND_DIRECTORY,+ {"prewarmed": True, "resume_from_run_id": "previous-run"},+ False,+ False,+ ),+ (SNAPSHOT_KIND_FILESYSTEM, {"resume_from_run_id": "previous-run"}, False, False),+ ],+)+def test_old_full_snapshot_agent_is_rejected_only_for_prewarmed_resume(+ mocker, snapshot_kind, state, capability, expected+):+ context = _context_for_desktop_bootstrap()+ context.state = state+ prepared = PrepareSandboxForRepositoryOutput(+ sandbox_name="task-sandbox-task-id",+ repository="posthog/posthog",+ github_token="",+ branch=None,+ environment_variables={},+ snapshot_id=None,+ snapshot_external_id="snapshot-1",+ used_snapshot=True,+ should_create_snapshot=False,+ shallow_clone=True,+ image_source="resume_snapshot",+ image_source_label="resume snapshot snapshot-1",+ snapshot_kind=snapshot_kind,+ )+ sandbox = mocker.Mock()+ sandbox.agent_server_supports_prewarmed_resume_idle.return_value = capability++ assert _prewarmed_resume_needs_fresh_agent(context, prepared, sandbox, used_snapshot=True) is expected++@pytest.mark.parametrize(("value", "expected"), [(None, "v1"), ("0", "v1"), ("1", "v2")])def test_modal_sandbox_backend_label(monkeypatch: pytest.MonkeyPatch, value: str | None, expected: str) -> None:if value is None:diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex fa74a4921f78..cbbabbc4e6cd 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -301,6 +301,24 @@ class TestFacadeReadsAndMappers(TestCase):other_user = User.objects.create(email="[email protected]", distinct_id="other")self.assertFalse(facade.is_task_controllable_by_user(task.id, other_user.id))+ def test_task_control_runtime_and_origin_uses_control_predicate(self):+ task = self._make_task(origin_product=Task.OriginProduct.POSTHOG_AI, runtime=Task.Runtime.PI)+ self.assertEqual(+ facade.task_control_runtime_and_origin(task.id, self.team.id, self.user.id),+ facade.ControlVisibleTask(+ runtime=Task.Runtime.PI.value, origin_product=Task.OriginProduct.POSTHOG_AI.value+ ),+ )++ # An experiments task is readable across the team but only its creator may drive it, so the+ # warm gate must use the control predicate, not the read predicate.+ other_user = User.objects.create(email="[email protected]", distinct_id="control-origin")+ experiments_task = self._make_task(origin_product=Task.OriginProduct.EXPERIMENTS)+ self.assertIsNotNone(facade.get_task_detail(experiments_task.id, self.team.id, other_user.id))+ self.assertIsNone(facade.task_control_runtime_and_origin(experiments_task.id, self.team.id, other_user.id))++ self.assertIsNone(facade.task_control_runtime_and_origin(uuid4(), self.team.id, self.user.id))+def _make_wizard_run(self, task: Task, status: TaskRun.Status, **kwargs) -> TaskRun:# A genuine server-started wizard run carries the markers create_wizard_cloud_run stamps:# a cloud environment and the (caller-unsettable) wizard_config state key.diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex 34a769c02370..7dd0df2f9e30 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -22,7 +22,13 @@ from products.tasks.backend.logic.services.staged_artifacts import (build_task_staged_artifact_cache_key,)from products.tasks.backend.logic.services.warm import WarmResult-from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun+from products.tasks.backend.models import (+ TASK_OWNERSHIP_VERSION_STATE_KEY,+ SandboxCustomImage,+ SandboxEnvironment,+ Task,+ TaskRun,+)from products.tasks.backend.redis import get_tasks_cacheFACADE = "products.tasks.backend.facade.api"@@ -112,6 +118,77 @@ class TestWarmTaskSandbox(APIBaseTest):assert mock_warm.call_args.kwargs["sandbox_environment_id"] == sandbox_environment.idassert mock_warm.call_args.kwargs["custom_image_id"] == custom_image.id+ @parameterized.expand(+ [+ ("posthog_ai_warms_with_every_flag_off", facade.TaskOriginProduct.POSTHOG_AI, False, True),+ ("code_app_stays_gated_when_off", facade.TaskOriginProduct.USER_CREATED, False, False),+ ("code_app_warms_when_on", facade.TaskOriginProduct.USER_CREATED, True, True),+ ]+ )+ def test_origin_product_decides_whether_a_flag_gates_warming(+ self, _name: str, origin_product: str, flag_enabled: bool, should_warm: bool+ ):+ with (+ patch("products.tasks.backend.facade.api.warm_task_sandbox") as mock_warm,+ patch(+ "products.tasks.backend.presentation.views.api.posthoganalytics.feature_enabled",+ return_value=flag_enabled,+ ),+ ):+ mock_warm.return_value = None+ response = self.client.post(+ "/api/projects/@current/tasks/warm/",+ {+ "repository": "posthog/posthog",+ "github_integration": self.integration.id,+ "branch": "main",+ "origin_product": origin_product,+ },+ format="json",+ )++ assert response.status_code == 200, response.content+ assert mock_warm.called is should_warm++ @patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)+ @patch("products.tasks.backend.facade.api.warm_task_resume_sandbox")+ def test_resume_warm_endpoint_forwards_terminal_run_selection(self, mock_warm, _mock_warm_enabled):+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ terminal = task.create_run(mode="interactive")+ terminal.status = TaskRun.Status.CANCELLED+ terminal.save(update_fields=["status"])+ mock_warm.return_value = contracts.WarmTaskDTO(task_id=task.id, run_id=terminal.id)++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/warm/",+ {+ "resume_from_run_id": str(terminal.id),+ "runtime_adapter": "claude",+ "model": "claude-sonnet-5",+ "reasoning_effort": "high",+ "initial_permission_mode": "plan",+ },+ format="json",+ )++ assert response.status_code == 200, response.content+ mock_warm.assert_called_once_with(+ str(task.id),+ self.team.id,+ self.user.id,+ resume_from_run_id=terminal.id,+ runtime_adapter="claude",+ model="claude-sonnet-5",+ reasoning_effort="high",+ initial_permission_mode="plan",+ )+@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)@patch("products.tasks.backend.facade.api.warm_task_sandbox")def test_warm_endpoint_accepts_repo_less_request(self, mock_warm, _mock_warm_enabled):@@ -885,6 +962,168 @@ class TestWarmRunRelease(APIBaseTest):assert m_signal.called is expect_signal+class TestWarmTaskResumeSandbox(APIBaseTest):+ def test_warms_and_activates_a_successor_for_the_latest_terminal_run(self):+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ terminal = task.create_run(+ mode="interactive",+ branch="main",+ extra_state={+ "snapshot_external_id": "snapshot-1",+ "pr_base_branch": "main",+ "auto_publish": True,+ "runtime_adapter": "claude",+ "model": "claude-sonnet-5",+ "initial_permission_mode": "plan",+ },+ )+ terminal.status = TaskRun.Status.CANCELLED+ terminal.save(update_fields=["status"])++ with (+ patch("products.tasks.backend.logic.services.warm.is_team_limited", return_value=False),+ patch("products.tasks.backend.logic.services.warm.execute_task_processing_workflow") as execute_workflow,+ self.captureOnCommitCallbacks(execute=True),+ ):+ warmed = facade.warm_task_resume_sandbox(+ task.id,+ self.team.id,+ self.user.id,+ resume_from_run_id=terminal.id,+ runtime_adapter="claude",+ model="claude-sonnet-5",+ reasoning_effort="high",+ initial_permission_mode="plan",+ )++ assert warmed is not None+ warm_run = TaskRun.objects.get(id=warmed.run_id)+ assert warm_run.state["resume_from_run_id"] == str(terminal.id)+ assert warm_run.state["snapshot_external_id"] == "snapshot-1"+ assert warm_run.state["await_user_message"] is True+ assert warm_run.state["auto_publish"] is True+ assert warm_run.state["pr_authorship_mode"] == "bot"+ execute_workflow.assert_called_once()+ assert execute_workflow.call_args.kwargs.get("create_pr", True) is True++ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as signal:+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={+ "mode": "interactive",+ "resume_from_run_id": terminal.id,+ "runtime_adapter": "claude",+ "model": "claude-sonnet-5",+ "reasoning_effort": "high",+ "initial_permission_mode": "plan",+ "pending_user_message": "continue",+ },+ )++ assert result is not None and result.error is None+ assert task.runs.count() == 2+ signal.assert_called_once()+ warm_run.refresh_from_db()+ assert "await_user_message" not in warm_run.state++ def _terminal_run(self, task: Task) -> TaskRun:+ terminal = task.create_run(+ mode="interactive",+ branch="main",+ extra_state={+ "pr_base_branch": "main",+ "runtime_adapter": "claude",+ "model": "claude-sonnet-5",+ "initial_permission_mode": "plan",+ },+ )+ terminal.status = TaskRun.Status.CANCELLED+ terminal.save(update_fields=["status"])+ return terminal++ def _warm_resume(self, task: Task, terminal: TaskRun):+ with (+ patch("products.tasks.backend.logic.services.warm.is_team_limited", return_value=False),+ patch("products.tasks.backend.logic.services.warm.execute_task_processing_workflow"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ return facade.warm_task_resume_sandbox(+ task.id,+ self.team.id,+ self.user.id,+ resume_from_run_id=terminal.id,+ runtime_adapter="claude",+ model="claude-sonnet-5",+ initial_permission_mode="plan",+ )++ def test_warms_again_after_a_successor_is_released(self):+ # A released successor is terminal and sits in front of its own source, so a source fence that+ # only accepts the source or a live warm would leave the task unable to warm for the rest of+ # its life — and releases are routine: an emptied draft, a changed model, leaving the composer.+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ terminal = self._terminal_run(task)++ first = self._warm_resume(task, terminal)+ assert first is not None+ released = TaskRun.objects.get(id=first.run_id)+ released.status = TaskRun.Status.CANCELLED+ released.save(update_fields=["status"])++ second = self._warm_resume(task, terminal)++ assert second is not None+ assert second.run_id != first.run_id+ # The replacement resumes from the original terminal run, not from the successor handed back.+ assert TaskRun.objects.get(id=second.run_id).state["resume_from_run_id"] == str(terminal.id)++ def test_does_not_warm_from_a_source_the_task_has_moved_past(self):+ # The relaxation above must not become a wildcard: a terminal run that is not a released+ # successor of the named source still means the task moved on.+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ terminal = self._terminal_run(task)+ self._terminal_run(task)++ assert self._warm_resume(task, terminal) is None++ def test_does_not_warm_a_resume_source_from_a_previous_task_owner(self):+ # A handed-off task re-stamps its ownership version but leaves old runs on the previous one.+ # create_run rejects that stale resume source, so this best-effort endpoint must skip warming+ # rather than raise the ownership error on every debounced keystroke of the new owner.+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.POSTHOG_AI,+ created_by=self.user,+ )+ terminal = self._terminal_run(task)+ task.state = {**(task.state or {}), TASK_OWNERSHIP_VERSION_STATE_KEY: "handed-off"}+ task.save(update_fields=["state"])++ assert self._warm_resume(task, terminal) is None++class TestRunTaskWarmActivation(APIBaseTest):"""The normal run path activates an idling warm Run instead of dispatching a fresh workflow."""@@ -1016,6 +1255,37 @@ class TestRunTaskWarmActivation(APIBaseTest):run.refresh_from_db()assert run.state.get("await_user_message") is True # warm run untouched+ def test_resume_successor_is_not_activated_for_a_run_that_asks_for_no_resume(self):+ # A successor's filesystem was restored from the run it resumes, so handing it to a request+ # that named no resume source would silently start "fresh" work on inherited state.+ task, predecessor = self._warm_run()+ predecessor.status = TaskRun.Status.CANCELLED+ predecessor.save(update_fields=["status"])+ run = task.create_run(+ mode="interactive",+ extra_state={+ "await_user_message": True,+ "branch": "main",+ "resume_from_run_id": str(predecessor.id),+ },+ branch="main",+ )+ with (+ patch(f"{FACADE}.signal_task_run_user_message") as m_signal,+ patch(f"{FACADE}._trigger_task_processing_workflow") as m_trigger,+ ):+ facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={"mode": "interactive", "branch": "main", "pending_user_message": "do it"},+ )++ m_signal.assert_not_called()+ m_trigger.assert_called_once()+ run.refresh_from_db()+ assert run.state.get("await_user_message") is True+def test_sandbox_environment_mismatch_does_not_activate_warm_run(self):warm_environment = SandboxEnvironment.objects.create(team=self.team,diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex f5e765491034..11fa7bd6a1fe 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -2889,6 +2889,50 @@ export interface TaskUsageResponseApi {total_cost_usd: number}+/**+ * Request body for warming a successor to an existing terminal task run.+ */+export interface WarmTaskResumeRequestApi {+ /** ID of the task's latest terminal run whose snapshot and conversation should be resumed. */+ resume_from_run_id: string+ /** Agent runtime adapter to start before the next message is submitted.+ *+ * * `claude` - claude+ * * `codex` - codex */+ runtime_adapter?: RuntimeAdapterEnumApi+ /** LLM model to start before the next message is submitted. */+ model?: string+ /** Reasoning effort to apply when the warmed successor receives its first message.+ *+ * * `low` - low+ * * `medium` - medium+ * * `high` - high+ * * `xhigh` - xhigh+ * * `max` - max+ * * `ultracode` - ultracode */+ reasoning_effort?: ReasoningEffortEnumApi+ /** Initial permission mode for the warmed successor's agent session.+ *+ * * `default` - default+ * * `acceptEdits` - acceptEdits+ * * `plan` - plan+ * * `bypassPermissions` - bypassPermissions+ * * `auto` - auto+ * * `read-only` - read-only+ * * `full-access` - full-access */+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi+}++/**+ * Response for a successfully warmed successor run on an existing task.+ */+export interface WarmTaskResumeResponseApi {+ /** ID of the existing task being resumed. */+ task_id: string+ /** ID of the idling successor run that submit will activate. */+ run_id: string+}+export interface PaginatedTaskRunDetailDTOListApi {count: number/** @nullable */diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 2ad636cfa664..70e41a0b09c6 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -145,6 +145,8 @@ import type {TasksThreadMessagesListParams,WarmTaskRequestApi,WarmTaskResponseApi,+ WarmTaskResumeRequestApi,+ WarmTaskResumeResponseApi,WizardCloudRunDTOApi,} from './api.schemas'@@ -1587,6 +1589,28 @@ export const tasksUsageRetrieve = async (})}+export const getTasksWarmResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/${id}/warm/`+}++/**+ * Warm an idling successor for the task's latest terminal Run while the user composes the next message. The successor restores the prior snapshot when compatible and waits for the normal run endpoint to activate it. Best-effort: returns an empty body when warming is disabled, capped, or the task advanced to another Run.+ * @summary Warm a resumed task sandbox+ */+export const tasksWarmResumeCreate = async (+ projectId: string,+ id: string,+ warmTaskResumeRequestApi: WarmTaskResumeRequestApi,+ options?: RequestInit+): Promise<WarmTaskResumeResponseApi> => {+ return apiMutator<WarmTaskResumeResponseApi>(getTasksWarmResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(warmTaskResumeRequestApi),+ })+}+export const getTasksRunsListUrl = (projectId: string, taskId: string, params?: TasksRunsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex d7a3452a5374..e7e099cabcb4 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -2175,6 +2175,44 @@ export const TasksStagedArtifactsPrepareUploadCreateBody = /* @__PURE__ */ zod.o.describe('Array of staged artifacts to prepare before creating a run'),})+/**+ * Warm an idling successor for the task's latest terminal Run while the user composes the next message. The successor restores the prior snapshot when compatible and waits for the normal run endpoint to activate it. Best-effort: returns an empty body when warming is disabled, capped, or the task advanced to another Run.+ * @summary Warm a resumed task sandbox+ */+export const TasksWarmResumeCreateBody = /* @__PURE__ */ zod+ .object({+ resume_from_run_id: zod+ .uuid()+ .describe("ID of the task's latest terminal run whose snapshot and conversation should be resumed."),+ runtime_adapter: zod+ .enum(['claude', 'codex'])+ .describe('\* `claude` - claude\n\* `codex` - codex')+ .optional()+ .describe(+ 'Agent runtime adapter to start before the next message is submitted.\n\n\* `claude` - claude\n\* `codex` - codex'+ ),+ model: zod.string().optional().describe('LLM model to start before the next message is submitted.'),+ reasoning_effort: zod+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .describe(+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ )+ .optional()+ .describe(+ 'Reasoning effort to apply when the warmed successor receives its first message.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ ),+ initial_permission_mode: zod+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto', 'read-only', 'full-access'])+ .describe(+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'+ )+ .optional()+ .describe(+ "Initial permission mode for the warmed successor's agent session.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access"+ ),+ })+ .describe('Request body for warming a successor to an existing terminal task run.')+/*** Create a new run for a specific task without starting execution.* @summary Create task rundiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 10e9416b914f..9a7747ba3649 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -707,3 +707,6 @@ tools:tasks-warm-create:operation: tasks_warm_createenabled: false+ tasks-warm-resume-create:+ operation: tasks_warm_resume_create+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cd4c1aac179b..98b44ab8a5fb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -84067,6 +84067,50 @@ export namespace Schemas {run_id: string;}+ /**+ * Request body for warming a successor to an existing terminal task run.+ */+ export interface WarmTaskResumeRequest {+ /** ID of the task's latest terminal run whose snapshot and conversation should be resumed. */+ resume_from_run_id: string;+ /** Agent runtime adapter to start before the next message is submitted.+ *+ * * `claude` - claude+ * * `codex` - codex */+ runtime_adapter?: RuntimeAdapterEnum;+ /** LLM model to start before the next message is submitted. */+ model?: string;+ /** Reasoning effort to apply when the warmed successor receives its first message.+ *+ * * `low` - low+ * * `medium` - medium+ * * `high` - high+ * * `xhigh` - xhigh+ * * `max` - max+ * * `ultracode` - ultracode */+ reasoning_effort?: ReasoningEffortEnum;+ /** Initial permission mode for the warmed successor's agent session.+ *+ * * `default` - default+ * * `acceptEdits` - acceptEdits+ * * `plan` - plan+ * * `bypassPermissions` - bypassPermissions+ * * `auto` - auto+ * * `read-only` - read-only+ * * `full-access` - full-access */+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum;+ }++ /**+ * Response for a successfully warmed successor run on an existing task.+ */+ export interface WarmTaskResumeResponse {+ /** ID of the existing task being resumed. */+ task_id: string;+ /** ID of the idling successor run that submit will activate. */+ run_id: string;+ }+export interface WebAnalyticsRecapResponse {/** Unique visitors. */visitors: NumericMetric;