Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add plan-based bot and machine limits with Stripe subscriptions (#752)

Gustavo Ye31ceb39c386d
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7cfe81a59..9f0f53f80 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -551,6 +551,9 @@ importers:
streamdown:
specifier: ^2.6.0
+ stripe:
+ specifier: 22.6.2
+ version: 22.6.2(@types/[email protected])
tailwind-merge:
specifier: ^3.6.0
version: 3.6.0
@@ -8920,6 +8923,15 @@ packages:
resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==}
engines: {node: '>=14.16'}
+ resolution: {integrity: sha512-PwRE2scocvXqDKPiskMa5vRJEAEkq46W69XyUYmAwrNSLr675lQnfqLwnsndAWizwgihOWw/irLmoFRo3ez7ew==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
resolution: {integrity: sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==}
@@ -19151,6 +19163,10 @@ snapshots:
+ optionalDependencies:
+ '@types/node': 25.9.4
+
dependencies:
stubborn-utils: 1.0.2
diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjs
index 08c468a5b..3774a78d9 100644
--- a/scripts/ci/changed-scopes.mjs
+++ b/scripts/ci/changed-scopes.mjs
@@ -43,6 +43,7 @@ const COVERAGE_EXCLUDES = [
/^src\/web\/scripts\//,
/^src\/web\/readme-capture\//,
/^src\/web\/src\/.*\.tsx$/,
+ /^src\/web\/src\/components\/community\/bots\/bot-list-types\.ts$/,
/^src\/web\/src\/test\/fixtures\//,
/^src\/web\/src\/test\/(?:e2e|e2e-ui)\//,
/^src\/web\/src\/hooks\/(?:use-agent-chat|use-chat-sheets|use-file-attachments|use-message-flags|use-text-selection-quote)\.ts$/,
diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.ts
index 4b475f718..a8790922a 100644
--- a/scripts/ci/changed-scopes.test.ts
+++ b/scripts/ci/changed-scopes.test.ts
@@ -355,6 +355,7 @@ describe("coverage name-status contract", () => {
"src/web/vitest.config.ts",
"src/web/vitest.runtime.config.mts",
"src/web/vitest.workspace.config.ts",
+ "src/web/src/components/community/bots/bot-list-types.ts",
]) {
expect(plan([path]).coverage.required_changed_files).toEqual([])
}
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index 9db3ef9ff..e050b4a74 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -444,6 +444,14 @@
"key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:2",
"strategy": "subquery"
},
+ {
+ "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:1",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/community/bot.ts:setBotActive:inArray:2",
+ "strategy": "subquery"
+ },
{
"key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:1",
"strategy": "subquery"
@@ -862,6 +870,30 @@
"key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:2",
"strategy": "fixed-literal"
},
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileActiveBotsBuilder:inArray:1",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:1",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:2",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:3",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:reconcileOnlineMachinesBuilders:inArray:4",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/product-plan.ts:setPlanEntitlement:inArray:1",
+ "strategy": "subquery"
+ },
{
"key": "src/shared/src/db/queries/runtime.ts:deleteRuntimesByDaemonId:inArray:1",
"strategy": "subquery"
diff --git a/src/shared/src/billing.ts b/src/shared/src/billing.ts
new file mode 100644
index 000000000..197f8d4fa
--- /dev/null
+++ b/src/shared/src/billing.ts
@@ -0,0 +1,65 @@
+import { z } from "zod";
+
+export const BillingPlanSchema = z.object({
+ id: z.string().min(1),
+ displayName: z.string().min(1),
+});
+
+export const BillingOfferSchema = z.object({
+ priceId: z.string().min(1),
+ botLimit: z.number().int().nonnegative(),
+ machineLimit: z.number().int().nonnegative(),
+ plan: BillingPlanSchema,
+ unitAmount: z.number().int().nonnegative(),
+ currency: z.string().min(1),
+ interval: z.enum(["month", "year", "week", "day"]),
+ intervalCount: z.number().int().positive(),
+});
+
+export const BillingSubscriptionSchema = z.object({
+ plan: BillingPlanSchema,
+ status: z.string().min(1),
+ currentPeriodEnd: z.string().datetime().nullable(),
+ cancelAt: z.string().datetime().nullable(),
+ scheduledChange: z.object({
+ plan: BillingPlanSchema,
+ effectiveAt: z.string().datetime(),
+ }).nullable(),
+});
+
+export const PublicPricingSchema = z.object({
+ free: z.object({
+ plan: BillingPlanSchema,
+ botLimit: z.number().int().nonnegative(),
+ machineLimit: z.number().int().nonnegative(),
+ }),
+ offers: z.array(BillingOfferSchema),
+});
+
+export const BillingSummarySchema = z.object({
+ plan: BillingPlanSchema,
+ isFounder: z.boolean(),
+ offers: z.array(BillingOfferSchema),
+ subscription: BillingSubscriptionSchema.nullable(),
+});
+
+export const BillingCheckoutRequestSchema = z.strictObject({
+ priceId: z.string().min(1).max(255),
+ founderAcknowledged: z.boolean().optional(),
+});
+
+export const BillingPortalRequestSchema = z.strictObject({
+ priceId: z.string().min(1).max(255).optional(),
+});
+
+export const BillingRedirectResponseSchema = z.object({
+ url: z.string().url(),
+});
+
+export type BillingSummary = z.infer<typeof BillingSummarySchema>;
+export type PublicPricing = z.infer<typeof PublicPricingSchema>;
+export type BillingOffer = z.infer<typeof BillingOfferSchema>;
+export type BillingSubscription = z.infer<typeof BillingSubscriptionSchema>;
+export type BillingCheckoutRequest = z.infer<typeof BillingCheckoutRequestSchema>;
+export type BillingPortalRequest = z.infer<typeof BillingPortalRequestSchema>;
+export type BillingRedirectResponse = z.infer<typeof BillingRedirectResponseSchema>;
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.ts
index 8c4c7cae9..5460cbc48 100644
--- a/src/shared/src/community/wake-dispatch.ts
+++ b/src/shared/src/community/wake-dispatch.ts
@@ -127,6 +127,7 @@ export type SkipReason =
| "bot_missing"
| "bot_deleted"
| "bot_unbound"
+ | "bot_inactive"
| "forbidden"
| "notice_channel_unresolvable"
| "already_read"
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index b64fb9777..479f34847 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -120,10 +120,10 @@ export const TERMINAL_MEETING_STATUSES: readonly MeetingStatusType[] = [
// ── Community bots ───────────────────────────────────────────────────────────
-// Anti-abuse floor. NOT a UX cap — per-server pollution is prevented by
-// explicit-add-per-server (no fan-out). Bump if abuse patterns change; do not
-// repurpose as a UX signal.
-export const COMMUNITY_BOT_LIMIT_PER_OWNER = 20;
+// Transport/schema safety ceiling for one community bot collection in a
+// request. This is NOT the owner's product-plan limit; business capacity is
+// resolved from the generic `bots.max` entitlement.
+export const COMMUNITY_BOT_REQUEST_MAX_ITEMS = 100;
// Display-line-fit at 375 px mobile width.
export const COMMUNITY_BOT_NAME_MIN = 1;
export const COMMUNITY_BOT_NAME_MAX = 32;
diff --git a/src/shared/src/db/billing-schema.ts b/src/shared/src/db/billing-schema.ts
new file mode 100644
index 000000000..f05ca7fc8
--- /dev/null
+++ b/src/shared/src/db/billing-schema.ts
@@ -0,0 +1,35 @@
+import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { user } from "./schema";
+import { productPlan } from "./product-plan-schema";
+import type { BillingSubscription } from "../billing";
+
+export type CheckoutAttempt = {
+ id: string;
+ priceId: string;
+ email: string;
+ origin: string;
+ startedAt: number;
+ sessionId: string | null;
+ founderAcknowledged?: boolean;
+};
+
+export const billingPrice = sqliteTable("billing_price", {
+ priceId: text("price_id").primaryKey(),
+ planId: text("plan_id").notNull().references(() => productPlan.id, { onDelete: "restrict" }),
+ portalConfigurationId: text("portal_configuration_id"),
+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
+});
+
+export const userBilling = sqliteTable("user_billing", {
+ userId: text("user_id").primaryKey().references(() => user.id, { onDelete: "cascade" }),
+ customerId: text("customer_id"),
+ subscriptionId: text("subscription_id"),
+ subscription: text("subscription_json", { mode: "json" }).$type<BillingSubscription>(),
+ revision: integer("revision").notNull().default(0),
+ applyToken: text("apply_token"),
+ checkoutAttempt: text("checkout_attempt_json", { mode: "json" }).$type<CheckoutAttempt>(),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+}, (t) => [
+ uniqueIndex("uq_user_billing_customer").on(t.customerId),
+ uniqueIndex("uq_user_billing_subscription").on(t.subscriptionId),
+]);
diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.ts
index e01221b37..00e489b75 100644
--- a/src/shared/src/db/community-machine-schema.ts
+++ b/src/shared/src/db/community-machine-schema.ts
@@ -266,6 +266,7 @@ export const communityBotBinding = sqliteTable(
modelName: text("model_name"),
reasoningEffort: text("reasoning_effort"),
runtimeConfigRevision: integer("runtime_config_revision").notNull().default(0),
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
createdAt: text("created_at")
.notNull()
.$defaultFn(() => new Date().toISOString()),
diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.ts
index e81b76f94..156cd18a0 100644
--- a/src/shared/src/db/index.ts
+++ b/src/shared/src/db/index.ts
@@ -2,8 +2,10 @@ import { drizzle, type AnyD1Database } from "drizzle-orm/d1";
import * as schema from "./schema";
import * as communitySchema from "./community-schema";
import * as communityMachineSchema from "./community-machine-schema";
+import * as billingSchema from "./billing-schema";
+import * as productPlanSchema from "./product-plan-schema";
-const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema };
+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema };
export function createDb(d1: AnyD1Database) {
return drizzle(d1, { schema: allSchema });
diff --git a/src/shared/src/db/product-plan-schema.ts b/src/shared/src/db/product-plan-schema.ts
new file mode 100644
index 000000000..a618a843e
--- /dev/null
+++ b/src/shared/src/db/product-plan-schema.ts
@@ -0,0 +1,54 @@
+import { index, integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
+import { user } from "./schema";
+
+export const productPlan = sqliteTable(
+ "product_plan",
+ {
+ id: text("id").primaryKey(),
+ displayName: text("display_name").notNull(),
+ isDefault: integer("is_default", { mode: "boolean" }).notNull().default(false),
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
+ sortOrder: integer("sort_order").notNull().default(0),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [
+ uniqueIndex("uq_product_plan_active_default")
+ .on(t.isDefault)
+ .where(sql`${t.isDefault} = 1 AND ${t.isActive} = 1`),
+ ],
+);
+
+export const productPlanEntitlement = sqliteTable(
+ "product_plan_entitlement",
+ {
+ planId: text("plan_id")
+ .notNull()
+ .references(() => productPlan.id, { onDelete: "cascade" }),
+ entitlementKey: text("entitlement_key").notNull(),
+ valueJson: text("value_json", { mode: "json" }).$type<unknown>().notNull(),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [
+ primaryKey({ columns: [t.planId, t.entitlementKey] }),
+ index("idx_product_plan_entitlement_key").on(t.entitlementKey, t.planId),
+ ],
+);
+
+export const userProductPlan = sqliteTable(
+ "user_product_plan",
+ {
+ userId: text("user_id")
+ .primaryKey()
+ .references(() => user.id, { onDelete: "cascade" }),
+ planId: text("plan_id")
+ .notNull()
+ .references(() => productPlan.id, { onDelete: "restrict" }),
+ isFounder: integer("is_founder", { mode: "boolean" }).notNull().default(false),
+ assignedAt: text("assigned_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [index("idx_user_product_plan_plan").on(t.planId)],
+);
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 483de04d2..14688eaa1 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -33,6 +33,7 @@ export * as issue from "./queries/issue";
export * as issueComment from "./queries/issue-comment";
export * as messageFlag from "./queries/message-flag";
export * as accountDeletion from "./queries/account-deletion";
+export * as productPlan from "./queries/product-plan";
export * as communityServer from "./queries/community/server";
export * as communityChannel from "./queries/community/channel";
export * as communityCategory from "./queries/community/category";
@@ -66,3 +67,5 @@ export * as communityBotAuditLog from "./queries/community/bot-audit-log";
export * as communityMessageTag from "./queries/community/message-tag";
export * as communityDiagnosticReport from "./queries/community/diagnostic-report";
export const nativeOauth = nativeOauthQueries;
+
+export * as billing from "./queries/billing";
diff --git a/src/shared/src/db/queries/billing.ts b/src/shared/src/db/queries/billing.ts
new file mode 100644
index 000000000..d7149e513
--- /dev/null
+++ b/src/shared/src/db/queries/billing.ts
@@ -0,0 +1,164 @@
+import { and, eq, exists, isNull, sql } from "drizzle-orm";
+import { alias } from "drizzle-orm/sqlite-core";
+import type { Database } from "../index";
+import { userBilling, billingPrice } from "../billing-schema";
+import { productPlan, productPlanEntitlement, userProductPlan } from "../product-plan-schema";
+import { user } from "../schema";
+import {
+ assignUserPlanBuilder, botsMaxForPlanSql, nonFounderCondition,
+ reconcileOwnerOnlineMachinesBuilders, machinesMaxForPlanSql, type DisconnectedMachine,
+ reconcileOwnerActiveBotsBuilder, resolveBotsMaxForUser,
+} from "./product-plan";
+
+export type BillingRow = typeof userBilling.$inferSelect;
+export type BillingPatch = Partial<Pick<BillingRow,
+ "customerId" | "subscriptionId" | "subscription" | "checkoutAttempt"
+>>;
+
+function billingOwnerCondition(db: Database, userId: string, allowFounder = false) {
+ return and(allowFounder ? undefined : nonFounderCondition(db, userId), exists(db.select({ id: user.id }).from(user).where(and(
+ eq(user.id, userId), eq(user.isBot, false), isNull(user.deletedAt),
+ ))));
+}
+
+export async function getBilling(db: Database, userId: string) {
+ const rows = await db.select().from(userBilling).where(eq(userBilling.userId, userId)).limit(1);
+ return rows[0] ?? null;
+}
+
+export async function getBillingByCustomer(db: Database, customerId: string) {
+ const rows = await db.select().from(userBilling).where(eq(userBilling.customerId, customerId)).limit(1);
+ return rows[0] ?? null;
+}
+
+export async function ensureBilling(db: Database, userId: string, founderAcknowledged = false) {
+ const now = new Date().toISOString();
+ await db.insert(userBilling).select(db.select({
+ userId: user.id,
+ customerId: sql<string | null>`NULL`.as("customer_id"),
+ subscriptionId: sql<string | null>`NULL`.as("subscription_id"),
+ subscription: sql<null>`NULL`.as("subscription_json"),
+ revision: sql<number>`0`.as("revision"),
+ applyToken: sql<string | null>`NULL`.as("apply_token"),
+ checkoutAttempt: sql<null>`NULL`.as("checkout_attempt_json"),
+ updatedAt: sql<string>`${now}`.as("updated_at"),
+ }).from(user).where(and(
+ eq(user.id, userId), eq(user.isBot, false), isNull(user.deletedAt),
+ founderAcknowledged ? undefined : nonFounderCondition(db, userId),
+ ))).onConflictDoNothing();
+ return getBilling(db, userId);
+}
+
+export async function listPrices(db: Database, includeDisabled = false) {
+ const machineEntitlement = alias(productPlanEntitlement, "machine_entitlement");
+ return db.select({
+ priceId: billingPrice.priceId,
+ portalConfigurationId: billingPrice.portalConfigurationId,
+ botLimit: productPlanEntitlement.valueJson,
+ machineLimit: machineEntitlement.valueJson,
+ planId: productPlan.id,
+ displayName: productPlan.displayName,
+ sortOrder: productPlan.sortOrder,
+ }).from(billingPrice).innerJoin(productPlan, eq(productPlan.id, billingPrice.planId))
+ .innerJoin(productPlanEntitlement, and(eq(productPlanEntitlement.planId, productPlan.id), eq(productPlanEntitlement.entitlementKey, "bots.max")))
+ .innerJoin(machineEntitlement, and(eq(machineEntitlement.planId, productPlan.id), eq(machineEntitlement.entitlementKey, "machines.max")))
+ .where(and(includeDisabled ? undefined : eq(billingPrice.enabled, true), eq(productPlan.isActive, true), eq(productPlan.isDefault, false)))
+ .orderBy(productPlan.sortOrder);
+}
+
+export async function getDefaultPlan(db: Database) {
+ const rows = await db.select({ id: productPlan.id, displayName: productPlan.displayName })
+ .from(productPlan).where(and(eq(productPlan.isDefault, true), eq(productPlan.isActive, true))).limit(1);
+ if (!rows[0]) throw new Error("DEFAULT_PLAN_UNAVAILABLE");
+ return rows[0];
+}
+
+export async function getDefaultPlanOffer(db: Database) {
+ const machineEntitlement = alias(productPlanEntitlement, "machine_entitlement");
+ const rows = await db.select({
+ plan: { id: productPlan.id, displayName: productPlan.displayName },
+ botLimit: productPlanEntitlement.valueJson,
+ machineLimit: machineEntitlement.valueJson,
+ }).from(productPlan).innerJoin(productPlanEntitlement, and(
+ eq(productPlanEntitlement.planId, productPlan.id),
+ eq(productPlanEntitlement.entitlementKey, "bots.max"),
+ )).innerJoin(machineEntitlement, and(eq(machineEntitlement.planId, productPlan.id), eq(machineEntitlement.entitlementKey, "machines.max"))).where(and(eq(productPlan.isDefault, true), eq(productPlan.isActive, true))).limit(1);
+ if (!rows[0]) throw new Error("DEFAULT_PLAN_UNAVAILABLE");
+ return rows[0];
+}
+
+export async function updateBilling(db: Database, current: BillingRow, patch: BillingPatch, founderAcknowledged = false) {
+ const rows = await db.update(userBilling).set({
+ ...patch,
+ revision: current.revision + 1,
+ applyToken: crypto.randomUUID(),
+ updatedAt: new Date().toISOString(),
+ }).where(and(
+ eq(userBilling.userId, current.userId), eq(userBilling.revision, current.revision),
+ billingOwnerCondition(db, current.userId, founderAcknowledged || current.checkoutAttempt?.founderAcknowledged === true),
+ )).returning();
+ return rows[0] ?? null;
+}
+
+export async function applyBillingPlan(
+ db: Database,
+ current: BillingRow,
+ patch: BillingPatch,
+ planId: string,
+ founderAttemptId?: string,
+): Promise<{ applied: boolean; deactivatedBotIds: string[]; disconnectedMachines: DisconnectedMachine[] }> {
+ const founderAttempt = current.checkoutAttempt;
+ if (founderAttemptId && (!founderAttempt?.founderAcknowledged || founderAttempt.id !== founderAttemptId
+ || patch.checkoutAttempt !== null || !patch.subscriptionId || !patch.subscription)) {
+ return { applied: false, deactivatedBotIds: [], disconnectedMachines: [] };
+ }
+ const machineEntitlement = alias(productPlanEntitlement, "machine_entitlement");
+ const available = await db.select({ value: productPlanEntitlement.valueJson, machineValue: machineEntitlement.valueJson }).from(productPlan)
+ .innerJoin(productPlanEntitlement, and(eq(productPlanEntitlement.planId, productPlan.id), eq(productPlanEntitlement.entitlementKey, "bots.max")))
+ .innerJoin(machineEntitlement, and(eq(machineEntitlement.planId, productPlan.id), eq(machineEntitlement.entitlementKey, "machines.max")))
+ .where(and(eq(productPlan.id, planId), eq(productPlan.isActive, true))).limit(1);
+ if (typeof available[0]?.value !== "number" || !Number.isInteger(available[0].value) || available[0].value < 0) {
+ throw new Error("BILLING_PLAN_UNAVAILABLE");
+ }
+ if (typeof available[0]?.machineValue !== "number" || !Number.isInteger(available[0].machineValue) || available[0].machineValue < 0) throw new Error("BILLING_PLAN_UNAVAILABLE");
+ const token = crypto.randomUUID();
+ const guard = exists(db.select({ one: sql<number>`1` }).from(userBilling).where(and(
+ eq(userBilling.userId, current.userId), eq(userBilling.applyToken, token),
+ billingOwnerCondition(db, current.userId, true),
+ )));
+ const projection = db.update(userBilling).set({
+ ...patch, revision: current.revision + 1, applyToken: token,
+ updatedAt: new Date().toISOString(),
+ }).where(and(
+ eq(userBilling.userId, current.userId), eq(userBilling.revision, current.revision),
+ billingOwnerCondition(db, current.userId, Boolean(founderAttemptId)),
+ founderAttemptId ? and(
+ eq(userBilling.checkoutAttempt, founderAttempt!),
+ exists(db.select({ id: billingPrice.priceId }).from(billingPrice).where(and(
+ eq(billingPrice.priceId, founderAttempt!.priceId), eq(billingPrice.planId, planId),
+ ))),
+ ) : undefined,
+ exists(db.select({ id: machineEntitlement.planId }).from(machineEntitlement).where(and(
+ eq(machineEntitlement.planId, planId), eq(machineEntitlement.entitlementKey, "machines.max"),
+ sql`json_type(${machineEntitlement.valueJson}) = 'integer' AND CAST(${machineEntitlement.valueJson} AS INTEGER) >= 0`,
+ ))),
+ exists(db.select({ id: productPlan.id }).from(productPlan).innerJoin(productPlanEntitlement, and(
+ eq(productPlanEntitlement.planId, productPlan.id), eq(productPlanEntitlement.entitlementKey, "bots.max"),
+ )).where(and(eq(productPlan.id, planId), eq(productPlan.isActive, true),
+ sql`json_type(${productPlanEntitlement.valueJson}) = 'integer' AND CAST(${productPlanEntitlement.valueJson} AS INTEGER) >= 0`,
+ ))),
+ )).returning({ userId: userBilling.userId });
+ const assignment = assignUserPlanBuilder(db, current.userId, planId, guard);
+ const reconcile = reconcileOwnerActiveBotsBuilder(db, current.userId, botsMaxForPlanSql(planId), guard);
+ const machines = reconcileOwnerOnlineMachinesBuilders(db, current.userId, machinesMaxForPlanSql(planId), guard);
+ if (founderAttemptId) {
+ const removeFounder = db.update(userProductPlan).set({ isFounder: false })
+ .where(and(eq(userProductPlan.userId, current.userId), eq(userProductPlan.isFounder, true), guard));
+ const results = await db.batch([projection, removeFounder, assignment, reconcile, ...machines]);
+ return { applied: results[0].length === 1, deactivatedBotIds: results[3].map((row) => row.botId), disconnectedMachines: results[4] };
+ }
+ const results = await db.batch([projection, assignment, reconcile, ...machines]);
+ return { applied: results[0].length === 1, deactivatedBotIds: results[2].map((row) => row.botId), disconnectedMachines: results[3] };
+}
+
+export { resolveBotsMaxForUser as getEffectivePlan };
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index ab6f4e9c2..feb7ba64f 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -18,7 +18,7 @@
* return null / 404 at the route. The victim's state must be untouched.
*/
-import { aliasedTable, and, count, eq, exists, gte, inArray, isNull, lt, or, sql } from "drizzle-orm";
+import { aliasedTable, and, count, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, ne, notExists, or, sql } from "drizzle-orm";
import { user } from "../../schema";
import {
communityBotBinding,
@@ -32,6 +32,12 @@ import {
communityBotDailyActivity,
communityBotDailyTokenUsage,
communityBotActivityEvent,
+ communityCategory,
+ communityChannel,
+ communityChannelMember,
+ communityFriendship,
+ communityMessage,
+ communityReadStateRevision,
} from "../../community-schema";
import type { DailyUsageSnapshot } from "../../../provider-telemetry";
import { communityMachine } from "../../community-machine-schema";
@@ -42,6 +48,9 @@ import { nanoid } from "nanoid";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
import type { ReasoningEffort } from "../../../runtime-config";
import { CommunityMachineRuntimeSchema, type CommunityMachineRuntime } from "../../../schemas";
+import { getBotCapacitySummary } from "../product-plan";
+import type { BotCapacitySummary } from "../../../product-entitlements";
+import { isPresenceOnline } from "../../../utils/status";
// ─── Types ──────────────────────────────────────────────────────────────────
@@ -71,6 +80,7 @@ export type BotBinding = {
modelName: string | null;
reasoningEffort: ReasoningEffort | null;
runtimeConfigRevision: number;
+ isActive: boolean;
createdAt: string;
};
@@ -81,6 +91,12 @@ export class OwnerHasBotsError extends Error {
}
}
+const BOT_ENTITLEMENT_LIMIT_ERROR = "BOT_ENTITLEMENT_LIMIT_REACHED";
+
+export function isBotEntitlementLimitError(error: unknown): boolean {
+ return error instanceof Error && error.message.includes(BOT_ENTITLEMENT_LIMIT_ERROR);
+}
+
// ─── Reads ─────────────────────────────────────────────────────────────────
/**
@@ -96,6 +112,8 @@ export async function listBotsForOwner(
modelName: string | null;
reasoningEffort: ReasoningEffort | null;
runtimeConfigRevision: number;
+ isActive: boolean;
+ presence: "online" | "offline";
tokenUsageTimeZone: string | null;
}>> {
const rows = await db
@@ -115,6 +133,8 @@ export async function listBotsForOwner(
modelName: communityBotBinding.modelName,
reasoningEffort: communityBotBinding.reasoningEffort,
runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,
+ isActive: communityBotBinding.isActive,
+ machineStatus: communityMachine.status,
tokenUsageTimeZone: communityMachine.timeZone,
})
.from(user)
@@ -143,6 +163,8 @@ export async function listBotsForOwner(
modelName: r.modelName ?? null,
reasoningEffort: r.reasoningEffort ?? null,
runtimeConfigRevision: r.runtimeConfigRevision ?? 0,
+ isActive: r.isActive,
+ presence: r.isActive && isPresenceOnline(r.machineStatus) ? "online" : "offline",
tokenUsageTimeZone: r.tokenUsageTimeZone ?? null,
}));
}
@@ -200,6 +222,7 @@ export async function getBotOwnedBy(
modelName: string | null;
reasoningEffort: ReasoningEffort | null;
runtimeConfigRevision: number;
+ isActive: boolean;
avatarObjectKey: string | null;
}) | null> {
const rows = await db
@@ -220,6 +243,7 @@ export async function getBotOwnedBy(
modelName: communityBotBinding.modelName,
reasoningEffort: communityBotBinding.reasoningEffort,
runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,
+ isActive: communityBotBinding.isActive,
})
.from(user)
.leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
@@ -251,6 +275,7 @@ export async function getBotOwnedBy(
modelName: r.modelName ?? null,
reasoningEffort: r.reasoningEffort ?? null,
runtimeConfigRevision: r.runtimeConfigRevision ?? 0,
+ isActive: r.isActive ?? false,
};
}
@@ -372,6 +397,7 @@ export async function getBotBinding(
modelName: string | null;
reasoningEffort: ReasoningEffort | null;
runtimeConfigRevision: number;
+ isActive: boolean;
} | null> {
const rows = await db
.select({
@@ -380,6 +406,7 @@ export async function getBotBinding(
modelName: communityBotBinding.modelName,
reasoningEffort: communityBotBinding.reasoningEffort,
runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,
+ isActive: communityBotBinding.isActive,
})
.from(communityBotBinding)
.where(eq(communityBotBinding.userId, botId))
@@ -392,9 +419,289 @@ export async function getBotBinding(
modelName: r.modelName ?? null,
reasoningEffort: r.reasoningEffort ?? null,
runtimeConfigRevision: r.runtimeConfigRevision ?? 0,
+ isActive: r.isActive,
};
}
+function ownerScopedBotIds(
+ db: Database,
+ botId: string,
+ ownerId: string,
+ isActive: boolean,
+) {
+ return db
+ .select({ id: user.id })
+ .from(user)
+ .innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
+ .where(
+ and(
+ eq(user.id, botId),
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ eq(communityBotBinding.isActive, isActive),
+ ),
+ );
+}
+
+function activationCursorCatchupBuilder(
+ db: Database,
+ botId: string,
+ ownerId: string,
+) {
+ const message = aliasedTable(communityMessage, "activation_message");
+ const newerMessage = aliasedTable(communityMessage, "activation_newer_message");
+ const channel = aliasedTable(communityChannel, "activation_channel");
+ const parent = aliasedTable(communityChannel, "activation_parent_channel");
+ const category = aliasedTable(communityCategory, "activation_category");
+ const serverMember = aliasedTable(communityServerMember, "activation_server_member");
+ const anchorMember = aliasedTable(communityChannelMember, "activation_anchor_member");
+ const dmSelf = aliasedTable(communityChannelMember, "activation_dm_self");
+ const dmPeer = aliasedTable(communityChannelMember, "activation_dm_peer");
+ const blocked = aliasedTable(communityFriendship, "activation_dm_block");
+
+ const anchorId = sql<string>`COALESCE(${parent.id}, ${channel.id})`;
+ const anchorCreatorId = sql<string | null>`COALESCE(${parent.creatorId}, ${channel.creatorId})`;
+ const anchorCategoryId = sql<string | null>`COALESCE(${parent.categoryId}, ${channel.categoryId})`;
+ const ownerScopedInactive = exists(ownerScopedBotIds(db, botId, ownerId, false));
+
+ const dmVisible = and(
+ eq(channel.type, "dm"),
+ exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(dmSelf)
+ .where(
+ and(
+ eq(dmSelf.channelId, channel.id),
+ eq(dmSelf.userId, botId),
+ eq(dmSelf.relation, "access"),
+ ),
+ ),
+ ),
+ notExists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(dmPeer)
+ .innerJoin(
+ blocked,
+ and(
+ eq(blocked.status, "blocked"),
+ or(
+ and(eq(blocked.requesterId, botId), eq(blocked.addresseeId, dmPeer.userId)),
+ and(eq(blocked.requesterId, dmPeer.userId), eq(blocked.addresseeId, botId)),
+ ),
+ ),
+ )
+ .where(
+ and(
+ eq(dmPeer.channelId, channel.id),
+ eq(dmPeer.relation, "access"),
+ ne(dmPeer.userId, botId),
+ ),
+ ),
+ ),
+ );
+
+ const serverVisible = and(
+ ne(channel.type, "dm"),
+ isNotNull(channel.serverId),
+ exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(serverMember)
+ .where(
+ and(
+ eq(serverMember.serverId, channel.serverId),
+ eq(serverMember.userId, botId),
+ ),
+ ),
+ ),
+ or(
+ isNull(anchorCategoryId),
+ eq(category.private, 0),
+ eq(anchorCreatorId, botId),
+ exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(anchorMember)
+ .where(
+ and(
+ eq(anchorMember.channelId, anchorId),
+ eq(anchorMember.userId, botId),
+ eq(anchorMember.relation, "access"),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ const latestVisibleMessages = db
+ .select({
+ id: sql<string>`lower(hex(randomblob(16)))`.as("id"),
+ userId: sql<string>`${botId}`.as("user_id"),
+ channelId: message.channelId,
+ lastReadAt: message.createdAt,
+ lastReadMessageId: message.id,
+ lastReadSeq: message.seq,
+ })
+ .from(message)
+ .innerJoin(channel, eq(channel.id, message.channelId))
+ .leftJoin(parent, eq(parent.id, channel.parentChannelId))
+ .leftJoin(category, eq(category.id, anchorCategoryId))
+ .where(
+ and(
+ ownerScopedInactive,
+ or(dmVisible, serverVisible),
+ notExists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(newerMessage)
+ .where(
+ and(
+ eq(newerMessage.channelId, message.channelId),
+ gt(newerMessage.seq, message.seq),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ return db
+ .insert(communityReadState)
+ .select(latestVisibleMessages)
+ .onConflictDoUpdate({
+ target: [communityReadState.userId, communityReadState.channelId],
+ set: {
+ lastReadAt: sql`excluded.last_read_at`,
+ lastReadMessageId: sql`excluded.last_read_message_id`,
+ lastReadSeq: sql`excluded.last_read_seq`,
+ },
+ setWhere: sql`${communityReadState.lastReadSeq} < excluded.last_read_seq`,
+ });
+}
+
+function activationReadStateRevisionBuilder(
+ db: Database,
+ botId: string,
+ ownerId: string,
+) {
+ const selected = db
+ .select({
+ userId: sql<string>`${botId}`.as("user_id"),
+ revision: sql<number>`1`.as("revision"),
+ })
+ .from(user)
+ .where(
+ and(
+ eq(user.id, botId),
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ exists(ownerScopedBotIds(db, botId, ownerId, false)),
+ ),
+ )
+ .limit(1);
+ return db
+ .insert(communityReadStateRevision)
+ .select(selected)
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ });
+}
+
+export type BotActivationMutationResult =
+ | { state: "not_found" }
+ | { state: "capacity"; capacity: BotCapacitySummary }
+ | {
+ state: "unchanged" | "updated";
+ bot: NonNullable<Awaited<ReturnType<typeof getBotOwnedBy>>>;
+ };
+
+export async function setBotActive(
+ db: Database,
+ botId: string,
+ ownerId: string,
+ active: boolean,
+): Promise<BotActivationMutationResult> {
+ const before = await getBotOwnedBy(db, botId, ownerId);
+ if (!before || !before.machineId || !before.runtime) return { state: "not_found" };
+ if (before.isActive === active) return { state: "unchanged", bot: before };
+
+ if (!active) {
+ // Keep the ownership predicate inside the mutation statement so a raced or
+ // cross-owner request cannot deactivate anything. This is a fixed-bind
+ // subquery, not a caller-sized `IN (...)` list.
+ const ownerScopedActiveIds = db
+ .select({ id: user.id })
+ .from(user)
+ .innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
+ .where(
+ and(
+ eq(user.id, botId),
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ eq(communityBotBinding.isActive, true),
+ ),
+ );
+ const updated = await db
+ .update(communityBotBinding)
+ .set({ isActive: false })
+ .where(inArray(communityBotBinding.userId, ownerScopedActiveIds))
+ .returning({ botId: communityBotBinding.userId });
+ if (updated.length === 0) {
+ const raced = await getBotOwnedBy(db, botId, ownerId);
+ return raced ? { state: "unchanged", bot: raced } : { state: "not_found" };
+ }
+ return { state: "updated", bot: { ...before, isActive: false } };
+ }
+
+ let capacity = await getBotCapacitySummary(db, ownerId);
+ if (capacity.activeCount >= capacity.limit) return { state: "capacity", capacity };
+
+ const cursorCatchup = activationCursorCatchupBuilder(db, botId, ownerId);
+ const revision = activationReadStateRevisionBuilder(db, botId, ownerId);
+ // Repeat the owner-scoped state check in the final UPDATE. The preflight and
+ // cursor statements are not authorization; this subquery is the mutation's
+ // race-safe ownership boundary.
+ const ownerScopedInactiveIds = db
+ .select({ id: user.id })
+ .from(user)
+ .innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
+ .where(
+ and(
+ eq(user.id, botId),
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ eq(communityBotBinding.isActive, false),
+ ),
+ );
+ const activate = db
+ .update(communityBotBinding)
+ .set({ isActive: true })
+ .where(inArray(communityBotBinding.userId, ownerScopedInactiveIds))
+ .returning({ botId: communityBotBinding.userId });
+ try {
+ const results = await db.batch([cursorCatchup, revision, activate] as any) as unknown as [
+ unknown,
+ unknown,
+ Array<{ botId: string }>,
+ ];
+ if (results[2].length === 0) {
+ const raced = await getBotOwnedBy(db, botId, ownerId);
+ return raced ? { state: "unchanged", bot: raced } : { state: "not_found" };
+ }
+ } catch (error) {
+ if (!isBotEntitlementLimitError(error)) throw error;
+ capacity = await getBotCapacitySummary(db, ownerId);
+ return { state: "capacity", capacity };
+ }
+ return { state: "updated", bot: { ...before, isActive: true } };
+}
+
/**
* Combined lookup: bot's machine binding + owner userId. Used by ws-do's audit
* event handler to (a) verify the frame originates from the machine that owns
@@ -404,7 +711,7 @@ export async function getBotBinding(
export async function getBotBindingWithOwner(
db: Database,
botId: string
-): Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null> {
+): Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string; isActive: boolean } | null> {
const rows = await db
.select({
machineId: communityBotBinding.machineId,
@@ -415,6 +722,7 @@ export async function getBotBindingWithOwner(
// reads the `user` row.
name: user.name,
discriminator: user.discriminator,
+ isActive: communityBotBinding.isActive,
})
.from(user)
.innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
@@ -422,13 +730,20 @@ export async function getBotBindingWithOwner(
and(
eq(user.id, botId),
eq(user.isBot, true),
- isNull(user.deletedAt)
+ isNull(user.deletedAt),
)
)
.limit(1);
const r = rows[0];
if (!r || !r.ownerUserId) return null;
- return { machineId: r.machineId, runtime: r.runtime, ownerUserId: r.ownerUserId, name: r.name, discriminator: r.discriminator };
+ return {
+ machineId: r.machineId,
+ runtime: r.runtime,
+ ownerUserId: r.ownerUserId,
+ name: r.name,
+ discriminator: r.discriminator,
+ isActive: r.isActive,
+ };
}
/**
@@ -473,7 +788,8 @@ export async function findWakeCandidates(
and(
inArray(user.id, ids),
eq(user.isBot, true),
- isNull(user.deletedAt)
+ isNull(user.deletedAt),
+ eq(communityBotBinding.isActive, true),
)
)
)
@@ -496,6 +812,7 @@ export type BotWakeContext =
| { state: "bot_missing" }
| { state: "bot_deleted" }
| { state: "bot_unbound" }
+ | { state: "bot_inactive" }
| {
state: "ready";
botUserId: string;
@@ -523,6 +840,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promis
modelName: communityBotBinding.modelName,
reasoningEffort: communityBotBinding.reasoningEffort,
runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,
+ isActive: communityBotBinding.isActive,
})
.from(user)
.leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
@@ -532,6 +850,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promis
if (!r || !r.isBot) return { state: "bot_missing" };
if (r.deletedAt) return { state: "bot_deleted" };
if (!r.machineId || !r.runtime) return { state: "bot_unbound" };
+ if (!r.isActive) return { state: "bot_inactive" };
return {
state: "ready",
botUserId: r.id,
@@ -592,6 +911,7 @@ export async function listBotsForMachine(
.where(
and(
eq(communityBotBinding.machineId, machineId),
+ eq(communityBotBinding.isActive, true),
eq(user.isBot, true),
isNull(user.deletedAt),
isNull(owner.deletedAt)
diff --git a/src/shared/src/db/queries/community/machine-session-epoch.ts b/src/shared/src/db/queries/community/machine-session-epoch.ts
index c90001b4c..cde152cd9 100644
--- a/src/shared/src/db/queries/community/machine-session-epoch.ts
+++ b/src/shared/src/db/queries/community/machine-session-epoch.ts
@@ -1,4 +1,4 @@
-import { and, eq, inArray, isNull } from "drizzle-orm";
+import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
import {
communityAgentRunnerKey,
communityMachine,
@@ -13,6 +13,8 @@ import {
type MachineRow,
} from "./machine";
+import { assertMachineCapacity, getMachineCapacitySummary, MachineLimitReachedError, machinesMaxForUserSql } from "../product-plan";
+
const CREDENTIAL_PREFIX = "cmk_";
export type MachineSessionEpochCommand =
@@ -136,6 +138,12 @@ async function transitionLiveLease(
and(
eq(communityMachine.id, prior.id),
statusGuard,
+ command.type === "ready" || command.type === "renew"
+ ? or(eq(communityMachine.status, "online"), sql`(
+ SELECT COUNT(*) FROM community_machine online_machine
+ WHERE online_machine.user_id = ${epoch.userId} AND online_machine.status = 'online'
+ ) < ${machinesMaxForUserSql(epoch.userId)}`)
+ : undefined,
inArray(communityMachine.id, currentEpochMachineIds),
),
)
@@ -196,6 +204,14 @@ async function rotateMachineSessionEpoch(
);
}
+ if (!token.machineId) {
+ await assertMachineCapacity(db, token.userId, "owned");
+ } else {
+ const machine = await db.select({ status: communityMachine.status }).from(communityMachine)
+ .where(and(eq(communityMachine.id, token.machineId), eq(communityMachine.userId, token.userId))).limit(1);
+ if (machine[0]?.status !== "online") await assertMachineCapacity(db, token.userId, "online");
+ }
+
const claimed = await db
.update(communityMachineToken)
.set({ status: "revoked", lastUsedAt: nowIso })
@@ -235,6 +251,7 @@ async function rotateMachineSessionEpoch(
});
} catch (error) {
await restoreClaimedToken(db, command.tokenId);
+ if (isMachineLimitConstraint(error)) throw new MachineLimitReachedError(await getMachineCapacitySummary(db, token.userId));
throw error;
}
return {
@@ -419,3 +436,10 @@ export class MachineSessionRotationError extends Error {
this.name = "MachineSessionRotationError";
}
}
+
+
+function isMachineLimitConstraint(error: unknown): boolean {
+ if (!(error instanceof Error)) return false;
+ return error.message.includes("MACHINE_LIMIT_REACHED")
+ || (error.cause !== error && isMachineLimitConstraint(error.cause));
+}
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index 03f5915fa..df123f88b 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -9,6 +9,7 @@ import {
} from "../../community-machine-schema";
import { user } from "../../schema";
import { communityUserProfile } from "../../community-schema";
+import { assertMachineCapacity } from "../product-plan";
import type { Database } from "../../index";
import { BOT_ACTIVITY_PRESETS, isBotActivityStatus } from "../../../community/bot-activity-presets";
import { COMMUNITY_MACHINE_PAIR_TOKEN_TTL_MS } from "../../../constants";
@@ -70,6 +71,7 @@ export async function createPairingToken(
userId: string,
opts: { machineId?: string | null } = {}
): Promise<{ tokenId: string; expiresAt: string }> {
+ if (!opts.machineId) await assertMachineCapacity(db, userId, "owned");
await db
.update(communityMachineToken)
.set({ status: "revoked" })
@@ -106,7 +108,7 @@ export async function createReconnectPairingToken(
machineId: string
): Promise<{ tokenId: string; expiresAt: string }> {
const owned = await db
- .select({ id: communityMachine.id })
+ .select({ id: communityMachine.id, status: communityMachine.status })
.from(communityMachine)
.where(
and(
@@ -118,6 +120,7 @@ export async function createReconnectPairingToken(
if (owned.length === 0) {
throw new Error("createReconnectPairingToken: machine not owned by user");
}
+ if (owned[0]!.status !== "online") await assertMachineCapacity(db, userId, "online");
return createPairingToken(db, userId, { machineId });
}
@@ -325,7 +328,12 @@ export async function reconcileBotActivityFromRunningAgents(
communityUserProfile,
eq(communityUserProfile.userId, communityBotBinding.userId)
)
- .where(eq(communityBotBinding.machineId, machineId));
+ .where(
+ and(
+ eq(communityBotBinding.machineId, machineId),
+ eq(communityBotBinding.isActive, true),
+ ),
+ );
if (rows.length === 0) return [];
const runningSet = new Set(runningAgentIds);
@@ -748,6 +756,7 @@ export async function isBotOnline(db: Database, botUserId: string): Promise<bool
.where(
and(
eq(communityBotBinding.userId, botUserId),
+ eq(communityBotBinding.isActive, true),
isNull(user.deletedAt),
eq(user.isBot, true),
),
diff --git a/src/shared/src/db/queries/product-plan.ts b/src/shared/src/db/queries/product-plan.ts
new file mode 100644
index 000000000..a46819e5e
--- /dev/null
+++ b/src/shared/src/db/queries/product-plan.ts
@@ -0,0 +1,474 @@
+import { and, count, eq, exists, gt, inArray, isNull, notExists, or, sql, type SQL } from "drizzle-orm";
+import type { z } from "zod";
+import { user } from "../schema";
+import { communityBotBinding, communityMachine, communityMachineCredential, communityAgentRunnerKey } from "../community-machine-schema";
+import {
+ productPlan,
+ productPlanEntitlement,
+ userProductPlan,
+} from "../product-plan-schema";
+import type { Database } from "../index";
+import {
+ BOTS_MAX_ENTITLEMENT_KEY,
+ MACHINES_MAX_ENTITLEMENT_KEY,
+ type MachineCapacitySummary,
+ EntitlementValueSchema,
+ NonNegativeIntegerEntitlementSchema,
+ type BotCapacitySummary,
+ type EntitlementValue,
+ type ResolvedProductPlan,
+} from "../../product-entitlements";
+
+export class ProductEntitlementUnavailableError extends Error {
+ constructor(
+ public readonly entitlementKey: string,
+ public readonly reason: "plan_unavailable" | "entitlement_missing" | "entitlement_malformed",
+ ) {
+ super(`product entitlement unavailable: ${entitlementKey} (${reason})`);
+ this.name = "ProductEntitlementUnavailableError";
+ }
+}
+
+type StoredEntitlement = {
+ planId: string;
+ displayName: string;
+ entitlementKey: string | null;
+ value: unknown;
+ isFounder?: boolean | null;
+};
+
+async function resolveStoredEntitlementForUser(
+ db: Database,
+ userId: string,
+ entitlementKey: string,
+): Promise<StoredEntitlement> {
+ const rows = await db
+ .select({
+ isFounder: userProductPlan.isFounder,
+ planId: productPlan.id,
+ displayName: productPlan.displayName,
+ entitlementKey: productPlanEntitlement.entitlementKey,
+ value: productPlanEntitlement.valueJson,
+ })
+ .from(productPlan)
+ .leftJoin(userProductPlan, eq(userProductPlan.userId, userId))
+ .leftJoin(
+ productPlanEntitlement,
+ and(
+ eq(productPlanEntitlement.planId, productPlan.id),
+ eq(productPlanEntitlement.entitlementKey, entitlementKey),
+ ),
+ )
+ .where(
+ and(
+ eq(productPlan.isActive, true),
+ or(
+ eq(productPlan.id, userProductPlan.planId),
+ and(isNull(userProductPlan.planId), eq(productPlan.isDefault, true)),
+ ),
+ ),
+ )
+ .limit(1);
+ const row = rows[0];
+ if (!row) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "plan_unavailable");
+ }
+ if (row.entitlementKey === null) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "entitlement_missing");
+ }
+ return row;
+}
+
+async function resolveStoredEntitlementForPlan(
+ db: Database,
+ planId: string,
+ entitlementKey: string,
+): Promise<StoredEntitlement> {
+ const rows = await db
+ .select({
+ planId: productPlan.id,
+ displayName: productPlan.displayName,
+ entitlementKey: productPlanEntitlement.entitlementKey,
+ value: productPlanEntitlement.valueJson,
+ })
+ .from(productPlan)
+ .leftJoin(
+ productPlanEntitlement,
+ and(
+ eq(productPlanEntitlement.planId, productPlan.id),
+ eq(productPlanEntitlement.entitlementKey, entitlementKey),
+ ),
+ )
+ .where(and(eq(productPlan.id, planId), eq(productPlan.isActive, true)))
+ .limit(1);
+ const row = rows[0];
+ if (!row) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "plan_unavailable");
+ }
+ if (row.entitlementKey === null) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "entitlement_missing");
+ }
+ return row;
+}
+
+function parseStoredEntitlement<T>(
+ row: StoredEntitlement,
+ entitlementKey: string,
+ schema: z.ZodType<T>,
+): { plan: ResolvedProductPlan; value: T; isFounder: boolean } {
+ const parsed = schema.safeParse(row.value);
+ if (!parsed.success) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "entitlement_malformed");
+ }
+ return {
+ plan: { id: row.planId, displayName: row.displayName },
+ value: parsed.data,
+ isFounder: row.isFounder ?? false,
+ };
+}
+
+export async function resolveEntitlementForUser<T>(
+ db: Database,
+ userId: string,
+ entitlementKey: string,
+ schema: z.ZodType<T>,
+): Promise<{ plan: ResolvedProductPlan; value: T; isFounder: boolean }> {
+ return parseStoredEntitlement(
+ await resolveStoredEntitlementForUser(db, userId, entitlementKey),
+ entitlementKey,
+ schema,
+ );
+}
+
+export async function resolveBotsMaxForUser(
+ db: Database,
+ userId: string,
+): Promise<{ plan: ResolvedProductPlan; value: number; isFounder: boolean }> {
+ return resolveEntitlementForUser(
+ db,
+ userId,
+ BOTS_MAX_ENTITLEMENT_KEY,
+ NonNegativeIntegerEntitlementSchema,
+ );
+}
+
+export async function resolveMachinesMaxForUser(db: Database, userId: string) {
+ return resolveEntitlementForUser(db, userId, MACHINES_MAX_ENTITLEMENT_KEY, NonNegativeIntegerEntitlementSchema);
+}
+
+export async function getMachineCapacitySummary(db: Database, ownerUserId: string): Promise<MachineCapacitySummary> {
+ const [{ plan, value: limit, isFounder }, counts] = await Promise.all([
+ resolveMachinesMaxForUser(db, ownerUserId),
+ db.select({
+ ownedCount: count(),
+ onlineCount: sql<number>`COALESCE(SUM(CASE WHEN ${communityMachine.status} = 'online' THEN 1 ELSE 0 END), 0)`,
+ }).from(communityMachine).where(eq(communityMachine.userId, ownerUserId)),
+ ]);
+ return { plan, isFounder, limit, ownedCount: counts[0]?.ownedCount ?? 0, onlineCount: counts[0]?.onlineCount ?? 0 };
+}
+
+export class MachineLimitReachedError extends Error {
+ constructor(public readonly capacity: MachineCapacitySummary) {
+ super("MACHINE_LIMIT_REACHED");
+ this.name = "MachineLimitReachedError";
+ }
+}
+
+export async function assertMachineCapacity(db: Database, userId: string, kind: "owned" | "online") {
+ const capacity = await getMachineCapacitySummary(db, userId);
+ if ((kind === "owned" ? capacity.ownedCount : capacity.onlineCount) >= capacity.limit) {
+ throw new MachineLimitReachedError(capacity);
+ }
+ return capacity;
+}
+
+export async function getBotCapacitySummary(
+ db: Database,
+ ownerUserId: string,
+): Promise<BotCapacitySummary> {
+ const [{ plan, value: limit, isFounder }, counts] = await Promise.all([
+ resolveBotsMaxForUser(db, ownerUserId),
+ db
+ .select({
+ ownedCount: count(),
+ activeCount: sql<number>`COALESCE(SUM(CASE WHEN ${communityBotBinding.isActive} = 1 THEN 1 ELSE 0 END), 0)`,
+ })
+ .from(user)
+ .innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
+ .where(
+ and(
+ eq(user.ownerUserId, ownerUserId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ ),
+ ),
+ ]);
+ return {
+ plan,
+ isFounder,
+ limit,
+ ownedCount: counts[0]?.ownedCount ?? 0,
+ activeCount: counts[0]?.activeCount ?? 0,
+ };
+}
+
+function reconcileActiveBotsBuilder(
+ db: Database,
+ ownerCondition: SQL<unknown>,
+ botsMax: number | SQL<number>,
+) {
+ const ranked = db.$with("ranked_active_bots").as(
+ db
+ .select({
+ botId: communityBotBinding.userId,
+ activeRank: sql<number>`ROW_NUMBER() OVER (
+ PARTITION BY ${user.ownerUserId}
+ ORDER BY ${user.createdAt} ASC, ${user.id} ASC
+ )`.as("active_rank"),
+ })
+ .from(communityBotBinding)
+ .innerJoin(user, eq(user.id, communityBotBinding.userId))
+ .where(
+ and(
+ eq(communityBotBinding.isActive, true),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ ownerCondition,
+ ),
+ ),
+ );
+ const overflow = db
+ .with(ranked)
+ .select({ botId: ranked.botId })
+ .from(ranked)
+ .where(gt(ranked.activeRank, botsMax));
+ return db
+ .update(communityBotBinding)
+ .set({ isActive: false })
+ .where(inArray(communityBotBinding.userId, overflow))
+ .returning({ botId: communityBotBinding.userId });
+}
+
+export function reconcileOwnerActiveBotsBuilder(
+ db: Database,
+ ownerUserId: string,
+ botsMax: number | SQL<number>,
+ guard?: SQL<unknown>,
+) {
+ return reconcileActiveBotsBuilder(db, and(eq(user.ownerUserId, ownerUserId), guard)!, botsMax);
+}
+
+function reconcilePlanActiveBotsBuilder(
+ db: Database,
+ planId: string,
+ botsMax: number,
+) {
+ const ownerHasExplicitPlan = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(userProductPlan)
+ .where(
+ and(
+ eq(userProductPlan.userId, user.ownerUserId),
+ eq(userProductPlan.planId, planId),
+ ),
+ ),
+ );
+ const targetIsDefault = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(productPlan)
+ .where(
+ and(
+ eq(productPlan.id, planId),
+ eq(productPlan.isActive, true),
+ eq(productPlan.isDefault, true),
+ ),
+ ),
+ );
+ const ownerHasNoAssignment = notExists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(userProductPlan)
+ .where(eq(userProductPlan.userId, user.ownerUserId)),
+ );
+ return reconcileActiveBotsBuilder(
+ db,
+ or(ownerHasExplicitPlan, and(targetIsDefault, ownerHasNoAssignment))!,
+ botsMax,
+ );
+}
+
+export type DisconnectedMachine = { machineId: string; userId: string; doName: string | null };
+
+export function machinesMaxForPlanSql(planId: string): SQL<number> {
+ return sql<number>`COALESCE((
+ SELECT CAST(e.value_json AS INTEGER) FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ WHERE e.plan_id = ${planId} AND e.entitlement_key = ${MACHINES_MAX_ENTITLEMENT_KEY}
+ AND json_type(e.value_json) = 'integer' AND CAST(e.value_json AS INTEGER) >= 0 LIMIT 1
+ ), 0)`;
+}
+
+function reconcileOnlineMachinesBuilders(db: Database, ownerCondition: SQL<unknown>, limit: number | SQL<number>) {
+ const ranked = db.$with("ranked_online_machines").as(
+ db.select({
+ machineId: communityMachine.id,
+ onlineRank: sql<number>`ROW_NUMBER() OVER (
+ PARTITION BY ${communityMachine.userId} ORDER BY ${communityMachine.createdAt} ASC, ${communityMachine.id} ASC
+ )`.as("online_rank"),
+ }).from(communityMachine).where(and(eq(communityMachine.status, "online"), ownerCondition)),
+ );
+ const overflow = db.with(ranked).select({ machineId: ranked.machineId }).from(ranked).where(gt(ranked.onlineRank, limit));
+ const affected = db.select({
+ machineId: communityMachine.id, userId: communityMachine.userId, doName: communityMachineCredential.doName,
+ }).from(communityMachine).leftJoin(communityMachineCredential, and(
+ eq(communityMachineCredential.machineId, communityMachine.id), isNull(communityMachineCredential.revokedAt),
+ )).where(inArray(communityMachine.id, overflow));
+ const now = new Date().toISOString();
+ const runners = db.update(communityAgentRunnerKey).set({ revokedAt: now })
+ .where(and(inArray(communityAgentRunnerKey.machineId, overflow), isNull(communityAgentRunnerKey.revokedAt)));
+ const credentials = db.update(communityMachineCredential).set({ revokedAt: now })
+ .where(and(inArray(communityMachineCredential.machineId, overflow), isNull(communityMachineCredential.revokedAt)));
+ const offline = db.update(communityMachine).set({ status: "offline", lastSeenAt: now, updatedAt: now })
+ .where(inArray(communityMachine.id, overflow));
+ return [affected, runners, credentials, offline] as const;
+}
+
+export function reconcileOwnerOnlineMachinesBuilders(db: Database, userId: string, limit: number | SQL<number>, guard?: SQL<unknown>) {
+ return reconcileOnlineMachinesBuilders(db, and(eq(communityMachine.userId, userId), guard)!, limit);
+}
+
+export function machinesMaxForUserSql(userId: string): SQL<number> {
+ return sql<number>`COALESCE((
+ SELECT CAST(e.value_json AS INTEGER)
+ FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ LEFT JOIN user_product_plan up ON up.user_id = ${userId}
+ WHERE e.entitlement_key = ${MACHINES_MAX_ENTITLEMENT_KEY}
+ AND json_type(e.value_json) = 'integer' AND CAST(e.value_json AS INTEGER) >= 0
+ AND p.id = COALESCE(up.plan_id, (SELECT id FROM product_plan WHERE is_default = 1 AND is_active = 1 LIMIT 1))
+ LIMIT 1
+ ), 0)`;
+}
+
+export function botsMaxForPlanSql(planId: string): SQL<number> {
+ return sql<number>`COALESCE((
+ SELECT CAST(entitlement.value_json AS INTEGER)
+ FROM product_plan_entitlement entitlement
+ INNER JOIN product_plan plan ON plan.id = entitlement.plan_id
+ WHERE plan.id = ${planId}
+ AND plan.is_active = 1
+ AND entitlement.entitlement_key = ${BOTS_MAX_ENTITLEMENT_KEY}
+ AND json_type(entitlement.value_json) = 'integer'
+ AND CAST(entitlement.value_json AS INTEGER) >= 0
+ LIMIT 1
+ ), 0)`;
+}
+
+export function nonFounderCondition(db: Database, userId: string): SQL<unknown> {
+ return notExists(db.select({ one: sql<number>`1` }).from(userProductPlan).where(
+ and(eq(userProductPlan.userId, userId), eq(userProductPlan.isFounder, true)),
+ ));
+}
+
+export function assignUserPlanBuilder(
+ db: Database,
+ userId: string,
+ planId: string,
+ guard?: SQL<unknown>,
+) {
+ const now = new Date().toISOString();
+ return db.insert(userProductPlan).select(db.select({
+ userId: user.id,
+ planId: sql<string>`${planId}`.as("plan_id"),
+ isFounder: sql<boolean>`0`.as("is_founder"),
+ assignedAt: sql<string>`${now}`.as("assigned_at"),
+ updatedAt: sql<string>`${now}`.as("updated_at"),
+ }).from(user).where(and(
+ eq(user.id, userId), eq(user.isBot, false), isNull(user.deletedAt),
+ nonFounderCondition(db, userId), guard,
+ ))).onConflictDoUpdate({
+ target: userProductPlan.userId,
+ set: { planId, updatedAt: now },
+ setWhere: and(eq(userProductPlan.isFounder, false), guard),
+ }).returning({ userId: userProductPlan.userId });
+}
+
+export async function assignUserPlan(
+ db: Database,
+ userId: string,
+ planId: string,
+): Promise<{ plan: ResolvedProductPlan; limit: number; deactivatedBotIds: string[]; disconnectedMachines: DisconnectedMachine[] }> {
+ const resolved = parseStoredEntitlement(
+ await resolveStoredEntitlementForPlan(db, planId, BOTS_MAX_ENTITLEMENT_KEY),
+ BOTS_MAX_ENTITLEMENT_KEY,
+ NonNegativeIntegerEntitlementSchema,
+ );
+ parseStoredEntitlement(await resolveStoredEntitlementForPlan(db, planId, MACHINES_MAX_ENTITLEMENT_KEY), MACHINES_MAX_ENTITLEMENT_KEY, NonNegativeIntegerEntitlementSchema);
+ const guard = and(nonFounderCondition(db, userId), exists(
+ db.select({ id: user.id }).from(user).where(and(
+ eq(user.id, userId), eq(user.isBot, false), isNull(user.deletedAt),
+ )),
+ ))!;
+ const assign = assignUserPlanBuilder(db, userId, planId, guard);
+ const reconcile = reconcileOwnerActiveBotsBuilder(
+ db, userId, botsMaxForPlanSql(planId), guard,
+ );
+ const machines = reconcileOwnerOnlineMachinesBuilders(db, userId, machinesMaxForPlanSql(planId), guard);
+ const results = await db.batch([assign, reconcile, ...machines]);
+
+ if (results[0].length === 0) throw new Error("PLAN_ASSIGNMENT_PROTECTED");
+ return {
+ plan: resolved.plan,
+ limit: resolved.value,
+ deactivatedBotIds: results[1].map((row) => row.botId),
+ disconnectedMachines: results[2],
+ };
+}
+
+export async function setPlanEntitlement(
+ db: Database,
+ planId: string,
+ entitlementKey: string,
+ value: EntitlementValue,
+): Promise<{ deactivatedBotIds: string[]; disconnectedMachines?: DisconnectedMachine[] }> {
+ const parsedValue = EntitlementValueSchema.parse(value);
+ const planRows = await db
+ .select({ id: productPlan.id })
+ .from(productPlan)
+ .where(and(eq(productPlan.id, planId), eq(productPlan.isActive, true)))
+ .limit(1);
+ if (!planRows[0]) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "plan_unavailable");
+ }
+ const now = new Date().toISOString();
+ const write = db
+ .insert(productPlanEntitlement)
+ .values({ planId, entitlementKey, valueJson: parsedValue, createdAt: now, updatedAt: now })
+ .onConflictDoUpdate({
+ target: [productPlanEntitlement.planId, productPlanEntitlement.entitlementKey],
+ set: { valueJson: parsedValue, updatedAt: now },
+ });
+ if (entitlementKey === MACHINES_MAX_ENTITLEMENT_KEY) {
+ const parsed = NonNegativeIntegerEntitlementSchema.safeParse(parsedValue);
+ if (!parsed.success) throw new ProductEntitlementUnavailableError(entitlementKey, "entitlement_malformed");
+ const explicit = inArray(communityMachine.userId, db.select({ id: userProductPlan.userId }).from(userProductPlan).where(eq(userProductPlan.planId, planId)));
+ const defaultPlan = exists(db.select({ id: productPlan.id }).from(productPlan).where(and(eq(productPlan.id, planId), eq(productPlan.isDefault, true))));
+ const unassigned = notExists(db.select({ id: userProductPlan.userId }).from(userProductPlan).where(eq(userProductPlan.userId, communityMachine.userId)));
+ const machines = reconcileOnlineMachinesBuilders(db, or(explicit, and(defaultPlan, unassigned))!, parsed.data);
+ const results = await db.batch([write, ...machines]);
+ return { deactivatedBotIds: [], disconnectedMachines: results[1] };
+ }
+ if (entitlementKey !== BOTS_MAX_ENTITLEMENT_KEY) {
+ await write;
+ return { deactivatedBotIds: [] };
+ }
+ const botsMax = NonNegativeIntegerEntitlementSchema.safeParse(parsedValue);
+ if (!botsMax.success) {
+ throw new ProductEntitlementUnavailableError(entitlementKey, "entitlement_malformed");
+ }
+ const reconcile = reconcilePlanActiveBotsBuilder(db, planId, botsMax.data);
+ const results = await db.batch([write, reconcile] as any) as unknown as [unknown, Array<{ botId: string }>];
+ return { deactivatedBotIds: results[1].map((row) => row.botId) };
+}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 874726977..48b7ee506 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -110,7 +110,7 @@ export {
devWsDoPort,
MeetingStatus,
TERMINAL_MEETING_STATUSES,
- COMMUNITY_BOT_LIMIT_PER_OWNER,
+ COMMUNITY_BOT_REQUEST_MAX_ITEMS,
COMMUNITY_BOT_NAME_MIN,
COMMUNITY_BOT_NAME_MAX,
COMMUNITY_BOT_DESCRIPTION_MAX,
@@ -188,6 +188,8 @@ export {
} from "./constants/community";
export type { NotifLevel, NotificationLevelValue, ParticipantSource, MentionKind } from "./constants/community";
export * from "./provider-telemetry";
+export * from "./product-entitlements";
+export * from "./billing";
export type {
AgentStatusType,
diff --git a/src/shared/src/product-entitlements.ts b/src/shared/src/product-entitlements.ts
new file mode 100644
index 000000000..255cb0b84
--- /dev/null
+++ b/src/shared/src/product-entitlements.ts
@@ -0,0 +1,55 @@
+import { z } from "zod";
+
+export type EntitlementValue =
+ | null
+ | boolean
+ | number
+ | string
+ | EntitlementValue[]
+ | { [key: string]: EntitlementValue };
+
+export const EntitlementValueSchema: z.ZodType<EntitlementValue> = z.lazy(() =>
+ z.union([
+ z.null(),
+ z.boolean(),
+ z.number().finite(),
+ z.string(),
+ z.array(EntitlementValueSchema),
+ z.record(z.string(), EntitlementValueSchema),
+ ]),
+);
+
+export const NonNegativeIntegerEntitlementSchema = z.number().int().nonnegative();
+
+export const BOTS_MAX_ENTITLEMENT_KEY = "bots.max";
+export const MACHINES_MAX_ENTITLEMENT_KEY = "machines.max";
+
+export const CommunityBotActivationRequestSchema = z.strictObject({
+ active: z.boolean(),
+});
+
+export type CommunityBotActivationRequest = z.infer<
+ typeof CommunityBotActivationRequestSchema
+>;
+
+export type ResolvedProductPlan = {
+ id: string;
+ displayName: string;
+};
+
+export type BotCapacitySummary = {
+ isFounder: boolean;
+ plan: ResolvedProductPlan;
+ limit: number;
+ ownedCount: number;
+ activeCount: number;
+};
+
+
+export type MachineCapacitySummary = {
+ isFounder: boolean;
+ plan: ResolvedProductPlan;
+ limit: number;
+ ownedCount: number;
+ onlineCount: number;
+};
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 1c7ff2c46..a80da4c88 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1159,7 +1159,7 @@ export type CommunityDaemonEnrollAgentResponse = z.infer<typeof CommunityDaemonE
// ---------------------------------------------------------------------------
import {
- COMMUNITY_BOT_LIMIT_PER_OWNER,
+ COMMUNITY_BOT_REQUEST_MAX_ITEMS,
COMMUNITY_BOT_NAME_MIN,
COMMUNITY_BOT_NAME_MAX,
COMMUNITY_BOT_DESCRIPTION_MAX,
@@ -1260,7 +1260,7 @@ export const CommunityServerOnboardRequestSchema = z.strictObject({
.refine((value) => value.trim().length > 0, "wakePrompt is required"),
}))
.min(1)
- .max(COMMUNITY_BOT_LIMIT_PER_OWNER)
+ .max(COMMUNITY_BOT_REQUEST_MAX_ITEMS)
.refine((bots) => new Set(bots.map((bot) => bot.id)).size === bots.length, "bot ids must be unique"),
leadBotId: z.string().min(1).max(128),
action: z.discriminatedUnion("type", [
diff --git a/src/shared/test/queries/billing.test.ts b/src/shared/test/queries/billing.test.ts
new file mode 100644
index 000000000..3edf94cf8
--- /dev/null
+++ b/src/shared/test/queries/billing.test.ts
@@ -0,0 +1,203 @@
+import { beforeEach, afterEach, describe, expect, it } from "vitest";
+import { createMachinePlanTables } from "./machine-plan-fixture";
+import Sqlite from "better-sqlite3";
+import { getTableConfig } from "drizzle-orm/sqlite-core";
+import { userBilling, billingPrice } from "../../src/db/billing-schema";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { readFileSync } from "node:fs";
+import type { Database } from "../../src/db";
+import * as billing from "../../src/db/queries/billing";
+import { assignUserPlan, getBotCapacitySummary } from "../../src/db/queries/product-plan";
+
+type Statement = { toSQL(): { sql: string }; all(): unknown[]; run(): unknown };
+let sqlite: Sqlite.Database;
+let db: Database;
+
+beforeEach(() => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.pragma("foreign_keys=ON");
+ sqlite.exec(`
+ CREATE TABLE user(id TEXT PRIMARY KEY, isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT, createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, deletedAt TEXT);
+ CREATE TABLE community_bot_binding(user_id TEXT PRIMARY KEY REFERENCES user(id), machine_id TEXT);
+ INSERT INTO user(id) VALUES ('founder');
+ `);
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0098_product_plan_bot_active.sql", import.meta.url), "utf8"));
+ sqlite.exec("INSERT INTO user(id) VALUES('new-user')");
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0099_billing_founder.sql", import.meta.url), "utf8"));
+ createMachinePlanTables(sqlite);
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0101_machine_plan_limits.sql", import.meta.url), "utf8"));
+ db = drizzle(sqlite) as unknown as Database;
+ db.batch = (async (statements: Statement[]) => sqlite.transaction(() => statements.map((s) =>
+ /^select\b|\breturning\b/i.test(s.toSQL().sql.trim()) ? s.all() : s.run(),
+ ))()) as Database["batch"];
+});
+afterEach(() => sqlite.close());
+
+const snapshot = {
+ plan: { id: "house", displayName: "House" }, status: "active",
+ currentPeriodEnd: null, cancelAt: null, scheduledChange: null,
+};
+
+async function ownerWithBots() {
+ await assignUserPlan(db, "new-user", "house");
+ for (let i = 0; i < 5; i++) {
+ sqlite.prepare("INSERT INTO user(id,isBot,ownerUserId,createdAt) VALUES(?,1,'new-user',?)").run(`bot${i}`, `2026-01-0${i+1}`);
+ sqlite.prepare("INSERT INTO community_bot_binding(user_id,machine_id) VALUES(?,'m')").run(`bot${i}`);
+ }
+ return (await billing.ensureBilling(db, "new-user"))!;
+}
+
+describe("billing transactional boundaries", () => {
+ async function founderAttempt() {
+ const row = (await billing.ensureBilling(db, "founder", true))!;
+ return (await billing.updateBilling(db, row, { customerId: "cus-founder", checkoutAttempt: {
+ id: "confirmed", priceId: "studio-price", email: "[email protected]", origin: "http://localhost:3000",
+ startedAt: 1, sessionId: "cs-founder", founderAcknowledged: true,
+ } }, true))!;
+ }
+
+ it("requires explicit consent for Founder billing reservation", async () => {
+ expect(await billing.ensureBilling(db, "founder")).toBeNull();
+ const row = await founderAttempt();
+ expect(row.checkoutAttempt?.founderAcknowledged).toBe(true);
+ expect(await getBotCapacitySummary(db, "founder")).toMatchObject({ isFounder: true, limit: 40 });
+ });
+
+ it("converts a confirmed Founder atomically and never restores Founder after cancellation", async () => {
+ sqlite.exec("INSERT INTO billing_price(price_id,plan_id) VALUES('studio-price','studio')");
+ const row = await founderAttempt();
+ for (let i = 0; i < 12; i++) {
+ sqlite.prepare("INSERT INTO user(id,isBot,ownerUserId,createdAt) VALUES(?,1,'founder',?)").run(`fbot${i}`, `2026-01-${String(i+1).padStart(2,'0')}`);
+ sqlite.prepare("INSERT INTO community_bot_binding(user_id,machine_id) VALUES(?,'m')").run(`fbot${i}`);
+ }
+ const patch = { subscriptionId: "sub-founder", subscription: { ...snapshot, plan: { id: "studio", displayName: "Studio" } }, checkoutAttempt: null };
+ expect(await billing.applyBillingPlan(db, row, patch, "studio")).toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ expect(await billing.applyBillingPlan(db, row, patch, "house", "confirmed")).toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ expect(await billing.applyBillingPlan(db, row, patch, "studio", "wrong")).toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ expect(await billing.applyBillingPlan(db, row, patch, "studio", "confirmed")).toEqual({ applied: true, deactivatedBotIds: ["fbot10", "fbot11"], disconnectedMachines: [] });
+ expect(await getBotCapacitySummary(db, "founder")).toMatchObject({ isFounder: false, plan: { id: "studio" }, ownedCount: 12, activeCount: 10 });
+ expect(await billing.applyBillingPlan(db, row, patch, "studio", "confirmed")).toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ const current = (await billing.getBilling(db, "founder"))!;
+ await billing.applyBillingPlan(db, current, { subscription: null }, "free");
+ expect(await getBotCapacitySummary(db, "founder")).toMatchObject({ isFounder: false, plan: { id: "free" }, ownedCount: 12, activeCount: 3 });
+ });
+
+ it("rolls back Founder removal if any later conversion statement fails", async () => {
+ sqlite.exec("INSERT INTO billing_price(price_id,plan_id) VALUES('studio-price','studio')");
+ const row = await founderAttempt();
+ sqlite.exec("CREATE TRIGGER fail_founder_plan BEFORE UPDATE OF plan_id ON user_product_plan BEGIN SELECT RAISE(ABORT,'injected'); END");
+ await expect(billing.applyBillingPlan(db, row, { subscriptionId: "sub-founder", subscription: snapshot, checkoutAttempt: null }, "studio", "confirmed")).rejects.toThrow("injected");
+ expect(await getBotCapacitySummary(db, "founder")).toMatchObject({ isFounder: true, plan: { id: "house" } });
+ expect(await billing.getBilling(db, "founder")).toMatchObject({ revision: row.revision, checkoutAttempt: { id: "confirmed" } });
+ });
+
+ it("reads public Free allowance from the active default entitlement without writes", async () => {
+ const before = sqlite.prepare("SELECT total_changes() AS changes").get();
+ expect(await billing.getDefaultPlanOffer(db)).toEqual({ plan: { id: "free", displayName: "Free" }, botLimit: 3, machineLimit: 1 });
+ expect(sqlite.prepare("SELECT total_changes() AS changes").get()).toEqual(before);
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='7' WHERE plan_id='free' AND entitlement_key='bots.max'");
+ expect(await billing.getDefaultPlanOffer(db)).toMatchObject({ botLimit: 7 });
+ sqlite.exec("UPDATE product_plan SET is_active=0 WHERE id='free'");
+ await expect(billing.getDefaultPlanOffer(db)).rejects.toThrow("DEFAULT_PLAN_UNAVAILABLE");
+ });
+
+ it("backfills only prior House human assignments and keeps later humans Free", async () => {
+ expect(await getBotCapacitySummary(db, "founder")).toMatchObject({ isFounder: true, plan: { id: "house" }, limit: 40 });
+ expect(await getBotCapacitySummary(db, "new-user")).toMatchObject({ isFounder: false, plan: { id: "free" }, limit: 3 });
+ expect(await billing.ensureBilling(db, "founder")).toBeNull();
+ });
+
+ it("updates the billing projection, assignment and deterministic overflow atomically", async () => {
+ const row = await ownerWithBots();
+ expect(await billing.applyBillingPlan(db, row, { subscriptionId: "sub1", subscription: snapshot }, "free"))
+ .toEqual({ applied: true, deactivatedBotIds: ["bot3", "bot4"], disconnectedMachines: [] });
+ expect(await getBotCapacitySummary(db, "new-user")).toMatchObject({ plan: { id: "free" }, ownedCount: 5, activeCount: 3 });
+ expect(await billing.getBilling(db, "new-user")).toMatchObject({ revision: 1, subscriptionId: "sub1" });
+ });
+
+ it("a stale snapshot loses every statement, including overflow", async () => {
+ const old = await ownerWithBots();
+ await billing.applyBillingPlan(db, old, { subscriptionId: "new-sub", subscription: snapshot }, "house");
+ expect(await billing.applyBillingPlan(db, old, { subscriptionId: "old-sub" }, "free"))
+ .toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ expect(await getBotCapacitySummary(db, "new-user")).toMatchObject({ plan: { id: "house" }, activeCount: 5 });
+ expect(await billing.getBilling(db, "new-user")).toMatchObject({ revision: 1, subscriptionId: "new-sub" });
+ });
+
+ it("rolls projection and assignment back when a trailing write fails", async () => {
+ const row = await ownerWithBots();
+ sqlite.exec("CREATE TRIGGER fail_deactivation BEFORE UPDATE OF is_active ON community_bot_binding BEGIN SELECT RAISE(ABORT,'injected'); END;");
+ await expect(billing.applyBillingPlan(db, row, { subscriptionId: "sub1" }, "free")).rejects.toThrow("injected");
+ expect(await billing.getBilling(db, "new-user")).toMatchObject({ revision: 0, subscriptionId: null });
+ expect(await getBotCapacitySummary(db, "new-user")).toMatchObject({ plan: { id: "house" }, activeCount: 5 });
+ });
+
+ it("guards a concurrent Founder transition at batch execution", async () => {
+ const row = await ownerWithBots();
+ sqlite.exec("UPDATE user_product_plan SET is_founder=1 WHERE user_id='new-user'");
+ expect(await billing.applyBillingPlan(db, row, { subscriptionId: "sub1" }, "free"))
+ .toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ await expect(assignUserPlan(db, "new-user", "free")).rejects.toThrow("PLAN_ASSIGNMENT_PROTECTED");
+ expect(await getBotCapacitySummary(db, "new-user")).toMatchObject({ isFounder: true, activeCount: 5 });
+ expect(await billing.updateBilling(db, row, { customerId: "cus-blocked" })).toBeNull();
+ });
+
+ it("does not apply a billing snapshot after its owner is deleted", async () => {
+ const row = await ownerWithBots();
+ sqlite.exec("UPDATE user SET deletedAt='2026-09-10' WHERE id='new-user'");
+ expect(await billing.applyBillingPlan(db, row, { subscriptionId: "sub1" }, "free"))
+ .toEqual({ applied: false, deactivatedBotIds: [], disconnectedMachines: [] });
+ expect(await billing.getBilling(db, "new-user")).toMatchObject({ revision: 0 });
+ });
+
+ it("reserves only one owner attempt and enforces unique customer mapping", async () => {
+ const row = (await billing.ensureBilling(db, "new-user"))!;
+ const attempt = { id: "attempt1", priceId: "price1", email: "[email protected]", origin: "http://localhost:3000", startedAt: 1, sessionId: null };
+ expect(await billing.updateBilling(db, row, { customerId: "cus1", checkoutAttempt: attempt })).toMatchObject({ revision: 1, checkoutAttempt: attempt });
+ expect(await billing.updateBilling(db, row, { checkoutAttempt: { ...attempt, id: "attempt2" } })).toBeNull();
+ sqlite.exec("INSERT INTO user(id) VALUES('other')");
+ const other = (await billing.ensureBilling(db, "other"))!;
+ await expect(billing.updateBilling(db, other, { customerId: "cus1" })).rejects.toThrow();
+ expect((await billing.getBillingByCustomer(db, "cus1"))?.userId).toBe("new-user");
+ });
+});
+
+describe("billing catalog persistence", () => {
+ it("filters sales catalog while retaining disabled mappings for reconciliation", async () => {
+ sqlite.exec("INSERT INTO billing_price(price_id,plan_id,enabled) VALUES('studio-on','studio',1),('house-off','house',0),('free-price','free',1)");
+ expect((await billing.listPrices(db)).map((p) => p.priceId)).toEqual(["studio-on"]);
+ expect((await billing.listPrices(db, true)).map((p) => p.priceId)).toEqual(["studio-on", "house-off"]);
+ sqlite.exec("UPDATE product_plan SET is_active=0 WHERE id='studio'");
+ expect(await billing.listPrices(db)).toEqual([]);
+ expect((await billing.listPrices(db, true)).map((p) => p.priceId)).toEqual(["house-off"]);
+ });
+
+ it("requires an active default plan for billing fallback", async () => {
+ expect(await billing.getDefaultPlan(db)).toEqual({ id: "free", displayName: "Free" });
+ sqlite.exec("UPDATE product_plan SET is_active=0 WHERE id='free'");
+ await expect(billing.getDefaultPlan(db)).rejects.toThrow("DEFAULT_PLAN_UNAVAILABLE");
+ });
+
+ it("rejects unavailable target allowances without changing billing state", async () => {
+ const row = (await billing.ensureBilling(db, "new-user"))!;
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='-1' WHERE plan_id='studio' AND entitlement_key='bots.max'");
+ await expect(billing.applyBillingPlan(db, row, { subscriptionId: "sub" }, "studio")).rejects.toThrow("BILLING_PLAN_UNAVAILABLE");
+ expect(await billing.getBilling(db, "new-user")).toEqual(row);
+ });
+
+ it("declares required foreign keys and unique Stripe identities, with a generated update timestamp", async () => {
+ const prices = getTableConfig(billingPrice);
+ const billingTable = getTableConfig(userBilling);
+ expect(prices.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, target: key.reference().foreignColumns[0].name, onDelete: key.onDelete })))
+ .toEqual([{ column: "plan_id", target: "id", onDelete: "restrict" }]);
+ expect(billingTable.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, onDelete: key.onDelete })))
+ .toEqual([{ column: "user_id", onDelete: "cascade" }]);
+ expect(billingTable.indexes.map((index) => ({ name: index.config.name, unique: index.config.unique })))
+ .toEqual([{ name: "uq_user_billing_customer", unique: true }, { name: "uq_user_billing_subscription", unique: true }]);
+ const inserted = await db.insert(userBilling).values({ userId: "new-user" }).returning();
+ expect(inserted[0]).toMatchObject({ userId: "new-user", revision: 0, customerId: null, subscriptionId: null });
+ expect(Number.isFinite(Date.parse(inserted[0].updatedAt))).toBe(true);
+ await expect(db.insert(billingPrice).values({ priceId: "bad", planId: "missing" })).rejects.toThrow();
+ });
+});
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index 8c976fdb0..b1b958963 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -5,7 +5,7 @@ import Sqlite from "better-sqlite3"
import * as q from "../../src/db/queries/community/bot"
import {
communityBotSyntheticEmail,
- COMMUNITY_BOT_LIMIT_PER_OWNER,
+ COMMUNITY_BOT_REQUEST_MAX_ITEMS,
COMMUNITY_BOT_NAME_MAX,
} from "../../src/constants"
import { computeDiscriminator } from "../../src/lib/discriminator"
@@ -183,6 +183,7 @@ describe("bot runtime-config read projections", () => {
modelName: "gpt-5",
reasoningEffort: "high",
runtimeConfigRevision: 7,
+ isActive: true,
}
function makeOwnerListChain(rows: unknown[]) {
@@ -199,20 +200,29 @@ describe("bot runtime-config read projections", () => {
chain.select = vi.fn(() => chain)
chain.from = vi.fn(() => chain)
chain.leftJoin = vi.fn(() => chain)
+ chain.innerJoin = vi.fn(() => chain)
chain.where = vi.fn(() => chain)
chain.limit = vi.fn(() => Promise.resolve(rows))
return chain
}
it("returns reasoning effort and revision when listing an owner's bots", async () => {
- await expect(q.listBotsForOwner(makeOwnerListChain([storedBot]), "owner_1")).resolves.toEqual([
- { ...storedBot, tokenUsageTimeZone: null },
+ await expect(q.listBotsForOwner(makeOwnerListChain([{ ...storedBot, machineStatus: "online" }]), "owner_1")).resolves.toEqual([
+ { ...storedBot, presence: "online", tokenUsageTimeZone: null },
+ ])
+ })
+
+ it("projects inactive bots offline even while their bound machine is online", async () => {
+ await expect(q.listBotsForOwner(makeOwnerListChain([
+ { ...storedBot, isActive: false, machineStatus: "online" },
+ ]), "owner_1")).resolves.toEqual([
+ { ...storedBot, isActive: false, presence: "offline", tokenUsageTimeZone: null },
])
})
it("returns reasoning effort and revision from the owner-scoped lookup", async () => {
await expect(q.getBotOwnedBy(makeLimitedReadChain([storedBot]), "bot_1", "owner_1")).resolves.toEqual(
- storedBot,
+ { ...storedBot, avatarObjectKey: undefined },
)
})
@@ -231,6 +241,22 @@ describe("bot runtime-config read projections", () => {
ownerUserId: "owner_1",
})
})
+
+ it("returns the owner binding state and stops wake resolution for an inactive bot", async () => {
+ const inactive = { ...storedBot, isBot: true, deletedAt: null, isActive: false }
+
+ await expect(q.getBotBindingWithOwner(makeLimitedReadChain([inactive]), "bot_1"))
+ .resolves.toEqual({
+ machineId: "machine_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "helper",
+ discriminator: "1234",
+ isActive: false,
+ })
+ await expect(q.getBotWakeContext(makeLimitedReadChain([inactive]), "bot_1"))
+ .resolves.toEqual({ state: "bot_inactive" })
+ })
})
describe("getBotBinding", () => {
@@ -244,7 +270,7 @@ describe("getBotBinding", () => {
}
it("returns the full runtime binding when it exists", async () => {
- const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex", modelName: null }])
+ const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex", modelName: null, isActive: true }])
const result = await q.getBotBinding(chain, "bot_1")
expect(result).toEqual({
machineId: "machine_1",
@@ -252,11 +278,12 @@ describe("getBotBinding", () => {
modelName: null,
reasoningEffort: null,
runtimeConfigRevision: 0,
+ isActive: true,
})
})
it("surfaces a stored modelName", async () => {
- const chain = makeSelectChain([{ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6" }])
+ const chain = makeSelectChain([{ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6", isActive: false }])
const result = await q.getBotBinding(chain, "bot_1")
expect(result).toEqual({
machineId: "machine_1",
@@ -264,6 +291,7 @@ describe("getBotBinding", () => {
modelName: "claude-opus-4-6",
reasoningEffort: null,
runtimeConfigRevision: 0,
+ isActive: false,
})
})
@@ -482,8 +510,8 @@ describe("listBotsForMachine", () => {
})
describe("bot limits", () => {
- it("cap is 20", () => {
- expect(COMMUNITY_BOT_LIMIT_PER_OWNER).toBe(20)
+ it("keeps the request payload safety bound above the largest seeded entitlement", () => {
+ expect(COMMUNITY_BOT_REQUEST_MAX_ITEMS).toBe(100)
})
it("name max is 32", () => {
expect(COMMUNITY_BOT_NAME_MAX).toBe(32)
diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.ts
index cb0d304db..8770ea44c 100644
--- a/src/shared/test/queries/community-machine.test.ts
+++ b/src/shared/test/queries/community-machine.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi } from "vitest";
+vi.mock("../../src/db/queries/product-plan", async (original) => ({ ...await original<typeof import("../../src/db/queries/product-plan")>(), assertMachineCapacity: vi.fn() }));
import * as q from "../../src/db/queries/community/machine";
import * as sessionEpoch from "../../src/db/queries/community/machine-session-epoch";
@@ -922,7 +923,7 @@ describe("session epoch rotation — success paths", () => {
});
chain.from = vi.fn(() => chain);
chain.where = vi.fn(() => {
- if (mode === "select" && selectCount === 3) {
+ if (mode === "select" && selectCount === 4) {
return Promise.resolve([{ doName: "old-do" }]);
}
return chain;
@@ -1009,7 +1010,7 @@ describe("session epoch rotation — success paths", () => {
});
chain.from = vi.fn(() => chain);
chain.where = vi.fn(() => {
- if (mode === "select" && selectCount === 3) return Promise.resolve([]);
+ if (mode === "select" && selectCount === 4) return Promise.resolve([]);
return chain;
});
chain.limit = vi.fn(() => Promise.resolve(
diff --git a/src/shared/test/queries/machine-plan-fixture.ts b/src/shared/test/queries/machine-plan-fixture.ts
new file mode 100644
index 000000000..31058d1ed
--- /dev/null
+++ b/src/shared/test/queries/machine-plan-fixture.ts
@@ -0,0 +1,22 @@
+import type Sqlite from "better-sqlite3";
+
+export function createMachinePlanTables(sqlite: Sqlite.Database) {
+ sqlite.exec(`
+ CREATE TABLE IF NOT EXISTS community_machine (
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL, display_name TEXT NOT NULL DEFAULT '',
+ hostname TEXT NOT NULL DEFAULT '', platform TEXT NOT NULL DEFAULT '', arch TEXT NOT NULL DEFAULT '',
+ os_release TEXT NOT NULL DEFAULT '', daemon_version TEXT NOT NULL DEFAULT '', time_zone TEXT,
+ metadata TEXT, available_runtimes TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL DEFAULT 'offline',
+ last_seen_at TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS test_machine_owner ON community_machine(user_id);
+ CREATE TABLE IF NOT EXISTS community_machine_credential (
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL, machine_id TEXT NOT NULL, credential_hash TEXT NOT NULL UNIQUE,
+ do_name TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, last_used_at TEXT, revoked_at TEXT
+ );
+ CREATE TABLE IF NOT EXISTS community_agent_runner_key (
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL, machine_id TEXT NOT NULL, agent_id TEXT NOT NULL,
+ runner_key_hash TEXT NOT NULL UNIQUE, do_name TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, revoked_at TEXT
+ );
+ `);
+}
diff --git a/src/shared/test/queries/machine-plan-limits.integration.test.ts b/src/shared/test/queries/machine-plan-limits.integration.test.ts
new file mode 100644
index 000000000..8beb93397
--- /dev/null
+++ b/src/shared/test/queries/machine-plan-limits.integration.test.ts
@@ -0,0 +1,182 @@
+import { readFileSync } from "node:fs";
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { Database } from "../../src/db";
+import * as plans from "../../src/db/queries/product-plan";
+import * as billing from "../../src/db/queries/billing";
+import { createPairingToken, createReconnectPairingToken, hashCredential } from "../../src/db/queries/community/machine";
+import { transitionMachineSessionEpoch } from "../../src/db/queries/community/machine-session-epoch";
+import { createMachinePlanTables } from "./machine-plan-fixture";
+
+let sqlite: Sqlite.Database;
+let db: Database;
+beforeEach(() => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.exec(`CREATE TABLE user(id TEXT PRIMARY KEY, isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT, createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, deletedAt TEXT);
+ CREATE TABLE community_bot_binding(user_id TEXT PRIMARY KEY, machine_id TEXT);
+ CREATE TABLE community_machine_token(id TEXT PRIMARY KEY, user_id TEXT NOT NULL, machine_id TEXT, status TEXT NOT NULL DEFAULT 'pending', expires_at TEXT NOT NULL, created_at TEXT NOT NULL, last_used_at TEXT);
+ CREATE UNIQUE INDEX one_pending_token_per_owner ON community_machine_token(user_id) WHERE status='pending';`);
+ createMachinePlanTables(sqlite);
+ for (const migration of ["0098_product_plan_bot_active", "0099_billing_founder", "0101_machine_plan_limits"]) {
+ sqlite.exec(readFileSync(new URL(`../../../web/migrations/${migration}.sql`, import.meta.url), "utf8"));
+ }
+ sqlite.exec("INSERT INTO user(id) VALUES('owner'),('other')");
+ db = drizzle(sqlite) as unknown as Database;
+ db.batch = (async (statements: Array<{ toSQL(): { sql: string; params: unknown[] }; all(): unknown[]; run(): unknown }>) =>
+ sqlite.transaction(() => statements.map((s) => {
+ const query = s.toSQL();
+ const prepared = sqlite.prepare(query.sql);
+ return prepared.reader ? s.all() : s.run();
+ }))()) as Database["batch"];
+});
+afterEach(() => sqlite.close());
+
+function machine(id: string, status = "offline", owner = "owner", createdAt = id) {
+ sqlite.prepare("INSERT INTO community_machine(id,user_id,status,created_at) VALUES(?,?,?,?)").run(id, owner, status, createdAt);
+ sqlite.prepare("INSERT INTO community_machine_credential(id,user_id,machine_id,credential_hash,do_name) VALUES(?,?,?,?,?)")
+ .run(`cred-${id}`, owner, id, `hash-${id}`, `do-${id}`);
+ sqlite.prepare("INSERT INTO community_agent_runner_key(id,user_id,machine_id,agent_id,runner_key_hash,do_name) VALUES(?,?,?,?,?,?)")
+ .run(`key-${id}`, owner, id, `bot-${id}`, `keyhash-${id}`, `runner-${id}`);
+}
+function token(id: string, machineId: string | null = null, owner = "owner") {
+ sqlite.prepare("INSERT INTO community_machine_token(id,user_id,machine_id,expires_at,created_at) VALUES(?,?,?,'9999-01-01','2026-01-01')").run(id, owner, machineId);
+}
+function ready(id: string, type: "ready" | "renew" = "ready") {
+ return transitionMachineSessionEpoch(db, { type, epoch: { userId: "owner", machineId: id, credentialHash: `hash-${id}` }, metadata: { hostname: id } });
+}
+function rotate(id: string, expectedMachineId?: string) {
+ return transitionMachineSessionEpoch(db, { type: "rotate", tokenId: id, expectedMachineId, metadata: { hostname: "test-host" } });
+}
+
+describe("machine plan SQL boundaries", () => {
+ it("restores the pairing token and preserves a non-quota machine insert error", async () => {
+ token("pending");
+ sqlite.exec("CREATE TRIGGER fail_machine_insert BEFORE INSERT ON community_machine BEGIN SELECT RAISE(ABORT,'machine storage failure'); END");
+ await expect(rotate("pending")).rejects.toThrow("machine storage failure");
+ expect(sqlite.prepare("SELECT status FROM community_machine_token WHERE id='pending'").get()).toEqual({ status: "pending" });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine").get()).toEqual({ n: 0 });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine_credential").get()).toEqual({ n: 0 });
+ sqlite.exec("DROP TRIGGER fail_machine_insert");
+ await expect(rotate("pending")).resolves.toMatchObject({ type: "rotated" });
+ });
+
+ it("resolves Free/Studio/House and counts offline ownership without writes or owner leakage", async () => {
+ machine("a"); machine("other-a", "online", "other");
+ const before = sqlite.prepare("SELECT total_changes() AS n").get();
+ expect(await plans.getMachineCapacitySummary(db, "owner")).toMatchObject({ limit: 1, ownedCount: 1, onlineCount: 0, isFounder: false });
+ expect(sqlite.prepare("SELECT total_changes() AS n").get()).toEqual(before);
+ await plans.assignUserPlan(db, "owner", "studio");
+ expect(await plans.getMachineCapacitySummary(db, "owner")).toMatchObject({ limit: 5 });
+ await plans.assignUserPlan(db, "owner", "house");
+ sqlite.exec("UPDATE user_product_plan SET is_founder=1 WHERE user_id='owner'");
+ expect(await plans.getMachineCapacitySummary(db, "owner")).toMatchObject({ limit: 10, isFounder: true });
+ });
+
+ it("rejects pair and preissued activation at owned cap without consuming the pending token", async () => {
+ token("pending"); machine("a");
+ await expect(createPairingToken(db, "owner")).rejects.toBeInstanceOf(plans.MachineLimitReachedError);
+ await expect(rotate("pending")).rejects.toBeInstanceOf(plans.MachineLimitReachedError);
+ expect(sqlite.prepare("SELECT status FROM community_machine_token").get()).toEqual({ status: "pending" });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine_credential").get()).toEqual({ n: 1 });
+ sqlite.exec("DELETE FROM community_machine WHERE id='a'");
+ await expect(createPairingToken(db, "owner")).resolves.toBeDefined();
+ });
+
+ it("atomically admits only one of two preissued activations into the last owned slot", async () => {
+ token("left");
+ const first = rotate("left");
+ while ((sqlite.prepare("SELECT status FROM community_machine_token WHERE id='left'").get() as { status: string }).status === "pending") await Promise.resolve();
+ token("right");
+ const results = await Promise.allSettled([first, rotate("right")]);
+ expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
+ const rejected = results.find((r) => r.status === "rejected") as PromiseRejectedResult;
+ expect(rejected.reason).toBeInstanceOf(plans.MachineLimitReachedError);
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine WHERE user_id='owner'").get()).toEqual({ n: 1 });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine_credential").get()).toEqual({ n: 1 });
+ expect(sqlite.prepare("SELECT status,count(*) AS n FROM community_machine_token GROUP BY status ORDER BY status").all())
+ .toEqual([{ status: "pending", n: 1 }, { status: "revoked", n: 1 }]);
+ });
+
+ it("reconnects the same machine at owned cap, but rejects an offline reconnect at online cap", async () => {
+ await plans.assignUserPlan(db, "owner", "house"); machine("a", "online"); machine("b");
+ await plans.assignUserPlan(db, "owner", "free");
+ await expect(createReconnectPairingToken(db, "owner", "b")).rejects.toBeInstanceOf(plans.MachineLimitReachedError);
+ token("b-reconnect", "b");
+ await expect(rotate("b-reconnect", "b")).rejects.toBeInstanceOf(plans.MachineLimitReachedError);
+ expect(sqlite.prepare("SELECT status FROM community_machine_token WHERE id='b-reconnect'").get()).toEqual({ status: "pending" });
+ expect(sqlite.prepare("SELECT revoked_at FROM community_machine_credential WHERE machine_id='b'").get()).toEqual({ revoked_at: null });
+ await expect(createReconnectPairingToken(db, "owner", "a")).resolves.toBeDefined();
+ const pending = sqlite.prepare("SELECT id FROM community_machine_token WHERE machine_id='a'").get() as { id: string };
+ expect(await rotate(pending.id, "a")).toMatchObject({ machineId: "a" });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine").get()).toEqual({ n: 2 });
+ });
+
+ it("serializes ready/renew admission and still permits the admitted machine heartbeat", async () => {
+ await plans.assignUserPlan(db, "owner", "house"); machine("a"); machine("b");
+ await plans.assignUserPlan(db, "owner", "free");
+ const results = await Promise.all([ready("a"), ready("b", "renew")]);
+ expect(results.map((r) => r.type).sort()).toEqual(["stale_epoch", "transitioned"]);
+ expect(await ready("a", "renew")).toMatchObject({ type: "transitioned" });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine WHERE status='online'").get()).toEqual({ n: 1 });
+ });
+
+ it("retains oldest machines with stable ID ties, preserving machines/bindings while revoking overflow epochs", async () => {
+ await plans.assignUserPlan(db, "owner", "house");
+ machine("b", "online", "owner", "same"); machine("a", "online", "owner", "same"); machine("c", "online", "owner", "z");
+ sqlite.exec("INSERT INTO user(id,isBot,ownerUserId) VALUES('bot',1,'owner'); INSERT INTO community_bot_binding(user_id,machine_id) VALUES('bot','b')");
+ const row = (await billing.ensureBilling(db, "owner"))!;
+ const result = await billing.applyBillingPlan(db, row, { subscriptionId: "sub" }, "free");
+ expect(result.disconnectedMachines).toEqual([{ machineId: "b", userId: "owner", doName: "do-b" }, { machineId: "c", userId: "owner", doName: "do-c" }]);
+ expect(sqlite.prepare("SELECT id,status FROM community_machine ORDER BY id").all()).toEqual([{ id: "a", status: "online" }, { id: "b", status: "offline" }, { id: "c", status: "offline" }]);
+ expect(sqlite.prepare("SELECT machine_id,is_active FROM community_bot_binding").get()).toEqual({ machine_id: "b", is_active: 1 });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_machine_credential WHERE revoked_at IS NOT NULL").get()).toEqual({ n: 2 });
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_agent_runner_key WHERE revoked_at IS NOT NULL").get()).toEqual({ n: 2 });
+ expect(await ready("b")).toEqual({ type: "stale_epoch" });
+ expect(await billing.applyBillingPlan(db, row, { subscriptionId: "stale" }, "free")).toMatchObject({ applied: false, disconnectedMachines: [] });
+ });
+
+ it("stale billing replay preserves a manually reconnected newer epoch", async () => {
+ await plans.assignUserPlan(db, "owner", "house"); machine("a", "online"); machine("b", "online");
+ const row = (await billing.ensureBilling(db, "owner"))!;
+ await billing.applyBillingPlan(db, row, {}, "free");
+ await transitionMachineSessionEpoch(db, { type: "close", epoch: { userId: "owner", machineId: "a", credentialHash: "hash-a" } });
+ const pairing = await createReconnectPairingToken(db, "owner", "b");
+ const rotated = await rotate(pairing.tokenId, "b");
+ const hash = await hashCredential(rotated.credential);
+ await transitionMachineSessionEpoch(db, { type: "ready", epoch: { userId: "owner", machineId: "b", credentialHash: hash }, metadata: { hostname: "fresh" } });
+ expect(await billing.applyBillingPlan(db, row, {}, "free")).toMatchObject({ applied: false, disconnectedMachines: [] });
+ expect(sqlite.prepare("SELECT status FROM community_machine WHERE id='b'").get()).toEqual({ status: "online" });
+ expect(sqlite.prepare("SELECT revoked_at FROM community_machine_credential WHERE credential_hash=?").get(hash)).toEqual({ revoked_at: null });
+ });
+
+ it("changing a default machine allowance reconciles unassigned owners but not another plan", async () => {
+ await plans.setPlanEntitlement(db, "free", "machines.max", 2);
+ machine("a", "online"); machine("b", "online");
+ await plans.assignUserPlan(db, "other", "studio"); machine("other-a", "online", "other"); machine("other-b", "online", "other");
+ expect(await plans.setPlanEntitlement(db, "free", "machines.max", 1)).toMatchObject({ disconnectedMachines: [{ machineId: "b" }] });
+ expect(await plans.getMachineCapacitySummary(db, "other")).toMatchObject({ onlineCount: 2, limit: 5 });
+ await expect(plans.setPlanEntitlement(db, "free", "machines.max", "invalid")).rejects.toBeInstanceOf(plans.ProductEntitlementUnavailableError);
+ expect(await plans.getMachineCapacitySummary(db, "owner")).toMatchObject({ limit: 1 });
+ });
+
+ it("rolls back billing, assignment, credential and runner writes when offline projection fails", async () => {
+ await plans.assignUserPlan(db, "owner", "house"); machine("a", "online"); machine("b", "online");
+ const row = (await billing.ensureBilling(db, "owner"))!;
+ sqlite.exec("CREATE TRIGGER fail_offline BEFORE UPDATE OF status ON community_machine BEGIN SELECT RAISE(ABORT,'offline failure'); END");
+ await expect(billing.applyBillingPlan(db, row, {}, "free")).rejects.toThrow("offline failure");
+ expect(await plans.getMachineCapacitySummary(db, "owner")).toMatchObject({ limit: 10, onlineCount: 2 });
+ expect((await billing.getBilling(db, "owner"))!.revision).toBe(row.revision);
+ for (const table of ["community_machine_credential", "community_agent_runner_key"]) {
+ expect(sqlite.prepare(`SELECT count(*) AS n FROM ${table} WHERE revoked_at IS NOT NULL`).get()).toEqual({ n: 0 });
+ }
+ });
+
+ it("rejects malformed allowances before pair mutation and actual machine insertion", async () => {
+ token("pending");
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='\"unlimited\"' WHERE plan_id='free' AND entitlement_key='machines.max'");
+ await expect(createPairingToken(db, "owner")).rejects.toBeInstanceOf(plans.ProductEntitlementUnavailableError);
+ expect(() => machine("a")).toThrow("MACHINE_LIMIT_REACHED");
+ expect(sqlite.prepare("SELECT status FROM community_machine_token").get()).toEqual({ status: "pending" });
+ });
+});
diff --git a/src/shared/test/queries/machine-session-epoch.integration.test.ts b/src/shared/test/queries/machine-session-epoch.integration.test.ts
index 40888c3f4..676a26233 100644
--- a/src/shared/test/queries/machine-session-epoch.integration.test.ts
+++ b/src/shared/test/queries/machine-session-epoch.integration.test.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from "node:fs";
import Sqlite from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -61,6 +62,10 @@ describe("machine session epoch SQL transaction", () => {
revoked_at TEXT
);
`);
+ sqlite.exec("CREATE TABLE user(id TEXT PRIMARY KEY, isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT, createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, deletedAt TEXT); CREATE TABLE community_bot_binding(user_id TEXT PRIMARY KEY, machine_id TEXT);");
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0098_product_plan_bot_active.sql", import.meta.url), "utf8"));
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0099_billing_founder.sql", import.meta.url), "utf8"));
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0101_machine_plan_limits.sql", import.meta.url), "utf8"));
db = drizzle(sqlite);
// Match D1's all-or-nothing batch contract using real generated SQL.
(db as any).batch = (statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>) =>
diff --git a/src/shared/test/queries/product-plan.test.ts b/src/shared/test/queries/product-plan.test.ts
new file mode 100644
index 000000000..a7e642f0c
--- /dev/null
+++ b/src/shared/test/queries/product-plan.test.ts
@@ -0,0 +1,672 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import { createMachinePlanTables } from "./machine-plan-fixture"
+import Sqlite from "better-sqlite3"
+import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3"
+import { getTableConfig } from "drizzle-orm/sqlite-core"
+import { z } from "zod"
+import * as productPlanQuery from "../../src/db/queries/product-plan"
+import {
+ productPlan,
+ productPlanEntitlement,
+ userProductPlan,
+} from "../../src/db/product-plan-schema"
+
+type ExecutableStatement = {
+ toSQL(): { sql: string }
+ all(): unknown[]
+ run(): unknown
+}
+
+function createDatabase() {
+ const sqlite = new Sqlite(":memory:")
+ sqlite.pragma("foreign_keys = ON")
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL DEFAULT '',
+ discriminator TEXT NOT NULL DEFAULT '0000',
+ email TEXT NOT NULL DEFAULT '',
+ emailVerified INTEGER NOT NULL DEFAULT 0,
+ image TEXT,
+ avatarVersion INTEGER NOT NULL DEFAULT 0,
+ avatarObjectKey TEXT,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ createdAt TEXT NOT NULL,
+ updatedAt TEXT NOT NULL,
+ deletedAt TEXT,
+ lastRefreshContextAt TEXT
+ );
+ CREATE TABLE community_bot_binding (
+ user_id TEXT PRIMARY KEY,
+ machine_id TEXT NOT NULL,
+ runtime TEXT NOT NULL DEFAULT 'codex',
+ instruction TEXT NOT NULL DEFAULT '',
+ model_name TEXT,
+ reasoning_effort TEXT,
+ runtime_config_revision INTEGER NOT NULL DEFAULT 0,
+ is_active INTEGER NOT NULL DEFAULT 1,
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE product_plan (
+ id TEXT PRIMARY KEY,
+ display_name TEXT NOT NULL,
+ is_default INTEGER NOT NULL DEFAULT 0,
+ is_active INTEGER NOT NULL DEFAULT 1,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE product_plan_entitlement (
+ plan_id TEXT NOT NULL REFERENCES product_plan(id) ON DELETE CASCADE,
+ entitlement_key TEXT NOT NULL,
+ value_json TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (plan_id, entitlement_key)
+ );
+ CREATE TABLE user_product_plan (
+ user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE,
+ plan_id TEXT NOT NULL REFERENCES product_plan(id) ON DELETE RESTRICT,
+ is_founder INTEGER NOT NULL DEFAULT 0,
+ assigned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE community_category (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL,
+ private INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ server_id TEXT,
+ category_id TEXT,
+ type TEXT NOT NULL DEFAULT 'text',
+ parent_channel_id TEXT,
+ creator_id TEXT
+ );
+ CREATE TABLE community_server_member (
+ id TEXT PRIMARY KEY,
+ server_id TEXT NOT NULL,
+ user_id TEXT NOT NULL
+ );
+ CREATE TABLE community_channel_member (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ relation TEXT NOT NULL DEFAULT 'access'
+ );
+ CREATE TABLE community_friendship (
+ id TEXT PRIMARY KEY,
+ requester_id TEXT NOT NULL,
+ addressee_id TEXT NOT NULL,
+ status TEXT NOT NULL
+ );
+ CREATE TABLE community_message (
+ id TEXT PRIMARY KEY,
+ author_id TEXT NOT NULL,
+ content TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ seq INTEGER NOT NULL
+ );
+ CREATE TABLE community_read_state (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ last_read_at TEXT NOT NULL,
+ last_read_message_id TEXT,
+ last_read_seq INTEGER NOT NULL DEFAULT 0,
+ UNIQUE (user_id, channel_id)
+ );
+ CREATE TABLE community_read_state_revision (
+ user_id TEXT PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TRIGGER enforce_active_bot_entitlement_before_update
+ BEFORE UPDATE OF is_active ON community_bot_binding
+ WHEN NEW.is_active = 1 AND OLD.is_active = 0 AND (
+ SELECT COUNT(*)
+ FROM community_bot_binding active_binding
+ INNER JOIN user active_bot ON active_bot.id = active_binding.user_id
+ WHERE active_bot.ownerUserId = (
+ SELECT ownerUserId FROM user WHERE id = NEW.user_id
+ )
+ AND active_bot.isBot = 1
+ AND active_bot.deletedAt IS NULL
+ AND active_binding.is_active = 1
+ ) >= COALESCE((
+ SELECT CAST(e.value_json AS INTEGER)
+ FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ LEFT JOIN user_product_plan up ON up.user_id = (
+ SELECT ownerUserId FROM user WHERE id = NEW.user_id
+ )
+ WHERE e.entitlement_key = 'bots.max'
+ AND json_type(e.value_json) = 'integer'
+ AND CAST(e.value_json AS INTEGER) >= 0
+ AND p.id = COALESCE(
+ up.plan_id,
+ (SELECT id FROM product_plan WHERE is_default = 1 AND is_active = 1 LIMIT 1)
+ )
+ LIMIT 1
+ ), 0)
+ BEGIN
+ SELECT RAISE(ABORT, 'BOT_ENTITLEMENT_LIMIT_REACHED');
+ END;
+ `)
+ const db = drizzleSqlite(sqlite) as ReturnType<typeof drizzleSqlite> & {
+ batch(statements: ExecutableStatement[]): Promise<unknown[]>
+ }
+ db.batch = async (statements: ExecutableStatement[]) => sqlite.transaction(() =>
+ statements.map((statement) => (
+ /\breturning\b/i.test(statement.toSQL().sql) ? statement.all() : statement.run()
+ )),
+ )()
+ createMachinePlanTables(sqlite)
+ return { sqlite, db }
+}
+
+function seedPlan(sqlite: Sqlite.Database, input: {
+ id: string
+ displayName?: string
+ isDefault?: boolean
+ isActive?: boolean
+ botsMax?: string
+}) {
+ sqlite.prepare(`
+ INSERT INTO product_plan (id, display_name, is_default, is_active)
+ VALUES (?, ?, ?, ?)
+ `).run(
+ input.id,
+ input.displayName ?? input.id,
+ input.isDefault ? 1 : 0,
+ input.isActive === false ? 0 : 1,
+ )
+ if (input.botsMax !== undefined) {
+ sqlite.prepare(`
+ INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+ VALUES (?, 'bots.max', ?)
+ `).run(input.id, input.botsMax)
+ }
+ sqlite.prepare("INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json) VALUES (?, 'machines.max', '10')").run(input.id)
+}
+
+function seedHuman(sqlite: Sqlite.Database, id: string, planId?: string) {
+ sqlite.prepare(`
+ INSERT INTO user (id, createdAt, updatedAt) VALUES (?, '2026-01-01', '2026-01-01')
+ `).run(id)
+ if (planId) {
+ sqlite.prepare(`INSERT INTO user_product_plan (user_id, plan_id) VALUES (?, ?)`).run(id, planId)
+ }
+}
+
+function seedBot(
+ sqlite: Sqlite.Database,
+ ownerId: string,
+ id: string,
+ createdAt: string,
+ active = true,
+) {
+ sqlite.prepare(`
+ INSERT INTO user (id, name, isBot, ownerUserId, createdAt, updatedAt)
+ VALUES (?, ?, 1, ?, ?, ?)
+ `).run(id, id, ownerId, createdAt, createdAt)
+ sqlite.prepare(`
+ INSERT INTO community_bot_binding (user_id, machine_id, is_active)
+ VALUES (?, 'machine_1', ?)
+ `).run(id, active ? 1 : 0)
+}
+
+describe("generic product plan entitlement queries", () => {
+ let sqlite: Sqlite.Database
+ let db: ReturnType<typeof createDatabase>["db"]
+
+ beforeEach(() => ({ sqlite, db } = createDatabase()))
+ afterEach(() => sqlite.close())
+
+ it("keeps runtime defaults, foreign keys, and indexes available in the Drizzle schema", () => {
+ const planConfig = getTableConfig(productPlan)
+ const entitlementConfig = getTableConfig(productPlanEntitlement)
+ const assignmentConfig = getTableConfig(userProductPlan)
+
+ expect(planConfig.indexes.map((index) => index.config.name)).toContain(
+ "uq_product_plan_active_default",
+ )
+ expect(entitlementConfig.indexes.map((index) => index.config.name)).toContain(
+ "idx_product_plan_entitlement_key",
+ )
+ expect(assignmentConfig.indexes.map((index) => index.config.name)).toContain(
+ "idx_user_product_plan_plan",
+ )
+ expect(entitlementConfig.foreignKeys[0]?.reference().foreignTable).toBe(productPlan)
+ expect(assignmentConfig.foreignKeys.map((key) => key.reference().foreignTable)).toEqual([
+ expect.anything(),
+ productPlan,
+ ])
+
+ for (const column of [
+ productPlan.createdAt,
+ productPlan.updatedAt,
+ productPlanEntitlement.createdAt,
+ productPlanEntitlement.updatedAt,
+ userProductPlan.assignedAt,
+ userProductPlan.updatedAt,
+ ]) {
+ expect(column.defaultFn?.()).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ }
+ })
+
+ it("uses the active default without an assignment and lets an explicit assignment override it", async () => {
+ seedPlan(sqlite, { id: "default-plan", displayName: "Default", isDefault: true, botsMax: "3" })
+ seedPlan(sqlite, { id: "larger-plan", displayName: "Larger", botsMax: "11" })
+ seedHuman(sqlite, "unassigned")
+ seedHuman(sqlite, "assigned", "larger-plan")
+
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "unassigned")).resolves.toEqual({
+ plan: { id: "default-plan", displayName: "Default" },
+ value: 3,
+ isFounder: false,
+ })
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "assigned")).resolves.toEqual({
+ plan: { id: "larger-plan", displayName: "Larger" },
+ value: 11,
+ isFounder: false,
+ })
+ })
+
+ it("resolves a newly inserted plan and structured entitlement without application branching", async () => {
+ seedPlan(sqlite, { id: "new-tier", displayName: "New Tier", botsMax: "17" })
+ seedHuman(sqlite, "owner", "new-tier")
+ sqlite.prepare(`
+ INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+ VALUES ('new-tier', 'feature.workflow', '{"enabled":true,"modes":["fast"]}')
+ `).run()
+ sqlite.prepare(`
+ INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+ VALUES ('new-tier', 'feature.optional', 'null')
+ `).run()
+
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "owner")).resolves.toMatchObject({
+ plan: { id: "new-tier" },
+ value: 17,
+ })
+ await expect(productPlanQuery.resolveEntitlementForUser(
+ db as never,
+ "owner",
+ "feature.workflow",
+ z.object({ enabled: z.boolean(), modes: z.array(z.string()) }),
+ )).resolves.toMatchObject({ value: { enabled: true, modes: ["fast"] } })
+ await expect(productPlanQuery.resolveEntitlementForUser(
+ db as never,
+ "owner",
+ "feature.optional",
+ z.null(),
+ )).resolves.toMatchObject({ value: null })
+ })
+
+ it("fails closed for missing, malformed, and inactive catalog data", async () => {
+ seedPlan(sqlite, { id: "missing", isDefault: true })
+ seedHuman(sqlite, "owner", "missing")
+
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "owner")).rejects.toMatchObject({
+ reason: "entitlement_missing",
+ })
+
+ sqlite.prepare(`
+ INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+ VALUES ('missing', 'bots.max', '"3"')
+ `).run()
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "owner")).rejects.toMatchObject({
+ reason: "entitlement_malformed",
+ })
+
+ sqlite.prepare(`UPDATE product_plan SET is_active = 0 WHERE id = 'missing'`).run()
+ await expect(productPlanQuery.resolveBotsMaxForUser(db as never, "owner")).rejects.toMatchObject({
+ reason: "plan_unavailable",
+ })
+ })
+
+ it("counts all live owned bots for creation capacity while counting Active separately", async () => {
+ seedPlan(sqlite, { id: "free", displayName: "Free", isDefault: true, botsMax: "3" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "active", "2026-01-01", true)
+ seedBot(sqlite, "owner", "inactive", "2026-01-02", false)
+ seedBot(sqlite, "owner", "deleted", "2026-01-03", true)
+ sqlite.prepare(`UPDATE user SET deletedAt = '2026-02-01' WHERE id = 'deleted'`).run()
+
+ await expect(productPlanQuery.getBotCapacitySummary(db as never, "owner")).resolves.toEqual({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 2,
+ activeCount: 1,
+ isFounder: false,
+ })
+ })
+
+ it("leaves assignment and active bots unchanged when the owner was deleted", async () => {
+ seedPlan(sqlite, { id: "large", botsMax: "3" })
+ seedPlan(sqlite, { id: "small", botsMax: "1" })
+ seedHuman(sqlite, "owner", "large")
+ seedBot(sqlite, "owner", "bot_a", "2026-01-01", true)
+ seedBot(sqlite, "owner", "bot_b", "2026-01-02", true)
+ seedBot(sqlite, "owner", "bot_c", "2026-01-03", true)
+ sqlite.prepare("UPDATE user SET deletedAt = '2026-02-01' WHERE id = 'owner'").run()
+ const beforePlan = sqlite.prepare("SELECT * FROM user_product_plan WHERE user_id = 'owner'").get()
+ const beforeBots = sqlite.prepare("SELECT * FROM community_bot_binding ORDER BY user_id").all()
+
+ await expect(productPlanQuery.assignUserPlan(db as never, "owner", "small"))
+ .rejects.toThrow("PLAN_ASSIGNMENT_PROTECTED")
+
+ expect(sqlite.prepare("SELECT * FROM user_product_plan WHERE user_id = 'owner'").get()).toEqual(beforePlan)
+ expect(sqlite.prepare("SELECT * FROM community_bot_binding ORDER BY user_id").all()).toEqual(beforeBots)
+ })
+
+ it("keeps Founder on the referenced plan and follows its changing entitlements", async () => {
+ seedPlan(sqlite, { id: "free", displayName: "Free", isDefault: true, botsMax: "3" })
+ seedPlan(sqlite, { id: "house", displayName: "House", botsMax: "40" })
+ seedHuman(sqlite, "owner", "house")
+ sqlite.prepare("UPDATE user_product_plan SET is_founder=1 WHERE user_id='owner'").run()
+ await expect(productPlanQuery.assignUserPlan(db as never, "owner", "free"))
+ .rejects.toThrow("PLAN_ASSIGNMENT_PROTECTED")
+ await productPlanQuery.setPlanEntitlement(db as never, "house", "bots.max", 50)
+ await expect(productPlanQuery.getBotCapacitySummary(db as never, "owner")).resolves.toMatchObject({
+ plan: { id: "house" }, isFounder: true, limit: 50,
+ })
+ })
+
+ it("downgrades deterministically without deletion, while an upgrade never reactivates", async () => {
+ seedPlan(sqlite, { id: "small", displayName: "Small", isDefault: true, botsMax: "2" })
+ seedPlan(sqlite, { id: "large", displayName: "Large", botsMax: "5" })
+ seedHuman(sqlite, "owner", "large")
+ seedBot(sqlite, "owner", "bot_b", "2026-01-01", true)
+ seedBot(sqlite, "owner", "bot_a", "2026-01-01", true)
+ seedBot(sqlite, "owner", "bot_c", "2026-01-02", true)
+
+ await expect(productPlanQuery.assignUserPlan(db as never, "owner", "small")).resolves.toMatchObject({
+ plan: { id: "small", displayName: "Small" },
+ limit: 2,
+ deactivatedBotIds: ["bot_c"],
+ })
+ expect(sqlite.prepare(`
+ SELECT u.id, b.is_active AS isActive
+ FROM user u JOIN community_bot_binding b ON b.user_id = u.id
+ WHERE u.ownerUserId = 'owner' ORDER BY u.id
+ `).all()).toEqual([
+ { id: "bot_a", isActive: 1 },
+ { id: "bot_b", isActive: 1 },
+ { id: "bot_c", isActive: 0 },
+ ])
+
+ await productPlanQuery.assignUserPlan(db as never, "owner", "large")
+ expect(sqlite.prepare(`SELECT is_active FROM community_bot_binding WHERE user_id = 'bot_c'`).get())
+ .toEqual({ is_active: 0 })
+ expect(sqlite.prepare(`SELECT COUNT(*) AS n FROM user WHERE ownerUserId = 'owner'`).get())
+ .toEqual({ n: 3 })
+ })
+
+ it("reactivates atomically after advancing every visible non-empty scope to its execution-time latest message", async () => {
+ seedPlan(sqlite, { id: "free", displayName: "Free", isDefault: true, botsMax: "5" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "bot", "2026-01-01", false)
+ seedHuman(sqlite, "peer")
+ sqlite.exec(`
+ INSERT INTO community_category (id, server_id, private)
+ VALUES ('private_category', 'server', 1);
+ INSERT INTO community_channel (id, server_id, type)
+ VALUES
+ ('public', 'server', 'text'),
+ ('thread_parent', 'server', 'text'),
+ ('empty', 'server', 'text');
+ INSERT INTO community_channel (id, server_id, category_id, type)
+ VALUES ('private', 'server', 'private_category', 'text');
+ INSERT INTO community_channel (id, server_id, type, parent_channel_id)
+ VALUES ('thread', 'server', 'thread', 'thread_parent');
+ INSERT INTO community_channel (id, type)
+ VALUES ('dm', 'dm');
+ INSERT INTO community_server_member (id, server_id, user_id)
+ VALUES ('sm_bot', 'server', 'bot');
+ INSERT INTO community_channel_member (id, channel_id, user_id, relation)
+ VALUES
+ ('private_access', 'private', 'bot', 'access'),
+ ('dm_bot', 'dm', 'bot', 'access'),
+ ('dm_peer', 'dm', 'peer', 'access');
+ INSERT INTO community_message (id, author_id, created_at, channel_id, seq)
+ VALUES
+ ('public_1', 'owner', '2026-02-01T00:00:01Z', 'public', 1),
+ ('public_2', 'owner', '2026-02-01T00:00:02Z', 'public', 2),
+ ('private_4', 'owner', '2026-02-01T00:00:04Z', 'private', 4),
+ ('thread_3', 'owner', '2026-02-01T00:00:03Z', 'thread', 3),
+ ('dm_7', 'peer', '2026-02-01T00:00:07Z', 'dm', 7);
+ INSERT INTO community_read_state (
+ id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq
+ ) VALUES ('old_public_cursor', 'bot', 'public', '2026-02-01T00:00:01Z', 'public_1', 1);
+ `)
+
+ await expect(productPlanQuery.getBotCapacitySummary(db as never, "owner")).resolves.toMatchObject({
+ limit: 5,
+ activeCount: 0,
+ })
+ const result = await import("../../src/db/queries/community/bot").then(({ setBotActive }) =>
+ setBotActive(db as never, "bot", "owner", true),
+ )
+ expect(result).toMatchObject({ state: "updated", bot: { id: "bot", isActive: true } })
+ expect(sqlite.prepare(`
+ SELECT channel_id AS channelId, last_read_message_id AS messageId, last_read_seq AS seq
+ FROM community_read_state WHERE user_id = 'bot' ORDER BY channel_id
+ `).all()).toEqual([
+ { channelId: "dm", messageId: "dm_7", seq: 7 },
+ { channelId: "private", messageId: "private_4", seq: 4 },
+ { channelId: "public", messageId: "public_2", seq: 2 },
+ { channelId: "thread", messageId: "thread_3", seq: 3 },
+ ])
+ expect(sqlite.prepare(`SELECT revision FROM community_read_state_revision WHERE user_id = 'bot'`).get())
+ .toEqual({ revision: 1 })
+ expect(sqlite.prepare(`SELECT is_active FROM community_bot_binding WHERE user_id = 'bot'`).get())
+ .toEqual({ is_active: 1 })
+
+ sqlite.prepare(`
+ INSERT INTO community_message (id, author_id, created_at, channel_id, seq)
+ VALUES ('public_3', 'owner', '2026-02-01T00:00:08Z', 'public', 3)
+ `).run()
+ expect(sqlite.prepare(`
+ SELECT last_read_seq FROM community_read_state
+ WHERE user_id = 'bot' AND channel_id = 'public'
+ `).get()).toEqual({ last_read_seq: 2 })
+ })
+
+ it("reconciles both explicit and default-plan owners when bots.max itself is lowered", async () => {
+ seedPlan(sqlite, { id: "target", displayName: "Target", isDefault: true, botsMax: "5" })
+ seedPlan(sqlite, { id: "other", displayName: "Other", botsMax: "5" })
+ seedHuman(sqlite, "default_owner")
+ seedHuman(sqlite, "explicit_owner", "target")
+ seedHuman(sqlite, "other_owner", "other")
+ for (const owner of ["default_owner", "explicit_owner", "other_owner"]) {
+ seedBot(sqlite, owner, `${owner}_a`, "2026-01-01", true)
+ seedBot(sqlite, owner, `${owner}_b`, "2026-01-02", true)
+ seedBot(sqlite, owner, `${owner}_c`, "2026-01-03", true)
+ }
+
+ const result = await productPlanQuery.setPlanEntitlement(db as never, "target", "bots.max", 2)
+
+ expect(new Set(result.deactivatedBotIds)).toEqual(new Set([
+ "default_owner_c",
+ "explicit_owner_c",
+ ]))
+ const counts = sqlite.prepare(`
+ SELECT u.ownerUserId AS ownerId, SUM(b.is_active) AS activeCount
+ FROM user u JOIN community_bot_binding b ON b.user_id = u.id
+ GROUP BY u.ownerUserId ORDER BY u.ownerUserId
+ `).all()
+ expect(counts).toEqual([
+ { ownerId: "default_owner", activeCount: 2 },
+ { ownerId: "explicit_owner", activeCount: 2 },
+ { ownerId: "other_owner", activeCount: 3 },
+ ])
+ expect(sqlite.prepare(`
+ SELECT value_json FROM product_plan_entitlement
+ WHERE plan_id = 'target' AND entitlement_key = 'bots.max'
+ `).get()).toEqual({ value_json: "2" })
+
+ await productPlanQuery.setPlanEntitlement(db as never, "target", "bots.max", 5)
+ expect(sqlite.prepare(`
+ SELECT is_active FROM community_bot_binding
+ WHERE user_id IN ('default_owner_c', 'explicit_owner_c') ORDER BY user_id
+ `).all()).toEqual([{ is_active: 0 }, { is_active: 0 }])
+ })
+
+ it("fails closed when plan-targeted mutations cannot resolve a valid bots.max", async () => {
+ seedPlan(sqlite, { id: "inactive", isActive: false, botsMax: "3" })
+ seedPlan(sqlite, { id: "missing" })
+ seedPlan(sqlite, { id: "active", botsMax: "3" })
+ seedHuman(sqlite, "owner")
+
+ await expect(productPlanQuery.assignUserPlan(db as never, "owner", "inactive"))
+ .rejects.toMatchObject({ reason: "plan_unavailable" })
+ await expect(productPlanQuery.assignUserPlan(db as never, "owner", "missing"))
+ .rejects.toMatchObject({ reason: "entitlement_missing" })
+ await expect(productPlanQuery.setPlanEntitlement(db as never, "inactive", "bots.max", 2))
+ .rejects.toMatchObject({ reason: "plan_unavailable" })
+ await expect(productPlanQuery.setPlanEntitlement(db as never, "active", "bots.max", "bad"))
+ .rejects.toMatchObject({ reason: "entitlement_malformed" })
+ })
+
+ it("updates a non-capacity entitlement without reconciling bots", async () => {
+ seedPlan(sqlite, { id: "active", botsMax: "3" })
+
+ await expect(productPlanQuery.setPlanEntitlement(
+ db as never,
+ "active",
+ "feature.workflow",
+ { enabled: true },
+ )).resolves.toEqual({ deactivatedBotIds: [] })
+ expect(sqlite.prepare(`
+ SELECT value_json FROM product_plan_entitlement
+ WHERE plan_id = 'active' AND entitlement_key = 'feature.workflow'
+ `).get()).toEqual({ value_json: '{"enabled":true}' })
+ })
+
+ it("keeps activation owner-scoped and deactivation idempotent", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", isDefault: true, botsMax: "3" })
+ seedHuman(sqlite, "owner")
+ seedHuman(sqlite, "other_owner")
+ seedBot(sqlite, "owner", "bot", "2026-01-01", true)
+
+ await expect(setBotActive(db as never, "bot", "other_owner", false)).resolves.toEqual({
+ state: "not_found",
+ })
+ expect(sqlite.prepare(`SELECT is_active FROM community_bot_binding WHERE user_id = 'bot'`).get())
+ .toEqual({ is_active: 1 })
+
+ await expect(setBotActive(db as never, "bot", "owner", false)).resolves.toMatchObject({
+ state: "updated",
+ bot: { id: "bot", isActive: false },
+ })
+ await expect(setBotActive(db as never, "bot", "owner", false)).resolves.toMatchObject({
+ state: "unchanged",
+ bot: { id: "bot", isActive: false },
+ })
+ })
+
+ it("returns the raced state when a deactivation loses its final ownership predicate", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", isDefault: true, botsMax: "3" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "bot", "2026-01-01", true)
+ const update = db.update.bind(db)
+ let injectedRace = false
+ db.update = ((table: Parameters<typeof update>[0]) => {
+ if (!injectedRace) {
+ injectedRace = true
+ sqlite.prepare(`UPDATE community_bot_binding SET is_active = 0 WHERE user_id = 'bot'`).run()
+ }
+ return update(table)
+ }) as typeof db.update
+
+ await expect(setBotActive(db as never, "bot", "owner", false)).resolves.toMatchObject({
+ state: "unchanged",
+ bot: { id: "bot", isActive: false },
+ })
+ })
+
+ it("returns capacity before activation cursor work when every active slot is occupied", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", displayName: "Free", isDefault: true, botsMax: "1" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "active", "2026-01-01", true)
+ seedBot(sqlite, "owner", "target", "2026-01-02", false)
+
+ await expect(setBotActive(db as never, "target", "owner", true)).resolves.toMatchObject({
+ state: "capacity",
+ capacity: { limit: 1, activeCount: 1 },
+ })
+ })
+
+ it("returns the raced state when another writer activates the target first", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", isDefault: true, botsMax: "3" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "bot", "2026-01-01", false)
+ const executeBatch = db.batch.bind(db)
+ db.batch = async (statements: ExecutableStatement[]) => {
+ sqlite.prepare(`UPDATE community_bot_binding SET is_active = 1 WHERE user_id = 'bot'`).run()
+ return executeBatch(statements)
+ }
+
+ await expect(setBotActive(db as never, "bot", "owner", true)).resolves.toMatchObject({
+ state: "unchanged",
+ bot: { id: "bot", isActive: true },
+ })
+ })
+
+ it("rethrows an unexpected activation batch failure", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", isDefault: true, botsMax: "3" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "bot", "2026-01-01", false)
+ db.batch = async () => { throw new Error("unexpected batch failure") }
+
+ await expect(setBotActive(db as never, "bot", "owner", true))
+ .rejects.toThrow("unexpected batch failure")
+ })
+
+ it("rolls cursor catch-up back when a concurrent activation consumes the final slot", async () => {
+ const { setBotActive } = await import("../../src/db/queries/community/bot")
+ seedPlan(sqlite, { id: "free", displayName: "Free", isDefault: true, botsMax: "1" })
+ seedHuman(sqlite, "owner")
+ seedBot(sqlite, "owner", "target", "2026-01-01", false)
+ sqlite.exec(`
+ INSERT INTO community_channel (id, server_id, type) VALUES ('public', 'server', 'text');
+ INSERT INTO community_server_member (id, server_id, user_id) VALUES ('sm', 'server', 'target');
+ INSERT INTO community_message (id, author_id, created_at, channel_id, seq)
+ VALUES ('message_1', 'owner', '2026-02-01T00:00:01Z', 'public', 1);
+ `)
+ const executeBatch = db.batch.bind(db)
+ let injectedRace = false
+ db.batch = async (statements: ExecutableStatement[]) => {
+ if (!injectedRace) {
+ injectedRace = true
+ seedBot(sqlite, "owner", "racer", "2026-01-02", true)
+ }
+ return executeBatch(statements)
+ }
+
+ await expect(setBotActive(db as never, "target", "owner", true)).resolves.toEqual({
+ state: "capacity",
+ capacity: {
+ plan: { id: "free", displayName: "Free" },
+ limit: 1,
+ ownedCount: 2,
+ activeCount: 1,
+ isFounder: false,
+ },
+ })
+ expect(sqlite.prepare(`SELECT is_active FROM community_bot_binding WHERE user_id = 'target'`).get())
+ .toEqual({ is_active: 0 })
+ expect(sqlite.prepare(`SELECT COUNT(*) AS n FROM community_read_state WHERE user_id = 'target'`).get())
+ .toEqual({ n: 0 })
+ expect(sqlite.prepare(`SELECT COUNT(*) AS n FROM community_read_state_revision WHERE user_id = 'target'`).get())
+ .toEqual({ n: 0 })
+ })
+})
diff --git a/src/web/migrations/0098_product_plan_bot_active.sql b/src/web/migrations/0098_product_plan_bot_active.sql
new file mode 100644
index 000000000..27c025345
--- /dev/null
+++ b/src/web/migrations/0098_product_plan_bot_active.sql
@@ -0,0 +1,128 @@
+-- Extensible product-plan catalog. Plans and their entitlements are data, not
+-- application enums: adding a tier or entitlement does not change this schema.
+CREATE TABLE product_plan (
+ id TEXT PRIMARY KEY,
+ display_name TEXT NOT NULL,
+ is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),
+ is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE UNIQUE INDEX uq_product_plan_active_default
+ ON product_plan(is_default)
+ WHERE is_default = 1 AND is_active = 1;
+
+CREATE TABLE product_plan_entitlement (
+ plan_id TEXT NOT NULL REFERENCES product_plan(id) ON DELETE CASCADE,
+ entitlement_key TEXT NOT NULL,
+ value_json TEXT NOT NULL CHECK (json_valid(value_json)),
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ PRIMARY KEY (plan_id, entitlement_key)
+);
+
+CREATE INDEX idx_product_plan_entitlement_key
+ ON product_plan_entitlement(entitlement_key, plan_id);
+
+CREATE TABLE user_product_plan (
+ user_id TEXT PRIMARY KEY REFERENCES "user"(id) ON DELETE CASCADE,
+ plan_id TEXT NOT NULL REFERENCES product_plan(id) ON DELETE RESTRICT,
+ assigned_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX idx_user_product_plan_plan
+ ON user_product_plan(plan_id);
+
+-- Initial commercial catalog. These ids and values are replaceable product
+-- data; application policy resolves only entitlement keys such as `bots.max`.
+INSERT INTO product_plan (id, display_name, is_default, is_active, sort_order)
+VALUES
+ ('free', 'Free', 1, 1, 10),
+ ('studio', 'Studio', 0, 1, 20),
+ ('house', 'House', 0, 1, 30);
+
+INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+VALUES
+ ('free', 'bots.max', '3'),
+ ('studio', 'bots.max', '10'),
+ ('house', 'bots.max', '40');
+
+ALTER TABLE community_bot_binding
+ ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1));
+
+CREATE INDEX idx_community_bot_binding_machine_active
+ ON community_bot_binding(machine_id, is_active);
+
+-- Rollout compatibility: every human that already exists keeps the current
+-- product capability through an explicit House assignment. Users created
+-- after this migration have no row and therefore resolve through Free, the
+-- active default. Existing bot bindings keep the new column's DEFAULT 1.
+INSERT INTO user_product_plan (user_id, plan_id)
+SELECT id, 'house'
+FROM "user"
+WHERE isBot = 0;
+
+-- Database backstop for concurrent creates. Domain code still performs the
+-- friendly preflight and returns plan evidence, but this trigger is the final
+-- authority if two requests race the same remaining slot.
+CREATE TRIGGER enforce_owned_bot_entitlement_before_insert
+BEFORE INSERT ON "user"
+WHEN NEW.isBot = 1 AND (
+ SELECT COUNT(*)
+ FROM "user" existing
+ WHERE existing.ownerUserId = NEW.ownerUserId
+ AND existing.isBot = 1
+ AND existing.deletedAt IS NULL
+) >= COALESCE((
+ SELECT CAST(e.value_json AS INTEGER)
+ FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ LEFT JOIN user_product_plan up ON up.user_id = NEW.ownerUserId
+ WHERE e.entitlement_key = 'bots.max'
+ AND json_type(e.value_json) = 'integer'
+ AND CAST(e.value_json AS INTEGER) >= 0
+ AND p.id = COALESCE(
+ up.plan_id,
+ (SELECT id FROM product_plan WHERE is_default = 1 AND is_active = 1 LIMIT 1)
+ )
+ LIMIT 1
+), 0)
+BEGIN
+ SELECT RAISE(ABORT, 'BOT_ENTITLEMENT_LIMIT_REACHED');
+END;
+
+-- Same backstop for two concurrent owner activation requests.
+CREATE TRIGGER enforce_active_bot_entitlement_before_update
+BEFORE UPDATE OF is_active ON community_bot_binding
+WHEN NEW.is_active = 1 AND OLD.is_active = 0 AND (
+ SELECT COUNT(*)
+ FROM community_bot_binding active_binding
+ INNER JOIN "user" active_bot ON active_bot.id = active_binding.user_id
+ WHERE active_bot.ownerUserId = (
+ SELECT ownerUserId FROM "user" WHERE id = NEW.user_id
+ )
+ AND active_bot.isBot = 1
+ AND active_bot.deletedAt IS NULL
+ AND active_binding.is_active = 1
+) >= COALESCE((
+ SELECT CAST(e.value_json AS INTEGER)
+ FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ LEFT JOIN user_product_plan up ON up.user_id = (
+ SELECT ownerUserId FROM "user" WHERE id = NEW.user_id
+ )
+ WHERE e.entitlement_key = 'bots.max'
+ AND json_type(e.value_json) = 'integer'
+ AND CAST(e.value_json AS INTEGER) >= 0
+ AND p.id = COALESCE(
+ up.plan_id,
+ (SELECT id FROM product_plan WHERE is_default = 1 AND is_active = 1 LIMIT 1)
+ )
+ LIMIT 1
+), 0)
+BEGIN
+ SELECT RAISE(ABORT, 'BOT_ENTITLEMENT_LIMIT_REACHED');
+END;
diff --git a/src/web/migrations/0099_billing_founder.sql b/src/web/migrations/0099_billing_founder.sql
new file mode 100644
index 000000000..8016a70f8
--- /dev/null
+++ b/src/web/migrations/0099_billing_founder.sql
@@ -0,0 +1,26 @@
+ALTER TABLE user_product_plan
+ ADD COLUMN is_founder INTEGER NOT NULL DEFAULT 0 CHECK (is_founder IN (0, 1));
+
+UPDATE user_product_plan SET is_founder = 1
+WHERE plan_id = 'house'
+ AND user_id IN (SELECT id FROM "user" WHERE isBot = 0);
+
+CREATE TABLE billing_price (
+ price_id TEXT PRIMARY KEY,
+ plan_id TEXT NOT NULL REFERENCES product_plan(id) ON DELETE RESTRICT,
+ portal_configuration_id TEXT,
+ enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1))
+);
+
+CREATE TABLE user_billing (
+ user_id TEXT PRIMARY KEY REFERENCES "user"(id) ON DELETE CASCADE,
+ customer_id TEXT,
+ subscription_id TEXT,
+ subscription_json TEXT CHECK (subscription_json IS NULL OR json_valid(subscription_json)),
+ revision INTEGER NOT NULL DEFAULT 0,
+ apply_token TEXT,
+ checkout_attempt_json TEXT CHECK (checkout_attempt_json IS NULL OR json_valid(checkout_attempt_json)),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+CREATE UNIQUE INDEX uq_user_billing_customer ON user_billing(customer_id);
+CREATE UNIQUE INDEX uq_user_billing_subscription ON user_billing(subscription_id);
diff --git a/src/web/migrations/0101_machine_plan_limits.sql b/src/web/migrations/0101_machine_plan_limits.sql
new file mode 100644
index 000000000..ea54c3e8a
--- /dev/null
+++ b/src/web/migrations/0101_machine_plan_limits.sql
@@ -0,0 +1,19 @@
+INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json)
+VALUES ('free', 'machines.max', '1'), ('studio', 'machines.max', '5'), ('house', 'machines.max', '10');
+
+CREATE TRIGGER enforce_owned_machine_entitlement_before_insert
+BEFORE INSERT ON community_machine
+WHEN (SELECT COUNT(*) FROM community_machine existing WHERE existing.user_id = NEW.user_id) >= COALESCE((
+ SELECT CAST(e.value_json AS INTEGER)
+ FROM product_plan_entitlement e
+ INNER JOIN product_plan p ON p.id = e.plan_id AND p.is_active = 1
+ LEFT JOIN user_product_plan up ON up.user_id = NEW.user_id
+ WHERE e.entitlement_key = 'machines.max'
+ AND json_type(e.value_json) = 'integer'
+ AND CAST(e.value_json AS INTEGER) >= 0
+ AND p.id = COALESCE(up.plan_id, (SELECT id FROM product_plan WHERE is_default = 1 AND is_active = 1 LIMIT 1))
+ LIMIT 1
+), 0)
+BEGIN
+ SELECT RAISE(ABORT, 'MACHINE_LIMIT_REACHED');
+END;
diff --git a/src/web/package.json b/src/web/package.json
index ce6c5feae..fdc237a18 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -126,6 +126,7 @@
"shiki": "^4.4.3",
"sonner": "^2.0.8",
"streamdown": "^2.6.0",
+ "stripe": "22.6.2",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0",
"unique-names-generator": "^4.7.1",
diff --git a/src/web/src/app/api/community/billing/cancel-change/route.ts b/src/web/src/app/api/community/billing/cancel-change/route.ts
new file mode 100644
index 000000000..6e8bd9201
--- /dev/null
+++ b/src/web/src/app/api/community/billing/cancel-change/route.ts
@@ -0,0 +1,21 @@
+import { BillingSummarySchema } from "@alook/shared"
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { cancelScheduledChange } from "@/lib/billing/service"
+
+export const POST = withCookieHumanAuth(async (req, ctx) => {
+ const text = await req.text()
+ if (text.trim()) {
+ try {
+ const body = JSON.parse(text)
+ if (!body || Array.isArray(body) || typeof body !== "object" || Object.keys(body).length) return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400)
+ } catch { return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400) }
+ }
+ try {
+ const result = await cancelScheduledChange(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env, ctx.userId)
+ return billingResponse(BillingSummarySchema.parse(result))
+ } catch (error) {
+ return billingFailure(error, "cancel-change")
+ }
+})
diff --git a/src/web/src/app/api/community/billing/checkout/route.ts b/src/web/src/app/api/community/billing/checkout/route.ts
new file mode 100644
index 000000000..1bb7663ad
--- /dev/null
+++ b/src/web/src/app/api/community/billing/checkout/route.ts
@@ -0,0 +1,16 @@
+import { BillingCheckoutRequestSchema, BillingRedirectResponseSchema } from "@alook/shared"
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { createCheckout } from "@/lib/billing/service"
+
+export const POST = withCookieHumanAuth(async (req, ctx) => {
+ const parsed = BillingCheckoutRequestSchema.safeParse(await req.json().catch(() => null))
+ if (!parsed.success) return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400)
+ try {
+ const result = await createCheckout(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env, ctx.userId, ctx.email, parsed.data.priceId, parsed.data.founderAcknowledged)
+ return billingResponse(BillingRedirectResponseSchema.parse(result))
+ } catch (error) {
+ return billingFailure(error, "checkout")
+ }
+})
diff --git a/src/web/src/app/api/community/billing/portal/route.ts b/src/web/src/app/api/community/billing/portal/route.ts
new file mode 100644
index 000000000..85929160e
--- /dev/null
+++ b/src/web/src/app/api/community/billing/portal/route.ts
@@ -0,0 +1,19 @@
+import { BillingPortalRequestSchema, BillingRedirectResponseSchema } from "@alook/shared"
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { createPortal } from "@/lib/billing/service"
+
+export const POST = withCookieHumanAuth(async (req, ctx) => {
+ const text = await req.text()
+ let body: unknown = {}
+ try { if (text.trim()) body = JSON.parse(text) } catch { body = null }
+ const parsed = BillingPortalRequestSchema.safeParse(body)
+ if (!parsed.success) return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400)
+ try {
+ const result = await createPortal(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env, ctx.userId, parsed.data.priceId)
+ return billingResponse(BillingRedirectResponseSchema.parse(result))
+ } catch (error) {
+ return billingFailure(error, "portal")
+ }
+})
diff --git a/src/web/src/app/api/community/billing/route.ts b/src/web/src/app/api/community/billing/route.ts
new file mode 100644
index 000000000..c510c7e47
--- /dev/null
+++ b/src/web/src/app/api/community/billing/route.ts
@@ -0,0 +1,18 @@
+import { BillingSummarySchema, queries } from "@alook/shared"
+import { withOptionalAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { getBillingSummary } from "@/lib/billing/service"
+
+export const GET = withOptionalAuth(async (req, ctx) => {
+ if (req.headers.has("Authorization") || !ctx.userId || ctx.user?.isBot) return billingResponse({ error: "UNAUTHORIZED" }, 401)
+ try {
+ const db = getPrimaryDb(ctx.env.DB)
+ const owner = await queries.user.getUserInternal(db, ctx.userId)
+ if (!owner || owner.isBot || owner.deletedAt !== null) return billingResponse({ error: "UNAUTHORIZED" }, 401)
+ const summary = await getBillingSummary(db, () => billingClient(ctx.env), ctx.env, ctx.userId)
+ return billingResponse(BillingSummarySchema.parse(summary))
+ } catch (error) {
+ return billingFailure(error, "summary")
+ }
+})
diff --git a/src/web/src/app/api/community/billing/routes.test.ts b/src/web/src/app/api/community/billing/routes.test.ts
new file mode 100644
index 000000000..276b55679
--- /dev/null
+++ b/src/web/src/app/api/community/billing/routes.test.ts
@@ -0,0 +1,177 @@
+import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocks = vi.hoisted(() => ({
+ session: vi.fn(), owner: vi.fn(), summary: vi.fn(), checkout: vi.fn(),
+ portal: vi.fn(), cancel: vi.fn(), webhook: vi.fn(),
+ db: { primary: true }, env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_route_fixture" },
+}))
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: mocks.env, ctx: { waitUntil: vi.fn() } })),
+}))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => mocks.db), getDb: vi.fn(() => mocks.db) }))
+vi.mock("@/lib/auth", () => ({
+ createAuth: vi.fn(() => ({ api: { getSession: mocks.session, signOut: vi.fn() } })),
+}))
+vi.mock("@alook/shared", async (original) => ({
+ ...await original<typeof import("@alook/shared")>(),
+ queries: { user: { getUserInternal: mocks.owner } },
+}))
+vi.mock("@/lib/billing/service", () => ({
+ getBillingSummary: mocks.summary, createCheckout: mocks.checkout,
+ createPortal: mocks.portal, cancelScheduledChange: mocks.cancel,
+}))
+vi.mock("@/lib/billing/webhook", () => ({ handleBillingWebhook: mocks.webhook }))
+
+import { GET } from "./route"
+import { POST as checkout } from "./checkout/route"
+import { POST as portal } from "./portal/route"
+import { POST as cancel } from "./cancel-change/route"
+import { POST as webhook } from "../../stripe/webhook/route"
+import { BillingError } from "@/lib/billing/client"
+
+const summary = { plan: { id: "free", displayName: "Free" }, isFounder: false, offers: [], subscription: null }
+const redirect = { url: "https://checkout.stripe.com/session" }
+const owner = { id: "owner", email: "[email protected]", isBot: false, deletedAt: null }
+const request = (body?: string, headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/billing", {
+ method: "POST", body, headers: { origin: "https://alook.ai", ...headers },
+})
+const getRequest = (headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/community/billing", { headers })
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocks.session.mockResolvedValue({ headers: new Headers(), response: { user: { ...owner, email: "[email protected]" } } })
+ mocks.owner.mockResolvedValue(owner)
+ mocks.summary.mockResolvedValue(summary)
+ mocks.checkout.mockResolvedValue(redirect)
+ mocks.portal.mockResolvedValue(redirect)
+ mocks.cancel.mockResolvedValue(summary)
+ vi.spyOn(console, "error").mockImplementation(() => {})
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe("billing HTTP route boundaries", () => {
+ it("returns validated private summary for a live cookie owner", async () => {
+ mocks.summary.mockImplementationOnce(async (_db, client) => {
+ expect(client()).toHaveProperty("checkout")
+ return summary
+ })
+ const response = await GET(getRequest())
+ expect(response.status).toBe(200)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(await response.json()).toEqual(summary)
+ expect(mocks.summary).toHaveBeenCalledWith(mocks.db, expect.any(Function), mocks.env, owner.id)
+ })
+
+ it.each(["anonymous", "authorization", "bot", "deleted", "missing"] as const)("rejects %s summary access without service work", async (kind) => {
+ if (kind === "anonymous") mocks.session.mockResolvedValue({ response: null })
+ if (kind === "bot") mocks.owner.mockResolvedValue({ ...owner, isBot: true })
+ if (kind === "deleted") mocks.owner.mockResolvedValue({ ...owner, deletedAt: "2026-01-01" })
+ if (kind === "missing") mocks.owner.mockResolvedValue(null)
+ const response = await GET(getRequest(kind === "authorization" ? { Authorization: "Bearer machine" } : {}))
+ expect(response.status).toBe(401)
+ expect(mocks.summary).not.toHaveBeenCalled()
+ })
+
+ it.each([true, false, undefined])("forwards validated Checkout consent %s with live owner email", async (founderAcknowledged) => {
+ const response = await checkout(request(JSON.stringify({ priceId: "price_studio", founderAcknowledged })))
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual(redirect)
+ expect(mocks.checkout).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", founderAcknowledged)
+ })
+
+ it.each(["{", "null", "{}", '{"priceId":""}', '{"priceId":"p","founderAcknowledged":"true"}', '{"priceId":"p","ownerId":"other"}'])("rejects malformed Checkout body %s before creating a Session", async (body) => {
+ const response = await checkout(request(body))
+ expect(response.status).toBe(400)
+ expect(await response.json()).toEqual({ error: "BILLING_REQUEST_INVALID" })
+ expect(mocks.checkout).not.toHaveBeenCalled()
+ })
+
+ it.each(["", "{}", '{"priceId":"price_house"}'])("accepts Portal body %s", async (body) => {
+ expect((await portal(request(body))).status).toBe(200)
+ expect(mocks.portal).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, owner.id, body.includes("price_house") ? "price_house" : undefined)
+ })
+
+ it.each(["{", "null", "[]", '{"priceId":""}', '{"customerId":"other"}'])("rejects invalid Portal body %s", async (body) => {
+ expect((await portal(request(body))).status).toBe(400)
+ expect(mocks.portal).not.toHaveBeenCalled()
+ })
+
+ it.each(["", " ", "{}"])("accepts empty cancel-change body %s", async (body) => {
+ const response = await cancel(request(body))
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual(summary)
+ expect(mocks.cancel).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, owner.id)
+ })
+
+ it.each(["{", "null", "[]", "false", "1", '"text"', '{"subscriptionId":"other"}'])("rejects nonempty cancel-change input %s", async (body) => {
+ expect((await cancel(request(body))).status).toBe(400)
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ })
+
+ describe.each([
+ ["checkout", checkout, mocks.checkout, '{"priceId":"price_studio"}'],
+ ["portal", portal, mocks.portal, "{}"],
+ ["cancel", cancel, mocks.cancel, "{}"],
+ ] as const)("%s authentication and failures", (_name, handler, service, body) => {
+ it.each(["cross-origin", "authorization", "anonymous", "deleted", "bot"] as const)("blocks %s before reaching billing service", async (kind) => {
+ if (kind === "anonymous") mocks.session.mockResolvedValue({ response: null })
+ if (kind === "deleted") mocks.owner.mockResolvedValue({ ...owner, deletedAt: "2026-01-01" })
+ if (kind === "bot") mocks.owner.mockResolvedValue({ ...owner, isBot: true })
+ const headers: Record<string, string> = kind === "cross-origin" ? { origin: "https://evil.example" } : kind === "authorization" ? { Authorization: "Bearer machine" } : {}
+ expect((await handler(request(body, headers))).status).toBe(kind === "cross-origin" ? 403 : 401)
+ expect(service).not.toHaveBeenCalled()
+ })
+
+ it("preserves explicit billing failure and avoids caching", async () => {
+ service.mockRejectedValue(new BillingError("BILLING_FOUNDER_PROTECTED", 403))
+ const response = await handler(request(body))
+ expect(response.status).toBe(403)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(await response.json()).toEqual({ error: "BILLING_FOUNDER_PROTECTED" })
+ })
+
+ it("sanitizes service failures", async () => {
+ service.mockRejectedValue(new Error("private upstream body"))
+ const response = await handler(request(body))
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ })
+
+ it("rejects invalid service response instead of leaking it", async () => {
+ service.mockResolvedValue({ private: "data" })
+ const response = await handler(request(body))
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ })
+ })
+
+ it("sanitizes summary lookup failures", async () => {
+ mocks.owner.mockRejectedValue(new Error("private database detail"))
+ const response = await GET(getRequest())
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ })
+})
+
+describe("Stripe webhook HTTP ingress", () => {
+ it.each(["t=123,v1=fixture", null])("passes exact raw bytes and signature %s without cookie auth", async (signature) => {
+ const raw = '{ "id": "evt_fixture",\n "data": {} }\n'
+ const response = await webhook(request(raw, signature ? { "stripe-signature": signature } : {}))
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ received: true })
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mocks.webhook).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, raw, signature)
+ expect(mocks.session).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [new BillingError("BILLING_SIGNATURE_INVALID", 400), 400, "BILLING_SIGNATURE_INVALID"],
+ [new Error("private upstream detail"), 503, "BILLING_UNAVAILABLE"],
+ ] as const)("returns handler error safely", async (error, status, code) => {
+ mocks.webhook.mockRejectedValue(error)
+ const response = await webhook(request("{}"))
+ expect(response.status).toBe(status)
+ expect(await response.json()).toEqual({ error: code })
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/active/route.test.ts b/src/web/src/app/api/community/bots/[id]/active/route.test.ts
new file mode 100644
index 000000000..beb6042b2
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/active/route.test.ts
@@ -0,0 +1,177 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockSetBotActive = vi.fn()
+const mockGetUserPublic = vi.fn()
+const mockIsBotOnline = vi.fn()
+const mockPushBotEventToMachine = vi.fn()
+const mockFanOutPresenceUpdate = vi.fn()
+const mockLogWarn = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityBot: { setBotActive: (...args: unknown[]) => mockSetBotActive(...args) },
+ communityMachine: { isBotOnline: (...args: unknown[]) => mockIsBotOnline(...args) },
+ user: { getUserPublic: (...args: unknown[]) => mockGetUserPublic(...args) },
+ },
+ }
+})
+vi.mock("@/lib/community/bot-push", () => ({
+ pushBotEventToMachine: (...args: unknown[]) => mockPushBotEventToMachine(...args),
+}))
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutPresenceUpdate: (...args: unknown[]) => mockFanOutPresenceUpdate(...args),
+}))
+vi.mock("@/lib/logger", () => ({ log: { warn: (...args: unknown[]) => mockLogWarn(...args) } }))
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => handler(req, {
+ env: { DB: {} },
+ userId: "owner_1",
+ email: "[email protected]",
+ params: ctx?.params,
+ }),
+}))
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ const actual = await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+ return {
+ ...actual,
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { PATCH } from "./route"
+
+const ctx = { params: { id: "bot_1" } } as any
+const bot = {
+ id: "bot_1",
+ ownerUserId: "owner_1",
+ machineId: "machine_1",
+ name: "Helper",
+ discriminator: "0042",
+ description: "helps",
+ isActive: true,
+}
+
+function request(active: unknown) {
+ return new NextRequest("http://localhost/api/community/bots/bot_1/active", {
+ method: "PATCH",
+ body: JSON.stringify({ active }),
+ })
+}
+
+describe("PATCH /api/community/bots/[id]/active", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetUserPublic.mockResolvedValue({ name: "Owner", discriminator: "1813" })
+ mockIsBotOnline.mockResolvedValue(false)
+ mockPushBotEventToMachine.mockResolvedValue({ sent: 1 })
+ mockFanOutPresenceUpdate.mockResolvedValue(undefined)
+ })
+
+ it("activates an owned bot, pushes it to the daemon, and restores Online when its machine is online", async () => {
+ mockSetBotActive.mockResolvedValue({ state: "updated", bot })
+ mockIsBotOnline.mockResolvedValue(true)
+
+ const res = await PATCH(request(true), ctx)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ bot: { id: "bot_1", isActive: true }, changed: true })
+ expect(mockSetBotActive).toHaveBeenCalledWith(expect.anything(), "bot_1", "owner_1", true)
+ expect(mockPushBotEventToMachine).toHaveBeenCalledWith(expect.anything(), "machine_1", {
+ type: "bot:added",
+ botId: "bot_1",
+ name: "Helper",
+ discriminator: "0042",
+ description: "helps",
+ ownerName: "Owner",
+ ownerDiscriminator: "1813",
+ })
+ expect(mockFanOutPresenceUpdate).toHaveBeenCalledWith("bot_1", true, "owner_1")
+ })
+
+ it("deactivates and publishes bot:removed plus Offline", async () => {
+ mockSetBotActive.mockResolvedValue({ state: "updated", bot: { ...bot, isActive: false } })
+
+ const res = await PATCH(request(false), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockPushBotEventToMachine).toHaveBeenCalledWith(expect.anything(), "machine_1", {
+ type: "bot:removed",
+ botId: "bot_1",
+ })
+ expect(mockFanOutPresenceUpdate).toHaveBeenCalledWith("bot_1", false, "owner_1")
+ expect(mockIsBotOnline).not.toHaveBeenCalled()
+ })
+
+ it("keeps idempotent requests side-effect free", async () => {
+ mockSetBotActive.mockResolvedValue({ state: "unchanged", bot })
+
+ const res = await PATCH(request(true), ctx)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ bot: { id: "bot_1", isActive: true }, changed: false })
+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()
+ expect(mockFanOutPresenceUpdate).not.toHaveBeenCalled()
+ })
+
+ it("returns owner-scoped 404", async () => {
+ mockSetBotActive.mockResolvedValue({ state: "not_found" })
+
+ const res = await PATCH(request(true), ctx)
+
+ expect(res.status).toBe(404)
+ })
+
+ it("returns plan evidence when the active limit is reached", async () => {
+ mockSetBotActive.mockResolvedValue({
+ state: "capacity",
+ capacity: {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 4,
+ activeCount: 3,
+ },
+ })
+
+ const res = await PATCH(request(true), ctx)
+
+ expect(res.status).toBe(409)
+ await expect(res.json()).resolves.toEqual({
+ error: "BOT_ACTIVE_LIMIT_REACHED",
+ plan: "free",
+ planDisplayName: "Free",
+ limit: 3,
+ ownedCount: 4,
+ activeCount: 3,
+ })
+ })
+
+ it("does not turn a committed activation into a 500 when best-effort presence resolution fails", async () => {
+ mockSetBotActive.mockResolvedValue({ state: "updated", bot })
+ mockIsBotOnline.mockRejectedValue(new Error("D1 unavailable after commit"))
+
+ const res = await PATCH(request(true), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "bot_activation_post_commit_delivery_failed",
+ expect.objectContaining({ botId: "bot_1" }),
+ )
+ })
+
+ it("rejects a non-boolean activation payload", async () => {
+ const res = await PATCH(request("true"), ctx)
+
+ expect(res.status).toBe(400)
+ expect(mockSetBotActive).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/active/route.ts b/src/web/src/app/api/community/bots/[id]/active/route.ts
new file mode 100644
index 000000000..651742c21
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/active/route.ts
@@ -0,0 +1,73 @@
+import { NextRequest } from "next/server"
+import { CommunityBotActivationRequestSchema, queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"
+import { pushBotEventToMachine } from "@/lib/community/bot-push"
+import { fanOutPresenceUpdate } from "@/lib/community/fanout"
+import { log } from "@/lib/logger"
+
+export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+ const id = ctx.params?.id as string
+ const [body, error] = await parseBody(req, CommunityBotActivationRequestSchema)
+ if (error) return error
+
+ const db = getDb(ctx.env.DB)
+ const result = await queries.communityBot.setBotActive(db, id, ctx.userId, body.active)
+ if (result.state === "not_found") return writeError("bot not found", 404)
+ if (result.state === "capacity") {
+ return writeJSON({
+ error: "BOT_ACTIVE_LIMIT_REACHED",
+ plan: result.capacity.plan.id,
+ planDisplayName: result.capacity.plan.displayName,
+ limit: result.capacity.limit,
+ ownedCount: result.capacity.ownedCount,
+ activeCount: result.capacity.activeCount,
+ }, 409)
+ }
+
+ const changed = result.state === "updated"
+ if (changed) {
+ if (body.active) {
+ try {
+ const owner = await queries.user.getUserPublic(db, ctx.userId)
+ if (owner && result.bot.machineId) {
+ await pushBotEventToMachine(ctx.env, result.bot.machineId, {
+ type: "bot:added",
+ botId: result.bot.id,
+ name: result.bot.name,
+ discriminator: result.bot.discriminator,
+ description: result.bot.description || undefined,
+ ownerName: owner.name,
+ ownerDiscriminator: owner.discriminator,
+ })
+ }
+ // Deactivation forced an Offline projection. If this binding's machine
+ // is already online, publish the matching Online edge immediately so
+ // viewers do not stay stale until the next daemon presence transition.
+ if (await queries.communityMachine.isBotOnline(db, result.bot.id)) {
+ await fanOutPresenceUpdate(result.bot.id, true, result.bot.ownerUserId)
+ }
+ } catch (err) {
+ // The entitlement transition already committed. Delivery is
+ // best-effort; cold-start roster and presence reads remain
+ // authoritative if this immediate edge fails.
+ log.warn("bot_activation_post_commit_delivery_failed", {
+ botId: result.bot.id,
+ err: String(err),
+ })
+ }
+ } else if (result.bot.machineId) {
+ await pushBotEventToMachine(ctx.env, result.bot.machineId, {
+ type: "bot:removed",
+ botId: result.bot.id,
+ })
+ await fanOutPresenceUpdate(result.bot.id, false, result.bot.ownerUserId)
+ }
+ }
+
+ return writeJSON({
+ bot: { id: result.bot.id, isActive: result.bot.isActive },
+ changed,
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.ts
index b4a4042e1..98f3f4ea6 100644
--- a/src/web/src/app/api/community/bots/[id]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts
@@ -41,7 +41,10 @@ vi.mock("@alook/shared", async () => {
}),
queries: {
communityBot: {
- getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ getBotOwnedBy: async (...a: unknown[]) => {
+ const bot = await mockGetBotOwnedBy(...a)
+ return bot ? { isActive: true, ...bot } : null
+ },
updateBot: (...a: unknown[]) => mockUpdateBot(...a),
updateBotModel: (...a: unknown[]) => mockUpdateBotModel(...a),
updateBotRuntime: (...a: unknown[]) => mockUpdateBotRuntime(...a),
@@ -181,6 +184,21 @@ describe("PATCH /api/community/bots/[id]", () => {
)
})
+ it("persists an inactive bot profile change without re-adding it to the daemon roster", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",
+ runtime: "claude", modelName: null, reasoningEffort: null, runtimeConfigRevision: 0,
+ isActive: false,
+ })
+
+ const res = await PATCH(patchReq({ name: "New" }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockUpdateBot).toHaveBeenCalled()
+ expect(mockGetUserPublic).not.toHaveBeenCalled()
+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()
+ })
+
it("resolves the owner BEFORE mutating: an unresolvable owner fails 500 without writing", async () => {
mockGetUserPublic.mockResolvedValue(null)
const res = await PATCH(patchReq({ name: "New" }), ctx)
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index e5d4f3f11..f9daa8be8 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -117,7 +117,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// integrity bug) we must fail WITHOUT having already written — otherwise a
// retry sees `before === updated`, computes no change, and never pushes,
// leaving the daemon's running system prompt permanently stale.
- const willPush = (nameChanged || descriptionChanged) && !!before.machineId
+ const willPush = before.isActive && (nameChanged || descriptionChanged) && !!before.machineId
const owner = willPush ? await queries.user.getUserPublic(db, before.ownerUserId) : null
if (willPush && !owner) {
return writeError("bot owner not resolvable — refusing to push a bot update with unknown ownership", 500)
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index 73c9e4c45..2b22e324e 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -10,6 +10,7 @@ const mockListBotsForOwner = vi.fn()
const mockGetBotDailyActivityForOwner = vi.fn()
const mockGetBotDailyTokenUsageForOwner = vi.fn()
const mockEnsureSiblingBotFriendship = vi.fn()
+const mockGetBotCapacitySummary = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -29,6 +30,10 @@ vi.mock("@alook/shared", async () => {
listBotsForOwner: (...a: unknown[]) => mockListBotsForOwner(...a),
getBotDailyActivityForOwner: (...a: unknown[]) => mockGetBotDailyActivityForOwner(...a),
getBotDailyTokenUsageForOwner: (...a: unknown[]) => mockGetBotDailyTokenUsageForOwner(...a),
+ isBotEntitlementLimitError: (error: unknown) => error instanceof Error && error.message.includes("BOT_ENTITLEMENT_LIMIT_REACHED"),
+ },
+ productPlan: {
+ getBotCapacitySummary: (...a: unknown[]) => mockGetBotCapacitySummary(...a),
},
communityFriendship: {
ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSiblingBotFriendship(...a),
@@ -88,6 +93,12 @@ describe("POST /api/community/bots — model", () => {
beforeEach(() => {
vi.clearAllMocks()
mockCountLiveBotsForOwner.mockResolvedValue(0)
+ mockGetBotCapacitySummary.mockResolvedValue({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 0,
+ activeCount: 0,
+ })
mockGetMachineForOwner.mockResolvedValue({
id: "mac1",
availableRuntimes: [{ id: "claude", status: "healthy" }, { id: "codex", status: "healthy" }],
@@ -167,6 +178,62 @@ describe("POST /api/community/bots — model", () => {
expect(mockCreateBot).not.toHaveBeenCalled()
})
+ it("returns stored plan evidence without attempting creation at total owned capacity", async () => {
+ mockGetBotCapacitySummary.mockResolvedValue({
+ plan: { id: "studio", displayName: "Studio" },
+ limit: 10,
+ ownedCount: 10,
+ activeCount: 7,
+ })
+
+ const res = await POST(postReq(base()), ctx)
+
+ expect(res.status).toBe(409)
+ await expect(res.json()).resolves.toEqual({
+ error: "BOT_LIMIT_REACHED",
+ plan: "studio",
+ planDisplayName: "Studio",
+ limit: 10,
+ ownedCount: 10,
+ activeCount: 7,
+ })
+ expect(mockCreateBot).not.toHaveBeenCalled()
+ })
+
+ it("maps the database race backstop to a fresh capacity conflict", async () => {
+ mockCreateBot.mockRejectedValue(new Error("BOT_ENTITLEMENT_LIMIT_REACHED"))
+ mockGetBotCapacitySummary
+ .mockResolvedValueOnce({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 2,
+ activeCount: 2,
+ })
+ .mockResolvedValueOnce({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 3,
+ activeCount: 3,
+ })
+
+ const res = await POST(postReq(base()), ctx)
+
+ expect(res.status).toBe(409)
+ await expect(res.json()).resolves.toMatchObject({
+ error: "BOT_LIMIT_REACHED",
+ plan: "free",
+ limit: 3,
+ ownedCount: 3,
+ activeCount: 3,
+ })
+ })
+
+ it("rethrows creation failures that are not entitlement conflicts", async () => {
+ mockCreateBot.mockRejectedValue(new Error("D1 unavailable"))
+
+ await expect(POST(postReq(base()), ctx)).rejects.toThrow("D1 unavailable")
+ })
+
it("persists a supported capability-backed reasoning effort", async () => {
mockGetMachineForOwner.mockResolvedValue({
id: "mac1",
@@ -223,6 +290,12 @@ describe("GET /api/community/bots — heatmap activity", () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map())
+ mockGetBotCapacitySummary.mockResolvedValue({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 0,
+ activeCount: 0,
+ })
})
it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {
@@ -257,7 +330,13 @@ describe("GET /api/community/bots — heatmap activity", () => {
mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
- expect((await res.json()) as { bots: unknown[] }).toEqual({ bots: [] })
+ expect((await res.json()) as { bots: unknown[] }).toEqual({
+ bots: [],
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 0,
+ activeCount: 0,
+ })
})
it("returns 30 oldest-to-newest usage days with nullable metrics and capability", async () => {
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index cf9355cc8..2b668ca09 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -2,7 +2,6 @@ import { NextRequest } from "next/server"
import {
queries,
CommunityBotCreateRequestSchema,
- COMMUNITY_BOT_LIMIT_PER_OWNER,
DAILY_TOKEN_USAGE_WINDOW_DAYS,
calendarDayKeyDaysAgo,
dayKeyInTimeZone,
@@ -31,7 +30,10 @@ export function tokenUsageDayWindow(now: Date, timeZone: string | null | undefin
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
- const bots = await queries.communityBot.listBotsForOwner(db, ctx.userId)
+ const [bots, capacity] = await Promise.all([
+ queries.communityBot.listBotsForOwner(db, ctx.userId),
+ queries.productPlan.getBotCapacitySummary(db, ctx.userId),
+ ])
// Attach each bot's last-30-day activity for the my-bots heatmap. One batched
// read scoped to the owner's bots (no N+1); bots with no rows default to [].
// The FE pads missing days to zero cells, so an empty array is the normal
@@ -77,7 +79,14 @@ export const GET = withAuth(async (_req, ctx) => {
},
}
})
- return writeJSON({ bots: withActivity })
+ return writeJSON({
+ bots: withActivity,
+ plan: capacity.plan,
+ isFounder: capacity.isFounder,
+ limit: capacity.limit,
+ ownedCount: capacity.ownedCount,
+ activeCount: capacity.activeCount,
+ })
})
export const POST = withAuth(async (req: NextRequest, ctx) => {
@@ -86,10 +95,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- // Cap check — anti-abuse floor, not a UX cap.
- const n = await queries.communityBot.countLiveBotsForOwner(db, ctx.userId)
- if (n >= COMMUNITY_BOT_LIMIT_PER_OWNER) {
- return writeError("BOT_LIMIT_REACHED", 409)
+ let capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)
+ if (capacity.ownedCount >= capacity.limit) {
+ return writeJSON({
+ error: "BOT_LIMIT_REACHED",
+ plan: capacity.plan.id,
+ planDisplayName: capacity.plan.displayName,
+ limit: capacity.limit,
+ ownedCount: capacity.ownedCount,
+ activeCount: capacity.activeCount,
+ }, 409)
}
// Machine must be owned by caller AND runtime must be in its availableRuntimes
@@ -125,16 +140,30 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError(`reasoning effort ${effort} is not supported by this runtime/model`, 400)
}
- const created = await queries.communityBot.createBot(db, {
- ownerId: ctx.userId,
- name: body.name,
- description: body.description,
- machineId: body.machineId,
- runtime: body.runtime,
- image: body.image ?? null,
- modelName,
- reasoningEffort: effortResolution.canonicalEffort,
- })
+ let created: Awaited<ReturnType<typeof queries.communityBot.createBot>>
+ try {
+ created = await queries.communityBot.createBot(db, {
+ ownerId: ctx.userId,
+ name: body.name,
+ description: body.description,
+ machineId: body.machineId,
+ runtime: body.runtime,
+ image: body.image ?? null,
+ modelName,
+ reasoningEffort: effortResolution.canonicalEffort,
+ })
+ } catch (error) {
+ if (!queries.communityBot.isBotEntitlementLimitError(error)) throw error
+ capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)
+ return writeJSON({
+ error: "BOT_LIMIT_REACHED",
+ plan: capacity.plan.id,
+ planDisplayName: capacity.plan.displayName,
+ limit: capacity.limit,
+ ownedCount: capacity.ownedCount,
+ activeCount: capacity.activeCount,
+ }, 409)
+ }
// The bot's owner is the authenticated caller — resolve their handle to
// carry in the bot:added push so the daemon can tell the agent who owns it.
@@ -196,6 +225,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
modelName,
reasoningEffort: effortResolution.canonicalEffort,
runtimeConfigRevision: 0,
+ isActive: true,
},
},
201,
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
index f221a5585..13368d8c9 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
@@ -80,7 +80,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockCreatePendingAttachment.mockResolvedValue({
id: "att_1",
filename: "hi.png",
diff --git a/src/web/src/app/api/community/daemon/activate/route.test.ts b/src/web/src/app/api/community/daemon/activate/route.test.ts
index 5fd54c857..50dbad90a 100644
--- a/src/web/src/app/api/community/daemon/activate/route.test.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.test.ts
@@ -8,7 +8,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
// The activate route also broadcasts machine.created — stub that.
vi.mock("@/lib/broadcast", () => ({
@@ -37,6 +37,7 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
+ productPlan: { ...actual.queries.productPlan, getMachineCapacitySummary: vi.fn(async () => ({ plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, onlineCount: 0 })) },
communityMachine: {
getMachineByIdForUser: (...a: unknown[]) => mockGetMachine(...a),
toSummary: (row: any) => ({
@@ -223,4 +224,18 @@ describe("POST /api/community/daemon/activate", () => {
error: "activate failed: D1_ERROR: database is locked",
})
})
+ it("marks quota denial as not committed and does not notify a creation", async () => {
+ const { queries } = await import("@alook/shared")
+ const capacity = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 1, onlineCount: 0 }
+ mockActivate.mockRejectedValue(new queries.productPlan.MachineLimitReachedError(capacity))
+ const response = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_pairtoken" }))
+ expect(response.status).toBe(409)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_REACHED", machineCapacity: capacity, sessionOutcome: "not_committed" })
+ expect(mockBroadcast).not.toHaveBeenCalled()
+ mockActivate.mockRejectedValue(new queries.productPlan.ProductEntitlementUnavailableError("machines.max", "entitlement_missing"))
+ const unavailable = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_pairtoken" }))
+ expect(unavailable.status).toBe(503)
+ expect(await unavailable.json()).toEqual({ error: "MACHINE_LIMIT_UNAVAILABLE", sessionOutcome: "not_committed" })
+ })
+
})
diff --git a/src/web/src/app/api/community/daemon/activate/route.ts b/src/web/src/app/api/community/daemon/activate/route.ts
index 0de048210..925afd221 100644
--- a/src/web/src/app/api/community/daemon/activate/route.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.ts
@@ -7,7 +7,7 @@ import {
type CommunityDaemonActivateResponse,
type CommunityMachineCreated,
} from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { broadcastToUser } from "@/lib/broadcast"
import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
import { withCommunityPairingToken } from "@/lib/middleware/community-pairing-token"
@@ -39,7 +39,7 @@ export const POST = withCommunityPairingToken(async (req, ctx) => {
)
}
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
try {
// Map wire field `runtimeReport` → persisted `availableRuntimes` so the
@@ -106,6 +106,12 @@ export const POST = withCommunityPairingToken(async (req, ctx) => {
}
return NextResponse.json(body)
} catch (err) {
+ if (err instanceof queries.productPlan.MachineLimitReachedError) {
+ return NextResponse.json({ error: "MACHINE_LIMIT_REACHED", machineCapacity: err.capacity, sessionOutcome: "not_committed" }, { status: 409 })
+ }
+ if (err instanceof queries.productPlan.ProductEntitlementUnavailableError) {
+ return NextResponse.json({ error: "MACHINE_LIMIT_UNAVAILABLE", sessionOutcome: "not_committed" }, { status: 503 })
+ }
if (err instanceof queries.communityMachineSession.MachineSessionRotationError) {
const errorBody = { error: err.message, sessionOutcome: err.sessionOutcome }
switch (err.kind) {
diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts
index 2273a01a9..a8b23f23b 100644
--- a/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts
+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts
@@ -52,7 +52,7 @@ describe("POST /api/community/daemon/enroll-agent", () => {
ownerUserId: "u_1",
deletedAt: null,
})
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "claude", isActive: true })
})
it("returns 200 + runnerKey on happy path", async () => {
@@ -162,10 +162,25 @@ describe("POST /api/community/daemon/enroll-agent", () => {
userId: "u_1",
machineId: "cm_1",
})
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_other", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_other", runtime: "claude", isActive: true })
const res = await POST(req({ agentId: "agent_a" }, { Authorization: "Bearer cmk_ok" }))
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: "bot not on this machine" })
expect(mockMint).not.toHaveBeenCalled()
})
+
+ it("404 without minting a runner key when the bot is inactive", async () => {
+ mockFindCred.mockResolvedValue({
+ credentialId: "cmk_ok",
+ userId: "u_1",
+ machineId: "cm_1",
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "claude", isActive: false })
+
+ const res = await POST(req({ agentId: "agent_a" }, { Authorization: "Bearer cmk_ok" }))
+
+ expect(res.status).toBe(404)
+ expect(await res.json()).toEqual({ error: "bot not on this machine" })
+ expect(mockMint).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
index 68b5145f1..2c350e3a2 100644
--- a/src/web/src/app/api/community/daemon/enroll-agent/route.ts
+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
@@ -56,7 +56,7 @@ export const POST = withCommunityDaemonAuth(async (req, ctx) => {
() => queries.communityBot.getBotBinding(db, parsed.data.agentId),
{ route: "community/daemon/enroll-agent:binding" }
)
- if (!binding || binding.machineId !== ctx.machineId) {
+ if (!binding || !binding.isActive || binding.machineId !== ctx.machineId) {
return NextResponse.json({ error: "bot not on this machine" }, { status: 404 })
}
diff --git a/src/web/src/app/api/community/friends/accepted/route.bot.test.ts b/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
index 385f41e57..4c6e5208f 100644
--- a/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
@@ -58,7 +58,7 @@ describe("GET /api/community/friends/accepted — bot arm (folds listFriends acc
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: BOT })
mockGetUserInternal.mockResolvedValue({ id: BOT, isBot: true, deletedAt: null, ownerUserId: "owner_1" })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockWsDoFetch.mockResolvedValue({ ok: true, json: async () => ({ online: ["u_alice"] }) })
})
diff --git a/src/web/src/app/api/community/friends/blocked/route.test.ts b/src/web/src/app/api/community/friends/blocked/route.test.ts
index 7f6baafd8..3f43a2713 100644
--- a/src/web/src/app/api/community/friends/blocked/route.test.ts
+++ b/src/web/src/app/api/community/friends/blocked/route.test.ts
@@ -53,7 +53,7 @@ describe("GET /api/community/friends/blocked", () => {
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_zoe" })
mockGetUserInternal.mockResolvedValue({ id: "bot_zoe", isBot: true, deletedAt: null, ownerUserId: "owner_1" })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
})
it("bot → 403 BEFORE any blocked query (owner-only, zero existence leak)", async () => {
diff --git a/src/web/src/app/api/community/friends/pending/route.bot.test.ts b/src/web/src/app/api/community/friends/pending/route.bot.test.ts
index e64c233bd..8db300896 100644
--- a/src/web/src/app/api/community/friends/pending/route.bot.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.bot.test.ts
@@ -51,7 +51,7 @@ describe("GET /api/community/friends/pending — bot arm (folds listFriends pend
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: BOT })
mockGetUserInternal.mockResolvedValue({ id: BOT, isBot: true, deletedAt: null, ownerUserId: "owner_1" })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockWsDoFetch.mockResolvedValue({ ok: true, json: async () => ({ online: ["u_bob"] }) })
})
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
index e54d7d286..e114fb9a4 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
@@ -71,7 +71,7 @@ describe("POST /api/community/invites/[token]/join — bot path", () => {
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
})
it("401 without Authorization", async () => {
diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
index 1d04de612..f29b4e97d 100644
--- a/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.test.ts
@@ -3,10 +3,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
const mockCreateReconnectPairingToken = vi.fn()
const mockRevokeRunnerKeysForMachine = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
-vi.mock("@alook/shared", () => ({
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
queries: {
+ productPlan: actual.queries.productPlan,
communityMachine: {
createReconnectPairingToken: (...args: unknown[]) =>
mockCreateReconnectPairingToken(...args),
@@ -14,7 +17,7 @@ vi.mock("@alook/shared", () => ({
mockRevokeRunnerKeysForMachine(...args),
},
},
-}))
+}})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) =>
@@ -36,6 +39,7 @@ vi.mock("@/lib/middleware/helpers", async () => {
})
import { POST } from "./route"
+import { queries } from "@alook/shared"
describe("POST /api/community/machines/[id]/reconnect", () => {
beforeEach(() => {
@@ -70,4 +74,20 @@ describe("POST /api/community/machines/[id]/reconnect", () => {
const response = await POST({} as any, { params: { id: "cm_other" } } as any)
expect(response.status).toBe(404)
})
+ it("returns authoritative capacity on quota denial", async () => {
+ const capacity = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 2, onlineCount: 1 }
+ mockCreateReconnectPairingToken.mockRejectedValue(new queries.productPlan.MachineLimitReachedError(capacity))
+ const response = await POST({} as any, { params: { id: "cm_abcdefgh" } } as any)
+ expect(response.status).toBe(409)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_REACHED", machineCapacity: capacity })
+ })
+ it("fails closed on unavailable entitlement and propagates unexpected failure", async () => {
+ mockCreateReconnectPairingToken.mockRejectedValue(new queries.productPlan.ProductEntitlementUnavailableError("machines.max", "entitlement_missing"))
+ const response = await POST({} as any, { params: { id: "cm_abcdefgh" } } as any)
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_UNAVAILABLE" })
+ mockCreateReconnectPairingToken.mockRejectedValue(new Error("database unavailable"))
+ await expect(POST({} as any, { params: { id: "cm_abcdefgh" } } as any)).rejects.toThrow("database unavailable")
+ })
+
})
diff --git a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts b/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
index 3006b623c..f7570c386 100644
--- a/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/reconnect/route.ts
@@ -1,5 +1,5 @@
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
@@ -8,7 +8,7 @@ import { writeError, writeJSON } from "@/lib/middleware/helpers"
// rotation happens only when the exact-machine reconnect command activates
// this token.
export const POST = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const id = ctx.params?.id as string
if (!id) return writeError("machine id is required", 400)
@@ -20,6 +20,12 @@ export const POST = withAuth(async (_req, ctx) => {
)
return writeJSON({ tokenId: token.tokenId, expiresAt: token.expiresAt })
} catch (err) {
+ if (err instanceof queries.productPlan.MachineLimitReachedError) {
+ return writeJSON({ error: "MACHINE_LIMIT_REACHED", machineCapacity: err.capacity }, 409)
+ }
+ if (err instanceof queries.productPlan.ProductEntitlementUnavailableError) {
+ return writeJSON({ error: "MACHINE_LIMIT_UNAVAILABLE" }, 503)
+ }
if (err instanceof Error && /not owned by user/.test(err.message)) {
return writeError("machine not found", 404)
}
diff --git a/src/web/src/app/api/community/machines/pair/route.test.ts b/src/web/src/app/api/community/machines/pair/route.test.ts
index eaa2d8957..91f2e0f17 100644
--- a/src/web/src/app/api/community/machines/pair/route.test.ts
+++ b/src/web/src/app/api/community/machines/pair/route.test.ts
@@ -2,15 +2,18 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockCreatePairingToken = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
-vi.mock("@alook/shared", () => ({
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
queries: {
+ productPlan: actual.queries.productPlan,
communityMachine: {
createPairingToken: (...a: unknown[]) => mockCreatePairingToken(...a),
},
},
-}))
+}})
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) =>
@@ -26,6 +29,7 @@ vi.mock("@/lib/middleware/helpers", () => {
})
import { POST } from "./route"
+import { queries } from "@alook/shared"
describe("POST /api/community/machines/pair", () => {
beforeEach(() => {
@@ -43,4 +47,20 @@ describe("POST /api/community/machines/pair", () => {
const body = await res.json()
expect(body).toEqual({ tokenId: "pair_tok_1", expiresAt: "2026-07-09T00:00:00.000Z" })
})
+ it("returns authoritative capacity on quota denial", async () => {
+ const capacity = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 2, onlineCount: 1 }
+ mockCreatePairingToken.mockRejectedValue(new queries.productPlan.MachineLimitReachedError(capacity))
+ const response = await POST({} as any, {} as any)
+ expect(response.status).toBe(409)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_REACHED", machineCapacity: capacity })
+ })
+ it("fails closed on unavailable entitlement and propagates unexpected failure", async () => {
+ mockCreatePairingToken.mockRejectedValue(new queries.productPlan.ProductEntitlementUnavailableError("machines.max", "entitlement_missing"))
+ const response = await POST({} as any, {} as any)
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_UNAVAILABLE" })
+ mockCreatePairingToken.mockRejectedValue(new Error("database unavailable"))
+ await expect(POST({} as any, {} as any)).rejects.toThrow("database unavailable")
+ })
+
})
diff --git a/src/web/src/app/api/community/machines/pair/route.ts b/src/web/src/app/api/community/machines/pair/route.ts
index ccc0d3582..14a266c51 100644
--- a/src/web/src/app/api/community/machines/pair/route.ts
+++ b/src/web/src/app/api/community/machines/pair/route.ts
@@ -1,10 +1,20 @@
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
export const POST = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
- const { tokenId, expiresAt } = await queries.communityMachine.createPairingToken(db, ctx.userId)
- return writeJSON({ tokenId, expiresAt })
+ const db = getPrimaryDb(ctx.env.DB)
+ try {
+ const { tokenId, expiresAt } = await queries.communityMachine.createPairingToken(db, ctx.userId)
+ return writeJSON({ tokenId, expiresAt })
+ } catch (error) {
+ if (error instanceof queries.productPlan.MachineLimitReachedError) {
+ return writeJSON({ error: "MACHINE_LIMIT_REACHED", machineCapacity: error.capacity }, 409)
+ }
+ if (error instanceof queries.productPlan.ProductEntitlementUnavailableError) {
+ return writeJSON({ error: "MACHINE_LIMIT_UNAVAILABLE" }, 503)
+ }
+ throw error
+ }
})
diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.ts
index 48bef9174..205d8876c 100644
--- a/src/web/src/app/api/community/machines/route.test.ts
+++ b/src/web/src/app/api/community/machines/route.test.ts
@@ -4,13 +4,14 @@ import { NextRequest } from "next/server"
const mockListMachinesForUser = vi.fn()
const mockListMachineBackendQuotasForUser = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
queries: {
+ productPlan: { ...actual.queries.productPlan, resolveMachinesMaxForUser: vi.fn(async () => ({ plan: { id: "free", displayName: "Free" }, isFounder: false, value: 1 })) },
communityMachine: {
listMachinesForUser: (...args: unknown[]) => mockListMachinesForUser(...args),
listMachineBackendQuotasForUser: (...args: unknown[]) =>
@@ -33,6 +34,7 @@ vi.mock("@/lib/middleware/helpers", async () => {
})
import { GET } from "./route"
+import { queries } from "@alook/shared"
describe("GET /api/community/machines — provider quota", () => {
beforeEach(() => {
@@ -181,6 +183,22 @@ describe("GET /api/community/machines — provider quota", () => {
expect(mockListMachineBackendQuotasForUser).toHaveBeenCalledWith(expect.anything(), "u1")
})
+ it("distinguishes explicitly unsupported runtimes from unknown runtime capabilities", async () => {
+ mockListMachinesForUser.mockResolvedValue([{
+ id: "cm_1", status: "online",
+ availableRuntimes: ["opencode", "pi", "custom-acp"].map((id) => ({ id, status: "healthy" })),
+ }])
+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map())
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ expect(response.status).toBe(200)
+ expect((await response.json()).machines[0].quota).toEqual([
+ ["opencode", "unsupported"], ["pi", "unsupported"], ["custom-acp", "unknown"],
+ ].map(([agentBackendId, capability]) => ({
+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId },
+ capability, runtimeState: "healthy", snapshot: { status: "pending" },
+ })))
+ })
+
it("marks an expired available observation stale and machine runtimes offline", async () => {
mockListMachinesForUser.mockResolvedValue([{
id: "cm_1",
@@ -218,4 +236,19 @@ describe("GET /api/community/machines — provider quota", () => {
snapshot: { status: "stale", observedAt: "2020-01-01T00:00:00.000Z" },
})
})
+ it("uses the listed rows for owned and online counts", async () => {
+ mockListMachinesForUser.mockResolvedValue([{ id: "a", status: "online", availableRuntimes: [] }, { id: "b", status: "offline", availableRuntimes: [] }])
+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map())
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ expect((await response.json()).machineCapacity).toEqual({ plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 2, onlineCount: 1 })
+ })
+ it("returns 503 when machine entitlement is missing", async () => {
+ vi.mocked(queries.productPlan.resolveMachinesMaxForUser).mockRejectedValueOnce(new queries.productPlan.ProductEntitlementUnavailableError("machines.max", "entitlement_missing"))
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "MACHINE_LIMIT_UNAVAILABLE" })
+ mockListMachinesForUser.mockRejectedValueOnce(new Error("db unavailable"))
+ await expect(GET(new NextRequest("http://localhost/api/community/machines"))).rejects.toThrow("db unavailable")
+ })
+
})
diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.ts
index 508da6b04..fdd9b3e4d 100644
--- a/src/web/src/app/api/community/machines/route.ts
+++ b/src/web/src/app/api/community/machines/route.ts
@@ -1,48 +1,65 @@
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
export const GET = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
- const machines = await queries.communityMachine.listMachinesForUser(db, ctx.userId)
- const quotaByMachine = await queries.communityMachine.listMachineBackendQuotasForUser(db, ctx.userId)
- const now = Date.now()
- const withQuota = machines.map((machine) => {
- const stored = quotaByMachine.get(machine.id) ?? []
- const quota = machine.availableRuntimes.map((runtime) => {
- const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok"
- ? "supported" as const
- : runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi"
- ? "unsupported" as const
- : "unknown" as const
- const runtimeState = machine.status === "offline"
- ? "offline" as const
- : runtime.status === "unhealthy"
- ? "unhealthy" as const
- : "healthy" as const
- const current = stored.find((entry) => entry.quota.agentBackendId === runtime.id)
- const observation = current?.quota.observation
- const snapshot = !current || !observation
- ? { status: "pending" as const }
- : observation.status === "error"
- ? { status: "error" as const, code: observation.code }
- : {
- status: now <= Date.parse(current.observedAt) + observation.freshForSeconds * 1_000
- ? "available" as const
- : "stale" as const,
- observedAt: current.observedAt,
- ...(observation.planName ? { planName: observation.planName } : {}),
- limits: observation.limits,
- }
- return {
- scope: { kind: "machine_backend" as const, machineId: machine.id, agentBackendId: runtime.id },
- capability,
- runtimeState,
- snapshot,
- }
+ const db = getPrimaryDb(ctx.env.DB)
+ try {
+ const [machines, entitlement] = await Promise.all([
+ queries.communityMachine.listMachinesForUser(db, ctx.userId),
+ queries.productPlan.resolveMachinesMaxForUser(db, ctx.userId),
+ ])
+ const machineCapacity = {
+ plan: entitlement.plan,
+ isFounder: entitlement.isFounder,
+ limit: entitlement.value,
+ ownedCount: machines.length,
+ onlineCount: machines.filter((machine) => machine.status === "online").length,
+ }
+ const quotaByMachine = await queries.communityMachine.listMachineBackendQuotasForUser(db, ctx.userId)
+ const now = Date.now()
+ const withQuota = machines.map((machine) => {
+ const stored = quotaByMachine.get(machine.id) ?? []
+ const quota = machine.availableRuntimes.map((runtime) => {
+ const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok"
+ ? "supported" as const
+ : runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi"
+ ? "unsupported" as const
+ : "unknown" as const
+ const runtimeState = machine.status === "offline"
+ ? "offline" as const
+ : runtime.status === "unhealthy"
+ ? "unhealthy" as const
+ : "healthy" as const
+ const current = stored.find((entry) => entry.quota.agentBackendId === runtime.id)
+ const observation = current?.quota.observation
+ const snapshot = !current || !observation
+ ? { status: "pending" as const }
+ : observation.status === "error"
+ ? { status: "error" as const, code: observation.code }
+ : {
+ status: now <= Date.parse(current.observedAt) + observation.freshForSeconds * 1_000
+ ? "available" as const
+ : "stale" as const,
+ observedAt: current.observedAt,
+ ...(observation.planName ? { planName: observation.planName } : {}),
+ limits: observation.limits,
+ }
+ return {
+ scope: { kind: "machine_backend" as const, machineId: machine.id, agentBackendId: runtime.id },
+ capability,
+ runtimeState,
+ snapshot,
+ }
+ })
+ return { ...machine, quota }
})
- return { ...machine, quota }
- })
- return writeJSON({ machines: withQuota })
+ return writeJSON({ machines: withQuota, machineCapacity })
+ } catch (error) {
+ if (error instanceof queries.productPlan.ProductEntitlementUnavailableError) {
+ return writeJSON({ error: "MACHINE_LIMIT_UNAVAILABLE" }, 503)
+ }
+ throw error
+ }
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
index 2395e1476..22923d165 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
@@ -62,7 +62,7 @@ describe("GET /api/community/servers/[id]/channels — bot arm (folds listChanne
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockListCategoriesByServer.mockResolvedValue([])
})
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
index 657a20a08..9f3654996 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
@@ -75,7 +75,7 @@ describe("GET /api/community/servers/[id]/members — bot arm (folds listMembers
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockFetchOnlineUserIds.mockResolvedValue(new Set<string>())
})
diff --git a/src/web/src/app/api/community/servers/channels/route.bot.test.ts b/src/web/src/app/api/community/servers/channels/route.bot.test.ts
index 8dcccc7e0..bb8e403fc 100644
--- a/src/web/src/app/api/community/servers/channels/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/channels/route.bot.test.ts
@@ -55,7 +55,7 @@ describe("GET /api/community/servers/channels — bot arm (folds listChannels al
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockListCategoriesByServer.mockResolvedValue([])
})
diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.ts
index d9532ac5a..d07f91d68 100644
--- a/src/web/src/app/api/community/servers/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/route.bot.test.ts
@@ -66,7 +66,7 @@ describe("GET /api/community/servers — bot path (folded listServers)", () => {
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockListEligibleUnreadServerIds.mockRejectedValue(new Error("human unread source failed"))
})
diff --git a/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
index 3ae90d806..19b82a950 100644
--- a/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
@@ -71,7 +71,7 @@ describe("POST /api/community/users/me/inbox/ack", () => {
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
index d135bb09d..ce371f587 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
@@ -28,7 +28,9 @@ vi.mock("@alook/shared", async () => {
...actual.queries,
communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
+ communityBot: {
+ getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a),
+ },
communityAgentInbox: {
listAccessVisibleChannelIdsForUser: (...a: unknown[]) => mockListAccessVisibleChannelIdsForUser(...a),
listUnreadMessagesForAgent: (...a: unknown[]) => mockListUnreadMessagesForAgent(...a),
@@ -63,7 +65,7 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
mockToAgentMessages.mockImplementation((_db: unknown, rows: unknown[]) => Promise.resolve(rows))
mockListByMessageIds.mockResolvedValue([])
mockListAccessVisibleChannelIdsForUser.mockResolvedValue(["c_1"])
@@ -80,6 +82,21 @@ describe("POST /api/community/users/me/inbox/pull — bot arm (folds inboxPull)"
expect(res.status).toBe(400)
})
+ it("returns an empty page for an inactive bot without querying or hydrating inbox data", async () => {
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: false })
+
+ const res = await POST(req(undefined, { Authorization: "Bearer crk_abc" }))
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ messages: [], hasMore: false, markedCount: 0 })
+ expect(mockListAccessVisibleChannelIdsForUser).not.toHaveBeenCalled()
+ expect(mockListUnreadMessagesForAgent).not.toHaveBeenCalled()
+ expect(mockCountMarksForUser).not.toHaveBeenCalled()
+ expect(mockListByMessageIds).not.toHaveBeenCalled()
+ expect(mockToAgentMessages).not.toHaveBeenCalled()
+ expect(mockGetBotBinding).toHaveBeenCalledOnce()
+ })
+
it("self-scoped: pull always queries the caller's OWN userId (bot_1), never a body-supplied target", async () => {
mockListUnreadMessagesForAgent.mockResolvedValue([{ id: "m_1" }])
// A body carrying a rogue `userId` must be ignored — the scope comes from the
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
index 3ce3a9a86..2166884ce 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.ts
@@ -25,7 +25,15 @@ const MAX_PULL = 200
export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
- const { userId: botUserId } = gate.bot
+ const { userId: botUserId, isActive } = gate.bot
+
+ // Inactive bots have no inbox surface at all. Gate before visibility,
+ // unread, mark, attachment, or hydration work so an inactive daemon cannot
+ // observe or consume backlog through the REST door. Runner auth already read
+ // this binding flag, so the polling hot path does not pay a duplicate D1 read.
+ if (!isActive) {
+ return NextResponse.json({ messages: [], hasMore: false, markedCount: 0 })
+ }
const db = getDb(ctx.env.DB)
@@ -102,4 +110,4 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
{ route: "community/users/me/inbox/pull:hydrate" },
)
return NextResponse.json({ messages, hasMore, markedCount })
-})
+}, { allowInactiveBot: true })
diff --git a/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
index 6c4d2b676..94f8368b4 100644
--- a/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
@@ -25,7 +25,9 @@ vi.mock("@alook/shared", async () => {
...actual.queries,
communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
+ communityBot: {
+ getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a),
+ },
communityAgentInbox: {
getInboxSnapshotForAgent: (...a: unknown[]) => mockGetInboxSnapshotForAgent(...a),
toInboxRows: (...a: unknown[]) => mockToInboxRows(...a),
@@ -52,7 +54,7 @@ describe("GET /api/community/users/me/inbox/snapshot — bot arm (folds inboxSna
vi.clearAllMocks()
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })
})
it("401 without Authorization (human arm, no session)", async () => {
@@ -81,6 +83,18 @@ describe("GET /api/community/users/me/inbox/snapshot — bot arm (folds inboxSna
expect(mockGetInboxSnapshotForAgent).toHaveBeenCalledWith(expect.anything(), "bot_1")
})
+ it("reports zero pending work for an inactive bot without reading or hydrating the inbox", async () => {
+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: false })
+
+ const res = await GET(req({ Authorization: "Bearer crk_abc" }))
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ rows: [], pendingChannels: 0, pendingMessages: 0 })
+ expect(mockGetInboxSnapshotForAgent).not.toHaveBeenCalled()
+ expect(mockToInboxRows).not.toHaveBeenCalled()
+ expect(mockGetBotBinding).toHaveBeenCalledOnce()
+ })
+
it("loudly rejects an orphan scope without leaking internal ids", async () => {
mockGetInboxSnapshotForAgent.mockResolvedValue([
{ channelId: "dm_channel_internal", latestSenderId: "peer_internal" },
diff --git a/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
index 40dce9510..2d38d03c6 100644
--- a/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.ts
@@ -18,7 +18,14 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor
export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
const gate = requireBot(ctx.actor)
if (!gate.ok) return gate.response
- const { userId: botUserId } = gate.bot
+ const { userId: botUserId, isActive } = gate.bot
+
+ // Match the consuming pull door: inactive bots expose no inbox state and do
+ // not pay the visibility/aggregation/hydration query cost. Runner auth
+ // already loaded the binding state, avoiding a second D1 read on every poll.
+ if (!isActive) {
+ return NextResponse.json({ rows: [], pendingChannels: 0, pendingMessages: 0 })
+ }
const db = getDb(ctx.env.DB)
@@ -36,4 +43,4 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
pendingChannels: rows.length,
pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0),
})
-})
+}, { allowInactiveBot: true })
diff --git a/src/web/src/app/api/pricing/route.test.ts b/src/web/src/app/api/pricing/route.test.ts
new file mode 100644
index 000000000..38cb92155
--- /dev/null
+++ b/src/web/src/app/api/pricing/route.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocked = vi.hoisted(() => ({ listPrices: vi.fn(), getDefaultPlanOffer: vi.fn(), retrieve: vi.fn() }))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_fake" } })) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
+vi.mock("@alook/shared", async (original) => ({
+ ...await original<typeof import("@alook/shared")>(),
+ queries: { billing: mocked },
+}))
+vi.mock("stripe", () => ({ default: class {
+ static createFetchHttpClient() { return {} }
+ prices = { retrieve: mocked.retrieve }
+} }))
+import { GET } from "./route"
+
+const mapping = { priceId: "price_studio", planId: "studio", displayName: "Studio", botLimit: 10, machineLimit: 5, portalConfigurationId: "private_config", sortOrder: 1 }
+const price = { id: "price_studio", active: true, livemode: false, type: "recurring", unit_amount: 2000, currency: "usd", recurring: { interval: "month", interval_count: 1 }, product: { active: true, metadata: { private: "hidden" } } }
+const request = () => GET(new NextRequest("http://localhost/api/pricing"))
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocked.listPrices.mockResolvedValue([mapping])
+ mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "free", displayName: "Free" }, botLimit: 3, machineLimit: 1 })
+ mocked.retrieve.mockResolvedValue(price)
+})
+
+describe("public pricing", () => {
+ it("returns only public fields anonymously from the existing catalog", async () => {
+ const response = await request()
+ expect(response.status).toBe(200)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(response.headers.get("set-cookie")).toBeNull()
+ expect(await response.json()).toEqual({
+ free: { plan: { id: "free", displayName: "Free" }, botLimit: 3, machineLimit: 1 },
+ offers: [{ priceId: "price_studio", plan: { id: "studio", displayName: "Studio" }, botLimit: 10, machineLimit: 5, unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1 }],
+ })
+ expect(mocked.listPrices).toHaveBeenCalledTimes(1)
+ expect(mocked.getDefaultPlanOffer).toHaveBeenCalledTimes(1)
+ expect(mocked.retrieve).toHaveBeenCalledWith("price_studio", { expand: ["product"] })
+ })
+
+ it("uses changed entitlement and Stripe amounts rather than marketing constants", async () => {
+ mocked.listPrices.mockResolvedValue([{ ...mapping, botLimit: 17, machineLimit: 5, planId: "new-plan" }])
+ mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "starter", displayName: "Starter" }, botLimit: 5, machineLimit: 1 })
+ mocked.retrieve.mockResolvedValue({ ...price, unit_amount: 3100, currency: "eur", recurring: { interval: "year", interval_count: 2 } })
+ expect(await (await request()).json()).toMatchObject({ free: { botLimit: 5, machineLimit: 1, plan: { id: "starter" } }, offers: [{ botLimit: 17, machineLimit: 5, unitAmount: 3100, currency: "eur", interval: "year", intervalCount: 2, plan: { id: "new-plan" } }] })
+ })
+
+ it.each([
+ { active: false }, { recurring: null }, { type: "one_time" }, { unit_amount: null },
+ { product: { active: false } }, { product: { deleted: true } },
+ ])("omits unavailable Stripe prices: %j", async (change) => {
+ mocked.retrieve.mockResolvedValue({ ...price, ...change })
+ expect(await (await request()).json()).toMatchObject({ offers: [] })
+ })
+
+ it("returns an empty paid catalog without inventing prices", async () => {
+ mocked.listPrices.mockResolvedValue([])
+ expect(await (await request()).json()).toMatchObject({ offers: [] })
+ expect(mocked.retrieve).not.toHaveBeenCalled()
+ })
+
+ it("fails closed on a Stripe environment mismatch", async () => {
+ mocked.retrieve.mockResolvedValue({ ...price, livemode: true })
+ const response = await request()
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_ENVIRONMENT_MISMATCH" })
+ })
+
+ it.each(["stripe", "default", "invalid quota"])("returns a retryable sanitized error for %s failure", async (failure) => {
+ const log = vi.spyOn(console, "error").mockImplementation(() => {})
+ if (failure === "stripe") mocked.retrieve.mockRejectedValue(new Error("private upstream details"))
+ if (failure === "default") mocked.getDefaultPlanOffer.mockRejectedValue(new Error("DEFAULT_PLAN_UNAVAILABLE"))
+ if (failure === "invalid quota") mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "free", displayName: "Free" }, botLimit: -1 })
+ const response = await request()
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ log.mockRestore()
+ })
+})
diff --git a/src/web/src/app/api/pricing/route.ts b/src/web/src/app/api/pricing/route.ts
new file mode 100644
index 000000000..7d657e494
--- /dev/null
+++ b/src/web/src/app/api/pricing/route.ts
@@ -0,0 +1,12 @@
+import { withEnv } from "@/lib/middleware/env"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { getPublicPricing } from "@/lib/billing/catalog"
+
+export const GET = withEnv(async (_req, ctx) => {
+ try {
+ return billingResponse(await getPublicPricing(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env))
+ } catch (error) {
+ return billingFailure(error, "public_pricing")
+ }
+})
diff --git a/src/web/src/app/api/stripe/webhook/route.ts b/src/web/src/app/api/stripe/webhook/route.ts
new file mode 100644
index 000000000..7a63f0c8c
--- /dev/null
+++ b/src/web/src/app/api/stripe/webhook/route.ts
@@ -0,0 +1,13 @@
+import { withEnv } from "@/lib/middleware/env"
+import { getPrimaryDb } from "@/lib/db"
+import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
+import { handleBillingWebhook } from "@/lib/billing/webhook"
+
+export const POST = withEnv(async (req, ctx) => {
+ try {
+ await handleBillingWebhook(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env, await req.text(), req.headers.get("stripe-signature"))
+ return billingResponse({ received: true })
+ } catch (error) {
+ return billingFailure(error, "webhook")
+ }
+})
diff --git a/src/web/src/app/pricing-concept/page.tsx b/src/web/src/app/pricing-concept/page.tsx
new file mode 100644
index 000000000..c883d7e22
--- /dev/null
+++ b/src/web/src/app/pricing-concept/page.tsx
@@ -0,0 +1,5 @@
+import { permanentRedirect } from "next/navigation"
+
+export default function PricingConceptPage() {
+ permanentRedirect("/pricing")
+}
diff --git a/src/web/src/app/pricing/page.tsx b/src/web/src/app/pricing/page.tsx
new file mode 100644
index 000000000..98b8808bc
--- /dev/null
+++ b/src/web/src/app/pricing/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next"
+import { Suspense } from "react"
+import PricingClient from "./pricing-client"
+
+export const metadata: Metadata = {
+ title: { absolute: "Alook Pricing — Free, Studio, and House Plans" },
+ description: "Compare Free, Studio, and House plans for your active bots. Bring your own AI models and runtime.",
+ alternates: { canonical: "/pricing" },
+}
+
+export default function PricingPage() {
+ return <Suspense fallback={<p role="status" className="p-8">Loading plans…</p>}><PricingClient /></Suspense>
+}
diff --git a/src/web/src/app/pricing/pricing-client.dom.test.tsx b/src/web/src/app/pricing/pricing-client.dom.test.tsx
new file mode 100644
index 000000000..d1d247137
--- /dev/null
+++ b/src/web/src/app/pricing/pricing-client.dom.test.tsx
@@ -0,0 +1,126 @@
+import { beforeEach, expect, it, vi } from "vitest"
+import { render, setupUser, waitFor } from "@/test/react-dom-harness"
+import PricingClient from "./pricing-client"
+
+vi.mock("./pricing.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))
+
+const state = vi.hoisted(() => ({
+ session: { data: null as null | { user: { id: string } }, isPending: false, error: null },
+ search: new URLSearchParams(),
+ push: vi.fn(), api: vi.fn(), checkout: vi.fn(), portal: vi.fn(), refresh: vi.fn(),
+ billing: {} as Record<string, unknown>,
+}))
+vi.mock("@/lib/auth-client", () => ({ useSession: () => state.session }))
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: state.push }), useSearchParams: () => state.search }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: state.api }))
+vi.mock("@/hooks/community/use-billing", () => ({ useBilling: () => ({ ...state.billing, checkout: state.checkout, portal: state.portal, refresh: state.refresh }) }))
+
+const offers = [
+ { plan: { id: "studio", displayName: "Studio" }, botLimit: 10, machineLimit: 5, priceId: "price_server_studio", unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1 },
+ { plan: { id: "house", displayName: "House" }, botLimit: 40, machineLimit: 10, priceId: "price_server_house", unitAmount: 4000, currency: "usd", interval: "month", intervalCount: 1 },
+]
+const catalog = { free: { plan: { id: "free", displayName: "Free" }, botLimit: 3, machineLimit: 1 }, offers }
+const free = { plan: catalog.free.plan, isFounder: false, subscription: null, offers }
+const subscription = { plan: offers[0].plan, status: "active", currentPeriodEnd: null, cancelAt: null, scheduledChange: null }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ state.session = { data: null, isPending: false, error: null }
+ state.search = new URLSearchParams()
+ state.api.mockResolvedValue(catalog)
+ state.billing = { data: undefined, isPending: false, isBusy: false, isError: false, actionError: null }
+})
+
+it("sends guests to sign-in with a valid selected plan preserved", async () => {
+ const view = render(<PricingClient />)
+ await setupUser().click(await view.findByRole("button", { name: "Choose Studio" }))
+ const url = new URL(state.push.mock.calls[0][0], "https://alook.ai")
+ expect(url.pathname).toBe("/sign-in")
+ expect(url.searchParams.get("redirect")).toBe("/pricing?plan=studio")
+ expect(state.checkout).not.toHaveBeenCalled()
+})
+
+it("preserves selected plan after sign-in without automatically starting payment", async () => {
+ state.session.data = { user: { id: "buyer" } }
+ state.billing.data = free
+ state.search = new URLSearchParams({ plan: "studio", priceId: "price_attacker" })
+ const view = render(<PricingClient />)
+ expect(await view.findByText("Studio selected. Choose it below to continue.")).toBeInTheDocument()
+ expect(state.checkout).not.toHaveBeenCalled()
+ await waitFor(() => expect(view.getByRole("button", { name: "Choose Studio" })).toBeEnabled())
+ await setupUser().click(view.getByRole("button", { name: "Choose Studio" }))
+ expect(state.checkout).toHaveBeenCalledWith("price_server_studio")
+})
+
+it("uses the authenticated offer price and Portal for subscription changes", async () => {
+ state.session.data = { user: { id: "subscriber" } }
+ state.billing.data = { ...free, plan: offers[0].plan, subscription, offers: [offers[0], { ...offers[1], priceId: "price_current_house" }] }
+ const view = render(<PricingClient />)
+ await setupUser().click(await view.findByRole("button", { name: "Choose House" }))
+ expect(state.portal).toHaveBeenCalledWith("price_current_house")
+ expect(state.checkout).not.toHaveBeenCalled()
+ expect(view.getByRole("button", { name: "Current plan" })).toBeDisabled()
+ await setupUser().click(view.getByRole("button", { name: "Manage cancellation" }))
+ expect(state.portal).toHaveBeenLastCalledWith()
+})
+
+it.each(["Studio", "House"])("requires explicit Founder confirmation for %s", async (name) => {
+ state.session.data = { user: { id: "founder" } }
+ state.billing.data = { ...free, plan: offers[1].plan, isFounder: true }
+ const view = render(<PricingClient />)
+ const user = setupUser()
+ await waitFor(() => expect(view.getByRole("button", { name: `Choose ${name}` })).toBeEnabled())
+ await user.click(view.getByRole("button", { name: `Choose ${name}` }))
+ expect(await view.findByRole("dialog")).toHaveTextContent("permanently ends your Founder access")
+ expect(state.checkout).not.toHaveBeenCalled()
+ await user.click(view.getByRole("button", { name: "Keep Founder" }))
+ await waitFor(() => expect(view.queryByRole("dialog")).not.toBeInTheDocument())
+ expect(state.checkout).not.toHaveBeenCalled()
+ await user.click(view.getByRole("button", { name: `Choose ${name}` }))
+ await user.click(view.getByRole("button", { name: "Continue to checkout" }))
+ expect(state.checkout).toHaveBeenCalledTimes(1)
+ expect(state.checkout).toHaveBeenCalledWith(offers.find((offer) => offer.plan.displayName === name)!.priceId, true)
+ expect(state.portal).not.toHaveBeenCalled()
+})
+
+it("disables scheduled changes", async () => {
+ state.session.data = { user: { id: "subscriber" } }
+ state.billing.data = { ...free, plan: offers[1].plan, subscription: { ...subscription, plan: offers[1].plan, scheduledChange: { plan: offers[0].plan, effectiveAt: "2027-01-01T00:00:00Z" } } }
+ const view = render(<PricingClient />)
+ expect(await view.findByRole("button", { name: "Scheduled" })).toBeDisabled()
+})
+
+it("fails closed on a catalog error and supports retry", async () => {
+ state.api.mockRejectedValueOnce(new Error("offline"))
+ const view = render(<PricingClient />)
+ expect(await view.findByRole("alert")).toHaveTextContent("Couldn't load plans")
+ expect(view.getByTestId("pricing-choose-studio")).toBeDisabled()
+ await setupUser().click(view.getByRole("button", { name: "Try again" }))
+ await waitFor(() => expect(view.getByRole("button", { name: "Choose Studio" })).toBeEnabled())
+})
+
+it("does not invent purchasable offers when the catalog is empty", async () => {
+ state.api.mockResolvedValue({ ...catalog, offers: [] })
+ state.search = new URLSearchParams({ plan: "unknown" })
+ const view = render(<PricingClient />)
+ await waitFor(() => expect(view.getByRole("button", { name: "Start free" })).toBeEnabled())
+ expect(view.getAllByRole("button", { name: "Unavailable" })).toHaveLength(2)
+ expect(view.queryByText(/selected/)).not.toBeInTheDocument()
+})
+
+it("does not allow stale public prices to initiate purchase when account loading failed", async () => {
+ state.session.data = { user: { id: "buyer" } }
+ state.billing = { ...state.billing, isError: true }
+ const view = render(<PricingClient />)
+ await view.findByRole("alert")
+ expect(view.getByTestId("pricing-choose-studio")).toBeDisabled()
+ expect(state.checkout).not.toHaveBeenCalled()
+})
+
+
+it("shows machine allowances supplied by the catalog", async () => {
+ state.api.mockResolvedValue({ ...catalog, offers: [{ ...offers[0], machineLimit: 7 }, offers[1]] })
+ const ui = render(<PricingClient />)
+ expect(await ui.findByText((_text, el) => el?.tagName === "P" && el.textContent === "Up to 7 online machines")).toBeInTheDocument()
+ expect(ui.getByText((_text, el) => el?.tagName === "P" && el.textContent === "Up to 1 online machine")).toBeInTheDocument()
+})
diff --git a/src/web/src/app/pricing/pricing-client.tsx b/src/web/src/app/pricing/pricing-client.tsx
new file mode 100644
index 000000000..daa160f2b
--- /dev/null
+++ b/src/web/src/app/pricing/pricing-client.tsx
@@ -0,0 +1,101 @@
+"use client"
+
+import { useState } from "react"
+import { useRouter, useSearchParams } from "next/navigation"
+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
+import { PublicPricingSchema, type PublicPricing, type BillingOffer } from "@alook/shared"
+import { useSession } from "@/lib/auth-client"
+import { apiFetch } from "@/lib/api/client"
+import { useBilling } from "@/hooks/community/use-billing"
+import { FounderPlanChangeDialog } from "@/components/community/billing/founder-plan-change-dialog"
+import { PricingView } from "./pricing-view"
+
+function PricingContent({ signedIn, sessionPending, sessionError }: { signedIn: boolean; sessionPending: boolean; sessionError: boolean }) {
+ const router = useRouter()
+ const search = useSearchParams()
+ const catalog = useQuery({
+ queryKey: ["public-pricing"],
+ queryFn: async ({ signal }) => PublicPricingSchema.parse(await apiFetch<unknown>("/api/pricing", { signal })),
+ staleTime: 30_000,
+ retry: false,
+ })
+ const billing = useBilling(null, signedIn)
+ const summary = signedIn ? billing.data : undefined
+ const [founderOffer, setFounderOffer] = useState<BillingOffer | null>(null)
+ const paymentOffer = (plan: string) => summary?.offers.find((item) => item.plan.id === plan)
+ const offer = (plan: string) => paymentOffer(plan) ?? catalog.data?.offers.find((item) => item.plan.id === plan)
+ const selected = offer(search.get("plan") ?? "")
+ const busy = sessionPending || billing.isBusy || catalog.isPending || (signedIn && billing.isPending)
+ const unavailable = sessionError || catalog.isError || (signedIn && billing.isError)
+ const disabled = (plan: string) => busy || unavailable || (plan !== "free" && (
+ !offer(plan) || (signedIn && !paymentOffer(plan)) || (!summary?.isFounder && summary?.plan.id === plan) || summary?.subscription?.scheduledChange?.plan.id === plan
+ ))
+ const label = (plan: string) => {
+ if (busy) return "Loading…"
+ if (plan === "free") return summary?.subscription && !summary.isFounder ? "Manage cancellation" : signedIn ? "Open Alook" : "Start free"
+ if (summary?.subscription?.scheduledChange?.plan.id === plan) return "Scheduled"
+ if (!summary?.isFounder && summary?.plan.id === plan) return "Current plan"
+ const item = offer(plan)
+ return item ? `Choose ${item.plan.displayName}` : "Unavailable"
+ }
+ const choose = (plan: string) => {
+ if (disabled(plan)) return
+ if (!signedIn) {
+ const destination = plan === "free" ? "/c/me/bots" : `/pricing?${new URLSearchParams({ plan })}`
+ router.push(`/sign-in?${new URLSearchParams({ redirect: destination })}`)
+ return
+ }
+ if (plan === "free") {
+ if (summary?.subscription && !summary.isFounder) void billing.portal()
+ else router.push("/c/me/bots")
+ return
+ }
+ const item = paymentOffer(plan)
+ if (!item) return
+ if (summary?.isFounder) { setFounderOffer(item); return }
+ void (summary?.subscription ? billing.portal(item.priceId) : billing.checkout(item.priceId))
+ }
+ const message = summary?.isFounder
+ ? `Your Founder plan includes permanent ${summary.plan.displayName} access.`
+ : selected ? `${selected.plan.displayName} selected. Choose it below to continue.`
+ : summary ? `Your current plan: ${summary.plan.displayName}.` : ""
+ const error = sessionError ? "Couldn't check your sign-in status. Reload this page to try again."
+ : unavailable ? "Couldn't load plans. Try again before choosing a plan."
+ : billing.actionError
+ const retry = () => {
+ if (sessionError) { window.location.reload(); return }
+ void catalog.refetch()
+ if (signedIn) billing.refresh()
+ }
+ return <>
+ <PricingView controller={{ catalog: catalog.data, offer, disabled, label, choose, message, error, retry }} />
+ <FounderPlanChangeDialog offer={founderOffer} busy={billing.isBusy} onCancel={() => setFounderOffer(null)} onConfirm={() => {
+ if (!founderOffer || disabled(founderOffer.plan.id)) return
+ const current = paymentOffer(founderOffer.plan.id)
+ if (!current || current.priceId !== founderOffer.priceId) { setFounderOffer(null); return }
+ setFounderOffer(null)
+ void billing.checkout(current.priceId, true)
+ }} />
+ </>
+}
+
+export type PricingController = {
+ catalog: PublicPricing | undefined
+ offer: (plan: string) => BillingOffer | undefined
+ disabled: (plan: string) => boolean
+ label: (plan: string) => string
+ choose: (plan: string) => void
+ message: string
+ error: string | null
+ retry: () => void
+}
+
+function PricingSession({ signedIn, sessionPending, sessionError }: { signedIn: boolean; sessionPending: boolean; sessionError: boolean }) {
+ const [client] = useState(() => new QueryClient())
+ return <QueryClientProvider client={client}><PricingContent signedIn={signedIn} sessionPending={sessionPending} sessionError={sessionError} /></QueryClientProvider>
+}
+
+export default function PricingClient() {
+ const session = useSession()
+ return <PricingSession key={session.data?.user.id ?? "guest"} signedIn={Boolean(session.data?.user)} sessionPending={session.isPending} sessionError={Boolean(session.error)} />
+}
diff --git a/src/web/src/app/pricing/pricing-view.tsx b/src/web/src/app/pricing/pricing-view.tsx
new file mode 100644
index 000000000..f580884d8
--- /dev/null
+++ b/src/web/src/app/pricing/pricing-view.tsx
@@ -0,0 +1,182 @@
+"use client"
+
+import Image from "next/image"
+import Link from "next/link"
+import { PlanBots, PlanBarcode } from "@/components/pricing/plan-art"
+import styles from "./pricing.module.css"
+import type { PricingController } from "./pricing-client"
+
+function PricingPrice({ offer, free, className, inverse }: { offer?: import("@alook/shared").BillingOffer; free?: boolean; className: string; inverse?: boolean }) {
+ if (free) return <div className={className}><span className={styles.currency}>$</span><span className={styles.amount}>0</span><span className={styles.cadence}> / month</span></div>
+ if (!offer) return <div className={className} aria-label="Price unavailable"><span className={styles.amount}>—</span></div>
+ const currency = offer.currency.toUpperCase()
+ const digits = new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2
+ const parts = new Intl.NumberFormat("en", { style: "currency", currency, minimumFractionDigits: 0 }).formatToParts(offer.unitAmount / 10 ** digits)
+ const symbol = parts.find((part) => part.type === "currency")?.value ?? currency
+ const amount = parts.filter((part) => part.type !== "currency" && part.type !== "literal").map((part) => part.value).join("")
+ const interval = offer.intervalCount === 1 ? offer.interval : `${offer.intervalCount} ${offer.interval}s`
+ return <div className={className} data-inverse={inverse || undefined}><span className={styles.currency}>{symbol}</span><span className={styles.amount}>{amount}</span><span className={styles.cadence}>{currency} / {interval}</span></div>
+}
+
+export function PricingView({ controller: c }: { controller: PricingController }) {
+ return (
+ <div className={`dark ${styles.page}`}>
+ <header className={styles.header}>
+ <Link className={styles.brand} href="/" aria-label="Alook home">
+ <Image src="/alook.svg" alt="" width={28} height={28} priority />
+ <span>Alook</span>
+ </Link>
+ <Link className={styles.backLink} href="/">
+ Back to Alook
+ </Link>
+ </header>
+
+ <main className={styles.main}>
+ <p className={styles.eyebrow}>Pricing</p>
+ <h1>Choose the right space for your bots.</h1>
+
+ <div className={styles.status} aria-live="polite">{c.message}</div>
+ {c.error && <div className={styles.status} role="alert">{c.error} <button type="button" onClick={c.retry}>Try again</button></div>}
+ <section className={styles.plans} aria-label="Alook plans">
+ <article className={`${styles.plan} ${styles.freePlan}`}>
+ <Image
+ className={styles.ghostMark}
+ src="/alook.svg"
+ alt=""
+ width={280}
+ height={280}
+ aria-hidden="true"
+ />
+ <div className={styles.freeContent}>
+ <h2>Free</h2>
+ <PricingPrice free className={styles.price} />
+ <p className={styles.limit}>
+ Up to <strong>{c.catalog?.free.botLimit ?? "—"}</strong> active bots
+ </p>
+ <p className={styles.limit}>Up to <strong>{c.catalog?.free.machineLimit ?? "—"}</strong> online machine{c.catalog?.free.machineLimit === 1 ? "" : "s"}</p>
+ <button className={styles.ghostButton} type="button" disabled={c.disabled("free")} onClick={() => c.choose("free")} data-testid="pricing-choose-free">
+ {c.label("free")}
+ </button>
+ </div>
+ </article>
+
+ <article className={`${styles.plan} ${styles.studioPlan}`}>
+ <div className={styles.hangingTag}>
+ <div className={styles.tagString} aria-hidden="true" />
+ <div className={styles.tagHole} aria-hidden="true" />
+ <PlanBots className={styles.ticketBots} botClassName={styles.ticketBot} avatarClassName={styles.generatedBotAvatar} />
+ <div className={styles.paperTag}>
+ <span className={styles.monthlyChip}>Monthly</span>
+ <h2>Studio</h2>
+ <PricingPrice offer={c.offer("studio")} className={styles.price} />
+
+ <div className={styles.tagRule} />
+ <p className={styles.limit}>
+ Up to <strong>{c.offer("studio")?.botLimit ?? "—"}</strong> active bots
+ </p>
+ <p className={styles.limit}>Up to <strong>{c.offer("studio")?.machineLimit ?? "—"}</strong> online machine{c.offer("studio")?.machineLimit === 1 ? "" : "s"}</p>
+ <button className={styles.studioButton} type="button" disabled={c.disabled("studio")} onClick={() => c.choose("studio")} data-testid="pricing-choose-studio">
+ {c.label("studio")}
+ </button>
+ <div className={styles.tagFooter}>
+ <span>ALO-STD-010</span>
+ <PlanBarcode className={styles.barcode} />
+ </div>
+ </div>
+ </div>
+ </article>
+
+ <article className={`${styles.plan} ${styles.housePlan}`}>
+ <div className={styles.ticketMain}>
+ <div className={styles.ticketTopline}>
+ <h2>House</h2>
+ <span>ALO · 040</span>
+ </div>
+ <PricingPrice offer={c.offer("house")} className={styles.price} inverse />
+
+ <p className={styles.houseLimit}>
+ Up to <strong>{c.offer("house")?.botLimit ?? "—"}</strong> active bots
+ </p>
+ <p className={styles.houseLimit}>Up to <strong>{c.offer("house")?.machineLimit ?? "—"}</strong> online machine{c.offer("house")?.machineLimit === 1 ? "" : "s"}</p>
+ <button className={styles.houseButton} type="button" disabled={c.disabled("house")} onClick={() => c.choose("house")} data-testid="pricing-choose-house">
+ {c.label("house")}
+ </button>
+ <span className={styles.ticketSerial}>ISSUE 01 / MONTHLY ACCESS</span>
+ </div>
+
+ <div className={styles.ticketStubWrap} aria-hidden="true">
+ <div className={styles.ticketStub}>
+ <span className={styles.perforation} />
+ <div className={styles.theater}>
+ <div className={styles.theaterScreen} />
+ <div className={styles.seatGrid}>
+ {Array.from({ length: Math.ceil((c.offer("house")?.botLimit ?? 0) / 8) }, (_, rowIndex) => (
+ <div className={styles.seatRow} key={rowIndex}>
+ {Array.from({ length: Math.min(8, (c.offer("house")?.botLimit ?? 0) - rowIndex * 8) }, (_, seatIndex) => (
+ <span className={styles.seat} key={seatIndex} />
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+ <PlanBarcode className={styles.barcode} />
+ </div>
+ </div>
+ </article>
+ </section>
+
+ <p className={styles.sharedLine}>Core Alook features are available on every plan.</p>
+
+ <section className={styles.faq} aria-labelledby="pricing-faq-title">
+ <h2 id="pricing-faq-title">Questions, answered.</h2>
+ <dl className={styles.faqGrid}>
+ <div className={styles.faqItem}>
+ <dt>Which machines count toward my plan?</dt>
+ <dd>Every machine you own counts, including offline machines. Disconnecting one does not make room for another. If you downgrade, newer excess machines are disconnected; your machines and bots are kept.</dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>Which bots count toward my plan?</dt>
+ <dd>Every bot you own counts toward your plan allowance, whether it&apos;s Active or Inactive.</dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>What happens when I reach my limit?</dt>
+ <dd>
+ You need room under your owned-bot allowance before creating another bot. Making one Inactive does
+ not free a slot.
+ </dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>What happens if I downgrade?</dt>
+ <dd>
+ Alook keeps your oldest active bots Active up to the new allowance and makes the rest Inactive. They
+ aren&apos;t deleted, but you can&apos;t create another bot until your owned total is below your plan’s limit.
+ </dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>What happens when a bot is Inactive?</dt>
+ <dd>
+ Inactive bots still count toward your owned-bot allowance. They don&apos;t receive messages, and
+ messages sent while they&apos;re Inactive aren&apos;t queued for later delivery.
+ </dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>Do bots from other people count toward my plan?</dt>
+ <dd>No. Bots other people bring into your rooms don&apos;t count toward your plan.</dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>Can I switch which bots are Active?</dt>
+ <dd>Yes. Choose which bots are Active or Inactive from My Bots.</dd>
+ </div>
+ <div className={styles.faqItem}>
+ <dt>Does Alook include AI model or runtime costs?</dt>
+ <dd>
+ No. Alook does not supply AI models. You connect a supported local runtime, and any model or
+ runtime charges are separate.
+ </dd>
+ </div>
+ </dl>
+ </section>
+ </main>
+ </div>
+ )
+}
diff --git a/src/web/src/app/pricing/pricing.module.css b/src/web/src/app/pricing/pricing.module.css
new file mode 100644
index 000000000..aadc90137
--- /dev/null
+++ b/src/web/src/app/pricing/pricing.module.css
@@ -0,0 +1,1097 @@
+.page {
+ --tag-paper: #f4d85b;
+ --tag-ink: #24221e;
+ --tag-muted: color-mix(in oklab, var(--tag-ink) 82%, var(--tag-paper));
+ --tag-border: color-mix(in oklab, var(--tag-ink) 18%, transparent);
+ --house-stock: color-mix(in oklab, var(--foreground) 22%, black);
+ --house-ink: color-mix(in oklab, var(--background) 18%, white);
+ --house-muted: color-mix(in oklab, var(--house-ink) 62%, transparent);
+ min-height: 100svh;
+ color-scheme: dark;
+ overflow: hidden;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: var(--font-sans);
+}
+
+.page ::selection {
+ background: var(--foreground);
+ color: var(--background);
+}
+
+.header {
+ display: flex;
+ width: min(100% - 64px, 1280px);
+ height: 80px;
+ margin-inline: auto;
+ align-items: center;
+ justify-content: space-between;
+ border-bottom: 1px solid color-mix(in oklab, var(--border) 68%, transparent);
+}
+
+.brand,
+.backLink {
+ color: inherit;
+ text-decoration: none;
+}
+
+.brand {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ font-family: var(--font-brand);
+ font-size: 26px;
+ font-weight: 700;
+ line-height: 1;
+}
+
+.backLink {
+ min-height: 44px;
+ display: inline-flex;
+ align-items: center;
+ padding-inline: 8px;
+ color: var(--muted-foreground);
+ font-size: 14px;
+ text-underline-offset: 4px;
+ transition: color 150ms ease;
+}
+
+.backLink:hover {
+ color: var(--foreground);
+ text-decoration: underline;
+}
+
+.main {
+ width: min(100% - 64px, 1280px);
+ margin-inline: auto;
+ padding: 64px 0 96px;
+}
+
+.eyebrow {
+ margin: 0 0 16px;
+ color: var(--muted-foreground);
+ font-family: var(--font-mono);
+ font-size: 10px;
+ letter-spacing: 0.14em;
+ line-height: 1;
+ text-align: center;
+ text-transform: uppercase;
+}
+
+.main h1 {
+ max-width: 760px;
+ margin: 0 auto;
+ font-family: var(--font-heading);
+ font-size: clamp(44px, 4.5vw, 64px);
+ font-weight: 600;
+ letter-spacing: -0.025em;
+ line-height: 1.05;
+ text-align: center;
+ text-wrap: balance;
+}
+
+.plans {
+ display: grid;
+ grid-template-columns: minmax(210px, 0.7fr) minmax(280px, 0.92fr) minmax(480px, 1.48fr);
+ gap: 32px;
+ align-items: end;
+ max-width: 1260px;
+ margin: 64px auto 0;
+}
+
+.plan {
+ position: relative;
+ min-width: 0;
+}
+
+.plan h2 {
+ margin: 0;
+ font-family: var(--font-brand);
+ font-size: 40px;
+ font-weight: 700;
+ letter-spacing: 0;
+ line-height: 1;
+}
+
+.price {
+ display: grid;
+ grid-template-columns: auto auto 1fr;
+ align-items: end;
+ width: fit-content;
+ margin-top: 16px;
+ color: var(--foreground);
+ font-variant-numeric: tabular-nums;
+}
+
+.price[data-inverse] {
+ color: var(--house-ink);
+}
+
+.currency {
+ margin-right: 4px;
+ padding-bottom: 8px;
+ font-size: 18px;
+ font-weight: 600;
+ line-height: 1;
+}
+
+.amount {
+ font-family: var(--font-heading);
+ font-size: 60px;
+ font-weight: 600;
+ letter-spacing: -0.035em;
+ line-height: 0.85;
+}
+
+.cadence {
+ padding: 0 0 5px 8px;
+ color: var(--muted-foreground);
+ font-size: 13px;
+ line-height: 1;
+}
+
+.limit {
+ max-width: 23ch;
+ margin: 32px 0 0;
+ color: var(--muted-foreground);
+ font-size: 15px;
+ line-height: 1.6;
+}
+
+.limit strong {
+ color: var(--foreground);
+ font-weight: 600;
+}
+
+.freePlan {
+ min-height: 352px;
+ display: flex;
+ align-items: flex-end;
+ isolation: isolate;
+ padding: 0 16px 32px;
+}
+
+.ghostMark {
+ position: absolute;
+ left: -56px;
+ bottom: 48px;
+ z-index: -1;
+ width: 240px;
+ height: 240px;
+ filter: grayscale(1);
+ opacity: 0.035;
+ transform: rotate(-8deg);
+ transition: opacity 220ms var(--ease-out), transform 220ms var(--ease-out);
+}
+
+.freeContent {
+ width: 100%;
+ padding-top: 32px;
+ border-top: 1px solid color-mix(in oklab, var(--border) 42%, transparent);
+}
+
+.freePlan .price,
+.freePlan h2,
+.ghostButton {
+ opacity: 0.82;
+ transition: opacity 220ms var(--ease-out);
+}
+
+.freePlan .limit {
+ opacity: 0.9;
+ transition: opacity 220ms var(--ease-out);
+}
+
+.freePlan:hover .ghostMark,
+.freePlan:focus-within .ghostMark {
+ opacity: 0.075;
+ transform: rotate(-4deg) translateY(-4px);
+}
+
+.freePlan:hover .price,
+.freePlan:hover .limit,
+.freePlan:hover h2,
+.freePlan:hover .ghostButton,
+.freePlan:focus-within .price,
+.freePlan:focus-within .limit,
+.freePlan:focus-within h2,
+.freePlan:focus-within .ghostButton {
+ opacity: 1;
+}
+
+.ghostButton,
+.studioButton,
+.houseButton {
+ min-height: 44px;
+ margin-top: 32px;
+ border: 0;
+ border-radius: var(--radius-md);
+ font: inherit;
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: background-color 150ms ease, color 150ms ease, transform 150ms ease;
+}
+
+.ghostButton {
+ padding: 0;
+ background: transparent;
+ color: var(--foreground);
+ text-decoration: underline;
+ text-decoration-color: color-mix(in oklab, var(--foreground) 28%, transparent);
+ text-underline-offset: 6px;
+}
+
+.ghostButton:hover {
+ text-decoration-color: var(--foreground);
+}
+
+.studioPlan {
+ display: flex;
+ min-height: 448px;
+ align-items: flex-end;
+ justify-content: center;
+}
+
+.hangingTag {
+ position: relative;
+ width: 100%;
+ min-height: 448px;
+ padding-top: 56px;
+ transform: rotate(-1deg);
+ transform-origin: 50% 0;
+ transition: transform 240ms var(--ease-out);
+ will-change: transform;
+}
+
+.studioPlan:hover .hangingTag,
+.studioPlan:focus-within .hangingTag {
+ transform: rotate(1deg) translateY(-4px);
+}
+
+.tagString {
+ position: absolute;
+ top: 0;
+ left: 50%;
+ z-index: 2;
+ width: 1px;
+ height: 64px;
+ background: var(--border);
+ transform: translateX(-50%);
+}
+
+.tagHole {
+ position: absolute;
+ top: 54px;
+ left: 50%;
+ z-index: 3;
+ width: 14px;
+ height: 14px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--background);
+ box-shadow: var(--e1);
+ transform: translateX(-50%);
+}
+
+.ticketBots {
+ position: absolute;
+ top: 32px;
+ left: 50%;
+ z-index: 0;
+ width: min(78%, 240px);
+ height: 40px;
+ pointer-events: none;
+ transform: translateX(-50%);
+}
+
+.ticketBot {
+ --bot-tilt: 0deg;
+ position: absolute;
+ bottom: 0;
+ left: 50%;
+ display: grid;
+ width: 38px;
+ height: 38px;
+ place-items: center;
+ border: 1px solid var(--tag-border);
+ border-radius: var(--radius-lg);
+ background: var(--tag-paper);
+ box-shadow: var(--e1);
+ opacity: 0;
+ transform: translate(-50%, 20px) rotate(var(--bot-tilt));
+ animation: studio-bot-peek 680ms var(--ease-out) forwards;
+}
+
+.generatedBotAvatar {
+ width: 100%;
+ height: 100%;
+ border-radius: inherit;
+}
+
+.ticketBot:nth-child(1) {
+ --bot-tilt: -8deg;
+ left: 18%;
+ animation-delay: 80ms;
+}
+
+.ticketBot:nth-child(2) {
+ --bot-tilt: 4deg;
+ left: 38%;
+ animation-delay: 150ms;
+}
+
+.ticketBot:nth-child(3) {
+ --bot-tilt: 9deg;
+ left: 82%;
+ animation-delay: 210ms;
+}
+
+.studioPlan:hover .ticketBot,
+.studioPlan:focus-within .ticketBot {
+ animation-name: studio-bot-peek-again;
+ animation-duration: 520ms;
+}
+
+.paperTag {
+ position: relative;
+ width: min(100%, 330px);
+ min-height: 392px;
+ margin-inline: auto;
+ padding: 48px 32px 24px;
+ border: 1px solid var(--tag-border);
+ border-radius: var(--radius-sm);
+ background: var(--tag-paper);
+ color: var(--tag-ink);
+ box-shadow: var(--e2);
+ transition: box-shadow 240ms var(--ease-out);
+ z-index: 1;
+}
+
+@keyframes studio-bot-peek {
+ 0% {
+ opacity: 0;
+ transform: translate(-50%, 20px) rotate(var(--bot-tilt));
+ }
+
+ 46% {
+ opacity: 1;
+ transform: translate(-50%, -12px) rotate(var(--bot-tilt));
+ }
+
+ 72% {
+ transform: translate(-50%, -5px) rotate(var(--bot-tilt));
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translate(-50%, 0) rotate(var(--bot-tilt));
+ }
+}
+
+@keyframes studio-bot-peek-again {
+ 0%,
+ 100% {
+ opacity: 1;
+ transform: translate(-50%, 0) rotate(var(--bot-tilt));
+ }
+
+ 48% {
+ opacity: 1;
+ transform: translate(-50%, -12px) rotate(var(--bot-tilt));
+ }
+}
+
+.studioPlan:hover .paperTag,
+.studioPlan:focus-within .paperTag {
+ box-shadow: 0 18px 34px -16px color-mix(in oklab, var(--foreground) 25%, transparent);
+}
+
+.monthlyChip {
+ position: absolute;
+ top: 20px;
+ right: 24px;
+ padding: 4px 7px;
+ border: 1px solid var(--tag-border);
+ border-radius: var(--radius-sm);
+ color: var(--tag-muted);
+ font-family: var(--font-mono);
+ font-size: 9px;
+ letter-spacing: 0.08em;
+ line-height: 1;
+ text-transform: uppercase;
+}
+
+.billing,
+.houseBilling {
+ margin: 8px 0 0;
+ color: var(--muted-foreground);
+ font-size: 12px;
+ line-height: 1;
+}
+
+.paperTag .price,
+.paperTag .limit strong {
+ color: var(--tag-ink);
+}
+
+.paperTag .cadence,
+.paperTag .billing,
+.paperTag .limit,
+.paperTag .tagFooter {
+ color: var(--tag-muted);
+}
+
+.tagRule {
+ margin-top: 32px;
+ border-top: 1px dashed var(--tag-border);
+}
+
+.studioButton {
+ width: 100%;
+ padding-inline: 16px;
+ background: var(--tag-ink);
+ color: #fff8e8;
+}
+
+.studioButton:hover {
+ background: color-mix(in oklab, var(--tag-ink) 88%, var(--tag-paper));
+}
+
+.tagFooter {
+ display: flex;
+ margin-top: 32px;
+ align-items: end;
+ justify-content: space-between;
+ gap: 16px;
+ color: var(--muted-foreground);
+ font-family: var(--font-mono);
+ font-size: 8px;
+ letter-spacing: 0.08em;
+}
+
+.barcode {
+ display: flex;
+ height: 25px;
+ align-items: stretch;
+ gap: 2px;
+}
+
+.barcode span {
+ width: 1px;
+ background: currentColor;
+ opacity: 0.48;
+}
+
+.barcode span[data-wide] {
+ width: 2px;
+ opacity: 0.72;
+}
+
+.housePlan {
+ --ticket-stub-width: 25%;
+ display: grid;
+ grid-template-columns: minmax(0, 3fr) minmax(120px, 1fr);
+ min-height: 352px;
+ overflow: visible;
+ background: transparent;
+ color: var(--house-ink);
+ transition: transform 240ms var(--ease-out);
+}
+
+.housePlan:hover,
+.housePlan:focus-within {
+ transform: translateY(-4px);
+}
+
+.ticketMain {
+ position: relative;
+ min-width: 0;
+ overflow: hidden;
+ padding: 32px;
+ border-radius: var(--radius-xl) 0 0 var(--radius-xl);
+ background: var(--house-stock);
+ box-shadow: var(--e2), inset 0 0 0 1px color-mix(in oklab, var(--house-ink) 9%, transparent);
+ -webkit-mask-image:
+ radial-gradient(circle 10px at 100% 0, transparent 9.5px, black 10px),
+ radial-gradient(circle 10px at 100% 100%, transparent 9.5px, black 10px);
+ -webkit-mask-position: top right, bottom right;
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100% 50%, 100% 50%;
+ mask-image:
+ radial-gradient(circle 10px at 100% 0, transparent 9.5px, black 10px),
+ radial-gradient(circle 10px at 100% 100%, transparent 9.5px, black 10px);
+ mask-position: top right, bottom right;
+ mask-repeat: no-repeat;
+ mask-size: 100% 50%, 100% 50%;
+}
+
+.ticketTopline {
+ display: flex;
+ align-items: start;
+ justify-content: space-between;
+ gap: 16px;
+}
+
+.ticketTopline h2 {
+ font-size: 44px;
+}
+
+.ticketTopline > span {
+ color: color-mix(in oklab, var(--house-ink) 44%, transparent);
+ font-family: var(--font-mono);
+ font-size: 9px;
+ letter-spacing: 0.12em;
+}
+
+.housePlan .price {
+ margin-top: 24px;
+}
+
+.housePlan .cadence,
+.houseBilling {
+ color: var(--house-muted);
+}
+
+.houseLimit {
+ margin: 24px 0 0;
+ color: color-mix(in oklab, var(--house-ink) 72%, transparent);
+ font-size: 15px;
+ line-height: 1.6;
+}
+
+.houseLimit strong {
+ color: var(--house-ink);
+ font-weight: 600;
+}
+
+.limit + .limit,
+.houseLimit + .houseLimit {
+ margin-top: 8px;
+}
+
+.houseButton {
+ width: 100%;
+ margin-top: 24px;
+ padding-inline: 16px;
+ background: var(--house-ink);
+ color: var(--house-stock);
+}
+
+.houseButton:hover {
+ background: color-mix(in oklab, var(--house-ink) 90%, var(--house-stock));
+}
+
+.ticketSerial {
+ display: block;
+ margin-top: 16px;
+ color: color-mix(in oklab, var(--house-ink) 34%, transparent);
+ font-family: var(--font-mono);
+ font-size: 8px;
+ letter-spacing: 0.12em;
+}
+
+.ticketStubWrap {
+ position: relative;
+ min-width: 0;
+ transform-origin: 0 50%;
+ transition: filter 240ms var(--ease-out), transform 240ms var(--ease-out);
+ will-change: filter, transform;
+}
+
+.ticketStub {
+ position: relative;
+ display: flex;
+ height: 100%;
+ overflow: hidden;
+ flex-direction: column;
+ align-items: center;
+ justify-content: space-between;
+ padding: 32px 10px;
+ border-radius: 0 var(--radius-xl) var(--radius-xl) 0;
+ background: color-mix(in oklab, var(--house-stock) 92%, var(--house-ink));
+ color: color-mix(in oklab, var(--house-ink) 68%, transparent);
+ box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--house-ink) 9%, transparent);
+ -webkit-mask-image:
+ radial-gradient(circle 10px at 0 0, transparent 9.5px, black 10px),
+ radial-gradient(circle 10px at 0 100%, transparent 9.5px, black 10px);
+ -webkit-mask-position: top left, bottom left;
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100% 50%, 100% 50%;
+ mask-image:
+ radial-gradient(circle 10px at 0 0, transparent 9.5px, black 10px),
+ radial-gradient(circle 10px at 0 100%, transparent 9.5px, black 10px);
+ mask-position: top left, bottom left;
+ mask-repeat: no-repeat;
+ mask-size: 100% 50%, 100% 50%;
+}
+
+.perforation {
+ position: absolute;
+ top: 10px;
+ bottom: 10px;
+ left: 0;
+ z-index: 2;
+ width: 1px;
+ background: repeating-linear-gradient(
+ to bottom,
+ color-mix(in oklab, var(--house-ink) 24%, transparent) 0 3px,
+ transparent 3px 7px
+ );
+ pointer-events: none;
+}
+
+.housePlan:hover .ticketStubWrap,
+.housePlan:focus-within .ticketStubWrap {
+ filter: drop-shadow(10px 18px 18px color-mix(in oklab, var(--foreground) 28%, transparent));
+ transform: translateX(32px) rotate(1.5deg);
+}
+
+.theater {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 25px;
+ isolation: isolate;
+}
+
+.theater::before {
+ position: absolute;
+ top: 46px;
+ left: 50%;
+ z-index: 0;
+ width: 140px;
+ height: 162px;
+ background: radial-gradient(
+ ellipse 74% 102% at 50% 0,
+ color-mix(in oklab, var(--house-ink) 9%, transparent) 0,
+ color-mix(in oklab, var(--house-ink) 5%, transparent) 32%,
+ color-mix(in oklab, var(--house-ink) 2%, transparent) 62%,
+ transparent 90%
+ );
+ content: "";
+ filter: blur(18px);
+ opacity: 0.72;
+ pointer-events: none;
+ transform: translateX(-50%);
+}
+
+.theater::after {
+ position: absolute;
+ top: -14px;
+ left: 50%;
+ z-index: 0;
+ width: 126px;
+ height: 92px;
+ background: radial-gradient(
+ ellipse,
+ color-mix(in oklab, var(--house-ink) 7%, transparent),
+ color-mix(in oklab, var(--house-ink) 2%, transparent) 44%,
+ transparent 72%
+ );
+ content: "";
+ filter: blur(12px);
+ opacity: 0.72;
+ pointer-events: none;
+ transform: translateX(-50%);
+}
+
+.theater > * {
+ position: relative;
+ z-index: 1;
+}
+
+.theaterScreen {
+ position: relative;
+ display: grid;
+ width: 112px;
+ height: 60px;
+ overflow: visible;
+ place-items: center;
+ background:
+ url("/alook.svg") center / 50px 50px no-repeat,
+ linear-gradient(
+ 180deg,
+ color-mix(in oklab, var(--house-ink) 7%, transparent),
+ color-mix(in oklab, var(--house-ink) 2%, transparent)
+ );
+ box-shadow: 0 10px 24px -16px color-mix(in oklab, var(--house-ink) 18%, transparent);
+ filter:
+ grayscale(1)
+ brightness(0.78)
+ contrast(1.08)
+ drop-shadow(0 0 9px color-mix(in oklab, var(--house-ink) 12%, transparent));
+ transform: perspective(140px) rotateX(-18deg) translateY(-2px) scale(1.04);
+ transform-origin: center top;
+}
+
+.theaterScreen::after {
+ position: absolute;
+ right: 12%;
+ bottom: -5px;
+ left: 12%;
+ height: 1px;
+ background: color-mix(in oklab, var(--house-ink) 12%, transparent);
+ box-shadow: 0 3px 9px color-mix(in oklab, var(--house-ink) 10%, transparent);
+ content: "";
+}
+
+.seatGrid {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 1px;
+ padding: 4px 2px 8px;
+}
+
+.seatRow {
+ --seat-gap: 2px;
+ --seat-width: 6px;
+ display: grid;
+ grid-template-columns: repeat(8, var(--seat-width));
+ column-gap: var(--seat-gap);
+ min-height: 9px;
+ align-items: end;
+ opacity: 0.76;
+}
+
+.seatRow:nth-child(2) {
+ --seat-width: 6.5px;
+ --seat-gap: 2.75px;
+ margin-top: 1px;
+ opacity: 0.69;
+}
+
+.seatRow:nth-child(3) {
+ --seat-width: 7px;
+ --seat-gap: 3.5px;
+ margin-top: 2px;
+ opacity: 0.62;
+}
+
+.seatRow:nth-child(4) {
+ --seat-width: 7.5px;
+ --seat-gap: 4.25px;
+ margin-top: 4px;
+ opacity: 0.55;
+}
+
+.seatRow:nth-child(5) {
+ --seat-width: 8px;
+ --seat-gap: 5px;
+ margin-top: 6px;
+ opacity: 0.48;
+}
+
+.seat {
+ position: relative;
+ width: var(--seat-width);
+ height: 9px;
+}
+
+.seat::before,
+.seat::after {
+ position: absolute;
+ left: 50%;
+ background: currentColor;
+ content: "";
+ transform: translateX(-50%);
+}
+
+.seat::before {
+ top: 0;
+ width: 100%;
+ height: 6px;
+ border-radius: 3px 3px 1px 1px;
+}
+
+.seat::after {
+ bottom: 0;
+ width: calc(100% + 2px);
+ height: 3px;
+ border-radius: 1px 1px 3px 3px;
+ box-shadow: 0 2px 0 color-mix(in oklab, currentColor 42%, transparent);
+}
+
+.ticketStub .barcode {
+ width: 54px;
+ height: 18px;
+ gap: 1px;
+}
+
+.sharedLine {
+ width: fit-content;
+ max-width: 100%;
+ margin: 64px auto 0;
+ padding: 16px 0;
+ border-top: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
+ border-bottom: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
+ color: var(--muted-foreground);
+ font-size: 15px;
+ line-height: 1.6;
+ text-align: center;
+}
+
+.faq {
+ max-width: 1040px;
+ margin: 112px auto 32px;
+}
+
+.faq > h2 {
+ max-width: 520px;
+ margin: 0;
+ font-family: var(--font-heading);
+ font-size: 40px;
+ font-weight: 600;
+ letter-spacing: -0.015em;
+ line-height: 1.15;
+}
+
+.faqGrid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ column-gap: 48px;
+ margin: 40px 0 0;
+}
+
+.faqItem {
+ padding: 32px 0;
+ border-top: 1px solid var(--border);
+}
+
+.faqItem dt {
+ max-width: 32ch;
+ font-size: 16px;
+ font-weight: 600;
+ line-height: 1.4;
+}
+
+.faqItem dd {
+ max-width: 54ch;
+ margin: 16px 0 0;
+ color: var(--muted-foreground);
+ font-size: 15px;
+ line-height: 1.6;
+}
+
+.ghostButton:focus-visible,
+.studioButton:focus-visible,
+.houseButton:focus-visible,
+.brand:focus-visible,
+.backLink:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 4px;
+}
+
+.ghostButton:active,
+.studioButton:active,
+.houseButton:active {
+ transform: translateY(1px);
+}
+
+@media (max-width: 1100px) {
+ .plans {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 48px 32px;
+ max-width: 720px;
+ }
+
+ .housePlan {
+ grid-column: 1 / -1;
+ grid-template-columns: minmax(0, 3fr) minmax(120px, 1fr);
+ }
+
+ .sharedLine {
+ margin-top: 64px;
+ }
+
+ .faq {
+ margin-top: 96px;
+ }
+}
+
+@media (max-width: 639px) {
+ .header,
+ .main {
+ width: min(100% - 32px, 520px);
+ }
+
+ .header {
+ height: 72px;
+ }
+
+ .main {
+ padding: 48px 0 64px;
+ }
+
+ .main h1 {
+ max-width: 12ch;
+ font-size: clamp(40px, 12vw, 48px);
+ }
+
+ .plans {
+ grid-template-columns: 1fr;
+ gap: 48px;
+ margin-top: 64px;
+ }
+
+ .freePlan {
+ min-height: 320px;
+ padding-inline: 24px;
+ }
+
+ .ghostMark {
+ left: auto;
+ right: -24px;
+ }
+
+ .studioPlan {
+ min-height: 448px;
+ }
+
+ .paperTag {
+ width: min(100% - 32px, 348px);
+ }
+
+ .housePlan {
+ --ticket-stub-width: 80px;
+ grid-column: auto;
+ grid-template-columns: minmax(0, 1fr) 80px;
+ min-height: 304px;
+ }
+
+ .ticketMain {
+ padding: 24px;
+ }
+
+ .ticketTopline h2 {
+ font-size: 38px;
+ }
+
+ .housePlan .amount {
+ font-size: 48px;
+ }
+
+ .housePlan .price,
+ .houseLimit,
+ .houseButton {
+ margin-top: 16px;
+ }
+
+ .ticketStub {
+ padding: 24px 8px;
+ }
+
+ .theater {
+ gap: 16px;
+ }
+
+ .theater::before {
+ top: 34px;
+ width: 84px;
+ height: 104px;
+ }
+
+ .theater::after {
+ top: -8px;
+ width: 76px;
+ height: 64px;
+ }
+
+ .theaterScreen {
+ width: 70px;
+ height: 44px;
+ background-size: 34px 34px, auto;
+ transform: perspective(95px) rotateX(-18deg) translateY(-1px) scale(1.03);
+ }
+
+ .seatGrid {
+ gap: 0;
+ padding: 2px 0 6px;
+ }
+
+ .seatRow {
+ --seat-gap: 1px;
+ --seat-width: 3.5px;
+ min-height: 7px;
+ }
+
+ .seatRow:nth-child(2) {
+ --seat-gap: 1.25px;
+ --seat-width: 3.75px;
+ }
+
+ .seatRow:nth-child(3) {
+ --seat-gap: 1.5px;
+ --seat-width: 4.25px;
+ }
+
+ .seatRow:nth-child(4) {
+ --seat-gap: 1.75px;
+ --seat-width: 4.75px;
+ }
+
+ .seatRow:nth-child(5) {
+ --seat-gap: 2px;
+ --seat-width: 5.5px;
+ }
+
+ .seat {
+ height: 7px;
+ }
+
+ .seat::before {
+ height: 5px;
+ border-radius: 2px 2px 1px 1px;
+ }
+
+ .seat::after {
+ width: calc(100% + 2px);
+ height: 2px;
+ border-radius: 1px 1px 2px 2px;
+ }
+
+ .faq {
+ margin-top: 80px;
+ }
+
+ .faqGrid {
+ grid-template-columns: 1fr;
+ margin-top: 32px;
+ }
+
+ .backLink {
+ font-size: 13px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ticketBot {
+ animation: none;
+ opacity: 1;
+ transform: translate(-50%, 0) rotate(var(--bot-tilt));
+ }
+
+ .ghostMark,
+ .freePlan .price,
+ .freePlan .limit,
+ .freePlan h2,
+ .ghostButton,
+ .hangingTag,
+ .paperTag,
+ .housePlan,
+ .ticketStubWrap,
+ .ticketStub,
+ .ghostButton,
+ .studioButton,
+ .houseButton,
+ .backLink {
+ transition: none;
+ }
+}
+
+.status { max-width: 70rem; margin: 16px auto; text-align: center; color: var(--muted-foreground); }
+.status:empty { display: none; }
+.status button { text-decoration: underline; min-height: 44px; padding: 0 8px; }
+.plans button:disabled { opacity: .55; cursor: default; }
diff --git a/src/web/src/components/community/billing/billing-plan.module.css b/src/web/src/components/community/billing/billing-plan.module.css
new file mode 100644
index 000000000..f9e6ca92c
--- /dev/null
+++ b/src/web/src/components/community/billing/billing-plan.module.css
@@ -0,0 +1,107 @@
+.content {
+ container: billing / inline-size;
+ display: flex;
+ flex-direction: column;
+ gap: 2rem;
+}
+
+.offers {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 2rem;
+}
+
+@container billing (min-width: 28rem) {
+ .offers { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
+
+.currentName {
+ font-family: var(--font-brand);
+ font-size: 3rem;
+ font-weight: 700;
+ line-height: 1;
+}
+
+@media (min-width: 40rem) {
+ .currentName { font-size: 3.75rem; }
+}
+
+.offer {
+ --paper: #f4d85b;
+ --ink: #24221e;
+ position: relative;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ padding: 32px 24px 20px;
+ color: var(--ink);
+ background: var(--paper);
+ transition: transform 240ms var(--ease-out);
+ transform-origin: 50% 12px;
+}
+.studio {
+ border-radius: 12px;
+ box-shadow: 0 6px 18px -12px #0005;
+}
+.studio::before {
+ content: "";
+ position: absolute;
+ top: 9px;
+ left: calc(50% - 4px);
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--background);
+}
+.house {
+ --paper: #292823;
+ --ink: #f4f0e8;
+ border-radius: 12px;
+ background: radial-gradient(circle at 0 calc(100% - 45px), transparent 7px, var(--paper) 7.5px) left / 51% 100% no-repeat,
+ radial-gradient(circle at 100% calc(100% - 45px), transparent 7px, var(--paper) 7.5px) right / 51% 100% no-repeat;
+}
+.name {
+ font-family: var(--font-brand);
+ font-size: 36px;
+ font-weight: 700;
+ line-height: 1;
+}
+.price { font-size: 16px; font-weight: 500; font-variant-numeric: tabular-nums; }
+.limit { font-size: 14px; line-height: 1.5; }
+.action {
+ width: 100%;
+ min-height: 44px;
+ margin-top: auto;
+ background: var(--ink);
+ color: var(--paper);
+ border: 0;
+}
+.action:hover { background: color-mix(in oklab, var(--ink) 88%, var(--paper)); }
+.action:disabled { opacity: .65; }
+.stub {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ border-top: 1px dashed color-mix(in oklab, var(--ink) 28%, transparent);
+ padding-top: 12px;
+ font-size: 11px;
+ line-height: 1;
+}
+.botDots { width: 80px; height: 32px; flex-shrink: 0; opacity: .55; }
+
+.studio:focus-within { transform: translateY(-3px) rotate(-.7deg); }
+.house:focus-within { transform: translateY(-3px); }
+@media (hover: hover) and (pointer: fine) {
+ .studio:hover { transform: translateY(-3px) rotate(-.7deg); }
+ .house:hover { transform: translateY(-3px); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .offer { transition: none; }
+ .offer:hover,
+ .offer:focus-within { transform: none; }
+}
+
+.studio .action { background: #fff8e8; color: var(--ink); }
+.studio .action:hover { background: color-mix(in oklab, #fff8e8 88%, var(--paper)); }
diff --git a/src/web/src/components/community/billing/billing-sheet.dom.test.tsx b/src/web/src/components/community/billing/billing-sheet.dom.test.tsx
new file mode 100644
index 000000000..703e229bd
--- /dev/null
+++ b/src/web/src/components/community/billing/billing-sheet.dom.test.tsx
@@ -0,0 +1,143 @@
+import React from "react"
+import { describe, expect, it, vi } from "vitest"
+import type { BillingSummary } from "@alook/shared"
+import { fireEvent, render } from "@/test/react-dom-harness"
+import type { BillingController } from "@/hooks/community/use-billing"
+import { BillingContent, BillingSheet } from "./billing-sheet"
+
+vi.mock("./billing-plan.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))
+
+vi.mock("@/components/community/shell/community-sheet", () => ({
+ CommunitySheet: ({ open, children, footer }: { open: boolean; children: React.ReactNode; footer: React.ReactNode }) => open ? <div>{children}{footer}</div> : null,
+}))
+
+const free: BillingSummary = {
+ plan: { id: "free", displayName: "Free" }, isFounder: false, subscription: null,
+ offers: [{ priceId: "price_a", plan: { id: "custom-tier", displayName: "Studio" }, botLimit: 10, machineLimit: 5, unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1 }],
+}
+function state(overrides: Partial<BillingController> = {}): BillingController {
+ return { data: free, isPending: false, isError: false, isFetching: false, isBusy: false, returnFrom: null, polling: false, actionError: null, checkout: vi.fn(), portal: vi.fn(), cancelChange: vi.fn(), isCancelingChange: false, refresh: vi.fn(), ...overrides } as unknown as BillingController
+}
+function view(billing: BillingController) { return render(<BillingContent billing={billing} />) }
+
+describe("billing sheet", () => {
+ it("shows server offers without fixed plan IDs and sends only the selected price", () => {
+ const billing = state()
+ const ui = view(billing)
+ expect(ui.queryByText("Up to 1 online machine")).not.toBeInTheDocument()
+ expect(ui.getByText((_text, el) => el?.tagName === "P" && el.textContent === "Up to 5 online machines")).toBeInTheDocument()
+ expect(ui.getByText("$20.00 USD / month")).toBeInTheDocument()
+ expect(ui.getByText((_text, element) => element?.tagName === "P" && element.textContent === "Up to 10 active bots")).toBeInTheDocument()
+ expect(ui.getByRole("img", { name: "10 bot slots" })).toBeInTheDocument()
+ fireEvent.click(ui.getByRole("button", { name: "Choose Studio" }))
+ expect(billing.checkout).toHaveBeenCalledWith("price_a")
+ })
+ it("shows Founder paid offers and requires explicit confirmation before checkout", () => {
+ const billing = state({ data: { ...free, isFounder: true, plan: { id: "house", displayName: "House" }, offers: [...free.offers, { ...free.offers[0]!, priceId: "price_house", plan: { id: "house", displayName: "House" } }] } })
+ const ui = view(billing)
+ expect(ui.getByText("Founder")).toBeInTheDocument()
+ expect(ui.getByText("Permanent House access")).toBeInTheDocument()
+ expect(ui.getByRole("button", { name: "Choose House" })).toBeEnabled()
+ fireEvent.click(ui.getByRole("button", { name: "Choose Studio" }))
+ expect(ui.getByRole("dialog")).toHaveTextContent("permanently ends your Founder access")
+ expect(billing.checkout).not.toHaveBeenCalled()
+ fireEvent.click(ui.getByRole("button", { name: "Keep Founder" }))
+ expect(billing.checkout).not.toHaveBeenCalled()
+ fireEvent.click(ui.getByRole("button", { name: "Choose House" }))
+ fireEvent.click(ui.getByRole("button", { name: "Continue to checkout" }))
+ expect(billing.checkout).toHaveBeenCalledWith("price_house", true)
+ expect(billing.portal).not.toHaveBeenCalled()
+ })
+ it("keeps Founder while a payment is awaiting confirmation", () => {
+ const ui = view(state({ data: { ...free, isFounder: true }, returnFrom: "checkout", polling: true }))
+ expect(ui.getByRole("status")).toHaveTextContent("Waiting for payment confirmation")
+ expect(ui.getByRole("button", { name: "Choose Studio" })).toBeDisabled()
+ })
+ it("shows delayed payment honestly and does not invite a second purchase", () => {
+ const ui = view(state({ returnFrom: "checkout" }))
+ expect(ui.getByRole("status")).toHaveTextContent("Payment confirmation hasn't arrived")
+ expect(ui.getByRole("button", { name: "Choose Studio" })).toBeDisabled()
+ })
+ it("keeps canceled checkout state and provides retry after read/action failures", () => {
+ const billing = state({ returnFrom: "cancel", isError: true, actionError: "Couldn't open checkout." })
+ const ui = view(billing)
+ expect(ui.getByRole("status")).toHaveTextContent("Checkout closed")
+ expect(ui.getAllByRole("alert")).toHaveLength(2)
+ fireEvent.click(ui.getByRole("button", { name: "Refresh status" }))
+ expect(billing.refresh).toHaveBeenCalledOnce()
+ })
+ it("uses Portal for a subscriber and shows the confirmed next plan and date", () => {
+ const billing = state({ data: { ...free, plan: { id: "house", displayName: "House" }, subscription: {
+ plan: { id: "house", displayName: "House" }, status: "past_due", cancelAt: null,
+ currentPeriodEnd: "2026-10-10T00:00:00Z", scheduledChange: { plan: free.offers[0]!.plan, effectiveAt: "2026-10-10T00:00:00Z" },
+ } } })
+ const ui = view(billing)
+ expect(ui.getByText(/Changes to Studio on/)).toBeInTheDocument()
+ expect(ui.getByText(/renewal payment needs attention/)).toBeInTheDocument()
+ expect(ui.queryByRole("button", { name: "Choose Studio" })).toBeNull()
+ fireEvent.click(ui.getByRole("button", { name: "Manage billing" }))
+ expect(billing.portal).toHaveBeenCalledOnce()
+ })
+ it("keeps period-end cancellation separate from an immediate loss of access", () => {
+ const ui = view(state({ data: { ...free, subscription: { plan: free.plan, status: "active", cancelAt: "2026-10-08T00:00:00Z", currentPeriodEnd: "2026-10-10T00:00:00Z", scheduledChange: null } } }))
+ expect(ui.getByText(/Ends Oct 8, 2026/)).toBeInTheDocument()
+ expect(ui.queryByText(/Current period ends/)).toBeNull()
+ expect(ui.getByText(/Your current access stays until then/)).toBeInTheDocument()
+ })
+ it("shows the billing period again after cancellation is revoked", () => {
+ const ui = view(state({ data: { ...free, subscription: { plan: free.plan, status: "active", cancelAt: null, currentPeriodEnd: "2026-10-10T00:00:00Z", scheduledChange: null } } }))
+ expect(ui.getByText(/Current period ends Oct 10, 2026/)).toBeInTheDocument()
+ expect(ui.queryByText(/Your current access stays until then/)).toBeNull()
+ })
+
+ it("lets a subscriber select another tier through the targeted Portal flow", () => {
+ const billing = state({ data: { ...free, plan: { id: "house", displayName: "House" }, subscription: {
+ plan: { id: "house", displayName: "House" }, status: "active", cancelAt: null, currentPeriodEnd: null, scheduledChange: null,
+ } } })
+ const ui = view(billing)
+ expect(ui.getByRole("img", { name: "10 bot slots" })).toBeInTheDocument()
+ fireEvent.click(ui.getByRole("button", { name: "Choose Studio" }))
+ expect(billing.portal).toHaveBeenCalledWith("price_a")
+ expect(billing.checkout).not.toHaveBeenCalled()
+ })
+
+ it("does not send the current price back to Portal when a downgrade is scheduled", () => {
+ const house = { id: "house", displayName: "House" }
+ const billing = state({ data: { ...free, plan: house, offers: [...free.offers, { ...free.offers[0]!, priceId: "price_house", plan: house, botLimit: 40, unitAmount: 4000 }], subscription: {
+ plan: house, status: "active", cancelAt: null, currentPeriodEnd: null,
+ scheduledChange: { plan: free.offers[0]!.plan, effectiveAt: "2026-10-10T00:00:00Z" },
+ } } })
+ const ui = view(billing)
+ expect(ui.getByRole("button", { name: "Scheduled" })).toBeDisabled()
+ expect(ui.getByRole("button", { name: "Current plan" })).toBeDisabled()
+ expect(billing.portal).not.toHaveBeenCalled()
+ fireEvent.click(ui.getByRole("button", { name: "Keep current plan" }))
+ expect(billing.cancelChange).toHaveBeenCalledOnce()
+ })
+ it("exposes unavailable offers without a dead purchase button", () => {
+ const ui = view(state({ data: { ...free, offers: [] } }))
+ expect(ui.getByText(/Paid plans are unavailable/)).toBeInTheDocument()
+ expect(ui.queryByRole("button", { name: /Choose/ })).toBeNull()
+ })
+})
+
+describe("upgrade prompt", () => {
+ it("explains the creation block before navigating to plans", () => {
+ const close = vi.fn(), plans = vi.fn()
+ const ui = render(<BillingSheet open onOpenChange={close} limit={3} onViewPlan={plans} />)
+ expect(ui.getByText("Plan limit reached")).toBeInTheDocument()
+ expect(ui.getByText(/can’t create another bot/)).toBeInTheDocument()
+ expect(plans).not.toHaveBeenCalled()
+ fireEvent.click(ui.getByRole("button", { name: "View plan" }))
+ expect(close).toHaveBeenCalledWith(false)
+ expect(plans).toHaveBeenCalledOnce()
+ })
+})
+
+it("explains ownership limits without promising an upgrade", () => {
+ const ui = render(<BillingSheet open onOpenChange={vi.fn()} limit={40} onViewPlan={vi.fn()} />)
+ expect(ui.getByText(/Delete bots until you own fewer than 40/)).toBeInTheDocument()
+ expect(ui.getByRole("button", { name: "View plan" })).toBeInTheDocument()
+ expect(ui.queryByText(/upgrade your plan/i)).toBeNull()
+ expect(ui.getByRole("button", { name: "Got it" })).toBeInTheDocument()
+})
diff --git a/src/web/src/components/community/billing/billing-sheet.tsx b/src/web/src/components/community/billing/billing-sheet.tsx
new file mode 100644
index 000000000..fa70bd39b
--- /dev/null
+++ b/src/web/src/components/community/billing/billing-sheet.tsx
@@ -0,0 +1,111 @@
+"use client"
+
+import { useState } from "react"
+import { FounderPlanChangeDialog } from "./founder-plan-change-dialog"
+import { ExternalLink, RefreshCw } from "lucide-react"
+import type { BillingSummary } from "@alook/shared"
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
+import { Button } from "@/components/ui/button"
+import { Skeleton } from "@/components/ui/skeleton"
+import type { BillingController } from "@/hooks/community/use-billing"
+import { PlanBotDots } from "@/components/pricing/plan-bot-dots"
+import styles from "./billing-plan.module.css"
+import { tid } from "@/lib/community/testids"
+
+function formatOffer(offer: BillingSummary["offers"][number]) {
+ const currency = offer.currency.toUpperCase()
+ const digits = new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2
+ const amount = new Intl.NumberFormat(undefined, { style: "currency", currency }).format(offer.unitAmount / 10 ** digits)
+ const period = offer.intervalCount === 1 ? offer.interval : `${offer.intervalCount} ${offer.interval}s`
+ return `${amount} ${currency} / ${period}`
+}
+
+function dateLabel(value: string) {
+ return new Intl.DateTimeFormat(undefined, { year: "numeric", month: "short", day: "numeric" }).format(new Date(value))
+}
+
+export function BillingContent({ billing }: { billing: BillingController }) {
+ const [founderOffer, setFounderOffer] = useState<BillingSummary["offers"][number] | null>(null)
+ const summary = billing.data
+ const subscription = summary?.isFounder ? null : summary?.subscription
+ const currentOffer = summary?.offers.find((offer) => offer.plan.id === summary.plan.id)
+ const checkoutPending = billing.returnFrom === "checkout" && (summary?.isFounder || !subscription || subscription.plan.id !== summary?.plan.id)
+
+ return <div className={styles.content} data-testid={tid.billingSheet}>
+ <section className="pb-2" aria-label="Current plan">
+ <div className="flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ {billing.isPending && <Skeleton className="h-14 w-36" aria-label="Loading billing" />}
+ {summary && <div className="flex flex-wrap items-start gap-2">
+ <h2 className={styles.currentName}>{summary.isFounder ? "Founder" : summary.plan.displayName}</h2>
+ <span className="mt-1 rounded-md bg-muted px-2 py-1 text-xs font-medium leading-none text-muted-foreground">Current</span>
+ </div>}
+ </div>
+ <Button variant="ghost" size="icon-sm" className="size-11 shrink-0 text-muted-foreground sm:size-8" onClick={billing.refresh} disabled={billing.isFetching} aria-label="Refresh status" data-testid={tid.billingRefresh}>
+ <RefreshCw className={`size-4 ${billing.isFetching ? "animate-spin motion-reduce:animate-none" : ""}`} />
+ </Button>
+ </div>
+ {summary && <>
+ {(summary.isFounder || currentOffer || subscription) && <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
+ {summary.isFounder ? <p className="text-sm text-muted-foreground">Permanent {summary.plan.displayName} access</p> : currentOffer && <p className="text-sm text-muted-foreground">{formatOffer(currentOffer)}</p>}
+ {subscription && !summary.isFounder && <Button variant="outline" onClick={() => void billing.portal()} disabled={billing.isBusy} data-testid={tid.billingPortal}>Manage billing<ExternalLink className="size-3.5" /></Button>}
+ </div>}
+ {(subscription?.scheduledChange || subscription?.cancelAt || subscription?.currentPeriodEnd || subscription?.status === "past_due") && <div className="mt-5 flex flex-col gap-3 border-t border-border pt-4 text-sm">
+ {subscription?.scheduledChange && <div className="flex flex-wrap items-center justify-between gap-3">
+ <p>Changes to {subscription.scheduledChange.plan.displayName} on {dateLabel(subscription.scheduledChange.effectiveAt)}</p>
+ {!summary.isFounder && <Button variant="outline" size="sm" onClick={() => void billing.cancelChange()} disabled={billing.isBusy} data-testid={tid.billingCancelChange}>{billing.isCancelingChange ? "Keeping current plan…" : "Keep current plan"}</Button>}
+ </div>}
+ {subscription?.cancelAt && <p>Ends {dateLabel(subscription.cancelAt)}. Your current access stays until then.</p>}
+ {subscription && !subscription.cancelAt && !subscription.scheduledChange && subscription.currentPeriodEnd && <p className="text-muted-foreground">Current period ends {dateLabel(subscription.currentPeriodEnd)}</p>}
+ {subscription?.status === "past_due" && <p>Your renewal payment needs attention. Update your payment method in billing management.</p>}
+ </div>}
+ </>}
+ </section>
+ {billing.isError && <p role="alert" className="text-sm text-destructive">Couldn&apos;t refresh your plan. Check your connection and refresh status.</p>}
+ {billing.returnFrom && <p role="status" className="text-sm text-muted-foreground">
+ {billing.returnFrom === "cancel" ? "Checkout closed. Your current plan is shown above." : checkoutPending ? billing.polling ? "Waiting for payment confirmation. Your current access stays in place." : "Payment confirmation hasn't arrived yet. Refresh status to check again." : billing.polling ? "Refreshing your plan and billing status…" : "Your current plan is shown above. Refresh status to check for further changes."}
+ </p>}
+ {summary && <section className="flex flex-col gap-4" aria-label="Available plans">
+ <h2 className="text-base font-medium">{subscription ? "Change plan" : "Choose a plan"}</h2>
+ {summary.offers.length === 0 && <p className="text-sm text-muted-foreground">Paid plans are unavailable right now. Refresh status to try again.</p>}
+ <div className={styles.offers}>
+ {summary.offers.map((offer) => {
+ const isCurrent = Boolean(subscription && offer.plan.id === summary.plan.id)
+ const isScheduled = subscription?.scheduledChange?.plan.id === offer.plan.id
+ return <article key={offer.priceId} className={`${styles.offer} ${offer.plan.id === "house" ? styles.house : styles.studio}`}>
+ <div className="flex flex-col gap-2">
+ <h3 className={styles.name}>{offer.plan.displayName}</h3>
+ <p className={styles.price}>{formatOffer(offer)}</p>
+ </div>
+ <div className="flex flex-col gap-2">
+ <p className={styles.limit}>Up to <strong>{offer.botLimit}</strong> active bots</p>
+ <p className={styles.limit}>Up to <strong>{offer.machineLimit}</strong> online machine{offer.machineLimit === 1 ? "" : "s"}</p>
+ </div>
+ <Button className={styles.action} variant={isCurrent || isScheduled ? "outline" : "default"} onClick={() => { if (summary.isFounder) setFounderOffer(offer); else void (subscription ? billing.portal(offer.priceId) : billing.checkout(offer.priceId)) }} disabled={billing.isBusy || Boolean(checkoutPending) || isCurrent || isScheduled} data-testid={subscription ? tid.billingChangePlan : tid.billingCheckout} data-price-id={offer.priceId}>
+ {billing.isBusy && !billing.isCancelingChange ? "Opening…" : isScheduled ? "Scheduled" : isCurrent ? "Current plan" : `Choose ${offer.plan.displayName}`}
+ </Button>
+ <div className={styles.stub}><span>Alook · {offer.botLimit} bots</span><PlanBotDots count={offer.botLimit} className={styles.botDots} /></div>
+ </article>
+ })}
+ </div>
+ <p className="text-xs text-muted-foreground">{subscription ? "Review changes and any payment on Stripe." : "Continue to Stripe to review and pay."}</p>
+ </section>}
+ <FounderPlanChangeDialog offer={founderOffer} busy={billing.isBusy} onCancel={() => setFounderOffer(null)} onConfirm={() => { if (!founderOffer) return; const priceId = founderOffer.priceId; setFounderOffer(null); void billing.checkout(priceId, true) }} />
+ {billing.actionError && <p role="alert" className="text-sm text-destructive">{billing.actionError}</p>}
+ </div>
+}
+
+export function BillingSheet({ open, onOpenChange, limit, onViewPlan }: { open: boolean; onOpenChange: (open: boolean) => void; limit: number; onViewPlan: () => void }) {
+ return <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md" data-testid="upgrade-plan-modal">
+ <DialogHeader>
+ <DialogTitle>Plan limit reached</DialogTitle>
+ <DialogDescription>Your owned bots have reached your plan’s limit of {limit}. You can’t create another bot. Delete bots until you own fewer than {limit} to make room.</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>Got it</Button>
+ <Button onClick={() => { onOpenChange(false); onViewPlan() }}>View plan</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+}
diff --git a/src/web/src/components/community/billing/founder-plan-change-dialog.tsx b/src/web/src/components/community/billing/founder-plan-change-dialog.tsx
new file mode 100644
index 000000000..f22c9e9f7
--- /dev/null
+++ b/src/web/src/components/community/billing/founder-plan-change-dialog.tsx
@@ -0,0 +1,25 @@
+"use client"
+
+import type { BillingSummary } from "@alook/shared"
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
+import { Button } from "@/components/ui/button"
+
+export function FounderPlanChangeDialog({ offer, busy, onCancel, onConfirm }: {
+ offer: BillingSummary["offers"][number] | null
+ busy: boolean
+ onCancel: () => void
+ onConfirm: () => void
+}) {
+ return <Dialog open={offer !== null} onOpenChange={(open) => { if (!open && !busy) onCancel() }}>
+ <DialogContent className="sm:max-w-md" showCloseButton={!busy}>
+ <DialogHeader>
+ <DialogTitle>Leave Founder for {offer?.plan.displayName}?</DialogTitle>
+ <DialogDescription>Completing this purchase permanently ends your Founder access. You can’t restore it, even if you later cancel your subscription. If you leave checkout without paying, you keep Founder.</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" disabled={busy} onClick={onCancel}>Keep Founder</Button>
+ <Button disabled={busy} onClick={onConfirm}>{busy ? "Opening…" : "Continue to checkout"}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+}
diff --git a/src/web/src/components/community/bots/bot-active-summary.dom.test.tsx b/src/web/src/components/community/bots/bot-active-summary.dom.test.tsx
new file mode 100644
index 000000000..ba011a810
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-active-summary.dom.test.tsx
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from "vitest"
+import { render, setupUser } from "@/test/react-dom-harness"
+import { BotActiveSummary } from "./bot-active-summary"
+
+const summary = {
+ isFounder: false,
+ plan: { id: "free", displayName: "Free" },
+ activeCount: 2,
+ ownedCount: 3,
+ limit: 3,
+}
+
+describe("BotActiveSummary", () => {
+ it("discloses counts and plan on click and keeps the default row compact", async () => {
+ const view = render(<BotActiveSummary summary={summary} />)
+ expect(view.queryByRole("progressbar")).not.toBeInTheDocument()
+ await setupUser().click(view.getByRole("button", { name: "Active Bots: 2 of 3 allowed, 3 owned, Free plan" }))
+ expect(view.getByLabelText("2 of 3 active bot slots used")).toBeInTheDocument()
+ expect(view.getByText("Free")).toBeInTheDocument()
+ })
+
+ it("reveals the details on desktop hover", async () => {
+ const view = render(<BotActiveSummary summary={summary} />)
+ await setupUser().hover(view.getByRole("button", { name: "Active Bots: 2 of 3 allowed, 3 owned, Free plan" }))
+ expect(await view.findByLabelText("2 of 3 active bot slots used")).toBeInTheDocument()
+ expect(view.getByText("Free")).toBeInTheDocument()
+ })
+
+ it("separates active allowance from retained bots after downgrade", async () => {
+ const view = render(<BotActiveSummary summary={{ ...summary, activeCount: 3, ownedCount: 40 }} />)
+ await setupUser().click(view.getByRole("button", { name: "Active Bots: 3 of 3 allowed, 40 owned, Free plan" }))
+ expect(view.getByLabelText("3 of 3 active bot slots used")).toBeInTheDocument()
+ expect(view.container.querySelector('[pathLength="100"]')).toHaveAttribute("stroke-dasharray", "100 100")
+ expect(view.getByText("40 bots owned")).toBeInTheDocument()
+ expect(view.queryByText("3 / 40 active")).not.toBeInTheDocument()
+ })
+
+ it("offers View plan from the usage popup", async () => {
+ const viewPlan = vi.fn()
+ const view = render(<BotActiveSummary summary={summary} onViewPlan={viewPlan} />)
+ const user = setupUser()
+ await user.click(view.getByRole("button", { name: /Active Bots:/ }))
+ await user.click(view.getByRole("button", { name: "View plan" }))
+ expect(viewPlan).toHaveBeenCalledOnce()
+ expect(view.queryByRole("button", { name: "View plan" })).not.toBeInTheDocument()
+ })
+
+ it("uses plan capacity rather than owned total and handles zero bots", () => {
+ const view = render(<BotActiveSummary summary={{ ...summary, activeCount: 1, ownedCount: 2 }} />)
+ expect(view.container.querySelector('[pathLength="100"]')).toHaveAttribute("stroke-dasharray", "33.33333333333333 100")
+ view.rerender(<BotActiveSummary summary={{ ...summary, activeCount: 0, ownedCount: 0 }} />)
+ expect(view.container.querySelector('[pathLength="100"]')).toHaveAttribute("stroke-dasharray", "0 100")
+ expect(view.getByRole("button", { name: "Active Bots: 0 of 3 allowed, 0 owned, Free plan" })).toBeEnabled()
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-active-summary.tsx b/src/web/src/components/community/bots/bot-active-summary.tsx
new file mode 100644
index 000000000..cd27db178
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-active-summary.tsx
@@ -0,0 +1,48 @@
+import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
+import { ArrowRight } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { tid } from "@/lib/community/testids"
+import type { BotPlanSummary } from "@/hooks/community/use-bots"
+
+export function BotActiveSummary({ summary, isFounder = false, onViewPlan }: { summary: BotPlanSummary | null; isFounder?: boolean; onViewPlan?: () => void }) {
+ const active = summary?.activeCount ?? 0
+ const total = summary?.ownedCount ?? 0
+ const limit = summary?.limit ?? 0
+ const percent = limit > 0 ? Math.min(100, Math.max(0, active / limit * 100)) : 0
+ return (
+ <Popover>
+ <PopoverTrigger
+ openOnHover
+ delay={150}
+ render={
+ <button
+ type="button"
+ data-testid={tid.myBotsPlanSummary}
+ disabled={!summary}
+ aria-label={summary ? `Active Bots: ${active} of ${summary.limit} allowed, ${total} owned, ${isFounder ? "Founder" : summary.plan.displayName} plan` : "Active Bots loading"}
+ className="flex min-h-11 w-fit items-center gap-2 rounded-sm text-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-6"
+ >
+ Active Bots
+ <svg aria-hidden="true" className="size-4 -rotate-90" viewBox="0 0 20 20" fill="none">
+ <circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="2" className="text-border" />
+ <circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="2" pathLength="100" strokeDasharray={`${percent} 100`} strokeLinecap={percent > 0 ? "round" : "butt"} />
+ </svg>
+ </button>
+ }
+ />
+ <PopoverContent className="w-64 overflow-hidden p-0" side="bottom" align="start">
+ <div className="flex flex-col gap-4 p-5">
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="text-sm font-medium">Active bots</span>
+ <span className="font-brand text-xl font-bold leading-none">{isFounder ? "Founder" : summary?.plan.displayName}</span>
+ </div>
+ <p className="text-2xl font-semibold leading-none tracking-tight tabular-nums" aria-label={`${active} of ${limit} active bot slots used`}>
+ {active}<span className="text-lg font-normal text-muted-foreground"> / {limit}</span>
+ </p>
+ <p className="text-sm text-muted-foreground">{total} bots owned</p>
+ {onViewPlan && <PopoverClose onClick={onViewPlan} render={<Button variant="ghost" size="sm" className="-mx-2 min-h-11 justify-between sm:min-h-8" />}>View plan<ArrowRight className="size-3.5" /></PopoverClose>}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/src/web/src/components/community/bots/bot-list-card.dom.test.ts b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
index ed777b339..ce9dccedc 100644
--- a/src/web/src/components/community/bots/bot-list-card.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
@@ -8,6 +8,8 @@ import { tid } from "@/lib/community/testids"
// so we can render just the card meta row and assert the model segment. What we
// assert is the presence/absence of the canonical model test ID and its text.
+vi.mock("@/components/community/billing/billing-plan.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))
+
const useBotsMock = vi.fn()
const bugReportDialogMock = vi.fn()
@@ -18,8 +20,13 @@ vi.mock("next/navigation", () => ({
vi.mock("@/hooks/community/use-machines", () => ({
useMachines: () => ({ machines: [{ id: "mac1", displayName: "Mac", hostname: "mac", status: "online" }] }),
}))
+vi.mock("@/hooks/community/use-billing", () => ({
+ readBillingReturn: () => null,
+ useBilling: () => ({ data: undefined, isPending: true, refresh: vi.fn() }),
+}))
vi.mock("@/hooks/community/use-bots", () => ({
useBots: () => useBotsMock(),
+ useSetBotActive: () => ({ mutateAsync: vi.fn(), isPending: false }),
useDeleteBot: () => ({ mutateAsync: vi.fn(), isPending: false }),
useResetBotSession: () => ({ mutateAsync: vi.fn(), isPending: false }),
useResetMachineAgents: () => ({ mutateAsync: vi.fn(), isPending: false }),
@@ -83,6 +90,7 @@ function bot(over: Partial<BotSummary>): BotSummary {
machineId: "mac1",
runtime: "claude",
modelName: null,
+ isActive: true,
lastRefreshContextAt: null,
dailyActivity: [],
...over,
@@ -142,7 +150,7 @@ describe("BotList — bug-report feature entry", () => {
useBotsMock.mockReturnValue({
bots,
isLoading: false,
- data: { bots },
+ data: { bots, plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 2, activeCount: 2 },
})
const renderer = render()
diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
index 7eb0392a5..816fd6bd5 100644
--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
@@ -16,6 +16,14 @@ const mocks = vi.hoisted(() => ({
audit: null as string | null,
bots: [] as BotSummary[],
botsDataReady: true,
+ isFounder: true,
+ billingReturn: null as string | null,
+ planSummary: {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 1,
+ activeCount: 1,
+ },
machines: [] as Array<Record<string, unknown>>,
botsLoading: false,
machinesLoading: false,
@@ -28,6 +36,7 @@ const mocks = vi.hoisted(() => ({
del: vi.fn(),
resetBot: vi.fn(),
resetMachine: vi.fn(),
+ setActive: vi.fn(),
advance: vi.fn(),
updateResources: vi.fn(),
recoverMachine: vi.fn(),
@@ -44,7 +53,7 @@ vi.mock("next/navigation", () => ({
useSearchParams: () => {
mocks.hookOrder.push("searchParams")
return {
- get: (key: string) => key === "machineId" ? mocks.target : mocks.audit,
+ get: (key: string) => key === "machineId" ? mocks.target : key === "audit" ? mocks.audit : mocks.billingReturn,
toString: () => {
const params = new URLSearchParams()
if (mocks.target) params.set("machineId", mocks.target)
@@ -59,7 +68,7 @@ vi.mock("@/hooks/community/use-bots", () => ({
mocks.hookOrder.push("bots")
return {
bots: mocks.bots,
- data: mocks.botsDataReady ? { bots: mocks.bots } : undefined,
+ data: mocks.botsDataReady ? { bots: mocks.bots, ...mocks.planSummary, isFounder: mocks.isFounder } : undefined,
isLoading: mocks.botsLoading,
}
},
@@ -75,6 +84,10 @@ vi.mock("@/hooks/community/use-bots", () => ({
mocks.hookOrder.push("resetMachine")
return { mutateAsync: mocks.resetMachine }
},
+ useSetBotActive: () => {
+ mocks.hookOrder.push("setActive")
+ return { mutateAsync: mocks.setActive }
+ },
}))
vi.mock("@/hooks/community/use-machines", () => ({
useMachines: () => {
@@ -109,6 +122,11 @@ vi.mock("sonner", () => ({
}))
vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))
+vi.mock("@/hooks/community/use-billing", () => ({
+ readBillingReturn: (value: string | null) => ["checkout", "cancel", "portal"].includes(value ?? "") ? value : null,
+ useBilling: () => ({ data: undefined, isPending: true, refresh: vi.fn() }),
+}))
+
import { useBotListController } from "./bot-list-controller"
let latest: BotListController
@@ -135,6 +153,7 @@ const bot = (id: string, machineId: string): BotSummary => ({
machineId,
runtime: "claude",
modelName: null,
+ isActive: true,
lastRefreshContextAt: null,
dailyActivity: [],
})
@@ -143,11 +162,19 @@ describe("useBotListController", () => {
beforeEach(() => {
vi.clearAllMocks()
vi.useFakeTimers()
+ mocks.isFounder = true
+ mocks.billingReturn = null
mocks.hookOrder.length = 0
mocks.target = "mac1"
mocks.audit = null
mocks.bots = [bot("b1", "mac1")]
mocks.botsDataReady = true
+ mocks.planSummary = {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 1,
+ activeCount: 1,
+ }
mocks.machines = [
{ id: "mac1", displayName: "One", hostname: "one", status: "online" },
{ id: "mac2", displayName: "Two", hostname: "two", status: "online" },
@@ -159,6 +186,7 @@ describe("useBotListController", () => {
mocks.del.mockResolvedValue(undefined)
mocks.resetBot.mockResolvedValue({ ok: true })
mocks.resetMachine.mockResolvedValue({ dispatched: 2 })
+ mocks.setActive.mockResolvedValue({ bot: { id: "b1", isActive: false }, changed: true })
scrollIntoView.mockReset()
})
@@ -172,9 +200,9 @@ describe("useBotListController", () => {
return renderer
}
- it("keeps the exact external hook order and source-owned thirteen states", () => {
+ it("keeps the exact external hook order and source-owned fourteen states", () => {
render()
- expect(mocks.hookOrder.slice(0, 9)).toEqual([
+ expect(mocks.hookOrder.slice(0, 10)).toEqual([
"router",
"searchParams",
"bots",
@@ -183,12 +211,13 @@ describe("useBotListController", () => {
"delete",
"resetBot",
"resetMachine",
+ "setActive",
"dm",
])
- expect(mocks.hookOrder[9]).toBe("onboarding")
+ expect(mocks.hookOrder[10]).toBe("onboarding")
const source = readWebSource("src/components/community/bots/bot-list-controller.ts")
- expect(source.match(/useState(?:<[^\n]+>)?\(/g)).toHaveLength(13)
+ expect(source.match(/useState(?:<[^\n]+>)?\(/g)).toHaveLength(15)
expect(source).not.toMatch(/useCallback\(/)
expect(source.match(/useMemo\(/g)).toHaveLength(1)
const orderedHooks = [
@@ -209,16 +238,18 @@ describe("useBotListController", () => {
"const [confirmResetMachine",
"const [collapsedMachines",
"const [helpOpen",
+ "const [pendingActiveBotIds",
"const del = useDeleteBot()",
"const resetSession = useResetBotSession()",
"const resetMachineAgents = useResetMachineAgents()",
+ "const setActive = useSetBotActive()",
"const createOrGetDm = useCreateOrGetDm()",
"const onboardingState = useCommunityOnboarding()",
"const groups = useMemo",
"const [highlightId",
"const groupRefs = useRef",
"const scrolledForRef = useRef",
- "useEffect(() =>",
+ "useEffect(() => {\n if (!targetMachineId",
]
const positions = orderedHooks.map((needle) => source.indexOf(needle))
expect(positions.every((position) => position >= 0)).toBe(true)
@@ -285,6 +316,106 @@ describe("useBotListController", () => {
expect(latest.machineName("gone")).toBe("Unknown machine")
})
+ it("projects plan inventory and blocks create at owned capacity with recovery copy", () => {
+ mocks.target = null
+ mocks.planSummary = {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 3,
+ activeCount: 2,
+ }
+ render()
+ expect(latest.planSummary).toEqual({ ...mocks.planSummary, isFounder: mocks.isFounder })
+ expect(latest.isCreateDisabled).toBe(true)
+ act(() => latest.openGuidedCreate())
+ expect(latest.createOpen).toBe(false)
+ expect(latest.billingOpen).toBe(true)
+ expect(mocks.toastError).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ { isFounder: false, ownedCount: 3 },
+ { isFounder: false, ownedCount: 4 },
+ { isFounder: true, ownedCount: 3 },
+ { isFounder: true, ownedCount: 4 },
+ ])("opens capacity recovery for owned=$ownedCount and Founder=$isFounder", ({ isFounder, ownedCount }) => {
+ mocks.target = null
+ mocks.isFounder = isFounder
+ mocks.planSummary = { ...mocks.planSummary, ownedCount, limit: 3 }
+ render()
+ expect(latest.canShowLimit).toBe(true)
+ act(() => latest.openGuidedCreate())
+ expect(latest.billingOpen).toBe(true)
+ expect(latest.createOpen).toBe(false)
+ })
+
+ it.each([false, true])("does not infer capacity without an exhausted loaded plan (loaded=%s)", (loaded) => {
+ mocks.target = null
+ mocks.botsDataReady = loaded
+ mocks.planSummary = { ...mocks.planSummary, ownedCount: 2, limit: 3 }
+ render()
+ expect(latest.canShowLimit).toBe(loaded)
+ expect(latest.isCreateDisabled).toBe(false)
+ act(() => latest.openGuidedCreate())
+ expect(latest.createOpen).toBe(true)
+ expect(latest.billingOpen).toBe(false)
+ expect(mocks.toastError).not.toHaveBeenCalled()
+ })
+
+ it("leaves billing returns to settings and opens the unified plan destination", () => {
+ mocks.billingReturn = "checkout"
+ window.history.replaceState(null, "", "/c/me/bots?billing=checkout&audit=bot1#details")
+ render()
+ expect(latest.billingOpen).toBe(false)
+ act(() => latest.viewPlan())
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe("/c/me/bots?audit=bot1&settings=billing#details")
+ expect(mocks.push).not.toHaveBeenCalled()
+ })
+
+ it("disables only the toggled bot, suppresses double clicks, and clears pending on success", async () => {
+ mocks.target = null
+ let resolveActive!: (value: { bot: { id: string; isActive: boolean }; changed: boolean }) => void
+ mocks.setActive.mockReturnValue(new Promise((resolve) => { resolveActive = resolve }))
+ render()
+ let completion!: Promise<void>
+ act(() => { completion = latest.setBotActive(mocks.bots[0]!, false) })
+ expect(latest.pendingActiveBotIds).toEqual(new Set(["b1"]))
+ await act(async () => { await latest.setBotActive(mocks.bots[0]!, false) })
+ expect(mocks.setActive).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ resolveActive({ bot: { id: "b1", isActive: false }, changed: true })
+ await completion
+ })
+ expect(latest.pendingActiveBotIds).toEqual(new Set())
+ expect(mocks.toastSuccess).toHaveBeenCalledWith("b1 is now Inactive")
+ })
+
+ it("keeps the prior state and gives an actionable capacity recovery on toggle failure", async () => {
+ mocks.target = null
+ mocks.setActive.mockRejectedValue({ status: 409, message: "BOT_ACTIVE_LIMIT_REACHED" })
+ render()
+ await act(async () => { await latest.setBotActive(mocks.bots[0]!, false) })
+ expect(latest.bots[0]?.isActive).toBe(true)
+ expect(latest.pendingActiveBotIds).toEqual(new Set())
+ expect(mocks.toastError).toHaveBeenCalledWith(
+ "Plan limit reached — make another bot inactive or change plan.",
+ )
+ expect(mocks.toastApiError).not.toHaveBeenCalled()
+ })
+
+ it("reports a generic activation failure through the shared API error path", async () => {
+ mocks.target = null
+ const error = new Error("activation failed")
+ mocks.setActive.mockRejectedValue(error)
+ render()
+
+ await act(async () => { await latest.setBotActive(mocks.bots[0]!, false) })
+
+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Couldn't make b1 inactive")
+ expect(mocks.toastError).not.toHaveBeenCalled()
+ expect(latest.pendingActiveBotIds).toEqual(new Set())
+ })
+
it("does nothing without a target or without bots", () => {
mocks.target = null
render()
diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.ts
index 341bd216f..fc0632e6d 100644
--- a/src/web/src/components/community/bots/bot-list-controller.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.ts
@@ -13,6 +13,7 @@ import {
useDeleteBot,
useResetBotSession,
useResetMachineAgents,
+ useSetBotActive,
type BotSummary,
} from "@/hooks/community/use-bots"
import { useCreateOrGetDm } from "@/hooks/community/mutations"
@@ -32,6 +33,14 @@ export function useBotListController(): BotListController {
const botsQuery = useBots()
const { bots, isLoading } = botsQuery
const botsResolved = botsQuery.data !== undefined
+ const [billingOpen, setBillingOpen] = useState(false)
+ const canShowLimit = botsResolved
+ const viewPlan = () => {
+ const next = new URL(window.location.href)
+ next.searchParams.delete("billing")
+ next.searchParams.set("settings", "billing")
+ window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)
+ }
const { machines, isLoading: machinesLoading } = useMachines()
const profilesByUserId = useProfilesByUserId()
const [createOpen, setCreateOpen] = useState(false)
@@ -48,15 +57,37 @@ export function useBotListController(): BotListController {
() => new Set(),
)
const [helpOpen, setHelpOpen] = useState(false)
+ const [pendingActiveBotIds, setPendingActiveBotIds] = useState<Set<string>>(
+ () => new Set(),
+ )
const del = useDeleteBot()
const resetSession = useResetBotSession()
const resetMachineAgents = useResetMachineAgents()
+ const setActive = useSetBotActive()
const createOrGetDm = useCreateOrGetDm()
const onboardingState = useCommunityOnboarding()
const guidedActive = onboardingState?.status === "active" && onboardingState.stage === "bot"
const guidedPendingBotId = guidedActive ? onboardingState.botId : undefined
const guidedNeedsMachine =
guidedActive && !machines.some((machine) => isPresenceOnline(machine.status))
+ const guidedCreateLabel = guidedNeedsMachine
+ ? "Connect a machine"
+ : guidedPendingBotId
+ ? "Open bot chat"
+ : "Create a bot"
+ const planSummary = botsQuery.data
+ ? {
+ plan: botsQuery.data.plan,
+ limit: botsQuery.data.limit,
+ ownedCount: botsQuery.data.ownedCount,
+ activeCount: botsQuery.data.activeCount,
+ isFounder: botsQuery.data.isFounder,
+ }
+ : null
+ const isAtCapacity = Boolean(
+ planSummary && planSummary.ownedCount >= planSummary.limit,
+ )
+ const isCreateDisabled = isAtCapacity && guidedCreateLabel === "Create a bot"
const chatWithBot = async (bot: BotSummary) => {
try {
@@ -99,14 +130,35 @@ export function useBotListController(): BotListController {
void openGuidedBotDm(state.botId)
return
}
+ if (isCreateDisabled) {
+ setBillingOpen(true)
+ return
+ }
setCreateOpen(true)
}
- const guidedCreateLabel = guidedNeedsMachine
- ? "Connect a machine"
- : guidedPendingBotId
- ? "Open bot chat"
- : "Create a bot"
+ const setBotActive = async (bot: BotSummary, active: boolean) => {
+ if (pendingActiveBotIds.has(bot.id) || bot.isActive === active) return
+ setPendingActiveBotIds((current) => new Set(current).add(bot.id))
+ try {
+ await setActive.mutateAsync({ id: bot.id, active })
+ toast.success(`${bot.name} is now ${active ? "Active" : "Inactive"}`)
+ } catch (error) {
+ const status = (error as { status?: number } | undefined)?.status
+ const message = (error as { message?: string } | undefined)?.message ?? ""
+ if (status === 409 && message === "BOT_ACTIVE_LIMIT_REACHED") {
+ toast.error("Plan limit reached — make another bot inactive or change plan.")
+ } else {
+ toastApiError(error, `Couldn't make ${bot.name} ${active ? "active" : "inactive"}`)
+ }
+ } finally {
+ setPendingActiveBotIds((current) => {
+ const next = new Set(current)
+ next.delete(bot.id)
+ return next
+ })
+ }
+ }
const machineName = (id: string): string => {
const machine = machines.find((item) => item.id === id)
@@ -252,7 +304,15 @@ export function useBotListController(): BotListController {
}
return {
+ viewPlan,
+ billingOpen,
+ setBillingOpen,
+ canShowLimit,
bots,
+ planSummary,
+ isCreateDisabled,
+ pendingActiveBotIds,
+ setBotActive,
isLoading,
machines,
machinesLoading,
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
index de25ec9a4..a43da8a63 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import type { BotSummary } from "@/hooks/community/use-bots"
import { tid } from "@/lib/community/testids"
import type { BotListController, BotMachineGroup } from "./bot-list-types"
-import { act, fireEvent, render } from "@/test/react-dom-harness"
+import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
avatar: vi.fn(),
@@ -74,6 +74,7 @@ const bot = (overrides: Partial<BotSummary> = {}): BotSummary => ({
machineId: "mac1",
runtime: "claude",
modelName: "claude-opus-4-6",
+ isActive: true,
lastRefreshContextAt: null,
dailyActivity: [],
...overrides,
@@ -83,6 +84,8 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
const noop = vi.fn()
return {
profilesByUserId: new Map(),
+ pendingActiveBotIds: new Set(),
+ setBotActive: noop,
collapsedMachines: new Set(),
setCollapsedMachines: noop,
setConfirmResetMachine: noop,
@@ -184,6 +187,54 @@ describe("renderBotMachineGroup", () => {
.toHaveLength(1)
})
+ it("renders menu actions, keeps entitlement separate from presence, and scopes pending", () => {
+ const setBotActive = vi.fn()
+ const activeBot = bot({ id: "active", name: "Active Bot" })
+ const inactiveBot = bot({ id: "inactive", name: "Inactive Bot", isActive: false })
+ const renderer = render(renderBotMachineGroup(
+ group({ bots: [activeBot, inactiveBot] }),
+ controller({
+ profilesByUserId: new Map([
+ ["active", { id: "active", presence: "online" }],
+ ["inactive", { id: "inactive", presence: "online" }],
+ ]),
+ pendingActiveBotIds: new Set(["active"]),
+ setBotActive,
+ }),
+ ))
+ const activeSwitch = renderer.getByRole("button", { name: "Deactivate" })
+ const inactiveSwitch = renderer.getByTestId(tid.botActive("inactive"))
+ expect(activeSwitch).toBeDisabled()
+ expect(activeSwitch).toHaveAttribute("aria-busy", "true")
+ expect(inactiveSwitch).not.toBeDisabled()
+ expect(renderer.getByTestId(tid.botActive("active"))).toBe(activeSwitch)
+ expect(renderer.queryByRole("switch")).not.toBeInTheDocument()
+ expect(renderer.getAllByText("Online")).toHaveLength(1)
+ expect(renderer.getAllByText("Offline")).toHaveLength(1)
+ expect(renderer.queryByRole("button", { name: "Bring online" })).not.toBeInTheDocument()
+ const inlineActivate = renderer.getAllByRole("button", { name: "Activate" })
+ .find((element) => !element.hasAttribute("data-host"))!
+ expect(inlineActivate).toHaveClass("h-6", "shrink-0", "px-2", "text-xs")
+ fireEvent.click(inlineActivate)
+ expect(setBotActive).toHaveBeenCalledWith(inactiveBot, true)
+ fireEvent.click(inactiveSwitch)
+ expect(setBotActive).toHaveBeenCalledWith(inactiveBot, true)
+ })
+
+ it("toggles the focused menu action with the keyboard", async () => {
+ const setBotActive = vi.fn()
+ const item = bot({ isActive: false })
+ const renderer = render(renderBotMachineGroup(
+ group({ bots: [item] }),
+ controller({ setBotActive }),
+ ))
+ const activeSwitch = renderer.getByTestId(tid.botActive("b1"))
+ activeSwitch.focus()
+ expect(activeSwitch).toHaveFocus()
+ await setupUser().keyboard(" ")
+ expect(setBotActive).toHaveBeenCalledWith(item, true)
+ })
+
it("projects bot-owned fixed-scale heatmaps and machine-scoped quota once", () => {
const usage = {
capability: "supported" as const,
@@ -352,6 +403,7 @@ describe("renderBotMachineGroup", () => {
" Edit",
" Reset",
" Report a problem",
+ " Deactivate",
" Delete",
])
expect(items[3]).toHaveAttribute("data-testid", "bot-reset-session-item")
@@ -363,7 +415,7 @@ describe("renderBotMachineGroup", () => {
.toEqual(["span", "span", "span", "span"])
expect(items[1]!.querySelectorAll("activity-icon")).toHaveLength(1)
expect(items[3]!.querySelectorAll("reset-icon")).toHaveLength(1)
- expect(items[5]).toHaveAttribute("data-variant", "destructive")
+ expect(items[6]).toHaveAttribute("data-variant", "destructive")
for (const item of items) fireEvent.click(item)
expect(chatWithBot).toHaveBeenCalledWith(item)
expect(openActivity).toHaveBeenCalledWith(item)
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsx
index 5a4b881e6..1e695827d 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx
+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx
@@ -80,7 +80,9 @@ export function renderBotMachineGroup(
</div>
<div className="flex flex-col gap-3" hidden={collapsed}>
{bots.map((bot) => {
- const online = controller.profilesByUserId.get(bot.id)?.presence === "online"
+ const online = bot.isActive
+ && controller.profilesByUserId.get(bot.id)?.presence === "online"
+ const activePending = controller.pendingActiveBotIds.has(bot.id)
return (
<Card key={bot.id} className="flex flex-col gap-3 p-4">
<div className="flex items-start justify-between gap-3">
@@ -107,17 +109,23 @@ export function renderBotMachineGroup(
/>
{online ? "Online" : "Offline"}
</span>
- {!online && machine && (
+ {(!bot.isActive || (!online && machine)) && (
<Button
size="sm"
variant="outline"
className="h-6 shrink-0 px-2 text-xs"
+ disabled={!bot.isActive && activePending}
+ aria-busy={!bot.isActive && activePending || undefined}
onClick={(event) => {
event.stopPropagation()
- controller.bringMachineOnline(machine.id)
+ if (!bot.isActive) {
+ void controller.setBotActive(bot, true)
+ } else if (machine) {
+ controller.bringMachineOnline(machine.id)
+ }
}}
>
- Bring online
+ {bot.isActive ? "Bring online" : "Activate"}
</Button>
)}
</div>
@@ -201,6 +209,14 @@ export function renderBotMachineGroup(
>
<span className="size-4" aria-hidden /> Report a problem
</DropdownMenuItem>
+ <DropdownMenuItem
+ data-testid={tid.botActive(bot.id)}
+ disabled={activePending}
+ aria-busy={activePending || undefined}
+ onClick={() => { void controller.setBotActive(bot, !bot.isActive) }}
+ >
+ <span className="size-4" aria-hidden /> {bot.isActive ? "Deactivate" : "Activate"}
+ </DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => controller.setConfirmDelete(bot)}
diff --git a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts b/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
index fd323105c..29b459f1f 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
@@ -20,6 +20,7 @@ function host(name: string) {
vi.mock("@/components/community/onboarding-tiles/agent-help-gallery", () => ({
AgentHelpGallery: host("help"),
}))
+vi.mock("@/components/community/billing/billing-sheet", () => ({ BillingSheet: host("billing") }))
vi.mock("./bot-activity-modal", () => ({ BotActivityModal: host("activity") }))
vi.mock("./bug-report-dialog", () => ({ BugReportDialog: host("bug") }))
vi.mock("./create-bot-sheet", () => ({ CreateBotSheet: host("create") }))
@@ -89,13 +90,14 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
describe("renderBotListOverlaySlots", () => {
beforeEach(() => vi.clearAllMocks())
- it("returns exactly eight named elements without an aggregate reconciliation boundary", () => {
+ it("returns all named elements without an aggregate reconciliation boundary", () => {
const emptySlots = renderBotListOverlaySlots(controller())
expect(emptySlots.bug).toBeNull()
const slots = renderBotListOverlaySlots(controller({
bugReportBot: { id: "b1", name: "Blake" },
}))
expect(Object.keys(slots)).toEqual([
+ "billing",
"create",
"help",
"edit",
@@ -110,8 +112,9 @@ describe("renderBotListOverlaySlots", () => {
expect(Array.isArray(slot)).toBe(false)
if (React.isValidElement(slot)) expect(slot.type).not.toBe(React.Fragment)
}
- expect(Object.values(slots).slice(0, 5).map((slot) =>
+ expect(Object.values(slots).slice(0, 6).map((slot) =>
(slot!.type as React.ComponentType).displayName)).toEqual([
+ "Host(billing)",
"Host(create)",
"Host(help)",
"Host(edit)",
diff --git a/src/web/src/components/community/bots/bot-list-overlays.tsx b/src/web/src/components/community/bots/bot-list-overlays.tsx
index 0d9480565..8e7220d52 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.tsx
+++ b/src/web/src/components/community/bots/bot-list-overlays.tsx
@@ -14,11 +14,13 @@ import { BugReportDialog } from "./bug-report-dialog"
import { CreateBotSheet } from "./create-bot-sheet"
import { EditBotSheet } from "./edit-bot-sheet"
import type { BotListController, BotListOverlaySlots } from "./bot-list-types"
+import { BillingSheet } from "@/components/community/billing/billing-sheet"
export function renderBotListOverlaySlots(
controller: BotListController,
): BotListOverlaySlots {
return {
+ billing: <BillingSheet open={controller.billingOpen && controller.canShowLimit} onOpenChange={controller.setBillingOpen} limit={controller.planSummary?.limit ?? 0} onViewPlan={controller.viewPlan} />,
create: (
<CreateBotSheet
open={controller.createOpen}
diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.ts
index 261629b55..043a9467f 100644
--- a/src/web/src/components/community/bots/bot-list-types.ts
+++ b/src/web/src/components/community/bots/bot-list-types.ts
@@ -1,5 +1,5 @@
import type { Dispatch, SetStateAction } from "react"
-import type { BotSummary } from "@/hooks/community/use-bots"
+import type { BotPlanSummary, BotSummary } from "@/hooks/community/use-bots"
import type { MachineSummary } from "@/hooks/community/use-machines"
import type { CommunityProfile } from "@/lib/community/models/people"
@@ -14,7 +14,15 @@ export type BotMachineGroup = {
}
export type BotListController = {
+ viewPlan: () => void
+ billingOpen: boolean
+ setBillingOpen: (open: boolean) => void
+ canShowLimit: boolean
bots: BotSummary[]
+ planSummary: BotPlanSummary | null
+ isCreateDisabled: boolean
+ pendingActiveBotIds: ReadonlySet<string>
+ setBotActive: (bot: BotSummary, active: boolean) => Promise<void>
isLoading: boolean
machines: MachineSummary[]
machinesLoading: boolean
@@ -61,6 +69,7 @@ export type BotListController = {
}
export type BotListOverlaySlots = {
+ billing: React.ReactElement
create: React.ReactElement
help: React.ReactElement
edit: React.ReactElement
diff --git a/src/web/src/components/community/bots/bot-list-view.dom.test.ts b/src/web/src/components/community/bots/bot-list-view.dom.test.ts
index 1528d2fc9..5d842a746 100644
--- a/src/web/src/components/community/bots/bot-list-view.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-view.dom.test.ts
@@ -2,6 +2,7 @@ import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import type { BotListController } from "./bot-list-types"
import { fireEvent, render } from "@/test/react-dom-harness"
+import { tid } from "@/lib/community/testids"
const mocks = vi.hoisted(() => ({
group: vi.fn(),
@@ -40,12 +41,18 @@ vi.mock("@/components/community/onboarding-tiles/create-tile", () => ({
CreateTile: () => React.createElement("create-tile"),
}))
+vi.mock("@/components/community/billing/billing-sheet", () => ({ BillingSheet: () => null }))
+
import { BotListSkeleton, renderBotListView } from "./bot-list-view"
function controller(overrides: Partial<BotListController> = {}): BotListController {
const noop = vi.fn()
return {
bots: [],
+ planSummary: null,
+ isCreateDisabled: false,
+ pendingActiveBotIds: new Set(),
+ setBotActive: noop,
isLoading: false,
machines: [],
machinesLoading: false,
@@ -128,6 +135,7 @@ describe("renderBotListView", () => {
expect(withClassFragment(renderer.container, "size-10 shrink-0 rounded-full")).toHaveLength(3)
expect(withClassFragment(renderer.container, "h-6 w-40 max-w-full rounded")).toHaveLength(3)
expect(withClassFragment(renderer.container, "h-4 w-48 max-w-full rounded")).toHaveLength(3)
+ expect(withClassFragment(renderer.container, "h-4 w-40 rounded")).toHaveLength(0)
expect(withClassFragment(renderer.container, "size-8 shrink-0 rounded-md")).toHaveLength(3)
expect(mocks.overlays).not.toHaveBeenCalled()
expect(mocks.createSheet).not.toHaveBeenCalled()
@@ -219,9 +227,7 @@ describe("renderBotListView", () => {
expect(withExactClass(renderer.container,
"flex items-center justify-between gap-4")).toHaveLength(1)
expect(renderer.getByText("My Bots")).toHaveClass("text-xl", "font-medium", "text-foreground")
- expect(renderer.getByText(
- "Bots you own — they show up as friends and can be added to any server.",
- )).toHaveClass("text-sm", "text-muted-foreground")
+ expect(renderer.getByRole("button", { name: "Active Bots loading" })).toBeDisabled()
expect(withExactClass(renderer.container, "flex items-center gap-1")).toHaveLength(1)
expect(withExactClass(renderer.container, "flex flex-col gap-6")).toHaveLength(1)
fireEvent.click(renderer.getByRole("button", { name: "How your agent works" }))
@@ -241,6 +247,54 @@ describe("renderBotListView", () => {
])
})
+ it("exposes the active summary trigger and explains why create is disabled at capacity", () => {
+ const openGuidedCreate = vi.fn()
+ const renderer = render(renderBotListView({}, controller({
+ bots: [{ id: "b1" }] as BotListController["bots"],
+ planSummary: {
+ isFounder: false,
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 3,
+ activeCount: 2,
+ },
+ isCreateDisabled: true,
+ openGuidedCreate,
+ groups: [],
+ })))
+ expect(renderer.getByTestId(tid.myBotsPlanSummary)).toBe(
+ renderer.getByRole("button", { name: "Active Bots: 2 of 3 allowed, 3 owned, Free plan" }),
+ )
+ expect(renderer.queryByRole("status")).not.toBeInTheDocument()
+ const create = renderer.getByTestId(tid.createBot)
+ expect(create).toBeDisabled()
+ expect(create).toHaveAttribute("title", "Bot limit reached. Delete a bot or change plan to create another.")
+ fireEvent.click(create)
+ expect(openGuidedCreate).not.toHaveBeenCalled()
+ })
+
+ it("preserves the create label at capacity for a non-Founder", () => {
+ const open = vi.fn()
+ const ui = render(renderBotListView({}, controller({
+ bots: [{ id: "b1" }] as BotListController["bots"],
+ isCreateDisabled: true,
+ canShowLimit: true,
+ openGuidedCreate: open,
+ })))
+ fireEvent.click(ui.getByRole("button", { name: "Create a bot" }))
+ expect(open).toHaveBeenCalledOnce()
+ expect(ui.queryByRole("button", { name: "Plan and billing" })).toBeNull()
+ })
+
+ it("keeps Founder visible with no bots and hides its billing entry", () => {
+ const ui = render(renderBotListView({}, controller({
+ planSummary: { plan: { id: "house", displayName: "House" }, isFounder: true, limit: 40, activeCount: 0, ownedCount: 0 },
+ canShowLimit: false,
+ })))
+ expect(ui.getByText("Founder plan")).toBeInTheDocument()
+ expect(ui.queryByTestId(tid.myBotsBilling)).toBeNull()
+ })
+
it("keeps the same outer/back-bar contract in loading, empty, and populated branches", () => {
const onBack = vi.fn()
const loadingRenderer = render(React.createElement(BotListSkeleton, { onBack }))
diff --git a/src/web/src/components/community/bots/bot-list-view.tsx b/src/web/src/components/community/bots/bot-list-view.tsx
index 4e9d4d8b9..4b22d89e1 100644
--- a/src/web/src/components/community/bots/bot-list-view.tsx
+++ b/src/web/src/components/community/bots/bot-list-view.tsx
@@ -3,10 +3,13 @@ import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { CreateTile } from "@/components/community/onboarding-tiles/create-tile"
+import { tid } from "@/lib/community/testids"
+import { BotActiveSummary } from "./bot-active-summary"
import { CreateBotSheet } from "./create-bot-sheet"
import { renderBotMachineGroup } from "./bot-list-machine-group"
import { renderBotListOverlaySlots } from "./bot-list-overlays"
import type { BotListController, BotListProps } from "./bot-list-types"
+import { BillingSheet } from "@/components/community/billing/billing-sheet"
function BotCardSkeleton() {
return (
@@ -122,10 +125,13 @@ export function renderBotListView(
<div data-onboarding-target="create-bot" className="w-fit">
<Button
onClick={needsMachine ? controller.openMachines : controller.openGuidedCreate}
+ disabled={!needsMachine && controller.isCreateDisabled && !controller.canShowLimit}
+ data-testid={!needsMachine ? tid.createBot : undefined}
>
{needsMachine ? "Connect a machine" : controller.guidedCreateLabel}
</Button>
</div>
+ {controller.planSummary?.isFounder && <p className="text-sm text-muted-foreground">Founder plan</p>}
</div>
<CreateBotSheet
open={controller.createOpen}
@@ -134,6 +140,7 @@ export function renderBotListView(
guided={controller.guidedActive}
avatarSeed={controller.guidedAvatarSeed}
/>
+ <BillingSheet open={controller.billingOpen && controller.canShowLimit} onOpenChange={controller.setBillingOpen} limit={controller.planSummary?.limit ?? 0} onViewPlan={controller.viewPlan} />
</div>
)
}
@@ -146,9 +153,7 @@ export function renderBotListView(
<header className="flex items-center justify-between gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-medium text-foreground">My Bots</h1>
- <p className="text-sm text-muted-foreground">
- Bots you own — they show up as friends and can be added to any server.
- </p>
+ <BotActiveSummary onViewPlan={controller.viewPlan} summary={controller.planSummary} isFounder={controller.planSummary?.isFounder} />
</div>
<div className="flex items-center gap-1">
<Button
@@ -161,7 +166,12 @@ export function renderBotListView(
<HelpCircle className="size-5" />
</Button>
<div data-onboarding-target="create-bot" className="w-fit">
- <Button onClick={controller.openGuidedCreate}>{controller.guidedCreateLabel}</Button>
+ <Button
+ onClick={controller.openGuidedCreate}
+ disabled={controller.isCreateDisabled && !controller.canShowLimit}
+ data-testid={tid.createBot}
+ title={controller.isCreateDisabled ? "Bot limit reached. Delete a bot or change plan to create another." : undefined}
+ >{controller.guidedCreateLabel}</Button>
</div>
</div>
</header>
@@ -172,6 +182,7 @@ export function renderBotListView(
</div>
{overlays.create}
+ {overlays.billing}
{overlays.help}
{overlays.edit}
{overlays.activity}
diff --git a/src/web/src/components/community/machines/machine-capacity.dom.test.tsx b/src/web/src/components/community/machines/machine-capacity.dom.test.tsx
new file mode 100644
index 000000000..81ba3c08b
--- /dev/null
+++ b/src/web/src/components/community/machines/machine-capacity.dom.test.tsx
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vitest"
+import { render, setupUser } from "@/test/react-dom-harness"
+import { MachineCapacityUsage, MachineLimitDialog } from "./machine-capacity"
+
+const summary = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 5, onlineCount: 1 }
+
+describe("Machine capacity", () => {
+ it("separates online use from retained owned machines and opens billing", async () => {
+ const viewPlan = vi.fn()
+ const view = render(<MachineCapacityUsage summary={summary} onViewPlan={viewPlan} />)
+ const user = setupUser()
+ await user.click(view.getByRole("button", { name: "Online machines: 1 of 1 allowed, 5 owned, Free plan" }))
+ expect(view.getByText("5 machines owned")).toBeInTheDocument()
+ expect(view.getByLabelText("1 of 1 online machine slots used")).toBeInTheDocument()
+ expect(view.container.querySelector('[pathLength="100"]')).toHaveAttribute("stroke-dasharray", "100 100")
+ await user.click(view.getByRole("button", { name: "View plan" }))
+ expect(viewPlan).toHaveBeenCalledOnce()
+ })
+ it("shows Founder allowance and safe zero/loading states", () => {
+ const view = render(<MachineCapacityUsage summary={{ ...summary, isFounder: true, limit: 10, onlineCount: 0 }} onViewPlan={vi.fn()} />)
+ expect(view.getByRole("button", { name: /Founder plan/ })).toBeEnabled()
+ expect(view.container.querySelector('[pathLength="100"]')).toHaveAttribute("stroke-dasharray", "0 100")
+ view.rerender(<MachineCapacityUsage summary={null} onViewPlan={vi.fn()} />)
+ expect(view.getByRole("button", { name: "Machine usage loading" })).toBeDisabled()
+ })
+ it("explains that offline machines count and closes before opening the plan", async () => {
+ const close = vi.fn(), viewPlan = vi.fn()
+ const view = render(<MachineLimitDialog open onOpenChange={close} onViewPlan={viewPlan} limit={1} />)
+ expect(view.getByText(/Offline machines also count/)).toBeInTheDocument()
+ await setupUser().click(view.getByRole("button", { name: "View plan" }))
+ expect(close).toHaveBeenCalledWith(false)
+ expect(viewPlan).toHaveBeenCalledOnce()
+ })
+ it("explains online capacity for a reconnect instead of asking to delete records", () => {
+ const view = render(<MachineLimitDialog open reconnect onOpenChange={vi.fn()} onViewPlan={vi.fn()} limit={1} />)
+ expect(view.getByText(/All online slots are in use/)).toBeInTheDocument()
+ expect(view.queryByText(/Offline machines also count/)).not.toBeInTheDocument()
+ })
+ it("dismisses without navigating", async () => {
+ const close = vi.fn(), viewPlan = vi.fn()
+ const view = render(<MachineLimitDialog open onOpenChange={close} onViewPlan={viewPlan} limit={5} />)
+ await setupUser().click(view.getByRole("button", { name: "Got it" }))
+ expect(close).toHaveBeenCalledWith(false)
+ expect(viewPlan).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/machines/machine-capacity.tsx b/src/web/src/components/community/machines/machine-capacity.tsx
new file mode 100644
index 000000000..aa18fcbef
--- /dev/null
+++ b/src/web/src/components/community/machines/machine-capacity.tsx
@@ -0,0 +1,42 @@
+"use client"
+
+import { ArrowRight } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
+import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
+import type { MachineCapacity } from "@/hooks/community/use-machines"
+
+export function MachineCapacityUsage({ summary, onViewPlan }: { summary: MachineCapacity | null; onViewPlan: () => void }) {
+ const online = summary?.onlineCount ?? 0
+ const limit = summary?.limit ?? 0
+ const percent = limit > 0 ? Math.min(100, online / limit * 100) : 0
+ const name = summary?.isFounder ? "Founder" : summary?.plan.displayName
+ return <Popover>
+ <PopoverTrigger openOnHover delay={150} render={<button type="button" data-testid="machine-plan-summary" disabled={!summary}
+ aria-label={summary ? `Online machines: ${online} of ${limit} allowed, ${summary.ownedCount} owned, ${name} plan` : "Machine usage loading"}
+ className="flex min-h-11 w-fit items-center gap-2 rounded-sm text-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-6">
+ Online machines
+ <svg aria-hidden="true" className="size-4 -rotate-90" viewBox="0 0 20 20" fill="none">
+ <circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="2" className="text-border" />
+ <circle cx="10" cy="10" r="8" stroke="currentColor" strokeWidth="2" pathLength="100" strokeDasharray={`${percent} 100`} strokeLinecap={percent > 0 ? "round" : "butt"} />
+ </svg>
+ </button>} />
+ <PopoverContent className="w-64 overflow-hidden p-0" side="bottom" align="start">
+ <div className="flex flex-col gap-4 p-5">
+ <div className="flex items-baseline justify-between gap-3"><span className="text-sm font-medium">Online machines</span><span className="font-brand text-xl font-bold leading-none">{name}</span></div>
+ <p className="text-2xl font-semibold leading-none tracking-tight tabular-nums" aria-label={`${online} of ${limit} online machine slots used`}>{online}<span className="text-lg font-normal text-muted-foreground"> / {limit}</span></p>
+ <p className="text-sm text-muted-foreground">{summary?.ownedCount ?? 0} {summary?.ownedCount === 1 ? "machine" : "machines"} owned</p>
+ <PopoverClose onClick={onViewPlan} render={<Button variant="ghost" size="sm" className="-mx-2 min-h-11 justify-between sm:min-h-8" />}>View plan<ArrowRight className="size-3.5" /></PopoverClose>
+ </div>
+ </PopoverContent>
+ </Popover>
+}
+
+export function MachineLimitDialog({ open, onOpenChange, onViewPlan, limit, reconnect = false }: { open: boolean; onOpenChange: (open: boolean) => void; onViewPlan: () => void; limit: number; reconnect?: boolean }) {
+ return <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md" data-testid="machine-limit-modal">
+ <DialogHeader><DialogTitle>Machine limit reached</DialogTitle><DialogDescription>{reconnect ? `Your plan allows ${limit} online ${limit === 1 ? "machine" : "machines"}. All online slots are in use. Disconnect another machine or change your plan before reconnecting this one.` : `Your plan allows ${limit} ${limit === 1 ? "machine" : "machines"}. Offline machines also count. Remove a machine or change your plan before connecting another.`}</DialogDescription></DialogHeader>
+ <DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>Got it</Button><Button onClick={() => { onOpenChange(false); onViewPlan() }}>View plan</Button></DialogFooter>
+ </DialogContent>
+ </Dialog>
+}
diff --git a/src/web/src/components/community/machines/machine-list.dom.test.ts b/src/web/src/components/community/machines/machine-list.dom.test.ts
index 680dc66bc..0a2c9e768 100644
--- a/src/web/src/components/community/machines/machine-list.dom.test.ts
+++ b/src/web/src/components/community/machines/machine-list.dom.test.ts
@@ -4,10 +4,12 @@ import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
apiFetch: vi.fn(),
+ fetchQuery: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn(),
fetchLatestDaemonVersion: vi.fn(),
machinesLoading: { current: false },
+ capacity: { current: { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, onlineCount: 0 } },
machines: { current: [] as unknown[] },
onboardingState: { current: "done" as unknown },
guideMotion: vi.fn(),
@@ -52,7 +54,7 @@ vi.mock("next/navigation", () => ({
}))
vi.mock("@tanstack/react-query", () => ({
- useQueryClient: () => ({ setQueryData: vi.fn() }),
+ useQueryClient: () => ({ setQueryData: vi.fn(), invalidateQueries: vi.fn(), fetchQuery: mocks.fetchQuery }),
}))
vi.mock("@/components/ui/button", () => ({
@@ -79,10 +81,11 @@ vi.mock("./machine-card", () => ({
MachineCardFrame: ({ children }: React.PropsWithChildren) =>
React.createElement("machine-card-frame", {}, children),
}))
-vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: () => null }))
+vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: ({ open, onLimitReached }: { open: boolean; onLimitReached: () => void }) => open ? React.createElement("button", { "data-testid": "test-pair-sheet", onClick: onLimitReached }, "Simulate server limit") : null }))
vi.mock("@/components/community/onboarding-tiles/connect-tile", () => ({ ConnectTile: () => null }))
vi.mock("@/hooks/community/use-machines", () => ({
- useMachines: () => ({ machines: mocks.machines.current, isLoading: mocks.machinesLoading.current }),
+ machinesQueryFn: vi.fn(),
+ useMachines: () => ({ machines: mocks.machines.current, isLoading: mocks.machinesLoading.current, data: { machineCapacity: mocks.capacity.current } }),
}))
vi.mock("@/hooks/community/use-bots", () => ({ useBots: () => ({ bots: [] }) }))
vi.mock("@/stores/community", () => ({
@@ -99,7 +102,7 @@ vi.mock("@/lib/community-onboarding", () => ({
vi.mock("@/lib/api/config", () => ({
fetchLatestDaemonVersion: mocks.fetchLatestDaemonVersion,
}))
-vi.mock("@/lib/utils", () => ({ getAppMode: () => "production" }))
+vi.mock("@/lib/utils", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/utils")>(), getAppMode: () => "production" }))
import type { CommunityMachineSummary } from "@alook/shared"
import { tid } from "@/lib/community/testids"
@@ -129,7 +132,9 @@ function withExactClass(container: HTMLElement, className: string): HTMLElement[
describe("machine daemon update UI", () => {
beforeEach(() => {
+ mocks.capacity.current = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, onlineCount: 0 }
mocks.apiFetch.mockReset()
+ mocks.fetchQuery.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
mocks.fetchLatestDaemonVersion.mockReset()
@@ -143,6 +148,48 @@ describe("machine daemon update UI", () => {
mocks.onboardingState.current = "done"
})
+ it("blocks adding at the owned cap even when every machine is offline", async () => {
+ mocks.machines.current = [machine({ status: "offline" })]
+ mocks.capacity.current = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 1, onlineCount: 0 }
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Connect a machine" }))
+ expect(await view.findByText("Machine limit reached")).toBeInTheDocument()
+ expect(view.queryByTestId("test-pair-sheet")).not.toBeInTheDocument()
+ expect(mocks.apiFetch).not.toHaveBeenCalled()
+ window.history.replaceState(null, "", "/c/me/machines?keep=1")
+ fireEvent.click(view.getByRole("button", { name: "View plan" }))
+ expect(window.location.search).toBe("?keep=1&settings=billing")
+ })
+
+ it("opens pairing when there is room", () => {
+ mocks.machines.current = []
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Connect a machine" }))
+ expect(view.getByTestId("test-pair-sheet")).toBeInTheDocument()
+ expect(view.queryByText("Machine limit reached")).not.toBeInTheDocument()
+ })
+
+ it("refreshes the allowance before showing a server rejection", async () => {
+ mocks.fetchQuery.mockImplementation(async () => {
+ mocks.capacity.current = { ...mocks.capacity.current, limit: 5, ownedCount: 5 }
+ })
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Connect a machine" }))
+ fireEvent.click(view.getByText("Simulate server limit"))
+ expect(await view.findByText(/Your plan allows 5 machines/)).toBeInTheDocument()
+ expect(mocks.fetchQuery).toHaveBeenCalledOnce()
+ expect(view.queryByTestId("test-pair-sheet")).not.toBeInTheDocument()
+ })
+
+ it("keeps a failed allowance refresh out of the limit dialog", async () => {
+ mocks.fetchQuery.mockRejectedValue(new Error("unavailable"))
+ const view = render(React.createElement(MachineList))
+ fireEvent.click(view.getByRole("button", { name: "Connect a machine" }))
+ fireEvent.click(view.getByText("Simulate server limit"))
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Couldn’t refresh your machine allowance. Refresh and try again."))
+ expect(view.queryByText("Machine limit reached")).not.toBeInTheDocument()
+ })
+
it("plays the guide once per empty-page mount and replays after remount", async () => {
mocks.onboardingState.current = null
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index c604ec0e5..1eb93f993 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -30,7 +30,7 @@ import { machineName } from "@/lib/community/machine-name"
import { MachineCard, MachineCardFrame } from "./machine-card"
import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"
import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"
-import { useMachines, type MachinesResponse } from "@/hooks/community/use-machines"
+import { useMachines, machinesQueryFn, replaceMachines, type MachinesResponse } from "@/hooks/community/use-machines"
import { useBots } from "@/hooks/community/use-bots"
import { useCommunityStore, usePendingMachineTokenId } from "@/stores/community"
import { communityKeys } from "@/lib/query-keys"
@@ -40,6 +40,7 @@ import {
useCommunityOnboarding,
} from "@/lib/community-onboarding"
import { removeCommunityParam } from "@/lib/community/community-route"
+import { MachineCapacityUsage, MachineLimitDialog } from "./machine-capacity"
import { GuideMeAvatarMotion } from "./guide-me-avatar-motion"
const MACHINE_LIST_HEADING_CLASS =
@@ -113,6 +114,7 @@ export function MachineListSkeleton({
<header data-slot="community-machines-heading" className={MACHINE_LIST_HEADING_CLASS}>
<div data-slot="community-machines-heading-copy" className={MACHINE_LIST_HEADING_COPY_CLASS}>
<Skeleton className="h-7 w-24 rounded" />
+ <Skeleton aria-hidden className="h-11 w-36 max-w-full rounded-sm sm:h-6" />
<div aria-hidden className="relative w-fit max-w-full">
<p className="invisible text-sm">{MACHINE_LIST_DESCRIPTION}</p>
<Skeleton className="absolute inset-0 rounded" />
@@ -203,7 +205,15 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const router = useRouter()
const searchParams = useSearchParams()
const queryClient = useQueryClient()
- const { machines, isLoading: machinesLoading } = useMachines()
+ const { machines, data: machinesData, isLoading: machinesLoading } = useMachines()
+ const capacity = machinesData?.machineCapacity ?? null
+ const [limitOpen, setLimitOpen] = useState(false)
+ const viewPlan = useCallback(() => {
+ const next = new URL(window.location.href)
+ next.searchParams.delete("billing")
+ next.searchParams.set("settings", "billing")
+ window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)
+ }, [])
const { bots } = useBots()
const pendingMachineTokenId = usePendingMachineTokenId()
const [pairOpen, setPairOpen] = useState(false)
@@ -254,11 +264,20 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const openPair = useCallback(() => {
setPairMode({ kind: "pair" })
+ if (!capacity) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.machines() })
+ toast.error("Couldn’t load your machine allowance. Refresh and try again.")
+ return
+ }
+ if (capacity.ownedCount >= capacity.limit) {
+ setLimitOpen(true)
+ return
+ }
setPendingTokenId(null)
setConnectedHostname(null)
useCommunityStore.getState().setPendingMachineTokenId(null)
setPairOpen(true)
- }, [])
+ }, [capacity, queryClient])
const openReconnect = useCallback((machine: CommunityMachineSummary) => {
setPairMode({
@@ -314,8 +333,9 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
queryClient.setQueryData<MachinesResponse | undefined>(
communityKeys.machines(),
(prev) =>
- prev ? { ...prev, machines: prev.machines.filter((m) => m.id !== id) } : prev,
+ prev ? replaceMachines(prev, prev.machines.filter((m) => m.id !== id)) : prev,
)
+ void queryClient.invalidateQueries({ queryKey: communityKeys.machines() })
} catch (err) {
// MACHINE_HAS_BOTS can still happen here despite the client-side
// guard above — e.g. a bot was created on this machine from another
@@ -349,6 +369,17 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
: []
const backBar = machineBackBar(onBack)
+ const limitDialog = <MachineLimitDialog open={limitOpen} onOpenChange={setLimitOpen} onViewPlan={viewPlan} limit={capacity?.limit ?? 0} reconnect={pairMode.kind === "reconnect"} />
+ const usage = <MachineCapacityUsage summary={capacity} onViewPlan={viewPlan} />
+ const onLimitReached = useCallback(async () => {
+ closePair(false)
+ try {
+ await queryClient.fetchQuery({ queryKey: communityKeys.machines(), queryFn: machinesQueryFn, staleTime: 0 })
+ setLimitOpen(true)
+ } catch {
+ toast.error("Couldn’t refresh your machine allowance. Refresh and try again.")
+ }
+ }, [closePair, queryClient])
if (machinesLoading) {
return <MachineListSkeleton onBack={onBack} />
@@ -397,8 +428,11 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
</Button>
</span>
</div>
+ {usage}
</div>
+ {limitDialog}
<PairMachineSheet
+ onLimitReached={onLimitReached}
open={pairOpen}
onOpenChange={closePair}
pendingTokenId={pendingTokenId}
@@ -418,6 +452,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
<header data-slot="community-machines-heading" className={MACHINE_LIST_HEADING_CLASS}>
<div data-slot="community-machines-heading-copy" className={MACHINE_LIST_HEADING_COPY_CLASS}>
<h1 className="text-xl font-medium text-foreground">Machines</h1>
+ {usage}
<p className="text-sm text-muted-foreground">
{MACHINE_LIST_DESCRIPTION}
</p>
@@ -451,7 +486,9 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
/>
))}
/>
+ {limitDialog}
<PairMachineSheet
+ onLimitReached={onLimitReached}
open={pairOpen}
onOpenChange={closePair}
pendingTokenId={pendingTokenId}
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
index 7440bcd13..2d39ba18b 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
+++ b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
@@ -66,6 +66,13 @@ describe("PairMachineSheet desktop daemon integration", () => {
})
})
+ it("hands a server quota rejection back to the machine limit flow", async () => {
+ const onLimitReached = vi.fn()
+ mocks.apiFetch.mockRejectedValue(new Error("MACHINE_LIMIT_REACHED"))
+ render(React.createElement(PairMachineSheet, { open: true, onOpenChange: vi.fn(), pendingTokenId: null, setPendingTokenId: vi.fn(), connectedHostname: null, onLimitReached }))
+ await waitFor(() => expect(onLimitReached).toHaveBeenCalledOnce())
+ })
+
it("probes and pairs once through Tauri while retaining the command fallback", async () => {
const renderer = render(React.createElement(PairMachineSheet, {
open: true,
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsx
index 4ee6b6ed5..e7516ec7f 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx
+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx
@@ -57,6 +57,7 @@ export function PairMachineSheet({
setPendingTokenId,
connectedHostname,
mode = { kind: "pair" },
+ onLimitReached,
}: {
open: boolean
onOpenChange: (open: boolean) => void
@@ -64,6 +65,7 @@ export function PairMachineSheet({
setPendingTokenId: (tokenId: string | null) => void
connectedHostname: string | null
mode?: PairMachineSheetMode
+ onLimitReached?: () => void
}) {
const isReconnect = mode.kind === "reconnect"
const [generating, setGenerating] = useState(false)
@@ -91,6 +93,10 @@ export function PairMachineSheet({
)
setPendingTokenId(res.tokenId)
} catch (err) {
+ if (err instanceof Error && err.message === "MACHINE_LIMIT_REACHED" && onLimitReached) {
+ onLimitReached()
+ return
+ }
const message = "Couldn't generate a key — try again."
setGenerationError(message)
toastApiError(err, message)
@@ -98,7 +104,7 @@ export function PairMachineSheet({
} finally {
setGenerating(false)
}
- }, [setPendingTokenId, mode])
+ }, [setPendingTokenId, mode, onLimitReached])
// Auto-generate the key when the sheet opens. Track per-open so re-opens or
// mode swaps trigger a fresh mint.
diff --git a/src/web/src/components/community/settings/server-settings-notifications.dom.test.ts b/src/web/src/components/community/settings/server-settings-notifications.dom.test.ts
index 765a1d0c2..557bf2d29 100644
--- a/src/web/src/components/community/settings/server-settings-notifications.dom.test.ts
+++ b/src/web/src/components/community/settings/server-settings-notifications.dom.test.ts
@@ -2,6 +2,8 @@ import { createElement } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { render, screen, setupUser } from "@/test/react-dom-harness"
+vi.mock("./settings-shell.module.css", () => ({ default: { shell: "settings-shell" } }))
+
vi.mock("@/hooks/community/use-bots", () => ({
useBots: () => ({ bots: [] }),
}))
diff --git a/src/web/src/components/community/settings/settings-navigation.test.ts b/src/web/src/components/community/settings/settings-navigation.test.ts
index 6098c1499..4dad967b6 100644
--- a/src/web/src/components/community/settings/settings-navigation.test.ts
+++ b/src/web/src/components/community/settings/settings-navigation.test.ts
@@ -10,7 +10,7 @@ import {
describe("responsive settings navigation", () => {
it("uses a top tab strip on mobile and the compact left rail on desktop", () => {
- expect(SETTINGS_NAV_CLASS).toContain("sm:w-44")
+ expect(SETTINGS_NAV_CLASS).not.toMatch(/(?:^|\s)sm:w-/u)
expect(SETTINGS_NAV_CLASS).not.toContain("w-60")
expect(SETTINGS_NAV_CLASS).not.toContain("border-b")
expect(SETTINGS_NAV_CLASS).not.toContain("sm:border-r")
diff --git a/src/web/src/components/community/settings/settings-navigation.ts b/src/web/src/components/community/settings/settings-navigation.ts
index c48617aeb..f13594041 100644
--- a/src/web/src/components/community/settings/settings-navigation.ts
+++ b/src/web/src/components/community/settings/settings-navigation.ts
@@ -1,5 +1,5 @@
export const SETTINGS_NAV_CLASS =
- "col-start-1 row-start-2 flex min-w-0 items-center gap-1 px-2 thin-scrollbar sm:row-span-2 sm:row-start-1 sm:w-44 sm:flex-col sm:items-stretch sm:gap-2 sm:overflow-y-auto sm:p-4"
+ "col-start-1 row-start-2 flex min-w-0 items-center gap-1 px-2 thin-scrollbar sm:row-span-2 sm:row-start-1 sm:flex-col sm:items-stretch sm:gap-2 sm:overflow-y-auto sm:p-4"
export const SETTINGS_TABS_LIST_CLASS =
"h-11 min-w-0 flex-1 flex-row justify-start gap-1 overflow-hidden p-0 group-data-horizontal/tabs:h-11 sm:h-auto sm:w-full sm:flex-none sm:flex-col"
diff --git a/src/web/src/components/community/settings/settings-shell.contract.test.ts b/src/web/src/components/community/settings/settings-shell.contract.test.ts
index 3ed20a694..53f1ac18f 100644
--- a/src/web/src/components/community/settings/settings-shell.contract.test.ts
+++ b/src/web/src/components/community/settings/settings-shell.contract.test.ts
@@ -12,9 +12,7 @@ describe("shared settings shell", () => {
expect(source).toContain("useBreakpoint()")
expect(source).toContain('breakpoint === "mobile" ? "horizontal" : "vertical"')
- expect(source).toContain("grid-rows-[4rem_auto_minmax(0,1fr)]")
- expect(source).toContain("sm:grid-cols-[11rem_minmax(0,1fr)]")
- expect(source).toContain("sm:grid-rows-[4rem_minmax(0,1fr)]")
+ expect(source).toContain("styles.shell")
expect(source).toContain("data-testid={tid.settingsNav}")
expect(source).toContain("data-testid={tid.settingsContent}")
expect(source).toContain("data-testid={tid.settingsClose}")
diff --git a/src/web/src/components/community/settings/settings-shell.module.css b/src/web/src/components/community/settings/settings-shell.module.css
new file mode 100644
index 000000000..1c99cc9a7
--- /dev/null
+++ b/src/web/src/components/community/settings/settings-shell.module.css
@@ -0,0 +1,12 @@
+.shell {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-rows: 4rem auto minmax(0, 1fr);
+}
+
+@media (min-width: 40rem) {
+ .shell {
+ grid-template-columns: 15rem minmax(0, 1fr);
+ grid-template-rows: 4rem minmax(0, 1fr);
+ }
+}
diff --git a/src/web/src/components/community/settings/settings-shell.tsx b/src/web/src/components/community/settings/settings-shell.tsx
index bd35457ae..5d4bbe06a 100644
--- a/src/web/src/components/community/settings/settings-shell.tsx
+++ b/src/web/src/components/community/settings/settings-shell.tsx
@@ -3,6 +3,7 @@
import type { LucideIcon } from "lucide-react"
import type { ComponentProps, ReactNode } from "react"
import { X } from "lucide-react"
+import styles from "./settings-shell.module.css"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useBreakpoint } from "@/hooks/use-mobile"
@@ -55,7 +56,7 @@ export function SettingsShell<Value extends string>({
orientation={breakpoint === "mobile" ? "horizontal" : "vertical"}
value={value}
onValueChange={(nextValue) => onValueChange(nextValue as Value)}
- className="grid min-h-0 flex-1 grid-cols-1 grid-rows-[4rem_auto_minmax(0,1fr)] gap-0 sm:grid-cols-[11rem_minmax(0,1fr)] sm:grid-rows-[4rem_minmax(0,1fr)]"
+ className={`grid min-h-0 w-full flex-1 gap-0 ${styles.shell}`}
data-testid={tid.settingsShell}
>
<header className="col-start-1 row-start-1 flex h-16 min-w-0 items-center px-4 sm:col-start-2 sm:px-8">
@@ -89,7 +90,7 @@ export function SettingsShell<Value extends string>({
data-testid={tid.settingsTab(tabValue)}
>
<Icon className="size-4" />
- <span className="sr-only sm:not-sr-only">{tabLabel}</span>
+ <span className="sr-only whitespace-nowrap sm:not-sr-only">{tabLabel}</span>
</TabsTrigger>
))}
</TabsList>
@@ -99,7 +100,7 @@ export function SettingsShell<Value extends string>({
</nav>
<div
- className="col-start-1 row-start-3 min-h-0 min-w-0 overflow-y-auto bg-background px-4 pt-2 pb-4 thin-scrollbar sm:col-start-2 sm:row-start-2 sm:p-8 sm:pt-4"
+ className="col-start-1 row-start-3 min-h-0 min-w-0 overflow-y-auto rounded-tl-xl bg-background px-4 pt-6 pb-4 thin-scrollbar sm:col-start-2 sm:row-start-2 sm:p-8 sm:pt-4"
data-testid={tid.settingsContent}
>
{children}
diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsx
index d34a5c9ce..9a57525b7 100644
--- a/src/web/src/components/community/settings/user-settings.tsx
+++ b/src/web/src/components/community/settings/user-settings.tsx
@@ -3,7 +3,7 @@
import { useEffect, useState } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
-import { User, LogOut, Palette, Sun, Moon, Monitor, Database, Camera, Shield } from "lucide-react"
+import { User, LogOut, Palette, Sun, Moon, Monitor, Database, Camera, Shield, CreditCard } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"
@@ -18,6 +18,8 @@ import {
SETTINGS_LOGOUT_CLASS,
} from "./settings-navigation"
import { SettingsShell, SettingsShellPanel, type SettingsShellTab } from "./settings-shell"
+import { BillingContent } from "../billing/billing-sheet"
+import { useBilling, type BillingReturn } from "@/hooks/community/use-billing"
import { AccountDeletionFlow } from "./account-deletion-flow"
const THEME_OPTIONS = [
@@ -26,10 +28,11 @@ const THEME_OPTIONS = [
{ value: "system", label: "System", icon: Monitor },
] as const
-type UserSettingsTab = "profile" | "appearance" | "advanced" | "privacy"
+type UserSettingsTab = "profile" | "appearance" | "advanced" | "privacy" | "billing"
const USER_SETTINGS_TABS: SettingsShellTab<UserSettingsTab>[] = [
{ value: "profile", label: "My Profile", icon: User },
+ { value: "billing", label: "Subscription & billing", icon: CreditCard },
{ value: "appearance", label: "Appearance", icon: Palette },
{ value: "advanced", label: "Advanced", icon: Database },
{ value: "privacy", label: "Privacy", icon: Shield },
@@ -133,7 +136,9 @@ function AdvancedSettings({ userId }: { userId: string | null }) {
)
}
-export function UserSettings({ onClose, userId, userName, userEmail, aboutMe, avatar, statusEmoji, statusText, onSave, onLogout, onAccountDeleted, onUploadAvatar }: {
+export function UserSettings({ initialTab = "profile", billingReturn = null, onClose, userId, userName, userEmail, aboutMe, avatar, statusEmoji, statusText, onSave, onLogout, onAccountDeleted, onUploadAvatar }: {
+ initialTab?: UserSettingsTab
+ billingReturn?: BillingReturn
onClose: () => void
userId: string | null
userName: string
@@ -159,7 +164,9 @@ export function UserSettings({ onClose, userId, userName, userEmail, aboutMe, av
emoji: statusEmoji ?? null,
text: statusText ?? null,
})
- const [tab, setTab] = useState<UserSettingsTab>("profile")
+ const [tab, setTab] = useState<UserSettingsTab>(initialTab)
+ useEffect(() => { setTab(initialTab) }, [initialTab])
+ const billing = useBilling(billingReturn, tab === "billing")
const [deletionOpen, setDeletionOpen] = useState(false)
const dirty =
@@ -196,7 +203,7 @@ export function UserSettings({ onClose, userId, userName, userEmail, aboutMe, av
value={tab}
onValueChange={setTab}
label="User Settings"
- title={deletionOpen ? "Delete account" : tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : "My Profile"}
+ title={tab === "billing" ? "Subscription & billing" : deletionOpen ? "Delete account" : tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : "My Profile"}
tabs={USER_SETTINGS_TABS}
onClose={onClose}
disabled={deletionOpen}
@@ -214,6 +221,7 @@ export function UserSettings({ onClose, userId, userName, userEmail, aboutMe, av
/>
) : (
<>
+ <SettingsShellPanel value="billing"><div className="mx-auto w-full max-w-xl"><BillingContent billing={billing} /></div></SettingsShellPanel>
<SettingsShellPanel value="profile">
<div className="mx-auto w-full max-w-md space-y-8">
{/* Avatar — centered in a soft rounded frame, with a hand-rolled
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index eebb3fd59..a2517de14 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { useShellProfileController } from "./use-shell-profile-controller"
const mocks = vi.hoisted(() => ({
+ search: "",
currentUser: {
id: "self",
name: "Self",
@@ -34,6 +35,7 @@ const mocks = vi.hoisted(() => ({
disposeCoordinator: vi.fn(),
}))
+vi.mock("next/navigation", () => ({ usePathname: () => "/c/me/bots", useSearchParams: () => new URLSearchParams(mocks.search) }))
vi.mock("sonner", () => ({ toast: mocks.toast }))
vi.mock("@/lib/api/client", () => ({
ACCOUNT_DELETED_SIGN_IN_PATH: "/sign-in?account_deleted=1",
@@ -122,7 +124,7 @@ function Capture({ options, onResult }: {
async function renderController() {
const pushed: string[] = []
const router = {
- push: (href: string) => { pushed.push(href) },
+ push: vi.fn((href: string) => { pushed.push(href) }),
replace: vi.fn(),
prefetch: vi.fn(),
}
@@ -162,6 +164,7 @@ function deferred<T>() {
describe("useShellProfileController", () => {
beforeEach(() => {
+ mocks.search = ""
for (const mock of Object.values(mocks)) {
if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()
}
@@ -187,6 +190,45 @@ describe("useShellProfileController", () => {
vi.restoreAllMocks()
})
+ it.each(["settings=billing", "billing=checkout", "billing=cancel", "billing=portal"])("opens billing settings from %s and clears only billing navigation on close", async (marker) => {
+ mocks.search = `${marker}&audit=bot1`
+ window.history.replaceState(null, "", `/c/me/bots?${mocks.search}#details`)
+ const hook = await renderController()
+ expect(hook.current.editingProfile).toBe(true)
+ expect(hook.current.userSettingsProps.initialTab).toBe("billing")
+ await act(async () => hook.current.userSettingsProps.onClose())
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe("/c/me/bots?audit=bot1#details")
+ expect(hook.router.replace).not.toHaveBeenCalled()
+ mocks.search = window.location.search.slice(1)
+ await hook.rerender()
+ expect(hook.current.editingProfile).toBe(false)
+ })
+
+ it("ignores arbitrary billing return values", async () => {
+ mocks.search = "billing=success"
+ const hook = await renderController()
+ expect(hook.current.editingProfile).toBe(false)
+ expect(hook.current.userSettingsProps.initialTab).toBe("profile")
+ })
+
+ it.each(["settings=billing", "settings=billing&billing=cancel&audit=bot1"])("dismisses the settings dialog through open-change while preserving unrelated navigation (%s)", async (query) => {
+ mocks.search = query
+ window.history.replaceState(null, "", `/c/me/bots?${query}#details`)
+ const hook = await renderController()
+ await act(async () => hook.current.onUserSettingsOpenChange(true))
+ expect(hook.current.editingProfile).toBe(true)
+ expect(window.location.search).toBe(`?${query}`)
+ await act(async () => hook.current.onUserSettingsOpenChange(false))
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe(
+ query.includes("audit=") ? "/c/me/bots?audit=bot1#details" : "/c/me/bots#details",
+ )
+ mocks.search = window.location.search.slice(1)
+ await hook.rerender()
+ expect(hook.current.editingProfile).toBe(false)
+ expect(hook.router.push).not.toHaveBeenCalled()
+ expect(hook.router.replace).not.toHaveBeenCalled()
+ })
+
it("opens self synchronously only for the exact target id", async () => {
const hook = await renderController()
await act(async () => hook.current.openProfile("Self", { clientX: 2, clientY: 3 } as never, undefined, "self"))
@@ -436,8 +478,9 @@ describe("useShellProfileController", () => {
expect(mocks.toastApiError).toHaveBeenLastCalledWith(saveError, "Failed to save profile")
})
- it("preserves logout ordering and rejection behavior", async () => {
+ it("replaces the document after logout cleanup and preserves rejection behavior", async () => {
const order: string[] = []
+ vi.stubGlobal("location", { replace: (href: string) => { order.push(`replace:${href}`) } })
const hook = await renderController()
hook.cancelPendingNavigation.mockImplementation(() => { order.push("cancel") })
mocks.communityReset.mockImplementation(() => { order.push("community") })
@@ -446,10 +489,11 @@ describe("useShellProfileController", () => {
mocks.disposeReconciliation.mockImplementation(() => { order.push("reconcile") })
hook.queryClient.clear.mockImplementation(() => { order.push("query") })
mocks.clearCache.mockImplementation(async () => { order.push("cache"); throw new Error("cache") })
- mocks.signOut.mockImplementation(async () => { order.push("signOut") })
- hook.router.push = (href: string) => { order.push(`push:${href}`) }
+ mocks.signOut.mockImplementation(async ({ fetchOptions }) => { order.push("signOut"); await fetchOptions.onSuccess(); order.push("session-notify") })
await act(async () => hook.current.userSettingsProps.onLogout())
- expect(order).toEqual(["cancel", "community", "ws", "stream", "reconcile", "query", "signOut", "cache", "push:/sign-in"])
+ expect(order).toEqual(["signOut", "cache", "replace:/sign-in", "session-notify"])
+ expect(hook.router.push).not.toHaveBeenCalled()
+ expect(hook.router.replace).not.toHaveBeenCalled()
order.length = 0
mocks.clearCache.mockClear()
@@ -457,7 +501,23 @@ describe("useShellProfileController", () => {
mocks.signOut.mockRejectedValue(new Error("auth"))
await expect(act(async () => hook.current.userSettingsProps.onLogout())).rejects.toThrow("auth")
expect(mocks.clearCache).not.toHaveBeenCalled()
- expect(order.some((entry) => entry.startsWith("push:"))).toBe(false)
+ expect(order.some((entry) => entry.startsWith("replace:"))).toBe(false)
+ })
+
+ it("does not navigate or delete persisted cache when signOut returns an error", async () => {
+ const replace = vi.fn()
+ vi.stubGlobal("location", { replace })
+ const error = { message: "Sign out failed", status: 503 }
+ mocks.signOut.mockResolvedValue({ error })
+ const hook = await renderController()
+ await act(async () => hook.current.userSettingsProps.onLogout())
+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Failed to log out")
+ expect(mocks.communityReset).not.toHaveBeenCalled()
+ expect(hook.queryClient.clear).not.toHaveBeenCalled()
+ expect(mocks.clearCache).not.toHaveBeenCalled()
+ expect(replace).not.toHaveBeenCalled()
+ expect(hook.router.push).not.toHaveBeenCalled()
+ expect(hook.router.replace).not.toHaveBeenCalled()
})
it("uses logout-equivalent local cleanup then replaces into the persistent deletion state", async () => {
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index 4876aa1a7..0ca571b14 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -1,6 +1,8 @@
"use client"
import { useCallback, useState, type ComponentProps } from "react"
+import { usePathname, useSearchParams } from "next/navigation"
+import { readBillingReturn } from "@/hooks/community/use-billing"
import { parseNameAndTag } from "@alook/shared"
import { toast } from "sonner"
import { ACCOUNT_DELETED_SIGN_IN_PATH, toastApiError } from "@/lib/api/client"
@@ -84,6 +86,19 @@ export function useShellProfileController({
view,
activeServerId,
}: Options) {
+ const pathname = usePathname()
+ const searchParams = useSearchParams()
+ const billingReturn = readBillingReturn(searchParams.get("billing"))
+ const billingRequested = searchParams.get("settings") === "billing" || Boolean(billingReturn)
+ const closeSettings = () => {
+ setEditingProfile(false)
+ if (billingRequested) {
+ const next = new URLSearchParams(searchParams.toString())
+ next.delete("settings")
+ next.delete("billing")
+ window.history.replaceState(null, "", `${pathname}${next.size ? `?${next}` : ""}${window.location.hash}`)
+ }
+ }
const currentUser = useCurrentUser()
const { friends } = useFriends()
const profileServerId = resolveProfileServerId(view, activeServerId)
@@ -289,14 +304,15 @@ export function useShellProfileController({
}
const onLogout = async () => {
- clearVolatileAccountState()
- await signOut()
- // Better Auth can synchronously remount the authenticated tree while its
- // sign-out state settles. Clear last so any transitional QueryProvider
- // has already captured the retired generation and cannot recreate this
- // account's persisted blob after logout.
- await clearPersistedCache(currentUser.id).catch(() => {})
- router.push("/sign-in")
+ const result = await signOut({
+ fetchOptions: {
+ onSuccess: async () => {
+ await clearPersistedCache(currentUser.id).catch(() => {})
+ globalThis.location.replace("/sign-in")
+ },
+ },
+ })
+ if (result?.error) toastApiError(result.error, "Failed to log out")
}
const onAccountDeleted = async () => {
@@ -307,7 +323,9 @@ export function useShellProfileController({
}
const userSettingsProps: ComponentProps<typeof UserSettings> = {
- onClose: () => setEditingProfile(false),
+ onClose: closeSettings,
+ initialTab: billingRequested ? "billing" : "profile",
+ billingReturn,
userId: currentUser.id,
userName: currentUser.name,
userEmail: currentUser.email,
@@ -368,10 +386,10 @@ export function useShellProfileController({
onAttachmentPreviewOpenChange: (open: boolean) => {
if (!open) setAttachmentPreview(null)
},
- editingProfile,
+ editingProfile: editingProfile || billingRequested,
openUserSettings: () => setEditingProfile(true),
onUserSettingsOpenChange: (open: boolean) => {
- if (!open) setEditingProfile(false)
+ if (!open) closeSettings()
},
userSettingsProps,
pendingAvatarCrop: pendingAvatarCropProps,
diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsx
index fa3c13b8a..be2186ea0 100644
--- a/src/web/src/components/home/landing-page.tsx
+++ b/src/web/src/components/home/landing-page.tsx
@@ -416,6 +416,7 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {
<footer className={styles.footer}>
<Brand />
<p>{BRAND_SLOGAN}</p>
+ <Link href="/pricing">Pricing</Link>
<FooterSocialLinks />
</footer>
</main>
diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsx
index c38ee40c9..0ebe9f2cc 100644
--- a/src/web/src/components/home/marketing-nav.tsx
+++ b/src/web/src/components/home/marketing-nav.tsx
@@ -61,6 +61,7 @@ export function MarketingNav({
</Link>
<div className="relative flex items-center gap-3">
+ <Link href="/pricing" className="px-3 py-2 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70" style={{ fontFamily: "var(--font-mono)", color: "var(--landing-text)" }}>Pricing</Link>
{showTemplates && (
<Link
href="/templates"
diff --git a/src/web/src/components/pricing/plan-art.tsx b/src/web/src/components/pricing/plan-art.tsx
new file mode 100644
index 000000000..167abac3b
--- /dev/null
+++ b/src/web/src/components/pricing/plan-art.tsx
@@ -0,0 +1,11 @@
+import { GeneratedAvatar } from "@/components/avatar"
+
+const studioBotSeeds = ["studio-lantern", "studio-pocket", "studio-orbit"]
+
+export function PlanBots({ className, botClassName, avatarClassName }: { className: string; botClassName: string; avatarClassName?: string }) {
+ return <div className={className} aria-hidden="true">{studioBotSeeds.map((seed) => <span className={botClassName} key={seed}><GeneratedAvatar seed={seed} size="100%" className={avatarClassName} /></span>)}</div>
+}
+
+export function PlanBarcode({ className }: { className: string }) {
+ return <div className={className} aria-hidden="true">{Array.from({ length: 25 }, (_, index) => <span key={index} data-wide={index % 7 === 0 || index % 11 === 0 || undefined} />)}</div>
+}
diff --git a/src/web/src/components/pricing/plan-bot-dots.tsx b/src/web/src/components/pricing/plan-bot-dots.tsx
new file mode 100644
index 000000000..3722f13cc
--- /dev/null
+++ b/src/web/src/components/pricing/plan-bot-dots.tsx
@@ -0,0 +1,11 @@
+export function PlanBotDots({ count, className }: { count: number; className?: string }) {
+ const columns = count <= 10 ? 5 : 10
+ const rows = Math.max(1, Math.ceil(count / columns))
+ const width = 80
+ const height = Math.max(32, rows * 8)
+ const left = (width - (Math.min(count, columns) - 1) * 8) / 2
+ const top = (height - (rows - 1) * 8) / 2
+ return <svg className={className} viewBox={`0 0 ${width} ${height}`} role="img" aria-label={`${count} bot slots`}>
+ {Array.from({ length: count }, (_, index) => <circle key={index} cx={left + index % columns * 8} cy={top + Math.floor(index / columns) * 8} r="1.5" fill="currentColor" />)}
+ </svg>
+}
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 698a129de..ab2700dda 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -1,4 +1,8 @@
interface RuntimeEnv {
+ STRIPE_SECRET_KEY?: string
+ STRIPE_WEBHOOK_SECRET?: string
+ STRIPE_PORTAL_CONFIGURATION_ID?: string
+ STRIPE_RETURN_ORIGIN?: string
ENCRYPTION_KEY: string
APP_REVIEW_EMAIL?: string
APP_REVIEW_OTP?: string
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
index ad5521d6d..3bdfb62ef 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
@@ -3,10 +3,14 @@ import type {
CommunityBotAuditEvent,
CommunityMachineCreated,
CommunityMachineStatus,
+ CommunityMachineSummary,
+ CommunityMachineUpdated,
+ CommunityMachineRemoved,
CommunityPresenceUpdate,
CommunityStatusUpdate,
} from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
+import type { MachinesResponse } from "@/hooks/community/use-machines"
import {
capturedOnMessage,
capturedQueryClient,
@@ -130,6 +134,73 @@ describe("useCommunityWs — bot audit events", () => {
})
describe("useCommunityWs — machines", () => {
+ const machine = (id: string, status: "online" | "offline" = "offline"): CommunityMachineSummary => ({
+ id, hostname: id, displayName: id, platform: "darwin", arch: "arm64",
+ osRelease: "24", daemonVersion: "0.1", lastSeenAt: null, status,
+ availableRuntimes: [], createdAt: "2026-07-03T00:00:00.000Z", updatedAt: "2026-07-03T00:00:00.000Z",
+ })
+ const capacity = {
+ plan: { id: "house", displayName: "House" }, isFounder: true,
+ limit: 10, ownedCount: 1, onlineCount: 0,
+ }
+ const readCache = () => capturedQueryClient.getQueryData<MachinesResponse>(communityKeys.machines())
+
+ it.each(["created", "updated"] as const)("machine.%s upserts without double-counting and preserves the allowance", async (kind) => {
+ await mountHook()
+ const original = machine("existing")
+ capturedQueryClient.setQueryData(communityKeys.machines(), { machines: [original], machineCapacity: capacity })
+ const inserted = machine("new", "online")
+ const dispatch = (value: CommunityMachineSummary) => {
+ capturedOnMessage!(kind === "created"
+ ? { type: "community:machine.created", tokenId: "cmt_live", machine: value } satisfies CommunityMachineCreated
+ : { type: "community:machine.updated", machine: value } satisfies CommunityMachineUpdated)
+ }
+ dispatch(inserted)
+ expect(readCache()).toEqual({ machines: [inserted, original], machineCapacity: { ...capacity, ownedCount: 2, onlineCount: 1 } })
+ dispatch(inserted)
+ expect(readCache()?.machines).toHaveLength(2)
+ const replacement = { ...inserted, status: "offline" as const, displayName: "Renamed" }
+ dispatch(replacement)
+ expect(readCache()).toEqual({ machines: [replacement, original], machineCapacity: { ...capacity, ownedCount: 2 } })
+ if (kind === "created") {
+ const { useCommunityStore } = await import("@/stores/community")
+ expect(useCommunityStore.getState().pendingMachineTokenId).toBe("cmt_live")
+ }
+ })
+
+ it("status changes online usage; removal alone frees owned slots and tolerates replay", async () => {
+ await mountHook()
+ const offline = machine("offline")
+ const online = machine("online", "online")
+ capturedQueryClient.setQueryData(communityKeys.machines(), {
+ machines: [offline, online], machineCapacity: { ...capacity, ownedCount: 2, onlineCount: 1 },
+ })
+ const status: CommunityMachineStatus = {
+ type: "community:machine.status", machineId: "online", status: "offline", lastSeenAt: "2026-07-03T01:00:00.000Z",
+ }
+ capturedOnMessage!(status)
+ expect(readCache()).toEqual({
+ machines: [offline, { ...online, status: "offline", lastSeenAt: status.lastSeenAt }],
+ machineCapacity: { ...capacity, ownedCount: 2 },
+ })
+ capturedOnMessage!({ ...status, machineId: "unknown", status: "online" })
+ expect(readCache()?.machineCapacity).toEqual({ ...capacity, ownedCount: 2 })
+ const removed: CommunityMachineRemoved = { type: "community:machine.removed", machineId: "online" }
+ capturedOnMessage!(removed)
+ capturedOnMessage!(removed)
+ expect(readCache()).toEqual({ machines: [offline], machineCapacity: capacity })
+ })
+
+ it("ignores status/removal without a snapshot and bootstraps update without inventing allowance", async () => {
+ await mountHook()
+ capturedOnMessage!({ type: "community:machine.status", machineId: "new", status: "online", lastSeenAt: "2026-07-03T01:00:00.000Z" } satisfies CommunityMachineStatus)
+ capturedOnMessage!({ type: "community:machine.removed", machineId: "new" } satisfies CommunityMachineRemoved)
+ expect(readCache()).toBeUndefined()
+ const event: CommunityMachineUpdated = { type: "community:machine.updated", machine: machine("new") }
+ capturedOnMessage!(event)
+ expect(readCache()).toEqual({ machines: [event.machine] })
+ })
+
it("machine.created upserts and stashes pending token", async () => {
await mountHook()
const created: CommunityMachineCreated = {
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
index c851eb585..d22e31b94 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
@@ -1,3 +1,4 @@
+import { replaceMachines } from "@/hooks/community/use-machines"
import type {
CommunityBotAuditEvent,
CommunityMachineCreated,
@@ -59,10 +60,10 @@ export function handleMachineCreated(
(prev) => {
if (!prev) return { machines: [event.machine] }
const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
- if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
+ if (idx === -1) return replaceMachines(prev, [event.machine, ...prev.machines])
const next = prev.machines.slice()
next[idx] = event.machine
- return { ...prev, machines: next }
+ return replaceMachines(prev, next)
},
)
useCommunityStore.getState().setPendingMachineTokenId(event.tokenId)
@@ -76,14 +77,11 @@ export function handleMachineStatus(
communityKeys.machines(),
(prev) =>
prev
- ? {
- ...prev,
- machines: prev.machines.map((m) =>
+ ? replaceMachines(prev, prev.machines.map((m) =>
m.id === event.machineId
? { ...m, lastSeenAt: event.lastSeenAt, status: event.status }
: m,
- ),
- }
+ ))
: prev,
)
}
@@ -97,10 +95,10 @@ export function handleMachineUpdated(
(prev) => {
if (!prev) return { machines: [event.machine] }
const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
- if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
+ if (idx === -1) return replaceMachines(prev, [event.machine, ...prev.machines])
const next: CommunityMachineSummary[] = prev.machines.slice()
next[idx] = event.machine
- return { ...prev, machines: next }
+ return replaceMachines(prev, next)
},
)
}
@@ -112,6 +110,6 @@ export function handleMachineRemoved(
queryClient.setQueryData<MachinesResponse | undefined>(
communityKeys.machines(),
(prev) =>
- prev ? { ...prev, machines: prev.machines.filter((m) => m.id !== event.machineId) } : prev,
+ prev ? replaceMachines(prev, prev.machines.filter((m) => m.id !== event.machineId)) : prev,
)
}
diff --git a/src/web/src/hooks/community/use-billing.dom.test.tsx b/src/web/src/hooks/community/use-billing.dom.test.tsx
new file mode 100644
index 000000000..1858fdca5
--- /dev/null
+++ b/src/web/src/hooks/community/use-billing.dom.test.tsx
@@ -0,0 +1,266 @@
+import React from "react"
+import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { readBillingReturn, useBilling } from "./use-billing"
+
+const mocks = vi.hoisted(() => ({ api: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api }))
+const free = { plan: { id: "free", displayName: "Free" }, isFounder: false, offers: [], subscription: null }
+
+function setup(returnFrom: Parameters<typeof useBilling>[0] = null, enabled = true) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
+ const invalidate = vi.spyOn(client, "invalidateQueries")
+ const wrapper = ({ children }: { children: React.ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ return { ...renderHook(() => useBilling(returnFrom, enabled), { wrapper }), client, invalidate }
+}
+
+describe("billing queries and redirects", () => {
+ beforeEach(() => { mocks.api.mockReset(); mocks.api.mockResolvedValue(free) })
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })
+
+ it("does not load billing for the ordinary My Bots view", () => {
+ const view = setup(null, false)
+ expect(mocks.api).not.toHaveBeenCalled()
+ view.unmount()
+ })
+
+ it("rejects arbitrary return markers and never grants from a checkout return", async () => {
+ expect(readBillingReturn("success")).toBeNull()
+ expect(readBillingReturn("checkout")).toBe("checkout")
+ const view = setup("checkout")
+ await waitFor(() => expect(view.result.current.data?.plan.id).toBe("free"))
+ expect(view.client.getQueryData(communityKeys.bots())).toBeUndefined()
+ expect(view.invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.bots() })
+ view.unmount()
+ })
+
+ it("bounds automatic return polling and still allows manual refresh", async () => {
+ vi.useFakeTimers()
+ const view = setup("portal")
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ expect(view.result.current.polling).toBe(true)
+ await act(async () => { await vi.advanceTimersByTimeAsync(31_000) })
+ expect(view.result.current.polling).toBe(false)
+ const calls = mocks.api.mock.calls.length
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
+ expect(mocks.api).toHaveBeenCalledTimes(calls)
+ await act(async () => { view.result.current.refresh(); await vi.advanceTimersByTimeAsync(1) })
+ expect(mocks.api.mock.calls.length).toBeGreaterThan(calls)
+ view.unmount()
+ })
+
+ it("resumes only the remaining return window without replaying invalidations", async () => {
+ vi.useFakeTimers()
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const invalidate = vi.spyOn(client, "invalidateQueries")
+ const wrapper = ({ children }: { children: React.ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ const view = renderHook(({ enabled }) => useBilling("portal", enabled), { wrapper, initialProps: { enabled: true } })
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ expect(view.result.current.polling).toBe(true)
+ view.rerender({ enabled: false })
+ expect(view.result.current.polling).toBe(false)
+ await act(async () => { await vi.advanceTimersByTimeAsync(20_000) })
+ const calls = mocks.api.mock.calls.length
+ view.rerender({ enabled: true })
+ expect(view.result.current.polling).toBe(true)
+ await act(async () => { await vi.advanceTimersByTimeAsync(4_000) })
+ expect(mocks.api.mock.calls.length).toBeGreaterThan(calls)
+ await act(async () => { await vi.advanceTimersByTimeAsync(6_001) })
+ expect(view.result.current.polling).toBe(false)
+ view.rerender({ enabled: false })
+ view.rerender({ enabled: true })
+ expect(view.result.current.polling).toBe(false)
+ expect(invalidate.mock.calls.filter(([args]) => JSON.stringify(args?.queryKey) === JSON.stringify(communityKeys.bots()))).toHaveLength(1)
+ view.unmount()
+ })
+
+ it("keeps return polling alive through StrictMode effect replay", async () => {
+ vi.useFakeTimers()
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const wrapper = ({ children }: { children: React.ReactNode }) => <React.StrictMode><QueryClientProvider client={client}>{children}</QueryClientProvider></React.StrictMode>
+ const view = renderHook(() => useBilling("portal", true), { wrapper })
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ expect(view.result.current.polling).toBe(true)
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_001) })
+ expect(view.result.current.polling).toBe(false)
+ view.unmount()
+ })
+
+ it("reuses fresh billing data on focus but refreshes stale data", async () => {
+ vi.useFakeTimers()
+ const view = setup()
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ const calls = mocks.api.mock.calls.length
+ await act(async () => { focusManager.setFocused(false); focusManager.setFocused(true); await vi.advanceTimersByTimeAsync(1) })
+ expect(mocks.api).toHaveBeenCalledTimes(calls)
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_001); focusManager.setFocused(false); focusManager.setFocused(true); await vi.advanceTimersByTimeAsync(1) })
+ expect(mocks.api).toHaveBeenCalledTimes(calls + 1)
+ view.unmount()
+ focusManager.setFocused(undefined)
+ })
+
+ it("does not poll an abandoned checkout", async () => {
+ const view = setup("cancel")
+ await waitFor(() => expect(view.result.current.data).toEqual(free))
+ expect(view.result.current.polling).toBe(false)
+ view.unmount()
+ })
+
+ it("does not reload bots for unchanged billing polls and stops when paid access is confirmed", async () => {
+ vi.useFakeTimers()
+ const view = setup("checkout")
+ await act(async () => { await vi.advanceTimersByTimeAsync(6_001) })
+ const botRefreshes = () => view.invalidate.mock.calls.filter(([args]) => JSON.stringify(args?.queryKey) === JSON.stringify(communityKeys.bots())).length
+ expect(botRefreshes()).toBe(1)
+ const paid = { ...free, plan: { id: "studio", displayName: "Studio" }, subscription: {
+ plan: { id: "studio", displayName: "Studio" }, status: "active", currentPeriodEnd: null, cancelAt: null, scheduledChange: null,
+ } }
+ mocks.api.mockResolvedValue(paid)
+ await act(async () => { await vi.advanceTimersByTimeAsync(2_001) })
+ expect(view.result.current.data?.plan.id).toBe("studio")
+ expect(botRefreshes()).toBe(2)
+ expect(view.result.current.polling).toBe(false)
+ const calls = mocks.api.mock.calls.length
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
+ expect(mocks.api).toHaveBeenCalledTimes(calls)
+ view.unmount()
+ })
+
+ it("blocks unacknowledged Founder checkout and unrelated mutations", async () => {
+ mocks.api.mockResolvedValue({ ...free, isFounder: true })
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data?.isFounder).toBe(true))
+ await act(async () => { await view.result.current.checkout("price_any"); await view.result.current.portal(); await view.result.current.cancelChange() })
+ expect(mocks.api.mock.calls.every(([url]) => url === "/api/community/billing")).toBe(true)
+ view.unmount()
+ })
+
+ it("sends Founder acknowledgment only on explicit confirmed checkout and serializes it", async () => {
+ const founder = { ...free, isFounder: true }
+ mocks.api.mockResolvedValue(founder)
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data?.isFounder).toBe(true))
+ let reject!: (error: Error) => void
+ mocks.api.mockImplementation((url: string) => url.endsWith("/checkout")
+ ? new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) : Promise.resolve(founder))
+ let request!: Promise<void>
+ await act(async () => {
+ request = view.result.current.checkout("price_house", true)
+ void view.result.current.checkout("price_studio", true)
+ })
+ expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(1)
+ expect(mocks.api).toHaveBeenCalledWith("/api/community/billing/checkout", { method: "POST", body: '{"priceId":"price_house","founderAcknowledged":true}' })
+ await act(async () => { reject(new Error("cancel")); await request })
+ expect(view.result.current.data?.isFounder).toBe(true)
+ view.unmount()
+ })
+
+ it("serializes double clicks and allows retry after an unknown outcome", async () => {
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(free))
+ let reject!: (error: Error) => void
+ mocks.api.mockImplementation((url: string) => url.endsWith("/checkout")
+ ? new Promise((_resolve, rejectPromise) => { reject = rejectPromise })
+ : Promise.resolve(free))
+ let request!: Promise<void>
+ await act(async () => {
+ request = view.result.current.checkout("price_one")
+ void view.result.current.checkout("price_two")
+ })
+ expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(1)
+ expect(mocks.api).toHaveBeenCalledWith("/api/community/billing/checkout", { method: "POST", body: '{"priceId":"price_one"}' })
+ await act(async () => { reject(new Error("timeout")); await request })
+ expect(view.result.current.isBusy).toBe(false)
+ expect(view.result.current.actionError).toContain("resume your purchase")
+ mocks.api.mockImplementation((url: string) => url.endsWith("/checkout") ? Promise.reject(new Error("timeout")) : Promise.resolve(free))
+ await act(async () => { await view.result.current.checkout("price_one") })
+ expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/checkout"))).toHaveLength(2)
+ view.unmount()
+ })
+
+ it("rejects an unsafe redirect and exposes a recoverable management error", async () => {
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(free))
+ mocks.api.mockImplementation((url: string) => Promise.resolve(url.endsWith("/portal") ? { url: "javascript:alert(1)" } : free))
+ await act(async () => { await view.result.current.portal() })
+ expect(view.result.current.actionError).toContain("billing management")
+ expect(view.result.current.isBusy).toBe(false)
+ view.unmount()
+ })
+
+ it("navigates to the hosted confirmation for a selected price and recovers after browser Back", async () => {
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(free))
+ const originalWindow = window
+ const assign = vi.fn()
+ const mockWindow = new Proxy(originalWindow, {
+ get: (target, key) => key === "location" ? { assign } : Reflect.get(target, key, target),
+ })
+ mocks.api.mockImplementation((url: string) => Promise.resolve(url.endsWith("/portal") ? { url: "https://billing.stripe.com/p/session" } : free))
+ vi.stubGlobal("window", mockWindow)
+ await act(async () => { await view.result.current.portal("price_target") })
+ expect(mocks.api).toHaveBeenCalledWith("/api/community/billing/portal", { method: "POST", body: '{"priceId":"price_target"}' })
+ expect(assign).toHaveBeenCalledWith("https://billing.stripe.com/p/session")
+ expect(view.result.current.isBusy).toBe(true)
+ vi.stubGlobal("window", originalWindow)
+ const restored = new Event("pageshow")
+ Object.defineProperty(restored, "persisted", { value: true })
+ await act(async () => { originalWindow.dispatchEvent(restored) })
+ expect(view.result.current.isBusy).toBe(false)
+ expect(view.invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.billing() })
+ view.unmount()
+ })
+
+ it.each([false, true])("uses the cancel-change response without assuming the old plan survives (crossed period: %s)", async (crossedPeriod) => {
+ const house = { id: "house", displayName: "House" }
+ const scheduled = { ...free, plan: house, subscription: {
+ plan: house, status: "active", currentPeriodEnd: "2026-10-10T00:00:00Z", cancelAt: "2026-10-08T00:00:00Z",
+ scheduledChange: { plan: free.plan, effectiveAt: "2026-10-10T00:00:00Z" },
+ } }
+ mocks.api.mockResolvedValue(scheduled)
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data?.subscription?.scheduledChange).toBeTruthy())
+ const response = { ...scheduled, plan: crossedPeriod ? free.plan : house, subscription: { ...scheduled.subscription, scheduledChange: null } }
+ let finish!: (value: unknown) => void
+ mocks.api.mockImplementation(() => new Promise((resolve) => { finish = resolve }))
+ let request!: Promise<void>
+ await act(async () => {
+ request = view.result.current.cancelChange()
+ void view.result.current.cancelChange()
+ void view.result.current.portal()
+ })
+ expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/cancel-change"))).toHaveLength(1)
+ expect(mocks.api).toHaveBeenLastCalledWith("/api/community/billing/cancel-change", { method: "POST" })
+ await waitFor(() => expect(view.result.current.isCancelingChange).toBe(true))
+ await act(async () => { finish(response); await request })
+ await waitFor(() => expect(view.result.current.data).toEqual(response))
+ expect(view.result.current.isBusy).toBe(false)
+ expect(view.invalidate.mock.calls.filter(([args]) => JSON.stringify(args?.queryKey) === JSON.stringify(communityKeys.bots()))).toHaveLength(crossedPeriod ? 1 : 0)
+ view.unmount()
+ })
+
+ it("keeps a failed cancellation recoverable without optimistic plan changes", async () => {
+ const scheduled = { ...free, subscription: { plan: free.plan, status: "active", currentPeriodEnd: null, cancelAt: null, scheduledChange: { plan: free.plan, effectiveAt: "2026-10-10T00:00:00Z" } } }
+ mocks.api.mockResolvedValue(scheduled)
+ const view = setup()
+ await waitFor(() => expect(view.result.current.data).toEqual(scheduled))
+ mocks.api.mockImplementation((url: string) => url.endsWith("/cancel-change") ? Promise.reject(new Error("timeout")) : Promise.resolve(scheduled))
+ await act(async () => { await view.result.current.cancelChange() })
+ expect(view.result.current.actionError).toContain("scheduled plan change")
+ expect(view.result.current.data).toEqual(scheduled)
+ expect(view.result.current.isBusy).toBe(false)
+ await act(async () => { await view.result.current.cancelChange() })
+ expect(mocks.api.mock.calls.filter(([url]) => url.endsWith("/cancel-change"))).toHaveLength(2)
+ view.unmount()
+ })
+
+ it("rejects a malformed summary instead of showing fabricated plan state", async () => {
+ mocks.api.mockResolvedValue({ plan: free.plan })
+ const view = setup()
+ await waitFor(() => expect(view.result.current.isError).toBe(true))
+ expect(view.result.current.data).toBeUndefined()
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-billing.ts b/src/web/src/hooks/community/use-billing.ts
new file mode 100644
index 000000000..9bfae06f3
--- /dev/null
+++ b/src/web/src/hooks/community/use-billing.ts
@@ -0,0 +1,185 @@
+"use client"
+
+import { useEffect, useRef, useState } from "react"
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
+import { BillingSummarySchema, BillingRedirectResponseSchema } from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+
+export type BillingReturn = "checkout" | "cancel" | "portal" | null
+type BillingAction = { kind: "checkout"; priceId: string; founderAcknowledged?: boolean } | { kind: "portal"; priceId?: string }
+
+export function readBillingReturn(value: string | null): BillingReturn {
+ return value === "checkout" || value === "cancel" || value === "portal" ? value : null
+}
+
+export function useBilling(returnFrom: BillingReturn = null, enabled = false) {
+ const qc = useQueryClient()
+ const [polling, setPolling] = useState(false)
+ const [actionError, setActionError] = useState<string | null>(null)
+ const actionLock = useRef(false)
+ const [redirecting, setRedirecting] = useState(false)
+ const observedPlan = useRef<string | null>(null)
+ const returnStartedAt = useRef(0)
+ const handledReturn = useRef<BillingReturn>(null)
+ const returnPollingComplete = useRef(false)
+ const query = useQuery({
+ queryKey: communityKeys.billing(),
+ enabled,
+ queryFn: async ({ signal }) => BillingSummarySchema.parse(
+ await apiFetch<unknown>("/api/community/billing", { signal }),
+ ),
+ staleTime: 30_000,
+ refetchOnWindowFocus: true,
+ refetchInterval: polling ? 2_000 : false,
+ retry: false,
+ })
+
+ useEffect(() => {
+ const restore = (event: PageTransitionEvent) => {
+ if (!event.persisted) return
+ actionLock.current = false
+ setRedirecting(false)
+ if (enabled) {
+ void qc.invalidateQueries({ queryKey: communityKeys.billing() })
+ void qc.invalidateQueries({ queryKey: communityKeys.bots() })
+ void qc.invalidateQueries({ queryKey: communityKeys.machines() })
+ }
+ }
+ window.addEventListener("pageshow", restore)
+ return () => window.removeEventListener("pageshow", restore)
+ }, [enabled, qc])
+
+ useEffect(() => {
+ if (!returnFrom) {
+ handledReturn.current = null
+ setPolling(false)
+ return
+ }
+ if (!enabled) {
+ setPolling(false)
+ return
+ }
+ if (handledReturn.current === returnFrom) {
+ if (!returnPollingComplete.current && returnFrom !== "cancel" && Date.now() - returnStartedAt.current < 30_000) setPolling(true)
+ return
+ }
+ handledReturn.current = returnFrom
+ returnPollingComplete.current = false
+ returnStartedAt.current = Date.now()
+ void qc.invalidateQueries({ queryKey: communityKeys.billing() })
+ void qc.invalidateQueries({ queryKey: communityKeys.bots() })
+ void qc.invalidateQueries({ queryKey: communityKeys.machines() })
+ if (returnFrom === "cancel") return
+ setPolling(true)
+ }, [enabled, returnFrom, qc])
+
+ useEffect(() => {
+ if (!enabled || !polling) return
+ const remaining = Math.max(0, 30_000 - (Date.now() - returnStartedAt.current))
+ const timer = setTimeout(() => {
+ returnPollingComplete.current = true
+ setPolling(false)
+ }, remaining)
+ return () => clearTimeout(timer)
+ }, [enabled, polling])
+
+ useEffect(() => {
+ if (!enabled || !query.data) return
+ const projection = `${query.data.plan.id}:${query.data.isFounder}`
+ const cachedBots = qc.getQueryData<{ plan: { id: string }; isFounder: boolean }>(communityKeys.bots())
+ const previous = observedPlan.current ?? (cachedBots ? `${cachedBots.plan.id}:${cachedBots.isFounder}` : null)
+ if (previous !== null && previous !== projection) {
+ void qc.invalidateQueries({ queryKey: communityKeys.bots() })
+ void qc.invalidateQueries({ queryKey: communityKeys.machines() })
+ }
+ observedPlan.current = projection
+ if (
+ returnFrom === "checkout" && !query.data.isFounder && query.dataUpdatedAt >= returnStartedAt.current &&
+ query.data.subscription?.status === "active" &&
+ query.data.subscription.plan.id === query.data.plan.id
+ ) {
+ returnPollingComplete.current = true
+ setPolling(false)
+ }
+ }, [enabled, returnFrom, query.data, query.dataUpdatedAt, qc])
+
+ const redirect = useMutation({
+ mutationFn: async (action: BillingAction) => {
+ const result = BillingRedirectResponseSchema.parse(await apiFetch<unknown>(
+ `/api/community/billing/${action.kind}`,
+ {
+ method: "POST",
+ ...(action.priceId ? { body: JSON.stringify({ priceId: action.priceId, ...(action.kind === "checkout" && action.founderAcknowledged ? { founderAcknowledged: true } : {}) }) } : {}),
+ },
+ ))
+ const url = new URL(result.url)
+ if (url.protocol !== "https:") throw new Error("INVALID_BILLING_URL")
+ return url.href
+ },
+ retry: false,
+ })
+
+ const start = async (action: BillingAction) => {
+ if (actionLock.current || !query.data) return
+ if (query.data.isFounder && (action.kind !== "checkout" || !action.founderAcknowledged)) return
+ actionLock.current = true
+ setActionError(null)
+ try {
+ const url = await redirect.mutateAsync(action)
+ setRedirecting(true)
+ window.location.assign(url)
+ } catch {
+ actionLock.current = false
+ setRedirecting(false)
+ setActionError(action.kind === "checkout"
+ ? "Couldn't open checkout. Try again to resume your purchase."
+ : "Couldn't open billing management. Try again.")
+ void query.refetch()
+ }
+ }
+
+ const cancelChangeMutation = useMutation({
+ mutationFn: async () => BillingSummarySchema.parse(await apiFetch<unknown>(
+ "/api/community/billing/cancel-change", { method: "POST" },
+ )),
+ retry: false,
+ })
+
+ const cancelChange = async () => {
+ if (actionLock.current || !query.data?.subscription?.scheduledChange || query.data.isFounder) return
+ actionLock.current = true
+ setActionError(null)
+ try {
+ const summary = await cancelChangeMutation.mutateAsync()
+ await qc.cancelQueries({ queryKey: communityKeys.billing() })
+ qc.setQueryData(communityKeys.billing(), summary)
+ } catch {
+ setActionError("Couldn't cancel the scheduled plan change. Refresh status and try again.")
+ void query.refetch()
+ } finally {
+ actionLock.current = false
+ }
+ }
+
+ const refresh = () => {
+ void query.refetch()
+ void qc.invalidateQueries({ queryKey: communityKeys.bots() })
+ void qc.invalidateQueries({ queryKey: communityKeys.machines() })
+ }
+
+ return {
+ ...query,
+ returnFrom,
+ polling,
+ actionError,
+ isBusy: redirect.isPending || redirecting || cancelChangeMutation.isPending,
+ isCancelingChange: cancelChangeMutation.isPending,
+ cancelChange,
+ checkout: (priceId: string, founderAcknowledged = false) => start({ kind: "checkout", priceId, founderAcknowledged }),
+ portal: (priceId?: string) => start({ kind: "portal", priceId }),
+ refresh,
+ }
+}
+
+export type BillingController = ReturnType<typeof useBilling>
diff --git a/src/web/src/hooks/community/use-bots.dom.test.ts b/src/web/src/hooks/community/use-bots.dom.test.ts
index 83fd0b31b..57eb05bbd 100644
--- a/src/web/src/hooks/community/use-bots.dom.test.ts
+++ b/src/web/src/hooks/community/use-bots.dom.test.ts
@@ -64,6 +64,10 @@ describe("invalidateBotSurfaces", () => {
describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
it("useBots fetches through the profile-seeding query function", async () => {
apiFetchMock.mockResolvedValue({
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 1,
+ activeCount: 1,
bots: [{
id: "bot_1",
name: "Seeded Bot",
@@ -73,6 +77,7 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
machineId: null,
runtime: null,
modelName: null,
+ isActive: true,
lastRefreshContextAt: null,
dailyActivity: [],
}],
@@ -86,6 +91,8 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
"data-name": result.bots[0]?.name,
"data-avatar": result.bots[0]?.image,
"data-version": result.bots[0]?.avatarVersion,
+ "data-plan": result.data?.plan.displayName,
+ "data-limit": result.data?.limit,
})
}
@@ -101,10 +108,52 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
expect(output).toHaveAttribute("data-name", "Seeded Bot")
expect(output).toHaveAttribute("data-avatar", "S")
expect(output).toHaveAttribute("data-version", "2")
+ expect(output).toHaveAttribute("data-plan", "Free")
+ expect(output).toHaveAttribute("data-limit", "3")
})
act(() => renderer.unmount())
})
+ it("heals missed presence pushes after activation refetch", async () => {
+ const { useBots, useSetBotActive } = await import("./use-bots")
+ let active = false
+ apiFetchMock.mockImplementation(async (_path: string, options?: RequestInit) => {
+ if (options?.method === "PATCH") {
+ active = true
+ return { bot: { id: "bot_1", isActive: true }, changed: true }
+ }
+ return {
+ plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 1, activeCount: Number(active),
+ bots: [{ id: "bot_1", name: "Bot", image: null, avatarVersion: 0, isActive: active, presence: active ? "online" : "offline" }],
+ }
+ })
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let mutation!: ReturnType<typeof useSetBotActive>
+ function Probe() { useBots(); mutation = useSetBotActive(); return null }
+ render(React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)))
+ await waitFor(() => expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("offline"))
+ await act(async () => { await mutation.mutateAsync({ id: "bot_1", active: true }) })
+ await waitFor(() => expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("online"))
+ })
+
+ it("does not overwrite a newer presence event with a late bot list", async () => {
+ const { useBots } = await import("./use-bots")
+ let resolve!: (value: unknown) => void
+ apiFetchMock.mockReturnValue(new Promise((done) => { resolve = done }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ function Probe() { useBots(); return null }
+ render(React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)))
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalled())
+ const profiles = useCommunityWsStore.getState()
+ act(() => profiles.patchProfiles(profiles.beginProfileSnapshot(), [{ id: "bot_1", presence: "offline" }]))
+ await act(async () => resolve({
+ plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 1, activeCount: 1,
+ bots: [{ id: "bot_1", name: "Bot", image: null, avatarVersion: 0, isActive: true, presence: "online" }],
+ }))
+ await waitFor(() => expect(queryClient.getQueryData(communityKeys.bots())).toBeDefined())
+ expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("offline")
+ })
+
it("useCreateBot commits the returned bot profile before invalidating metadata", async () => {
const { useCreateBot } = await import("./use-bots")
apiFetchMock.mockResolvedValue({
@@ -149,6 +198,76 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
act(() => renderer.unmount())
})
+ it("useSetBotActive PATCHes once and commits the returned state before invalidating", async () => {
+ const { useSetBotActive } = await import("./use-bots")
+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
+ queryClient.setQueryData(communityKeys.bots(), {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 1,
+ activeCount: 1,
+ bots: [{ id: "bot_1", name: "Bot", isActive: true }],
+ })
+ apiFetchMock.mockResolvedValue({
+ bot: { id: "bot_1", isActive: false },
+ changed: true,
+ })
+ let mutation!: ReturnType<typeof useSetBotActive>
+ function Probe() {
+ mutation = useSetBotActive()
+ return null
+ }
+ const renderer = render(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe),
+ ))
+
+ await act(async () => {
+ await mutation.mutateAsync({ id: "bot_1", active: false })
+ })
+
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots/bot_1/active", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ active: false }),
+ })
+ expect(queryClient.getQueryData(communityKeys.bots())).toMatchObject({
+ activeCount: 0,
+ bots: [{ id: "bot_1", isActive: false }],
+ })
+ expect(queryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)
+ act(() => renderer.unmount())
+ })
+
+ it("leaves a missing or already-current bot cache unchanged after an activation response", async () => {
+ const { useSetBotActive } = await import("./use-bots")
+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
+ const original = {
+ plan: { id: "free", displayName: "Free" },
+ limit: 3,
+ ownedCount: 1,
+ activeCount: 1,
+ bots: [{ id: "bot_1", name: "Bot", isActive: true }],
+ }
+ apiFetchMock.mockResolvedValue({ bot: { id: "bot_1", isActive: true }, changed: false })
+ let mutation!: ReturnType<typeof useSetBotActive>
+ function Probe() { mutation = useSetBotActive(); return null }
+ const renderer = render(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe),
+ ))
+
+ await act(async () => { await mutation.mutateAsync({ id: "bot_1", active: true }) })
+ expect(queryClient.getQueryData(communityKeys.bots())).toBeUndefined()
+
+ queryClient.setQueryData(communityKeys.bots(), original)
+ await act(async () => { await mutation.mutateAsync({ id: "bot_1", active: true }) })
+ expect(queryClient.getQueryData(communityKeys.bots())).toBe(original)
+ act(() => renderer.unmount())
+ })
+
it("useUpdateBot forwards explicit reasoning effort values and omission", async () => {
const { useUpdateBot } = await import("./use-bots")
const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index a9b2fc6c2..528a53de3 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -37,6 +37,8 @@ export type BotSummary = {
modelName: string | null
reasoningEffort: ReasoningEffort | null
runtimeConfigRevision: number
+ isActive: boolean
+ presence: "online" | "offline"
// Context lifecycle (my-bots #516): when the agent last refreshed its context
// (nap, session reset, or provider switch), ISO string, null if it never has. Rendered as the
// awake-duration "Awake 17h" (Gus #672/#674 — how long the agent has been
@@ -51,7 +53,17 @@ export type BotSummary = {
// placeholder instead of inventing zero usage.
usage?: BotTokenUsage
}
-export type BotsResponse = { bots: BotSummary[] }
+export type BotPlanSummary = {
+ isFounder: boolean
+ plan: {
+ id: string
+ displayName: string
+ }
+ limit: number
+ ownedCount: number
+ activeCount: number
+}
+export type BotsResponse = BotPlanSummary & { bots: BotSummary[] }
const EMPTY_BOTS: readonly BotSummary[] = Object.freeze([])
@@ -77,7 +89,7 @@ export function useBots(): UseQueryResult<BotsResponse> & { bots: BotSummary[] }
queryKey: communityKeys.bots(),
queryFn: () => apiFetchProfiles<BotsResponse>(
"/api/community/bots",
- (data) => data.bots.map(botProfilePatch),
+ (data) => data.bots.map((bot) => ({ ...botProfilePatch(bot), presence: bot.presence })),
),
})
const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
@@ -140,6 +152,43 @@ export function useCreateBot() {
})
}
+export type SetBotActiveInput = {
+ id: string
+ active: boolean
+}
+
+export type SetBotActiveResponse = {
+ bot: Pick<BotSummary, "id" | "isActive">
+ changed: boolean
+}
+
+export function useSetBotActive() {
+ const qc = useQueryClient()
+ return useMutation({
+ mutationFn: ({ id, active }: SetBotActiveInput) =>
+ apiFetch<SetBotActiveResponse>(`/api/community/bots/${id}/active`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ active }),
+ }),
+ onSuccess: (data) => {
+ qc.setQueryData<BotsResponse>(communityKeys.bots(), (current) => {
+ if (!current) return current
+ const previous = current.bots.find((bot) => bot.id === data.bot.id)
+ if (!previous || previous.isActive === data.bot.isActive) return current
+ return {
+ ...current,
+ activeCount: Math.max(0, current.activeCount + (data.bot.isActive ? 1 : -1)),
+ bots: current.bots.map((bot) => (
+ bot.id === data.bot.id ? { ...bot, isActive: data.bot.isActive } : bot
+ )),
+ }
+ })
+ qc.invalidateQueries({ queryKey: communityKeys.bots() })
+ },
+ })
+}
+
export type UpdateBotInput = {
id: string
name?: string
diff --git a/src/web/src/hooks/community/use-machines.test.ts b/src/web/src/hooks/community/use-machines.test.ts
index ee79d3ac0..ff6502a48 100644
--- a/src/web/src/hooks/community/use-machines.test.ts
+++ b/src/web/src/hooks/community/use-machines.test.ts
@@ -53,3 +53,15 @@ describe("useMachines / machinesQueryFn", () => {
expect(state?.isInvalidated).toBe(true)
})
})
+
+
+describe("machine capacity cache", () => {
+ it("updates owned and online counts when a machine disconnects or is removed", async () => {
+ const { replaceMachines } = await import("./use-machines")
+ const original = { machines: [machineFixture], machineCapacity: { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 1, onlineCount: 1 } }
+ const offline = replaceMachines(original, [{ ...machineFixture, status: "offline" }])
+ expect(offline.machineCapacity).toMatchObject({ limit: 1, ownedCount: 1, onlineCount: 0 })
+ expect(replaceMachines(offline, []).machineCapacity).toMatchObject({ ownedCount: 0, onlineCount: 0 })
+ expect(replaceMachines({ machines: [] }, [machineFixture])).toEqual({ machines: [machineFixture] })
+ })
+})
diff --git a/src/web/src/hooks/community/use-machines.ts b/src/web/src/hooks/community/use-machines.ts
index a75d2cd37..db0a3f257 100644
--- a/src/web/src/hooks/community/use-machines.ts
+++ b/src/web/src/hooks/community/use-machines.ts
@@ -1,10 +1,12 @@
"use client"
import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import { isPresenceOnline } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type {
CommunityMachineSummary,
+ MachineCapacitySummary,
ProviderQuotaObservation,
QuotaLimit,
} from "@alook/shared"
@@ -47,7 +49,20 @@ export type MachineSummary = CommunityMachineSummary & {
* live-patch `communityKeys.machines()` via `queryClient.setQueryData` on
* `community:machine.*` WS events, so this list stays fresh without a refetch.
*/
-export type MachinesResponse = { machines: MachineSummary[] }
+export type MachineCapacity = MachineCapacitySummary
+export type MachinesResponse = { machines: MachineSummary[]; machineCapacity?: MachineCapacity }
+
+export function replaceMachines(data: MachinesResponse, machines: MachineSummary[]): MachinesResponse {
+ return {
+ ...data,
+ machines,
+ ...(data.machineCapacity ? { machineCapacity: {
+ ...data.machineCapacity,
+ ownedCount: machines.length,
+ onlineCount: machines.filter(machine => isPresenceOnline(machine.status)).length,
+ } } : {}),
+ }
+}
// Frozen empty fallback — see `use-servers.ts` for the rationale.
const EMPTY_MACHINES: readonly MachineSummary[] = Object.freeze([])
diff --git a/src/web/src/lib/billing/catalog.test.ts b/src/web/src/lib/billing/catalog.test.ts
new file mode 100644
index 000000000..158363ff6
--- /dev/null
+++ b/src/web/src/lib/billing/catalog.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type Stripe from "stripe"
+import type { Database } from "@alook/shared"
+
+const mocked = vi.hoisted(() => ({ listPrices: vi.fn() }))
+vi.mock("@alook/shared", async (original) => ({
+ ...await original<typeof import("@alook/shared")>(),
+ queries: { billing: mocked },
+}))
+import { getCatalog, requireOffer } from "./catalog"
+
+const db = {} as Database
+const env = { STRIPE_SECRET_KEY: "sk_test_fixture" } as Env
+const mapping = { priceId: "studio", planId: "studio", displayName: "Studio", botLimit: 10, machineLimit: 5 }
+const retrieve = vi.fn()
+const stripe = { prices: { retrieve } } as unknown as Stripe
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocked.listPrices.mockResolvedValue([mapping])
+ retrieve.mockResolvedValue({
+ id: "studio", active: true, livemode: false, type: "recurring", unit_amount: 2000,
+ currency: "usd", recurring: { interval: "month", interval_count: 1 }, product: { active: true },
+ })
+})
+
+describe("billing catalog purchase boundary", () => {
+ it("includes disabled mappings when reconciling historical purchases", async () => {
+ expect(await getCatalog(db)).toEqual([mapping])
+ expect(mocked.listPrices).toHaveBeenCalledWith(db, true)
+ expect(retrieve).not.toHaveBeenCalled()
+ })
+ it("requires an enabled server mapping and validates the actual Stripe price", async () => {
+ expect(await requireOffer(db, stripe, env, "studio")).toEqual({
+ priceId: "studio", plan: { id: "studio", displayName: "Studio" }, botLimit: 10, machineLimit: 5,
+ unitAmount: 2000, currency: "usd", interval: "month", intervalCount: 1,
+ })
+ expect(mocked.listPrices).toHaveBeenCalledWith(db)
+ expect(retrieve).toHaveBeenCalledWith("studio", { expand: ["product"] })
+ })
+ it("rejects unlisted prices without asking Stripe", async () => {
+ await expect(requireOffer(db, stripe, env, "foreign")).rejects.toMatchObject({ code: "BILLING_PRICE_UNAVAILABLE", status: 400 })
+ expect(retrieve).not.toHaveBeenCalled()
+ })
+ it("rejects a mapped price disabled upstream", async () => {
+ retrieve.mockResolvedValue({ active: false, livemode: false })
+ await expect(requireOffer(db, stripe, env, "studio")).rejects.toMatchObject({ code: "BILLING_PRICE_UNAVAILABLE", status: 400 })
+ })
+})
diff --git a/src/web/src/lib/billing/catalog.ts b/src/web/src/lib/billing/catalog.ts
new file mode 100644
index 000000000..a816c50cf
--- /dev/null
+++ b/src/web/src/lib/billing/catalog.ts
@@ -0,0 +1,48 @@
+import { BillingOfferSchema, PublicPricingSchema, queries, type Database } from "@alook/shared"
+import type Stripe from "stripe"
+import { assertStripeMode, BillingError } from "./client"
+
+type Mapping = Awaited<ReturnType<typeof queries.billing.listPrices>>[number]
+
+export async function getCatalog(db: Database) {
+ return queries.billing.listPrices(db, true)
+}
+
+async function offerFor(stripe: Stripe, env: Env, mapping: Mapping) {
+ const price = await stripe.prices.retrieve(mapping.priceId, { expand: ["product"] })
+ assertStripeMode(env, price)
+ const product = price.product
+ if (!price.active || !price.recurring || price.type !== "recurring" || price.unit_amount === null
+ || typeof product === "string" || product.deleted || !product.active) return null
+ return BillingOfferSchema.parse({
+ priceId: price.id,
+ plan: { id: mapping.planId, displayName: mapping.displayName },
+ botLimit: mapping.botLimit,
+ machineLimit: mapping.machineLimit,
+ unitAmount: price.unit_amount,
+ currency: price.currency,
+ interval: price.recurring.interval,
+ intervalCount: price.recurring.interval_count,
+ })
+}
+
+export async function getOffers(db: Database, stripe: Stripe, env: Env) {
+ const mappings = await queries.billing.listPrices(db)
+ const offers = await Promise.all(mappings.map((mapping) => offerFor(stripe, env, mapping)))
+ return offers.filter((offer) => offer !== null)
+}
+
+export async function getPublicPricing(db: Database, stripe: Stripe, env: Env) {
+ const [free, offers] = await Promise.all([
+ queries.billing.getDefaultPlanOffer(db),
+ getOffers(db, stripe, env),
+ ])
+ return PublicPricingSchema.parse({ free, offers })
+}
+
+export async function requireOffer(db: Database, stripe: Stripe, env: Env, priceId: string) {
+ const mapping = (await queries.billing.listPrices(db)).find((item) => item.priceId === priceId)
+ const offer = mapping ? await offerFor(stripe, env, mapping) : null
+ if (!offer) throw new BillingError("BILLING_PRICE_UNAVAILABLE", 400)
+ return offer
+}
diff --git a/src/web/src/lib/billing/client.test.ts b/src/web/src/lib/billing/client.test.ts
new file mode 100644
index 000000000..e0cbc2946
--- /dev/null
+++ b/src/web/src/lib/billing/client.test.ts
@@ -0,0 +1,6 @@
+import { expect, it } from "vitest"
+import { billingOrigin } from "./client"
+
+it.each(["http://alook.ai", "ftp://alook.ai"])("rejects unsafe billing return origin %s", (origin) => {
+ expect(() => billingOrigin({ STRIPE_RETURN_ORIGIN: origin } as Env)).toThrow("BILLING_UNAVAILABLE")
+})
diff --git a/src/web/src/lib/billing/client.ts b/src/web/src/lib/billing/client.ts
new file mode 100644
index 000000000..c41487cd0
--- /dev/null
+++ b/src/web/src/lib/billing/client.ts
@@ -0,0 +1,53 @@
+import Stripe from "stripe"
+import { NextResponse } from "next/server"
+
+export class BillingError extends Error {
+ constructor(public readonly code: string, public readonly status = 409) {
+ super(code)
+ }
+}
+
+export function billingClient(env: Env) {
+ if (!env.STRIPE_SECRET_KEY) throw new BillingError("BILLING_UNAVAILABLE", 503)
+ return new Stripe(env.STRIPE_SECRET_KEY, {
+ apiVersion: "2026-08-26.dahlia",
+ httpClient: Stripe.createFetchHttpClient(),
+ maxNetworkRetries: 2,
+ timeout: 20_000,
+ })
+}
+
+export function assertStripeMode(env: Env, object: { livemode: boolean }) {
+ const live = /^(sk|rk)_live_/.test(env.STRIPE_SECRET_KEY ?? "")
+ if (object.livemode !== live) throw new BillingError("BILLING_ENVIRONMENT_MISMATCH", 503)
+}
+
+export function billingOrigin(env: Env) {
+ const url = new URL(env.STRIPE_RETURN_ORIGIN ?? env.BETTER_AUTH_URL)
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
+ throw new BillingError("BILLING_UNAVAILABLE", 503)
+ }
+ return url.origin
+}
+
+export function billingResponse(value: unknown, status = 200) {
+ return NextResponse.json(value, { status, headers: { "Cache-Control": "no-store" } })
+}
+
+export function billingFailure(error: unknown, operation: string = "billing") {
+ if (!(error instanceof BillingError)) {
+ const detail = error as { name?: string; type?: string; code?: string; requestId?: string; statusCode?: number; cause?: { code?: string; name?: string } } | null
+ console.error("billing_request_failed", {
+ operation, name: detail?.name, type: detail?.type, code: detail?.code,
+ status: detail?.statusCode, requestId: detail?.requestId,
+ causeName: detail?.cause?.name, causeCode: detail?.cause?.code,
+ })
+ }
+ return error instanceof BillingError
+ ? billingResponse({ error: error.code }, error.status)
+ : billingResponse({ error: "BILLING_UNAVAILABLE" }, 503)
+}
+
+export function stripeId(value: string | { id: string } | null | undefined) {
+ return typeof value === "string" ? value : value?.id ?? null
+}
diff --git a/src/web/src/lib/billing/machine-notifications.test.ts b/src/web/src/lib/billing/machine-notifications.test.ts
new file mode 100644
index 000000000..02fae3da4
--- /dev/null
+++ b/src/web/src/lib/billing/machine-notifications.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { queries } from "@alook/shared"
+import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
+import { broadcastToUser } from "@/lib/broadcast"
+import { fanOutPresenceUpdate } from "@/lib/community/fanout"
+import { notifyDisconnectedMachines } from "./reconcile"
+vi.mock("@/lib/community/machine-disconnect", () => ({ forceCloseCommunityMachinesByDoNames: vi.fn(async () => {}) }))
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn(async () => {}) }))
+vi.mock("@/lib/community/fanout", () => ({ fanOutPresenceUpdate: vi.fn(async () => {}) }))
+vi.mock("@/lib/community/bot-push", () => ({ pushBotEventToMachine: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries,
+ communityMachine: { ...actual.queries.communityMachine, getMachineByIdForUser: vi.fn() },
+ communityBot: { ...actual.queries.communityBot, listBotsBoundToMachine: vi.fn() },
+ } }
+})
+const machine = { machineId: "m", userId: "owner", doName: "old-do" }
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(queries.communityMachine.getMachineByIdForUser).mockResolvedValue({ status: "offline", lastSeenAt: "then" } as never)
+ vi.mocked(queries.communityBot.listBotsBoundToMachine).mockResolvedValue([{ id: "bot" }] as never)
+})
+describe("committed machine disconnection notifications", () => {
+ it("closes captured epochs once and broadcasts owner-scoped machine and bot status", async () => {
+ await notifyDisconnectedMachines({} as Env, {} as never, [machine, machine, { ...machine, doName: null }])
+ expect(forceCloseCommunityMachinesByDoNames).toHaveBeenCalledWith({}, ["old-do"])
+ expect(broadcastToUser).toHaveBeenCalledExactlyOnceWith("owner", { type: "community:machine.status", machineId: "m", status: "offline", lastSeenAt: "then" })
+ expect(queries.communityBot.listBotsBoundToMachine).toHaveBeenCalledWith({}, "m", "owner")
+ expect(fanOutPresenceUpdate).toHaveBeenCalledExactlyOnceWith("bot", false, "owner")
+ })
+ it("does not mark a manually reconnected machine or its bots offline", async () => {
+ vi.mocked(queries.communityMachine.getMachineByIdForUser).mockResolvedValue({ status: "online" } as never)
+ await notifyDisconnectedMachines({} as Env, {} as never, [machine])
+ expect(forceCloseCommunityMachinesByDoNames).toHaveBeenCalledWith({}, ["old-do"])
+ expect(broadcastToUser).not.toHaveBeenCalled()
+ expect(fanOutPresenceUpdate).not.toHaveBeenCalled()
+ })
+ it("stops bot notifications if reconnect wins between broadcasts", async () => {
+ vi.mocked(queries.communityMachine.getMachineByIdForUser).mockResolvedValueOnce({ status: "offline", lastSeenAt: null } as never).mockResolvedValueOnce({ status: "online" } as never)
+ await notifyDisconnectedMachines({} as Env, {} as never, [machine])
+ expect(broadcastToUser).toHaveBeenCalledWith("owner", expect.objectContaining({ lastSeenAt: expect.any(String) }))
+ expect(fanOutPresenceUpdate).not.toHaveBeenCalled()
+ })
+ it("skips deleted rows and contains post-commit delivery failures", async () => {
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {})
+ vi.mocked(queries.communityMachine.getMachineByIdForUser).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error("unavailable"))
+ await notifyDisconnectedMachines({} as Env, {} as never, [machine, { machineId: "n", userId: "owner", doName: null }])
+ expect(broadcastToUser).not.toHaveBeenCalled()
+ expect(warning).toHaveBeenCalledWith("billing_post_commit_machine_notification_failed", { machineId: "n" })
+ warning.mockRestore()
+ })
+})
diff --git a/src/web/src/lib/billing/reconcile-races.test.ts b/src/web/src/lib/billing/reconcile-races.test.ts
new file mode 100644
index 000000000..34f9200a4
--- /dev/null
+++ b/src/web/src/lib/billing/reconcile-races.test.ts
@@ -0,0 +1,224 @@
+vi.mock("@/lib/community/machine-disconnect", () => ({ forceCloseCommunityMachinesByDoNames: vi.fn(async () => {}) }))
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn(async () => {}) }))
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type Stripe from "stripe"
+import type { Database } from "@alook/shared"
+const mocked = vi.hoisted(() => ({ getBilling: vi.fn(), getEffectivePlan: vi.fn(), getDefaultPlan: vi.fn(), applyBillingPlan: vi.fn(), getUserInternal: vi.fn(), getBotOwnedBy: vi.fn(), getCatalog: vi.fn(), push: vi.fn(), presence: vi.fn() }))
+vi.mock("@alook/shared", () => ({ queries: { billing: mocked, user: mocked, communityBot: mocked } }))
+vi.mock("./catalog", () => ({ getCatalog: mocked.getCatalog }))
+vi.mock("@/lib/community/bot-push", () => ({ pushBotEventToMachine: mocked.push }))
+vi.mock("@/lib/community/fanout", () => ({ fanOutPresenceUpdate: mocked.presence }))
+import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
+import { currentSubscription, notifyDeactivated, reconcileBilling } from "./reconcile"
+
+const db = {} as Database
+const env = { STRIPE_SECRET_KEY: "sk_test_fixture" } as Env
+const row = { userId: "owner", customerId: "cus_1", subscriptionId: "sub_old", subscription: null, checkoutAttempt: null, revision: 1, applyToken: null, updatedAt: "2026-09-10" }
+function sub(id: string, price: string) {
+ return { id, customer: "cus_1", livemode: false, metadata: { alook_user_id: "owner" }, status: "active", cancel_at: null, cancel_at_period_end: false,
+ items: { data: [{ id: "si_1", quantity: 1, price: { id: price }, current_period_end: 1791604427 }] },
+ latest_invoice: { status: "paid", lines: { data: [{ amount: 2000, parent: { subscription_item_details: { subscription: id } }, pricing: { price_details: { price } } }] } },
+ }
+}
+let stripe: Stripe
+let retrieve: ReturnType<typeof vi.fn>
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocked.getBilling.mockResolvedValue(row)
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: false })
+ mocked.getUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })
+ mocked.getDefaultPlan.mockResolvedValue({ id: "free", displayName: "Free" })
+ mocked.getCatalog.mockResolvedValue([{ priceId: "studio", planId: "studio", displayName: "Studio" }, { priceId: "house", planId: "house", displayName: "House" }])
+ mocked.applyBillingPlan.mockResolvedValue({ applied: true, deactivatedBotIds: [] })
+ retrieve = vi.fn(async () => sub("sub_new", "house"))
+ stripe = { customers: { retrieve: vi.fn(async () => ({ livemode: false, metadata: { alook_user_id: "owner" } })) }, subscriptions: {
+ list: vi.fn(() => ({ async *[Symbol.asyncIterator]() { yield sub("sub_new", "house") } })), retrieve,
+ } } as unknown as Stripe
+})
+
+describe("reconciliation freshness and post-commit effects", () => {
+ it("passes the committed machine epochs into automatic disconnection", async () => {
+ mocked.applyBillingPlan.mockResolvedValue({ applied: true, deactivatedBotIds: [], disconnectedMachines: [{ machineId: "m", userId: "owner", doName: "captured-old-epoch" }] })
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {})
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(forceCloseCommunityMachinesByDoNames).toHaveBeenCalledExactlyOnceWith(env, ["captured-old-epoch"])
+ warning.mockRestore()
+ })
+
+ function confirmedFounder() {
+ const attempt = { id: "attempt-founder", priceId: "studio", founderAcknowledged: true, sessionId: "cs-founder" }
+ mocked.getBilling.mockResolvedValue({ ...row, checkoutAttempt: attempt })
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: true })
+ const subscription = { ...sub("sub_new", "studio"), metadata: { alook_user_id: "owner", alook_attempt_id: attempt.id } }
+ retrieve.mockResolvedValue(subscription)
+ const session = { id: "cs-founder", livemode: false, status: "complete", payment_status: "paid", mode: "subscription",
+ customer: "cus_1", subscription: "sub_new", client_reference_id: "owner", metadata: subscription.metadata }
+ stripe.checkout = { sessions: { retrieve: vi.fn(async () => session) } } as unknown as Stripe["checkout"]
+ return { attempt, subscription, session }
+ }
+
+ it("only converts the current acknowledged paid Founder purchase", async () => {
+ confirmedFounder()
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).toHaveBeenCalledWith(db, expect.objectContaining({ checkoutAttempt: { id: "attempt-founder", priceId: "studio", founderAcknowledged: true, sessionId: "cs-founder" } }), expect.objectContaining({ checkoutAttempt: null, subscriptionId: "sub_new" }), "studio", "attempt-founder")
+ })
+
+ it.each([
+ { status: "open" }, { payment_status: "unpaid" }, { customer: "foreign" }, { subscription: "sub_old" },
+ { client_reference_id: "other" }, { metadata: { alook_user_id: "owner", alook_attempt_id: "old" } },
+ ])("keeps Founder for an unpaid or mismatched Checkout: %j", async (change) => {
+ const { session } = confirmedFounder()
+ vi.mocked(stripe.checkout.sessions.retrieve).mockResolvedValue({ ...session, ...change } as Stripe.Response<Stripe.Checkout.Session>)
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it.each(["canceled", "unpaid", "incomplete", "incomplete_expired"])("keeps Founder for subscription status %s", async (status) => {
+ const { subscription } = confirmedFounder()
+ retrieve.mockResolvedValue({ ...subscription, status })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("does not use a paid unrelated subscription or a pending update as Founder consent", async () => {
+ const { subscription } = confirmedFounder()
+ retrieve.mockResolvedValue({ ...subscription, metadata: { alook_user_id: "owner", alook_attempt_id: "old" } })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ retrieve.mockResolvedValue({ ...subscription, pending_update: {} })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("recovers a paid Founder session after the session-id write was lost", async () => {
+ const { attempt, session } = confirmedFounder()
+ mocked.getBilling.mockResolvedValue({ ...row, checkoutAttempt: { ...attempt, sessionId: null } })
+ stripe.checkout.sessions.list = vi.fn(() => ({ async *[Symbol.asyncIterator]() {
+ yield { ...session, id: "unrelated", metadata: { alook_attempt_id: "old" } }
+ yield session
+ } })) as unknown as typeof stripe.checkout.sessions.list
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(stripe.checkout.sessions.retrieve).not.toHaveBeenCalled()
+ expect(mocked.applyBillingPlan).toHaveBeenCalledWith(db, expect.anything(), expect.objectContaining({ checkoutAttempt: null }), "studio", attempt.id)
+ })
+
+ it("keeps ambiguous lost-session recovery retryable without Founder conversion", async () => {
+ const { attempt, session } = confirmedFounder()
+ mocked.getBilling.mockResolvedValue({ ...row, checkoutAttempt: { ...attempt, sessionId: null } })
+ stripe.checkout.sessions.list = vi.fn(() => ({ async *[Symbol.asyncIterator]() {
+ yield session
+ yield { ...session, id: "another-session" }
+ } })) as unknown as typeof stripe.checkout.sessions.list
+ await expect(reconcileBilling(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_CHECKOUT_MISMATCH", status: 503 })
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("does not carry consent across a losing revision into an unacknowledged attempt", async () => {
+ const { attempt } = confirmedFounder()
+ mocked.getBilling.mockResolvedValueOnce({ ...row, checkoutAttempt: attempt })
+ .mockResolvedValue({ ...row, revision: 2, checkoutAttempt: { ...attempt, id: "replacement", founderAcknowledged: false } })
+ mocked.applyBillingPlan.mockResolvedValueOnce({ applied: false, deactivatedBotIds: [] })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).toHaveBeenCalledOnce()
+ expect(retrieve).toHaveBeenCalledOnce()
+ expect(mocked.push).not.toHaveBeenCalled()
+ expect(mocked.presence).not.toHaveBeenCalled()
+ })
+
+ it.each(["current-price", "paid-price", "invoice-subscription"])("preserves Founder when %s does not match the authorized purchase", async (mismatch) => {
+ const { subscription } = confirmedFounder()
+ if (mismatch === "current-price") subscription.items.data[0].price.id = "house"
+ if (mismatch === "paid-price") subscription.latest_invoice.lines.data[0].pricing.price_details.price = "house"
+ if (mismatch === "invoice-subscription") subscription.latest_invoice.lines.data[0].parent.subscription_item_details.subscription = "foreign"
+ retrieve.mockResolvedValue(subscription)
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("reads primary revision before fetching Stripe and refetches everything after losing a batch", async () => {
+ mocked.applyBillingPlan.mockResolvedValueOnce({ applied: false, deactivatedBotIds: [] })
+ retrieve.mockResolvedValueOnce(sub("sub_new", "studio"))
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(retrieve).toHaveBeenCalledTimes(2)
+ expect(mocked.getBilling).toHaveBeenCalledTimes(2)
+ expect(mocked.applyBillingPlan.mock.calls.map((call) => call[3])).toEqual(["studio", "house"])
+ expect(mocked.getBilling.mock.invocationCallOrder[0]).toBeLessThan(retrieve.mock.invocationCallOrder[0])
+ expect(mocked.getBilling.mock.invocationCallOrder[1]).toBeLessThan(retrieve.mock.invocationCallOrder[1])
+ })
+ it("keeps a persistent conflict retryable after bounded fresh attempts", async () => {
+ mocked.applyBillingPlan.mockResolvedValue({ applied: false, deactivatedBotIds: [] })
+ await expect(reconcileBilling(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_RETRY_REQUIRED", status: 503 })
+ expect(retrieve).toHaveBeenCalledTimes(4)
+ })
+ it("selects the current managed subscription instead of the stored old canceled identity", async () => {
+ expect((await currentSubscription(stripe, env, row))?.id).toBe("sub_new")
+ expect(retrieve).toHaveBeenCalledWith("sub_new", expect.anything())
+ })
+ it("rejects foreign customer metadata before looking at subscriptions", async () => {
+ vi.mocked(stripe.customers.retrieve).mockResolvedValue({ livemode: false, metadata: { alook_user_id: "other" } } as Stripe.Response<Stripe.Customer>)
+ await expect(currentSubscription(stripe, env, row)).rejects.toMatchObject({ code: "BILLING_CUSTOMER_MISMATCH" })
+ expect(retrieve).not.toHaveBeenCalled()
+ })
+ it("can revoke the canceled subscription after Stripe deletes its customer", async () => {
+ vi.mocked(stripe.customers.retrieve).mockResolvedValue({ id: "cus_1", deleted: true } as Stripe.Response<Stripe.DeletedCustomer>)
+ retrieve.mockResolvedValue({ ...sub("sub_old", "house"), status: "canceled" })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(mocked.applyBillingPlan).toHaveBeenCalledWith(db, row, expect.objectContaining({ subscription: null }), "free")
+ })
+ it("does not call Stripe or apply a projection for a Founder", async () => {
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: true })
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(stripe.customers.retrieve).not.toHaveBeenCalled()
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+ it("does not send an old removal after a bot has been reactivated", async () => {
+ mocked.getBotOwnedBy.mockResolvedValue({ isActive: true, machineId: "m1" })
+ await notifyDeactivated(env, db, "owner", ["bot1"])
+ expect(mocked.push).not.toHaveBeenCalled()
+ expect(mocked.presence).not.toHaveBeenCalled()
+ })
+ it("checks current state again before forcing Offline", async () => {
+ mocked.getBotOwnedBy.mockResolvedValueOnce({ isActive: false, machineId: "m1" }).mockResolvedValueOnce({ isActive: true, machineId: "m1" })
+ await notifyDeactivated(env, db, "owner", ["bot1"])
+ expect(mocked.push).toHaveBeenCalledOnce()
+ expect(mocked.presence).not.toHaveBeenCalled()
+ })
+ it("does not turn best-effort notification failure into a failed durable commit", async () => {
+ mocked.applyBillingPlan.mockResolvedValue({ applied: true, deactivatedBotIds: ["bot1"] })
+ mocked.getBotOwnedBy.mockResolvedValue({ isActive: false, machineId: "m1" })
+ mocked.push.mockRejectedValue(new Error("offline"))
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBeUndefined()
+ expect(mocked.applyBillingPlan).toHaveBeenCalledOnce()
+ })
+})
+
+it("refuses a deleted customer's still-active subscription instead of revoking blindly", async () => {
+ vi.mocked(stripe.customers.retrieve).mockResolvedValue({ id: "cus_1", deleted: true } as Stripe.Response<Stripe.DeletedCustomer>)
+ await expect(currentSubscription(stripe, env, row)).rejects.toMatchObject({ code: "BILLING_CUSTOMER_UNAVAILABLE", status: 503 })
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+})
+
+it("refuses a retrieved subscription that belongs to another customer", async () => {
+ retrieve.mockResolvedValue({ ...sub("sub_new", "house"), customer: "foreign" })
+ await expect(currentSubscription(stripe, env, row)).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_MISMATCH", status: 503 })
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+})
+
+it("rejects multiple subscription units without changing entitlements", async () => {
+ const subscription = sub("sub_new", "house")
+ subscription.items.data[0].quantity = 2
+ retrieve.mockResolvedValue(subscription)
+ await expect(reconcileBilling(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_UNSUPPORTED", status: 503 })
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+})
+
+it("retains the last paid tier when the newest renewal invoice is still open", async () => {
+ const subscription = sub("sub_new", "house")
+ const paid = structuredClone(subscription.latest_invoice)
+ retrieve.mockResolvedValue({ ...subscription, status: "past_due", latest_invoice: { status: "open" } })
+ const list = vi.fn(async () => ({ data: [paid] }))
+ stripe.invoices = { list } as unknown as Stripe["invoices"]
+ await reconcileBilling(db, stripe, env, "owner")
+ expect(list).toHaveBeenCalledWith({ subscription: "sub_new", status: "paid", limit: 1 })
+ expect(mocked.applyBillingPlan).toHaveBeenCalledWith(db, row, expect.objectContaining({ subscription: expect.objectContaining({ status: "past_due" }) }), "house")
+})
diff --git a/src/web/src/lib/billing/reconcile.test.ts b/src/web/src/lib/billing/reconcile.test.ts
new file mode 100644
index 000000000..f3e073b42
--- /dev/null
+++ b/src/web/src/lib/billing/reconcile.test.ts
@@ -0,0 +1,98 @@
+vi.mock("@/lib/community/machine-disconnect", () => ({ forceCloseCommunityMachinesByDoNames: vi.fn(async () => {}) }))
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn(async () => {}) }))
+import { describe, expect, it, vi } from "vitest"
+import type Stripe from "stripe"
+vi.mock("@/lib/community/bot-push", () => ({ pushBotEventToMachine: vi.fn() }))
+vi.mock("@/lib/community/fanout", () => ({ fanOutPresenceUpdate: vi.fn() }))
+import { projectSubscription } from "./reconcile"
+
+const catalog = [
+ { priceId: "price_studio", planId: "studio", displayName: "Studio", botLimit: 10, machineLimit: 5, sortOrder: 1, portalConfigurationId: "bpc_studio" },
+ { priceId: "price_house", planId: "house", displayName: "House", botLimit: 40, machineLimit: 10, sortOrder: 2, portalConfigurationId: "bpc_house" },
+]
+const free = { id: "free", displayName: "Free" }
+function invoice(price: string, status = "paid", reason = "subscription_create") {
+ return { id: "in_1", status, billing_reason: reason,
+ lines: { data: [{ parent: { subscription_item_details: { subscription: "sub_1" } }, amount: 2000, pricing: { price_details: { price } } }] },
+ } as unknown as Stripe.Invoice
+}
+function subscription(price = "price_studio", status = "active", latest: Stripe.Invoice | null = invoice(price)) {
+ return { id: "sub_1", status, cancel_at_period_end: false, pending_update: null,
+ latest_invoice: latest, schedule: null,
+ items: { data: [{ id: "si_1", quantity: 1, price: { id: price, unit_amount: price === "price_house" ? 4000 : 2000, currency: "usd", recurring: { interval: "month", interval_count: 1 } }, current_period_end: 1791604427 }] },
+ } as unknown as Stripe.Subscription
+}
+
+describe("payment-backed subscription projection", () => {
+ it("does not grant an active initial subscription without a paid invoice", () => {
+ expect(projectSubscription(subscription("price_house", "active", invoice("price_house", "open")), null, catalog, free).plan).toEqual(free)
+ })
+ it("grants the paid plan and carries its confirmed period", () => {
+ expect(projectSubscription(subscription(), invoice("price_studio"), catalog, free)).toMatchObject({
+ plan: { id: "studio" }, subscription: { plan: { id: "studio" }, currentPeriodEnd: new Date(1791604427 * 1000).toISOString() },
+ })
+ })
+ it("retains the paid tier for an unpaid upgrade even if Stripe's current item changed", () => {
+ const sub = subscription("price_house", "active", invoice("price_house", "open", "subscription_update"))
+ expect(projectSubscription(sub, invoice("price_studio"), catalog, free).plan.id).toBe("studio")
+ })
+ it("does not interpret a requested 3DS pending item as paid", () => {
+ const sub = subscription("price_studio", "active", invoice("price_house", "open", "subscription_update"))
+ sub.pending_update = { subscription_items: [{ price: "price_house" }], expires_at: 1791000000 } as Stripe.Subscription.PendingUpdate
+ expect(projectSubscription(sub, invoice("price_studio"), catalog, free).plan.id).toBe("studio")
+ })
+ it("applies a paid proration and disregards its negative old-tier credit line", () => {
+ const paid = invoice("price_house", "paid", "subscription_update")
+ paid.lines.data.unshift({ parent: { subscription_item_details: { subscription: "sub_1" } }, amount: -2000, pricing: { price_details: { price: "price_studio" } } } as Stripe.InvoiceLineItem)
+ expect(projectSubscription(subscription("price_house", "active", paid), paid, catalog, free).plan.id).toBe("house")
+ })
+ it("keeps a paid tier during renewal retries", () => {
+ const sub = subscription("price_house", "past_due", invoice("price_house", "open", "subscription_cycle"))
+ expect(projectSubscription(sub, invoice("price_house"), catalog, free).plan.id).toBe("house")
+ })
+ it("does not grant initial access merely because a cycle invoice exists", () => {
+ const sub = subscription("price_house", "past_due", invoice("price_house", "open", "subscription_cycle"))
+ expect(projectSubscription(sub, null, catalog, free).plan).toEqual(free)
+ })
+ it("projects a scheduled downgrade without changing current entitlement", () => {
+ const sub = subscription("price_house")
+ sub.schedule = { status: "active", current_phase: { start_date: 1, end_date: 1791604427 }, phases: [
+ { start_date: 1, end_date: 1791604427, items: [{ price: "price_house" }] },
+ { start_date: 1791604427, items: [{ price: "price_studio" }] },
+ ] } as Stripe.SubscriptionSchedule
+ expect(projectSubscription(sub, invoice("price_house"), catalog, free)).toMatchObject({
+ plan: { id: "house" }, subscription: { scheduledChange: { plan: { id: "studio" }, effectiveAt: new Date(1791604427 * 1000).toISOString() } },
+ })
+ })
+ it("uses the new cycle tier when a scheduled downgrade reaches renewal retries", () => {
+ const sub = subscription("price_studio", "past_due", invoice("price_studio", "open", "subscription_cycle"))
+ expect(projectSubscription(sub, invoice("price_house"), catalog, free, { id: "price_house", unit_amount: 4000, currency: "usd", recurring: { interval: "month", interval_count: 1 } } as Stripe.Price).plan.id).toBe("studio")
+ })
+ it("does not grant a higher tier from an unpaid cycle invoice", () => {
+ const sub = subscription("price_house", "past_due", invoice("price_house", "open", "subscription_cycle"))
+ expect(projectSubscription(sub, invoice("price_studio"), catalog, free, { id: "price_studio", unit_amount: 2000, currency: "usd", recurring: { interval: "month", interval_count: 1 } } as Stripe.Price).plan.id).toBe("studio")
+ })
+ it.each(["canceled", "unpaid", "incomplete_expired"])("returns terminal %s to Free", (status) => {
+ expect(projectSubscription(subscription("price_house", status), invoice("price_house"), catalog, free).plan).toEqual(free)
+ })
+ it("keeps period-end cancellation on the paid tier until termination", () => {
+ const sub = subscription("price_house")
+ sub.cancel_at_period_end = true
+ expect(projectSubscription(sub, invoice("price_house"), catalog, free)).toMatchObject({ plan: { id: "house" }, subscription: { cancelAt: new Date(1791604427 * 1000).toISOString() } })
+ })
+ it("projects explicit period-end cancel_at even when Stripe clears cancel_at_period_end", () => {
+ const sub = subscription("price_house")
+ sub.cancel_at = 1791604427
+ expect(projectSubscription(sub, invoice("price_house"), catalog, free)).toMatchObject({
+ plan: { id: "house" }, subscription: { cancelAt: new Date(1791604427 * 1000).toISOString(), currentPeriodEnd: new Date(sub.cancel_at * 1000).toISOString() },
+ })
+ })
+ it("rejects an unmapped live price rather than silently granting or revoking", () => {
+ expect(() => projectSubscription(subscription("unknown"), invoice("unknown"), catalog, free)).toThrow("BILLING_PRICE_UNAVAILABLE")
+ })
+ it("never accepts another subscription's paid invoice lines", () => {
+ const paid = invoice("price_house")
+ paid.lines.data[0].parent!.subscription_item_details!.subscription = "sub_other"
+ expect(projectSubscription(subscription("price_house"), paid, catalog, free).plan).toEqual(free)
+ })
+})
diff --git a/src/web/src/lib/billing/reconcile.ts b/src/web/src/lib/billing/reconcile.ts
new file mode 100644
index 000000000..c1a44c01b
--- /dev/null
+++ b/src/web/src/lib/billing/reconcile.ts
@@ -0,0 +1,206 @@
+import { queries, type Database, type BillingSubscription, type ResolvedProductPlan } from "@alook/shared"
+import type Stripe from "stripe"
+import { assertStripeMode, BillingError, stripeId } from "./client"
+import { getCatalog } from "./catalog"
+import { pushBotEventToMachine } from "@/lib/community/bot-push"
+import { fanOutPresenceUpdate } from "@/lib/community/fanout"
+import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
+import { broadcastToUser } from "@/lib/broadcast"
+
+type Catalog = Awaited<ReturnType<typeof getCatalog>>
+type BillingRow = NonNullable<Awaited<ReturnType<typeof queries.billing.getBilling>>>
+
+const terminal = new Set(["canceled", "unpaid", "incomplete_expired"])
+
+export async function currentSubscription(stripe: Stripe, env: Env, row: BillingRow) {
+ if (!row.customerId) return null
+ const customer = await stripe.customers.retrieve(row.customerId)
+ if (customer.deleted) {
+ if (!row.subscriptionId) return null
+ const canceled = await stripe.subscriptions.retrieve(row.subscriptionId, { expand: ["latest_invoice", "schedule"] })
+ assertStripeMode(env, canceled)
+ if (stripeId(canceled.customer) !== row.customerId || canceled.metadata.alook_user_id !== row.userId
+ || !terminal.has(canceled.status)) throw new BillingError("BILLING_CUSTOMER_UNAVAILABLE", 503)
+ return canceled
+ }
+ assertStripeMode(env, customer)
+ if (customer.metadata.alook_user_id !== row.userId) throw new BillingError("BILLING_CUSTOMER_MISMATCH", 503)
+ const candidates: Stripe.Subscription[] = []
+ for await (const subscription of stripe.subscriptions.list({ customer: row.customerId, status: "all", limit: 100 })) {
+ if (subscription.metadata.alook_user_id !== row.userId || ["canceled", "incomplete_expired"].includes(subscription.status)) continue
+ assertStripeMode(env, subscription)
+ candidates.push(subscription)
+ if (candidates.length > 1) throw new BillingError("BILLING_MULTIPLE_SUBSCRIPTIONS", 503)
+ }
+ const id = candidates[0]?.id ?? row.subscriptionId
+ if (!id) return null
+ const subscription = await stripe.subscriptions.retrieve(id, { expand: ["latest_invoice", "schedule"] })
+ assertStripeMode(env, subscription)
+ if (stripeId(subscription.customer) !== row.customerId || subscription.metadata.alook_user_id !== row.userId) {
+ throw new BillingError("BILLING_SUBSCRIPTION_MISMATCH", 503)
+ }
+ return subscription
+}
+
+function paidLineFor(subscription: Stripe.Subscription, paidInvoice: Stripe.Invoice | null, catalog: Catalog) {
+ const invoiceLines = paidInvoice?.status === "paid" ? paidInvoice.lines.data.filter((line) =>
+ stripeId(line.parent?.subscription_item_details?.subscription ?? line.subscription) === subscription.id && line.amount >= 0,
+ ) : []
+ return invoiceLines.find((line) => stripeId(line.pricing?.price_details?.price) === subscription.items.data[0]?.price.id)
+ ?? invoiceLines.find((line) => catalog.some((entry) => entry.priceId === stripeId(line.pricing?.price_details?.price)))
+}
+
+export function projectSubscription(
+ subscription: Stripe.Subscription | null,
+ paidInvoice: Stripe.Invoice | null,
+ catalog: Catalog,
+ free: ResolvedProductPlan,
+ previousPaidPrice: Stripe.Price | null = null,
+): { plan: ResolvedProductPlan; subscription: BillingSubscription | null } {
+ if (!subscription || ["canceled", "incomplete_expired"].includes(subscription.status)) return { plan: free, subscription: null }
+ const item = subscription.items.data[0]
+ if (!item || subscription.items.data.length !== 1 || item.quantity !== 1) {
+ throw new BillingError("BILLING_SUBSCRIPTION_UNSUPPORTED", 503)
+ }
+ const current = catalog.find((entry) => entry.priceId === item.price.id)
+ if (!current) throw new BillingError("BILLING_PRICE_UNAVAILABLE", 503)
+ const asPlan = (entry: Catalog[number]) => ({ id: entry.planId, displayName: entry.displayName })
+ const latest = typeof subscription.latest_invoice === "object" ? subscription.latest_invoice : null
+ const paidLine = paidLineFor(subscription, paidInvoice, catalog)
+ const paid = catalog.find((entry) => entry.priceId === stripeId(paidLine?.pricing?.price_details?.price))
+ let plan = free
+ if (!terminal.has(subscription.status) && ["active", "past_due"].includes(subscription.status) && paid) {
+ plan = asPlan(paid)
+ const cycleDowngrade = latest?.billing_reason === "subscription_cycle" && !subscription.pending_update
+ && previousPaidPrice?.id === paid.priceId && previousPaidPrice.currency === item.price.currency
+ && previousPaidPrice.recurring?.interval === item.price.recurring?.interval
+ && previousPaidPrice.recurring?.interval_count === item.price.recurring?.interval_count
+ && previousPaidPrice.unit_amount !== null && item.price.unit_amount !== null
+ && item.price.unit_amount < previousPaidPrice.unit_amount
+ if (paid.priceId === current.priceId || cycleDowngrade) {
+ plan = asPlan(current)
+ }
+ }
+ const schedule = typeof subscription.schedule === "object" ? subscription.schedule : null
+ const next = schedule?.status === "active" && schedule.current_phase
+ ? schedule.phases.find((phase) => phase.start_date >= schedule.current_phase!.end_date)
+ : undefined
+ const nextMapping = next?.items.length === 1 ? catalog.find((entry) => entry.priceId === stripeId(next.items[0].price)) : undefined
+ return {
+ plan,
+ subscription: {
+ plan: asPlan(current),
+ status: subscription.status,
+ currentPeriodEnd: item.current_period_end ? new Date(item.current_period_end * 1000).toISOString() : null,
+ cancelAt: subscription.cancel_at != null ? new Date(subscription.cancel_at * 1000).toISOString()
+ : subscription.cancel_at_period_end && item.current_period_end ? new Date(item.current_period_end * 1000).toISOString() : null,
+ scheduledChange: next && nextMapping && nextMapping.planId !== current.planId && (!subscription.cancel_at || subscription.cancel_at > next.start_date)
+ ? { plan: asPlan(nextMapping), effectiveAt: new Date(next.start_date * 1000).toISOString() }
+ : null,
+ },
+ }
+}
+
+async function paidInvoiceFor(stripe: Stripe, subscription: Stripe.Subscription) {
+ const latest = typeof subscription.latest_invoice === "object" ? subscription.latest_invoice : null
+ if (latest?.status === "paid") return latest
+ const invoices = await stripe.invoices.list({ subscription: subscription.id, status: "paid", limit: 1 })
+ return invoices.data[0] ?? null
+}
+
+async function acknowledgedFounderSession(stripe: Stripe, env: Env, row: BillingRow, subscription: Stripe.Subscription) {
+ const attempt = row.checkoutAttempt!
+ let session: Stripe.Checkout.Session | null = null
+ if (attempt.sessionId) {
+ session = await stripe.checkout.sessions.retrieve(attempt.sessionId)
+ } else {
+ for await (const candidate of stripe.checkout.sessions.list({ customer: row.customerId!, limit: 100 })) {
+ if (candidate.metadata?.alook_attempt_id !== attempt.id) continue
+ if (session) throw new BillingError("BILLING_CHECKOUT_MISMATCH", 503)
+ session = candidate
+ }
+ }
+ if (!session) return false
+ assertStripeMode(env, session)
+ return session.status === "complete" && session.payment_status === "paid" && session.mode === "subscription"
+ && stripeId(session.customer) === row.customerId && stripeId(session.subscription) === subscription.id
+ && session.client_reference_id === row.userId && session.metadata?.alook_user_id === row.userId
+ && session.metadata?.alook_attempt_id === attempt.id
+}
+
+export async function notifyDeactivated(env: Env, db: Database, ownerId: string, ids: string[]) {
+ for (const id of ids) {
+ try {
+ const bot = await queries.communityBot.getBotOwnedBy(db, id, ownerId)
+ if (!bot || bot.isActive) continue
+ if (bot.machineId) await pushBotEventToMachine(env, bot.machineId, { type: "bot:removed", botId: id })
+ const current = await queries.communityBot.getBotOwnedBy(db, id, ownerId)
+ if (current && !current.isActive) await fanOutPresenceUpdate(id, false, ownerId)
+ } catch {
+ console.warn("billing_post_commit_notification_failed", { botId: id })
+ }
+ }
+}
+
+export async function notifyDisconnectedMachines(env: Env, db: Database, machines: Array<{ machineId: string; userId: string; doName: string | null }>) {
+ await forceCloseCommunityMachinesByDoNames(env, [...new Set(machines.flatMap((machine) => machine.doName ? [machine.doName] : []))]);
+ const unique = new Map(machines.map((machine) => [machine.machineId, machine]));
+ for (const { machineId, userId } of unique.values()) {
+ try {
+ const machine = await queries.communityMachine.getMachineByIdForUser(db, userId, machineId);
+ if (!machine || machine.status !== "offline") continue;
+ await broadcastToUser(userId, { type: "community:machine.status", machineId, status: "offline", lastSeenAt: machine.lastSeenAt ?? new Date().toISOString() });
+ const bots = await queries.communityBot.listBotsBoundToMachine(db, machineId, userId);
+ for (const bot of bots) {
+ const current = await queries.communityMachine.getMachineByIdForUser(db, userId, machineId);
+ if (current?.status !== "offline") break;
+ await fanOutPresenceUpdate(bot.id, false, userId);
+ }
+ } catch {
+ console.warn("billing_post_commit_machine_notification_failed", { machineId });
+ }
+ }
+}
+
+export async function reconcileBilling(db: Database, stripe: Stripe, env: Env, userId: string) {
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const row = await queries.billing.getBilling(db, userId)
+ const effective = await queries.billing.getEffectivePlan(db, userId)
+ if (!row || (effective.isFounder && !row.checkoutAttempt?.founderAcknowledged)) return
+ const owner = await queries.user.getUserInternal(db, userId)
+ if (!owner || owner.deletedAt !== null || owner.isBot) return
+ const subscription = await currentSubscription(stripe, env, row)
+ if (effective.isFounder && (!subscription || !["active", "past_due"].includes(subscription.status)
+ || subscription.pending_update || subscription.metadata.alook_attempt_id !== row.checkoutAttempt!.id
+ || subscription.items.data[0]?.price.id !== row.checkoutAttempt!.priceId)) return
+ const [catalog, free, paidInvoice] = await Promise.all([
+ getCatalog(db), queries.billing.getDefaultPlan(db),
+ subscription ? paidInvoiceFor(stripe, subscription) : Promise.resolve(null),
+ ])
+ const previousPriceId = subscription ? stripeId(paidLineFor(subscription, paidInvoice, catalog)?.pricing?.price_details?.price) : null
+ const latest = typeof subscription?.latest_invoice === "object" ? subscription.latest_invoice : null
+ const previousPaidPrice = previousPriceId && previousPriceId !== subscription?.items.data[0]?.price.id && latest?.billing_reason === "subscription_cycle"
+ ? await stripe.prices.retrieve(previousPriceId) : null
+ if (previousPaidPrice) assertStripeMode(env, previousPaidPrice)
+ const projection = projectSubscription(subscription, paidInvoice, catalog, free, previousPaidPrice)
+ if (effective.isFounder && (paidInvoice?.status !== "paid"
+ || stripeId(paidLineFor(subscription!, paidInvoice, catalog)?.pricing?.price_details?.price) !== row.checkoutAttempt!.priceId
+ || projection.plan.id !== catalog.find((entry) => entry.priceId === row.checkoutAttempt!.priceId)?.planId
+ || !await acknowledgedFounderSession(stripe, env, row, subscription!))) return
+ const patch = {
+ subscriptionId: subscription?.id ?? null,
+ subscription: projection.subscription,
+ ...(subscription && row.checkoutAttempt && subscription.metadata.alook_attempt_id === row.checkoutAttempt.id
+ ? { checkoutAttempt: null } : {}),
+ }
+ const result = effective.isFounder
+ ? await queries.billing.applyBillingPlan(db, row, patch, projection.plan.id, row.checkoutAttempt!.id)
+ : await queries.billing.applyBillingPlan(db, row, patch, projection.plan.id)
+ if (result.applied) {
+ await notifyDeactivated(env, db, userId, result.deactivatedBotIds)
+ await notifyDisconnectedMachines(env, db, result.disconnectedMachines ?? [])
+ return
+ }
+ }
+ throw new BillingError("BILLING_RETRY_REQUIRED", 503)
+}
diff --git a/src/web/src/lib/billing/service.test.ts b/src/web/src/lib/billing/service.test.ts
new file mode 100644
index 000000000..3243315f4
--- /dev/null
+++ b/src/web/src/lib/billing/service.test.ts
@@ -0,0 +1,280 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { Database } from "@alook/shared"
+import type Stripe from "stripe"
+
+const mocked = vi.hoisted(() => ({
+ getEffectivePlan: vi.fn(), getUserInternal: vi.fn(), ensureBilling: vi.fn(), getBilling: vi.fn(), updateBilling: vi.fn(), listPrices: vi.fn(),
+ requireOffer: vi.fn(), getOffers: vi.fn(), currentSubscription: vi.fn(), reconcileBilling: vi.fn(),
+}))
+vi.mock("@alook/shared", () => ({ queries: { billing: mocked, user: mocked } }))
+vi.mock("./catalog", () => ({ requireOffer: mocked.requireOffer, getOffers: mocked.getOffers }))
+vi.mock("./reconcile", () => ({ currentSubscription: mocked.currentSubscription, reconcileBilling: mocked.reconcileBilling }))
+import { createCheckout, createPortal, getBillingSummary, cancelScheduledChange } from "./service"
+import { BillingError } from "./client"
+
+type Row = {
+ userId: string; customerId: string | null; subscriptionId: string | null; subscription: null; revision: number;
+ checkoutAttempt: null | { id: string; priceId: string; email: string; origin: string; startedAt: number; sessionId: string | null; founderAcknowledged?: boolean };
+}
+let row: Row
+let founder: boolean
+let sessions: Array<Record<string, unknown>>
+let customers: Map<string, { id: string; livemode: boolean }>
+let stripe: Stripe
+let sessionCreates: ReturnType<typeof vi.fn>
+let customerCreates: ReturnType<typeof vi.fn>
+const db = {} as Database
+const env = { STRIPE_SECRET_KEY: "sk_test_fake", BETTER_AUTH_URL: "http://localhost:3000", STRIPE_PORTAL_CONFIGURATION_ID: "bpc_manage" } as Env
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ founder = false
+ row = { userId: "owner", customerId: null, subscriptionId: null, subscription: null, revision: 0, checkoutAttempt: null }
+ sessions = []
+ customers = new Map()
+ mocked.getEffectivePlan.mockImplementation(async () => ({ plan: { id: founder ? "house" : "free", displayName: founder ? "House" : "Free" }, isFounder: founder }))
+ mocked.getUserInternal.mockResolvedValue({ id: "owner", email: "[email protected]", isBot: false, deletedAt: null })
+ mocked.getBilling.mockImplementation(async () => structuredClone(row))
+ mocked.ensureBilling.mockImplementation(async () => structuredClone(row))
+ mocked.updateBilling.mockImplementation(async (_db, current: Row, patch: Partial<Row>, acknowledged = false) => {
+ if ((founder && !acknowledged && !current.checkoutAttempt?.founderAcknowledged) || current.revision !== row.revision) return null
+ row = { ...row, ...patch, revision: row.revision + 1 }
+ return structuredClone(row)
+ })
+ mocked.requireOffer.mockImplementation(async (_db, _stripe, _env, priceId) => ({ priceId }))
+ mocked.getOffers.mockResolvedValue([])
+ mocked.currentSubscription.mockResolvedValue(null)
+ mocked.listPrices.mockResolvedValue([{ priceId: "house", portalConfigurationId: "bpc_house" }])
+ customerCreates = vi.fn(async (_params, options) => {
+ if (!customers.has(options.idempotencyKey)) customers.set(options.idempotencyKey, { id: `cus_${customers.size}`, livemode: false })
+ return customers.get(options.idempotencyKey)
+ })
+ sessionCreates = vi.fn(async (params) => {
+ const existing = sessions.find((session) => (session.metadata as { alook_attempt_id: string }).alook_attempt_id === params.metadata.alook_attempt_id)
+ if (existing) return existing
+ const session = { id: `cs_${sessions.length}`, status: "open", url: "https://checkout.stripe.com/test", livemode: false, ...params }
+ sessions.push(session)
+ return session
+ })
+ stripe = {
+ customers: { create: customerCreates },
+ checkout: { sessions: {
+ create: sessionCreates,
+ retrieve: vi.fn(async (id) => sessions.find((s) => s.id === id)),
+ expire: vi.fn(async (id) => { const session = sessions.find((s) => s.id === id)!; session.status = "expired"; return session }),
+ list: vi.fn(() => ({ async *[Symbol.asyncIterator]() { yield* sessions } })),
+ } },
+ billingPortal: { sessions: { create: vi.fn(async () => ({ url: "https://billing.stripe.com/test" })) } },
+ } as unknown as Stripe
+})
+const checkout = (price = "studio") => createCheckout(db, stripe, env, "owner", "[email protected]", price)
+
+describe("one unresolved Checkout per owner", () => {
+ it("converges parallel same-offer requests to one customer and session", async () => {
+ const results = await Promise.all([checkout(), checkout(), checkout()])
+ expect(results.every((result) => result.url === "https://checkout.stripe.com/test")).toBe(true)
+ expect(customers.size).toBe(1)
+ expect(sessions).toHaveLength(1)
+ expect(row.checkoutAttempt?.sessionId).toBe("cs_0")
+ })
+ it("expires the old payable session before switching to a new offer", async () => {
+ await checkout()
+ await checkout("house")
+ expect(sessions).toHaveLength(2)
+ expect(sessions[0].status).toBe("expired")
+ expect(sessions.filter((session) => session.status === "open")).toHaveLength(1)
+ })
+ it("reconciles payment that wins the expiration race without opening another session", async () => {
+ await checkout()
+ vi.mocked(stripe.checkout.sessions.expire).mockImplementationOnce(async () => { sessions[0].status = "complete"; throw new Error("already completed") })
+ await expect(checkout("house")).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_EXISTS" })
+ expect(mocked.reconcileBilling).toHaveBeenCalled()
+ expect(sessions).toHaveLength(1)
+ })
+ it("retains the attempt when expiration is not confirmed", async () => {
+ await checkout()
+ vi.mocked(stripe.checkout.sessions.expire).mockRejectedValueOnce(new Error("timeout"))
+ await expect(checkout("house")).rejects.toMatchObject({ code: "BILLING_CHECKOUT_UNRESOLVED" })
+ expect(sessions).toHaveLength(1)
+ expect(row.checkoutAttempt?.sessionId).toBe("cs_0")
+ })
+ it("resumes a session created before a lost network response", async () => {
+ const realCreate = sessionCreates.getMockImplementation()!
+ sessionCreates.mockImplementationOnce(async (...args) => { await realCreate(...args); throw new Error("network timeout") })
+ await expect(checkout()).rejects.toThrow("network timeout")
+ expect(row.checkoutAttempt?.sessionId).toBeNull()
+ await expect(checkout()).resolves.toHaveProperty("url")
+ expect(sessions).toHaveLength(1)
+ })
+ it("reuses frozen customer arguments after a customer-create timeout", async () => {
+ const realCreate = customerCreates.getMockImplementation()!
+ customerCreates.mockImplementationOnce(async (...args) => { await realCreate(...args); throw new Error("timeout") })
+ await expect(checkout()).rejects.toThrow("timeout")
+ await createCheckout(db, stripe, env, "owner", "[email protected]", "studio")
+ expect(customers.size).toBe(1)
+ expect(customerCreates.mock.calls[0]).toEqual(customerCreates.mock.calls[1])
+ })
+ it("recovers failed local session persistence without a second Stripe session", async () => {
+ const realUpdate = mocked.updateBilling.getMockImplementation()!
+ let lost = false
+ mocked.updateBilling.mockImplementation(async (...args) => {
+ if (!lost && args[2].checkoutAttempt?.sessionId) { lost = true; return null }
+ return realUpdate(...args)
+ })
+ await expect(checkout()).resolves.toHaveProperty("url")
+ expect(sessions).toHaveLength(1)
+ })
+ it("does not rotate an aged unknown Stripe outcome", async () => {
+ row.checkoutAttempt = { id: "old", priceId: "studio", email: "[email protected]", origin: "http://localhost:3000", startedAt: 1, sessionId: null }
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_CHECKOUT_UNRESOLVED" })
+ expect(customerCreates).not.toHaveBeenCalled()
+ expect(sessionCreates).not.toHaveBeenCalled()
+ expect(row.checkoutAttempt.id).toBe("old")
+ })
+ it("permits replacement only after Stripe confirms the previous session expired", async () => {
+ await checkout()
+ sessions[0].status = "expired"
+ await checkout("house")
+ expect(sessions).toHaveLength(2)
+ expect(sessions.filter((session) => session.status === "open")).toHaveLength(1)
+ })
+ it("reconciles completion instead of replacing a completed session", async () => {
+ await checkout()
+ sessions[0].status = "complete"
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_EXISTS" })
+ expect(mocked.reconcileBilling).toHaveBeenCalled()
+ expect(sessions).toHaveLength(1)
+ })
+ it("detects an upstream subscription before a delayed webhook", async () => {
+ row.customerId = "cus_existing"
+ mocked.currentSubscription.mockResolvedValue({ id: "sub_existing", status: "active" })
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_EXISTS" })
+ expect(sessionCreates).not.toHaveBeenCalled()
+ })
+ it("keeps unpaid subscriptions manageable without a second purchase", async () => {
+ row.customerId = "cus_existing"
+ mocked.currentSubscription.mockResolvedValue({ id: "sub_existing", status: "unpaid" })
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_EXISTS" })
+ })
+ it("rejects a foreign customer on a stored session", async () => {
+ await checkout()
+ sessions[0].customer = "cus_foreign"
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_CHECKOUT_MISMATCH" })
+ })
+ it("uses configured return URLs and frozen attempt parameters", async () => {
+ await checkout()
+ expect(sessionCreates.mock.calls[0][0]).toMatchObject({ success_url: "http://localhost:3000/c/me/bots?billing=checkout", cancel_url: "http://localhost:3000/c/me/bots?billing=cancel", mode: "subscription", managed_payments: { enabled: false } })
+ expect(sessionCreates.mock.calls[0][1].idempotencyKey).toBe(`alook:checkout:${row.checkoutAttempt!.id}`)
+ })
+ it("requires Founder acknowledgment before purchase and returns normal offers", async () => {
+ founder = true
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
+ await expect(createPortal(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
+ const client = vi.fn(() => stripe)
+ expect(await getBillingSummary(db, client, env, "owner")).toMatchObject({ isFounder: true, offers: [], subscription: null })
+ expect(client).toHaveBeenCalledOnce()
+ expect(customerCreates).not.toHaveBeenCalled()
+ })
+ it("freezes Founder consent and reuses the session while keeping Founder until payment", async () => {
+ founder = true
+ await expect(createCheckout(db, stripe, env, "owner", "[email protected]", "house", false)).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
+ await createCheckout(db, stripe, env, "owner", "[email protected]", "house", true)
+ expect(row.checkoutAttempt).toMatchObject({ founderAcknowledged: true, priceId: "house" })
+ await createCheckout(db, stripe, env, "owner", "[email protected]", "house", true)
+ expect(sessions).toHaveLength(1)
+ expect(founder).toBe(true)
+ expect(mocked.reconcileBilling).not.toHaveBeenCalled()
+ })
+ it("does not reuse an unacknowledged old checkout for a Founder", async () => {
+ await checkout()
+ founder = true
+ await expect(createCheckout(db, stripe, env, "owner", "[email protected]", "studio", true)).rejects.toMatchObject({ code: "BILLING_CHECKOUT_UNRESOLVED" })
+ expect(sessions).toHaveLength(1)
+ })
+ it("rejects a disabled or unknown offer before reserving an attempt", async () => {
+ mocked.requireOffer.mockRejectedValue(new BillingError("BILLING_PRICE_UNAVAILABLE", 400))
+ await expect(checkout("foreign")).rejects.toMatchObject({ code: "BILLING_PRICE_UNAVAILABLE" })
+ expect(mocked.ensureBilling).not.toHaveBeenCalled()
+ })
+ it("chooses the target config for a change and the ordinary config for management", async () => {
+ row.customerId = "cus_0"
+ mocked.currentSubscription.mockResolvedValue({ id: "sub_1", status: "active", items: { data: [{ id: "si_1", quantity: 1 }] } })
+ await createPortal(db, stripe, env, "owner", "house")
+ expect(stripe.billingPortal.sessions.create).toHaveBeenLastCalledWith(expect.objectContaining({ customer: "cus_0", configuration: "bpc_house", flow_data: expect.objectContaining({ type: "subscription_update_confirm" }) }))
+ await createPortal(db, stripe, env, "owner")
+ expect(stripe.billingPortal.sessions.create).toHaveBeenLastCalledWith(expect.objectContaining({ configuration: "bpc_manage", flow_data: undefined }))
+ })
+})
+
+
+describe("withdraw a future plan change", () => {
+ function setupSchedule() {
+ row.customerId = "cus_0"
+ const schedule = { id: "sched_1", customer: "cus_0", subscription: "sub_1", livemode: false,
+ status: "active", current_phase: { start_date: 1, end_date: 200 }, phases: [
+ { start_date: 1, end_date: 200, items: [{ price: "house" }] },
+ { start_date: 200, end_date: 201, items: [{ price: "studio" }] },
+ ],
+ }
+ const sub = { id: "sub_1", cancel_at: 300, items: { data: [{ id: "si_1", price: { id: "house" }, quantity: 1 }] }, schedule }
+ mocked.currentSubscription.mockResolvedValue(sub)
+ const release = vi.fn(async () => ({ status: "released" }))
+ const retrieve = vi.fn(async () => ({ status: "released" }))
+ Object.assign(stripe, { subscriptionSchedules: { release, retrieve } })
+ return { sub, schedule, release, retrieve }
+ }
+ it("releases only the future change, preserving cancellation and then reconciling", async () => {
+ const { release } = setupSchedule()
+ await cancelScheduledChange(db, stripe, env, "owner")
+ expect(release).toHaveBeenCalledWith("sched_1", { preserve_cancel_date: true }, { idempotencyKey: "alook:release:sched_1" })
+ expect(mocked.reconcileBilling).toHaveBeenCalledWith(db, stripe, env, "owner")
+ expect(sessionCreates).not.toHaveBeenCalled()
+ expect(stripe.billingPortal.sessions.create).not.toHaveBeenCalled()
+ })
+ it("is a no-op when a repeated request finds no schedule", async () => {
+ const { release, sub } = setupSchedule()
+ mocked.currentSubscription.mockResolvedValue({ ...sub, schedule: null })
+ await cancelScheduledChange(db, stripe, env, "owner")
+ expect(release).not.toHaveBeenCalled()
+ expect(mocked.reconcileBilling).toHaveBeenCalledOnce()
+ })
+ it("does not restore an old tier after the phase boundary has passed", async () => {
+ const { release, sub, schedule } = setupSchedule()
+ sub.items.data[0].price.id = "studio"
+ schedule.current_phase = { start_date: 200, end_date: 201 }
+ await cancelScheduledChange(db, stripe, env, "owner")
+ expect(release).not.toHaveBeenCalled()
+ expect(mocked.reconcileBilling).toHaveBeenCalledOnce()
+ })
+ it("recovers a release whose response was lost after Stripe committed", async () => {
+ const { release, retrieve } = setupSchedule()
+ release.mockRejectedValue(new Error("lost response"))
+ await expect(cancelScheduledChange(db, stripe, env, "owner")).resolves.toHaveProperty("plan")
+ expect(retrieve).toHaveBeenCalledWith("sched_1")
+ expect(mocked.reconcileBilling).toHaveBeenCalledOnce()
+ })
+ it("leaves an unresolved release retryable", async () => {
+ const { release, retrieve } = setupSchedule()
+ release.mockRejectedValue(new Error("timeout"))
+ retrieve.mockResolvedValue({ status: "active" })
+ await expect(cancelScheduledChange(db, stripe, env, "owner")).rejects.toThrow("timeout")
+ expect(mocked.reconcileBilling).not.toHaveBeenCalled()
+ })
+ it("rejects Founder and a foreign attached schedule without releasing", async () => {
+ const { release, schedule } = setupSchedule()
+ founder = true
+ await expect(cancelScheduledChange(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
+ founder = false
+ schedule.customer = "cus_foreign"
+ await expect(cancelScheduledChange(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_SUBSCRIPTION_MISMATCH" })
+ expect(release).not.toHaveBeenCalled()
+ })
+})
+
+it("bounds persistent reservation conflicts without creating Stripe resources", async () => {
+ mocked.updateBilling.mockResolvedValue(null)
+ await expect(checkout()).rejects.toMatchObject({ code: "BILLING_RETRY_REQUIRED", status: 503 })
+ expect(mocked.ensureBilling).toHaveBeenCalledTimes(5)
+ expect(customerCreates).not.toHaveBeenCalled()
+ expect(sessionCreates).not.toHaveBeenCalled()
+})
diff --git a/src/web/src/lib/billing/service.ts b/src/web/src/lib/billing/service.ts
new file mode 100644
index 000000000..6bc8bd297
--- /dev/null
+++ b/src/web/src/lib/billing/service.ts
@@ -0,0 +1,186 @@
+import { queries, type Database, type BillingSummary } from "@alook/shared"
+import type Stripe from "stripe"
+import { assertStripeMode, billingOrigin, BillingError, stripeId } from "./client"
+import { getOffers, requireOffer } from "./catalog"
+import { currentSubscription, reconcileBilling } from "./reconcile"
+
+type BillingRow = NonNullable<Awaited<ReturnType<typeof queries.billing.getBilling>>>
+
+async function requireBillingOwner(db: Database, userId: string, founderAcknowledged = false) {
+ const effective = await queries.billing.getEffectivePlan(db, userId)
+ if (effective.isFounder && !founderAcknowledged) throw new BillingError("BILLING_FOUNDER_PROTECTED", 403)
+ const owner = await queries.user.getUserInternal(db, userId)
+ if (!owner || owner.isBot || owner.deletedAt !== null) throw new BillingError("UNAUTHORIZED", 401)
+ return effective
+}
+
+export async function getBillingSummary(db: Database, stripe: () => Stripe, env: Env, userId: string): Promise<BillingSummary> {
+ const effective = await queries.billing.getEffectivePlan(db, userId)
+ if (effective.isFounder) return { plan: effective.plan, isFounder: true, offers: await getOffers(db, stripe(), env), subscription: null }
+ const [row, offers] = await Promise.all([queries.billing.getBilling(db, userId), getOffers(db, stripe(), env)])
+ return { plan: effective.plan, isFounder: false, offers, subscription: row?.subscription ?? null }
+}
+
+async function sessionForAttempt(stripe: Stripe, env: Env, row: BillingRow) {
+ const attempt = row.checkoutAttempt
+ if (!attempt || !row.customerId) return null
+ if (attempt.sessionId) {
+ const session = await stripe.checkout.sessions.retrieve(attempt.sessionId)
+ assertStripeMode(env, session)
+ if (stripeId(session.customer) !== row.customerId || session.metadata?.alook_attempt_id !== attempt.id) {
+ throw new BillingError("BILLING_CHECKOUT_MISMATCH", 503)
+ }
+ return session
+ }
+ for await (const session of stripe.checkout.sessions.list({ customer: row.customerId, limit: 100 })) {
+ if (session.metadata?.alook_attempt_id !== attempt.id) continue
+ assertStripeMode(env, session)
+ return session
+ }
+ return null
+}
+
+export async function createCheckout(db: Database, stripe: Stripe, env: Env, userId: string, email: string, priceId: string, founderAcknowledged = false) {
+ const effective = await requireBillingOwner(db, userId, founderAcknowledged)
+ await requireOffer(db, stripe, env, priceId)
+ for (let retry = 0; retry < 5; retry++) {
+ let row = await queries.billing.ensureBilling(db, userId, founderAcknowledged)
+ if (!row) throw new BillingError("BILLING_FOUNDER_PROTECTED", 403)
+ if (row.customerId && await currentSubscription(stripe, env, row).then((sub) => sub && !["canceled", "incomplete_expired"].includes(sub.status))) {
+ await reconcileBilling(db, stripe, env, userId)
+ throw new BillingError("BILLING_SUBSCRIPTION_EXISTS")
+ }
+ if (!row.checkoutAttempt) {
+ const reserved = await queries.billing.updateBilling(db, row, { checkoutAttempt: {
+ id: crypto.randomUUID(), priceId, email, origin: billingOrigin(env),
+ startedAt: Math.floor(Date.now() / 1000), sessionId: null,
+ ...(founderAcknowledged ? { founderAcknowledged: true } : {}),
+ } }, founderAcknowledged)
+ if (!reserved) continue
+ row = reserved
+ }
+ const attempt = row.checkoutAttempt!
+ if (effective.isFounder && !attempt.founderAcknowledged) {
+ throw new BillingError("BILLING_CHECKOUT_UNRESOLVED", 503)
+ }
+ let session = await sessionForAttempt(stripe, env, row)
+ if (session?.status === "complete") {
+ await reconcileBilling(db, stripe, env, userId)
+ throw new BillingError("BILLING_SUBSCRIPTION_EXISTS")
+ }
+ if (session?.status === "expired") {
+ if (!await queries.billing.updateBilling(db, row, { checkoutAttempt: null })) continue
+ continue
+ }
+ if (attempt.priceId !== priceId) {
+ if (!session || session.status !== "open") throw new BillingError("BILLING_CHECKOUT_IN_PROGRESS")
+ try {
+ session = await stripe.checkout.sessions.expire(session.id, {}, { idempotencyKey: `alook:expire:${attempt.id}` })
+ } catch {
+ session = await stripe.checkout.sessions.retrieve(session.id)
+ }
+ assertStripeMode(env, session)
+ if (session.status === "complete") {
+ await reconcileBilling(db, stripe, env, userId)
+ throw new BillingError("BILLING_SUBSCRIPTION_EXISTS")
+ }
+ if (session.status !== "expired") throw new BillingError("BILLING_CHECKOUT_UNRESOLVED", 503)
+ if (!await queries.billing.updateBilling(db, row, { checkoutAttempt: null })) continue
+ continue
+ }
+ if (!session) {
+ if (Date.now() / 1000 - attempt.startedAt >= 23 * 3600) throw new BillingError("BILLING_CHECKOUT_UNRESOLVED", 503)
+ if (!row.customerId) {
+ await requireBillingOwner(db, userId, founderAcknowledged)
+ const customer = await stripe.customers.create({
+ email: attempt.email,
+ metadata: { alook_user_id: userId, alook_attempt_id: attempt.id },
+ }, { idempotencyKey: `alook:customer:${attempt.id}` })
+ assertStripeMode(env, customer)
+ const saved = await queries.billing.updateBilling(db, row, { customerId: customer.id })
+ if (!saved) continue
+ row = saved
+ }
+ await requireBillingOwner(db, userId, founderAcknowledged)
+ session = await stripe.checkout.sessions.create({
+ mode: "subscription",
+ managed_payments: { enabled: false },
+ customer: row.customerId!,
+ client_reference_id: userId,
+ line_items: [{ price: attempt.priceId, quantity: 1 }],
+ metadata: { alook_user_id: userId, alook_attempt_id: attempt.id },
+ subscription_data: { metadata: { alook_user_id: userId, alook_attempt_id: attempt.id } },
+ expires_at: attempt.startedAt + 24 * 3600 - 60,
+ success_url: `${attempt.origin}/c/me/bots?billing=checkout`,
+ cancel_url: `${attempt.origin}/c/me/bots?billing=cancel`,
+ }, { idempotencyKey: `alook:checkout:${attempt.id}` })
+ assertStripeMode(env, session)
+ }
+ if (!session.url || session.status !== "open") throw new BillingError("BILLING_CHECKOUT_UNRESOLVED", 503)
+ if (row.checkoutAttempt?.sessionId !== session.id) {
+ if (!await queries.billing.updateBilling(db, row, { checkoutAttempt: { ...attempt, sessionId: session.id } })) continue
+ }
+ await requireBillingOwner(db, userId, founderAcknowledged)
+ return { url: session.url }
+ }
+ throw new BillingError("BILLING_RETRY_REQUIRED", 503)
+}
+
+export async function createPortal(db: Database, stripe: Stripe, env: Env, userId: string, priceId?: string) {
+ await requireBillingOwner(db, userId)
+ const row = await queries.billing.getBilling(db, userId)
+ if (!row?.customerId) throw new BillingError("BILLING_SUBSCRIPTION_REQUIRED")
+ const subscription = await currentSubscription(stripe, env, row)
+ if (!subscription || ["canceled", "incomplete_expired"].includes(subscription.status)) throw new BillingError("BILLING_SUBSCRIPTION_REQUIRED")
+ let configuration = env.STRIPE_PORTAL_CONFIGURATION_ID
+ let flowData: Stripe.BillingPortal.SessionCreateParams.FlowData | undefined
+ if (priceId) {
+ await requireOffer(db, stripe, env, priceId)
+ const mapping = (await queries.billing.listPrices(db)).find((item) => item.priceId === priceId)
+ configuration = mapping?.portalConfigurationId ?? undefined
+ const item = subscription.items.data[0]
+ if (!item || subscription.items.data.length !== 1 || item.quantity !== 1) throw new BillingError("BILLING_SUBSCRIPTION_UNSUPPORTED")
+ flowData = {
+ type: "subscription_update_confirm",
+ subscription_update_confirm: { subscription: subscription.id, items: [{ id: item.id, price: priceId, quantity: 1 }] },
+ after_completion: { type: "redirect", redirect: { return_url: `${billingOrigin(env)}/c/me/bots?billing=portal` } },
+ }
+ }
+ if (!configuration) throw new BillingError("BILLING_UNAVAILABLE", 503)
+ await requireBillingOwner(db, userId)
+ const session = await stripe.billingPortal.sessions.create({
+ customer: row.customerId, configuration, flow_data: flowData,
+ return_url: `${billingOrigin(env)}/c/me/bots?billing=portal`,
+ })
+ return { url: session.url }
+}
+
+export async function cancelScheduledChange(db: Database, stripe: Stripe, env: Env, userId: string) {
+ await requireBillingOwner(db, userId)
+ const row = await queries.billing.getBilling(db, userId)
+ if (row?.customerId) {
+ const subscription = await currentSubscription(stripe, env, row)
+ const schedule = typeof subscription?.schedule === "object" ? subscription.schedule : null
+ const item = subscription?.items.data[0]
+ const next = schedule?.status === "active" && schedule.current_phase
+ ? schedule.phases.find((phase) => phase.start_date >= schedule.current_phase!.end_date)
+ : undefined
+ if (subscription && schedule && item && next?.items.length === 1 && stripeId(next.items[0].price) !== item.price.id) {
+ if (stripeId(schedule.customer) !== row.customerId || stripeId(schedule.subscription) !== subscription.id) {
+ throw new BillingError("BILLING_SUBSCRIPTION_MISMATCH", 503)
+ }
+ assertStripeMode(env, schedule)
+ await requireBillingOwner(db, userId)
+ try {
+ await stripe.subscriptionSchedules.release(schedule.id, { preserve_cancel_date: true }, {
+ idempotencyKey: `alook:release:${schedule.id}`,
+ })
+ } catch (error) {
+ const fresh = await stripe.subscriptionSchedules.retrieve(schedule.id)
+ if (!["released", "completed", "canceled"].includes(fresh.status)) throw error
+ }
+ }
+ await reconcileBilling(db, stripe, env, userId)
+ }
+ return getBillingSummary(db, () => stripe, env, userId)
+}
diff --git a/src/web/src/lib/billing/webhook.test.ts b/src/web/src/lib/billing/webhook.test.ts
new file mode 100644
index 000000000..8e5d4a1a8
--- /dev/null
+++ b/src/web/src/lib/billing/webhook.test.ts
@@ -0,0 +1,79 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import Stripe from "stripe"
+import type { Database } from "@alook/shared"
+const mocked = vi.hoisted(() => ({ getBillingByCustomer: vi.fn(), getBilling: vi.fn(), getEffectivePlan: vi.fn(), updateBilling: vi.fn(), reconcileBilling: vi.fn() }))
+vi.mock("@alook/shared", () => ({ queries: { billing: mocked } }))
+vi.mock("./reconcile", () => ({ reconcileBilling: mocked.reconcileBilling }))
+import { handleBillingWebhook } from "./webhook"
+
+const db = {} as Database
+const stripe = new Stripe("sk_test_fixture")
+const env = { STRIPE_SECRET_KEY: "sk_test_fixture", STRIPE_WEBHOOK_SECRET: "whsec_fixture" } as Env
+const body = (object: Record<string, unknown> = { customer: "cus_owner" }, livemode = false) => JSON.stringify({
+ id: "evt_fixture", object: "event", type: "invoice.paid", livemode, data: { object },
+}, null, 2)
+const signature = (raw: string) => stripe.webhooks.generateTestHeaderString({ payload: raw, secret: env.STRIPE_WEBHOOK_SECRET! })
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ mocked.getBillingByCustomer.mockResolvedValue({ userId: "owner", customerId: "cus_owner", revision: 2 })
+})
+
+describe("Stripe signed ingress", () => {
+ it("verifies the untouched formatted body and reconciles its server-owned customer", async () => {
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.reconcileBilling).toHaveBeenCalledWith(db, stripe, env, "owner")
+ })
+ it.each([null, "invalid"])("rejects missing or invalid signatures before database access", async (header) => {
+ await expect(handleBillingWebhook(db, stripe, env, body(), header)).rejects.toMatchObject({ code: "BILLING_SIGNATURE_INVALID", status: 400 })
+ expect(mocked.getBillingByCustomer).not.toHaveBeenCalled()
+ })
+ it("rejects a parsed-and-reserialized body against the original signature", async () => {
+ const raw = body()
+ await expect(handleBillingWebhook(db, stripe, env, JSON.stringify(JSON.parse(raw)), signature(raw))).rejects.toMatchObject({ code: "BILLING_SIGNATURE_INVALID" })
+ })
+ it("rejects the wrong Stripe environment before touching entitlements", async () => {
+ const raw = body(undefined, true)
+ await expect(handleBillingWebhook(db, stripe, env, raw, signature(raw))).rejects.toMatchObject({ code: "BILLING_ENVIRONMENT_MISMATCH" })
+ expect(mocked.reconcileBilling).not.toHaveBeenCalled()
+ })
+ it("lets a durable reconciliation failure propagate for webhook retry", async () => {
+ mocked.reconcileBilling.mockRejectedValue(new Error("D1 unavailable"))
+ const raw = body()
+ await expect(handleBillingWebhook(db, stripe, env, raw, signature(raw))).rejects.toThrow("D1 unavailable")
+ })
+ it("reconciles duplicates again instead of treating event receipt as completed work", async () => {
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.reconcileBilling).toHaveBeenCalledTimes(2)
+ })
+ it("recovers a customer created before local persistence only for the matching reserved attempt", async () => {
+ mocked.getBillingByCustomer.mockResolvedValue(null)
+ vi.spyOn(stripe.customers, "retrieve").mockResolvedValue({ id: "cus_owner", livemode: false, metadata: { alook_user_id: "owner", alook_attempt_id: "attempt" } } as Stripe.Response<Stripe.Customer>)
+ mocked.getBilling.mockResolvedValue({ userId: "owner", customerId: null, checkoutAttempt: { id: "attempt" }, revision: 1 })
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: false })
+ mocked.updateBilling.mockResolvedValue({ userId: "owner", customerId: "cus_owner", revision: 2 })
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.updateBilling).toHaveBeenCalledWith(db, expect.objectContaining({ revision: 1 }), { customerId: "cus_owner" })
+ expect(mocked.reconcileBilling).toHaveBeenCalledWith(db, stripe, env, "owner")
+ })
+ it("does not adopt a foreign or obsolete attempt's customer", async () => {
+ mocked.getBillingByCustomer.mockResolvedValue(null)
+ vi.spyOn(stripe.customers, "retrieve").mockResolvedValue({ id: "cus_owner", livemode: false, metadata: { alook_user_id: "owner", alook_attempt_id: "old" } } as Stripe.Response<Stripe.Customer>)
+ mocked.getBilling.mockResolvedValue({ userId: "owner", customerId: null, checkoutAttempt: { id: "new" } })
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.updateBilling).not.toHaveBeenCalled()
+ expect(mocked.reconcileBilling).not.toHaveBeenCalled()
+ })
+})
+
+it("ignores a validly signed unrelated event without looking up billing", async () => {
+ const raw = JSON.stringify({ ...JSON.parse(body()), type: "payment_intent.succeeded" })
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.getBillingByCustomer).not.toHaveBeenCalled()
+ expect(mocked.reconcileBilling).not.toHaveBeenCalled()
+})
diff --git a/src/web/src/lib/billing/webhook.ts b/src/web/src/lib/billing/webhook.ts
new file mode 100644
index 000000000..ccbe617b2
--- /dev/null
+++ b/src/web/src/lib/billing/webhook.ts
@@ -0,0 +1,36 @@
+import { queries, type Database } from "@alook/shared"
+import Stripe from "stripe"
+import { assertStripeMode, BillingError, stripeId } from "./client"
+import { reconcileBilling } from "./reconcile"
+
+export async function handleBillingWebhook(db: Database, stripe: Stripe, env: Env, raw: string, signature: string | null) {
+ if (!env.STRIPE_WEBHOOK_SECRET) throw new BillingError("BILLING_UNAVAILABLE", 503)
+ if (!signature) throw new BillingError("BILLING_SIGNATURE_INVALID", 400)
+ let event: Stripe.Event
+ try {
+ event = await stripe.webhooks.constructEventAsync(raw, signature, env.STRIPE_WEBHOOK_SECRET, undefined, Stripe.createSubtleCryptoProvider())
+ } catch {
+ throw new BillingError("BILLING_SIGNATURE_INVALID", 400)
+ }
+ assertStripeMode(env, event)
+ if (!event.type.startsWith("customer.subscription.") && !event.type.startsWith("invoice.")
+ && !event.type.startsWith("checkout.session.") && !event.type.startsWith("subscription_schedule.")) return
+ const object = event.data.object as unknown as { customer?: string | { id: string } | null }
+ const customerId = stripeId(object.customer)
+ if (!customerId) return
+ let row = await queries.billing.getBillingByCustomer(db, customerId)
+ if (!row) {
+ const customer = await stripe.customers.retrieve(customerId)
+ if (customer.deleted) return
+ assertStripeMode(env, customer)
+ const userId = customer.metadata.alook_user_id
+ if (!userId) return
+ const candidate = await queries.billing.getBilling(db, userId)
+ if (!candidate || candidate.customerId || !candidate.checkoutAttempt
+ || candidate.checkoutAttempt.id !== customer.metadata.alook_attempt_id) return
+ if ((await queries.billing.getEffectivePlan(db, userId)).isFounder && !candidate.checkoutAttempt.founderAcknowledged) return
+ row = await queries.billing.updateBilling(db, candidate, { customerId })
+ if (!row) throw new BillingError("BILLING_RETRY_REQUIRED", 503)
+ }
+ await reconcileBilling(db, stripe, env, row.userId)
+}
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index f12ae9c4b..5e0611a6e 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -83,6 +83,7 @@ import {
fanOutToChannel,
fanOutToDM,
fanOutStatusUpdate,
+ fanOutPresenceUpdate,
fanOutIdentityUpdate,
fanOutProfileUpdate,
broadcastToUserSafe,
@@ -290,6 +291,41 @@ describe("fanOutStatusUpdate", () => {
})
})
+describe("fanOutPresenceUpdate", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
+ mockBroadcastToUsers.mockResolvedValue(undefined)
+ mockGetCoMemberUserIds.mockResolvedValue(["co-member", "shared"])
+ mockGetFriendUserIds.mockResolvedValue(["friend", "shared"])
+ mockListDmPeerUserIds.mockResolvedValue(["dm-peer"])
+ })
+
+ it("broadcasts presence to the canonical profile audience including the bot owner", async () => {
+ await fanOutPresenceUpdate("bot_1", false, "owner_1")
+
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["bot_1", "co-member", "shared", "friend", "dm-peer", "owner_1"],
+ {
+ type: WS_EVENTS.PRESENCE_UPDATE,
+ userId: "bot_1",
+ online: false,
+ },
+ )
+ })
+
+ it("absorbs an audience failure and logs the presence context", async () => {
+ mockGetCoMemberUserIds.mockRejectedValue(new Error("db down"))
+
+ await expect(fanOutPresenceUpdate("bot_1", true)).resolves.toBeUndefined()
+
+ expect(mockWarn).toHaveBeenCalledWith(
+ "fanout_presence_update_failed",
+ expect.objectContaining({ userId: "bot_1", online: true, err: expect.stringContaining("db down") }),
+ )
+ })
+})
+
describe("fanOutIdentityUpdate", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index 4b5dcb152..670f605b4 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -213,6 +213,25 @@ export async function fanOutStatusUpdate(
}
}
+export async function fanOutPresenceUpdate(
+ userId: string,
+ online: boolean,
+ ownerUserId?: string | null,
+): Promise<void> {
+ try {
+ const { env } = getCloudflareContext()
+ const db = getDb((env as Env).DB)
+ const audience = await getProfileAudience(db, userId, ownerUserId)
+ await broadcastToRecipients(audience, {
+ type: WS_EVENTS.PRESENCE_UPDATE,
+ userId,
+ online,
+ })
+ } catch (err) {
+ log.warn("fanout_presence_update_failed", { userId, online, err: String(err) })
+ }
+}
+
export async function fanOutProfileUpdate(profile: {
id: string
name: string
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 7bc612bf4..491c70a20 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -107,6 +107,16 @@ export const tid = {
botAvatarPickerTrigger: "community-bot-avatar-picker-trigger",
botReasoningEffort: "community-bot-reasoning-effort",
botCardModel: "bot-card-model",
+ myBotsPlanSummary: "my-bots-plan-summary",
+ myBotsBilling: "my-bots-billing",
+ billingSheet: "billing-sheet",
+ billingRefresh: "billing-refresh",
+ billingPortal: "billing-portal",
+ billingCancelChange: "billing-cancel-change",
+ billingCheckout: "billing-checkout",
+ billingChangePlan: "billing-change-plan",
+ createBot: "create-bot",
+ botActive: (botId: string) => `bot-active-${botId}`,
botUsage: (botId: string) => `community-bot-usage-${botId}`,
botUsageTrigger: (botId: string) => `community-bot-usage-trigger-${botId}`,
botUsageDialog: (botId: string) => `community-bot-usage-dialog-${botId}`,
diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.ts
index 5a2f5231e..8ebaf05ee 100644
--- a/src/web/src/lib/middleware/community-actor.test.ts
+++ b/src/web/src/lib/middleware/community-actor.test.ts
@@ -55,12 +55,12 @@ describe("withCommunityActor", () => {
it("resolves a crk_ bearer to a bot actor (kind:bot, userId=botUserId)", async () => {
mockResolveBotActor.mockResolvedValue({
kind: "bot",
- actor: { botUserId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },
+ actor: { botUserId: "bot_1", ownerUserId: "owner_1", machineId: "m_1", isActive: true },
})
const res = await wrapped(bearer("Bearer crk_abc"))
expect(res.status).toBe(200)
const body = (await res.json()) as { actor: CommunityActor }
- expect(body.actor).toEqual({ kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" })
+ expect(body.actor).toEqual({ kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1", isActive: true })
})
it("a crk_ bearer that fails to resolve returns the error response and NEVER falls through to human", async () => {
@@ -102,7 +102,7 @@ describe("withCommunityActor", () => {
describe("rejectBot / requireBot guards", () => {
const human: CommunityActor = { kind: "human", userId: "h", email: "e" }
- const bot: CommunityActor = { kind: "bot", userId: "b", ownerUserId: "o", machineId: "m" }
+ const bot: CommunityActor = { kind: "bot", userId: "b", ownerUserId: "o", machineId: "m", isActive: true }
it("rejectBot: 403 for a bot, null for a human", () => {
expect(rejectBot(bot)?.status).toBe(403)
@@ -116,6 +116,6 @@ describe("rejectBot / requireBot guards", () => {
const botGate = requireBot(bot)
expect(botGate.ok).toBe(true)
- if (botGate.ok) expect(botGate.bot).toEqual({ kind: "bot", userId: "b", ownerUserId: "o", machineId: "m" })
+ if (botGate.ok) expect(botGate.bot).toEqual({ kind: "bot", userId: "b", ownerUserId: "o", machineId: "m", isActive: true })
})
})
diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.ts
index eb09ce45d..e25461b62 100644
--- a/src/web/src/lib/middleware/community-actor.ts
+++ b/src/web/src/lib/middleware/community-actor.ts
@@ -44,6 +44,8 @@ export type CommunityActor =
/** The bot's OWNER (the human who minted the runner key). */
ownerUserId: string
machineId: string
+ /** Server-internal binding state resolved by runner auth. */
+ isActive: boolean
}
interface CommunityActorContext {
@@ -74,7 +76,10 @@ export type CommunityActorHandler = (
* A bot request never pays the session-validation cost; a human never hits the
* runner-key lookups.
*/
-export function withCommunityActor(handler: CommunityActorHandler) {
+export function withCommunityActor(
+ handler: CommunityActorHandler,
+ options: { allowInactiveBot?: boolean } = {},
+) {
return async (
req: NextRequest,
context?: { params?: Promise<Record<string, string>> | Record<string, string> },
@@ -95,7 +100,9 @@ export function withCommunityActor(handler: CommunityActorHandler) {
const cloudflareEnv = env as Env
const db = getDb(cloudflareEnv.DB)
- const resolved = await resolveBotActor(db, authHeader)
+ const resolved = await resolveBotActor(db, authHeader, {
+ allowInactive: options.allowInactiveBot,
+ })
if (resolved.kind === "error") return resolved.response
// A crk_ bearer that resolves to `not_bot` is unreachable (the guard above
// guarantees the crk_ prefix), but treat it as an auth failure rather than
@@ -111,6 +118,7 @@ export function withCommunityActor(handler: CommunityActorHandler) {
userId: resolved.actor.botUserId,
ownerUserId: resolved.actor.ownerUserId,
machineId: resolved.actor.machineId,
+ isActive: resolved.actor.isActive,
},
params: resolvedParams,
})
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.test.ts b/src/web/src/lib/middleware/community-agent-runner-auth.test.ts
new file mode 100644
index 000000000..a1d1ed599
--- /dev/null
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mockFindRunnerKey = vi.fn()
+const mockGetUserInternal = vi.fn()
+const mockGetBotBinding = vi.fn()
+const mockLogWarn = vi.fn()
+
+vi.mock("@alook/shared", () => ({
+ createLogger: () => ({ warn: (...args: unknown[]) => mockLogWarn(...args) }),
+ withD1Retry: async (fn: () => Promise<unknown>) => fn(),
+ queries: {
+ communityMachine: {
+ findActiveAgentRunnerKeyByBearer: (...args: unknown[]) => mockFindRunnerKey(...args),
+ },
+ user: {
+ getUserInternal: (...args: unknown[]) => mockGetUserInternal(...args),
+ },
+ communityBot: {
+ getBotBinding: (...args: unknown[]) => mockGetBotBinding(...args),
+ },
+ },
+}))
+
+import { resolveBotActor } from "./community-agent-runner-auth"
+
+describe("resolveBotActor active entitlement gate", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockFindRunnerKey.mockResolvedValue({
+ userId: "owner_1",
+ machineId: "machine_1",
+ agentId: "bot_1",
+ })
+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
+ mockGetBotBinding.mockResolvedValue({ machineId: "machine_1", isActive: true })
+ })
+
+ it("resolves an active bot runner key", async () => {
+ await expect(resolveBotActor({} as never, "Bearer crk_valid")).resolves.toEqual({
+ kind: "bot",
+ actor: {
+ botUserId: "bot_1",
+ ownerUserId: "owner_1",
+ machineId: "machine_1",
+ isActive: true,
+ },
+ })
+ })
+
+ it("rejects a stale runner key after its bot becomes inactive", async () => {
+ mockGetBotBinding.mockResolvedValue({ machineId: "machine_1", isActive: false })
+
+ const result = await resolveBotActor({} as never, "Bearer crk_valid")
+
+ expect(result.kind).toBe("error")
+ if (result.kind !== "error") throw new Error("expected auth error")
+ expect(result.response.status).toBe(401)
+ await expect(result.response.json()).resolves.toEqual({ error: "bot binding mismatch" })
+ })
+
+ it("carries inactive binding state only when the caller explicitly allows it", async () => {
+ mockGetBotBinding.mockResolvedValue({ machineId: "machine_1", isActive: false })
+
+ await expect(resolveBotActor(
+ {} as never,
+ "Bearer crk_valid",
+ { allowInactive: true },
+ )).resolves.toEqual({
+ kind: "bot",
+ actor: {
+ botUserId: "bot_1",
+ ownerUserId: "owner_1",
+ machineId: "machine_1",
+ isActive: false,
+ },
+ })
+ })
+})
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.ts
index 5b2157fa5..477017f97 100644
--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts
@@ -16,6 +16,12 @@ export interface ResolvedBotActor {
botUserId: string
ownerUserId: string
machineId: string
+ isActive: boolean
+}
+
+interface ResolveBotActorOptions {
+ /** Narrow escape hatch for inbox pull/snapshot to return their inactive empty shape. */
+ allowInactive?: boolean
}
const RETRY_OPTS = { route: "community-agent-runner-auth" }
@@ -76,6 +82,7 @@ async function lookupOr503<T>(
export async function resolveBotActor(
db: Database,
authHeader: string | null,
+ options: ResolveBotActorOptions = {},
): Promise<
| { kind: "bot"; actor: ResolvedBotActor }
| { kind: "not_bot" }
@@ -115,9 +122,17 @@ export async function resolveBotActor(
if (!binding || binding.machineId !== row.machineId) {
return { kind: "error", response: NextResponse.json({ error: "bot binding mismatch" }, { status: 401 }) }
}
+ if (!binding.isActive && !options.allowInactive) {
+ return { kind: "error", response: NextResponse.json({ error: "bot binding mismatch" }, { status: 401 }) }
+ }
return {
kind: "bot",
- actor: { botUserId: row.agentId, ownerUserId: row.userId, machineId: row.machineId },
+ actor: {
+ botUserId: row.agentId,
+ ownerUserId: row.userId,
+ machineId: row.machineId,
+ isActive: binding.isActive,
+ },
}
}
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 0f9ba555c..54fc5a7b2 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -143,6 +143,7 @@ export const communityKeys = {
// ── Bots ────────────────────────────────────────────────────────────────
bots: () => [...communityKeys.all, "bots"] as const,
+ billing: () => [...communityKeys.all, "billing"] as const,
bugReport: (reportId: string) =>
[...communityKeys.all, "bug-report", reportId] as const,
botAuditLog: (botId: string) =>
diff --git a/src/web/src/lib/root-sitemap.test.ts b/src/web/src/lib/root-sitemap.test.ts
index 17e06ec81..899a9cc68 100644
--- a/src/web/src/lib/root-sitemap.test.ts
+++ b/src/web/src/lib/root-sitemap.test.ts
@@ -35,6 +35,8 @@ describe("sitemap", () => {
expect(urls).toContain("https://alook.ai");
expect(urls).toContain("https://alook.ai/templates");
+ expect(urls).toContain("https://alook.ai/pricing");
+ expect(urls).not.toContain("https://alook.ai/pricing-concept");
expect(urls).toContain("https://alook.ai/blog");
expect(urls).toContain("https://alook.ai/privacy");
expect(urls).toContain("https://alook.ai/blog/revised");
diff --git a/src/web/src/lib/root-sitemap.ts b/src/web/src/lib/root-sitemap.ts
index 8777896f9..c8d7007c3 100644
--- a/src/web/src/lib/root-sitemap.ts
+++ b/src/web/src/lib/root-sitemap.ts
@@ -24,6 +24,7 @@ export function buildRootSitemap(manifest: BlogDiscoveryManifestV1 | null): Meta
return [
{ url: SITE_URL, changeFrequency: "weekly", priority: 1 },
+ { url: `${SITE_URL}/pricing`, changeFrequency: "monthly", priority: 0.8 },
{ url: `${SITE_URL}/templates`, changeFrequency: "weekly", priority: 0.8 },
...templateEntries,
...(manifest
diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
index ee5dc3367..f6c20187a 100644
--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
@@ -43,6 +43,7 @@ describe("human account read-state writer contract", () => {
.sort()
expect(directWriters).toEqual([
+ "src/shared/src/db/queries/community/bot.ts",
"src/shared/src/db/queries/community/forum-post-delete.ts",
"src/shared/src/db/queries/community/message.ts",
"src/shared/src/db/queries/community/read-state.ts",
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
index 6097ab75e..78748eab2 100644
--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -10,6 +10,30 @@ import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"
type UserKey = "alice" | "bob"
type Rect = { x: number; y: number; width: number; height: number }
+const createdBotIds: string[] = []
+const createdMachineIds: string[] = []
+
+async function cleanupCreatedResources(): Promise<void> {
+ for (const botId of [...createdBotIds]) {
+ const response = await fetch(`${WEB_URL}/api/community/bots/${botId}`, {
+ method: "DELETE",
+ headers: headersFor("alice"),
+ })
+ expect(response.status, `delete test bot ${botId}`).toBe(204)
+ createdBotIds.splice(createdBotIds.indexOf(botId), 1)
+ }
+ for (const machineId of [...createdMachineIds]) {
+ const response = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, {
+ method: "DELETE",
+ headers: headersFor("alice"),
+ })
+ expect(response.status, `delete test machine ${machineId}`).toBe(204)
+ createdMachineIds.splice(createdMachineIds.indexOf(machineId), 1)
+ }
+}
+
+test.afterEach(cleanupCreatedResources)
+
async function rect(locator: Locator): Promise<Rect> {
const value = await locator.boundingBox()
expect(value).not.toBeNull()
@@ -221,7 +245,9 @@ async function pairMachine(): Promise<{ credential: string; machineId: string }>
}),
})
expect(response.status).toBe(200)
- return response.json() as Promise<{ credential: string; machineId: string }>
+ const data = await response.json() as { credential: string; machineId: string }
+ createdMachineIds.push(data.machineId)
+ return data
}
async function createBot(machineId: string, name: string): Promise<string> {
@@ -229,6 +255,7 @@ async function createBot(machineId: string, name: string): Promise<string> {
method: "POST",
body: JSON.stringify({ name, machineId, runtime: "codex" }),
})
+ createdBotIds.push(data.bot.id)
return data.bot.id
}
@@ -304,6 +331,8 @@ type MachineSocket = {
once(event: "open", listener: () => void): void
once(event: "error", listener: (error: Error) => void): void
once(event: "message", listener: (data: unknown) => void): void
+ on(event: "message", listener: (data: unknown) => void): void
+ off(event: "message", listener: (data: unknown) => void): void
}
function connectMachine(credential: string) {
@@ -551,14 +580,31 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned aud
.toBe(true)
expect((await auditRows.allTextContents()).some((text) =>
/open activity log 0$/i.test(text))).toBe(false)
- machine.socket.send(JSON.stringify({
- type: "bot_audit_event",
- eventId: `bae_${suffix}_11`,
- agentId: botId,
- sessionId: `session-${suffix}`,
- launchId: `launch-${suffix}`,
- event: { kind: "tool_call", payload: { name: "Open activity log 11" } },
- }))
+ const liveEventId = `bae_${suffix}_11`
+ let liveEventAcknowledged = false
+ const onAuditAck = (data: unknown) => {
+ const frame = JSON.parse(String(data)) as { type?: string; eventId?: string }
+ if (frame.type === "bot_audit_event_ack" && frame.eventId === liveEventId) {
+ liveEventAcknowledged = true
+ }
+ }
+ machine.socket.on("message", onAuditAck)
+ try {
+ machine.socket.send(JSON.stringify({
+ type: "bot_audit_event",
+ eventId: liveEventId,
+ agentId: botId,
+ sessionId: `session-${suffix}`,
+ launchId: `launch-${suffix}`,
+ event: { kind: "tool_call", payload: { name: "Open activity log 11" } },
+ }))
+ await expect.poll(() => liveEventAcknowledged, {
+ message: `machine receives bot_audit_event_ack for ${liveEventId}`,
+ timeout: 30_000,
+ }).toBe(true)
+ } finally {
+ machine.socket.off("message", onAuditAck)
+ }
await expect.poll(async () =>
(await auditRows.allTextContents()).join(" ").toLowerCase())
.toContain("open activity log 11")
@@ -714,14 +760,20 @@ test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390
const { page } = await asUser("alice")
await gotoAfterUserWsAuth(page, "/c/me/bots")
- await page.getByRole("button", { name: "Create a bot", exact: true }).click()
+ const capacity = await jsonRequest<{ ownedCount: number; limit: number }>("alice", "/api/community/bots")
+ expect(capacity.ownedCount).toBeLessThan(capacity.limit)
+ const create = page.getByRole("button", { name: "Create a bot", exact: true })
+ await expect(create).toBeEnabled()
+ await create.click()
for (const width of [390, 639, 640] as const) {
await expectFooterGeometry(page, "Create a bot", ["Cancel", "Create bot"], width)
}
await page.getByRole("dialog", { name: "Create a bot", exact: true })
.getByRole("button", { name: "Close", exact: true }).click()
- await page.getByRole("button", { name: "Bot actions", exact: true }).first().click()
+ await page.locator('[data-slot="card"]')
+ .filter({ has: page.getByText(botName, { exact: true }) })
+ .getByRole("button", { name: "Bot actions", exact: true }).click()
await page.getByRole("menuitem", { name: "Edit", exact: true }).click()
for (const width of [390, 639, 640] as const) {
await expectFooterGeometry(page, `Edit ${botName}`, ["Cancel", "Save"], width)
@@ -729,6 +781,7 @@ test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390
await page.getByRole("dialog", { name: `Edit ${botName}`, exact: true })
.getByRole("button", { name: "Close", exact: true }).click()
+ await cleanupCreatedResources()
await gotoAfterUserWsAuth(page, "/c/me/machines")
await page.getByTestId(tid.machinePairOpen).click()
for (const width of [390, 639, 640] as const) {
diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
index 60855b606..fbd9e24c8 100644
--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
@@ -244,6 +244,14 @@ const bots = [
},
]
+const botsResponse = {
+ bots,
+ plan: { id: "house", displayName: "House" },
+ limit: 40,
+ ownedCount: bots.length,
+ activeCount: bots.length,
+}
+
async function attachScreenshot(page: Page, testInfo: TestInfo, name: string) {
const path = testInfo.outputPath(`${name}.png`)
await page.screenshot({ path, fullPage: true })
@@ -262,7 +270,7 @@ async function expectDarkTheme(page: Page, expected: boolean) {
test("My Bots restores the 30-day token heatmap across PC and mobile", async ({ asUser }, testInfo) => {
const { page } = await asUser("alice", { hasTouch: true })
await page.route("**/api/community/bots", async (route) => {
- await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ bots }) })
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(botsResponse) })
})
await page.route("**/api/community/machines", async (route) => {
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ machines: [machine] }) })
diff --git a/src/web/test-runtime/d1-bind-community.runtime.test.ts b/src/web/test-runtime/d1-bind-community.runtime.test.ts
index 7062e5353..7fcfda302 100644
--- a/src/web/test-runtime/d1-bind-community.runtime.test.ts
+++ b/src/web/test-runtime/d1-bind-community.runtime.test.ts
@@ -27,6 +27,20 @@ async function rows<T>(sql: string, ...bindings: unknown[]): Promise<T[]> {
return (await runtimeEnv.DB.prepare(sql).bind(...bindings).all<T>()).results;
}
+async function grantBotCapacity(userId: string, planId: string, maximum: number) {
+ await runtimeEnv.DB.batch([
+ runtimeEnv.DB.prepare(
+ "INSERT INTO product_plan (id, display_name, is_default, is_active, sort_order) VALUES (?, 'High-cardinality fixture', 0, 1, 0)",
+ ).bind(planId),
+ runtimeEnv.DB.prepare(
+ "INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json) VALUES (?, 'bots.max', ?)",
+ ).bind(planId, JSON.stringify(maximum)),
+ runtimeEnv.DB.prepare(
+ "INSERT INTO user_product_plan (user_id, plan_id) VALUES (?, ?)",
+ ).bind(userId, planId),
+ ]);
+}
+
afterEach(async () => {
for (const prefix of prefixes.splice(0)) {
await run("DELETE FROM community_bot_binding WHERE user_id GLOB ?", `${prefix}*`);
@@ -39,6 +53,7 @@ afterEach(async () => {
await run("DELETE FROM agent_runtime WHERE id GLOB ?", `${prefix}*`);
await run("DELETE FROM workspace WHERE id GLOB ?", `${prefix}*`);
await run("DELETE FROM user WHERE id GLOB ?", `${prefix}*`);
+ await run("DELETE FROM product_plan WHERE id GLOB ?", `${prefix}*`);
}
});
@@ -184,6 +199,11 @@ describe("community high-cardinality D1 queries", () => {
ownerId,
`${ownerId}@example.com`,
);
+ await grantBotCapacity(ownerId, `${prefix}_plan`, 125);
+ await run(
+ "INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json) VALUES (?, 'machines.max', '1')",
+ `${prefix}_plan`,
+ );
await run(
"INSERT INTO community_machine (id, user_id, display_name, hostname, available_runtimes, status, created_at, updated_at) VALUES (?, ?, 'Machine', 'host', '[]', 'online', ?, ?)",
machineId,
@@ -222,6 +242,7 @@ describe("community high-cardinality D1 queries", () => {
ownerId,
`${ownerId}@example.com`,
);
+ await grantBotCapacity(ownerId, `${prefix}_plan`, 125);
const botIds = Array.from({ length: 125 }, (_, index) => `${prefix}_bot_${index}`);
const peerIds = Array.from({ length: 125 }, (_, index) => `${prefix}_peer_${index}`);
diff --git a/src/ws-do/src/ws-durable/agent-interrupt.test.ts b/src/ws-do/src/ws-durable/agent-interrupt.test.ts
index bb944eaeb..fe2196722 100644
--- a/src/ws-do/src/ws-durable/agent-interrupt.test.ts
+++ b/src/ws-do/src/ws-durable/agent-interrupt.test.ts
@@ -40,6 +40,17 @@ describe("agent running-turn interrupt WS routing", () => {
expect(mockStubFetch).not.toHaveBeenCalled()
})
+ it("does not forward a control request for an inactive bot", async () => {
+ const { durable } = createDO()
+ const ws = userSocket()
+ mockGetBotBindingWithOwner.mockResolvedValue({ ...binding, isActive: false })
+
+ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify(request))
+
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
it("logs a binding lookup failure without forwarding", async () => {
const { durable } = createDO()
const ws = userSocket()
diff --git a/src/ws-do/src/ws-durable/agent-interrupt.ts b/src/ws-do/src/ws-durable/agent-interrupt.ts
index fdf32e9eb..c26308529 100644
--- a/src/ws-do/src/ws-durable/agent-interrupt.ts
+++ b/src/ws-do/src/ws-durable/agent-interrupt.ts
@@ -21,7 +21,7 @@ export async function handleUserAgentInterrupt(
() => queries.communityBot.getBotBindingWithOwner(db, request.data.agentId),
{ route: "ws-do:agent-interrupt-binding" },
)
- if (!binding || binding.ownerUserId !== state.userId) return true
+ if (!binding || !binding.isActive || binding.ownerUserId !== state.userId) return true
const doNames = await withD1Retry(
() => queries.communityMachine.getActiveDoNamesForMachine(db, binding.machineId),
{ route: "ws-do:agent-interrupt-machine" },
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
index 2ba71fc8d..f21032dff 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createMockWebSocket } from "../__mocks__/cf"
import {
+ mockAssertMachineCapacity,
CFResponse,
cleanupHarness,
createDO,
@@ -116,6 +117,34 @@ describe("WebSocketDurableObject", () => {
mockFindCredentialByHash.mockReset()
})
+
+ it("rejects offline admission at capacity before accepting a socket", async () => {
+ const { queries } = await import("@alook/shared")
+ mockFindCredentialByHash.mockResolvedValue(auth)
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "offline" })
+ mockAssertMachineCapacity.mockRejectedValue(new queries.productPlan.MachineLimitReachedError({ plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 2, onlineCount: 1 }))
+ const { durable, ctx } = createDO()
+ const request = () => new Request("http://internal/", { headers: { Upgrade: "websocket", Authorization: "Bearer cmk_secret" } })
+ expect((await durable.fetch(request())).status).toBe(409)
+ expect(ctx.acceptWebSocket).not.toHaveBeenCalled()
+ expect(mockAssertMachineCapacity).toHaveBeenCalledWith({}, "u_1", "online")
+ mockAssertMachineCapacity.mockRejectedValue(new Error("entitlement unavailable"))
+ expect((await durable.fetch(request())).status).toBe(503)
+ mockGetMachineByIdForUser.mockResolvedValue(null)
+ expect((await durable.fetch(request())).status).toBe(401)
+ })
+ it("checks offline allowance once and skips quota queries for an existing online connection", async () => {
+ mockFindCredentialByHash.mockResolvedValue(auth)
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "offline" })
+ const { durable } = createDO()
+ const request = () => new Request("http://internal/", { headers: { Upgrade: "websocket", Authorization: "Bearer cmk_secret" } })
+ expect((await durable.fetch(request())).status).toBe(101)
+ expect(mockAssertMachineCapacity).toHaveBeenCalledOnce()
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "online" })
+ expect((await durable.fetch(request())).status).toBe(101)
+ expect(mockAssertMachineCapacity).toHaveBeenCalledOnce()
+ })
+
it("accepts cmk credentials in exact lookup, socket, attachment, storage, and alarm order", async () => {
vi.spyOn(Date, "now").mockReturnValue(1_000_000)
mockFindCredentialByHash.mockResolvedValue(auth)
diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.ts
index c65e6b9aa..23d4c9431 100644
--- a/src/ws-do/src/ws-durable/machine-control.ts
+++ b/src/ws-do/src/ws-durable/machine-control.ts
@@ -194,6 +194,16 @@ export async function acceptCommunityMachineWebSocket(
return new Response("credential revoked or unknown", { status: 401 })
}
+ try {
+ const machine = await queries.communityMachine.getMachineByIdForUser(db, auth.userId, auth.machineId)
+ if (!machine) return new Response("machine not found", { status: 401 })
+ if (machine.status !== "online") await queries.productPlan.assertMachineCapacity(db, auth.userId, "online")
+ } catch (error) {
+ if (error instanceof queries.productPlan.MachineLimitReachedError) return new Response("MACHINE_LIMIT_REACHED", { status: 409 })
+ context.log.warn("community machine capacity lookup failed", { err: String(error) })
+ return new Response("machine allowance unavailable", { status: 503 })
+ }
+
const pair = new WebSocketPair()
const [client, server] = Object.values(pair)
context.ctx.acceptWebSocket(server)
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index 89654c4da..8507ff94d 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -775,6 +775,39 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).not.toHaveBeenCalled()
})
+ it("agent_typing: drops a stale frame for an inactive bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "u_1",
+ name: "Bot",
+ discriminator: "0007",
+ isActive: false,
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "agent_typing",
+ agentId: "bot_1",
+ channelId: "dm_1",
+ }))
+
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
it("agent_typing: drops a frame for a bot that is not a DM participant — no fan-out", async () => {
const { durable, store } = createDO()
store.set("community-machine-identity", {
@@ -1325,6 +1358,19 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).not.toHaveBeenCalled()
})
+ it("does not project an activity status from an inactive bot", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBinding.mockResolvedValue({ ...binding, isActive: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" }),
+ )
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
it("classifies activity write failures as plain write drops", async () => {
const { durable, ws } = setup()
mockGetBotBinding.mockResolvedValue(binding)
@@ -1407,6 +1453,26 @@ describe("WebSocketDurableObject", () => {
)
})
+ it("preserves an in-flight audit completion after the bot becomes inactive", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBindingWithOwner.mockResolvedValue({ ...binding, isActive: false })
+ mockInsertBotActivityEventAndPrune.mockResolvedValue({
+ id: "audit_1",
+ createdAt: "2026-09-09T06:00:00.000Z",
+ })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "tool_call", payload: { name: "Read" } },
+ }),
+ )
+
+ expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledOnce()
+ })
+
it("skips awake and owner notification when an agent-session audit insert returns null", async () => {
const { durable, store, ws } = setup()
store.set("reset-pending:l_nap", { kind: "nap" })
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.ts
index 0d7a2bdb6..cf566ce3e 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts
@@ -146,7 +146,10 @@ export async function handleActivityFrame(
const customStatus =
(priorEmoji !== null || priorText !== null) &&
!isBotActivityStatus(priorEmoji, priorText)
- const profileWritable = !customStatus
+ // An in-flight heartbeat may arrive after deactivation. Preserve its
+ // bounded usage/quota telemetry, but never let an inactive bot project a
+ // new activity status to viewers.
+ const profileWritable = binding.isActive && !customStatus
const priorIsRunning =
priorEmoji !== null &&
RUNNING_PRESETS.some((preset) => preset.emoji === priorEmoji && preset.text === priorText)
@@ -264,7 +267,7 @@ export async function handleTypingFrame(
() => queries.communityBot.getBotBindingWithOwner(db, agentId),
{ route: "ws-do:agent-typing-binding" },
),
- isMatch: (binding) => binding.machineId === identity.machineId,
+ isMatch: (binding) => binding.isActive && binding.machineId === identity.machineId,
write: async (binding) => {
// Membership is enforced by `fanOutTyping`; the binding already carries
// the bot display identity, avoiding another roster query per heartbeat.
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index ab572d13f..0205e540a 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -88,6 +88,7 @@ export const mockCreateDb = vi.fn().mockReturnValue({})
export const mockHashCredential = vi.fn(async (bearer: string) => `hash:${bearer}`)
export const mockFindCredentialByHash = vi.fn()
export const mockGetMachineByIdForUser = vi.fn()
+export const mockAssertMachineCapacity = vi.fn()
export const mockGetActiveDoNamesForMachine = vi.fn<(db: unknown, machineId: string) => Promise<string[]>>().mockResolvedValue([])
export const mockUpsertMachineByMachineId = vi.fn()
export const mockTouchMachineHeartbeat = vi.fn()
@@ -119,7 +120,7 @@ export const mockListMembers = vi.fn()
export const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
export const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
export const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
-export const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null>>().mockResolvedValue(null)
+export const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string; isActive?: boolean } | null>>().mockResolvedValue(null)
export const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: any, extraStatements?: unknown[]) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
@@ -372,6 +373,7 @@ vi.mock("@alook/shared", async () => {
return pairs.some((p) => p.emoji === emoji && p.text === text)
},
queries: {
+ productPlan: { ...actual.queries.productPlan, assertMachineCapacity: (...a: any[]) => mockAssertMachineCapacity(...a) },
session: {
getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token),
getValidSessionWithIdentity: (db: unknown, token: string) => mockGetValidSessionWithIdentity(db, token),
@@ -464,8 +466,14 @@ vi.mock("@alook/shared", async () => {
},
communityBot: {
listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
- getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
- getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),
+ getBotBinding: async (...a: [unknown, string]) => {
+ const binding = await mockGetBotBinding(...a)
+ return binding ? { isActive: true, ...binding } : null
+ },
+ getBotBindingWithOwner: async (...a: [unknown, string]) => {
+ const binding = await mockGetBotBindingWithOwner(...a)
+ return binding ? { isActive: true, ...binding } : null
+ },
touchBotRefreshContext: (...a: [unknown, string, string]) => mockTouchBotRefreshContext(...a),
touchBotRefreshContextForAuditEventStatement: (...a: [unknown, string, string, string]) =>
mockTouchBotRefreshContextForAuditEventStatement(...a),
@@ -517,6 +525,8 @@ export const flushAsyncWork = async () => {
}
export function resetHarness() {
vi.clearAllMocks()
+ mockAssertMachineCapacity.mockReset().mockResolvedValue(undefined)
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "online", availableRuntimes: [] })
mockListReadableChannelsForUser.mockImplementation(async (_db, _userId, ids: string[]) => ids.map((id) => ({ id, serverId: null, parentChannelId: null })))
mockGetReadableMessageChannelId.mockResolvedValue("ch-1")
// `clearAllMocks` doesn't undo a `mockResolvedValue` set by a prior test —