: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(desktop): add assisted model switching (#89810)
Shy Alterbddacf8f7ec6
diff --git a/products/desktop/packages/core/src/billing/modelPricing.test.ts b/products/desktop/packages/core/src/billing/modelPricing.test.tsindex 371531bbb904..b76f1fb4bdd1 100644--- a/products/desktop/packages/core/src/billing/modelPricing.test.ts+++ b/products/desktop/packages/core/src/billing/modelPricing.test.ts@@ -1,9 +1,9 @@import { describe, expect, it } from "vitest";import {+ estimateUncachedInputCost,formatModelRates,modelCostInfo,modelListPrice,- relativeCostLabel,} from "./modelPricing";describe("modelPricing", () => {@@ -41,12 +41,17 @@ describe("modelPricing", () => {);});- it("compares two models for the switch dialog", () => {- expect(relativeCostLabel("claude-opus-5", "claude-haiku-4-5")).toBe("0.2×");- expect(relativeCostLabel("claude-haiku-4-5", "claude-fable-5")).toBe("10×");- expect(relativeCostLabel("claude-opus-5", "claude-opus-4-8")).toBeNull();- expect(relativeCostLabel("claude-opus-5", "unknown-model")).toBeNull();- });+ it.each([+ ["gpt-5.6-terra", 100_000, 0.25],+ ["claude-haiku-4-5", 50_000, 0.05],+ ["unknown-model", 100_000, null],+ ["claude-opus-5", 0, null],+ ] as const)(+ "estimates uncached input cost for %s with %s tokens",+ (modelId, tokens, expected) => {+ expect(estimateUncachedInputCost(modelId, tokens)).toBe(expected);+ },+ );});// The gateway pins the contract rates these three families bill at, and thisdiff --git a/products/desktop/packages/core/src/billing/modelPricing.ts b/products/desktop/packages/core/src/billing/modelPricing.tsindex e0133c3de488..10b3c55dacf1 100644--- a/products/desktop/packages/core/src/billing/modelPricing.ts+++ b/products/desktop/packages/core/src/billing/modelPricing.ts@@ -117,20 +117,11 @@ export function modelCostInfo(modelId: string): ModelCostInfo | null {};}-/**- * Per-token rate of `toModelId` relative to `fromModelId`, e.g. "0.2×", for- * the switch dialog, whose copy already frames it as approximate ("about").- * Null when either model has no known list price, or when the rates match.- */-export function relativeCostLabel(- fromModelId: string,- toModelId: string,-): string | null {- const from = modelListPrice(fromModelId);- const to = modelListPrice(toModelId);- if (!from || !to) return null;- const { blended, approximate } = blendedRatio(to, from);- // Same list price reads as no line at all, not "1×".- if (!approximate && Math.abs(blended - 1) < 0.001) return null;- return formatMultiplier(blended, false);+export function estimateUncachedInputCost(+ modelId: string,+ inputTokens: number,+): number | null {+ const price = modelListPrice(modelId);+ if (!price || inputTokens <= 0) return null;+ return (inputTokens / 1_000_000) * price.inputPerMtok;}diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 3b4d0eacd7fd..ccb6049c5c76 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -5875,27 +5875,35 @@ export class SessionService {* Set a session configuration option with optimistic update and rollback.* This is the unified method for model, mode, thought level, etc.*/+ /**+ * Returns whether the change reached the agent: `true` once the backend+ * accepted it (or it was already set), `false` when the session is missing,+ * the option is unknown, the change was skipped because the local session is+ * offline, or the backend call failed and rolled back. Callers that gate a+ * user action on the switch (the mid-session model switch) rely on this to+ * tell success from a swallowed failure.+ */async setSessionConfigOption(taskId: string,configId: string,value: string,- ): Promise<void> {+ ): Promise<boolean> {const session = this.d.store.getSessionByTaskId(taskId);- if (!session) return;+ if (!session) return false;// Find the config option and save previous value for rollbackconst configOptions = session.configOptions ?? [];const optionIndex = configOptions.findIndex((opt) => opt.id === configId);if (optionIndex === -1) {this.d.log.warn("Config option not found", { taskId, configId });- return;+ return false;}const previousValue = configOptions[optionIndex].currentValue;// Skip if value is already set — avoids expensive IPC round-trip (e.g. setModel ~2s)if (previousValue === value) {- return;+ return true;}// Optimistic update@@ -5909,13 +5917,35 @@ export class SessionService {});this.d.setPersistedConfigOptions(session.taskRunId, updatedOptions);+ const rollbackConfigOption = (): void => {+ const latestConfigOptions =+ this.d.store.getSessionByTaskId(taskId)?.configOptions ?? [];+ const latestOption = latestConfigOptions.find(+ (option) => option.id === configId,+ );+ if (latestOption?.currentValue !== value) return;+ const rolledBackOptions = latestConfigOptions.map((option) =>+ option.id === configId+ ? ({+ ...option,+ currentValue: previousValue,+ } as SessionConfigOption)+ : option,+ );+ this.d.store.updateSession(session.taskRunId, {+ configOptions: rolledBackOptions,+ });+ this.d.setPersistedConfigOptions(session.taskRunId, rolledBackOptions);+ };+if (!session.isCloud &&(session.idleKilled ||session.status === "disconnected" ||session.status === "connecting")) {- return;+ rollbackConfigOption();+ return false;}try {@@ -5931,26 +5961,9 @@ export class SessionService {value,});}+ return true;} catch (error) {- const latestConfigOptions =- this.d.store.getSessionByTaskId(taskId)?.configOptions ?? [];- const latestOption = latestConfigOptions.find(- (option) => option.id === configId,- );- if (latestOption?.currentValue === value) {- const rolledBackOptions = latestConfigOptions.map((option) =>- option.id === configId- ? ({- ...option,- currentValue: previousValue,- } as SessionConfigOption)- : option,- );- this.d.store.updateSession(session.taskRunId, {- configOptions: rolledBackOptions,- });- this.d.setPersistedConfigOptions(session.taskRunId, rolledBackOptions);- }+ rollbackConfigOption();this.d.log.error("Failed to set session config option", {taskId,configId,@@ -5958,6 +5971,7 @@ export class SessionService {error,});this.d.toast.error("Failed to change setting. Please try again.");+ return false;}}diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex f21a64433b36..94053c3d0a71 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -398,6 +398,19 @@ export interface SessionConfigChangedProperties {to_value: string;}+export interface ModelSwitchWarningShownProperties {+ task_id?: string;+ from_model: string;+ to_model: string;+ context_tokens?: number;+}++export interface ModelSwitchWarningActionProperties+ extends ModelSwitchWarningShownProperties {+ action: "cancel" | "copy_handoff_summary" | "switch_now";+ result?: "failed" | "succeeded";+}+// Tour eventstype TourAction = "started" | "step_advanced" | "dismissed" | "completed";@@ -1434,6 +1447,8 @@ export const ANALYTICS_EVENTS = {// Session config eventsSESSION_CONFIG_CHANGED: "Session config changed",+ MODEL_SWITCH_WARNING_SHOWN: "Model switch warning shown",+ MODEL_SWITCH_WARNING_ACTION: "Model switch warning action",// Settings eventsSETTING_CHANGED: "Setting changed",@@ -1627,6 +1642,8 @@ export type EventPropertyMap = {// Session config events[ANALYTICS_EVENTS.SESSION_CONFIG_CHANGED]: SessionConfigChangedProperties;+ [ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_SHOWN]: ModelSwitchWarningShownProperties;+ [ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION]: ModelSwitchWarningActionProperties;// Settings events[ANALYTICS_EVENTS.SETTING_CHANGED]: SettingChangedProperties;diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsxindex 166fb636033b..16824deb90d4 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx@@ -6,11 +6,13 @@ const meta: Meta<typeof ModelSwitchCacheDialog> = {component: ModelSwitchCacheDialog,args: {open: true,- fromModelId: "claude-opus-5",fromModelLabel: "Claude Opus 5",toModelId: "claude-haiku-4-5",toModelLabel: "Claude Haiku 4.5",- onConfirm: () => {},+ contextTokens: 84_000,+ sessionCostUsd: 1.42,+ onConfirm: async () => {},+ onCopyHandoffSummary: async () => {},onCancel: () => {},},};@@ -22,7 +24,6 @@ export const SwitchToCheaper: Story = {};export const SwitchToPricier: Story = {args: {- fromModelId: "claude-sonnet-5",fromModelLabel: "Claude Sonnet 5",toModelId: "claude-fable-5",toModelLabel: "Claude Fable 5",@@ -31,9 +32,16 @@ export const SwitchToPricier: Story = {export const UnknownPricing: Story = {args: {- fromModelId: "custom-model-a",fromModelLabel: "Custom model A",toModelId: "custom-model-b",toModelLabel: "Custom model B",},};++export const SwitchOnly: Story = {+ args: {+ contextTokens: undefined,+ sessionCostUsd: undefined,+ onCopyHandoffSummary: undefined,+ },+};diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsxnew file mode 100644index 000000000000..2f804b4269b1--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.test.tsx@@ -0,0 +1,50 @@+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ModelSwitchCacheDialog } from "./ModelSwitchCacheDialog";++describe("ModelSwitchCacheDialog", () => {+ beforeEach(() => {+ useSettingsStore.setState({ warnOnMidSessionModelSwitch: true });+ });++ it("keeps future warnings enabled when the user selects do not show again and cancels", () => {+ const onCancel = vi.fn();+ render(+ <ModelSwitchCacheDialog+ open+ fromModelLabel="Claude Sonnet 5"+ toModelId="claude-opus-5"+ toModelLabel="Claude Opus 5"+ onConfirm={vi.fn().mockResolvedValue(undefined)}+ onCancel={onCancel}+ />,+ );++ fireEvent.click(screen.getByText("Do not show this ever again"));+ fireEvent.click(screen.getByText("Cancel"));++ expect(onCancel).toHaveBeenCalledOnce();+ expect(useSettingsStore.getState().warnOnMidSessionModelSwitch).toBe(true);+ });++ it("does not inherit a prior action's busy state when reopened for a new switch", () => {+ const onConfirm = vi.fn().mockReturnValue(new Promise<void>(() => {}));+ const onCancel = vi.fn();+ const props = {+ fromModelLabel: "Claude Sonnet 5",+ toModelId: "claude-opus-5",+ toModelLabel: "Claude Opus 5",+ onConfirm,+ onCancel,+ };+ const { rerender } = render(<ModelSwitchCacheDialog open {...props} />);++ fireEvent.click(screen.getByText("Switch now"));+ rerender(<ModelSwitchCacheDialog open={false} {...props} />);+ rerender(<ModelSwitchCacheDialog open {...props} />);++ fireEvent.click(screen.getByText("Cancel"));+ expect(onCancel).toHaveBeenCalledOnce();+ });+});diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsxindex 26bb39b2ed93..7f6c787ef172 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx@@ -1,5 +1,5 @@import { ArrowRight } from "@phosphor-icons/react";-import { relativeCostLabel } from "@posthog/core/billing/modelPricing";+import { estimateUncachedInputCost } from "@posthog/core/billing/modelPricing";import {AlertDialog,AlertDialogContent,@@ -9,114 +9,203 @@ import {AlertDialogTitle,Button,Checkbox,+ Label,Text,} from "@posthog/quill";+import { formatCostUsd } from "@posthog/ui/features/sessions/contextColors";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";-import { type ReactElement, useId, useState } from "react";+import { type ReactElement, useEffect, useId, useRef, useState } from "react";interface ModelSwitchCacheDialogProps {open: boolean;- fromModelId: string;fromModelLabel: string;toModelId: string;toModelLabel: string;- onConfirm: () => void;+ contextTokens?: number;+ sessionCostUsd?: number;+ onConfirm: () => Promise<boolean>;+ onCopyHandoffSummary?: () => Promise<void>;onCancel: () => void;}-/**- * Inform-only pause before a mid-session model switch: the switch always- * goes through on confirm; the dialog only explains the cache cost and, when- * both list prices are known, the relative per-token rate.- */+type ActiveAction = "copy_summary" | "switch" | null;+export function ModelSwitchCacheDialog({open,- fromModelId,fromModelLabel,toModelId,toModelLabel,+ contextTokens = 0,+ sessionCostUsd,onConfirm,+ onCopyHandoffSummary,onCancel,}: ModelSwitchCacheDialogProps): ReactElement {const setWarnOnModelSwitch = useSettingsStore((state) => state.setWarnOnMidSessionModelSwitch,);const [dontShowAgain, setDontShowAgain] = useState(false);+ const [activeAction, setActiveAction] = useState<ActiveAction>(null);const checkboxId = useId();- const rateLabel = relativeCostLabel(fromModelId, toModelId);+ const cancelButtonRef = useRef<HTMLButtonElement>(null);+ const requestTokenRef = useRef(0);+ const estimatedInputCost = estimateUncachedInputCost(+ toModelId,+ contextTokens,+ );+ const hasCostInfo =+ estimatedInputCost !== null || sessionCostUsd !== undefined;+ const busy = activeAction !== null;++ useEffect(() => {+ if (open) {+ setDontShowAgain(false);+ setActiveAction(null);+ requestTokenRef.current += 1;+ }+ }, [open]);- const rememberChoice = () => {+ const rememberChoice = (): void => {if (dontShowAgain) setWarnOnModelSwitch(false);};+ const handleConfirm = async (): Promise<void> => {+ const token = requestTokenRef.current;+ setActiveAction("switch");+ try {+ if (await onConfirm()) rememberChoice();+ } finally {+ if (requestTokenRef.current === token) setActiveAction(null);+ }+ };++ const handleCopyHandoffSummary = async (): Promise<void> => {+ if (!onCopyHandoffSummary) return;+ const token = requestTokenRef.current;+ setActiveAction("copy_summary");+ try {+ await onCopyHandoffSummary();+ } finally {+ if (requestTokenRef.current === token) setActiveAction(null);+ }+ };+return (<AlertDialogopen={open}onOpenChange={(next) => {- if (!next) onCancel();+ if (!next && !busy) onCancel();}}>- <AlertDialogContent>+ <AlertDialogContent initialFocus={cancelButtonRef}><AlertDialogHeader><AlertDialogTitle>Switch model mid-session?</AlertDialogTitle><AlertDialogDescription>- Cached context doesn't carry over between models. Your next message- will reprocess the whole conversation instead of reading it from- cache, which costs more on long sessions.+ Cached context does not carry between models. Switching now resends+ the full conversation to the new model.</AlertDialogDescription></AlertDialogHeader>- <div className="flex flex-col gap-2 rounded-(--radius-3) border border-(--gray-4) bg-(--gray-2) px-4 py-3">- <div className="flex items-center justify-center gap-2.5">- <span className="rounded-(--radius-2) bg-(--gray-4) px-2 py-1 text-[12px] text-muted-foreground">- {fromModelLabel}- </span>- <ArrowRight size={13} className="shrink-0 text-muted-foreground" />- <span className="rounded-(--radius-2) bg-(--gray-4) px-2 py-1 font-medium text-[12px] text-foreground">- {toModelLabel}- </span>- </div>- {rateLabel && (- <Text className="text-center text-[12px] text-muted-foreground">- {toModelLabel} runs at about{" "}- <span className="font-medium text-foreground tabular-nums">- {rateLabel}- </span>{" "}- {fromModelLabel}'s per-token rate.- </Text>+ <div className="flex flex-col gap-4 px-4 pb-4">+ {hasCostInfo && (+ <div className="overflow-hidden rounded-(--radius-3) border border-(--gray-4) bg-(--gray-2)">+ <div className="flex items-center justify-center gap-2.5 px-3 py-3">+ <span className="truncate rounded-(--radius-2) bg-(--gray-4) px-2 py-1 text-[12px] text-muted-foreground">+ {fromModelLabel}+ </span>+ <ArrowRight+ size={13}+ className="shrink-0 text-muted-foreground"+ />+ <span className="truncate rounded-(--radius-2) bg-(--gray-4) px-2 py-1 font-medium text-[12px] text-foreground">+ {toModelLabel}+ </span>+ </div>+ <div className="flex flex-col gap-2 border-(--gray-4) border-t px-3 py-3">+ {estimatedInputCost !== null && (+ <div className="flex items-center justify-between gap-4">+ <Text className="text-[12px] text-muted-foreground">+ Estimated cost to resend history+ </Text>+ <Text className="shrink-0 font-medium text-[12px] text-foreground tabular-nums">+ {formatCostUsd(estimatedInputCost)}+ </Text>+ </div>+ )}+ {sessionCostUsd !== undefined && (+ <div className="flex items-center justify-between gap-4">+ <Text className="text-[12px] text-muted-foreground">+ Session cost so far+ </Text>+ <Text className="shrink-0 font-medium text-[12px] text-foreground tabular-nums">+ {formatCostUsd(sessionCostUsd)}+ </Text>+ </div>+ )}+ </div>+ </div>)}- </div>- <div className="flex items-center gap-2">- <Checkbox- id={checkboxId}- checked={dontShowAgain}- onCheckedChange={(checked) => setDontShowAgain(checked === true)}- data-attr="model-switch-cache-dialog-dont-show-again"- />- <label htmlFor={checkboxId}>- <Text className="text-[13px] text-muted-foreground">- Don't show this again+ {onCopyHandoffSummary && (+ <div className="flex items-center justify-between gap-4">+ <div className="flex min-w-0 flex-col">+ <Text className="font-medium text-[12px] text-foreground">+ Continue with another agent+ </Text>+ <Text className="text-[12px] text-muted-foreground">+ Copy the important context from this conversation.+ </Text>+ </div>+ <Button+ variant="outline"+ size="sm"+ loading={activeAction === "copy_summary"}+ disabled={busy}+ data-attr="model-switch-cache-dialog-copy-summary"+ onClick={handleCopyHandoffSummary}+ >+ Copy summary+ </Button>+ </div>+ )}+ <div className="flex flex-col gap-1 border-(--gray-4) border-t pt-3">+ <div className="flex items-center gap-2">+ <Checkbox+ id={checkboxId}+ checked={dontShowAgain}+ disabled={busy}+ onCheckedChange={(checked) =>+ setDontShowAgain(checked === true)+ }+ data-attr="model-switch-cache-dialog-dont-show-again"+ />+ <Label+ htmlFor={checkboxId}+ className="cursor-pointer text-[13px] text-muted-foreground"+ >+ Do not show this ever again+ </Label>+ </div>+ <Text className="text-[12px] text-muted-foreground">+ You can always change your mind in Cost management settings.</Text>- </label>+ </div></div>- <AlertDialogFooter>+ <AlertDialogFooter className="flex-row justify-end"><Button+ ref={cancelButtonRef}variant="outline"- onClick={() => {- rememberChoice();- onCancel();- }}+ disabled={busy}+ onClick={onCancel}>Cancel</Button><Buttonvariant="primary"+ loading={activeAction === "switch"}+ disabled={busy}data-attr="model-switch-cache-dialog-confirm"- onClick={() => {- rememberChoice();- onConfirm();- }}+ onClick={handleConfirm}>- Switch to {toModelLabel}+ Switch now</Button></AlertDialogFooter></AlertDialogContent>diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex 7a7f425e29ae..6233a43f91eb 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -11,7 +11,12 @@ import {FAST_MODE_OPTION_CATEGORY,} from "@posthog/core/task-detail/previewConfig";import { useService } from "@posthog/di/react";-import { type AcpMessage, FAST_MODE_FLAG } from "@posthog/shared";+import {+ type AcpMessage,+ FAST_MODE_FLAG,+ sessionSupportsSideQuestion,+} from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";import {spendStopMessage,@@ -76,11 +81,13 @@ import {useSessionViewActions,useShowRawLogs,} from "@posthog/ui/features/sessions/sessionViewStore";+import { useSideQuestionStore } from "@posthog/ui/features/sessions/sideQuestionStore";import type { Plan } from "@posthog/ui/features/sessions/types";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { useIsWorkspaceCloudRun } from "@posthog/ui/features/workspace/useWorkspace";import { useConnectivity } from "@posthog/ui/hooks/useConnectivity";import { toast } from "@posthog/ui/primitives/toast";+import { captureException, track } from "@posthog/ui/shell/analytics";import {pendingTaskPromptStoreApi,usePendingTaskPrompt,@@ -139,6 +146,8 @@ interface SessionViewProps {const DEFAULT_ERROR_MESSAGE ="Failed to resume this session. The working directory may have been deleted. Please start a new session.";+const HANDOFF_SUMMARY_PROMPT = `Create a concise handoff summary for another coding agent. Include the user's goal, constraints, decisions, current progress, relevant files, commands and tests, remaining work, and blockers. Do not continue the task. Return only the handoff summary.`;+export function SessionView({events,taskId,@@ -246,10 +255,23 @@ export function SessionView({[taskId, thoughtOption, sessionService],);+ const contextUsage = useContextUsage(events);+ const canCopyHandoffSummary = useSessionSelector(taskId, (session) =>+ session ? sessionSupportsSideQuestion(session) : false,+ );+ const hasPendingSideQuestion = useSideQuestionStore((s) =>+ taskId ? s.byTaskId[taskId]?.status === "pending" : false,+ );+ const activeTaskRunId = useSessionSelector(taskId, (s) => s?.taskRunId);+const applyConfigOption = useCallback(- (configId: string, value: string) => {- if (!taskId) return;- sessionService.setSessionConfigOption(taskId, configId, value);+ async (configId: string, value: string): Promise<boolean> => {+ if (!taskId) return false;+ return await sessionService.setSessionConfigOption(+ taskId,+ configId,+ value,+ );},[taskId, sessionService],);@@ -263,14 +285,63 @@ export function SessionView({taskId,sessionModelOption,hasConversationStarted: hasSessionPromptEvent(events),+ contextTokens: contextUsage?.used,onApply: applyConfigOption,});+ const handleCopyHandoffSummary = useCallback(async (): Promise<void> => {+ if (!taskId || !activeTaskRunId || !pendingModelSwitch) return;+ const { ask, resolve, fail } = useSideQuestionStore.getState();+ const questionId = ask(taskId, activeTaskRunId, HANDOFF_SUMMARY_PROMPT);+ if (!questionId) return;+ try {+ const summary = await sessionService.askSideQuestion(+ taskId,+ HANDOFF_SUMMARY_PROMPT,+ );+ resolve(taskId, activeTaskRunId, questionId, summary);+ await navigator.clipboard.writeText(summary);+ track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {+ task_id: taskId,+ from_model: pendingModelSwitch.fromValue,+ to_model: pendingModelSwitch.value,+ context_tokens: contextUsage?.used,+ action: "copy_handoff_summary",+ result: "succeeded",+ });+ toast.success("Handoff summary copied");+ } catch (error) {+ const caughtError =+ error instanceof Error ? error : new Error("Handoff summary failed");+ fail(taskId, activeTaskRunId, questionId, caughtError.message);+ captureException(caughtError, {+ feature: "model_switch_handoff_summary",+ });+ track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {+ task_id: taskId,+ from_model: pendingModelSwitch.fromValue,+ to_model: pendingModelSwitch.value,+ context_tokens: contextUsage?.used,+ action: "copy_handoff_summary",+ result: "failed",+ });+ toast.error("Could not copy a handoff summary", {+ description: "Try again, or continue without a summary.",+ });+ }+ }, [+ taskId,+ activeTaskRunId,+ pendingModelSwitch,+ sessionService,+ contextUsage?.used,+ ]);+const handleConfigOptionChange = useCallback((configId: string, value: string) => {if (!taskId) return;if (interceptModelSwitch(configId, value)) return;- applyConfigOption(configId, value);+ void applyConfigOption(configId, value);},[taskId, interceptModelSwitch, applyConfigOption],);@@ -299,7 +370,6 @@ export function SessionView({const isCloudRun = useIsWorkspaceCloudRun(taskId);const editorRef = useRef<PromptInputHandle>(null);- const contextUsage = useContextUsage(events);const isCompacting = useSessionSelector(taskId,(session) => session?.isCompacting ?? false,@@ -458,7 +528,6 @@ export function SessionView({(s) => !!s?.editingQueuedId,);const cancelQueuedEdit = useCancelQueuedMessageEdit(taskId);- const activeTaskRunId = useSessionSelector(taskId, (s) => s?.taskRunId);const [isDraggingFile, setIsDraggingFile] = useState(false);const promptRecallRef = useRef<PromptRecallHandler | null>(null);@@ -882,11 +951,21 @@ export function SessionView({</ContextMenu.Trigger><ModelSwitchCacheDialogopen={pendingModelSwitch !== null}- fromModelId={pendingModelSwitch?.fromValue ?? ""}fromModelLabel={pendingModelSwitch?.fromLabel ?? ""}toModelId={pendingModelSwitch?.value ?? ""}toModelLabel={pendingModelSwitch?.label ?? ""}+ contextTokens={contextUsage?.used}+ sessionCostUsd={+ olderHistoryCursor === 0 && contextUsage?.cost?.currency === "USD"+ ? contextUsage.cost.amount+ : undefined+ }onConfirm={confirmModelSwitch}+ onCopyHandoffSummary={+ canCopyHandoffSummary && !hasPendingSideQuestion+ ? handleCopyHandoffSummary+ : undefined+ }onCancel={cancelModelSwitch}/><ContextMenu.Content size="1">diff --git a/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.test.tsxindex 3d30e878b916..e289af2a3e59 100644--- a/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.test.tsx@@ -4,6 +4,9 @@ import { act, renderHook } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { usePendingModelSwitch } from "./usePendingModelSwitch";+const { trackMock } = vi.hoisted(() => ({ trackMock: vi.fn() }));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: trackMock }));+function modelOption(): SessionConfigOption {return {type: "select",@@ -20,7 +23,7 @@ function modelOption(): SessionConfigOption {interface Props {taskId: string | undefined;- onApply: (configId: string, value: string) => void;+ onApply: (configId: string, value: string) => Promise<boolean>;hasConversationStarted: boolean;}@@ -37,17 +40,24 @@ function setup(hasConversationStarted: props.hasConversationStarted,onApply: props.onApply,}),- { initialProps: { taskId, onApply, hasConversationStarted } },+ {+ initialProps: {+ taskId,+ onApply,+ hasConversationStarted,+ },+ },);}describe("usePendingModelSwitch", () => {beforeEach(() => {+ trackMock.mockClear();useSettingsStore.setState({ warnOnMidSessionModelSwitch: true });});- it("queues a mid-session switch and applies it on confirm", () => {- const onApply = vi.fn();+ it("queues a mid-session switch and applies it on confirm", async () => {+ const onApply = vi.fn().mockResolvedValue(true);const { result } = setup("task-a", onApply);let intercepted = false;@@ -60,13 +70,31 @@ describe("usePendingModelSwitch", () => {expect(intercepted).toBe(true);expect(result.current.pendingModelSwitch?.value).toBe("claude-sonnet-5");- act(() => result.current.confirmModelSwitch());+ await act(() => result.current.confirmModelSwitch());expect(onApply).toHaveBeenCalledWith("model", "claude-sonnet-5");expect(result.current.pendingModelSwitch).toBeNull();});+ it("keeps the dialog open when the switch does not reach the agent", async () => {+ const onApply = vi.fn().mockResolvedValue(false);+ const { result } = setup("task-a", onApply);++ act(() => {+ result.current.interceptModelSwitch("model", "claude-sonnet-5");+ });++ let confirmResult: boolean | undefined;+ await act(async () => {+ confirmResult = await result.current.confirmModelSwitch();+ });++ expect(onApply).toHaveBeenCalledWith("model", "claude-sonnet-5");+ expect(confirmResult).toBe(false);+ expect(result.current.pendingModelSwitch).not.toBeNull();+ });+it("does not queue a switch before the conversation has started", () => {- const onApply = vi.fn();+ const onApply = vi.fn().mockResolvedValue(true);const { result } = setup("task-a", onApply, false);let intercepted = true;@@ -81,8 +109,8 @@ describe("usePendingModelSwitch", () => {expect(onApply).not.toHaveBeenCalled();});- it("drops the queued switch when the task changes so confirm cannot apply it to another session", () => {- const onApply = vi.fn();+ it("drops the queued switch when the task changes so confirm cannot apply it to another session", async () => {+ const onApply = vi.fn().mockResolvedValue(true);const { result, rerender } = setup("task-a", onApply);act(() => {@@ -91,10 +119,14 @@ describe("usePendingModelSwitch", () => {expect(result.current.pendingModelSwitch).not.toBeNull();// The view swaps to another task without remounting.- rerender({ taskId: "task-b", onApply, hasConversationStarted: true });+ rerender({+ taskId: "task-b",+ onApply,+ hasConversationStarted: true,+ });expect(result.current.pendingModelSwitch).toBeNull();- act(() => result.current.confirmModelSwitch());+ await act(() => result.current.confirmModelSwitch());expect(onApply).not.toHaveBeenCalled();});});diff --git a/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.ts b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.tsindex 8f01e7335a24..40675f46b3ca 100644--- a/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.ts@@ -1,6 +1,8 @@import type { SessionConfigOption } from "@agentclientprotocol/sdk";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { flattenSelectOptions } from "@posthog/ui/features/sessions/sessionStore";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";+import { track } from "@posthog/ui/shell/analytics";import { useCallback, useState } from "react";export interface PendingModelSwitch {@@ -22,8 +24,9 @@ interface UsePendingModelSwitchInput {* before any prompt, so this must track conversation content, not raw events.*/hasConversationStarted: boolean;+ contextTokens?: number;/** Applies the queued switch unchanged once the dialog is confirmed. */- onApply: (configId: string, value: string) => void;+ onApply: (configId: string, value: string) => Promise<boolean>;}interface UsePendingModelSwitchResult {@@ -33,7 +36,7 @@ interface UsePendingModelSwitchResult {* the change was intercepted, so the caller must not apply it itself.*/interceptModelSwitch: (configId: string, value: string) => boolean;- confirmModelSwitch: () => void;+ confirmModelSwitch: () => Promise<boolean>;cancelModelSwitch: () => void;}@@ -46,6 +49,7 @@ export function usePendingModelSwitch({taskId,sessionModelOption,hasConversationStarted,+ contextTokens,onApply,}: UsePendingModelSwitchInput): UsePendingModelSwitchResult {const warnOnMidSessionModelSwitch = useSettingsStore(@@ -77,28 +81,61 @@ export function usePendingModelSwitch({const nameOf = (modelValue: string) =>modelOptions.find((option) => option.value === modelValue)?.name ??modelValue;- setPendingModelSwitch({+ const nextSwitch = {configId,value,label: nameOf(value),fromValue: sessionModelOption.currentValue,fromLabel: nameOf(sessionModelOption.currentValue),+ };+ setPendingModelSwitch(nextSwitch);+ track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_SHOWN, {+ task_id: taskId,+ from_model: nextSwitch.fromValue,+ to_model: nextSwitch.value,+ context_tokens: contextTokens,});return true;},- [warnOnMidSessionModelSwitch, hasConversationStarted, sessionModelOption],+ [+ warnOnMidSessionModelSwitch,+ hasConversationStarted,+ sessionModelOption,+ taskId,+ contextTokens,+ ],);- const confirmModelSwitch = useCallback(() => {- if (pendingModelSwitch) {- onApply(pendingModelSwitch.configId, pendingModelSwitch.value);- }- setPendingModelSwitch(null);- }, [pendingModelSwitch, onApply]);+ const confirmModelSwitch = useCallback(async () => {+ if (!pendingModelSwitch) return false;+ const succeeded = await onApply(+ pendingModelSwitch.configId,+ pendingModelSwitch.value,+ );+ track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {+ task_id: taskId,+ from_model: pendingModelSwitch.fromValue,+ to_model: pendingModelSwitch.value,+ context_tokens: contextTokens,+ action: "switch_now",+ result: succeeded ? "succeeded" : "failed",+ });+ if (succeeded) setPendingModelSwitch(null);+ return succeeded;+ }, [pendingModelSwitch, onApply, taskId, contextTokens]);const cancelModelSwitch = useCallback(() => {+ if (pendingModelSwitch) {+ track(ANALYTICS_EVENTS.MODEL_SWITCH_WARNING_ACTION, {+ task_id: taskId,+ from_model: pendingModelSwitch.fromValue,+ to_model: pendingModelSwitch.value,+ context_tokens: contextTokens,+ action: "cancel",+ });+ }setPendingModelSwitch(null);- }, []);+ }, [pendingModelSwitch, taskId, contextTokens]);return {pendingModelSwitch,diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex 4f369dcad6be..596eb5b4543a 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -9420,12 +9420,13 @@ describe("SessionService", () => {const service = getSessionService();mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);- await service.setSessionConfigOption(+ const result = await service.setSessionConfigOption("task-123","model","claude-3-sonnet",);+ expect(result).toBe(false);expect(mockTrpcAgent.setConfigOption.mutate).not.toHaveBeenCalled();});@@ -9472,12 +9473,13 @@ describe("SessionService", () => {}),);- await service.setSessionConfigOption(+ const result = await service.setSessionConfigOption("task-123","model","claude-3-sonnet",);+ expect(result).toBe(true);// Optimistic updateexpect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith("run-123",@@ -9535,8 +9537,13 @@ describe("SessionService", () => {new Error("Failed"),);- await service.setSessionConfigOption("task-123", "mode", "acceptEdits");+ const result = await service.setSessionConfigOption(+ "task-123",+ "mode",+ "acceptEdits",+ );+ expect(result).toBe(false);expect(currentSession.configOptions).toEqual([expect.objectContaining({id: "mode",@@ -9648,8 +9655,13 @@ describe("SessionService", () => {}),);- await service.setSessionConfigOption("task-123", "mode", "acceptEdits");+ const result = await service.setSessionConfigOption(+ "task-123",+ "mode",+ "acceptEdits",+ );+ expect(result).toBe(false);expect(mockTrpcAgent.setConfigOption.mutate).not.toHaveBeenCalled();expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledTimes(1);expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(