Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Pause every bot: one call and one menu item on the existing pause (#6158)

Milind Soni9f04922546a2
diff --git a/docs/pausing-bots.md b/docs/pausing-bots.md
index 471bd9ac1e..0bcfa24ba1 100644
--- a/docs/pausing-bots.md
+++ b/docs/pausing-bots.md
@@ -1,9 +1,12 @@
-# Pausing a bot or a department
+# Pausing a bot, a department or every bot
**Pause bot** (a bot's menu in the sidebar, under More) and **Pause department** (a department's menu) stop
everything that bot or department is doing and keep it from starting anything new, until you choose **Resume**.
It is the one switch for "stop all effort for now", for example to save what is left of a plan's usage.
+**Pause every bot** (any bot's menu, under More) does the same for all bots at once, the ones made later included,
+until **Resume every bot**.
+
## What pausing does
Right away, for every bot it pauses:
@@ -25,17 +28,21 @@ shows **Paused** under its name in the sidebar.
A bot is paused by itself, or with its department. One paused with its department is resumed from the department's
menu. A department keeps its pause when it is renamed; a bot moved into a paused department is paused with it.
+While every bot is paused, each one says so; resuming every bot leaves a bot or department that was paused by itself
+paused.
## Who can pause
The owner of the server, or an admin on a Team Cloud. Each pause and resume is recorded in the admin activity log
-(`bot.pause`, `bot.resume`, `department.pause`, `department.resume`).
+(`bot.pause`, `bot.resume`, `department.pause`, `department.resume`, `all.pause`, `all.resume`).
This is separate from the Starter plan keeping only some bots awake: a bot can be paused for either reason, and is
resumed for each in its own place.
## API
-- `GET /api/paused`: `{ bots, departments, heldBots }`, what is paused and every bot that is held because of it.
+- `GET /api/paused`: `{ bots, departments, heldBots }`, what is paused and every bot that is held because of it;
+ `all: true` is there while every bot is paused.
- `POST /api/paused` with `{ "kind": "bot" | "department", "id": "<bot id or department name>", "paused": true | false }`:
answers with the new state and `stopped`, how many conversations it stopped.
+- `POST /api/paused` with `{ "kind": "all", "paused": true | false }` pauses or resumes every bot, with the same answer.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 972ef371cd..cefe068b24 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1489,6 +1489,49 @@ turn's tools runs, the turn may show nothing for up to 60 minutes (the longest
an MCP call can be set to take) or the room's limit if that is longer. These two
settings do not change it.
+## Keeping unattended bots from spending on failures
+
+Work that nobody is watching (a routine, an event, work one bot hands to
+another) backs off when it keeps failing, and has an upper bound when it keeps
+going. Nothing here turns a routine off or asks you anything. Each limit that
+stops something leaves one line saying so, on the routine's run row or in the
+thread. A failure that is this server's own (it could not start another
+process, its disk is full, a tool server is down, an AI is signed out) is told
+apart from the AI's errors, because starting the same work again cannot fix it.
+
+### Routines and incidents
+
+A routine stays on however often it fails.
+
+### Hand-offs and unattended turns
+
+A turn with a person waiting in the chat keeps the limits described under
+"A turn that goes silent".
+
+### Pausing every bot
+
+A paused bot's routines skip quietly and leave a row saying so.
+
+**Pause every bot** (any bot's menu in the sidebar, under More) pauses all of
+them at once, the bots made later included. It is the same pause as
+**Pause bot** ([Pausing a bot, a department or every bot](pausing-bots.md)): work in
+progress stops as Stop does, and until **Resume every bot** each routine or
+webhook run that comes due is let go with one line in its run log, "Every bot
+is paused, so <bot> takes no new work. Resume every bot from any bot's menu in
+the sidebar." A message to a bot is refused with the same line. Resuming leaves
+a bot or department that was paused by itself paused.
+
+From a terminal on the server, to stop spending at once (an admin route like
+any other: see "Loopback trust: owner or service"):
+
+```sh
+curl -X POST http://127.0.0.1:8799/api/paused \
+ -H 'content-type: application/json' -d '{"kind":"all","paused":true}'
+```
+
+It has no setting: the pause is kept in `paused-bots.json` in the data
+directory and lasts across restarts until it is resumed.
+
## Updating
Self-hosted servers follow the **stable** channel: a released version that our
diff --git a/server/host-fault.test.ts b/server/host-fault.test.ts
new file mode 100644
index 0000000000..2aaa60404f
--- /dev/null
+++ b/server/host-fault.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { hostFaultOf } from "./host-fault.ts";
+
+describe("hostFaultOf", () => {
+ it.each([
+ ["spawn /usr/local/bin/claude EAGAIN", "process_start"],
+ ["Error: spawn EMFILE", "process_start"],
+ ["posix_spawn failed: ENOMEM", "process_start"],
+ ["fork: Resource temporarily unavailable", "process_start"],
+ ["EMFILE: too many open files, open '/data/x'", "process_start"],
+ ["ENOSPC: no space left on device, write", "disk_full"],
+ ["write failed: Disk quota exceeded", "disk_full"],
+ ["MCP server could not start; check its command and installation", "tool_server"],
+ ["MCP server exited before the session closed. last words", "tool_server"],
+ ['MCP server "crm" is not connected', "tool_server"],
+ ['The "crm" MCP server couldn\'t be set up, so Claude couldn\'t start this reply.', "tool_server"],
+ ["MCP startup timed out", "tool_server"],
+ ["401 Unauthorized", "signed_out"],
+ ["Not logged in · Please run /login", "signed_out"],
+ ] as const)("%s is %s", (failure, fault) => {
+ expect(hostFaultOf(failure)).toBe(fault);
+ });
+
+ it("reads the engine's own stop reason for a sign-in", () => {
+ expect(hostFaultOf("The turn ended", "auth_required")).toBe("signed_out");
+ });
+
+ it.each([
+ "503 Service Unavailable",
+ "429 rate limit exceeded",
+ "ECONNRESET",
+ "socket hang up",
+ "The AI stopped before it answered",
+ "read EAGAIN",
+ "Tool search_crm failed: record not found",
+ ])("%s is not this server's fault", (failure) => {
+ expect(hostFaultOf(failure)).toBeNull();
+ });
+});
diff --git a/server/host-fault.ts b/server/host-fault.ts
new file mode 100644
index 0000000000..4f0383d8bb
--- /dev/null
+++ b/server/host-fault.ts
@@ -0,0 +1,35 @@
+// A failure whose cause is this server, one of its tool servers or a sign-in, not the AI's work: starting the same work
+// again meets it again and spends the person's AI budget for nothing. Read from the failure's own words, so every caller
+// (a routine's second start, a Chief's incident, a hand-off's resume, the turn admission) judges one failure one way.
+import { classifyError } from "./drivers/retry.ts";
+
+/** process_start: the server could not start another process (out of processes, file handles or memory);
+ * disk_full: no room left to write; tool_server: an MCP server did not start, died or needs its own sign-in;
+ * signed_out: the bot's AI needs signing in again. */
+export type HostFault = "process_start" | "disk_full" | "tool_server" | "signed_out";
+
+const EXHAUSTED = String.raw`(?:EAGAIN|EMFILE|ENFILE|ENOMEM)`;
+const PROCESS_START = new RegExp(
+ String.raw`\b(?:posix_)?spawn(?:Sync)?\b[^\n]*\b${EXHAUSTED}\b|\b${EXHAUSTED}\b[^\n]*\b(?:posix_)?spawn\b` +
+ String.raw`|\bfork\b[^\n]*\b(?:resource temporarily unavailable|cannot allocate memory)\b|\btoo many open files\b|\bcannot allocate memory\b`, "i");
+const DISK_FULL = /\bno space left on device\b|\bENOSPC\b|\bdisk quota exceeded\b|\bEDQUOT\b/i;
+const TOOL_SERVER = new RegExp(
+ String.raw`\bMCP server\b[^\n]*\b(?:could not start|couldn't be set up|failed to start|exited|input closed|stdin (?:is )?closed|is not connected|session expired|needs (?:a sign-in|authentication)|refused the sign-in)\b` +
+ String.raw`|\bMCP (?:request|startup) timed out\b|\bMCP session closed\b|\bCould not reach this MCP server\b`, "i");
+
+/** Which such fault a failure's words name; null for anything else, the AI's own errors and its provider's among them. */
+export function hostFaultOf(failure: string, stopReason?: string | null): HostFault | null {
+ if (PROCESS_START.test(failure)) return "process_start";
+ if (DISK_FULL.test(failure)) return "disk_full";
+ if (TOOL_SERVER.test(failure)) return "tool_server";
+ if (stopReason === "auth_required" || classifyError({ text: failure }).reason === "auth") return "signed_out";
+ return null;
+}
+
+/** The fault in the words a model is given, to follow "because". */
+export const HOST_FAULT_WHY: Readonly<Record<HostFault, string>> = {
+ process_start: "this server could not start another process",
+ disk_full: "this server's disk is full",
+ tool_server: "one of its tool servers is not running or not signed in",
+ signed_out: "its AI is signed out",
+};
diff --git a/server/host/bot-holds.test.ts b/server/host/bot-holds.test.ts
index 44379496ee..380f630371 100644
--- a/server/host/bot-holds.test.ts
+++ b/server/host/bot-holds.test.ts
@@ -70,6 +70,30 @@ describe("pausing a bot or a department", () => {
});
});
+describe("pausing every bot", () => {
+ it("holds every bot, says so, survives a restart, and ending it leaves the earlier pauses in place", () => {
+ const { make, dataDir, bots } = setup();
+ const holds = make();
+ holds.set("bot", "cy", true);
+ expect(holds.set("all", "", true).newlyHeld).toEqual(["ada", "bo", "di"]);
+ expect(holds.state()).toEqual({ bots: ["cy"], departments: [], all: true });
+ expect(holds.heldBots()).toEqual(["ada", "bo", "cy", "di"]);
+ expect(holds.text("cy")).toBe("server.botHeldAll:Cy");
+ expect(holds.handoff("di")).toContain("@Di is paused by the person (every bot is paused)");
+ bots.push({ id: "ed", name: "Ed" });
+ expect(holds.held("ed")).toBe(true);
+ expect(JSON.parse(readFileSync(join(dataDir, "paused-bots.json"), "utf8"))).toMatchObject({ bots: ["cy"], all: true });
+ expect(make().heldBots()).toEqual(["ada", "bo", "cy", "di", "ed"]);
+ expect(holds.set("all", "", true).newlyHeld).toEqual([]);
+
+ expect(holds.set("all", "", false).newlyHeld).toEqual([]);
+ expect(holds.state()).toEqual({ bots: ["cy"], departments: [] });
+ expect(holds.heldBots()).toEqual(["cy"]);
+ expect(holds.text("cy")).toBe("server.botHeld:Cy");
+ expect(make().state()).toEqual({ bots: ["cy"], departments: [] });
+ });
+});
+
describe("the pause routes", () => {
function call(routes: ReturnType<typeof createBotHoldRoutes>, method: string, body?: unknown) {
const out: { status?: number; body?: Record<string, unknown> } = {};
@@ -101,4 +125,28 @@ describe("the pause routes", () => {
expect(await call(routes, "POST", { kind: "bot", id: "nobody", paused: true })).toMatchObject({ status: 404 });
expect(await call(routes, "POST", { kind: "room", id: "x", paused: true })).toMatchObject({ status: 400 });
});
+
+ it("pauses every bot in one call, stops the ones that were still working, and records it", async () => {
+ const { make } = setup();
+ const holds = make();
+ holds.set("bot", "ada", true);
+ const stop = vi.fn(async (ids: readonly string[]) => ids.length);
+ const audit = vi.fn();
+ const named = vi.fn(() => null);
+ const routes = createBotHoldRoutes({ holds, stop, audit, named });
+
+ expect(await call(routes, "POST", { kind: "all", paused: true })).toMatchObject({ status: 200, body: { all: true, bots: ["ada"], heldBots: ["ada", "bo", "cy", "di"], stopped: 3 } });
+ expect(stop.mock.calls).toEqual([[["bo", "cy", "di"]]]);
+ expect(await call(routes, "GET")).toMatchObject({ status: 200, body: { all: true, heldBots: ["ada", "bo", "cy", "di"] } });
+ const resumed = await call(routes, "POST", { kind: "all", paused: false });
+ expect(resumed).toMatchObject({ status: 200, body: { bots: ["ada"], heldBots: ["ada"], stopped: 0 } });
+ expect(resumed.body).not.toHaveProperty("all");
+ expect(stop).toHaveBeenCalledTimes(1);
+ expect(named).not.toHaveBeenCalled();
+ expect(audit.mock.calls.map(([entry]) => entry)).toEqual([
+ { kind: "all", id: "all", name: "Every bot", paused: true },
+ { kind: "all", id: "all", name: "Every bot", paused: false },
+ ]);
+ expect(await call(routes, "POST", { kind: "all" })).toMatchObject({ status: 400 });
+ });
});
diff --git a/server/host/bot-holds.ts b/server/host/bot-holds.ts
index ca799997e7..1a68d4e89b 100644
--- a/server/host/bot-holds.ts
+++ b/server/host/bot-holds.ts
@@ -1,6 +1,6 @@
-// Bots the person paused: one bot, or every bot in a department, takes no new work until it is resumed.
-// <data>/paused-bots.json keeps which bots and departments are paused; a bot is paused when it is named, or its
-// department is. Every way work starts asks here, beside the Starter plan's own pause (starter-caps.ts): a person's
+// Bots the person paused: one bot, every bot in a department, or every bot there is takes no new work until it is
+// resumed. <data>/paused-bots.json keeps which bots and departments are paused and whether all are; a bot is paused when
+// it is named, its department is, or all are. Every way work starts asks here, beside the Starter plan's own pause (starter-caps.ts): a person's
// message, the bot API, a routine or webhook run, a hand-off from another bot, and its turn in a room.
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -11,20 +11,24 @@ import { sectionKey } from "../store.ts";
export interface PausedState {
bots: string[];
departments: string[];
+ /** Every bot is paused, whatever else is. Ending it leaves the bots and departments above paused. */
+ all?: true;
}
+export type PauseKind = "bot" | "department" | "all";
+
export interface BotHolds {
- /** The bot takes no new work: it, or its department, is paused. */
+ /** The bot takes no new work: it, its department, or every bot is paused. */
held(botId: string): boolean;
- /** Every paused bot, by itself or with its department. */
+ /** Every paused bot, by itself, with its department or with all. */
heldBots(): string[];
state(): PausedState;
/** The words a paused bot's turn is refused with, in this language; null when it is not paused. */
text(botId: string, language?: string): string | null;
/** What a bot that tried to hand it work is told; null when it is not paused. */
handoff(botId: string): string | null;
- /** Pauses or resumes one bot or one department; the bots that became paused, so their running work can be stopped. */
- set(kind: "bot" | "department", id: string, paused: boolean): { state: PausedState; newlyHeld: string[] };
+ /** Pauses or resumes one bot, one department, or all bots (`id` is then unused); the bots that became paused, so their running work can be stopped. */
+ set(kind: PauseKind, id: string, paused: boolean): { state: PausedState; newlyHeld: string[] };
/** A bot or department that is gone stops being remembered. */
forget(kind: "bot" | "department", id: string): void;
/** A paused department that is renamed stays paused under its new name. */
@@ -35,7 +39,7 @@ export function createBotHolds(deps: {
dataDir: string;
bots(): ReadonlyArray<{ id: string; name: string; section?: string }>;
/** serverLine(language, key, params) */
- line(language: string | undefined, key: "server.botHeld" | "server.botHeldDepartment", params: Record<string, string>): string;
+ line(language: string | undefined, key: "server.botHeld" | "server.botHeldDepartment" | "server.botHeldAll", params: Record<string, string>): string;
changed(): void;
}): BotHolds {
const file = join(deps.dataDir, "paused-bots.json");
@@ -45,7 +49,7 @@ export function createBotHolds(deps: {
try {
const raw = JSON.parse(readFileSync(file, "utf8")) as Partial<PausedState>;
const list = (value: unknown) => (Array.isArray(value) ? [...new Set(value.filter((item): item is string => typeof item === "string" && item.length > 0 && item.length <= 200))] : []);
- return { bots: list(raw.bots), departments: list(raw.departments) };
+ return { bots: list(raw.bots), departments: list(raw.departments), ...(raw.all === true ? { all: true } : {}) };
} catch {
return { bots: [], departments: [] };
}
@@ -61,30 +65,36 @@ export function createBotHolds(deps: {
const key = sectionKey(found?.section);
return key && state.departments.includes(key) ? key : null;
};
- const held = (botId: string) => state.bots.includes(botId) || department(bot(botId)) !== null;
+ const held = (botId: string) => state.all === true || state.bots.includes(botId) || department(bot(botId)) !== null;
return {
held,
- heldBots: () => deps.bots().filter((candidate) => state.bots.includes(candidate.id) || department(candidate) !== null).map((candidate) => candidate.id),
- state: () => ({ bots: [...state.bots], departments: [...state.departments] }),
+ heldBots: () => deps.bots().filter((candidate) => held(candidate.id)).map((candidate) => candidate.id),
+ state: () => ({ bots: [...state.bots], departments: [...state.departments], ...(state.all ? { all: true as const } : {}) }),
text(botId, language) {
const found = bot(botId);
if (!found || !held(botId)) return null;
+ if (state.all) return deps.line(language, "server.botHeldAll", { bot: found.name });
const by = state.bots.includes(botId) ? null : department(found);
return by ? deps.line(language, "server.botHeldDepartment", { bot: found.name, department: by }) : deps.line(language, "server.botHeld", { bot: found.name });
},
handoff(botId) {
const found = bot(botId);
if (!found || !held(botId)) return null;
+ if (state.all) return `@${found.name} is paused by the person (every bot is paused), so nothing was handed to it. `
+ + "Tell the person in one line that they can resume every bot from any bot's menu in the sidebar. Do not retry, and do not hand this to another bot to work around the pause.";
return `@${found.name} is paused by the person${state.bots.includes(botId) ? "" : ` (its ${department(found)} department is paused)`}, so nothing was handed to it. `
+ "Tell the person in one line that they can resume it from its menu in the sidebar. Do not retry, and do not hand this to another bot to work around the pause.";
},
set(kind, id, paused) {
const before = new Set(this.heldBots());
- const key = kind === "department" ? sectionKey(id) : id;
- const list = kind === "bot" ? state.bots : state.departments;
- const next = paused ? [...new Set([...list, key])] : list.filter((item) => item !== key);
- state = kind === "bot" ? { ...state, bots: next } : { ...state, departments: next };
+ if (kind === "all") state = { bots: state.bots, departments: state.departments, ...(paused ? { all: true as const } : {}) };
+ else {
+ const key = kind === "department" ? sectionKey(id) : id;
+ const list = kind === "bot" ? state.bots : state.departments;
+ const next = paused ? [...new Set([...list, key])] : list.filter((item) => item !== key);
+ state = kind === "bot" ? { ...state, bots: next } : { ...state, departments: next };
+ }
save();
return { state: this.state(), newlyHeld: this.heldBots().filter((botId) => !before.has(botId)) };
},
diff --git a/server/pause-all.e2e.test.ts b/server/pause-all.e2e.test.ts
new file mode 100644
index 0000000000..ab2c587864
--- /dev/null
+++ b/server/pause-all.e2e.test.ts
@@ -0,0 +1,78 @@
+// Pausing every bot on a real server whose AI is the scripted Claude engine: FAKE_CLAUDE_PROMPTS gets one line per
+// model turn, so the test counts what the pause saved.
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, expect, it } from "vitest";
+
+import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+let fixture: VerificationServer;
+const logDir = mkdtempSync(join(tmpdir(), "omb-pause-all-"));
+const promptLog = join(logDir, "prompts.jsonl");
+const modelRequests = () => {
+ try { return readFileSync(promptLog, "utf8").split("\n").filter(Boolean).length; } catch { return 0; }
+};
+const call = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(fixture.info.url + path, {
+ method, headers: { "content-type": "application/json", origin: fixture.info.url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json().catch(() => ({})) as Record<string, any> };
+};
+const ok = async (method: string, path: string, body?: unknown) => {
+ const answer = await call(method, path, body);
+ expect(answer.status, `${method} ${path}: ${JSON.stringify(answer.body)}`).toBeLessThan(300);
+ return answer.body;
+};
+type FixtureBot = { id: string; activeTaskId: string };
+const newBot = async (name: string) => (await runControlOmb(["new-bot", "--name", name, "--url", fixture.info.url]) as { bot: FixtureBot }).bot;
+const send = (bot: FixtureBot, text: string) => call("POST", `/api/bots/${bot.id}/messages`, { text, threadId: bot.activeTaskId, sendId: randomUUID() });
+const dueSoon = async (bot: FixtureBot, name: string, inMs: number) =>
+ (await ok("POST", "/api/routines", { name, prompt: `Do ${name}.`, botId: bot.id, schedule: { type: "once", at: Date.now() + inMs } })).routine as { id: string };
+const runsOf = async (routineIds: string[]) => ((await ok("GET", "/api/routines")).runs as Array<{ routineId: string; status: string; error?: string }>)
+ .filter((run) => routineIds.includes(run.routineId));
+
+beforeAll(async () => { fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_PROMPTS: promptLog }); }, 120_000);
+afterAll(async () => { await fixture?.close(); await removeTempDir(logDir); });
+
+it("pausing every bot stops what the routines spend, each due run leaving its row, and resuming brings them back", async () => {
+ const chief = ((await ok("GET", "/api/bots")).bots as Array<{ id: string; chiefOfStaff?: boolean }>).find((bot) => bot.chiefOfStaff);
+ if (chief) await ok("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: false });
+ const bots = [await newBot("Ada"), await newBot("Bo"), await newBot("Cy")];
+ const everyBot = ((await ok("GET", "/api/bots")).bots as Array<{ id: string }>).map((bot) => bot.id).sort();
+
+ const before = await Promise.all(bots.map((bot, index) => dueSoon(bot, `Morning ${index}`, 1_500)));
+ await expect.poll(async () => (await runsOf(before.map((routine) => routine.id))).map((run) => run.status), { timeout: 60_000 }).toEqual(["completed", "completed", "completed"]);
+ const spentUnpaused = modelRequests();
+ expect(spentUnpaused).toBe(3);
+
+ await ok("POST", "/api/paused", { kind: "bot", id: bots[0]!.id, paused: true });
+ const during = await Promise.all(bots.map((bot, index) => dueSoon(bot, `Noon ${index}`, 4_000)));
+ const paused = await ok("POST", "/api/paused", { kind: "all", paused: true });
+ expect(paused).toMatchObject({ all: true, bots: [bots[0]!.id], departments: [] });
+ expect([...paused.heldBots as string[]].sort()).toEqual(everyBot);
+ expect((await ok("GET", "/api/config")).pausedByPerson).toMatchObject({ all: true });
+
+ await expect.poll(async () => (await runsOf(during.map((routine) => routine.id))).map((run) => run.status), { timeout: 60_000 }).toEqual(["cancelled", "cancelled", "cancelled"]);
+ const rows = await runsOf(during.map((routine) => routine.id));
+ expect(rows.map((run) => run.error).sort()).toEqual(["Ada", "Bo", "Cy"].map((name) =>
+ `Every bot is paused, so ${name} takes no new work. Resume every bot from any bot’s menu in the sidebar.`));
+ const refused = await send(bots[1]!, "Hello.");
+ expect(refused.status).toBe(409);
+ expect(refused.body).toMatchObject({ code: "bot_held" });
+ expect(modelRequests() - spentUnpaused).toBe(0);
+
+ const resumed = await ok("POST", "/api/paused", { kind: "all", paused: false });
+ expect(resumed).toMatchObject({ bots: [bots[0]!.id], heldBots: [bots[0]!.id], stopped: 0 });
+ expect(resumed.all).toBeUndefined();
+ const after = [await dueSoon(bots[1]!, "Evening", 1_000)];
+ await expect.poll(async () => (await runsOf(after.map((routine) => routine.id))).map((run) => run.status), { timeout: 60_000 }).toEqual(["completed"]);
+ expect(modelRequests() - spentUnpaused).toBe(1);
+ expect((await send(bots[0]!, "Still paused?")).status).toBe(409);
+ expect((await call("POST", "/api/paused", { kind: "all", id: "x", paused: true })).status).toBe(400);
+ const fromTerminal = await fetch(`${fixture.info.url}/api/paused`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ kind: "all", paused: true }) });
+ expect(fromTerminal.status).toBe(200);
+ expect(await fromTerminal.json()).toMatchObject({ all: true });
+}, 240_000);
diff --git a/server/routes/bot-holds.ts b/server/routes/bot-holds.ts
index 0ab27724c5..00f6b118f5 100644
--- a/server/routes/bot-holds.ts
+++ b/server/routes/bot-holds.ts
@@ -1,9 +1,9 @@
-// Pausing a bot or a department: GET what is paused; POST {kind, id, paused} pauses or resumes one, and pausing
-// also stops the work its bots are doing now. Admin-scope routes: on a Team Cloud only an owner or admin pauses.
+// Pausing a bot, a department or every bot: GET what is paused; POST {kind, id, paused} pauses or resumes one
+// ({kind: "all", paused} every bot), and pausing also stops the work its bots are doing now. Admin-scope routes: on a Team Cloud only an owner or admin pauses.
import type { IncomingMessage } from "node:http";
import { z } from "zod";
-import type { BotHolds } from "../host/bot-holds.ts";
+import type { BotHolds, PauseKind } from "../host/bot-holds.ts";
import type { RequestAuth } from "../request-auth.ts";
import { PASS, type RouteHandler } from "./table.ts";
@@ -14,10 +14,15 @@ export interface BotHoldRouteDeps {
/** Stops every running turn, routine run and hand-off of these bots; how many conversations it stopped. */
stop(botIds: readonly string[]): Promise<number>;
/** Records the change in the admin activity log. */
- audit(entry: { kind: "bot" | "department"; id: string; name: string; paused: boolean }, auth: RequestAuth, req: IncomingMessage): void;
+ audit(entry: { kind: PauseKind; id: string; name: string; paused: boolean }, auth: RequestAuth, req: IncomingMessage): void;
}
-const body = z.object({ kind: z.enum(["bot", "department"]), id: z.string().trim().min(1).max(200), paused: z.boolean() }).strict();
+const body = z.union([
+ z.object({ kind: z.enum(["bot", "department"]), id: z.string().trim().min(1).max(200), paused: z.boolean() }).strict(),
+ z.object({ kind: z.literal("all"), paused: z.boolean() }).strict(),
+]);
+/** What the admin activity log names an all-bots pause by. */
+const ALL = { id: "all", name: "Every bot" };
export function createBotHoldRoutes(deps: BotHoldRouteDeps): RouteHandler {
return async ({ req, res, path, method, auth, json, readBody }) => {
@@ -25,9 +30,10 @@ export function createBotHoldRoutes(deps: BotHoldRouteDeps): RouteHandler {
if (method === "GET") return void json(res, 200, { ...deps.holds.state(), heldBots: deps.holds.heldBots() });
if (method !== "POST") return PASS;
const parsed = body.safeParse(await readBody(req, 4_096).catch(() => null));
- if (!parsed.success) return void json(res, 400, { error: "Send kind (bot or department), id and paused (true or false)." });
- const { kind, id, paused } = parsed.data;
- const name = deps.named(kind, id);
+ if (!parsed.success) return void json(res, 400, { error: "Send kind (bot or department) with id, or kind all, and paused (true or false)." });
+ const { kind, paused } = parsed.data;
+ const id = parsed.data.kind === "all" ? ALL.id : parsed.data.id;
+ const name = parsed.data.kind === "all" ? ALL.name : deps.named(parsed.data.kind, id);
if (name === null) return void json(res, 404, { error: kind === "bot" ? "No such bot." : "No such department." });
const { state, newlyHeld } = deps.holds.set(kind, id, paused);
const stopped = paused && newlyHeld.length ? await deps.stop(newlyHeld) : 0;
diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsx
index 67a2f13b22..3a4685b259 100644
--- a/src/components/SidebarBotMenu.tsx
+++ b/src/components/SidebarBotMenu.tsx
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Archive, BellDot, Check, CheckCheck, ChevronRight, ClipboardCopy, Copy, Crown, FolderMinus, FolderOpen, FolderPlus, Loader2, MessagesSquare, MoreHorizontal, Pause, Pencil, Pin, PinOff, Play, SquarePen, Star, Trash2, Users } from "lucide-react";
-import { isBotHeld, isPausedHere, setPaused } from "@/lib/bot-pause";
+import { isBotHeld, isEveryBotPaused, isPausedHere, setEveryBotPaused, setPaused } from "@/lib/bot-pause";
import { api, useStore, openBot, type Bot } from "@/state/store";
import { cn } from "@/lib/cn";
import { useHeldMenuMotion } from "./MenuMotion";
@@ -264,14 +264,18 @@ export function BotContextMenu({
)
: item(<BellDot size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.markUnread"), () => dispatch({ type: "markUnread", botId: bot.id }));
// Only the owner or an admin pauses; a bot paused with its department is resumed from the department's menu.
- const pausedHere = isPausedHere(state.config, "bot", bot.id);
+ const pausedHere = isPausedHere(state.config, "bot", bot.id), everyBotPaused = isEveryBotPaused(state.config);
const pause = admin !== true ? null : item(pausedHere ? <Play size={16} className="text-ink-secondary" /> : <Pause size={16} className="text-ink-secondary" />,
t(pausedHere ? "pause.resumeBot" : "pause.pauseBot"),
() => { void setPaused("bot", bot.id, !pausedHere).catch((error: unknown) => dispatch({ type: "error", message: error instanceof Error ? error.message : String(error) })); },
- !pausedHere && isBotHeld(state.config, bot.id) ? { disabled: true, hint: t("pause.byDepartment") } : undefined);
+ !pausedHere && isBotHeld(state.config, bot.id) ? { disabled: true, hint: t(everyBotPaused ? "pause.byAll" : "pause.byDepartment") } : undefined);
+ const pauseAll = admin !== true ? null : item(everyBotPaused ? <Play size={16} className="text-ink-secondary" /> : <Pause size={16} className="text-ink-secondary" />,
+ t(everyBotPaused ? "pause.resumeAll" : "pause.pauseAll"),
+ () => { void setEveryBotPaused(!everyBotPaused).catch((error: unknown) => dispatch({ type: "error", message: error instanceof Error ? error.message : String(error) })); });
const moreItems = remoteClient ? [editProfile, owner, ...deleteAll] : [
editProfile,
pause,
+ pauseAll,
team ? null : chiefItem(),
member && !ownEdit ? null : item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () => dispatch({ type: "duplicateBot", botId: bot.id })),
owner,
diff --git a/src/components/SidebarBotRead.test.ts b/src/components/SidebarBotRead.test.ts
index d4cc09a72e..5df9454106 100644
--- a/src/components/SidebarBotRead.test.ts
+++ b/src/components/SidebarBotRead.test.ts
@@ -157,6 +157,29 @@ describe("Simple mode's bot menu", () => {
expect([...flyout()!.querySelectorAll("button")].map((node) => node.textContent)).not.toContain("Delete all conversations…");
});
+ it("pauses every bot from More in one call, and offers Resume every bot while they are paused", async () => {
+ const fetch = vi.fn(async (_url: unknown, _init?: RequestInit) => new Response(JSON.stringify({ stopped: 0 }), { headers: { "content-type": "application/json" } }));
+ vi.stubGlobal("fetch", fetch); draw();
+ flushSync(() => more().click());
+ const labels = () => [...flyout()!.querySelectorAll<HTMLButtonElement>("button")];
+ flushSync(() => labels().find((node) => node.textContent === "Pause every bot")!.click());
+ await wait(20);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(String(fetch.mock.calls[0]![0])).toContain("/api/paused");
+ expect(JSON.parse(String(fetch.mock.calls[0]![1]?.body))).toEqual({ kind: "all", paused: true });
+
+ state = { ...state, config: { ...state.config!, pausedByPerson: { bots: [], departments: [], all: true }, heldBots: [bot.id] } };
+ menu = { botId: bot.id, x: 50, y: 50 };
+ draw();
+ flushSync(() => more().click());
+ expect(labels().map((node) => node.textContent)).toContain("Resume every bot");
+ const own = labels().find((node) => node.textContent?.startsWith("Pause bot"))!;
+ expect(own.disabled).toBe(true);
+ flushSync(() => labels().find((node) => node.textContent === "Resume every bot")!.click());
+ await wait(20);
+ expect(JSON.parse(String(fetch.mock.calls[1]![1]?.body))).toEqual({ kind: "all", paused: false });
+ });
+
it("opens More only after the pointer rests on it, closes it when a sibling row takes the pointer, and opens it at once on a click", async () => {
draw();
const pin = button("Pin");
@@ -169,7 +192,7 @@ describe("Simple mode's bot menu", () => {
point(more(), 200);
await wait(320);
expect(flyout()).not.toBeNull();
- expect([...flyout()!.querySelectorAll("button")].map((node) => node.textContent)).toEqual(["Edit profile", "Pause bot", "Make Chief of Staff", "Duplicate", "Delete all conversations…"]);
+ expect([...flyout()!.querySelectorAll("button")].map((node) => node.textContent)).toEqual(["Edit profile", "Pause bot", "Pause every bot", "Make Chief of Staff", "Duplicate", "Delete all conversations…"]);
point(pin, 80);
await wait(20);
expect(flyout()).toBeNull();
diff --git a/src/lib/bot-pause.ts b/src/lib/bot-pause.ts
index c5ef919bdf..005ae5a5a9 100644
--- a/src/lib/bot-pause.ts
+++ b/src/lib/bot-pause.ts
@@ -1,4 +1,4 @@
-// Pausing a bot or a department: it takes no new work, and what it is doing now stops, until it is resumed. The
+// Pausing a bot, a department or every bot: it takes no new work, and what it is doing now stops, until it is resumed. The
// server sends the new state to every open app in its config frame.
import type { ConfigStatus } from "@/state/store";
import { api } from "@/state/api";
@@ -8,6 +8,7 @@ export type PauseKind = "bot" | "department";
export interface PausedByPerson {
bots: string[];
departments: string[];
+ all?: true;
}
const NONE: PausedByPerson = { bots: [], departments: [] };
@@ -20,9 +21,15 @@ export function isPausedHere(config: Pick<ConfigStatus, "pausedByPerson"> | null
return kind === "bot" ? state.bots.includes(id) : state.departments.includes(id.trim());
}
-/** Taking no new work, by itself or with its department. */
+export const isEveryBotPaused = (config: Pick<ConfigStatus, "pausedByPerson"> | null | undefined): boolean => pausedByPerson(config).all === true;
+
+/** Taking no new work, by itself, with its department or with every bot. */
export const isBotHeld = (config: Pick<ConfigStatus, "heldBots"> | null | undefined, botId: string): boolean => config?.heldBots?.includes(botId) === true;
export async function setPaused(kind: PauseKind, id: string, paused: boolean): Promise<{ stopped: number }> {
return api<{ stopped: number }>("/api/paused", { method: "POST", body: JSON.stringify({ kind, id, paused }), timeoutMs: 60_000 });
}
+
+export async function setEveryBotPaused(paused: boolean): Promise<{ stopped: number }> {
+ return api<{ stopped: number }>("/api/paused", { method: "POST", body: JSON.stringify({ kind: "all", paused }), timeoutMs: 60_000 });
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index 51e18990c1..d85350d161 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -219,6 +219,7 @@
"server.botPaused": "Pausiert: Starter hält {limit} Bots wach. Führe ein Upgrade durch, um ihn zu wecken, oder tausche, welche Bots wach sind.",
"server.botHeld": "{bot} ist pausiert und nimmt keine neue Arbeit an. Setze ihn über sein Menü in der Seitenleiste fort.",
"server.botHeldDepartment": "{bot} ist mit der Abteilung {department} pausiert und nimmt keine neue Arbeit an. Setze die Abteilung über ihr Menü in der Seitenleiste fort.",
+ "server.botHeldAll": "Alle Bots sind pausiert, daher nimmt {bot} keine neue Arbeit an. Setze alle Bots über das Menü eines beliebigen Bots in der Seitenleiste fort.",
"server.teammates.queued.thread": "{bot} hat damit noch nicht begonnen: Ein früherer Durchlauf in diesem Thread läuft noch.",
"server.teammates.queued.slots": "{bot} hat damit noch nicht begonnen: Es laufen bereits {busy} von {limit} Threads gleichzeitig.",
"server.teammates.queued.room": "{bot} hat damit noch nicht begonnen: Es beendet gerade einen Durchlauf in einem Raum.",
diff --git a/src/locales/en.json b/src/locales/en.json
index a3e2f91196..7b065c8164 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -355,11 +355,15 @@
"server.botPaused": "Paused: Starter keeps {limit} bots awake. Upgrade to wake it, or swap which bots are awake.",
"server.botHeld": "{bot} is paused, so it takes no new work. Resume it from its menu in the sidebar.",
"server.botHeldDepartment": "{bot} is paused with the {department} department, so it takes no new work. Resume the department from its menu in the sidebar.",
+ "server.botHeldAll": "Every bot is paused, so {bot} takes no new work. Resume every bot from any bot’s menu in the sidebar.",
"pause.pauseBot": "Pause bot",
"pause.resumeBot": "Resume bot",
"pause.pauseDepartment": "Pause department",
"pause.resumeDepartment": "Resume department",
"pause.byDepartment": "Paused with its department: resume the department",
+ "pause.pauseAll": "Pause every bot",
+ "pause.resumeAll": "Resume every bot",
+ "pause.byAll": "Paused with every bot: resume every bot",
"pause.badge": "Paused",
"routines.botHeld": "Its bot is paused, so this routine won’t run until the bot is resumed.",
"server.teammates.queued.thread": "{bot} hasn't started this yet: an earlier turn in that thread is still running.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3441bea5c7..e146c859d9 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -338,11 +338,15 @@
"server.botPaused": "Pausado: o Starter mantém {limit} bots ativos. Faça upgrade para ativá-lo ou troque quais bots ficam ativos.",
"server.botHeld": "{bot} está pausado e não recebe trabalho novo. Retome-o pelo menu dele na barra lateral.",
"server.botHeldDepartment": "{bot} está pausado junto com o departamento {department} e não recebe trabalho novo. Retome o departamento pelo menu dele na barra lateral.",
+ "server.botHeldAll": "Todos os bots estão pausados, então {bot} não recebe trabalho novo. Retome todos os bots pelo menu de qualquer bot na barra lateral.",
"pause.pauseBot": "Pausar bot",
"pause.resumeBot": "Retomar bot",
"pause.pauseDepartment": "Pausar departamento",
"pause.resumeDepartment": "Retomar departamento",
"pause.byDepartment": "Pausado junto com o departamento: retome o departamento",
+ "pause.pauseAll": "Pausar todos os bots",
+ "pause.resumeAll": "Retomar todos os bots",
+ "pause.byAll": "Pausado junto com todos os bots: retome todos os bots",
"pause.badge": "Pausado",
"routines.botHeld": "O bot está pausado, então esta rotina não roda até ele ser retomado.",
"server.teammates.queued.thread": "{bot} ainda não começou esta tarefa: uma sessão anterior nessa conversa ainda está em andamento.",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 0cbf1b34ee..4acace4ab5 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -3990,6 +3990,7 @@
"chat.notice.devinAccountRefused": "6f12d9c4c2912bc75bfbc26d0b43a2da3b02c1e4e16a807a9162670fcdab80fc",
"server.botHeld": "5980b395f2c56023b870eacc8b6d9bdbc746171c7b8b5b44fcb07c657b64b6ce",
"server.botHeldDepartment": "ad3c5b51e8e3c5271f998a9ce283fe62a5fd23660096f757050a942168ab7361",
+ "server.botHeldAll": "bae5b35a054c94e0b4ef049f576d76eef48a47d11a66dc7405e09592b9f3f49c",
"devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0",
"devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8",
"devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",
@@ -36903,11 +36904,15 @@
"chat.notice.devinAccountRefused": "6f12d9c4c2912bc75bfbc26d0b43a2da3b02c1e4e16a807a9162670fcdab80fc",
"server.botHeld": "5980b395f2c56023b870eacc8b6d9bdbc746171c7b8b5b44fcb07c657b64b6ce",
"server.botHeldDepartment": "ad3c5b51e8e3c5271f998a9ce283fe62a5fd23660096f757050a942168ab7361",
+ "server.botHeldAll": "bae5b35a054c94e0b4ef049f576d76eef48a47d11a66dc7405e09592b9f3f49c",
"pause.pauseBot": "eada7664ee24f58006b5e94a3badd100143184249a6f6fa04ca647fa666deee0",
"pause.resumeBot": "44def306f4c23ef1938c7c7e4d6c48eceff18f800043cdeaecc897da0d46d70f",
"pause.pauseDepartment": "8007675f16f892b29ca6f032943976fa4e91041bb30aad4df2d9ca6c1a32648c",
"pause.resumeDepartment": "80e179186e640845a0f550941a19a5bf2aec67e9a3ccf064077c721de83a2d9e",
"pause.byDepartment": "a9966733d4878dc396e71a2af9bf0997a1ed662f9564e1af28c8be2df44024c3",
+ "pause.pauseAll": "334c0445b222f290a26a0baf6344e49ff7dbbedcc0fe76344defbd3f15d6bbf4",
+ "pause.resumeAll": "d9c9c1cd215b678f000893574b9e8ba5763b2a4ed4fb8a0794c34a6812eecbd3",
+ "pause.byAll": "443f7ecff8aff327291319b5facc9f25efd1424319c258c55ec7c76a471b5c92",
"pause.badge": "e159b06187d369a0615f66ce577582b5c983d4ea59b3a62b702049f61753f0bf",
"routines.botHeld": "38a39eee7b4e86aa10dded18a024c1978fc4dcb4b3d77b262c1239dfd1d4da12",
"settings.customThemes.history": "f66a12ef4fd99fa604a5229012d70e40f68a73c531b583e5e9b6a77ed5a5c6fc",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 561ab05672..0d35d24f46 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -73,7 +73,7 @@ export interface ConfigStatus {
/** Bots paused for the plan's limit: kept, but taking no turns. */
pausedBots?: string[];
/** What the person paused (Pause in the sidebar menus): bots by id and departments by name. Absent from older servers. */
- pausedByPerson?: { bots: string[]; departments: string[] };
+ pausedByPerson?: { bots: string[]; departments: string[]; all?: true };
/** Every bot taking no new work because the person paused it or its department. */
heldBots?: string[];
/** The server cannot read its saved routines, so none runs until it can. */