Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Starter makes five bots, then offers the upgrade
milind-soni607b7a5d5ceb
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex b5e0c20c86..bfcb2c3577 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1108,6 +1108,16 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):thread per bot for what a person or a routine starts; the Admin says so with itssigned `POST /api/cloud/plan` `{"v":1,"tier":"starter"}` (`server/host/cloud-plan-tier.ts`), and ahome it never told has no such limit. What a bot's own turn starts always goes through.+- **How many bots a Starter Cloud makes.** Five beside its MausBot, one number in+ `server/host/starter-bot-limit.ts`, from the same signed plan. An archived bot or one+ that moved away takes no room. Making one past it answers `409` with+ `{"code":"bot_limit","error":"…"}` from `POST /api/bots`, `POST /api/teams/import`,+ `POST /api/org-library/add` and a Chief's `create_bot` and `propose_team_setup`; a group that+ doesn't fit is refused whole, before anything is written. The app opens its upgrade popup+ when a create button is pressed with no room, and on that refusal. A bot is never taken away:+ a Cloud over the limit (a downgrade, a move) keeps every one and only making a new one stops.+ A bot arriving with its own id (a move) and a backup restored are never refused. The limit+ lifts as soon as the Admin tells the home its new plan, with no restart.- **OpenCode threads share a process.** Threads whose OpenCode would startthe same way (same login, approval level and settings) run as sessions of one`opencode acp` process, up to six at a time and twelve over its lifediff --git a/server/host/starter-bot-limit.test.ts b/server/host/starter-bot-limit.test.tsnew file mode 100644index 0000000000..758652b74a--- /dev/null+++ b/server/host/starter-bot-limit.test.ts@@ -0,0 +1,98 @@+import { readdirSync, readFileSync } from "node:fs";+import { join, relative, sep } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++import { BOT_LIMIT_CODE, botsTowardLimit } from "../../shared/bot-limit.ts";+import { createBotLimit, STARTER_BOT_LIMIT } from "./starter-bot-limit.ts";++const SERVER = fileURLToPath(new URL("..", import.meta.url));+const made = (count: number) => Array.from({ length: count }, () => ({}));+const onStarter = (bots: Parameters<typeof botsTowardLimit>[0], starter = true) => createBotLimit({ starter: () => starter, bots: () => bots });++function sources(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) return ["node_modules", "testing", "dist"].includes(entry.name) ? [] : sources(path);+ return entry.name.endsWith(".ts") && !/\.test\.|\.d\.ts$/.test(entry.name) ? [path] : [];+ });+}+const calling = (pattern: RegExp) => sources(SERVER).filter((path) => pattern.test(readFileSync(path, "utf8")))+ .map((path) => relative(SERVER, path).split(sep).join("/")).sort();++describe("a Starter Cloud's bots", () => {+ it("is five, in one number", () => {+ expect(STARTER_BOT_LIMIT).toBe(5);+ });++ it("counts every bot but its MausBot, an archived one and one that moved away", () => {+ expect(botsTowardLimit([{}, { defaultBot: {} }, { hidden: true }, { movedTo: { state: "moved" } }, {}])).toBe(2);+ });++ it("makes the fifth and refuses the sixth", () => {+ expect(onStarter(made(4)).refusal()).toBeNull();+ expect(onStarter(made(5)).refusal()).toMatchObject({ code: BOT_LIMIT_CODE });+ expect(onStarter(made(5)).limit()).toBe(5);+ });++ it("leaves the MausBot out of the count", () => {+ expect(onStarter([{ defaultBot: {} }, ...made(4)]).refusal()).toBeNull();+ expect(onStarter([{ defaultBot: {} }, ...made(5)]).refusal()).not.toBeNull();+ });++ it("refuses a group that doesn't fit, whole, and takes one that does", () => {+ expect(onStarter(made(3)).refusal(2)).toBeNull();+ const refused = onStarter(made(3)).refusal(3);+ expect(refused?.error).toBe("This adds 3 bots, and your Starter plan has room for 2 more of its 5. To add them all, upgrade this Cloud.");+ });++ it("still refuses a Cloud already over the limit, in the same words as one at it", () => {+ expect(onStarter(made(9)).refusal()?.error).toBe(onStarter(made(5)).refusal()?.error);+ });++ it("tells a person to upgrade, in words an older app can show as they are", () => {+ expect(onStarter(made(5)).refusal()?.error).toBe("You've reached the 5 bots Starter includes. To create more, upgrade this Cloud.");+ });++ it("tells a bot to explain it to the person, not to retry or work around it", () => {+ const words = onStarter(made(5)).refusal(1, "bot")?.error;+ expect(words).toContain("Explain this to the person");+ expect(words).toContain("upgrade this Cloud");+ expect(words).toContain("Do not retry");+ expect(words).toContain("do not try to work around it");+ expect(onStarter(made(4)).refusal(3, "bot")?.error).toContain("Do not retry");+ expect(onStarter(made(9)).refusal(0, "bot"), "changing the bots it has").toBeNull();+ });++ it("has no limit on any other plan, and follows the plan at each question", () => {+ expect(onStarter(made(50), false).refusal(10)).toBeNull();+ expect(onStarter(made(50), false).limit()).toBeUndefined();+ let starter = true;+ const limit = createBotLimit({ starter: () => starter, bots: () => made(5) });+ expect(limit.refusal()).not.toBeNull();+ starter = false;+ expect(limit.refusal()).toBeNull();+ expect(limit.limit()).toBeUndefined();+ });+});++describe("where a bot gets made", () => {+ // A new caller here decides what a plan's limit means for it, and adds itself to the gated or exempt list in this test.+ it("is only the paths the limit has an answer for", () => {+ expect(calling(/\.createBot\(/)).toEqual([+ "default-bot.ts", // a place's MausBot: never counted+ "package-import.ts", // gated before its first record: file imports, templates, the move importer, the org library+ "routes/bots-create.ts", // gated, unless the bot arrives with its own id: a move+ "store.ts", // the store's own seed on an empty place+ "team-backup.ts", // a restore: never refused+ ]);+ expect(calling(/\.applyTeamSetup\(/)).toEqual(["team-setup-requests.ts"]);+ });++ it("gates each of them with the one check", () => {+ const read = (file: string) => readFileSync(join(SERVER, file), "utf8");+ expect(read("routes/bots-create.ts")).toContain("kept.id ? null : deps.botLimit.refusal()");+ expect(read("package-import.ts")).toContain("deps.botLimit?.refusal(members.length)");+ expect(read("team-setup-requests.ts")).toContain("this.options.botLimit?.refusal(creating,");+ });+});diff --git a/server/host/starter-bot-limit.ts b/server/host/starter-bot-limit.tsnew file mode 100644index 0000000000..9e7c162006--- /dev/null+++ b/server/host/starter-bot-limit.ts@@ -0,0 +1,42 @@+// A Starter Cloud's bots. Asked at each request, so a plan change counts at once, and only when a new bot is made: a bot that+// already exists never goes anywhere, whatever the plan says now.+import { BOT_LIMIT_CODE, botsTowardLimit, type BotLimitRefusal } from "../../shared/bot-limit.ts";++/** How many bots a Starter Cloud can make, not counting its MausBot. The one number to change. */+export const STARTER_BOT_LIMIT = 5;++export type BotLimitReader = "person" | "bot";++export interface BotLimit {+ /** The most bots this Cloud's plan makes; undefined when its plan has no such limit. */+ limit(): number | undefined;+ /** The answer to making `adding` more, in words for whoever reads them; null when they fit. */+ refusal(adding?: number, reader?: BotLimitReader): BotLimitRefusal | null;+}++function personWords(limit: number, room: number, adding: number): string {+ return room > 0+ ? `This adds ${adding} bots, and your Starter plan has room for ${room} more of its ${limit}. To add them all, upgrade this Cloud.`+ : `You've reached the ${limit} bots Starter includes. To create more, upgrade this Cloud.`;+}++function botWords(limit: number, room: number, adding: number): string {+ const fact = room > 0+ ? `This adds ${adding} bots, and this Cloud's Starter plan has room for ${room} more of its ${limit}`+ : `This Cloud's Starter plan includes ${limit} bots and has no room for another`;+ return `${fact}, so nothing was created. Explain this to the person in one line: to create more bots they need to upgrade this Cloud. Do not retry, and do not try to work around it.`;+}++export function createBotLimit(deps: { starter(): boolean; bots(): Parameters<typeof botsTowardLimit>[0] }): BotLimit {+ const limit = () => (deps.starter() ? STARTER_BOT_LIMIT : undefined);+ return {+ limit,+ refusal(adding = 1, reader = "person") {+ const most = limit();+ if (most === undefined) return null;+ const room = Math.max(0, most - botsTowardLimit(deps.bots()));+ if (adding <= room) return null;+ return { error: (reader === "bot" ? botWords : personWords)(most, room, adding), code: BOT_LIMIT_CODE };+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex 8104d276fa..b3e209afce 100644--- a/server/index.ts+++ b/server/index.ts@@ -110,7 +110,7 @@ import { vpsLeftBehindNotice } from "./cloud-backend.ts";import * as composio from "./composio.ts";import { connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";import { connectorCardDescription, connectorCardText, signInCardText } from "./connector-card-text.ts";-import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";+import { BOT_LIMIT_CODE } from "../shared/bot-limit.ts"; import { createBotLimit } from "./host/starter-bot-limit.ts"; import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";import { buildRecall, recallRooms, recallThreadIds, withRecalled } from "./recall.ts";import { hostTimeZone, takesTurnClock, turnClockLine, withTurnClock } from "./turn-clock.ts";import { createMemoryUpkeep, dreamConversations, upkeepEnabled } from "./memory-upkeep.ts";@@ -2825,7 +2825,7 @@ function packageImportDeps(selection: ModelSelection): PackageImportDeps {return avatarUrl;},},- defaultSelection: () => selection,+ defaultSelection: () => selection, botLimit,presets: presetStore,};}@@ -2910,7 +2910,7 @@ const phones = createPhones({mint: (botId, turn) => mintInternalCapability({ botId, ...turn, kind: "device", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }),active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});-const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.+const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const botLimit = createBotLimit({ starter: () => cloudPlanTier.starter(), bots: () => store.bots }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),@@ -9394,7 +9394,7 @@ const modelRequests = new ModelRequestService({});const teamSetupTeams = () => [...new Set(["", ...readSections(), ...store.bots.map((bot) => sectionKey(bot.section)), ...store.groups.map((group) => sectionKey(group.section))])];const teamSetupRequests = new TeamSetupRequestService({- store, teams: teamSetupTeams, hasTeamAuthority, canPersist: proposalPersistence, maxBots: MAX_WORKSPACE_BOTS,+ store, teams: teamSetupTeams, hasTeamAuthority, canPersist: proposalPersistence, maxBots: MAX_WORKSPACE_BOTS, botLimit,autoApply: appliesDirectly,validateChange: (before, fields) => assertTeamComputerChangeIdle(before, { ...before, ...fields }),ownsThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)),@@ -11879,7 +11879,7 @@ function configStatus() {const eventLogMaxBytes = threadEventLogMaxBytes(cfg);const eventLogRetentionDays = threadEventLogRetentionDays(cfg);return {- cloudStarter: cloudPlanTier.starter(), xai: keyStatus(cfg.xai?.key),+ cloudStarter: cloudPlanTier.starter(), botLimit: botLimit.limit(), xai: keyStatus(cfg.xai?.key),mistral: keyStatus(cfg.mistral?.key),cerebras: keyStatus(cfg.cerebras?.key),groq: keyStatus(cfg.groq?.key), greenference: keyStatus(cfg.greenference?.key),@@ -12288,7 +12288,7 @@ ROUTES.push(createThreadRoutes({ROUTES.push(createBotCreateRoutes({store, cfg, presetStore, orgInstallStatuses,hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,- maxWorkspaceBots: MAX_WORKSPACE_BOTS, cloudOwnerKey: CLOUD_OWNER_KEY,+ maxWorkspaceBots: MAX_WORKSPACE_BOTS, botLimit, cloudOwnerKey: CLOUD_OWNER_KEY,hostedModels, cloudRoutineAuthors,routines: () => routines,storedAvatarExists, defaultSelection, checkedModelSelection, cloudOwnerSession, wireBot, team: CLOUD_TEAM && teamOwners.people ? { name: CLOUD_TEAM.name, people: teamOwners.people } : null,@@ -15581,7 +15581,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {} catch (e) {const status = (e as any)?.status ?? 500;const candidateCode = (e as { code?: unknown })?.code;- const code = typeof candidateCode === "string" && ["guarded_busy", "guarded_branch", "guarded_permissions", "guarded_request_changed", "guarded_request_untracked", "outside_workspace"].includes(candidateCode)+ const code = typeof candidateCode === "string" && ["guarded_busy", "guarded_branch", "guarded_permissions", "guarded_request_changed", "guarded_request_untracked", "outside_workspace", BOT_LIMIT_CODE].includes(candidateCode)? candidateCode : undefined;return json(res, status, { error: e instanceof Error ? e.message : String(e), ...(code ? { code } : {}) });} finally {diff --git a/server/org-library.test.ts b/server/org-library.test.tsindex 4512496cbf..ccce372585 100644--- a/server/org-library.test.ts+++ b/server/org-library.test.ts@@ -227,6 +227,34 @@ describe("release files", () => {});});+describe("adding from the shelf on a Starter Cloud", () => {+ it("answers 409 at the limit, adds nothing, reports no broken package, and adds it once there is room", async () => {+ const app = await installation();+ for (let i = 0; i < 5; i++) app.store.createBot({ name: `Bot ${i}` });+ const { createBotLimit } = await import("./host/starter-bot-limit.ts");+ let starter = true;+ const deps = { ...app.importDeps, botLimit: createBotLimit({ starter: () => starter, bots: () => app.store.bots }) };+ const library = app.open();+ const team = release("full-team.v2.json");+ app.writeBlob(team.bytes);+ library.applyRelay(relay(catalog([entry(TEAM_ID, team)])));+ await library.settled();+ const before = app.store.bots.length;+ app.posted.length = 0;++ expect(library.add(TEAM_ID, deps)).toMatchObject({ ok: false, status: 409, code: "bot_limit", error: expect.stringContaining("upgrade this Cloud") });+ await library.settled();+ expect(app.store.bots).toHaveLength(before);+ expect(app.posted.flatMap((report: { packages: Array<{ state: string }> }) => report.packages).filter((row) => row.state === "failed")).toEqual([]);+ expect(app.readState().adding ?? {}).toEqual({});++ starter = false;+ const added = library.add(TEAM_ID, deps);+ expect(added).toMatchObject({ ok: true, status: 201 });+ expect(app.store.bots.length).toBe(before + 3);+ });+});+describe("the relay", () => {it("acknowledges before any work, then reconciles and reports", async () => {const app = await installation();diff --git a/server/org-library.ts b/server/org-library.tsindex 1b1b65d278..99a70cd924 100644--- a/server/org-library.ts+++ b/server/org-library.ts@@ -871,7 +871,7 @@ export class OrgLibrary {try {this.save();} catch {}- if (error instanceof PackageImportError) return fail(refusal(422, error.code, error.message), "invalid_package");+ if (error instanceof PackageImportError) return error.status === 409 ? refusal(409, error.code, error.message) : fail(refusal(422, error.code, error.message), "invalid_package");console.error(`[org-library] could not add ${entry.ref}: ${error instanceof Error ? error.message : String(error)}`);return fail(refusal(500, "import_failed", ADD_FAILED), "import_failed");}diff --git a/server/package-import.test.ts b/server/package-import.test.tsindex 36ce635b80..ed112b4f3e 100644--- a/server/package-import.test.ts+++ b/server/package-import.test.ts@@ -226,3 +226,55 @@ describe("importing a whole team", () => {.toThrow("not published by the organization");});});++describe("importing onto a Starter Cloud", () => {+ const onStarter = async (bots: number, starter = true) => {+ const app = await installation();+ for (let i = 0; i < bots; i++) app.store.createBot({ name: `Bot ${i}` });+ const { createBotLimit } = await import("./host/starter-bot-limit.ts");+ return { ...app, deps: { ...app.deps, botLimit: createBotLimit({ starter: () => starter, bots: () => app.store.bots }) } };+ };+ const team = (app: { parsePackageDocument: (input: unknown) => PackageDocument }) => app.parsePackageDocument(fixture("full-team.v2.json"));++ it("refuses a team that doesn't fit before writing anything", async () => {+ const app = await onStarter(3);+ const before = app.snapshot();+ expect(() => app.importer.importPackageDocument(team(app), { trust: "file", mode: "add" }, app.deps))+ .toThrow(expect.objectContaining({ code: "bot_limit", status: 409 }));+ expect(app.snapshot()).toBe(before);+ expect(app.events).toEqual([]);+ });++ it("refuses a template's manifest the same way", async () => {+ const app = await onStarter(5);+ const before = app.snapshot();+ const { parseTeamManifest } = await import("./team-manifest.ts");+ const manifest = parseTeamManifest({ format: "openmaus.team", version: 2, team: { name: "Desk", members: [{ key: "helper", name: "Helper", appearance: { color: "blue" } }] } });+ expect(() => app.importer.importTeamManifest(manifest, { mode: "add", cwd: null }, app.deps))+ .toThrow(expect.objectContaining({ code: "bot_limit", status: 409 }));+ expect(app.snapshot()).toBe(before);+ });++ it("adds a team that fits, exactly up to the limit", async () => {+ const app = await onStarter(2);+ const result = app.importer.importPackageDocument(team(app), { trust: "file", mode: "add" }, app.deps);+ if (result.alreadyAdded) throw new Error("unexpected");+ expect(result.bots).toHaveLength(3);+ expect(app.store.bots).toHaveLength(5);+ });++ it("adds it on another plan however many are here", async () => {+ const app = await onStarter(9, false);+ const result = app.importer.importPackageDocument(team(app), { trust: "file", mode: "add" }, app.deps);+ if (result.alreadyAdded) throw new Error("unexpected");+ expect(result.bots).toHaveLength(3);+ });++ it("registers a preset library at the limit: it makes no bot", async () => {+ const app = await onStarter(5);+ const library = app.parsePackageDocument(fixture("library-only.v2.json"));+ const presets = { register: vi.fn(() => ({ added: [], existing: [], skipped: [] })) };+ expect(() => app.importer.importPackageDocument(library, { trust: "file", mode: "add" }, { ...app.deps, presets: presets as never })).not.toThrow();+ expect(presets.register).toHaveBeenCalledOnce();+ });+});diff --git a/server/package-import.ts b/server/package-import.tsindex 8e90a07138..ebaec024a5 100644--- a/server/package-import.ts+++ b/server/package-import.ts@@ -7,11 +7,13 @@ import {ROOM_PARTS, roomReleaseValues, ROUTINE_PARTS, routineReleaseValues, scheduleValue, sha256Hex, TEAM_PARTS,type AgentPart, type PartPair, type TeamPart,} from "./package-parts.ts";+import type { BotLimit } from "./host/starter-bot-limit.ts";import type { PresetRegistry } from "./presets.ts";import type { Routine, RoutineInput, RoutineManager } from "./routines.ts";import type { SkillListing, SkillPackageStamp } from "./skills.ts";import type { BotRecord, GroupRecord, InstalledPackageMetadata, Store } from "./store.ts";import { importedMemberProfile, type ParsedTeamManifest, type TeamManifestMember } from "./team-manifest.ts";+import { BOT_LIMIT_CODE } from "../shared/bot-limit.ts";import { takeImportName } from "../shared/import-name.ts";import { decodeBase64, type PackageAgent, type PackageDocument, type PackageTrust } from "../shared/package-format.ts";import type { BotVisibility, ModelSelection } from "../shared/wire.ts";@@ -19,15 +21,16 @@ import type { BotVisibility, ModelSelection } from "../shared/wire.ts";export const NO_BOTS_MESSAGE = "This package has no bots. Add it from your organization's shelf, or update OpenMausBot.";export const NO_PRESETS_MESSAGE = "This file has no bots or preset bots to add. Its skills can be added from your organization's shelf.";-export type PackageImportErrorCode = "no_bots" | "invalid_package";+export type PackageImportErrorCode = "no_bots" | "invalid_package" | typeof BOT_LIMIT_CODE;export class PackageImportError extends Error {- readonly status = 400;+ readonly status: number;readonly code: PackageImportErrorCode;- constructor(code: PackageImportErrorCode, message: string) {+ constructor(code: PackageImportErrorCode, message: string, status = 400) {super(message);this.name = "PackageImportError";this.code = code;+ this.status = status;}}@@ -62,6 +65,7 @@ export interface PackageImportDeps {images: { save(bytes: Uint8Array, mime: string): string };broadcast?: (event: { kind: "bot"; bot: BotRecord } | { kind: "group"; group: GroupRecord }) => void;defaultSelection: () => ModelSelection;+ botLimit?: Pick<BotLimit, "refusal">;presets?: PresetRegistry;}@@ -223,6 +227,8 @@ function runImport(source: ImportSource, options: PackageImportOptions, deps: Paconst members = pkg? pkg.agents.map((agent) => ({ member: memberFromAgent(agent), agent })): (source as { manifest: ParsedTeamManifest }).manifest.team.members.map((member) => ({ member, agent: undefined }));+ const overPlan = deps.botLimit?.refusal(members.length);+ if (overPlan) throw new PackageImportError(overPlan.code, overPlan.error, 409);const importedBots: BotRecord[] = [];const createdGroups: GroupRecord[] = [];diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.tsindex f6d62a2bea..3ca24beea8 100644--- a/server/routes/bots-create.ts+++ b/server/routes/bots-create.ts@@ -1,4 +1,5 @@import type { WireBot } from "../../shared/wire.ts";+import type { BotLimit } from "../host/starter-bot-limit.ts";import { freshLook } from "../bot-look.ts";import { validateBotCwd } from "../bot-cwd.ts";import { parseBotProfilePatch } from "../bot-profile.ts";@@ -31,6 +32,7 @@ export interface BotCreateRouteDeps {hostedFullAccessRefusal: string;desktopManaged: boolean;maxWorkspaceBots: number;+ botLimit: Pick<BotLimit, "refusal">;cloudOwnerKey: string | null;hostedModels: ReturnType<typeof hostedModelPolicy>;cloudRoutineAuthors: ReturnType<typeof createCloudRoutineAuthors> | null;@@ -180,6 +182,9 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {if (store.bots.length >= MAX_WORKSPACE_BOTS) {return json(res, 409, { error: `this workspace is limited to ${MAX_WORKSPACE_BOTS} bots` });}+ // A bot with its own id is arriving from the person's other computer: a move never loses a bot to a plan's limit.+ const overPlan = kept.id ? null : deps.botLimit.refusal();+ if (overPlan) return json(res, 409, overPlan);// Apply the audience before creation can announce the bot to members.const created = body.visibility === undefined ? null : parseVisibility(body.visibility);if (created && !created.ok) return json(res, 400, { error: created.error });diff --git a/server/starter-bot-limit.e2e.test.ts b/server/starter-bot-limit.e2e.test.tsnew file mode 100644index 0000000000..099b05ada6--- /dev/null+++ b/server/starter-bot-limit.e2e.test.ts@@ -0,0 +1,253 @@+// A real server as a personal Cloud, told its plan as the Admin tells it, with the fake engine driving a real Chief turn.+import { randomBytes } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import { cloudPairingSignature, cloudRequestSignature } from "./cloud-home.ts";+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { freePortBlock } from "./testing/ports.ts";++const SERVER_DIR = dirname(fileURLToPath(import.meta.url));+const HOST = "omb-t-0123456789ab.fly.dev";+const FORWARDED = { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https" };+const CLAUDE = { instanceId: "claude", model: "claude-sonnet-5" };+const PACKAGE = JSON.parse(readFileSync(join(SERVER_DIR, "..", "shared", "package-fixtures", "full-team.v2.json"), "utf8"));+const manifest = (name: string) => ({ format: "openmaus.team", version: 2, team: { name, members: [{ key: "helper", name: `${name} helper`, appearance: { color: "blue" } }] } });++class Cloud {+ home = mkdtempSync(join(tmpdir(), "omb-bot-limit-"));+ dataDir = join(this.home, ".openmausbot");+ gate = join(this.home, "finish");+ dump = join(this.home, "claude.json");+ secret = randomBytes(32).toString("base64url");+ base = "";+ token = "";+ log = "";+ child: ChildProcess | null = null;+ port = 0;++ headers(extra: Record<string, string> = {}) {+ return { ...FORWARDED, origin: `https://${HOST}`, ...(this.token ? { authorization: `Bearer ${this.token}` } : {}), ...extra };+ }+ async api(method: string, path: string, body?: unknown) {+ const response = await fetch(`${this.base}${path}`, { method, headers: this.headers(body === undefined ? {} : { "content-type": "application/json" }),+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ }+ async start() {+ mkdirSync(this.dataDir, { recursive: true });+ const claude = join(this.home, "held-claude.mjs");+ writeFileSync(claude, `#!/usr/bin/env node+if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" })); process.exit(0); }+process.env.FAKE_CLAUDE_VERSION = "2.1.284";+if (process.argv[2] !== "--version") {+ process.env.FAKE_CLAUDE_MODE = "slow";+ process.env.FAKE_CLAUDE_SLOW_FINISH_GATE = ${JSON.stringify(this.gate)};+ process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(this.dump)};+}+await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});+`, { mode: 0o755 });+ writeFileSync(join(this.dataDir, "config.json"), JSON.stringify({+ features: { smartSetupChoices: false },+ instances: {+ ...Object.fromEntries(["codex", "cursor", "githubCopilot", "qwen", "hermes", "pi"].map((id) => [id, { driver: "not-a-real-driver" }])),+ claude: { driver: "claudeAgent", displayName: "Claude", config: { cli: claude } },+ },+ }));+ this.port = await freePortBlock([0, 1]);+ this.base = `http://127.0.0.1:${this.port}`;+ await this.run();+ }+ async run() {+ const prelude = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("{}", { status: 503 });')}`;+ this.child = spawn(process.execPath, ["--import", prelude, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: { PATH: process.env.PATH, HOME: this.home, USERPROFILE: this.home, OMB_DATA_DIR: this.dataDir, OMB_PORT: String(this.port), OMB_WEBHOOK_PORT: String(this.port + 1),+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_CLOUD_BOOTSTRAP_SECRET: this.secret, OMB_PUBLIC_URL: `https://${HOST}` },+ stdio: ["ignore", "pipe", "pipe"],+ });+ this.child.stdout?.on("data", (chunk) => { this.log += chunk; });+ this.child.stderr?.on("data", (chunk) => { this.log += chunk; });+ await expect.poll(async () => {+ if (this.child!.exitCode !== null) throw new Error(`the server exited:\n${this.log}`);+ return fetch(`${this.base}/api/health`).then((r) => r.ok).catch(() => false);+ }, { timeout: 30_000, interval: 100 }).toBe(true);+ if (!this.token) await this.pair();+ }+ async pair() {+ const body = JSON.stringify({ label: "OpenMausBot app (Cloud)", ttlSeconds: 300 });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${this.base}/api/cloud/pairing`, { method: "POST", headers: { ...FORWARDED, "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(this.secret, timestamp, nonce, body)}` }, body });+ const granted = await response.json() as { code: string };+ this.token = (await this.api("POST", "/api/auth/pair", { code: granted.code })).body.token;+ }+ /** What the Admin says, signed as it signs: which plan this Cloud is on. */+ async tellPlan(tier: string) {+ const body = JSON.stringify({ v: 1, tier }), timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${this.base}/api/cloud/plan`, { method: "POST", body, headers: { ...FORWARDED, "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudRequestSignature(this.secret, timestamp, nonce, "POST", "/api/cloud/plan", body)}` } });+ expect(response.status).toBe(200);+ }+ async bots() { return (await this.api("GET", "/api/bots?messages=0")).body.bots as any[]; }+ async config() { return (await this.api("GET", "/api/config")).body; }+ create(name: string) { return this.api("POST", "/api/bots", { name, modelSelection: CLAUDE, useDefaults: false }); }+ async fill(count: number, prefix = "Bot") {+ for (let i = 0; i < count; i++) {+ const made = await this.create(`${prefix} ${i + 1}`);+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ }+ }+ /** The capability of a real turn of this Cloud's Chief, for what the bot's own tools call. */+ async chiefTurn() {+ const chief = (await this.bots()).find((bot) => bot.chiefOfStaff);+ expect(chief, "a new Cloud's MausBot is its Chief").toBeTruthy();+ const sent = await this.api("POST", `/api/bots/${chief.id}/messages`, { text: "Add a specialist." });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await expect.poll(() => existsSync(this.dump), { timeout: 20_000 }).toBe(true);+ const agents = JSON.parse(readFileSync(this.dump, "utf8")).mcpConfig.mcpServers.agents;+ const env = agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env;+ return { chief, token: env.OMB_COMMS_TOKEN as string };+ }+ async internal(path: string, token: string, body: unknown) {+ const response = await fetch(`${this.base}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });+ return { status: response.status, body: await response.json() as any };+ }+ finishTurn() { writeFileSync(this.gate, "finish"); }+ async restart() {+ this.child!.kill("SIGTERM");+ await waitForExit(this.child!);+ await this.run();+ }+ async stop() {+ this.finishTurn();+ if (this.child && this.child.exitCode === null) { this.child.kill("SIGTERM"); await waitForExit(this.child); }+ await removeTempDir(this.home);+ }+}++const REFUSED = { status: 409, body: { code: "bot_limit" } };++describe("a Starter Cloud's bots, on a real server", () => {+ let cloud: Cloud;+ afterEach(async () => { await cloud?.stop(); });+ const starter = async (tier = "starter") => {+ cloud = new Cloud();+ await cloud.start();+ await cloud.tellPlan(tier);+ };++ it("makes five beside its MausBot, says so in config, then refuses each way of making one and writes nothing", async () => {+ await starter();+ expect(await cloud.config()).toMatchObject({ cloudStarter: true, botLimit: 5 });+ const mausBot = (await cloud.bots()).filter((bot) => bot.defaultBot);+ expect(mausBot).toHaveLength(1);+ await cloud.fill(5);+ const held = (await cloud.bots()).map((bot) => bot.id).sort();+ expect(held).toHaveLength(6);++ const refused = await cloud.create("Sixth");+ expect(refused).toMatchObject(REFUSED);+ expect(refused.body.error).toBe("You've reached the 5 bots Starter includes. To create more, upgrade this Cloud.");+ // What Duplicate and a paired device's New bot send.+ expect(await cloud.api("POST", "/api/bots", {})).toMatchObject(REFUSED);+ expect(await cloud.api("POST", "/api/teams/import?mode=add", manifest("Desk"))).toMatchObject(REFUSED);+ expect(await cloud.api("POST", "/api/teams/import?mode=add", PACKAGE)).toMatchObject(REFUSED);++ const { token, chief } = await cloud.chiefTurn();+ const tool = await cloud.internal("/api/internal/create-bot", token, { fromBotId: chief.id, fromThreadId: chief.threadId, name: "Scout", role: "Specialist", instructions: "Work." });+ expect(tool).toMatchObject(REFUSED);+ expect(tool.body.error).toContain("Explain this to the person");+ expect(tool.body.error).toContain("Do not retry");+ const setup = await cloud.internal("/api/internal/team-setup-requests", token, { plan: { reason: "Add a specialist", newTeams: [],+ operations: [{ action: "create", key: "scout", fields: { name: "Scout", title: "Specialist", soul: "Work.", modelSelection: CLAUDE } }] } });+ expect(setup).toMatchObject(REFUSED);+ expect(setup.body.error).toContain("Do not retry");++ expect((await cloud.bots()).map((bot) => bot.id).sort()).toEqual(held);+ }, 120_000);++ it("takes a move and a restore at the limit, and a bot moved in keeps its id and conversation", async () => {+ await starter();+ await cloud.fill(5);+ const backup = await cloud.api("POST", "/api/teams/export", { format: "backup", name: "Saved" });+ expect(backup.status, JSON.stringify(backup.body)).toBe(200);++ const moved = await cloud.api("POST", "/api/bots", { id: "from-the-laptop-1", threadId: "laptop-thread-1", name: "From the laptop", useDefaults: false });+ expect(moved.status, JSON.stringify(moved.body)).toBe(201);+ expect(moved.body.bot).toMatchObject({ id: "from-the-laptop-1", threadId: "laptop-thread-1" });+ const after = (await cloud.bots()).length;++ const restored = await cloud.api("POST", "/api/teams/import?mode=add", backup.body);+ expect(restored.status, JSON.stringify(restored.body)).toBe(201);+ expect(restored.body.bots.length).toBeGreaterThanOrEqual(6);+ expect((await cloud.bots()).length).toBe(after + restored.body.bots.length);++ // Over the limit now: every one stays, and a new one is still refused.+ expect(await cloud.create("One more")).toMatchObject(REFUSED);+ }, 120_000);++ it("keeps every bot of a downgraded Cloud, across a restart, and lifts the limit the moment it upgrades, with no restart", async () => {+ await starter("pro");+ expect((await cloud.config()).botLimit).toBeUndefined();+ await cloud.fill(7);+ const seven = (await cloud.bots()).map((bot) => bot.id).sort();++ await cloud.tellPlan("starter");+ expect(await cloud.config()).toMatchObject({ cloudStarter: true, botLimit: 5 });+ expect((await cloud.bots()).map((bot) => bot.id).sort()).toEqual(seven);+ expect(await cloud.create("New")).toMatchObject(REFUSED);++ await cloud.restart();+ expect((await cloud.bots()).map((bot) => bot.id).sort()).toEqual(seven);+ expect(await cloud.create("New")).toMatchObject(REFUSED);++ const pid = cloud.child!.pid;+ await cloud.tellPlan("pro");+ expect((await cloud.config()).botLimit).toBeUndefined();+ expect((await cloud.create("New")).status).toBe(201);+ expect(cloud.child!.pid).toBe(pid);+ }, 120_000);++ it("makes room when a bot is archived, and the MausBot never takes any", async () => {+ await starter();+ await cloud.fill(5);+ const one = (await cloud.bots()).find((bot) => !bot.defaultBot);+ expect((await cloud.api("PATCH", `/api/bots/${one.id}`, { hidden: true })).status).toBe(200);+ expect((await cloud.create("In its place")).status).toBe(201);+ expect(await cloud.create("And another")).toMatchObject(REFUSED);+ expect((await cloud.bots()).filter((bot) => !bot.hidden)).toHaveLength(6);+ }, 120_000);++ it.each([["max"], ["personal"], ["team"]])("has no such limit on %s", async (tier) => {+ await starter(tier);+ expect((await cloud.config()).botLimit).toBeUndefined();+ await cloud.fill(6);+ expect((await cloud.api("POST", "/api/teams/import?mode=add", manifest("Desk"))).status).toBe(201);+ }, 120_000);++ it("has no limit when the Admin never said a plan, whatever the machine", async () => {+ cloud = new Cloud();+ await cloud.start();+ expect(await cloud.config()).toMatchObject({ cloudStarter: false });+ expect((await cloud.config()).botLimit).toBeUndefined();+ await cloud.fill(6);+ expect(existsSync(join(cloud.dataDir, "cloud-plan-tier.json"))).toBe(false);+ }, 120_000);++ it("a Chief's create_bot works while there's room, up to the limit", async () => {+ await starter();+ await cloud.fill(4);+ if (existsSync(cloud.dump)) unlinkSync(cloud.dump);+ const { token, chief } = await cloud.chiefTurn();+ const made = await cloud.internal("/api/internal/create-bot", token, { fromBotId: chief.id, fromThreadId: chief.threadId, name: "Fifth", role: "Specialist", instructions: "Work." });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ expect(made.body).toMatchObject({ state: "applied", name: "Fifth" });+ const refused = await cloud.internal("/api/internal/create-bot", token, { fromBotId: chief.id, fromThreadId: chief.threadId, name: "Sixth", role: "Specialist", instructions: "Work." });+ expect(refused).toMatchObject(REFUSED);+ }, 120_000);+});diff --git a/server/team-setup-requests.test.ts b/server/team-setup-requests.test.tsindex 24507e7098..fef6350cbe 100644--- a/server/team-setup-requests.test.ts+++ b/server/team-setup-requests.test.ts@@ -1,3 +1,4 @@+import { createBotLimit } from "./host/starter-bot-limit.ts";import { describe, expect, it, vi } from "vitest";import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";@@ -9,7 +10,7 @@ import type { BotRecord, OptionCardData } from "./store.ts";import type { TeamSetupRequest, TeamSetupResult } from "../shared/team-setup.ts";import type { DirectApply } from "./direct-apply.ts";-function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean }>) {+function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean }>, plan: { starter: boolean } = { starter: false }) {const bots: BotRecord[] = [];const messages: Array<{ id: string; role?: string; card?: OptionCardData }> = [];const teams = ["", "Work", "Engineering", "Private"];@@ -47,7 +48,7 @@ function harness(caps?: Record<string, { driverKind: string; agentsMcp: booleanconst targetBusy = vi.fn((id: string, _sourceThreadId?: string) => Boolean(store.bot(id)?.busy));const validateChange = vi.fn();const canPersist = vi.fn((): { ok: true } | { ok: false; status: number; error: string } => ({ ok: true }));- const service = new TeamSetupRequestService({ store, teams: () => teams, maxBots: 100, hasTeamAuthority,+ const service = new TeamSetupRequestService({ store, teams: () => teams, maxBots: 100, hasTeamAuthority, botLimit: createBotLimit({ starter: () => plan.starter, bots: () => bots }),canPersist, ownsThread: () => sourceExists, targetBusy, deleteBot, autoApply, validateChange,validateModel: (selection, current) => {if (!({ claude: ["sonnet", "opus"], codex: ["gpt-fixture"] }[selection.instanceId]?.includes(selection.model))) return "Model is not in the current catalog";@@ -609,3 +610,64 @@ describe("MausBot's Chief-level team setup", () => {.toThrow(/Maus can't be deleted or archived/);});});++describe("a Starter Cloud's limit on bots", () => {+ const SELECTION = { instanceId: "claude", model: "sonnet" };+ const specialist = (key: string) => ({ action: "create", key, fields: { name: key, title: "Specialist", soul: "Work.", modelSelection: SELECTION, section: "Work" } });+ /** Clive and Ada are two; `others` more makes the count. */+ const full = (others: number, starter = true) => {+ const plan = { starter };+ const app = harness(undefined, plan);+ for (let i = 0; i < others; i++) app.bot(`Other${i}`);+ return { ...app, plan };+ };++ it("refuses a proposal at the limit with the words a bot acts on, and shows no card", () => {+ const app = full(3);+ expect(() => app.propose([specialist("Scout")])).toThrow(expect.objectContaining({ status: 409, code: "bot_limit", message: expect.stringContaining("Do not retry") }));+ expect(app.messages).toHaveLength(0);+ expect(app.apply).not.toHaveBeenCalled();+ });++ it("refuses a whole setup that doesn't fit: no bot of it is made", async () => {+ const app = full(2);+ app.autoApply.mockReturnValue({ source: "profile" } as never);+ await expect(app.submit([specialist("Scout"), specialist("Writer")])).rejects.toMatchObject({ status: 409, code: "bot_limit" });+ expect(app.apply).not.toHaveBeenCalled();+ expect(app.store.bots).toHaveLength(4);+ });++ it("takes a setup that fits", () => {+ const app = full(2);+ expect(app.propose([specialist("Scout")]).requestId).toBeTruthy();+ });++ it("at the limit still changes the bots it has", () => {+ const app = full(3);+ const proposal = app.propose([{ action: "update", botId: app.peer.id, fields: { title: "Lead" } }]);+ expect(proposal.requestId).toBeTruthy();+ });++ it("asks again when the person confirms, and tells them, not the bot", async () => {+ const app = full(2);+ const { requestId } = app.propose([specialist("Scout")]);+ app.bot("Late arrival");+ const answered = await app.resolve(requestId);+ expect(app.apply).not.toHaveBeenCalled();+ expect(answered?.result).toMatchObject({ state: "cancelled", error: "You've reached the 5 bots Starter includes. To create more, upgrade this Cloud." });+ });++ it("makes what was proposed on Starter once the plan is bigger", async () => {+ const app = full(2);+ const { requestId } = app.propose([specialist("Scout")]);+ app.bot("Late arrival");+ app.plan.starter = false;+ const answered = await app.resolve(requestId);+ expect(answered?.result).toMatchObject({ state: "applied" });+ });++ it("has no such limit on another plan", () => {+ const app = full(10, false);+ expect(app.propose([specialist("Scout")]).requestId).toBeTruthy();+ });+});diff --git a/server/team-setup-requests.ts b/server/team-setup-requests.tsindex 2a910a7318..5e5c169e32 100644--- a/server/team-setup-requests.ts+++ b/server/team-setup-requests.ts@@ -9,6 +9,7 @@ import { validateBotCwd } from "./bot-cwd.ts";import { UNDO_STALE, type DirectApply } from "./direct-apply.ts";import { harnessCapabilityLines, type DriverCapabilities } from "./harness-capabilities.ts";import { redactSecretsInText } from "./redact.ts"; import { chiefLevel } from "./chief-level.ts"; import { defaultBotRefusal } from "./default-bot.ts";+import type { BotLimit } from "./host/starter-bot-limit.ts";import type { BotRecord, OptionCardData } from "./store.ts";import type { TeamSetupFields, TeamSetupOperation, TeamSetupRequest, TeamSetupResult, TeamSetupUndo } from "../shared/team-setup.ts";@@ -35,7 +36,8 @@ const planSchema = z.object({export class TeamSetupError extends Error {readonly status: number;- constructor(message: string, status = 400) { super(message); this.status = status; }+ readonly code?: string;+ constructor(message: string, status = 400, code?: string) { super(message); this.status = status; this.code = code; }}/** Without `fields` (deletions) any drift cancels; with them it pins only the before-values the card showed, and authority is re-checked at confirm. */@@ -83,6 +85,7 @@ interface Options {driverCapabilities?(instanceId: string): DriverCapabilities | undefined;validateChange?(before: BotRecord, fields: TeamSetupFields): void;maxBots: number;+ botLimit?: Pick<BotLimit, "refusal">;ownsThread(botId: string, threadId: string): boolean;/** `request` only for a reviewed deletion; Undo of a creation deletes without one. */deleteBot(botId: string, revalidate: () => void, request?: TeamSetupRequest): Promise<void>;@@ -171,7 +174,10 @@ export class TeamSetupRequestService {const at = projected.findIndex((bot) => bot.id === operation.botId);if (at < 0) projected.push(next); else projected[at] = next;}- if (this.options.store.bots.length + request.operations.filter((op) => op.action === "create").length > this.options.maxBots) throw new TeamSetupError("This setup exceeds the workspace bot limit", 409);+ const creating = request.operations.filter((op) => op.action === "create").length;+ if (this.options.store.bots.length + creating > this.options.maxBots) throw new TeamSetupError("This setup exceeds the workspace bot limit", 409);+ const overPlan = this.options.botLimit?.refusal(creating, confirming && !immediate ? "person" : "bot");+ if (overPlan) throw new TeamSetupError(overPlan.error, 409, overPlan.code);for (const name of request.newTeams) if (!request.operations.some((op) => section(op.fields.section) === name)) throw new TeamSetupError(`New team ${JSON.stringify(name)} needs a specialist in this setup`);for (const operation of request.operations) {const candidate = projected.find((bot) => bot.id === operation.botId)!;diff --git a/shared/bot-limit.ts b/shared/bot-limit.tsnew file mode 100644index 0000000000..ffc1f2566d--- /dev/null+++ b/shared/bot-limit.ts@@ -0,0 +1,11 @@+import type { DefaultBotFields } from "./default-bot.ts";++/** The code on a refused creation, `409 { error, code }`: this plan has no room for it. `error` is plain text any client can show. */+export const BOT_LIMIT_CODE = "bot_limit";++export interface BotLimitRefusal { error: string; code: typeof BOT_LIMIT_CODE }++/** The bots a plan's limit counts. A place's MausBot comes with it; an archived bot or one that moved away isn't at work here. */+export function botsTowardLimit(bots: ReadonlyArray<Pick<DefaultBotFields, "defaultBot"> & { hidden?: boolean; movedTo?: unknown }>): number {+ return bots.filter((bot) => !bot.defaultBot && !bot.hidden && !bot.movedTo).length;+}diff --git a/src/App.tsx b/src/App.tsxindex 8d2027286b..b48a1940bb 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -28,6 +28,7 @@ import { NotificationRail, NotificationsPanel } from "@/components/Notificationsimport { useNotificationFeed } from "@/lib/notification-preferences";import { UpdateBanner } from "@/components/UpdateBanner";import { AppNotices } from "@/components/AppNotices";+import { BotLimitPopup } from "@/components/BotLimitPopup";import { CloudAsleepStrip } from "@/components/CloudAsleepStrip";import { LiveConnectionStrip } from "@/components/LiveConnectionStrip";import { CloudSendStrip } from "@/components/CloudSendStrip";@@ -313,6 +314,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {return (<div className={cn("flex h-full flex-col", framed && "bg-frame")}><WindowFrameBar />+ <BotLimitPopup />{!framed && strips}<div className="relative flex min-h-0 flex-1">{!calendarFocus && <buttondiff --git a/src/components/BotLimitPopup.test.ts b/src/components/BotLimitPopup.test.tsnew file mode 100644index 0000000000..86a1238131--- /dev/null+++ b/src/components/BotLimitPopup.test.ts@@ -0,0 +1,152 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ state: { config: { cloudHome: true, botLimit: 5 } as Record<string, unknown>, bots: [] as unknown[] } }));+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: vi.fn() }) }));+vi.mock("./Avatar", () => ({ MausAvatar: () => createElement("i", { "data-mark": "" }) }));+vi.mock("@/lib/app-links", async (original) => ({ ...await original<typeof import("@/lib/app-links")>(), openExternalLink: vi.fn(async () => {}) }));++import { botLimitShown, closeBotLimit, showBotLimit } from "@/lib/bot-limit";+import { openExternalLink } from "@/lib/app-links";+import { setLocale } from "@/lib/i18n";+import { BotLimitPopup } from "./BotLimitPopup";++const STARTER = { tier: "starter", resetsAt: 1, meters: [], upgrades: [{ tier: "pro", amount: 4900 }, { tier: "max", amount: 9900 }] };+const made = (count: number) => Array.from({ length: count }, (_, i) => ({ id: `b${i}` }));++let root: Root;+let host: HTMLElement;+const dialog = () => document.querySelector<HTMLElement>("[data-bot-limit-popup]");+const buttons = () => [...dialog()!.querySelectorAll("button")].map((node) => node.textContent?.trim() || node.getAttribute("aria-label"));+const press = (label: string, within: ParentNode = document) => act(async () => {+ [...within.querySelectorAll("button")].find((node) => node.textContent?.trim() === label || node.getAttribute("aria-label") === label)!.click();+});+const key = (name: string, init: KeyboardEventInit = {}) => act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true, ...init })); });++function bridge(snapshot: Record<string, unknown>) {+ return {+ state: vi.fn(async () => snapshot),+ manage: vi.fn(async () => {}),+ upgradePreview: vi.fn(async (plan: string) => ({ outcome: "preview", preview: { plan, trial: false, price: 4900, chargeNow: 3400, tax: 0 } })),+ upgrade: vi.fn(async (plan: string) => ({ outcome: "upgraded", tier: plan })),+ };+}+async function open(plan?: ReturnType<typeof bridge>) {+ (window as unknown as { ogb?: unknown }).ogb = plan ? { cloudPlan: plan } : undefined;+ await act(async () => { root.render(createElement(BotLimitPopup)); });+ await act(async () => { showBotLimit(); });+ await act(async () => {});+}++beforeEach(() => {+ setLocale("en");+ fixture.state = { config: { cloudHome: true, botLimit: 5 }, bots: made(5) };+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(async () => {+ await act(async () => { closeBotLimit(); root.unmount(); });+ host.remove();+ delete (window as unknown as { ogb?: unknown }).ogb;+});++describe("the bot limit popup", () => {+ it("shows nothing until something opens it", async () => {+ await act(async () => { root.render(createElement(BotLimitPopup)); });+ expect(dialog()).toBeNull();+ });++ it("says they've reached Starter's bots and offers the in-app upgrade, with its price", async () => {+ await open(bridge({ status: "paid", tier: "starter", usage: STARTER }));+ expect(dialog()!.getAttribute("aria-modal")).toBe("true");+ expect(dialog()!.querySelector("h2")?.textContent).toBe("You've reached Starter's 5 bots");+ expect(dialog()!.querySelector("p")?.textContent).toBe("To create more, upgrade this Cloud. Every bot you have stays as it is.");+ expect(buttons()).toEqual(["Upgrade to Pro · $49/month", "Not now", "Close"]);+ expect(document.activeElement?.textContent).toBe("Upgrade to Pro · $49/month");+ });++ it("goes through the usual preview and confirmation, and only the confirmation changes the plan", async () => {+ const plan = bridge({ status: "paid", tier: "starter", usage: STARTER });+ await open(plan);+ await press("Upgrade to Pro · $49/month");+ expect(plan.upgradePreview).toHaveBeenCalledExactlyOnceWith("pro", "app_usage");+ expect(plan.upgrade).not.toHaveBeenCalled();+ expect(dialog(), "the card steps aside for the confirmation").toBeNull();+ const confirm = document.querySelector('[role="alertdialog"]')!;+ expect(confirm.parentElement!.className).toContain("z-[80]");+ await press("Upgrade to Pro", confirm);+ expect(plan.upgrade).toHaveBeenCalledExactlyOnceWith("pro", "app_usage");+ expect(dialog()!.querySelector("h2")?.textContent).toBe("You're on Pro now. Your new allowances are ready.");+ expect(buttons()).toEqual(["Got it", "Close"]);+ await press("Got it");+ expect(botLimitShown()).toBe(false);+ });++ it("names what went wrong and stays open when the upgrade is refused", async () => {+ const plan = bridge({ status: "paid", tier: "starter", usage: STARTER });+ plan.upgradePreview.mockResolvedValue({ outcome: "refused", code: "rate_limited" } as never);+ await open(plan);+ await press("Upgrade to Pro · $49/month");+ expect(dialog()!.querySelector('[role="alert"]')).not.toBeNull();+ expect(botLimitShown()).toBe(true);+ });++ it("says the upgrade is going through in the minute before this Cloud hears of it", async () => {+ await open(bridge({ status: "paid", tier: "pro", usage: { ...STARTER, tier: "pro", upgrades: [{ tier: "max", amount: 9900 }] } }));+ expect(dialog()!.querySelector("h2")?.textContent).toBe("Your upgrade is going through. This can take a minute.");+ expect(buttons()).toEqual(["Got it", "Close"]);+ });++ it("a template too big for the room left says so, and doesn't claim the limit is reached", async () => {+ fixture.state = { config: { cloudHome: true, botLimit: 5 }, bots: made(4) };+ await open(bridge({ status: "paid", tier: "starter", usage: STARTER }));+ expect(dialog()!.querySelector("h2")?.textContent).toBe("That's more bots than Starter has room for");+ });++ it("in a browser tab, with no bridge, opens the Plan page", async () => {+ await open();+ expect(dialog()!.querySelector("p")?.textContent).toBe("To create more, upgrade this Cloud on its Plan page. Every bot you have stays as it is.");+ expect(buttons()).toEqual(["Open the Plan page", "Not now", "Close"]);+ await press("Open the Plan page");+ expect(openExternalLink).toHaveBeenCalledExactlyOnceWith("https://cloud.openmausbot.com/cloud");+ });++ it("on a person's other Cloud, which only reads its plan, opens its Plan page and closes", async () => {+ const plan = bridge({ status: "paid", tier: "starter" });+ await open(plan);+ expect(buttons()).toEqual(["Open the Plan page", "Not now", "Close"]);+ await press("Open the Plan page");+ expect(plan.manage).toHaveBeenCalledOnce();+ expect(botLimitShown()).toBe(false);+ });++ it.each([["Not now"], ["Close"]])("%s closes it, and the next press opens it again", async (label) => {+ await open(bridge({ status: "paid", tier: "starter", usage: STARTER }));+ await press(label);+ expect(dialog()).toBeNull();+ await act(async () => { showBotLimit(); });+ expect(dialog()).not.toBeNull();+ });++ it("Escape closes it, and Tab stays inside", async () => {+ await open(bridge({ status: "paid", tier: "starter", usage: STARTER }));+ await key("Tab");+ expect(document.activeElement?.textContent).toBe("Not now");+ await key("Tab", { shiftKey: true });+ await key("Tab", { shiftKey: true });+ expect(document.activeElement?.getAttribute("aria-label")).toBe("Close");+ await key("Escape");+ expect(botLimitShown()).toBe(false);+ });++ it("leaves Escape to the confirmation while it is open", async () => {+ await open(bridge({ status: "paid", tier: "starter", usage: STARTER }));+ await press("Upgrade to Pro · $49/month");+ await key("Escape");+ expect(botLimitShown()).toBe(true);+ expect(dialog(), "back to the card").not.toBeNull();+ });+});diff --git a/src/components/BotLimitPopup.tsx b/src/components/BotLimitPopup.tsxnew file mode 100644index 0000000000..241a7db593--- /dev/null+++ b/src/components/BotLimitPopup.tsx@@ -0,0 +1,100 @@+import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import { ArrowUpRight, X } from "lucide-react";+import { CLOUD_PLAN_URL } from "@/lib/app-links";+import { botRoom, closeBotLimit, useBotLimitOpen } from "@/lib/bot-limit";+import { cloudPlanLabel } from "@/lib/cloud-plan";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { useStore } from "@/state/store";+import { MausAvatar } from "./Avatar";+import { useCloudPlanSnapshot } from "./CloudTrialNotice";+import { NoteLine, UpgradeButton, usageBridge, useUpgrade } from "./CloudUsageMeter";+import { LinkButton, NotNowButton, PRIMARY_BUTTON } from "./NoticeCard";++const POPUP = "[data-bot-limit-popup]";+const TITLE = "bot-limit-title";+const BODY = "bot-limit-body";+/** Above every dialog a person can press a create button in, and the upgrade's confirmation with it. */+const LAYER = "z-[80]";++export function BotLimitPopup() {+ return useBotLimitOpen() ? <BotLimitDialog onClose={closeBotLimit} /> : null;+}++function BotLimitDialog({ onClose }: { onClose: () => void }) {+ const { state } = useStore();+ const bridge = usageBridge(state.config?.cloudHome === true);+ const plan = useCloudPlanSnapshot(bridge);+ const usage = plan?.status === "paid" ? plan.usage ?? null : null;+ const [upgraded, setUpgraded] = useState<string | null>(null);+ const [planFailed, setPlanFailed] = useState(false);+ const upgrade = useUpgrade(bridge, usage, "app_usage", setUpgraded, LAYER);+ const confirming = upgrade.confirming;+ // The Admin tells this Cloud about a new plan within a minute; until then the plan page and this Cloud disagree.+ const goingThrough = plan?.tier !== undefined && plan.tier !== "starter";+ const settled = upgraded !== null || goingThrough;+ const limit = state.config?.botLimit;+ const noRoom = limit !== undefined && botRoom(state) === 0;++ useEffect(() => {+ document.querySelector<HTMLElement>(`${POPUP} button`)?.focus();+ }, [plan === null, Boolean(usage), settled]);+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ const root = document.querySelector<HTMLElement>(POPUP);+ if (!root) return;+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ onClose();+ return;+ }+ if (event.key !== "Tab") return;+ event.preventDefault();+ event.stopPropagation();+ const controls = [...root.querySelectorAll<HTMLButtonElement>("button")].filter((button) => !button.disabled);+ const at = controls.indexOf(document.activeElement as HTMLButtonElement), step = event.shiftKey ? -1 : 1;+ controls[at === -1 ? (step > 0 ? 0 : controls.length - 1) : (at + step + controls.length) % controls.length]?.focus();+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ }, [onClose]);++ const title = upgraded ? t("usageMeter.done", { plan: cloudPlanLabel(upgraded) })+ : goingThrough ? t("usageMeter.pending")+ : noRoom ? t("botLimit.title", { count: limit }) : t("botLimit.titleTooMany");+ // A person's other Cloud reads its plan but upgrades on its Plan page; a browser tab or a paired device has no bridge at all.+ const inApp = Boolean(bridge && (usage || plan === null));++ return createPortal(<>+ {!confirming && (+ <div className={cn("ui-scrim fixed inset-0 flex items-center justify-center p-4 motion-reduce:animate-none", LAYER)}>+ <div role="dialog" aria-modal="true" aria-labelledby={TITLE} aria-describedby={settled ? undefined : BODY} data-bot-limit-popup=""+ className="ui-modal animate-pop-in relative flex w-[min(380px,calc(100vw-32px))] flex-col items-center border-0 px-6 pb-3 pt-8 text-center text-ink motion-reduce:animate-none">+ <div aria-hidden="true"><MausAvatar color="chrome" size={52} state="idle" animated={false} /></div>+ <h2 id={TITLE} className="mt-5 text-[19px] font-semibold leading-6 tracking-[-0.012em] [text-wrap:balance]">{title}</h2>+ {!settled && <p id={BODY} className="mt-1.5 text-[14px] leading-5 text-ink-secondary [text-wrap:pretty]">{t(inApp ? "botLimit.body" : "botLimit.bodyElsewhere")}</p>}+ {settled ? (+ <button type="button" onClick={onClose} className={cn(PRIMARY_BUTTON, "mt-5 w-full justify-center")}>{t("roomCard.gotIt")}</button>+ ) : usage ? (+ <div className="mt-5 w-full">+ <UpgradeButton usage={usage} upgrade={{ busy: upgrade.busy, note: upgrade.note, onUpgrade: upgrade.start }} className="w-full justify-center" />+ </div>+ ) : !bridge ? (+ <div className="mt-5 w-full [&>div]:w-full"><LinkButton url={CLOUD_PLAN_URL} label={t("botLimit.openPlan")} className={cn(PRIMARY_BUTTON, "w-full justify-center")} /></div>+ ) : plan !== null ? (+ <button type="button" className={cn(PRIMARY_BUTTON, "mt-5 w-full justify-center")} onClick={() => { setPlanFailed(false); void bridge.manage().then(onClose, () => setPlanFailed(true)); }}>+ {t("botLimit.openPlan")}<ArrowUpRight size={14} aria-hidden="true" />+ </button>+ ) : null}+ {planFailed && <p role="alert" className="mt-2 text-[12px] text-danger">{t("notice.openFailed")}</p>}+ {upgrade.note && !upgraded && <div className="mt-2"><NoteLine note={upgrade.note} /></div>}+ {!settled && <div className="mt-1"><NotNowButton onClick={onClose} /></div>}+ <button type="button" onClick={onClose} aria-label={t("common.close")} className="ui-icon-button absolute end-3 top-3"><X size={16} /></button>+ </div>+ </div>+ )}+ {upgrade.dialog}+ </>, document.body);+}diff --git a/src/components/CloudUsageMeter.tsx b/src/components/CloudUsageMeter.tsxindex d58d45cd36..653d7d746b 100644--- a/src/components/CloudUsageMeter.tsx+++ b/src/components/CloudUsageMeter.tsx@@ -99,7 +99,7 @@ export async function confirmUpgrade(bridge: CloudPlanBridge, preview: CloudUpgr}/** `onUpgraded`: the plan the person's Cloud is on now, once an upgrade went through. */-export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsage | null, source: UpgradeSource, onUpgraded?: (tier: string) => void) {+export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsage | null, source: UpgradeSource, onUpgraded?: (tier: string) => void, dialogLayer?: string) {const [busy, setBusy] = useState<"preview" | "change" | null>(null);const [preview, setPreview] = useState<CloudUpgradePreview | null>(null);const [note, setNote] = useState<UpgradeNote | null>(null);@@ -133,6 +133,7 @@ export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsagconfirmLabel={preview ? t("usageMeter.confirm.action", { plan: cloudPlanLabel(preview.plan) }) : ""}cancelLabel={t("usageMeter.confirm.cancel")}pending={busy === "change"}+ layer={dialogLayer}onCancel={() => { if (busy !== "change") setPreview(null); }}onConfirm={confirm}/>diff --git a/src/components/ConfirmDialog.tsx b/src/components/ConfirmDialog.tsxindex 93df57a63b..0300ac3406 100644--- a/src/components/ConfirmDialog.tsx+++ b/src/components/ConfirmDialog.tsx@@ -21,6 +21,8 @@ export interface ConfirmDialogProps {alternative?: { label: string; onClick: () => void };pending?: boolean;returnFocusRef?: RefObject<HTMLElement | null>;+ /** Where it sits among open dialogs, when another one above the usual layer asked it. */+ layer?: string;}/**@@ -76,7 +78,7 @@ export function ConfirmDialog(props: ConfirmDialogProps) {return createPortal(<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-6"+ className={`fixed inset-0 ${props.layer ?? "z-50"} flex items-center justify-center bg-black/55 p-6`}onMouseDown={(event) => event.target === event.currentTarget && onCancel()}><ConfirmDialogCard ref={dialogRef} cancelRef={cancelRef} {...props} />diff --git a/src/components/ReadyBotGallery.test.ts b/src/components/ReadyBotGallery.test.tsindex dd960b31a9..44100222a5 100644--- a/src/components/ReadyBotGallery.test.ts+++ b/src/components/ReadyBotGallery.test.ts@@ -4,11 +4,11 @@ import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const opened = vi.hoisted(() => ({ props: null as null | { readyBotId?: string; onClose?: () => void; onCreated?: (bot: { id: string }) => void }, dispatch: vi.fn() }));+const opened = vi.hoisted(() => ({ props: null as null | { readyBotId?: string; onClose?: () => void; onCreated?: (bot: { id: string }) => void }, dispatch: vi.fn(), state: { config: null, bots: [] } as { config: { botLimit?: number } | null; bots: object[] } }));vi.mock("./lazy-screens", () => ({NewBotDialog: (props: NonNullable<typeof opened.props>) => { opened.props = props; return null; },}));-vi.mock("@/state/store", () => ({ useStore: () => ({ dispatch: opened.dispatch }) }));+vi.mock("@/state/store", () => ({ useStore: () => ({ dispatch: opened.dispatch, state: opened.state }) }));const { ReadyBotGallery } = await import("./ReadyBotGallery");const { READY_BOTS } = await import("@/lib/ready-bots");@@ -30,6 +30,7 @@ beforeEach(() => {document.body.append(host);root = createRoot(host);opened.props = null;+ opened.state = { config: null, bots: [] };opened.dispatch.mockReset();onDialog.mockClear();onAdded.mockClear();@@ -87,4 +88,15 @@ describe("ready-made bots gallery", () => {expect(onDialog).toHaveBeenLastCalledWith(false);expect(onAdded).not.toHaveBeenCalled();});++ it("at Starter's limit opens the upgrade popup instead of a form to fill in", async () => {+ const { botLimitShown, closeBotLimit } = await import("@/lib/bot-limit");+ opened.state = { config: { botLimit: 5 }, bots: Array.from({ length: 5 }, () => ({})) };+ render();+ flushSync(() => button("Add Fern, Plant care log").click());+ expect(opened.props).toBeNull();+ expect(onDialog).not.toHaveBeenCalled();+ expect(botLimitShown()).toBe(true);+ closeBotLimit();+ });});diff --git a/src/components/ReadyBotGallery.tsx b/src/components/ReadyBotGallery.tsxindex 26beb41379..217702eeb2 100644--- a/src/components/ReadyBotGallery.tsx+++ b/src/components/ReadyBotGallery.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { createPortal } from "react-dom";import { Plus } from "lucide-react";+import { stoppedAtBotLimit } from "@/lib/bot-limit";import { MausAvatar } from "./Avatar";import { NewBotDialog } from "./lazy-screens";import { READY_BOT_CATEGORIES, READY_BOTS, matchesReadyBot, type ReadyBotCategory } from "@/lib/ready-bots";@@ -26,9 +27,10 @@ export function ReadyBotGallery({ search, onDialog, onAdded }: {onAdded: (bot: Bot) => void;}) {const [category, setCategory] = useState<ReadyBotCategory | null>(null);- const { dispatch } = useStore();+ const { state, dispatch } = useStore();const [adding, setAdding] = useState<string | null>(null);const open = (id: string | null) => {+ if (id !== null && stoppedAtBotLimit(state)) return;// A paired device may not read the host's New bot defaults that the review is filled from.if (id !== null && window.ogb?.remoteClient?.active) { dispatch({ type: "newBot", onCreated: onAdded }); return; }setAdding(id); onDialog(id !== null);diff --git a/src/lib/app-links.ts b/src/lib/app-links.tsindex f03946b02b..3f9f9e7294 100644--- a/src/lib/app-links.ts+++ b/src/lib/app-links.ts@@ -7,6 +7,7 @@ export const PASSKEY_HELP_URL = "https://docs.openmausbot.com/docs/troubleshootiexport const FEEDBACK_URL = "https://discord.gg/9Wb8MEpXRs";export const RELEASES_URL = `${APP_REPOSITORY}/releases`;export const PRICING_URL = "https://www.openmausbot.com/pricing";+export const CLOUD_PLAN_URL = "https://cloud.openmausbot.com/cloud";export function withSource(url: string, source: string): string {const target = new URL(url);target.searchParams.set("src", source);diff --git a/src/lib/bot-limit.test.ts b/src/lib/bot-limit.test.tsnew file mode 100644index 0000000000..5eb4e65fbf--- /dev/null+++ b/src/lib/bot-limit.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it } from "vitest";+import { botLimitShown, botRoom, closeBotLimit, isBotLimitRefusal, showBotLimit, stoppedAtBotLimit } from "./bot-limit";++afterEach(closeBotLimit);+const state = (botLimit: number | undefined, bots: Array<{ defaultBot?: object; hidden?: boolean; movedTo?: unknown }>) => ({ config: { botLimit }, bots });+const made = (count: number) => Array.from({ length: count }, () => ({}));++describe("how many more bots this plan makes", () => {+ it("has no answer on a plan without a limit, or before config has loaded", () => {+ expect(botRoom(state(undefined, made(50)))).toBeNull();+ expect(botRoom({ config: null, bots: made(50) })).toBeNull();+ });++ it("counts as the server does: not the MausBot, an archived bot, or one that moved away", () => {+ expect(botRoom(state(5, [{ defaultBot: {} }, { hidden: true }, { movedTo: { state: "moved" } }, {}]))).toBe(4);+ });++ it("is never below nothing on a Cloud over the limit", () => {+ expect(botRoom(state(5, made(9)))).toBe(0);+ });+});++describe("pressing a create button", () => {+ it("opens the popup instead when there is no room", () => {+ expect(stoppedAtBotLimit(state(5, made(5)))).toBe(true);+ expect(botLimitShown()).toBe(true);+ });++ it.each([[state(5, made(4))], [state(undefined, made(9))], [{ config: null, bots: [] }]])("goes on otherwise", (facts) => {+ expect(stoppedAtBotLimit(facts)).toBe(false);+ expect(botLimitShown()).toBe(false);+ });+});++describe("a refused request", () => {+ it("is known by its code, not its words", () => {+ expect(isBotLimitRefusal({ body: { code: "bot_limit", error: "anything" } })).toBe(true);+ for (const other of [{ body: { code: "thread_limit" } }, { body: {} }, new Error("bot_limit"), null, undefined]) expect(isBotLimitRefusal(other)).toBe(false);+ });++ it("opening twice and closing once closes it", () => {+ showBotLimit();+ showBotLimit();+ closeBotLimit();+ expect(botLimitShown()).toBe(false);+ });+});diff --git a/src/lib/bot-limit.ts b/src/lib/bot-limit.tsnew file mode 100644index 0000000000..0c38728623--- /dev/null+++ b/src/lib/bot-limit.ts@@ -0,0 +1,37 @@+import { useSyncExternalStore } from "react";+import { BOT_LIMIT_CODE, botsTowardLimit } from "../../shared/bot-limit";++let open = false;+const listeners = new Set<() => void>();+function setOpen(next: boolean): void {+ if (open === next) return;+ open = next;+ for (const listener of listeners) listener();+}++export const botLimitShown = () => open;+export const showBotLimit = () => setOpen(true);+export const closeBotLimit = () => setOpen(false);++export function useBotLimitOpen(): boolean {+ return useSyncExternalStore((listener) => { listeners.add(listener); return () => listeners.delete(listener); }, botLimitShown);+}++type LimitFacts = { config?: { botLimit?: number } | null; bots: Parameters<typeof botsTowardLimit>[0] };++/** How many more bots this plan makes; null when it has no such limit. */+export function botRoom(state: LimitFacts): number | null {+ const limit = state.config?.botLimit;+ return limit === undefined ? null : Math.max(0, limit - botsTowardLimit(state.bots));+}++/** A create button pressed with no room: the popup instead of a form to fill in. */+export function stoppedAtBotLimit(state: LimitFacts): boolean {+ if (botRoom(state) !== 0) return false;+ showBotLimit();+ return true;+}++export function isBotLimitRefusal(error: unknown): boolean {+ return (error as { body?: { code?: unknown } } | null | undefined)?.body?.code === BOT_LIMIT_CODE;+}diff --git a/src/lib/new-bot.test.ts b/src/lib/new-bot.test.tsindex bfadb9c6aa..8ffb21bc85 100644--- a/src/lib/new-bot.test.ts+++ b/src/lib/new-bot.test.ts@@ -47,6 +47,18 @@ beforeEach(() => { fixture.track.mockReset(); fixture.openBot.mockReset(); });afterEach(() => { vi.unstubAllGlobals(); setTeamPeople(null); setTeamChats(null); });describe("New bot", () => {+ it("leaves a plan's refusal to the popup: no error line beside it, and no onError", async () => {+ const onError = vi.fn();+ const request = vi.fn(async (path: string, init?: RequestInit) => {+ if (path === "/api/bot-defaults") return { defaults: { profile: {}, memory: {}, skills: [], routines: [] }, modelSelection: { instanceId: "claude", model: "sonnet" }, suggestedName: "Pixel" };+ if (init?.method === "POST") throw Object.assign(new Error("You've reached the 5 bots Starter includes."), { body: { code: "bot_limit" } });+ return {};+ });+ expect(await newBot(request as never, { onError })).toEqual([]);+ expect(onError).not.toHaveBeenCalled();+ expect(fixture.track).not.toHaveBeenCalled();+ });+it("makes a bot at once from the New bot defaults and opens its chat", async () => {const { calls, request, created } = server();const sent = await newBot(request);diff --git a/src/lib/new-bot.ts b/src/lib/new-bot.tsindex c55cd23051..b66a4e1acd 100644--- a/src/lib/new-bot.ts+++ b/src/lib/new-bot.ts@@ -5,6 +5,7 @@ import { currentTeamPeople, departmentOwner, type TeamPeople } from "@/state/teaimport { openBot } from "@/state/thread-navigation";import type { BotSource } from "./analytics-allowlist";import { BotCreationDraft } from "./bot-creation-draft";+import { isBotLimitRefusal } from "./bot-limit";import { createConfiguredBot } from "./create-configured-bot";import { t } from "./i18n";import { botCreated } from "./product-events";@@ -73,6 +74,7 @@ export async function makeNewBot(action: Extract<Action, { type: "newBot" }>, botry {made = await createNewBot(action.section, bots, currentTeamPeople(), request);} catch (cause) {+ if (isBotLimitRefusal(cause)) return;const message = t("newBot.failed", { error: cause instanceof Error ? cause.message : String(cause) });if (action.onError) action.onError(message);else dispatch({ type: "error", message });diff --git a/src/locales/de.json b/src/locales/de.jsonindex 69ff67dbcc..d97807ae6c 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -2556,6 +2556,11 @@"usageMeter.err.priceChanged": "Der Preis hat sich seit dem Ansehen geändert, es wurde nichts berechnet. Wähle Upgraden, um den neuen Preis zu sehen.","usageMeter.err.rateLimited": "Zu viele Versuche. Warte ein paar Minuten und versuch es dann erneut.","usageMeter.err.failed": "Wir konnten deinen Tarif nicht ändern. Es wurde nichts berechnet. Versuch es in einer Minute erneut.",+ "botLimit.title": "Du hast die {count} Bots von Starter erreicht",+ "botLimit.titleTooMany": "Das sind mehr Bots, als in Starter Platz haben",+ "botLimit.body": "Um weitere zu erstellen, stufe diese Cloud hoch. Alle deine Bots bleiben, wie sie sind.",+ "botLimit.bodyElsewhere": "Um weitere zu erstellen, stufe diese Cloud auf ihrer Tarifseite hoch. Alle deine Bots bleiben, wie sie sind.",+ "botLimit.openPlan": "Tarifseite öffnen","chat.compactionExcerptTitle": "Früherer Kontext auf aktuelle Auszüge gekürzt","chat.compactionExcerptHint": "Es gab keine geschriebene Zusammenfassung, deshalb macht der Agent mit diesen Auszügen und den letzten Nachrichten weiter. Ältere Details können in seinem Kontext fehlen. Dein ganzes Gespräch ist weiterhin hier.","chat.turnStoppedByYou": "Du hast das gestoppt.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 7686f3f943..2a96e90319 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7226,6 +7226,11 @@"roomCard.notNow": "Not now","roomCard.gotIt": "Got it","roomCard.done": "You're on {plan} now. This Cloud gets its new size the next time it's not busy.",+ "botLimit.title": "You've reached Starter's {count} bots",+ "botLimit.titleTooMany": "That's more bots than Starter has room for",+ "botLimit.body": "To create more, upgrade this Cloud. Every bot you have stays as it is.",+ "botLimit.bodyElsewhere": "To create more, upgrade this Cloud on its Plan page. Every bot you have stays as it is.",+ "botLimit.openPlan": "Open the Plan page","roomCard.restartNow": "Restart now","roomCard.restartHint": "Takes about a minute, and stops anything running now.","roomCard.restarting": "Restarting this Cloud with its new size. It's back in about a minute.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex aa3007af52..749bad70e0 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -5609,6 +5609,11 @@"usageMeter.err.priceChanged": "El precio cambió desde que lo viste, así que no se cobró nada. Elige Mejorar plan para ver el nuevo precio.","usageMeter.err.rateLimited": "Demasiados intentos. Espera unos minutos y vuelve a intentarlo.","usageMeter.err.failed": "No pudimos cambiar tu plan. No se cobró nada. Inténtalo de nuevo en un minuto.",+ "botLimit.title": "Has llegado a los {count} bots de Starter",+ "botLimit.titleTooMany": "Son más bots de los que caben en Starter",+ "botLimit.body": "Para crear más, mejora el plan de esta Cloud. Todos tus bots seguirán como están.",+ "botLimit.bodyElsewhere": "Para crear más, mejora el plan de esta Cloud en su página del plan. Todos tus bots seguirán como están.",+ "botLimit.openPlan": "Abrir la página del plan","voice.search": "Busca voces o pega un enlace","voice.noMatches": "Ninguna voz coincide","voice.noMatchesHint": "Prueba con otro nombre o pega un enlace a la voz.",diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.tsindex 6611462b05..8d0dbcb30d 100644--- a/src/locales/everyday-words.test.ts+++ b/src/locales/everyday-words.test.ts@@ -23,7 +23,7 @@ const EVERYDAY_PREFIXES: Record<string, readonly string[]> = {"MausBot Cloud: buying it, setting it up, moving to it and sharing with it": ["cloudBuy.", "cloudIntro.", "cloudTrial.", "cloudCancel.", "cloudSetup.", "cloudIntent.", "cloudNotice.", "cloudHowTo.", "whatsNew.","cloudCredit.", "cloudPower.", "cloudSignIn.", "cloudAdd.", "cloudHome.", "cloudPhone.", "cloudAccount.", "pro.", "lending.",- "files.", "usageMeter.", "roomCard.",+ "files.", "usageMeter.", "roomCard.", "botLimit.",],"routines and automations": ["routines.", "automations."],"the team map": ["canvas.", "mapComputer.", "canvasComputers."],diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex e35c88773f..b72eb63328 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -2528,6 +2528,11 @@"usageMeter.err.priceChanged": "Le prix a changé depuis que vous l'avez consulté, rien n'a donc été facturé. Choisissez Passer au forfait supérieur pour voir le nouveau prix.","usageMeter.err.rateLimited": "Trop d'essais. Attendez quelques minutes, puis réessayez.","usageMeter.err.failed": "Nous n'avons pas pu changer votre forfait. Rien n'a été facturé. Réessayez dans une minute.",+ "botLimit.title": "Vous avez atteint les {count} bots de Starter",+ "botLimit.titleTooMany": "C'est plus de bots que Starter ne peut en accueillir",+ "botLimit.body": "Pour en créer d'autres, passez ce Cloud au forfait supérieur. Tous vos bots restent tels quels.",+ "botLimit.bodyElsewhere": "Pour en créer d'autres, passez ce Cloud au forfait supérieur sur sa page Forfait. Tous vos bots restent tels quels.",+ "botLimit.openPlan": "Ouvrir la page Forfait","chat.compactionExcerptTitle": "Contexte antérieur réduit à des extraits récents","chat.compactionExcerptHint": "Aucun résumé rédigé n'était disponible : l'agent continue donc à partir de ces extraits et des messages récents. Des détails plus anciens peuvent manquer dans son contexte. Toute votre conversation est toujours là.","chat.turnStoppedByYou": "Vous l'avez arrêté.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 3330da0f9a..c98f5d0308 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -2528,6 +2528,11 @@"usageMeter.err.priceChanged": "आपके देखने के बाद कीमत बदल गई, इसलिए कुछ भी चार्ज नहीं हुआ। नई कीमत देखने के लिए अपग्रेड करें चुनें।","usageMeter.err.rateLimited": "बहुत ज़्यादा कोशिशें हुईं। कुछ मिनट रुकें, फिर दोबारा कोशिश करें।","usageMeter.err.failed": "हम आपका प्लान नहीं बदल पाए। कुछ भी चार्ज नहीं हुआ। एक मिनट बाद दोबारा कोशिश करें।",+ "botLimit.title": "आप Starter के {count} बॉट तक पहुँच गए हैं",+ "botLimit.titleTooMany": "ये Starter में जगह से ज़्यादा बॉट हैं",+ "botLimit.body": "और बनाने के लिए इस Cloud को अपग्रेड करें। आपके सभी बॉट जैसे हैं वैसे ही रहेंगे।",+ "botLimit.bodyElsewhere": "और बनाने के लिए इस Cloud को उसके प्लान पेज पर अपग्रेड करें। आपके सभी बॉट जैसे हैं वैसे ही रहेंगे।",+ "botLimit.openPlan": "प्लान पेज खोलें","chat.compactionExcerptTitle": "पिछला संदर्भ हाल के अंशों तक छोटा किया गया","chat.compactionExcerptHint": "लिखित सारांश उपलब्ध नहीं था, इसलिए एजेंट इन अंशों और हाल के संदेशों से आगे बढ़ता है। पुराने विवरण उसके संदर्भ से छूट सकते हैं। आपकी पूरी बातचीत अब भी यहीं है।","chat.turnStoppedByYou": "आपने इसे रोका।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex f336bdf68f..55b9b4cc09 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6254,6 +6254,11 @@"usageMeter.err.priceChanged": "Il prezzo è cambiato da quando l'hai visto, quindi non è stato addebitato nulla. Scegli Passa al piano superiore per vedere il nuovo prezzo.","usageMeter.err.rateLimited": "Troppi tentativi. Aspetta qualche minuto, poi riprova.","usageMeter.err.failed": "Non siamo riusciti a cambiare il piano. Non è stato addebitato nulla. Riprova tra un minuto.",+ "botLimit.title": "Hai raggiunto i {count} bot di Starter",+ "botLimit.titleTooMany": "Sono più bot di quanti Starter ne preveda",+ "botLimit.body": "Per crearne altri, passa questo Cloud a un piano superiore. Tutti i tuoi bot restano come sono.",+ "botLimit.bodyElsewhere": "Per crearne altri, passa questo Cloud a un piano superiore dalla pagina del piano. Tutti i tuoi bot restano come sono.",+ "botLimit.openPlan": "Apri la pagina del piano","inbox.from": "Da {name}","inbox.via": "tramite {name}","inbox.in": "in {title}",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 3c6fe3bc2d..793c99121f 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -6509,6 +6509,11 @@"usageMeter.err.priceChanged": "確認後に価格が変わったため、請求は発生していません。アップグレードを選んで新しい価格をご確認ください。","usageMeter.err.rateLimited": "試行回数が多すぎます。数分待ってから、もう一度お試しください。","usageMeter.err.failed": "プランを変更できませんでした。請求は発生していません。1 分後にもう一度お試しください。",+ "botLimit.title": "Starter の {count} 個のボットに達しました",+ "botLimit.titleTooMany": "Starter に入りきらない数のボットです",+ "botLimit.body": "さらに作成するには、この Cloud をアップグレードしてください。今あるボットはそのまま残ります。",+ "botLimit.bodyElsewhere": "さらに作成するには、プランページでこの Cloud をアップグレードしてください。今あるボットはそのまま残ります。",+ "botLimit.openPlan": "プランページを開く","approval.yourComputer.browserSite": "{site} にサインインしているあなたの {app} を使う必要があります。今回だけ許可しますか?","approval.yourComputer.browser": "サインインしているあなたの {app} を使う必要があります。今回だけ許可しますか?","approval.yourComputer.site": "{site} にサインインしているあなたのブラウザーを使う必要があります。今回だけ許可しますか?",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 14a9767c40..7d3d721088 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -6950,6 +6950,11 @@"usageMeter.err.priceChanged": "확인한 뒤로 가격이 바뀌어서 아무것도 청구되지 않았어요. 업그레이드를 눌러 새 가격을 확인하세요.","usageMeter.err.rateLimited": "시도 횟수가 너무 많아요. 몇 분 기다린 뒤 다시 시도하세요.","usageMeter.err.failed": "요금제를 바꾸지 못했어요. 청구된 금액은 없어요. 1분 뒤 다시 시도하세요.",+ "botLimit.title": "Starter의 봇 {count}개를 모두 만들었어요",+ "botLimit.titleTooMany": "Starter에 넣을 수 있는 봇보다 많아요",+ "botLimit.body": "더 만들려면 이 Cloud를 업그레이드하세요. 지금 있는 봇은 모두 그대로 남아요.",+ "botLimit.bodyElsewhere": "더 만들려면 요금제 페이지에서 이 Cloud를 업그레이드하세요. 지금 있는 봇은 모두 그대로 남아요.",+ "botLimit.openPlan": "요금제 페이지 열기","chat.setupCard.title": "무엇부터 도와드릴까요?","chat.setupCard.other": "다른 것","chat.setupCard.answer": "내 답변",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex e99002faec..98bccba1b8 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6383,6 +6383,11 @@"usageMeter.err.priceChanged": "Cena zmieniła się od chwili, gdy ją sprawdzono, więc nic nie zostało pobrane. Wybierz Zmień na wyższy plan, aby zobaczyć nową cenę.","usageMeter.err.rateLimited": "Zbyt wiele prób. Odczekaj kilka minut i spróbuj ponownie.","usageMeter.err.failed": "Nie udało się zmienić planu. Nic nie zostało pobrane. Spróbuj ponownie za minutę.",+ "botLimit.title": "Masz już {count} boty z planu Starter",+ "botLimit.titleTooMany": "To więcej botów, niż mieści plan Starter",+ "botLimit.body": "Aby utworzyć więcej, zmień plan tej chmury na wyższy. Wszystkie Twoje boty zostają bez zmian.",+ "botLimit.bodyElsewhere": "Aby utworzyć więcej, zmień plan tej chmury na wyższy na stronie planu. Wszystkie Twoje boty zostają bez zmian.",+ "botLimit.openPlan": "Otwórz stronę planu","voice.search": "Szukaj głosów lub wklej link","voice.noMatches": "Brak pasujących głosów","voice.noMatchesHint": "Spróbuj innej nazwy lub wklej link do głosu.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 7290786b5c..7d34a7fd24 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6288,6 +6288,11 @@"usageMeter.err.priceChanged": "O preço mudou desde que você viu, então nada foi cobrado. Escolha Fazer upgrade para ver o novo preço.","usageMeter.err.rateLimited": "Tentativas demais. Espere alguns minutos e tente de novo.","usageMeter.err.failed": "Não conseguimos mudar seu plano. Nada foi cobrado. Tente de novo em um minuto.",+ "botLimit.title": "Você chegou aos {count} bots do Starter",+ "botLimit.titleTooMany": "São mais bots do que cabem no Starter",+ "botLimit.body": "Para criar mais, faça upgrade desta Cloud. Todos os seus bots continuam como estão.",+ "botLimit.bodyElsewhere": "Para criar mais, faça upgrade desta Cloud na página do plano. Todos os seus bots continuam como estão.",+ "botLimit.openPlan": "Abrir a página do plano","voice.search": "Busque vozes ou cole um link","voice.noMatches": "Nenhuma voz corresponde","voice.noMatchesHint": "Tente outro nome ou cole um link para a voz.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 36f21208ea..c3eaf734f9 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -6478,6 +6478,11 @@"usageMeter.err.priceChanged": "Цена изменилась с момента просмотра, поэтому списаний не было. Нажмите «Улучшить», чтобы увидеть актуальную цену.","usageMeter.err.rateLimited": "Слишком много попыток. Подождите несколько минут и попробуйте снова.","usageMeter.err.failed": "Не удалось сменить тариф. Списаний не было. Попробуйте ещё раз через минуту.",+ "botLimit.title": "Вы достигли предела Starter: {count} ботов",+ "botLimit.titleTooMany": "Это больше ботов, чем помещается в Starter",+ "botLimit.body": "Чтобы создать ещё, перейдите на другой тариф для этого Cloud. Все ваши боты останутся как есть.",+ "botLimit.bodyElsewhere": "Чтобы создать ещё, смените тариф этого Cloud на странице тарифов. Все ваши боты останутся как есть.",+ "botLimit.openPlan": "Открыть страницу тарифов","composer.setupRequest.placeholder": "Напишите {name}, с чем нужна помощь","composer.setupRequest.waiting": "{name} готов к настройке","composer.setupRequest.cancel": "Остановить настройку {name}",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 014e35f861..249c2b9f88 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -4986,6 +4986,11 @@"usageMeter.err.priceChanged": "Fiyat siz baktıktan sonra değişti, bu yüzden hiçbir ücret alınmadı. Yeni fiyatı görmek için Yükselt'i seçin.","usageMeter.err.rateLimited": "Çok fazla deneme yapıldı. Birkaç dakika bekleyip yeniden deneyin.","usageMeter.err.failed": "Planınızı değiştiremedik. Hiçbir ücret alınmadı. Bir dakika sonra yeniden deneyin.",+ "botLimit.title": "Starter'ın {count} botuna ulaştınız",+ "botLimit.titleTooMany": "Bu, Starter'a sığacak bot sayısından fazla",+ "botLimit.body": "Daha fazla oluşturmak için bu Cloud'u yükseltin. Mevcut botlarınız olduğu gibi kalır.",+ "botLimit.bodyElsewhere": "Daha fazla oluşturmak için bu Cloud'u plan sayfasından yükseltin. Mevcut botlarınız olduğu gibi kalır.",+ "botLimit.openPlan": "Plan sayfasını aç","voice.search": "Ses arayın veya bağlantı yapıştırın","voice.noMatches": "Eşleşen ses yok","voice.noMatchesHint": "Başka bir ad deneyin veya sesin bağlantısını yapıştırın.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 14c34fd934..cc33941903 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -2973,6 +2973,11 @@"usageMeter.err.priceChanged": "Ціна змінилася відтоді, як ви її переглянули, тому нічого не списано. Виберіть «Покращити тариф», щоб побачити нову ціну.","usageMeter.err.rateLimited": "Забагато спроб. Зачекайте кілька хвилин і спробуйте знову.","usageMeter.err.failed": "Не вдалося змінити ваш тариф. Нічого не списано. Спробуйте знову за хвилину.",+ "botLimit.title": "Ви досягли межі Starter: {count} ботів",+ "botLimit.titleTooMany": "Це більше ботів, ніж вміщує Starter",+ "botLimit.body": "Щоб створити більше, покращте тариф цього Cloud. Усі ваші боти залишаться такими, як є.",+ "botLimit.bodyElsewhere": "Щоб створити більше, покращте тариф цього Cloud на сторінці плану. Усі ваші боти залишаться такими, як є.",+ "botLimit.openPlan": "Відкрити сторінку плану","chat.compactionExcerptTitle": "Попередній контекст скорочено до останніх уривків","chat.compactionExcerptHint": "Письмового підсумку не було, тож агент продовжує з цих уривків і останніх повідомлень. Давніших подробиць може бракувати в його контексті. Уся ваша розмова досі тут.","chat.turnStoppedByYou": "Ви це зупинили.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex a5dde251bb..087bf1a18f 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -4986,6 +4986,11 @@"usageMeter.err.priceChanged": "Giá đã thay đổi kể từ lúc bạn xem nên bạn không bị tính phí. Chọn Nâng cấp để xem giá mới.","usageMeter.err.rateLimited": "Bạn đã thử quá nhiều lần. Hãy đợi vài phút rồi thử lại.","usageMeter.err.failed": "Chúng tôi không thể đổi gói của bạn. Bạn không bị tính phí. Hãy thử lại sau một phút.",+ "botLimit.title": "Bạn đã dùng hết {count} bot của gói Starter",+ "botLimit.titleTooMany": "Số bot này nhiều hơn mức gói Starter cho phép",+ "botLimit.body": "Để tạo thêm, hãy nâng cấp Cloud này. Mọi bot bạn đang có vẫn giữ nguyên.",+ "botLimit.bodyElsewhere": "Để tạo thêm, hãy nâng cấp Cloud này trên trang Gói. Mọi bot bạn đang có vẫn giữ nguyên.",+ "botLimit.openPlan": "Mở trang Gói","voice.search": "Tìm giọng nói hoặc dán liên kết","voice.noMatches": "Không có giọng nói nào khớp","voice.noMatchesHint": "Hãy thử tên khác hoặc dán liên kết tới giọng nói.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 9438c47b31..fc47ab7bf2 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -4375,6 +4375,11 @@"usageMeter.err.priceChanged": "價格在你查看後有所變動,因此沒有收費。請選擇升級查看新價格。","usageMeter.err.rateLimited": "嘗試次數過多。請等幾分鐘後再試。","usageMeter.err.failed": "無法變更你的方案。沒有產生任何費用。請過一分鐘再試。",+ "botLimit.title": "你已達到 Starter 的 {count} 個機器人",+ "botLimit.titleTooMany": "這超過了 Starter 可容納的機器人數量",+ "botLimit.body": "如要建立更多,請升級這個 Cloud。你現有的機器人都會保持原樣。",+ "botLimit.bodyElsewhere": "如要建立更多,請在方案頁面升級這個 Cloud。你現有的機器人都會保持原樣。",+ "botLimit.openPlan": "開啟方案頁面","voice.search": "搜尋語音或貼上連結","voice.noMatches": "沒有符合的語音","voice.noMatchesHint": "請試試其他名稱,或貼上語音的連結。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 27f7877297..bd75eacf12 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7146,6 +7146,11 @@"roomCard.notNow": "以后再说","roomCard.gotIt": "知道了","roomCard.done": "你已升级到 {plan}。此 Cloud 会在下次空闲时获得新的容量。",+ "botLimit.title": "你已达到 Starter 的 {count} 个机器人",+ "botLimit.titleTooMany": "这超过了 Starter 可容纳的机器人数量",+ "botLimit.body": "如需创建更多,请升级这个 Cloud。你现有的机器人都会保持原样。",+ "botLimit.bodyElsewhere": "如需创建更多,请在方案页面升级这个 Cloud。你现有的机器人都会保持原样。",+ "botLimit.openPlan": "打开方案页面","roomCard.restartNow": "立即重启","roomCard.restartHint": "大约需要一分钟,并且会停止当前正在运行的任务。","roomCard.restarting": "正在以新容量重启此 Cloud,大约一分钟后恢复。",diff --git a/src/state/api.ts b/src/state/api.tsindex a667320a26..8cc5d83614 100644--- a/src/state/api.ts+++ b/src/state/api.ts@@ -2,6 +2,7 @@// (src/lib/cloud-power.ts), and a page out of sight sends none at all.import { asleepAnswer, BACKGROUND_HEADER, cloudAsleep, markCloudAsleep, markCloudAwake, pageHidden, pageShown } from "../lib/cloud-power";import { lacksAdminScope } from "../lib/admin-scope";+import { isBotLimitRefusal, showBotLimit } from "../lib/bot-limit";import { noteRefusedRequest } from "../lib/session-ended";export class ApiError extends Error {@@ -48,6 +49,7 @@ export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {const message = typeof error === "string" ? error : typeof error?.message === "string" ? error.message : `${res.status} ${res.statusText}`;const refused = new ApiError(message, res.status, body);if (res.status === 401 || (res.status === 403 && !lacksAdminScope(refused))) noteRefusedRequest();+ if (res.status === 409 && isBotLimitRefusal(refused)) showBotLimit();throw refused;}return body;diff --git a/src/state/bot-limit-actions.test.ts b/src/state/bot-limit-actions.test.tsnew file mode 100644index 0000000000..161368b035--- /dev/null+++ b/src/state/bot-limit-actions.test.ts@@ -0,0 +1,151 @@+// @vitest-environment happy-dom+import { createElement, type Dispatch } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Action, AppState, BotAnnouncement } from "./store";++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const botNamed = (id: string, extra: Partial<BotAnnouncement> = {}): BotAnnouncement => ({+ id, threadId: `${id}-thread`, name: id, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "fake", model: "m" }, tasks: [{ threadId: `${id}-thread`, title: "Thread", createdAt: 1 }], messages: [], ...extra,+});+const REFUSED = { error: "You've reached the 5 bots Starter includes. To create more, upgrade this Cloud.", code: "bot_limit" };+const json = (body: unknown, status = 200) => Promise.resolve(new Response(JSON.stringify(body), { status }));++const { StoreProvider, useStore } = await import("./store");+const { api, ApiError } = await import("./api");+const { botLimitShown, closeBotLimit } = await import("@/lib/bot-limit");++let seen!: AppState;+let dispatch!: Dispatch<Action>;+function Probe() {+ ({ state: seen, dispatch } = useStore());+ return null;+}+let root: Root;+let container: HTMLElement;+let creates: number;+let created: () => Promise<Response>;+const settle = async () => { for (let i = 0; i < 8; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };++async function mount(bots: BotAnnouncement[], config: Record<string, unknown>) {+ FixtureEventSource.opened = [];+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {+ if (path.startsWith("/api/bots?")) return json({ bots, groups: [] });+ if (path === "/api/config") return json(config);+ if (path === "/api/instances") return json({ instances: [] });+ if (path.startsWith("/api/routines")) return json({ routines: [], runs: [] });+ if (path.startsWith("/api/webhooks")) return json({ webhooks: [], attempts: [] });+ if (path === "/api/bot-defaults") return json({ defaults: { profile: {}, memory: {}, skills: [], routines: [] }, modelSelection: { instanceId: "fake", model: "m" }, suggestedName: "Scout" });+ if (path === "/api/bots" && init?.method === "POST") { creates += 1; return created(); }+ return json({});+ });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ expect(seen.bots).toHaveLength(bots.length);+ expect(seen.config).toMatchObject(config);+}+/** Sends it and waits for New bot or Duplicate to have finished asking, so nothing it sends lands in the next test. */+const send = async (action: Action) => {+ flushSync(() => dispatch(action));+ await settle();+ await vi.waitFor(() => expect(seen.botCreationPending).toBe(false));+ await settle();+};+const five = () => Array.from({ length: 5 }, (_, i) => botNamed(`b${i}`));+const STARTER = { cloudStarter: true, botLimit: 5 };++beforeEach(() => {+ creates = 0;+ created = () => json(REFUSED, 409);+ closeBotLimit();+});+afterEach(async () => {+ root?.unmount();+ container?.remove();+ vi.unstubAllGlobals();+});++describe("a create button with no room", () => {+ it.each<[string, Action]>([["New bot", { type: "newBot" }], ["Duplicate", { type: "duplicateBot", botId: "b0" }]])("%s opens the popup and asks the server nothing", async (_name, action) => {+ await mount(five(), STARTER);+ await send(action);+ expect(botLimitShown()).toBe(true);+ expect(creates).toBe(0);+ expect(seen.error).toBeNull();+ });++ it("leaves the MausBot out of the count, as the server does", async () => {+ await mount([botNamed("maus", { defaultBot: {} } as never), ...five().slice(1)], STARTER);+ created = () => json({ bot: botNamed("new") }, 201);+ await send({ type: "newBot" });+ await vi.waitFor(() => expect(creates).toBe(1));+ expect(botLimitShown()).toBe(false);+ });++ it("goes straight on the moment the plan is bigger, with nothing reloaded", async () => {+ await mount(five(), STARTER);+ FixtureEventSource.opened[0]!.send({ kind: "config", ...seen.config, cloudStarter: false, botLimit: undefined }, "run:1");+ await settle();+ created = () => json({ bot: botNamed("new") }, 201);+ await send({ type: "newBot" });+ await vi.waitFor(() => expect(creates).toBe(1));+ expect(botLimitShown()).toBe(false);+ });++ it("has no limit on a plan that doesn't say one", async () => {+ await mount(five(), { cloudStarter: false });+ created = () => json({ bot: botNamed("new") }, 201);+ await send({ type: "newBot" });+ await vi.waitFor(() => expect(creates).toBe(1));+ expect(botLimitShown()).toBe(false);+ });+});++describe("the server's refusal, when the page's count was stale", () => {+ it.each<[string, Action]>([["New bot", { type: "newBot" }], ["Duplicate", { type: "duplicateBot", botId: "b1" }]])("%s shows the popup and no error beside it", async (_name, action) => {+ await mount(five().slice(1), STARTER);+ await send(action);+ await vi.waitFor(() => expect(botLimitShown()).toBe(true));+ expect(creates).toBe(1);+ expect(seen.error).toBeNull();+ });++ it("any other refusal is still an error", async () => {+ await mount(five().slice(1), STARTER);+ created = () => json({ error: "this workspace is limited to 100 bots" }, 409);+ await send({ type: "duplicateBot", botId: "b1" });+ await vi.waitFor(() => expect(seen.error).toBe("this workspace is limited to 100 bots"));+ expect(botLimitShown()).toBe(false);+ });++ it("opens the popup from any request, and leaves the rest to whoever asked", async () => {+ await mount([], {});+ vi.stubGlobal("fetch", () => json(REFUSED, 409));+ await expect(api("/api/teams/import?mode=add", { method: "POST" })).rejects.toBeInstanceOf(ApiError);+ expect(botLimitShown()).toBe(true);+ });++ it.each<[Record<string, unknown>, number]>([[{ error: "busy", code: "thread_busy" }, 409], [{ error: "no", code: "bot_limit" }, 500]])("leaves %j (%i) alone", async (body, status) => {+ await mount([], {});+ vi.stubGlobal("fetch", () => json(body, status));+ await expect(api("/api/bots", { method: "POST" })).rejects.toBeInstanceOf(ApiError);+ expect(botLimitShown()).toBe(false);+ });+});diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex b3d56628b0..ecba1490fe 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -55,6 +55,8 @@ export interface ConfigStatus {newBots?: { effort?: EffortLevel };/** This Cloud is on the Starter plan, as the Admin last said; absent or false otherwise. */cloudStarter?: boolean;+ /** The most bots this Cloud's plan makes, its MausBot aside; absent when its plan has no such limit. */+ botLimit?: number;threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };automaticRecovery?: { enabled: boolean; backup?: ModelSelection };/** Prompt-cache keep-warm for idle Claude threads. Absent from older servers. */diff --git a/src/state/store.tsx b/src/state/store.tsxindex c977bf6ff9..e48d1a8a0e 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -34,7 +34,7 @@ import type { ModelVariantOption, RuntimeEvent } from "../../shared/runtime-evenimport type { MausColor, MausMotion } from "@/lib/mascot";import type { BotAvatarCrop } from "../../shared/bot-avatar";import { approvalModeFor, type ApprovalMode } from "../../shared/approval-mode";-import { askResetBridge, desktopCapabilitiesNow } from "@/lib/desktop";+import { askResetBridge, desktopCapabilitiesNow } from "@/lib/desktop"; import { isBotLimitRefusal, stoppedAtBotLimit } from "@/lib/bot-limit";import { sameModelSelection } from "../../shared/thread-model";import type { BotBodyId } from "../../shared/bot-body";import { StoreRefContext } from "./store-ref-context";@@ -2160,7 +2160,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const newTaskOnce = createNewTaskOnce();let creatingBot = false;const showError = (e: unknown) => {- rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });+ if (!isBotLimitRefusal(e)) rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });};const showSavedState = (owner: SavedOwner) => (error: unknown) => {showError(error);@@ -2604,7 +2604,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {}break;}- case "newBot": {+ case "newBot": { if (stoppedAtBotLimit(stateRef.current)) break;// A double click lands before React paints the pending state.if (creatingBot || stateRef.current.botCreationPending) break;creatingBot = true;@@ -2618,7 +2618,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {});break;}- case "duplicateBot": {+ case "duplicateBot": { if (stoppedAtBotLimit(stateRef.current)) break;const source = stateRef.current.bots.find((b) => b.id === action.botId);if (!source) break;const duplicateProfile = duplicateBotProfile(source);