:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): match the desktop model picker in the task composer (#78313)
Vojta Bartoš8b844e16e1d9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 53ff565e719a..148fca7d3856 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7753,9 +7753,9 @@ snapshots:scenes-app-tasks--mobile-list--light:hash: v1.k794b7964.9fd49300ca0d02ce3fe8cf6ea7eb850af2f42332d19a821ac73a6108f33fd651.aHbvQ9EqCKA43njPMkK_xgXEq4rToiJ0U8zAsxjwEWAscenes-app-tasks--mobile-new-task--dark:- hash: v1.k794b7964.c659bc768ad6ece501075207672466dd3a7f3401fd9fbffbef400d552cfd3007.Nm4GPHMsfybaB-1wJbcZ5Gr8oUCY0qiTPRujpHMpl0g+ hash: v1.k794b7964.152028e19d3bfdd9a5b43056cc7a534f9306670b6378580c738d91ce8aa0f1ae.kpF88GS5QmzTmo2SghRIiNKvuyb37HLoHPyCl0TO1pwscenes-app-tasks--mobile-new-task--light:- hash: v1.k794b7964.7d4307cef0f64137bd0278b3e9ca94c620ecbc63a726096ca6bdbc9570073ab5.p-KShlBQ8CPGw75SWnLVHxKGeUOnzvX3tACb5usDH9c+ hash: v1.k794b7964.30f8365a26f5d40ce829f565fbd5e6ce1a46e91804667fe47847d95ba48a9260.u2eo4jAXtM3tsVq4nl03Q88ivKFl0E4D2si5BGfxtO8scenes-app-tasks--mobile-task-selected--dark:hash: v1.k794b7964.db0156b3fd83b5c3494116788236075e0bc2c5ace019e4c1d9947d2b21fa70fb.4HfTdy-PBBkgEn0HFlUkrJm0D6GCiujf_ljrGGrLrscscenes-app-tasks--mobile-task-selected--light:diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex fcfc5d4d1ac3..7d9606242b08 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -21,6 +21,7 @@ export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESS// --- Composer model/effort helpers (pure — no component imports) ---export { resolveEffortForModel, DEFAULT_COMPOSER_MODEL, DEFAULT_COMPOSER_EFFORT } from '../utils/composerModels'+export { modelCatalogueLogic } from '../logics/modelCatalogueLogic'// --- Attached-context store + injection hook (headless) ---// Global registry of on-screen context providers; `contextItems` is what the send paths wrap into thediff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsxindex 925c624d52ec..d77f8d0a2767 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.test.tsx@@ -11,14 +11,19 @@ describe('ComposerModePicker', () => {cleanup()})- it('shows the three product modes with one description at a time and emits their server values', () => {+ it('shows the runtime\u2019s modes with one description at a time and emits their server values', () => {const onModeChange = jest.fn()render(<ComposerModePicker selectedMode={InitialPermissionModeEnumApi.Auto} onModeChange={onModeChange} />)fireEvent.click(screen.getByLabelText('Mode'))- expect(screen.queryByText('Default')).not.toBeInTheDocument()- expect(screen.queryByText('Accept edits')).not.toBeInTheDocument()+ // Claude's own set, in its own order — Codex's `read-only` / `full access` belong to the other runtime.+ expect(screen.getByText('Default')).toBeInTheDocument()+ expect(screen.getByText('Accept edits')).toBeInTheDocument()+ expect(screen.queryByText('Read only')).not.toBeInTheDocument()+ expect(screen.queryByText('Full access')).not.toBeInTheDocument()+ // Never-ask modes are gated out, as they are in the desktop app by default.+ expect(screen.queryByText('Full auto')).not.toBeInTheDocument()// The footer describes the selected mode on open; the other descriptions stay out of the menu.expect(@@ -27,25 +32,25 @@ describe('ComposerModePicker', () => {)).toBeInTheDocument()expect(- screen.queryByText('Never asks. The agent can change or delete live data on its own.')+ screen.queryByText('Plans the work first. Nothing runs until you approve the plan.')).not.toBeInTheDocument()// Hovering another option swaps the footer to its description. This breaks if ModeItemRow// stops forwarding Base UI's ref — the item then never registers for hover highlighting.- const fullAutoOption = screen.getByText('Full auto').closest('[role="option"]')- expect(fullAutoOption).not.toBeNull()- fireEvent.mouseMove(fullAutoOption!)- expect(screen.getByText('Never asks. The agent can change or delete live data on its own.')).toBeInTheDocument()+ const planOption = screen.getByText('Plan').closest('[role="option"]')+ expect(planOption).not.toBeNull()+ fireEvent.mouseMove(planOption!)+ expect(screen.getByText('Plans the work first. Nothing runs until you approve the plan.')).toBeInTheDocument()expect(screen.queryByText('Accepts file edits and shell commands automatically. Always asks before PostHog tools that change live data. Creating or publishing content asks only while you watch the run.')).not.toBeInTheDocument()- fireEvent.pointerDown(fullAutoOption!, { pointerType: 'mouse' })- fireEvent.click(fullAutoOption!)+ fireEvent.pointerDown(planOption!, { pointerType: 'mouse' })+ fireEvent.click(planOption!)- expect(onModeChange).toHaveBeenCalledWith(InitialPermissionModeEnumApi.BypassPermissions)+ expect(onModeChange).toHaveBeenCalledWith(InitialPermissionModeEnumApi.Plan)})it('never describes a mode the narrowed menu does not offer', () => {@@ -59,8 +64,8 @@ describe('ComposerModePicker', () => {fireEvent.click(screen.getByLabelText('Mode'))- // The selected mode is filtered out, so the footer falls back to an offered mode's description.- expect(screen.getByText('Never asks. The agent can change or delete live data on its own.')).toBeInTheDocument()+ // The selected mode is filtered out, so the footer falls back to the first offered mode.+ expect(screen.getByText('Plans the work first. Nothing runs until you approve the plan.')).toBeInTheDocument()expect(screen.queryByText('Accepts file edits and shell commands automatically. Always asks before PostHog tools that change live data. Creating or publishing content asks only while you watch the run.'diff --git a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsxindex b5a12c6deb4d..2cfc949615b2 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModePicker.tsx@@ -1,20 +1,41 @@import { forwardRef, useEffect, useState, type HTMLAttributes } from 'react'-import { IconPause, IconShield, IconUnlock } from '@posthog/icons'+import { IconEye, IconLock, IconPause, IconPencil, IconShield, IconUnlock } from '@posthog/icons'import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@posthog/quill-primitives'-import { getModeOption, MODE_OPTIONS, type PermissionMode } from 'products/posthog_ai/frontend/utils/composerModes'-import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ getModeOption,+ getModesForRuntimeAdapter,+ MODE_OPTIONS,+ type PermissionMode,+} from 'products/posthog_ai/frontend/utils/composerModes'+import {+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,+ InitialPermissionModeEnumApi,+ RuntimeAdapterEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'interface ModeStyle {icon: JSX.ElementclassName: string}+// Keyed by how much the agent may do unattended, so the same colour means the same freedom on both+// runtimes: read-only/plan warn, ask-first is neutral, unattended edits pass, never-ask is danger.const MODE_STYLES: Record<PermissionMode, ModeStyle> = {+ [InitialPermissionModeEnumApi.Default]: { icon: <IconLock />, className: 'text-secondary' },+ [InitialPermissionModeEnumApi.AcceptEdits]: { icon: <IconPencil />, className: 'text-success' },+ [InitialPermissionModeEnumApi.Plan]: { icon: <IconPause />, className: 'text-warning' },+ [CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.ReadOnly]: {+ icon: <IconEye />,+ className: 'text-warning',+ },[InitialPermissionModeEnumApi.Auto]: { icon: <IconShield />, className: 'text-success' },[InitialPermissionModeEnumApi.BypassPermissions]: { icon: <IconUnlock />, className: 'text-danger' },- [InitialPermissionModeEnumApi.Plan]: { icon: <IconPause />, className: 'text-warning' },+ [CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess]: {+ icon: <IconUnlock />,+ className: 'text-danger',+ },}interface ModeItemRowProps extends HTMLAttributes<HTMLDivElement> {@@ -44,7 +65,10 @@ const ModeItemRow = forwardRef<HTMLDivElement, ModeItemRowProps>(function ModeItexport interface ComposerModePickerProps {selectedMode: PermissionModeonModeChange: (mode: PermissionMode) => void- /** Restrict the picker to a subset of modes, such as the modes a plan approval offers. */+ /**+ * The modes to offer, in order — normally the runtime's own set via `getModesForRuntimeAdapter`, or a+ * narrower list such as the modes a plan approval offers. Defaults to Claude's, the default harness.+ */modes?: PermissionMode[]}@@ -57,7 +81,9 @@ export interface ComposerModePickerProps {* a footer strip pinned to two lines of height, so the menu never jumps while moving between modes.*/export function ComposerModePicker({ selectedMode, onModeChange, modes }: ComposerModePickerProps): JSX.Element {- const options = modes ? MODE_OPTIONS.filter((option) => modes.includes(option.value)) : MODE_OPTIONS+ // Ordered by `modes`, not by MODE_OPTIONS: each runtime lists its modes in its own order.+ const offered = modes ?? getModesForRuntimeAdapter(RuntimeAdapterEnumApi.Claude)+ const options = offered.flatMap((mode) => MODE_OPTIONS.filter((option) => option.value === mode))const selectedOption = getModeOption(selectedMode)// The mode whose description the footer shows. Base UI highlights the selected item on open, which// seeds this; reset on open so a hover from the previous open can't leak into the next one.diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsxindex b549ed39f7f0..fe3f66333112 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx@@ -1,103 +1,183 @@-import { useState } from 'react'+import { useMemo, useState } from 'react'-import { IconBrain, IconChevronDown } from '@posthog/icons'+import { IconChevronDown } from '@posthog/icons'import {Button,DropdownMenu,DropdownMenuContent,- DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from '@posthog/quill-primitives'import {- COMPOSER_MODELS,getEffortLabel,getEffortsForModel,getModelLabel,+ getRuntimeAdapterForModel,+ getRuntimeAdapterLabel,+ listRuntimeAdapters,+ modelsForRuntimeAdapter,} from 'products/posthog_ai/frontend/utils/composerModels'-import { ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ ModelChoiceApi,+ ReasoningEffortEnumApi,+ RuntimeAdapterEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'export interface ComposerModelEffortPickersProps {+ /** Models to offer, and the efforts each supports. Callers pass `modelCatalogueLogic`'s live catalogue. */+ models: ModelChoiceApi[]selectedModel: stringselectedEffort: ReasoningEffortEnumApionModelChange: (model: string) => voidonEffortChange: (effort: ReasoningEffortEnumApi) => void+ /**+ * The harness a live run already booted, if any. A running sandbox is one agent binary, and the mid-run config+ * channel only carries model/effort — so the other harnesses can't be reached without starting a new run, and are+ * offered as disabled. `null`/omitted means nothing is running and every harness is selectable.+ */+ lockedRuntimeAdapter?: string | null}/**- * Controlled, logic-free model + reasoning-effort pickers for a composer footer. The caller owns the selection- * and the side effects of changing it — the run composer wires it to `runInteractionLogic` (held client-side and- * applied at send time), the new-task composer wires it to the form that seeds the first run. This component only- * renders the dropdowns and reports changes up.+ * Controlled, logic-free model + reasoning-effort picker for a composer footer. The caller owns the selection and the+ * side effects of changing it — the run composer wires it to `runInteractionLogic` (held client-side and applied at+ * send time), the new-task composer wires it to the form that seeds the first run.+ *+ * Laid out as one chip opening a Harness → Model → Reasoning cascade, mirroring the desktop app's advanced view so the+ * two surfaces read the same. Every option comes from the passed catalogue; nothing about a specific model is+ * hardcoded here.*/+interface PickerSectionProps {+ title: string+ /** Right-aligned summary on the closed row — the value this section currently holds. */+ current: string+ value: string+ onValueChange: (value: string) => void+ children: React.ReactNode+}++/** One `label … current ›` row of the cascade, opening a radio list. */+function PickerSection({ title, current, value, onValueChange, children }: PickerSectionProps): JSX.Element {+ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span>{title}</span>+ <span className="flex-1 text-right text-muted">{current}</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuRadioGroup value={value} onValueChange={onValueChange}>+ {children}+ </DropdownMenuRadioGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )+}+export function ComposerModelEffortPickers({+ models,selectedModel,selectedEffort,onModelChange,onEffortChange,+ lockedRuntimeAdapter,}: ComposerModelEffortPickersProps): JSX.Element {- const effortOptions = getEffortsForModel(selectedModel)- const [modelOpen, setModelOpen] = useState(false)- const [effortOpen, setEffortOpen] = useState(false)+ const [open, setOpen] = useState(false)++ // The catalogue only changes when the gateway list reloads, so derive the whole tree in one pass — this+ // component re-renders on every keystroke in the composer above it.+ const { selectedAdapter, modelLabel, effortOptions, adapters, adapterModels } = useMemo(() => {+ const adapter = getRuntimeAdapterForModel(models, selectedModel)+ return {+ selectedAdapter: adapter,+ modelLabel: getModelLabel(models, selectedModel),+ effortOptions: getEffortsForModel(models, selectedModel),+ adapters: listRuntimeAdapters(models),+ adapterModels: modelsForRuntimeAdapter(models, adapter),+ }+ }, [models, selectedModel])++ // Switching harness picks that harness's first model; the caller clamps the effort to one it supports.+ const selectAdapter = (adapter: string): void => {+ const runtimeAdapter = adapter as RuntimeAdapterEnumApi+ const first = modelsForRuntimeAdapter(models, runtimeAdapter)[0]+ if (first && first.model !== selectedModel) {+ onModelChange(first.model)+ }+ }return (- <div className="flex items-center gap-1">- <DropdownMenu open={modelOpen} onOpenChange={setModelOpen}>- <DropdownMenuTrigger- render={- <Button variant="outline" size="sm">- {getModelLabel(selectedModel)}- <IconChevronDown />- </Button>- }- />- <DropdownMenuContent className="w-auto min-w-(--anchor-width)">- <DropdownMenuRadioGroup- value={selectedModel}- onValueChange={(value) => {- onModelChange(value)- setModelOpen(false)- }}+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ render={+ <Button variant="outline" size="sm">+ {modelLabel}+ {effortOptions.length > 0 && (+ <span className="text-muted">{getEffortLabel(selectedEffort)}</span>+ )}+ <IconChevronDown />+ </Button>+ }+ />+ <DropdownMenuContent className="w-auto min-w-56">+ {adapters.length > 1 && (+ <PickerSection+ title="Harness"+ current={getRuntimeAdapterLabel(selectedAdapter)}+ value={selectedAdapter}+ onValueChange={selectAdapter}>- <DropdownMenuLabel>Model</DropdownMenuLabel>- {COMPOSER_MODELS.map((option) => (- <DropdownMenuRadioItem key={option.value} value={option.value}>- {option.label}+ {adapters.map((adapter) => (+ <DropdownMenuRadioItem+ key={adapter}+ value={adapter}+ disabled={!!lockedRuntimeAdapter && adapter !== lockedRuntimeAdapter}+ >+ {getRuntimeAdapterLabel(adapter)}</DropdownMenuRadioItem>))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ </PickerSection>+ )}++ <PickerSection+ title="Model"+ current={modelLabel}+ value={selectedModel}+ onValueChange={(value) => {+ onModelChange(value)+ setOpen(false)+ }}+ >+ {adapterModels.map((option) => (+ <DropdownMenuRadioItem key={option.model} value={option.model}>+ {option.display_name}+ </DropdownMenuRadioItem>+ ))}+ </PickerSection>- <DropdownMenu open={effortOpen} onOpenChange={setEffortOpen}>- <DropdownMenuTrigger- render={- <Button variant="outline" size="sm">- <IconBrain />- {getEffortLabel(selectedEffort)}- <IconChevronDown />- </Button>- }- />- <DropdownMenuContent className="w-auto min-w-(--anchor-width)">- <DropdownMenuRadioGroup+ {/* A model with no effort control reports no supported efforts — then there's nothing to pick. */}+ {effortOptions.length > 0 && (+ <PickerSection+ title="Reasoning"+ current={getEffortLabel(selectedEffort)}value={selectedEffort}- onValueChange={(value: string) => {+ onValueChange={(value) => {onEffortChange(value as ReasoningEffortEnumApi)- setEffortOpen(false)+ setOpen(false)}}>- <DropdownMenuLabel>Effort</DropdownMenuLabel>{effortOptions.map((option) => (<DropdownMenuRadioItem key={option.value} value={option.value}>{option.label}</DropdownMenuRadioItem>))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- </div>+ </PickerSection>+ )}+ </DropdownMenuContent>+ </DropdownMenu>)}diff --git a/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.tsnew file mode 100644index 000000000000..6a14bb38048f--- /dev/null+++ b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts@@ -0,0 +1,86 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { FALLBACK_MODEL_CHOICES } from '../utils/composerModels'+import { modelCatalogueLogic } from './modelCatalogueLogic'++describe('modelCatalogueLogic', () => {+ const MODELS = [+ {+ runtime_adapter: 'claude' as const,+ model: 'claude-opus-4-8',+ display_name: 'Claude Opus 4.8',+ supported_efforts: ['low' as const, 'high' as const],+ },+ {+ runtime_adapter: 'codex' as const,+ model: 'gpt-5.6-luna',+ display_name: 'GPT-5.6 Luna',+ supported_efforts: ['low' as const, 'high' as const],+ },+ ]++ let logic: ReturnType<typeof modelCatalogueLogic.build>++ function useCatalogueMocks(models: typeof MODELS | 'error'): void {+ useMocks({+ get: {+ '/api/projects/:team_id/tasks/models/': () =>+ models === 'error' ? [500, { detail: 'gateway down' }] : [200, { models }],+ },+ })+ }++ function mount(): void {+ logic = modelCatalogueLogic()+ logic.mount()+ }++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('serves the fetched catalogue and keeps it for the next mount', async () => {+ useCatalogueMocks(MODELS)+ mount()+ await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess']).toMatchValues({ catalogue: MODELS })++ // Remounting renders the stored catalogue right away rather than the built-in stand-in, so the+ // picker doesn't briefly lose the models it was showing a moment ago.+ logic.unmount()+ useCatalogueMocks('error')+ mount()+ expect(logic.values.catalogue).toEqual(MODELS)+ })++ // A failed revalidation must not cost the models we already had — the built-in list is only a+ // stand-in for having nothing at all.+ it.each([['error' as const], [[] as typeof MODELS]])(+ 'keeps the stored catalogue when the refetch answers with %s',+ async (response) => {+ useCatalogueMocks(MODELS)+ mount()+ await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess'])+ logic.unmount()++ useCatalogueMocks(response)+ mount()+ await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess']).toMatchValues({ catalogue: MODELS })+ }+ )++ it('falls back to the built-in list when nothing has ever been fetched', async () => {+ useCatalogueMocks('error')+ mount()+ await expectLogic(logic)+ .toDispatchActions(['loadCatalogueSuccess'])+ .toMatchValues({ catalogue: FALLBACK_MODEL_CHOICES })+ })+})diff --git a/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts b/products/posthog_ai/frontend/logics/modelCatalogueLogic.tsnew file mode 100644index 000000000000..e8f30d3d43b2--- /dev/null+++ b/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts@@ -0,0 +1,116 @@+import { MakeLogicType, afterMount, connect, kea, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { projectLogic } from 'scenes/projectLogic'++import { tasksModelsRetrieve } from 'products/tasks/frontend/generated/api'+import { ModelChoiceApi } from 'products/tasks/frontend/generated/api.schemas'++import { FALLBACK_MODEL_CHOICES } from '../utils/composerModels'++const CATALOGUE_STORAGE_KEY = 'posthog_ai_model_catalogue'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface modelCatalogueLogicValues {+ currentProjectId: number | null // projectLogic+ cachedCatalogue: ModelChoiceApi[] | null+ catalogue: ModelChoiceApi[]+ fetchedCatalogue: ModelChoiceApi[] | null+ fetchedCatalogueLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface modelCatalogueLogicActions {+ loadCatalogue: () => any+ loadCatalogueFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCatalogueSuccess: (+ fetchedCatalogue: ModelChoiceApi[] | null,+ payload?: any+ ) => {+ fetchedCatalogue: ModelChoiceApi[] | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface modelCatalogueLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ catalogue: (+ fetchedCatalogue: ModelChoiceApi[] | null,+ cachedCatalogue: ModelChoiceApi[] | null+ ) => ModelChoiceApi[]+ }+}++export type modelCatalogueLogicType = MakeLogicType<+ modelCatalogueLogicValues,+ modelCatalogueLogicActions,+ Record<string, any>,+ modelCatalogueLogicMeta+>++/**+ * The models a task run may use, fetched from the tasks API rather than hardcoded — the endpoint derives it from the+ * live LLM gateway catalogue, so a newly released model reaches the composer without a frontend change.+ *+ * Served stale-while-revalidate: the last catalogue seen is kept in local storage and rendered immediately, while a+ * fresh one is fetched in the background. Whatever the fetch can't answer — no project, an unreachable gateway (the+ * endpoint answers with an empty list), a failed request — leaves the last known catalogue in place, and a small+ * built-in list stands in until there is one, so the model dropdown is never empty and never briefly loses the models+ * it showed a moment ago.+ */+export const modelCatalogueLogic = kea<modelCatalogueLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'modelCatalogueLogic']),++ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),++ loaders(({ values }) => ({+ fetchedCatalogue: [+ null as ModelChoiceApi[] | null,+ {+ loadCatalogue: async (): Promise<ModelChoiceApi[] | null> => {+ if (values.currentProjectId == null) {+ return null+ }+ try {+ const response = await tasksModelsRetrieve(String(values.currentProjectId))+ // An empty list means the gateway is unreachable, not that no model exists.+ return response.models.length ? response.models : null+ } catch {+ return null+ }+ },+ },+ ],+ })),++ reducers({+ cachedCatalogue: [+ null as ModelChoiceApi[] | null,+ { persist: true, storageKey: CATALOGUE_STORAGE_KEY },+ {+ loadCatalogueSuccess: (state, { fetchedCatalogue }) => fetchedCatalogue ?? state,+ },+ ],+ }),++ selectors({+ catalogue: [+ (s) => [s.fetchedCatalogue, s.cachedCatalogue],+ (fetched: ModelChoiceApi[] | null, cached: ModelChoiceApi[] | null): ModelChoiceApi[] =>+ fetched ?? cached ?? FALLBACK_MODEL_CHOICES,+ ],+ }),++ afterMount(({ actions }) => {+ actions.loadCatalogue()+ }),+])diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex eb28ef28256a..943e241f2d5d 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -217,7 +217,8 @@ describe('runInteractionLogic', () => {it('syncs a changed permission mode to the agent right before the message, and only when it changed', async () => {setThinking(false)- logic.actions.setMode('plan')+ // Not `plan` — that's the runtime's default, so it would be no change to sync.+ logic.actions.setMode('bypassPermissions')logic.actions.setComposerFormValues({ draft: 'ship it' })await expectLogic(logic, () => {@@ -226,7 +227,7 @@ describe('runInteractionLogic', () => {// The mode sync is a `set_config_option { configId: 'mode' }` command that lands before the message.expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([- setConfigCommand('mode', 'plan'),+ setConfigCommand('mode', 'bypassPermissions'),userMessageCommand('ship it'),])@@ -260,19 +261,19 @@ describe('runInteractionLogic', () => {expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('go on')])})- it('seeds the picker from the stored launch mode and ignores unrecognized wire modes', () => {+ it('seeds the picker from the stored launch mode and coerces the other runtime\u2019s modes', () => {// No live `current_mode_update` yet — the run's REST-stored launch mode drives the display.logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted, currentMode: 'plan' })expect(logic.values.selectedMode).toBe('plan')- // An unrecognized wire mode (a future mode, another runtime's vocabulary) must not leak out as a- // fake PermissionMode — it degrades to the stored launch mode.+ // A wire mode in the other runtime's vocabulary (a run started from desktop or Slack on Codex)+ // is coerced to this runtime's nearest ceiling rather than shown — or sent — as-is.stream.actions.setCurrentMode('full-access')- expect(logic.values.selectedMode).toBe('plan')+ expect(logic.values.selectedMode).toBe('bypassPermissions')- // The retired acceptEdits wire mode (older runs, resumed snapshots) normalizes to auto.+ // `acceptEdits` is one of Claude's own modes, so it stays put.stream.actions.setCurrentMode('acceptEdits')- expect(logic.values.selectedMode).toBe('auto')+ expect(logic.values.selectedMode).toBe('acceptEdits')})it('seeds a fresh run with the picked permission mode when the run is terminal', async () => {@@ -366,7 +367,7 @@ describe('runInteractionLogic', () => {runtime_adapter: 'claude',model: 'claude-sonnet-5',reasoning_effort: 'high',- initial_permission_mode: 'auto',+ initial_permission_mode: 'plan',resume_from_run_id: RUN_ID,pending_user_message: 'continue from here',})diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 2c2d6ff7d01f..11849416900b 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -7,14 +7,16 @@ import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import {+ buildRunCreateRequest,DEFAULT_COMPOSER_EFFORT,DEFAULT_COMPOSER_MODEL,resolveEffortForModel,} from 'products/posthog_ai/frontend/utils/composerModels'import {- DEFAULT_COMPOSER_MODE,+ getDefaultModeForRuntimeAdapter,getModeOption,type PermissionMode,+ resolveModeForRuntimeAdapter,} from 'products/posthog_ai/frontend/utils/composerModes'import {tasksRunCreate,@@ -22,15 +24,16 @@ import {tasksRunsCommandCreate,} from 'products/tasks/frontend/generated/api'import {- ClaudeRuntimeAdapterEnumApi,- type ClaudeTaskRunCreateSchemaApi,+ type ModelChoiceApi,type ReasoningEffortEnumApi,+ RuntimeAdapterEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'import type { PermissionRequestRecord } from '../types/streamTypes'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'import { attachedContextLogic } from './attachedContextLogic'+import { modelCatalogueLogic } from './modelCatalogueLogic'import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'import type { RunStatus } from './runStreamLogic'import { toolStreamEventsLogic } from './toolStreamEventsLogic'@@ -50,6 +53,8 @@ export interface RunInteractionLogicProps {currentModel?: string | nullcurrentEffort?: string | nullcurrentMode?: string | null+ /** The harness the run booted on. Authoritative — a live run can't be moved to another one. */+ currentRuntimeAdapter?: string | null/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can* re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */onRunStarted?: (runId: string) => void@@ -83,6 +88,7 @@ export interface runInteractionLogicValues {contextItems: AttachedContextItem[] // attachedContextLogicseenContextLinesByTask: Record<string, string[]> // attachedContextLogicsentContextKeysByTask: Record<string, string[]> // attachedContextLogic+ catalogue: ModelChoiceApi[] // modelCatalogueLogiccurrentProjectId: number | null // projectLogicconversationClearSupported: boolean // runStreamLogiccurrentMode: string | null // runStreamLogic@@ -318,8 +324,18 @@ export interface runInteractionLogicMeta {__keaTypeGenInternalSelectorTypes: {isTerminal: (currentRunStatus: RunStatus | null) => booleanselectedModel: (modelOverride: string | null, arg: any) => string- selectedEffort: (effortOverride: string | null, arg: any, selectedModel: string) => ReasoningEffortEnumApi- selectedMode: (modeOverride: PermissionMode | null, currentMode: string | null, arg: any) => PermissionMode+ selectedEffort: (+ effortOverride: string | null,+ arg: any,+ selectedModel: string,+ catalogue: ModelChoiceApi[]+ ) => ReasoningEffortEnumApi+ selectedMode: (+ modeOverride: PermissionMode | null,+ currentMode: string | null,+ arg: any,+ arg2: any+ ) => PermissionModeisBusy: (isThinking: boolean) => booleancanSend: (sending: boolean, isTerminal: boolean, currentProjectId: number | null) => booleanisSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean@@ -374,6 +390,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([['contextItems', 'sentContextKeysByTask', 'seenContextLinesByTask'],aiConsentLogic,['dataProcessingAccepted'],+ modelCatalogueLogic,+ ['catalogue'],],actions: [runStreamLogic({ streamKey: props.streamKey ?? props.runId }),@@ -587,9 +605,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([(override: string | null, current): string => override ?? current ?? DEFAULT_COMPOSER_MODEL,],selectedEffort: [- (s) => [s.effortOverride, (_, p) => p.currentEffort, s.selectedModel],- (override: string | null, current, model: string): ReasoningEffortEnumApi =>- resolveEffortForModel(override ?? current ?? DEFAULT_COMPOSER_EFFORT, model),+ (s) => [s.effortOverride, (_, p) => p.currentEffort, s.selectedModel, s.catalogue],+ (+ override: string | null,+ current: string | null | undefined,+ model: string,+ catalogue: ModelChoiceApi[]+ ): ReasoningEffortEnumApi =>+ resolveEffortForModel(catalogue, override ?? current ?? DEFAULT_COMPOSER_EFFORT, model),],// The permission mode to display and launch with: the client-side override, else the session's live// mode (from the stream's `current_mode_update` frames), else the run's stored launch mode, else the@@ -597,9 +620,20 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// mode, another runtime's vocabulary) degrades to the next fallback instead of leaking out as a// fake `PermissionMode`.selectedMode: [- (s) => [s.modeOverride, s.currentMode, (_, p) => p.currentMode],- (override: PermissionMode | null, current: string | null, initial): PermissionMode =>- override ?? getModeOption(current)?.value ?? getModeOption(initial)?.value ?? DEFAULT_COMPOSER_MODE,+ (s) => [s.modeOverride, s.currentMode, (_, p) => p.currentMode, (_, p) => p.currentRuntimeAdapter],+ (+ override: PermissionMode | null,+ current: string | null,+ initial: string | null | undefined,+ runtimeAdapter: string | null | undefined+ ): PermissionMode => {+ // Coerce onto the run's own harness: the wire can carry the other runtime's vocabulary+ // (a run started from desktop or Slack), and showing `full access` on a Claude run — or+ // sending it — is a mode that runtime rejects.+ const adapter = runtimeAdapter ?? RuntimeAdapterEnumApi.Claude+ const picked = override ?? getModeOption(current)?.value ?? getModeOption(initial)?.value+ return picked ? resolveModeForRuntimeAdapter(adapter, picked) : getDefaultModeForRuntimeAdapter(adapter)+ },],// The agent is actively working a turn — a follow-up typed now should stage rather than send.isBusy: [(s) => [s.isThinking], (isThinking: boolean): boolean => isThinking],@@ -697,6 +731,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// successful sync so the next send retries an unsent change.const activeModel = values.sentModel ?? props.currentModel ?? DEFAULT_COMPOSER_MODELconst activeEffort = resolveEffortForModel(+ values.catalogue,values.sentEffort ?? props.currentEffort ?? DEFAULT_COMPOSER_EFFORT,activeModel)@@ -716,11 +751,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([})actions.setSentEffort(values.selectedEffort)}- const activeMode =+ const modeAdapter = props.currentRuntimeAdapter ?? RuntimeAdapterEnumApi.Claude+ const lastKnownMode =values.sentMode ??getModeOption(values.currentMode)?.value ??- getModeOption(props.currentMode)?.value ??- DEFAULT_COMPOSER_MODE+ getModeOption(props.currentMode)?.value+ const activeMode = lastKnownMode+ ? resolveModeForRuntimeAdapter(modeAdapter, lastKnownMode)+ : getDefaultModeForRuntimeAdapter(modeAdapter)if (values.selectedMode !== activeMode) {await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {jsonrpc: '2.0',@@ -765,7 +803,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// unsupported value. No network here: the pick is synced to the agent at send time.setModel: ({ model }) => {const currentEffort = values.effortOverride ?? props.currentEffort- const resolvedEffort = resolveEffortForModel(currentEffort, model)+ const resolvedEffort = resolveEffortForModel(values.catalogue, currentEffort, model)if (resolvedEffort !== currentEffort) {actions.setEffort(resolvedEffort)}@@ -785,14 +823,16 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// from the finished run so the new run continues the thread, and carrying the picked model /// reasoning effort (the resume schema can't, so we send the Claude create shape). The response// carries the new run id as `latest_run`; the consumer-provided `onRunStarted` re-points to it.- const createRequest: ClaudeTaskRunCreateSchemaApi = {- runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,- model: values.selectedModel,- reasoning_effort: values.selectedEffort,- initial_permission_mode: values.selectedMode,- resume_from_run_id: props.runId,- pending_user_message: wrapWithPosthogContext(content, pendingContext),- }+ const createRequest = buildRunCreateRequest(+ values.catalogue,+ values.selectedModel,+ values.selectedEffort,+ values.selectedMode,+ {+ resume_from_run_id: props.runId,+ pending_user_message: wrapWithPosthogContext(content, pendingContext),+ }+ )const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)actions.resetComposerForm()markPendingContextSent(pendingContext)diff --git a/products/posthog_ai/frontend/logics/taskLogic.test.ts b/products/posthog_ai/frontend/logics/taskLogic.test.tsindex df0bdeacc2b1..025c9298ece7 100644--- a/products/posthog_ai/frontend/logics/taskLogic.test.ts+++ b/products/posthog_ai/frontend/logics/taskLogic.test.ts@@ -123,6 +123,9 @@ describe('taskLogic', () => {branch: null,status: TaskRunStatus.QUEUED,environment: TaskRunEnvironment.CLOUD,+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,log_url: null,error_message: null,output: null,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsxindex 3deda6766123..118b62072e15 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx@@ -31,6 +31,9 @@ function mockRun(taskId: string, status: TaskRunStatus, createdAt: string, complbranch: status === TaskRunStatus.COMPLETED ? 'posthog/task-branch' : null,status,environment: TaskRunEnvironment.CLOUD,+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,log_url: null,error_message: null,output: null,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex f3be673725fb..465fb70c3496 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -11,8 +11,13 @@ import {Suggestions,Welcome,} from 'products/posthog_ai/frontend/api/primitives'-import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'-import { cycleMode } from 'products/posthog_ai/frontend/utils/composerModes'+import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'+import { getRuntimeAdapterForModel, resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'+import {+ cycleMode,+ getModesForRuntimeAdapter,+ resolveModeForRuntimeAdapter,+} from 'products/posthog_ai/frontend/utils/composerModes'import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'@@ -27,6 +32,9 @@ export function TaskComposer(): JSX.Element {useActions(taskTrackerSceneLogic)const { newTaskData, isSubmittingTask, activeSuggestionGroup, displayHeadline, consentBlocked } =useValues(taskTrackerSceneLogic)+ const { catalogue } = useValues(modelCatalogueLogic)+ // Permission modes belong to the harness, so they follow the picked model.+ const composerAdapter = getRuntimeAdapterForModel(catalogue, newTaskData.model)// Buffer the description locally and debounce the write to kea so each keystroke is a cheap, isolated// re-render instead of a store dispatch. `Composer.Root` already blocks send on an empty `draft.value`@@ -60,7 +68,11 @@ export function TaskComposer(): JSX.Element {onChange={(config) => setNewTaskData({ repositoryConfig: config })}/><ComposerModeShortcut- onCycle={() => setNewTaskData({ permissionMode: cycleMode(newTaskData.permissionMode) })}+ onCycle={() =>+ setNewTaskData({+ permissionMode: cycleMode(composerAdapter, newTaskData.permissionMode),+ })+ }/><Composer.Rootvalue={draft.value}@@ -79,19 +91,29 @@ export function TaskComposer(): JSX.Element {</Composer.Field><Composer.Footer className="flex flex-wrap items-center gap-1 pl-2"><ComposerModePicker+ modes={getModesForRuntimeAdapter(composerAdapter)}selectedMode={newTaskData.permissionMode}onModeChange={(permissionMode) => setNewTaskData({ permissionMode })}/><ComposerModelEffortPickers+ models={catalogue}selectedModel={newTaskData.model}selectedEffort={newTaskData.reasoningEffort}onModelChange={(model) =>setNewTaskData({model,reasoningEffort: resolveEffortForModel(+ catalogue,newTaskData.reasoningEffort,model),+ // Clamp the mode too, not just the effort: leaving a+ // Claude-only mode selected against a Codex model would+ // show one permission ceiling and send a broader one.+ permissionMode: resolveModeForRuntimeAdapter(+ getRuntimeAdapterForModel(catalogue, model),+ newTaskData.permissionMode+ ),})}onEffortChange={(reasoningEffort) => setNewTaskData({ reasoningEffort })}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex ea45becf0507..8f9a3b6304ed 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -9,7 +9,9 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr// surface is its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'-import { cycleMode } from 'products/posthog_ai/frontend/utils/composerModes'+import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'+import { getRuntimeAdapterForModel } from 'products/posthog_ai/frontend/utils/composerModels'+import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'@@ -54,6 +56,7 @@ export function TaskRunChat({ taskId, runId, streamKey, onRunStarted }: TaskRunCcurrentModel: selectedRun?.state?.model,currentEffort: selectedRun?.state?.reasoning_effort,currentMode: selectedRun?.state?.initial_permission_mode,+ currentRuntimeAdapter: selectedRun?.runtime_adapter,onRunStarted: (newRunId) => {setSelectedRunId(newRunId, taskId)loadTaskRuns()@@ -119,6 +122,9 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):consentBlocked,selectedMode,} = useValues(runInteractionLogic(logicProps))+ const { catalogue } = useValues(modelCatalogueLogic)+ // A live run's harness is whatever it booted on; once terminal the next run follows the picked model.+ const composerAdapter = logicProps.currentRuntimeAdapter ?? getRuntimeAdapterForModel(catalogue, selectedModel)const {setComposerFormValues,submitComposerForm,@@ -136,7 +142,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):return (<>{/* Inside the slot children: detaches while a pending approval replaces the composer. */}- <ComposerModeShortcut onCycle={() => setMode(cycleMode(selectedMode))} />+ <ComposerModeShortcut onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))} /><Composer.Rootvalue={draft.value}onChange={draft.onChange}@@ -168,12 +174,20 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):{/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and isapplied when the message is sent — synced to the running agent on a follow-up,or used to seed the next run once terminal. */}- <ComposerModePicker selectedMode={selectedMode} onModeChange={setMode} />+ <ComposerModePicker+ selectedMode={selectedMode}+ onModeChange={setMode}+ modes={getModesForRuntimeAdapter(composerAdapter)}+ /><ComposerModelEffortPickers+ models={catalogue}selectedModel={selectedModel}selectedEffort={selectedEffort}onModelChange={setModel}onEffortChange={setEffort}+ // While the run is live its harness is fixed to whatever the sandbox booted; once+ // terminal the next send starts a fresh run, which may pick any harness.+ lockedRuntimeAdapter={isTerminal ? null : logicProps.currentRuntimeAdapter}/></Composer.Footer></Composer.Frame>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsxindex 28c3fd8d10a0..75abb2c3d426 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx@@ -1,11 +1,17 @@+import { useValues } from 'kea'+import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { humanFriendlyDuration } from 'lib/utils/durations'+import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'import { TaskRun } from '../../../types/taskTypes'+import { getEffortLabel, getModelLabel } from '../../../utils/composerModels'-/** Created / completed / duration row shown above the run log for the selected run. */+/** Created / completed / duration / model row shown above the run log for the selected run. */export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRun }): JSX.Element {+ const { catalogue } = useValues(modelCatalogueLogic)+return (<div className="items-center gap-4 text-xs text-muted hidden lg:flex"><dl className="inline-flex gap-1 items-center">@@ -30,6 +36,17 @@ export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRun }): JSX.</dd></dl>)}+ {/* What the run actually launched with, not what the composer currently has picked — a read-only+ viewer has no pickers to read, and on a resumed task the two can differ. */}+ {selectedRun.model && (+ <dl className="inline-flex gap-1 items-center">+ <dt className="m-0">Model:</dt>+ <dd className="m-0 inline-flex items-center">+ {getModelLabel(catalogue, selectedRun.model)}+ {selectedRun.reasoning_effort && ` · ${getEffortLabel(selectedRun.reasoning_effort)}`}+ </dd>+ </dl>+ )}</div>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.tsindex 50f7fde410c1..6c5769002704 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts@@ -37,6 +37,9 @@ const createMockRun = (id: string, status: TaskRunStatus): TaskRun => ({branch: null,status,environment: TaskRunEnvironment.CLOUD,+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,log_url: null,error_message: null,output: null,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 486dd86ede83..58a274767d3a 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -96,7 +96,8 @@ describe('taskTrackerSceneLogic', () => {// state). Dropping either regresses follow-up streaming / loses the first prompt.expect(runBody).toMatchObject({mode: 'interactive',- initial_permission_mode: 'auto',+ // Claude's default is Plan, matching the desktop app's per-runtime default.+ initial_permission_mode: 'plan',pending_user_message: 'do the thing',})const streamKey = logic.values.activeCreation?.streamKey@@ -213,6 +214,9 @@ describe('taskTrackerSceneLogic', () => {branch: null,status: TaskRunStatus.COMPLETED,environment: TaskRunEnvironment.CLOUD,+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,log_url: null,error_message: null,output: null,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 8bb9127a47fd..b00f17dc2cc8 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -10,7 +10,7 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { tasksCreate, tasksRunCreate } from 'products/tasks/frontend/generated/api'import {- ClaudeRuntimeAdapterEnumApi,+ type ModelChoiceApi,OriginProductEnumApi,ReasoningEffortEnumApi,type TaskWriteApi,@@ -23,6 +23,7 @@ import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'import { composerSeedLogic } from '../../logics/composerSeedLogic'import type { ComposerSeed } from '../../logics/composerSeedLogic'+import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'import { runnerPanelLogic } from '../../logics/runnerPanelLogic'import type { ActiveCreation } from '../../logics/runnerPanelLogic'import { tasksLogic } from '../../logics/tasksLogic'@@ -31,7 +32,12 @@ import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'import type { AttachedContextItem } from '../../types/contextTypes'import type { RepositoryConfig, Task } from '../../types/taskTypes'import type { TaskListParams } from '../../types/taskTypes'-import { DEFAULT_COMPOSER_EFFORT, DEFAULT_COMPOSER_MODEL, resolveEffortForModel } from '../../utils/composerModels'+import {+ buildRunCreateRequest,+ DEFAULT_COMPOSER_EFFORT,+ DEFAULT_COMPOSER_MODEL,+ resolveEffortForModel,+} from '../../utils/composerModels'import { DEFAULT_COMPOSER_MODE, type PermissionMode } from '../../utils/composerModes'import { wrapWithPosthogContext } from '../../utils/posthogContextBlock'@@ -76,6 +82,7 @@ export interface taskTrackerSceneLogicValues {contextItems: AttachedContextItem[] // attachedContextLogicseed: ComposerSeed | null // composerSeedLogicintegrations: IntegrationType[] | null // integrationsLogic+ catalogue: ModelChoiceApi[] // modelCatalogueLogiccurrentProjectId: number | null // projectLogicactiveCreation: ActiveCreation | null // runnerPanelLogichistoryExpanded: boolean // runnerPanelLogic@@ -325,6 +332,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['seed'],welcomeOverrideLogic,['overrideHeadlines'],+ modelCatalogueLogic,+ ['catalogue'],],actions: [runnerPanelLogic(props),@@ -529,22 +538,28 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// 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)// and launches with the picked model / reasoning effort (clamped to one the model supports).- const runResponse = await tasksRunCreate(projectId, newTask.id, {- branch: repositoryConfig.branch ?? null,- runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,- model,- reasoning_effort: resolveEffortForModel(reasoningEffort, model),- initial_permission_mode: permissionMode,- // 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),- })+ 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),+ }+ )+ )// 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.diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.tsindex e691fb9bbc19..dab9e4288c8e 100644--- a/products/posthog_ai/frontend/types/taskTypes.ts+++ b/products/posthog_ai/frontend/types/taskTypes.ts@@ -68,6 +68,9 @@ export interface TaskRun {branch: string | nullstatus: TaskRunStatusenvironment: TaskRunEnvironment+ runtime_adapter: string | null+ model: string | null+ reasoning_effort: string | nulllog_url: string | nullerror_message: string | nulloutput: Record<string, any> | nulldiff --git a/products/posthog_ai/frontend/utils/composerModels.test.ts b/products/posthog_ai/frontend/utils/composerModels.test.tsnew file mode 100644index 000000000000..a06b1fdabb87--- /dev/null+++ b/products/posthog_ai/frontend/utils/composerModels.test.ts@@ -0,0 +1,96 @@+import {+ ClaudeTaskRunCreateSchemaApi,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,+ InitialPermissionModeEnumApi,+ ModelChoiceApi,+ ReasoningEffortEnumApi,+ RuntimeAdapterEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'++import { buildRunCreateRequest, listRuntimeAdapters, modelsForRuntimeAdapter } from './composerModels'+import { type PermissionMode } from './composerModes'++describe('composerModels', () => {+ const CATALOGUE: ModelChoiceApi[] = [+ {+ runtime_adapter: 'claude',+ model: 'claude-opus-4-8',+ display_name: 'Claude Opus 4.8',+ supported_efforts: ['low', 'medium', 'high'],+ },+ {+ runtime_adapter: 'codex',+ model: 'gpt-5.6-luna',+ display_name: 'GPT-5.6 Luna',+ supported_efforts: ['low', 'medium', 'high'],+ },+ ]++ // The runtime follows from the model, so a Codex pick must not launch on the Claude adapter — and each+ // runtime validates permission modes against its own vocabulary, so `bypassPermissions` has to become+ // `full-access` on the way out. Getting either wrong is a request the backend rejects.+ it.each([+ ['claude-opus-4-8', 'claude', InitialPermissionModeEnumApi.BypassPermissions],+ ['gpt-5.6-luna', 'codex', CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess],+ ])('%s launches on %s', (model, expectedAdapter, expectedMode) => {+ const request = buildRunCreateRequest(+ CATALOGUE,+ model,+ ReasoningEffortEnumApi.High,+ InitialPermissionModeEnumApi.BypassPermissions as PermissionMode,+ { branch: 'main' }+ )++ expect(request).toMatchObject({+ runtime_adapter: expectedAdapter,+ model,+ initial_permission_mode: expectedMode,+ branch: 'main',+ })+ })++ // A model absent from the catalogue (still loading, or retired from the gateway) must still produce a+ // sendable request rather than an undefined adapter.+ it('falls back to the claude adapter for an unknown model', () => {+ const request = buildRunCreateRequest(+ CATALOGUE,+ 'some-unreleased-model',+ ReasoningEffortEnumApi.High,+ InitialPermissionModeEnumApi.Auto as PermissionMode,+ {}+ )++ expect(request).toMatchObject({ runtime_adapter: 'claude' })+ })++ // Some models take no reasoning effort at all, and the backend rejects any value for them+ // ("Supported values: none"). The composer always holds an effort for display, so the request has to drop it.+ it('omits the effort for a model that takes none', () => {+ const request = buildRunCreateRequest(+ [+ ...CATALOGUE,+ {+ runtime_adapter: 'claude',+ model: 'moonshotai/kimi-k3',+ display_name: 'Moonshotai Kimi K3',+ supported_efforts: [],+ },+ ],+ 'moonshotai/kimi-k3',+ ReasoningEffortEnumApi.High,+ InitialPermissionModeEnumApi.Plan as PermissionMode,+ {}+ )++ expect((request as ClaudeTaskRunCreateSchemaApi).reasoning_effort).toBeUndefined()+ })++ // The picker groups by harness and offers one row per runtime, so both have to come off the catalogue rather+ // than a hardcoded list — a runtime the gateway stops serving must stop being offered.+ it("derives the harness list and each harness's models from the catalogue", () => {+ expect(listRuntimeAdapters(CATALOGUE)).toEqual(['claude', 'codex'])+ expect(modelsForRuntimeAdapter(CATALOGUE, RuntimeAdapterEnumApi.Codex).map((o) => o.model)).toEqual([+ 'gpt-5.6-luna',+ ])+ })+})diff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.tsindex 1e31d6094e21..18ce752682fb 100644--- a/products/posthog_ai/frontend/utils/composerModels.ts+++ b/products/posthog_ai/frontend/utils/composerModels.ts@@ -1,27 +1,51 @@-import { ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ ClaudeRuntimeAdapterEnumApi,+ CodexRuntimeAdapterEnumApi,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,+ InitialPermissionModeEnumApi,+ ModelChoiceApi,+ ReasoningEffortEnumApi,+ RuntimeAdapterEnumApi,+ TaskRunCreateRequestSchemaApi,+} from 'products/tasks/frontend/generated/api.schemas'-export interface ComposerModelOption {- value: string- label: string-}+import { type PermissionMode, resolveModeForRuntimeAdapter } from './composerModes'export interface ComposerEffortOption {value: ReasoningEffortEnumApilabel: string}-// Claude-only lineup — the task tracker always launches the `claude` runtime adapter, so Codex/GPT models are-// intentionally absent. Add new Claude models here as they ship.-export const COMPOSER_MODELS: ComposerModelOption[] = [- { value: 'claude-sonnet-5', label: 'Claude Sonnet 5' },- { value: 'claude-opus-5', label: 'Claude Opus 5' },- { value: 'claude-opus-4-8', label: 'Claude Opus 4.8' },+// What a thinking model supports at minimum. Only reached for a model the catalogue hasn't described yet — while the+// first fetch is in flight, or for a run started on a model since retired from the gateway.+const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = [+ ReasoningEffortEnumApi.Low,+ ReasoningEffortEnumApi.Medium,+ ReasoningEffortEnumApi.High,+]++// Used only when the tasks API can't answer: an unreachable LLM gateway makes the catalogue endpoint return an empty+// list, and an empty model dropdown is worse than a stale one. The live catalogue is the source of truth — see+// `modelCatalogueLogic`. Claude-only: without the catalogue we can't know a Codex model exists, and Claude is the default.+export const FALLBACK_MODEL_CHOICES: ModelChoiceApi[] = [+ {+ runtime_adapter: RuntimeAdapterEnumApi.Claude,+ model: 'claude-sonnet-5',+ display_name: 'Claude Sonnet 5',+ supported_efforts: FALLBACK_EFFORTS,+ },+ {+ runtime_adapter: RuntimeAdapterEnumApi.Claude,+ model: 'claude-opus-5',+ display_name: 'Claude Opus 5',+ supported_efforts: FALLBACK_EFFORTS,+ },]export const DEFAULT_COMPOSER_MODEL = 'claude-sonnet-5'export const DEFAULT_COMPOSER_EFFORT: ReasoningEffortEnumApi = ReasoningEffortEnumApi.High-const EFFORT_LABELS: Record<ReasoningEffortEnumApi, string> = {+const EFFORT_LABELS: Record<string, string> = {[ReasoningEffortEnumApi.Low]: 'Low',[ReasoningEffortEnumApi.Medium]: 'Medium',[ReasoningEffortEnumApi.High]: 'High',@@ -30,64 +54,112 @@ const EFFORT_LABELS: Record<ReasoningEffortEnumApi, string> = {[ReasoningEffortEnumApi.Ultracode]: 'Ultracode',}-// Mirrors backend CLAUDE_REASONING_EFFORTS_BY_MODEL (products/tasks/backend/temporal/process_task/utils.py):-// xhigh/max are only offered for models that support them.-const EFFORTS_BY_MODEL: Record<string, ReasoningEffortEnumApi[]> = {- 'claude-opus-4-8': [- ReasoningEffortEnumApi.Low,- ReasoningEffortEnumApi.Medium,- ReasoningEffortEnumApi.High,- ReasoningEffortEnumApi.Xhigh,- ReasoningEffortEnumApi.Max,- ReasoningEffortEnumApi.Ultracode,- ],- 'claude-opus-5': [- ReasoningEffortEnumApi.Low,- ReasoningEffortEnumApi.Medium,- ReasoningEffortEnumApi.High,- ReasoningEffortEnumApi.Xhigh,- ReasoningEffortEnumApi.Max,- ReasoningEffortEnumApi.Ultracode,- ],- 'claude-sonnet-5': [- ReasoningEffortEnumApi.Low,- ReasoningEffortEnumApi.Medium,- ReasoningEffortEnumApi.High,- ReasoningEffortEnumApi.Xhigh,- ReasoningEffortEnumApi.Max,- ReasoningEffortEnumApi.Ultracode,- ],+export function getEffortsForModel(+ catalogue: ModelChoiceApi[],+ model: string | null | undefined+): ComposerEffortOption[] {+ const efforts = catalogue.find((option) => option.model === model)?.supported_efforts ?? FALLBACK_EFFORTS+ return efforts.map((value) => ({ value, label: EFFORT_LABELS[value] ?? value }))}-const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = [- ReasoningEffortEnumApi.Low,- ReasoningEffortEnumApi.Medium,- ReasoningEffortEnumApi.High,-]+// Which runtime drives this model. The adapter is a property of the model, not an independent choice, so+// deriving it is what keeps a `(runtime_adapter, model)` pair from ever disagreeing. Defaults to `claude` for a+// model the catalogue hasn't described — the fallback lineup is Claude-only.+export function getRuntimeAdapterForModel(+ catalogue: ModelChoiceApi[],+ model: string | null | undefined+): RuntimeAdapterEnumApi {+ return catalogue.find((option) => option.model === model)?.runtime_adapter ?? RuntimeAdapterEnumApi.Claude+}++// The harnesses the catalogue actually offers, in the order the models arrive. Derived rather than enumerated, so a+// runtime the gateway stops serving disappears from the picker on its own.+export function listRuntimeAdapters(catalogue: ModelChoiceApi[]): RuntimeAdapterEnumApi[] {+ return [...new Set(catalogue.map((option) => option.runtime_adapter))]+}++export function modelsForRuntimeAdapter(+ catalogue: ModelChoiceApi[],+ runtimeAdapter: RuntimeAdapterEnumApi+): ModelChoiceApi[] {+ return catalogue.filter((option) => option.runtime_adapter === runtimeAdapter)+}++const RUNTIME_ADAPTER_LABELS: Record<RuntimeAdapterEnumApi, string> = {+ [RuntimeAdapterEnumApi.Claude]: 'Claude',+ [RuntimeAdapterEnumApi.Codex]: 'Codex',+}-export function getEffortsForModel(model: string | null | undefined): ComposerEffortOption[] {- const efforts = (model && EFFORTS_BY_MODEL[model]) || FALLBACK_EFFORTS- return efforts.map((value) => ({ value, label: EFFORT_LABELS[value] }))+export function getRuntimeAdapterLabel(runtimeAdapter: string): string {+ return RUNTIME_ADAPTER_LABELS[runtimeAdapter as RuntimeAdapterEnumApi] ?? runtimeAdapter}-export function getModelLabel(model: string | null | undefined): string {- return COMPOSER_MODELS.find((option) => option.value === model)?.label ?? model ?? 'Model'+export function getModelLabel(catalogue: ModelChoiceApi[], model: string | null | undefined): string {+ return catalogue.find((option) => option.model === model)?.display_name ?? model ?? 'Model'}export function getEffortLabel(effort: string | null | undefined): string {- return effort ? (EFFORT_LABELS[effort as ReasoningEffortEnumApi] ?? effort) : 'Effort'+ return effort ? (EFFORT_LABELS[effort] ?? effort) : 'Effort'}// Clamp an effort to one the selected model actually supports — the new-run path can inherit an effort from a-// previous run on a different model (e.g. `max` carried over to Sonnet, which only offers low/medium/high), and-// the backend rejects an out-of-range effort. Falls back to the default when valid, else the highest available.+// previous run on a different model (e.g. `max` carried over to a model that only offers low/medium/high), and the+// backend rejects an out-of-range effort. Falls back to the default when valid, else the highest available.export function resolveEffortForModel(+ catalogue: ModelChoiceApi[],effort: string | null | undefined,model: string | null | undefined): ReasoningEffortEnumApi {- const allowed = getEffortsForModel(model).map((option) => option.value)+ const allowed = getEffortsForModel(catalogue, model).map((option) => option.value)+ // A model with no effort control reports none; the picker hides the row, and `buildRunCreateRequest`+ // omits the field entirely. This value is only ever a display fallback.+ if (!allowed.length) {+ return DEFAULT_COMPOSER_EFFORT+ }if (effort && allowed.includes(effort as ReasoningEffortEnumApi)) {return effort as ReasoningEffortEnumApi}return allowed.includes(DEFAULT_COMPOSER_EFFORT) ? DEFAULT_COMPOSER_EFFORT : allowed[allowed.length - 1]}++/**+ * Build a run-create request for the picked model.+ *+ * The request schema is discriminated on `runtime_adapter`, and each runtime names its permission modes+ * differently — so which runtime a model belongs to has to be decided in one place rather than assumed at each+ * call site. Everything else the caller needs (branch, resume id, message) rides along in `rest`.+ */+export function buildRunCreateRequest(+ catalogue: ModelChoiceApi[],+ model: string,+ reasoningEffort: ReasoningEffortEnumApi,+ permissionMode: PermissionMode,+ rest: Partial<TaskRunCreateRequestSchemaApi>+): TaskRunCreateRequestSchemaApi {+ // A model with no effort control rejects any effort at all — `get_reasoning_effort_error` answers+ // "Supported values: none" — so the field is left off rather than sent with a display fallback.+ const effort = getEffortsForModel(catalogue, model).length ? reasoningEffort : undefined++ if (getRuntimeAdapterForModel(catalogue, model) === CodexRuntimeAdapterEnumApi.Codex) {+ return {+ ...rest,+ runtime_adapter: CodexRuntimeAdapterEnumApi.Codex,+ model,+ reasoning_effort: effort,+ initial_permission_mode: resolveModeForRuntimeAdapter(+ CodexRuntimeAdapterEnumApi.Codex,+ permissionMode+ ) as CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,+ }+ }+ return {+ ...rest,+ runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,+ model,+ reasoning_effort: effort,+ initial_permission_mode: resolveModeForRuntimeAdapter(+ ClaudeRuntimeAdapterEnumApi.Claude,+ permissionMode+ ) as InitialPermissionModeEnumApi,+ }+}diff --git a/products/posthog_ai/frontend/utils/composerModes.test.ts b/products/posthog_ai/frontend/utils/composerModes.test.tsindex 1e110be48443..e96ad63b9e58 100644--- a/products/posthog_ai/frontend/utils/composerModes.test.ts+++ b/products/posthog_ai/frontend/utils/composerModes.test.ts@@ -1,26 +1,75 @@-import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi as CodexMode,+ InitialPermissionModeEnumApi as ClaudeMode,+ RuntimeAdapterEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'-import { cycleMode, DEFAULT_COMPOSER_MODE, getModeOption } from './composerModes'+import {+ cycleMode,+ getDefaultModeForRuntimeAdapter,+ getModesForRuntimeAdapter,+ resolveModeForRuntimeAdapter,+} from './composerModes'describe('composerModes', () => {- // The `shift+tab` cycle: advances through every mode and wraps back to the first, so no mode is- // unreachable and the last one loops around.+ // Each runtime validates against its own vocabulary, so the picker must offer that runtime's modes —+ // sending Claude's `bypassPermissions` to Codex, or Codex's `read-only` to Claude, is rejected.it.each([- [InitialPermissionModeEnumApi.Auto, InitialPermissionModeEnumApi.BypassPermissions],- [InitialPermissionModeEnumApi.BypassPermissions, InitialPermissionModeEnumApi.Plan],- [InitialPermissionModeEnumApi.Plan, InitialPermissionModeEnumApi.Auto],- ])('cycleMode(%s) → %s', (current, next) => {- expect(cycleMode(current)).toBe(next)+ [RuntimeAdapterEnumApi.Claude, ClaudeMode.AcceptEdits, true],+ [RuntimeAdapterEnumApi.Claude, CodexMode.ReadOnly, false],+ [RuntimeAdapterEnumApi.Codex, CodexMode.ReadOnly, true],+ [RuntimeAdapterEnumApi.Codex, ClaudeMode.AcceptEdits, false],+ ])('%s offers %s: %s', (adapter, mode, offered) => {+ expect(getModesForRuntimeAdapter(adapter).includes(mode)).toBe(offered)})- it.each([[null], [undefined], ['not-a-mode']])('cycleMode(%s) resets to the default', (current) => {- expect(cycleMode(current)).toBe(DEFAULT_COMPOSER_MODE)+ // Never-ask modes stay out of the picker while the web surface has no equivalent of desktop's+ // `allowBypassPermissions` setting — but each runtime still accepts one, so a run already launched on+ // it keeps resolving instead of degrading.+ it.each([+ [RuntimeAdapterEnumApi.Claude, ClaudeMode.BypassPermissions],+ [RuntimeAdapterEnumApi.Codex, CodexMode.FullAccess],+ ])('%s gates %s out of the picker but still accepts it', (adapter, mode) => {+ expect(getModesForRuntimeAdapter(adapter)).not.toContain(mode)+ expect(resolveModeForRuntimeAdapter(adapter, mode)).toBe(mode)+ })++ // A mode carried across harnesses — switching model, or opening a run started from another surface —+ // must land on the nearest ceiling rather than silently loosening what the agent may do.+ it.each([+ [RuntimeAdapterEnumApi.Codex, ClaudeMode.BypassPermissions, CodexMode.FullAccess],+ [RuntimeAdapterEnumApi.Codex, ClaudeMode.AcceptEdits, CodexMode.Auto],+ [RuntimeAdapterEnumApi.Codex, ClaudeMode.Default, CodexMode.Auto],+ [RuntimeAdapterEnumApi.Claude, CodexMode.ReadOnly, ClaudeMode.Plan],+ [RuntimeAdapterEnumApi.Claude, CodexMode.FullAccess, ClaudeMode.BypassPermissions],+ // Shared on both, so it passes straight through.+ [RuntimeAdapterEnumApi.Codex, ClaudeMode.Plan, ClaudeMode.Plan],+ ])('%s coerces %s → %s', (adapter, mode, expected) => {+ expect(resolveModeForRuntimeAdapter(adapter, mode)).toBe(expected)+ })++ // Claude opens on Plan and Codex on Auto, matching the desktop app.+ it.each([+ [RuntimeAdapterEnumApi.Claude, ClaudeMode.Plan],+ [RuntimeAdapterEnumApi.Codex, CodexMode.Auto],+ ])('%s defaults to %s', (adapter, expected) => {+ expect(getDefaultModeForRuntimeAdapter(adapter)).toBe(expected)+ })++ // The `shift+tab` cycle stays inside the run's own runtime and wraps, so no mode is unreachable and+ // the cycle can never hand the runtime a mode it rejects.+ it('cycles within the runtime and wraps around', () => {+ const codexModes = getModesForRuntimeAdapter(RuntimeAdapterEnumApi.Codex)+ const seen = codexModes.map((_, i) =>+ codexModes.reduce((mode) => mode, cycleMode(RuntimeAdapterEnumApi.Codex, codexModes[i]))+ )+ expect(seen).toEqual([...codexModes.slice(1), codexModes[0]])})- // Persisted selections and older runs still carry the retired acceptEdits mode — it must keep- // resolving to a real option instead of falling back to the bare 'Mode' trigger.- it('resolves legacy acceptEdits to the auto option', () => {- expect(getModeOption(InitialPermissionModeEnumApi.AcceptEdits)?.value).toBe(InitialPermissionModeEnumApi.Auto)- expect(cycleMode(InitialPermissionModeEnumApi.AcceptEdits)).toBe(InitialPermissionModeEnumApi.BypassPermissions)+ // An unknown or absent mode is coerced onto the runtime first, so the cycle starts somewhere real.+ it.each([[null], [undefined], ['not-a-mode']])('cycleMode(codex, %s) still yields a codex mode', (current) => {+ expect(getModesForRuntimeAdapter(RuntimeAdapterEnumApi.Codex)).toContain(+ cycleMode(RuntimeAdapterEnumApi.Codex, current)+ )})})diff --git a/products/posthog_ai/frontend/utils/composerModes.ts b/products/posthog_ai/frontend/utils/composerModes.tsindex 6c71888348bc..f2eb7c6f22c2 100644--- a/products/posthog_ai/frontend/utils/composerModes.ts+++ b/products/posthog_ai/frontend/utils/composerModes.ts@@ -1,10 +1,15 @@-import { InitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi,+ InitialPermissionModeEnumApi,+ RuntimeAdapterEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'-/** The permission modes exposed by the PostHog AI composer. */-export type PermissionMode =- | typeof InitialPermissionModeEnumApi.Auto- | typeof InitialPermissionModeEnumApi.BypassPermissions- | typeof InitialPermissionModeEnumApi.Plan+/**+ * A permission mode in either runtime's vocabulary. Claude and Codex name these differently and each+ * validates against its own set, so the picker offers the modes of the harness the run will use rather+ * than one blended list. Mirrors the desktop app's `ExecutionMode`.+ */+export type PermissionMode = InitialPermissionModeEnumApi | CodexTaskRunCreateSchemaInitialPermissionModeEnumApiexport interface ComposerModeOption {value: PermissionMode@@ -12,10 +17,28 @@ export interface ComposerModeOption {description: string}-export const DEFAULT_COMPOSER_MODE: PermissionMode = InitialPermissionModeEnumApi.Auto--// Ordered for the Shift+Tab cycle and the picker.+/** Every mode either runtime offers, described once. `plan` and `auto` are shared. */export const MODE_OPTIONS: ComposerModeOption[] = [+ {+ value: InitialPermissionModeEnumApi.Default,+ label: 'Default',+ description: 'Asks before anything that changes files, runs commands, or touches live data.',+ },+ {+ value: InitialPermissionModeEnumApi.AcceptEdits,+ label: 'Accept edits',+ description: 'Accepts file edits automatically. Still asks before shell commands and live data.',+ },+ {+ value: InitialPermissionModeEnumApi.Plan,+ label: 'Plan',+ description: 'Plans the work first. Nothing runs until you approve the plan.',+ },+ {+ value: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.ReadOnly,+ label: 'Read only',+ description: 'Inspects the repo and answers, but changes nothing.',+ },{value: InitialPermissionModeEnumApi.Auto,label: 'Auto',@@ -28,37 +51,96 @@ export const MODE_OPTIONS: ComposerModeOption[] = [description: 'Never asks. The agent can change or delete live data on its own.',},{- value: InitialPermissionModeEnumApi.Plan,- label: 'Plan',- description: 'Plans the work first. Nothing runs until you approve the plan.',+ value: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess,+ label: 'Full access',+ description: 'Never asks. The agent can change or delete live data on its own.',},]-// Modes retired from the picker resolve to their closest current equivalent, so persisted-// selections and runs started before the retirement keep resolving to a real option.-const LEGACY_MODE_ALIASES: Record<string, PermissionMode> = {- [InitialPermissionModeEnumApi.AcceptEdits]: InitialPermissionModeEnumApi.Auto,+// Each runtime's own modes, in the order its picker shows them — the same sets and order the desktop app+// uses, so a mode means the same thing and sits in the same place on both surfaces.+const CLAUDE_MODES: PermissionMode[] = [+ InitialPermissionModeEnumApi.Default,+ InitialPermissionModeEnumApi.AcceptEdits,+ InitialPermissionModeEnumApi.Plan,+ InitialPermissionModeEnumApi.BypassPermissions,+ InitialPermissionModeEnumApi.Auto,+]++const CODEX_MODES: PermissionMode[] = [+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Plan,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.ReadOnly,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Auto,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess,+]++// Hidden from the picker, exactly as the desktop app hides them: its `allowBypassPermissions` setting+// defaults to off and filters these two out of the menu (ModeSelector.tsx). Uncomment them here once the+// web surface has the equivalent setting. They stay in the vocabularies above on purpose — a run already+// launched on one must still render its label and coerce across runtimes, it just can't be picked.+const GATED_MODES: PermissionMode[] = [+ InitialPermissionModeEnumApi.BypassPermissions,+ CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess,+]++/** The modes the picker offers for a runtime — its vocabulary minus anything gated. */+export function getModesForRuntimeAdapter(runtimeAdapter: string): PermissionMode[] {+ return getRuntimeModeVocabulary(runtimeAdapter).filter((mode) => !GATED_MODES.includes(mode))}-export function getModeOption(mode: string | null | undefined): ComposerModeOption | undefined {- if (mode == null) {- return undefined+/** Every mode a runtime accepts, gated or not — what coercion and label lookup resolve against. */+export function getRuntimeModeVocabulary(runtimeAdapter: string): PermissionMode[] {+ return runtimeAdapter === RuntimeAdapterEnumApi.Codex ? CODEX_MODES : CLAUDE_MODES+}++/** Claude opens on Plan, Codex on Auto — matching the desktop app's per-runtime defaults. */+export function getDefaultModeForRuntimeAdapter(runtimeAdapter: string): PermissionMode {+ return runtimeAdapter === RuntimeAdapterEnumApi.Codex+ ? CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Auto+ : InitialPermissionModeEnumApi.Plan+}++export const DEFAULT_COMPOSER_MODE: PermissionMode = getDefaultModeForRuntimeAdapter(RuntimeAdapterEnumApi.Claude)++// A mode that only exists on the other runtime maps to the nearest ceiling on this one, so switching+// harness — or opening a run started from another surface — never silently loosens what the agent may do.+const CODEX_FALLBACKS: Record<string, PermissionMode> = {+ [InitialPermissionModeEnumApi.Default]: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Auto,+ [InitialPermissionModeEnumApi.AcceptEdits]: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Auto,+ [InitialPermissionModeEnumApi.BypassPermissions]: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess,+}++const CLAUDE_FALLBACKS: Record<string, PermissionMode> = {+ [CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.ReadOnly]: InitialPermissionModeEnumApi.Plan,+ [CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.FullAccess]: InitialPermissionModeEnumApi.BypassPermissions,+}++/** Coerce a mode into the vocabulary the given runtime validates against. */+export function resolveModeForRuntimeAdapter(runtimeAdapter: string, mode: PermissionMode): PermissionMode {+ const native = getRuntimeModeVocabulary(runtimeAdapter)+ if (native.includes(mode)) {+ return mode+ }+ if (runtimeAdapter === RuntimeAdapterEnumApi.Codex) {+ return CODEX_FALLBACKS[mode] ?? CodexTaskRunCreateSchemaInitialPermissionModeEnumApi.Auto}- const normalized = LEGACY_MODE_ALIASES[mode] ?? mode- return MODE_OPTIONS.find((option) => option.value === normalized)+ return CLAUDE_FALLBACKS[mode] ?? InitialPermissionModeEnumApi.Default+}++export function getModeOption(mode: string | null | undefined): ComposerModeOption | undefined {+ return mode == null ? undefined : MODE_OPTIONS.find((option) => option.value === mode)}export function getModeLabel(mode: string | null | undefined): string {return getModeOption(mode)?.label ?? 'Mode'}-// Advance to the next mode, wrapping around. Port of `/code`'s `cycleModeOption`. An unknown `current`-// (null/undefined or a value not in the set) resets to the default so the cycle stays predictable.-export function cycleMode(current: string | null | undefined): PermissionMode {- const order = MODE_OPTIONS.map((option) => option.value)- const index = order.indexOf((getModeOption(current)?.value ?? current) as PermissionMode)- if (index === -1) {- return DEFAULT_COMPOSER_MODE- }- return order[(index + 1) % order.length]+// Advance to the next mode of the run's own runtime, wrapping around. Port of `/code`'s `cycleModeOption`.+// A mode the runtime doesn't offer — carried from the other harness, or from a run started elsewhere — is+// coerced onto this runtime first, so the cycle always starts from something the runtime accepts.+export function cycleMode(runtimeAdapter: string, current: string | null | undefined): PermissionMode {+ const order = getModesForRuntimeAdapter(runtimeAdapter)+ const from = resolveModeForRuntimeAdapter(runtimeAdapter, (current ?? '') as PermissionMode)+ const index = order.indexOf(from)+ return index === -1 ? order[0] : order[(index + 1) % order.length]}