Skip to content

An open-source, faster Devin alternative

TypeScript

Billing funnel events and ?plan= through signup

Mohamed Habib via Computer3f864829eaf0
diff --git a/cloudflare-workers/api-edge/migrations/0012_orgs_first_work_minute_at.sql b/cloudflare-workers/api-edge/migrations/0012_orgs_first_work_minute_at.sql
new file mode 100644
index 00000000..427d8670
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0012_orgs_first_work_minute_at.sql
@@ -0,0 +1,4 @@
+-- orgs.first_work_minute_at — when the org's first work minute was tracked to
+-- Autumn, in unix seconds (serverless-agents-ws 086, billing.first_work_minute).
+-- Set once by the agent runtime usage route; NULL until then.
+ALTER TABLE orgs ADD COLUMN first_work_minute_at INTEGER;
diff --git a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
index b2ce87d5..16edd3dc 100644
--- a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
+++ b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
@@ -15,7 +15,7 @@ async function hmacHex(secret: string, data: string) {
.join("");
}
-function env(): AutumnEnv {
+function env(overrides: Partial<AutumnEnv> = {}): AutumnEnv {
return {
AUTUMN_SECRET_KEY: "autumn-secret",
AUTUMN_BASE_URL: "https://autumn.test/v1",
@@ -24,10 +24,11 @@ function env(): AutumnEnv {
AGENT_RUNTIME_USAGE_HMAC_SECRET: "agent-runtime-secret",
CF_ADMIN_SECRET: "admin-secret",
OPENCOMPUTER_DB: {} as D1Database,
+ ...overrides,
};
}
-async function post(fields: Record<string, unknown>) {
+async function post(fields: Record<string, unknown>, envOverrides: Partial<AutumnEnv> = {}) {
const body = JSON.stringify({
org_id: "org_1",
deployment_id: "dep_1",
@@ -49,7 +50,7 @@ async function post(fields: Record<string, unknown>) {
headers: { "X-Timestamp": ts, "X-Signature": sig },
body,
}),
- env(),
+ env(envOverrides),
);
}
@@ -117,6 +118,48 @@ describe("managed-agent runtime usage billing", () => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});
+ it("sends the work-minute funnel events, the first minute once", async () => {
+ const posthog: Array<{ event: string; properties: Record<string, unknown> }> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ const url = String(input);
+ if (url.startsWith("https://ph.test/")) {
+ posthog.push(JSON.parse(String(init?.body)));
+ return new Response("{}");
+ }
+ if (url.endsWith("/track")) return Response.json({ balance: { remaining: 590 } });
+ return Response.json({
+ id: "org_1",
+ subscriptions: [{ plan_id: "trial", status: "active" }],
+ balances: { work_minutes: { remaining: 600 } },
+ });
+ });
+ let stamped = false;
+ const db = {
+ prepare: () => ({
+ bind: () => ({
+ first: async () => {
+ if (stamped) return null;
+ stamped = true;
+ return { trial_started_at: Math.floor(Date.now() / 1000) - 600, created_at: 0 };
+ },
+ }),
+ }),
+ } as unknown as D1Database;
+ const telemetry = { OPENCOMPUTER_DB: db, POSTHOG_PROJECT_TOKEN: "phc_test", POSTHOG_HOST: "https://ph.test" };
+
+ await post({ deployment_id: "computer", close_reason: "idle", quantity_seconds: 90 }, telemetry);
+ await post({ close_reason: "turn_settled", quantity_seconds: 30, idempotency_key: "t:turn" }, telemetry);
+
+ expect(posthog.map((e) => e.event)).toEqual([
+ "billing.work_minutes_recorded",
+ "billing.first_work_minute",
+ "billing.work_minutes_recorded",
+ ]);
+ expect(posthog[0]!.properties).toMatchObject({ minutes: 1.5, surface: "computer", plan: "trial", org_id: "org_1" });
+ expect(posthog[1]!.properties).toMatchObject({ surface: "computer", minutes_since_signup: 10 });
+ expect(posthog[2]!.properties).toMatchObject({ minutes: 0.5, surface: "automation" });
+ });
+
it("keeps an org the edge cannot find in Autumn on agent runtime", async () => {
const fetchMock = vi
.spyOn(globalThis, "fetch")
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index 046bce9b..811d05ab 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -16,6 +16,8 @@
// is Deprecated and ignored. Because we always re-check, every event is handled
// uniformly — the type only decides whether we bother projecting at all.
+import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
+
// AutumnApiEnv is the minimal binding set for calling Autumn's REST API
// (GetCustomer / checkout). The dashboard handlers satisfy this without the
// webhook/dispatch secrets.
@@ -30,7 +32,7 @@ export interface AutumnSyncEnv extends AutumnApiEnv {
}
// AutumnEnv adds the secrets needed to dispatch halt to cells + verify webhooks.
-export interface AutumnEnv extends AutumnSyncEnv {
+export interface AutumnEnv extends AutumnSyncEnv, BillingEventsEnv {
CF_ADMIN_SECRET: string;
EVENT_SECRET: string;
AUTUMN_WEBHOOK_SECRET: string;
@@ -361,6 +363,45 @@ export async function browserUsageInternal(req: Request, env: AutumnEnv): Promis
// has finalized a bounded lease segment. The segment ID is the financial
// idempotency key; authenticated organization and session attribution travel
// with it, but only the fixed resource tier controls the Autumn feature.
+const WORK_MINUTE_PLANS = new Set(["trial", "pro", "max"]);
+
+// The funnel's billing.work_minutes_recorded, and billing.first_work_minute
+// the first time an org's minutes are tracked. A retried segment emits again
+// (Autumn drops the track, not the event); the first-minute stamp is set once.
+async function recordWorkMinutes(
+ env: AutumnEnv,
+ orgID: string,
+ customer: AutumnCustomer | null,
+ w: { minutes: number; surface: "computer" | "automation" },
+): Promise<void> {
+ const plan =
+ customer?.subscriptions?.find(
+ (s) => (!s.status || s.status === "active") && WORK_MINUTE_PLANS.has(s.plan_id),
+ )?.plan_id ?? null;
+ await emitBillingEvent(env, "billing.work_minutes_recorded", {
+ orgId: orgID,
+ data: { minutes: Math.round(w.minutes * 100) / 100, surface: w.surface, plan },
+ });
+ try {
+ const nowSec = Math.floor(Date.now() / 1000);
+ const first = await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE orgs SET first_work_minute_at = ?1
+ WHERE id = ?2 AND first_work_minute_at IS NULL
+ RETURNING trial_started_at, created_at`,
+ )
+ .bind(nowSec, orgID)
+ .first<{ trial_started_at: number | null; created_at: number }>();
+ if (!first) return;
+ const since = first.trial_started_at ?? first.created_at;
+ await emitBillingEvent(env, "billing.first_work_minute", {
+ orgId: orgID,
+ data: { surface: w.surface, minutes_since_signup: Math.max(0, Math.round((nowSec - since) / 60)) },
+ });
+ } catch (err) {
+ console.error(`agent runtime usage: first work minute for ${orgID}:`, (err as Error).message);
+ }
+}
+
export async function agentRuntimeUsageInternal(
req: Request,
env: AutumnEnv,
@@ -431,6 +472,12 @@ export async function agentRuntimeUsageInternal(
idempotencyKey: p.idempotency_key,
});
if (remaining !== null && remaining <= 0) await projectOrg(env, p.org_id);
+ if (workMinutes) {
+ await recordWorkMinutes(env, p.org_id, customer, {
+ minutes: Number(p.quantity_seconds) / 60,
+ surface: p.deployment_id === "computer" ? "computer" : "automation",
+ });
+ }
return json({
ok: true,
billed: true,
diff --git a/cloudflare-workers/api-edge/src/billing_events.test.ts b/cloudflare-workers/api-edge/src/billing_events.test.ts
new file mode 100644
index 00000000..c8921740
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/billing_events.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { emitBillingEvent } from "./billing_events";
+import { planIntentOf } from "./index";
+
+describe("billing funnel events", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("sends one event to Tinybird and PostHog under the same name", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
+
+ await emitBillingEvent(
+ {
+ TINYBIRD_API_URL: "https://tb.test/",
+ TINYBIRD_APPEND_TOKEN: "tb-token",
+ POSTHOG_PROJECT_TOKEN: "phc_test",
+ },
+ "billing.trial_started",
+ { orgId: "org_1", userId: "user_1", data: { plan_intent: null, via: "browser" } },
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const [tbURL, tbInit] = fetchMock.mock.calls[0]!;
+ expect(String(tbURL)).toBe("https://tb.test/v0/events?name=calvin_events&wait=false");
+ const line = JSON.parse(String(tbInit?.body));
+ expect(line).toMatchObject({ event_name: "billing.trial_started", service_name: "edge", org_id: "org_1" });
+ expect(JSON.parse(line.data)).toEqual({ via: "browser" });
+ const [phURL, phInit] = fetchMock.mock.calls[1]!;
+ expect(String(phURL)).toBe("https://us.i.posthog.com/i/v0/e/");
+ expect(JSON.parse(String(phInit?.body))).toMatchObject({
+ api_key: "phc_test",
+ event: "billing.trial_started",
+ distinct_id: "user_1",
+ properties: { via: "browser", org_id: "org_1", $groups: { organization: "org_1" } },
+ });
+ });
+
+ it("sends nothing unconfigured, and never throws", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("down"));
+ await emitBillingEvent({}, "billing.checkout_opened", { orgId: "org_1", data: {} });
+ expect(fetchMock).not.toHaveBeenCalled();
+ await expect(
+ emitBillingEvent({ POSTHOG_PROJECT_TOKEN: "phc_test" }, "billing.checkout_opened", { orgId: "org_1", data: {} }),
+ ).resolves.toBeUndefined();
+ });
+
+ it("reads the signup's plan intent from returnTo", () => {
+ expect(planIntentOf("/?plan=pro")).toBe("pro");
+ expect(planIntentOf("/billing?plan=max&x=1")).toBe("max");
+ expect(planIntentOf("/?plan=gold")).toBeNull();
+ expect(planIntentOf(null)).toBeNull();
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/billing_events.ts b/cloudflare-workers/api-edge/src/billing_events.ts
new file mode 100644
index 00000000..29589c2c
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/billing_events.ts
@@ -0,0 +1,124 @@
+// Billing funnel events (serverless-agents-ws 086, "Funnel events"): the same
+// event, by name, to Tinybird (`calvin_events`, the envelope edge.request uses;
+// catalogued as `edge` entries in blue's src/computer/telemetry/catalog.ts) and
+// to PostHog, keyed by org id plus the user id where there is one.
+//
+// Each sink is off unless configured: TINYBIRD_API_URL + TINYBIRD_APPEND_TOKEN,
+// and POSTHOG_PROJECT_TOKEN (POSTHOG_HOST defaults to PostHog US). Never throws,
+// never retries; one attempt per sink, bounded, so a billing path can await it.
+//
+// Data policy (work 054): ids and scalars only, never emails or amounts tied
+// to a card.
+
+import { edgeTelemetryEnabled, tbTime, uuidv7, type EdgeTelemetryEnv } from "./computer_telemetry";
+
+export interface BillingEventsEnv extends EdgeTelemetryEnv {
+ POSTHOG_PROJECT_TOKEN?: string;
+ POSTHOG_HOST?: string;
+}
+
+export type BillingEventName =
+ | "billing.trial_started"
+ | "billing.work_minutes_recorded"
+ | "billing.first_work_minute"
+ | "billing.checkout_opened";
+
+export interface BillingEvent {
+ orgId: string;
+ userId?: string;
+ data: Record<string, string | number | boolean | null>;
+}
+
+const POST_TIMEOUT_MS = 2_000;
+const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
+
+/** The Tinybird line for one billing event. */
+export function billingTinybirdEvent(
+ env: BillingEventsEnv,
+ name: BillingEventName,
+ event: BillingEvent,
+ now = Date.now(),
+): Record<string, unknown> {
+ return {
+ schema_version: 1,
+ event_id: uuidv7(now),
+ event_name: name,
+ occurred_at: tbTime(now),
+ service_name: "edge",
+ service_version: env.CF_VERSION_METADATA?.id || "dev",
+ region: "unknown",
+ synthetic: false,
+ surface: "api",
+ org_id: event.orgId,
+ ...(event.userId ? { user_id: event.userId } : {}),
+ outcome: "completed",
+ data: JSON.stringify(withoutNulls(event.data)),
+ };
+}
+
+/** The PostHog capture body for one billing event. */
+export function billingPostHogEvent(
+ token: string,
+ name: BillingEventName,
+ event: BillingEvent,
+ now = Date.now(),
+): Record<string, unknown> {
+ return {
+ api_key: token,
+ event: name,
+ // The web app identifies people by user id; an event with no user (a
+ // usage record) is the org's own.
+ distinct_id: event.userId ?? `org:${event.orgId}`,
+ timestamp: new Date(now).toISOString(),
+ properties: {
+ ...withoutNulls(event.data),
+ org_id: event.orgId,
+ $groups: { organization: event.orgId },
+ ...(event.userId ? {} : { $process_person_profile: false }),
+ },
+ };
+}
+
+export async function emitBillingEvent(
+ env: BillingEventsEnv,
+ name: BillingEventName,
+ event: BillingEvent,
+): Promise<void> {
+ const now = Date.now();
+ const sends: Promise<unknown>[] = [];
+ try {
+ if (edgeTelemetryEnabled(env)) {
+ sends.push(
+ post(
+ `${env.TINYBIRD_API_URL!.trim().replace(/\/+$/, "")}/v0/events?name=calvin_events&wait=false`,
+ { authorization: `Bearer ${env.TINYBIRD_APPEND_TOKEN!.trim()}`, "content-type": "application/x-ndjson" },
+ JSON.stringify(billingTinybirdEvent(env, name, event, now)),
+ ),
+ );
+ }
+ const token = env.POSTHOG_PROJECT_TOKEN?.trim();
+ if (token) {
+ sends.push(
+ post(
+ `${(env.POSTHOG_HOST?.trim() || DEFAULT_POSTHOG_HOST).replace(/\/+$/, "")}/i/v0/e/`,
+ { "content-type": "application/json" },
+ JSON.stringify(billingPostHogEvent(token, name, event, now)),
+ ),
+ );
+ }
+ } catch {
+ // Telemetry never fails the billing path.
+ }
+ await Promise.allSettled(sends);
+}
+
+async function post(url: string, headers: Record<string, string>, body: string): Promise<void> {
+ const res = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(POST_TIMEOUT_MS) });
+ await res.body?.cancel().catch(() => {});
+}
+
+function withoutNulls(data: BillingEvent["data"]): Record<string, string | number | boolean> {
+ const out: Record<string, string | number | boolean> = {};
+ for (const [k, v] of Object.entries(data)) if (v !== null && v !== undefined) out[k] = v;
+ return out;
+}
diff --git a/cloudflare-workers/api-edge/src/computer_telemetry.ts b/cloudflare-workers/api-edge/src/computer_telemetry.ts
index f19c9722..6deb2eb4 100644
--- a/cloudflare-workers/api-edge/src/computer_telemetry.ts
+++ b/cloudflare-workers/api-edge/src/computer_telemetry.ts
@@ -101,12 +101,12 @@ export function blueMs(response: Response): number | undefined {
}
/** A Tinybird `DateTime64` string. */
-function tbTime(ms: number): string {
+export function tbTime(ms: number): string {
return new Date(ms).toISOString().replace("T", " ").replace("Z", "");
}
/** UUIDv7: a 48-bit ms timestamp, then random bits. */
-function uuidv7(now: number): string {
+export function uuidv7(now: number): string {
const b = new Uint8Array(16);
crypto.getRandomValues(b);
let t = now;
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 8079c9bb..2f3a063f 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -28,6 +28,7 @@ import {
autumnSetAutoTopup,
autumnOpenCustomerPortal,
} from "./autumn_webhook";
+import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";
import {
acknowledgeAgentSecurityNotification,
@@ -43,7 +44,7 @@ import { computerEnabledFor } from "./computer";
import { enableManagedBilling } from "./model_billing";
import { insufficientManagedAgentCredits } from "./managed_agent_credit_gate";
-export interface DashboardEnv {
+export interface DashboardEnv extends BillingEventsEnv {
/** Computer rollout (work 052): see computerEnabledFor in computer.ts. */
COMPUTER_ENABLED_FOR_ALL?: string;
COMPUTER_ENABLED_ORGS?: string;
@@ -1786,12 +1787,15 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { o
});
}
-// POST /api/dashboard/billing/autumn/plan { plan } — subscribe to or switch
+// Where a checkout was opened from (086 funnel); anything else is the Billing page.
+const CHECKOUT_FROM = new Set(["paywall", "warning", "billing_page", "signup"]);
+
+// POST /api/dashboard/billing/autumn/plan { plan, from? } — subscribe to or switch
// between the recurring Pro and Max shared-credit plans. Usage remains the
// automatic fallback when a paid subscription is cancelled in Stripe.
-async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: { orgID: string; userID?: string }): Promise<Response> {
if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
- let body: { plan?: string };
+ let body: { plan?: string; from?: string };
try {
body = await req.json();
} catch {
@@ -1808,6 +1812,11 @@ async function handleAutumnUsagePlan(req: Request, env: DashboardEnv, caller: {
planId: plan,
successUrl: `${origin}/billing?usage-plan=${plan}`,
});
+ await emitBillingEvent(env, "billing.checkout_opened", {
+ orgId: caller.orgID,
+ userId: caller.userID,
+ data: { plan, from: CHECKOUT_FROM.has(body.from ?? "") ? body.from! : "billing_page" },
+ });
return json({ url: co.url });
} catch (e) {
console.error("billing/autumn plan:", e);
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 5232e04c..b7c1b765 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -110,16 +110,16 @@ import {
withComputerApiCors,
COMPUTER_API_PREFIX,
} from "./computer_api";
+import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
import {
type EdgeRequestFacts,
- type EdgeTelemetryEnv,
newEdgeRequestFacts,
reportEdgeRequest,
} from "./computer_telemetry";
import { computerEnabledFor } from "./computer";
import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";
-export interface Env extends DashboardEnv, AgentFeedbackEnv, EdgeTelemetryEnv {
+export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv {
CF_ADMIN_SECRET: string;
STRIPE_WEBHOOK_SECRET: string;
EVENT_SECRET: string;
@@ -3943,6 +3943,7 @@ async function provisionWorkOSIdentity(
profile: WorkOSProfile,
workosOrgID: string | undefined,
selection: IdentitySelection,
+ planIntent: string | null = null,
): Promise<ProvisionedIdentity> {
const nowSec = Math.floor(Date.now() / 1000);
const displayName =
@@ -4079,6 +4080,13 @@ async function provisionWorkOSIdentity(
)
.bind(orgID, userID, nowSec)
.run();
+ if (provider === "autumn") {
+ await emitBillingEvent(env, "billing.trial_started", {
+ orgId: orgID,
+ userId: userID,
+ data: { plan_intent: planIntent, via: selection },
+ });
+ }
orgRow = {
id: orgID,
name: orgName,
@@ -4160,6 +4168,14 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
}
}
+// The plan a signup came for: the site's pricing CTAs link `/?plan=pro|max`,
+// which reaches here inside returnTo.
+export function planIntentOf(returnTo: string | null): string | null {
+ if (!returnTo) return null;
+ const plan = new URL(returnTo, "https://app.invalid").searchParams.get("plan");
+ return plan === "pro" || plan === "max" ? plan : null;
+}
+
function parseAuthState(raw: string | null): { returnTo: string | null; retried: boolean } {
if (!raw) return { returnTo: null, retried: false };
try {
@@ -4179,12 +4195,16 @@ async function completeAuthCallback(
const profile = tokenBody.user;
// WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.
const workosSessionID = workosSessionIdFromAccessToken(tokenBody.access_token);
+ // Re-validate here: `state` is attacker-influenceable, so the path is only
+ // trusted after safeReturnTo passes a second time.
+ const returnTo = parseAuthState(reqURL.searchParams.get("state")).returnTo;
const identity = await provisionWorkOSIdentity(
req,
env,
profile,
tokenBody.organization_id ?? profile.organization_id,
"browser",
+ planIntentOf(returnTo),
);
// Mint session JWT — same signing secret as cap-token but a different
@@ -4198,9 +4218,7 @@ async function completeAuthCallback(
);
// Land on the deferred deep link if `state` carried a valid one, else the
- // dashboard. Re-validate here: `state` is attacker-influenceable, so the path
- // is only trusted after safeReturnTo passes a second time.
- const returnTo = parseAuthState(reqURL.searchParams.get("state")).returnTo;
+ // dashboard.
const landingURL = `${reqURL.origin}${returnTo ?? "/dashboard"}`;
return new Response(null, {
status: 302,
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4007d135..9bdaab1c 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -61,11 +61,15 @@ function NewProject() {
}
// `app.opencomputer.dev/?security=1` drops into the independent CVE Swarm
-// onboarding path; the param survives the login round-trip via returnTo.
+// onboarding path; `?plan=pro|max` (the site's pricing CTAs) opens that plan
+// on Billing. Both survive the login round-trip via returnTo.
function HomeRoute() {
const [searchParams] = useSearchParams()
if (searchParams.get('security') === '1')
return <Navigate to="/security" replace />
+ const plan = searchParams.get('plan')
+ if (plan === 'pro' || plan === 'max')
+ return <Navigate to={`/billing?plan=${plan}`} replace />
return managedAgentsExperimentEnabled ? <ManagedAgentsHome /> : <Dashboard />
}