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.

17.7 KB
Raw Blame
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, tasksWarmResumeCreate } from 'products/tasks/frontend/generated/api'
import type { WarmTaskRequestApi, WarmTaskResumeRequestApi } from 'products/tasks/frontend/generated/api.schemas'

/** Debounce before warming, measured from the keystroke that first made the draft non-empty. */
const WARM_DEBOUNCE_MS = 250
/** 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 WarmSubmission {
    projectId: string
    lease: WarmLease | null
    runId?: string | null
    superseded?: boolean
}

export interface TaskWarmLogicProps {
    /** Matches `taskTrackerSceneLogicProps.panelId` so each composer instance owns its own lease. */
    panelId?: string
    taskId?: string
    resumeFromRunId?: string
}

export type TaskWarmRequest = WarmTaskRequestApi | WarmTaskResumeRequestApi

/**
 * Build the lease key from the fields the backend matches a warm Run on. Reasoning effort is
 * deliberately excluded: activation applies the final effort before the first turn, so changing it must
 * not throw the warm away (`_find_idling_warm_run` omits it from the match for the same reason).
 */
export function warmLeaseKey(request: TaskWarmRequest): string {
    if ('resume_from_run_id' in request) {
        return [
            request.resume_from_run_id,
            request.runtime_adapter ?? '',
            request.model ?? '',
            request.initial_permission_mode ?? '',
        ].join('|')
    }
    return [
        request.repository ?? '',
        (request.repositories ?? []).join(','),
        request.github_integration ?? '',
        request.branch ?? '',
        request.runtime_adapter ?? '',
        request.model ?? '',
        request.initial_permission_mode ?? '',
        request.sandbox_environment_id ?? '',
        request.custom_image_id ?? '',
    ].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)
    }
}

