Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 85 additions & 28 deletions apps/code/src/renderer/api/posthogClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ export class SeatPaymentFailedError extends Error {
}
}

export type UsageLimitType = "burst" | "sustained" | null;

// Stable message so callers recognize this after a saga reduces the error to a string.
export const CLOUD_USAGE_LIMIT_ERROR_MESSAGE = "Cloud usage limit reached";

/** Thrown when the backend rejects a cloud run with a 429 usage-limit error. */
export class CloudUsageLimitError extends Error {
limitType: UsageLimitType;
resetAt: string | null;
isPro: boolean;
constructor(params: {
limitType: UsageLimitType;
resetAt: string | null;
isPro: boolean;
}) {
super(CLOUD_USAGE_LIMIT_ERROR_MESSAGE);
this.name = "CloudUsageLimitError";
this.limitType = params.limitType;
this.resetAt = params.resetAt;
this.isPro = params.isPro;
}
}

const log = logger.scope("posthog-client");

export const MCP_CATEGORIES = [
Expand Down Expand Up @@ -1106,12 +1129,11 @@ export class PostHogAPIClient {
mode: "interactive",
});

const data = await this.api.post(
`/api/projects/{project_id}/tasks/{id}/run/`,
{
const data = await this.withCloudUsageLimitCheck(() =>
this.api.post(`/api/projects/{project_id}/tasks/{id}/run/`, {
path: { project_id: teamId.toString(), id: taskId },
body,
},
}),
);

return data as unknown as Task;
Expand Down Expand Up @@ -1328,20 +1350,22 @@ export class PostHogAPIClient {
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/runs/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/`,
overrides: {
body: JSON.stringify({
...buildCloudRunRequestBody({
...options,
mode: options?.mode ?? "background",
const response = await this.withCloudUsageLimitCheck(() =>
this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/`,
overrides: {
body: JSON.stringify({
...buildCloudRunRequestBody({
...options,
mode: options?.mode ?? "background",
}),
environment: options?.environment ?? "local",
}),
environment: options?.environment ?? "local",
}),
},
});
},
}),
);

if (!response.ok) {
throw new Error(`Failed to create task run: ${response.statusText}`);
Expand All @@ -1359,17 +1383,19 @@ export class PostHogAPIClient {
const url = new URL(
`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/start/`,
);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/start/`,
overrides: {
body: JSON.stringify({
pending_user_message: options?.pendingUserMessage,
pending_user_artifact_ids: options?.pendingUserArtifactIds,
}),
},
});
const response = await this.withCloudUsageLimitCheck(() =>
this.api.fetcher.fetch({
method: "post",
url,
path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/start/`,
overrides: {
body: JSON.stringify({
pending_user_message: options?.pendingUserMessage,
pending_user_artifact_ids: options?.pendingUserArtifactIds,
}),
},
}),
);

if (!response.ok) {
throw new Error(`Failed to start task run: ${response.statusText}`);
Expand Down Expand Up @@ -2777,6 +2803,37 @@ export class PostHogAPIClient {
}
}

/**
* Run a cloud-run request, re-throwing a backend 429 usage-limit error as a
* typed CloudUsageLimitError so the UI can show the upgrade prompt.
*/
private async withCloudUsageLimitCheck<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (error) {
const parsed = this.parseFetcherError(error);
if (
parsed &&
parsed.status === 429 &&
parsed.body.code === "usage_limit_exceeded"
) {
const limitType = parsed.body.limit_type;
throw new CloudUsageLimitError({
limitType:
limitType === "burst" || limitType === "sustained"
? limitType
: null,
resetAt:
typeof parsed.body.reset_at === "string"
? parsed.body.reset_at
: null,
isPro: parsed.body.is_pro === true,
});
}
throw error;
}
}

