Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Room to grow: memory never takes the workspace down, says why in one line, retries, and offers the plan that fixes it
milind-soni405846c9b8eb
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex d329708e7f..1faa3b66ee 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1121,10 +1121,14 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):least), or the memory stall reaches 40% below the tenth, it stops an idleengine, else the newest of two or more busy ones, at most every 15 s, andnot in the tick right after the kernel's own OOM killer acted.-- **The kernel's order** (`server/oom-score.ts`): engines, and everything they- start, are born with `oom_score_adj` 1000; Chrome scores its tabs 200 and- up; the server is -800 and Caddy -900, so the health check is the last to- go.+- **The kernel's order** (`server/oom-score.ts`): everything a bot runs is+ born with `oom_score_adj` 1000: its engine and every tool and MCP server+ that engine starts, the MCP servers the server runs for it, the helper+ engines (background text, keep-warm pings), and its browser (agent-browser,+ its daemon and Chrome, whose tabs Chrome then scores 200 and up). The+ server is -800 and Caddy -900, so the health check is the last to go, and+ the root supervisor that restarts them is -1000, never picked. When memory+ runs out the kernel takes a bot's process, never the workspace.- **OpenCode reaches OpenMausBot's own tools over HTTP.** The agents,browser, computer, Data and HighLevel servers are endpoints of this server(`/api/internal/mcp-http/<name>`, `server/routes/own-mcp-http.ts`) with the@@ -1132,13 +1136,25 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):process each (about 20–30 MB PSS apiece) in every OpenCode session. A serverbehind a tool selection keeps its stdio gate; the person's own servers areunchanged.-- **The reason is said.** A turn whose engine was stopped for memory, by the- home or by the kernel (a SIGKILL while `/proc/vmstat`'s `oom_kill` rose),- fails with "This Cloud ran out of memory while N tasks ran at once, so this- one was stopped. It was not a problem with the AI provider. New tasks now- wait until there is memory for them.", and a turn that stalled while memory- was short says so after "no activity for 20 minutes". The health report- counts both as `out_of_memory`.+- **The reason is said, in one line.** A turn whose engine was stopped for+ memory, by the home or by the kernel (a SIGKILL while `/proc/vmstat`'s+ `oom_kill` rose), ends with "Ran out of room, so I closed the browser to+ keep everything else running." when its bot's browser was open (it is+ closed too), else "Ran out of room, so I stopped this task to keep+ everything else running."; a turn that stalled while memory was short says+ so after "no activity for 20 minutes". The health report counts both as+ `out_of_memory`.+- **The work starts again when there is room.** A routine run gets its one+ automatic retry, and a teammate's thread its Chief's; any other run stopped+ for memory (the Chief's own chat, a bot without a Chief) starts once more by+ itself 30 s later (`server/host/chief-notices.ts`), as a continuation of the+ same request, and the memory gate holds it until it fits. The person hears+ of it only if that run fails too.+- **The day's pressure is reported** (`room` in the health report, below):+ tasks that waited for memory and how long, turns stopped for it, processes+ the kernel stopped, and minutes the machine stalled on memory (its `full+ avg10` at 20% or more). The Admin offers a bigger plan from it+ (openmaus-cloud `server/cloud-room.ts`).### Why the server stays on loopback@@ -1479,10 +1495,19 @@ wait for the next read, `truncated: true`):"disk": { "totalBytes": 10737418240, "freeBytes": 8589934592 }, "eventLogWritable": true },"firstHour": { "startedAt": 1790000000000, "apps": ["gmail"], "look": "delivered","ms": { "seen": 41000, "firstMessage": 52000, "offered": 61000, "firstApp": 118000, "firstLook": 171000, "briefOn": 172000, "phoneOffered": 172000 } },- "value": { "sorted": 40, "drafted": 6, "prepped": 4, "routines": 0, "minutes": 110 }+ "value": { "sorted": 40, "drafted": 6, "prepped": 4, "routines": 0, "minutes": 110 },+ "room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2 }}```+**`room`** is the last day's memory pressure where the home watches it (a Cloud+home on Linux, `server/engine-memory.ts`), else `null`: how many tasks had to+wait for memory and how long they waited in all (a wait still going counts its+time so far), how many turns were stopped for memory (`stopped`), how many+processes the kernel stopped (`killed`), and in how many minutes the machine+stalled on memory. Counted in memory since boot, so a restart starts them+again.+**`firstHour`** is there on a personal Cloud that began with its first hour(`server/host/first-hour.ts`), else `null`: `startedAt` is the first boot,and each milestone in `ms` is how long after it that step happened, present@@ -1985,6 +2010,28 @@ page alike (`ogb.cloudPlan`), so the meter reads the same on both (`src/componenchanged, nothing charged; couldn't, nothing charged. Where the Admin can't change plans from the app (off, or an olderAdmin), Upgrade opens the Cloud page instead. Funnel source `app_usage` (the card) or `app_settings`.+### Room card: short on memory or disk, and the plan that fixes it++The session's `cloud.room` (additive, only beside `cloud.usage`; the Admin's `server/cloud-room.ts`, behind its+`OMB_CLOUD_ROOM_OFFERS`) says this Cloud is short on room, from its health report's `room` and disk: `cause` is+`{kind: "memory", waits, waitMinutes, stopped}` (the last day) or `{kind: "disk", usedGb, capGb}`, then either `plan`+(the next plan up that fixes it: `tier`, `amount` in US cents a month, `memoryMb`/`fromMemoryMb`, `diskGb`/`fromDiskGb`)+or `tip: true` on the top plan, and `id`. `electron/cloud-home.mjs` `parseCloudRoom` drops anything malformed; it is display+only.++- **Where:** the card sits where the usage meter's card is (the sidebar's foot and the phone bar, `src/components/CloudRoomCard.tsx`,+ `src/lib/room-card.ts`), never while any bot is working (never mid-turn), never beside the usage meter's card, and on a+ Team Cloud only for the team's own plan (its payer).+- **What it says:** the cause ("3 tasks waited 6 minutes for memory today."), what the plan gives and costs ("Pro has twice+ the memory. $49 a month. Today you pay only for the rest of this month."), **Upgrade** and **Not now**; on the top plan+ a tip ("run fewer bots at once and close browsers you're not using") and **Got it**.+- **Upgrade** is the usual one: the preview, then the person's confirm, with source `app_room`. After it the card offers+ **Restart now** (`ogb.cloudPlan.restartNow()`, `POST /api/cloud/desktop/resize-now`, "Takes about a minute, and stops anything+ running now"); otherwise the Cloud gets its new size the next time it's not busy.+- **Not now** (`ogb.cloudPlan.roomNotNow(id)`, `POST /api/cloud/desktop/room`) hides it here at once and the Admin offers+ nothing for two weeks. A new offer comes at most once a week. Both channels act only on the session's own Cloud, only from+ a click.+## Add a CloudThe one way to buy MausBot Cloud in the app, the same for every way in:diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex b6b931633c..f933168b8f 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -47,6 +47,8 @@ export interface CloudAccountState {offer?: import("./cloud-home.mjs").CloudOffer;/** Connected with an active plan: its allowances and this month's use of them, and the bigger plans the app can move to (display only). */usage?: import("./cloud-home.mjs").CloudUsage;+ /** Connected beside `usage`: the Cloud is short on room (display only; its plan moves through the usual upgrade). */+ room?: import("./cloud-home.mjs").CloudRoom;/** A checkout this app opened (or a sign-in it started on the way to* one: `signIn`) in the last 24 hours: the plan, and when (Reopen checkout* starts the 30-minute watch again). `link`: main keeps its page, so Reopen@@ -187,6 +189,8 @@ export interface CloudPlanSnapshot {home?: true;/** Verified, with an active plan: its allowances and their use this month (the usage meter). */usage?: import("./cloud-home.mjs").CloudUsage;+ /** Verified, beside `usage`: this Cloud is short on room, and the plan that fixes it or a tip (the room card). */+ room?: import("./cloud-home.mjs").CloudRoom;/** Verified, while this account pays for a plan that runs: what Cancel and Keep act on. */renewal?: import("./cloud-list.mjs").CloudRenewal;}@@ -203,6 +207,9 @@ export interface CloudPlanBridge {/** Cancel trial / Cancel plan and Keep my plan on the Cloud's own page (only from the person's click). Absent on an older app. */cancel?(survey: CloudCancelSurvey | null): Promise<CloudRenewalResult>;keep?(): Promise<CloudRenewalResult>;+ /** The room card's Not now, and Restart now after its upgrade (only from the person's click). Absent on an older app. */+ roomNotNow?(id: string): Promise<boolean>;+ restartNow?(): Promise<"restarting" | "current" | "failed">;}export declare const CLOUD_ORIGIN: string;@@ -265,6 +272,10 @@ export interface CloudAccountClient {cancelPlan(survey: unknown): Promise<CloudRenewalResult>;/** POST /api/cloud/desktop/clouds/<the session's own Cloud>/keep. */keepPlan(): Promise<CloudRenewalResult>;+ /** POST /api/cloud/desktop/room: Not now on the room card for the session's own Cloud; false when it couldn't be said. */+ roomNotNow(id: string): Promise<boolean>;+ /** POST /api/cloud/desktop/resize-now: the bigger size after an upgrade goes at once. */+ restartNow(): Promise<"restarting" | "current" | "failed">;homeTarget(): { origin: string } | null;/** The Admin's last word on a Cloud whose plan sleeps; null for any other. */power(): import("./cloud-power.mjs").CloudPower | null;diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex 31af07c70d..ea85ec39a6 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -1,5 +1,5 @@import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managed-desktop.mjs";-import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";+import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudRoom, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, ORGANIZATION_BLOCKS, otherOwnClouds, ownCloud, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion } from "./cloud-list.mjs";import { planTeam, teamPlan } from "./cloud-team-plan.mjs";import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";@@ -31,7 +31,7 @@ const MAX_ENROLL_SECONDS = 1800;const OFFER_MS = 10 * 60_000, OFFER_RETRY_MS = 30_000;const CHECKOUT_WATCH_MS = 30 * 60_000, CHECKOUT_KEPT_MS = 24 * 3600_000;export const CHECKOUT_SOURCES = Object.freeze(["app_card", "app_howto", "app_menu", "app_settings", "app_routines", "app_pages", "update_popup", "app_onboarding"]);-export const UPGRADE_SOURCES = Object.freeze(["app_usage", "app_settings"]);+export const UPGRADE_SOURCES = Object.freeze(["app_usage", "app_settings", "app_room"]);const UPGRADE_TIERS = Object.freeze(["starter", "personal", "pro", "max"]);const UPGRADE_REFUSALS = Object.freeze(["payment_failed", "not_subscribed", "already_on_plan", "plan_change_unavailable", "confirmation_required", "price_changed", "rate_limited"]);const CONFIRMATION = /^[A-Za-z0-9_-]{43}$/;@@ -256,7 +256,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst machine = parseCloudSummary(result.cloud), teams = parseCloudTeams(result.teams);const purchase = parseCloudPurchase(result.cloud?.purchase);const trial = parseCloudTrial(result.cloud?.trial), credit = parseCloudCredit(result.cloud?.credit), offer = parseCloudOffer(result.offer);- const usage = access.status === "active" ? parseCloudUsage(result.cloud?.usage) : null;+ const usage = access.status === "active" ? parseCloudUsage(result.cloud?.usage) : null, room = usage ? parseCloudRoom(result.cloud?.room) : null;const clouds = parseCloudList(result.clouds), more = clouds ? addOffer(result) : null, latest = clouds ? releaseVersion(result.latestVersion) : null;const organizations = clouds ? parseOrganizations(result.organizations) : null;const { cloudId: renewingCloud = null, ...renewal } = parseCloudRenewal(result.clouds) ?? {};@@ -287,7 +287,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNverifiedUntil = Math.min(grant.expiresAt, now() + STEADY_MS,access.status === "active" && access.expiresAt !== null ? access.expiresAt : Infinity);publish({ ...view("connected"), entitlement: access, ...(machine ? { machine } : {}), ...(teams.length ? { teams } : {}), ...(purchase ? { purchase } : {}),- ...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}), ...(renewingCloud ? { renewal } : {}),+ ...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}), ...(room ? { room } : {}), ...(renewingCloud ? { renewal } : {}),...(clouds ? { clouds, addCloud: more } : {}), ...(organizations ? { organizations } : {}), ...(latest ? { latestVersion: latest } : {}), verifiedAt: now(), verifiedUntil });const planCloud = teamPlan(value) ? planTeam(value)?.machine ?? null : machine;const settingUp = planCloud?.status === "provisioning" || (access.status === "active" && !planCloud) || Boolean(purchase) || otherOwnClouds(clouds).some(cloud => cloud.status === "setting_up");@@ -575,6 +575,25 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN}return current.status === "connected" ? withoutTrial(offerCache.value) : offerCache.value;},+ /** Not now on the room card: the Admin offers this Cloud nothing more for two weeks. The Cloud is the session's own. */+ async roomNotNow(id) {+ const signedIn = grant;+ if (!signedIn || state().status !== "connected") return false;+ try { await request("room", { method: "POST", body: { ...(typeof id === "string" ? { id } : {}), answer: "not_now" }, token: signedIn.token }); }+ catch { return false; }+ await refresh().catch(() => {});+ return true;+ },+ /** Restart now, after an upgrade: the bigger size goes at once instead of the next idle moment (`restarting`), or the+ * Cloud already has it (`current`); `failed` when the Admin couldn't be asked. */+ async restartNow() {+ const signedIn = grant;+ if (!signedIn || state().status !== "connected") return "failed";+ try {+ const result = await request("resize-now", { method: "POST", body: {}, token: signedIn.token, timeoutMs: 30_000 });+ return ["restarting", "current"].includes(result?.state) ? result.state : "failed";+ } catch { return "failed"; }+ },async interest(kind) {if (kind !== "another_cloud") throw new Error("Invalid Cloud interest.");const signedIn = grant;@@ -911,7 +930,8 @@ export function cloudPlanSnapshot(state, { notice = null } = {}) {const named = typeof tier === "string" ? { tier } : {};const trial = state?.status === "connected"? { ...(state.trial ? { trial: state.trial } : {}), ...(state.credit ? { credit: state.credit } : {}), ...(notice && state.trial ? { notice } : {}),- ...(state.machine?.power?.sleeps ? { sleeps: true } : {}), ...(state.usage ? { usage: state.usage } : {}), ...(state.renewal ? { renewal: state.renewal } : {}) } : {};+ ...(state.machine?.power?.sleeps ? { sleeps: true } : {}), ...(state.usage ? { usage: state.usage } : {}), ...(state.room ? { room: state.room } : {}),+ ...(state.renewal ? { renewal: state.renewal } : {}) } : {};if (state?.status === "connected" && state.entitlement?.plan === "pro") return { status: state.entitlement.status === "active" ? "paid" : "attention", ...named, ...trial };if (state?.status === "reauth-required") return { status: "signin", ...(state.lastPlan ? { tier: state.lastPlan.tier ?? "pro" } : {}) };if (state?.status !== "connected" && state?.lastPlan) return { status: "checking", ...named };diff --git a/electron/cloud-home.d.mts b/electron/cloud-home.d.mtsindex 04ae7da68a..601f55d4b6 100644--- a/electron/cloud-home.d.mts+++ b/electron/cloud-home.d.mts@@ -68,6 +68,17 @@ export interface CloudUsage {tier: string; resetsAt: number; trialEndsAt?: number; meters: CloudUsageMeter[];upgrades: { tier: "starter" | "personal" | "pro" | "max"; amount: number }[];}+/** Why the Cloud is short on room over the last day: tasks that waited for memory and the minutes they waited in all, tasks+ * stopped for it; or its disk, in GB of the most its plan grows it to. */+export type CloudRoomCause = { kind: "memory"; waits: number; waitMinutes: number; stopped: number } | { kind: "disk"; usedGb: number; capGb: number };+/** The session's `cloud.room`: the Cloud this account pays for is short on room. `plan`: the next plan up that fixes it, its+ * price (US cents a month before tax) and its memory (MB) and disk cap (GB) against this plan's; `tip`: on the top plan, a+ * tip instead. `id` names the offer for Not now. */+export interface CloudRoom {+ id: string; cause: CloudRoomCause;+ plan?: { tier: "starter" | "personal" | "pro" | "max"; amount: number; memoryMb: number; fromMemoryMb: number; diskGb: number; fromDiskGb: number };+ tip?: true;+}/** What a plan includes, as the Admin's catalog says. */export interface CloudPlanAllowances {cpus: number; memoryMb: number;@@ -128,6 +139,7 @@ export declare function parseCloudTrial(input: unknown): CloudTrial | null;export declare function parseCloudCredit(input: unknown): CloudCredit | null;export declare const CLOUD_USAGE_KINDS: readonly CloudUsageKind[];export declare function parseCloudUsage(input: unknown): CloudUsage | null;+export declare function parseCloudRoom(input: unknown): CloudRoom | null;export declare function parseCloudOffer(input: unknown): CloudOffer | null;export declare function parsePublicOffer(config: unknown): CloudOffer | null;export declare function withoutTrial(offer: CloudOffer | null): CloudOffer | null;diff --git a/electron/cloud-home.mjs b/electron/cloud-home.mjsindex 0cb5d90b1a..7d4ca75bf9 100644--- a/electron/cloud-home.mjs+++ b/electron/cloud-home.mjs@@ -126,6 +126,24 @@ export function parseCloudUsage(input) {return { tier: input.tier, resetsAt: input.resetsAt, ...(moment(input.trialEndsAt) ? { trialEndsAt: input.trialEndsAt } : {}), meters: unique, upgrades };}+const ROOM_ID = /^[A-Za-z0-9-]{1,64}$/;+const whole = (value, max) => Number.isSafeInteger(value) && value >= 0 && value <= max;+/** The session's `cloud.room` (contract v1, additive): the Cloud this account pays for is short on room. Display only: the+ * plan it names is moved to through the usual upgrade, which main allows only for a plan `usage` lists. */+export function parseCloudRoom(input) {+ if (!record(input) || typeof input.id !== "string" || !ROOM_ID.test(input.id) || !record(input.cause)) return null;+ const { cause } = input;+ const memory = cause.kind === "memory" && whole(cause.waits, 1e6) && whole(cause.waitMinutes, 1e6) && whole(cause.stopped, 1e6);+ const disk = cause.kind === "disk" && amount(cause.usedGb) && whole(cause.capGb, 1e5) && cause.capGb > 0;+ if (!memory && !disk) return null;+ const plan = input.plan, sizes = record(plan) && ["memoryMb", "fromMemoryMb", "diskGb", "fromDiskGb"].every(key => whole(plan[key], 1e7));+ const offered = sizes && PLAN_TIERS.includes(plan.tier) && Number.isSafeInteger(plan.amount) && plan.amount >= 1 && plan.amount <= 10_000_000+ ? { tier: plan.tier, amount: plan.amount, memoryMb: plan.memoryMb, fromMemoryMb: plan.fromMemoryMb, diskGb: plan.diskGb, fromDiskGb: plan.fromDiskGb } : null;+ if (!offered && input.tip !== true) return null;+ return { id: input.id, cause: memory ? { kind: "memory", waits: cause.waits, waitMinutes: cause.waitMinutes, stopped: cause.stopped }+ : { kind: "disk", usedGb: cause.usedGb, capGb: cause.capGb }, ...(offered ? { plan: offered } : { tip: true }) };+}+const days = (value, max) => Number.isSafeInteger(value) && value >= 1 && value <= max ? value : null;const count = value => Number.isSafeInteger(value) && value >= 0 && value <= 1_000_000_000;// oxlint-disable-next-line no-control-regexdiff --git a/electron/cloud-plan-ipc.mjs b/electron/cloud-plan-ipc.mjsindex 2b10f839c6..6251b86c9f 100644--- a/electron/cloud-plan-ipc.mjs+++ b/electron/cloud-plan-ipc.mjs@@ -30,4 +30,7 @@ export function installCloudPlanIpc({ ipcMain, pageSender, account, client, noti// Cancel trial / Cancel plan and Keep my plan: the page's survey is checked in main, and the Cloud is the session's own.ipcMain.handle("cloud-plan:cancel", (event, survey) => pageSender("cloud-plan:cancel", () => client().cancelPlan(survey))(event));ipcMain.handle("cloud-plan:keep", pageSender("cloud-plan:keep", () => client().keepPlan()));+ // The room card (the session's `room`): Not now, and Restart now after its upgrade; both for the session's own Cloud.+ ipcMain.handle("cloud-plan:room-not-now", (event, id) => pageSender("cloud-plan:room-not-now", () => client().roomNotNow(typeof id === "string" ? id.slice(0, 64) : ""))(event));+ ipcMain.handle("cloud-plan:restart-now", pageSender("cloud-plan:restart-now", () => client().restartNow()));}diff --git a/electron/cloud-room.node-test.mjs b/electron/cloud-room.node-test.mjsnew file mode 100644index 0000000000..f29cf38d1d--- /dev/null+++ b/electron/cloud-room.node-test.mjs@@ -0,0 +1,68 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createServer } from "node:http";++import { cloudPlanSnapshot, createCloudAccountClient } from "./cloud-account.mjs";++// The room card's data and its two actions (the session's `cloud.room`, POST room and POST resize-now), against a fake Admin.+const accessToken = `omc_${"T".repeat(43)}`;+const NOW = 1_800_000_000_000;+const paid = { plan: "pro", tier: "pro", status: "active", expiresAt: NOW + 30 * 86400_000, version: 1 };+const usage = { tier: "pro", resetsAt: NOW + 86400_000, meters: [], upgrades: [{ tier: "max", amount: 9900 }] };+const room = { id: "4f1d6c2e-room", cause: { kind: "memory", waits: 3, waitMinutes: 6, stopped: 1 },+ plan: { tier: "max", amount: 9900, memoryMb: 8192, fromMemoryMb: 4096, diskGb: 100, fromDiskGb: 100 } };++/** A fake Admin: the session's `cloud` is `f.cloud`; POST room answers `f.room`, POST resize-now `f.resizeNow`. */+async function admin(t) {+ const f = { requests: [], cloud: { state: "ready", origin: "https://omb-u-1a2b3c4d5e6f.fly.dev", pairingAvailable: true, usage, room: { ...room, extra: "dropped" } },+ room: [404, { error: "not_found" }], resizeNow: [404, { error: "not_found" }] };+ const server = createServer(async (req, res) => {+ let body = ""; for await (const chunk of req) body += chunk;+ f.requests.push({ route: req.url, method: req.method, body: body ? JSON.parse(body) : undefined });+ const send = ([status, data]) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(data)); };+ if (req.headers.authorization !== `Bearer ${accessToken}`) return send([401, { error: "invalid_token" }]);+ if (req.url === "/api/cloud/desktop/session") return send([200, { cloudContractVersion: 1, expiresAt: NOW + 86400_000, device: { id: "device-1" },+ account: { id: "acct-1", email: "[email protected]" }, entitlement: paid, cloud: f.cloud }]);+ if (req.url === "/api/cloud/desktop/room" && req.method === "POST") return send(f.room);+ if (req.url === "/api/cloud/desktop/resize-now" && req.method === "POST") return send(f.resizeNow);+ send([404, { error: "not_found" }]);+ });+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+ const origin = `http://127.0.0.1:${server.address().port}`;+ const saved = { origin, token: accessToken, expiresAt: NOW + 86400_000, device: { id: "device-1" }, account: { id: "acct-1", email: "[email protected]" } };+ f.client = createCloudAccountClient({ origin, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.fixture", now: () => NOW,+ store: { read: async () => saved, write: async () => {} }, openBrowser: async () => {}, setTimer: () => 1, clearTimer: () => {} });+ t.after(async () => { f.client.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });+ return f;+}++test("the session's room reaches the state and the Cloud page's snapshot, checked, and only beside the usage it belongs to", async t => {+ const f = await admin(t);+ await f.client.start();+ assert.deepEqual(f.client.state().room, room);+ assert.deepEqual(cloudPlanSnapshot(f.client.state()).room, room);+ // On the top plan: a tip, never a plan.+ f.cloud = { ...f.cloud, room: { id: "tip-1", cause: { kind: "disk", usedGb: 87.5, capGb: 100 }, tip: true } };+ assert.deepEqual((await f.client.refresh()).room, { id: "tip-1", cause: { kind: "disk", usedGb: 87.5, capGb: 100 }, tip: true });+ // One that doesn't read, names neither a plan nor a tip, or comes without the usage it belongs to: none.+ for (const bad of [{ ...room, cause: { kind: "memory", waits: -1, waitMinutes: 6, stopped: 0 } }, { id: "x", cause: room.cause }, { ...room, plan: { ...room.plan, tier: "gold" } }]) {+ f.cloud = { ...f.cloud, usage, room: bad };+ assert.equal((await f.client.refresh()).room, undefined, JSON.stringify(bad));+ }+ f.cloud = { state: "ready", origin: f.cloud.origin, pairingAvailable: true, room };+ assert.equal((await f.client.refresh()).room, undefined);+});++test("Not now and Restart now go to the Admin for the session's own Cloud, in the app's words; an Admin without them changes nothing", async t => {+ const f = await admin(t);+ await f.client.start();+ assert.equal(await f.client.roomNotNow(room.id), false);+ f.room = [200, { cloudContractVersion: 1, answered: true }];+ assert.equal(await f.client.roomNotNow(room.id), true);+ assert.deepEqual(f.requests.findLast(request => request.route === "/api/cloud/desktop/room").body, { id: room.id, answer: "not_now" });+ assert.equal(await f.client.restartNow(), "failed");+ f.resizeNow = [200, { cloudContractVersion: 1, state: "restarting" }];+ assert.equal(await f.client.restartNow(), "restarting");+ f.resizeNow = [200, { cloudContractVersion: 1, state: "sideways" }];+ assert.equal(await f.client.restartNow(), "failed");+});diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjsindex e00e123e85..753091c66a 100644--- a/electron/home-window.node-test.mjs+++ b/electron/home-window.node-test.mjs@@ -418,7 +418,9 @@ function pageIpc(overrides = {}) {upgradePreview: async (...args) => { calls.push(["upgrade-preview", ...args]); return { outcome: "failed" }; },upgrade: async (...args) => { calls.push(["upgrade", ...args]); return { outcome: "failed" }; },cancelPlan: async (...args) => { calls.push(["cancel", ...args]); return { outcome: "failed" }; },- keepPlan: async (...args) => { calls.push(["keep", ...args]); return { outcome: "failed" }; } }),+ keepPlan: async (...args) => { calls.push(["keep", ...args]); return { outcome: "failed" }; },+ roomNotNow: async (...args) => { calls.push(["room-not-now", ...args]); return true; },+ restartNow: async (...args) => { calls.push(["restart-now", ...args]); return "restarting"; } }),homeWindow: { homePage: () => false },...overrides,});@@ -437,14 +439,14 @@ test("no page gets a control over lending this computer: not My Cloud's, anothertest("Settings on the person's own Cloud shows the plan read only, says when it is home, and can open the Plan page or sign in again; never switch away", async () => {const page = preload(CLOUD);- assert.deepEqual(Object.keys(page.bridge.cloudPlan), ["state", "manage", "signIn", "noticeSeen", "upgradePreview", "upgrade", "cancel", "keep"]);+ assert.deepEqual(Object.keys(page.bridge.cloudPlan), ["state", "manage", "signIn", "noticeSeen", "upgradePreview", "upgrade", "cancel", "keep", "roomNotNow", "restartNow"]);assert.equal(page.bridge.cloudAccount, undefined, "no account, credential or address reaches the Cloud's page");await page.bridge.cloudPlan.state({ origin: "https://evil.example.test" });await assert.rejects(page.bridge.cloudPlan.manage(), /Choose Manage/);const ipc = pageIpc();const event = { sender: ipc.cloudContents, senderFrame: ipc.cloudFrame };assert.deepEqual(Object.keys(Object.fromEntries(ipc.handlers)), ["cloud-plan:state", "cloud-plan:notice-seen", "cloud-plan:manage",- "cloud-plan:upgrade-preview", "cloud-plan:upgrade", "cloud-plan:cancel", "cloud-plan:keep"]);+ "cloud-plan:upgrade-preview", "cloud-plan:upgrade", "cloud-plan:cancel", "cloud-plan:keep", "cloud-plan:room-not-now", "cloud-plan:restart-now"]);assert.deepEqual(plain(await ipc.handlers.get("cloud-plan:state")(event, { tier: "personal" })), { status: "paid", tier: "max" });ipc.context.homeWindow = { homePage: (asked) => asked === event };assert.deepEqual(plain(await ipc.handlers.get("cloud-plan:state")(event)), { status: "paid", tier: "max", home: true });@@ -742,6 +744,31 @@ test("Cancel and Keep my plan on the Cloud's own page: only from the person's classert.equal(ipc.calls.length, 2);});+test("the room card on the person's own Cloud: the offer read only, Not now and Restart now only from their click there, for the session's own Cloud", async () => {+ const page = preload(CLOUD);+ await assert.rejects(page.bridge.cloudPlan.roomNotNow("offer-1"), /Choose Not now/);+ await assert.rejects(page.bridge.cloudPlan.restartNow(), /Choose Restart now/);+ const clicked = preload(CLOUD, { activation: true });+ await clicked.bridge.cloudPlan.roomNotNow("offer-1", { cloudId: "someone-elses" });+ await clicked.bridge.cloudPlan.restartNow({ cloudId: "someone-elses" });+ await clicked.bridge.cloudPlan.upgradePreview("max", "app_room");+ assert.deepEqual(clicked.invoked, [["cloud-plan:room-not-now", "offer-1"], ["cloud-plan:restart-now"], ["cloud-plan:upgrade-preview", "max", "app_room"]]);+ const ipc = pageIpc();+ const event = { sender: ipc.cloudContents, senderFrame: ipc.cloudFrame };+ ipc.account.usage = { tier: "pro", resetsAt: 1, meters: [], upgrades: [{ tier: "max", amount: 9900 }] };+ ipc.account.room = { id: "offer-1", cause: { kind: "memory", waits: 3, waitMinutes: 6, stopped: 0 },+ plan: { tier: "max", amount: 9900, memoryMb: 8192, fromMemoryMb: 4096, diskGb: 100, fromDiskGb: 100 } };+ assert.deepEqual(plain(await ipc.handlers.get("cloud-plan:state")(event)).room, ipc.account.room);+ await ipc.handlers.get("cloud-plan:room-not-now")(event, "offer-1", { cloudId: "someone-elses" });+ await ipc.handlers.get("cloud-plan:restart-now")(event, { cloudId: "someone-elses" });+ await ipc.handlers.get("cloud-plan:upgrade-preview")(event, "max", "app_room");+ assert.deepEqual(ipc.calls, [["room-not-now", "offer-1"], ["restart-now"], ["upgrade-preview", "max", "app_room"]]);+ for (const sender of [{ sender: ipc.cloudContents, senderFrame: { url: "https://other.example.test/" } }, { sender: {}, senderFrame: ipc.cloudFrame }]) {+ for (const channel of ["cloud-plan:room-not-now", "cloud-plan:restart-now"]) assert.throws(() => ipc.handlers.get(channel)(sender, "offer-1"), /only available/);+ }+ assert.equal(ipc.calls.length, 3);+});+test("another Cloud of the person's own is the place asked for by its id, from the session's list; one it no longer lists is simply My Cloud again", () => {const state = { ...connected(), clouds: [{ ...CLIENT_A, id: "c-home", name: "My Cloud", origin: CLOUD, primary: true }, CLIENT_A] };assert.deepEqual(placeOf({ ask: { cloud: "c-a" }, state }), { kind: "own", id: "c-a", name: "Client A", role: "owner", origin: CLIENT, machine: { status: "ready", origin: CLIENT } });diff --git a/electron/preload.cjs b/electron/preload.cjsindex 432da6a24f..4fd1e8eda6 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -485,6 +485,11 @@ const bridge = {? ipcRenderer.invoke("cloud-plan:cancel", survey ?? null) : Promise.reject(new Error("Choose Cancel to cancel your plan.")),keep: () => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("cloud-plan:keep") : Promise.reject(new Error("Choose Keep my plan to keep it.")),+ // The room card's Not now, and Restart now after its upgrade: only from the person's click.+ roomNotNow: id => navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("cloud-plan:room-not-now", String(id)) : Promise.reject(new Error("Choose Not now.")),+ restartNow: () => navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("cloud-plan:restart-now") : Promise.reject(new Error("Choose Restart now to restart the Cloud.")),} : undefined,organization: process.argv.includes("--omb-company-desktop=1") ? {settingsOpened: () => ipcRenderer.invoke("organization:settings-opened"),diff --git a/room-card-preview.html b/room-card-preview.htmlnew file mode 100644index 0000000000..122b0f9d77--- /dev/null+++ b/room-card-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Room Card Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/room-card-preview.tsx"></script>+ </body>+</html>diff --git a/server/browser-engine.test.ts b/server/browser-engine.test.tsindex 3ff5fc2714..d7e4f9b6d3 100644--- a/server/browser-engine.test.ts+++ b/server/browser-engine.test.ts@@ -36,6 +36,7 @@ import {} from "./browser-engine.ts";import { AGENT_BROWSER_VERSION, agentBrowserReleaseUrl, agentBrowserReleaseVersion, resolveAgentBrowserReleaseAsset } from "./browser-engine-release.ts";import { browserBundlePaths, browserBundleSpec, SUPPORTED_BROWSER_TARGETS } from "./browser-bundle-release.ts";+import { spawnBotWork } from "./oom-score.ts";import { removeTempDir } from "./testing/cleanup.ts";const posix = process.platform !== "win32";@@ -44,6 +45,10 @@ vi.mock("node:child_process", async (importOriginal) => {const actual = await importOriginal<typeof import("node:child_process")>();return { ...actual, spawn: vi.fn(actual.spawn) };});+vi.mock("./oom-score.ts", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./oom-score.ts")>();+ return { ...actual, spawnBotWork: vi.fn(actual.spawnBotWork) };+});afterEach(async () => {vi.unstubAllEnvs();vi.mocked(spawn).mockReset();@@ -80,12 +85,25 @@ describe("sizing the page of a launched browser", () => {it("sets the standard viewport through the session's own launch environment", async () => {vi.mocked(spawn).mockImplementation(() => viewportChild(JSON.stringify({ success: true, data: { width: 1280, height: 720 } })));+ vi.mocked(spawnBotWork).mockClear();expect(await setBrowserViewport("/engine", env)).toBe(true);+ // A call can start the session's daemon and its Chrome: they are the bot's, first in line when memory runs out.+ expect(spawnBotWork).toHaveBeenCalledTimes(1);expect(vi.mocked(spawn).mock.calls[0]?.[0]).toBe("/engine");expect(vi.mocked(spawn).mock.calls[0]?.[1]).toEqual(["set", "viewport", "1280", "720", "--json", "--no-webmcp"]);expect(vi.mocked(spawn).mock.calls[0]?.[2]?.env).toMatchObject(env);});+ it.runIf(process.platform === "linux")("starts the engine, and the daemon and Chrome it starts, first in line when memory runs out", async () => {+ const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");+ vi.mocked(spawn).mockImplementation(actual.spawn);+ const dir = mkdtempSync(join(tmpdir(), "omb-engine-score-"));+ scratch.push(dir);+ const engine = join(dir, "agent-browser");+ writeFileSync(engine, `#!/bin/sh\n[ "$(cat /proc/self/oom_score_adj)" = 1000 ] && echo '{"success":true}' || echo '{"success":false}'\n`, { mode: 0o755 });+ expect(await setBrowserViewport(engine, env)).toBe(true);+ });+it("reports failure instead of throwing", async () => {vi.mocked(spawn).mockImplementation(() => viewportChild(JSON.stringify({ success: false, error: "no page" })));expect(await setBrowserViewport("/engine", env)).toBe(false);diff --git a/server/browser-engine.ts b/server/browser-engine.tsindex 9eacdc64b0..d05fa21752 100644--- a/server/browser-engine.ts+++ b/server/browser-engine.ts@@ -11,6 +11,7 @@ import { browserBundlePaths } from "./browser-bundle-release.ts";import { browserProcessesRunning, browserProcessTree, releaseBrowserProfile, stopBrowserProcesses } from "./browser-processes.ts";import { BROWSER_VIEWPORT, viewportArgs, type PageSize } from "./browser-page-size.ts";import { browserRuntimeEnv, ownsBrowserViewport } from "./browser-runtime.ts";+import { spawnBotWork } from "./oom-score.ts";import { SIGN_IN_PROMPT } from "./system-prompt.ts";import { gateChromeSettings } from "./browser/egress/gate.ts";import {@@ -85,7 +86,7 @@ function runBrowserCommand(binaryPath: string, env: NodeJS.ProcessEnv, args: strlet output = "";const finish = (ok: boolean) => { if (!settled) { settled = true; done({ ok, output }); } };let child: ReturnType<typeof spawn>;- try { child = spawn(binaryPath, args, { env, stdio: capture ? ["ignore", "pipe", "ignore"] : "ignore", windowsHide: true }); }+ try { child = spawnBotWork(() => spawn(binaryPath, args, { env, stdio: capture ? ["ignore", "pipe", "ignore"] : "ignore", windowsHide: true })); }catch { return finish(false); }let exited = false;let killTimer: NodeJS.Timeout | undefined;@@ -473,7 +474,7 @@ export function ensureChrome(binaryPath: string, options: { withDeps?: boolean;}const args = ["install", ...(options.withDeps ? ["--with-deps"] : [])];return new Promise((done, fail) => {- const child = spawn(binaryPath, args, { env: options.env ?? process.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });+ const child = spawnBotWork(() => spawn(binaryPath, args, { env: options.env ?? process.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));let output = "";const record = (chunk: Buffer) => {output += String(chunk);@@ -632,7 +633,7 @@ export function setBrowserViewport(binaryPath: string, env: NodeJS.ProcessEnv, sif (!ownsBrowserViewport(env)) return Promise.resolve(true);return new Promise((settle) => {let child: ReturnType<typeof spawn>;- try { child = spawn(binaryPath, [...viewportArgs(size), "--json", "--no-webmcp"], { env: browserRuntimeEnv(env), stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); }+ try { child = spawnBotWork(() => spawn(binaryPath, [...viewportArgs(size), "--json", "--no-webmcp"], { env: browserRuntimeEnv(env), stdio: ["ignore", "pipe", "ignore"], windowsHide: true })); }catch { settle(false); return; }let output = "";let settled = false;diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.tsindex 54f1406f8c..acdcd2ee3e 100644--- a/server/browser-runtime.test.ts+++ b/server/browser-runtime.test.ts@@ -255,6 +255,12 @@ function daemonSpec(): { spec: BrowserSpawnSpec; busy: string; calls: () => stri}describe("server-owned browser MCP runtime", () => {+ it.runIf(process.platform === "linux")("starts a bot's browser engine first in line when memory runs out, before the server", async () => {+ const value = runtime();+ const listed = await value.agentRpc("scored", spec(), "tools/list", {}) as { pid: number };+ expect(readFileSync(`/proc/${listed.pid}/oom_score_adj`, "utf8").trim()).toBe("1000");+ });+it("never lets agent_browser_read fetch an address itself, around the browser and its egress gate", async () => {const value = runtime();const daemon = spec();diff --git a/server/browser-runtime.ts b/server/browser-runtime.tsindex 0ef09488e1..f726224587 100644--- a/server/browser-runtime.ts+++ b/server/browser-runtime.ts@@ -153,7 +153,7 @@ class BrowserClient {this.onClose = onClose;this.onRequestTimeout = onRequestTimeout;this.child = spawnCli(spec.command, spec.args, {- env: browserRuntimeEnv(spec.env), stdio: ["pipe", "pipe", "pipe"], shell: false,+ env: browserRuntimeEnv(spec.env), stdio: ["pipe", "pipe", "pipe"], shell: false, botWork: true,});this.child.stderr.resume();this.child.stdout.on("data", (chunk: Buffer) => this.read(chunk));diff --git a/server/browser/chrome/launch.ts b/server/browser/chrome/launch.tsindex 19f2389be1..dd966aba2b 100644--- a/server/browser/chrome/launch.ts+++ b/server/browser/chrome/launch.ts@@ -1,6 +1,7 @@import { execFile, spawn, type ChildProcess } from "node:child_process";import type { Readable, Writable } from "node:stream";+import { spawnBotWork } from "../../oom-score.ts";import { pipeTransport, type CdpTransport } from "../cdp/transport.ts";import { chromeArgs, chromeEnv, type ChromeEnvInput, type ChromeFlagsInput } from "./flags.ts";import { diagnoseLaunchFailure } from "./host-setup.ts";@@ -103,7 +104,7 @@ export async function launchChrome(options: LaunchOptions): Promise<ChromeProcessandboxHelper: options.sandboxHelper ?? null,profileMarker: options.profileMarker ?? null,});- const child = spawn(options.executablePath, argv, { stdio: ["ignore", "pipe", "pipe", "pipe", "pipe"], env, windowsHide: true });+ const child = spawnBotWork(() => spawn(options.executablePath, argv, { stdio: ["ignore", "pipe", "pipe", "pipe", "pipe"], env, windowsHide: true }));let output = "";const keep = (chunk: Buffer) => {output = (output + chunk.toString("utf8")).slice(-OUTPUT_LIMIT);diff --git a/server/browser/chrome/sidecar.ts b/server/browser/chrome/sidecar.tsindex f73e543b6f..fe85a25196 100644--- a/server/browser/chrome/sidecar.ts+++ b/server/browser/chrome/sidecar.ts@@ -5,6 +5,7 @@ import { execFile } from "node:child_process";import { inRunningBrowser } from "../../browser-engine.ts";import { browserRuntimeEnv } from "../../browser-runtime.ts";+import { spawnBotWork } from "../../oom-score.ts";import { connectCdp, type Cdp, type CdpEvent } from "../../browser-sites.ts";import { NO_PASSKEY_COMMANDS } from "../cdp/passkeys.ts";import type { ChromeIdentity } from "./identity.ts";@@ -110,7 +111,7 @@ async function runningBrowserCdpUrl(session: string, spec: LaunchSpec): Promise<let answer = await inRunningBrowser(spec.command, env, ["get", "cdp-url"]);if (!answer) {await new Promise<void>((resolve, reject) => {- execFile(spec.command, ["open", "--json", "--no-webmcp"], { env, timeout: 60_000, windowsHide: true }, (error) => error ? reject(error) : resolve());+ spawnBotWork(() => execFile(spec.command, ["open", "--json", "--no-webmcp"], { env, timeout: 60_000, windowsHide: true }, (error) => error ? reject(error) : resolve()));});answer = await inRunningBrowser(spec.command, env, ["get", "cdp-url"]);}diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.tsindex dc037d9e61..9886e05bdc 100644--- a/server/cloud-health.test.ts+++ b/server/cloud-health.test.ts@@ -48,6 +48,14 @@ function world(overrides: Partial<CloudHealthDeps> = {}) {const incidents = (w: ReturnType<typeof world>, after?: string) => w.health.report(after).incidents.map(({ kind, code, engine, count }) => ({ kind, code, engine, count }));const place = (state: PlaceRow["state"]): PlaceRow => ({ state, params: { bot: "Tallyspoon Ops", cause: "Boat said: quota exceeded for [email protected]." }, source: "works-on" });+describe("a Cloud home's memory pressure in its health report", () => {+ it("carries the last day's counts where the home watches memory, and null where it does not", () => {+ expect(world().health.report(undefined)).toMatchObject({ room: null });+ const room = { waits: 3, waitMs: 360_000, stopped: 1, killed: 2, stallMinutes: 4 };+ expect(world({ room: () => room }).health.report(undefined)).toMatchObject({ room });+ });+});+describe("a new Cloud's first hour in its health report", () => {it("carries the milestones and the Chief's counts, and null where there are none", () => {expect(world().health.report(undefined)).toMatchObject({ firstHour: null, value: null });@@ -109,14 +117,15 @@ describe("the failure code a Cloud home reports", () => {w.fail("this thread could not start — the engine is not installed");w.fail("queued message could not start — the engine is not installed");w.fail(TRIAL_CREDIT_REFUSED.used_up);- w.fail(`${memoryStopText(5)} (opencodeGo exited null before the prompt result)`);+ w.fail(`${memoryStopText(false)} (opencodeGo exited null before the prompt result)`);w.fail(memoryStallText("no activity for 20 minutes — the turn was stopped", 1));+ w.fail(memoryStopText(true));expect(incidents(w)).toEqual([{ kind: "turn", code: "stalled", engine: null, count: 1 },{ kind: "turn", code: "restart", engine: null, count: 1 },{ kind: "turn", code: "could_not_start", engine: null, count: 2 },{ kind: "turn", code: "trial_used_up", engine: null, count: 1 },- { kind: "turn", code: "out_of_memory", engine: null, count: 2 },+ { kind: "turn", code: "out_of_memory", engine: null, count: 3 },]);});diff --git a/server/cloud-health.ts b/server/cloud-health.tsindex f938818428..f6d38128a2 100644--- a/server/cloud-health.ts+++ b/server/cloud-health.ts@@ -8,6 +8,7 @@ import { PLACE_STATES } from "../shared/place-view.ts";import type { RoutineRunStatus } from "../shared/routines.ts";import { trialCreditKind } from "../shared/trial-credit.ts";import type { BoxReport } from "./bot-box/box.ts";+import type { RoomReport } from "./engine-memory.ts";import type { FirstHourReport } from "./host/first-hour.ts";import type { ValueReport } from "./host/value-ledger.ts";import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";@@ -42,6 +43,7 @@ const ROWLESS_STOPS = new Set(["shutdown_timeout", "auth_required", "update_requ/** Causes the server writes itself, by fixed code. */const FIXED_CAUSES: ReadonlyArray<[RegExp, string]> = [[/ran out of memory while \d+ tasks? ran at once/, "out_of_memory"],+ [/^Ran out of room, so I (closed the browser|stopped this task) to keep everything else running\./, "out_of_memory"],[/^no activity for \d+ minutes — the turn was stopped$/, "stalled"],[/^turn interrupted — OpenMausBot restarted$/, "restart"],[/could not start — /, "could_not_start"],@@ -249,6 +251,8 @@ export interface CloudHealthDeps {box?: () => BoxReport;/** A personal Cloud's milestones since its first boot, and the work its Chief did: times and counts only. */firstHour?: () => { firstHour?: FirstHourReport; value?: ValueReport };+ /** The last day's memory pressure (engine-memory.ts), where this home watches it. */+ room?: () => RoomReport;now?: () => number;}@@ -295,7 +299,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {turns: read.turns, routines: read.routines, engines: engines(), connectors: connectorState(),browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },box: boxSummary(deps.box?.()),- firstHour: first?.firstHour ?? null, value: first?.value ?? null,+ firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null,system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },};let budget = CLOUD_HEALTH_MAX_BYTES - JSON.stringify({ ...base, cursor: ledger.cursor(read.seq), truncated: true, incidents: [] }).length;diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex d5b01ec713..d85e107599 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -11,7 +11,7 @@ import {withoutCloudSecrets, withoutIgnoredCloudKeys, type CloudHomeConfig,} from "./cloud-home.ts";import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";-import { OOM_SCORE, spawnWithOomScore } from "./oom-score.ts";+import { OOM_SCORE, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";import { restartPolicy } from "./restart.ts";const SERVICE_USER = "maus";@@ -196,6 +196,7 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {ids = passwdIds(readFileSync("/etc/passwd", "utf8"), SERVICE_USER);if (!ids) throw new Error(`The ${SERVICE_USER} user is missing from this image.`);if (process.platform === "linux") for (const note of hardenHost(env)) console.log(`cloud home: ${note}`);+ if (protectSupervisor()) console.log("cloud home: the supervisor is never stopped for memory");// Only the mount point changes owner; anything inside keeps its owner.const stat = statSync(home);if (stat.uid !== ids.uid || stat.gid !== ids.gid) chownSync(home, ids.uid, ids.gid);diff --git a/server/drivers/acp/background-text.ts b/server/drivers/acp/background-text.tsindex 2ecdc9b1d0..08bf4ca26a 100644--- a/server/drivers/acp/background-text.ts+++ b/server/drivers/acp/background-text.ts@@ -34,7 +34,7 @@ export function runAcpOneShot(input: AcpOneShotInput): Promise<string> {const name = input.displayName;if (signal?.aborted) return Promise.reject(new Error(`${name} background call aborted`));return new Promise<string>((resolve, reject) => {- const child = input.spawn(input.command, input.argv, { cwd: input.cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"] });+ const child = input.spawn(input.command, input.argv, { cwd: input.cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"], botWork: true });let settled = false;let buffer = "";let received = 0;diff --git a/server/drivers/claude-background.ts b/server/drivers/claude-background.tsindex c723757d6b..09d5d216fa 100644--- a/server/drivers/claude-background.ts+++ b/server/drivers/claude-background.ts@@ -34,7 +34,7 @@ export function spawnBackgroundCall(cli: string, args: string[], env: NodeJS.Proconst cwd = mkdtempSync(join(tmpdir(), "omb-claude-background-"));const removeCwd = () => { try { rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch {} };try {- return { child: spawnCli(cli, args, { cwd, stdio: ["pipe", "pipe", "pipe"], env }), removeCwd };+ return { child: spawnCli(cli, args, { cwd, stdio: ["pipe", "pipe", "pipe"], env, botWork: true }), removeCwd };} catch (error) {removeCwd();throw error;diff --git a/server/drivers/claude-keepwarm.ts b/server/drivers/claude-keepwarm.tsindex dbb5b6727c..3b32c3dcb0 100644--- a/server/drivers/claude-keepwarm.ts+++ b/server/drivers/claude-keepwarm.ts@@ -152,7 +152,7 @@ export function runKeepWarmPing(opts: {return new Promise((resolve) => {let child: ReturnType<typeof spawnCli>;try {- child = spawnCli(opts.cli, args, { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true });+ child = spawnCli(opts.cli, args, { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true, botWork: true });} catch (error) {cleanup();resolve({ ok: false, reason: `the ping could not start: ${(error as Error).message}` });diff --git a/server/drivers/codex-background-text.ts b/server/drivers/codex-background-text.tsindex 2fc8541bad..909842aa9e 100644--- a/server/drivers/codex-background-text.ts+++ b/server/drivers/codex-background-text.ts@@ -116,7 +116,7 @@ export async function runCodexOneShot(input: CodexOneShotInput): Promise<string>try {return await new Promise<string>((resolve, reject) => {const argv = codexBackgroundArgs({ model: input.model, modelProvider: input.modelProvider, providerArgs: input.providerArgs, cwd });- const child = input.spawn(input.cli, argv, { cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"] });+ const child = input.spawn(input.cli, argv, { cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"], botWork: true });const describe = input.describeError ?? ((message: string) => message.slice(0, 400));let settled = false;let closed = false;diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.tsindex 30bd22fafd..7b22e22f45 100644--- a/server/engine-memory.test.ts+++ b/server/engine-memory.test.ts@@ -3,10 +3,10 @@ import { EventEmitter } from "node:events";import { describe, expect, it } from "vitest";import { TurnNotStartedError, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener, type SendTurnInput } from "./contracts.ts";import {- BROWSER_BYTES, EngineMemory, memoryStallText, memoryStillWaitingText, memoryStopText, memoryWaitText, processGroupBytes, readHostMemory, withEngineMemory,- type HostMemory,+ BROWSER_BYTES, EngineMemory, memoryStallText, memoryStillWaitingText, memoryStopped, memoryStopText, memoryWaitText, PressureLedger, processGroupBytes, readHostMemory,+ withEngineMemory, type HostMemory,} from "./engine-memory.ts";-import { OOM_SCORE, spawnWithOomScore } from "./oom-score.ts";+import { OOM_SCORE, protectSupervisor, spawnBotWork, spawnWithOomScore } from "./oom-score.ts";const MB = 1024 * 1024, GB = 1024 * MB;@@ -54,13 +54,25 @@ describe("reading the host", () => {const writes: string[] = [];let own = "-800";const file = { read: () => `${own}\n`, write: (_path: string, data: string) => { writes.push(data); own = data; } };- const spawned = spawnWithOomScore(OOM_SCORE.engine, () => own, file);+ const spawned = spawnWithOomScore(OOM_SCORE.bot, () => own, file);expect(process.platform === "linux" ? [spawned, writes, own] : [spawned, writes]).toEqual(process.platform === "linux" ? ["1000", ["1000", "-800"], "-800"] : ["-800", []]);writes.length = 0;- expect(() => spawnWithOomScore(OOM_SCORE.engine, () => { throw new Error("ENOENT"); }, file)).toThrow("ENOENT");+ expect(() => spawnWithOomScore(OOM_SCORE.bot, () => { throw new Error("ENOENT"); }, file)).toThrow("ENOENT");if (process.platform === "linux") expect([writes, own]).toEqual([["1000", "-800"], "-800"]);// A score that can't be read or set: the process starts as before.- expect(spawnWithOomScore(OOM_SCORE.engine, () => "started", { read: () => { throw new Error("EACCES"); }, write: () => { throw new Error("no"); } })).toBe("started");+ expect(spawnWithOomScore(OOM_SCORE.bot, () => "started", { read: () => { throw new Error("EACCES"); }, write: () => { throw new Error("no"); } })).toBe("started");+ // A bot's browser, helper engine or tool starts where its engine does: first in line when memory runs out.+ writes.length = 0;+ expect(spawnBotWork(() => own, file)).toBe(process.platform === "linux" ? "1000" : "-800");+ });++ it("keeps the supervisor from ever being picked when memory runs out, where root can say so", () => {+ let own = "0";+ const file = { read: () => `${own}\n`, write: (_path: string, data: string) => { own = data; } };+ expect([protectSupervisor(file), own]).toEqual(process.platform === "linux" ? [true, "-1000"] : [false, "0"]);+ // Not root: the kernel refuses a lower score, and the supervisor starts as before.+ expect(protectSupervisor({ read: () => "0\n", write: () => { throw Object.assign(new Error("EACCES"), { code: "EACCES" }); } })).toBe(false);+ expect([OOM_SCORE.supervisor, OOM_SCORE.edge, OOM_SCORE.server, OOM_SCORE.bot]).toEqual([-1000, -900, -800, 1000]);});});@@ -213,8 +225,10 @@ describe("running short", () => {h.memory.tick();await settle();expect(h.signals).toEqual(["SIGKILL -1004"]);- expect(h.memory.stopText("e")).toBe(memoryStopText(5));- expect(memoryStopText(5)).toBe("This Cloud ran out of memory while 5 tasks ran at once, so this one was stopped. It was not a problem with the AI provider. New tasks now wait until there is memory for them.");+ expect(h.memory.stopText("e")).toBe(memoryStopText(false));+ expect(memoryStopText(false)).toBe("Ran out of room, so I stopped this task to keep everything else running.");+ expect(memoryStopText(true)).toBe("Ran out of room, so I closed the browser to keep everything else running.");+ expect([memoryStopped(`${memoryStopText(true)} (opencodeGo exited null)`), memoryStopped(memoryStopText(false)), memoryStopped("the run ended without a result")]).toEqual([true, true, false]);// Within the cooldown, the next tick stops nothing more.h.memory.tick();await settle();@@ -263,7 +277,7 @@ describe("running short", () => {h.memory.turnStarted("b"); h.spawn("b");h.oomKill();a.exit("SIGKILL");- expect(h.memory.stopText("a")).toBe(memoryStopText(2));+ expect(h.memory.stopText("a")).toBe(memoryStopText(false));// A kill without the kernel's count moving (someone's kill -9) is not memory.const c = (h.memory.turnStarted("c"), h.spawn("c"));c.exit("SIGKILL");@@ -273,9 +287,9 @@ describe("running short", () => {describe("bots' browsers", () => {/** Threads whose bot may browse and whose browser is not running yet, and the threads whose browser was told to close. */- function browsers(h: ReturnType<typeof host>, starting: Iterable<string>) {- const pending = new Set(starting), closed: string[] = [];- h.memory.useBrowsers({ starts: (threadId) => pending.has(threadId), stopped: (threadId) => closed.push(threadId) });+ function browsers(h: ReturnType<typeof host>, starting: Iterable<string>, open: Iterable<string> = []) {+ const pending = new Set(starting), running = new Set(open), closed: string[] = [];+ h.memory.useBrowsers({ starts: (threadId) => pending.has(threadId), running: (threadId) => running.has(threadId), stopped: (threadId) => closed.push(threadId) });return { pending, closed };}@@ -338,14 +352,19 @@ describe("bots' browsers", () => {expect(closed).toEqual(["c"]);});- it("closes the browser of a turn the kernel's OOM killer stopped", () => {+ it("closes the browser of a turn the kernel's OOM killer stopped, and its turn says so in one line", () => {const h = host();- const { closed } = browsers(h, []);+ const { closed } = browsers(h, [], ["a"]);h.memory.turnStarted("a"); const a = h.spawn("a");- h.memory.turnStarted("b"); h.spawn("b");+ h.memory.turnStarted("b"); const b = h.spawn("b");h.oomKill();a.exit("SIGKILL");expect(closed).toEqual(["a"]);+ expect(h.memory.stopText("a")).toBe("Ran out of room, so I closed the browser to keep everything else running.");+ // A turn whose bot had no browser open: only the task was stopped.+ h.oomKill();+ b.exit("SIGKILL");+ expect(h.memory.stopText("b")).toBe(memoryStopText(false));});});@@ -418,13 +437,13 @@ describe("an engine's adapter on a Cloud home", () => {fake.emit({ threadId: "b", turnId: "tb", type: "turn.completed", ok: false, stopReason: "exit_before_result" });await settle();expect(seen.map((event) => event.type === "runtime.error" ? event.message : event.type)).toEqual([- `${memoryStopText(2)} (opencodeGo exited null before the prompt result)`, "turn.completed"]);+ `${memoryStopText(false)} (opencodeGo exited null before the prompt result)`, "turn.completed"]);expect(h.memory.stopText("b")).toBeNull();// An engine that ends its turn without an error of its own: the reason comes first.h.oomKill();h.children.get(1000)!.exit("SIGKILL");fake.emit({ threadId: "a", turnId: "ta", type: "turn.completed", ok: false, stopReason: "exit_before_result" });- expect(seen.slice(2).map((event) => event.type === "runtime.error" ? event.message : event.type)).toEqual([memoryStopText(1), "turn.completed"]);+ expect(seen.slice(2).map((event) => event.type === "runtime.error" ? event.message : event.type)).toEqual([memoryStopText(false), "turn.completed"]);});it("leaves engines that start no process of their own, and every engine where the gate is off, as they are", () => {@@ -491,7 +510,8 @@ describe("engines that run several threads' sessions", () => {h.memory.tick();await settle();expect(h.signals).toEqual([`SIGKILL -${shared.pid}`]);- expect([h.memory.stopText("s1"), h.memory.stopText("s2"), h.memory.stopText("x")]).toEqual([memoryStopText(3), memoryStopText(3), null]);+ expect([h.memory.stopText("s1"), h.memory.stopText("s2"), h.memory.stopText("x")]).toEqual([memoryStopText(false), memoryStopText(false), null]);+ expect(h.memory.stallCause("s2", "x")).toBe(memoryStallText("x", 3));const g = host();for (const thread of ["s1", "s2"]) g.memory.turnStarted(thread);@@ -532,3 +552,75 @@ describe("engines that run several threads' sessions", () => {it("words a stall the same way the Cloud's health report classifies it", () => {expect(memoryStallText("no activity for 20 minutes — the turn was stopped", 1)).toMatch(/ran out of memory while 1 task ran at once/);});++describe("the day's memory pressure, for the Admin", () => {+ it("counts the tasks that waited and how long, the turns stopped, the kernel's kills and the stalled minutes, over the last day", async () => {+ const h = host({ available: 1.2 * GB, tickMs: 60_000 });+ h.memory.turnStarted("a"); h.spawn("a");+ expect(h.memory.dayPressure()).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 });+ // "b" waits three minutes for memory; a wait still going counts its time so far.+ const stop = new AbortController();+ const b = h.memory.admit("b", stop.signal, () => {});+ await settle();+ h.advance(3 * 60_000);+ expect(h.memory.dayPressure()).toMatchObject({ waits: 1, waitMs: 3 * 60_000 });+ h.memory.turnEnded("a");+ h.children.get(1000)!.exit();+ expect(await b).toBe(true);+ expect(h.memory.dayPressure()).toMatchObject({ waits: 1, waitMs: 3 * 60_000 });+ // The machine stalls on memory for two minutes, and the kernel stops a turn's engine.+ h.state.available = 3.4 * GB;+ h.memory.turnStarted("b"); const engine = h.spawn("b");+ h.memory.turnStarted("c"); h.spawn("c");+ h.state.fullStall10 = 45;+ h.memory.tick(); h.memory.tick();+ h.advance(60_000);+ h.memory.tick();+ h.state.fullStall10 = 0;+ h.oomKill();+ engine.exit("SIGKILL");+ expect(h.memory.dayPressure()).toEqual({ waits: 1, waitMs: 3 * 60_000, stopped: 1, killed: 1, stallMinutes: 2 });+ // A day on, none of it counts.+ h.advance(24 * 60 * 60_000);+ expect(h.memory.dayPressure()).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 });+ });++ it("reads the pressure from the kernel's own files: memory left, the OOM kill count and the memory stall", async () => {+ const proc = { kills: 7, stall: "0.00", available: 2_400_000 };+ const files = (path: string) => {+ if (path === "/proc/meminfo") return `MemTotal: 4022248 kB\nMemAvailable: ${proc.available} kB\nSwapFree: 0 kB\n`;+ if (path === "/proc/vmstat") return `oom_kill ${proc.kills}\n`;+ if (path === "/proc/pressure/memory") return `some avg10=10.00 avg60=1.00 avg300=0.10 total=1\nfull avg10=${proc.stall} avg60=0.00 avg300=0.00 total=1\n`;+ throw new Error("ENOENT");+ };+ let clock = 1_800_000_000_000;+ const memory = new EngineMemory({ enabled: true, tickMs: 60_000, read: () => readHostMemory(files), groups: () => new Map(), now: () => clock, signal: () => {}, log: () => {} });+ const engine = new FakeChild(4242);+ memory.within("t", () => memory.track(engine as unknown as ChildProcess));+ memory.turnStarted("t");+ // The machine stalls on memory, then the kernel stops two processes (a bot's browser, say): counted, nothing else stopped.+ proc.stall = "38.50";+ memory.tick();+ clock += 60_000;+ proc.kills = 9; proc.stall = "0.00";+ memory.tick();+ expect(memory.dayPressure()).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 2, stallMinutes: 1 });+ expect(memory.stopText("t")).toBeNull();+ // The kernel then stops the turn's own engine: one plain line for it, and the server goes on.+ proc.kills = 10;+ engine.exit("SIGKILL");+ expect(memory.stopText("t")).toBe(memoryStopText(false));+ expect(memory.dayPressure()).toMatchObject({ stopped: 1, killed: 3 });+ memory.turnEnded("t");+ expect(await memory.admit("next", new AbortController().signal, () => {})).toBe(true);+ });++ it("keeps a minute's counts once and forgets them after a day", () => {+ const ledger = new PressureLedger(), start = 1_800_000_000_000;+ ledger.note(start, "waits"); ledger.note(start + 10_000, "waits"); ledger.note(start, "waitMs", 90_000);+ ledger.note(start, "stalled"); ledger.note(start + 20_000, "stalled");+ ledger.note(start, "killed", 3); ledger.note(start, "stopped");+ expect(ledger.read(start + 60_000, [start])).toEqual({ waits: 2, waitMs: 150_000, stopped: 1, killed: 3, stallMinutes: 1 });+ expect(ledger.read(start + 24 * 60 * 60_000 + 60_000)).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 });+ });+});diff --git a/server/engine-memory.ts b/server/engine-memory.tsindex 9551d86783..e25851c1a7 100644--- a/server/engine-memory.ts+++ b/server/engine-memory.ts@@ -20,6 +20,10 @@ export const BROWSER_BYTES = 400 * MB;/** A new engine's share is held back this long while it starts and grows; it is measured once it has run this long. */const RESERVE_MS = 90_000, SETTLED_MS = 30_000;const TICK_MS = 2_000, RELIEF_COOLDOWN_MS = 15_000, NOTICE_REPEAT_MS = 10 * 60_000, STOP_GRACE_MS = 5_000;+/** A minute counts as stalled on memory when every task that could run waited on memory this much of ten seconds (the+ * kernel's `full avg10`, in percent). */+const STALL_PERCENT = 20;+const MINUTE_MS = 60_000, DAY_MINUTES = 24 * 60;/** Engines that run each thread's turns in processes of their own. */export const ENGINE_PROCESS_KINDS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "opencodeGo", "grokAgent", "geminiAgent", "kimiAgent","droidAgent", "cursorAgent", "qwenAgent", "hermesAgent", "clineAgent", "copilotAgent", "customAcp", "piAgent", "antigravityAgent"]);@@ -72,17 +76,51 @@ export function processGroupBytes(list: () => string[] = () => readdirSync("/proconst tasks = (count: number) => `${count} ${count === 1 ? "task" : "tasks"}`;const running = (count: number) => `${tasks(count)} ${count === 1 ? "is" : "are"} running on this Cloud`;-export const memoryStopText = (count: number) => `This Cloud ran out of memory while ${tasks(count)} ran at once, so this one was stopped. `- + "It was not a problem with the AI provider. New tasks now wait until there is memory for them.";+/** The one line a turn stopped for memory ends with: what was closed to keep everything else running. */+export const memoryStopText = (browser: boolean) => `Ran out of room, so I ${browser ? "closed the browser" : "stopped this task"} to keep everything else running.`;+/** Whether a failed turn's cause is `memoryStopText`'s: such a run is started again once there is room. */+export const memoryStopped = (cause: string) => /^Ran out of room, so I (closed the browser|stopped this task) to keep everything else running\./.test(cause);export const memoryWaitText = (count: number) => `Waiting for memory: ${running(count)}, and one more could run it out of memory. `+ "This one starts by itself when there is room.";export const memoryStillWaitingText = (count: number) => `Still waiting for memory: ${running(count)}.`;export const memoryStallText = (cause: string, count: number) => `${cause}. This Cloud ran out of memory while ${tasks(count)} ran at once (not a problem with the AI provider)`;+/** The last day's memory pressure on a Cloud home: tasks that had to wait for memory and how long they waited in all (a wait+ * still going included), turns stopped for memory, processes the kernel stopped, and minutes the machine stalled on it. */+export interface RoomReport { waits: number; waitMs: number; stopped: number; killed: number; stallMinutes: number }+type PressureKind = "waits" | "waitMs" | "stopped" | "killed" | "stalled";++/** Counts by minute over the last day. */+export class PressureLedger {+ private readonly minutes = new Map<number, Record<PressureKind, number>>();++ note(at: number, kind: PressureKind, amount = 1): void {+ const minute = Math.floor(at / MINUTE_MS);+ const slot = this.minutes.get(minute) ?? { waits: 0, waitMs: 0, stopped: 0, killed: 0, stalled: 0 };+ slot[kind] = kind === "stalled" ? 1 : slot[kind] + amount;+ this.minutes.set(minute, slot);+ for (const key of this.minutes.keys()) if (key <= minute - DAY_MINUTES) this.minutes.delete(key);+ }++ /** `waiting`: when each task still waiting began to. */+ read(at: number, waiting: Iterable<number> = []): RoomReport {+ const report: RoomReport = { waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 };+ const since = Math.floor(at / MINUTE_MS) - DAY_MINUTES;+ for (const [minute, slot] of this.minutes) {+ if (minute <= since) continue;+ report.waits += slot.waits; report.waitMs += slot.waitMs; report.stopped += slot.stopped; report.killed += slot.killed; report.stallMinutes += slot.stalled;+ }+ for (const start of waiting) report.waitMs += Math.max(0, at - start);+ return report;+ }+}+/** The bots' browsers, which start during a turn rather than with its engine. */export interface EngineBrowsers {/** Whether this thread's bot may browse and its browser is not running yet. */starts(threadId: string): boolean;+ /** Whether this thread's bot's browser is running now. */+ running(threadId: string): boolean;/** This thread's engine was stopped for memory: its browser can close too once no turn holds it. */stopped(threadId: string): void;}@@ -115,11 +153,14 @@ export class EngineMemory {/** Threads admitted in the last RESERVE_MS: when, and what they were let in for. */private readonly reserved = new Map<string, { at: number; start: "process" | "session"; browser: boolean; browserSince?: number }>();private readonly queue: Waiter[] = [];- /** Threads whose engine was stopped for memory: how many tasks ran then. */- private readonly stops = new Map<string, number>();+ /** Threads whose engine was stopped for memory: how many tasks ran then, and whether their browser was running. */+ private readonly stops = new Map<string, { count: number; browser: boolean }>();/** Threads that ran while memory was short: the most tasks running then. */private readonly pressure = new Map<string, number>();private oomKills: number | null = null;+ private readonly ledger = new PressureLedger();+ /** Tasks waiting for memory now, and since when. */+ private readonly waitingSince = new Map<Waiter, number>();private lastRelief = -Infinity;private timer: ReturnType<typeof setInterval> | null = null;private browsers: EngineBrowsers | null = null;@@ -221,6 +262,7 @@ export class EngineMemory {}if (announced === null || this.now() - announced >= NOTICE_REPEAT_MS) {const others = this.othersBusy(threadId);+ if (announced === null) { this.waitingSince.set(waiter, this.now()); this.ledger.note(this.now(), "waits"); }notify(announced === null ? memoryWaitText(others) : memoryStillWaitingText(others));announced = this.now();}@@ -234,31 +276,35 @@ export class EngineMemory {}} finally {this.queue.splice(this.queue.indexOf(waiter), 1);+ const since = this.waitingSince.get(waiter);+ if (since !== undefined) { this.waitingSince.delete(waiter); this.ledger.note(this.now(), "waitMs", this.now() - since); }this.wake();}}/** The sentence for a turn of this thread whose engine was stopped for memory; null when it was not. */stopText(threadId: string): string | null {- const count = this.stops.get(threadId);- return count === undefined ? null : memoryStopText(count);+ const stop = this.stops.get(threadId);+ return stop === undefined ? null : memoryStopText(stop.browser);}/** A stalled turn's cause, saying so when memory ran short while it ran. */stallCause(threadId: string, cause: string): string {- const count = this.stops.get(threadId) ?? this.pressure.get(threadId);+ const count = this.stops.get(threadId)?.count ?? this.pressure.get(threadId);return count === undefined ? cause : memoryStallText(cause, count);}+ /** The last day's memory pressure, for the Admin's health check (cloud-health.ts): times only, never what ran. */+ dayPressure(): RoomReport { return this.ledger.read(this.now(), this.waitingSince.values()); }+/** Every couple of seconds while engines run: notes short memory against the running turns, and stops an engine before* the machine runs out: an idle one first, else the newest of two or more busy ones. */tick(): void {const memory = this.read();if (!memory) return;- // The kernel's OOM killer just stopped something (an engine first: oom-score.ts): its memory comes back first.- const killed = memory.oomKills !== null && this.oomKills !== null && memory.oomKills > this.oomKills;- this.oomKills = memory.oomKills ?? this.oomKills;- if (killed) return;+ if ((memory.fullStall10 ?? 0) >= STALL_PERCENT) this.ledger.note(this.now(), "stalled");+ // The kernel's OOM killer just stopped something (a bot's process: oom-score.ts): its memory comes back first.+ if (this.kernelKilled(memory.oomKills)) return;const free = this.free(memory), count = this.busy();if (free < this.floor(memory)) for (const threadId of this.active) this.pressure.set(threadId, Math.max(this.pressure.get(threadId) ?? 1, count));const critical = free < Math.max(160 * MB, memory.totalBytes * 0.04) || ((memory.fullStall10 ?? 0) >= 40 && free < this.floor(memory));@@ -270,7 +316,7 @@ export class EngineMemory {this.lastRelief = this.now();if (idle) { void this.stop(victim, "idle"); return; }const stopped = this.working(victim);- for (const threadId of stopped) this.stops.set(threadId, count);+ this.noteStops(stopped, () => count);void this.stop(victim, "relief").then(() => this.closeBrowsers(stopped));}@@ -341,19 +387,31 @@ export class EngineMemory {private exited(pid: number, engine: Engine, signal: NodeJS.Signals | null): void {if (this.engines.get(pid) === engine) this.engines.delete(pid);const working = this.working(engine);- if (signal === "SIGKILL" && !engine.stopping && working.length) {- const kills = this.read()?.oomKills ?? null;- if (kills !== null && this.oomKills !== null && kills > this.oomKills) {- for (const threadId of working) this.stops.set(threadId, this.busy(threadId));- this.log(`the kernel stopped an engine (pid ${pid}) for memory`);- this.closeBrowsers(working);- }- this.oomKills = kills ?? this.oomKills;+ if (signal === "SIGKILL" && !engine.stopping && working.length && this.kernelKilled(this.read()?.oomKills ?? null)) {+ this.noteStops(working, (threadId) => this.busy(threadId));+ this.log(`the kernel stopped an engine (pid ${pid}) for memory`);+ this.closeBrowsers(working);}if (!this.engines.size && this.timer) { clearInterval(this.timer); this.timer = null; }this.wake();}+ /** Whether the kernel stopped processes since the last read of its count, each counted for the day's pressure. */+ private kernelKilled(kills: number | null): boolean {+ const killed = kills !== null && this.oomKills !== null && kills > this.oomKills ? kills - this.oomKills : 0;+ this.oomKills = kills ?? this.oomKills;+ if (killed) this.ledger.note(this.now(), "killed", killed);+ return killed > 0;+ }++ /** These threads' turns were stopped for memory, with how many tasks ran then: each says whether its browser was closed. */+ private noteStops(threadIds: string[], count: (threadId: string) => number): void {+ for (const threadId of threadIds) {+ if (!this.stops.has(threadId)) this.ledger.note(this.now(), "stopped");+ this.stops.set(threadId, { count: count(threadId), browser: this.browsers?.running(threadId) === true });+ }+ }+private wake(): void { for (const waiter of this.queue) waiter.wake(); }private arm(): void {diff --git a/server/host/browser.ts b/server/host/browser.tsindex be07f041ec..c2985e1d34 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -438,6 +438,10 @@ export function createBrowserHost(deps: BrowserHostDeps) {const browser = threadBrowser(threadId);return browser !== null && (browser.session === undefined || !browserRunning(browser.session, browser.spec));},+ running: (threadId) => {+ const browser = threadBrowser(threadId);+ return browser?.session !== undefined && browserRunning(browser.session, browser.spec);+ },stopped: (threadId) => {const browser = threadBrowser(threadId);if (browser?.session !== undefined && browser.spec) void closeForMemory(browser.session, browser.spec);diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.tsindex 9ad5105492..16fa0d8eea 100644--- a/server/host/chief-notices-retry.test.ts+++ b/server/host/chief-notices-retry.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";import { TRIAL_CREDIT_REFUSED } from "../../shared/trial-credit.ts";import { AUTO_RETRY_LEAD, RETRY_BLOCKED } from "../incidents.ts";import type { RoutineFailureFacts } from "../routine-recovery.ts";-import { createChiefNotices, type ChiefNoticeDeps } from "./chief-notices.ts";+import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";function fixture(over: Partial<ChiefNoticeDeps> = {}) {const bots = [@@ -152,3 +152,66 @@ describe("OpenMausBot's one automatic retry of a teammate's failed thread", () =expect(AUTO_RETRY_LEAD.startsWith("[Retry requested by ")).toBe(true);});});++describe("a run stopped to free memory", () => {+ const STOPPED = "Ran out of room, so I closed the browser to keep everything else running. (claude exited null before result)";+ function roomFixture(over: Partial<ChiefNoticeDeps> = {}) {+ const waiting: Array<{ run: () => void; ms: number }> = [];+ const continued: Array<{ botId: string; threadId: string; text: string }> = [];+ const told: unknown[] = [];+ const f = fixture({+ later: (run, ms) => { waiting.push({ run, ms }); },+ continueRequest: async (botId, threadId, text) => { continued.push({ botId, threadId, text }); },+ notify: (notification) => { told.push(notification); },+ ...over,+ });+ // The Chief's own conversation, as the person's chat with it.+ f.chief.tasks.push({ threadId: "chief-main", title: "Clive" });+ return { ...f, waiting, continued, told, settle: () => { for (const { run } of waiting.splice(0)) run(); } };+ }++ it("starts once more by itself after the machine settles, with no Chief to retry it, and the person hears only if that fails too", async () => {+ const f = roomFixture();+ f.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Book the train to Leeds." });+ f.notices.reportIncident({ kind: "failed", bot: f.chief as never, threadId: "chief-main", detail: STOPPED });+ expect(f.told).toEqual([]);+ expect(f.waiting.map(({ ms }) => ms)).toEqual([MEMORY_RETRY_MS]);+ expect(MEMORY_RETRY_MS).toBe(30_000);+ f.settle();+ expect(f.continued).toEqual([{ botId: "chief", threadId: "chief-main", text: MEMORY_RETRY_TEXT }]);+ expect(f.startTurn).not.toHaveBeenCalled();+ // That run is stopped for memory too: the person hears now, and nothing starts again.+ f.notices.reportIncident({ kind: "failed", bot: f.chief as never, threadId: "chief-main", detail: STOPPED });+ f.settle();+ expect(f.continued).toHaveLength(1);+ expect(f.told).toHaveLength(1);+ });++ it("starts nothing when someone wrote in the thread since, or it runs or waits again", () => {+ const wrote = roomFixture();+ wrote.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Book the train." });+ wrote.notices.reportIncident({ kind: "failed", bot: wrote.chief as never, threadId: "chief-main", detail: STOPPED });+ vi.useFakeTimers({ now: Date.now() + 60_000 });+ try {+ wrote.store.appendMessage("chief-main", { role: "user", kind: "text", text: "Never mind, I booked it." });+ } finally {+ vi.useRealTimers();+ }+ wrote.settle();+ expect(wrote.continued).toEqual([]);+ const busy = roomFixture({ threadBusy: () => true });+ busy.notices.reportIncident({ kind: "failed", bot: busy.chief as never, threadId: "chief-main", detail: STOPPED });+ busy.settle();+ expect(busy.continued).toEqual([]);+ });++ it("leaves a teammate's run to the Chief's own retry, and any other failure to the person", () => {+ const teammate = roomFixture();+ teammate.notices.reportIncident({ kind: "failed", bot: teammate.ada as never, threadId: "ada-job", detail: STOPPED });+ expect(teammate.turnsOf("ada")).toEqual([{ threadId: "ada-job", text: expect.stringMatching(/^\[Retry requested by OpenMausBot, automatically, once/) }]);+ expect(teammate.waiting).toEqual([]);+ const other = roomFixture();+ other.notices.reportIncident({ kind: "failed", bot: other.chief as never, threadId: "chief-main", detail: CRASH });+ expect([other.waiting, other.told.length]).toEqual([[], 1]);+ });+});diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex f3855b1cbf..2a5ec547b3 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -1,5 +1,6 @@import { failedTurnTool } from "../../shared/failed-turn.ts";import { admit } from "../admission.ts";+import { memoryStopped } from "../engine-memory.ts";import { ESCALATIONS_THREAD_TITLE, EscalationLedger, escalationChip, escalationDeliverable, escalationText, type Escalation, type EscalationKind } from "../escalations.ts";import {AUTO_RETRY_LEAD, chiefForBot, INCIDENTS_THREAD_TITLE, IncidentLedger, incidentChip, incidentContext, incidentText, RETRY_BLOCKED, RETRY_LEAD,@@ -32,6 +33,11 @@ export interface ChiefNoticeDeps {threadQueued?(botId: string, threadId: string): boolean;/** Runs OpenMausBot's automatic retry after the failed turn's own handling is done; the host's next tick by default. */schedule?(run: () => void): void;+ /** Starts this thread's request again where it stopped: a continuation of the request the harness recorded, never a line+ * of the person's. Absent: a run stopped for memory with no Chief to retry it is only reported. */+ continueRequest?(botId: string, threadId: string, text: string): Promise<unknown>;+ /** Runs a retry after a run stopped for memory, MEMORY_RETRY_MS later by default, so the machine settles first. */+ later?(run: () => void, ms: number): void;/** Security invariant: a read-and-draft run's prompt and reply carry mail and invite text, so its failures and* questions never reach a Chief as a notice. */quietThread?(botId: string, threadId: string): boolean;@@ -47,11 +53,39 @@ export interface ChiefNoticeDeps {};}+/** How long a run stopped for memory waits before it starts again; the memory gate then holds it until there is room. */+export const MEMORY_RETRY_MS = 30_000;+export const MEMORY_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run was stopped to free memory on this Cloud. "+ + "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";+export function createChiefNotices(deps: ChiefNoticeDeps) {const { store } = deps;const incidentLedger = new IncidentLedger();const escalationLedger = new EscalationLedger();const schedule = deps.schedule ?? ((run: () => void) => { setTimeout(run, 0).unref?.(); });+ const later = deps.later ?? ((run: () => void, ms: number) => { setTimeout(run, ms).unref?.(); });+ /** Each thread's last request a run stopped for memory was started again for: once a request. */+ const roomRetries = new Map<string, string>();++ /** A run stopped for memory that no Chief retries starts once more by itself; the person hears only if that one fails too,+ * or can't start. Never a run whose thread someone wrote in since, or that is running or queued again. */+ function retryForRoom(bot: BotRecord, threadId: string, report: (retry?: IncidentRetry) => void): boolean {+ const continueRequest = deps.continueRequest;+ if (!continueRequest) return false;+ const asked = store.activePath(threadId).findLast((line) => line.role === "user")?.id ?? "";+ if (roomRetries.get(threadId) === asked) { report({ retried: true }); return true; }+ roomRetries.set(threadId, asked);+ if (roomRetries.size > 500) roomRetries.delete(roomRetries.keys().next().value!);+ const failedAt = Date.now();+ later(() => {+ if (!store.bot(bot.id) || !store.taskByThread(bot.id, threadId)) return;+ if (store.activePath(threadId).some((line) => line.role === "user" && line.at > failedAt)) return;+ if (deps.threadBusy(bot.id, threadId) || deps.threadQueued?.(bot.id, threadId)) return;+ continueRequest(bot.id, threadId, MEMORY_RETRY_TEXT)+ .catch((error) => report({ notRetried: `its retry could not start (${error instanceof Error ? error.message : String(error)})` }));+ }, MEMORY_RETRY_MS);+ return true;+ }/** Why a teammate's stopped thread cannot be retried now, in words a Chief can act on, or null. */function retryRefusal(botId: string, threadId: string): string | null {@@ -176,7 +210,9 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {chip: incidentChip(incident), text: incidentText(incident, count, retry),alreadyNotified: input.notified === true || input.kind === "could-not-start" || input.kind === "routine-failed",});- if (!chief || group || !reachesChief(chief, bot, threadId)) return report();+ const chiefRetries = Boolean(chief && !group && reachesChief(chief, bot, threadId));+ if (input.kind === "failed" && !group && !chiefRetries && memoryStopped(input.detail) && retryForRoom(bot, threadId, report)) return;+ if (!chief || !chiefRetries) return report();const answered = store.activePath(threadId).findLast((line) => line.role === "user")?.text ?? "";if (answered.startsWith(AUTO_RETRY_LEAD)) return report({ retried: true });if (input.kind !== "failed" || answered.startsWith(RETRY_LEAD) || !count.mayRetry || !retriesTeammateThread(input.detail, input.facts)) return report();diff --git a/server/index.ts b/server/index.tsindex 1df8f1cbc6..7bbf5cedc6 100644--- a/server/index.ts+++ b/server/index.ts@@ -2892,7 +2892,7 @@ let cloudPower: CloudPower | null = null; // The sleep handshake of a plan thatconst { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),- browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health() } });+ browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });const teamComputers = new TeamComputers(join(DATA_DIR, "team-computers.json"), ENVIRONMENT_ID);let followupsReady = false;const sendSequencer = new SendSequencer();@@ -7079,6 +7079,7 @@ const { reportIncident, reportEscalation, incidentRefused, retryThread } = creatthreadSettling: (threadId) => settlingTurns.has(threadId), threadQueued: (botId, threadId) => queuedThreadPosition(botId, threadId) !== null,groupTurnActive: (botId) => Boolean(activeGroupTurnForBot(botId)),escalationsEnabled: () => chiefEscalationsEnabled(cfg), ...(teamOwners.noticeRouting ? { routing: teamOwners.noticeRouting } : {}),+ continueRequest: (botId, threadId, text) => startTurn(botId, text, { threadId, unattended: true, cardContinuation: true, requestMessageId: directRequestOwners.get(threadId)?.messageId }),});function turnAnswers(threadId: string, opts?: {diff --git a/server/oom-score.ts b/server/oom-score.tsindex ccae934428..46efab4c64 100644--- a/server/oom-score.ts+++ b/server/oom-score.ts@@ -1,19 +1,23 @@import { readFileSync, writeFileSync } from "node:fs";/** Linux's OOM killer takes the process with the highest score first, and `oom_score_adj` (-1000 to 1000) moves a process- * up or down that order. On a Cloud home the engines (and the MCP servers they start) go first, Chrome's tabs next (Chrome- * scores them 200 and up itself), and the server and the edge, which answer the health check, last. */-export const OOM_SCORE = { engine: 1000, server: -800, edge: -900 } as const;+ * up or down that order. On a Cloud home everything a bot runs goes first: its engine and the tools and MCP servers that+ * engine starts, the MCP servers the server runs for it, the helper engines, and its browser (agent-browser's daemon and+ * Chrome, whose tabs Chrome then scores 200 and up itself). The server and the edge, which answer the health check, go last,+ * and the root supervisor that restarts them never. */+export const OOM_SCORE = { bot: 1000, server: -800, edge: -900, supervisor: -1000 } as const;const OWN = "/proc/self/oom_score_adj";+type ScoreFile = { read: (path: string) => string; write: (path: string, data: string) => void };+const procFile: ScoreFile = { read: (path) => readFileSync(path, "utf8"), write: writeFileSync };+/*** Runs `spawn` with this process's own score set to `score` for that instant. A child takes its parent's score when it is* forked, so the process is born with it, and so is everything it starts, however soon. Raising a score needs no privilege;* going back down needs root, or a score no lower than the one root last set, which is where it goes back to.*/-export function spawnWithOomScore<T>(score: number, spawn: () => T,- file: { read: (path: string) => string; write: (path: string, data: string) => void } = { read: (path) => readFileSync(path, "utf8"), write: writeFileSync }): T {+export function spawnWithOomScore<T>(score: number, spawn: () => T, file: ScoreFile = procFile): T {if (process.platform !== "linux") return spawn();let own: string | null = null;try {@@ -28,3 +32,18 @@ export function spawnWithOomScore<T>(score: number, spawn: () => T,if (own !== null) try { file.write(OWN, own); } catch {}}}++/** A bot's own work (its browser, a helper engine, a tool): started with OOM_SCORE.bot, so memory runs out on it first. */+export const spawnBotWork = <T>(spawn: () => T, file: ScoreFile = procFile): T => spawnWithOomScore(OOM_SCORE.bot, spawn, file);++/** The root supervisor's own score, set once at start: root may lower it, and the kernel then never picks it. False where+ * it can't be set (not Linux, not root). */+export function protectSupervisor(file: ScoreFile = procFile): boolean {+ if (process.platform !== "linux") return false;+ try {+ file.write(OWN, String(OOM_SCORE.supervisor));+ return file.read(OWN).trim() === String(OOM_SCORE.supervisor);+ } catch {+ return false;+ }+}diff --git a/server/procs.test.ts b/server/procs.test.tsindex 7a6f914956..7eb6014487 100644--- a/server/procs.test.ts+++ b/server/procs.test.ts@@ -91,15 +91,17 @@ describe("execCli timeout", () => {});describe("out of memory", () => {- it.runIf(process.platform === "linux")("a bot's engine is the first the kernel stops, and anything else keeps its score", async () => {+ it.runIf(process.platform === "linux")("a bot's engine and its other work are the first the kernel stops, and anything else keeps its score", async () => {const forever = ["-e", "setInterval(() => {}, 1000)"];const engine = spawnCli(process.execPath, forever, { stdio: ["pipe", "pipe", "pipe"] }, "bot");+ const browser = spawnCli(process.execPath, forever, { stdio: ["pipe", "pipe", "pipe"], botWork: true });const other = spawnCli(process.execPath, forever, { stdio: ["pipe", "pipe", "pipe"] });try {expect(readFileSync(`/proc/${engine.pid}/oom_score_adj`, "utf8").trim()).toBe("1000");+ expect(readFileSync(`/proc/${browser.pid}/oom_score_adj`, "utf8").trim()).toBe("1000");expect(readFileSync(`/proc/${other.pid}/oom_score_adj`, "utf8").trim()).toBe(readFileSync("/proc/self/oom_score_adj", "utf8").trim());} finally {- await Promise.all([killCliTree(engine), killCliTree(other)]);+ await Promise.all([killCliTree(engine), killCliTree(browser), killCliTree(other)]);}});});diff --git a/server/procs.ts b/server/procs.tsindex d53a956f48..bee4ea3818 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -18,7 +18,7 @@ import { engineMemory } from "./engine-memory.ts";import { engineHomes } from "./engine-homes/engine-homes.ts";import type { HomedSpawn } from "./engine-homes/layout.ts";import { resolveCliSpawn, type ResolvedSpawn } from "./env-path.ts";-import { OOM_SCORE, spawnWithOomScore } from "./oom-score.ts";+import { spawnBotWork } from "./oom-score.ts";export function resolveCli(cli: string, args: string[] = [], env?: NodeJS.ProcessEnv): ResolvedSpawn {return resolveCliSpawn(cli, args, env);@@ -163,6 +163,9 @@ export interface BoxSpawnOptions {box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "allowEnv">;/** On a Team Cloud, runs in its conversation's engine home though it is not a bot's engine (a keep-warm ping). */engineHome?: boolean;+ /** A bot's own work that is not its engine (its browser, a helper engine): memory runs out on it first, as on a `bot`+ * spawn (oom-score.ts), with no box and no engine tracking. */+ botWork?: boolean;}export type CliSpawnOptions = SpawnOptions & BoxSpawnOptions;@@ -185,7 +188,7 @@ export function spawnCli(const homed = owner === "bot" || opts.engineHome ? engineHomes.forSpawn(opts.env ?? process.env) : null;const options: CliSpawnOptions = homed ? { ...opts, env: homed.env } : opts;const boxed = boxedSpawn(resolved, options, owner, homed);- const { box: _box, engineHome: _engineHome, ...spawnOpts } = options;+ const { box: _box, engineHome: _engineHome, botWork, ...spawnOpts } = options;// The box's extra descriptors (its seccomp filter) follow stdio; only a plain three-entry stdio can take them.const stdio = boxed?.extraFds.length && Array.isArray(spawnOpts.stdio) && spawnOpts.stdio.length === 3 ? [...spawnOpts.stdio, ...boxed.extraFds] : spawnOpts.stdio;const start = () => spawn(boxed?.command ?? resolved.command, boxed?.args ?? resolved.args, {@@ -196,7 +199,7 @@ export function spawnCli(}) as ChildProcessByStdio<Writable, Readable, Readable>;let child: ChildProcessByStdio<Writable, Readable, Readable>;try {- child = owner === "bot" ? spawnWithOomScore(OOM_SCORE.engine, start) : start();+ child = owner === "bot" || botWork ? spawnBotWork(start) : start();} finally {for (const fd of boxed?.extraFds ?? []) try { closeSync(fd); } catch {}}diff --git a/src/components/CloudRoomCard.dom.test.ts b/src/components/CloudRoomCard.dom.test.tsnew file mode 100644index 0000000000..526d130079--- /dev/null+++ b/src/components/CloudRoomCard.dom.test.ts@@ -0,0 +1,113 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { CloudPlanBridge, CloudPlanSnapshot } from "../../electron/cloud-account.mjs";+import type { CloudRoom, CloudUsage } from "../../electron/cloud-home.mjs";+import { setLocale } from "@/lib/i18n";++const store = vi.hoisted(() => ({ bots: [] as Array<{ id: string; busy?: boolean }> }));+vi.mock("@/state/store", async original => ({ ...await original<typeof import("@/state/store")>(),+ useStore: () => ({ state: { bots: store.bots, config: { cloudHome: true } }, dispatch: vi.fn() }) }));+import { CloudRoomCard } from "./CloudRoomCard";++// The room card on the person's own Cloud, rendered as the sidebar renders it, against a bridge that answers as main does.+const usage: CloudUsage = { tier: "starter", resetsAt: Date.UTC(2026, 10, 1), meters: [{ kind: "storage", used: 2, max: 10 }], upgrades: [{ tier: "pro", amount: 4900 }, { tier: "max", amount: 9900 }] };+const memory: CloudRoom = { id: "offer-1", cause: { kind: "memory", waits: 3, waitMinutes: 6, stopped: 0 },+ plan: { tier: "pro", amount: 4900, memoryMb: 4096, fromMemoryMb: 2048, diskGb: 100, fromDiskGb: 10 } };+const PREVIEW = { plan: "pro", from: "starter", trial: false, price: 4900, chargeNow: 3120, tax: 0, nextBillingAt: Date.UTC(2026, 10, 18), expiresAt: Date.now() + 600_000 };+let container: HTMLDivElement, root: Root, snapshot: CloudPlanSnapshot;+function bridge(): CloudPlanBridge & Record<"upgradePreview" | "upgrade" | "roomNotNow" | "restartNow", ReturnType<typeof vi.fn>> {+ return { state: vi.fn(async () => snapshot), manage: vi.fn(async () => {}),+ upgradePreview: vi.fn(async () => ({ outcome: "preview" as const, preview: PREVIEW })),+ upgrade: vi.fn(async () => { snapshot = { status: "paid", tier: "pro", usage: { ...usage, tier: "pro", upgrades: [{ tier: "max", amount: 9900 }] } }; return { outcome: "upgraded" as const, tier: "pro" }; }),+ roomNotNow: vi.fn(async () => true), restartNow: vi.fn(async () => "restarting" as const) } as never;+}+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setLocale("en");+ globalThis.localStorage?.clear();+ store.bots = [{ id: "chief" }];+ snapshot = { status: "paid", tier: "starter", usage, room: memory };+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); document.body.innerHTML = ""; vi.unstubAllGlobals(); vi.restoreAllMocks(); });++const settle = async () => { for (let i = 0; i < 6; i++) await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); };+const show = async (plan: CloudPlanBridge) => { vi.stubGlobal("window", Object.assign(window, { ogb: { cloudPlan: plan } })); await act(async () => { root.render(createElement(CloudRoomCard)); }); await settle(); };+const card = () => document.querySelector<HTMLElement>("[data-cloud-room-card]");+const text = () => card()?.textContent ?? "";+const button = (label: string) => [...document.querySelectorAll("button")].find(item => item.textContent === label);+const click = async (target: Element | null | undefined) => { expect(target).toBeTruthy(); await act(async () => { (target as HTMLElement).click(); }); await settle(); };++describe("the room card", () => {+ it("says what ran short and what fixes it, and its Upgrade goes through the usual preview and confirmation, then offers Restart now", async () => {+ const plan = bridge();+ await show(plan);+ expect(card()?.getAttribute("data-cloud-room-card")).toBe("upgrade");+ expect(text()).toBe("This Cloud is short on room3 tasks waited 6 minutes for memory today.Pro has twice the memory. $49 a month. Today you pay only for the rest of this month.UpgradeNot now");+ await click(button("Upgrade"));+ expect(plan.upgradePreview).toHaveBeenCalledExactlyOnceWith("pro", "app_room");+ expect(plan.upgrade).not.toHaveBeenCalled();+ await click(button("Upgrade to Pro"));+ expect(plan.upgrade).toHaveBeenCalledExactlyOnceWith("pro", "app_room");+ expect(card()?.getAttribute("data-cloud-room-card")).toBe("upgraded");+ expect(text()).toContain("You're on Pro now. This Cloud gets its new size the next time it's not busy.");+ await click(button("Restart now"));+ expect(plan.restartNow).toHaveBeenCalledOnce();+ expect(text()).toBe("Restarting this Cloud with its new size. It's back in about a minute.");+ });++ it("forgets an upgrade once the session that made it ends, so Restart now never reaches another account's Cloud", async () => {+ const plan = bridge();+ await show(plan);+ await click(button("Upgrade"));+ await click(button("Upgrade to Pro"));+ expect(button("Restart now")).toBeTruthy();+ snapshot = { status: "none" };+ await act(async () => { window.dispatchEvent(new Event("focus")); });+ await settle();+ snapshot = { status: "paid", tier: "starter", usage };+ await act(async () => { window.dispatchEvent(new Event("focus")); });+ await settle();+ expect(button("Restart now")).toBeUndefined();+ expect(card()).toBeNull();+ });++ it("shows no offer whose plan the session's upgrades don't list: its Upgrade could never go through", async () => {+ snapshot = { status: "paid", tier: "starter", usage: { ...usage, upgrades: [{ tier: "max", amount: 9900 }] }, room: memory };+ await show(bridge());+ expect(card()).toBeNull();+ });++ it("waits while any bot is working, and Not now hides it here and tells the Admin", async () => {+ store.bots = [{ id: "chief", busy: true }];+ const plan = bridge();+ await show(plan);+ expect(card()).toBeNull();+ store.bots = [{ id: "chief" }];+ await act(async () => { root.render(createElement(CloudRoomCard)); });+ await settle();+ expect(card()).not.toBeNull();+ await click(button("Not now"));+ expect(plan.roomNotNow).toHaveBeenCalledExactlyOnceWith("offer-1");+ expect(card()).toBeNull();+ expect(plan.upgradePreview).not.toHaveBeenCalled();+ });++ it("shows the top plan a tip and no Upgrade, and nothing while the usage card is showing", async () => {+ const plan = bridge();+ snapshot = { status: "paid", tier: "max", usage: { ...usage, tier: "max", upgrades: [] }, room: { id: "tip-1", cause: { kind: "disk", usedGb: 87.5, capGb: 100 }, tip: true } };+ await show(plan);+ expect(card()?.getAttribute("data-cloud-room-card")).toBe("tip");+ expect(text()).toBe("This Cloud is almost out of space87.5 GB of 100 GB used.You're on the biggest plan. To free up space, delete files and folders you no longer need.Got it");+ expect(button("Upgrade")).toBeUndefined();+ await click(button("Got it"));+ expect(plan.roomNotNow).toHaveBeenCalledExactlyOnceWith("tip-1");+ await act(async () => root.unmount()); root = createRoot(container);+ snapshot = { status: "paid", tier: "starter", usage: { ...usage, meters: [{ kind: "computerHours", used: 95, max: 100 }] }, room: { ...memory, id: "offer-2" } };+ await show(bridge());+ expect(card()).toBeNull();+ });+});diff --git a/src/components/CloudRoomCard.tsx b/src/components/CloudRoomCard.tsxnew file mode 100644index 0000000000..5d955f5485--- /dev/null+++ b/src/components/CloudRoomCard.tsx@@ -0,0 +1,106 @@+import { useEffect, useState, type ReactNode } from "react";+import { ArrowUpRight, Loader2 } from "lucide-react";++import type { CloudPlanBridge, CloudPlanSnapshot } from "../../electron/cloud-account.mjs";+import { usageBridge, useUpgrade, NoteLine, type UpgradeUi } from "./CloudUsageMeter";+import { useCloudPlanSnapshot } from "./CloudTrialNotice";+import { cloudPlanLabel } from "@/lib/cloud-plan";+import { t } from "@/lib/i18n";+import { readRoomCardHidden, rememberRoomCardHidden, roomCardView, type RoomCardView } from "@/lib/room-card";+import { readUsageCardDismissed, upgradePath, usageCardView } from "@/lib/usage-meter";+import { useStore } from "@/state/store";++type Restart = "asking" | "restarting" | "current" | "failed";+const RESTART_NOTE: Record<Exclude<Restart, "asking">, string> = {+ restarting: "roomCard.restarting", current: "roomCard.current", failed: "roomCard.restartFailed",+} as const;++/** The card as it looks: the cause, the plan that fixes it with its price (or a tip on the top plan), Upgrade and Not now;+ * after an upgrade, Restart now. */+export function CloudRoomCardView({ view, upgrade, browser, upgraded, restart, onNotNow, onRestart, children }: {+ view: RoomCardView | null; upgrade: UpgradeUi; browser: boolean; upgraded: string | null; restart: Restart | null;+ onNotNow: () => void; onRestart: () => void; children?: ReactNode;+}) {+ if (upgraded) {+ return (+ <section data-cloud-room-card="upgraded" className="mb-2 rounded-xl border border-hairline/50 bg-card p-3 text-ink shadow-sm">+ <p role="status" className="text-[12px] leading-relaxed text-ink">{restart && restart !== "asking" ? t(RESTART_NOTE[restart] as Parameters<typeof t>[0]) : t("roomCard.done", { plan: cloudPlanLabel(upgraded) })}</p>+ {(restart === null || restart === "asking") && <>+ <button type="button" className="ui-button mt-2.5 w-full justify-center gap-1.5" disabled={restart === "asking"} onClick={onRestart}>+ {restart === "asking" && <Loader2 size={13} className="animate-spin" aria-hidden="true" />}+ {t("roomCard.restartNow")}+ </button>+ <p className="mt-1.5 text-center text-[11px] leading-4 text-ink-secondary">{t("roomCard.restartHint")}</p>+ </>}+ {children}+ </section>+ );+ }+ if (!view) return <>{children}</>;+ return (+ <section aria-labelledby="cloud-room-card-title" data-cloud-room-card={view.offer ? "upgrade" : "tip"} data-room-cause={view.kind}+ className="mb-2 rounded-xl border border-hairline/50 bg-card p-3 text-ink shadow-sm">+ <h2 id="cloud-room-card-title" className="text-[13px] font-semibold leading-5">{view.title}</h2>+ <p className="mt-1 text-[12px] leading-relaxed text-ink">{view.cause}</p>+ {view.offer ? <>+ <p className="mt-1.5 text-[12px] leading-relaxed text-ink-secondary">{view.offer.text} {view.offer.price}</p>+ <div className="mt-2.5 flex items-center gap-2">+ <button type="button" className="ui-button ui-button-primary min-w-0 flex-1 justify-center gap-1.5" disabled={upgrade.busy !== null} onClick={() => upgrade.onUpgrade(view.offer!.tier)}>+ {upgrade.busy === "preview" && <Loader2 size={13} className="animate-spin" aria-hidden="true" />}+ {t("roomCard.upgrade")}+ {browser && <ArrowUpRight size={13} aria-hidden="true" />}+ </button>+ <button type="button" className="ui-button min-w-0 flex-1 justify-center" disabled={upgrade.busy !== null} onClick={onNotNow}>{t("roomCard.notNow")}</button>+ </div>+ </> : <>+ <p className="mt-1.5 text-[12px] leading-relaxed text-ink-secondary">{view.tip}</p>+ <button type="button" className="ui-button mt-2.5 w-full justify-center" onClick={onNotNow}>{t("roomCard.gotIt")}</button>+ </>}+ {upgrade.note && <div className="mt-2"><NoteLine note={upgrade.note} /></div>}+ {children}+ </section>+ );+}++/** The plan's snapshot as the room card reads it, with the bridge that acts on it. */+export function useCloudRoom(): { snapshot: CloudPlanSnapshot | null; bridge: CloudPlanBridge | undefined; teamHome: boolean } {+ const { state } = useStore();+ const bridge = usageBridge(state.config?.cloudHome === true);+ return { snapshot: useCloudPlanSnapshot(bridge), bridge, teamHome: Boolean(state.config?.cloudHome && state.config?.team) };+}++/**+ * Where the usage meter's card is (the sidebar's foot, the phone's bar): this Cloud is short on room, said once, calmly. Its+ * Upgrade is the usual one (its preview, then the person's confirmation); Not now holds it back (the Admin, for two weeks).+ */+export function CloudRoomCard() {+ const { state } = useStore();+ const { snapshot, bridge, teamHome } = useCloudRoom();+ const usage = snapshot?.status === "paid" ? snapshot.usage ?? null : null;+ const [hidden, setHidden] = useState(readRoomCardHidden);+ const [upgraded, setUpgraded] = useState<string | null>(null);+ const [restart, setRestart] = useState<Restart | null>(null);+ const upgrade = useUpgrade(bridge, usage, "app_room", setUpgraded);+ // Restart now acts on the session's own Cloud: once that session ends, an upgrade made in it is no longer this card's.+ const paid = snapshot?.status === "paid";+ useEffect(() => { if (!paid) { setUpgraded(null); setRestart(null); } }, [paid]);+ const view = roomCardView({ room: snapshot?.status === "paid" ? snapshot.room : null, usage, busy: state.bots.some((bot) => bot.busy), hidden, teamHome,+ usageCardShown: Boolean(usageCardView({ usage, teamHome, dismissed: readUsageCardDismissed() })) });+ const notNow = () => {+ if (!view) return;+ rememberRoomCardHidden(view.id);+ setHidden(view.id);+ void bridge?.roomNotNow?.(view.id).catch(() => false);+ };+ const restartNow = () => {+ if (!bridge?.restartNow) { setRestart("failed"); return; }+ setRestart("asking");+ void bridge.restartNow().then(setRestart, () => setRestart("failed"));+ };+ return (+ <CloudRoomCardView view={view} upgrade={{ busy: upgrade.busy, note: upgrade.note, onUpgrade: upgrade.start }} browser={Boolean(usage) && upgradePath(usage!) === "browser"}+ upgraded={upgraded} restart={restart} onNotNow={notNow} onRestart={restartNow}>+ {upgrade.dialog}+ </CloudRoomCardView>+ );+}diff --git a/src/components/CloudUsageMeter.test.ts b/src/components/CloudUsageMeter.test.tsindex 589c3c4c90..d770efabef 100644--- a/src/components/CloudUsageMeter.test.ts+++ b/src/components/CloudUsageMeter.test.ts@@ -122,6 +122,9 @@ describe("Upgrade", () => {text: "Your plan can't be changed from the app right now. Nothing was charged. Open your Plan page to see your options." } });const settled = bridge({ upgradePreview: vi.fn(async () => ({ outcome: "settled" as const, status: "pending" as const, tier: "pro" })) });expect(await previewUpgrade(settled, usage(), "app_usage")).toEqual({ note: { tone: "info", text: "Your upgrade is going through. This can take a minute." } });+ // A change already gone through, to another plan than the one asked for, names the plan it is on now.+ const elsewhere = bridge({ upgradePreview: vi.fn(async () => ({ outcome: "settled" as const, status: "upgraded" as const, tier: "pro" })) });+ expect(await previewUpgrade(elsewhere, usage(), "app_usage", "max")).toEqual({ note: { tone: "good", text: "You're on Pro now. Your new allowances are ready." }, upgraded: "pro" });const declined = bridge({ upgrade: vi.fn(async () => ({ outcome: "refused" as const, code: "payment_failed" as const })) });expect(await confirmUpgrade(declined, PREVIEW, "app_usage")).toEqual({ tone: "bad",text: "Your payment didn't go through, so your plan hasn't changed. Update your card on your Plan page, then try again." });diff --git a/src/components/CloudUsageMeter.tsx b/src/components/CloudUsageMeter.tsxindex f203a9dd6d..d58d45cd36 100644--- a/src/components/CloudUsageMeter.tsx+++ b/src/components/CloudUsageMeter.tsx@@ -19,7 +19,7 @@ import type { LocaleKey } from "@/locales";import { useStore } from "@/state/store";const TEAM_TIERS: readonly string[] = ["team", "business"];-export type UpgradeSource = "app_usage" | "app_settings";+export type UpgradeSource = "app_usage" | "app_settings" | "app_room";export function usageBridge(cloudHome: boolean): CloudPlanBridge | undefined {if (window.ogb?.remoteClient?.active === true) return undefined;@@ -68,8 +68,9 @@ const failed = (): UpgradeNote => ({ tone: "bad", text: t("usageMeter.err.failedconst done = (tier: string): UpgradeNote => ({ tone: "good", text: t("usageMeter.done", { plan: cloudPlanLabel(tier) }) });const pending = (): UpgradeNote => ({ tone: "info", text: t("usageMeter.pending") });+/** `upgraded`: a change already going through settled on this plan, which may not be the one asked for. */export async function previewUpgrade(bridge: CloudPlanBridge, usage: CloudUsage, source: UpgradeSource, tier: string | undefined = nextPlan(usage)?.tier):- Promise<{ preview: CloudUpgradePreview } | { note: UpgradeNote }> {+ Promise<{ preview: CloudUpgradePreview } | { note: UpgradeNote; upgraded?: string }> {if (upgradePath(usage) !== "app" || !tier || !bridge.upgradePreview) {await bridge.manage();return { note: { tone: "info", text: t("usageMeter.browser") } };@@ -77,7 +78,7 @@ export async function previewUpgrade(bridge: CloudPlanBridge, usage: CloudUsage,const shown = await bridge.upgradePreview(tier, source);switch (shown.outcome) {case "preview": return { preview: shown.preview };- case "settled": return { note: shown.status === "upgraded" ? done(shown.tier) : pending() };+ case "settled": return shown.status === "upgraded" ? { note: done(shown.tier), upgraded: shown.tier } : { note: pending() };case "browser": return { note: { tone: "info", text: t("usageMeter.browser") } };case "refused": return { note: { tone: "bad", text: t(REFUSAL[shown.code]) } };default: return { note: failed() };@@ -97,7 +98,8 @@ export async function confirmUpgrade(bridge: CloudPlanBridge, preview: CloudUpgr}}-export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsage | null, source: UpgradeSource) {+/** `onUpgraded`: the plan the person's Cloud is on now, once an upgrade went through. */+export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsage | null, source: UpgradeSource, onUpgraded?: (tier: string) => void) {const [busy, setBusy] = useState<"preview" | "change" | null>(null);const [preview, setPreview] = useState<CloudUpgradePreview | null>(null);const [note, setNote] = useState<UpgradeNote | null>(null);@@ -110,11 +112,16 @@ export function useUpgrade(bridge: CloudPlanBridge | undefined, usage: CloudUsagconst start = (tier?: string) => run("preview", async () => {if (!usage) return;const next = await previewUpgrade(bridge!, usage, source, tier ?? nextPlan(usage)?.tier);- if ("preview" in next) setPreview(next.preview); else { setNote(next.note); cloudPlanChanged(); }+ if ("preview" in next) setPreview(next.preview);+ else { setNote(next.note); if (next.upgraded) onUpgraded?.(next.upgraded); cloudPlanChanged(); }});const confirm = () => run("change", async () => {if (!preview) return;- try { setNote(await confirmUpgrade(bridge!, preview, source)); } finally { setPreview(null); cloudPlanChanged(); }+ try {+ const note = await confirmUpgrade(bridge!, preview, source);+ setNote(note);+ if (note.tone === "good") onUpgraded?.(preview.plan);+ } finally { setPreview(null); cloudPlanChanged(); }});const dialog = (<ConfirmDialogdiff --git a/src/components/SidebarFooter.tsx b/src/components/SidebarFooter.tsxindex 951600ef51..d59e3f4592 100644--- a/src/components/SidebarFooter.tsx+++ b/src/components/SidebarFooter.tsx@@ -5,6 +5,7 @@ import type { SidebarDensity } from "@/lib/sidebar-preferences";import { useStore } from "@/state/store";import { AccountMoveStatus, useAccountMoveLine } from "./AccountMove";+import { CloudRoomCard } from "./CloudRoomCard";import { CloudUsageCard } from "./CloudUsageMeter";import { endCloudHowTo, useWorkspacePlace, type WorkspacePlace } from "./DesktopWorkspaceSwitcher";import { SidebarConnectApps } from "./SidebarConnectApps";@@ -34,6 +35,7 @@ function SimpleSidebarFooter({ owner, archived }: { owner: string | null; archivconst openAccount = () => footer.current?.querySelector("[data-sidebar-account]")?.closest("button")?.click();return (<div ref={footer} data-sidebar-footer="simple" className="px-4 pb-4 pt-2">+ <CloudRoomCard /><CloudUsageCard /><SidebarPlaceStatus place={place} className="mb-2 px-1" /><AccountMoveStatus kind={move.kind} retry={move.retry} onOpen={openAccount} className="ps-1" />@@ -69,6 +71,7 @@ export function SidebarFooter({ density, simple = false, owner = null, archived,</>) : (<>+ <CloudRoomCard /><CloudUsageCard /><div className="flex items-center gap-1 not-first:mt-3"><div className="min-w-0 flex-1">diff --git a/src/components/SidebarPhoneBar.tsx b/src/components/SidebarPhoneBar.tsxindex 68f176170d..c5b92245ff 100644--- a/src/components/SidebarPhoneBar.tsx+++ b/src/components/SidebarPhoneBar.tsx@@ -4,6 +4,7 @@ import { useCloudFilesReady } from "@/lib/cloud-files";import { t } from "@/lib/i18n";import { useStore } from "@/state/store";+import { CloudRoomCard } from "./CloudRoomCard";import { CloudUsageCard } from "./CloudUsageMeter";import { useAutomationsNeedYou } from "./SidebarFooterNav";import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";@@ -47,6 +48,7 @@ export function SidebarPhoneBar({ query, onQuery }: { query: string; onQuery: (q];return (<div data-sidebar-phone-bar className="px-3 pb-3 pt-1">+ <CloudRoomCard /><CloudUsageCard /><div className="flex items-center gap-2 not-first:mt-2"><SidebarPopoverMenudiff --git a/src/lib/room-card.test.ts b/src/lib/room-card.test.tsnew file mode 100644index 0000000000..615790dfc4--- /dev/null+++ b/src/lib/room-card.test.ts@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it } from "vitest";+import type { CloudRoom, CloudUsage } from "../../electron/cloud-home.mjs";+import { setLocale } from "@/lib/i18n";+import { roomCardView, roomCauseText } from "@/lib/room-card";++const usage: CloudUsage = { tier: "starter", resetsAt: Date.UTC(2026, 10, 1), meters: [], upgrades: [{ tier: "pro", amount: 4900 }, { tier: "max", amount: 9900 }] };+const room = (over: Partial<CloudRoom> = {}): CloudRoom => ({ id: "offer-1", cause: { kind: "memory", waits: 3, waitMinutes: 6, stopped: 0 },+ plan: { tier: "pro", amount: 4900, memoryMb: 4096, fromMemoryMb: 2048, diskGb: 100, fromDiskGb: 10 }, ...over });+const view = (over: Partial<Parameters<typeof roomCardView>[0]> = {}) => roomCardView({ room: room(), usage, busy: false, hidden: null, usageCardShown: false, ...over });++beforeEach(() => setLocale("en"));++describe("what the card says ran short", () => {+ it("counts the day's waits and stops in plain words", () => {+ const memory = (cause: Partial<Extract<CloudRoom["cause"], { kind: "memory" }>>) => roomCauseText({ kind: "memory", waits: 0, waitMinutes: 0, stopped: 0, ...cause });+ expect(memory({ waits: 3, waitMinutes: 6 })).toBe("3 tasks waited 6 minutes for memory today.");+ expect(memory({ waits: 1, waitMinutes: 1 })).toBe("1 task waited 1 minute for memory today.");+ expect(memory({ waits: 4 })).toBe("4 tasks had to wait for memory today.");+ expect(memory({ stopped: 1 })).toBe("1 task was stopped today to keep everything else running.");+ expect(memory({ waits: 2, waitMinutes: 3, stopped: 2 })).toBe("2 tasks waited 3 minutes for memory today. 2 tasks were stopped today to keep everything else running.");+ // A wait that began before the day still names a task.+ expect(memory({ waitMinutes: 4 })).toBe("1 task waited 4 minutes for memory today.");+ expect(roomCauseText({ kind: "disk", usedGb: 17.25, capGb: 20 })).toBe("17.3 GB of 20 GB used.");+ });+});++describe("the card", () => {+ it("names the plan that fixes it by what it gives, with its price this month or after a trial", () => {+ expect(view()).toEqual({ id: "offer-1", kind: "memory", title: "This Cloud is short on room", cause: "3 tasks waited 6 minutes for memory today.",+ offer: { tier: "pro", text: "Pro has twice the memory.", price: "$49 a month. Today you pay only for the rest of this month." }, tip: null });+ const max = { tier: "max" as const, amount: 9900, diskGb: 100, fromDiskGb: 10 };+ expect(view({ room: room({ plan: { ...max, memoryMb: 8192, fromMemoryMb: 2048 } }) })?.offer?.text).toBe("Max has 4 times the memory.");+ expect(view({ room: room({ plan: { ...max, memoryMb: 8192, fromMemoryMb: 3072 } }) })?.offer?.text).toBe("Max has 8 GB of memory.");+ expect(view({ room: room({ cause: { kind: "disk", usedGb: 9, capGb: 10 } }) })).toMatchObject({ kind: "disk", title: "This Cloud is almost out of space",+ cause: "9 GB of 10 GB used.", offer: { text: "Pro has room for 100 GB." } });+ expect(view({ usage: { ...usage, trialEndsAt: Date.UTC(2026, 10, 3) } })?.offer?.price).toBe("$49 a month once your trial ends. Nothing is charged today.");+ });++ it("gives the top plan a tip instead of an offer", () => {+ expect(view({ room: { id: "tip-1", cause: { kind: "memory", waits: 0, waitMinutes: 0, stopped: 2 }, tip: true } })).toEqual({ id: "tip-1", kind: "memory",+ title: "This Cloud is short on room", cause: "2 tasks were stopped today to keep everything else running.", offer: null,+ tip: "You're on the biggest plan. To give it more room, run fewer bots at once and close browsers you're not using." });+ });++ it("is never shown mid-turn, after Not now on this offer, beside the usage card, or without an offer", () => {+ expect(view({ busy: true })).toBeNull();+ // On a team's Cloud: only an offer about the team's own plan, never one about the person's own Cloud.+ expect(view({ teamHome: true })).toBeNull();+ expect(view({ teamHome: true, usage: { ...usage, tier: "team", upgrades: [] }, room: room({ plan: undefined, tip: true }) })?.tip).toContain("biggest plan");+ expect(view({ hidden: "offer-1" })).toBeNull();+ expect(view({ hidden: "an-older-offer" })).not.toBeNull();+ expect(view({ usageCardShown: true })).toBeNull();+ expect(view({ room: null })).toBeNull();+ // An offer whose plan the session's upgrades don't list could never go through.+ expect(view({ usage: { ...usage, upgrades: [{ tier: "max", amount: 9900 }] } })).toBeNull();+ });+});diff --git a/src/lib/room-card.ts b/src/lib/room-card.tsnew file mode 100644index 0000000000..a809b701f3--- /dev/null+++ b/src/lib/room-card.ts@@ -0,0 +1,69 @@+// Display only: the room card never changes a plan or a limit. The Admin decides when a Cloud is short on room and which+// plan fixes it (the session's `cloud.room`); its Upgrade goes through the usual preview and confirmation.+import type { CloudRoom, CloudUsage } from "../../electron/cloud-home.mjs";+import { cloudPlanLabel, usd } from "@/lib/cloud-plan";+import { activeLocale, t } from "@/lib/i18n";+import { TEAM_TIERS } from "@/lib/usage-meter";++export interface RoomCardView {+ id: string;+ kind: "memory" | "disk";+ title: string;+ /** What ran short, in the person's own numbers. */+ cause: string;+ /** The plan that fixes it, what it gives and its price; null on the top plan, which has a tip instead. */+ offer: { tier: string; text: string; price: string } | null;+ tip: string | null;+}++const count = (value: number, one: Parameters<typeof t>[0], many: Parameters<typeof t>[0]) => value === 1 ? t(one) : t(many, { count: String(value) });+const gb = (value: number) => new Intl.NumberFormat(activeLocale(), { maximumFractionDigits: 1 }).format(value);++export function roomCauseText(cause: CloudRoom["cause"]): string {+ if (cause.kind === "disk") return t("roomCard.cause.disk", { used: gb(cause.usedGb), cap: gb(cause.capGb) });+ // A wait that began before the day counts its minutes but not its start.+ const waits = Math.max(cause.waits, cause.waitMinutes > 0 ? 1 : 0), tasks = count(waits, "roomCard.tasks.one", "roomCard.tasks.many");+ const waited = waits === 0 ? null : cause.waitMinutes > 0+ ? t("roomCard.cause.waited", { tasks, minutes: count(cause.waitMinutes, "roomCard.minutes.one", "roomCard.minutes.many") })+ : t("roomCard.cause.waitedBriefly", { tasks });+ const stopped = cause.stopped === 0 ? null : count(cause.stopped, "roomCard.cause.stopped.one", "roomCard.cause.stopped.many");+ return [waited, stopped].filter(Boolean).join(" ");+}++function offerText(plan: NonNullable<CloudRoom["plan"]>, kind: RoomCardView["kind"]): string {+ const name = cloudPlanLabel(plan.tier);+ if (kind === "disk") return t("roomCard.offer.disk", { plan: name, gb: gb(plan.diskGb) });+ const times = plan.fromMemoryMb > 0 ? plan.memoryMb / plan.fromMemoryMb : 0;+ if (times === 2) return t("roomCard.offer.memoryTwice", { plan: name });+ if (Number.isInteger(times) && times > 2) return t("roomCard.offer.memoryTimes", { plan: name, times: String(times) });+ return t("roomCard.offer.memoryMore", { plan: name, gb: gb(plan.memoryMb / 1024) });+}++/**+ * The card, or null while there is nothing to show now: no offer, a turn running anywhere (never shown mid-turn), the person+ * said Not now to this very offer here, the usage meter's card is showing (one card at a time), or this is a team's Cloud and+ * the offer is about the person's own plan's Cloud, not the team's.+ */+export function roomCardView(input: { room: CloudRoom | null | undefined; usage: CloudUsage | null; busy: boolean; hidden: string | null; usageCardShown: boolean;+ teamHome?: boolean }): RoomCardView | null {+ const { room } = input;+ if (!room || input.busy || input.hidden === room.id || input.usageCardShown) return null;+ if (input.teamHome && !TEAM_TIERS.includes(input.usage?.tier ?? "")) return null;+ // Its Upgrade moves only to a plan the session's usage lists (main refuses any other), as the Admin makes it.+ if (room.plan && !input.usage?.upgrades.some((option) => option.tier === room.plan!.tier)) return null;+ const kind = room.cause.kind;+ const offer = room.plan ? {+ tier: room.plan.tier, text: offerText(room.plan, kind),+ price: t(input.usage?.trialEndsAt ? "roomCard.priceTrial" : "roomCard.price", { price: usd(room.plan.amount / 100) }),+ } : null;+ return { id: room.id, kind, title: t(kind === "disk" ? "roomCard.title.disk" : "roomCard.title.memory"), cause: roomCauseText(room.cause), offer,+ tip: offer ? null : t(kind === "disk" ? "roomCard.tip.disk" : "roomCard.tip.memory") };+}++const HIDDEN_KEY = "openmausbot.roomCard.hidden.v1";+export function readRoomCardHidden(): string | null {+ try { return globalThis.localStorage?.getItem(HIDDEN_KEY) ?? null; } catch { return null; }+}+export function rememberRoomCardHidden(id: string): void {+ try { globalThis.localStorage?.setItem(HIDDEN_KEY, id); } catch { /* Hidden only until reload; the Admin holds it back anyway. */ }+}diff --git a/src/lib/usage-meter.ts b/src/lib/usage-meter.tsindex a7ec6ca9fa..261e66f204 100644--- a/src/lib/usage-meter.ts+++ b/src/lib/usage-meter.ts@@ -6,7 +6,7 @@ import type { LocaleKey } from "@/locales";export const NEAR_LIMIT_PERCENT = 80;export const CARD_METERS = 2;-const TEAM_TIERS: readonly string[] = ["team", "business"];+export const TEAM_TIERS: readonly string[] = ["team", "business"];export type MeterBand = "ok" | "near" | "full";diff --git a/src/locales/en.json b/src/locales/en.jsonindex 60b913829f..461edc14af 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6845,6 +6845,34 @@"usageMeter.err.priceChanged": "The price changed since you looked, so nothing was charged. Choose Upgrade to see the new price.","usageMeter.err.rateLimited": "Too many tries. Wait a few minutes, then try again.","usageMeter.err.failed": "We couldn't change your plan. Nothing was charged. Try again in a minute.",+ "roomCard.title.memory": "This Cloud is short on room",+ "roomCard.title.disk": "This Cloud is almost out of space",+ "roomCard.tasks.one": "1 task",+ "roomCard.tasks.many": "{count} tasks",+ "roomCard.minutes.one": "1 minute",+ "roomCard.minutes.many": "{count} minutes",+ "roomCard.cause.waited": "{tasks} waited {minutes} for memory today.",+ "roomCard.cause.waitedBriefly": "{tasks} had to wait for memory today.",+ "roomCard.cause.stopped.one": "1 task was stopped today to keep everything else running.",+ "roomCard.cause.stopped.many": "{count} tasks were stopped today to keep everything else running.",+ "roomCard.cause.disk": "{used} GB of {cap} GB used.",+ "roomCard.offer.memoryTwice": "{plan} has twice the memory.",+ "roomCard.offer.memoryTimes": "{plan} has {times} times the memory.",+ "roomCard.offer.memoryMore": "{plan} has {gb} GB of memory.",+ "roomCard.offer.disk": "{plan} has room for {gb} GB.",+ "roomCard.price": "{price} a month. Today you pay only for the rest of this month.",+ "roomCard.priceTrial": "{price} a month once your trial ends. Nothing is charged today.",+ "roomCard.tip.memory": "You're on the biggest plan. To give it more room, run fewer bots at once and close browsers you're not using.",+ "roomCard.tip.disk": "You're on the biggest plan. To free up space, delete files and folders you no longer need.",+ "roomCard.upgrade": "Upgrade",+ "roomCard.notNow": "Not now",+ "roomCard.gotIt": "Got it",+ "roomCard.done": "You're on {plan} now. This Cloud gets its new size the next time it's not busy.",+ "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.",+ "roomCard.current": "This Cloud already has its new size.",+ "roomCard.restartFailed": "Couldn't restart it now. It gets its new size the next time it's not busy.","chat.savedSteps.learned": "Saved these steps · next time no AI","chat.savedSteps.replayed": "Repeated saved steps · no AI","chat.savedSteps.forget": "Forget",diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.tsindex 8e26dd3d7d..056d36a09c 100644--- a/src/locales/everyday-words.test.ts+++ b/src/locales/everyday-words.test.ts@@ -22,7 +22,7 @@ const EVERYDAY_PREFIXES: Record<string, readonly string[]> = {"MausBot Cloud: buying it, setting it up, moving to it and sharing with it": ["cloudBuy.", "cloudIntro.", "cloudTrial.", "cloudCancel.", "cloudSetup.", "cloudIntent.", "cloudNotice.", "cloudHowTo.", "cloudProPopup.","cloudCredit.", "cloudPower.", "cloudSignIn.", "cloudAdd.", "cloudHome.", "cloudPhone.", "cloudAccount.", "pro.", "lending.",- "files.", "usageMeter.",+ "files.", "usageMeter.", "roomCard.",],"routines and automations": ["routines.", "automations."],"the team map": ["canvas.", "mapComputer.", "canvasComputers."],diff --git a/src/room-card-preview.tsx b/src/room-card-preview.tsxnew file mode 100644index 0000000000..3ef214b116--- /dev/null+++ b/src/room-card-preview.tsx@@ -0,0 +1,99 @@+// Dev-only gallery of the room card, served at /room-card-preview.html; not in the packaged app.+// ?state=memory|stopped|disk|tip|trial|upgraded|restarting|confirm&layout=desktop|phone&skin=midnight|daylight&lang=de+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { Bot, CalendarClock, Gauge, LayoutGrid, MessageSquare, Plus, Search, Settings } from "lucide-react";+import type { CloudRoom, CloudUsage } from "../electron/cloud-home.mjs";+import { InitialsAvatar } from "@/components/Avatar";+import { ConfirmDialogCard } from "@/components/ConfirmDialog";+import { CloudRoomCardView } from "@/components/CloudRoomCard";+import { cloudPlanLabel } from "@/lib/cloud-plan";+import { setLocale, t } from "@/lib/i18n";+import { roomCardView } from "@/lib/room-card";+import { SKIN_IDS, type SkinId } from "@/lib/skins";+import { upgradeConfirmBody } from "@/lib/usage-meter";+import "./styles.css";++const RESETS = Date.UTC(2026, 10, 1);+const STARTER: CloudUsage = { tier: "starter", resetsAt: RESETS, meters: [], upgrades: [{ tier: "pro", amount: 4900 }, { tier: "max", amount: 9900 }] };+const PRO_PLAN = { tier: "pro" as const, amount: 4900, memoryMb: 4096, fromMemoryMb: 2048, diskGb: 100, fromDiskGb: 10 };+const STATES: Record<string, { usage: CloudUsage; room: CloudRoom }> = {+ memory: { usage: STARTER, room: { id: "a", cause: { kind: "memory", waits: 3, waitMinutes: 6, stopped: 0 }, plan: PRO_PLAN } },+ stopped: { usage: STARTER, room: { id: "b", cause: { kind: "memory", waits: 2, waitMinutes: 4, stopped: 1 }, plan: PRO_PLAN } },+ disk: { usage: STARTER, room: { id: "c", cause: { kind: "disk", usedGb: 8.9, capGb: 10 }, plan: PRO_PLAN } },+ tip: { usage: { tier: "max", resetsAt: RESETS, meters: [], upgrades: [] }, room: { id: "d", cause: { kind: "memory", waits: 5, waitMinutes: 14, stopped: 2 }, tip: true } },+ trial: { usage: { ...STARTER, trialEndsAt: Date.UTC(2026, 10, 3) }, room: { id: "e", cause: { kind: "memory", waits: 4, waitMinutes: 9, stopped: 0 }, plan: PRO_PLAN } },+};+const noop = () => {};+const IDLE = { busy: null, note: null, onUpgrade: noop };++function Card({ state }: { state: string }) {+ const sample = STATES[state] ?? STATES.memory!;+ if (state === "upgraded" || state === "restarting") {+ return <CloudRoomCardView view={null} upgrade={IDLE} browser={false} upgraded="pro" restart={state === "restarting" ? "restarting" : null} onNotNow={noop} onRestart={noop} />;+ }+ const view = roomCardView({ room: sample.room, usage: sample.usage, busy: false, hidden: null, usageCardShown: false });+ return <CloudRoomCardView view={view} upgrade={IDLE} browser={false} upgraded={null} restart={null} onNotNow={noop} onRestart={noop} />;+}++function row(Icon: typeof Bot, label: string, active = false) {+ return <div key={label} className={`flex min-h-9 items-center gap-3 rounded-xl px-3 py-1.5 text-[14px] font-medium ${active ? "bg-raised text-ink" : "text-ink"}`}><Icon size={18} className="text-ink-secondary" />{label}</div>;+}++function Desktop({ state }: { state: string }) {+ return <div className="flex h-full bg-app text-ink">+ <aside className="flex w-[260px] shrink-0 flex-col border-e border-hairline/40 bg-panel">+ <div className="flex gap-[7px] px-3.5 pb-1.5 pt-3.5">{[0, 1, 2].map(dot => <i key={dot} className="block size-[11px] rounded-full bg-raised" />)}</div>+ <div className="mx-3 my-2 flex items-center gap-2 rounded-xl bg-card px-3 py-2 text-[13px] text-ink-secondary"><Search size={15} />Search</div>+ <div className="px-3">{row(MessageSquare, "Chief", true)}{row(Bot, "Research")}{row(Bot, "Inbox")}{row(Plus, "New bot")}</div>+ <div className="flex-1" />+ <div className="px-3 pb-3 pt-2">+ {row(CalendarClock, "Routines")}{row(LayoutGrid, "Apps")}{row(Settings, "Settings")}+ <div className="mt-3"><Card state={state} /></div>+ <div className="flex min-h-[46px] items-center gap-3 rounded-xl px-3 py-2"><InitialsAvatar initials="MS" size={28} /><span className="truncate text-[14px] font-medium">Maya Shah</span></div>+ </div>+ </aside>+ <main className="flex flex-1 flex-col gap-3.5 p-10 opacity-60">+ {[58, 44, 36, 62, 30].map((width, index) => <div key={index} className={`h-3.5 rounded-md ${index === 2 ? "self-end bg-raised" : "bg-card"}`} style={{ width: `${width}%` }} />)}+ </main>+ </div>;+}++function Phone({ state }: { state: string }) {+ return <div className="flex h-full flex-col bg-panel text-ink">+ <div className="px-4 pb-2 pt-5 text-[22px] font-semibold">Chats</div>+ <div className="flex-1 px-3">{row(MessageSquare, "Chief", true)}{row(Bot, "Research")}{row(Bot, "Inbox")}{row(Bot, "Travel")}{row(Plus, "New bot")}</div>+ <div className="px-3 pb-3 pt-1">+ <Card state={state} />+ <div className="flex items-center gap-2 not-first:mt-2">+ <span className="flex size-11 items-center justify-center rounded-full border border-hairline bg-card text-ink"><LayoutGrid size={19} aria-hidden="true" /></span>+ <div className="flex h-11 min-w-0 flex-1 items-center gap-2 rounded-full border border-hairline bg-card pl-3.5 pr-1.5 text-ink-secondary"><Search size={17} aria-hidden="true" />Search</div>+ </div>+ </div>+ </div>;+}++function Confirm({ layout }: { layout: string }) {+ const preview = { plan: "pro", trial: false, price: 4900, chargeNow: 3120, tax: 0, nextBillingAt: Date.UTC(2026, 10, 18) };+ return <div className="relative h-full">+ {layout === "phone" ? <Phone state="memory" /> : <Desktop state="memory" />}+ <div className="absolute inset-0 flex items-center justify-center bg-black/55 p-6">+ <ConfirmDialogCard open tone="neutral" icon={<Gauge size={18} className="text-accent" />} title={t("usageMeter.confirm.title", { plan: cloudPlanLabel("pro") })}+ body={upgradeConfirmBody(preview)} confirmLabel={t("usageMeter.confirm.action", { plan: cloudPlanLabel("pro") })} cancelLabel={t("usageMeter.confirm.cancel")}+ onCancel={noop} onConfirm={noop} />+ </div>+ </div>;+}++function Preview() {+ const params = new URLSearchParams(location.search);+ const skin = (SKIN_IDS as readonly string[]).includes(params.get("skin") ?? "") ? params.get("skin") as SkinId : "midnight";+ document.documentElement.dataset.skin = skin;+ setLocale(params.get("lang") ?? "en");+ const state = params.get("state") ?? "memory", layout = params.get("layout") ?? "desktop";+ return <div className="h-screen overflow-hidden">+ {state === "confirm" ? <Confirm layout={layout} /> : layout === "phone" ? <Phone state={state} /> : <Desktop state={state} />}+ </div>;+}++createRoot(document.getElementById("root")!).render(<StrictMode><Preview /></StrictMode>);