async function releaseUnusedWarm(submission: WarmSubmission): Promise<void> {
    // A failed or aborted submission may still deliver its message. Leave uncertain warms to the reaper.
    if (
        !submission.superseded &&
        submission.runId !== undefined &&
        submission.lease &&
        submission.lease.runId !== submission.runId
    ) {
        await cancelWarmRun(submission.projectId, submission.lease)
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskWarmLogicValues {
    currentProjectId: number | null // projectLogic
    warmLease: WarmLease | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskWarmLogicActions {
    consumeWarm: (
        submission: WarmSubmission,
        runId: string | null
    ) => {
        runId: string | null
        submission: WarmSubmission
    }
    noteDraft: (
        hasText: boolean,
        request: TaskWarmRequest
    ) => {
        hasText: boolean
        request: TaskWarmRequest
    }
    prepareSubmit: (submission: WarmSubmission) => {
        submission: WarmSubmission
    }
    prewarm: (request: TaskWarmRequest) => {
        request: TaskWarmRequest
    }
    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 ?? ([props.taskId, props.resumeFromRunId].filter(Boolean).join(':') || 'scene')),

    connect({
        values: [projectLogic, ['currentProjectId']],
    }),

    actions({
        noteDraft: (hasText: boolean, request: TaskWarmRequest) => ({ hasText, request }),
        prewarm: (request: TaskWarmRequest) => ({ request }),
        prepareSubmit: (submission: WarmSubmission) => ({ submission }),
        releaseWarm: true,
        consumeWarm: (submission: WarmSubmission, runId: string | null) => ({ submission, runId }),
        setWarmLease: (lease: WarmLease | null) => ({ lease }),
    }),

    reducers({
        warmLease: [
            null as WarmLease | null,
            {
                setWarmLease: (_, { lease }) => lease,
            },
        ],
    }),

    listeners(({ actions, values, cache, props }) => ({
        noteDraft: ({ hasText, request }) => {
            if (!hasText) {
                // Draft emptied — drop a pending warm and schedule a release, so a user who clears the
                // 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
            }
            // Route on the payload, not on `props.taskId`: the request shape is what each endpoint
            // accepts, and only a resume request names a source run. The scene composer mounts this logic
            // under the `/tasks/:taskId` route param, so `props.taskId` can be the `new` sentinel — a
            // fresh-task body posted to `tasks/new/warm/` is rejected for the missing `resume_from_run_id`
            // and that composer never warms at all.
            const resumeRequest = 'resume_from_run_id' in request ? request : null
            if (resumeRequest && !props.taskId) {
                return
            }
            if (cache.warming) {
                // Only one warm POST runs at a time. A newer selection that arrives mid-flight must not
                // be dropped, or the completing POST installs a lease on the stale selection and the
                // 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
            const warmRequest: { submission: WarmSubmission | null } = { submission: null }
            cache.warmRequest = warmRequest
            const projectId = String(values.currentProjectId)
            const disposables = cache.disposables
            try {
                const warm = resumeRequest
                    ? await tasksWarmResumeCreate(projectId, props.taskId as string, resumeRequest)
                    : await tasksWarmCreate(projectId, request as WarmTaskRequestApi)
                const lease = warm?.task_id && warm?.run_id ? { key, taskId: warm.task_id, runId: warm.run_id } : null
                if (warmRequest.submission) {
                    warmRequest.submission.lease = lease
                    await releaseUnusedWarm(warmRequest.submission)
                    return
                }
                if (disposables.isDisposed) {
                    if (lease) {
                        await cancelWarmRun(projectId, lease)
                    }
                    return
                }
                // An empty body is the documented "not warmed" answer — the flag is off, the pool is
                // full, or the integration didn't resolve. Not an error, just no speedup this time.
                if (lease) {
                    actions.setWarmLease(lease)
                    // The cooldown throttles repeated "not warmed" answers, which leave no lease. This
                    // warm produced one, so drop the stamp: once a submit consumes the lease or a
                    // release drops it, the next draft for the same selection must warm again instead
                    // of waiting out the cooldown.
                    cache.lastWarmRequestKey = null
                    cache.lastWarmRequestAt = null
                }
                // The user may have abandoned the draft while this POST was in flight, in which case the
                // release hit the early-exit below with nothing to release. Honor that intent now so the
                // 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
                cache.warmRequest = null
            }
            // A newer selection arrived while the POST was open. Now that the slot is free, release the
            // sandbox booted for the stale selection and warm for the latest one instead. A pending
            // 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)
        },

        prepareSubmit: ({ submission }) => {
            // A warm started after submission can miss the backend's pool lookup and create an extra task.
            cache.disposables.dispose('warm-debounce')
            cache.disposables.dispose('warm-release')
            cache.pendingRelease = false
            cache.pendingWarmRequest = null
            // A submission-owned warm never installs a lease to clear this stamp. Let the next draft warm.
            cache.lastWarmRequestKey = null
            cache.lastWarmRequestAt = null
            if (values.currentProjectId == null) {
                return
            }
            // Another submission can activate the same warm, so the earlier result cannot authorize cleanup.
            if (cache.submission) {
                cache.submission.superseded = true
            }
            submission.lease = values.warmLease
            cache.submission = submission
            if (cache.warmRequest && !cache.warmRequest.submission) {
                cache.warmRequest.submission = submission
            }
            // Teardown must not cancel a run while its first message is being delivered.
            actions.setWarmLease(null)
        },

        consumeWarm: async ({ submission, runId }) => {
            submission.runId = runId
            await releaseUnusedWarm(submission)
        },
    })),

    // Leaving the composer (this logic is connected to the scene, so it unmounts when the scene or panel
    // does) is the most common way to abandon a draft, more so than clearing the box and waiting out the
    // release timer. Cancel the held warm here too, so navigating away reclaims the sandbox immediately
    // instead of leaving it to idle until the server reaper. Cancel inline rather than dispatching
    // releaseWarm, because a listener dispatched during teardown does not run. Submitted warms belong to
    // their submission until its outcome is known. Unsubmitted warms still mid-boot are released on arrival.
    beforeUnmount(({ values }) => {
        const lease = values.warmLease
        if (lease && values.currentProjectId != null) {
            void cancelWarmRun(String(values.currentProjectId), lease)
        }
    }),
])