Skip to content

Commit 2ae389a

Browse files
fix(den): gate billing at shared workspace launch (anomalyco#1718)
1 parent 4806da8 commit 2ae389a

17 files changed

Lines changed: 148 additions & 371 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ User mental model:
3737
* The server is the execution/control API layer.
3838
* A worker is a remote runtime destination.
3939
* Connecting to a worker happens through `Add worker` -> `Connect remote` using URL + token (or deep link).
40+
* Billing gates belong to shared cloud workspace launch, not base Den sign-up or organization creation.
4041

4142
Read `ARCHITECTURE.md` for runtime flow, server-vs-shell ownership, and architecture behavior. Read `INFRASTRUCTURE.md` for deployment and control-plane details.
4243

‎ARCHITECTURE.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -350,10 +350,11 @@ This is intentional for now: predictable scoping beats clever cross-root auto-ro
350350
## Cloud Worker Connect Flow (Canonical)
351351

352352
1. Authenticate in OpenWork Cloud control surface.
353-
2. Launch worker (with checkout/paywall when needed).
354-
3. Wait for provisioning and health.
355-
4. Generate/retrieve connect credentials.
356-
5. Connect in OpenWork app via deep link or manual URL + token.
353+
2. Create or select a Den organization without billing gates.
354+
3. Launch a shared cloud workspace/worker (with checkout/paywall when the hosted shared-workspace gate is enabled).
355+
4. Wait for provisioning and health.
356+
5. Generate/retrieve connect credentials.
357+
6. Connect in OpenWork app via deep link or manual URL + token.
357358

358359
Technical note:
359360

‎ee/apps/den-api/src/routes/org/core.ts‎

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ import type { Hono } from "hono"
66
import { describeRoute } from "hono-openapi"
77
import { z } from "zod"
88
import { auth } from "../../auth.js"
9-
import { requireCloudWorkerAccess } from "../../billing/polar.js"
109
import { db } from "../../db.js"
11-
import { env } from "../../env.js"
1210
import { jsonValidator, queryValidator, requireUserMiddleware, resolveMemberTeamsMiddleware, resolveOrganizationContextMiddleware } from "../../middleware/index.js"
1311
import { denTypeIdSchema, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
1412
import {
@@ -57,16 +55,6 @@ const organizationOwnerSchema = z.object({
5755
image: z.string().nullable().optional(),
5856
}).meta({ ref: "OrganizationOwner" })
5957

60-
const paymentRequiredSchema = z.object({
61-
error: z.literal("payment_required"),
62-
message: z.string(),
63-
polar: z.object({
64-
checkoutUrl: z.string().nullable(),
65-
productId: z.string().nullable().optional(),
66-
benefitId: z.string().nullable().optional(),
67-
}).passthrough(),
68-
}).meta({ ref: "PaymentRequiredError" })
69-
7058
const invitationPreviewResponseSchema = z.object({}).passthrough().meta({ ref: "InvitationPreviewResponse" })
7159

7260
const invitationAcceptedResponseSchema = z.object({
@@ -141,12 +129,11 @@ export function registerOrgCoreRoutes<T extends { Variables: OrgRouteVariables }
141129
tags: ["Organizations"],
142130
hide: true,
143131
summary: "Create organization",
144-
description: "Creates a new organization for the signed-in user after verifying that their account can provision OpenWork Cloud workspaces.",
132+
description: "Creates a new organization for the signed-in user. Billing is enforced only when launching shared cloud workspaces.",
145133
responses: {
146134
201: jsonResponse("Organization created successfully.", organizationResponseSchema),
147135
400: jsonResponse("The organization creation request body was invalid.", invalidRequestSchema),
148136
401: jsonResponse("The caller must be signed in to create an organization.", unauthorizedSchema),
149-
402: jsonResponse("The caller needs an active cloud plan before creating an organization.", paymentRequiredSchema),
150137
403: jsonResponse("API keys cannot create organizations.", forbiddenSchema),
151138
},
152139
}),
@@ -162,29 +149,6 @@ export function registerOrgCoreRoutes<T extends { Variables: OrgRouteVariables }
162149

163150
const user = c.get("user")
164151
const input = c.req.valid("json")
165-
const email = getRequiredUserEmail(user)
166-
167-
if (!email) {
168-
return c.json({ error: "user_email_required" }, 400)
169-
}
170-
171-
const access = await requireCloudWorkerAccess({
172-
userId: normalizeDenTypeId("user", user.id),
173-
email,
174-
name: user.name ?? user.email ?? "OpenWork User",
175-
})
176-
177-
if (!access.allowed) {
178-
return c.json({
179-
error: "payment_required",
180-
message: "Creating a workspace requires an active OpenWork Cloud plan.",
181-
polar: {
182-
checkoutUrl: access.checkoutUrl,
183-
productId: env.polar.productId,
184-
benefitId: env.polar.benefitId,
185-
},
186-
}, 402)
187-
}
188152

189153
const organizationId = await createOrganizationForUser({
190154
userId: normalizeDenTypeId("user", user.id),

‎ee/apps/den-api/src/routes/workers/core.ts‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { desc, eq } from "@openwork-ee/den-db/drizzle"
22
import { WorkerTable, WorkerTokenTable } from "@openwork-ee/den-db/schema"
3-
import { createDenTypeId } from "@openwork-ee/utils/typeid"
3+
import { createDenTypeId, normalizeDenTypeId } from "@openwork-ee/utils/typeid"
44
import type { Hono } from "hono"
55
import { describeRoute } from "hono-openapi"
66
import { z } from "zod"
77
import { db } from "../../db.js"
8+
import { env } from "../../env.js"
89
import { jsonValidator, paramValidator, queryValidator, requireUserMiddleware, resolveUserOrganizationsMiddleware } from "../../middleware/index.js"
910
import { denTypeIdSchema, emptyResponse, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
1011
import { getOrganizationLimitStatus } from "../../organization-limits.js"
12+
import { getRequiredUserEmail } from "../../user.js"
1113
import type { WorkerRouteVariables } from "./shared.js"
1214
import {
1315
continueCloudProvisioning,
@@ -18,6 +20,7 @@ import {
1820
getWorkerTokensAndConnect,
1921
listWorkersQuerySchema,
2022
parseWorkerIdParam,
23+
requireCloudAccessOrPayment,
2124
toInstanceResponse,
2225
toWorkerResponse,
2326
token,
@@ -105,6 +108,20 @@ const orgLimitReachedSchema = z.object({
105108
message: z.string(),
106109
}).meta({ ref: "WorkerOrgLimitReachedError" })
107110

111+
const paymentRequiredSchema = z.object({
112+
error: z.literal("payment_required"),
113+
message: z.string(),
114+
polar: z.object({
115+
checkoutUrl: z.string().nullable(),
116+
productId: z.string().nullable().optional(),
117+
benefitId: z.string().nullable().optional(),
118+
}).passthrough(),
119+
}).meta({ ref: "WorkerPaymentRequiredError" })
120+
121+
const userEmailRequiredSchema = z.object({
122+
error: z.literal("user_email_required"),
123+
}).meta({ ref: "WorkerUserEmailRequiredError" })
124+
108125
const workerRuntimeUnavailableSchema = z.object({
109126
error: z.literal("worker_tokens_unavailable"),
110127
message: z.string(),
@@ -164,12 +181,13 @@ export function registerWorkerCoreRoutes<T extends { Variables: WorkerRouteVaria
164181
describeRoute({
165182
tags: ["Workers"],
166183
summary: "Create worker",
167-
description: "Creates a local or cloud worker for the active organization and returns the initial tokens needed to connect to it.",
184+
description: "Creates a local worker or shared cloud workspace for the active organization and returns the initial tokens needed to connect to it.",
168185
responses: {
169186
201: jsonResponse("Local worker created successfully.", workerCreateResponseSchema),
170187
202: jsonResponse("Cloud worker creation started successfully.", workerCreateResponseSchema),
171-
400: jsonResponse("The worker creation payload was invalid.", z.union([invalidRequestSchema, organizationUnavailableSchema, workspacePathRequiredSchema])),
188+
400: jsonResponse("The worker creation payload was invalid.", z.union([invalidRequestSchema, organizationUnavailableSchema, workspacePathRequiredSchema, userEmailRequiredSchema])),
172189
401: jsonResponse("The caller must be signed in to create workers.", unauthorizedSchema),
190+
402: jsonResponse("The caller needs an active cloud plan before launching a shared workspace.", paymentRequiredSchema),
173191
409: jsonResponse("The organization has reached its worker limit.", orgLimitReachedSchema),
174192
},
175193
}),
@@ -190,6 +208,29 @@ export function registerWorkerCoreRoutes<T extends { Variables: WorkerRouteVaria
190208
}
191209

192210
if (input.destination === "cloud") {
211+
const email = getRequiredUserEmail(user)
212+
if (!email) {
213+
return c.json({ error: "user_email_required" }, 400)
214+
}
215+
216+
const access = await requireCloudAccessOrPayment({
217+
userId: normalizeDenTypeId("user", user.id),
218+
email,
219+
name: user.name ?? user.email ?? "OpenWork User",
220+
})
221+
222+
if (!access.allowed) {
223+
return c.json({
224+
error: "payment_required",
225+
message: "Launching a shared workspace requires an active OpenWork Cloud plan.",
226+
polar: {
227+
checkoutUrl: access.checkoutUrl,
228+
productId: env.polar.productId,
229+
benefitId: env.polar.benefitId,
230+
},
231+
}, 402)
232+
}
233+
193234
const workerLimit = await getOrganizationLimitStatus(orgId, "workers")
194235
if (workerLimit.exceeded) {
195236
return c.json({

‎ee/apps/den-web/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,18 @@ Frontend for `app.openworklabs.com`.
77
- Signs up / signs in users against Den service auth.
88
- Handles invited-org signup flows where the invited email stays locked and the user verifies access before joining.
99
- Launches cloud workers via `POST /v1/workers`.
10-
- Handles paywall responses (`402 payment_required`), routes users through Polar checkout, and only enables worker launch after purchase.
10+
- Handles shared workspace paywall responses (`402 payment_required`) from cloud worker launch and routes users through Polar checkout.
1111
- Offers desktop handoff actions so users can open the generated worker directly in OpenWork or copy the connect credentials manually.
1212
- Uses a Next.js proxy route (`/api/den/*`) to reach `api.openworklabs.com` without browser CORS issues.
1313
- Uses a same-origin auth proxy (`/api/auth/*`) so GitHub OAuth callbacks can land on `app.openworklabs.com`.
1414

1515
## Current hosted user flow
1616

1717
1. Sign in with a standard provider or accept an org invite.
18-
2. If the org requires billing, complete checkout before launching a worker.
19-
3. Launch the worker from the cloud dashboard.
20-
4. Open the worker in the desktop app with the provided deep link, or copy the URL/token into `Connect remote` manually.
18+
2. Create or select an organization without a billing gate.
19+
3. If the shared workspace launch requires billing, complete checkout before launching the hosted worker.
20+
4. Launch the worker from the cloud dashboard.
21+
5. Open the worker in the desktop app with the provided deep link, or copy the URL/token into `Connect remote` manually.
2122

2223
## Local development
2324

‎ee/apps/den-web/app/(den)/_components/checkout-screen.tsx‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,9 @@ export function CheckoutScreen({ customerSessionToken }: { customerSessionToken:
197197
<div className="flex flex-col gap-4 lg:max-w-3xl">
198198
<div className="grid gap-3">
199199
<p className="den-eyebrow">OpenWork Cloud</p>
200-
<h1 className="den-title-xl max-w-[14ch]">Purchase a plan before creating your workspace.</h1>
200+
<h1 className="den-title-xl max-w-[14ch]">Purchase a plan before launching a shared workspace.</h1>
201201
<p className="den-copy max-w-2xl">
202-
Start with one workspace plan for $50/month. Each plan includes up to 5 members and 1 hosted worker.
202+
Den is free for solo setup. Shared cloud workspaces require a workspace plan with up to 5 members and 1 hosted worker.
203203
</p>
204204
</div>
205205

@@ -218,8 +218,8 @@ export function CheckoutScreen({ customerSessionToken }: { customerSessionToken:
218218
Refresh purchase link
219219
</button>
220220
)}
221-
<a href="https://openworklabs.com/download" className="den-button-secondary w-full sm:w-auto">
222-
Use desktop only
221+
<a href="https://github.com/different-ai/openwork/releases/latest" target="_blank" rel="noreferrer" className="den-button-secondary w-full sm:w-auto">
222+
Download desktop app
223223
</a>
224224
</div>
225225

@@ -290,8 +290,8 @@ export function CheckoutScreen({ customerSessionToken }: { customerSessionToken:
290290
</div>
291291

292292
<div className="mt-auto pt-2">
293-
<a href="https://openworklabs.com/download" className="den-button-secondary w-full sm:w-auto">
294-
Use desktop only
293+
<a href="https://github.com/different-ai/openwork/releases/latest" target="_blank" rel="noreferrer" className="den-button-secondary w-full sm:w-auto">
294+
Download desktop app
295295
</a>
296296
</div>
297297
</article>
@@ -302,7 +302,7 @@ export function CheckoutScreen({ customerSessionToken }: { customerSessionToken:
302302
<p className="den-eyebrow">Billing status</p>
303303
<h2 className="text-2xl font-semibold tracking-tight text-[var(--dls-text-primary)]">{subscriptionStatus}</h2>
304304
<p className="den-copy text-sm">
305-
{billingSummary.hasActivePlan ? "Your workspace plan is active." : "Purchase a plan to create your first workspace."}
305+
{billingSummary.hasActivePlan ? "Your workspace plan is active." : "Purchase a plan to launch shared workspaces."}
306306
</p>
307307
</div>
308308

‎ee/apps/den-web/app/(den)/_components/dashboard-screen.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,7 @@ export function DashboardScreen({ showSidebar = true }: { showSidebar?: boolean
558558
{billingSummary?.featureGateEnabled
559559
? billingSummary.hasActivePlan
560560
? "Your account has active worker billing."
561-
: "Workers stay disabled until you purchase one for $50/month."
561+
: "Shared workspace launches require a workspace plan."
562562
: "Billing gates are disabled in this environment."}
563563
</p>
564564
<Link
@@ -575,12 +575,12 @@ export function DashboardScreen({ showSidebar = true }: { showSidebar?: boolean
575575
<div className="rounded-[24px] border border-[var(--dls-border)] bg-[var(--dls-surface)] p-8">
576576
<div className="mx-auto max-w-[30rem] text-center">
577577
<h2 className="text-2xl font-semibold tracking-tight text-[var(--dls-text-primary)]">No workers yet</h2>
578-
<p className="mt-3 text-sm leading-6 text-[var(--dls-text-secondary)]">Purchase your first worker to unlock connection details and runtime controls.</p>
578+
<p className="mt-3 text-sm leading-6 text-[var(--dls-text-secondary)]">Launch a shared workspace to unlock connection details and runtime controls.</p>
579579
<Link
580580
href="/checkout"
581581
className="mt-5 inline-flex rounded-[12px] border border-[var(--dls-border)] bg-[var(--dls-surface)] px-3 py-2 text-xs font-semibold text-[var(--dls-text-secondary)] transition hover:bg-[var(--dls-hover)] hover:text-[var(--dls-text-primary)]"
582582
>
583-
Purchase worker billing
583+
Open shared workspace billing
584584
</Link>
585585
</div>
586586
</div>
@@ -659,7 +659,7 @@ export function DashboardScreen({ showSidebar = true }: { showSidebar?: boolean
659659

660660
{workersBusy ? <p className="text-xs text-[var(--dls-text-secondary)]">Loading workers...</p> : null}
661661
{workersError ? <p className="text-xs font-medium text-rose-600">{workersError}</p> : null}
662-
{workers.length === 0 && !workersBusy ? <p className="text-xs text-[var(--dls-text-secondary)]">No workers yet. Purchase one to get started.</p> : null}
662+
{workers.length === 0 && !workersBusy ? <p className="text-xs text-[var(--dls-text-secondary)]">No shared workspaces yet.</p> : null}
663663
</div>
664664

665665
<div className="text-xs text-[var(--dls-text-secondary)] md:text-sm">

0 commit comments

Comments
 (0)