Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): use the team/user model preference in the task composer (#84110)

Vojta Bartoš75c37e179fae
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 1ad47c2f396f..bb88224c1aae 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -275,6 +275,48 @@ export interface TaskSearchResult {
metadata: Record<string, unknown>;
}
+/**
+ * The effective AI run defaults for the signed-in user in a project, as resolved
+ * by the tasks backend: their own preference over the project default. `source`
+ * says which level supplied them, and is `"none"` when neither is set.
+ */
+export interface TaskRunDefaults {
+ runtime_adapter: string | null;
+ model: string | null;
+ reasoning_effort: string | null;
+ source: "user" | "team" | "none";
+}
+
+export const NO_TASK_RUN_DEFAULTS: TaskRunDefaults = {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ source: "none",
+};
+
+/**
+ * A stored preference triple. All three null means the level is unset and the one
+ * below it applies — a personal preference falls back to the project default, and
+ * the project default to each surface's built-in model.
+ */
+export interface TaskRunPreferences {
+ runtime_adapter: string | null;
+ model: string | null;
+ reasoning_effort: string | null;
+}
+
+export const NO_TASK_RUN_PREFERENCES: TaskRunPreferences = {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+};
+
+/** What the signed-in user has stored for this project, and what it resolves to. */
+export interface MyTaskRunConfig {
+ preferences: TaskRunPreferences;
+ resolved: TaskRunDefaults;
+}
+
export interface TaskSessionStorageAccess {
id: string;
download_url: string | null;
@@ -2105,6 +2147,86 @@ export class PostHogAPIClient {
return data as Schemas.Team;
}
+ /**
+ * The AI run triple a task run gets when the caller pins no runtime selection —
+ * the signed-in user's per-project preference over the project default.
+ *
+ * Hand-rolled rather than routed through the generated client because
+ * `tasks/@me/config/` postdates the last schema pull.
+ */
+ async getTaskRunDefaults(projectId: number): Promise<TaskRunDefaults> {
+ return (await this.getMyTaskRunConfig(projectId)).resolved;
+ }
+
+ /** The signed-in user's stored preference for this project, plus what it resolves to. */
+ async getMyTaskRunConfig(projectId: number): Promise<MyTaskRunConfig> {
+ return await this.taskRunConfigRequest(
+ "get",
+ `/api/projects/${projectId}/tasks/@me/config/`,
+ );
+ }
+
+ /**
+ * Store the signed-in user's preference for this project. All three fields null
+ * clears it, which is how "use the project default" is expressed.
+ */
+ async updateMyTaskRunPreferences(
+ projectId: number,
+ preferences: TaskRunPreferences,
+ ): Promise<MyTaskRunConfig> {
+ return await this.taskRunConfigRequest(
+ "post",
+ `/api/projects/${projectId}/tasks/@me/config/`,
+ preferences,
+ );
+ }
+
+ /**
+ * The project-wide default. Readable by any member; only project admins may change
+ * it, which is why this client offers no writer for it — the settings page links to
+ * PostHog rather than presenting a control that would 403.
+ */
+ async getTeamTaskRunPreferences(
+ projectId: number,
+ ): Promise<TaskRunPreferences> {
+ return (
+ await this.taskRunConfigRequest(
+ "get",
+ `/api/projects/${projectId}/tasks/config/`,
+ )
+ ).preferences;
+ }
+
+ private async taskRunConfigRequest(
+ method: "get" | "post",
+ urlPath: string,
+ body?: TaskRunPreferences,
+ ): Promise<MyTaskRunConfig> {
+ const response = await this.api.fetcher.fetch({
+ method,
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ ...(body ? { overrides: { body: JSON.stringify(body) } } : {}),
+ });
+ if (!response.ok) {
+ throw new Error(`Task run config request failed: ${response.status}`);
+ }
+ const payload = (await response.json()) as {
+ ai_run_preferences?: Partial<TaskRunPreferences> | null;
+ resolved_ai_run_defaults?: TaskRunDefaults | null;
+ };
+ return {
+ // The API stores a cleared preference as `{}`, so read each field rather than
+ // assuming the triple is present.
+ preferences: {
+ runtime_adapter: payload.ai_run_preferences?.runtime_adapter ?? null,
+ model: payload.ai_run_preferences?.model ?? null,
+ reasoning_effort: payload.ai_run_preferences?.reasoning_effort ?? null,
+ },
+ resolved: payload.resolved_ai_run_defaults ?? NO_TASK_RUN_DEFAULTS,
+ };
+ }
+
async listSignalSourceConfigs(
projectId: number,
): Promise<SignalSourceConfig[]> {
diff --git a/products/desktop/packages/core/src/task-detail/previewConfig.test.ts b/products/desktop/packages/core/src/task-detail/previewConfig.test.ts
index d60006ecd191..9124676f3905 100644
--- a/products/desktop/packages/core/src/task-detail/previewConfig.test.ts
+++ b/products/desktop/packages/core/src/task-detail/previewConfig.test.ts
@@ -5,7 +5,9 @@ import {
applyConfigChange,
clampEffortToAvailable,
deriveInitialConfig,
+ matchesPreferredRunSelection,
type PreviewSettingsSnapshot,
+ pickPreferredRunSelection,
} from "./previewConfig";
function toggleOption(
@@ -225,3 +227,166 @@ describe("applyConfigChange (toggle sync via context_window / fast)", () => {
expect(result.find((o) => o.id === "context_window")).toEqual(existing);
});
});
+
+describe("pickPreferredRunSelection", () => {
+ const modelOption = {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "claude-sonnet-5",
+ description: "",
+ options: [
+ { value: "claude-sonnet-5", name: "claude-sonnet-5" },
+ { value: "claude-opus-5", name: "claude-opus-5" },
+ ],
+ } as SessionConfigOption;
+
+ it.each([
+ {
+ label: "takes the stored preference when nothing is picked locally",
+ defaults: {
+ runtime_adapter: "claude",
+ model: "claude-opus-5",
+ reasoning_effort: "high",
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ expected: { model: "claude-opus-5", reasoningEffort: "high" },
+ },
+ {
+ label: "keeps an explicit local pick ahead of the preference",
+ defaults: {
+ runtime_adapter: "claude",
+ model: "claude-opus-5",
+ reasoning_effort: "high",
+ },
+ lastUsedModel: "claude-sonnet-5",
+ lastUsedReasoningEffort: null,
+ expected: null,
+ },
+ {
+ label: "keeps an explicit local effort pick ahead of the preference",
+ defaults: {
+ runtime_adapter: "claude",
+ model: "claude-opus-5",
+ reasoning_effort: "high",
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: "medium",
+ expected: null,
+ },
+ {
+ label: "ignores a preference stored for a different harness",
+ defaults: {
+ runtime_adapter: "codex",
+ model: "gpt-5.5",
+ reasoning_effort: "medium",
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ expected: null,
+ },
+ {
+ label: "ignores a model this adapter no longer offers",
+ defaults: {
+ runtime_adapter: "claude",
+ model: "claude-opus-4-8",
+ reasoning_effort: "high",
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ expected: null,
+ },
+ {
+ label: "drops an effort-less preference to the model's own default",
+ defaults: {
+ runtime_adapter: "claude",
+ model: "claude-opus-5",
+ reasoning_effort: null,
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ expected: { model: "claude-opus-5", reasoningEffort: null },
+ },
+ {
+ label: "returns nothing when no preference is stored",
+ defaults: {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ },
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ expected: null,
+ },
+ ])(
+ "$label",
+ ({ defaults, lastUsedModel, lastUsedReasoningEffort, expected }) => {
+ expect(
+ pickPreferredRunSelection(
+ defaults,
+ "claude",
+ modelOption,
+ lastUsedModel,
+ lastUsedReasoningEffort,
+ ),
+ ).toEqual(expected);
+ },
+ );
+});
+
+describe("matchesPreferredRunSelection", () => {
+ const preferred = { model: "claude-opus-5", reasoningEffort: "high" };
+
+ it.each([
+ {
+ label: "no applicable preference never reads as the default",
+ pref: null,
+ current: { model: "gpt-5.6-sol", reasoningEffort: "medium" },
+ effortPicked: false,
+ expected: false,
+ },
+ {
+ label: "a selection sitting exactly on the preference is the default",
+ pref: preferred,
+ current: { model: "claude-opus-5", reasoningEffort: "high" },
+ effortPicked: true,
+ expected: true,
+ },
+ {
+ label: "a different model deviates",
+ pref: preferred,
+ current: { model: "claude-sonnet-5", reasoningEffort: "high" },
+ effortPicked: false,
+ expected: false,
+ },
+ {
+ label: "a different effort deviates",
+ pref: preferred,
+ current: { model: "claude-opus-5", reasoningEffort: "max" },
+ effortPicked: true,
+ expected: false,
+ },
+ {
+ label:
+ "an effort-less preference matches on model while the effort is inherited",
+ pref: { model: "claude-opus-5", reasoningEffort: null },
+ current: { model: "claude-opus-5", reasoningEffort: "medium" },
+ effortPicked: false,
+ expected: true,
+ },
+ {
+ label:
+ "an explicit effort pick against an effort-less preference deviates",
+ pref: { model: "claude-opus-5", reasoningEffort: null },
+ current: { model: "claude-opus-5", reasoningEffort: "max" },
+ effortPicked: true,
+ expected: false,
+ },
+ ])("$label", ({ pref, current, effortPicked, expected }) => {
+ expect(matchesPreferredRunSelection(pref, current, effortPicked)).toBe(
+ expected,
+ );
+ });
+});
diff --git a/products/desktop/packages/core/src/task-detail/previewConfig.ts b/products/desktop/packages/core/src/task-detail/previewConfig.ts
index 0962c2b97dda..10e129fe9768 100644
--- a/products/desktop/packages/core/src/task-detail/previewConfig.ts
+++ b/products/desktop/packages/core/src/task-detail/previewConfig.ts
@@ -1,4 +1,5 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import type { TaskRunDefaults } from "@posthog/api-client/posthog-client";
import { flattenConfigValues } from "@posthog/core/task-detail/configOptions";
import type { Adapter } from "@posthog/shared";
import { EFFORT_LEVELS } from "@posthog/shared/domain-types";
@@ -131,6 +132,90 @@ export function deriveInitialConfig(
});
}
+/** The subset of the tasks backend's resolved AI run defaults the composer acts on. */
+export type PreferredRunDefaults = Pick<
+ TaskRunDefaults,
+ "runtime_adapter" | "model" | "reasoning_effort"
+>;
+
+export interface PreferredRunSelection {
+ model: string;
+ reasoningEffort: string | null;
+}
+
+/**
+ * The model and effort the composer should open on, taken from the project or
+ * user preference stored server-side. Returns null when the preference doesn't
+ * apply, leaving the caller on its built-in fallback:
+ *
+ * - `lastUsedModel` or `lastUsedReasoningEffort` is set — an explicit pick on
+ * this device outranks a preference, which must never silently move a model
+ * or effort someone chose.
+ * - no default is stored.
+ * - the preference names a different harness, so its model is meaningless here.
+ * - this adapter no longer offers the model (a de-listed id would fail the run
+ * at the gateway rather than launching on something usable).
+ */
+export function pickPreferredRunSelection(
+ defaults: PreferredRunDefaults | null | undefined,
+ adapter: Adapter,
+ modelOption: SessionConfigOption | undefined,
+ lastUsedModel: string | null | undefined,
+ lastUsedReasoningEffort: string | null | undefined,
+): PreferredRunSelection | null {
+ if (lastUsedModel || lastUsedReasoningEffort) return null;
+ const model = defaults?.model;
+ if (!model) return null;
+ if (defaults?.runtime_adapter && defaults.runtime_adapter !== adapter) {
+ return null;
+ }
+ if (
+ modelOption?.type !== "select" ||
+ !flattenConfigValues(modelOption).includes(model)
+ ) {
+ return null;
+ }
+ return { model, reasoningEffort: defaults?.reasoning_effort || null };
+}
+
+/**
+ * The harness the configured default (user's, else the team's) runs on, when
+ * both a model and a known adapter are stored. The composer's harness is a
+ * separate local setting, so a caller adopting the default must move it too —
+ * a Claude default is unreachable from a composer left on Codex.
+ */
+export function preferredRunAdapter(
+ defaults: PreferredRunDefaults | null | undefined,
+): Adapter | null {
+ if (!defaults?.model) return null;
+ return defaults.runtime_adapter === "claude" ||
+ defaults.runtime_adapter === "codex"
+ ? defaults.runtime_adapter
+ : null;
+}
+
+/**
+ * Whether the composer's current selection sits exactly on the configured
+ * project/user default (as resolved by pickPreferredRunSelection) — the marker
+ * condition for "Default ·" and for greying out the reset. False whenever no
+ * preference applies to this surface: a fallback selection is not the default,
+ * it just is what's left. An explicit effort pick against an effort-less
+ * preference is a deviation, since a reset would put the effort back on the
+ * model's own default.
+ */
+export function matchesPreferredRunSelection(
+ preferred: PreferredRunSelection | null,
+ current: { model: string | undefined; reasoningEffort: string | undefined },
+ hasExplicitEffortPick: boolean,
+): boolean {
+ if (!preferred) return false;
+ if (current.model !== preferred.model) return false;
+ if (preferred.reasoningEffort) {
+ return current.reasoningEffort === preferred.reasoningEffort;
+ }
+ return !hasExplicitEffortPick;
+}
+
export interface ApplyConfigChangeArgs {
adapter: Adapter;
configId: string;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
index 476b3b81dd12..be491545c59f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
@@ -694,6 +694,103 @@ describe("ReasoningLevelSelector", () => {
expect(onChange).toHaveBeenCalledWith("medium");
});
+ it("resets through onNotchSelect atomically when the caller wants the pair", async () => {
+ const onChange = vi.fn();
+ const onModelChange = vi.fn();
+ const onNotchSelect = vi.fn();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption({ currentValue: "max" })}
+ modelOption={claudeModelOption("claude-fable-5")}
+ adapter="claude"
+ onChange={onChange}
+ onModelChange={onModelChange}
+ onNotchSelect={onNotchSelect}
+ />
+ </Theme>,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /Model and reasoning/ }),
+ );
+ await user.click(await screen.findByRole("button", { name: "Advanced" }));
+ await user.click(await screen.findByText("Reset to default"));
+
+ await pollUntil(() => onNotchSelect.mock.calls.length > 0);
+ // The pair lands in one call, never the split changeModel/onChange that
+ // would let the effort persist against the previously-shown model.
+ expect(onNotchSelect).toHaveBeenCalledWith({
+ model: "claude-opus-5",
+ effort: "medium",
+ });
+ expect(onModelChange).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("hands reset to onResetToDefault instead of moving to the notch", async () => {
+ const onChange = vi.fn();
+ const onModelChange = vi.fn();
+ const onResetToDefault = vi.fn();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption({ currentValue: "max" })}
+ modelOption={claudeModelOption("claude-fable-5")}
+ adapter="claude"
+ onChange={onChange}
+ onModelChange={onModelChange}
+ onResetToDefault={onResetToDefault}
+ />
+ </Theme>,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /Model and reasoning/ }),
+ );
+ await user.click(await screen.findByRole("button", { name: "Advanced" }));
+ await user.click(await screen.findByText("Reset to default"));
+
+ await pollUntil(() => onResetToDefault.mock.calls.length > 0);
+ expect(onModelChange).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ "shows a disabled reset on the slider face while on the default",
+ fastOption("off"),
+ "true",
+ ],
+ ["keeps reset live while fast mode deviates", fastOption("on"), "false"],
+ ])("%s", async (_label, fast, ariaDisabled) => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption({ currentValue: "max" })}
+ modelOption={claudeModelOption("claude-fable-5")}
+ adapter="claude"
+ fastModeOption={fast}
+ resetToDefaultDisabled
+ onResetToDefault={vi.fn()}
+ onConfigOptionChange={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ // No Advanced click: the reset row sits under the slider face too.
+ await user.click(
+ screen.getByRole("button", { name: /Model and reasoning/ }),
+ );
+ const item = (await screen.findByText("Reset to default")).closest(
+ "[role=menuitem]",
+ );
+ expect(item?.getAttribute("aria-disabled") ?? "false").toBe(ariaDisabled);
+ });
+
it.each([
["undefined option", undefined],
["non-select type", thoughtOption({ type: "boolean" })],
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
index 97c22688e966..61a9c7c39da3 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
@@ -63,6 +63,14 @@ interface ReasoningLevelSelectorProps {
fastModeOption?: SessionConfigOption;
onChange?: (value: string) => void;
onModelChange?: (value: string) => void;
+ /**
+ * A ladder notch carries a model and an effort together. When one drag moves
+ * both, the split onModelChange/onChange callbacks fire back to back with no
+ * render between them, so a caller that reads the model from render props in
+ * its effort handler sees the old value. Callers that persist the pair as a
+ * single value pass this to receive the notch atomically instead.
+ */
+ onNotchSelect?: (selection: { model: string; effort: string }) => void;
onAdapterChange?: (adapter: AgentAdapter) => void;
onHarnessChange?: (harness: AgentHarness) => void;
/**
@@ -80,6 +88,35 @@ interface ReasoningLevelSelectorProps {
showBillingMenu?: boolean;
/** Workspace mode of the task being composed; cloud disables plan billing. */
workspaceMode?: WorkspaceModeForAccess;
+ /**
+ * The selection shown is inherited rather than picked here — the trigger prefixes it
+ * with "Default ·" so an inherited value can't be mistaken for one you chose. Matches
+ * the web composer's marker.
+ */
+ isDefaultSelection?: boolean;
+ /**
+ * Clears the explicit pick so the configured project/user default applies again.
+ * When provided, the "Reset to default" row calls this instead of the built-in
+ * reset to the ladder's balanced notch. Matches the web composer's single
+ * reset row.
+ */
+ onResetToDefault?: () => void;
+ /**
+ * Resetting via onResetToDefault would change nothing, so the row reads
+ * disabled. Kept separate from isDefaultSelection, which only drives the
+ * trigger's "Default ·" marker — the two diverge when no default applies.
+ */
+ resetToDefaultDisabled?: boolean;
+ /**
+ * Position and size the popup against this element instead of the trigger.
+ *
+ * The popup takes both its placement and its width from its anchor, and the trigger
+ * resizes as the label under the cursor changes — so dragging the slider walks the
+ * popup around. Callers whose layout lets the trigger move (a right-aligned settings
+ * row, say) pass a fixed-size element to hold it still. Composers, where the trigger
+ * is left-anchored, need nothing.
+ */
+ anchor?: React.RefObject<HTMLElement | null>;
}
function toDropdownOptions(
@@ -107,6 +144,7 @@ export function ReasoningLevelSelector({
fastModeOption,
onChange,
onModelChange,
+ onNotchSelect,
onAdapterChange,
onHarnessChange,
onHarnessModelChange,
@@ -119,6 +157,10 @@ export function ReasoningLevelSelector({
modelAccess,
showBillingMenu,
workspaceMode,
+ isDefaultSelection,
+ onResetToDefault,
+ resetToDefaultDisabled,
+ anchor,
}: ReasoningLevelSelectorProps) {
const [internalMenuOpen, setInternalMenuOpen] = useState(false);
const open = menuOpen ?? internalMenuOpen;
@@ -195,6 +237,7 @@ export function ReasoningLevelSelector({
align="start"
side="top"
sideOffset={6}
+ anchor={anchor}
className="min-w-[230px]"
>
<DropdownMenuItem disabled>
@@ -285,6 +328,19 @@ export function ReasoningLevelSelector({
const handleStopSelect = (key: string) => {
if (key.includes(STOP_SEPARATOR)) {
const [model, effort] = key.split(STOP_SEPARATOR);
+ // A notch moves model and effort as one; deliver them together when the
+ // caller wants the pair, so it never has to read the model back from
+ // render props that this handler has not let re-render yet.
+ if (onNotchSelect) {
+ if (
+ model &&
+ effort &&
+ (model !== currentModel || effort !== currentEffort)
+ ) {
+ onNotchSelect({ model, effort });
+ }
+ return;
+ }
if (model && model !== currentModel) changeModel(model);
if (effort && effort !== currentEffort) onChange?.(effort);
return;
@@ -336,19 +392,33 @@ export function ReasoningLevelSelector({
setOpen(false);
};
+ // Where the built-in reset lands: the ladder's balanced middle notch, or the
+ // adapter's default effort for non-ladder pickers. Shared by the reset
+ // handler and the disabled check so the two can never disagree.
+ const middleStop = stops[Math.floor((stops.length - 1) / 2)];
+ const defaultEffortOption = effortOptions.find((option) => option.isDefault);
+
const resetToDefaults = () => {
+ // One reset for both meanings of "default": drop the pick so the configured
+ // project/user default applies where the surface knows about one, else land
+ // on the ladder's balanced notch.
+ if (onResetToDefault) {
+ selectAndClose(onResetToDefault);
+ return;
+ }
selectAndClose(() => {
if (useLadder) {
- // The middle notch is the balanced default for the whole ladder.
- const middle = stops[Math.floor((stops.length - 1) / 2)];
- const [model, effort] = middle?.key.split(STOP_SEPARATOR) ?? [];
- if (model && model !== currentModel) changeModel(model);
- if (effort && effort !== currentEffort) onChange?.(effort);
- } else {
- const defaultEffort = effortOptions.find((option) => option.isDefault);
- if (defaultEffort && defaultEffort.value !== currentEffort) {
- onChange?.(defaultEffort.value);
- }
+ // Route through the same handler a notch drag uses so the pair is
+ // delivered atomically via onNotchSelect when the caller wants it —
+ // the split changeModel/onChange path here would let the effort land
+ // on the previously-shown model, the exact hazard onNotchSelect exists
+ // to avoid.
+ if (middleStop) handleStopSelect(middleStop.key);
+ } else if (
+ defaultEffortOption &&
+ defaultEffortOption.value !== currentEffort
+ ) {
+ onChange?.(defaultEffortOption.value);
}
for (const row of toggleRows) {
if (row.defaultValue && row.defaultValue !== row.value) {
@@ -361,6 +431,34 @@ export function ReasoningLevelSelector({
});
};
+ const togglesAtDefault =
+ !fastActive &&
+ toggleRows.every(
+ (row) => !row.defaultValue || row.value === row.defaultValue,
+ );
+ // Where a configured default exists the caller says whether resetting would
+ // change anything; otherwise "default" means where the built-in reset lands.
+ const selectionAtDefault = onResetToDefault
+ ? (resetToDefaultDisabled ?? false)
+ : useLadder
+ ? currentStopKey === middleStop?.key
+ : currentEffort === defaultEffortOption?.value;
+
+ // Shown on both faces so a deviation is always one click from the default;
+ // with nothing to undo, the row is disabled rather than a silent no-op.
+ const resetRow = (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={selectionAtDefault && togglesAtDefault}
+ onClick={resetToDefaults}
+ >
+ <ArrowCounterClockwise size={12} weight="bold" />
+ Reset to default
+ </DropdownMenuItem>
+ </>
+ );
+
// Both labels can be blank while a config reloads. The trigger has no icon
// to fall back on, so it would render as an empty pill announced as
// "Reasoning: undefined".
@@ -414,7 +512,9 @@ export function ReasoningLevelSelector({
</span>
)}
{modelLabel && (
- <span className="font-medium text-foreground">{modelLabel}</span>
+ <span className="font-medium text-foreground">
+ {isDefaultSelection ? `Default · ${modelLabel}` : modelLabel}
+ </span>
)}
{effortLabel && (
<span
@@ -437,6 +537,7 @@ export function ReasoningLevelSelector({
align="start"
side="top"
sideOffset={6}
+ anchor={anchor}
className="min-w-[230px]"
>
<AnimatedHeight>
@@ -549,11 +650,7 @@ export function ReasoningLevelSelector({
</DropdownMenuSubContent>
</DropdownMenuSub>
))}
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={resetToDefaults}>
- <ArrowCounterClockwise size={12} weight="bold" />
- Reset to default
- </DropdownMenuItem>
+ {resetRow}
</motion.div>
) : (
<motion.div
@@ -573,6 +670,7 @@ export function ReasoningLevelSelector({
}}
fastToggle={fastToggle}
/>
+ {resetRow}
</motion.div>
)}
</AnimatePresence>
diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx
index 372816905610..ac4afcca7496 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx
@@ -14,6 +14,7 @@ import { QuickAskSettings } from "@posthog/ui/features/settings/sections/QuickAs
import { ShortcutsSettings } from "@posthog/ui/features/settings/sections/ShortcutsSettings";
import { SignalSourcesSettings } from "@posthog/ui/features/settings/sections/SignalSourcesSettings";
import { SlackSettings } from "@posthog/ui/features/settings/sections/SlackSettings";
+import { TaskAgentDefaultsSettings } from "@posthog/ui/features/settings/sections/TaskAgentDefaultsSettings";
import { TerminalSettings } from "@posthog/ui/features/settings/sections/TerminalSettings";
import { WorkspacesSettings } from "@posthog/ui/features/settings/sections/WorkspacesSettings";
import { WorktreesSettings } from "@posthog/ui/features/settings/sections/worktrees/WorktreesSettings";
@@ -59,6 +60,7 @@ const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {
EnvironmentsSettings,
),
agents: defineSettingsPage("Agents", AgentsSettings),
+ "task-agent-defaults": defineSettingsPage("Model", TaskAgentDefaultsSettings),
skills: defineSettingsPage(
"Skills",
SkillsView,
diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
index b0d45e98761e..d6e09a21e7ac 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
@@ -17,6 +17,7 @@ import {
Plugs,
Robot,
SlackLogo,
+ Sparkle,
Terminal,
TrafficSignal,
TreeStructure,
@@ -84,6 +85,7 @@ const SIDEBAR_GROUPS: SidebarGroup[] = [
{
label: "Code",
items: [
+ { id: "task-agent-defaults", icon: <Sparkle size={16} /> },
{ id: "workspaces", icon: <Folder size={16} /> },
{ id: "worktrees", icon: <TreeStructure size={16} /> },
{ id: "environments", icon: <Cube size={16} /> },
diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.test.tsx b/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.test.tsx
new file mode 100644
index 000000000000..97a1e02b2d4a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.test.tsx
@@ -0,0 +1,193 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const PROJECT_ID = 7;
+
+const mockClient = vi.hoisted(() => ({
+ getMyTaskRunConfig: vi.fn(),
+ getTeamTaskRunPreferences: vi.fn(),
+ updateMyTaskRunPreferences: vi.fn(),
+}));
+const settingsStore = vi.hoisted(() => ({
+ setLastUsedModel: vi.fn(),
+ setLastUsedReasoningEffort: vi.fn(),
+ setLastUsedAdapter: vi.fn(),
+}));
+const toastMock = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => mockClient,
+}));
+vi.mock("@posthog/ui/features/auth/store", () => ({
+ useAuthStateValue: (select: (state: unknown) => unknown) =>
+ select({ currentProjectId: PROJECT_ID }),
+}));
+vi.mock("@posthog/ui/features/settings/settingsStore", () => ({
+ useSettingsStore: { getState: () => settingsStore },
+}));
+vi.mock("@posthog/ui/primitives/toast", () => ({ toast: toastMock }));
+
+import { taskRunDefaultsQueryKey } from "@posthog/ui/features/task-detail/hooks/useTaskRunDefaults";
+import { useTaskAgentDefaults } from "./useTaskAgentDefaults";
+
+const TEAM_DEFAULT = {
+ runtime_adapter: "claude",
+ model: "claude-fable-5",
+ reasoning_effort: "high",
+};
+const MY_PICK = {
+ runtime_adapter: "codex",
+ model: "gpt-5.6-terra",
+ reasoning_effort: null,
+};
+
+describe("useTaskAgentDefaults", () => {
+ let queryClient: QueryClient;
+
+ function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+
+ async function mounted() {
+ const rendered = renderHook(() => useTaskAgentDefaults(), { wrapper });
+ await waitFor(() => expect(rendered.result.current.isLoading).toBe(false));
+ return rendered;
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ mockClient.getMyTaskRunConfig.mockResolvedValue({
+ preferences: {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ },
+ resolved: { ...TEAM_DEFAULT, source: "team" },
+ });
+ mockClient.getTeamTaskRunPreferences.mockResolvedValue(TEAM_DEFAULT);
+ mockClient.updateMyTaskRunPreferences.mockResolvedValue({
+ preferences: MY_PICK,
+ resolved: { ...MY_PICK, source: "user" },
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ // The composer reads its default from a separate, long-lived cache entry. Twice now a
+ // change made here left the task UI opening on the model it replaced, so this pins the
+ // link between the two rather than the write on its own.
+ it("hands the composer the new default as soon as one is saved", async () => {
+ const { result } = await mounted();
+
+ act(() => result.current.save(MY_PICK));
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ await waitFor(() =>
+ expect(
+ queryClient.getQueryData(taskRunDefaultsQueryKey(PROJECT_ID)),
+ ).toEqual({ ...MY_PICK, source: "user" }),
+ );
+ // Seeding alone would leave a mismatched key or an observer elsewhere reading the old
+ // value until the stale window expired, so the entry is also marked for refetch.
+ expect(
+ queryClient.getQueryState(taskRunDefaultsQueryKey(PROJECT_ID))
+ ?.isInvalidated,
+ ).toBe(true);
+ });
+
+ // A device pick outranks the preference when the composer seeds, so leaving it in place
+ // shadows the default on any machine that has ever chosen a model.
+ it("drops the device's last-used pick so the new default isn't shadowed", async () => {
+ const { result } = await mounted();
+
+ act(() => result.current.save(MY_PICK));
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ await waitFor(() =>
+ expect(settingsStore.setLastUsedModel).toHaveBeenCalledWith(null),
+ );
+ expect(settingsStore.setLastUsedReasoningEffort).toHaveBeenCalledWith(null);
+ });
+
+ // The composer opens on the adapter it last used and skips a default belonging to a
+ // different one, so a Claude default set from a composer left on Codex was ignored
+ // outright — the model shown never changed.
+ it("moves the harness to the one the new default runs on", async () => {
+ const claudeDefault = {
+ runtime_adapter: "claude",
+ model: "claude-opus-4-8",
+ reasoning_effort: "medium",
+ };
+ mockClient.updateMyTaskRunPreferences.mockResolvedValue({
+ preferences: claudeDefault,
+ resolved: { ...claudeDefault, source: "user" },
+ });
+ const { result } = await mounted();
+
+ act(() => result.current.save(claudeDefault));
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ await waitFor(() =>
+ expect(settingsStore.setLastUsedAdapter).toHaveBeenCalledWith("claude"),
+ );
+ });
+
+ // Picking a model and then its effort is two interactions moments apart; writing on each
+ // one is what made the settings row flicker.
+ it("coalesces a model-then-effort pick into one write", async () => {
+ const { result } = await mounted();
+
+ act(() => result.current.save(MY_PICK));
+ act(() => result.current.save({ ...MY_PICK, reasoning_effort: "medium" }));
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ await waitFor(() =>
+ expect(mockClient.updateMyTaskRunPreferences).toHaveBeenCalledTimes(1),
+ );
+ expect(mockClient.updateMyTaskRunPreferences).toHaveBeenCalledWith(
+ PROJECT_ID,
+ { ...MY_PICK, reasoning_effort: "medium" },
+ );
+ });
+
+ // A failed write used to leave the unsaved pick in the cache with no error, so the
+ // picker kept showing a default the server never stored. Roll it back and say so.
+ it("rolls back the optimistic pick and shows an error when the save fails", async () => {
+ mockClient.updateMyTaskRunPreferences.mockRejectedValue(
+ new Error("network down"),
+ );
+ const { result } = await mounted();
+
+ act(() => result.current.save(MY_PICK));
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ await waitFor(() => expect(toastMock.error).toHaveBeenCalled());
+ await waitFor(() =>
+ expect(result.current.myPreferences).toEqual({
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ }),
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.ts b/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.ts
new file mode 100644
index 000000000000..a2d64b05e8b3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/hooks/useTaskAgentDefaults.ts
@@ -0,0 +1,191 @@
+import {
+ type MyTaskRunConfig,
+ NO_TASK_RUN_DEFAULTS,
+ NO_TASK_RUN_PREFERENCES,
+ type TaskRunDefaults,
+ type TaskRunPreferences,
+} from "@posthog/api-client/posthog-client";
+import { preferredRunAdapter } from "@posthog/core/task-detail/previewConfig";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { taskRunDefaultsQueryKey } from "@posthog/ui/features/task-detail/hooks/useTaskRunDefaults";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useRef } from "react";
+
+export interface TaskAgentDefaultsResult {
+ /** The project-wide default, which only project admins can change. */
+ teamPreferences: TaskRunPreferences;
+ /** What this user has stored for the project; all-null means "inherit". */
+ myPreferences: TaskRunPreferences;
+ /** What a run without an explicit pick actually launches on. */
+ resolved: TaskRunDefaults;
+ isLoading: boolean;
+ isSaving: boolean;
+ /** Persist a personal preference; an all-null triple clears it. */
+ save: (preferences: TaskRunPreferences) => void;
+ /** Clear the personal preference so the project default applies again. */
+ reset: () => void;
+}
+
+const MY_CONFIG_KEY = "task-agent-my-config";
+const TEAM_CONFIG_KEY = "task-agent-team-config";
+
+/**
+ * Picking a model and then its effort is two interactions moments apart, and writing on
+ * each one costs two round trips and two re-renders — which is what the settings page
+ * flickers on. Long enough to coalesce a pair, short enough that nobody waits on it.
+ */
+const SAVE_DEBOUNCE_MS = 600;
+
+/**
+ * The project and personal task-agent defaults for the current project.
+ *
+ * Reads both levels because the settings page names what the project sets as well as
+ * what this person overrode it with — seeing only the resolved answer leaves "why is
+ * it this model" unanswerable. Writes are personal-only: the project default is
+ * admin-gated server-side, so offering a control for it here would just 403.
+ */
+export function useTaskAgentDefaults(): TaskAgentDefaultsResult {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const client = useOptionalAuthenticatedClient();
+ const queryClient = useQueryClient();
+ const enabled = projectId != null;
+
+ const myConfig = useAuthenticatedQuery(
+ [MY_CONFIG_KEY, projectId],
+ async (c) => await c.getMyTaskRunConfig(Number(projectId)),
+ { enabled, retry: false },
+ );
+ const teamConfig = useAuthenticatedQuery(
+ [TEAM_CONFIG_KEY, projectId],
+ async (c) => await c.getTeamTaskRunPreferences(Number(projectId)),
+ { enabled, retry: false },
+ );
+
+ // The value the personal cache held before the current change, so a failed
+ // write can put it back instead of leaving an unsaved pick on screen.
+ const rollbackSnapshot = useRef<MyTaskRunConfig | undefined>(undefined);
+
+ const mutation = useMutation({
+ mutationFn: async (preferences: TaskRunPreferences) => {
+ if (!client || projectId == null) {
+ throw new Error("Not authenticated");
+ }
+ return await client.updateMyTaskRunPreferences(
+ Number(projectId),
+ preferences,
+ );
+ },
+ // Carry the pre-change snapshot per mutation so a rollback restores the right
+ // value even if another pick starts while this write is in flight.
+ onMutate: () => ({ rollback: rollbackSnapshot.current }),
+ onSuccess: (next: MyTaskRunConfig) => {
+ // The write returns the row and its resolution, so seed both caches from it — the
+ // page and the composer show the new value without waiting on a round trip.
+ queryClient.setQueryData([MY_CONFIG_KEY, projectId], next);
+ queryClient.setQueryData(
+ taskRunDefaultsQueryKey(projectId),
+ next.resolved,
+ );
+ // Then invalidate rather than trust the seed. The composer holds this for the whole
+ // stale window, so anything the seed misses — a key that didn't match, an observer
+ // mounted elsewhere — would leave the task UI opening on the replaced model until
+ // it expired. Invalidating makes the next read go to the server regardless.
+ void queryClient.invalidateQueries({
+ queryKey: taskRunDefaultsQueryKey(projectId),
+ });
+ // A stored last-used pick outranks the preference in the composer, so without this
+ // the new default would be shadowed on any device that has ever picked a model —
+ // the setting would look ignored. Choosing a default here is the more deliberate
+ // act of the two, so it clears the stale pick. Same reset the v1 migration does.
+ const settings = useSettingsStore.getState();
+ settings.setLastUsedModel(null);
+ settings.setLastUsedReasoningEffort(null);
+ // The harness has to move with it. The composer opens on whichever adapter it last
+ // used and ignores a default belonging to a different one, so a Claude default set
+ // from a composer left on Codex would be skipped outright — clearing the model
+ // alone doesn't help, because the two never meet.
+ const adapter = preferredRunAdapter(next.resolved);
+ if (adapter) {
+ settings.setLastUsedAdapter(adapter);
+ }
+ },
+ onError: (error, _preferences, context) => {
+ // The optimistic write in `save` already showed the pick, but the server
+ // never took it. Put the previous value back, refetch the truth, and say
+ // so — otherwise the picker keeps showing a default that was never saved.
+ queryClient.setQueryData([MY_CONFIG_KEY, projectId], context?.rollback);
+ void queryClient.invalidateQueries({
+ queryKey: [MY_CONFIG_KEY, projectId],
+ });
+ toast.error("Couldn't save your task agent default", {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ },
+ });
+
+ const pending = useRef<TaskRunPreferences | null>(null);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const mutate = mutation.mutate;
+
+ const flush = useCallback(() => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ const next = pending.current;
+ pending.current = null;
+ if (next) mutate(next);
+ }, [mutate]);
+
+ const save = useCallback(
+ (preferences: TaskRunPreferences) => {
+ // Snapshot once at the start of a debounced burst, so a failed write rolls
+ // the whole burst back rather than to a mid-burst optimistic value.
+ if (pending.current === null) {
+ rollbackSnapshot.current = queryClient.getQueryData<MyTaskRunConfig>([
+ MY_CONFIG_KEY,
+ projectId,
+ ]);
+ }
+ pending.current = preferences;
+ // Show the pick straight away; the debounced write only decides when it lands.
+ queryClient.setQueryData(
+ [MY_CONFIG_KEY, projectId],
+ (prev: MyTaskRunConfig | undefined) =>
+ prev ? { ...prev, preferences } : prev,
+ );
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(flush, SAVE_DEBOUNCE_MS);
+ },
+ [flush, queryClient, projectId],
+ );
+
+ const reset = useCallback(() => {
+ // Reset writes no optimistic value, so its snapshot is the current one — a
+ // failed reset then restores it unchanged rather than a stale save's value.
+ rollbackSnapshot.current = queryClient.getQueryData<MyTaskRunConfig>([
+ MY_CONFIG_KEY,
+ projectId,
+ ]);
+ pending.current = NO_TASK_RUN_PREFERENCES;
+ flush();
+ }, [flush, queryClient, projectId]);
+
+ // A pick made and then navigated away from within the debounce window still has to
+ // land — the alternative is silently dropping the change the user just made.
+ useEffect(() => flush, [flush]);
+
+ return {
+ teamPreferences: teamConfig.data ?? NO_TASK_RUN_PREFERENCES,
+ myPreferences: myConfig.data?.preferences ?? NO_TASK_RUN_PREFERENCES,
+ resolved: myConfig.data?.resolved ?? NO_TASK_RUN_DEFAULTS,
+ isLoading: enabled && (myConfig.isLoading || teamConfig.isLoading),
+ isSaving: mutation.isPending,
+ save,
+ reset,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.test.tsx
new file mode 100644
index 000000000000..bebf827cd328
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.test.tsx
@@ -0,0 +1,250 @@
+import { Theme } from "@radix-ui/themes";
+import {
+ configure,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Menu open/close and submenu reveals ride animations that starve under
+// parallel suite load; the default 1s async timeout flakes.
+configure({ asyncUtilTimeout: 5000 });
+
+const saveMock = vi.hoisted(() => vi.fn());
+const previewState = vi.hoisted(() => ({
+ lastAdapter: null as string | null,
+ setConfigOption: vi.fn(),
+}));
+// The personal preference the mocked hook reports; a test flips it to simulate
+// a reset (which clears it to all-null) and re-renders.
+const defaultsState = vi.hoisted(() => ({
+ myPreferences: {
+ runtime_adapter: null as string | null,
+ model: null as string | null,
+ reasoning_effort: null as string | null,
+ },
+}));
+
+vi.mock("@posthog/ui/features/auth/store", () => ({
+ useAuthStateValue: (
+ selector: (state: {
+ cloudRegion: string;
+ currentProjectId: number;
+ status: string;
+ }) => unknown,
+ ) =>
+ selector({
+ cloudRegion: "us",
+ currentProjectId: 1,
+ status: "authenticated",
+ }),
+}));
+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
+ useFeatureFlag: () => true,
+}));
+vi.mock("@posthog/ui/features/settings/hooks/useTaskAgentDefaults", () => ({
+ useTaskAgentDefaults: () => ({
+ teamPreferences: {
+ runtime_adapter: "claude",
+ model: "claude-fable-5",
+ reasoning_effort: "high",
+ },
+ myPreferences: defaultsState.myPreferences,
+ resolved: {
+ runtime_adapter: "claude",
+ model: "claude-fable-5",
+ reasoning_effort: "high",
+ source: "team",
+ },
+ isLoading: false,
+ isSaving: false,
+ save: saveMock,
+ reset: vi.fn(),
+ }),
+}));
+vi.mock("@posthog/ui/features/task-detail/hooks/usePreviewConfig", () => ({
+ usePreviewConfig: (adapter: string) => {
+ previewState.lastAdapter = adapter;
+ const models =
+ adapter === "codex"
+ ? [
+ { name: "GPT-5.6 Sol", value: "gpt-5.6-sol" },
+ { name: "GPT-5.6 Terra", value: "gpt-5.6-terra" },
+ ]
+ : [
+ { name: "Claude Opus 5", value: "claude-opus-5" },
+ { name: "Claude Fable 5", value: "claude-fable-5" },
+ ];
+ return {
+ modelOption: {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: models[0].value,
+ options: models,
+ },
+ thoughtOption: {
+ id: "effort",
+ name: "Effort",
+ type: "select",
+ category: "thought_level",
+ currentValue: "high",
+ options: [
+ { name: "High", value: "high" },
+ { name: "Max", value: "max" },
+ ],
+ },
+ isLoading: false,
+ setConfigOption: previewState.setConfigOption,
+ };
+ },
+}));
+
+import { TaskAgentDefaultsSettings } from "./TaskAgentDefaultsSettings";
+
+// The submenus open on Base UI timers that RTL's act-wrapped waitFor never
+// flushes in jsdom, so poll with plain sleeps instead of findByRole.
+async function openSub(user: ReturnType<typeof userEvent.setup>, name: RegExp) {
+ const trigger = await screen.findByRole("menuitem", { name });
+ await user.click(trigger);
+ for (let attempt = 0; attempt < 100; attempt++) {
+ if (screen.queryAllByRole("menuitemradio").length > 0) return;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error("submenu did not open");
+}
+
+describe("TaskAgentDefaultsSettings", () => {
+ beforeEach(() => {
+ saveMock.mockClear();
+ previewState.setConfigOption.mockClear();
+ previewState.lastAdapter = null;
+ defaultsState.myPreferences = {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ };
+ });
+
+ // Switching harness used to save {adapter, null, null}, which wiped a stored
+ // personal default and flipped the derived harness straight back — a dead
+ // control. The switch must persist nothing until a model pick completes the
+ // triple, which then carries the new harness.
+ it("holds a harness switch unsaved until a model pick completes the triple", async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <TaskAgentDefaultsSettings />
+ </Theme>,
+ );
+
+ // Nothing stored: the pill shows the inherited default behind the marker.
+ const trigger = screen.getByRole("button", {
+ name: /Model and reasoning/,
+ });
+ expect(trigger).toHaveTextContent("Default ·");
+
+ await user.click(trigger);
+ await openSub(user, /^Harness/);
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Codex" }));
+
+ // The switch itself: control moves, nothing is saved, and a mid-switch
+ // browse no longer claims to be the inherited default.
+ expect(saveMock).not.toHaveBeenCalled();
+ expect(previewState.lastAdapter).toBe("codex");
+ expect(trigger).not.toHaveTextContent("Default ·");
+
+ await openSub(user, /^Model/);
+ const model = await screen.findByRole("menuitemradio", {
+ name: /GPT-5.6 Terra/,
+ });
+ fireEvent.click(model);
+
+ expect(saveMock).toHaveBeenCalledTimes(1);
+ expect(saveMock).toHaveBeenCalledWith({
+ runtime_adapter: "codex",
+ model: "gpt-5.6-terra",
+ reasoning_effort: null,
+ });
+ });
+
+ // Mid-switch the stored triple still names the previous harness's model. A
+ // reasoning-only pick must pair the effort with the new harness's own seated
+ // model, or it saves a preference (Codex adapter + Claude model) no surface
+ // can apply.
+ it("pairs a reasoning-only pick with the new harness's model after a switch", async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <TaskAgentDefaultsSettings />
+ </Theme>,
+ );
+
+ const trigger = screen.getByRole("button", {
+ name: /Model and reasoning/,
+ });
+
+ await user.click(trigger);
+ await openSub(user, /^Harness/);
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Codex" }));
+ expect(previewState.lastAdapter).toBe("codex");
+
+ await openSub(user, /^Reasoning/);
+ const level = await screen.findByRole("menuitemradio", { name: "Max" });
+ fireEvent.click(level);
+
+ expect(saveMock).toHaveBeenCalledTimes(1);
+ expect(saveMock).toHaveBeenCalledWith({
+ runtime_adapter: "codex",
+ model: "gpt-5.6-sol",
+ reasoning_effort: "max",
+ });
+ });
+
+ // Switching harness then resetting an existing default used to leave the
+ // picker stuck on the previewed harness: reset clears the personal model, so
+ // the "stored adapter matches pending" clear never fires. The control must
+ // snap back to the inherited project harness instead.
+ it("drops a pending harness browse when the default is reset", async () => {
+ defaultsState.myPreferences = {
+ runtime_adapter: "claude",
+ model: "claude-fable-5",
+ reasoning_effort: "high",
+ };
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { rerender } = render(
+ <Theme>
+ <TaskAgentDefaultsSettings />
+ </Theme>,
+ );
+
+ const trigger = screen.getByRole("button", {
+ name: /Model and reasoning/,
+ });
+ await user.click(trigger);
+ await openSub(user, /^Harness/);
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Codex" }));
+ expect(previewState.lastAdapter).toBe("codex");
+
+ // Reset clears the personal default: myPreferences flips to all-null.
+ defaultsState.myPreferences = {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ };
+ rerender(
+ <Theme>
+ <TaskAgentDefaultsSettings />
+ </Theme>,
+ );
+
+ // The pending browse is dropped, so the picker returns to the inherited
+ // (Claude) harness rather than staying on Codex.
+ await waitFor(() => expect(previewState.lastAdapter).toBe("claude"));
+ expect(trigger).toHaveTextContent("Default ·");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.tsx
new file mode 100644
index 000000000000..a3bbfc8ee323
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/TaskAgentDefaultsSettings.tsx
@@ -0,0 +1,303 @@
+import { ArrowSquareOut } from "@phosphor-icons/react";
+import type { TaskRunPreferences } from "@posthog/api-client/posthog-client";
+import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";
+import { Button } from "@posthog/quill";
+import { type Adapter, formatModelId } from "@posthog/shared";
+import { EFFORT_LEVEL_LABELS } from "@posthog/shared/domain-types";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { ReasoningLevelSelector } from "@posthog/ui/features/sessions/components/ReasoningLevelSelector";
+import {
+ SettingsCard,
+ SettingsCardRow,
+} from "@posthog/ui/features/settings/components/SettingsCard";
+import { useTaskAgentDefaults } from "@posthog/ui/features/settings/hooks/useTaskAgentDefaults";
+import { usePreviewConfig } from "@posthog/ui/features/task-detail/hooks/usePreviewConfig";
+import { Text } from "@radix-ui/themes";
+import { useEffect, useRef, useState } from "react";
+
+/** The tasks settings page in PostHog, where the project default is set. */
+const POSTHOG_SETTINGS_PATH = "/settings/environment-task-agents";
+
+const INHERIT_PROJECT_DEFAULT = "Use project default";
+
+function effortLabel(effort: string): string {
+ return (
+ EFFORT_LEVEL_LABELS[effort as keyof typeof EFFORT_LEVEL_LABELS] ?? effort
+ );
+}
+
+/** A stored triple as prose, or a note that the level is unset. */
+function describe(preferences: TaskRunPreferences, emptyLabel: string): string {
+ if (!preferences.model) return emptyLabel;
+ const model = formatModelId(preferences.model);
+ return preferences.reasoning_effort
+ ? `${model} · ${effortLabel(preferences.reasoning_effort)}`
+ : model;
+}
+
+/**
+ * The composer's own picker, wired to the stored preference instead of a run's config.
+ *
+ * With nothing stored it shows the inherited project default behind a "Default ·"
+ * prefix, so what your runs will use is visible without reading as a pick you made.
+ */
+function MyDefaultPicker({
+ preferences,
+ inherited,
+ disabled,
+ onSave,
+}: {
+ preferences: TaskRunPreferences;
+ inherited: TaskRunPreferences;
+ disabled: boolean;
+ onSave: (next: TaskRunPreferences) => void;
+}) {
+ const isInherited = !preferences.model;
+ const shown = isInherited ? inherited : preferences;
+ const storedAdapter: Adapter =
+ shown.runtime_adapter === "codex" ? "codex" : "claude";
+ // A harness choice lives here until a model pick on it completes the triple.
+ // Saving an all-null pair on the switch would both clear an existing personal
+ // default and flip `shown` back to the inherited row, snapping the control
+ // to the old harness under the cursor.
+ const [pendingAdapter, setPendingAdapter] = useState<Adapter | null>(null);
+ const adapter = pendingAdapter ?? storedAdapter;
+ useEffect(() => {
+ if (pendingAdapter && storedAdapter === pendingAdapter) {
+ setPendingAdapter(null);
+ }
+ }, [pendingAdapter, storedAdapter]);
+ // Resetting the personal default (from the row below) flips the stored model
+ // from a value to null. That is not a harness switch, so the effect above
+ // won't match its adapter — drop any pending browse here too, or the control
+ // stays stuck on the previewed harness with no in-page way back, contradicting
+ // the summary line and losing the "Default ·" marker.
+ const prevPersonalModel = useRef(preferences.model);
+ useEffect(() => {
+ if (prevPersonalModel.current && !preferences.model) {
+ setPendingAdapter(null);
+ }
+ prevPersonalModel.current = preferences.model;
+ }, [preferences.model]);
+ const { modelOption, thoughtOption, isLoading, setConfigOption } =
+ usePreviewConfig(adapter);
+
+ const anchorRef = useRef<HTMLDivElement | null>(null);
+
+ // Reflect the stored triple into the fetched options, so the pill names the preference
+ // rather than whatever the last preview session happened to select.
+ const seeded = useRef<string | null>(null);
+ const seedKey = `${adapter}:${shown.model ?? ""}:${shown.reasoning_effort ?? ""}`;
+ useEffect(() => {
+ if (isLoading || seeded.current === seedKey) return;
+ // The stored triple belongs to another harness while a switch is pending;
+ // seeding its model into this harness's options would show a phantom pick.
+ if (pendingAdapter) return;
+ seeded.current = seedKey;
+ if (shown.model && modelOption) {
+ setConfigOption(modelOption.id, shown.model);
+ }
+ if (shown.reasoning_effort && thoughtOption) {
+ setConfigOption(thoughtOption.id, shown.reasoning_effort);
+ }
+ }, [
+ isLoading,
+ seedKey,
+ pendingAdapter,
+ modelOption,
+ thoughtOption,
+ setConfigOption,
+ shown.model,
+ shown.reasoning_effort,
+ ]);
+
+ const handleModelChange = (model: string) => {
+ if (modelOption) setConfigOption(modelOption.id, model);
+ // The effort belongs to the model it was chosen against, so a model switch drops it
+ // rather than storing one the new model may not support.
+ onSave({ runtime_adapter: adapter, model, reasoning_effort: null });
+ };
+
+ const handleEffortChange = (effort: string) => {
+ if (thoughtOption) setConfigOption(thoughtOption.id, effort);
+ // An effort alone is not a preference: it needs the model it was judged
+ // against. Read that from the harness's seated option, not the stored
+ // triple — mid-switch shown.model still names the previous harness's model,
+ // and pairing it with the new adapter saves a preference no surface applies.
+ const model =
+ modelOption?.type === "select" ? modelOption.currentValue : undefined;
+ if (!model) return;
+ onSave({
+ runtime_adapter: adapter,
+ model,
+ reasoning_effort: effort || null,
+ });
+ };
+
+ return (
+ // The popup takes its position and width from its anchor. The trigger is a poor one
+ // here: this row right-aligns its control, so the button's left edge slides as the
+ // label under the cursor changes, and dragging the slider walks the popup with it.
+ // This wrapper is a fixed size in a fixed place, so the popup holds still.
+ <div ref={anchorRef} className="flex w-[280px] justify-end">
+ <ReasoningLevelSelector
+ modelOption={modelOption}
+ thoughtOption={thoughtOption}
+ adapter={adapter}
+ anchor={anchorRef}
+ // Mid-switch the pill shows the new harness's own default, which is a
+ // browse, not the inherited project default — no "Default ·" marker.
+ isDefaultSelection={isInherited && !pendingAdapter}
+ onModelChange={handleModelChange}
+ onChange={handleEffortChange}
+ // A slider notch changes model and effort at once. Save them as one
+ // preference so the effort can't land on the previously-shown model.
+ onNotchSelect={({ model, effort }) => {
+ if (modelOption) setConfigOption(modelOption.id, model);
+ if (thoughtOption) setConfigOption(thoughtOption.id, effort);
+ onSave({
+ runtime_adapter: adapter,
+ model,
+ reasoning_effort: effort || null,
+ });
+ }}
+ onAdapterChange={(next) => {
+ // Nothing is saved yet: the next model pick on this harness supplies
+ // the pair and carries the adapter with it.
+ seeded.current = null;
+ setPendingAdapter(next);
+ }}
+ onConfigOptionChange={(configId, value) => {
+ if (modelOption && configId === modelOption.id) {
+ handleModelChange(value);
+ } else if (thoughtOption && configId === thoughtOption.id) {
+ handleEffortChange(value);
+ }
+ }}
+ disabled={disabled}
+ isLoading={isLoading}
+ />
+ </div>
+ );
+}
+
+/**
+ * What agent runs in this project launch with when nobody picks a model.
+ *
+ * Both levels are shown because only seeing the resolved answer leaves "why this
+ * model" unanswerable. The project default is read-only here: it is admin-gated in
+ * PostHog, so this links out rather than offering a control that would be refused.
+ */
+export function TaskAgentDefaultsSettings() {
+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
+ const currentProjectId = useAuthStateValue((state) => state.currentProjectId);
+ const isAuthenticated = useAuthStateValue(
+ (state) => state.status === "authenticated",
+ );
+ const {
+ teamPreferences,
+ myPreferences,
+ resolved,
+ isLoading,
+ isSaving,
+ save,
+ reset,
+ } = useTaskAgentDefaults();
+
+ // The section is per-environment, so the link must name the desktop app's own
+ // project — otherwise the web app fills in the browser's active project, which
+ // can be a different one, and Manage edits the wrong project's default.
+ const settingsUrl = currentProjectId
+ ? buildPostHogUrl(
+ `/project/${currentProjectId}${POSTHOG_SETTINGS_PATH}`,
+ cloudRegion,
+ )
+ : null;
+
+ if (!isAuthenticated) {
+ return (
+ <Text className="text-(--gray-11) text-sm">
+ Sign in to PostHog to see the defaults this project runs with.
+ </Text>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-7">
+ <SettingsCard>
+ <SettingsCardRow
+ label="Project default"
+ description="What everyone on this project inherits. Only project admins can change it."
+ >
+ <div className="flex items-center gap-2">
+ <Text className="text-(--gray-11) text-sm">
+ {isLoading
+ ? "Loading…"
+ : describe(teamPreferences, "No project default")}
+ </Text>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!settingsUrl}
+ onClick={() => {
+ if (settingsUrl) window.open(settingsUrl, "_blank");
+ }}
+ >
+ Manage
+ <ArrowSquareOut size={12} />
+ </Button>
+ </div>
+ </SettingsCardRow>
+
+ <SettingsCardRow
+ label="My default"
+ description="Overrides the project default for your own runs, everywhere in PostHog — not just this app."
+ >
+ {/* Deliberately not disabled while saving: the write is debounced and the pick
+ already shows, so toggling the control would just make it blink. */}
+ <MyDefaultPicker
+ preferences={myPreferences}
+ inherited={teamPreferences}
+ disabled={isLoading}
+ onSave={save}
+ />
+ </SettingsCardRow>
+
+ <SettingsCardRow
+ label="Reset my default"
+ // Deliberately one fixed sentence: swapping it for a state-dependent one
+ // resizes the row on every save, which reads as a flicker.
+ description="Clears your own default so the project default applies again."
+ >
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!myPreferences.model || isSaving}
+ onClick={reset}
+ >
+ {INHERIT_PROJECT_DEFAULT}
+ </Button>
+ </SettingsCardRow>
+ </SettingsCard>
+
+ {/* Height is reserved rather than left to the text: this line's length changes on
+ every save, and letting it reflow between one and two lines shifts the card
+ above it each time. */}
+ <div className="min-h-10">
+ <Text className="text-(--gray-11) text-sm">
+ {isLoading
+ ? ""
+ : resolved.model
+ ? `Runs you start without picking a model use ${describe(resolved, "")}, from ${
+ resolved.source === "user"
+ ? "your default"
+ : "the project default"
+ }.`
+ : "No default is set — runs use each surface's built-in model."}
+ </Text>
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
index 9304df5bdbb3..5d294750203c 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
@@ -208,6 +208,27 @@ const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [
label: "Agents",
keywords: ["responders", "scouts", "signal sources", "setup agent"],
},
+ {
+ category: "task-agent-defaults",
+ label: "Project default",
+ keywords: [
+ "default model",
+ "team default",
+ "reasoning effort",
+ "claude",
+ "codex",
+ ],
+ },
+ {
+ category: "task-agent-defaults",
+ label: "My default",
+ keywords: [
+ "default model",
+ "my model",
+ "personal default",
+ "reasoning effort",
+ ],
+ },
{
category: "signals",
label: "Self-driving",
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index cf738b13b72b..9bf05ee08226 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -172,9 +172,9 @@ export interface SettingsStore {
setLastUsedWorkspaceMode: (mode: WorkspaceMode) => void;
setLastUsedAgentRuntime: (runtime: AgentRuntime) => void;
setLastUsedAdapter: (adapter: AgentAdapter) => void;
- setLastUsedModel: (model: string) => void;
+ setLastUsedModel: (model: string | null) => void;
setLastUsedPiModel: (model: string) => void;
- setLastUsedReasoningEffort: (effort: string) => void;
+ setLastUsedReasoningEffort: (effort: string | null) => void;
setLastUsedContextWindow: (value: "200k" | "1m") => void;
setLastUsedFastMode: (enabled: boolean) => void;
setLastUsedCloudRepository: (repo: string | null) => void;
diff --git a/products/desktop/packages/ui/src/features/settings/types.ts b/products/desktop/packages/ui/src/features/settings/types.ts
index 7c2006c09f8b..76ec6e51001d 100644
--- a/products/desktop/packages/ui/src/features/settings/types.ts
+++ b/products/desktop/packages/ui/src/features/settings/types.ts
@@ -8,6 +8,7 @@ export type SettingsCategory =
| "environments"
| "cloud-environments"
| "agents"
+ | "task-agent-defaults"
| "skills"
| "mcp-servers"
| "personalization"
@@ -31,6 +32,7 @@ const SETTINGS_CATEGORIES: readonly SettingsCategory[] = [
"environments",
"cloud-environments",
"agents",
+ "task-agent-defaults",
"skills",
"mcp-servers",
"personalization",
@@ -62,6 +64,7 @@ export const SETTINGS_PAGE_LABELS: Record<SettingsCategory, string> = {
environments: "Environments",
"cloud-environments": "Environments",
agents: "Agents",
+ "task-agent-defaults": "Model",
skills: "Skills",
"mcp-servers": "MCP servers",
personalization: "Personalization",
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index e4567fd4a927..dc8df4ddfe76 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -722,6 +722,9 @@ export function TaskInput({
fastModeOption,
isLoading: isPreviewLoading,
setConfigOption,
+ resetToDefault,
+ isDefaultSelection,
+ resetToDefaultDisabled,
} = usePreviewConfig(adapter, { allHarnessModels: true });
const lastAppliedDeepLinkConfigKey = useRef<string | undefined>(undefined);
@@ -1689,6 +1692,9 @@ export function TaskInput({
modelAccess={composerModelAccess}
showBillingMenu
workspaceMode={workspaceMode}
+ isDefaultSelection={isDefaultSelection}
+ onResetToDefault={resetToDefault}
+ resetToDefaultDisabled={resetToDefaultDisabled}
/>
)
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/usePreviewConfig.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/usePreviewConfig.ts
index 9701baed7f63..62c821a970ac 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/usePreviewConfig.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/usePreviewConfig.ts
@@ -14,6 +14,9 @@ import {
CONTEXT_WINDOW_OPTION_CATEGORY,
deriveInitialConfig,
FAST_MODE_OPTION_CATEGORY,
+ matchesPreferredRunSelection,
+ pickPreferredRunSelection,
+ preferredRunAdapter,
} from "@posthog/core/task-detail/previewConfig";
import { useHostTRPCClient } from "@posthog/host-router/react";
import {
@@ -29,9 +32,18 @@ import { logger } from "../../../shell/logger";
import { useAuthStateValue } from "../../auth/store";
import { useFeatureFlag } from "../../feature-flags/useFeatureFlag";
import { useSettingsStore } from "../../settings/settingsStore";
+import { useTaskRunDefaults } from "./useTaskRunDefaults";
const log = logger.scope("preview-config");
+/** The saved run picks a harness switch or a reset clears, as one write. */
+const CLEARED_RUN_PICKS = {
+ lastUsedModel: null,
+ lastUsedReasoningEffort: null,
+ lastUsedContextWindow: null,
+ lastUsedFastMode: null,
+};
+
interface PreviewConfigResult {
configOptions: SessionConfigOption[];
modeOption: SessionConfigOption | undefined;
@@ -41,6 +53,19 @@ interface PreviewConfigResult {
fastModeOption: SessionConfigOption | undefined;
isLoading: boolean;
setConfigOption: (configId: string, value: string) => void;
+ /**
+ * Drops the explicit local picks and re-derives the selection, landing on the
+ * configured project/user default when one applies, else the ladder's balanced notch.
+ */
+ resetToDefault: () => void;
+ /**
+ * The shown selection sits exactly on the resolved project/user default.
+ * False when no default is configured or it belongs to another harness — a
+ * fallback selection is not "the default".
+ */
+ isDefaultSelection: boolean;
+ /** Resetting would change nothing, so the reset control should read disabled. */
+ resetToDefaultDisabled: boolean;
}
function getOptionByCategory(
@@ -81,46 +106,34 @@ export function usePreviewConfig(
);
const [configOptions, setConfigOptions] = useState<SessionConfigOption[]>([]);
const [isLoading, setIsLoading] = useState(true);
- const abortRef = useRef<AbortController | null>(null);
+ // Raw server options, tagged with the adapter they were fetched for so the
+ // derivation below can never seat one adapter's selection on another's list.
+ const [fetched, setFetched] = useState<{
+ adapter: Adapter;
+ options: SessionConfigOption[];
+ } | null>(null);
const prevAdapterRef = useRef<Adapter | null>(null);
const hasHydrated = useSettingsStore((state) => state._hasHydrated);
+ // Truthiness only: selecting the raw pick values would re-render every
+ // mounted instance of this hook on each pick, even when the answers computed
+ // here don't change.
+ const hasModelPick = useSettingsStore((state) => state.lastUsedModel != null);
+ const hasEffortPick = useSettingsStore(
+ (state) => state.lastUsedReasoningEffort != null,
+ );
+ const { defaults: runDefaults, isSettled: runDefaultsSettled } =
+ useTaskRunDefaults();
+ // The harness the configured default (user's, else the team's) runs on.
+ const defaultAdapter = preferredRunAdapter(runDefaults);
useEffect(() => {
if (!apiHost) return;
- // Wait for the settings store to finish its async hydration before
- // resolving the model. Otherwise lastUsedModel and lastUsedAdapter read as
- // their pre-hydration defaults, the restore below is skipped, and the
- // selector silently falls back to the server default (Opus for Claude).
- // isLoading initializes to true, so the picker stays loading until hydration
- // lands and the fetch below resolves.
- if (!hasHydrated) return;
-
- // A harness switch resets the saved selections so the new harness starts
- // on its default preset notch (and the slider face shows). A saved model
- // that already belongs to the new harness survives: that is the
- // cross-harness model pick, where the model choice drives the switch.
- if (prevAdapterRef.current !== null && prevAdapterRef.current !== adapter) {
- const { lastUsedModel } = useSettingsStore.getState();
- useSettingsStore.setState({
- lastUsedModel:
- lastUsedModel && adapterForModelId(lastUsedModel) === adapter
- ? lastUsedModel
- : null,
- lastUsedReasoningEffort: null,
- lastUsedContextWindow: null,
- lastUsedFastMode: null,
- });
- }
- prevAdapterRef.current = adapter;
-
- abortRef.current?.abort();
const abort = new AbortController();
- abortRef.current = abort;
-
setIsLoading(true);
- // Drop the previous adapter's options so a stale model id can never be sent
- // as the current selection while the new adapter's config is loading.
+ // Drop the previous adapter's options so a stale model id can never be
+ // sent as the current selection while the new adapter's config is loading.
+ setFetched(null);
setConfigOptions([]);
hostClient.agent.getPreviewConfigOptions
@@ -128,144 +141,213 @@ export function usePreviewConfig(
{ apiHost, adapter, allHarnessModels: allHarnessModels || undefined },
{ signal: abort.signal },
)
- .then((serverOptions) => {
+ .then((options) => {
+ if (abort.signal.aborted) return;
+ setFetched({ adapter, options });
+ })
+ .catch((error) => {
if (abort.signal.aborted) return;
+ log.error("Failed to fetch preview config options", { error });
+ setIsLoading(false);
+ });
+
+ return () => {
+ abort.abort();
+ };
+ }, [adapter, allHarnessModels, apiHost, hostClient]);
+
+ /**
+ * Pure local derivation from the fetched options, the saved picks, and the
+ * configured default. Kept out of the fetch so a reset or a default change
+ * re-seats the selection without a round trip or a loading flash.
+ */
+ const deriveSelection = useCallback(
+ (serverOptions: SessionConfigOption[]): SessionConfigOption[] => {
+ const options = serverOptions
+ .map((option) => stripDisabledModelOption(option, modelFlags))
+ .filter((option) => fastModeFlagEnabled || option.id !== "fast");
- const options = serverOptions
- .map((option) => stripDisabledModelOption(option, modelFlags))
- .filter((option) => fastModeFlagEnabled || option.id !== "fast");
+ const {
+ defaultInitialTaskMode,
+ lastUsedInitialTaskMode,
+ defaultReasoningEffort,
+ lastUsedReasoningEffort,
+ lastUsedContextWindow,
+ lastUsedFastMode,
+ lastUsedModel,
+ } = useSettingsStore.getState();
- const {
+ let initial = deriveInitialConfig(
+ options,
+ {
defaultInitialTaskMode,
lastUsedInitialTaskMode,
defaultReasoningEffort,
lastUsedReasoningEffort,
lastUsedContextWindow,
lastUsedFastMode,
- lastUsedModel,
- } = useSettingsStore.getState();
+ },
+ adapter,
+ );
- let initial = deriveInitialConfig(
- options,
- {
- defaultInitialTaskMode,
- lastUsedInitialTaskMode,
- defaultReasoningEffort,
- lastUsedReasoningEffort,
- lastUsedContextWindow,
- lastUsedFastMode,
- },
+ // Seeding a selection is always "set the model, then carry an effort if the
+ // model still offers that tier" — the restore, preference, and ladder paths
+ // below differ only in where the pair comes from.
+ const seedSettings = {
+ defaultInitialTaskMode: "",
+ lastUsedInitialTaskMode: undefined,
+ defaultReasoningEffort,
+ lastUsedReasoningEffort,
+ lastUsedContextWindow,
+ lastUsedFastMode,
+ };
+ const seedSelection = (
+ config: SessionConfigOption[],
+ model: string,
+ effort?: string | null,
+ ): SessionConfigOption[] => {
+ const modelId = getOptionByCategory(config, "model")?.id ?? "model";
+ let seeded = applyConfigChange(config, {
adapter,
- );
-
- // The server always returns its default model as the current value, so
- // without this the user's last (default-eligible) pick is lost on every
- // refetch/remount. Restore it through applyConfigChange so the
- // dependent effort options are recomputed for the restored model.
- const modelOpt = getOptionByCategory(initial, "model");
- // The user's explicit last pick always restores, premium families
- // included — a fresh launch must not silently downgrade the model.
- // A grouped list also holds the other harness's models, so the pick has
- // to belong to this harness or it would run on the wrong one.
- const restorableModel =
- lastUsedModel &&
- harnessForModelValue(modelOpt, lastUsedModel) === adapter
- ? lastUsedModel
- : undefined;
+ configId: modelId,
+ value: model,
+ effortOptions: getReasoningEffortOptions(adapter, model) ?? undefined,
+ contextWindowOptions:
+ getContextWindowOptions(adapter, model) ?? undefined,
+ fastModeOptions: fastModeFlagEnabled
+ ? (getFastModeOptions(adapter, model) ?? undefined)
+ : undefined,
+ settings: seedSettings,
+ });
+ const thoughtOpt = getOptionByCategory(seeded, "thought_level");
if (
- restorableModel &&
- modelOpt?.type === "select" &&
- modelOpt.currentValue !== restorableModel &&
- flattenConfigValues(modelOpt).includes(restorableModel)
+ effort &&
+ thoughtOpt &&
+ flattenConfigValues(thoughtOpt).includes(effort)
) {
- initial = applyConfigChange(initial, {
+ seeded = applyConfigChange(seeded, {
adapter,
- configId: modelOpt.id,
- value: restorableModel,
- effortOptions:
- getReasoningEffortOptions(adapter, restorableModel) ?? undefined,
- contextWindowOptions:
- getContextWindowOptions(adapter, restorableModel) ?? undefined,
- fastModeOptions: fastModeFlagEnabled
- ? (getFastModeOptions(adapter, restorableModel) ?? undefined)
- : undefined,
- settings: {
- defaultInitialTaskMode: "",
- lastUsedInitialTaskMode: undefined,
- defaultReasoningEffort,
- lastUsedReasoningEffort,
- lastUsedContextWindow,
- lastUsedFastMode,
- },
+ configId: thoughtOpt.id,
+ value: effort,
+ effortOptions: undefined,
+ settings: seedSettings,
});
}
+ return seeded;
+ };
+
+ // The server always returns its default model as the current value, so
+ // without this the user's last (default-eligible) pick is lost on every
+ // refetch/remount. Restore it through applyConfigChange so the
+ // dependent effort options are recomputed for the restored model.
+ const modelOpt = getOptionByCategory(initial, "model");
+ // The user's explicit last pick always restores, premium families
+ // included — a fresh launch must not silently downgrade the model.
+ // A grouped list also holds the other harness's models, so the pick has
+ // to belong to this harness or it would run on the wrong one.
+ const restorableModel =
+ lastUsedModel &&
+ harnessForModelValue(modelOpt, lastUsedModel) === adapter
+ ? lastUsedModel
+ : undefined;
+ if (
+ restorableModel &&
+ modelOpt?.type === "select" &&
+ modelOpt.currentValue !== restorableModel &&
+ flattenConfigValues(modelOpt).includes(restorableModel)
+ ) {
+ initial = seedSelection(initial, restorableModel);
+ }
- // With no saved picks (fresh install or a harness switch), land on
- // the ladder's middle notch so the slider face is the default view.
- if (!lastUsedModel && !lastUsedReasoningEffort) {
- const ladder = getCapabilityLadder(adapter);
- const middle = ladder[Math.floor((ladder.length - 1) / 2)];
- const midModelOpt = getOptionByCategory(initial, "model");
- if (
- middle &&
- midModelOpt?.type === "select" &&
- flattenConfigValues(midModelOpt).includes(middle.model)
- ) {
- const previewSettings = {
- defaultInitialTaskMode: "",
- lastUsedInitialTaskMode: undefined,
- defaultReasoningEffort,
- lastUsedReasoningEffort,
- lastUsedContextWindow,
- lastUsedFastMode,
- };
- initial = applyConfigChange(initial, {
- adapter,
- configId: midModelOpt.id,
- value: middle.model,
- effortOptions:
- getReasoningEffortOptions(adapter, middle.model) ?? undefined,
- contextWindowOptions:
- getContextWindowOptions(adapter, middle.model) ?? undefined,
- fastModeOptions: fastModeFlagEnabled
- ? (getFastModeOptions(adapter, middle.model) ?? undefined)
- : undefined,
- settings: previewSettings,
- });
- const midThoughtOpt = getOptionByCategory(initial, "thought_level");
- if (midThoughtOpt) {
- initial = applyConfigChange(initial, {
- adapter,
- configId: midThoughtOpt.id,
- value: middle.effort,
- effortOptions: undefined,
- settings: previewSettings,
- });
- }
- }
+ // With no local pick (fresh install or a harness switch), the project or
+ // user preference stored server-side decides what the composer opens on,
+ // ahead of the ladder's middle notch.
+ const preferred = pickPreferredRunSelection(
+ runDefaults,
+ adapter,
+ getOptionByCategory(initial, "model"),
+ lastUsedModel,
+ lastUsedReasoningEffort,
+ );
+ if (preferred) {
+ initial = seedSelection(
+ initial,
+ preferred.model,
+ preferred.reasoningEffort,
+ );
+ }
+
+ // With no saved picks and no server-side preference, land on the ladder's
+ // middle notch so the slider face is the default view.
+ if (!preferred && !lastUsedModel && !lastUsedReasoningEffort) {
+ const ladder = getCapabilityLadder(adapter);
+ const middle = ladder[Math.floor((ladder.length - 1) / 2)];
+ const midModelOpt = getOptionByCategory(initial, "model");
+ if (
+ middle &&
+ midModelOpt?.type === "select" &&
+ flattenConfigValues(midModelOpt).includes(middle.model)
+ ) {
+ initial = seedSelection(initial, middle.model, middle.effort);
}
+ }
- setConfigOptions(initial);
- setIsLoading(false);
- })
- .catch((error) => {
- if (abort.signal.aborted) return;
- log.error("Failed to fetch preview config options", { error });
- setIsLoading(false);
+ return initial;
+ },
+ [adapter, modelFlags, fastModeFlagEnabled, runDefaults],
+ );
+
+ useEffect(() => {
+ if (!fetched || fetched.adapter !== adapter) return;
+
+ // Wait for the settings store to finish its async hydration before
+ // resolving the model. Otherwise lastUsedModel and lastUsedAdapter read as
+ // their pre-hydration defaults, the restore is skipped, and the selector
+ // silently falls back to the server default (Opus for Claude). isLoading
+ // initializes to true, so the picker stays loading until hydration lands
+ // and the derivation below runs.
+ if (!hasHydrated) return;
+
+ // Same reasoning for the server-side defaults: resolving before they land
+ // would seat the picker on the built-in fallback and then jump.
+ if (!runDefaultsSettled) return;
+
+ // A harness switch resets the saved selections so the new harness starts
+ // on its default preset notch (and the slider face shows). A saved model
+ // that already belongs to the new harness survives: that is the
+ // cross-harness model pick, where the model choice drives the switch.
+ if (prevAdapterRef.current !== null && prevAdapterRef.current !== adapter) {
+ const { lastUsedModel } = useSettingsStore.getState();
+ useSettingsStore.setState({
+ ...CLEARED_RUN_PICKS,
+ lastUsedModel:
+ lastUsedModel && adapterForModelId(lastUsedModel) === adapter
+ ? lastUsedModel
+ : null,
});
+ }
+ prevAdapterRef.current = adapter;
- return () => {
- abort.abort();
- };
- }, [
- adapter,
- allHarnessModels,
- apiHost,
- hostClient,
- hasHydrated,
- modelFlags,
- fastModeFlagEnabled,
- ]);
+ setConfigOptions(deriveSelection(fetched.options));
+ setIsLoading(false);
+ }, [fetched, adapter, hasHydrated, runDefaultsSettled, deriveSelection]);
+
+ const resetToDefault = useCallback(() => {
+ useSettingsStore.setState({
+ ...CLEARED_RUN_PICKS,
+ // The default names its harness, and it is unreachable from the other
+ // one — so reset moves the adapter with it rather than being skipped.
+ ...(defaultAdapter ? { lastUsedAdapter: defaultAdapter } : {}),
+ });
+ // Moving the harness re-renders with the new adapter and refetches; on the
+ // same harness, re-seat locally from the options already in hand.
+ if (
+ (!defaultAdapter || defaultAdapter === adapter) &&
+ fetched?.adapter === adapter
+ ) {
+ setConfigOptions(deriveSelection(fetched.options));
+ }
+ }, [adapter, defaultAdapter, deriveSelection, fetched]);
const setConfigOption = useCallback(
(configId: string, value: string) => {
@@ -323,6 +405,39 @@ export function usePreviewConfig(
FAST_MODE_OPTION_CATEGORY,
);
+ // The picks are passed as null: the question here is whether a preference
+ // applies to this surface at all, not whether it outranks an explicit pick.
+ const preferred = pickPreferredRunSelection(
+ runDefaults,
+ adapter,
+ modelOption,
+ null,
+ null,
+ );
+ const isDefaultSelection = matchesPreferredRunSelection(
+ preferred,
+ {
+ model:
+ modelOption?.type === "select" ? modelOption.currentValue : undefined,
+ reasoningEffort:
+ thoughtOption?.type === "select"
+ ? thoughtOption.currentValue
+ : undefined,
+ },
+ hasEffortPick,
+ );
+ // A default on the other harness always leaves reset live — it switches the
+ // adapter over. On this harness it's live until the selection matches; with
+ // no applicable default a reset just clears picks, pointless only while
+ // nothing was picked.
+ const resetSwitchesHarness =
+ defaultAdapter !== null && defaultAdapter !== adapter;
+ const resetToDefaultDisabled = resetSwitchesHarness
+ ? false
+ : preferred
+ ? isDefaultSelection
+ : !hasModelPick && !hasEffortPick;
+
return {
configOptions,
modeOption,
@@ -332,5 +447,8 @@ export function usePreviewConfig(
fastModeOption,
isLoading,
setConfigOption,
+ resetToDefault,
+ isDefaultSelection,
+ resetToDefaultDisabled,
};
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskRunDefaults.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskRunDefaults.ts
new file mode 100644
index 000000000000..177f361f7f5c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskRunDefaults.ts
@@ -0,0 +1,64 @@
+import {
+ NO_TASK_RUN_DEFAULTS,
+ type TaskRunDefaults,
+} from "@posthog/api-client/posthog-client";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { useRef } from "react";
+import { useAuthStateFetched, useAuthStateValue } from "../../auth/store";
+
+export interface TaskRunDefaultsResult {
+ defaults: TaskRunDefaults;
+ /** Whether the answer is final — the fetch finished, failed, or was never applicable. */
+ isSettled: boolean;
+}
+
+/**
+ * Shared so the settings page can drop this cache when it changes the preference behind
+ * it. The composer holds the answer for `staleTime`, which is right for a value that
+ * rarely moves and wrong for the moment someone just moved it.
+ */
+export function taskRunDefaultsQueryKey(
+ projectId: number | string | null,
+): [string, number | string | null] {
+ return ["task-run-defaults", projectId];
+}
+
+/**
+ * The project/user default AI run configuration for the signed-in user, which
+ * the composer opens on when nothing has been picked locally.
+ *
+ * Defaults are a nicety: an unauthenticated or failed fetch resolves to "no
+ * default" so the composer falls back to its built-in selection rather than
+ * stalling.
+ */
+export function useTaskRunDefaults(): TaskRunDefaultsResult {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const authFetched = useAuthStateFetched();
+ const query = useAuthenticatedQuery(
+ taskRunDefaultsQueryKey(projectId),
+ async (client) => await client.getTaskRunDefaults(Number(projectId)),
+ {
+ enabled: projectId != null,
+ // The preference is shared, so it also moves in the web app, in Slack, or via a
+ // teammate changing the project default — none of which this app hears about. A
+ // short window plus a refetch when the app is focused again keeps it close to the
+ // truth without polling; a change made *here* doesn't wait for it, since the write
+ // invalidates this key directly.
+ staleTime: 30 * 1000,
+ refetchOnWindowFocus: true,
+ retry: false,
+ },
+ );
+
+ // Monotonic: `projectId` only arrives once auth bootstraps, so a plain `projectId == null`
+ // arm would read settled, then unsettled, then settled — restarting whatever waits on it.
+ // Once true it stays true for the life of the hook.
+ const settledRef = useRef(false);
+ settledRef.current =
+ settledRef.current || query.isFetched || (authFetched && projectId == null);
+
+ return {
+ defaults: query.data ?? NO_TASK_RUN_DEFAULTS,
+ isSettled: settledRef.current,
+ };
+}