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.

feat(phai): prewarm sandboxes for the PostHog AI composer (#83605)

Georgiy Tarasov50757cd213f1
diff --git a/.semgrep/rules/security/openai-hipaa-eligible-endpoints.py b/.semgrep/rules/security/openai-hipaa-eligible-endpoints.py
index 20755b95ae64..55e597b6c75a 100644
--- a/.semgrep/rules/security/openai-hipaa-eligible-endpoints.py
+++ b/.semgrep/rules/security/openai-hipaa-eligible-endpoints.py
@@ -99,7 +99,7 @@ def test_legacy_completions_create() -> None:
def test_legacy_completions_create_async() -> None:
# ruleid: openai-non-hipaa-legacy-completions
- async_client.completions.create(model="text-davinci-003", prompt="hi")
+ async_client.completions.create(model="text-davinci-003", prompt="hi") # ty: ignore[unused-awaitable]
# ============================================================
@@ -114,7 +114,9 @@ def test_chat_completions_create() -> None:
def test_chat_completions_create_async() -> None:
# ok: openai-non-hipaa-legacy-completions
- async_client.chat.completions.create(model="gpt-4", messages=[{"role": "user", "content": "hi"}])
+ async_client.chat.completions.create( # ty: ignore[unused-awaitable]
+ model="gpt-4", messages=[{"role": "user", "content": "hi"}]
+ )
# ============================================================
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 04035874cd96..a701f84f5419 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -597,6 +597,11 @@ SPECTACULAR_SETTINGS = {
"ExperimentMetricKindEnum": "products.ai_observability.backend.models.score_definitions.ScoreDefinition.Kind",
"EvaluationTargetEnum": "products.ai_observability.backend.models.evaluations.EvaluationTarget",
"IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind",
+ # Shared by TaskCreate.origin_product and TaskWrite.origin_product. Needs naming because
+ # WarmTaskRequest.origin_product offers only the warmable subset, so "origin_product" alone
+ # no longer identifies one choice set. Keyed to the name the generator already produced
+ # (`OriginProductEnumApi`) so naming it doesn't rename the type its consumers import.
+ "OriginProductEnum": "products.tasks.backend.models.Task.OriginProduct",
"TicketStatusEnum": "products.conversations.backend.models.constants.Status",
"EmailChannelKindEnum": "products.conversations.backend.models.team_conversations_email_config.EmailChannelKind",
"EmailThreadMessageDirectionEnum": "products.conversations.backend.models.email_thread.EmailThreadMessageDirection",
@@ -915,6 +920,16 @@ SPECTACULAR_SETTINGS = {
"TaskExecutionModeEnum": ["interactive", "background"],
# Shared by ClaudeTaskRunCreateSchema and SandboxOpen (the conversations `open` body).
"InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],
+ "TaskRunBootstrapCreateRequestInitialPermissionModeEnum": [
+ "default",
+ "acceptEdits",
+ "plan",
+ "bypassPermissions",
+ "auto",
+ "read-only",
+ "full-access",
+ None,
+ ],
"HogFunctionTemplatingEnum": ["hog", "liquid"],
"HogFlowEdgeTypeEnum": ["continue", "branch"],
"SourceMatchEnum": ["none", "auto", "mapped"],
diff --git a/products/demo/backend/test/test_hedgebox_matrix.py b/products/demo/backend/test/test_hedgebox_matrix.py
index a23a3b70f160..ff246590b9e6 100644
--- a/products/demo/backend/test/test_hedgebox_matrix.py
+++ b/products/demo/backend/test/test_hedgebox_matrix.py
@@ -278,7 +278,7 @@ class TestHedgeboxMatrixDemoWarehouseTables(SimpleTestCase):
def test_save_demo_data_warehouse_tables_writes_source_team_files(self, mock_write):
matrix = HedgeboxMatrix(seed="warehouse-test", n_clusters=0)
matrix.is_complete = True
- matrix.clusters = [] # ty: ignore[invalid-assignment] # no people -> empty rows, keys are what matters
+ matrix.clusters = [] # no people -> empty rows, keys are what matters
source_team = cast(Any, SimpleNamespace(pk=0))
matrix.save_demo_data_warehouse_tables(source_team)
diff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts
new file mode 100644
index 000000000000..eb0b2aca34e4
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.test.ts
@@ -0,0 +1,342 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import {
+ ClaudeRuntimeAdapterEnumApi,
+ InitialPermissionModeEnumApi,
+ WarmTaskRequestOriginProductEnumApi,
+ type WarmTaskRequestApi,
+} from 'products/tasks/frontend/generated/api.schemas'
+
+import { taskWarmLogic } from './taskWarmLogic'
+
+const WARM_REQUEST: WarmTaskRequestApi = {
+ repository: 'posthog/posthog',
+ github_integration: 1,
+ branch: 'master',
+ runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,
+ model: 'claude-sonnet-5',
+ initial_permission_mode: InitialPermissionModeEnumApi.Auto,
+ origin_product: WarmTaskRequestOriginProductEnumApi.PosthogAi,
+}
+
+describe('taskWarmLogic', () => {
+ let logic: ReturnType<typeof taskWarmLogic.build>
+ let warmCalls: number
+ let cancelledRuns: string[]
+ let resolveWarm: ((value: unknown) => void) | null
+
+ beforeEach(() => {
+ warmCalls = 0
+ cancelledRuns = []
+ resolveWarm = null
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ warmCalls += 1
+ return [200, { task_id: `warm-task-${warmCalls}`, run_id: `warm-run-${warmCalls}` }]
+ },
+ '/api/projects/:team/tasks/:taskId/runs/:runId/cancel/': async ({ params }) => {
+ cancelledRuns.push(params.runId as string)
+ return [200, {}]
+ },
+ },
+ })
+ initKeaTests()
+ logic = taskWarmLogic({ panelId: 'test' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ // A test may unmount the logic itself (to exercise beforeUnmount); guard against a double unmount.
+ if (logic.isMounted()) {
+ logic.unmount()
+ }
+ jest.useRealTimers()
+ })
+
+ it('warms after the debounce and holds the lease', async () => {
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(warmCalls).toBe(1)
+ 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('releases the warm when the draft is abandoned', async () => {
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.releaseWarm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.warmLease).toBeNull()
+ expect(cancelledRuns).toEqual(['warm-run-1'])
+ })
+
+ it('honors a release that raced an in-flight warm request', async () => {
+ // Abandoning while the POST is still open hits the "nothing to release yet" branch. Without the
+ // deferred intent the sandbox that lands a moment later is orphaned until the server reaps it.
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ await new Promise((resolve) => {
+ resolveWarm = resolve
+ })
+ 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()
+ logic.actions.releaseWarm()
+
+ resolveWarm?.(undefined)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.warmLease).toBeNull()
+ expect(cancelledRuns).toEqual(['warm-run-1'])
+ })
+
+ it('releases and re-warms when the selection changes under an existing warm', async () => {
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, { ...WARM_REQUEST, branch: 'feature' })
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // The first sandbox is checked out on the wrong branch, so it can never serve this submit.
+ expect(cancelledRuns).toEqual(['warm-run-1'])
+ expect(warmCalls).toBe(2)
+ expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-2' })
+ })
+
+ it('does not re-warm while the selection is unchanged', async () => {
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, { ...WARM_REQUEST })
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warmCalls).toBe(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 that
+ // was one POST every couple of hundred milliseconds for the length of the draft.
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ warmCalls += 1
+ return [200, {}]
+ },
+ },
+ })
+
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(warmCalls).toBe(1)
+ expect(logic.values.warmLease).toBeNull()
+
+ jest.useFakeTimers()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(warmCalls).toBe(1)
+
+ // Past the cooldown the composer tries once more, in case the answer has changed.
+ jest.useFakeTimers()
+ jest.setSystemTime(Date.now() + 6 * 60 * 1000)
+ logic.actions.noteDraft(true, WARM_REQUEST)
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(warmCalls).toBe(2)
+ })
+
+ it('re-warms for a selection changed while the first warm was still in flight', async () => {
+ // Hold the first warm POST open so a model change collides with it. Without queuing the newer
+ // selection, the completing POST leaves the lease on the stale model and never warms the new
+ // one, so the submit silently takes the cold path and the first sandbox idles until the reaper.
+ let resolveFirst: () => void = () => {}
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ warmCalls += 1
+ const n = warmCalls
+ if (n === 1) {
+ await new Promise<void>((resolve) => {
+ resolveFirst = resolve
+ })
+ }
+ return [200, { task_id: `warm-task-${n}`, run_id: `warm-run-${n}` }]
+ },
+ '/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()
+ // A different model arrives before the first warm resolves.
+ logic.actions.prewarm({ ...WARM_REQUEST, model: 'claude-opus-4-8' })
+
+ resolveFirst()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // The stale first sandbox is released and the latest selection is the one left warm.
+ expect(warmCalls).toBe(2)
+ expect(cancelledRuns).toEqual(['warm-run-1'])
+ expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-2' })
+ })
+
+ it('keeps a warm the user re-engaged after a release raced the in-flight POST', async () => {
+ // Release fires while the POST is open (no lease yet), then the user types the same selection
+ // again before it resolves. Re-engaging must clear the deferred release so the landing sandbox
+ // is kept, not cancelled the moment it appears.
+ let resolveHeldWarm: () => void = () => {}
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ await new Promise<void>((resolve) => {
+ resolveHeldWarm = resolve
+ })
+ 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()
+ logic.actions.releaseWarm()
+ logic.actions.noteDraft(true, WARM_REQUEST)
+
+ resolveHeldWarm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.warmLease).toMatchObject({ runId: 'warm-run-1' })
+ 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 = () => {}
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/warm/': async () => {
+ await new Promise<void>((resolve) => {
+ resolveHeldWarm = resolve
+ })
+ 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()
+
+ 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([])
+ })
+
+ 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.
+ let cancelSeen: () => void = () => {}
+ const cancelled = new Promise<void>((resolve) => {
+ cancelSeen = resolve
+ })
+ 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/runs/:runId/cancel/': async ({ params }) => {
+ cancelledRuns.push(params.runId as string)
+ 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' })
+
+ // Leaving the composer unmounts the logic; the deferred promise resolves only if the cancel fires.
+ logic.unmount()
+ await cancelled
+
+ expect(cancelledRuns).toEqual(['warm-run-1'])
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/taskWarmLogic.ts b/products/posthog_ai/frontend/logics/taskWarmLogic.ts
new file mode 100644
index 000000000000..ccfed0417f09
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskWarmLogic.ts
@@ -0,0 +1,317 @@
+import { MakeLogicType, actions, beforeUnmount, connect, kea, key, listeners, path, props, reducers } from 'kea'
+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'
+
+/** Debounce before warming, measured from the keystroke that first made the draft non-empty. */
+const WARM_DEBOUNCE_MS = 250
+/** Grace period after the draft empties before the warm sandbox is released. */
+const RELEASE_AFTER_EMPTY_MS = 5000
+/** Minimum gap between warm requests for the same selection, counted from the request, not the answer. */
+const WARM_RETRY_AFTER_MS = 5 * 60 * 1000
+
+/**
+ * A warm sandbox the backend is holding for this composer. `key` is the selection the warm was booted
+ * for — repo, branch, runtime, model, permission mode — so a later change to any of them invalidates it.
+ */
+export interface WarmLease {
+ key: string
+ taskId: string
+ runId: string
+}
+
+export interface TaskWarmLogicProps {
+ /** Matches `taskTrackerSceneLogicProps.panelId` so each composer instance owns its own lease. */
+ panelId?: string
+}
+
+/**
+ * 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 {
+ return [
+ request.repository ?? '',
+ (request.repositories ?? []).join(','),
+ request.github_integration ?? '',
+ request.branch ?? '',
+ request.runtime_adapter ?? '',
+ request.model ?? '',
+ request.initial_permission_mode ?? '',
+ ].join('|')
+}
+
+/**
+ * Cancel a warm Run, which drives it terminal so it drops out of the warm-pool count immediately
+ * instead of waiting out the server's idle timeout. Best-effort: a failed cancel just leaves the Run
+ * for the server-side reaper.
+ *
+ * The run-level `cancel` endpoint, NOT the `cancel` relay command the streaming surfaces use: that one
+ * is proxied to the agent server to abort the turn in flight, and a warm Run has no turn. It answers
+ * `{cancelled: true}` and leaves the Run idling until the inactivity timer reclaims it, so the pool
+ * slot stays held and the miss is booked as `idle_timeout` rather than `released`.
+ *
+ * `only_if_awaiting_first_message` makes the server refuse to stop a Run that has since been activated.
+ * A lease is not exclusive: the backend hands the same warm Run to every composer holding the same
+ * selection, so a submit in one composer can activate the Run another composer is still holding. Without
+ * the fence, that composer releasing — on unmount, an emptied draft, or a selection change — would stop
+ * the run the user just started.
+ */
+async function cancelWarmRun(projectId: string, lease: WarmLease): Promise<void> {
+ try {
+ await tasksRunsCancelCreate(projectId, lease.taskId, lease.runId, {
+ only_if_awaiting_first_message: true,
+ })
+ } catch (error) {
+ posthog.captureException(error)
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskWarmLogicValues {
+ currentProjectId: number | null // projectLogic
+ warmLease: WarmLease | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskWarmLogicActions {
+ consumeWarm: () => {
+ value: true
+ }
+ noteDraft: (
+ hasText: boolean,
+ request: WarmTaskRequestApi
+ ) => {
+ hasText: boolean
+ request: WarmTaskRequestApi
+ }
+ prewarm: (request: WarmTaskRequestApi) => {
+ request: WarmTaskRequestApi
+ }
+ releaseWarm: () => {
+ value: true
+ }
+ setWarmLease: (lease: WarmLease | null) => {
+ lease: WarmLease | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskWarmLogicMeta {
+ key: string
+}
+
+export type taskWarmLogicType = MakeLogicType<
+ taskWarmLogicValues,
+ taskWarmLogicActions,
+ TaskWarmLogicProps,
+ taskWarmLogicMeta
+>
+
+/**
+ * Boots a sandbox while the user is still typing, so submitting a task lands on one that is already up.
+ *
+ * A cold PostHog AI task spends ~16s provisioning and booting the agent server before the typed message
+ * even reaches the agent. Warming moves that off the user's perceived path; it does not make the boot
+ * faster. Best-effort throughout — every failure just means the submit takes the cold path.
+ *
+ * Ported from `scenes/max/maxThreadLogic`'s prewarm, which drives the legacy conversations route. This
+ * one drives the tasks warm endpoint instead, which is what the `/tasks` composer submits through.
+ */
+export const taskWarmLogic = kea<taskWarmLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'taskWarmLogic']),
+ props({} as TaskWarmLogicProps),
+ key((props) => props.panelId ?? 'scene'),
+
+ connect({
+ values: [projectLogic, ['currentProjectId']],
+ }),
+
+ actions({
+ noteDraft: (hasText: boolean, request: WarmTaskRequestApi) => ({ hasText, request }),
+ prewarm: (request: WarmTaskRequestApi) => ({ request }),
+ releaseWarm: true,
+ consumeWarm: true,
+ setWarmLease: (lease: WarmLease | null) => ({ lease }),
+ }),
+
+ reducers({
+ warmLease: [
+ null as WarmLease | null,
+ {
+ setWarmLease: (_, { lease }) => lease,
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, cache }) => ({
+ noteDraft: ({ hasText, request }) => {
+ if (!hasText) {
+ // Draft emptied — drop a pending warm and schedule a release, so a user who clears the
+ // box and walks away doesn't leave a sandbox idling until the server-side reaper.
+ cache.disposables.dispose('warm-debounce')
+ // Also drop any selection queued behind an in-flight warm, so an abandon isn't followed
+ // by a re-warm for a selection the user no longer wants.
+ cache.pendingWarmRequest = null
+ if (values.warmLease || cache.warming) {
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => actions.releaseWarm(), RELEASE_AFTER_EMPTY_MS)
+ return () => clearTimeout(timer)
+ }, 'warm-release')
+ }
+ return
+ }
+ cache.disposables.dispose('warm-release')
+ const key = warmLeaseKey(request)
+ if (values.warmLease?.key === key || cache.warmingKey === key) {
+ // Re-engaging the selection we already warmed or are still warming. A release may have
+ // raced the in-flight POST and deferred itself via pendingRelease; clear it so the warm
+ // that lands is kept for this submit rather than cancelled out from under the user.
+ cache.pendingRelease = false
+ return
+ }
+ // A warm request that answered "not warmed" (the flag is off, the pool is full, the
+ // integration didn't resolve) leaves no lease, so the checks above can't stop the next
+ // keystroke from asking again — that is one POST per typing pause for the whole draft. Ask
+ // once per selection, then only after the cooldown, on the chance the answer has changed.
+ if (
+ cache.lastWarmRequestKey === key &&
+ cache.lastWarmRequestAt != null &&
+ Date.now() - cache.lastWarmRequestAt < WARM_RETRY_AFTER_MS
+ ) {
+ return
+ }
+ // The selection changed out from under an existing warm (a different repo, branch, model or
+ // permission mode); that sandbox can no longer serve this submit, so let it go and warm again.
+ if (values.warmLease) {
+ actions.releaseWarm()
+ }
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => actions.prewarm(request), WARM_DEBOUNCE_MS)
+ return () => clearTimeout(timer)
+ }, 'warm-debounce')
+ },
+
+ prewarm: async ({ request }) => {
+ cache.disposables.dispose('warm-debounce')
+ const key = warmLeaseKey(request)
+ if (values.currentProjectId == null || values.warmLease?.key === key) {
+ 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
+ // submit cold-creates while that sandbox idles until the reaper. Record the latest
+ // selection so the completion below re-warms for it. This is the re-warm partner of the
+ // pendingRelease handling.
+ if (cache.warmingKey !== key) {
+ cache.pendingWarmRequest = request
+ }
+ return
+ }
+ cache.warming = true
+ cache.warmingKey = key
+ // Stamped here rather than on the answer, so a slow or failed warm still holds off the next
+ // request for the full cooldown.
+ cache.lastWarmRequestKey = key
+ cache.lastWarmRequestAt = Date.now()
+ cache.pendingRelease = false
+ cache.pendingWarmRequest = null
+ cache.consumedWhileWarming = false
+ try {
+ const warm = await tasksWarmCreate(String(values.currentProjectId), request)
+ 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.
+ 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 })
+ }
+ // 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
+ // freshly warmed sandbox isn't left for the reaper.
+ if (cache.pendingRelease) {
+ cache.pendingRelease = false
+ actions.releaseWarm()
+ }
+ } catch (error) {
+ posthog.captureException(error)
+ } finally {
+ cache.warming = false
+ cache.warmingKey = 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
+ // release above has already cleared the lease and dropped pendingWarmRequest via noteDraft,
+ // so this only fires when the latest selection still stands.
+ const pending = cache.pendingWarmRequest
+ cache.pendingWarmRequest = null
+ if (pending && warmLeaseKey(pending) !== values.warmLease?.key) {
+ if (values.warmLease) {
+ actions.releaseWarm()
+ }
+ actions.prewarm(pending)
+ }
+ },
+
+ releaseWarm: async () => {
+ cache.disposables.dispose('warm-debounce')
+ cache.disposables.dispose('warm-release')
+ const lease = values.warmLease
+ if (!lease) {
+ // Nothing to release yet. If a warm POST is still in flight, record the intent so its
+ // completion releases rather than dropping the request on the floor.
+ if (cache.warming) {
+ cache.pendingRelease = true
+ }
+ return
+ }
+ actions.setWarmLease(null)
+ if (values.currentProjectId == null) {
+ return
+ }
+ 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.
+ cache.disposables.dispose('warm-debounce')
+ cache.disposables.dispose('warm-release')
+ cache.pendingRelease = false
+ cache.pendingWarmRequest = 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
+ }
+ actions.setWarmLease(null)
+ },
+ })),
+
+ // 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.
+ beforeUnmount(({ values }) => {
+ const lease = values.warmLease
+ if (lease && values.currentProjectId != null) {
+ void cancelWarmRun(String(values.currentProjectId), lease)
+ }
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 406ca840a149..9d465255c787 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -108,6 +108,39 @@ describe('taskTrackerSceneLogic', () => {
expect(router.values.location.pathname).toContain('/tasks/new-task')
})
+ // A warm sandbox is adopted inside `tasks/create`, which returns the activated Run as `latest_run`.
+ // Issuing the usual run-create on top would strand that warm sandbox and cold-boot a second one —
+ // exactly the ~16s the warm existed to avoid. The create must also carry the warm-reuse hints, since
+ // the backend never even attempts a match unless `branch` is present as a key.
+ it('skips the run create when the backend activated a warm run', async () => {
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/': async ({ request }) => {
+ createBody = (await request.json()) as Record<string, any>
+ return [200, { id: 'new-task', latest_run: { id: 'warm-run-1' } }]
+ },
+ '/api/projects/:team/tasks/:id/run/': async ({ request }) => {
+ runBody = (await request.json()) as Record<string, any>
+ return [200, { id: 'new-task', latest_run: 'run-1' }]
+ },
+ },
+ })
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'do the thing' })
+ logic.actions.submitNewTask()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBody).toMatchObject({
+ branch: null,
+ model: 'claude-sonnet-5',
+ initial_permission_mode: 'auto',
+ pending_user_message: 'do the thing',
+ })
+ expect(runBody).toBeNull()
+ expect(logic.values.activeCreation?.runId).toBe('warm-run-1')
+ })
+
// The seeded first message wraps the on-screen context, and the wrapped non-text refs must be marked
// sent under the created task's id — otherwise the run's first follow-up (sent via
// `runInteractionLogic`, which prunes against the task-scoped store) re-wraps the same refs.
@@ -132,19 +165,23 @@ describe('taskTrackerSceneLogic', () => {
// The tasks backend has no server-side consent check (unlike the conversations coordinator), so a
// send must be blocked client-side before it ever reaches `api.tasks.create` — otherwise a sandbox
- // run starts with zero consent enforcement. Uses a distinct `panelId` key so the logic is built
- // (and connects to `aiConsentLogic`) after the selector is stubbed.
- it('blocks submitNewTask without creating a task when AI data processing consent is not accepted', async () => {
+ // run starts with zero consent enforcement. Warming is held to the same rule: it boots a cloud
+ // sandbox and clones the selected repository, so typing must not start one either. Uses a distinct
+ // `panelId` key so the logic is built (and connects to `aiConsentLogic`) after the selector is stubbed.
+ it('blocks submitNewTask and warming when AI data processing consent is not accepted', async () => {
const consent = aiConsentLogic()
consent.mount()
jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)
const blockedLogic = taskTrackerSceneLogic({ panelId: 'consent-test' })
blockedLogic.mount()
- blockedLogic.actions.setNewTaskData({ description: 'do the thing' })
- blockedLogic.actions.submitNewTask()
- await expectLogic(blockedLogic).toFinishAllListeners()
+ await expectLogic(blockedLogic, () => {
+ blockedLogic.actions.setNewTaskData({ description: 'do the thing' })
+ blockedLogic.actions.submitNewTask()
+ })
+ .toNotHaveDispatchedActions(['noteDraft'])
+ .toFinishAllListeners()
expect(createBody).toBeNull()
expect(blockedLogic.values.consentBlocked).toBe(true)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 3f2592303f4b..f010911d137e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -15,6 +15,8 @@ import {
ReasoningEffortEnumApi,
type TaskWriteApi,
TaskExecutionModeEnumApi,
+ type WarmTaskRequestApi,
+ WarmTaskRequestOriginProductEnumApi,
} from 'products/tasks/frontend/generated/api.schemas'
import type { IntegrationType, UserBasicType } from '../../../../../frontend/src/types'
@@ -27,6 +29,8 @@ import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'
import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import type { ActiveCreation } from '../../logics/runnerPanelLogic'
import { tasksLogic } from '../../logics/tasksLogic'
+import { taskWarmLogic } from '../../logics/taskWarmLogic'
+import type { WarmLease } from '../../logics/taskWarmLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import type { AttachedContextItem } from '../../types/contextTypes'
@@ -65,6 +69,41 @@ export interface TaskTrackerSceneLogicProps {
const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'
+/**
+ * The warm request for the current composer selection, or `null` when this selection can't be warmed.
+ *
+ * A repo-scoped warm must already know its branch: the backend matches branch as a `None`-normalized
+ * exact value, so warming while `GitHubBranchCombobox` is still resolving the repo's default would
+ * book a sandbox on `null` and then miss on submit. Repo-less drafts carry `null` on both sides and
+ * warm immediately.
+ */
+function buildWarmRequest(form: TaskCreateForm, catalogue: ModelChoiceApi[]): WarmTaskRequestApi | null {
+ const { repositoryConfig, model, reasoningEffort, permissionMode } = form
+ if (repositoryConfig.repository && !repositoryConfig.branch) {
+ return null
+ }
+ const runRequest = buildRunCreateRequest(
+ catalogue,
+ model,
+ resolveEffortForModel(catalogue, reasoningEffort, model),
+ permissionMode,
+ { branch: repositoryConfig.branch ?? null }
+ )
+ if (!('runtime_adapter' in runRequest)) {
+ return null
+ }
+ return {
+ repository: repositoryConfig.repository ?? null,
+ github_integration: repositoryConfig.integrationId ?? null,
+ branch: runRequest.branch,
+ runtime_adapter: runRequest.runtime_adapter,
+ model: runRequest.model,
+ reasoning_effort: runRequest.reasoning_effort,
+ initial_permission_mode: runRequest.initial_permission_mode,
+ origin_product: WarmTaskRequestOriginProductEnumApi.PosthogAi,
+ }
+}
+
const EMPTY_TASK_FORM: TaskCreateForm = {
description: '',
repositoryConfig: {
@@ -86,6 +125,7 @@ export interface taskTrackerSceneLogicValues {
currentProjectId: number | null // projectLogic
activeCreation: ActiveCreation | null // runnerPanelLogic
historyExpanded: boolean // runnerPanelLogic
+ warmLease: WarmLease | null // taskWarmLogic
repositories: string[] // tasksLogic
taskListParams: TaskListParams // tasksLogic
tasks: Task[] // tasksLogic
@@ -245,6 +285,19 @@ export interface taskTrackerSceneLogicActions {
toggleHistory: () => {
value: true
} // runnerPanelLogic
+ consumeWarm: () => {
+ value: true
+ } // taskWarmLogic
+ noteDraft: (
+ hasText: boolean,
+ request: WarmTaskRequestApi
+ ) => {
+ hasText: boolean
+ request: WarmTaskRequestApi
+ } // taskWarmLogic
+ releaseWarm: () => {
+ value: true
+ } // taskWarmLogic
deleteTask: (args_0: { taskId: string }) => {
taskId: string
} // tasksLogic
@@ -346,6 +399,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['overrideHeadlines'],
modelCatalogueLogic,
['catalogue'],
+ taskWarmLogic(props),
+ ['warmLease'],
],
actions: [
runnerPanelLogic(props),
@@ -360,6 +415,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['claimApplyBackTargets', 'releaseApplyBackTargets'],
composerSeedLogic(props),
['consumeSeed', 'setSeed'],
+ taskWarmLogic(props),
+ ['noteDraft', 'consumeWarm', 'releaseWarm'],
],
})),
@@ -465,6 +522,19 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
const { integrationId, repository } = data.repositoryConfig
actions.setPersistedRepositoryConfig({ integrationId, repository })
}
+ // Warm a sandbox while the user is still typing, so the submit lands on one that is already
+ // up. `useDebouncedDraft` already coalesces keystrokes into this action, and `taskWarmLogic`
+ // debounces again before it commits to a sandbox. Skipped while a run is being created —
+ // that run is the desired state, not a warm.
+ // Consent gates warming as it gates submitting (see `submitNewTask`): a warm boots a cloud
+ // sandbox and clones the selected repository, so it must not run before the organization
+ // accepts AI data processing.
+ if (!values.activeCreation && values.dataProcessingAccepted) {
+ const request = buildWarmRequest(values.newTaskData, values.catalogue)
+ if (request) {
+ actions.noteDraft(values.newTaskData.description.trim().length > 0, request)
+ }
+ }
},
// Restore the remembered repo (or fall back to the first connected GitHub integration) when nothing is
// chosen yet. The IntegrationChoice picker that used to own this selection is no longer rendered.
@@ -535,6 +605,21 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
stream.actions.startOptimisticRun(description)
try {
+ const pendingUserMessage = wrapWithPosthogContext(description, seededContext)
+ const runRequest = buildRunCreateRequest(
+ values.catalogue,
+ model,
+ resolveEffortForModel(values.catalogue, reasoningEffort, model),
+ permissionMode,
+ {
+ branch: repositoryConfig.branch ?? null,
+ mode: TaskExecutionModeEnumApi.Interactive,
+ pending_user_message: pendingUserMessage,
+ }
+ )
+ if (!('runtime_adapter' in runRequest)) {
+ throw new Error('Run request is missing a runtime adapter')
+ }
const taskData: TaskWriteApi = {
title: '',
description,
@@ -542,36 +627,36 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// PostHog AI can run without a repo; null means the task is not scoped to any repository.
repository: repositoryConfig.repository ?? null,
github_integration: repositoryConfig.integrationId ?? null,
+ // Warm-reuse hints. The backend matches these against an idling warm Run and, on a hit,
+ // activates it in place and returns it as `latest_run` — no second Run is created. All of
+ // them are write-only and ignored on a cold create. `branch` must be present as a key
+ // (even `null`) or reuse is never attempted at all.
+ branch: runRequest.branch ?? null,
+ runtime_adapter: runRequest.runtime_adapter,
+ model: runRequest.model,
+ reasoning_effort: runRequest.reasoning_effort,
+ initial_permission_mode: runRequest.initial_permission_mode,
+ pending_user_message: pendingUserMessage,
}
const projectId = String(values.currentProjectId)
const newTask = await tasksCreate(projectId, taskData)
+ // 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()
- // Auto-run the task after creation; the detail scene shows the latest run by default. The
- // run checks out the chosen branch (server falls back to the repo's default branch if unset)
+ // `latest_run` set means the create matched an idling warm Run and activated it in place,
+ // with `pending_user_message` as turn 1. Creating a second Run here would strand that warm
+ // sandbox and cold-boot another one.
+ //
+ // Otherwise auto-run the task; the detail scene shows the latest run by default. The run
+ // checks out the chosen branch (server falls back to the repo's default branch if unset)
// and launches with the picked model / reasoning effort (clamped to one the model supports).
- const runResponse = await tasksRunCreate(
- projectId,
- newTask.id,
- buildRunCreateRequest(
- values.catalogue,
- model,
- resolveEffortForModel(values.catalogue, reasoningEffort, model),
- permissionMode,
- {
- branch: repositoryConfig.branch ?? null,
- // Interactive keeps the sandbox agent-server's event stream open across turns, so
- // follow-up messages stream their reply over the same SSE (background runs seal the
- // stream after the first turn). Interactive runs boot with the agent-server pulling
- // pending_user_message from run state (the workflow doesn't forward it), so seed the
- // typed message as turn 1 — otherwise the first prompt is lost and the run idles.
- mode: TaskExecutionModeEnumApi.Interactive,
- // Wrap only the message sent to the agent with the on-screen context block; the task
- // `description` field and the optimistic seed (`startOptimisticRun`) stay raw.
- pending_user_message: wrapWithPosthogContext(description, seededContext),
- }
- )
- )
+ let runId = newTask.latest_run?.id
+ if (!runId) {
+ const runResponse = await tasksRunCreate(projectId, newTask.id, runRequest)
+ runId = runResponse.latest_run?.id
+ }
// Mark the seeded non-text refs sent under the created task, so the run's first follow-up
// (sent via `runInteractionLogic`) doesn't re-wrap them. Text items always resend.
@@ -583,7 +668,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Attach the real ids to the optimistic creation so the detail page adopts this seeded stream
// (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.
// Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.
- actions.setActiveCreation({ streamKey, taskId: newTask.id, runId: runResponse.latest_run?.id })
+ actions.setActiveCreation({ streamKey, taskId: newTask.id, runId })
// An embedded instance (`panelId` set) keeps the run in place — the host renders it from
// `activeCreation` — rather than navigating the main app to the `/tasks/:id` detail page.
if (!props.panelId) {
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index ee4052730d10..ab28301353a5 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2590,6 +2590,7 @@ def update_task_run(
)
from products.tasks.backend.metrics import ( # noqa: PLC0415 — keep prometheus deps off the api import path
observe_agent_turn_failed,
+ observe_prewarmed_unused_if_never_activated,
observe_wizard_run_unbound,
)
@@ -2714,6 +2715,12 @@ def update_task_run(
},
)
observe_wizard_run_unbound(run)
+ # This write terminalizes the Run on its own — the cancel fallback takes it when the workflow
+ # is already gone — so the warm miss is booked here rather than by the status activity, which
+ # sees the row already terminal and skips.
+ observe_prewarmed_unused_if_never_activated(
+ run, reason="released" if new_status == TaskRun.Status.CANCELLED else "other"
+ )
signal_workflow_completion(run.id, new_status, validated_data.get("error_message"))
if new_status == TaskRun.Status.CANCELLED:
from products.tasks.backend.push_dispatcher import ( # noqa: PLC0415 — keep push deps off the api import path
@@ -5401,6 +5408,7 @@ def create_task(
warm_reasoning_effort = validated_data.pop("reasoning_effort", None)
warm_sandbox_environment_id = validated_data.pop("sandbox_environment_id", None)
warm_custom_image_id = validated_data.pop("custom_image_id", None)
+ warm_initial_permission_mode = validated_data.pop("initial_permission_mode", None)
pending_user_message = (validated_data.pop("pending_user_message", None) or "").strip() or None
pending_user_artifact_ids = validated_data.pop("pending_user_artifact_ids", None) or []
warm_auto_publish = validated_data.pop("auto_publish", None)
@@ -5432,14 +5440,16 @@ def create_task(
if default_integration:
validated_data["github_integration"] = default_integration
- if (
- warm_branch_provided
- and validated_data["origin_product"] == Task.OriginProduct.USER_CREATED
- and user_id is not None
- ):
+ # Reuse is scoped to the submitting origin product: `_find_idling_warm_run` filters on it, so an
+ # origin that never warms simply finds nothing. The warm call and this create call are separate
+ # requests that must agree on the origin — when they disagree the lookup misses and we cold-create,
+ # which costs latency but can never hand over a Run booted under another product's budget or
+ # PR-authorship rules.
+ if warm_branch_provided and user_id is not None:
warm_run = _find_idling_warm_run(
team_id,
user_id,
+ origin_product=validated_data["origin_product"],
repository=validated_data.get("repository"),
repositories=validated_data.get("repositories", []),
github_integration_id=getattr(validated_data.get("github_integration"), "id", None),
@@ -5449,6 +5459,7 @@ def create_task(
reasoning_effort=warm_reasoning_effort,
sandbox_environment_id=warm_sandbox_environment_id,
custom_image_id=warm_custom_image_id,
+ initial_permission_mode=warm_initial_permission_mode,
)
if warm_run is not None and not _warm_sandbox_selection_is_accessible(
team_id=team_id,
@@ -6004,6 +6015,7 @@ def _find_idling_warm_run(
team_id: int,
user_id: int | None,
*,
+ origin_product: str,
repository: str | None,
repositories: list[str] | None = None,
github_integration_id: int | None,
@@ -6013,18 +6025,25 @@ def _find_idling_warm_run(
reasoning_effort: str | None = None,
sandbox_environment_id: str | UUID | None = None,
custom_image_id: str | UUID | None = None,
+ initial_permission_mode: str | None = None,
) -> TaskRun | None:
"""Most-recent idling pre-warmed Run matching this user's cloud composing selection, or ``None``.
- A warm Run is a non-terminal ``USER_CREATED`` Run for the same optional repo+branch still awaiting its
- first user message (the ``await_user_message`` state marker). This is the backend's single source
- of truth for the warm pool: it dedupes warm provisioning (so a repeated ``warm`` call reuses the
+ A warm Run is a non-terminal Run of the same origin product, for the same optional repo+branch, still
+ awaiting its first user message (the ``await_user_message`` state marker). This is the backend's single
+ source of truth for the warm pool: it dedupes warm provisioning (so a repeated ``warm`` call reuses the
live Run instead of spawning a second) and lets the normal create+run path transparently reuse a
warm Run on submit. Team + user scoped; branch compared as ``None``-normalized exact match.
+ ``origin_product`` is required and never defaulted: it selects the OAuth app, the warm quota gate, the
+ pool caps, and PR authorship, all of which are fixed when the warm boots and cannot be changed at
+ activation. Matching across origins would hand a Run provisioned under one product's budget and
+ authorship rules to another.
+
Reuse also requires the warm Run's runtime, model, sandbox environment, and custom image selections to
- match the request. Reasoning effort is deliberately excluded: activation applies the final effort before
- the first turn. Other mismatches return ``None`` so the caller cold-creates on the correct sandbox.
+ match the request, plus its permission mode when the caller states one. Reasoning effort is deliberately
+ excluded: activation applies the final effort before the first turn. Other mismatches return ``None`` so
+ the caller cold-creates on the correct sandbox.
The optional repo/branch/``await_user_message`` predicates stay in the query; the remaining selection is
matched in Python over the small candidate set.
"""
@@ -6036,7 +6055,7 @@ def _find_idling_warm_run(
TaskRun.objects.filter( # nosemgrep: idor-lookup-without-team — team_id filter applied via the task FK below
task__team_id=team_id,
task__created_by_id=user_id,
- task__origin_product=Task.OriginProduct.USER_CREATED,
+ task__origin_product=origin_product,
task__deleted=False,
task__github_integration_id=github_integration_id,
state__await_user_message=True,
@@ -6066,8 +6085,15 @@ def _find_idling_warm_run(
state.get("sandbox_environment_id") or None,
state.get("custom_image_id") or None,
)
- if have == wanted:
- return run
+ if have != wanted:
+ continue
+ # Asymmetric on purpose, and load-bearing: a warm Run's state ALWAYS holds a concrete permission
+ # mode (warm_task_sandbox writes one unconditionally), while callers that never send one — the
+ # Code app — must keep reusing their warms. Folding this into the tuple above would compare None
+ # against "default" and break every one of those reuses.
+ if initial_permission_mode is not None and state.get("initial_permission_mode") != initial_permission_mode:
+ continue
+ return run
return None
@@ -6158,7 +6184,11 @@ def _activate_warm_run(
if description and not (task.description or "").strip():
task.description = description
task.save(update_fields=["description", "updated_at"])
- activation_state_updates: dict[str, object] = {}
+ # Claims the Run as activated before the signal goes out. `await_user_message` can only be cleared
+ # after the signal — clearing it first would drop a Run out of the warm pool that a failed signal
+ # never activated, stranding its sandbox. That leaves a window where the Run is being activated but
+ # still looks idle, so this marker is what the unused-warm metric reads to tell the two apart.
+ activation_state_updates: dict[str, object] = {"warm_activated": True}
if auto_publish is not None:
# Before the signal: the agent-server re-reads run state when the forwarded
# first message arrives, so the choice must already be persisted by then.
@@ -6194,10 +6224,18 @@ def warm_task_sandbox(
sandbox_environment_id: str | UUID | None = None,
custom_image_id: str | UUID | None = None,
client_provenance: TaskClientProvenance | None = None,
+ origin_product: str = Task.OriginProduct.USER_CREATED,
+ initial_permission_mode: str | None = None,
) -> contracts.WarmTaskDTO | None:
- """Warm a full idling Run for a Code-app cloud task while the user composes.
+ """Warm a full idling Run for a cloud task while the user composes.
+
+ ``origin_product`` is stamped on the draft Task and fixes what the warm can later be reused for: it
+ selects the OAuth app, the warm quota gate (``USER_CREATED`` has no billing gate; ``POSTHOG_AI`` runs
+ the AI-credit check), the warm-pool caps, and PR authorship. None of these can change at activation,
+ so a submit only reuses a warm born under the same origin. Defaults to ``USER_CREATED`` for the
+ Code-app callers that predate the parameter.
- Births a draft Task (``USER_CREATED``), then ``SandboxWarmer.warm()`` provisions an interactive
+ Births a draft Task, then ``SandboxWarmer.warm()`` provisions an interactive
Run that boots, optionally clones and checks out ``branch``, then starts the agent on the selected
``runtime_adapter``/``model``/``reasoning_effort`` (carried on the Run state and read by the
agent-server at launch, so the sandbox boots on the right runtime), then idles awaiting the first
@@ -6260,6 +6298,7 @@ def warm_task_sandbox(
existing = _find_idling_warm_run(
team_id,
user_id,
+ origin_product=origin_product,
repository=repository,
repositories=normalized_repositories,
github_integration_id=github_integration_id,
@@ -6269,6 +6308,7 @@ def warm_task_sandbox(
reasoning_effort=reasoning_effort,
sandbox_environment_id=sandbox_environment_id,
custom_image_id=custom_image_id,
+ initial_permission_mode=initial_permission_mode,
)
if existing is not None:
return contracts.WarmTaskDTO(task_id=existing.task_id, run_id=existing.id)
@@ -6277,7 +6317,7 @@ def warm_task_sandbox(
team=team,
title="",
description="",
- origin_product=Task.OriginProduct.USER_CREATED,
+ origin_product=Task.OriginProduct(origin_product),
user_id=user_id,
repository=repository,
client_provenance=client_provenance,
@@ -6288,10 +6328,15 @@ def warm_task_sandbox(
assert task.created_by is not None # create_without_run always sets created_by from user_id
provider = get_provider_for_runtime_adapter(runtime_adapter)
- initial_permission_mode = "auto" if runtime_adapter == RuntimeAdapter.CODEX.value else "default"
+ # The agent session is constructed with this mode at boot and it cannot be changed once the sandbox
+ # is warm, so an explicit request wins and reuse matches on it. Callers that omit it (the Code app)
+ # keep the runtime-derived default they have always had.
+ resolved_permission_mode = initial_permission_mode or (
+ "auto" if runtime_adapter == RuntimeAdapter.CODEX.value else "default"
+ )
extra_state: dict = {
"branch": branch,
- "initial_permission_mode": initial_permission_mode,
+ "initial_permission_mode": resolved_permission_mode,
}
if sandbox_environment is not None:
extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
diff --git a/products/tasks/backend/facade/cancellation.py b/products/tasks/backend/facade/cancellation.py
index f9d96aea9ab7..a46a2908bc78 100644
--- a/products/tasks/backend/facade/cancellation.py
+++ b/products/tasks/backend/facade/cancellation.py
@@ -101,7 +101,16 @@ def cancel_task_run(
source: str = "api",
requested_by_user_id: int | None = None,
requested_by_distinct_id: str | None = None,
+ only_if_awaiting_first_message: bool = False,
) -> tuple[str, contracts.TaskRunDetailDTO | None]:
+ """Cancel a run. Returns the outcome and the run as it now stands.
+
+ ``only_if_awaiting_first_message`` makes this a warm hand-back rather than a cancel: the run is
+ stopped only while it is still idling for its first message. One warm Run is shared by every
+ composer holding the same selection (``_find_idling_warm_run`` dedupes on the selection, not on the
+ composer), so without this fence a composer that releases its lease after another one submitted
+ would stop the run that submit activated.
+ """
run = tasks_api._get_visible_run(run_id, task_id, team_id)
if run is None:
return "not_found", None
@@ -109,6 +118,8 @@ def cancel_task_run(
if not _publish_cancel_fallback_completion(run):
return "unavailable", tasks_api._task_run_detail_to_dto(run)
return "already_terminal", tasks_api._task_run_detail_to_dto(run)
+ if only_if_awaiting_first_message and not (run.state or {}).get("await_user_message"):
+ return "already_activated", tasks_api._task_run_detail_to_dto(run)
if run.environment != TaskRun.Environment.CLOUD:
return "not_cloud", tasks_api._task_run_detail_to_dto(run)
diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.py
index 32aef0178f12..79abe6b5ca38 100644
--- a/products/tasks/backend/facade/run_config.py
+++ b/products/tasks/backend/facade/run_config.py
@@ -22,7 +22,10 @@ from products.tasks.backend.feature_flags import get_model_access_error
# TaskArtifact's choice enums live on the model as Django ``TextChoices``; re-exported here
# so presentation builds serializer choices without importing the ORM model directly.
-from products.tasks.backend.models import TaskArtifact as _TaskArtifact
+from products.tasks.backend.models import (
+ Task as _Task,
+ TaskArtifact as _TaskArtifact,
+)
from products.tasks.backend.temporal.process_task.utils import (
CONTEXT_WINDOW_CHOICES,
PUBLIC_REASONING_EFFORTS,
@@ -47,11 +50,21 @@ TaskArtifactType = _TaskArtifact.ArtifactType
TaskArtifactAdapter = _TaskArtifact.Adapter
TaskArtifactStatus = _TaskArtifact.Status
+# Origin products a client may request a warm sandbox for. Deliberately an explicit list rather than
+# `SandboxWarmer.ORIGIN_PRODUCT_QUOTA.keys()`: registering an origin in the warm service is an internal
+# capability decision, and deriving the public API from it would silently widen this endpoint the day
+# someone adds a registry entry. `test_warmable_origin_products_are_registered` pins it as a subset.
+WARMABLE_ORIGIN_PRODUCTS: list[str] = [
+ _Task.OriginProduct.USER_CREATED,
+ _Task.OriginProduct.POSTHOG_AI,
+]
+
__all__ = [
"ALL_INITIAL_PERMISSION_MODE_CHOICES",
"CODEX_INITIAL_PERMISSION_MODE_CHOICES",
"CONTEXT_WINDOW_CHOICES",
"INITIAL_PERMISSION_MODE_CHOICES",
+ "WARMABLE_ORIGIN_PRODUCTS",
"InitialPermissionMode",
"MODEL_ACCESS_FLAGS",
"PUBLIC_REASONING_EFFORTS",
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 158b92a3f348..f455b56ea4df 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -10,6 +10,10 @@ if TYPE_CHECKING:
TaskWorkflowStartOutcome = Literal["attempted", "blocked", "failed", "started"]
+# Why a warm Run died unused. `released` is a deliberate hand-back (the composer cancels the run when
+# the draft is abandoned) and is the cheap, expected miss; `idle_timeout` means nobody released it and
+# it sat until the workflow reclaimed it, which is the wasteful one to drive down.
+PrewarmedUnusedReason = Literal["released", "idle_timeout", "other"]
CustomImageBuildOutcome = Literal["started", "succeeded", "failed", "scan_rejected"]
DevStackImageBakeOutcome = Literal["succeeded", "bake_failed", "failed", "dispatch_failed"]
# Outcome of an SSE task-run stream connection when it closes.
@@ -128,6 +132,15 @@ PREWARMED_ACTIVATED_TOTAL = Counter(
labelnames=["origin_product"],
)
+PREWARMED_UNUSED_TOTAL = Counter(
+ "posthog_tasks_prewarmed_unused_total",
+ "Pre-warmed Runs that reached terminal without ever receiving a first user message — a sandbox was "
+ "booted and paid for, then thrown away. The miss counterpart to posthog_tasks_prewarmed_activated_total: "
+ "activated / (activated + unused) is the warm hit rate, and `reason` says where the misses go "
+ "(a user who abandoned the composer looks different from a warm nobody released).",
+ labelnames=["origin_product", "reason"],
+)
+
TASK_RUN_FAILED_TOTAL = Counter(
"posthog_tasks_task_run_failed_total",
"TaskRun workflow failures with bounded attribution labels",
@@ -473,6 +486,38 @@ def observe_prewarmed_activated(task_run: "TaskRun") -> None:
PREWARMED_ACTIVATED_TOTAL.labels(origin_product=origin_product_label(task_run)).inc()
+def observe_prewarmed_unused(task_run: "TaskRun", *, reason: PrewarmedUnusedReason) -> None:
+ """Count a warm Run that terminalized still awaiting its first message.
+
+ Callers must check `state.prewarmed` and `state.await_user_message` first — activation clears the
+ latter, so a run that still carries it never got used. Never raises: a metric must not fail a
+ terminal status transition.
+ """
+ try:
+ PREWARMED_UNUSED_TOTAL.labels(origin_product=origin_product_label(task_run), reason=reason).inc()
+ except Exception:
+ logger.exception("prewarmed_unused_metric_failed", run_id=str(task_run.id))
+
+
+def observe_prewarmed_unused_if_never_activated(task_run: "TaskRun", *, reason: PrewarmedUnusedReason) -> None:
+ """Count a terminal Run as an unused warm, if that is what it is.
+
+ Owns the "never used" test so every path that terminalizes a Run books the miss the same way —
+ the workflow's status activity and the direct status write the cancel fallback uses when the
+ workflow is already gone.
+
+ `warm_activated` is what separates a real miss from a race: activation sets that marker before it
+ signals the first message and clears `await_user_message` only after, so a Run that terminalizes
+ between the two still carries both of the older markers while already being counted as activated.
+ """
+ run_state = task_run.state if isinstance(task_run.state, dict) else {}
+ if not run_state.get("prewarmed") or not run_state.get("await_user_message"):
+ return
+ if run_state.get("warm_activated"):
+ return
+ observe_prewarmed_unused(task_run, reason=reason)
+
+
def observe_custom_image_build(outcome: CustomImageBuildOutcome) -> None:
try:
CUSTOM_IMAGE_BUILD_TOTAL.labels(outcome=outcome).inc()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index e88ac42f7b26..fc7205d1234f 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -47,6 +47,7 @@ from products.tasks.backend.facade.run_config import (
CONTEXT_WINDOW_CHOICES,
INITIAL_PERMISSION_MODE_CHOICES,
PUBLIC_REASONING_EFFORTS,
+ WARMABLE_ORIGIN_PRODUCTS,
LLMProvider,
PrAuthorshipMode,
RunSource,
@@ -325,6 +326,32 @@ class TaskRunArtifactMetadataField(serializers.JSONField):
pass
+def get_initial_permission_mode_error(initial_permission_mode: str | None, runtime_adapter: str | None) -> str | None:
+ """Error message when a permission mode does not belong to the selected runtime, else ``None``.
+
+ The field's own ``ChoiceField`` accepts the union of both runtimes' vocabularies, which share only
+ ``plan`` and ``auto``. Pairing is checked here so every entry point that takes a mode — run, warm,
+ and task create — agrees on which pairs are valid, rather than a warm booting a sandbox on a mode
+ the matching run request would reject.
+ """
+ if initial_permission_mode is None:
+ return None
+ if runtime_adapter is None:
+ return "This field requires runtime_adapter to be set."
+ 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 in allowed_permission_modes:
+ return None
+ allowed_values = ", ".join(f"'{value}'" for value in allowed_permission_modes)
+ return (
+ f"Invalid choice '{initial_permission_mode}' for runtime_adapter "
+ f"'{runtime_adapter}'. Supported values: {allowed_values}."
+ )
+
+
def validate_task_run_artifact_metadata(attrs: dict[str, Any]) -> dict[str, Any]:
artifact_type = attrs.get("type")
metadata = attrs.get("metadata")
@@ -663,6 +690,17 @@ class TaskWriteSerializer(serializers.Serializer):
write_only=True,
help_text="Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.",
)
+ initial_permission_mode = serializers.ChoiceField(
+ choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
+ required=False,
+ default=None,
+ allow_null=True,
+ write_only=True,
+ help_text=(
+ "Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same "
+ "mode. Omit to reuse a warm Run whatever mode it booted on."
+ ),
+ )
pending_user_message = serializers.CharField(
required=False,
default=None,
@@ -831,6 +869,14 @@ class TaskWriteSerializer(serializers.Serializer):
if model_access_error is not None:
raise serializers.ValidationError({"model": model_access_error})
+ # Same reason: this selects the warm Run to activate, so it takes the pairing rule the run
+ # request applies rather than accepting a pair no runtime can serve.
+ permission_mode_error = get_initial_permission_mode_error(
+ attrs.get("initial_permission_mode"), attrs.get("runtime_adapter")
+ )
+ if permission_mode_error is not None:
+ raise serializers.ValidationError({"initial_permission_mode": permission_mode_error})
+
rel = attrs.get("signal_report_task_relationship")
if rel is not None:
if not attrs.get("signal_report"):
@@ -2915,22 +2961,8 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
errors["relayed_mcp_servers"] = collision_error
initial_permission_mode = attrs.get("initial_permission_mode")
runtime_adapter = attrs.get("runtime_adapter")
- 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}."
- )
+ if permission_mode_error := get_initial_permission_mode_error(initial_permission_mode, runtime_adapter):
+ errors["initial_permission_mode"] = permission_mode_error
pending_user_message = attrs.get("pending_user_message")
pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []
@@ -3125,22 +3157,8 @@ class TaskRunBootstrapCreateRequestSerializer(
raise serializers.ValidationError(errors)
return attrs
- 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}."
- )
+ if permission_mode_error := get_initial_permission_mode_error(initial_permission_mode, runtime_adapter):
+ errors["initial_permission_mode"] = permission_mode_error
runtime_fields = ("runtime_adapter", "model")
has_runtime_selection = any(
@@ -3258,6 +3276,27 @@ class WarmTaskRequestSerializer(serializers.Serializer):
allow_null=True,
help_text="Optional custom base image to provision before the task is submitted; takes precedence over the environment's image.",
)
+ origin_product = serializers.ChoiceField(
+ choices=WARMABLE_ORIGIN_PRODUCTS,
+ required=False,
+ default=tasks_facade.TaskOriginProduct.USER_CREATED,
+ help_text=(
+ "Product the warm Run is for. Fixed when the sandbox boots — it selects the OAuth app, the "
+ "quota gate, the warm-pool budget, and PR authorship — so a submit only reuses a warm born "
+ "under the same origin. Defaults to the Code app."
+ ),
+ )
+ initial_permission_mode = serializers.ChoiceField(
+ choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
+ required=False,
+ default=None,
+ allow_null=True,
+ help_text=(
+ "Permission mode to boot the agent session on. Read at session construction, so it cannot be "
+ "changed once the sandbox is warm — a submit selecting a different mode falls through to a "
+ "cold Run. Omit to take the runtime's default."
+ ),
+ )
def validate_repository(self, value: str | None) -> str | None:
if value is None:
@@ -3278,6 +3317,14 @@ class WarmTaskRequestSerializer(serializers.Serializer):
model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))
if model_access_error is not None:
raise serializers.ValidationError({"model": model_access_error})
+
+ # The agent session is built with this mode at boot and cannot be changed once warm, so a pair
+ # the run request would reject must not reach a sandbox here either.
+ permission_mode_error = get_initial_permission_mode_error(
+ attrs.get("initial_permission_mode"), attrs.get("runtime_adapter")
+ )
+ if permission_mode_error is not None:
+ raise serializers.ValidationError({"initial_permission_mode": permission_mode_error})
return attrs
@@ -3324,6 +3371,15 @@ class TaskRunCancelRequestSerializer(serializers.Serializer):
max_length=500,
help_text="Optional reason for the cancellation, recorded on the run and shown to run watchers.",
)
+ only_if_awaiting_first_message = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Cancel only while the run is still a warm sandbox awaiting its first message. A run that "
+ "has since received one is left alone and returned unchanged. Set this when handing a warm "
+ "sandbox back, so a release that races a submit cannot stop the run that submit started."
+ ),
+ )
class ClaudeTaskRunCreateSchemaSerializer(TaskRunCreateRequestSerializer):
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index c8b942382e90..6f7f33766b56 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -85,7 +85,7 @@ from products.tasks.backend.facade.metrics import (
observe_stream_resume_gap,
)
from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices
-from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
+from products.tasks.backend.facade.run_config import WARMABLE_ORIGIN_PRODUCTS, TaskArtifactAdapter, TaskArtifactType
from products.tasks.backend.facade.streams import (
TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
@@ -219,6 +219,14 @@ 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.
+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,
+}
# 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.
@@ -551,6 +559,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
request=TaskCreateSerializer,
responses={
201: TaskSerializer,
+ 403: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access is required for a create that can activate a warm sandbox",
+ ),
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
description=(
@@ -558,11 +570,32 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"task limit (code `signal_report_task_cap`), or the per-user creation rate limit fired"
),
),
+ 503: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="PostHog Desktop access could not be verified",
+ ),
},
)
def create(self, request, **kwargs):
serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)
+ # A create that carries warm-reuse hints can activate an idling sandbox in place, which starts
+ # the agent without the client ever calling the run endpoint — so the gates that endpoint puts
+ # in front of a cloud run have to be applied here too. Without this, a warm booted while the
+ # caller was entitled still runs after Desktop access or the usage limit turns against them.
+ # Scoped to warmable origins, which is what a warm can ever be reused for; the code-access
+ # exempt Inbox shapes are not among them, matching how the warm endpoint gates.
+ # `origin_product` is optional on the wire; `create_task` defaults it the same way.
+ if (
+ "branch" in serializer.validated_data
+ and serializer.validated_data.get("origin_product", tasks_facade.TaskOriginProduct.USER_CREATED)
+ in WARMABLE_ORIGIN_PRODUCTS
+ ):
+ if access_response := code_access_required_response(request, self.organization):
+ return access_response
+ if limit_response := usage_limit_response(request.user, self.team_id):
+ return limit_response
+
# Read before create_task, which pops the relationship out of the dict it's handed.
relationship = serializer.validated_data.get("signal_report_task_relationship")
from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off this module's import path
@@ -1052,15 +1085,22 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return self._task_error_response(result.error)
return Response(TaskSerializer(result.task).data)
- def _warm_enabled(self) -> bool:
- """Person + org level gate for the sandbox-warming feature. Fail-closed on any error."""
+ 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.
+ """
+ flag = WARM_SANDBOX_FLAGS_BY_ORIGIN_PRODUCT.get(origin_product)
+ if flag is None:
+ return False
user = self.request.user
distinct_id = getattr(user, "distinct_id", None) or str(getattr(user, "uuid", ""))
organization_id = str(getattr(self.team, "organization_id", "") or "")
try:
return bool(
posthoganalytics.feature_enabled(
- TASKS_PREWARM_SANDBOX_FLAG,
+ flag,
distinct_id,
groups={"organization": organization_id},
group_properties={"organization": {"id": organization_id}},
@@ -1069,7 +1109,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
)
except Exception:
- logger.exception("tasks-prewarm-sandbox flag check failed; treating as disabled")
+ logger.exception("%s flag check failed; treating as disabled", flag)
return False
@validated_request(
@@ -1092,7 +1132,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
},
summary="Warm a task sandbox",
description=(
- "Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, "
+ "Warm a full idling Run for a cloud task while the user composes: boot a sandbox, "
"clone the repo, check out the branch, and start the agent, then idle awaiting the first "
"message. On submit the normal create+run path transparently reuses and activates this Run; "
"abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty "
@@ -1103,10 +1143,13 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
@action(detail=False, methods=["post"], url_path="warm", required_scopes=["task:write"])
def warm(self, request, **kwargs):
- if not self._warm_enabled():
+ origin_product = request.validated_data["origin_product"]
+ if not self._warm_enabled(origin_product):
return Response(status=status.HTTP_200_OK)
- # Warming is a Desktop-composer feature with no Inbox caller, so no exemption applies.
+ # Every warmable origin's submit path gates on Desktop access too — POSTHOG_AI is not in
+ # `task_exempt_from_code_access`, only the Inbox shapes are — so warming applies it flat. A
+ # caller who can't run the task must not be able to provision a sandbox for it either.
if access_response := code_access_required_response(request, self.organization):
return access_response
@@ -1136,6 +1179,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
sandbox_environment_id=request.validated_data.get("sandbox_environment_id"),
custom_image_id=request.validated_data.get("custom_image_id"),
client_provenance=get_task_client_provenance(request),
+ origin_product=request.validated_data["origin_product"],
+ initial_permission_mode=request.validated_data.get("initial_permission_mode"),
)
if result is None:
return Response(status=status.HTTP_200_OK)
@@ -1487,7 +1532,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
request_serializer=TaskRunCancelRequestSerializer,
responses={
200: OpenApiResponse(
- response=TaskRunDetailSerializer, description="Run already finished; returned unchanged"
+ response=TaskRunDetailSerializer,
+ description=(
+ "Run already finished, or `only_if_awaiting_first_message` was set and the run has "
+ "since received its first message; returned unchanged"
+ ),
),
202: OpenApiResponse(response=TaskRunDetailSerializer, description="Cancellation accepted"),
400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Run is not a cloud run"),
@@ -1514,10 +1563,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
source="api",
requested_by_user_id=request.user.id,
requested_by_distinct_id=request.user.distinct_id,
+ only_if_awaiting_first_message=request.validated_data.get("only_if_awaiting_first_message", False),
)
if outcome == "not_found" or run is None:
raise NotFound()
- if outcome == "already_terminal":
+ if outcome in ("already_terminal", "already_activated"):
return Response(TaskRunDetailSerializer(run).data)
if outcome == "not_cloud":
return Response(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index 62d000ae9df6..d65d04448ff8 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -116,6 +116,44 @@ class TestUpdateTaskRunStatusActivity:
test_task_run.task.refresh_from_db()
assert test_task_run.task.deleted is True
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "state,timed_out,expected_reason",
+ [
+ ({"prewarmed": True, "await_user_message": True}, True, "idle_timeout"),
+ ({"prewarmed": True, "await_user_message": True}, False, "other"),
+ # Activation clears `await_user_message`, so this warm was used. Counting it as a miss
+ # would understate the warm hit rate the rollout decision reads.
+ ({"prewarmed": True}, True, None),
+ # Mid-activation: the marker is set before the first message is signaled and
+ # `await_user_message` is cleared only after, so a run that terminalizes in between still
+ # carries both older markers while already counted as activated.
+ ({"prewarmed": True, "await_user_message": True, "warm_activated": True}, True, None),
+ # Never warmed at all — a plain run terminalizing is not a warm miss.
+ ({}, True, None),
+ ],
+ )
+ def test_counts_a_warm_run_that_terminalized_unused(
+ self, activity_environment: ActivityEnvironment, test_task_run: TaskRun, state, timed_out, expected_reason
+ ) -> None:
+ test_task_run.state = state
+ test_task_run.save(update_fields=["state", "updated_at"])
+
+ with patch("products.tasks.backend.metrics.observe_prewarmed_unused") as m_observe:
+ async_to_sync(_run_update_task_run_status)(
+ activity_environment,
+ UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=TaskRun.Status.COMPLETED,
+ timed_out_inactivity=timed_out,
+ ),
+ )
+
+ if expected_reason is None:
+ m_observe.assert_not_called()
+ else:
+ assert m_observe.call_args.kwargs["reason"] == expected_reason
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
"marker",
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index fa9be8eda9a0..31d6f9098e4d 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -10,7 +10,7 @@ from temporalio.exceptions import ApplicationError
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.error_telemetry import truncate_error_message
-from products.tasks.backend.metrics import observe_wizard_run_unbound
+from products.tasks.backend.metrics import observe_prewarmed_unused_if_never_activated, observe_wizard_run_unbound
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.metrics import record_run_token_usage
from products.tasks.backend.temporal.observability import log_with_activity_context
@@ -124,6 +124,17 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
if input.timed_out_inactivity and old_status != input.status:
task_run.task.soft_delete_if_unclaimed_prewarm(task_run)
+ # A warm Run that reaches terminal without ever being activated was never used — the sandbox was
+ # booted and thrown away. Counting it against `prewarmed_activated_total` gives the warm hit rate,
+ # and the reason separates a deliberate hand-back from one nobody reclaimed.
+ if input.status in _TERMINAL_STATUSES and old_status != input.status:
+ observe_prewarmed_unused_if_never_activated(
+ task_run,
+ reason="idle_timeout"
+ if input.timed_out_inactivity
+ else ("released" if input.status == TaskRun.Status.CANCELLED else "other"),
+ )
+
if input.status in _TERMINAL_STATUSES:
from products.tasks.backend.logic.services.loop_runs import ( # noqa: PLC0415 — breaks the loop_runs -> process_task -> activities import cycle
handle_loop_run_terminal,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index d10239a01ca4..c205cf00fcb6 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -1504,6 +1504,7 @@ class TestTaskAPI(BaseTaskAPITest):
mock_find_warm_run.assert_called_once_with(
self.team.id,
self.user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
repository="posthog/posthog",
repositories=["posthog/posthog", "posthog/code"],
github_integration_id=integration.id,
@@ -1513,6 +1514,7 @@ class TestTaskAPI(BaseTaskAPITest):
reasoning_effort=None,
sandbox_environment_id=None,
custom_image_id=None,
+ initial_permission_mode=None,
)
update = self.client.patch(
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index b014df0c49ac..f435161f1181 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -158,6 +158,54 @@ class TestTaskRunMetrics(TestCase):
assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before + 1
+ def test_activation_claims_the_run_before_signaling_the_first_message(self) -> None:
+ # Activation cannot clear `await_user_message` until the signal lands — a failed signal would
+ # otherwise drop a never-activated run out of the warm pool and strand its sandbox. So it
+ # claims the run first, and a terminal transition arriving mid-signal must read that claim
+ # rather than book the run as a miss it is also counting as activated.
+ from products.tasks.backend.facade import api as facade
+ from products.tasks.backend.metrics import observe_prewarmed_unused_if_never_activated
+
+ run = self.task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ mode="interactive",
+ extra_state={"await_user_message": True, "prewarmed": True},
+ )
+ labels = {"origin_product": "user_created", "reason": "other"}
+ before = _sample_value("posthog_tasks_prewarmed_unused_total", labels)
+
+ def _terminalize_during_signal(*_args: object, **_kwargs: object) -> bool:
+ observe_prewarmed_unused_if_never_activated(TaskRun.objects.get(id=run.id), reason="other")
+ return True
+
+ with patch.object(facade, "signal_task_run_user_message", side_effect=_terminalize_during_signal):
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+
+ assert _sample_value("posthog_tasks_prewarmed_unused_total", labels) == before
+
+ def test_direct_terminal_write_counts_a_released_warm(self) -> None:
+ # The cancel fallback writes the terminal status itself when the workflow is already gone, so
+ # the status activity never runs and never books the miss.
+ from products.tasks.backend.facade import api as facade
+
+ run = self.task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ mode="interactive",
+ extra_state={"await_user_message": True, "prewarmed": True},
+ )
+ labels = {"origin_product": "user_created", "reason": "released"}
+ before = _sample_value("posthog_tasks_prewarmed_unused_total", labels)
+
+ with patch.object(facade, "signal_workflow_completion"):
+ facade.update_task_run(
+ run.id,
+ self.task.id,
+ self.team.id,
+ validated_data={"status": TaskRun.Status.CANCELLED},
+ )
+
+ assert _sample_value("posthog_tasks_prewarmed_unused_total", labels) == before + 1
+
def test_activating_run_without_prewarmed_marker_does_not_increment(self) -> None:
# Warm Runs provisioned before this ships have await_user_message but no prewarmed marker;
# activating them must not inflate the numerator (would push hit rate above 1).
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 92b3199c991e..34a769c02370 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -5,6 +5,7 @@ from unittest.mock import patch
from django.utils import timezone as django_timezone
+from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import PermissionDenied, Throttled
@@ -153,6 +154,53 @@ class TestWarmTaskSandbox(APIBaseTest):
assert response.status_code == 400
+ @parameterized.expand(
+ [
+ (
+ "claude_rejects_codex_mode",
+ "claude",
+ "claude-opus-4-6",
+ "full-access",
+ ),
+ (
+ "codex_rejects_claude_mode",
+ "codex",
+ "gpt-5.4",
+ "bypassPermissions",
+ ),
+ ("mode_without_a_runtime", None, None, "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_rejects_mismatched_permission_mode(
+ self,
+ _case_name,
+ runtime_adapter,
+ model,
+ initial_permission_mode,
+ mock_warm,
+ _mock_warm_enabled,
+ ):
+ # The mode is fixed when the sandbox boots, so a pair the run request would reject must not
+ # reach one here either — the submit that follows would be rejected against a booted sandbox.
+ response = self.client.post(
+ "/api/projects/@current/tasks/warm/",
+ {
+ "repository": "posthog/posthog",
+ "github_integration": self.integration.id,
+ "branch": "main",
+ "runtime_adapter": runtime_adapter,
+ "model": model,
+ "initial_permission_mode": initial_permission_mode,
+ },
+ format="json",
+ )
+
+ assert response.status_code == 400, response.content
+ assert response.json()["attr"] == "initial_permission_mode"
+ mock_warm.assert_not_called()
+
def test_provisions_selected_sandbox_environment_and_custom_image(self):
sandbox_environment = SandboxEnvironment.objects.create(
team=self.team,
@@ -378,12 +426,13 @@ class TestCreateTaskWarmReuse(APIBaseTest):
branch="main",
created_by=None,
extra_state: dict[str, Any] | None = None,
+ origin_product=Task.OriginProduct.USER_CREATED,
) -> tuple[Task, TaskRun]:
task = Task.objects.create(
team=self.team,
title="",
description="",
- origin_product=Task.OriginProduct.USER_CREATED,
+ origin_product=origin_product,
created_by=created_by or self.user,
repository=repository,
repositories=repositories or ([repository] if repository else []),
@@ -406,6 +455,53 @@ class TestCreateTaskWarmReuse(APIBaseTest):
validated.update(data)
return facade.create_task(self.team.id, self.user.id, validated_data=validated)
+ def test_desktop_create_without_permission_mode_still_reuses_warm(self):
+ # A warm Run's state always carries a concrete permission mode, but the Code app never sends one
+ # on create. Folding the mode into the equality tuple would compare None against "default" and
+ # break every Desktop warm reuse — this pins the asymmetric comparison that prevents it.
+ warm_task, run = self._warm_run(extra_state={"initial_permission_mode": "default"})
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ dto = self._create()
+
+ assert str(dto.id) == str(warm_task.id)
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 1
+
+ def test_reuses_matching_posthog_ai_warm_task(self):
+ warm_task, run = self._warm_run(
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ extra_state={"initial_permission_mode": "auto"},
+ )
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ dto = self._create(origin_product=Task.OriginProduct.POSTHOG_AI, initial_permission_mode="auto")
+
+ assert str(dto.id) == str(warm_task.id)
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 1
+
+ @parameterized.expand(
+ [
+ ("warm_is_code_submit_is_phai", Task.OriginProduct.USER_CREATED, Task.OriginProduct.POSTHOG_AI),
+ ("warm_is_phai_submit_is_code", Task.OriginProduct.POSTHOG_AI, Task.OriginProduct.USER_CREATED),
+ ]
+ )
+ def test_does_not_reuse_a_warm_from_a_different_origin_product(self, _name, warm_origin, submit_origin):
+ # Origin fixes the OAuth app, the quota gate, the pool budget and PR authorship at boot, so a
+ # cross-origin reuse would run under the wrong product's entitlements and authorship.
+ self._warm_run(origin_product=warm_origin)
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ dto = self._create(origin_product=submit_origin)
+
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 2
+ assert str(dto.origin_product) == submit_origin
+
+ def test_permission_mode_mismatch_creates_a_new_cold_task(self):
+ # The mode is read when the agent session is constructed, so a warm booted on one mode can't
+ # serve a submit that asked for another.
+ self._warm_run(extra_state={"initial_permission_mode": "default"})
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ self._create(initial_permission_mode="bypassPermissions")
+
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 2
+
def test_reuses_matching_warm_task_and_activates_it_in_place(self):
warm_task, run = self._warm_run()
with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal:
@@ -693,6 +789,101 @@ class TestCreateTaskWarmReuse(APIBaseTest):
assert kwargs["content"] == "resolved skill message"
assert kwargs["artifact_ids"] == ["artifact-1"]
+ def test_create_endpoint_regates_a_warm_reuse_that_would_activate_a_sandbox(self):
+ # Activating a warm starts the agent from the create endpoint, so the client never calls the run
+ # endpoint that normally applies this gate. A warm booted while the caller was entitled must not
+ # still run after entitlement is withdrawn.
+ _warm_task, run = self._warm_run()
+
+ with (
+ patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ return_value=tasks_access.DesktopAccessDecision.STARTUP_PLAN,
+ ),
+ patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal,
+ ):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "description": "fix the bug",
+ "repository": "posthog/posthog",
+ "github_integration": self.integration.id,
+ "branch": "main",
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ m_signal.assert_not_called()
+ run.refresh_from_db()
+ assert run.state.get("await_user_message") is True
+
+ def test_create_endpoint_without_warm_hints_is_not_regated(self):
+ # Only a create that can activate a sandbox takes the run-start gates; a plain create still
+ # goes through, and the run endpoint gates it when execution is actually requested.
+ with patch(
+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
+ return_value=tasks_access.DesktopAccessDecision.STARTUP_PLAN,
+ ):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "fix the bug"},
+ format="json",
+ )
+
+ assert response.status_code == 201, response.content
+
+
+class TestWarmRunRelease(APIBaseTest):
+ """Handing a warm sandbox back must never stop a run that has already been activated."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ _allow_desktop_access(self)
+ self.task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ created_by=self.user,
+ )
+
+ def _run(self, *, awaiting: bool) -> TaskRun:
+ return self.task.create_run(
+ mode="interactive",
+ extra_state={"prewarmed": True, **({"await_user_message": True} if awaiting else {})},
+ )
+
+ def _release(self, run: TaskRun):
+ return self.client.post(
+ f"/api/projects/@current/tasks/{self.task.id}/runs/{run.id}/cancel/",
+ {"only_if_awaiting_first_message": True},
+ format="json",
+ )
+
+ @parameterized.expand(
+ [
+ # One warm Run is shared by every composer holding the same selection, so a composer that
+ # releases after another one submitted would otherwise stop the run that submit started.
+ ("activated_run_is_left_alone", False, status.HTTP_200_OK, False),
+ # And the fence must not turn every release into a no-op, or abandoned sandboxes pile up
+ # in the warm pool until the reaper takes them.
+ ("idling_warm_is_still_stopped", True, status.HTTP_202_ACCEPTED, True),
+ ]
+ )
+ def test_release_only_stops_a_run_still_awaiting_its_first_message(
+ self, _case_name, awaiting, expected_status, expect_signal
+ ):
+ run = self._run(awaiting=awaiting)
+
+ with patch(
+ "products.tasks.backend.facade.cancellation._signal_complete_task", return_value="signaled"
+ ) as m_signal:
+ response = self._release(run)
+
+ assert response.status_code == expected_status, response.content
+ assert m_signal.called is expect_signal
+
class TestRunTaskWarmActivation(APIBaseTest):
"""The normal run path activates an idling warm Run instead of dispatching a fresh workflow."""
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index b37f5634f8d9..f5e765491034 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1723,6 +1723,28 @@ export const OriginProductEnumApi = {
Workflow: 'workflow',
} as const
+/**
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access
+ */
+export type TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi =
+ (typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi)[keyof typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi]
+
+export const TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = {
+ Default: 'default',
+ AcceptEdits: 'acceptEdits',
+ Plan: 'plan',
+ BypassPermissions: 'bypassPermissions',
+ Auto: 'auto',
+ ReadOnly: 'read-only',
+ FullAccess: 'full-access',
+} as const
+
/**
* Request body for creating or updating a task.
*
@@ -1829,6 +1851,16 @@ export interface TaskCreateApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -1974,6 +2006,16 @@ export interface TaskWriteApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -2102,6 +2144,16 @@ export interface PatchedTaskWriteApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -2858,28 +2910,6 @@ export const TaskRunBootstrapCreateRequestEnvironmentEnumApi = {
Cloud: 'cloud',
} as const
-/**
- * * `default` - default
- * * `acceptEdits` - acceptEdits
- * * `plan` - plan
- * * `bypassPermissions` - bypassPermissions
- * * `auto` - auto
- * * `read-only` - read-only
- * * `full-access` - full-access
- */
-export type TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi =
- (typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi)[keyof typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi]
-
-export const TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = {
- Default: 'default',
- AcceptEdits: 'acceptEdits',
- Plan: 'plan',
- BypassPermissions: 'bypassPermissions',
- Auto: 'auto',
- ReadOnly: 'read-only',
- FullAccess: 'full-access',
-} as const
-
/**
* Request body for creating a task run without starting execution yet.
*/
@@ -3539,6 +3569,8 @@ export interface TaskRunCancelRequestApi {
* @nullable
*/
reason?: string | null
+ /** Cancel only while the run is still a warm sandbox awaiting its first message. A run that has since received one is left alone and returned unchanged. Set this when handing a warm sandbox back, so a release that races a submit cannot stop the run that submit started. */
+ only_if_awaiting_first_message?: boolean
}
/**
@@ -4523,6 +4555,18 @@ export interface PaginatedTaskSummaryDTOListApi {
results: TaskSummaryDTOApi[]
}
+/**
+ * * `user_created` - user_created
+ * * `posthog_ai` - posthog_ai
+ */
+export type WarmTaskRequestOriginProductEnumApi =
+ (typeof WarmTaskRequestOriginProductEnumApi)[keyof typeof WarmTaskRequestOriginProductEnumApi]
+
+export const WarmTaskRequestOriginProductEnumApi = {
+ UserCreated: 'user_created',
+ PosthogAi: 'posthog_ai',
+} as const
+
/**
* Request body for warming a full idling Run while composing a Code-app cloud task.
*
@@ -4584,6 +4628,21 @@ export interface WarmTaskRequestApi {
* @nullable
*/
custom_image_id?: string | null
+ /** Product the warm Run is for. Fixed when the sandbox boots — it selects the OAuth app, the quota gate, the warm-pool budget, and PR authorship — so a submit only reuses a warm born under the same origin. Defaults to the Code app.
+ *
+ * * `user_created` - user_created
+ * * `posthog_ai` - posthog_ai */
+ origin_product?: WarmTaskRequestOriginProductEnumApi
+ /** Permission mode to boot the agent session on. Read at session construction, so it cannot be changed once the sandbox is warm — a submit selecting a different mode falls through to a cold Run. Omit to take the runtime's default.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
}
/**
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index a040f86bb76c..2ad636cfa664 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -2759,7 +2759,7 @@ export const getTasksWarmCreateUrl = (projectId: string) => {
}
/**
- * Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
+ * Warm a full idling Run for a cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
* @summary Warm a task sandbox
*/
export const tasksWarmCreate = async (
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 16af2c8e631e..d7a3452a5374 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1178,6 +1178,19 @@ export const TasksCreateBody = /* @__PURE__ */ zod
.describe(
'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
+ initial_permission_mode: zod
+ .union([
+ 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'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\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'
+ ),
pending_user_message: zod
.string()
.nullish()
@@ -1346,6 +1359,19 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
.describe(
'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
+ initial_permission_mode: zod
+ .union([
+ 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'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\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'
+ ),
pending_user_message: zod
.string()
.nullish()
@@ -1493,6 +1519,19 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
+ initial_permission_mode: zod
+ .union([
+ 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'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\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'
+ ),
pending_user_message: zod
.string()
.nullish()
@@ -2892,12 +2931,20 @@ export const TasksRunsArtifactsReferencesCreateBody = /* @__PURE__ */ zod.object
*/
export const tasksRunsCancelCreateBodyReasonMax = 500
+export const tasksRunsCancelCreateBodyOnlyIfAwaitingFirstMessageDefault = false
+
export const TasksRunsCancelCreateBody = /* @__PURE__ */ zod.object({
reason: zod
.string()
.max(tasksRunsCancelCreateBodyReasonMax)
.nullish()
.describe('Optional reason for the cancellation, recorded on the run and shown to run watchers.'),
+ only_if_awaiting_first_message: zod
+ .boolean()
+ .default(tasksRunsCancelCreateBodyOnlyIfAwaitingFirstMessageDefault)
+ .describe(
+ 'Cancel only while the run is still a warm sandbox awaiting its first message. A run that has since received one is left alone and returned unchanged. Set this when handing a warm sandbox back, so a release that races a submit cannot stop the run that submit started.'
+ ),
})
/**
@@ -3237,7 +3284,7 @@ export const TasksSummariesCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
+ * Warm a full idling Run for a cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
* @summary Warm a task sandbox
*/
export const tasksWarmCreateBodyRepositoryMax = 255
@@ -3248,6 +3295,8 @@ export const tasksWarmCreateBodyRepositoriesMax = 3
export const tasksWarmCreateBodyBranchMax = 255
+export const tasksWarmCreateBodyOriginProductDefault = `user_created`
+
export const TasksWarmCreateBody = /* @__PURE__ */ zod
.object({
repository: zod
@@ -3306,6 +3355,26 @@ export const TasksWarmCreateBody = /* @__PURE__ */ zod
.describe(
"Optional custom base image to provision before the task is submitted; takes precedence over the environment's image."
),
+ origin_product: zod
+ .enum(['user_created', 'posthog_ai'])
+ .describe('\* `user_created` - user_created\n\* `posthog_ai` - posthog_ai')
+ .default(tasksWarmCreateBodyOriginProductDefault)
+ .describe(
+ 'Product the warm Run is for. Fixed when the sandbox boots — it selects the OAuth app, the quota gate, the warm-pool budget, and PR authorship — so a submit only reuses a warm born under the same origin. Defaults to the Code app.\n\n\* `user_created` - user_created\n\* `posthog_ai` - posthog_ai'
+ ),
+ initial_permission_mode: zod
+ .union([
+ 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'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Permission mode to boot the agent session on. Read at session construction, so it cannot be changed once the sandbox is warm — a submit selecting a different mode falls through to a cold Run. Omit to take the runtime's default.\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 full idling Run while composing a Code-app cloud task.\n\nCollection-level: no task exists yet at typing time. The warmer births a draft Task and an\ninteractive Run that boots and starts the agent, optionally cloning and checking out a repository,\nthen idles awaiting the first message. `github_integration` is a plain integration PK (an integer);\nthe view re-scopes it to the caller's team before use."
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2ebab6aaae2f..cd4c1aac179b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64997,6 +64997,28 @@ export namespace Schemas {
environment?: TaskRunUpdateEnvironmentEnum;
}
+ /**
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access
+ */
+ export type TaskRunBootstrapCreateRequestInitialPermissionModeEnum = typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnum[keyof typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnum];
+
+
+ export const TaskRunBootstrapCreateRequestInitialPermissionModeEnum = {
+ Default: 'default',
+ AcceptEdits: 'acceptEdits',
+ Plan: 'plan',
+ BypassPermissions: 'bypassPermissions',
+ Auto: 'auto',
+ ReadOnly: 'read-only',
+ FullAccess: 'full-access',
+ } as const;
+
/**
* Request body for creating or updating a task.
*
@@ -65103,6 +65125,16 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -81235,6 +81267,16 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -81650,28 +81692,6 @@ export namespace Schemas {
Cloud: 'cloud',
} as const;
- /**
- * * `default` - default
- * * `acceptEdits` - acceptEdits
- * * `plan` - plan
- * * `bypassPermissions` - bypassPermissions
- * * `auto` - auto
- * * `read-only` - read-only
- * * `full-access` - full-access
- */
- export type TaskRunBootstrapCreateRequestInitialPermissionModeEnum = typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnum[keyof typeof TaskRunBootstrapCreateRequestInitialPermissionModeEnum];
-
-
- export const TaskRunBootstrapCreateRequestInitialPermissionModeEnum = {
- Default: 'default',
- AcceptEdits: 'acceptEdits',
- Plan: 'plan',
- BypassPermissions: 'bypassPermissions',
- Auto: 'auto',
- ReadOnly: 'read-only',
- FullAccess: 'full-access',
- } as const;
-
/**
* Request body for creating a task run without starting execution yet.
*/
@@ -81777,6 +81797,8 @@ export namespace Schemas {
* @nullable
*/
reason?: string | null;
+ /** Cancel only while the run is still a warm sandbox awaiting its first message. A run that has since received one is left alone and returned unchanged. Set this when handing a warm sandbox back, so a release that races a submit cannot stop the run that submit started. */
+ only_if_awaiting_first_message?: boolean;
}
/**
@@ -82639,6 +82661,16 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
+ /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
* First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
* @nullable
@@ -83935,6 +83967,18 @@ export namespace Schemas {
schema_name: string | null;
}
+ /**
+ * * `user_created` - user_created
+ * * `posthog_ai` - posthog_ai
+ */
+ export type WarmTaskRequestOriginProductEnum = typeof WarmTaskRequestOriginProductEnum[keyof typeof WarmTaskRequestOriginProductEnum];
+
+
+ export const WarmTaskRequestOriginProductEnum = {
+ UserCreated: 'user_created',
+ PosthogAi: 'posthog_ai',
+ } as const;
+
/**
* Request body for warming a full idling Run while composing a Code-app cloud task.
*
@@ -83996,6 +84040,21 @@ export namespace Schemas {
* @nullable
*/
custom_image_id?: string | null;
+ /** Product the warm Run is for. Fixed when the sandbox boots — it selects the OAuth app, the quota gate, the warm-pool budget, and PR authorship — so a submit only reuses a warm born under the same origin. Defaults to the Code app.
+ *
+ * * `user_created` - user_created
+ * * `posthog_ai` - posthog_ai */
+ origin_product?: WarmTaskRequestOriginProductEnum;
+ /** Permission mode to boot the agent session on. Read at session construction, so it cannot be changed once the sandbox is warm — a submit selecting a different mode falls through to a cold Run. Omit to take the runtime's default.
+ *
+ * * `default` - default
+ * * `acceptEdits` - acceptEdits
+ * * `plan` - plan
+ * * `bypassPermissions` - bypassPermissions
+ * * `auto` - auto
+ * * `read-only` - read-only
+ * * `full-access` - full-access */
+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
}
/**
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index c7827e165bf2..8f21fd61b51d 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -1098,6 +1098,19 @@ export const TasksCreateBody = /* @__PURE__ */ zod
.describe(
'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
+ initial_permission_mode: zod
+ .union([
+ 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'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\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'
+ ),
pending_user_message: zod
.string()
.nullish()
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index d097a2c94d39..1589ef2266ef 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -514,6 +514,7 @@ const TasksCreateSchema = TasksCreateBody.omit({
runtime_adapter: true,
model: true,
reasoning_effort: true,
+ initial_permission_mode: true,
pending_user_message: true,
pending_user_artifact_ids: true,
auto_publish: true,