private throwSeatError(error: unknown): never {
const parsed = this.parseFetcherError(error);

Expand Down
151 changes: 151 additions & 0 deletions apps/code/src/renderer/features/billing/preflightCloudUsage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import type { UsageOutput } from "@main/services/llm-gateway/schemas";
import { beforeEach, describe, expect, it, vi } from "vitest";

const refresh = vi.fn();
const getLatest = vi.fn();
const track = vi.fn();

vi.mock("@renderer/trpc/client", () => ({
trpcClient: {
usageMonitor: {
refresh: { mutate: () => refresh() },
getLatest: { query: () => getLatest() },
},
},
}));

vi.mock("@utils/analytics", () => ({
track: (...args: unknown[]) => track(...args),
}));

import { ANALYTICS_EVENTS } from "@shared/types/analytics";
import { assertCloudUsageAvailable } from "./preflightCloudUsage";
import { useUsageLimitStore } from "./stores/usageLimitStore";

function makeUsage(
overrides: Partial<{
sustained: boolean;
burst: boolean;
isRateLimited: boolean;
isPro: boolean;
}> = {},
): UsageOutput {
return {
product: "posthog_code",
user_id: 1,
sustained: {
used_percent: 50,
reset_at: "2026-05-01T13:00:00.000Z",
exceeded: overrides.sustained ?? false,
},
burst: {
used_percent: 30,
reset_at: "2026-05-01T12:10:00.000Z",
exceeded: overrides.burst ?? false,
},
is_rate_limited: overrides.isRateLimited ?? false,
is_pro: overrides.isPro ?? false,
};
}

interface Case {
name: string;
arrange: () => void;
available: boolean;
modal: {
isOpen: boolean;
bucket?: "burst" | "sustained" | null;
resetAt?: string | null;
isPro?: boolean | null;
};
trackPayload?: { bucket: "burst" | "sustained" | null; is_pro: boolean };
}

const cases: Case[] = [
{
name: "allows creation and shows no modal when under limit",
arrange: () => refresh.mockResolvedValue(makeUsage()),
available: true,
modal: { isOpen: false },
},
{
name: "blocks and shows the burst modal when the daily limit is exceeded",
arrange: () =>
refresh.mockResolvedValue(
makeUsage({ burst: true, isRateLimited: true, isPro: true }),
),
available: false,
modal: {
isOpen: true,
bucket: "burst",
resetAt: "2026-05-01T12:10:00.000Z",
isPro: true,
},
trackPayload: { bucket: "burst", is_pro: true },
},
{
name: "falls back to the latest snapshot when refresh fails",
arrange: () => {
refresh.mockRejectedValue(new Error("network"));
getLatest.mockResolvedValue(makeUsage({ sustained: true }));
},
available: false,
modal: { isOpen: true, bucket: "sustained" },
trackPayload: { bucket: "sustained", is_pro: false },
},
{
name: "falls back to the monthly bucket when only is_rate_limited is set",
arrange: () =>
refresh.mockResolvedValue(makeUsage({ isRateLimited: true })),
available: false,
modal: {
isOpen: true,
bucket: "sustained",
resetAt: "2026-05-01T13:00:00.000Z",
},
trackPayload: { bucket: "sustained", is_pro: false },
},
{
name: "fails open (allows creation) when usage cannot be fetched",
arrange: () => {
refresh.mockRejectedValue(new Error("network"));
getLatest.mockRejectedValue(new Error("network"));
},
available: true,
modal: { isOpen: false },
},
];

describe("assertCloudUsageAvailable", () => {
beforeEach(() => {
refresh.mockReset();
getLatest.mockReset();
track.mockReset();
useUsageLimitStore.getState().hide();
});

it.each(cases)(
"$name",
async ({ arrange, available, modal, trackPayload }) => {
arrange();

expect(await assertCloudUsageAvailable()).toBe(available);

const state = useUsageLimitStore.getState();
expect(state.isOpen).toBe(modal.isOpen);
if (modal.bucket !== undefined) expect(state.bucket).toBe(modal.bucket);
if (modal.resetAt !== undefined)
expect(state.resetAt).toBe(modal.resetAt);
if (modal.isPro !== undefined) expect(state.isPro).toBe(modal.isPro);

if (trackPayload) {
expect(track).toHaveBeenCalledWith(
ANALYTICS_EVENTS.CLOUD_TASK_USAGE_BLOCKED,
trackPayload,
);
} else {
expect(track).not.toHaveBeenCalled();
}
},
);
});
62 changes: 62 additions & 0 deletions apps/code/src/renderer/features/billing/preflightCloudUsage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
type UsageLimitBucket,
useUsageLimitStore,
} from "@features/billing/stores/usageLimitStore";
import { isUsageExceeded } from "@features/billing/utils";
import type { UsageOutput } from "@main/services/llm-gateway/schemas";
import { trpcClient } from "@renderer/trpc/client";
import { ANALYTICS_EVENTS } from "@shared/types/analytics";
import { track } from "@utils/analytics";
import { logger } from "@utils/logger";

const log = logger.scope("preflight-cloud-usage");

function usageLimitArgs(usage: UsageOutput): {
bucket: UsageLimitBucket;
resetAt: string;
isPro: boolean;
} {
// Prefer the bucket that's actually exceeded (burst/daily takes priority); if neither
// is flagged (is_rate_limited via a server-side valve), fall back to the monthly bucket
// so the modal still shows a title and reset time rather than a bare prompt.
const bucket: UsageLimitBucket = usage.burst.exceeded ? "burst" : "sustained";
return { bucket, resetAt: usage[bucket].reset_at, isPro: usage.is_pro };
}

async function fetchUsageSnapshot(): Promise<UsageOutput | null> {
const fresh = await trpcClient.usageMonitor.refresh
.mutate()
.catch((error) => {
log.warn("Usage refresh failed; falling back to latest snapshot", {
error,
});
return null;
});
if (fresh) return fresh;

return trpcClient.usageMonitor.getLatest.query().catch((error) => {
log.warn("Usage lookup failed; allowing cloud creation", { error });
return null;
});
}

/**
* Pre-flight gate for cloud task creation. Returns false (and shows the upgrade
* modal) when the team is over its usage limit, so no cloud task/run is created.
*
* Best-effort: if usage can't be fetched, returns true (fail open) — a usage
* service hiccup must never block task creation.
*/
export async function assertCloudUsageAvailable(): Promise<boolean> {
const usage = await fetchUsageSnapshot();
if (usage && isUsageExceeded(usage)) {
const args = usageLimitArgs(usage);
track(ANALYTICS_EVENTS.CLOUD_TASK_USAGE_BLOCKED, {
bucket: args.bucket,
is_pro: usage.is_pro,
});
useUsageLimitStore.getState().show(args);
Comment thread
tatoalo marked this conversation as resolved.
return false;
}
return true;
}
Loading
Loading