Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Starter makes any number of bots, keeping five awake (#5298)
Milind Soni956a23691513
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 8bb509639f..c0209348e1 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1178,16 +1178,24 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):signed `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,and a teammate's hand-off never takes that one thread from the person.-- **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.+- **How many bots a Starter Cloud makes and keeps awake.** Any number; five of them,+ beside its MausBot and its Chief of Staff, take turns (`STARTER_AWAKE_LIMIT` in+ `server/host/starter-awake.ts`), from the same signed plan, and the rest are paused with+ everything they know kept. An archived bot or one that moved away isn't counted. The awake+ set is written down (`starter-awake.json`) while every bot still fits, so a bot made past+ the five starts paused and never pushes out one the person was using: `POST /api/bots`+ answers it with `"paused": true`, and the app opens **Keep these awake** with the new bot+ chosen in place of the least recently active one that isn't working (`POST /api/starter/awake`).+ A Chief's `create_bot` answers with a `paused` line for the person. A restore or a move into a+ Cloud that never wrote a set down wakes the most recently active. A paused bot's turn answers+ `409` `{"code":"bot_paused"}`, a hand-off to it is refused, a routine or webhook run for it+ fails at once with that line (no conversation is made, and it never wakes a sleeping Cloud),+ and its daily memory upkeep waits. Every bot wakes as soon as the Admin tells the home its new+ plan, with no restart. An older server refuses a sixth bot with `409` `{"code":"bot_limit"}`;+ the app still shows its upgrade popup for that. Every plan holds at most 100 bots+ (`MAX_WORKSPACE_BOTS`), counted on `POST /api/bots`, a package import and a Chief's setup.+- **How much a Starter Cloud runs at once.** Two turns Cloud-wide, and four hand-offs waiting+ beyond them; past that a new hand-off is refused (`server/host/starter-caps.ts`).- **Who goes first.** The gate only changes the order, never how much it lets in. Aperson's own work goes first: their line, or a turn going on from what they answered.Bot work that has waited 5 minutes takes its place by arrival, so it is never starveddiff --git a/server/host/starter-awake.test.ts b/server/host/starter-awake.test.tsindex 2905a13c33..10492773dc 100644--- a/server/host/starter-awake.test.ts+++ b/server/host/starter-awake.test.ts@@ -51,6 +51,40 @@ describe("which of a Starter Cloud's bots stay awake", () => {expect(createStarterAwake({ dataDir: dir, starter: () => true, bots: () => bots(7) }).paused()).toEqual(["b0", "b1"]);});+ it("starts a sixth bot and a twentieth paused, and never pauses one the person was using to make room", () => {+ const dir = dataDir(), list = bots(4);+ const awake = createStarterAwake({ dataDir: dir, starter: () => true, bots: () => list });+ const make = (id: string) => { list.unshift({ id, createdAt: Date.now(), tasks: [{ updatedAt: Date.now() }] }); return awake.paused(); };+ expect(make("fifth")).toEqual([]);+ expect(make("sixth")).toEqual(["sixth"]);+ for (let n = 7; n <= 20; n++) make(`bot${n}`);+ expect(awake.paused()).toHaveLength(15);+ expect(awake.paused()).toEqual(expect.arrayContaining(["sixth", "bot7", "bot20"]));+ expect(new Set(list.map((bot) => bot.id).filter((id) => !awake.isPaused(id)))).toEqual(new Set(["b0", "b1", "b2", "b3", "fifth"]));+ // A restart reads the same five.+ expect(createStarterAwake({ dataDir: dir, starter: () => true, bots: () => list }).paused()).toHaveLength(15);+ });++ it("swaps a new bot in for one the person picks, keeping five awake", () => {+ const list = bots(5);+ const awake = createStarterAwake({ dataDir: dataDir(), starter: () => true, bots: () => list });+ expect(awake.paused()).toEqual([]);+ list.unshift({ id: "new", createdAt: Date.now() });+ expect(awake.paused()).toEqual(["new"]);+ expect(awake.choose(["new", "b1", "b2", "b3", "b4"])).toEqual({ ok: true });+ expect(awake.paused()).toEqual(["b0"]);+ });++ it("gives a freed place to a bot already paused, not to the next one made", () => {+ const list = bots(5);+ const awake = createStarterAwake({ dataDir: dataDir(), starter: () => true, bots: () => list });+ awake.paused();+ list.unshift({ id: "sixth", createdAt: Date.now() });+ expect(awake.paused()).toEqual(["sixth"]);+ list.splice(list.findIndex((bot) => bot.id === "b2"), 1);+ expect(awake.paused()).toEqual([]);+ });+it("wakes every bot at once on an upgrade", () => {let starter = true;const awake = createStarterAwake({ dataDir: dataDir(), starter: () => starter, bots: () => bots(9) });diff --git a/server/host/starter-awake.ts b/server/host/starter-awake.tsindex 19ce0ace72..535ee88d94 100644--- a/server/host/starter-awake.ts+++ b/server/host/starter-awake.ts@@ -1,16 +1,18 @@-// Which of a Starter Cloud's bots stay awake. A restore or a move brings every bot whatever the plan, so past its limit the-// bots are all kept but only that many take turns; the rest are paused until the person swaps them in or upgrades. The set-// is written down the first time it is needed, so a paused bot that receives a message never pushes an awake one out.+// Which of a Starter Cloud's bots stay awake. Starter makes as many bots as the person likes, but only this many take turns;+// the rest are paused until the person swaps them in or upgrades. The awake set is written down while every bot still fits,+// so a bot made past the limit starts paused and never pushes out one the person was using, and a paused bot that receives+// a message never does either. A restore or a move into a Cloud that never wrote one down wakes the most recently active.import { readFileSync } from "node:fs";import { join } from "node:path";import { z } from "zod";import { botsTowardLimit } from "../../shared/bot-limit.ts";import { writeFileAtomic } from "../atomic.ts";-import { STARTER_BOT_LIMIT } from "./starter-bot-limit.ts";+/** How many bots a Starter Cloud keeps awake, not counting its MausBot or chief of staff. The one number to change. */+export const STARTER_AWAKE_LIMIT = 5;export const STARTER_AWAKE_FILE = "starter-awake.json";-const fileSchema = z.object({ v: z.literal(1), awake: z.array(z.string().min(1).max(200)).max(STARTER_BOT_LIMIT) });+const fileSchema = z.object({ v: z.literal(1), awake: z.array(z.string().min(1).max(200)).max(STARTER_AWAKE_LIMIT) });type CountedBot = Parameters<typeof botsTowardLimit>[0][number];export type AwakeBot = CountedBot & { id: string; chiefOfStaff?: boolean; createdAt?: number; tasks?: ReadonlyArray<{ updatedAt?: number }> };@@ -47,11 +49,15 @@ export function createStarterAwake(deps: { dataDir: string; starter(): boolean;};/** The bots the limit counts, the chief of staff aside: it hands out the work, so it never sleeps. */const candidates = () => deps.bots().filter((bot) => botsTowardLimit([bot]) === 1 && !bot.chiefOfStaff);- const limit = () => (deps.starter() ? STARTER_BOT_LIMIT : undefined);+ const limit = () => (deps.starter() ? STARTER_AWAKE_LIMIT : undefined);const awake = (): Set<string> | null => {const most = limit(), bots = candidates();- if (most === undefined || bots.length <= most) return null;+ if (most === undefined) return null;const ids = new Set(bots.map((bot) => bot.id));+ if (bots.length <= most) {+ if (chosen?.length !== ids.size || chosen.some((id) => !ids.has(id))) save([...ids]);+ return null;+ }const kept = (chosen ?? []).filter((id) => ids.has(id));if (kept.length < most) {const rest = bots.filter((bot) => !kept.includes(bot.id)).sort((a, b) => lastActive(b) - lastActive(a));diff --git a/server/host/starter-bot-limit.test.ts b/server/host/starter-bot-limit.test.tsdeleted file mode 100644index 758652b74a..0000000000--- a/server/host/starter-bot-limit.test.ts+++ /dev/null@@ -1,98 +0,0 @@-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.tsdeleted file mode 100644index 9e7c162006..0000000000--- a/server/host/starter-bot-limit.ts+++ /dev/null@@ -1,42 +0,0 @@-// 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/host/starter-caps.test.ts b/server/host/starter-caps.test.tsindex 475385a075..ad881c7abf 100644--- a/server/host/starter-caps.test.ts+++ b/server/host/starter-caps.test.ts@@ -39,6 +39,15 @@ describe("how much work a Starter Cloud runs at once", () => {expect(made.pausedText("awake", "de")).toBeNull();});+ it("tells a bot that made a paused one, without refusing anything or opening the popup", () => {+ const { made, refusals } = caps({ paused: ["scout"] });+ expect(made.createdPaused("scout")).toMatch(/^@scout was created, and is paused: this Cloud's Starter plan keeps 5 bots awake/);+ expect(made.createdPaused("scout")).not.toMatch(/upgrade this Cloud to create|no room/);+ expect(made.createdPaused("awake")).toBeNull();+ expect(caps({ starter: false, paused: ["scout"] }).made.createdPaused("scout")).toBeNull();+ expect([refusals(), made.status()?.refused]).toEqual([0, undefined]);+ });+it("refuses nothing off Starter", () => {const { made, refusals } = caps({ starter: false, paused: ["sleepy"] });expect(made.handoffs.refusal("sleepy", () => 100)).toBeNull();diff --git a/server/host/starter-caps.ts b/server/host/starter-caps.tsindex 4a73fad5ae..ef18ffe6b7 100644--- a/server/host/starter-caps.ts+++ b/server/host/starter-caps.ts@@ -18,6 +18,8 @@ export interface StarterCaps {status(): { running: number; waiting: number; refusedAt?: number; refused?: PlanLimitReason } | undefined;/** The words a paused bot's turn is refused with, in the person's language; null when the bot is awake. */pausedText(botId: string, language: string | undefined): string | null;+ /** What a bot that just made this one is told when it starts paused; null when it is awake. */+ createdPaused(botId: string): string | null;}export function createStarterCaps(deps: {@@ -55,6 +57,11 @@ export function createStarterCaps(deps: {},},status: () => (deps.starter() ? { running: STARTER_RUNNING_TURNS, waiting: STARTER_WAITING_HANDOFFS, ...(last ? { refusedAt: last.at, refused: last.reason } : {}) } : undefined),+ createdPaused(botId) {+ if (!deps.starter() || !deps.awake.isPaused(botId)) return null;+ return `@${deps.botName(botId) ?? "The new bot"} was created, and is paused: this Cloud's Starter plan keeps ${deps.awake.limit()} bots awake, so it takes no work yet. `+ + "Tell the person in one line: they can choose which bots stay awake, or upgrade this Cloud to wake them all. Do not hand it work until then.";+ },pausedText(botId, language) {return deps.starter() && deps.awake.isPaused(botId) ? deps.pausedLine(language, deps.awake.limit() ?? 0) : null;},diff --git a/server/index.ts b/server/index.tsindex d0723dcff7..2b18062d60 100644--- a/server/index.ts+++ b/server/index.ts@@ -118,7 +118,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 { BOT_LIMIT_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotLimit } from "./host/starter-bot-limit.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";+import { BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.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";@@ -2743,7 +2743,7 @@ function packageImportDeps(selection: ModelSelection): PackageImportDeps {return avatarUrl;},},- defaultSelection: () => selection, botLimit,+ defaultSelection: () => selection, maxBots: MAX_WORKSPACE_BOTS,presets: presetStore,};}@@ -2837,7 +2837,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() }) }); const botLimit = createBotLimit({ starter: () => cloudPlanTier.starter(), bots: () => store.bots }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); 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 starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); 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: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),@@ -5115,7 +5115,7 @@ const setupSuggestions = setupSuggestionsFor({ store, config: () => cfg, shared:withinBudget: () => { try { assertWithinBudget(cfg, DATA_DIR); return true; } catch { return false; } }, writer: (botId) => sideJobs.text("setup-suggestions", botId), apps: { configured: () => composio.configured(cfg), mode: () => composio.connectionMode(cfg), connected: () => composio.connectedServices(cfg) }, log: (line) => console.log(line) });const memoryUpkeep = createMemoryUpkeep({- bots: () => store.bots,+ bots: () => { const paused = new Set(starterAwake.paused()); return store.bots.filter((bot) => !paused.has(bot.id)); },bot: (id) => store.bot(teamHost.baseBotId(id)) ?? undefined,engine: (botId) => sideJobs.text("memory", teamHost.baseBotId(botId)),busy: (botId) => botHasActiveTurn(teamHost.baseBotId(botId)),@@ -8780,7 +8780,7 @@ routines = new RoutineManager({skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined,- botState: unattendedDispatchState,+ botState: unattendedDispatchState, pausedText: (botId) => starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")),goalState: (groupId, coordinatorBotId) => {if (!groupId) return unattendedDispatchState(coordinatorBotId);const group = store.group(groupId);@@ -9253,7 +9253,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, botLimit,+ store, teams: teamSetupTeams, hasTeamAuthority, canPersist: proposalPersistence, maxBots: MAX_WORKSPACE_BOTS,autoApply: appliesDirectly,validateChange: (before, fields) => assertTeamComputerChangeIdle(before, { ...before, ...fields }),ownsThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)),@@ -11725,7 +11725,7 @@ function configStatus() {const eventLogMaxBytes = threadEventLogMaxBytes(cfg);const eventLogRetentionDays = threadEventLogRetentionDays(cfg);return {- cloudStarter: cloudPlanTier.starter(), botLimit: botLimit.limit(), waitingForRoom: engineMemory.waiting(), planTurns: starterCaps.status(), awakeLimit: starterAwake.limit(), pausedBots: starterAwake.paused(), xai: keyStatus(cfg.xai?.key),+ cloudStarter: cloudPlanTier.starter(), waitingForRoom: engineMemory.waiting(), planTurns: starterCaps.status(), awakeLimit: starterAwake.limit(), pausedBots: starterAwake.paused(), 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),@@ -12135,7 +12135,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, botLimit, cloudOwnerKey: CLOUD_OWNER_KEY,+ maxWorkspaceBots: MAX_WORKSPACE_BOTS, paused: (botId) => starterAwake.isPaused(botId), 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,@@ -14229,6 +14229,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const createdId = "result" in proposed ? proposed.result.bots.find((bot) => bot.action === "created")?.id : undefined;const created = createdId ? store.bot(createdId) : undefined;if (!created) return json(res, 201, proposed);+ const paused = starterCaps.createdPaused(created.id);return json(res, 201, {...proposed,id: created.id,@@ -14237,6 +14238,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {section: created.section || "General",model: created.modelSelection.model,modelSelection: created.modelSelection, ...(botNameClash.warning(created.name) ? { warning: botNameClash.warning(created.name) } : {}),+ ...(paused ? { paused } : {}),});}if (method === "POST" && (path === "/api/internal/create-room" || path === "/api/internal/manage-room")) {@@ -15350,7 +15352,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", "file_too_large", "no_ai", BOT_LIMIT_CODE, BOT_PAUSED_CODE].includes(candidateCode)+ const code = typeof candidateCode === "string" && ["guarded_busy", "guarded_branch", "guarded_permissions", "guarded_request_changed", "guarded_request_untracked", "outside_workspace", "file_too_large", "no_ai", BOT_PAUSED_CODE].includes(candidateCode)? candidateCode : undefined;return json(res, status, { error: e instanceof Error ? e.message : String(e), ...(code ? { code } : {}), ...userErrorFields(e) });} finally {@@ -15433,6 +15435,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAliveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));+let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });server.listen(PORT, listenHost(server), async () => {companyRuntimeReady(); cloudHealth?.speed.ready();console.log(`openmausbot server on http://127.0.0.1:${PORT}`);diff --git a/server/org-library.test.ts b/server/org-library.test.tsindex ccce372585..9b48f4a405 100644--- a/server/org-library.test.ts+++ b/server/org-library.test.ts@@ -227,13 +227,12 @@ 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 () => {+describe("adding from the shelf past five bots", () => {+ it("adds a team to a Cloud that has five already, and refuses one past the workspace's ceiling as no broken package", 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 }) };+ let maxBots = 7;+ const deps = () => ({ ...app.importDeps, maxBots });const library = app.open();const team = release("full-team.v2.json");app.writeBlob(team.bytes);@@ -242,14 +241,14 @@ describe("adding from the shelf on a Starter Cloud", () => {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") });+ expect(library.add(TEAM_ID, deps())).toMatchObject({ ok: false, status: 409, code: "too_many_bots" });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);+ maxBots = 100;+ const added = library.add(TEAM_ID, deps());expect(added).toMatchObject({ ok: true, status: 201 });expect(app.store.bots.length).toBe(before + 3);});diff --git a/server/package-import.test.ts b/server/package-import.test.tsindex ed112b4f3e..7d26e20f45 100644--- a/server/package-import.test.ts+++ b/server/package-import.test.ts@@ -227,51 +227,41 @@ describe("importing a whole team", () => {});});-describe("importing onto a Starter Cloud", () => {- const onStarter = async (bots: number, starter = true) => {+describe("importing past five bots, and the workspace's ceiling", () => {+ const withBots = async (bots: number, maxBots?: number) => {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 }) } };+ return { ...app, deps: { ...app.deps, ...(maxBots === undefined ? {} : { maxBots }) } };};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("adds a whole team to a Cloud that already has five or more bots", async () => {+ const app = await withBots(5, 100);+ 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(8);});- it("refuses a template's manifest the same way", async () => {- const app = await onStarter(5);- const before = app.snapshot();+ it("adds a template's manifest past five bots", async () => {+ const app = await withBots(19, 100);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);+ app.importer.importTeamManifest(manifest, { mode: "add", cwd: null }, app.deps);+ expect(app.store.bots).toHaveLength(20);});- 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("refuses a team past the workspace's ceiling before writing anything, in words that name no plan", async () => {+ const app = await withBots(98, 100);+ const before = app.snapshot();+ expect(() => app.importer.importPackageDocument(team(app), { trust: "file", mode: "add" }, app.deps))+ .toThrow(expect.objectContaining({ code: "too_many_bots", status: 409, message: "This adds 3 bots, and this workspace is limited to 100 bots." }));+ expect(app.snapshot()).toBe(before);+ expect(app.events).toEqual([]);});- it("registers a preset library at the limit: it makes no bot", async () => {- const app = await onStarter(5);+ it("registers a preset library at the ceiling: it makes no bot", async () => {+ const app = await withBots(5, 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();diff --git a/server/package-import.ts b/server/package-import.tsindex ebaec024a5..2599d3607e 100644--- a/server/package-import.ts+++ b/server/package-import.ts@@ -7,13 +7,11 @@ 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";@@ -21,7 +19,7 @@ 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" | typeof BOT_LIMIT_CODE;+export type PackageImportErrorCode = "no_bots" | "invalid_package" | "too_many_bots";export class PackageImportError extends Error {readonly status: number;@@ -65,7 +63,8 @@ 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">;+ /** The most bots this workspace holds, every plan alike. */+ maxBots?: number;presets?: PresetRegistry;}@@ -227,8 +226,9 @@ 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);+ if (deps.maxBots !== undefined && store.bots.length + members.length > deps.maxBots) {+ throw new PackageImportError("too_many_bots", `This adds ${members.length} bots, and this workspace is limited to ${deps.maxBots} bots.`, 409);+ }const importedBots: BotRecord[] = [];const createdGroups: GroupRecord[] = [];diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.tsindex b57a998464..ff3c17c199 100644--- a/server/routes/bots-create.ts+++ b/server/routes/bots-create.ts@@ -1,5 +1,4 @@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";@@ -34,7 +33,8 @@ export interface BotCreateRouteDeps {hostedFullAccessRefusal: string;desktopManaged: boolean;maxWorkspaceBots: number;- botLimit: Pick<BotLimit, "refusal">;+ /** Whether this bot is paused: a Starter Cloud keeps only so many awake, and one made past them starts paused. */+ paused(botId: string): boolean;cloudOwnerKey: string | null;hostedModels: ReturnType<typeof hostedModelPolicy>;cloudRoutineAuthors: ReturnType<typeof createCloudRoutineAuthors> | null;@@ -184,9 +184,6 @@ 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 });@@ -264,7 +261,7 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {}deps.personaliseSetupCard?.(bot);return json(res, 201, {- ...(warnings.length ? { warnings } : {}),+ ...(warnings.length ? { warnings } : {}), ...(deps.paused(bot.id) ? { paused: true } : {}),bot: {...wireBot(bot),messages: store.messagesFor(bot.threadId),diff --git a/server/routines.test.ts b/server/routines.test.tsindex b90b345c0c..a2f008f50c 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -3977,6 +3977,24 @@ describe("turning a schedule back on, and a deleted bot's schedules", () => {expect(h.manager.listRuns()).toEqual([]);expect(h.started).toEqual([]);});++ it("fails a paused bot's runs at once in the person's words, making no conversation and waking nothing for them", async () => {+ const h = harness(start);+ let paused: string | null = "Paused: Starter keeps 5 bots awake.";+ h.options.pausedText = (botId) => (botId === "maus-1" ? paused : null);+ h.manager.create(once(start + 60_000));+ expect(h.manager.nextDueAt()).toBeNull();+ h.setNow(start + 60_000);+ await h.manager.tick();+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "d1", receivedAt: start });+ await h.manager.tick();+ expect([h.taskTitles, h.started]).toEqual([[], []]);+ expect(h.manager.listRuns().map((run) => [run.status, run.error])).toEqual([["failed", "Paused: Starter keeps 5 bots awake."], ["failed", "Paused: Starter keeps 5 bots awake."]]);++ paused = null;+ h.manager.create(once(start + 120_000));+ expect(h.manager.nextDueAt()).toBe(start + 120_000);+ });});describe("runs that report into a chat", () => {diff --git a/server/routines.ts b/server/routines.tsindex d20e885dff..7d8203953f 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -225,6 +225,7 @@ export interface RoutineManagerOptions {/** Every payload must be `{ kind, … }`: the server numbers and replays frames by it. */emit?: (payload: Record<string, unknown>) => void;botState: (botId: string) => "ready" | "busy" | "missing";+ /** Why this bot takes no runs now, in the person's words (a Starter Cloud keeps only so many bots awake); null when it does. */ pausedText?: (botId: string) => string | null;goalState?: (groupId: string | undefined, coordinatorBotId: string) => "ready" | "busy" | "missing";createTask: (botId: string, title: string, run?: RoutineRun) => { threadId: string } | null;joinConversation?: (run: RoutineRun) => string | null;@@ -425,7 +426,7 @@ export class RoutineManager {wakeHold(horizonMs = WAKE_HORIZON_MS) { return wakeHoldOf(this.routines, this.runs, this.now(), horizonMs); }/** A Cloud home's sleep check (server/routine-due.ts). */hasActiveRuns(): boolean { return activeRunsOf(this.runs, this.now()); }- nextDueAt(): number | null { return nextDueOf(this.routines, this.runs, this.now()); }+ nextDueAt(): number | null { return nextDueOf(this.routines.filter((routine) => routine.target === "room-goal" || !this.options.pausedText?.(routine.botId)), this.runs, this.now()); }listRuns(from?: number, to?: number): RoutineRun[] {return this.runs@@ -1122,10 +1123,9 @@ export class RoutineManager {}continue;}- if (state === "missing") {- this.failRun(run, this.missingTargetMessage(run.target));- continue;- }+ if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }+ const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);+ if (paused) { this.failRun(run, paused); continue; }const startedAt = this.now();const suffix = ` · ${new Date(startedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;const title = `${run.routineName.slice(0, 80 - suffix.length).trimEnd()}${suffix}`;diff --git a/server/starter-bot-limit.e2e.test.ts b/server/starter-bots.e2e.test.tssimilarity index 64%rename from server/starter-bot-limit.e2e.test.tsrename to server/starter-bots.e2e.test.tsindex 099b05ada6..f302a5b8f4 100644--- a/server/starter-bot-limit.e2e.test.ts+++ b/server/starter-bots.e2e.test.ts@@ -1,7 +1,7 @@// 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";@@ -18,7 +18,7 @@ const PACKAGE = JSON.parse(readFileSync(join(SERVER_DIR, "..", "shared", "packagconst 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-"));+ home = mkdtempSync(join(tmpdir(), "omb-starter-bots-"));dataDir = join(this.home, ".openmausbot");gate = join(this.home, "finish");dump = join(this.home, "claude.json");@@ -130,7 +130,10 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl}}-const REFUSED = { status: 409, body: { code: "bot_limit" } };+const made = (response: { status: number; body: any }) => {+ expect(response.status, JSON.stringify(response.body)).toBe(201);+ return response.body;+};describe("a Starter Cloud's bots, on a real server", () => {let cloud: Cloud;@@ -140,114 +143,119 @@ describe("a Starter Cloud's bots, on a real server", () => {await cloud.start();await cloud.tellPlan(tier);};+ const paused = async () => ((await cloud.config()).pausedBots ?? []) as string[];+ const send = (botId: string) => cloud.api("POST", `/api/bots/${botId}/messages`, { text: "Hello" });- it("makes five beside its MausBot, says so in config, then refuses each way of making one and writes nothing", async () => {+ it("makes a sixth bot and a twentieth: each starts paused, the first five stay awake, and nothing says the plan is full", 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);+ expect(await cloud.config()).toMatchObject({ cloudStarter: true, awakeLimit: 5, planTurns: { running: 2, waiting: 4 } });+ expect((await cloud.config()).botLimit).toBeUndefined();await cloud.fill(5);- const held = (await cloud.bots()).map((bot) => bot.id).sort();- expect(held).toHaveLength(6);+ const five = (await cloud.bots()).filter((bot) => !bot.defaultBot).map((bot) => bot.id);+ expect(await paused()).toEqual([]);++ const sixth = made(await cloud.create("Sixth"));+ expect(sixth.paused).toBe(true);+ expect(await paused()).toEqual([sixth.bot.id]);+ const refused = await send(sixth.bot.id);+ expect(refused).toMatchObject({ status: 409, body: { code: "bot_paused" } });+ expect(refused.body.error).toContain("Starter keeps 5 bots awake");++ // What Duplicate and a paired device's New bot send, a template's manifest, and a package.+ expect(made(await cloud.api("POST", "/api/bots", {})).paused).toBe(true);+ made(await cloud.api("POST", "/api/teams/import?mode=add", manifest("Desk")));+ made(await cloud.api("POST", "/api/teams/import?mode=add", PACKAGE));+ // A Chief of Staff (one came with the package) hands out the work, so it never sleeps and isn't counted.+ const counted = async () => (await cloud.bots()).filter((bot) => !bot.defaultBot && !bot.hidden && !bot.chiefOfStaff).map((bot) => bot.id as string);+ while ((await counted()).length < 20) made(await cloud.create(`More ${Math.random()}`));++ const all = await counted();+ expect(all).toHaveLength(20);+ const asleep = await paused();+ expect(asleep).toHaveLength(15);+ expect(all.filter((id) => !asleep.includes(id)).sort()).toEqual([...five].sort());+ const text = JSON.stringify(await cloud.config());+ expect(text).not.toMatch(/bot_limit|Starter includes/);+ }, 180_000);- 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);+ it("swaps the new bot in with one choice, and the one it replaced is paused", async () => {+ await starter();+ await cloud.fill(5);+ const [first, ...rest] = (await cloud.bots()).filter((bot) => !bot.defaultBot).map((bot) => bot.id);+ const sixth = made(await cloud.create("Sixth")).bot.id;+ const chosen = await cloud.api("POST", "/api/starter/awake", { awake: [sixth, ...rest] });+ expect(chosen).toEqual({ status: 200, body: { paused: [first] } });+ expect(await send(first)).toMatchObject({ status: 409, body: { code: "bot_paused" } });+ await cloud.restart();+ expect(await paused()).toEqual([first]);+ }, 120_000);+ it("a Chief's create_bot and team setup make bots past five, and the bot is told the new one is paused", async () => {+ await starter();+ await cloud.fill(5);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");+ expect(tool.status, JSON.stringify(tool.body)).toBe(201);+ expect(tool.body).toMatchObject({ state: "applied", name: "Scout" });+ expect(tool.body.paused).toMatch(/^@Scout was created, and is paused: this Cloud's Starter plan keeps 5 bots awake/);+ expect(await paused()).toEqual([tool.body.id]);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);+ operations: [{ action: "create", key: "writer", fields: { name: "Writer", title: "Specialist", soul: "Work.", modelSelection: CLAUDE } }] } });+ expect(setup.status, JSON.stringify(setup.body)).not.toBe(409);+ expect(JSON.stringify(setup.body)).not.toContain("bot_limit");}, 120_000);- it("takes a move and a restore at the limit, and a bot moved in keeps its id and conversation", async () => {+ it("takes a move and a restore past five, and keeps the bots that were awake awake", async () => {await starter();await cloud.fill(5);+ const five = (await cloud.bots()).filter((bot) => !bot.defaultBot).map((bot) => bot.id);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);+ const moved = made(await cloud.api("POST", "/api/bots", { id: "from-the-laptop-1", threadId: "laptop-thread-1", name: "From the laptop", useDefaults: false }));+ expect(moved.bot).toMatchObject({ id: "from-the-laptop-1", threadId: "laptop-thread-1" });+ const restored = made(await cloud.api("POST", "/api/teams/import?mode=add", backup.body));+ expect(restored.bots.length).toBeGreaterThanOrEqual(6);+ const asleep = await paused();+ expect(five.filter((id) => asleep.includes(id))).toEqual([]);+ expect(asleep).toContain("from-the-laptop-1");}, 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 () => {+ it("keeps every bot of a downgraded Cloud, across a restart, and wakes them all the moment it upgrades, with no restart", async () => {await starter("pro");- expect((await cloud.config()).botLimit).toBeUndefined();+ expect((await cloud.config()).awakeLimit).toBeUndefined();await cloud.fill(7);const seven = (await cloud.bots()).map((bot) => bot.id).sort();+ expect(await paused()).toEqual([]);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);-+ expect(await paused()).toHaveLength(2);+ expect(made(await cloud.create("New")).paused).toBe(true);await cloud.restart();- expect((await cloud.bots()).map((bot) => bot.id).sort()).toEqual(seven);- expect(await cloud.create("New")).toMatchObject(REFUSED);+ expect((await cloud.bots()).map((bot) => bot.id).filter((id) => seven.includes(id)).sort()).toEqual(seven);+ expect(await paused()).toHaveLength(3);const pid = cloud.child!.pid;await cloud.tellPlan("pro");- expect((await cloud.config()).botLimit).toBeUndefined();- expect((await cloud.create("New")).status).toBe(201);+ expect(await paused()).toEqual([]);+ expect((await cloud.config()).awakeLimit).toBeUndefined();+ expect(made(await cloud.create("Another")).paused).toBeUndefined();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) => {+ it.each([["max"], ["personal"], ["team"]])("has no awake limit on %s", async (tier) => {await starter(tier);- expect((await cloud.config()).botLimit).toBeUndefined();+ expect((await cloud.config()).awakeLimit).toBeUndefined();await cloud.fill(6);- expect((await cloud.api("POST", "/api/teams/import?mode=add", manifest("Desk"))).status).toBe(201);+ expect(made(await cloud.api("POST", "/api/teams/import?mode=add", manifest("Desk")))).toBeTruthy();+ expect(await paused()).toEqual([]);}, 120_000);- it("has no limit when the Admin never said a plan, whatever the machine", async () => {+ it("has no awake 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(await paused()).toEqual([]);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 491686afed..d3e218a59b 100644--- a/server/team-setup-requests.test.ts+++ b/server/team-setup-requests.test.ts@@ -1,4 +1,3 @@-import { createBotLimit } from "./host/starter-bot-limit.ts";import { describe, expect, it, vi } from "vitest";import { mkdirSync, mkdtempSync } from "node:fs";import { tmpdir } from "node:os";@@ -12,7 +11,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 }>, plan: { starter: boolean } = { starter: false }) {+function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean }>) {const bots: BotRecord[] = [];const messages: Array<{ id: string; role?: string; card?: OptionCardData }> = [];const teams = ["", "Work", "Engineering", "Private"];@@ -50,7 +49,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, botLimit: createBotLimit({ starter: () => plan.starter, bots: () => bots }),+ const service = new TeamSetupRequestService({ store, teams: () => teams, maxBots: 100, hasTeamAuthority,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";@@ -618,63 +617,30 @@ describe("MausBot's Chief-level team setup", () => {});});-describe("a Starter Cloud's limit on bots", () => {+describe("a Chief making bots, whatever the plan", () => {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);+ const full = (others: number) => {+ const app = harness();for (let i = 0; i < others; i++) app.bot(`Other${i}`);- return { ...app, plan };+ return app;};- 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("proposes a sixth bot and more: making them is never refused for the plan", () => {+ const app = full(10);+ expect(app.propose([specialist("Scout"), specialist("Writer")]).requestId).toBeTruthy();});- it("refuses a whole setup that doesn't fit: no bot of it is made", async () => {- const app = full(2);+ it("applies a whole setup past five bots", async () => {+ const app = full(4);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);+ await app.submit([specialist("Scout"), specialist("Writer")]);+ expect(app.apply).toHaveBeenCalledTimes(1);});- 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();+ it("still holds the workspace's own ceiling", () => {+ const app = full(97);+ expect(() => app.propose([specialist("Scout"), specialist("Writer")])).toThrow(expect.objectContaining({ status: 409, message: "This setup exceeds the workspace bot limit" }));});});diff --git a/server/team-setup-requests.ts b/server/team-setup-requests.tsindex 93a1146eeb..2562ed7763 100644--- a/server/team-setup-requests.ts+++ b/server/team-setup-requests.ts@@ -10,7 +10,6 @@ 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";@@ -86,7 +85,6 @@ 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>;@@ -177,8 +175,6 @@ export class TeamSetupRequestService {}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.tsindex dcdb2ff0fd..93d3bcb270 100644--- a/shared/bot-limit.ts+++ b/shared/bot-limit.ts@@ -1,14 +1,13 @@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. */+/** The code on a creation an older server refused, `409 { error, code }`, when Starter capped how many bots it made. No server+ * sends it now; clients still read it from one that does. `error` is plain text any client can show. */export const BOT_LIMIT_CODE = "bot_limit";/** The code on a turn refused because its bot is paused: a Starter Cloud keeps only so many bots awake. */export const BOT_PAUSED_CODE = "bot_paused";-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. */+/** The bots a plan's awake 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/components/AwakeBotsPicker.tsx b/src/components/AwakeBotsPicker.tsxindex 303d3d339f..3d159d4188 100644--- a/src/components/AwakeBotsPicker.tsx+++ b/src/components/AwakeBotsPicker.tsx@@ -4,19 +4,32 @@ import { awakeCandidates, showBotLimit } from "@/lib/bot-limit";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { api } from "@/state/api";-import { useStore } from "@/state/store";+import { useStore, type Bot } from "@/state/store";import { BotAvatar } from "./Avatar";import { PRIMARY_BUTTON } from "./NoticeCard";+type Candidate = Pick<Bot, "id" | "busy" | "tasks">;+const lastActive = (bot: Candidate) => Math.max(0, ...(bot.tasks ?? []).map((task) => task.updatedAt ?? task.createdAt ?? 0));++/** The bots offered awake: those awake now, or with `swapIn` chosen in place of the least recently active one not working. */+export function initialAwake(bots: readonly Candidate[], paused: ReadonlySet<string>, wanted: number, swapIn?: string): Set<string> {+ const awake = bots.filter((bot) => !paused.has(bot.id) && bot.id !== swapIn);+ if (!swapIn || !bots.some((bot) => bot.id === swapIn)) return new Set(awake.map((bot) => bot.id));+ const idleFirst = [...awake].sort((a, b) => Number(Boolean(a.busy)) - Number(Boolean(b.busy)) || lastActive(a) - lastActive(b));+ const kept = new Set(awake.map((bot) => bot.id));+ for (const bot of idleFirst) if (kept.size > wanted - 1) kept.delete(bot.id);+ return new Set([...kept, swapIn]);+}+/** Which of a Starter Cloud's bots stay awake: the plan's number of them, the rest paused until swapped in or an upgrade. */-export function AwakeBotsPicker({ limit, onSaved }: { limit: number; onSaved: () => void }) {+export function AwakeBotsPicker({ limit, onSaved, swapIn }: { limit: number; onSaved: () => void; swapIn?: string }) {const { state } = useStore();const bots = awakeCandidates(state.bots);const paused = new Set(state.config?.pausedBots ?? []);- const [chosen, setChosen] = useState<Set<string>>(() => new Set(bots.filter((bot) => !paused.has(bot.id)).map((bot) => bot.id)));+ const wanted = Math.min(limit, bots.length);+ const [chosen, setChosen] = useState<Set<string>>(() => initialAwake(bots, paused, wanted, swapIn));const [busy, setBusy] = useState(false);const [failed, setFailed] = useState(false);- const wanted = Math.min(limit, bots.length);const toggle = (id: string) => setChosen((before) => {const next = new Set(before);if (next.has(id)) next.delete(id);diff --git a/src/components/BotLimitPopup.test.ts b/src/components/BotLimitPopup.test.tsindex b02d786f8e..ec75fce420 100644--- a/src/components/BotLimitPopup.test.ts+++ b/src/components/BotLimitPopup.test.ts@@ -10,9 +10,10 @@ const posted = vi.hoisted(() => [] as Array<{ path: string; body: unknown }>);vi.mock("@/state/api", () => ({ api: vi.fn(async (path: string, init?: { body?: string }) => { posted.push({ path, body: init?.body ? JSON.parse(init.body) : undefined }); return {}; }) }));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 { botLimitShown, closeBotLimit, showBotLimit, showCreatedPaused } from "@/lib/bot-limit";import { openExternalLink } from "@/lib/app-links";import { setLocale } from "@/lib/i18n";+import { initialAwake } from "./AwakeBotsPicker";import { BotLimitPopup } from "./BotLimitPopup";const STARTER = { tier: "starter", resetsAt: 1, meters: [], upgrades: [{ tier: "pro", amount: 4900 }, { tier: "max", amount: 9900 }] };@@ -186,4 +187,35 @@ describe("the popup for Starter's other limits", () => {expect(posted).toEqual([{ path: "/api/starter/awake", body: { awake: ["b1", "b2", "b3", "b4", "b5"] } }]);expect(botLimitShown()).toBe(false);});++ it("says a bot just made is paused, and swaps it in for the least recently used idle bot with one tap", async () => {+ posted.length = 0;+ const bots = made(6).map((bot, n) => ({ ...bot, name: n === 5 ? "Scout" : bot.id, tasks: [{ updatedAt: n === 1 ? 1 : 100 + n }], ...(n === 0 ? { busy: true } : {}) }));+ // A server that makes any number of bots sends no botLimit.+ fixture.state = { config: { cloudHome: true, awakeLimit: 5, pausedBots: ["b5"] }, bots };+ (window as unknown as { ogb?: unknown }).ogb = { cloudPlan: bridge({ status: "paid", tier: "starter", usage: STARTER }) };+ await act(async () => { root.render(createElement(BotLimitPopup)); });+ await act(async () => { showCreatedPaused("b5"); });+ await act(async () => {});+ expect(dialog()!.querySelector("h2")?.textContent).toBe("Created Scout, paused for now");+ expect(dialog()!.textContent).toContain("Starter keeps 5 bots awake, so this one is paused. Choose which 5 stay awake, or upgrade to wake them all.");+ expect(dialog()!.textContent).not.toContain("You've reached");+ const picker = dialog()!.querySelector("[data-awake-bots]")!;+ await press("Keep these awake", picker);+ expect(posted).toEqual([{ path: "/api/starter/awake", body: { awake: ["b0", "b2", "b3", "b4", "b5"] } }]);+ expect(botLimitShown()).toBe(false);+ });+});++describe("the bots first offered awake", () => {+ const bot = (id: string, at: number, busy = false) => ({ id, busy, tasks: [{ updatedAt: at }] as never });+ it("keeps the awake ones as they are when nothing new is swapped in", () => {+ expect(initialAwake([bot("a", 1), bot("b", 2), bot("c", 3)], new Set(["c"]), 2)).toEqual(new Set(["a", "b"]));+ });++ it("swaps a new bot in for the least recently active one that isn't working, even before the paused list arrives", () => {+ const bots = [bot("new", 9), bot("a", 1, true), bot("b", 2), bot("c", 3), bot("d", 4), bot("e", 5)];+ expect(initialAwake(bots, new Set(["new"]), 5, "new")).toEqual(new Set(["new", "a", "c", "d", "e"]));+ expect(initialAwake(bots, new Set(), 5, "new")).toEqual(new Set(["new", "a", "c", "d", "e"]));+ });});diff --git a/src/components/BotLimitPopup.tsx b/src/components/BotLimitPopup.tsxindex 206532d7d7..8bc6c99606 100644--- a/src/components/BotLimitPopup.tsx+++ b/src/components/BotLimitPopup.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, 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, planRefusal, showBotLimit, useBotLimitReason, type BotLimitReason } from "@/lib/bot-limit";+import { botRoom, closeBotLimit, planRefusal, showBotLimit, useBotLimitReason, useCreatedPausedBot, type BotLimitReason } from "@/lib/bot-limit";import { cloudPlanLabel } from "@/lib/cloud-plan";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -28,11 +28,11 @@ export function BotLimitPopup() {seen.current = next.seen;if (next.show) showBotLimit(next.show);}, [loaded, turns?.refusedAt]);- const reason = useBotLimitReason();- return reason ? <BotLimitDialog reason={reason} onClose={closeBotLimit} /> : null;+ const reason = useBotLimitReason(), created = useCreatedPausedBot();+ return reason ? <BotLimitDialog reason={reason} created={created} onClose={closeBotLimit} /> : null;}-function BotLimitDialog({ reason, onClose }: { reason: BotLimitReason; onClose: () => void }) {+function BotLimitDialog({ reason, created, onClose }: { reason: BotLimitReason; created: string | null; onClose: () => void }) {const { state } = useStore();const bridge = usageBridge(state.config?.cloudHome === true);const plan = useCloudPlanSnapshot(bridge);@@ -46,7 +46,8 @@ function BotLimitDialog({ reason, onClose }: { reason: BotLimitReason; onClose:const settled = upgraded !== null || goingThrough;const limit = state.config?.botLimit, awake = state.config?.awakeLimit;const noRoom = limit !== undefined && botRoom(state) === 0;- const picking = reason === "paused" && awake !== undefined && !settled;+ const picking = (reason === "paused" || reason === "created") && awake !== undefined && !settled;+ const createdName = state.bots.find((bot) => bot.id === created)?.name ?? "";useEffect(() => {document.querySelector<HTMLElement>(`${POPUP} button`)?.focus();@@ -75,9 +76,11 @@ function BotLimitDialog({ reason, onClose }: { reason: BotLimitReason; onClose:const title = upgraded ? t("usageMeter.done", { plan: cloudPlanLabel(upgraded) }): goingThrough ? t("usageMeter.pending"): reason === "tasks" ? t("botLimit.tasks.title", { count: state.config?.planTurns?.running ?? 2 })- : reason === "paused" ? t("botLimit.paused.title", { count: awake ?? limit ?? 5 })- : noRoom ? t("botLimit.title", { count: limit }) : t("botLimit.titleTooMany");- const body = reason === "tasks" ? t("botLimit.tasks.body") : reason === "paused" ? t("botLimit.paused.body", { count: awake ?? limit ?? 5 }) : null;+ : reason === "created" ? t("botLimit.created.title", { name: createdName })+ : reason === "paused" ? t("botLimit.paused.title", { count: awake ?? limit ?? 5 })+ : noRoom ? t("botLimit.title", { count: limit }) : t("botLimit.titleTooMany");+ const body = reason === "tasks" ? t("botLimit.tasks.body") : reason === "paused" ? t("botLimit.paused.body", { count: awake ?? limit ?? 5 })+ : reason === "created" ? t("botLimit.created.body", { count: awake ?? 5 }) : null;// 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));@@ -89,7 +92,7 @@ function BotLimitDialog({ reason, onClose }: { reason: BotLimitReason; onClose:<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]">{body ?? t(inApp ? "botLimit.body" : "botLimit.bodyElsewhere")}</p>}- {picking && <AwakeBotsPicker limit={awake} onSaved={onClose} />}+ {picking && <AwakeBotsPicker limit={awake} onSaved={onClose} {...(reason === "created" && created ? { swapIn: created } : {})} />}{settled ? (<button type="button" onClick={onClose} className={cn(PRIMARY_BUTTON, "mt-5 w-full justify-center")}>{t("roomCard.gotIt")}</button>) : usage ? (diff --git a/src/components/NewBotDialog.tsx b/src/components/NewBotDialog.tsxindex df2f03ca42..a01dc13816 100644--- a/src/components/NewBotDialog.tsx+++ b/src/components/NewBotDialog.tsx@@ -120,9 +120,9 @@ export function NewBotDialog({ defaultsMode = false, onClose, onCreated, readyBotry {if (defaultsMode) await api("/api/config", { method: "PATCH", body: JSON.stringify({ newBotDefaults: await preparedBotTemplate(draft) }) });else {- const { bot, warnings } = await createConfiguredBot(draft, undefined, undefined, undefined, visibility?.ok ? visibility.visibility : undefined,+ const { bot, warnings, paused } = await createConfiguredBot(draft, undefined, undefined, undefined, visibility?.ok ? visibility.visibility : undefined,team ? reportsToFor(chosenOwner, draft.bot.section, parent.state.bots, team) ?? undefined : undefined);- announceNewBot(parent.dispatch, bot, warnings, { showThreads, source: draft.preset ? "preset" : draft.role ? "template" : "blank", role: draft.role });+ announceNewBot(parent.dispatch, bot, warnings, { showThreads, source: draft.preset ? "preset" : draft.role ? "template" : "blank", role: draft.role, paused });try { await onCreated?.(bot); }catch (cause) { parent.dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }); }}diff --git a/src/lib/bot-limit.ts b/src/lib/bot-limit.tsindex b4a18b7c5d..079998cc54 100644--- a/src/lib/bot-limit.ts+++ b/src/lib/bot-limit.ts@@ -1,20 +1,27 @@import { useSyncExternalStore } from "react";import { BOT_LIMIT_CODE, BOT_PAUSED_CODE, botsTowardLimit } from "../../shared/bot-limit";-/** Which plan limit the popup is about: making bots, work handed out past what runs at once, or a paused bot. */-export type BotLimitReason = "bots" | "tasks" | "paused";+/** Which plan limit the popup is about: making bots (a server that still caps them), work handed out past what runs at+ * once, a paused bot, or a bot just made that starts paused. */+export type BotLimitReason = "bots" | "tasks" | "paused" | "created";let open: BotLimitReason | null = null;+let created: string | null = null;const listeners = new Set<() => void>();-function setOpen(next: BotLimitReason | null): void {- if (open === next) return;+function setOpen(next: BotLimitReason | null, bot: string | null = null): void {+ if (open === next && created === bot) return;open = next;+ created = bot;for (const listener of listeners) listener();}export const botLimitShown = () => open !== null;export const botLimitReason = () => open;-export const showBotLimit = (reason: BotLimitReason = "bots") => setOpen(reason);+/** The bot a "created" popup is about. */+export const createdPausedBot = () => created;+export const showBotLimit = (reason: Exclude<BotLimitReason, "created"> = "bots") => setOpen(reason);+/** A bot just made on Starter past the bots it keeps awake: it starts paused, and the popup offers to swap it in. */+export const showCreatedPaused = (botId: string) => setOpen("created", botId);export const closeBotLimit = () => setOpen(null);const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };@@ -27,10 +34,14 @@ export function useBotLimitReason(): BotLimitReason | null {return useSyncExternalStore(subscribe, botLimitReason);}+export function useCreatedPausedBot(): string | null {+ return useSyncExternalStore(subscribe, createdPausedBot);+}+/** What a config frame's refusal means for the popup: `seen` is the last refusal noted, null before the first frame, so one* from before the page opened never opens it. */export function planRefusal(seen: number | undefined | null, turns: { refusedAt?: number; refused?: "tasks" | "paused" } | undefined):- { seen: number | undefined; show: BotLimitReason | null } {+ { seen: number | undefined; show: "tasks" | "paused" | null } {const at = turns?.refusedAt;if (seen === null || at === undefined || at === seen) return { seen: seen === null ? at : seen, show: null };return { seen: at, show: turns?.refused ?? "tasks" };@@ -43,7 +54,7 @@ export function awakeCandidates<T extends Parameters<typeof botsTowardLimit>[0][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. */+/** How many more bots this plan makes; null when it has no such limit, as on every server that makes any number. */export function botRoom(state: LimitFacts): number | null {const limit = state.config?.botLimit;return limit === undefined ? null : Math.max(0, limit - botsTowardLimit(state.bots));diff --git a/src/lib/create-configured-bot.ts b/src/lib/create-configured-bot.tsindex fd04f5af03..04f9d1366d 100644--- a/src/lib/create-configured-bot.ts+++ b/src/lib/create-configured-bot.ts@@ -26,13 +26,13 @@ export async function createConfiguredBot(approvals = desktopApprovalBridge(),visibility?: BotVisibility,reportsTo?: string,-): Promise<{ bot: Bot; warnings: string[] }> {+): Promise<{ bot: Bot; warnings: string[]; paused?: true }> {const template = await preparedBotTemplate(draft);const { chiefOfStaff, managedSections, toolScope, modelSelection, ...profile } = template.profile;if (!profile.name?.trim()) throw new Error(t("newBot.nameRequired"));const preset = draft.preset;const chosenAi = modelSelection?.instanceId && modelSelection.model ? { modelSelection, requireAvailableModel: true } : {};- const response = await request<{ bot: Bot }>("/api/bots", {+ const response = await request<{ bot: Bot; paused?: true }>("/api/bots", {method: "POST", body: JSON.stringify({ name: profile.name, title: profile.title,description: profile.description, ...chosenAi, section: profile.section,useDefaults: false, ...(visibility !== undefined ? { visibility } : {}), ...(reportsTo ? { reportsTo } : {}),@@ -100,5 +100,5 @@ export async function createConfiguredBot(try { await request(`/api/routines/${routine.id}`, { method: "PATCH", body: JSON.stringify({ enabled: true }) }); }catch (error) { warnings.push(t("newBot.warning.routine", { error: error instanceof Error ? error.message : String(error) })); }}- return { bot, warnings };+ return { bot, warnings, ...(response.paused ? { paused: true as const } : {}) };}diff --git a/src/lib/new-bot.test.ts b/src/lib/new-bot.test.tsindex 8a121aa09c..4195575fc3 100644--- a/src/lib/new-bot.test.ts+++ b/src/lib/new-bot.test.ts@@ -9,13 +9,14 @@ vi.mock("@/state/thread-navigation", async (importOriginal) => ({import type { Action, Bot } from "@/state/store";import { setTeamChats } from "@/state/team-chats";import { setTeamPeople, type TeamPeople } from "@/state/team-people";+import { botLimitReason, closeBotLimit, createdPausedBot } from "./bot-limit";import { makeNewBot, type BotDefaultsAnswer } from "./new-bot";const ME = { email: "[email protected]", name: "Ada", role: "member", you: true as const };const BOB = { email: "[email protected]", name: "Bob", role: "admin" };const team: TeamPeople = { people: [ME, BOB], me: ME, admin: true, needsYou: [] };-function server(answer: Partial<BotDefaultsAnswer> = {}, fail?: { on: "POST" | "PATCH"; error: string }) {+function server(answer: Partial<BotDefaultsAnswer> = {}, fail?: { on: "POST" | "PATCH"; error: string }, paused = false) {const calls: Array<{ method: string; path: string; body: Record<string, unknown> }> = [];let bot: Bot | null = null;const request = vi.fn(async (path: string, init?: RequestInit) => {@@ -29,7 +30,7 @@ function server(answer: Partial<BotDefaultsAnswer> = {}, fail?: { on: "POST" | "if (path === "/api/bots" && method === "POST") {bot = { id: "created", threadId: "created-main", name: body.name, title: "", description: "", soul: "", color: "green", notifications: true,unread: false, messages: [], section: body.section, modelSelection: body.modelSelection ?? { instanceId: "", model: "" } } as Bot;- return { bot };+ return paused ? { bot, paused: true } : { bot };}if (path === "/api/bots/created" && method === "PATCH") { bot = { ...bot!, ...body }; return { bot }; }return {};@@ -44,10 +45,10 @@ async function newBot(request: never, action: Partial<Extract<Action, { type: "n}beforeEach(() => { fixture.track.mockReset(); fixture.openBot.mockReset(); });-afterEach(() => { vi.unstubAllGlobals(); setTeamPeople(null); setTeamChats(null); });+afterEach(() => { vi.unstubAllGlobals(); setTeamPeople(null); setTeamChats(null); closeBotLimit(); });describe("New bot", () => {- it("leaves a plan's refusal to the popup: no error line beside it, and no onError", async () => {+ it("leaves an older server's refusal of a sixth Starter bot 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" };@@ -59,6 +60,18 @@ describe("New bot", () => {expect(fixture.track).not.toHaveBeenCalled();});+ it("makes a Starter bot past the five awake, opens its chat, and offers to swap it in", async () => {+ const { request } = server({}, undefined, true);+ const sent = await newBot(request);+ expect(sent[0]).toMatchObject({ type: "botAdded", bot: { id: "created" } });+ expect([botLimitReason(), createdPausedBot()]).toEqual(["created", "created"]);+ });++ it("opens no popup for a bot made awake", async () => {+ await newBot(server().request);+ expect(botLimitReason()).toBeNull();+ });+it("makes nothing for a User on a team, however it was asked for", async () => {setTeamPeople({ ...team, admin: false });const { calls, request } = server();diff --git a/src/lib/new-bot.ts b/src/lib/new-bot.tsindex e657205667..991fc29df0 100644--- a/src/lib/new-bot.ts+++ b/src/lib/new-bot.ts@@ -5,7 +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 { isBotLimitRefusal, showCreatedPaused } from "./bot-limit";import { createConfiguredBot } from "./create-configured-bot";import { t } from "./i18n";import { botCreated } from "./product-events";@@ -37,21 +37,22 @@ export function reportsToFor(chosen: string | null, section: string | undefined,}/** A bot just made joins the sidebar and, unless the caller keeps its own place, its chat opens: on a team's Cloud the- * creator's own conversation, never the main chat every member reads. */+ * creator's own conversation, never the main chat every member reads. One that starts paused offers to swap it in. */export function announceNewBot(dispatch: (action: Action) => void, bot: Bot, warnings: readonly string[],- { preserveSelection = false, showThreads, source, role }: { preserveSelection?: boolean; showThreads: boolean; source: BotSource; role?: string }) {+ { preserveSelection = false, showThreads, source, role, paused }: { preserveSelection?: boolean; showThreads: boolean; source: BotSource; role?: string; paused?: boolean }) {botCreated(source, role);dispatch({ type: "botAdded", bot, preserveSelection });if (!preserveSelection && teamChats()) openBot(dispatch, bot, showThreads);if (warnings.length) dispatch({ type: "error", message: warnings.join("\n") });+ if (paused) showCreatedPaused(bot.id);}/** A paired device may not read the host's New bot defaults: the host applies them to an empty request. Auto on this* computer needs the person's own OK, so a bot whose defaults ask for it starts on Ask. */async function createNewBot(section: string | undefined, bots: readonly Bot[], team: TeamPeople | null, request: typeof api) {if (typeof window !== "undefined" && window.ogb?.remoteClient?.active) {- const { bot } = await request<{ bot: Bot }>("/api/bots", { method: "POST", body: JSON.stringify(section === undefined ? {} : { section }) });- return { bot, warnings: [] as string[], startsOnAsk: false };+ const { bot, paused } = await request<{ bot: Bot; paused?: true }>("/api/bots", { method: "POST", body: JSON.stringify(section === undefined ? {} : { section }) });+ return { bot, warnings: [] as string[], startsOnAsk: false, ...(paused ? { paused } : {}) };}const template = startingTemplate(await request<BotDefaultsAnswer>("/api/bot-defaults"), true);template.profile.name = freeName(template.profile.name!, bots);@@ -81,7 +82,7 @@ export async function makeNewBot(action: Extract<Action, { type: "newBot" }>, boelse dispatch({ type: "error", message });return;}- announceNewBot(dispatch, made.bot, made.warnings, { preserveSelection: action.preserveSelection, showThreads, source: "blank" });+ announceNewBot(dispatch, made.bot, made.warnings, { preserveSelection: action.preserveSelection, showThreads, source: "blank", paused: made.paused });if (made.startsOnAsk) dispatch({ type: "notice", notice: { kind: "note", botName: null, text: t("newBot.startsOnAsk", { name: made.bot.name }) } });action.onCreated?.(made.bot);}diff --git a/src/locales/de.json b/src/locales/de.jsonindex e114e59f99..f0862c1c8c 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -2663,6 +2663,8 @@"botLimit.paused.badge": "Pausiert","botLimit.paused.saveFailed": "Konnte nicht gespeichert werden. Versuch es noch einmal.","botLimit.paused.chooseAction": "Wache Bots wählen ({count} pausiert)",+ "botLimit.created.title": "{name} erstellt, vorerst pausiert",+ "botLimit.created.body": "Starter hält {count} Bots wach, deshalb ist dieser pausiert. Wähle, welche {count} wach bleiben, oder führe ein Upgrade durch, um alle zu wecken.","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 8be16df278..74ec718645 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7656,6 +7656,8 @@"botLimit.paused.badge": "Paused","botLimit.paused.saveFailed": "Couldn't save that. Try again.","botLimit.paused.chooseAction": "Choose awake bots ({count} paused)",+ "botLimit.created.title": "Created {name}, paused for now",+ "botLimit.created.body": "Starter keeps {count} bots awake, so this one is paused. Choose which {count} stay awake, or upgrade to wake them all.","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 e3b32b243f..8853034711 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -5686,6 +5686,8 @@"botLimit.paused.badge": "En pausa","botLimit.paused.saveFailed": "No se pudo guardar. Inténtalo de nuevo.","botLimit.paused.chooseAction": "Elegir bots despiertos ({count} en pausa)",+ "botLimit.created.title": "{name} creado, en pausa por ahora",+ "botLimit.created.body": "Starter mantiene {count} bots despiertos, así que este está en pausa. Elige cuáles {count} siguen despiertos, o mejora el plan para despertarlos a todos.","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/fr.json b/src/locales/fr.jsonindex 3daf168ba4..5b6d042c1b 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -2587,6 +2587,8 @@"botLimit.paused.badge": "En pause","botLimit.paused.saveFailed": "Impossible d'enregistrer. Réessayez.","botLimit.paused.chooseAction": "Choisir les bots éveillés ({count} en pause)",+ "botLimit.created.title": "{name} créé, en pause pour l'instant",+ "botLimit.created.body": "Starter garde {count} bots éveillés, donc celui-ci est en pause. Choisissez les {count} qui restent éveillés, ou passez à un plan supérieur pour tous les réveiller.","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 eba66a51f6..aa234b2fe9 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -2587,6 +2587,8 @@"botLimit.paused.badge": "रुका हुआ","botLimit.paused.saveFailed": "सेव नहीं हो सका। फिर से कोशिश करें।","botLimit.paused.chooseAction": "जगे रहने वाले बॉट चुनें ({count} रुके हुए)",+ "botLimit.created.title": "{name} बन गया, अभी रुका हुआ है",+ "botLimit.created.body": "Starter {count} बॉट जगाए रखता है, इसलिए यह रुका हुआ है। चुनें कि कौन से {count} जगे रहें, या सबको जगाने के लिए अपग्रेड करें।","chat.compactionExcerptTitle": "पिछला संदर्भ हाल के अंशों तक छोटा किया गया","chat.compactionExcerptHint": "लिखित सारांश उपलब्ध नहीं था, इसलिए एजेंट इन अंशों और हाल के संदेशों से आगे बढ़ता है। पुराने विवरण उसके संदर्भ से छूट सकते हैं। आपकी पूरी बातचीत अब भी यहीं है।","chat.turnStoppedByYou": "आपने इसे रोका।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex e64451c3aa..30cb582a40 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6328,6 +6328,8 @@"botLimit.paused.badge": "In pausa","botLimit.paused.saveFailed": "Impossibile salvare. Riprova.","botLimit.paused.chooseAction": "Scegli i bot svegli ({count} in pausa)",+ "botLimit.created.title": "{name} creato, in pausa per ora",+ "botLimit.created.body": "Starter tiene svegli {count} bot, quindi questo è in pausa. Scegli quali {count} restano svegli, oppure passa a un piano superiore per svegliarli tutti.","inbox.from": "Da {name}","inbox.via": "tramite {name}","inbox.in": "in {title}",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex f67dac559f..a01a176ba0 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -7369,6 +7369,8 @@"botLimit.paused.badge": "一時停止中","botLimit.paused.saveFailed": "保存できませんでした。もう一度お試しください。","botLimit.paused.chooseAction": "起動しておくボットを選ぶ({count} 体が一時停止中)",+ "botLimit.created.title": "{name} を作成しました。いまは一時停止中です",+ "botLimit.created.body": "Starter で起動しておけるボットは {count} 体なので、このボットは一時停止中です。起動しておく {count} 体を選ぶか、アップグレードしてすべて起こしてください。","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 f0bd77e53f..889a959c25 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7028,6 +7028,8 @@"botLimit.paused.badge": "일시 중지됨","botLimit.paused.saveFailed": "저장하지 못했어요. 다시 시도하세요.","botLimit.paused.chooseAction": "깨어 있을 봇 고르기 ({count}개 일시 중지됨)",+ "botLimit.created.title": "{name} 봇을 만들었어요. 지금은 일시 중지 상태예요",+ "botLimit.created.body": "Starter는 봇 {count}개만 깨어 있게 해서 이 봇은 일시 중지되었어요. 깨어 있을 봇 {count}개를 고르거나, 업그레이드해서 모두 깨우세요.","chat.setupCard.title": "무엇부터 도와드릴까요?","chat.setupCard.other": "다른 것","chat.setupCard.answer": "내 답변",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 7be79de531..801926c145 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6456,6 +6456,8 @@"botLimit.paused.badge": "Wstrzymany","botLimit.paused.saveFailed": "Nie udało się zapisać. Spróbuj ponownie.","botLimit.paused.chooseAction": "Wybierz aktywne boty (wstrzymane: {count})",+ "botLimit.created.title": "Utworzono {name}, na razie wstrzymany",+ "botLimit.created.body": "Starter utrzymuje aktywne {count} boty, więc ten jest wstrzymany. Wybierz, które {count} mają pozostać aktywne, albo zmień plan, aby obudzić wszystkie.","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 d7daf535db..453b60d48a 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7559,6 +7559,8 @@"botLimit.paused.badge": "Pausado","botLimit.paused.saveFailed": "Não foi possível salvar. Tente de novo.","botLimit.paused.chooseAction": "Escolher bots ativos ({count} pausados)",+ "botLimit.created.title": "{name} criado, pausado por enquanto",+ "botLimit.created.body": "O Starter mantém {count} bots ativos, então este está pausado. Escolha quais {count} ficam ativos ou faça upgrade para ativar todos.","roomCard.restartNow": "Reiniciar agora","roomCard.restartHint": "Leva cerca de um minuto e interrompe tudo que estiver em execução.","roomCard.restarting": "Reiniciando este Cloud com a nova capacidade. Ele volta em cerca de um minuto.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 4cfb43b499..24cdf5551b 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -6552,6 +6552,8 @@"botLimit.paused.badge": "На паузе","botLimit.paused.saveFailed": "Не удалось сохранить. Попробуйте ещё раз.","botLimit.paused.chooseAction": "Выбрать активных ботов (на паузе: {count})",+ "botLimit.created.title": "{name} создан и пока на паузе",+ "botLimit.created.body": "Starter держит активными {count} ботов, поэтому этот на паузе. Выберите, какие {count} останутся активными, или перейдите на план выше, чтобы разбудить всех.","composer.setupRequest.placeholder": "Напишите {name}, с чем нужна помощь","composer.setupRequest.waiting": "{name} готов к настройке","composer.setupRequest.cancel": "Остановить настройку {name}",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex d4f521a9b3..56bcab98f7 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5048,6 +5048,8 @@"botLimit.paused.badge": "Duraklatıldı","botLimit.paused.saveFailed": "Kaydedilemedi. Tekrar deneyin.","botLimit.paused.chooseAction": "Uyanık botları seç ({count} duraklatıldı)",+ "botLimit.created.title": "{name} oluşturuldu, şimdilik duraklatıldı",+ "botLimit.created.body": "Starter {count} botu uyanık tutar, bu yüzden bu bot duraklatıldı. Hangi {count} botun uyanık kalacağını seçin ya da hepsini uyandırmak için yükseltin.","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 4c0292bd0b..d8235c4f41 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3032,6 +3032,8 @@"botLimit.paused.badge": "Призупинено","botLimit.paused.saveFailed": "Не вдалося зберегти. Спробуйте ще раз.","botLimit.paused.chooseAction": "Вибрати активних ботів (призупинено: {count})",+ "botLimit.created.title": "{name} створено, поки що на паузі",+ "botLimit.created.body": "Starter тримає активними {count} ботів, тому цей призупинено. Виберіть, які {count} залишаться активними, або перейдіть на вищий план, щоб розбудити всіх.","chat.compactionExcerptTitle": "Попередній контекст скорочено до останніх уривків","chat.compactionExcerptHint": "Письмового підсумку не було, тож агент продовжує з цих уривків і останніх повідомлень. Давніших подробиць може бракувати в його контексті. Уся ваша розмова досі тут.","chat.turnStoppedByYou": "Ви це зупинили.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex db2c54ee38..7268fcd0e7 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5048,6 +5048,8 @@"botLimit.paused.badge": "Tạm dừng","botLimit.paused.saveFailed": "Không lưu được. Hãy thử lại.","botLimit.paused.chooseAction": "Chọn bot hoạt động ({count} đang tạm dừng)",+ "botLimit.created.title": "Đã tạo {name}, tạm dừng lúc này",+ "botLimit.created.body": "Starter giữ {count} bot hoạt động, nên bot này đang tạm dừng. Chọn {count} bot tiếp tục hoạt động, hoặc nâng cấp để đánh thức tất cả.","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 9c8d7de015..eceb74ec18 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -7520,6 +7520,8 @@"botLimit.paused.badge": "已暫停","botLimit.paused.saveFailed": "無法儲存,請再試一次。","botLimit.paused.chooseAction": "選擇保持運作的機器人({count} 個已暫停)",+ "botLimit.created.title": "已建立 {name},暫時暫停",+ "botLimit.created.body": "Starter 只讓 {count} 個機器人保持運作,所以這個已暫停。選擇要保持運作的 {count} 個,或升級以喚醒全部。","roomCard.restartNow": "立即重新啟動","roomCard.restartHint": "大約需要一分鐘,並會停止目前正在執行的工作。","roomCard.restarting": "正在以新的大小重新啟動這個 Cloud,大約一分鐘後就會恢復。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 3920c58db1..bace5e00f8 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7269,6 +7269,8 @@"botLimit.paused.badge": "已暂停","botLimit.paused.saveFailed": "无法保存,请重试。","botLimit.paused.chooseAction": "选择在线的机器人({count} 个已暂停)",+ "botLimit.created.title": "已创建 {name},暂时暂停",+ "botLimit.created.body": "Starter 只让 {count} 个机器人保持在线,所以这个已暂停。选择保持在线的 {count} 个,或升级以唤醒全部。","roomCard.restartNow": "立即重启","roomCard.restartHint": "大约需要一分钟,并且会停止当前正在运行的任务。","roomCard.restarting": "正在以新容量重启此 Cloud,大约一分钟后恢复。",diff --git a/src/state/bot-limit-actions.test.ts b/src/state/bot-limit-actions.test.tsindex 161368b035..53e2aae861 100644--- a/src/state/bot-limit-actions.test.ts+++ b/src/state/bot-limit-actions.test.ts@@ -24,7 +24,7 @@ const json = (body: unknown, status = 200) => Promise.resolve(new Response(JSON.const { StoreProvider, useStore } = await import("./store");const { api, ApiError } = await import("./api");-const { botLimitShown, closeBotLimit } = await import("@/lib/bot-limit");+const { botLimitReason, botLimitShown, closeBotLimit, createdPausedBot } = await import("@/lib/bot-limit");let seen!: AppState;let dispatch!: Dispatch<Action>;@@ -82,7 +82,7 @@ afterEach(async () => {vi.unstubAllGlobals();});-describe("a create button with no room", () => {+describe("a create button with no room, on an older server that caps Starter's bots", () => {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);@@ -118,7 +118,19 @@ describe("a create button with no room", () => {});});-describe("the server's refusal, when the page's count was stale", () => {+describe("a sixth bot on a Starter Cloud that makes any number", () => {+ it.each<[string, Action]>([["New bot", { type: "newBot" }], ["Duplicate", { type: "duplicateBot", botId: "b0" }]])("%s makes it and offers to swap it in", async (_name, action) => {+ await mount(five(), { cloudStarter: true, awakeLimit: 5 });+ created = () => json({ bot: botNamed("sixth"), paused: true }, 201);+ await send(action);+ await vi.waitFor(() => expect(creates).toBe(1));+ await vi.waitFor(() => expect([botLimitReason(), createdPausedBot()]).toEqual(["created", "sixth"]));+ expect(seen.bots.map((bot) => bot.id)).toContain("sixth");+ expect(seen.error).toBeNull();+ });+});++describe("an older 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);diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex 4aef3c6f20..5ab7aaffa6 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -58,7 +58,7 @@ 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. */+ /** The most bots this Cloud's plan makes, its MausBot aside. Sent only by servers that capped Starter's bots; absent otherwise. */botLimit?: number;/** A task on this Cloud is waiting for memory right now. */waitingForRoom?: boolean;diff --git a/src/state/store.tsx b/src/state/store.tsxindex c7e17b7b22..81462941e0 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 { isBotLimitRefusal, stoppedAtBotLimit } from "@/lib/bot-limit";+import { askResetBridge, desktopCapabilitiesNow } from "@/lib/desktop"; import { isBotLimitRefusal, showCreatedPaused, stoppedAtBotLimit } from "@/lib/bot-limit";import { sameModelSelection } from "../../shared/thread-model";import type { BotBodyId } from "../../shared/bot-body";import { StoreRefContext } from "./store-ref-context";@@ -2619,13 +2619,14 @@ export function StoreProvider({ children }: { children: ReactNode }) {method: "POST",body: JSON.stringify(restrictedCopyRequest(source)),})- .then(({ bot }) =>+ .then(({ bot, paused }) =>api(`/api/bots/${bot.id}`, {method: "PATCH",body: JSON.stringify(duplicateProfile),- }).then(({ bot: patched }) =>- rawDispatch({ type: "botAdded", bot: { ...bot, ...patched, messages: bot.messages } }),- ),+ }).then(({ bot: patched }) => {+ rawDispatch({ type: "botAdded", bot: { ...bot, ...patched, messages: bot.messages } });+ if (paused) showCreatedPaused(bot.id);+ }),).catch(showError);break;