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): spend limits with warn and stop lines (#87675)

Shy Alter934a9463ea18
diff --git a/products/desktop/packages/agent/src/agent.test.ts b/products/desktop/packages/agent/src/agent.test.ts
index f611ad10555f..65575c370ce0 100644
--- a/products/desktop/packages/agent/src/agent.test.ts
+++ b/products/desktop/packages/agent/src/agent.test.ts
@@ -123,6 +123,38 @@ describe("Agent", () => {
);
});
+ it("asserts the person's node so the gateway's per-user spend limit applies", async () => {
+ fetchMock.mockImplementation((url: unknown) =>
+ Promise.resolve({
+ ok: true,
+ json: vi
+ .fn()
+ .mockResolvedValue(
+ String(url).includes("/api/users/@me/")
+ ? { distinct_id: "user-distinct-1" }
+ : { origin_product: "posthog_code" },
+ ),
+ }),
+ );
+ const agent = new Agent({
+ posthog: {
+ apiUrl: "https://us.posthog.com",
+ getApiKey: vi.fn().mockResolvedValue("token"),
+ projectId: 7,
+ },
+ skipLogPersistence: true,
+ });
+
+ await agent.run("task-1", "run-1", { adapter: "claude" });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(config.claudeGatewayEnv?.anthropicCustomHeaders).toContain(
+ "X-PostHog-User: user-distinct-1",
+ );
+ });
+
it("does not fetch or add task attribution for preview sessions", async () => {
const agent = new Agent({
posthog: {
diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.ts
index 1e6a5e969ed8..543023f79372 100644
--- a/products/desktop/packages/agent/src/agent.ts
+++ b/products/desktop/packages/agent/src/agent.ts
@@ -2,6 +2,8 @@ import { buildPrOutput, mergePrUrls, readPrUrls } from "@posthog/shared";
import {
buildPosthogPropertyHeaderLines,
buildPosthogPropertyHeaderRecord,
+ buildPosthogUserHeaderLines,
+ buildPosthogUserHeaderRecord,
} from "@posthog/shared/posthog-property-headers";
import {
createAcpConnection,
@@ -83,13 +85,22 @@ export class Agent {
const gatewayConfig = await this._resolveGatewayConfig(options.gatewayUrl);
this.taskRunId = taskRunId;
- const task =
+ // getTask and getUserNode are independent, so start both before building
+ // attribution rather than serializing two startup round trips.
+ const taskPromise =
this.posthogAPI && taskId !== "__preview__"
- ? await this.posthogAPI.getTask(taskId).catch((error) => {
+ ? this.posthogAPI.getTask(taskId).catch((error) => {
this.logger.debug("Failed to fetch task attribution", error);
return null;
})
- : null;
+ : Promise.resolve(null);
+ // The node the gateway holds a person's spend limit against. Null (a
+ // task-scoped credential) simply carries no user node, so the limit does
+ // not apply rather than applying to the wrong person.
+ const userNodePromise =
+ this.posthogAPI?.getUserNode() ?? Promise.resolve(null);
+ const [task, userNode] = await Promise.all([taskPromise, userNodePromise]);
+
const attribution =
taskId === "__preview__"
? {}
@@ -156,8 +167,12 @@ export class Agent {
this.posthogApiConfig?.projectId != null
? String(this.posthogApiConfig.projectId)
: undefined,
- anthropicCustomHeaders:
+ anthropicCustomHeaders: [
buildPosthogPropertyHeaderLines(attribution),
+ buildPosthogUserHeaderLines(userNode),
+ ]
+ .filter(Boolean)
+ .join("\n"),
}
: undefined;
@@ -187,11 +202,14 @@ export class Agent {
reasoningEffort: options.reasoningEffort,
developerInstructions: options.developerInstructions,
httpHeaders: taskId
- ? buildPosthogPropertyHeaderRecord({
- ...attribution,
- $ai_session_id: taskId,
- })
- : undefined,
+ ? {
+ ...buildPosthogPropertyHeaderRecord({
+ ...attribution,
+ $ai_session_id: taskId,
+ }),
+ ...buildPosthogUserHeaderRecord(userNode),
+ }
+ : buildPosthogUserHeaderRecord(userNode),
additionalDirectories: options.additionalDirectories,
}
: undefined,
diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.ts
index 54d543f045ae..3832cd1fccc4 100644
--- a/products/desktop/packages/agent/src/posthog-api.test.ts
+++ b/products/desktop/packages/agent/src/posthog-api.test.ts
@@ -46,6 +46,24 @@ describe("PostHogAPIClient", () => {
expect(mockFetch).toHaveBeenCalledTimes(2);
});
+ // The lookup gates session start, so a stalled socket must degrade to null
+ // rather than hang. The bound is what makes the best-effort catch reachable.
+ it("bounds the user-node lookup and returns null when it times out", async () => {
+ const client = new PostHogAPIClient({
+ apiUrl: "https://app.posthog.com",
+ getApiKey: vi.fn().mockResolvedValue("token"),
+ projectId: 1,
+ });
+ mockFetch.mockRejectedValue(
+ new DOMException("The operation was aborted.", "TimeoutError"),
+ );
+
+ await expect(client.getUserNode()).resolves.toBeNull();
+
+ const init = mockFetch.mock.calls[0]?.[1] as RequestInit | undefined;
+ expect(init?.signal).toBeInstanceOf(AbortSignal);
+ });
+
it("loads policies for managed MCP servers and keeps unmanaged servers", async () => {
const client = new PostHogAPIClient({
apiUrl: "https://app.posthog.com",
diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.ts
index 8a511418fa4f..de903393bd9d 100644
--- a/products/desktop/packages/agent/src/posthog-api.ts
+++ b/products/desktop/packages/agent/src/posthog-api.ts
@@ -124,6 +124,7 @@ export type TaskRunUpdate = Partial<
export class PostHogAPIClient {
private config: PostHogAPIConfig;
+ private userNode: string | null | undefined;
constructor(config: PostHogAPIConfig) {
this.config = config;
@@ -222,6 +223,35 @@ export class PostHogAPIClient {
return getLlmGatewayUrl(this.baseUrl);
}
+ /**
+ * The gateway user node for the signed-in person, or null when the credential
+ * resolves to no user (a task-scoped token). This is the distinct id, not the
+ * uuid: it has to match what a per-person spend limit is keyed on and what a
+ * cloud run pins into its token, so the `user_{id}` fallback mirrors
+ * products/ai_gateway/backend/logic.py (_spend_node) exactly — diverging from it writes a
+ * budget nothing debits. Successful lookups are cached, since the node never
+ * changes for a credential; a failed lookup is not, so a startup network blip
+ * doesn't permanently disable the spend-limit header.
+ */
+ async getUserNode(): Promise<string | null> {
+ if (this.userNode !== undefined) return this.userNode;
+ try {
+ const user = await this.apiRequest<{
+ id?: number;
+ distinct_id?: string;
+ }>("/api/users/@me/", {
+ // Best-effort header on session start: bound the request so a stalled
+ // socket can't hold up the run. The catch below then returns null.
+ signal: AbortSignal.timeout(API_TRANSFER_TIMEOUT_MS),
+ });
+ this.userNode =
+ user.distinct_id || (user.id != null ? `user_${user.id}` : null);
+ } catch {
+ return null;
+ }
+ return this.userNode;
+ }
+
async getTask(taskId: string): Promise<Task> {
const teamId = this.getTeamId();
return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`);
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index ed925a66df38..74453b23b3c0 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -10,6 +10,37 @@ import {
} from "./posthog-client";
describe("PostHogAPIClient", () => {
+ describe("setUserSpendLimit", () => {
+ // The shared fetcher throws on non-2xx, so the endpoint's `detail` must be
+ // unwrapped for the settings toast rather than the raw fetcher string.
+ it("surfaces the endpoint detail when the gateway rejects the limit", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(
+ JSON.stringify({ detail: "Limit must be above current spend." }),
+ { status: 400, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ const error = await client
+ .setUserSpendLimit(10, 30 * 24 * 60 * 60)
+ .catch((e: unknown) => e);
+ // The exact clean detail, not the raw `Failed request: [400] {...}`.
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toBe(
+ "Limit must be above current spend.",
+ );
+ });
+ });
+
describe("getInsightDefinition", () => {
it("loads the saved insight with a blocking refresh and returns its result", async () => {
const fetch = vi.fn().mockResolvedValue(
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 98ca16725a60..801865d7bb0a 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -125,6 +125,7 @@ import type {
TeamMcpGatewayConfigUpdate,
} from "./mcp-gateway";
import type { SpendAnalysisResponse } from "./spend-analysis";
+import { parseUserSpendLimit, type UserSpendLimit } from "./spend-limit";
import {
normalizeTaskResponse,
normalizeTaskRunArtifact,
@@ -6272,6 +6273,60 @@ export class PostHogAPIClient {
return (await response.json()) as SpendAnalysisResponse;
}
+ /**
+ * The signed-in person's own spend limit, as the gateway holds it. A
+ * deployment without the gateway wired answers `available: false` rather than
+ * failing, so the settings page can say the limit informs only.
+ */
+ async getUserSpendLimit(): Promise<UserSpendLimit> {
+ return parseUserSpendLimit(await this.spendLimitRequest("get"));
+ }
+
+ /** Sets the limit; `windowSeconds` is the window it resets over. */
+ async setUserSpendLimit(
+ limitUsd: number,
+ windowSeconds: number,
+ ): Promise<UserSpendLimit> {
+ return parseUserSpendLimit(
+ await this.spendLimitRequest("post", "", {
+ limit_usd: String(limitUsd),
+ window_seconds: windowSeconds,
+ }),
+ );
+ }
+
+ /** Removes the limit, so nothing holds this person's spend. */
+ async clearUserSpendLimit(): Promise<UserSpendLimit> {
+ return parseUserSpendLimit(
+ await this.spendLimitRequest("delete", "clear/"),
+ );
+ }
+
+ private async spendLimitRequest(
+ method: "get" | "post" | "delete",
+ suffix = "",
+ body?: Record<string, unknown>,
+ ): Promise<unknown> {
+ const teamId = await this.getTeamId();
+ const urlPath = `/api/projects/${teamId}/ai_gateway/@me/spend_limit/${suffix}`;
+ // The shared fetcher throws `Failed request: [<status>] <json-body>` for any
+ // non-2xx, so unwrap that into the endpoint's clean message rather than
+ // surfacing the raw string in the settings toast.
+ try {
+ const response = await this.api.fetcher.fetch({
+ method,
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ ...(body ? { overrides: { body: JSON.stringify(body) } } : {}),
+ });
+ return await response.json();
+ } catch (error) {
+ throw new Error(
+ extractRequestErrorMessage(error, "Couldn't update your spend limit."),
+ );
+ }
+ }
+
/**
* Lists the team's LLM skills (latest versions, no bodies).
* Returns null when the feature is unavailable for this org (the
diff --git a/products/desktop/packages/api-client/src/spend-limit.ts b/products/desktop/packages/api-client/src/spend-limit.ts
new file mode 100644
index 000000000000..482ec9b82f49
--- /dev/null
+++ b/products/desktop/packages/api-client/src/spend-limit.ts
@@ -0,0 +1,37 @@
+/** A person's own spend limit for model traffic through the gateway. */
+export interface UserSpendLimit {
+ /** The limit in USD, or null when none is set. */
+ limitUsd: number | null;
+ /** Length of the accounting window in seconds; null with no limit. */
+ windowSeconds: number | null;
+ /**
+ * The deployment can hold a spend cap. False means a stop line cannot be
+ * set at all, so the app offers warning lines only.
+ */
+ available: boolean;
+}
+
+interface UserSpendLimitPayload {
+ limit_usd?: string | null;
+ window_seconds?: number | null;
+ available?: boolean;
+}
+
+export function parseUserSpendLimit(payload: unknown): UserSpendLimit {
+ const body = (payload ?? {}) as UserSpendLimitPayload;
+ let limitUsd: number | null = null;
+ if (body.limit_usd != null) {
+ limitUsd = Number(body.limit_usd);
+ if (!Number.isFinite(limitUsd)) {
+ // Coercing a malformed limit to null would show "no limit" while one exists.
+ throw new Error(
+ "Couldn't read the spend limit from the server response.",
+ );
+ }
+ }
+ return {
+ limitUsd,
+ windowSeconds: body.window_seconds ?? null,
+ available: body.available === true,
+ };
+}
diff --git a/products/desktop/packages/core/src/billing/costChecklist.test.ts b/products/desktop/packages/core/src/billing/costChecklist.test.ts
new file mode 100644
index 000000000000..6b29390cb5fd
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/costChecklist.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildCostChecklist,
+ type CostChecklistInput,
+ modelNotchSuggestion,
+} from "./costChecklist";
+
+const base: CostChecklistInput = {
+ defaultModelId: "claude-sonnet-5",
+ hasCustomImage: false,
+ skills: [],
+ completed: [],
+};
+
+describe("buildCostChecklist", () => {
+ it("recommends an image when there is none, whatever else is set up", () => {
+ expect(buildCostChecklist(base)).toEqual([
+ { kind: "custom-image", done: false },
+ ]);
+ });
+
+ it("checks the image row off the image itself, not a stored completion", () => {
+ expect(buildCostChecklist({ ...base, hasCustomImage: true })).toEqual([
+ { kind: "custom-image", done: true },
+ ]);
+ // A build that was started and then failed or deleted leaves the stored
+ // kind behind; the row must go back to unchecked all the same.
+ expect(
+ buildCostChecklist({ ...base, completed: ["custom-image"] }),
+ ).toEqual([{ kind: "custom-image", done: false }]);
+ });
+
+ it("omits the image row when the account is not known or custom images are off", () => {
+ // Null means unavailable or not yet loaded, so no image row appears at all
+ // rather than a suggestion the user cannot act on.
+ expect(buildCostChecklist({ ...base, hasCustomImage: null })).toEqual([]);
+ expect(
+ buildCostChecklist({
+ ...base,
+ hasCustomImage: null,
+ completed: ["custom-image"],
+ }),
+ ).toEqual([]);
+ });
+
+ it("keeps a completed item as a checked record and sinks it below active work", () => {
+ const items = buildCostChecklist({
+ ...base,
+ defaultModelId: "claude-sonnet-5",
+ completed: ["model-notch"],
+ });
+ expect(items).toEqual([
+ { kind: "custom-image", done: false },
+ { kind: "model-notch", done: true, modelId: "claude-sonnet-5" },
+ ]);
+ });
+
+ it("re-fires the suggestion when the default still warrants one after completion", () => {
+ const items = buildCostChecklist({
+ ...base,
+ defaultModelId: "claude-opus-5",
+ hasCustomImage: true,
+ completed: ["model-notch"],
+ });
+ // A stored completion does not hold the row checked once the current
+ // default is expensive again; the cheaper-model suggestion comes back.
+ expect(items).toEqual([
+ {
+ kind: "model-notch",
+ done: false,
+ fromModelId: "claude-opus-5",
+ toModelId: "claude-sonnet-5",
+ },
+ { kind: "custom-image", done: true },
+ ]);
+ });
+
+ it("gives every skill its own row, installed ones below the rest", () => {
+ expect(
+ buildCostChecklist({
+ ...base,
+ hasCustomImage: true,
+ skills: [
+ { skillId: "ponytail", name: "Ponytail", installed: true },
+ {
+ skillId: "context-budget",
+ name: "Context budget",
+ installed: false,
+ },
+ ],
+ }),
+ ).toEqual([
+ {
+ kind: "install-skill",
+ done: false,
+ skillId: "context-budget",
+ name: "Context budget",
+ },
+ { kind: "custom-image", done: true },
+ {
+ kind: "install-skill",
+ done: true,
+ skillId: "ponytail",
+ name: "Ponytail",
+ },
+ ]);
+ });
+});
+
+describe("modelNotchSuggestion", () => {
+ it.each([
+ [
+ "claude-opus-5",
+ { fromModelId: "claude-opus-5", toModelId: "claude-sonnet-5" },
+ ],
+ [
+ "claude-fable-5",
+ { fromModelId: "claude-fable-5", toModelId: "claude-opus-5" },
+ ],
+ // Already at the cheapest priced rung on its ladder.
+ ["claude-sonnet-5", null],
+ // Below the trigger multiplier.
+ ["claude-haiku-4-5", null],
+ // No default set, and models with no known list price.
+ [null, null],
+ ["some-unpriced-model", null],
+ ] as const)("%s", (modelId, expected) => {
+ expect(modelNotchSuggestion(modelId)).toEqual(expected);
+ });
+
+ it("suggests a cheaper model on the codex ladder", () => {
+ // Sol matches gpt-5.5 per token, so the notch down is the cheaper Terra.
+ expect(modelNotchSuggestion("gpt-5.5")).toEqual({
+ fromModelId: "gpt-5.5",
+ toModelId: "gpt-5.6-terra",
+ });
+ });
+});
diff --git a/products/desktop/packages/core/src/billing/costChecklist.ts b/products/desktop/packages/core/src/billing/costChecklist.ts
new file mode 100644
index 000000000000..855c1e16179d
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/costChecklist.ts
@@ -0,0 +1,159 @@
+import type { Adapter } from "@posthog/shared";
+import { getCapabilityLadder } from "@posthog/shared";
+import { modelCostMultiplier } from "./modelPricing";
+
+/**
+ * The Cost management checklist.
+ *
+ * An item exists because there is a change to make, and its button makes it.
+ * Whether it reads as a suggestion or as a check is derived from the current
+ * setup, not from a stored record of the button having been clicked. Acting on
+ * an item moves it out of the active list and into the checked records below.
+ */
+
+export type CostChecklistItemKind =
+ | "model-notch"
+ | "custom-image"
+ | "install-skill";
+
+export type CostChecklistItem =
+ | {
+ kind: "model-notch";
+ done: false;
+ fromModelId: string;
+ toModelId: string;
+ }
+ | { kind: "model-notch"; done: true; modelId: string }
+ | { kind: "custom-image"; done: boolean }
+ | { kind: "install-skill"; done: boolean; skillId: string; name: string };
+
+/**
+ * A default model at or above this per-token multiple of the baseline earns
+ * a "move down a notch" recommendation. 2.5× is the Opus-class rate, the
+ * lowest tier where the everyday-task premium is large enough to point out.
+ */
+const MODEL_NOTCH_TRIGGER_MULTIPLIER = 2.5;
+
+export interface ModelNotchSuggestion {
+ fromModelId: string;
+ toModelId: string;
+}
+
+function adapterForModel(modelId: string): Adapter {
+ return modelId.toLowerCase().includes("gpt") ? "codex" : "claude";
+}
+
+/**
+ * The next capability notch down from the user's default model: the most
+ * capable model on the adapter's ladder with a strictly lower per-token
+ * multiplier. Null when the default is unset, unpriced, already below the
+ * trigger, or nothing on the ladder is cheaper, so the suggestion is always
+ * derived from the ladder and always strictly cheaper.
+ */
+export function modelNotchSuggestion(
+ defaultModelId: string | null,
+): ModelNotchSuggestion | null {
+ if (!defaultModelId) return null;
+ const currentMultiplier = modelCostMultiplier(defaultModelId);
+ if (
+ currentMultiplier === null ||
+ currentMultiplier < MODEL_NOTCH_TRIGGER_MULTIPLIER
+ ) {
+ return null;
+ }
+ const ladder = getCapabilityLadder(adapterForModel(defaultModelId));
+ const models = [...new Set(ladder.map((notch) => notch.model))];
+ for (let index = models.length - 1; index >= 0; index--) {
+ const model = models[index];
+ if (model === undefined) continue;
+ const multiplier = modelCostMultiplier(model);
+ if (multiplier !== null && multiplier < currentMultiplier) {
+ return { fromModelId: defaultModelId, toModelId: model };
+ }
+ }
+ return null;
+}
+
+export interface CostChecklistInput {
+ /** The model new sessions start on, or null when the user has not picked one. */
+ defaultModelId: string | null;
+ /**
+ * True when a ready custom image exists, false when custom images are
+ * available but none is ready, null when they are unavailable or not yet
+ * loaded. Null omits the row rather than advertising a build the user
+ * cannot start.
+ */
+ hasCustomImage: boolean | null;
+ /**
+ * Every skill worth a row, in ranked order, each already resolved to
+ * whether it is present locally.
+ */
+ skills: readonly { skillId: string; name: string; installed: boolean }[];
+ /** Item kinds the user has already acted on, which stay as checked records. */
+ completed: readonly CostChecklistItemKind[];
+}
+
+/**
+ * Builds the list in reading order: what to do now, then what was done. An
+ * item appears only when its trigger fires or when it was completed.
+ */
+export function buildCostChecklist({
+ defaultModelId,
+ hasCustomImage,
+ skills,
+ completed,
+}: CostChecklistInput): CostChecklistItem[] {
+ const isDone = (kind: CostChecklistItemKind) => completed.includes(kind);
+ const active: CostChecklistItem[] = [];
+ const finished: CostChecklistItem[] = [];
+
+ // A completed model-notch reads as a checked row only while the current
+ // default no longer warrants a cheaper model. Picking an expensive model
+ // again — which every composer picker does — re-fires the suggestion instead
+ // of leaving a stale checked row that claims a move that no longer holds.
+ const notchSuggestion = modelNotchSuggestion(defaultModelId);
+ if (isDone("model-notch") && !notchSuggestion) {
+ if (defaultModelId) {
+ finished.push({
+ kind: "model-notch",
+ done: true,
+ modelId: defaultModelId,
+ });
+ }
+ } else if (notchSuggestion) {
+ active.push({ kind: "model-notch", done: false, ...notchSuggestion });
+ }
+
+ // The image itself is the record, so this row reads the account rather than
+ // a stored completion: a build that was started and then failed or deleted
+ // leaves nothing behind, and the recommendation comes back. Null means the
+ // account is not known yet or custom images are off, so no row is shown.
+ if (hasCustomImage === true) {
+ finished.push({ kind: "custom-image", done: true });
+ } else if (hasCustomImage === false) {
+ active.push({ kind: "custom-image", done: false });
+ }
+
+ // Installing is its own record, so these rows follow the skill list rather
+ // than a stored completion. An installed one stays as a checked row so it
+ // can be uninstalled from the same place it was added.
+ for (const skill of skills) {
+ if (skill.installed) {
+ finished.push({
+ kind: "install-skill",
+ done: true,
+ skillId: skill.skillId,
+ name: skill.name,
+ });
+ } else {
+ active.push({
+ kind: "install-skill",
+ done: false,
+ skillId: skill.skillId,
+ name: skill.name,
+ });
+ }
+ }
+
+ return [...active, ...finished];
+}
diff --git a/products/desktop/packages/core/src/billing/leanSkills.ts b/products/desktop/packages/core/src/billing/leanSkills.ts
new file mode 100644
index 000000000000..dfaa12f33d58
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/leanSkills.ts
@@ -0,0 +1,121 @@
+/**
+ * Skills that reduce what a run costs, ranked.
+ *
+ * Everything here installs and uninstalls in one click, so no entry has to
+ * carry setup instructions instead of a button. Every measurement is shown with
+ * the name of whoever measured it, and where an independent trial failed to
+ * reproduce a project's own figure, the trial's number is the one shown. Each
+ * description comes from the skill's own SKILL.md rather than its pitch.
+ *
+ * Deliberately absent: JetBrains/benjamin-plus-skill. Its ruleset measured
+ * -17.9% cost, the best of any of these, but it only works injected into the
+ * system prompt. Its authors measured the same text as a skill folder at
+ * -0.5%, so no one-click install can deliver it. Adopting it means shipping
+ * the rules in the prompt every harness appends, which is its own change.
+ */
+
+export interface LeanSkill {
+ name: string;
+ /** GitHub `owner/repo` the installer fetches. */
+ source: string;
+ /**
+ * Commit the installer fetches, so the content someone vetted here is the
+ * content that lands, not whatever the repository's HEAD has become.
+ * Updating a skill means re-reading it at the new commit, then bumping this.
+ */
+ ref: string;
+ /** Directory inside that repo holding SKILL.md, for the installer. */
+ skillId: string;
+ /** One line, for the row. */
+ summary: string;
+ /** How it goes about it, taken from its own instructions. */
+ approach: string;
+ /** The project's own illustration of the difference it makes. */
+ example?: { ask: string; without: string; with: string };
+ /**
+ * An independent trial's finding, always in the trial's name. A skill
+ * nobody measured carries none, and the dialog then shows none rather than
+ * a line of ours saying it is unmeasured.
+ */
+ trial?: {
+ source: string;
+ /** The figure worth scanning for, e.g. "10%". */
+ headline: string;
+ /** What that figure is, e.g. "lower cost". */
+ headlineLabel: string;
+ /** How much work it was measured over, e.g. "80 paired tasks". */
+ sample: string;
+ /** The rest of the finding, in the trial's terms. */
+ finding: string;
+ url: string;
+ };
+ license: string;
+}
+
+export const LEAN_SKILLS: readonly LeanSkill[] = [
+ {
+ name: "Ponytail",
+ source: "DietrichGebert/ponytail",
+ ref: "2ed6c52c9d7e5e56942508591085fd45dea277d3",
+ skillId: "ponytail",
+ summary:
+ "Pushes the agent toward the simplest solution, so it writes less code.",
+ approach:
+ "A ladder it climbs on every coding task, stopping at the first rung that works: does this need to exist, is it already in the codebase, does the standard library or the platform cover it, is a dependency already installed, can it be one line. Only then does it write the minimum, and it leaves a comment naming each simplification it chose.",
+ example: {
+ ask: "Asked for a date picker",
+ without: "installs a picker library and wraps it in a component",
+ with: '<input type="date">',
+ },
+ trial: {
+ source: "JetBrains",
+ headline: "10%",
+ headlineLabel: "lower cost",
+ sample: "80 paired tasks",
+ finding:
+ "No quality difference. Concentrated on larger builds, near zero on small ones.",
+ url: "https://blog.jetbrains.com/ai/2026/07/ponytail-skill-claude-tested/",
+ },
+ license: "MIT",
+ },
+ {
+ name: "Context budget",
+ source: "affaan-m/ecc",
+ ref: "d8409a4b0813771235555e32e3d8046a73988bfa",
+ skillId: "context-budget",
+ summary:
+ "Audits what is eating your context and says what to drop or load later.",
+ approach:
+ "Inventories your agents, skills, rules and MCP servers, estimates what each one costs from its word count, then sorts them into always, sometimes and rarely needed. It ends on the three changes with the largest projected saving, leaving the cutting to you.",
+ license: "MIT",
+ },
+ {
+ name: "Caveman",
+ source: "juliusbrussee/caveman",
+ ref: "7bb71309e8749a4f112aacd3a54b3941d8689905",
+ skillId: "caveman",
+ summary: "Strips filler from the agent's prose, leaving code untouched.",
+ approach:
+ "An output mode that holds for the session: articles, hedges, pleasantries, tables and tool-call narration go, and what is left is written in fragments. Code blocks, API names, commands and error strings stay verbatim, and it refuses invented abbreviations, which cost tokens rather than save them.",
+ trial: {
+ source: "JetBrains",
+ headline: "8.5%",
+ headlineLabel: "fewer output tokens",
+ sample: "82 paired tasks",
+ finding: "Cost down near 10%.",
+ url: "https://blog.jetbrains.com/ai/2026/07/speak-to-ai-agents-like-cavemen-tosave-tokens/",
+ },
+ // The repository is MIT with several runtime directories carved out under
+ // BSL-1.1. Only the MIT-covered skills directory is fetched.
+ license: "MIT (skills directory)",
+ },
+];
+
+/** The project's page, for reading more than the dialog carries. */
+export function leanSkillRepoUrl(skill: LeanSkill): string {
+ return `https://github.com/${skill.source}`;
+}
+
+export function leanSkillById(skillId: string): LeanSkill | null {
+ return LEAN_SKILLS.find((skill) => skill.skillId === skillId) ?? null;
+}
diff --git a/products/desktop/packages/core/src/billing/modelPricing.test.ts b/products/desktop/packages/core/src/billing/modelPricing.test.ts
new file mode 100644
index 000000000000..3cf2f565e773
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/modelPricing.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatModelRates,
+ modelCostInfo,
+ modelListPrice,
+ relativeCostLabel,
+} from "./modelPricing";
+
+describe("modelPricing", () => {
+ it.each([
+ // The baseline anchors the scale; an exact ratio carries no ≈; diverging
+ // input/output ratios earn one; sub-1 multipliers keep two decimals.
+ ["claude-sonnet-5", "1×"],
+ ["claude-opus-5", "2.5×"],
+ ["gpt-5.5", "≈2.8×"],
+ ["deepseek-v4", "≈0.05×"],
+ ] as const)("%s -> %s", (modelId, expected) => {
+ expect(modelCostInfo(modelId)?.multiplierLabel).toBe(expected);
+ });
+
+ it("returns null for unknown models so no wrong chip ever renders", () => {
+ expect(modelCostInfo("totally-unknown-model")).toBeNull();
+ expect(modelListPrice("totally-unknown-model")).toBeNull();
+ });
+
+ it("matches specific families before the broader ones they contain", () => {
+ expect(modelListPrice("gpt-5.6-luna")?.inputPerMtok).toBe(1);
+ expect(modelListPrice("gpt-5.5")?.inputPerMtok).toBe(5);
+ expect(modelListPrice("claude-sonnet-4-5")?.inputPerMtok).toBe(3);
+ expect(modelListPrice("claude-sonnet-5")?.inputPerMtok).toBe(2);
+ });
+
+ it("formats exact rates for tooltips", () => {
+ // A sub-dollar rate exercises the two-decimal formatting branch.
+ const price = modelListPrice("deepseek-v4");
+ expect(price && formatModelRates(price)).toBe(
+ "Input $0.13 · Output $0.26 per 1M tokens",
+ );
+ });
+
+ 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();
+ });
+});
+
+// The gateway pins the contract rates these three families bill at, and this
+// table claims to mirror them. In the monorepo the gateway file is six
+// directories up; a standalone desktop checkout skips the comparison.
+const MONOREPO_ROOT_RELATIVE = "../../../../../..";
+const MONOREPO_SENTINEL_RELATIVE = `${MONOREPO_ROOT_RELATIVE}/pyproject.toml`;
+const GATEWAY_OVERRIDES_RELATIVE = `${MONOREPO_ROOT_RELATIVE}/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_overrides.py`;
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function gatewayRate(
+ source: string,
+ block: string,
+ key: string,
+): number | null {
+ const b = escapeRegExp(block);
+ // The gateway holds rates in two shapes: a top-level `NAME = { ... }`
+ // constant (the Baseten/Kimi models) and a quoted `"model-id": { ... }`
+ // entry in the overrides dict (Fable and the GPT-5.6 models).
+ const blockMatch = source.match(
+ new RegExp(`(?:"${b}"\\s*:|${b}[^=\\n]*=)\\s*\\{([\\s\\S]*?)\\}`),
+ );
+ if (!blockMatch?.[1]) return null;
+ const rate = blockMatch[1].match(
+ new RegExp(`"${escapeRegExp(key)}":\\s*([0-9][0-9_.e-]*)`),
+ );
+ return rate?.[1] ? Number(rate[1].replaceAll("_", "")) : null;
+}
+
+describe("contract rates match the gateway's pinned table", () => {
+ it.each([
+ ["kimi", "KIMI_K3_COST"],
+ ["glm", "BASETEN_GLM_COST"],
+ ["deepseek", "BASETEN_DEEPSEEK_COST"],
+ ["fable", "claude-fable-5"],
+ ["gpt-5.6-sol", "gpt-5.6-sol"],
+ ["gpt-5.6-terra", "gpt-5.6-terra"],
+ ["gpt-5.6-luna", "gpt-5.6-luna"],
+ ] as const)("%s", async (family, block) => {
+ // A dynamic import keeps the pure-layer lint honest: only this test
+ // touches the filesystem, and only to read the gateway's table.
+ const { access, readFile } = await import("node:fs/promises");
+ try {
+ await access(new URL(MONOREPO_SENTINEL_RELATIVE, import.meta.url));
+ } catch {
+ // Not the monorepo, so there is no gateway table to compare against.
+ return;
+ }
+ // In the monorepo the gateway file must exist: a read failure here means
+ // it moved, and the mirror claim above needs its path updated.
+ const gateway = await readFile(
+ new URL(GATEWAY_OVERRIDES_RELATIVE, import.meta.url),
+ "utf-8",
+ );
+ const price = modelListPrice(family);
+ const input = gatewayRate(gateway, block, "input_cost_per_token");
+ const output = gatewayRate(gateway, block, "output_cost_per_token");
+ expect(input).not.toBeNull();
+ expect(output).not.toBeNull();
+ expect(price?.inputPerMtok).toBeCloseTo((input ?? 0) * 1e6, 6);
+ expect(price?.outputPerMtok).toBeCloseTo((output ?? 0) * 1e6, 6);
+ });
+});
diff --git a/products/desktop/packages/core/src/billing/modelPricing.ts b/products/desktop/packages/core/src/billing/modelPricing.ts
new file mode 100644
index 000000000000..5ab388aea613
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/modelPricing.ts
@@ -0,0 +1,135 @@
+/**
+ * List prices per 1M tokens for every model the pickers can show, and the
+ * relative per-token cost derived from them. One place on the client; keep in
+ * sync with the gateway's billing source
+ * (services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_overrides.py).
+ *
+ * Sources, checked 2026-08-22:
+ * - Anthropic (Opus, Sonnet, Haiku): platform.claude.com/docs/en/about-claude/pricing
+ * - GPT-5.5: developers.openai.com/api/docs/pricing
+ * - Fable, GPT-5.6, Kimi K3, GLM, DeepSeek: the gateway's billing rates, what
+ * the user is actually charged (pinned in the file above). The drift test
+ * binds these rows to it.
+ */
+
+export interface ModelListPrice {
+ inputPerMtok: number;
+ outputPerMtok: number;
+}
+
+export interface ModelCostInfo {
+ price: ModelListPrice;
+ /** Per-token cost relative to the baseline, e.g. "0.5×" or "≈1.1×". */
+ multiplierLabel: string;
+ /** True when input and output ratios diverge and the label is approximate. */
+ approximate: boolean;
+}
+
+/** The 1× anchor every multiplier is stated against. */
+export const MODEL_COST_BASELINE_NAME = "Claude Sonnet 5";
+const BASELINE: ModelListPrice = { inputPerMtok: 2, outputPerMtok: 10 };
+
+// Matched by lowercase substring, first hit wins, so keep specific ids
+// (gpt-5.6-*, sonnet-4) ahead of their broader families.
+const LIST_PRICES: [family: string, price: ModelListPrice][] = [
+ ["fable", { inputPerMtok: 10, outputPerMtok: 50 }],
+ ["mythos", { inputPerMtok: 10, outputPerMtok: 50 }],
+ ["opus", { inputPerMtok: 5, outputPerMtok: 25 }],
+ ["sonnet-4", { inputPerMtok: 3, outputPerMtok: 15 }],
+ ["sonnet", { inputPerMtok: 2, outputPerMtok: 10 }],
+ ["haiku", { inputPerMtok: 1, outputPerMtok: 5 }],
+ ["gpt-5.6-sol", { inputPerMtok: 5, outputPerMtok: 30 }],
+ ["gpt-5.6-terra", { inputPerMtok: 2.5, outputPerMtok: 15 }],
+ ["gpt-5.6-luna", { inputPerMtok: 1, outputPerMtok: 6 }],
+ ["gpt-5.5", { inputPerMtok: 5, outputPerMtok: 30 }],
+ ["kimi", { inputPerMtok: 3, outputPerMtok: 15 }],
+ ["glm", { inputPerMtok: 1.4, outputPerMtok: 4.4 }],
+ ["deepseek", { inputPerMtok: 0.13, outputPerMtok: 0.26 }],
+];
+
+export function modelListPrice(modelId: string): ModelListPrice | null {
+ const id = modelId.toLowerCase();
+ for (const [family, price] of LIST_PRICES) {
+ if (id.includes(family)) return price;
+ }
+ return null;
+}
+
+/** "$4" for whole dollars, "$0.20" otherwise. */
+function formatPerMtok(amount: number): string {
+ if (Number.isInteger(amount)) return `$${amount}`;
+ return `$${amount.toFixed(2)}`;
+}
+
+/** "Input $2 · Output $10 per 1M tokens": the exact rates behind a chip. */
+export function formatModelRates(price: ModelListPrice): string {
+ return `Input ${formatPerMtok(price.inputPerMtok)} · Output ${formatPerMtok(price.outputPerMtok)} per 1M tokens`;
+}
+
+function formatMultiplier(value: number, approximate: boolean): string {
+ let rounded: string;
+ if (value >= 10) {
+ rounded = String(Math.round(value));
+ } else if (value >= 0.95) {
+ const oneDecimal = Math.round(value * 10) / 10;
+ rounded = Number.isInteger(oneDecimal)
+ ? String(oneDecimal)
+ : oneDecimal.toFixed(1);
+ } else {
+ const twoDecimals = Math.round(value * 100) / 100;
+ rounded = String(twoDecimals);
+ }
+ return `${approximate ? "≈" : ""}${rounded}×`;
+}
+
+/**
+ * Mean of the input and output rate ratios between two prices, flagged
+ * approximate when the two ratios diverge by more than 10%.
+ */
+function blendedRatio(
+ numerator: ModelListPrice,
+ denominator: ModelListPrice,
+): { blended: number; approximate: boolean } {
+ const inputRatio = numerator.inputPerMtok / denominator.inputPerMtok;
+ const outputRatio = numerator.outputPerMtok / denominator.outputPerMtok;
+ const approximate =
+ Math.abs(inputRatio - outputRatio) / Math.max(inputRatio, outputRatio) >
+ 0.1;
+ return { blended: (inputRatio + outputRatio) / 2, approximate };
+}
+
+/** Blended per-token multiplier vs the baseline, e.g. 2.5. Null when unpriced. */
+export function modelCostMultiplier(modelId: string): number | null {
+ const price = modelListPrice(modelId);
+ if (!price) return null;
+ return blendedRatio(price, BASELINE).blended;
+}
+
+export function modelCostInfo(modelId: string): ModelCostInfo | null {
+ const price = modelListPrice(modelId);
+ if (!price) return null;
+ const { blended, approximate } = blendedRatio(price, BASELINE);
+ return {
+ price,
+ multiplierLabel: formatMultiplier(blended, approximate),
+ approximate,
+ };
+}
+
+/**
+ * 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);
+}
diff --git a/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts b/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts
index 9133e0d7ce62..692a0a385165 100644
--- a/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts
+++ b/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts
@@ -2,11 +2,27 @@ import { describe, expect, it } from "vitest";
import {
fillSpendDays,
formatTokens,
+ formatUsdCompact,
type SpendAnalysisWindow,
windowToDateFrom,
windowToDays,
} from "./spendAnalysisFormat";
+describe("formatUsdCompact", () => {
+ it.each([
+ [20, undefined, "$20"],
+ [1250, undefined, "$1,250"],
+ [12.4, undefined, "$12.40"],
+ [0, undefined, "$0"],
+ [0, { exactCents: true }, "$0.00"],
+ [20, { exactCents: true }, "$20.00"],
+ [999.994, { exactCents: true }, "$999.99"],
+ [1250.4, { exactCents: true }, "$1,250"],
+ ] as const)("formats %s (%o) as %s", (value, options, expected) => {
+ expect(formatUsdCompact(value, options)).toBe(expected);
+ });
+});
+
describe("formatTokens", () => {
it.each([
[0, "0"],
diff --git a/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts b/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts
index 330e52e3e3f4..1bb55e6718dd 100644
--- a/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts
+++ b/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts
@@ -11,6 +11,23 @@ export function formatUsd(amount: number): string {
return `$${Math.round(amount).toLocaleString()}`;
}
+/**
+ * USD for the spend-limit surfaces. Whole-dollar amounts drop the cents so a
+ * set line reads as "$20" rather than "$20.00"; `exactCents` keeps cents on
+ * amounts under $1,000 so a running total reads as measured, not rounded.
+ */
+export function formatUsdCompact(
+ value: number,
+ options: { exactCents?: boolean } = {},
+): string {
+ if (options.exactCents) {
+ if (value >= 1000) return `$${Math.round(value).toLocaleString("en-US")}`;
+ return `$${value.toFixed(2)}`;
+ }
+ if (Number.isInteger(value)) return `$${value.toLocaleString()}`;
+ return formatUsd(value);
+}
+
export function formatTokens(n: number): string {
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}B`;
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
diff --git a/products/desktop/packages/core/src/billing/spendLimits.test.ts b/products/desktop/packages/core/src/billing/spendLimits.test.ts
new file mode 100644
index 000000000000..20b0bf6cb7b6
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/spendLimits.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from "vitest";
+import {
+ EMPTY_SPEND_LIMITS,
+ evaluateSpendLimits,
+ maskStops,
+ parseSpendAmount,
+ projectedMonthUsd,
+ pruneSpendNoticesSeen,
+ type SpendLimits,
+ type SpendLimitsPatch,
+ spendLimitNoticeKey,
+ spendTickIncrement,
+ spendTotalsFromDays,
+ suggestedSpendLimits,
+} from "./spendLimits";
+
+const TODAY = "2026-08-22";
+
+function limits(patch: SpendLimitsPatch): SpendLimits {
+ return {
+ day: { ...EMPTY_SPEND_LIMITS.day, ...patch.day },
+ month: { ...EMPTY_SPEND_LIMITS.month, ...patch.month },
+ };
+}
+
+describe("spendLimits", () => {
+ it("splits today's spend from the month's and excludes other months", () => {
+ const totals = spendTotalsFromDays(
+ [
+ { day: "2026-07-31", cost_usd: 100 },
+ { day: "2026-08-01", cost_usd: 3 },
+ { day: "2026-08-22", cost_usd: 7 },
+ ],
+ TODAY,
+ );
+ expect(totals).toEqual({ todayUsd: 7, monthUsd: 10 });
+ });
+
+ it.each<{
+ name: string;
+ limits: SpendLimitsPatch;
+ totals: { todayUsd: number; monthUsd: number };
+ expected: { period: string; level: string; limitUsd: number }[];
+ }>([
+ {
+ name: "no lines set never crosses",
+ limits: {},
+ totals: { todayUsd: 999, monthUsd: 999 },
+ expected: [],
+ },
+ {
+ name: "spend below the line does not cross",
+ limits: { day: { warnUsd: 20 } },
+ totals: { todayUsd: 19.99, monthUsd: 19.99 },
+ expected: [],
+ },
+ {
+ name: "spend exactly on the line crosses",
+ limits: { day: { warnUsd: 20 } },
+ totals: { todayUsd: 20, monthUsd: 20 },
+ expected: [{ period: "day", level: "warn", limitUsd: 20 }],
+ },
+ {
+ name: "stop supersedes warn for the same period",
+ limits: { day: { warnUsd: 20, stopUsd: 50 } },
+ totals: { todayUsd: 60, monthUsd: 60 },
+ expected: [{ period: "day", level: "stop", limitUsd: 50 }],
+ },
+ {
+ name: "daily and monthly cross independently, daily first",
+ limits: { day: { warnUsd: 20 }, month: { stopUsd: 200 } },
+ totals: { todayUsd: 25, monthUsd: 250 },
+ expected: [
+ { period: "day", level: "warn", limitUsd: 20 },
+ { period: "month", level: "stop", limitUsd: 200 },
+ ],
+ },
+ {
+ name: "a zero line is treated as off",
+ limits: { day: { warnUsd: 0 } },
+ totals: { todayUsd: 5, monthUsd: 5 },
+ expected: [],
+ },
+ ])("$name", ({ limits: patch, totals, expected }) => {
+ const crossings = evaluateSpendLimits(limits(patch), totals, TODAY);
+ expect(
+ crossings.map(({ period, level, limitUsd }) => ({
+ period,
+ level,
+ limitUsd,
+ })),
+ ).toEqual(expected);
+ });
+
+ it("keys notices by period, level, anchor, and amount", () => {
+ const key = spendLimitNoticeKey({
+ period: "day",
+ level: "stop",
+ limitUsd: 50,
+ spentUsd: 61,
+ anchor: TODAY,
+ });
+ expect(key).toBe("day:stop:2026-08-22:50");
+ });
+
+ it("re-arms a raised line within the same day via a distinct key", () => {
+ const at20 = evaluateSpendLimits(
+ limits({ day: { warnUsd: 20 } }),
+ { todayUsd: 30, monthUsd: 30 },
+ TODAY,
+ )[0];
+ const at25 = evaluateSpendLimits(
+ limits({ day: { warnUsd: 25 } }),
+ { todayUsd: 30, monthUsd: 30 },
+ TODAY,
+ )[0];
+ expect(spendLimitNoticeKey(at20)).not.toBe(spendLimitNoticeKey(at25));
+ });
+
+ it("prunes seen notices from past months but keeps this month's", () => {
+ const pruned = pruneSpendNoticesSeen(
+ {
+ "day:warn:2026-07-30:20": "2026-07-30",
+ "month:warn:2026-07:200": "2026-07",
+ "day:stop:2026-08-22:50": "2026-08-22",
+ "month:stop:2026-08:200": "2026-08",
+ },
+ TODAY,
+ );
+ expect(Object.keys(pruned).sort()).toEqual([
+ "day:stop:2026-08-22:50",
+ "month:stop:2026-08:200",
+ ]);
+ });
+
+ it("projects the month from the daily average and the month's length", () => {
+ expect(projectedMonthUsd(10, "2026-08-22")).toBe(310);
+ expect(projectedMonthUsd(10, "2026-02-10")).toBe(280);
+ });
+
+ it.each([
+ // Non-colliding: the rounded stop already clears the warn line.
+ [
+ 12.4,
+ {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: 500, stopUsd: 1000 },
+ },
+ ],
+ // Both pairs would round onto one rung; each stop steps up to the next.
+ [
+ 11,
+ {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: 500, stopUsd: 1000 },
+ },
+ ],
+ // Only the monthly pair collides here.
+ [
+ 5,
+ {
+ day: { warnUsd: 5, stopUsd: 10 },
+ month: { warnUsd: 200, stopUsd: 500 },
+ },
+ ],
+ // A low average collides on both periods.
+ [
+ 2.4,
+ {
+ day: { warnUsd: 5, stopUsd: 10 },
+ month: { warnUsd: 100, stopUsd: 200 },
+ },
+ ],
+ ] as const)(
+ "suggests round lines with a warn below the stop for %d/day",
+ (avgDailyUsd, expected) => {
+ const suggested = suggestedSpendLimits(avgDailyUsd, "2026-08-22");
+ expect(suggested).toEqual(expected);
+ // The warn line must stay strictly below the stop so its notice can fire.
+ expect(suggested?.day.warnUsd).toBeLessThan(suggested?.day.stopUsd ?? 0);
+ expect(suggested?.month.warnUsd).toBeLessThan(
+ suggested?.month.stopUsd ?? 0,
+ );
+ },
+ );
+
+ it("returns null without history to derive lines from", () => {
+ expect(suggestedSpendLimits(0, "2026-08-22")).toBeNull();
+ });
+
+ it.each([
+ ["20", 20],
+ ["$20", 20],
+ ["8,950", 8950],
+ ["12.345", 12.35],
+ ["", null],
+ ["0", null],
+ ["-5", null],
+ ["abc", null],
+ ] as const)("parseSpendAmount(%j) -> %s", (raw, expected) => {
+ expect(parseSpendAmount(raw)).toBe(expected);
+ });
+
+ it.each([
+ // A day's average anchors the daily track.
+ [100, 12.4, 10],
+ // A month's pace, rounded, then halved until enough ticks fit.
+ [2000, 384, 250],
+ // No reference figure: fall back to a readable division of the scale.
+ [100, null, 10],
+ [10, null, 1],
+ // A reference so large it would leave one tick gets halved until enough
+ // fit.
+ [100, 90, 12.5],
+ [0, 12, 0],
+ ] as const)(
+ "spendTickIncrement(%s, %s) -> %s",
+ (scale, reference, expected) => {
+ expect(spendTickIncrement(scale, reference)).toBe(expected);
+ },
+ );
+
+ it("always leaves between 6 and 12 ticks on the track", () => {
+ for (const scale of [10, 50, 100, 500, 2000, 20000]) {
+ for (const reference of [null, 0.5, 12.4, 384, 9000]) {
+ const increment = spendTickIncrement(scale, reference);
+ const ticks = scale / increment;
+ expect(ticks).toBeGreaterThanOrEqual(6);
+ expect(ticks).toBeLessThanOrEqual(12);
+ }
+ }
+ });
+
+ it("maskStops keeps both warn values and nulls both stop values", () => {
+ const input: SpendLimits = {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: 200, stopUsd: 500 },
+ };
+ expect(maskStops(input)).toEqual({
+ day: { warnUsd: 20, stopUsd: null },
+ month: { warnUsd: 200, stopUsd: null },
+ });
+ });
+});
diff --git a/products/desktop/packages/core/src/billing/spendLimits.ts b/products/desktop/packages/core/src/billing/spendLimits.ts
new file mode 100644
index 000000000000..3f94aade97aa
--- /dev/null
+++ b/products/desktop/packages/core/src/billing/spendLimits.ts
@@ -0,0 +1,280 @@
+import type { SpendAnalysisDayRow } from "@posthog/api-client/spend-analysis";
+
+export type SpendLimitLevel = "warn" | "stop";
+export type SpendLimitPeriod = "day" | "month";
+
+/**
+ * User-set spend lines for this app's personal LLM spend, per period. `null`
+ * means the line is off. A warning line notifies; a stop line pauses new
+ * agent messages until the line is raised or cleared.
+ */
+export type SpendLimits = Record<
+ SpendLimitPeriod,
+ { warnUsd: number | null; stopUsd: number | null }
+>;
+
+/** A per-period partial update to `SpendLimits`; omitted lines keep their value. */
+export type SpendLimitsPatch = {
+ [Period in SpendLimitPeriod]?: Partial<SpendLimits[Period]>;
+};
+
+export const EMPTY_SPEND_LIMITS: SpendLimits = {
+ day: { warnUsd: null, stopUsd: null },
+ month: { warnUsd: null, stopUsd: null },
+};
+
+/**
+ * The same lines with every stop cleared. Used where the deployment cannot
+ * hold a stop, so a stored stop value stays inert instead of engaging.
+ */
+export function maskStops(limits: SpendLimits): SpendLimits {
+ return {
+ day: { warnUsd: limits.day.warnUsd, stopUsd: null },
+ month: { warnUsd: limits.month.warnUsd, stopUsd: null },
+ };
+}
+
+export interface SpendLimitCrossing {
+ period: SpendLimitPeriod;
+ level: SpendLimitLevel;
+ limitUsd: number;
+ spentUsd: number;
+ /** `YYYY-MM-DD` for daily crossings, `YYYY-MM` for monthly ones. */
+ anchor: string;
+}
+
+/** The adjective copy uses for a period's lines and notices. */
+export function spendPeriodLabel(period: SpendLimitPeriod): string {
+ return period === "day" ? "Daily" : "Monthly";
+}
+
+/**
+ * A typed spend amount, or null when the text is not one. Accepts a leading
+ * `$` and thousands separators, since that is how the amount is displayed.
+ */
+export function parseSpendAmount(raw: string): number | null {
+ const trimmed = raw.trim().replace(/[$,]/g, "");
+ if (trimmed === "") return null;
+ const parsed = Number(trimmed);
+ if (!Number.isFinite(parsed) || parsed <= 0) return null;
+ return Math.round(parsed * 100) / 100;
+}
+
+/**
+ * The gap between tick marks on a spend track. Anchored to a reference figure
+ * so a tick means something in that scope's terms (roughly a day's average on
+ * a daily track, a month's pace on a monthly one), then rounded to a 1/2/5
+ * step and adjusted until the track carries between 6 and 12 of them: with
+ * fewer, the knobs sit on top of most of the ticks.
+ */
+export function spendTickIncrement(
+ scale: number,
+ referenceUsd: number | null,
+): number {
+ if (scale <= 0) return 0;
+ const seed =
+ referenceUsd !== null && referenceUsd > 0 ? referenceUsd : scale / 8;
+ let increment = niceRound(seed);
+ if (increment <= 0) return 0;
+ // Under 6 ticks does not read as a scale, over 12 crowds into a solid line.
+ while (scale / increment > 12) increment *= 2;
+ while (scale / increment < 6) increment /= 2;
+ return increment;
+}
+
+export interface SpendTotals {
+ todayUsd: number;
+ monthUsd: number;
+}
+
+/** The UTC calendar day (`YYYY-MM-DD`) the spend endpoint's rows align to. */
+export function utcDayIso(date: Date = new Date()): string {
+ return date.toISOString().slice(0, 10);
+}
+
+/**
+ * Mean spend per calendar day over the fetched window, zero days included,
+ * so the average reflects how the person actually spends across a week.
+ */
+export function averageDailySpend(
+ days: Pick<SpendAnalysisDayRow, "cost_usd">[],
+ windowDays: number,
+): number {
+ if (windowDays <= 0) return 0;
+ const total = days.reduce((sum, row) => sum + Math.max(0, row.cost_usd), 0);
+ return total / windowDays;
+}
+
+/**
+ * Month total the current 30-day average pace lands on: average per day
+ * times the number of days in `todayIso`'s UTC month. A pace estimate, so
+ * copy that shows it must frame it as approximate.
+ */
+export function projectedMonthUsd(
+ avgDailyUsd: number,
+ todayIso: string,
+): number {
+ const year = Number(todayIso.slice(0, 4));
+ const month = Number(todayIso.slice(5, 7));
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
+ return avgDailyUsd * daysInMonth;
+}
+
+/** The 1/2/5 × 10^k ladder both spend roundings land on. */
+function spendLadder(value: number): number[] {
+ const base = 10 ** Math.floor(Math.log10(value));
+ return [1, 2, 5, 10].map((m) => m * base);
+}
+
+/** Nearest rung, so suggested lines land on round numbers. */
+function niceRound(value: number): number {
+ if (value <= 0) return 0;
+ return spendLadder(value).reduce((best, candidate) =>
+ Math.abs(candidate - value) < Math.abs(best - value) ? candidate : best,
+ );
+}
+
+/** Smallest rung at or above `value`, so a track's end is round. */
+export function niceCeil(value: number): number {
+ if (value <= 0) return 100;
+ return spendLadder(value).find((rung) => value <= rung * (1 + 1e-9)) ?? value;
+}
+
+/** Smallest ladder rung strictly greater than `value`. */
+function nextSpendRung(value: number): number {
+ if (value <= 0) return 1;
+ const base = 10 ** Math.floor(Math.log10(value) + 1e-9);
+ for (const rung of [1, 2, 5, 10, 20].map((m) => m * base)) {
+ if (rung > value * (1 + 1e-9)) return rung;
+ }
+ return value * 2;
+}
+
+/**
+ * A warn/stop pair on round rungs. The stop rounds on its own, then steps up
+ * to the next rung when rounding would land it on or below the warn line.
+ * Without this a seeded stop can equal the warn line, and `pickCrossing`
+ * reports the stop first, so the warn notice would never fire.
+ */
+function suggestedLinePair(
+ warnTarget: number,
+ stopTarget: number,
+): { warnUsd: number; stopUsd: number } {
+ const warnUsd = niceRound(warnTarget);
+ const stopUsd = niceRound(stopTarget);
+ return {
+ warnUsd,
+ stopUsd: stopUsd > warnUsd ? stopUsd : nextSpendRung(warnUsd),
+ };
+}
+
+/**
+ * Starting lines derived from the user's own history: the warning sits near
+ * a busy day, the stop well above one, and the monthly pair frames the
+ * current pace. Null without history to derive them from.
+ */
+export function suggestedSpendLimits(
+ avgDailyUsd: number,
+ todayIso: string,
+): Record<SpendLimitPeriod, { warnUsd: number; stopUsd: number }> | null {
+ if (avgDailyUsd <= 0) return null;
+ const projected = projectedMonthUsd(avgDailyUsd, todayIso);
+ return {
+ day: suggestedLinePair(avgDailyUsd * 1.5, avgDailyUsd * 3),
+ month: suggestedLinePair(projected * 1.25, projected * 2),
+ };
+}
+
+/**
+ * Starting lines for a scope switched on before any history exists to derive
+ * suggestions from. Round figures the person adjusts on the slider right
+ * away, not a claim about their spend — without them, enabling a scope with
+ * no history would commit two nulls and read as the switch refusing to turn
+ * on.
+ */
+export const STARTER_SPEND_LINES: Record<
+ SpendLimitPeriod,
+ { warnUsd: number; stopUsd: number }
+> = {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: 200, stopUsd: 500 },
+};
+
+/**
+ * Today's and this month's spend from the endpoint's UTC day rows. Rows are
+ * UTC-day aligned, so `todayIso` must be the UTC date (`YYYY-MM-DD`).
+ */
+export function spendTotalsFromDays(
+ days: Pick<SpendAnalysisDayRow, "day" | "cost_usd">[],
+ todayIso: string,
+): SpendTotals {
+ const monthPrefix = todayIso.slice(0, 7);
+ let todayUsd = 0;
+ let monthUsd = 0;
+ for (const row of days) {
+ if (row.day === todayIso) todayUsd += row.cost_usd;
+ if (row.day.startsWith(monthPrefix)) monthUsd += row.cost_usd;
+ }
+ return { todayUsd, monthUsd };
+}
+
+/**
+ * Which lines the current totals sit past, daily first since it resets
+ * first. At most one crossing per period: the stop line supersedes the warn
+ * line so a single spike never stacks two notices for the same period.
+ */
+export function evaluateSpendLimits(
+ limits: SpendLimits,
+ totals: SpendTotals,
+ todayIso: string,
+): SpendLimitCrossing[] {
+ const crossings: SpendLimitCrossing[] = [];
+ for (const period of ["day", "month"] as const) {
+ const spentUsd = period === "day" ? totals.todayUsd : totals.monthUsd;
+ const anchor = period === "day" ? todayIso : todayIso.slice(0, 7);
+ const crossing = pickCrossing(period, limits[period], spentUsd, anchor);
+ if (crossing) crossings.push(crossing);
+ }
+ return crossings;
+}
+
+function pickCrossing(
+ period: SpendLimitPeriod,
+ lines: SpendLimits[SpendLimitPeriod],
+ spentUsd: number,
+ anchor: string,
+): SpendLimitCrossing | null {
+ const { warnUsd, stopUsd } = lines;
+ if (stopUsd !== null && stopUsd > 0 && spentUsd >= stopUsd) {
+ return { period, level: "stop", limitUsd: stopUsd, spentUsd, anchor };
+ }
+ if (warnUsd !== null && warnUsd > 0 && spentUsd >= warnUsd) {
+ return { period, level: "warn", limitUsd: warnUsd, spentUsd, anchor };
+ }
+ return null;
+}
+
+/**
+ * Dedupe key for a crossing notice. Includes the limit value so raising a
+ * line re-arms the notice at the new amount within the same period.
+ */
+export function spendLimitNoticeKey(crossing: SpendLimitCrossing): string {
+ return `${crossing.period}:${crossing.level}:${crossing.anchor}:${crossing.limitUsd}`;
+}
+
+/**
+ * Drops seen-notice entries from past months so the persisted map stays
+ * small. Daily anchors (`YYYY-MM-DD`) and monthly anchors (`YYYY-MM`) both
+ * start with the month prefix.
+ */
+export function pruneSpendNoticesSeen(
+ seen: Record<string, string>,
+ todayIso: string,
+): Record<string, string> {
+ const monthPrefix = todayIso.slice(0, 7);
+ const pruned: Record<string, string> = {};
+ for (const [key, anchor] of Object.entries(seen)) {
+ if (anchor.startsWith(monthPrefix)) pruned[key] = anchor;
+ }
+ return pruned;
+}
diff --git a/products/desktop/packages/core/src/sessions/autoCompact.test.ts b/products/desktop/packages/core/src/sessions/autoCompact.test.ts
new file mode 100644
index 000000000000..b5b8fb02bd74
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/autoCompact.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import {
+ type AutoCompactInput,
+ clampAutoCompactPercent,
+ decideAutoCompact,
+} from "./autoCompact";
+
+const base: AutoCompactInput = {
+ thresholdPercent: 70,
+ percentage: 80,
+ isCompacting: false,
+ isRunning: false,
+ armed: true,
+};
+
+describe("decideAutoCompact", () => {
+ it("compacts once the window passes the threshold at a resting point", () => {
+ expect(decideAutoCompact(base)).toEqual({ compact: true, armed: false });
+ });
+
+ it.each([
+ ["off", { thresholdPercent: null }],
+ ["no usage reported yet", { percentage: null }],
+ ["under the threshold", { percentage: 40 }],
+ ["already compacting", { isCompacting: true }],
+ ["mid-turn", { isRunning: true }],
+ ["this crossing already fired", { armed: false }],
+ ])("does not compact when %s", (_name, patch) => {
+ expect(decideAutoCompact({ ...base, ...patch }).compact).toBe(false);
+ });
+
+ it("re-arms only after the window drops back under the threshold", () => {
+ // Still above the line after firing: stays disarmed, so a compaction that
+ // freed nothing cannot loop.
+ expect(
+ decideAutoCompact({ ...base, armed: false, percentage: 95 }),
+ ).toEqual({ compact: false, armed: false });
+ expect(
+ decideAutoCompact({ ...base, armed: false, percentage: 30 }),
+ ).toEqual({ compact: false, armed: true });
+ });
+
+ it.each([
+ [10, 50],
+ [70, 70],
+ [200, 90],
+ [72.4, 72],
+ ])("clampAutoCompactPercent(%s) -> %s", (value, expected) => {
+ expect(clampAutoCompactPercent(value)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/core/src/sessions/autoCompact.ts b/products/desktop/packages/core/src/sessions/autoCompact.ts
new file mode 100644
index 000000000000..04ad8ad84937
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/autoCompact.ts
@@ -0,0 +1,63 @@
+/**
+ * Compacting a session earlier than the model would on its own.
+ *
+ * The model already compacts near the context limit. Doing it sooner keeps
+ * every following turn smaller, which is where the saving comes from: the
+ * compaction turn itself costs something, so this only pays off on sessions
+ * long enough to keep going afterwards.
+ */
+
+/** Below this the window is too small for compaction to be worth a turn. */
+export const AUTO_COMPACT_MIN_PERCENT = 50;
+/** Above this the model's own compaction is imminent anyway. */
+export const AUTO_COMPACT_MAX_PERCENT = 90;
+export const AUTO_COMPACT_DEFAULT_PERCENT = 70;
+
+export interface AutoCompactInput {
+ /** The user's threshold as a percent of the window; null when off. */
+ thresholdPercent: number | null;
+ /** How full the window is now; null before the first response. */
+ percentage: number | null;
+ /** A compaction is already under way. */
+ isCompacting: boolean;
+ /** A turn is in flight, so the session is not at a resting point. */
+ isRunning: boolean;
+ /**
+ * False once this crossing has fired, so a session compacts once per
+ * crossing rather than on every render while it sits above the line.
+ */
+ armed: boolean;
+}
+
+export interface AutoCompactDecision {
+ compact: boolean;
+ armed: boolean;
+}
+
+/**
+ * Whether to compact now, and whether the next crossing should fire. Firing
+ * disarms; dropping back under the threshold re-arms, so a session that keeps
+ * growing compacts again later but a failed compaction does not loop.
+ */
+export function decideAutoCompact({
+ thresholdPercent,
+ percentage,
+ isCompacting,
+ isRunning,
+ armed,
+}: AutoCompactInput): AutoCompactDecision {
+ if (thresholdPercent === null || percentage === null) {
+ return { compact: false, armed: true };
+ }
+ if (percentage < thresholdPercent) return { compact: false, armed: true };
+ if (!armed || isCompacting || isRunning) return { compact: false, armed };
+ return { compact: true, armed: false };
+}
+
+/** Keeps a stored threshold inside the range the slider offers. */
+export function clampAutoCompactPercent(value: number): number {
+ return Math.min(
+ AUTO_COMPACT_MAX_PERCENT,
+ Math.max(AUTO_COMPACT_MIN_PERCENT, Math.round(value)),
+ );
+}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 60fbdc116986..84c1732067f8 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -66,6 +66,7 @@ export type CommandMenuAction =
| "open-archived"
| "open-loops"
| "open-usage"
+ | "open-cost-management"
| "search-files"
| "open-file"
| "reload-window"
diff --git a/products/desktop/packages/shared/src/posthog-property-headers.ts b/products/desktop/packages/shared/src/posthog-property-headers.ts
index d54e129fdec9..4d39ad7596c0 100644
--- a/products/desktop/packages/shared/src/posthog-property-headers.ts
+++ b/products/desktop/packages/shared/src/posthog-property-headers.ts
@@ -61,6 +61,34 @@ export function buildPosthogPropertyHeaderLines(
.join("\n");
}
+/**
+ * Attribution node header for the person a request is spent on behalf of. The
+ * gateway keys its per-user spend limit on this value, so it must be the same
+ * node the spend-limit endpoint writes the limit against: the user's distinct
+ * id, not their uuid (see products/ai_gateway/backend/logic.py, _spend_node).
+ *
+ * Trust model: for local sessions this header is asserted by the client, so
+ * the limit it keys is a self-imposed guardrail, not a security boundary.
+ * Cloud runs pin the node server-side into the run's scoped token.
+ */
+export const POSTHOG_USER_HEADER = "X-PostHog-User";
+
+export function buildPosthogUserHeaderRecord(
+ userNode: string | null | undefined,
+): Record<string, string> {
+ return userNode
+ ? { [POSTHOG_USER_HEADER]: sanitizeHeaderValue(userNode) }
+ : {};
+}
+
+export function buildPosthogUserHeaderLines(
+ userNode: string | null | undefined,
+): string {
+ return userNode
+ ? `${POSTHOG_USER_HEADER}: ${sanitizeHeaderValue(userNode)}`
+ : "";
+}
+
export function buildPosthogProjectHeaderRecord(
projectId: number | null | undefined,
): Record<string, string> {
diff --git a/products/desktop/packages/ui/src/features/billing/SpendGuardrailNotices.stories.tsx b/products/desktop/packages/ui/src/features/billing/SpendGuardrailNotices.stories.tsx
new file mode 100644
index 000000000000..dfc86842080a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/SpendGuardrailNotices.stories.tsx
@@ -0,0 +1,47 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useEffect } from "react";
+import { toast } from "../../primitives/toast";
+
+/**
+ * The two notices the spend guardrails raise, fired through the real toast
+ * pipeline so copy and styling review the same way they ship.
+ */
+function SpendGuardrailNotices({ level }: { level: "warn" | "stop" | "both" }) {
+ useEffect(() => {
+ const action = { label: "View spend", onClick: () => {} };
+ if (level !== "stop") {
+ toast.warning("Daily spend passed $20.00", {
+ id: "story-spend-warn",
+ description: "$21.37 spent today.",
+ action,
+ duration: Number.POSITIVE_INFINITY,
+ });
+ }
+ if (level !== "warn") {
+ toast.warning("Monthly spend passed your $1,000 stop line", {
+ id: "story-spend-stop",
+ description:
+ "New agent messages are paused until you raise or clear the line.",
+ action: { label: "Adjust limits", onClick: () => {} },
+ duration: Number.POSITIVE_INFINITY,
+ });
+ }
+ }, [level]);
+ return (
+ <div className="p-6 text-(--gray-11) text-sm">
+ Spend notices render as toasts in the corner.
+ </div>
+ );
+}
+
+const meta: Meta<typeof SpendGuardrailNotices> = {
+ title: "Billing/Spend guardrail notices",
+ component: SpendGuardrailNotices,
+};
+
+export default meta;
+type Story = StoryObj<typeof SpendGuardrailNotices>;
+
+export const WarningNotice: Story = { args: { level: "warn" } };
+export const StopNotice: Story = { args: { level: "stop" } };
+export const BothNotices: Story = { args: { level: "both" } };
diff --git a/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.test.tsx b/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.test.tsx
new file mode 100644
index 000000000000..0449e44a60ca
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.test.tsx
@@ -0,0 +1,95 @@
+import type { SpendSnapshot } from "@posthog/ui/features/billing/useSpendTotals";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const spendTotals = vi.hoisted(() => ({
+ value: null as SpendSnapshot | null,
+}));
+const toastMock = vi.hoisted(() => ({ warning: vi.fn(), dismiss: vi.fn() }));
+const spendAvailable = vi.hoisted(() => ({ value: true }));
+
+vi.mock("@posthog/ui/features/billing/useSpendTotals", () => ({
+ useSpendTotals: () => spendTotals.value,
+}));
+vi.mock("@posthog/ui/features/billing/useUserSpendLimit", () => ({
+ useSpendLimitAvailable: () => spendAvailable.value,
+}));
+vi.mock("../../primitives/toast", () => ({ toast: toastMock }));
+vi.mock("@posthog/ui/features/settings/hooks/useOpenSettings", () => ({
+ openSettings: vi.fn(),
+}));
+
+import { useSpendGuardrails } from "./useSpendGuardrails";
+
+describe("useSpendGuardrails", () => {
+ beforeEach(() => {
+ toastMock.warning.mockClear();
+ toastMock.dismiss.mockClear();
+ spendAvailable.value = true;
+ useSettingsStore.setState({
+ spendLimits: {
+ day: { warnUsd: null, stopUsd: null },
+ month: { warnUsd: null, stopUsd: null },
+ },
+ spendNoticesSeen: {},
+ });
+ });
+
+ it("dismisses the sticky stop notice once the stop line no longer applies", () => {
+ useSettingsStore.setState({
+ spendLimits: {
+ day: { warnUsd: null, stopUsd: 50 },
+ month: { warnUsd: null, stopUsd: null },
+ },
+ });
+ spendTotals.value = { todayUsd: 60, monthUsd: 60, avgDailyUsd: 0 };
+
+ renderHook(() => useSpendGuardrails());
+ expect(toastMock.warning).toHaveBeenCalledWith(
+ expect.stringContaining("stop line"),
+ expect.objectContaining({ id: "spend-limit-day-stop" }),
+ );
+
+ toastMock.dismiss.mockClear();
+ // Raise the stop above current spend: the crossing clears, so the notice
+ // that still says the composer is paused must be dismissed.
+ act(() => {
+ useSettingsStore.setState({
+ spendLimits: {
+ day: { warnUsd: null, stopUsd: 100 },
+ month: { warnUsd: null, stopUsd: null },
+ },
+ });
+ });
+
+ expect(toastMock.dismiss).toHaveBeenCalledWith("spend-limit-day-stop");
+ });
+
+ it("raises no stop and pauses nothing when availability is off, but the warn at the same threshold still fires", () => {
+ useSettingsStore.setState({
+ spendLimits: {
+ day: { warnUsd: 50, stopUsd: 50 },
+ month: { warnUsd: null, stopUsd: null },
+ },
+ });
+ spendTotals.value = { todayUsd: 60, monthUsd: 60, avgDailyUsd: 0 };
+ spendAvailable.value = false;
+
+ renderHook(() => useSpendGuardrails());
+
+ // The stored stop is inert while the deployment cannot hold it: no stop
+ // toast fires, and the sticky stop id is never registered.
+ const stopCalls = toastMock.warning.mock.calls.filter((call) =>
+ String(call[0]).includes("stop line"),
+ );
+ expect(stopCalls).toHaveLength(0);
+ expect(toastMock.dismiss).toHaveBeenCalledWith("spend-limit-day-stop");
+
+ // The warn at the same threshold still fires.
+ expect(toastMock.warning).toHaveBeenCalledWith(
+ expect.stringContaining("passed $50.00"),
+ expect.objectContaining({ id: "spend-limit-day-warn" }),
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.ts b/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.ts
new file mode 100644
index 000000000000..6b0c633c5650
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/useSpendGuardrails.ts
@@ -0,0 +1,84 @@
+import { formatUsd } from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ evaluateSpendLimits,
+ maskStops,
+ type SpendLimitCrossing,
+ spendLimitNoticeKey,
+ spendPeriodLabel,
+ utcDayIso,
+} from "@posthog/core/billing/spendLimits";
+import { useSpendTotals } from "@posthog/ui/features/billing/useSpendTotals";
+import { useSpendLimitAvailable } from "@posthog/ui/features/billing/useUserSpendLimit";
+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { useEffect } from "react";
+import { toast } from "../../primitives/toast";
+
+/**
+ * Watches the user's personal spend in this app against their configured
+ * spend lines and raises a notice when a line is crossed.
+ */
+export function useSpendGuardrails(): void {
+ const totals = useSpendTotals();
+ const spendLimits = useSettingsStore((state) => state.spendLimits);
+ const stopAvailable = useSpendLimitAvailable();
+
+ useEffect(() => {
+ if (!totals) return;
+ const todayIso = utcDayIso();
+ const effective = stopAvailable ? spendLimits : maskStops(spendLimits);
+ const crossings = evaluateSpendLimits(effective, totals, todayIso);
+ // Read seen-state imperatively: marking a notice seen must not re-run
+ // this effect and re-evaluate the same fetch.
+ const { spendNoticesSeen, markSpendNoticeSeen } =
+ useSettingsStore.getState();
+ const stoppedPeriods = new Set<string>();
+ for (const crossing of crossings) {
+ if (crossing.level === "stop") stoppedPeriods.add(crossing.period);
+ const key = spendLimitNoticeKey(crossing);
+ if (spendNoticesSeen[key]) continue;
+ markSpendNoticeSeen(key, crossing.anchor, todayIso);
+ showSpendNotice(crossing);
+ }
+ // The stop notice never auto-dismisses, so clear it once its period is no
+ // longer stopped (line raised or cleared); otherwise it keeps saying the
+ // composer is paused after it has re-enabled.
+ for (const period of ["day", "month"] as const) {
+ if (!stoppedPeriods.has(period)) {
+ toast.dismiss(`spend-limit-${period}-stop`);
+ }
+ }
+ }, [totals, spendLimits, stopAvailable]);
+}
+
+function showSpendNotice(crossing: SpendLimitCrossing): void {
+ const periodLabel = spendPeriodLabel(crossing.period);
+ const windowLabel = crossing.period === "day" ? "today" : "this month";
+ const description = `${formatUsd(crossing.spentUsd)} spent ${windowLabel}.`;
+ const action = {
+ label: "View spend",
+ onClick: () => openSettings("cost-management"),
+ };
+
+ // Warning toasts self-dismiss; the stop notice stays until dismissed.
+ // Neither is an error toast: nothing failed, the stop is the user's own.
+ if (crossing.level === "stop") {
+ toast.warning(
+ `${periodLabel} spend passed your ${formatUsd(crossing.limitUsd)} stop line`,
+ {
+ id: `spend-limit-${crossing.period}-stop`,
+ description: `New agent messages are paused until you raise or clear the line.`,
+ action: { label: "Adjust limits", onClick: action.onClick },
+ duration: Number.POSITIVE_INFINITY,
+ },
+ );
+ return;
+ }
+
+ toast.warning(`${periodLabel} spend passed ${formatUsd(crossing.limitUsd)}`, {
+ id: `spend-limit-${crossing.period}-warn`,
+ description,
+ action,
+ duration: 12_000,
+ });
+}
diff --git a/products/desktop/packages/ui/src/features/billing/useSpendStop.ts b/products/desktop/packages/ui/src/features/billing/useSpendStop.ts
new file mode 100644
index 000000000000..f1b0fd52b5e7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/useSpendStop.ts
@@ -0,0 +1,37 @@
+import { formatUsd } from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ evaluateSpendLimits,
+ maskStops,
+ type SpendLimitCrossing,
+ spendPeriodLabel,
+ utcDayIso,
+} from "@posthog/core/billing/spendLimits";
+import { useSpendTotals } from "@posthog/ui/features/billing/useSpendTotals";
+import { useSpendLimitAvailable } from "@posthog/ui/features/billing/useUserSpendLimit";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+
+/**
+ * The user's own stop line currently holding new agent work, or null. Null
+ * also while spend data is unavailable: a stop must never engage on missing
+ * data. Null also where the deployment cannot hold a stop line. The daily
+ * line wins when both are crossed since it resets first.
+ */
+export function useSpendStop(): SpendLimitCrossing | null {
+ const totals = useSpendTotals();
+ const spendLimits = useSettingsStore((state) => state.spendLimits);
+ const stopAvailable = useSpendLimitAvailable();
+ if (!totals) return null;
+ const effective = stopAvailable ? spendLimits : maskStops(spendLimits);
+ return (
+ evaluateSpendLimits(effective, totals, utcDayIso()).find(
+ (crossing) => crossing.level === "stop",
+ ) ?? null
+ );
+}
+
+/** The composer tooltip while a stop line holds new messages. */
+export function spendStopMessage(
+ stop: Pick<SpendLimitCrossing, "period" | "limitUsd">,
+): string {
+ return `${spendPeriodLabel(stop.period)} spend passed your ${formatUsd(stop.limitUsd)} stop line. Raise or clear it in Cost management to continue.`;
+}
diff --git a/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts b/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts
new file mode 100644
index 000000000000..4d6a95c0080a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts
@@ -0,0 +1,83 @@
+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
+import type { SpendAnalysisResponse } from "@posthog/api-client/spend-analysis";
+import {
+ type SpendAnalysisWindow,
+ windowToDateFrom,
+ windowToDays,
+} from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ averageDailySpend,
+ spendTotalsFromDays,
+ utcDayIso,
+} from "@posthog/core/billing/spendLimits";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { useSpendAnalysisEnabled } from "@posthog/ui/features/usage/useSpendAnalysisEnabled";
+import { useQuery } from "@tanstack/react-query";
+import { useMemo } from "react";
+
+// The watcher needs spend to keep arriving to notice a line being crossed.
+const POLL_INTERVAL_MS = 5 * 60_000;
+
+// Matches the spend analysis page scope so lines, meters, and charts agree.
+const SPEND_SCOPE_PRODUCT = "posthog_code";
+
+// 30 UTC calendar days including today: always covers the current month.
+const SPEND_WINDOW: SpendAnalysisWindow = "30d";
+const WINDOW_DAYS = windowToDays(SPEND_WINDOW);
+
+// The same key shape useSpendAnalysis uses, so opening Plan & usage at this
+// window reads this cache entry instead of fetching the endpoint again.
+const SPEND_TOTALS_QUERY_KEY = [
+ "billing",
+ "spend-analysis",
+ SPEND_WINDOW,
+ SPEND_SCOPE_PRODUCT,
+] as const;
+
+export interface SpendSnapshot {
+ todayUsd: number;
+ monthUsd: number;
+ /** Mean spend per day over the fetched window, zero days included. */
+ avgDailyUsd: number;
+}
+
+function fetchSpendWindow(
+ client: PostHogAPIClient,
+): Promise<SpendAnalysisResponse> {
+ return client.getPersonalSpendAnalysis({
+ dateFrom: windowToDateFrom(SPEND_WINDOW),
+ product: SPEND_SCOPE_PRODUCT,
+ });
+}
+
+/**
+ * Today's and this month's personal spend in this app, or null while the
+ * data hasn't loaded (or the endpoint is unavailable).
+ */
+export function useSpendTotals(): SpendSnapshot | null {
+ const client = useOptionalAuthenticatedClient();
+ const enabled = useSpendAnalysisEnabled();
+ const query = useQuery({
+ queryKey: SPEND_TOTALS_QUERY_KEY,
+ queryFn: () => {
+ if (!client) throw new Error("Not authenticated");
+ return fetchSpendWindow(client);
+ },
+ enabled: client !== null && enabled,
+ refetchInterval: POLL_INTERVAL_MS,
+ staleTime: 60_000,
+ retry: false,
+ // Personal billing data: drop it on any auth transition so a new account
+ // never reads the previous one's spend from the shared cache key.
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+ const days = query.data?.by_day?.items;
+ return useMemo(() => {
+ if (!days) return null;
+ return {
+ ...spendTotalsFromDays(days, utcDayIso()),
+ avgDailyUsd: averageDailySpend(days, WINDOW_DAYS),
+ };
+ }, [days]);
+}
diff --git a/products/desktop/packages/ui/src/features/billing/useUserSpendLimit.ts b/products/desktop/packages/ui/src/features/billing/useUserSpendLimit.ts
new file mode 100644
index 000000000000..4976063495d6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/billing/useUserSpendLimit.ts
@@ -0,0 +1,56 @@
+import type { UserSpendLimit } from "@posthog/api-client/spend-limit";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+export const USER_SPEND_LIMIT_QUERY_KEY = [
+ "billing",
+ "user-spend-limit",
+] as const;
+
+/** The stop line the gateway holds, which is what actually refuses spend. */
+export function useUserSpendLimit() {
+ const client = useOptionalAuthenticatedClient();
+ return useQuery({
+ queryKey: USER_SPEND_LIMIT_QUERY_KEY,
+ queryFn: () => {
+ if (!client) throw new Error("Not authenticated");
+ return client.getUserSpendLimit();
+ },
+ enabled: client !== null,
+ staleTime: 60_000,
+ retry: false,
+ // The stop limit is per user: drop it on any auth transition so a new
+ // account never reads the previous one's line from this shared key.
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+}
+
+/**
+ * Writes the stop line to the gateway. Null clears it. The query cache takes
+ * the response, so the card reflects the limit that is actually held
+ * rather than the one that was requested.
+ */
+export function useSetUserSpendLimit() {
+ const client = useOptionalAuthenticatedClient();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (input: {
+ limitUsd: number | null;
+ windowSeconds: number;
+ }): Promise<UserSpendLimit> => {
+ if (!client) throw new Error("Not authenticated");
+ return input.limitUsd === null
+ ? client.clearUserSpendLimit()
+ : client.setUserSpendLimit(input.limitUsd, input.windowSeconds);
+ },
+ onSuccess: (limit) =>
+ queryClient.setQueryData(USER_SPEND_LIMIT_QUERY_KEY, limit),
+ });
+}
+
+/** Whether this deployment can hold a stop line. False while loading or on error. */
+export function useSpendLimitAvailable(): boolean {
+ const limit = useUserSpendLimit();
+ return limit.data?.available === true;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index 06dde34785c8..2eb0c08389ca 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -15,6 +15,7 @@ import {
} from "react";
import { useConnectivity } from "../../../hooks/useConnectivity";
import { toast } from "../../../primitives/toast";
+import { spendStopMessage, useSpendStop } from "../../billing/useSpendStop";
import { useChannelWikiContext } from "../../context-wiki/hooks/useContextWiki";
import { useContextLayerFlag } from "../../feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "../../feature-flags/useFeatureFlag";
@@ -382,6 +383,7 @@ export const ChannelHomeComposer = forwardRef<
);
const isBusy = isCreatingTask;
+ const spendStop = useSpendStop();
return (
<div className="relative flex w-full flex-col">
@@ -452,7 +454,11 @@ export const ChannelHomeComposer = forwardRef<
isBusy ||
!isOnline ||
(runtime === "pi" ? isPiConfigLoading : isLoading) ||
- (runtime === "pi" && !currentPiModel)
+ (runtime === "pi" && !currentPiModel) ||
+ spendStop !== null
+ }
+ submitTooltipOverride={
+ spendStop ? spendStopMessage(spendStop) : undefined
}
modeOption={runtime === "pi" ? undefined : modeOption}
onModeChange={runtime === "pi" ? undefined : handleModeChange}
diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
index 4144ac7c3e23..173d1399d8e3 100644
--- a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
@@ -4,6 +4,7 @@ import {
CaretRightIcon,
ChartLine,
EnvelopeSimple,
+ Gauge,
GitDiffIcon,
SquaresFourIcon,
} from "@phosphor-icons/react";
@@ -79,6 +80,7 @@ import {
} from "@posthog/ui/features/settings/hooks/useOpenSettings";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { useTasks } from "@posthog/ui/features/tasks/useTasks";
+import { useSpendAnalysisEnabled } from "@posthog/ui/features/usage/useSpendAnalysisEnabled";
import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";
import { LoopIcon } from "@posthog/ui/primitives/LoopIcon";
import {
@@ -220,6 +222,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
const loopsEnabled = useFeatureFlag(LOOPS_FLAG, import.meta.env.DEV);
// With channel reports on, spaces own reports and the inbox entry goes away.
const channelReportsEnabled = useChannelReportsEnabled();
+ const spendAnalysisEnabled = useSpendAnalysisEnabled();
const { channels } = useChannels({ enabled: bluebirdEnabled });
const { theme, setTheme } = useThemeStore();
const toggleLeftSidebar = useSidebarStore((state) => state.toggle);
@@ -408,6 +411,21 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
},
]
: []),
+ // Gated like every other cost-management entry point: without spend
+ // analysis the settings page is hidden and redirects to General, so the
+ // command would not do what its label says.
+ ...(spendAnalysisEnabled
+ ? [
+ {
+ id: "cost-management",
+ label: "Cost management",
+ keywords: "cost spend limits budget savings recommendations",
+ icon: <Gauge size={12} className="text-gray-11" />,
+ action: "open-cost-management" as CommandMenuAction,
+ onRun: () => openSettingsDialog("cost-management"),
+ },
+ ]
+ : []),
{
id: "plan-usage",
label: "Plan & usage",
@@ -580,6 +598,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
openFilePicker,
loopsEnabled,
channelReportsEnabled,
+ spendAnalysisEnabled,
]);
const taskSections = useMemo<CommandSection[]>(() => {
diff --git a/products/desktop/packages/ui/src/features/cost-management/ContextCompactionSettings.tsx b/products/desktop/packages/ui/src/features/cost-management/ContextCompactionSettings.tsx
new file mode 100644
index 000000000000..13ccd1486175
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/ContextCompactionSettings.tsx
@@ -0,0 +1,112 @@
+import {
+ AUTO_COMPACT_DEFAULT_PERCENT,
+ AUTO_COMPACT_MAX_PERCENT,
+ AUTO_COMPACT_MIN_PERCENT,
+} from "@posthog/core/sessions/autoCompact";
+import { Slider, Switch, Text } from "@posthog/quill";
+import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+
+export function ContextCompactionSettings() {
+ const percent = useSettingsStore((state) => state.autoCompactPercent);
+ const setPercent = useSettingsStore((state) => state.setAutoCompactPercent);
+ const warnOnModelSwitch = useSettingsStore(
+ (state) => state.warnOnMidSessionModelSwitch,
+ );
+ const setWarnOnModelSwitch = useSettingsStore(
+ (state) => state.setWarnOnMidSessionModelSwitch,
+ );
+ return (
+ <ContextCompactionSettingsView
+ percent={percent}
+ onChange={setPercent}
+ warnOnModelSwitch={warnOnModelSwitch}
+ onWarnOnModelSwitchChange={setWarnOnModelSwitch}
+ />
+ );
+}
+
+interface ContextCompactionSettingsViewProps {
+ /** The threshold, or null when compaction is left to the model. */
+ percent: number | null;
+ onChange: (percent: number | null) => void;
+ warnOnModelSwitch: boolean;
+ onWarnOnModelSwitchChange: (enabled: boolean) => void;
+}
+
+export function ContextCompactionSettingsView({
+ percent,
+ onChange,
+ warnOnModelSwitch,
+ onWarnOnModelSwitchChange,
+}: ContextCompactionSettingsViewProps) {
+ const enabled = percent !== null;
+ return (
+ <SettingsSubsection
+ title="Context"
+ description="The model compacts a session on its own once the context is nearly full. Compacting sooner keeps every turn after it smaller."
+ >
+ <div className="flex flex-col gap-3 rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid) px-4 py-3.5">
+ <div className="flex items-center justify-between gap-4">
+ <span className="flex flex-col gap-0.5">
+ <Text className="text-(--gray-12) text-[13px]">Compact early</Text>
+ <Text className="text-(--gray-11) text-[12px]">
+ Runs the same compaction you get from typing /compact, once a
+ session passes the mark you set.
+ </Text>
+ </span>
+ <Switch
+ checked={enabled}
+ onCheckedChange={(next) =>
+ onChange(next ? AUTO_COMPACT_DEFAULT_PERCENT : null)
+ }
+ aria-label="Compact early"
+ data-attr="cost-management-auto-compact-toggle"
+ />
+ </div>
+ {enabled && (
+ <div className="flex items-center gap-4 border-(--gray-4) border-t border-dashed pt-3.5">
+ <Text className="shrink-0 text-(--gray-11) text-[12px]">
+ Compact at
+ </Text>
+ <Slider
+ className="flex-1"
+ min={AUTO_COMPACT_MIN_PERCENT}
+ max={AUTO_COMPACT_MAX_PERCENT}
+ step={5}
+ value={[percent ?? AUTO_COMPACT_DEFAULT_PERCENT]}
+ onValueChange={(next) => {
+ const value = Array.isArray(next) ? next[0] : next;
+ if (typeof value === "number") onChange(value);
+ }}
+ aria-label="Compact when the context window passes this percent"
+ data-attr="cost-management-auto-compact-percent"
+ />
+ <Text className="w-24 shrink-0 text-right text-(--gray-12) text-[12px] tabular-nums">
+ {percent}% full
+ </Text>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-col gap-3 rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid) px-4 py-3.5">
+ <div className="flex items-center justify-between gap-4">
+ <span className="flex flex-col gap-0.5">
+ <Text className="text-(--gray-12) text-[13px]">
+ Warn before a mid-session model switch
+ </Text>
+ <Text className="text-(--gray-11) text-[12px]">
+ Switching models mid-session reprocesses the conversation instead
+ of reading it from cache.
+ </Text>
+ </span>
+ <Switch
+ checked={warnOnModelSwitch}
+ onCheckedChange={onWarnOnModelSwitchChange}
+ aria-label="Warn before a mid-session model switch"
+ data-attr="spend-limits-model-switch-warning-toggle"
+ />
+ </div>
+ </div>
+ </SettingsSubsection>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.stories.tsx b/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.stories.tsx
new file mode 100644
index 000000000000..41d9f91170d0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.stories.tsx
@@ -0,0 +1,88 @@
+import type { CostChecklistItem } from "@posthog/core/billing/costChecklist";
+import { CostChecklistPanel } from "@posthog/ui/features/cost-management/CostChecklistPanel";
+import type { Meta, StoryObj } from "@storybook/react";
+
+const meta: Meta<typeof CostChecklistPanel> = {
+ title: "Cost management/CostChecklistPanel",
+ component: CostChecklistPanel,
+ args: {
+ onSwitchModel: () => {},
+ onCreateImage: () => {},
+ onInstallSkill: () => {},
+ onUninstallSkill: () => {},
+ onOpenSkill: () => {},
+ busySkillIds: new Set(),
+ },
+ decorators: [
+ (Story) => (
+ <div className="max-w-3xl p-6">
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+
+const modelNotch: CostChecklistItem = {
+ kind: "model-notch",
+ done: false,
+ fromModelId: "claude-opus-5",
+ toModelId: "claude-sonnet-5",
+};
+
+const customImage: CostChecklistItem = { kind: "custom-image", done: false };
+
+export const BothActive: StoryObj<typeof CostChecklistPanel> = {
+ args: { items: [modelNotch, customImage] },
+};
+
+export const OneDone: StoryObj<typeof CostChecklistPanel> = {
+ args: {
+ items: [
+ customImage,
+ { kind: "model-notch", done: true, modelId: "claude-sonnet-5" },
+ ],
+ },
+};
+
+export const AllDone: StoryObj<typeof CostChecklistPanel> = {
+ args: {
+ items: [
+ { kind: "model-notch", done: true, modelId: "claude-sonnet-5" },
+ { kind: "custom-image", done: true },
+ ],
+ },
+};
+
+export const NothingToChange: StoryObj<typeof CostChecklistPanel> = {
+ args: { items: [] },
+};
+
+export const SkillItems: StoryObj<typeof CostChecklistPanel> = {
+ args: {
+ items: [
+ {
+ kind: "install-skill",
+ done: false,
+ skillId: "ponytail",
+ name: "Ponytail",
+ },
+ ],
+ },
+};
+
+export const EverySuggestion: StoryObj<typeof CostChecklistPanel> = {
+ args: {
+ items: [
+ modelNotch,
+ customImage,
+ {
+ kind: "install-skill",
+ done: false,
+ skillId: "ponytail",
+ name: "Ponytail",
+ },
+ ],
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.tsx b/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.tsx
new file mode 100644
index 000000000000..1e983f581c1b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CostChecklistPanel.tsx
@@ -0,0 +1,271 @@
+import { ArrowRight, Check } from "@phosphor-icons/react";
+import type { CostChecklistItem } from "@posthog/core/billing/costChecklist";
+import { leanSkillById } from "@posthog/core/billing/leanSkills";
+import { modelCostInfo } from "@posthog/core/billing/modelPricing";
+import { Button, Text } from "@posthog/quill";
+import { formatModelId } from "@posthog/shared";
+import { modelCostTitle } from "@posthog/ui/features/sessions/components/ModelCostChip";
+import type { ReactNode } from "react";
+
+interface CostChecklistPanelProps {
+ items: CostChecklistItem[];
+ onSwitchModel: (toModelId: string) => void;
+ onCreateImage: () => void;
+ onInstallSkill: (skillId: string) => void;
+ onUninstallSkill: (skillId: string) => void;
+ /** Opens one skill's details, with its links. */
+ onOpenSkill: (skillId: string) => void;
+ /** The skills an install or removal is in flight for. */
+ busySkillIds: ReadonlySet<string>;
+}
+
+/**
+ * The recommendation checklist. Each row is a change worth making with the
+ * button that makes it; a row that has been acted on stays as a muted record
+ * at the bottom. There is no dismiss.
+ */
+export function CostChecklistPanel({
+ items,
+ onSwitchModel,
+ onCreateImage,
+ onInstallSkill,
+ onUninstallSkill,
+ onOpenSkill,
+ busySkillIds,
+}: CostChecklistPanelProps) {
+ if (items.length === 0) {
+ return (
+ <div className="rounded-(--radius-3) border border-(--gray-5) border-dashed px-4 py-3.5">
+ <Text className="text-(--gray-11) text-[12.5px]">
+ Nothing to change right now. New suggestions show up here when your
+ setup has something worth changing.
+ </Text>
+ </div>
+ );
+ }
+
+ const allDone = items.every((item) => item.done);
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col divide-y divide-(--gray-4) overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)">
+ {items.map((item) => (
+ <ChecklistRow
+ key={
+ item.kind === "install-skill"
+ ? `${item.kind}:${item.skillId}`
+ : item.kind
+ }
+ done={item.done}
+ {...rowContent(item, {
+ onSwitchModel,
+ onCreateImage,
+ onInstallSkill,
+ onUninstallSkill,
+ onOpenSkill,
+ busySkillIds,
+ })}
+ />
+ ))}
+ </div>
+ {allDone && (
+ <Text className="px-1 text-(--gray-10) text-[11.5px]">
+ Everything here is checked off.
+ </Text>
+ )}
+ </div>
+ );
+}
+
+interface RowHandlers {
+ onSwitchModel: (toModelId: string) => void;
+ onCreateImage: () => void;
+ onInstallSkill: (skillId: string) => void;
+ onUninstallSkill: (skillId: string) => void;
+ onOpenSkill: (skillId: string) => void;
+ busySkillIds: ReadonlySet<string>;
+}
+
+interface RowContent {
+ title: string;
+ detail: ReactNode;
+ action: ReactNode;
+}
+
+function rowContent(item: CostChecklistItem, h: RowHandlers): RowContent {
+ switch (item.kind) {
+ case "model-notch":
+ return item.done
+ ? {
+ title: "Default model moved down a notch",
+ detail: (
+ <span className="flex flex-wrap items-center gap-1.5">
+ New sessions start on
+ <ModelChip modelId={item.modelId} emphasis />
+ </span>
+ ),
+ action: null,
+ }
+ : {
+ title: "Move your default model one notch down",
+ detail: (
+ <span className="flex flex-col gap-1.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <ModelChip modelId={item.fromModelId} />
+ <ArrowRight
+ size={11}
+ className="text-(--gray-9)"
+ aria-hidden="true"
+ />
+ <ModelChip modelId={item.toModelId} emphasis />
+ </span>
+ <span>
+ The next step down your capability ladder. New sessions only,
+ so open sessions keep the model they are on.
+ </span>
+ </span>
+ ),
+ action: (
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="cost-management-switch-default-model"
+ onClick={() => h.onSwitchModel(item.toModelId)}
+ >
+ Switch default
+ </Button>
+ ),
+ };
+
+ case "custom-image":
+ return item.done
+ ? {
+ title: "Custom sandbox image built",
+ detail:
+ "Pick it as the base image of a cloud environment to start runs from it.",
+ action: null,
+ }
+ : {
+ title: "Build a custom sandbox image",
+ detail:
+ "Cloud runs start from your dependencies and a lean set of search tools instead of installing them each time.",
+ action: (
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="cost-management-open-image-preset"
+ onClick={() => h.onCreateImage()}
+ >
+ Build image
+ </Button>
+ ),
+ };
+
+ case "install-skill": {
+ const skill = leanSkillById(item.skillId);
+ const busy = h.busySkillIds.has(item.skillId);
+ const details = (
+ <button
+ type="button"
+ className="text-(--gray-12) underline decoration-(--gray-7)"
+ onClick={() => h.onOpenSkill(item.skillId)}
+ >
+ Details
+ </button>
+ );
+ return {
+ title: item.name,
+ detail: (
+ <span className="flex flex-wrap items-center gap-x-2">
+ {skill?.summary ?? ""}
+ {details}
+ </span>
+ ),
+ action: item.done ? (
+ <Button
+ variant="link-muted"
+ size="sm"
+ loading={busy}
+ disabled={busy}
+ data-attr="cost-management-uninstall-lean-skill"
+ onClick={() => h.onUninstallSkill(item.skillId)}
+ >
+ Uninstall
+ </Button>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ loading={busy}
+ disabled={busy}
+ data-attr="cost-management-install-lean-skill"
+ onClick={() => h.onInstallSkill(item.skillId)}
+ >
+ Install
+ </Button>
+ ),
+ };
+ }
+ }
+}
+
+function ChecklistRow({
+ done,
+ title,
+ detail,
+ action,
+}: RowContent & { done: boolean }) {
+ return (
+ <div
+ className={`flex items-start gap-3 px-4 py-3 ${done ? "opacity-65" : ""}`}
+ >
+ <span
+ aria-hidden="true"
+ className={`mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full ${
+ done ? "bg-(--gray-12) text-(--gray-1)" : "border border-(--gray-7)"
+ }`}
+ >
+ {done && <Check size={10} weight="bold" />}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <Text
+ className={`text-[12.5px] ${done ? "font-normal text-(--gray-11)" : "font-medium text-(--gray-12)"}`}
+ >
+ {title}
+ </Text>
+ <Text className="text-(--gray-11) text-[11.5px] leading-snug">
+ {detail}
+ </Text>
+ </div>
+ {action && <span className="shrink-0 pt-0.5">{action}</span>}
+ </div>
+ );
+}
+
+/** A model with its per-token multiplier, matching the picker's chips. */
+function ModelChip({
+ modelId,
+ emphasis = false,
+}: {
+ modelId: string;
+ emphasis?: boolean;
+}) {
+ const cost = modelCostInfo(modelId);
+ return (
+ <span
+ className={`inline-flex items-center gap-1.5 rounded-(--radius-2) bg-(--gray-3) px-1.5 py-0.5 ${
+ emphasis ? "text-(--gray-12)" : "text-(--gray-11)"
+ }`}
+ title={modelCostTitle(modelId)}
+ >
+ <span className={`text-[11px] ${emphasis ? "font-medium" : ""}`}>
+ {formatModelId(modelId)}
+ </span>
+ {cost && (
+ <span className="text-(--gray-10) text-[10px] tabular-nums">
+ {cost.multiplierLabel}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.stories.tsx b/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.stories.tsx
new file mode 100644
index 000000000000..87c98f5fc3ae
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.stories.tsx
@@ -0,0 +1,48 @@
+import type { CostChecklistItem } from "@posthog/core/billing/costChecklist";
+import { CostManagementView } from "@posthog/ui/features/cost-management/CostManagementView";
+import type { Meta, StoryObj } from "@storybook/react";
+
+const meta: Meta<typeof CostManagementView> = {
+ title: "Cost management/CostManagementView",
+ component: CostManagementView,
+ args: {
+ onSwitchModel: () => {},
+ onCreateImage: () => {},
+ onInstallSkill: () => {},
+ onUninstallSkill: () => {},
+ onOpenSkill: () => {},
+ busySkillIds: new Set(),
+ },
+ decorators: [
+ (Story) => (
+ <div className="max-w-4xl p-8">
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+
+const items: CostChecklistItem[] = [
+ {
+ kind: "model-notch",
+ done: false,
+ fromModelId: "claude-opus-5",
+ toModelId: "claude-sonnet-5",
+ },
+ { kind: "custom-image", done: false },
+];
+
+export const Page: StoryObj<typeof CostManagementView> = {
+ args: { items },
+};
+
+export const EverythingChecked: StoryObj<typeof CostManagementView> = {
+ args: {
+ items: [
+ { kind: "model-notch", done: true, modelId: "claude-sonnet-5" },
+ { kind: "custom-image", done: true },
+ ],
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.tsx b/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.tsx
new file mode 100644
index 000000000000..d18dda3b77b8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CostManagementSettings.tsx
@@ -0,0 +1,158 @@
+import { Gauge } from "@phosphor-icons/react";
+import { leanSkillById } from "@posthog/core/billing/leanSkills";
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from "@posthog/quill";
+import { formatModelId } from "@posthog/shared";
+import { CostManagementView } from "@posthog/ui/features/cost-management/CostManagementView";
+import { CustomImageBuildDialog } from "@posthog/ui/features/cost-management/CustomImageBuildDialog";
+import { LeanSkillDialog } from "@posthog/ui/features/cost-management/LeanSkillDialog";
+import {
+ useCostChecklist,
+ useInstalledLeanSkills,
+} from "@posthog/ui/features/cost-management/useCostChecklist";
+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { skillErrorDescription } from "@posthog/ui/features/skills/skillErrors";
+import { useInstallMarketplaceSkill } from "@posthog/ui/features/skills/useMarketplace";
+import { useDeleteSkill } from "@posthog/ui/features/skills/useSkillMutations";
+import { useSpendAnalysisEnabled } from "@posthog/ui/features/usage/useSpendAnalysisEnabled";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useState } from "react";
+
+export function CostManagementSettings() {
+ const spendAnalysisEnabled = useSpendAnalysisEnabled();
+ const setLastUsedModel = useSettingsStore((state) => state.setLastUsedModel);
+ const markDone = useSettingsStore((state) => state.markCostChecklistDone);
+ const items = useCostChecklist();
+ const cloudRepository = useSettingsStore(
+ (state) => state.lastUsedCloudRepository,
+ );
+ const installedSkills = useInstalledLeanSkills();
+ const installSkill = useInstallMarketplaceSkill();
+ const deleteSkill = useDeleteSkill();
+ const [openSkillId, setOpenSkillId] = useState<string | null>(null);
+ const [buildingImage, setBuildingImage] = useState(false);
+ // A set, not one slot, so overlapping installs each disable and re-enable
+ // only their own row instead of clobbering each other's busy state.
+ const [busySkillIds, setBusySkillIds] = useState<ReadonlySet<string>>(
+ new Set(),
+ );
+ const markSkillBusy = (skillId: string) =>
+ setBusySkillIds((prev) => new Set(prev).add(skillId));
+ const clearSkillBusy = (skillId: string) =>
+ setBusySkillIds((prev) => {
+ const next = new Set(prev);
+ next.delete(skillId);
+ return next;
+ });
+ const openSkill = openSkillId === null ? null : leanSkillById(openSkillId);
+
+ if (!spendAnalysisEnabled) {
+ return (
+ <Empty className="mx-auto max-w-md py-16">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Gauge size={24} />
+ </EmptyMedia>
+ <EmptyTitle>Cost management isn't available</EmptyTitle>
+ <EmptyDescription>
+ Spend reporting isn't enabled for your account yet, so there is
+ nothing to set limits against.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+
+ const switchDefaultModel = (toModelId: string) => {
+ const previous = useSettingsStore.getState().lastUsedModel;
+ setLastUsedModel(toModelId);
+ markDone("model-notch");
+ toast.success(`New sessions start on ${formatModelId(toModelId)}`, {
+ description: "Sessions already open keep the model they are on.",
+ action: previous
+ ? {
+ label: "Undo",
+ onClick: () => setLastUsedModel(previous),
+ }
+ : undefined,
+ });
+ };
+
+ const installById = async (skillId: string) => {
+ const skill = leanSkillById(skillId);
+ if (!skill) return;
+ markSkillBusy(skillId);
+ try {
+ await installSkill.mutateAsync({
+ source: skill.source,
+ ref: skill.ref,
+ skillId: skill.skillId,
+ });
+ toast.success(`${skill.name} installed`, {
+ description: "New sessions pick it up. Manage it under Skills.",
+ action: { label: "Open skills", onClick: () => openSettings("skills") },
+ });
+ } catch (error) {
+ toast.error(`Couldn't install ${skill.name}`, {
+ description: skillErrorDescription(error),
+ });
+ } finally {
+ clearSkillBusy(skillId);
+ }
+ };
+
+ const uninstallById = async (skillId: string) => {
+ const skill = leanSkillById(skillId);
+ const skillPath = installedSkills.get(skillId);
+ if (!skill || !skillPath) return;
+ markSkillBusy(skillId);
+ try {
+ await deleteSkill.mutateAsync({ skillPath });
+ toast.success(`${skill.name} uninstalled`, {
+ description: "New sessions start without it.",
+ });
+ } catch (error) {
+ toast.error(`Couldn't uninstall ${skill.name}`, {
+ description: skillErrorDescription(error),
+ });
+ } finally {
+ clearSkillBusy(skillId);
+ }
+ };
+
+ return (
+ <>
+ <CostManagementView
+ items={items}
+ onSwitchModel={switchDefaultModel}
+ onCreateImage={() => setBuildingImage(true)}
+ onInstallSkill={(skillId) => void installById(skillId)}
+ onUninstallSkill={(skillId) => void uninstallById(skillId)}
+ onOpenSkill={setOpenSkillId}
+ busySkillIds={busySkillIds}
+ />
+ {buildingImage && (
+ <CustomImageBuildDialog
+ defaultRepository={cloudRepository}
+ onClose={() => setBuildingImage(false)}
+ />
+ )}
+ {openSkill && (
+ <LeanSkillDialog
+ skill={openSkill}
+ installed={installedSkills.has(openSkill.skillId)}
+ busy={busySkillIds.has(openSkill.skillId)}
+ onInstall={() => void installById(openSkill.skillId)}
+ onUninstall={() => void uninstallById(openSkill.skillId)}
+ onClose={() => setOpenSkillId(null)}
+ />
+ )}
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/CostManagementView.tsx b/products/desktop/packages/ui/src/features/cost-management/CostManagementView.tsx
new file mode 100644
index 000000000000..a5d3d2974612
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CostManagementView.tsx
@@ -0,0 +1,46 @@
+import type { CostChecklistItem } from "@posthog/core/billing/costChecklist";
+import { ContextCompactionSettings } from "@posthog/ui/features/cost-management/ContextCompactionSettings";
+import { CostChecklistPanel } from "@posthog/ui/features/cost-management/CostChecklistPanel";
+import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";
+import { SpendLimitsSettings } from "@posthog/ui/features/settings/sections/SpendLimitsSettings";
+
+interface CostManagementViewProps {
+ items: CostChecklistItem[];
+ onSwitchModel: (toModelId: string) => void;
+ onCreateImage: () => void;
+ onInstallSkill: (skillId: string) => void;
+ onUninstallSkill: (skillId: string) => void;
+ onOpenSkill: (skillId: string) => void;
+ busySkillIds: ReadonlySet<string>;
+}
+
+export function CostManagementView({
+ items,
+ onSwitchModel,
+ onCreateImage,
+ onInstallSkill,
+ onUninstallSkill,
+ onOpenSkill,
+ busySkillIds,
+}: CostManagementViewProps) {
+ return (
+ <div className="flex flex-col gap-8">
+ <SpendLimitsSettings />
+ <ContextCompactionSettings />
+ <SettingsSubsection
+ title="Recommendations"
+ description="Ways to spend less on your runs. Each button makes the change, and done items stay checked below."
+ >
+ <CostChecklistPanel
+ items={items}
+ onSwitchModel={onSwitchModel}
+ onCreateImage={onCreateImage}
+ onInstallSkill={onInstallSkill}
+ onUninstallSkill={onUninstallSkill}
+ onOpenSkill={onOpenSkill}
+ busySkillIds={busySkillIds}
+ />
+ </SettingsSubsection>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/CustomImageBuildDialog.tsx b/products/desktop/packages/ui/src/features/cost-management/CustomImageBuildDialog.tsx
new file mode 100644
index 000000000000..4b14fdb66ea7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/CustomImageBuildDialog.tsx
@@ -0,0 +1,117 @@
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@posthog/quill";
+import {
+ isImageBuildFailed,
+ type SandboxCustomImage,
+} from "@posthog/shared/domain-types";
+import { BuildLogPane } from "@posthog/ui/features/settings/sections/environments/BuildLogPane";
+import { imageFailureDetail } from "@posthog/ui/features/settings/sections/environments/imageBuildWatcher";
+import { EnvironmentSetupFlow } from "@posthog/ui/features/settings/sections/environments/setup/EnvironmentSetupFlow";
+import { useSandboxCustomImageDetail } from "@posthog/ui/features/settings/sections/environments/useSandboxCustomImages";
+import { useState } from "react";
+
+interface CustomImageBuildDialogProps {
+ /** Preselected repository, so the recommendation lands on a filled form. */
+ defaultRepository: string | null;
+ onClose: () => void;
+}
+
+/**
+ * Building an image from the recommendation, start to finish, without leaving
+ * Cost management: the same setup flow the environments page uses, and then
+ * the build it started.
+ */
+export function CustomImageBuildDialog({
+ defaultRepository,
+ onClose,
+}: CustomImageBuildDialogProps) {
+ const [building, setBuilding] = useState<SandboxCustomImage | null>(null);
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ >
+ <DialogContent className="max-w-[640px]">
+ {building ? (
+ <BuildProgress image={building} onClose={onClose} />
+ ) : (
+ <>
+ <DialogHeader>
+ <DialogTitle>Build a custom sandbox image</DialogTitle>
+ <DialogDescription>
+ Cloud runs start from your dependencies and tools already
+ installed instead of installing them each run.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <EnvironmentSetupFlow
+ scope="image"
+ embedded
+ defaultRepository={defaultRepository}
+ onDone={(image) => {
+ if (image) setBuilding(image);
+ else onClose();
+ }}
+ />
+ </DialogBody>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** The build the flow just started, followed to its end. */
+function BuildProgress({
+ image,
+ onClose,
+}: {
+ image: SandboxCustomImage;
+ onClose: () => void;
+}) {
+ const { data } = useSandboxCustomImageDetail(image.id);
+ const current = data ?? image;
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{current.name}</DialogTitle>
+ <DialogDescription>{buildStatusLine(current)}</DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <BuildLogPane image={current} />
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="cost-management-close-image-build"
+ onClick={onClose}
+ >
+ Close
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
+
+function buildStatusLine(image: SandboxCustomImage): string {
+ if (image.status === "ready") {
+ return "Ready. Pick it as the base image of a cloud environment to start runs from it.";
+ }
+ if (isImageBuildFailed(image.status)) {
+ return imageFailureDetail(image);
+ }
+ return "It scans first, then builds. Closing this doesn't stop the build.";
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.stories.tsx b/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.stories.tsx
new file mode 100644
index 000000000000..413531bc5d5f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.stories.tsx
@@ -0,0 +1,28 @@
+import { LEAN_SKILLS } from "@posthog/core/billing/leanSkills";
+import { LeanSkillDialog } from "@posthog/ui/features/cost-management/LeanSkillDialog";
+import type { Meta, StoryObj } from "@storybook/react";
+
+const meta: Meta<typeof LeanSkillDialog> = {
+ title: "Cost management/LeanSkillDialog",
+ component: LeanSkillDialog,
+ args: {
+ skill: LEAN_SKILLS[0],
+ installed: false,
+ busy: false,
+ onInstall: () => {},
+ onUninstall: () => {},
+ onClose: () => {},
+ },
+};
+
+export default meta;
+
+export const Measured: StoryObj<typeof LeanSkillDialog> = {};
+
+export const Installed: StoryObj<typeof LeanSkillDialog> = {
+ args: { installed: true },
+};
+
+export const NoTrial: StoryObj<typeof LeanSkillDialog> = {
+ args: { skill: LEAN_SKILLS[1] },
+};
diff --git a/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.tsx b/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.tsx
new file mode 100644
index 000000000000..4a11ef3073dc
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/LeanSkillDialog.tsx
@@ -0,0 +1,186 @@
+import { ArrowSquareOut } from "@phosphor-icons/react";
+import {
+ type LeanSkill,
+ leanSkillRepoUrl,
+} from "@posthog/core/billing/leanSkills";
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Text,
+} from "@posthog/quill";
+import type React from "react";
+
+interface LeanSkillDialogProps {
+ skill: LeanSkill;
+ installed: boolean;
+ busy: boolean;
+ onInstall: () => void;
+ onUninstall: () => void;
+ onClose: () => void;
+}
+
+/**
+ * One skill, with one thing to look at first: the figure a trial measured,
+ * inside a quote that names the trial. Everything under it is smaller, so the
+ * card has a reading order.
+ */
+export function LeanSkillDialog({
+ skill,
+ installed,
+ busy,
+ onInstall,
+ onUninstall,
+ onClose,
+}: LeanSkillDialogProps) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ >
+ <DialogContent className="max-w-[520px]">
+ <DialogHeader>
+ <DialogTitle>{skill.name}</DialogTitle>
+ <DialogDescription>{skill.summary}</DialogDescription>
+ </DialogHeader>
+
+ <DialogBody>
+ <div className="flex flex-col gap-5">
+ {skill.trial && <TrialQuote trial={skill.trial} />}
+
+ <Block label="How it goes about it">
+ <Text size="xs" variant="muted">
+ {skill.approach}
+ </Text>
+ </Block>
+
+ {skill.example && (
+ <Block label="In practice">
+ <div className="flex flex-col gap-2 rounded-(--radius-3) bg-(--gray-2) px-3 py-2.5">
+ <Text size="xxs" variant="muted">
+ {skill.example.ask}
+ </Text>
+ <ExampleRow label="without" body={skill.example.without} />
+ <ExampleRow label="with" body={skill.example.with} mono />
+ </div>
+ </Block>
+ )}
+ </div>
+ </DialogBody>
+
+ <DialogFooter>
+ <span className="mr-auto flex items-center gap-2 self-center">
+ <Text size="xxs" variant="muted" render={<span />}>
+ {skill.license}
+ </Text>
+ <SkillLink href={leanSkillRepoUrl(skill)}>Repository</SkillLink>
+ </span>
+ <Button variant="outline" size="sm" onClick={onClose}>
+ Close
+ </Button>
+ <Button
+ variant={installed ? "outline" : "primary"}
+ size="sm"
+ loading={busy}
+ disabled={busy}
+ data-attr={`cost-management-${installed ? "uninstall" : "install"}-${skill.skillId}`}
+ onClick={installed ? onUninstall : onInstall}
+ >
+ {installed ? "Uninstall" : "Install"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** The trial's finding, led by its figure and closed by its name. */
+function TrialQuote({ trial }: { trial: NonNullable<LeanSkill["trial"]> }) {
+ return (
+ <blockquote className="m-0 flex flex-col gap-2 border-(--gray-6) border-l-2 pl-3.5">
+ <span className="flex items-baseline gap-2">
+ <span className="font-medium text-(--gray-12) text-[26px] tabular-nums leading-none">
+ {trial.headline}
+ </span>
+ <Text size="xs" render={<span />}>
+ {trial.headlineLabel}
+ </Text>
+ </span>
+ <Text size="xs" variant="muted">
+ {trial.finding}
+ </Text>
+ <span className="flex flex-wrap items-center gap-x-1.5">
+ <Text size="xxs" variant="muted" render={<span />}>
+ {`${trial.source} · ${trial.sample} ·`}
+ </Text>
+ <SkillLink href={trial.url}>Read the trial</SkillLink>
+ </span>
+ </blockquote>
+ );
+}
+
+/** A small dark label heading a block of quieter content. */
+function Block({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-2">
+ <Text size="xxs" weight="medium">
+ {label}
+ </Text>
+ {children}
+ </div>
+ );
+}
+
+/** One side of the project's illustration, labeled so it reads as one. */
+function ExampleRow({
+ label,
+ body,
+ mono = false,
+}: {
+ label: string;
+ body: string;
+ mono?: boolean;
+}) {
+ return (
+ <span className="flex items-baseline gap-3">
+ <Text
+ size="xxs"
+ variant="muted"
+ render={<span />}
+ className="w-[46px] shrink-0"
+ >
+ {label}
+ </Text>
+ <Text size="xs" render={<span />} className={mono ? "font-mono" : ""}>
+ {body}
+ </Text>
+ </span>
+ );
+}
+
+function SkillLink({ href, children }: { href: string; children: string }) {
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex w-fit items-center gap-1 text-[11px] underline decoration-(--gray-7)"
+ >
+ {children}
+ <ArrowSquareOut size={10} aria-hidden="true" />
+ </a>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/cost-management/useCostChecklist.ts b/products/desktop/packages/ui/src/features/cost-management/useCostChecklist.ts
new file mode 100644
index 000000000000..4d1cc47e5c96
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/cost-management/useCostChecklist.ts
@@ -0,0 +1,68 @@
+import {
+ buildCostChecklist,
+ type CostChecklistItem,
+} from "@posthog/core/billing/costChecklist";
+import { LEAN_SKILLS } from "@posthog/core/billing/leanSkills";
+import { useSandboxCustomImages } from "@posthog/ui/features/settings/sections/environments/useSandboxCustomImages";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { useSkills } from "@posthog/ui/features/skills/useSkills";
+import { useMemo } from "react";
+
+/**
+ * The checklist for the signed-in user: their default model, the images their
+ * cloud runs can start from, which lean skills they have, and what they have
+ * acted on.
+ */
+export function useCostChecklist(): CostChecklistItem[] {
+ const defaultModelId = useSettingsStore((state) => state.lastUsedModel);
+ const completed = useSettingsStore((state) => state.costChecklistDone);
+ const { images, customImagesEnabled, customImagesDisabled } =
+ useSandboxCustomImages();
+ const skills = useSkills();
+ const installed = useInstalledLeanSkills();
+
+ // Custom images are usable only when the feature is on, its list has loaded,
+ // and the org has not disabled it — the same signal the base-image pickers
+ // use. Until then hasCustomImage is null so no row is shown, rather than a
+ // permanent build suggestion the user cannot act on. Once usable, only a
+ // ready image checks the row off, matching the pickers' ready filter.
+ const customImagesReady = customImagesEnabled && !customImagesDisabled;
+ const hasCustomImage = customImagesReady
+ ? images.some((image) => image.status === "ready")
+ : null;
+
+ // Wait for the installed-skills list before deriving skill rows; an empty
+ // list before it loads would mislabel installed skills as installable and
+ // invite a duplicate install that fails.
+ const skillsLoaded = skills.data !== undefined;
+
+ return buildCostChecklist({
+ defaultModelId,
+ hasCustomImage,
+ skills: skillsLoaded
+ ? LEAN_SKILLS.map((skill) => ({
+ skillId: skill.skillId,
+ name: skill.name,
+ installed: installed.has(skill.skillId),
+ }))
+ : [],
+ completed,
+ });
+}
+
+/**
+ * Lean skills present locally, mapped to the path they live at so one can be
+ * removed from the same place it was added.
+ */
+export function useInstalledLeanSkills(): Map<string, string> {
+ const skills = useSkills();
+ return useMemo(() => {
+ const byId = new Map<string, string>();
+ for (const skill of skills.data ?? []) {
+ if (LEAN_SKILLS.some((lean) => lean.skillId === skill.name)) {
+ byId.set(skill.name, skill.path);
+ }
+ }
+ return byId;
+ }, [skills.data]);
+}
diff --git a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
index 07d83cd198ac..59093023f4f5 100644
--- a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
+++ b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx
@@ -17,6 +17,10 @@ vi.mock("../sessions/components/ThreadView", async () => {
};
});
+vi.mock("../billing/useSpendStop", () => ({
+ useSpendStop: () => null,
+ spendStopMessage: () => "",
+}));
vi.mock("../sessions/hooks/useSessionEventsResidency", () => ({
useSessionEventsResidency: vi.fn(),
}));
diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionControls.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionControls.tsx
index f8109655874f..751e12254fb8 100644
--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionControls.tsx
+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionControls.tsx
@@ -26,6 +26,10 @@ import {
type AgentHarness,
HarnessSubmenu,
} from "@posthog/ui/features/sessions/components/HarnessSubmenu";
+import {
+ ModelCostChip,
+ ModelCostFooter,
+} from "@posthog/ui/features/sessions/components/ModelCostChip";
import type { MessagingMode } from "@posthog/ui/features/sessions/messagingModeStore";
import { useState } from "react";
@@ -211,9 +215,11 @@ export function PiModelSelector({
closeOnClick={false}
>
<span className="whitespace-nowrap">{modelLabel(model)}</span>
+ <ModelCostChip modelId={model.id} />
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
+ <ModelCostFooter />
</DropdownMenuSubContent>
</DropdownMenuSub>
{thinkingLevel &&
diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
index 786d80cb64e4..95a315123d37 100644
--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
@@ -34,6 +34,10 @@ import type { Task } from "@posthog/shared/domain-types";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
import { useUsageLimitStore } from "@posthog/ui/features/billing/usageLimitStore";
+import {
+ spendStopMessage,
+ useSpendStop,
+} from "@posthog/ui/features/billing/useSpendStop";
import { PromptInput } from "@posthog/ui/features/message-editor/components/PromptInput";
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
import { PermissionSelector } from "@posthog/ui/features/permissions/PermissionSelector";
@@ -601,6 +605,8 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
[mcpPermission, piSessionController, taskId],
);
+ const spendStop = useSpendStop();
+
if (!session) {
return <TaskDetailSkeleton />;
}
@@ -754,7 +760,8 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
!status ||
!isOnline ||
hasQueuedMessage ||
- isAuthRestoring
+ isAuthRestoring ||
+ spendStop !== null
}
submitTooltipOverride={
!isOnline
@@ -763,7 +770,9 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
? "Restoring authentication"
: hasQueuedMessage
? "A message is already queued"
- : undefined
+ : spendStop
+ ? spendStopMessage(spendStop)
+ : undefined
}
enableBashMode
enableCommands
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.stories.tsx
new file mode 100644
index 000000000000..3a61ca2c5e95
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.stories.tsx
@@ -0,0 +1,53 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuTrigger,
+} from "@posthog/quill";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ModelCostFooter } from "./ModelCostChip";
+import { ModelRadioItem } from "./ModelRadioItem";
+
+const MODELS = [
+ { value: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
+ { value: "claude-sonnet-5", name: "Claude Sonnet 5" },
+ { value: "claude-opus-5", name: "Claude Opus 5" },
+ { value: "claude-fable-5", name: "Claude Fable 5" },
+ { value: "gpt-5.6-sol", name: "GPT-5.6 Sol" },
+ { value: "gpt-5.6-terra", name: "GPT-5.6 Terra" },
+ { value: "gpt-5.6-luna", name: "GPT-5.6 Luna" },
+ { value: "glm-5.3", name: "GLM 5.3" },
+ { value: "some-custom-model", name: "Custom model" },
+];
+
+/** The model list with cost chips, held open for visual review. */
+function OpenModelList() {
+ return (
+ <div className="flex h-[420px] items-end p-6">
+ <DropdownMenu open>
+ <DropdownMenuTrigger
+ render={<Button size="sm">Claude Sonnet 5</Button>}
+ />
+ <DropdownMenuContent align="start" side="top" className="min-w-[230px]">
+ <DropdownMenuRadioGroup value="claude-sonnet-5">
+ {MODELS.map((model) => (
+ <ModelRadioItem key={model.value} model={model} />
+ ))}
+ </DropdownMenuRadioGroup>
+ <ModelCostFooter />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+}
+
+const meta: Meta<typeof OpenModelList> = {
+ title: "Sessions/ModelCostChip",
+ component: OpenModelList,
+};
+
+export default meta;
+type Story = StoryObj<typeof OpenModelList>;
+
+export const OpenList: Story = {};
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.tsx
new file mode 100644
index 000000000000..4059a01efa0e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelCostChip.tsx
@@ -0,0 +1,40 @@
+import {
+ formatModelRates,
+ MODEL_COST_BASELINE_NAME,
+ modelCostInfo,
+} from "@posthog/core/billing/modelPricing";
+
+/** The exact rates behind a multiplier, for the chip's title. */
+export function modelCostTitle(modelId: string): string | undefined {
+ const cost = modelCostInfo(modelId);
+ if (!cost) return undefined;
+ return `Cost per token vs ${MODEL_COST_BASELINE_NAME} · ${formatModelRates(cost.price)}`;
+}
+
+/**
+ * Per-token cost multiplier chip for model picker rows. Renders nothing for
+ * unpriced models so a chip is never wrong. Presentational so the row's
+ * accessible name stays the model name; the title carries the exact rates.
+ */
+export function ModelCostChip({ modelId }: { modelId: string }) {
+ const cost = modelCostInfo(modelId);
+ if (!cost) return null;
+ return (
+ <span
+ className="ml-auto pl-3 font-normal text-[10px] text-muted-foreground/80 tabular-nums"
+ title={modelCostTitle(modelId)}
+ aria-hidden="true"
+ >
+ {cost.multiplierLabel}
+ </span>
+ );
+}
+
+/** The legend for the chips: one muted line under a model list. */
+export function ModelCostFooter() {
+ return (
+ <div className="px-2 pt-1 pb-1.5 text-[10px] text-muted-foreground/70">
+ × is cost per token vs {MODEL_COST_BASELINE_NAME}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
index 5402be626c18..266b465d2a93 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
@@ -1,11 +1,13 @@
import { Lock } from "@phosphor-icons/react";
import { DropdownMenuRadioItem } from "@posthog/quill";
import { isRestrictedModel } from "@posthog/ui/features/billing/modelGate";
+import { ModelCostChip } from "@posthog/ui/features/sessions/components/ModelCostChip";
/**
* Model picker entry. Plan-restricted models render dimmed with a lock;
* picking one is intercepted by the selector's change handler, which opens
- * the upgrade gate instead of selecting.
+ * the upgrade gate instead of selecting. Priced models carry a per-token
+ * cost multiplier chip.
*/
export function ModelRadioItem({
model,
@@ -26,8 +28,10 @@ export function ModelRadioItem({
className={restricted ? "opacity-60" : undefined}
>
<span className="whitespace-nowrap">{model.name}</span>
- {restricted && (
+ {restricted ? (
<Lock size={11} className="ml-auto text-muted-foreground" />
+ ) : (
+ <ModelCostChip modelId={model.value} />
)}
</DropdownMenuRadioItem>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSelector.tsx
index 0c3ef3360b93..f16c0cd87040 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ModelSelector.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSelector.tsx
@@ -21,6 +21,7 @@ import {
} from "@posthog/shared";
import { gateRestrictedModelPick } from "@posthog/ui/features/billing/modelGate";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { ModelCostFooter } from "@posthog/ui/features/sessions/components/ModelCostChip";
import { ModelRadioItem } from "@posthog/ui/features/sessions/components/ModelRadioItem";
import { stripDisabledModelOption } from "@posthog/ui/features/sessions/modelOptionFilters";
import {
@@ -142,6 +143,7 @@ export function ModelSelector({
))}
</DropdownMenuRadioGroup>
)}
+ <ModelCostFooter />
</DropdownMenuContent>
</DropdownMenu>
);
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.tsx
new file mode 100644
index 000000000000..166fb636033b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.stories.tsx
@@ -0,0 +1,39 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ModelSwitchCacheDialog } from "./ModelSwitchCacheDialog";
+
+const meta: Meta<typeof ModelSwitchCacheDialog> = {
+ title: "Sessions/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: () => {},
+ onCancel: () => {},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof ModelSwitchCacheDialog>;
+
+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",
+ },
+};
+
+export const UnknownPricing: Story = {
+ args: {
+ fromModelId: "custom-model-a",
+ fromModelLabel: "Custom model A",
+ toModelId: "custom-model-b",
+ toModelLabel: "Custom model B",
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx
new file mode 100644
index 000000000000..26bb39b2ed93
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelSwitchCacheDialog.tsx
@@ -0,0 +1,125 @@
+import { ArrowRight } from "@phosphor-icons/react";
+import { relativeCostLabel } from "@posthog/core/billing/modelPricing";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ Checkbox,
+ Text,
+} from "@posthog/quill";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { type ReactElement, useId, useState } from "react";
+
+interface ModelSwitchCacheDialogProps {
+ open: boolean;
+ fromModelId: string;
+ fromModelLabel: string;
+ toModelId: string;
+ toModelLabel: string;
+ onConfirm: () => 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.
+ */
+export function ModelSwitchCacheDialog({
+ open,
+ fromModelId,
+ fromModelLabel,
+ toModelId,
+ toModelLabel,
+ onConfirm,
+ onCancel,
+}: ModelSwitchCacheDialogProps): ReactElement {
+ const setWarnOnModelSwitch = useSettingsStore(
+ (state) => state.setWarnOnMidSessionModelSwitch,
+ );
+ const [dontShowAgain, setDontShowAgain] = useState(false);
+ const checkboxId = useId();
+ const rateLabel = relativeCostLabel(fromModelId, toModelId);
+
+ const rememberChoice = () => {
+ if (dontShowAgain) setWarnOnModelSwitch(false);
+ };
+
+ return (
+ <AlertDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onCancel();
+ }}
+ >
+ <AlertDialogContent>
+ <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.
+ </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>
+ <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
+ </Text>
+ </label>
+ </div>
+ <AlertDialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => {
+ rememberChoice();
+ onCancel();
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ data-attr="model-switch-cache-dialog-confirm"
+ onClick={() => {
+ rememberChoice();
+ onConfirm();
+ }}
+ >
+ Switch to {toModelLabel}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
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 6a6e0472069a..c4f8dfc9c250 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
@@ -40,6 +40,7 @@ import {
type AgentHarness,
HarnessSubmenu,
} from "@posthog/ui/features/sessions/components/HarnessSubmenu";
+import { ModelCostFooter } from "@posthog/ui/features/sessions/components/ModelCostChip";
import { ModelRadioItem } from "@posthog/ui/features/sessions/components/ModelRadioItem";
import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";
import { AnimatedHeight } from "@posthog/ui/primitives/AnimatedHeight";
@@ -489,6 +490,7 @@ export function ReasoningLevelSelector({
/>
))}
</DropdownMenuRadioGroup>
+ <ModelCostFooter />
</DropdownMenuSubContent>
</DropdownMenuSub>
)}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index bc0d6995db85..dd353ac91c28 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -1,5 +1,6 @@
import { Pause, Spinner, Warning } from "@phosphor-icons/react";
import type { FileAttachment } from "@posthog/core/message-editor/content";
+import { hasSessionPromptEvent } from "@posthog/core/sessions/sessionEvents";
import {
createLatestPlanTracker,
SESSION_SERVICE,
@@ -12,6 +13,10 @@ import {
import { useService } from "@posthog/di/react";
import { type AcpMessage, FAST_MODE_FLAG } from "@posthog/shared";
import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";
+import {
+ spendStopMessage,
+ useSpendStop,
+} from "@posthog/ui/features/billing/useSpendStop";
import { showOfflineToast } from "@posthog/ui/features/connectivity/connectivityToast";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import type { AttachmentUploadStatus } from "@posthog/ui/features/message-editor/components/AttachmentsBar";
@@ -35,6 +40,7 @@ import {
getGithubRefUrlFromEventTarget,
} from "@posthog/ui/features/sessions/components/copyContextTarget";
import { DropZoneOverlay } from "@posthog/ui/features/sessions/components/DropZoneOverlay";
+import { ModelSwitchCacheDialog } from "@posthog/ui/features/sessions/components/ModelSwitchCacheDialog";
import { PendingChatView } from "@posthog/ui/features/sessions/components/PendingChatView";
import { PermissionDock } from "@posthog/ui/features/sessions/components/PermissionDock";
import { PlanStatusBar } from "@posthog/ui/features/sessions/components/PlanStatusBar";
@@ -50,7 +56,9 @@ import {
submitComposerPrompt,
} from "@posthog/ui/features/sessions/components/submitComposerPrompt";
import { ThreadView } from "@posthog/ui/features/sessions/components/ThreadView";
+import { usePendingModelSwitch } from "@posthog/ui/features/sessions/components/usePendingModelSwitch";
import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";
+import { useAutoCompact } from "@posthog/ui/features/sessions/hooks/useAutoCompact";
import { useContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { useCancelQueuedMessageEdit } from "@posthog/ui/features/sessions/hooks/useEditQueuedMessage";
import { useSessionEventsResidency } from "@posthog/ui/features/sessions/hooks/useSessionEventsResidency";
@@ -185,6 +193,7 @@ export function SessionView({
const fastModeOption = fastModeFlagEnabled ? liveFastModeOption : undefined;
const toggleMessagingMode = useToggleMessagingMode(taskId);
const { allowBypassPermissions } = useSettingsStore();
+ const spendStop = useSpendStop();
const { isOnline } = useConnectivity();
const currentModeId = modeOption?.currentValue;
const handoffInProgress = useSessionHandoffInProgress(taskId);
@@ -239,7 +248,7 @@ export function SessionView({
[taskId, thoughtOption, sessionService],
);
- const handleConfigOptionChange = useCallback(
+ const applyConfigOption = useCallback(
(configId: string, value: string) => {
if (!taskId) return;
sessionService.setSessionConfigOption(taskId, configId, value);
@@ -247,6 +256,27 @@ export function SessionView({
[taskId, sessionService],
);
+ const {
+ pendingModelSwitch,
+ interceptModelSwitch,
+ confirmModelSwitch,
+ cancelModelSwitch,
+ } = usePendingModelSwitch({
+ taskId,
+ sessionModelOption,
+ hasConversationStarted: hasSessionPromptEvent(events),
+ onApply: applyConfigOption,
+ });
+
+ const handleConfigOptionChange = useCallback(
+ (configId: string, value: string) => {
+ if (!taskId) return;
+ if (interceptModelSwitch(configId, value)) return;
+ applyConfigOption(configId, value);
+ },
+ [taskId, interceptModelSwitch, applyConfigOption],
+ );
+
const sessionId = taskId ?? "default";
const setContext = useDraftStore((s) => s.actions.setContext);
const requestFocus = useDraftStore((s) => s.actions.requestFocus);
@@ -272,6 +302,17 @@ export function SessionView({
const isCloudRun = useIsWorkspaceCloudRun(taskId);
const editorRef = useRef<PromptInputHandle>(null);
const contextUsage = useContextUsage(events);
+ const isCompacting = useSessionSelector(
+ taskId,
+ (session) => session?.isCompacting ?? false,
+ );
+ useAutoCompact({
+ sessionKey: sessionId,
+ usage: contextUsage,
+ isCompacting,
+ isRunning,
+ sendPrompt: onSendPrompt,
+ });
const sendInFlightRef = useRef(false);
const composerSubmissionRef = useRef(0);
const attachmentIdsRef = useRef<Set<string>>(new Set());
@@ -770,7 +811,8 @@ export function SessionView({
handoffInProgress ||
!isOnline ||
attachmentsUploading ||
- attachmentUploadFailed
+ attachmentUploadFailed ||
+ spendStop !== null
}
clearOnSubmit={false}
submitTooltipOverride={
@@ -780,7 +822,9 @@ export function SessionView({
? "Uploading attachments…"
: attachmentUploadFailed
? "Attachment upload failed"
- : undefined
+ : spendStop
+ ? spendStopMessage(spendStop)
+ : undefined
}
isLoading={!!isPromptPending}
isActiveSession={isActiveSession}
@@ -839,6 +883,15 @@ export function SessionView({
</Flex>
)}
</ContextMenu.Trigger>
+ <ModelSwitchCacheDialog
+ open={pendingModelSwitch !== null}
+ fromModelId={pendingModelSwitch?.fromValue ?? ""}
+ fromModelLabel={pendingModelSwitch?.fromLabel ?? ""}
+ toModelId={pendingModelSwitch?.value ?? ""}
+ toModelLabel={pendingModelSwitch?.label ?? ""}
+ onConfirm={confirmModelSwitch}
+ onCancel={cancelModelSwitch}
+ />
<ContextMenu.Content size="1">
<ContextMenu.Item
onSelect={() => {
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.tsx
new file mode 100644
index 000000000000..3d30e878b916
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.test.tsx
@@ -0,0 +1,100 @@
+import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { usePendingModelSwitch } from "./usePendingModelSwitch";
+
+function modelOption(): SessionConfigOption {
+ return {
+ type: "select",
+ id: "model",
+ name: "Model",
+ category: "model",
+ currentValue: "claude-opus-5",
+ options: [
+ { name: "Claude Sonnet 5", value: "claude-sonnet-5" },
+ { name: "Claude Opus 5", value: "claude-opus-5" },
+ ],
+ } as unknown as SessionConfigOption;
+}
+
+interface Props {
+ taskId: string | undefined;
+ onApply: (configId: string, value: string) => void;
+ hasConversationStarted: boolean;
+}
+
+function setup(
+ taskId: string | undefined,
+ onApply: Props["onApply"],
+ hasConversationStarted = true,
+) {
+ return renderHook(
+ (props: Props) =>
+ usePendingModelSwitch({
+ taskId: props.taskId,
+ sessionModelOption: modelOption(),
+ hasConversationStarted: props.hasConversationStarted,
+ onApply: props.onApply,
+ }),
+ { initialProps: { taskId, onApply, hasConversationStarted } },
+ );
+}
+
+describe("usePendingModelSwitch", () => {
+ beforeEach(() => {
+ useSettingsStore.setState({ warnOnMidSessionModelSwitch: true });
+ });
+
+ it("queues a mid-session switch and applies it on confirm", () => {
+ const onApply = vi.fn();
+ const { result } = setup("task-a", onApply);
+
+ let intercepted = false;
+ act(() => {
+ intercepted = result.current.interceptModelSwitch(
+ "model",
+ "claude-sonnet-5",
+ );
+ });
+ expect(intercepted).toBe(true);
+ expect(result.current.pendingModelSwitch?.value).toBe("claude-sonnet-5");
+
+ act(() => result.current.confirmModelSwitch());
+ expect(onApply).toHaveBeenCalledWith("model", "claude-sonnet-5");
+ expect(result.current.pendingModelSwitch).toBeNull();
+ });
+
+ it("does not queue a switch before the conversation has started", () => {
+ const onApply = vi.fn();
+ const { result } = setup("task-a", onApply, false);
+
+ let intercepted = true;
+ act(() => {
+ intercepted = result.current.interceptModelSwitch(
+ "model",
+ "claude-sonnet-5",
+ );
+ });
+ expect(intercepted).toBe(false);
+ expect(result.current.pendingModelSwitch).toBeNull();
+ 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();
+ const { result, rerender } = setup("task-a", onApply);
+
+ act(() => {
+ result.current.interceptModelSwitch("model", "claude-sonnet-5");
+ });
+ expect(result.current.pendingModelSwitch).not.toBeNull();
+
+ // The view swaps to another task without remounting.
+ rerender({ taskId: "task-b", onApply, hasConversationStarted: true });
+ expect(result.current.pendingModelSwitch).toBeNull();
+
+ 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.ts
new file mode 100644
index 000000000000..8f01e7335a24
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/usePendingModelSwitch.ts
@@ -0,0 +1,109 @@
+import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import { flattenSelectOptions } from "@posthog/ui/features/sessions/sessionStore";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { useCallback, useState } from "react";
+
+export interface PendingModelSwitch {
+ configId: string;
+ value: string;
+ label: string;
+ fromValue: string;
+ fromLabel: string;
+}
+
+interface UsePendingModelSwitchInput {
+ /** The session the queued switch belongs to. The view can swap sessions
+ * without remounting, so a queued switch clears when this changes. */
+ taskId: string | undefined;
+ sessionModelOption: SessionConfigOption | undefined;
+ /**
+ * The dialog only guards mid-session, once a prompt has been sent. Protocol
+ * updates (available commands, config options) land in the event stream
+ * before any prompt, so this must track conversation content, not raw events.
+ */
+ hasConversationStarted: boolean;
+ /** Applies the queued switch unchanged once the dialog is confirmed. */
+ onApply: (configId: string, value: string) => void;
+}
+
+interface UsePendingModelSwitchResult {
+ pendingModelSwitch: PendingModelSwitch | null;
+ /**
+ * Queues a mid-session model switch behind the cache-cost dialog. True when
+ * the change was intercepted, so the caller must not apply it itself.
+ */
+ interceptModelSwitch: (configId: string, value: string) => boolean;
+ confirmModelSwitch: () => void;
+ cancelModelSwitch: () => void;
+}
+
+/**
+ * A mid-session model switch first pauses on an inform-only cache-cost
+ * dialog (ModelSwitchCacheDialog); confirming applies the queued switch
+ * unchanged.
+ */
+export function usePendingModelSwitch({
+ taskId,
+ sessionModelOption,
+ hasConversationStarted,
+ onApply,
+}: UsePendingModelSwitchInput): UsePendingModelSwitchResult {
+ const warnOnMidSessionModelSwitch = useSettingsStore(
+ (state) => state.warnOnMidSessionModelSwitch,
+ );
+ const [pendingModelSwitch, setPendingModelSwitch] =
+ useState<PendingModelSwitch | null>(null);
+
+ // A switch queued for one session must not linger over another. Navigating
+ // to a different task does not remount this view, so drop the pending switch
+ // when the task changes; otherwise confirming would write the old session's
+ // choice to the new one and the dialog would show the wrong labels.
+ const [trackedTaskId, setTrackedTaskId] = useState(taskId);
+ if (taskId !== trackedTaskId) {
+ setTrackedTaskId(taskId);
+ setPendingModelSwitch(null);
+ }
+
+ const interceptModelSwitch = useCallback(
+ (configId: string, value: string) => {
+ const isMidSessionModelSwitch =
+ warnOnMidSessionModelSwitch &&
+ hasConversationStarted &&
+ sessionModelOption?.type === "select" &&
+ sessionModelOption.id === configId &&
+ sessionModelOption.currentValue !== value;
+ if (!isMidSessionModelSwitch) return false;
+ const modelOptions = flattenSelectOptions(sessionModelOption.options);
+ const nameOf = (modelValue: string) =>
+ modelOptions.find((option) => option.value === modelValue)?.name ??
+ modelValue;
+ setPendingModelSwitch({
+ configId,
+ value,
+ label: nameOf(value),
+ fromValue: sessionModelOption.currentValue,
+ fromLabel: nameOf(sessionModelOption.currentValue),
+ });
+ return true;
+ },
+ [warnOnMidSessionModelSwitch, hasConversationStarted, sessionModelOption],
+ );
+
+ const confirmModelSwitch = useCallback(() => {
+ if (pendingModelSwitch) {
+ onApply(pendingModelSwitch.configId, pendingModelSwitch.value);
+ }
+ setPendingModelSwitch(null);
+ }, [pendingModelSwitch, onApply]);
+
+ const cancelModelSwitch = useCallback(() => {
+ setPendingModelSwitch(null);
+ }, []);
+
+ return {
+ pendingModelSwitch,
+ interceptModelSwitch,
+ confirmModelSwitch,
+ cancelModelSwitch,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.test.tsx b/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.test.tsx
new file mode 100644
index 000000000000..4592352adeca
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.test.tsx
@@ -0,0 +1,84 @@
+import type { ContextUsage } from "@posthog/core/sessions/contextUsage";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { type AutoCompactArgs, useAutoCompact } from "./useAutoCompact";
+
+vi.mock("@posthog/ui/primitives/toast", () => ({
+ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() },
+}));
+
+function usageAt(percentage: number): ContextUsage {
+ return {
+ used: percentage,
+ size: 100,
+ percentage,
+ cost: null,
+ breakdown: null,
+ };
+}
+
+function props(overrides: Partial<AutoCompactArgs> = {}): AutoCompactArgs {
+ return {
+ sessionKey: "task-a",
+ usage: usageAt(80),
+ isCompacting: false,
+ isRunning: false,
+ sendPrompt: vi.fn().mockResolvedValue(true),
+ ...overrides,
+ };
+}
+
+describe("useAutoCompact", () => {
+ beforeEach(() => {
+ useSettingsStore.setState({ autoCompactPercent: 70 });
+ });
+
+ it("fires once per crossing and not again while the session stays above the line", () => {
+ const p = props();
+ const { rerender } = renderHook((args) => useAutoCompact(args), {
+ initialProps: p,
+ });
+ expect(p.sendPrompt).toHaveBeenCalledTimes(1);
+ rerender({ ...p, usage: usageAt(85) });
+ expect(p.sendPrompt).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not start a second compaction after a send while still above the line", async () => {
+ let resolveSend: ((sent: boolean) => void) | undefined;
+ const sendPrompt = vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ resolveSend = resolve;
+ }),
+ );
+ const p = props({ sendPrompt });
+ const { rerender } = renderHook((args) => useAutoCompact(args), {
+ initialProps: p,
+ });
+ expect(sendPrompt).toHaveBeenCalledTimes(1);
+
+ // A render arrives while the compaction send is still in flight.
+ rerender({ ...p, usage: usageAt(82) });
+ expect(sendPrompt).toHaveBeenCalledTimes(1);
+
+ // The send resolves and the session settles still above the threshold; the
+ // latch must stay closed rather than firing a second, paid compaction.
+ await act(async () => {
+ resolveSend?.(true);
+ });
+ rerender({ ...p, usage: usageAt(83) });
+ expect(sendPrompt).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-arms for a different session so the old latch does not suppress it", () => {
+ const p = props();
+ const { rerender } = renderHook((args) => useAutoCompact(args), {
+ initialProps: p,
+ });
+ expect(p.sendPrompt).toHaveBeenCalledTimes(1);
+ // The mounted view swaps to another session already above the threshold.
+ rerender({ ...p, sessionKey: "task-b" });
+ expect(p.sendPrompt).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.ts
new file mode 100644
index 000000000000..bd868de6bc1f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useAutoCompact.ts
@@ -0,0 +1,95 @@
+import { decideAutoCompact } from "@posthog/core/sessions/autoCompact";
+import type { ContextUsage } from "@posthog/core/sessions/contextUsage";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useEffect, useRef } from "react";
+
+export interface AutoCompactArgs {
+ /** Identifies the session the latch belongs to. The view can swap sessions
+ * without remounting, so the latch resets when this changes. */
+ sessionKey: string;
+ usage: ContextUsage | null;
+ isCompacting: boolean;
+ isRunning: boolean;
+ /** The session's own send path, so compaction goes through the same route a
+ * typed `/compact` takes. */
+ sendPrompt: (text: string) => Promise<boolean>;
+}
+
+/**
+ * Compacts the session when its context passes the user's threshold, using the
+ * same command a person would type. Silent when the setting is off, which is
+ * the default.
+ */
+export function useAutoCompact({
+ sessionKey,
+ usage,
+ isCompacting,
+ isRunning,
+ sendPrompt,
+}: AutoCompactArgs): void {
+ const thresholdPercent = useSettingsStore(
+ (state) => state.autoCompactPercent,
+ );
+ const armedRef = useRef(true);
+ // Held in a ref so a re-render mid-send cannot start a second compaction.
+ const sendingRef = useRef(false);
+
+ // This view can receive a different session without remounting, so the latch
+ // is scoped to the session by hand. Without this reset the old session's
+ // disarmed latch would carry over and suppress the new session's compaction.
+ const sessionKeyRef = useRef(sessionKey);
+ if (sessionKeyRef.current !== sessionKey) {
+ sessionKeyRef.current = sessionKey;
+ armedRef.current = true;
+ sendingRef.current = false;
+ }
+
+ useEffect(() => {
+ // While a send is in flight the latch is already held. A re-render here
+ // must not recompute it: writing the decision back mid-send would rearm the
+ // latch the fire just opened and start a second compaction once the session
+ // settles — the loop decideAutoCompact is written to prevent.
+ if (sendingRef.current) return;
+
+ const decision = decideAutoCompact({
+ thresholdPercent,
+ percentage: usage?.percentage ?? null,
+ isCompacting,
+ isRunning,
+ armed: armedRef.current,
+ });
+ armedRef.current = decision.armed;
+ if (!decision.compact) return;
+
+ sendingRef.current = true;
+ // The session can change while the send is in flight; the completion must
+ // not touch the latch or toast of whatever session is shown by then.
+ const sentForKey = sessionKey;
+ void sendPrompt("/compact")
+ .then((sent) => {
+ if (sessionKeyRef.current !== sentForKey) return;
+ if (!sent) {
+ // Re-arm so a rejected send is retried at the next resting point
+ // rather than silently disabling the setting for this session.
+ armedRef.current = true;
+ return;
+ }
+ toast.info("Compacting the session", {
+ description: `The context passed ${thresholdPercent}% of the window.`,
+ });
+ })
+ .finally(() => {
+ if (sessionKeyRef.current === sentForKey) {
+ sendingRef.current = false;
+ }
+ });
+ }, [
+ sessionKey,
+ thresholdPercent,
+ usage,
+ isCompacting,
+ isRunning,
+ sendPrompt,
+ ]);
+}
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 059d260e0473..19e7395dd3b9 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx
@@ -1,3 +1,4 @@
+import { CostManagementSettings } from "@posthog/ui/features/cost-management/CostManagementSettings";
import { McpServersView } from "@posthog/ui/features/mcp-servers/components/McpServersView";
import { AdvancedSettings } from "@posthog/ui/features/settings/sections/AdvancedSettings";
import { AgentsSettings } from "@posthog/ui/features/settings/sections/AgentsSettings";
@@ -47,6 +48,10 @@ const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {
general: defineSettingsPage("General", GeneralSettings),
notifications: defineSettingsPage("Notifications", NotificationsSettings),
"plan-usage": defineSettingsPage("Plan & usage", PlanUsageSettings),
+ "cost-management": defineSettingsPage(
+ "Cost management",
+ CostManagementSettings,
+ ),
workspaces: defineSettingsPage("Workspaces", WorkspacesSettings),
worktrees: defineSettingsPage("Worktrees", WorktreesSettings),
environments: defineSettingsPage("Environments", EnvironmentsSettings),
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 1b5a298f083e..dfc0489b46ab 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
@@ -7,6 +7,7 @@ import {
Cube,
DiscordLogo,
Folder,
+ Gauge,
GearSix,
GithubLogo,
Keyboard,
@@ -79,7 +80,10 @@ const SIDEBAR_GROUPS: SidebarGroup[] = [
},
{
label: "Account",
- items: [{ id: "plan-usage", icon: <CreditCard size={16} /> }],
+ items: [
+ { id: "plan-usage", icon: <CreditCard size={16} /> },
+ { id: "cost-management", icon: <Gauge size={16} /> },
+ ],
},
{
label: "Code",
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.test.tsx
new file mode 100644
index 000000000000..d685663eef3d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.test.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import { SpendKnobValue } from "./SpendKnobValue";
+
+async function typeAmount(
+ user: ReturnType<typeof userEvent.setup>,
+ amount: string,
+): Promise<HTMLInputElement> {
+ const input = screen.getByLabelText(/in dollars/i) as HTMLInputElement;
+ await user.click(input);
+ await user.clear(input);
+ await user.type(input, amount);
+ return input;
+}
+
+describe("SpendKnobValue", () => {
+ it("discards the typed amount on Escape and restores the label", async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <SpendKnobValue
+ valueUsd={20}
+ label="$20"
+ name="Daily warning"
+ onCommit={onCommit}
+ />,
+ );
+
+ const input = await typeAmount(user, "999");
+ await user.keyboard("{Escape}");
+
+ expect(onCommit).not.toHaveBeenCalled();
+ expect(input).toHaveValue("$20");
+ });
+
+ it("commits the typed amount on Enter", async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <SpendKnobValue
+ valueUsd={20}
+ label="$20"
+ name="Daily warning"
+ onCommit={onCommit}
+ />,
+ );
+
+ await typeAmount(user, "999");
+ await user.keyboard("{Enter}");
+
+ expect(onCommit).toHaveBeenCalledWith(999);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.tsx
new file mode 100644
index 000000000000..241d52fe8cd1
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendKnobValue.tsx
@@ -0,0 +1,104 @@
+import { PencilSimple } from "@phosphor-icons/react";
+import { parseSpendAmount } from "@posthog/core/billing/spendLimits";
+import { useRef, useState } from "react";
+
+interface SpendKnobValueProps {
+ valueUsd: number;
+ /** The amount as displayed, e.g. "$1,000". */
+ label: string;
+ /** Accessible name, since the amount alone does not say which line it is. */
+ name: string;
+ onCommit: (value: number) => void;
+}
+
+/** Shared by the input and the hidden sizer, so the two measure identically. */
+const BOX =
+ "rounded-(--radius-2) border px-2 py-1 pr-6 font-medium text-[12px] tabular-nums leading-none";
+
+/**
+ * A knob's amount, in a callout above the knob.
+ *
+ * It is always the same input element: clicking focuses it rather than
+ * swapping it for something else, so nothing moves. Width comes from a hidden
+ * copy of the text behind it, so the callout fits its value without the
+ * element itself having to resize on focus.
+ */
+export function SpendKnobValue({
+ valueUsd,
+ label,
+ name,
+ onCommit,
+}: SpendKnobValueProps) {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(label);
+ // Escape blurs the input to end the edit, but blur() dispatches focusout
+ // synchronously, so onBlur's commit runs before the setDraft(label) it
+ // queues re-renders. A ref, read at commit time, tells commit to discard.
+ const cancelEdit = useRef(false);
+
+ // Re-sync while idle, so dragging the knob updates the text without an
+ // effect and without clobbering what is being typed.
+ if (!editing && draft !== label) setDraft(label);
+
+ const commit = () => {
+ setEditing(false);
+ if (cancelEdit.current) {
+ cancelEdit.current = false;
+ setDraft(label);
+ return;
+ }
+ const parsed = parseSpendAmount(draft);
+ if (parsed === null) {
+ setDraft(label);
+ return;
+ }
+ if (parsed !== valueUsd) onCommit(parsed);
+ };
+
+ const border = editing ? "border-(--accent-9)" : "border-(--gray-6)";
+
+ return (
+ <span className="relative block">
+ {/* Sizer: same text and metrics as the input, so the callout is exactly
+ as wide as its value. */}
+ <span aria-hidden="true" className={`${BOX} invisible block border`}>
+ {draft}
+ </span>
+ <input
+ aria-label={`${name} in dollars. Click to type an amount`}
+ inputMode="decimal"
+ className={`${BOX} absolute inset-0 cursor-pointer bg-(--color-panel-solid) text-(--gray-12) shadow-sm outline-none focus:cursor-text ${border} ${
+ editing ? "" : "hover:border-(--gray-8) hover:bg-(--gray-2)"
+ }`}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onFocus={(event) => {
+ setEditing(true);
+ event.currentTarget.select();
+ }}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.currentTarget.blur();
+ return;
+ }
+ if (event.key === "Escape") {
+ cancelEdit.current = true;
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ <PencilSimple
+ size={10}
+ aria-hidden="true"
+ className="-translate-y-1/2 pointer-events-none absolute top-1/2 right-1.5 text-(--gray-10)"
+ />
+ {/* A rotated square borrowing the callout's own fill and border, so the
+ callout points at the knob it belongs to. */}
+ <span
+ aria-hidden="true"
+ className={`-bottom-[4px] -translate-x-1/2 absolute left-1/2 size-[7px] rotate-45 border-r border-b bg-(--color-panel-solid) ${border}`}
+ />
+ </span>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitCard.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitCard.tsx
new file mode 100644
index 000000000000..321e35516225
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitCard.tsx
@@ -0,0 +1,147 @@
+import { formatUsdCompact } from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ type SpendLimitPeriod,
+ type SpendLimits,
+ type SpendLimitsPatch,
+ STARTER_SPEND_LINES,
+} from "@posthog/core/billing/spendLimits";
+import { Switch, Text } from "@posthog/quill";
+import {
+ clampSpendLine,
+ SpendLimitSlider,
+} from "@posthog/ui/features/settings/sections/SpendLimitSlider";
+import { navigateToSettings } from "@posthog/ui/router/navigationBridge";
+
+interface SpendLimitCardProps {
+ scope: SpendLimitPeriod;
+ title: string;
+ /** Spend so far in this scope; null when it has no running total. */
+ spentUsd: number | null;
+ /** What the figure counts, e.g. "today". */
+ soFarLabel?: string;
+ /** Subheader under the title, saying what the scope counts. */
+ description: string;
+ markerUsd?: number | null;
+ markerTitle?: string;
+ markerLabel?: string;
+ tickReferenceUsd?: number | null;
+ limits: SpendLimits;
+ onCommit: (limits: SpendLimitsPatch) => void;
+ /** Lines to apply when the scope is switched on, if any can be derived. */
+ suggested?: { warnUsd: number; stopUsd: number } | null;
+ /** The deployment can hold a stop line. False renders and seeds the warning line only. */
+ stopAvailable: boolean;
+}
+
+/**
+ * One scope's limit, on its own switch. Off means both of its lines are clear,
+ * so the switch is the scope's state rather than a separate setting that could
+ * disagree with it. The setter only appears once it is on.
+ */
+export function SpendLimitCard({
+ scope,
+ title,
+ spentUsd,
+ soFarLabel,
+ description,
+ markerUsd = null,
+ markerTitle,
+ markerLabel,
+ tickReferenceUsd,
+ limits,
+ onCommit,
+ suggested = null,
+ stopAvailable,
+}: SpendLimitCardProps) {
+ const { warnUsd, stopUsd } = limits[scope];
+ const effectiveStopUsd = stopAvailable ? stopUsd : null;
+ const enabled = warnUsd !== null || effectiveStopUsd !== null;
+ const summary =
+ spentUsd !== null
+ ? `${formatUsdCompact(spentUsd, { exactCents: true })}${soFarLabel ? ` ${soFarLabel}` : ""}`
+ : null;
+
+ const toggle = (next: boolean) => {
+ if (!next) {
+ onCommit({ [scope]: { warnUsd: null, stopUsd: null } });
+ return;
+ }
+ // Start from the person's own history where there is any; without any,
+ // round starter lines keep the scope editable rather than committing
+ // nulls, which would read as the switch refusing to turn on.
+ const seed = suggested ?? STARTER_SPEND_LINES[scope];
+ onCommit({
+ [scope]: {
+ warnUsd: seed.warnUsd,
+ stopUsd: stopAvailable ? seed.stopUsd : null,
+ },
+ });
+ };
+
+ return (
+ <div className="flex flex-col gap-3 rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid) px-4 py-3.5">
+ <div className="flex items-center justify-between gap-4">
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <Text className="text-(--gray-12) text-[13px]">{title}</Text>
+ <Text className="text-(--gray-11) text-[12px]">
+ {description}
+ {/* Only while off: once on, the track's own legend carries the
+ figures, and saying them twice reads as clutter. */}
+ {!enabled && summary && (
+ <>
+ {" "}
+ <button
+ type="button"
+ className="cursor-pointer border-(--gray-8) border-0 border-b border-dashed bg-transparent p-0 text-(--gray-11) text-[12px] tabular-nums hover:text-(--gray-12)"
+ onClick={() => navigateToSettings("plan-usage")}
+ title="See where this went"
+ data-attr={`spend-limit-${scope}-spent`}
+ >
+ {summary}
+ </button>
+ .
+ </>
+ )}
+ </Text>
+ </span>
+ <Switch
+ checked={enabled}
+ onCheckedChange={toggle}
+ aria-label={`${title} spend limit`}
+ data-attr={`spend-limit-${scope}-toggle`}
+ />
+ </div>
+ {enabled && (
+ <div className="border-(--gray-4) border-t border-dashed pt-3.5">
+ <SpendLimitSlider
+ warnUsd={warnUsd}
+ stopUsd={effectiveStopUsd}
+ spentUsd={spentUsd ?? 0}
+ markerUsd={markerUsd}
+ markerTitle={markerTitle}
+ markerLabel={markerLabel}
+ tickReferenceUsd={tickReferenceUsd}
+ periodLabel={title}
+ onCommit={(level, value) =>
+ onCommit({
+ [scope]: {
+ // The real ordering invariant: drags arrive pre-clamped, but
+ // typed input reaches here unclamped.
+ [level]: clampSpendLine(
+ level,
+ value,
+ level === "warn" ? effectiveStopUsd : warnUsd,
+ ),
+ // A stop commit is inert where the deployment cannot hold one.
+ ...(level === "stop" && !stopAvailable
+ ? { stopUsd: null }
+ : {}),
+ },
+ })
+ }
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.pointer.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.pointer.test.tsx
new file mode 100644
index 000000000000..9599d9632e37
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.pointer.test.tsx
@@ -0,0 +1,56 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SpendLimitSlider } from "./SpendLimitSlider";
+
+describe("SpendLimitSlider pointer drag", () => {
+ beforeEach(() => {
+ // jsdom implements neither pointer capture nor layout, so stub both: the
+ // handle captures the pointer on pointerdown, and valueFromPointer needs a
+ // non-zero track width to map a position to a value.
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue({
+ left: 0,
+ width: 200,
+ top: 0,
+ right: 200,
+ bottom: 14,
+ height: 14,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ } as DOMRect);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("drops the drag on pointercancel so a later click commits the saved line, not the drifted value", () => {
+ const onCommit = vi.fn();
+ render(
+ <SpendLimitSlider
+ warnUsd={20}
+ stopUsd={50}
+ spentUsd={0}
+ markerUsd={null}
+ periodLabel="Daily"
+ onCommit={onCommit}
+ />,
+ );
+ const warn = screen.getByLabelText("Daily warning line");
+
+ // Drag the handle to the middle of the track, then have the browser preempt
+ // the gesture the way a trackpad does mid-drag.
+ fireEvent.pointerDown(warn, { pointerId: 1, clientX: 0 });
+ fireEvent.pointerMove(warn, { pointerId: 1, clientX: 100 });
+ fireEvent.pointerCancel(warn, { pointerId: 1 });
+
+ // A plain click now must commit the saved $20, never the drifted amount.
+ fireEvent.pointerDown(warn, { pointerId: 2, clientX: 0 });
+ fireEvent.pointerUp(warn, { pointerId: 2, clientX: 0 });
+
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(onCommit).toHaveBeenCalledWith("warn", 20);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.test.ts b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.test.ts
new file mode 100644
index 000000000000..e275a4db6266
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.test.ts
@@ -0,0 +1,45 @@
+import { niceCeil } from "@posthog/core/billing/spendLimits";
+import { describe, expect, it } from "vitest";
+import { clampSpendLine, resolveScale, sliderStep } from "./SpendLimitSlider";
+
+describe("SpendLimitSlider", () => {
+ it.each([
+ [55, 100],
+ [100, 100],
+ [101, 200],
+ [440, 500],
+ [7, 10],
+ [1.4, 2],
+ [0, 100],
+ ] as const)("niceCeil(%s) -> %s", (value, expected) => {
+ expect(niceCeil(value)).toBe(expected);
+ });
+
+ it("keeps the scale stable across small edits", () => {
+ const scale = resolveScale(null, 55);
+ expect(scale).toBe(100);
+ // Lowering a line a bit must not rescale the track.
+ expect(resolveScale(scale, 44)).toBe(100);
+ // Passing the top grows it immediately.
+ expect(resolveScale(scale, 130)).toBe(200);
+ // Only a large drop shrinks it back.
+ expect(resolveScale(scale, 12)).toBe(20);
+ });
+
+ it.each([
+ [25, 0.5],
+ [100, 1],
+ [500, 5],
+ [1200, 10],
+ ] as const)("scale %s -> step %s", (scale, step) => {
+ expect(sliderStep(scale)).toBe(step);
+ });
+
+ it("never lets the warning line pass the stop line, and vice versa", () => {
+ expect(clampSpendLine("warn", 80, 50)).toBe(50);
+ expect(clampSpendLine("warn", 30, 50)).toBe(30);
+ expect(clampSpendLine("stop", 10, 20)).toBe(20);
+ expect(clampSpendLine("stop", 60, 20)).toBe(60);
+ expect(clampSpendLine("warn", 80, null)).toBe(80);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.tsx
new file mode 100644
index 000000000000..1b5e606663c3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitSlider.tsx
@@ -0,0 +1,319 @@
+import {
+ formatUsd,
+ formatUsdCompact,
+} from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ niceCeil,
+ type SpendLimitLevel,
+ spendTickIncrement,
+} from "@posthog/core/billing/spendLimits";
+import { SpendKnobValue } from "@posthog/ui/features/settings/sections/SpendKnobValue";
+import { useRef, useState } from "react";
+
+function isPositive(value: number | null): value is number {
+ return value !== null && value > 0;
+}
+
+/**
+ * The track's dollar range, kept stable across small edits: it grows the
+ * moment a value passes the top, but shrinks only once everything sits far
+ * below it. Without the hysteresis every drag release would rescale the
+ * track and make all the handles jump.
+ */
+export function resolveScale(previous: number | null, needed: number): number {
+ const target = niceCeil(needed);
+ if (previous === null || previous <= 0) return target;
+ if (needed > previous) return target;
+ if (needed < previous * 0.4) return target;
+ return previous;
+}
+
+/** Drag granularity grows with the track's range so values stay round. */
+export function sliderStep(scale: number): number {
+ if (scale <= 30) return 0.5;
+ if (scale <= 120) return 1;
+ if (scale <= 600) return 5;
+ return 10;
+}
+
+/**
+ * Keeps the pair ordered: the warning line never sits above the stop line.
+ * Applied on every commit path (drag, keys, inputs) so the invariant holds
+ * no matter how a value arrives.
+ */
+export function clampSpendLine(
+ level: SpendLimitLevel,
+ value: number,
+ otherUsd: number | null,
+): number {
+ if (!isPositive(otherUsd)) return value;
+ if (level === "warn") return Math.min(value, otherUsd);
+ return Math.max(value, otherUsd);
+}
+
+interface SpendLimitSliderProps {
+ warnUsd: number | null;
+ stopUsd: number | null;
+ /** Spend so far in the period; 0 when unknown. */
+ spentUsd: number;
+ /** Optional reference marker, e.g. average per day or projected pace. */
+ markerUsd: number | null;
+ /** Tooltip explaining what the marker is. */
+ markerTitle?: string;
+ /** Short label under the marker, e.g. "avg $12.40". */
+ markerLabel?: string;
+ /**
+ * The figure tick spacing is anchored to, so a tick reads as roughly a day's
+ * average or a month's pace rather than an arbitrary slice of the track.
+ */
+ tickReferenceUsd?: number | null;
+ /** "Daily" or "Monthly", for the handles' accessible names. */
+ periodLabel: string;
+ onCommit: (level: SpendLimitLevel, value: number) => void;
+}
+
+/**
+ * The lines as a draggable control: spend so far fills the track and each
+ * set line is a handle that can be dragged (or arrow-keyed) to a new
+ * amount. The track carries no labels at rest, since the inputs below hold the
+ * values, and a value bubble follows the handle only while it moves.
+ */
+export function SpendLimitSlider({
+ warnUsd,
+ stopUsd,
+ spentUsd,
+ markerUsd,
+ markerTitle,
+ markerLabel,
+ tickReferenceUsd,
+ periodLabel,
+ onCommit,
+}: SpendLimitSliderProps) {
+ const trackRef = useRef<HTMLDivElement>(null);
+ const [drag, setDrag] = useState<{
+ level: SpendLimitLevel;
+ value: number;
+ } | null>(null);
+
+ // A preempted pointer (trackpad or touch gesture the browser cancels
+ // mid-drag, or lost capture) must drop the live drag without committing, so
+ // the handle stops tracking the cursor and the callout falls back to the
+ // saved line. Mirrors the grid-drag cleanup.
+ const cancelDrag = (level: SpendLimitLevel) => {
+ setDrag((current) => (current?.level === level ? null : current));
+ };
+
+ const liveWarn = drag?.level === "warn" ? drag.value : warnUsd;
+ const liveStop = drag?.level === "stop" ? drag.value : stopUsd;
+
+ const needed =
+ Math.max(...[warnUsd, stopUsd, markerUsd, spentUsd].filter(isPositive), 0) *
+ 1.1;
+ const [scale, setScale] = useState(() => resolveScale(null, needed || 90));
+ // Derive during render, never mid-drag: rescaling under a moving handle
+ // would shift every other handle with it.
+ if (drag === null) {
+ const next = resolveScale(scale, needed || 90);
+ if (next !== scale) setScale(next);
+ }
+
+ const step = sliderStep(scale);
+ const percent = (value: number) =>
+ Math.min(100, Math.max(0, (value / scale) * 100));
+ const settleClass = drag
+ ? ""
+ : "transition-[left,width,background-color] duration-300 motion-reduce:transition-none";
+
+ const otherLine = (level: SpendLimitLevel): number | null =>
+ level === "warn" ? stopUsd : warnUsd;
+
+ const valueFromPointer = (
+ level: SpendLimitLevel,
+ clientX: number,
+ ): number => {
+ const rect = trackRef.current?.getBoundingClientRect();
+ if (!rect || rect.width === 0) return step;
+ const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
+ const snapped = Math.max(step, Math.round((ratio * scale) / step) * step);
+ return clampSpendLine(level, snapped, otherLine(level));
+ };
+
+ const handles: {
+ level: SpendLimitLevel;
+ value: number;
+ name: string;
+ }[] = [];
+ if (isPositive(liveWarn)) {
+ handles.push({ level: "warn", value: liveWarn, name: "warning" });
+ }
+ if (isPositive(liveStop)) {
+ handles.push({ level: "stop", value: liveStop, name: "stop" });
+ }
+ // With no lines yet, the track still shows spend and the reference marker,
+ // so the suggestion above has something visual to anchor to.
+ if (handles.length === 0 && spentUsd <= 0 && !isPositive(markerUsd)) {
+ return null;
+ }
+
+ const warnPercent = isPositive(liveWarn) ? percent(liveWarn) : null;
+ const stopPercent = isPositive(liveStop) ? percent(liveStop) : null;
+ // Zones read left to right: fine up to the warning, caution up to the stop,
+ // and the tail past the stop is where spend cannot go.
+ const tickIncrement = spendTickIncrement(scale, tickReferenceUsd ?? null);
+ const tickPercents: number[] = [];
+ if (tickIncrement > 0) {
+ for (let value = tickIncrement; value < scale; value += tickIncrement) {
+ tickPercents.push(percent(value));
+ }
+ }
+ const cautionStart = warnPercent ?? 0;
+ const cautionWidth = Math.max(
+ 0,
+ (stopPercent ?? cautionStart) - cautionStart,
+ );
+
+ return (
+ <div className="pt-10 pb-1">
+ <div ref={trackRef} className="relative h-3.5 w-full">
+ <div className="absolute inset-0 overflow-hidden rounded-full bg-(--gray-4)">
+ {/* One colored band, between the warning and the stop. Everything
+ else is the track's own gray, so color only ever means caution. */}
+ {cautionWidth > 0 && (
+ <div
+ className={`absolute inset-y-0 bg-(--amber-9) ${settleClass}`}
+ style={{ left: `${cautionStart}%`, width: `${cautionWidth}%` }}
+ />
+ )}
+ {stopPercent !== null && (
+ <div
+ className={`absolute inset-y-0 right-0 bg-(--red-9) ${settleClass}`}
+ style={{ left: `${stopPercent}%` }}
+ />
+ )}
+ {/* A ruler: one dot per increment, so a position on the track can be
+ read rather than guessed. */}
+ {tickPercents.map((tickPercent) => (
+ <span
+ key={tickPercent}
+ aria-hidden="true"
+ className="-translate-x-1/2 -translate-y-1/2 absolute top-1/2 size-[3px] rounded-full bg-(--gray-a7)"
+ style={{ left: `${tickPercent}%` }}
+ />
+ ))}
+ {/* Spend so far: a drifting hatch, so a live figure reads as live
+ without competing with the caution band for meaning. */}
+ {spentUsd > 0 && (
+ <div
+ aria-hidden="true"
+ className={`absolute inset-y-0 left-0 animate-[spend-usage-drift_1.1s_linear_infinite] bg-(--gray-6) [background-image:repeating-linear-gradient(115deg,rgba(255,255,255,0.5)_0_2px,transparent_2px_6px)] motion-reduce:animate-none ${settleClass}`}
+ style={{ width: `${percent(spentUsd)}%` }}
+ />
+ )}
+ </div>
+ {isPositive(markerUsd) && (
+ <div
+ className={`-translate-x-1/2 absolute inset-y-0 w-[2px] rounded-full bg-(--gray-12) opacity-40 ${settleClass}`}
+ style={{ left: `${percent(markerUsd)}%` }}
+ title={markerTitle}
+ />
+ )}
+ {handles.map((handle) => (
+ <span
+ key={`${handle.level}-value`}
+ className={`-top-9 -translate-x-1/2 absolute z-20 whitespace-nowrap ${settleClass}`}
+ style={{
+ left: `${Math.min(94, Math.max(6, percent(handle.value)))}%`,
+ }}
+ >
+ <SpendKnobValue
+ valueUsd={handle.value}
+ label={formatUsdCompact(handle.value)}
+ name={`${periodLabel} ${handle.name} line`}
+ onCommit={(value) => onCommit(handle.level, value)}
+ />
+ </span>
+ ))}
+ {handles.map((handle) => (
+ <div
+ key={handle.level}
+ className={`-translate-x-1/2 absolute top-1/2 z-10 ${settleClass}`}
+ style={{ left: `${percent(handle.value)}%` }}
+ >
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label={`${periodLabel} ${handle.name} line`}
+ aria-valuemin={0}
+ aria-valuemax={Math.round(scale)}
+ aria-valuenow={handle.value}
+ aria-valuetext={formatUsd(handle.value)}
+ data-attr={`spend-limit-slider-${handle.level}`}
+ // A larger transparent hit area around a notch the size of the
+ // track, so the handle sits inside the color rather than on it.
+ className="-translate-y-1/2 flex size-6 cursor-grab touch-none items-center justify-center rounded-full focus-visible:outline focus-visible:outline-(--accent-9) focus-visible:outline-2 focus-visible:outline-offset-1 active:cursor-grabbing"
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ setDrag({ level: handle.level, value: handle.value });
+ }}
+ onPointerMove={(event) => {
+ if (drag?.level !== handle.level) return;
+ setDrag({
+ level: handle.level,
+ value: valueFromPointer(handle.level, event.clientX),
+ });
+ }}
+ onPointerUp={() => {
+ if (drag?.level !== handle.level) return;
+ onCommit(handle.level, drag.value);
+ setDrag(null);
+ }}
+ onPointerCancel={() => cancelDrag(handle.level)}
+ onLostPointerCapture={() => cancelDrag(handle.level)}
+ onKeyDown={(event) => {
+ const direction =
+ event.key === "ArrowRight" || event.key === "ArrowUp"
+ ? 1
+ : event.key === "ArrowLeft" || event.key === "ArrowDown"
+ ? -1
+ : 0;
+ if (direction === 0) return;
+ event.preventDefault();
+ const next = clampSpendLine(
+ handle.level,
+ Math.max(step, handle.value + direction * step),
+ otherLine(handle.level),
+ );
+ if (next !== handle.value) onCommit(handle.level, next);
+ }}
+ >
+ <span
+ aria-hidden="true"
+ className="size-3.5 rounded-full bg-[#fff] shadow-[0_1px_2px_rgba(0,0,0,0.3)] transition-transform duration-150 motion-reduce:transition-none"
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ <div className="relative mt-2 h-3">
+ <span className="absolute left-0 whitespace-nowrap text-(--gray-11) text-[9.5px] tabular-nums leading-none">
+ {spentUsd > 0 ? `${formatUsdCompact(spentUsd)} spent` : "$0"}
+ </span>
+ {isPositive(markerUsd) && markerLabel && (
+ <span
+ className={`-translate-x-1/2 absolute whitespace-nowrap text-(--gray-11) text-[9.5px] tabular-nums leading-none ${settleClass}`}
+ style={{
+ left: `${Math.min(88, Math.max(8, percent(markerUsd)))}%`,
+ }}
+ title={markerTitle}
+ >
+ {markerLabel}
+ </span>
+ )}
+ <span className="absolute right-0 text-(--gray-9) text-[9px] tabular-nums leading-none">
+ {formatUsdCompact(scale)}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.stories.tsx
new file mode 100644
index 000000000000..890d9a8c6146
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.stories.tsx
@@ -0,0 +1,55 @@
+import {
+ EMPTY_SPEND_LIMITS,
+ type SpendLimits,
+} from "@posthog/core/billing/spendLimits";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { SpendLimitsSettingsView } from "./SpendLimitsSettings";
+
+const LINES: SpendLimits = {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: 500, stopUsd: 1000 },
+};
+
+const meta: Meta<typeof SpendLimitsSettingsView> = {
+ title: "Settings/SpendLimitsSettings",
+ component: SpendLimitsSettingsView,
+ decorators: [
+ (Story) => (
+ <div className="mx-auto max-w-3xl p-6">
+ <Story />
+ </div>
+ ),
+ ],
+ args: {
+ spendLimits: LINES,
+ totals: { todayUsd: 7.31, monthUsd: 84.2, avgDailyUsd: 12.4 },
+ stopAvailable: true,
+ onCommit: () => {},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof SpendLimitsSettingsView>;
+
+export const BelowLines: Story = {};
+
+export const AllOff: Story = {
+ args: { spendLimits: EMPTY_SPEND_LIMITS },
+};
+
+export const NoLinesNoHistory: Story = {
+ args: { spendLimits: EMPTY_SPEND_LIMITS, totals: null },
+};
+
+export const WarningCrossed: Story = {
+ args: { totals: { todayUsd: 26.4, monthUsd: 231.9, avgDailyUsd: 12.4 } },
+};
+
+export const StopCrossed: Story = {
+ args: { totals: { todayUsd: 61.75, monthUsd: 412.5, avgDailyUsd: 15.8 } },
+};
+
+/** No gateway behind the lines, so they inform and pause this app only. */
+export const InformOnly: Story = {
+ args: { stopAvailable: false },
+};
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.tsx
new file mode 100644
index 000000000000..6c38ad700a21
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SpendLimitsSettings.tsx
@@ -0,0 +1,171 @@
+import { formatUsd } from "@posthog/core/billing/spendAnalysisFormat";
+import {
+ projectedMonthUsd,
+ type SpendLimits,
+ type SpendLimitsPatch,
+ suggestedSpendLimits,
+ utcDayIso,
+} from "@posthog/core/billing/spendLimits";
+import {
+ type SpendSnapshot,
+ useSpendTotals,
+} from "@posthog/ui/features/billing/useSpendTotals";
+import {
+ USER_SPEND_LIMIT_QUERY_KEY,
+ useSetUserSpendLimit,
+ useUserSpendLimit,
+} from "@posthog/ui/features/billing/useUserSpendLimit";
+import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";
+import { SpendLimitCard } from "@posthog/ui/features/settings/sections/SpendLimitCard";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { useEffect } from "react";
+
+/**
+ * The window the stop line resets over. The gateway counts a fixed window
+ * that starts at the first spend after a reset, so this is 30 days of spend
+ * rather than a calendar month.
+ */
+const MONTH_WINDOW_SECONDS = 30 * 24 * 60 * 60;
+
+export function SpendLimitsSettings() {
+ const spendLimits = useSettingsStore((state) => state.spendLimits);
+ const setSpendLimits = useSettingsStore((state) => state.setSpendLimits);
+ const totals = useSpendTotals();
+ const spendLimit = useUserSpendLimit();
+ const pushLimit = useSetUserSpendLimit();
+ const queryClient = useQueryClient();
+ const serverLimitUsd = spendLimit.data?.available
+ ? (spendLimit.data.limitUsd ?? null)
+ : undefined;
+
+ // The gateway holds the line whether this app is running or not, so its
+ // stored value is the truth a stale local one has to give way to. Keyed on
+ // the fetched value alone: a local edit is pushed below, and reacting to it
+ // here would fight the person typing.
+ useEffect(() => {
+ if (serverLimitUsd === undefined) return;
+ setSpendLimits({ month: { stopUsd: serverLimitUsd } });
+ }, [serverLimitUsd, setSpendLimits]);
+
+ const commit = (limits: SpendLimitsPatch) => {
+ setSpendLimits(limits);
+ if (
+ !limits.month ||
+ !("stopUsd" in limits.month) ||
+ !spendLimit.data?.available
+ ) {
+ return;
+ }
+ pushLimit.mutate(
+ {
+ limitUsd: limits.month.stopUsd ?? null,
+ windowSeconds: MONTH_WINDOW_SECONDS,
+ },
+ {
+ onError: (error) => {
+ // The gateway still holds its old line, so put the store back on it
+ // and refetch; otherwise the card would show a stop the gateway
+ // never accepted, and the reconcile effect above would not re-fire.
+ setSpendLimits({ month: { stopUsd: serverLimitUsd ?? null } });
+ queryClient.invalidateQueries({
+ queryKey: USER_SPEND_LIMIT_QUERY_KEY,
+ });
+ toast.error("Couldn't save your stop line", {
+ description:
+ error instanceof Error ? error.message : "Try again in a moment.",
+ });
+ },
+ },
+ );
+ };
+
+ return (
+ <SpendLimitsSettingsView
+ spendLimits={spendLimits}
+ totals={totals}
+ stopAvailable={spendLimit.data?.available ?? false}
+ onCommit={commit}
+ />
+ );
+}
+
+interface SpendLimitsSettingsViewProps {
+ spendLimits: SpendLimits;
+ /** Live spend for the sliders; null renders them without fill or marker. */
+ totals: SpendSnapshot | null;
+ /** The deployment can hold a stop line; without it only warning lines are offered. */
+ stopAvailable: boolean;
+ onCommit: (limits: SpendLimitsPatch) => void;
+}
+
+export function SpendLimitsSettingsView({
+ spendLimits,
+ totals,
+ stopAvailable,
+ onCommit,
+}: SpendLimitsSettingsViewProps) {
+ const todayIso = utcDayIso();
+ const avgUsd = totals && totals.avgDailyUsd > 0 ? totals.avgDailyUsd : null;
+ const projectedUsd =
+ avgUsd !== null ? projectedMonthUsd(avgUsd, todayIso) : null;
+ const suggestion =
+ avgUsd !== null ? suggestedSpendLimits(avgUsd, todayIso) : null;
+
+ return (
+ <SettingsSubsection
+ title="Spend limits"
+ description={
+ stopAvailable
+ ? "A warning line notifies you. A stop line pauses new agent messages until you raise or clear it, and a turn already running always plays out. Lines count model spend, not sandbox compute."
+ : "A warning line notifies you when spend passes it, and a turn already running always plays out. Lines count model spend, not sandbox compute."
+ }
+ >
+ <SpendLimitCard
+ scope="day"
+ title="Per day"
+ description="Counts every task you run in a day, and resets at midnight UTC."
+ spentUsd={totals?.todayUsd ?? null}
+ soFarLabel="today"
+ markerUsd={avgUsd}
+ markerLabel={avgUsd !== null ? `avg ${formatUsd(avgUsd)}` : undefined}
+ tickReferenceUsd={avgUsd}
+ markerTitle={
+ avgUsd !== null
+ ? `Average per day over the last 30 days · ${formatUsd(avgUsd)}`
+ : undefined
+ }
+ limits={spendLimits}
+ onCommit={onCommit}
+ suggested={suggestion?.day ?? null}
+ stopAvailable={stopAvailable}
+ />
+ <SpendLimitCard
+ scope="month"
+ title="Per month"
+ description={
+ stopAvailable
+ ? "Counts 30 days of model spend, and restarts once the window runs out."
+ : "Counts the whole calendar month, and resets on the first."
+ }
+ spentUsd={totals?.monthUsd ?? null}
+ soFarLabel="this month"
+ markerUsd={projectedUsd}
+ markerLabel={
+ projectedUsd !== null ? `pace ${formatUsd(projectedUsd)}` : undefined
+ }
+ tickReferenceUsd={projectedUsd}
+ markerTitle={
+ projectedUsd !== null
+ ? `Projected month total at your average pace · about ${formatUsd(projectedUsd)}`
+ : undefined
+ }
+ limits={spendLimits}
+ onCommit={onCommit}
+ suggested={suggestion?.month ?? null}
+ stopAvailable={stopAvailable}
+ />
+ </SettingsSubsection>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
index fd8c22345965..a3abf420d048 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
@@ -142,6 +142,32 @@ export const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [
label: "Plan & usage",
keywords: ["billing", "credits", "spend", "subscription"],
},
+ {
+ category: "cost-management",
+ label: "Cost management",
+ keywords: ["cost", "spend", "budget", "savings", "recommendations"],
+ },
+ {
+ category: "cost-management",
+ label: "Spend limits",
+ keywords: [
+ "budget",
+ "warning",
+ "stop line",
+ "daily spend",
+ "monthly spend",
+ ],
+ },
+ {
+ category: "cost-management",
+ label: "Default model",
+ keywords: ["cheaper model", "multiplier", "model cost", "switch model"],
+ },
+ {
+ category: "cost-management",
+ label: "Custom sandbox image",
+ keywords: ["image", "tools", "ripgrep", "cloud runs", "setup"],
+ },
{
category: "workspaces",
label: "Workspaces",
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.test.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.test.ts
index 5a8e4338678e..d7a314b9d6e1 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.test.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.test.ts
@@ -1,3 +1,4 @@
+import { EMPTY_SPEND_LIMITS } from "@posthog/core/billing/spendLimits";
import { TIP_KEYS } from "@posthog/ui/features/settings/tipKeys";
import {
flushRendererStateWrites,
@@ -451,6 +452,48 @@ describe("feature settingsStore custom sounds", () => {
);
});
+describe("feature settingsStore spend limits rehydrate", () => {
+ beforeEach(async () => {
+ await resetPersistenceMocks();
+ });
+
+ it.each([
+ {
+ label: "flat pre-rename keys into the per-period shape",
+ persistedLimits: {
+ dailyWarnUsd: 20,
+ dailyAlertUsd: 50,
+ monthlyStopUsd: 400,
+ },
+ expected: {
+ day: { warnUsd: 20, stopUsd: 50 },
+ month: { warnUsd: null, stopUsd: 400 },
+ },
+ },
+ {
+ label: "a warn line above its stop line down onto it",
+ persistedLimits: { day: { warnUsd: 80, stopUsd: 50 } },
+ expected: {
+ day: { warnUsd: 50, stopUsd: 50 },
+ month: { warnUsd: null, stopUsd: null },
+ },
+ },
+ {
+ label: "garbage values into cleared lines",
+ persistedLimits: { day: "nope", dailyWarnUsd: -3, monthlyStopUsd: "x" },
+ expected: EMPTY_SPEND_LIMITS,
+ },
+ ])("rehydrate migrates $label", async ({ persistedLimits, expected }) => {
+ getItem.mockResolvedValue(
+ JSON.stringify({ state: { spendLimits: persistedLimits }, version: 1 }),
+ );
+
+ await useSettingsStore.persist.rehydrate();
+
+ expect(useSettingsStore.getState().spendLimits).toEqual(expected);
+ });
+});
+
describe("getEffectiveCustomInstructions", () => {
const synced = {
path: "/home/u/.claude/CLAUDE.md",
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index d5094be18405..1abbb3694c20 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -1,4 +1,12 @@
+import type { CostChecklistItemKind } from "@posthog/core/billing/costChecklist";
+import {
+ EMPTY_SPEND_LIMITS,
+ pruneSpendNoticesSeen,
+ type SpendLimits,
+ type SpendLimitsPatch,
+} from "@posthog/core/billing/spendLimits";
import type { UserRepositoryIntegrationRef } from "@posthog/core/integrations/repositories";
+import { clampAutoCompactPercent } from "@posthog/core/sessions/autoCompact";
import type {
Adapter,
AgentRuntime,
@@ -236,6 +244,29 @@ interface SettingsStore {
diffOpenMode: DiffOpenMode;
setDiffOpenMode: (mode: DiffOpenMode) => void;
+ // Spend limits. A warn line only notifies; a stop line pauses new agent
+ // messages in this app, and the monthly stop also syncs to the gateway
+ // where deployments enforce it.
+ spendLimits: SpendLimits;
+ // Crossing notices already shown, keyed by period/level/anchor/amount so
+ // each line notifies once per day or month at a given amount.
+ spendNoticesSeen: Record<string, string>;
+ warnOnMidSessionModelSwitch: boolean;
+ // Cost management checklist items the user has acted on. Nothing here is a
+ // dismissal: an item lands here only once its change was made, and then
+ // stays as the checked record of it.
+ costChecklistDone: CostChecklistItemKind[];
+ /**
+ * Compact a session once the context window passes this percent, or null to
+ * leave compaction to the model. Off by default.
+ */
+ autoCompactPercent: number | null;
+ setSpendLimits: (limits: SpendLimitsPatch) => void;
+ markSpendNoticeSeen: (key: string, anchor: string, todayIso: string) => void;
+ setWarnOnMidSessionModelSwitch: (enabled: boolean) => void;
+ markCostChecklistDone: (kind: CostChecklistItemKind) => void;
+ setAutoCompactPercent: (percent: number | null) => void;
+
// System / power / permissions
allowBypassPermissions: boolean;
preventSleepWhileRunning: boolean;
@@ -469,6 +500,40 @@ export const useSettingsStore = create<SettingsStore>()(
diffOpenMode: "auto",
setDiffOpenMode: (mode) => set({ diffOpenMode: mode }),
+ // Spend limits
+ spendLimits: EMPTY_SPEND_LIMITS,
+ spendNoticesSeen: {},
+ warnOnMidSessionModelSwitch: true,
+ setSpendLimits: (limits) =>
+ set((state) => ({
+ spendLimits: {
+ day: { ...state.spendLimits.day, ...limits.day },
+ month: { ...state.spendLimits.month, ...limits.month },
+ },
+ })),
+ markSpendNoticeSeen: (key, anchor, todayIso) =>
+ set((state) => ({
+ spendNoticesSeen: {
+ ...pruneSpendNoticesSeen(state.spendNoticesSeen, todayIso),
+ [key]: anchor,
+ },
+ })),
+ setWarnOnMidSessionModelSwitch: (enabled) =>
+ set({ warnOnMidSessionModelSwitch: enabled }),
+ costChecklistDone: [],
+ autoCompactPercent: null,
+ setAutoCompactPercent: (percent) =>
+ set({
+ autoCompactPercent:
+ percent === null ? null : clampAutoCompactPercent(percent),
+ }),
+ markCostChecklistDone: (kind) =>
+ set((state) =>
+ state.costChecklistDone.includes(kind)
+ ? state
+ : { costChecklistDone: [...state.costChecklistDone, kind] },
+ ),
+
// System / power / permissions
allowBypassPermissions: false,
preventSleepWhileRunning: false,
@@ -620,6 +685,13 @@ export const useSettingsStore = create<SettingsStore>()(
// Diff viewer
diffOpenMode: state.diffOpenMode,
+ // Spend limits
+ spendLimits: state.spendLimits,
+ spendNoticesSeen: state.spendNoticesSeen,
+ warnOnMidSessionModelSwitch: state.warnOnMidSessionModelSwitch,
+ costChecklistDone: state.costChecklistDone,
+ autoCompactPercent: state.autoCompactPercent,
+
// System / power / permissions
allowBypassPermissions: state.allowBypassPermissions,
preventSleepWhileRunning: state.preventSleepWhileRunning,
@@ -675,6 +747,54 @@ export const useSettingsStore = create<SettingsStore>()(
) {
(merged as Record<string, unknown>).completionSound = "none";
}
+ // Persisted blobs from before the per-period shape carry flat keys
+ // (and older ones alert keys); every line must come back as a
+ // positive number or null, never undefined.
+ {
+ const raw = (merged.spendLimits ?? {}) as unknown as Record<
+ string,
+ unknown
+ >;
+ const line = (...values: unknown[]): number | null => {
+ for (const value of values) {
+ if (
+ typeof value === "number" &&
+ Number.isFinite(value) &&
+ value > 0
+ ) {
+ return value;
+ }
+ }
+ return null;
+ };
+ const migratedLines = (
+ period: "day" | "month",
+ flatPrefix: "daily" | "monthly",
+ ): SpendLimits["day"] => {
+ const nested = raw[period];
+ const lines =
+ typeof nested === "object" && nested !== null
+ ? (nested as Record<string, unknown>)
+ : {};
+ const stopUsd = line(
+ lines.stopUsd,
+ raw[`${flatPrefix}StopUsd`],
+ raw[`${flatPrefix}AlertUsd`],
+ );
+ const warnUsd = line(lines.warnUsd, raw[`${flatPrefix}WarnUsd`]);
+ return {
+ warnUsd:
+ warnUsd !== null && stopUsd !== null
+ ? Math.min(warnUsd, stopUsd)
+ : warnUsd,
+ stopUsd,
+ };
+ };
+ merged.spendLimits = {
+ day: migratedLines("day", "daily"),
+ month: migratedLines("month", "monthly"),
+ };
+ }
return merged;
},
},
diff --git a/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts b/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts
index 1567d70c73fa..223c4d3c8908 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsVisibility.test.ts
@@ -21,7 +21,19 @@ describe("getHiddenSettingsCategories", () => {
localWorkspaces: true,
quickAskAvailable: true,
},
- expected: ["plan-usage"],
+ expected: ["plan-usage", "cost-management"],
+ },
+ {
+ // Every limit and recommendation on the page is measured against
+ // personal spend, so without it the page has nothing to show.
+ name: "hides cost management without spend analysis",
+ input: {
+ billingEnabled: true,
+ spendAnalysisEnabled: false,
+ localWorkspaces: true,
+ quickAskAvailable: true,
+ },
+ expected: ["cost-management"],
},
{
name: "hides host-specific categories without local workspaces",
diff --git a/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts b/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts
index c4166eac9d3e..8f27e921cd46 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsVisibility.ts
@@ -36,6 +36,9 @@ export function getHiddenSettingsCategories({
if (!billingEnabled && !spendAnalysisEnabled) {
hiddenCategories.add("plan-usage");
}
+ if (!spendAnalysisEnabled) {
+ hiddenCategories.add("cost-management");
+ }
if (!localWorkspaces) {
for (const category of LOCAL_ONLY_CATEGORIES) {
hiddenCategories.add(category);
diff --git a/products/desktop/packages/ui/src/features/settings/types.ts b/products/desktop/packages/ui/src/features/settings/types.ts
index 1c5558e1e600..1b31eebde7c9 100644
--- a/products/desktop/packages/ui/src/features/settings/types.ts
+++ b/products/desktop/packages/ui/src/features/settings/types.ts
@@ -2,6 +2,7 @@ export type SettingsCategory =
| "general"
| "notifications"
| "plan-usage"
+ | "cost-management"
| "workspaces"
| "worktrees"
| "environments"
@@ -25,6 +26,7 @@ export const SETTINGS_CATEGORIES: readonly SettingsCategory[] = [
"general",
"notifications",
"plan-usage",
+ "cost-management",
"workspaces",
"worktrees",
"environments",
@@ -56,6 +58,7 @@ export const SETTINGS_PAGE_LABELS: Record<SettingsCategory, string> = {
general: "General",
notifications: "Notifications",
"plan-usage": "Plan & usage",
+ "cost-management": "Cost management",
workspaces: "Workspaces",
worktrees: "Worktrees",
environments: "Environments",
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 23003883a861..538a7dd66096 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
@@ -15,6 +15,10 @@ import { useHostTRPC, useHostTRPCClient } from "@posthog/host-router/react";
import { ButtonGroup } from "@posthog/quill";
import { type AgentRuntime, ANALYTICS_EVENTS } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
+import {
+ spendStopMessage,
+ useSpendStop,
+} from "@posthog/ui/features/billing/useSpendStop";
import {
TaskRepositoryChip,
TaskRepositoryDialog,
@@ -284,6 +288,7 @@ export function TaskInput({
setLastUsedPiModel,
_hasHydrated: settingsHydrated,
} = useSettingsStore();
+ const spendStop = useSpendStop();
const { data: skills } = useSkills();
const editorRef = useRef<EditorHandle>(null);
@@ -1444,7 +1449,11 @@ export function TaskInput({
channelContextBlocked ||
!isOnline ||
(runtime === "pi" ? isPiConfigLoading : isPreviewLoading) ||
- (runtime === "pi" && !currentPiModel)
+ (runtime === "pi" && !currentPiModel) ||
+ spendStop !== null
+ }
+ submitTooltipOverride={
+ spendStop ? spendStopMessage(spendStop) : undefined
}
tourTarget="task-input"
submitAdornment={
diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.stories.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.stories.tsx
new file mode 100644
index 000000000000..69ca9aff62ed
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.stories.tsx
@@ -0,0 +1,92 @@
+import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisTypes";
+import { EMPTY_SPEND_LIMITS } from "@posthog/core/billing/spendLimits";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useEffect } from "react";
+import { SpendOverTimeCard } from "./SpendOverTimeCard";
+
+function day(
+ dayIso: string,
+ costUsd: number,
+ models: { model: string; share: number }[] = [
+ { model: "claude-opus-4-8", share: 0.7 },
+ { model: "claude-haiku-4-5", share: 0.3 },
+ ],
+): SpendAnalysisFilledDay {
+ return {
+ day: dayIso,
+ cost_usd: costUsd,
+ event_count: Math.round(costUsd * 20),
+ input_tokens: Math.round(costUsd * 90_000),
+ output_tokens: Math.round(costUsd * 12_000),
+ models: models.map((entry) => ({
+ day: dayIso,
+ model: entry.model,
+ cost_usd: costUsd * entry.share,
+ input_tokens: Math.round(costUsd * entry.share * 90_000),
+ output_tokens: Math.round(costUsd * entry.share * 12_000),
+ generation_count: Math.round(costUsd * entry.share * 20),
+ })),
+ };
+}
+
+const COSTS = [4, 11, 7, 23, 15, 3, 0, 9, 27, 18, 6, 12, 54, 21] as const;
+const FILLED_DAYS = COSTS.map((cost, index) =>
+ day(`2026-08-${String(index + 5).padStart(2, "0")}`, cost),
+);
+
+function SpendLimitsDecorator({
+ children,
+ warnUsd,
+ stopUsd,
+}: {
+ children: React.ReactNode;
+ warnUsd: number | null;
+ stopUsd: number | null;
+}) {
+ useEffect(() => {
+ useSettingsStore.setState({
+ spendLimits: { ...EMPTY_SPEND_LIMITS, day: { warnUsd, stopUsd } },
+ });
+ return () => {
+ useSettingsStore.setState({ spendLimits: EMPTY_SPEND_LIMITS });
+ };
+ }, [warnUsd, stopUsd]);
+ return <>{children}</>;
+}
+
+const meta: Meta<typeof SpendOverTimeCard> = {
+ title: "Usage/SpendOverTimeCard",
+ component: SpendOverTimeCard,
+ decorators: [
+ (Story) => (
+ <div className="mx-auto max-w-3xl p-6">
+ <Story />
+ </div>
+ ),
+ ],
+ args: { filledDays: FILLED_DAYS },
+};
+
+export default meta;
+type Story = StoryObj<typeof SpendOverTimeCard>;
+
+export const NoLimits: Story = {
+ decorators: [
+ (Story) => (
+ <SpendLimitsDecorator warnUsd={null} stopUsd={null}>
+ <Story />
+ </SpendLimitsDecorator>
+ ),
+ ],
+};
+
+export const WithSpendLines: Story = {
+ decorators: [
+ (Story) => (
+ <SpendLimitsDecorator warnUsd={20} stopUsd={50}>
+ <Story />
+ </SpendLimitsDecorator>
+ ),
+ ],
+};
diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts
index c08444ebf851..795584e3148c 100644
--- a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts
+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts
@@ -9,6 +9,7 @@ vi.mock("@posthog/quill-charts", () => ({
import {
modelColorsForDays,
+ spendLimitGoalLines,
spendSeriesForDays,
tokenTotalsForDay,
} from "./SpendOverTimeCard";
@@ -86,3 +87,18 @@ describe("spendSeriesForDays", () => {
expect(colors.get("gpt-5")).not.toBe(colors.get("claude-opus-4-8"));
});
});
+
+describe("spendLimitGoalLines", () => {
+ it("draws a line only for the daily limits that are set", () => {
+ expect(spendLimitGoalLines({ warnUsd: null, stopUsd: null })).toEqual([]);
+
+ const lines = spendLimitGoalLines({
+ warnUsd: 20,
+ stopUsd: 50,
+ });
+ expect(lines.map((line) => [line.value, line.label])).toEqual([
+ [20, "Warning $20.00"],
+ [50, "Stop $50.00"],
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx
index 2299e38e58ad..ed49b6ae9d22 100644
--- a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx
+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx
@@ -4,7 +4,9 @@ import {
formatUsd,
} from "@posthog/core/billing/spendAnalysisFormat";
import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisTypes";
+import type { SpendLimits } from "@posthog/core/billing/spendLimits";
import {
+ type GoalLineConfig,
type Series,
TimeSeriesComboChart,
type TimeSeriesComboChartConfig,
@@ -13,6 +15,7 @@ import {
TooltipSwatch,
useChartTheme,
} from "@posthog/quill-charts";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { UsageCard } from "./UsageCard";
interface SpendOverTimeCardProps {
@@ -146,6 +149,28 @@ function SpendTooltip({
);
}
+/** The user's daily spend lines as chart goal lines on the daily axis. */
+export function spendLimitGoalLines(
+ limits: SpendLimits["day"],
+): GoalLineConfig[] {
+ const lines: GoalLineConfig[] = [];
+ if (limits.warnUsd !== null) {
+ lines.push({
+ value: limits.warnUsd,
+ label: `Warning ${formatUsd(limits.warnUsd)}`,
+ color: "var(--amber-9)",
+ });
+ }
+ if (limits.stopUsd !== null) {
+ lines.push({
+ value: limits.stopUsd,
+ label: `Stop ${formatUsd(limits.stopUsd)}`,
+ color: "var(--red-9)",
+ });
+ }
+ return lines;
+}
+
export function modelColorsForDays(
filledDays: SpendAnalysisFilledDay[],
): ReadonlyMap<string | null, string> {
@@ -164,6 +189,8 @@ export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {
const theme = useChartTheme();
const series = spendSeriesForDays(filledDays);
const modelColors = modelColorsForDays(filledDays);
+ const spendLimits = useSettingsStore((state) => state.spendLimits);
+ const goalLines = spendLimitGoalLines(spendLimits.day);
return (
<UsageCard
@@ -204,6 +231,7 @@ export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {
currency: "USD",
},
] as unknown as TimeSeriesComboChartConfig["yAxis"],
+ goalLines: goalLines.length > 0 ? goalLines : undefined,
barLayout: "grouped",
barCornerRadius: 2,
showCrosshair: true,
diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsx
index 3fce14d6cedb..54dc1213484f 100644
--- a/products/desktop/packages/ui/src/router/routes/__root.tsx
+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx
@@ -14,6 +14,7 @@ import { useServerArchiveSync } from "@posthog/ui/features/archive/useServerArch
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { UsageButton } from "@posthog/ui/features/billing/UsageButton";
import { UsageLimitModal } from "@posthog/ui/features/billing/UsageLimitModal";
+import { useSpendGuardrails } from "@posthog/ui/features/billing/useSpendGuardrails";
import { BrowserTabStrip } from "@posthog/ui/features/browser-tabs/BrowserTabStrip";
import { BrowserTabsDndProvider } from "@posthog/ui/features/browser-tabs/BrowserTabsDnd";
import { TabShortcutFallback } from "@posthog/ui/features/browser-tabs/TabShortcutFallback";
@@ -195,6 +196,7 @@ function RootLayout() {
const queryClient = useQueryClient();
const reconcilingTaskIds = useRef<Set<string>>(new Set());
const billingEnabled = useFeatureFlag(BILLING_FLAG);
+ useSpendGuardrails();
// "PostHog Web" is a channels-world affordance — show it only while the user
// is actually seeing channels (toggle on, which itself requires the flag).
const bluebirdEnabled = useFeatureFlag(
diff --git a/products/desktop/packages/ui/src/styles/globals.css b/products/desktop/packages/ui/src/styles/globals.css
index 928cb3ec2456..5051aa239846 100644
--- a/products/desktop/packages/ui/src/styles/globals.css
+++ b/products/desktop/packages/ui/src/styles/globals.css
@@ -1481,3 +1481,17 @@ body.ph-window-blurred .app-fade-in {
background-color: var(--fill-selected) !important;
}
}
+
+/*
+ * Spend-limit slider: the hatched overlay marking spend so far drifts, so a
+ * live figure reads as live rather than as a static striped fill. The stripe
+ * period is 6px, so translating by that lands back on an identical frame.
+ */
+@keyframes spend-usage-drift {
+ from {
+ background-position-x: 0;
+ }
+ to {
+ background-position-x: 6px;
+ }
+}
diff --git a/products/desktop/packages/workspace-server/src/services/skills-marketplace/schemas.ts b/products/desktop/packages/workspace-server/src/services/skills-marketplace/schemas.ts
index 2e262f47fe08..672c4a25864d 100644
--- a/products/desktop/packages/workspace-server/src/services/skills-marketplace/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills-marketplace/schemas.ts
@@ -5,6 +5,11 @@ export const marketplaceSkillRef = z.object({
source: z.string(),
/** Skill directory name inside the repository. */
skillId: z.string(),
+ /**
+ * Commit SHA, tag, or branch to fetch instead of HEAD. Curated installs pin
+ * a SHA so the content someone vetted is the content that lands.
+ */
+ ref: z.string().optional(),
});
export const marketplaceSearchInput = z.object({
diff --git a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
index 8ddcd98be29c..6b5907f02b73 100644
--- a/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
+++ b/products/desktop/packages/workspace-server/src/services/skills-marketplace/skills-marketplace.ts
@@ -16,6 +16,9 @@ import {
const SKILLS_SH_SEARCH_URL = "https://skills.sh/api/search";
const REPO_SOURCE_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
+// SHAs, tags, and slashless branch names; anything else could rewrite the
+// codeload URL path.
+const GIT_REF_PATTERN = /^[A-Za-z0-9_.-]+$/;
const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;
const MAX_UNZIPPED_BYTES = 500 * 1024 * 1024;
const MAX_PREVIEW_FILE_BYTES = 256 * 1024;
@@ -197,7 +200,7 @@ export class SkillsMarketplaceService {
private async getSkillFiles(
ref: MarketplaceSkillRef,
): Promise<Map<string, Uint8Array>> {
- const entries = await this.getRepoArchive(ref.source);
+ const entries = await this.getRepoArchive(ref.source, ref.ref);
const prefix = findSkillDirPrefix(entries, ref.skillId);
if (!prefix) {
throw new Error(`Skill "${ref.skillId}" was not found in ${ref.source}`);
@@ -211,21 +214,28 @@ export class SkillsMarketplaceService {
return files;
}
- private async getRepoArchive(source: string): Promise<Unzipped> {
+ private async getRepoArchive(
+ source: string,
+ gitRef?: string,
+ ): Promise<Unzipped> {
if (!REPO_SOURCE_PATTERN.test(source)) {
throw new Error(`Invalid repository reference: ${source}`);
}
+ if (gitRef !== undefined && !GIT_REF_PATTERN.test(gitRef)) {
+ throw new Error(`Invalid git ref: ${gitRef}`);
+ }
- const cached = this.archives.get(source);
+ const cacheKey = `${source}@${gitRef ?? "HEAD"}`;
+ const cached = this.archives.get(cacheKey);
if (cached && Date.now() - cached.fetchedAt < ARCHIVE_CACHE_TTL_MS) {
// LRU: refresh recency on hit.
- this.archives.delete(source);
- this.archives.set(source, cached);
+ this.archives.delete(cacheKey);
+ this.archives.set(cacheKey, cached);
return cached.entries;
}
const response = await fetch(
- `https://codeload.github.com/${source}/zip/HEAD`,
+ `https://codeload.github.com/${source}/zip/${gitRef ?? "HEAD"}`,
{ signal: AbortSignal.timeout(ARCHIVE_DOWNLOAD_TIMEOUT_MS) },
);
if (!response.ok) {
@@ -239,7 +249,7 @@ export class SkillsMarketplaceService {
const buffer = await readBodyWithLimit(response, MAX_ARCHIVE_BYTES, source);
const entries = await unzipWithLimit(buffer, MAX_UNZIPPED_BYTES, source);
- this.archives.set(source, { fetchedAt: Date.now(), entries });
+ this.archives.set(cacheKey, { fetchedAt: Date.now(), entries });
while (this.archives.size > ARCHIVE_CACHE_MAX_ENTRIES) {
const oldest = this.archives.keys().next().value;
if (oldest === undefined) break;