An open-source, faster Devin alternative
TypeScript
Name the re-projected halt reason after self-heal; count billing warnings only when displayed
Mohamed Habib via Computer6c2a2dd0e31a
diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex 94558588..be5881ed 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -380,6 +380,21 @@ test("a 402 carries the halt reason and prefers the action link", async (context);});+test("credits signals display only when the caller shows the warning", async (context) => {+ const urls: string[] = [];+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request) => {+ urls.push(String(input instanceof Request ? input.url : input));+ return Response.json({ usagePlan: "base" });+ });+ const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev", apiKey: "test" });+ await client.credits();+ await client.credits(true);+ assert.deepEqual(urls, [+ "https://app.opencomputer.dev/api/billing/credits",+ "https://app.opencomputer.dev/api/billing/credits?display=1",+ ]);+});+test("managed GitHub App requests use project-scoped status and connect routes", async (context) => {const requests: Request[] = [];context.mock.method(diff --git a/cli/src/api.ts b/cli/src/api.tsindex b58aa33f..a2bd3027 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -601,10 +601,13 @@ export class OpenComputerClient {return body as T;}- /** Prepaid credit status; `null` for orgs without a credit meter (legacy billing). */- async credits(): Promise<CreditsStatus | null> {+ /**+ * Prepaid credit status; `null` for orgs without a credit meter (legacy billing).+ * `display`: the caller shows the returned billing warning, so the edge counts it.+ */+ async credits(display = false): Promise<CreditsStatus | null> {try {- return await this.request<CreditsStatus>("/api/billing/credits");+ return await this.request<CreditsStatus>(`/api/billing/credits${display ? "?display=1" : ""}`);} catch (error) {if (error instanceof APIError && (error.status === 404 || error.status === 503)) {return null;diff --git a/cli/src/billing.ts b/cli/src/billing.tsindex 5b6e739f..5abbec2f 100644--- a/cli/src/billing.ts+++ b/cli/src/billing.ts@@ -157,9 +157,10 @@ export function creditsSummary(/** Best-effort fetch: billing must never fail an otherwise successful command. */export async function fetchCredits(client: OpenComputerClient,+ display = false,): Promise<CreditsStatus | null> {try {- return await client.credits();+ return await client.credits(display);} catch {return null;}diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex e4babcc3..1f709000 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -1377,7 +1377,7 @@ export async function runCommand(if (command === "billing" || command === "credits") {if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);- const status = await client.credits();+ const status = await client.credits(true);if (globals.json) printJSON(status);else if (!status) {process.stdout.write(@@ -1609,7 +1609,7 @@ export async function runCommand(globals.verbose === true,globals.idempotencyKey,);- const credits = await fetchCredits(client);+ const credits = await fetchCredits(client, true);if (globals.json) {const summary = creditsSummary(credits);printJSON(diff --git a/cloudflare-workers/api-edge/src/billing_onramp.test.ts b/cloudflare-workers/api-edge/src/billing_onramp.test.tsindex 88174e27..af1572aa 100644--- a/cloudflare-workers/api-edge/src/billing_onramp.test.ts+++ b/cloudflare-workers/api-edge/src/billing_onramp.test.ts@@ -5,6 +5,7 @@ import {billingWarningOf,emitPaywallShown,FREE_CREDITS_PAYWALL,+ handleCreditsStatus,insufficientCreditsLegacyResponse,insufficientCreditsResponse,lowCreditThresholdCents,@@ -13,6 +14,19 @@ import {} from "./billing_onramp";import type { AutumnCustomer } from "./autumn_webhook";+vi.mock("./autumn_webhook", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./autumn_webhook")>()),+ syncAutumnToD1: vi.fn(async () => ({+ customer: { subscriptions: [] },+ creditsRemaining: 10,+ maxConcurrent: 1,+ halted: false,+ haltReason: null,+ wasHalted: false,+ usagePlan: "base",+ })),+}));+const req = new Request("https://app.opencomputer.dev/api/v3/sessions");describe("billing_onramp", () => {@@ -175,4 +189,35 @@ describe("billing_onramp", () => {expect(billingWarningOf("soon")).toBeNull();expect(billingWarningOf(null)).toBeNull();});++ it("counts a billing warning only for a caller that displays it", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));+ const env = {+ AUTUMN_SECRET_KEY: "sk_test",+ POSTHOG_PROJECT_TOKEN: "phc_test",+ OPENCOMPUTER_DB: {+ prepare: () => ({+ bind: () => ({ first: async () => ({ billing_warning: "trial_days", trial_started_at: 1 }) }),+ }),+ },+ } as unknown as Parameters<typeof handleCreditsStatus>[1];+ const caller = { orgID: "org_warning_display" };+ const waits: Promise<unknown>[] = [];+ const status = (u: string) =>+ handleCreditsStatus(new Request(u), env, caller, (p) => waits.push(p));++ // `opencomputer upgrade` looks the status up without showing the warning.+ const hidden = await status("https://app.opencomputer.dev/api/billing/credits");+ expect(await hidden.json()).toMatchObject({ billingWarning: "trial_days" });+ await Promise.all(waits);+ expect(fetchMock).not.toHaveBeenCalled();++ await status("https://app.opencomputer.dev/api/billing/credits?display=1");+ await Promise.all(waits);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String(fetchMock.mock.calls[0]![1]?.body))).toMatchObject({+ event: "billing.warning_shown",+ properties: { reason: "trial_days", surface: "cli" },+ });+ });});diff --git a/cloudflare-workers/api-edge/src/billing_onramp.ts b/cloudflare-workers/api-edge/src/billing_onramp.tsindex 19cd6eef..6047a126 100644--- a/cloudflare-workers/api-edge/src/billing_onramp.ts+++ b/cloudflare-workers/api-edge/src/billing_onramp.ts@@ -263,9 +263,10 @@ export function usagePlanOffers(current: UsagePlan): CreditsStatus["plans"] {// GET /api/billing/credits — API-key authenticated credit status for the CLI.// Re-syncs Autumn → D1 like the dashboard endpoint so a fresh upgrade clears a// halt on the next CLI call too. Legacy (Stripe) orgs have no Autumn customer-// and get a 404 — clients treat that as "no credit meter". The CLI is the only-// caller and shows a warning it returns, so billing.warning_shown is counted-// here (deduped like the paywall event).+// and get a 404 — clients treat that as "no credit meter". billing.warning_shown+// is counted here (deduped like the paywall event) only when the caller says it+// displays the warning (?display=1): a lookup that doesn't show it (e.g.+// `opencomputer upgrade`) must not count it or consume the dedupe key.export async function handleCreditsStatus(req: Request,env: AutumnSyncEnv & { AUTUMN_SECRET_KEY?: string },@@ -301,7 +302,7 @@ export async function handleCreditsStatus(...links,plans: usagePlanOffers(usagePlan),};- if (billingWarning) {+ if (billingWarning && new URL(req.url).searchParams.get("display") === "1") {waitUntil(onceAnHour(`warning:${caller.orgID}:${billingWarning}`, () =>emitBillingEvent(env, "billing.warning_shown", {diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.tsindex e79bad9f..e8cd2842 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts@@ -259,6 +259,25 @@ describe("managed-agent credit admission", () => {).resolves.toMatchObject({ allowed: false, isHalted: true });});+ it("names the re-projected halt reason when the re-check keeps the halt", async () => {+ const reasons = ["payment", "credits_empty"];+ const db = {+ OPENCOMPUTER_DB: {+ prepare: () =>+ new FakeStatement(1, 1_789_707_077, "pro", "free", "autumn", reasons.shift() ?? null),+ } as unknown as D1Database,+ };+ const selfHeal = vi.fn(async () => true);+ const request = new Request(+ "https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",+ { method: "POST" },+ );+ const response = await enforceManagedAgentCreditGate(request, db, "org_test", selfHeal);+ expect(response?.status).toBe(402);+ const body = (await response!.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({ haltReason: "credits_empty" });+ });+it("re-checks only halted Autumn orgs", async () => {const selfHeal = vi.fn(async () => false);await getManagedAgentBillingAdmission(env(0), "org_test", selfHeal);diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex 41de0ea2..05ae257a 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -99,18 +99,23 @@ export async function getManagedAgentBillingAdmission(orgID: string,selfHeal?: ManagedAgentSelfHeal,): Promise<ManagedAgentBillingAdmission> {- const row = await env.OPENCOMPUTER_DB.prepare(- `SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason, billing_warning, billing_warning_at- FROM orgs WHERE id = ?1`,- )- .bind(orgID)- .first<ManagedAgentCreditRow>();+ const readRow = () =>+ env.OPENCOMPUTER_DB.prepare(+ `SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason, billing_warning, billing_warning_at+ FROM orgs WHERE id = ?1`,+ )+ .bind(orgID)+ .first<ManagedAgentCreditRow>();+ let row = await readRow();let isHalted = row?.is_halted === 1;// Like the sandbox create/wake gates: a halted Autumn org re-checks the// authoritative balance, so a user who just topped up isn't denied until// the webhook/reconciler catches up.if (isHalted && row?.billing_provider === "autumn" && selfHeal) {isHalted = await selfHeal(orgID);+ // The re-check re-projects halt_reason/usage_plan; a still-halted org's+ // 402 must name the current reason, not the pre-heal one.+ if (isHalted) row = (await readRow()) ?? row;}// Existing paid orgs predate usage_plan and initially carry its conservative// 'base' default. Keep their established Pro entitlement effective until an