: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
fix(desktop): disable own-plan billing for cloud tasks (#93070)
Shy Alter59fd3c1e13fc
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsxindex e0df4f377013..c2611a4cbe1d 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx@@ -566,6 +566,7 @@ export const ChannelHomeComposer = forwardRef<workspaceMode,)}showBillingMenu+ workspaceMode={workspaceMode}disabled={isBusy}isLoading={isLoading}/>diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.stories.tsxindex a4ee1e5f92b1..42807b5679be 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.stories.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.stories.tsx@@ -1,5 +1,12 @@import type { SessionConfigOption } from "@agentclientprotocol/sdk";-import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";+import {+ subscriptionModelAccess,+ type WorkspaceModeForAccess,+} from "@posthog/ui/features/settings/adapterSubscription";+import {+ type AgentAdapter,+ useSettingsStore,+} from "@posthog/ui/features/settings/settingsStore";import type { Meta, StoryObj } from "@storybook/react-vite";import { type ReactElement, useState } from "react";import { within } from "storybook/test";@@ -101,17 +108,41 @@ function contextWindowOption(): SessionConfigOption {} as unknown as SessionConfigOption;}-function Harness(): ReactElement {- const [adapter, setAdapter] = useState<AgentAdapter>("claude");+function Harness({+ workspaceMode,+ subscriptionOn = false,+ billingAdapter = "claude",+}: {+ workspaceMode?: WorkspaceModeForAccess;+ /** Provider picked in the Billing menu; true reveals the logged-out login note. */+ subscriptionOn?: boolean;+ /** Adapter whose Billing submenu is shown. */+ billingAdapter?: AgentAdapter;+}): ReactElement {+ const [, setAdapter] = useState<AgentAdapter>("claude");const [model, setModel] = useState("claude-opus-5");const [effort, setEffort] = useState("medium");+ // The submenu reads the real useAdapterSubscription hook, which reads the+ // settings store; the modelAccess prop below only gates the model list.+ const store = useSettingsStore.getState();+ store.setClaudeModelAccess(+ billingAdapter === "claude" && subscriptionOn+ ? "own-subscription"+ : "posthog-gateway",+ );+ store.setCodexModelAccess(+ billingAdapter === "codex" && subscriptionOn+ ? "own-subscription"+ : "posthog-gateway",+ );+return (<div className="flex h-[520px] items-end p-2"><ReasoningLevelSelectorthoughtOption={effortOption(effort)}modelOption={groupedModelOption(model)}- adapter={adapter}+ adapter={billingAdapter}contextWindowOption={contextWindowOption()}onChange={setEffort}onModelChange={setModel}@@ -121,6 +152,27 @@ function Harness(): ReactElement {setModel(nextModel);}}onConfigOptionChange={() => {}}+ showBillingMenu={workspaceMode !== undefined}+ workspaceMode={workspaceMode}+ // Storybook never resolves the subscription status query, so the+ // provider counts as not logged in; the store write above picks the+ // billing shown in the submenu.+ modelAccess={+ workspaceMode === undefined+ ? undefined+ : subscriptionModelAccess(+ {+ flagEnabled: true,+ subscriptionOn,+ status: undefined,+ loggedIn: false,+ loginState: "unknown",+ needsConnection: subscriptionOn,+ setSubscriptionOn: () => {},+ },+ workspaceMode,+ )+ }/></div>);@@ -149,3 +201,94 @@ export const GroupedModelSubmenu: Story = {await body.findByText("GPT-5.6 Sol");},};++async function openBillingSubmenu(+ canvas: ReturnType<typeof within>,+ canvasElement: HTMLElement,+ userEvent: {+ click: (el: HTMLElement) => Promise<void>;+ hover: (el: HTMLElement) => Promise<void>;+ },+): Promise<void> {+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ canvas.getByRole("button", { name: /Model and reasoning/ }),+ );+ // An off-ladder combo opens straight on the Advanced view, with no toggle.+ const advanced = body.queryByRole("button", { name: "Advanced" });+ if (advanced) {+ await userEvent.click(advanced);+ }+ await userEvent.click(await body.findByRole("menuitem", { name: /Billing/ }));+}++function BillingHarnessLocal(): ReactElement {+ return <Harness workspaceMode="local" />;+}++function BillingHarnessCloud(): ReactElement {+ return <Harness workspaceMode="cloud" />;+}++function BillingHarnessLoginPrompt(): ReactElement {+ return <Harness workspaceMode="local" subscriptionOn />;+}++export const LocalBilling: StoryObj<typeof BillingHarnessLocal> = {+ render: () => <BillingHarnessLocal />,+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await openBillingSubmenu(canvas, canvasElement, userEvent);+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole("menuitemradio", { name: "PostHog" });+ await body.findByRole("menuitemradio", { name: "Anthropic" });+ },+};++export const LoginPromptBilling: StoryObj<typeof BillingHarnessLoginPrompt> = {+ render: () => <BillingHarnessLoginPrompt />,+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await openBillingSubmenu(canvas, canvasElement, userEvent);+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole("button", { name: "Log in to Claude Code" });+ await body.findByText(+ (_, element) =>+ element?.textContent ===+ "Log in to Claude Code to use Anthropic billing.",+ );+ },+};++function BillingHarnessCodexLoginPrompt(): ReactElement {+ return (+ <Harness workspaceMode="local" subscriptionOn billingAdapter="codex" />+ );+}++export const LoginPromptBillingCodex: StoryObj<+ typeof BillingHarnessCodexLoginPrompt+> = {+ render: () => <BillingHarnessCodexLoginPrompt />,+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await openBillingSubmenu(canvas, canvasElement, userEvent);+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole("menuitemradio", { name: "OpenAI" });+ await body.findByRole("button", { name: "Connect ChatGPT" });+ await body.findByText(+ (_, element) =>+ element?.textContent === "Connect ChatGPT to use OpenAI billing.",+ );+ },+};++export const CloudBilling: StoryObj<typeof BillingHarnessCloud> = {+ render: () => <BillingHarnessCloud />,+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await openBillingSubmenu(canvas, canvasElement, userEvent);+ const body = within(canvasElement.ownerDocument.body);+ const provider = await body.findByRole("menuitemradio", {+ name: "Anthropic",+ });+ await userEvent.hover(provider);+ await body.findByText(/Anthropic billing only works/);+ },+};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.tsxindex 9d99148a06ab..476b3b81dd12 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@@ -6,6 +6,7 @@ import {import { Theme } from "@radix-ui/themes";import { configure, fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { cloneElement } from "react";import { describe, expect, it, vi } from "vitest";import { ReasoningLevelSelector } from "./ReasoningLevelSelector";@@ -19,6 +20,75 @@ vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({useFeatureFlag: () => true,}));+const useAdapterSubscription = vi.hoisted(() => vi.fn());+const applyModelAccess = vi.hoisted(() => vi.fn());+vi.mock(+ "@posthog/ui/features/settings/adapterSubscription",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@posthog/ui/features/settings/adapterSubscription")+ >();+ return {+ ...actual,+ useAdapterSubscription,+ // The real one writes the settings store and resolves the analytics+ // service, which no test container provides; the click path only needs+ // the menu to keep rendering.+ applyModelAccess,+ };+ },+);++// Base UI tooltips never open under jsdom's zero layout, so render their+// content unconditionally and assert on it directly (see TaskHeaderActions+// tests for the same trick). Triggers keep honoring their `render` prop —+// children are merged into the rendered element, as real Base UI does.+vi.mock("@posthog/quill", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@posthog/quill")>();+ const passthrough = ({ children }: { children: React.ReactNode }) => children;+ const renderPassthrough = ({+ children,+ render,+ }: {+ children?: React.ReactNode;+ render?: React.ReactElement;+ }) =>+ render && children+ ? cloneElement(render, undefined, children)+ : (render ?? children);+ return {+ ...actual,+ TooltipProvider: passthrough,+ Tooltip: passthrough,+ TooltipTrigger: renderPassthrough,+ TooltipContent: passthrough,+ };+});++function subscriptionState(+ overrides?: Partial<{+ flagEnabled: boolean;+ subscriptionOn: boolean;+ loggedIn: boolean;+ }>,+) {+ const state = {+ flagEnabled: true,+ subscriptionOn: true,+ loggedIn: true,+ status: { loginState: "logged-in" as const },+ loginState: "logged-in" as const,+ needsConnection: false,+ setSubscriptionOn: () => {},+ ...overrides,+ };+ // Mirror the real hook: the connection is only "needed" once the+ // subscription is picked while logged out.+ state.needsConnection = state.subscriptionOn && !state.loggedIn;+ return state;+}+const ultracodeDocsUrl = "https://code.claude.com/docs/en/workflows";function thoughtOption(@@ -788,4 +858,112 @@ describe("ReasoningLevelSelector", () => {expect(onModelChange).toHaveBeenCalledWith("@cf/zai-org/glm-5.2");}, 20000);++ it.each([+ ["claude", "Anthropic", "Anthropic"],+ ["codex", "OpenAI", "OpenAI"],+ ] as const)(+ "disables the %s billing option for cloud tasks and names the reason",+ async (adapter, planLabel, reasonPrefix) => {+ useAdapterSubscription.mockReturnValue(subscriptionState());+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ render(+ <Theme>+ <ReasoningLevelSelector+ thoughtOption={thoughtOption()}+ adapter={adapter}+ showBillingMenu+ workspaceMode="cloud"+ />+ </Theme>,+ );++ await openAdvanced(user);+ await openSub(user, /^Billing/);+ const planItem = screen.getByRole("menuitemradio", {+ name: planLabel,+ });+ expect(planItem).toHaveAttribute("aria-disabled", "true");++ await expect(+ screen.findByText(new RegExp(`^${reasonPrefix} billing only works`)),+ ).resolves.toBeInTheDocument();+ },+ 20000,+ );++ it("keeps the billing option selectable for local tasks", async () => {+ useAdapterSubscription.mockReturnValue(subscriptionState());+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ render(+ <Theme>+ <ReasoningLevelSelector+ thoughtOption={thoughtOption()}+ adapter="claude"+ showBillingMenu+ workspaceMode="local"+ />+ </Theme>,+ );++ await openAdvanced(user);+ await openSub(user, /^Billing/);+ expect(+ screen.getByRole("menuitemradio", { name: "Anthropic" }),+ ).not.toHaveAttribute("aria-disabled", "true");+ // Logged in, so the login note stays hidden.+ expect(screen.queryByText(/Log in to Claude Code/)).not.toBeInTheDocument();+ }, 20000);++ it("shows the login note only when the logged-out billing pick needs it", async () => {+ // Persisted billing is PostHog, account is logged out: no login prompt.+ useAdapterSubscription.mockReturnValue(+ subscriptionState({ subscriptionOn: false, loggedIn: false }),+ );+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ const { unmount } = render(+ <Theme>+ <ReasoningLevelSelector+ thoughtOption={thoughtOption()}+ adapter="claude"+ showBillingMenu+ workspaceMode="local"+ />+ </Theme>,+ );++ await openAdvanced(user);+ await openSub(user, /^Billing/);+ expect(screen.queryByText(/Log in to Claude Code/)).not.toBeInTheDocument();+ unmount();++ // Billing picked while logged out: the quiet login note appears.+ useAdapterSubscription.mockReturnValue(+ subscriptionState({ subscriptionOn: true, loggedIn: false }),+ );+ render(+ <Theme>+ <ReasoningLevelSelector+ thoughtOption={thoughtOption()}+ adapter="claude"+ showBillingMenu+ workspaceMode="local"+ />+ </Theme>,+ );++ await openAdvanced(user);+ await openSub(user, /^Billing/);+ expect(+ await screen.findByRole("button", { name: "Log in to Claude Code" }),+ ).toBeInTheDocument();+ // One sentence, no separate "Log in" row: the link carries the whole note.+ expect(+ screen.getByText(+ (_, element) =>+ element?.textContent ===+ "Log in to Claude Code to use Anthropic billing.",+ ),+ ).toBeInTheDocument();+ }, 20000);});diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsxindex 38753314771b..97c22688e966 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx@@ -37,6 +37,7 @@ import {} from "@posthog/ui/features/sessions/components/HarnessSubmenu";import { ModelSelectList } from "@posthog/ui/features/sessions/components/ModelSelectList";import { SubscriptionSubmenu } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";+import type { WorkspaceModeForAccess } from "@posthog/ui/features/settings/adapterSubscription";import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";import { AnimatedHeight } from "@posthog/ui/primitives/AnimatedHeight";import { Spinner } from "@posthog/ui/primitives/Spinner";@@ -77,6 +78,8 @@ interface ReasoningLevelSelectorProps {isLoading?: boolean;modelAccess?: ModelAccess;showBillingMenu?: boolean;+ /** Workspace mode of the task being composed; cloud disables plan billing. */+ workspaceMode?: WorkspaceModeForAccess;}function toDropdownOptions(@@ -115,6 +118,7 @@ export function ReasoningLevelSelector({isLoading,modelAccess,showBillingMenu,+ workspaceMode,}: ReasoningLevelSelectorProps) {const [internalMenuOpen, setInternalMenuOpen] = useState(false);const open = menuOpen ?? internalMenuOpen;@@ -146,7 +150,7 @@ export function ReasoningLevelSelector({adapter === "claude" && modelAccess === "own-subscription";const unavailableReason = (modelId: string): string | undefined =>onOwnSubscription && !isAnthropicModelId(modelId)- ? "Your Claude plan cannot run this model. Change billing to PostHog credits to use it."+ ? "Anthropic billing cannot run this model. Change billing to PostHog to use it.": undefined;const handleHarnessSelect = (harness: AgentHarness) => {@@ -490,7 +494,10 @@ export function ReasoningLevelSelector({/>)}{showBillingMenu && adapter && (- <SubscriptionSubmenu adapter={adapter} />+ <SubscriptionSubmenu+ adapter={adapter}+ workspaceMode={workspaceMode}+ />)}{hasEffort && (<DropdownMenuSub>diff --git a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsxindex c8838d945136..a46fa79e6b64 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx@@ -1,27 +1,36 @@-import { SignIn } from "@phosphor-icons/react";import {- DropdownMenuItem,DropdownMenuRadioGroup,DropdownMenuRadioItem,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,} from "@posthog/quill";import type { Adapter, ModelAccess } from "@posthog/shared";import {applyModelAccess,useAdapterSubscription,+ type WorkspaceModeForAccess,} from "@posthog/ui/features/settings/adapterSubscription";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";-const PLAN_LABEL: Record<Adapter, string> = {- claude: "Your Claude plan",- codex: "Your ChatGPT plan",+const PROVIDER_LABEL: Record<Adapter, string> = {+ claude: "Anthropic",+ codex: "OpenAI",};-const LOGIN_LABEL: Record<Adapter, string> = {- claude: "Log in to Claude Code",- codex: "Log in to ChatGPT",+const LOGIN_NOTE: Record<Adapter, { link: string; rest: string }> = {+ claude: {+ link: "Log in to Claude Code",+ rest: " to use Anthropic billing.",+ },+ codex: {+ link: "Connect ChatGPT",+ rest: " to use OpenAI billing.",+ },};export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {@@ -29,28 +38,44 @@ export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {codex: "codex-login",};+const CLOUD_ONLY_REASON: Record<Adapter, string> = {+ claude:+ "Anthropic billing only works for local and worktree tasks. Cloud tasks always use PostHog.",+ codex:+ "OpenAI billing only works for local and worktree tasks. Cloud tasks always use PostHog.",+};++const TOOLTIP_DELAY_MS = 150;+interface SubscriptionSubmenuProps {adapter: Adapter;closeOnChange?: boolean;+ /** Workspace mode of the task being composed; cloud forces PostHog credits. */+ workspaceMode?: WorkspaceModeForAccess;}export function SubscriptionSubmenu({adapter,closeOnChange = false,+ workspaceMode,}: SubscriptionSubmenuProps): React.JSX.Element | null {const subscription = useAdapterSubscription(adapter);if (!subscription.flagEnabled) {return null;}- const planLabel = PLAN_LABEL[adapter];- const value: ModelAccess = subscription.subscriptionOn- ? "own-subscription"- : "posthog-gateway";+ // Cloud tasks always bill PostHog credits (see effectiveModelAccess), so the+ // provider option is disabled there instead of silently overriding the pick.+ const cloudTask = workspaceMode === "cloud";+ const providerLabel = PROVIDER_LABEL[adapter];+ const value: ModelAccess =+ cloudTask || !subscription.subscriptionOn+ ? "posthog-gateway"+ : "own-subscription";const valueLabel =- subscription.subscriptionOn && subscription.loggedIn- ? planLabel- : "PostHog credits";+ subscription.subscriptionOn && subscription.loggedIn && !cloudTask+ ? providerLabel+ : "PostHog";return (<DropdownMenuSub>@@ -77,26 +102,56 @@ export function SubscriptionSubmenu({value="posthog-gateway"closeOnClick={closeOnChange}>- PostHog credits- </DropdownMenuRadioItem>- <DropdownMenuRadioItem- value="own-subscription"- closeOnClick={closeOnChange}- disabled={!subscription.loggedIn}- >- {planLabel}+ PostHog</DropdownMenuRadioItem>+ {cloudTask ? (+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>+ <Tooltip disableHoverablePopup>+ <TooltipTrigger render={<span className="flex" />}>+ <DropdownMenuRadioItem+ value="own-subscription"+ closeOnClick={closeOnChange}+ disabled+ className="opacity-60"+ >+ {providerLabel}+ </DropdownMenuRadioItem>+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-60">+ {CLOUD_ONLY_REASON[adapter]}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : (+ <DropdownMenuRadioItem+ value="own-subscription"+ closeOnClick={closeOnChange}+ >+ {providerLabel}+ </DropdownMenuRadioItem>+ )}</DropdownMenuRadioGroup>- {subscription.loggedIn ? null : (- <DropdownMenuItem- onClick={() =>- openSettings("harness", SUBSCRIPTION_LOGIN_ACTION[adapter])- }- >- <SignIn size={12} />- {LOGIN_LABEL[adapter]}- </DropdownMenuItem>- )}+ {!cloudTask &&+ subscription.subscriptionOn &&+ !subscription.loggedIn && (+ // A quiet inline note rather than a permanent menu row: it appears+ // only once the provider option is picked without a confirmed+ // login, and sessions keep running on PostHog until the login+ // completes. Unknown status counts as not logged in, so the note+ // stays reachable when the status check cannot run or is pending.+ <div className="px-2 py-1.5 text-muted-foreground text-xs">+ <button+ type="button"+ className="underline underline-offset-2 hover:text-foreground"+ onClick={() =>+ openSettings("harness", SUBSCRIPTION_LOGIN_ACTION[adapter])+ }+ >+ {LOGIN_NOTE[adapter].link}+ </button>+ {LOGIN_NOTE[adapter].rest}+ </div>+ )}</DropdownMenuSubContent></DropdownMenuSub>);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.tsxindex 3061f083b96d..9262de095241 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@@ -1677,6 +1677,7 @@ export function TaskInput({isLoading={isPreviewLoading}modelAccess={composerModelAccess}showBillingMenu+ workspaceMode={workspaceMode}/>)}