Skip to content

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

Memory relief: close unused browsers first, and stop the only busy engine once the machine thrashes (#6860)

Milind Soni1c3d3fe012e1
diff --git a/server/chat-notices.ts b/server/chat-notices.ts
index eee7dd0ce4..d6b5f10524 100644
--- a/server/chat-notices.ts
+++ b/server/chat-notices.ts
@@ -156,6 +156,8 @@ export const CHAT_NOTICE = {
"{bot} used more memory than this computer allows for one bot ({used} MB of {cap} MB) while memory was running short, so I stopped this task to keep the other bots running. Send the message again to start over; if it keeps happening, give this task less to do at once, or give this computer more memory.",
"chat.notice.memoryReclaimedBrowserDetail": "Ran out of room, so I closed the browser to keep everything else running. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Ran out of room, so I stopped this task to keep everything else running. ({detail})",
+ "chat.notice.memoryReclaimedOnly": "Ran out of room, so I stopped this task to keep everything here from freezing.",
+ "chat.notice.memoryReclaimedOnlyDetail": "Ran out of room, so I stopped this task to keep everything here from freezing. ({detail})",
"chat.notice.outOfProcesses": "There is no room to start another program ({code}), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.",
} as const;
diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.ts
index 22a4d4c735..5843214606 100644
--- a/server/engine-memory.test.ts
+++ b/server/engine-memory.test.ts
@@ -106,13 +106,14 @@ class FakeChild extends EventEmitter {
function host(options: { available?: number; perEngine?: number; tickMs?: number } = {}) {
let clock = 1_800_000_000_000, oomKills = 0;
const perEngine = options.perEngine ?? 700 * MB;
- const state = { available: options.available ?? 3.4 * GB, fullStall10: 0 };
+ const state: { available: number; fullStall10: number; swapFree: number; stallScope?: "host" } = { available: options.available ?? 3.4 * GB, fullStall10: 0, swapFree: 0 };
const children = new Map<number, FakeChild>();
const signals: string[] = [];
const logs: string[] = [];
const memory = new EngineMemory({
enabled: true, tickMs: options.tickMs ?? 5,
- read: (): HostMemory => ({ totalBytes: 4 * GB, availableBytes: Math.max(0, state.available - children.size * perEngine), swapFreeBytes: 0, oomKills, fullStall10: state.fullStall10 }),
+ read: (): HostMemory => ({ totalBytes: 4 * GB, availableBytes: Math.max(0, state.available - children.size * perEngine), swapFreeBytes: state.swapFree, oomKills, fullStall10: state.fullStall10,
+ ...(state.stallScope ? { stallScope: state.stallScope } : {}) }),
groups: () => new Map([...children.keys()].map((pid) => [pid, perEngine])),
now: () => clock,
signal: (pid, signal) => {
@@ -370,6 +371,161 @@ describe("running short", () => {
expect(h.memory.stopText("a")).toBeNull();
});
+ /** A stand-in for the browser host: `unused` browsers no task uses; `close` resolves each stopped thread's close. */
+ function reclaimer(h: ReturnType<typeof host>, options: { unused?: number; running?: boolean; close?: Promise<unknown> } = {}) {
+ const asks: Array<{ thrashing: boolean; busy: readonly string[] }> = [];
+ let unused = options.unused ?? 0;
+ h.memory.useBrowsers({ starts: () => false, running: () => false, stopped: () => options.close, anyRunning: () => options.running ?? false,
+ reclaimUnused: (pressure) => { asks.push(pressure); const asked = unused; unused = 0; return asked; } });
+ return asks;
+ }
+
+ it("stops the only busy engine once the machine has thrashed for a cooldown, and its turn says it was the only one", async () => {
+ const h = host();
+ h.memory.turnStarted("a"); h.spawn("a");
+ h.state.available = 100 * MB + 700 * MB;
+ // Short, but not stalled: the only busy engine keeps running.
+ h.state.fullStall10 = 10;
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual([]);
+ // Thrashing on one look: still kept, a burst may pass.
+ h.state.fullStall10 = 70;
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual([]);
+ h.advance(15_000);
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1000"]);
+ expect(h.memory.stopText("a")).toBe(memoryStopText(false, true));
+ expect(memoryStopText(false, true)).toBe("Ran out of room, so I stopped this task to keep everything here from freezing.");
+ expect(memoryStopped(memoryStopText(false, true))).toBe(true);
+ });
+
+ it("leaves the only busy engine alone through a burst: 40% stalled with 400 MB of 4 GB available", async () => {
+ const h = host();
+ h.memory.turnStarted("a"); h.spawn("a");
+ h.state.available = 400 * MB + 700 * MB;
+ h.state.fullStall10 = 40;
+ for (let look = 0; look < 4; look++) { h.memory.tick(); await settle(); h.advance(16_000); }
+ expect(h.signals).toEqual([]);
+ });
+
+ it("never stops the only busy engine on a host's stall it borrowed (a cgroup without its own)", async () => {
+ const h = host();
+ h.memory.turnStarted("a"); h.spawn("a");
+ h.state.available = 20 * MB + 700 * MB;
+ h.state.fullStall10 = 90;
+ h.state.stallScope = "host";
+ for (let look = 0; look < 3; look++) { h.memory.tick(); await settle(); h.advance(16_000); }
+ expect(h.signals).toEqual([]);
+ });
+
+ it("sees a home thrash with swap free: memory available, not swap, decides", async () => {
+ const h = host();
+ h.memory.turnStarted("a"); h.spawn("a");
+ // 20 MB available, 3 GB of swap free (counted at half), and every task stalled most of the time.
+ h.state.available = 20 * MB + 700 * MB;
+ h.state.swapFree = 3 * GB;
+ h.state.fullStall10 = 80;
+ h.memory.tick();
+ h.advance(15_000);
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1000"]);
+ });
+
+ it("closes the browsers no task is using before it stops a busy engine, and asks them once per two cooldowns", async () => {
+ const h = host();
+ const asks = reclaimer(h, { unused: 1 });
+ for (const thread of ["a", "b"]) { h.memory.turnStarted(thread); h.spawn(thread); h.advance(1_000); }
+ h.state.available = 100 * MB + 2 * 700 * MB;
+ h.memory.tick();
+ await settle();
+ expect([asks.length, h.signals]).toEqual([1, []]);
+ expect(asks[0]).toEqual({ thrashing: false, busy: ["a", "b"] });
+ // Within the cooldown nothing more; past it, the browsers aren't asked again so soon: the newest busy engine goes.
+ h.memory.tick();
+ await settle();
+ expect(asks).toHaveLength(1);
+ h.advance(20_000);
+ h.memory.tick();
+ await settle();
+ expect([asks.length, h.signals]).toEqual([1, ["SIGKILL -1001"]]);
+ });
+
+ it("stops an idle engine before closing any browser, and asks the browsers in the same look once the machine thrashes", async () => {
+ const calm = host();
+ const calmAsks = reclaimer(calm, { unused: 1 });
+ calm.memory.turnStarted("a"); calm.spawn("a"); calm.memory.turnEnded("a");
+ calm.state.available = 100 * MB + 700 * MB;
+ calm.memory.tick();
+ await settle();
+ expect([calmAsks.length, calm.signals]).toEqual([0, ["SIGTERM -1000"]]);
+ // One idle engine, an unused browser, stalled 80% with 100 MB available: both in one look.
+ const h = host();
+ const asks = reclaimer(h, { unused: 1 });
+ h.memory.turnStarted("a"); h.spawn("a"); h.memory.turnEnded("a");
+ h.state.available = 100 * MB + 700 * MB;
+ h.state.fullStall10 = 80;
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGTERM -1000"]);
+ expect(asks).toEqual([{ thrashing: true, busy: [] }]);
+ });
+
+ it("keeps watching memory while a bot's browser runs after the last engine is gone", async () => {
+ const h = host({ tickMs: 5 });
+ const asks = reclaimer(h, { unused: 1, running: true });
+ h.memory.turnStarted("a"); h.spawn("a"); h.memory.turnEnded("a");
+ [...h.children.values()][0]!.exit(null);
+ await settle();
+ expect(h.children.size).toBe(0);
+ h.state.available = 50 * MB;
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(asks.length).toBeGreaterThan(0);
+ });
+
+ it("stops one busy engine at a time: none while a stop or its browser's close is under way, and two cooldowns after", async () => {
+ const h = host();
+ let closed!: () => void;
+ reclaimer(h, { close: new Promise((resolve) => { closed = () => resolve(undefined); }) });
+ for (const thread of ["a", "b", "c"]) { h.memory.turnStarted(thread); h.spawn(thread); h.advance(1_000); }
+ h.state.available = 100 * MB + 3 * 700 * MB;
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1002"]);
+ // Still short after it (what it freed went to the others), and its browser's close still runs: nothing more, however long.
+ h.state.available = 100 * MB + 2 * 700 * MB;
+ h.advance(60_000);
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toHaveLength(1);
+ closed();
+ await settle();
+ // Closed now: two cooldowns from then.
+ h.advance(20_000);
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toHaveLength(1);
+ h.advance(11_000);
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1002", "SIGKILL -1001"]);
+ });
+
+ it("stops a bot's own work before a turn a person started", async () => {
+ const h = host();
+ h.memory.useTurnOrder((threadId) => threadId === "person");
+ h.memory.turnStarted("bot"); h.spawn("bot"); h.advance(1_000);
+ h.memory.turnStarted("person"); h.spawn("person");
+ h.state.available = 100 * MB + 2 * 700 * MB;
+ h.memory.tick();
+ await settle();
+ expect(h.signals).toEqual(["SIGKILL -1000"]);
+ });
+
it("lets the memory the kernel's OOM killer just freed come back before stopping anything itself", async () => {
const h = host({ tickMs: 60_000 });
for (const thread of ["a", "b", "c"]) { h.memory.turnStarted(thread); h.spawn(thread); h.advance(1_000); }
@@ -402,7 +558,7 @@ 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>, 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) });
+ h.memory.useBrowsers({ starts: (threadId) => pending.has(threadId), running: (threadId) => running.has(threadId), stopped: (threadId) => { closed.push(threadId); } });
return { pending, closed };
}
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index 49b5b2c2df..db04c99bbf 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -41,6 +41,13 @@ export const BOT_TURN_GIVES_WAY_MS = 5 * 60_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;
+/** Every task stalled on memory this much of the time, with room below the floor: the machine is thrashing. A Cloud home
+ * that does stops answering, and its Admin restarts it within minutes, every turn with it (Nov 2026: 75 of 112 restarts
+ * on Fly in a week, 58 of them 2 GB homes without swap, memory available 7 MB and the stall 70% at the median). */
+const THRASH_PERCENT = 40;
+/** After a busy engine is stopped for room, no other busy one is for this long, nor while that stop or its browser's
+ * close is still under way: what it frees takes a moment to show. */
+const BUSY_STOP_GAP_MS = 2 * RELIEF_COOLDOWN_MS;
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",
@@ -49,7 +56,12 @@ export const ENGINE_PROCESS_KINDS: ReadonlySet<string> = new Set(["claudeAgent",
/** Chat-runtime engines (openai-chat.ts) have no process of their own, but each turn starts its MCP servers, each a Node process. */
export const CHAT_RUNTIME_KINDS: ReadonlySet<string> = new Set(["openai-compat", "cerebras", "greenference", "grok", "groq", "meta", "minimax", "mistral", "modelgo"]);
-export interface HostMemory { totalBytes: number; availableBytes: number; swapFreeBytes: number; oomKills: number | null; fullStall10: number | null }
+export interface HostMemory {
+ totalBytes: number; availableBytes: number; swapFreeBytes: number; oomKills: number | null; fullStall10: number | null;
+ /** "host": `fullStall10` is the whole machine's, read for a cgroup that has no stall of its own (cgroup v1), not this
+ * server's. Absent: its own. */
+ stallScope?: "host";
+}
const procText = (path: string) => readFileSync(path, "utf8");
@@ -63,7 +75,7 @@ export function readHostMemory(read: (path: string) => string = procText): HostM
const cgroup = readCgroupMemory((path) => { try { return read(path); } catch { return null; } });
if (!cgroup || cgroup.limitBytes >= host.totalBytes) return host;
return { totalBytes: cgroup.limitBytes, availableBytes: Math.max(0, Math.min(host.availableBytes, cgroup.limitBytes - cgroup.usedBytes)), swapFreeBytes: 0,
- oomKills: cgroup.oomKills ?? host.oomKills, fullStall10: cgroup.fullStall10 ?? host.fullStall10 };
+ oomKills: cgroup.oomKills ?? host.oomKills, fullStall10: cgroup.fullStall10 ?? host.fullStall10, ...(cgroup.fullStall10 === null && host.fullStall10 !== null ? { stallScope: "host" as const } : {}) };
}
function readMachineMemory(read: (path: string) => string): HostMemory | null {
@@ -109,13 +121,17 @@ export function processGroupBytes(list: () => string[] = () => readdirSync("/pro
const tasks = (count: number) => `${count} ${count === 1 ? "task" : "tasks"}`;
const running = (count: number) => `${tasks(count)} ${count === 1 ? "is" : "are"} running on this Cloud`;
-const memoryStopKey = (browser: boolean, detail = false) => detail
- ? browser ? "chat.notice.memoryReclaimedBrowserDetail" : "chat.notice.memoryReclaimedTaskDetail"
- : browser ? "chat.notice.memoryReclaimedBrowser" : "chat.notice.memoryReclaimedTask";
+/** `only`: it was the one task running (stopped as the machine thrashed): nothing else was kept running by it. */
+const memoryStopKey = (browser: boolean, detail = false, only = false) => only
+ ? detail ? "chat.notice.memoryReclaimedOnlyDetail" : "chat.notice.memoryReclaimedOnly"
+ : detail
+ ? browser ? "chat.notice.memoryReclaimedBrowserDetail" : "chat.notice.memoryReclaimedTaskDetail"
+ : browser ? "chat.notice.memoryReclaimedBrowser" : "chat.notice.memoryReclaimedTask";
/** The one line a turn stopped for memory ends with: what was closed to keep everything else running. */
-export const memoryStopText = (browser: boolean) => chatNotice(memoryStopKey(browser));
+export const memoryStopText = (browser: boolean, only = false) => chatNotice(memoryStopKey(browser, false, only));
/** 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 memoryStopped = (cause: string) =>
+ /^Ran out of room, so I (closed the browser|stopped this task) to keep (everything else running|everything here from freezing)\./.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)}.`;
@@ -168,8 +184,15 @@ export interface EngineBrowsers {
which?(threadId: string): string | undefined;
/** 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;
+ /** This thread's engine was stopped for memory: its browser can close too once no turn holds it. Resolves once it has
+ * closed, or given up. */
+ stopped(threadId: string): void | Promise<unknown>;
+ /** Closes running browsers no turn holds and no call runs in, before their idle time is up; how many it asked to close.
+ * `thrashing`: the machine thrashes, and a browser a person watches, one of a running turn that hasn't used it yet, or
+ * one whose close loses its sign-ins goes too. `busy`: the threads with a turn running (host/browser-reclaim.ts). */
+ reclaimUnused?(pressure: { thrashing: boolean; busy: readonly string[] }): number;
+ /** Whether any bot's browser runs now: memory is watched while one does, engine or not. */
+ anyRunning?(): boolean;
}
/** A plan's limit on how many turns run at once, whatever memory allows. */
@@ -220,7 +243,7 @@ export class EngineMemory {
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, and whether their browser was running. */
- private readonly stops = new Map<string, { count: number; browser: boolean }>();
+ private readonly stops = new Map<string, { count: number; browser: boolean; only?: true }>();
/** Threads whose turn could not run its engine for want of room: the code its failure names, and whether the engine's own
* spawn was refused (a later spawn in the same turn that works clears that) or the engine was stopped as silent. */
private readonly starved = new Map<string, { code: ShortageCode; why: "refused" | "silent" }>();
@@ -239,6 +262,11 @@ export class EngineMemory {
/** Tasks waiting for memory now, and since when. */
private readonly waitingSince = new Map<Waiter, number>();
private lastRelief = -Infinity;
+ private lastBrowserRelief = -Infinity;
+ private lastBusyStop = -Infinity;
+ private busyStopping = false;
+ /** Since when every reading has thrashed, the home's own stall (not a host's) with memory below the critical line. */
+ private thrashingSince: number | null = null;
private timer: ReturnType<typeof setInterval> | null = null;
private browsers: EngineBrowsers | null = null;
private personsOwn: (threadId: string) => boolean = () => false;
@@ -558,7 +586,7 @@ export class EngineMemory {
const starved = this.starved.get(threadId);
if (starved !== undefined && !interrupted && (detail === undefined || !namesOwnCause(detail))) return noticeFailure("chat.notice.outOfProcesses", { code: starved.code });
const stop = this.stops.get(threadId);
- return stop === undefined ? null : noticeFailure(memoryStopKey(stop.browser, detail !== undefined), detail === undefined ? undefined : { detail });
+ return stop === undefined ? null : noticeFailure(memoryStopKey(stop.browser, detail !== undefined, stop.only === true), detail === undefined ? undefined : { detail });
}
/** A stalled turn's cause, saying so when memory ran short while it ran. */
@@ -570,8 +598,11 @@ export class EngineMemory {
/** 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. */
+ /** Every couple of seconds while an engine or a bot's browser runs: notes short memory against the running turns, and
+ * makes room before the machine runs out: an idle engine first (and, thrashing, the unused browsers with it), then the
+ * browsers no turn is using, then one of two or more busy engines (a bot's own work before a person's, then the
+ * newest), one at a time; the only busy one only once the machine has thrashed on its own stall for a cooldown with
+ * memory below the critical line, when the Admin's restart that follows would stop it and everything else. */
tick(): void {
try { this.idleSweep?.(); } catch (error) { this.log(`idle sweep failed: ${error instanceof Error ? error.message : String(error)}`); }
const memory = this.read();
@@ -581,18 +612,52 @@ export class EngineMemory {
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));
+ // Short memory is noted against the running turns above on every look. Relief, and the watch itself, only while an
+ // engine or a bot's browser runs; with neither, the next engine starts the watch again.
+ if (!this.engines.size && !this.browsersRunning()) { if (this.timer) { clearInterval(this.timer); this.timer = null; } return; }
+ // Memory available, not counting swap: a home with gigabytes of swap free thrashes all the same (Nov 2026: memory
+ // available 0–100 MB, the stall at 40–98%, with 1.8–3.9 GB of swap free).
+ const thrashing = (memory.fullStall10 ?? 0) >= THRASH_PERCENT && memory.availableBytes < this.floor(memory);
+ const criticalLine = Math.max(160 * MB, memory.totalBytes * 0.04);
+ // The only busy engine goes only on this server's own stall, with memory itself below the critical line, read so on
+ // two looks at least a cooldown apart: a burst (an install, a build) that passes does not end a turn.
+ const severe = thrashing && memory.stallScope !== "host" && memory.availableBytes < criticalLine;
+ this.thrashingSince = severe ? this.thrashingSince ?? this.now() : null;
+ const critical = free < criticalLine || thrashing;
if (!critical || this.now() - this.lastRelief < RELIEF_COOLDOWN_MS) return;
+ const pressure = { thrashing, busy: [...this.active] };
+ const reclaimBrowsers = () => {
+ if (this.now() - this.lastBrowserRelief < 2 * RELIEF_COOLDOWN_MS) return 0;
+ let asked = 0;
+ try { asked = this.browsers?.reclaimUnused?.(pressure) ?? 0; } catch {}
+ if (asked > 0) this.lastBrowserRelief = this.now();
+ return asked;
+ };
const idle = this.idle();
- const newest = [...this.engines.values()].filter((engine) => !engine.stopping && this.working(engine).length).sort((a, b) => b.startedAt - a.startedAt);
- const victim = idle ?? (newest.length >= 2 ? newest[0]! : null);
+ if (idle) {
+ this.lastRelief = this.now();
+ void this.stop(idle, "idle");
+ // Thrashing, the browsers no task uses go in the same look: one idle engine at a time is too slow.
+ if (thrashing) reclaimBrowsers();
+ return;
+ }
+ // A browser no turn is using goes before any turn does: its idle time may be minutes away. Once per two cooldowns:
+ // if memory is still short after that, a busy engine goes, whatever the browsers say.
+ if (reclaimBrowsers() > 0) { this.lastRelief = this.now(); return; }
+ if (this.busyStopping || this.now() - this.lastBusyStop < BUSY_STOP_GAP_MS) return;
+ // A bot's own work goes before a turn a person started, then the newest.
+ const own = (engine: Engine) => this.working(engine).some((threadId) => this.personsOwn(threadId));
+ const busy = [...this.engines.values()].filter((engine) => !engine.stopping && this.working(engine).length)
+ .sort((a, b) => Number(own(a)) - Number(own(b)) || b.startedAt - a.startedAt);
+ const only = busy.length === 1;
+ const victim = busy.length >= 2 || (only && this.thrashingSince !== null && this.now() - this.thrashingSince >= RELIEF_COOLDOWN_MS) ? busy[0]! : null;
if (!victim) return;
- this.lastRelief = this.now();
- if (idle) { void this.stop(victim, "idle"); return; }
+ this.lastRelief = this.lastBusyStop = this.now();
+ this.busyStopping = true;
const stopped = this.working(victim);
- this.noteStops(stopped, () => count);
+ this.noteStops(stopped, () => count, only);
this.noteRoomStopped(victim);
- void this.stop(victim, "relief").then(() => this.closeBrowsers(stopped));
+ void this.stop(victim, "relief").then(() => this.closeBrowsers(stopped)).finally(() => { this.busyStopping = false; this.lastBusyStop = this.now(); });
}
/** How much of an idle engine's keep-alive memory allows: 1 with half the machine free above the floor, down to a tenth
@@ -693,7 +758,11 @@ export class EngineMemory {
private browserStarts(threadId: string): boolean { return this.browsers?.starts(threadId) === true; }
- private closeBrowsers(threadIds: string[]): void { for (const threadId of threadIds) this.browsers?.stopped(threadId); }
+ private browsersRunning(): boolean { try { return this.browsers?.anyRunning?.() === true; } catch { return false; } }
+
+ private closeBrowsers(threadIds: string[]): Promise<unknown> {
+ return Promise.all(threadIds.map((threadId) => { try { return this.browsers?.stopped(threadId); } catch { return undefined; } }));
+ }
private async stop(engine: Engine, why: "idle" | "relief"): Promise<void> {
const pid = engine.child.pid!, gone = () => engine.child.exitCode !== null || engine.child.signalCode !== null;
@@ -717,7 +786,7 @@ export class EngineMemory {
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; }
+ if (!this.engines.size && !this.browsersRunning() && this.timer) { clearInterval(this.timer); this.timer = null; }
this.wake();
}
@@ -730,10 +799,10 @@ export class EngineMemory {
}
/** 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 {
+ private noteStops(threadIds: string[], count: (threadId: string) => number, only = false): 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 });
+ this.stops.set(threadId, { count: count(threadId), browser: this.browsers?.running(threadId) === true, ...(only ? { only: true as const } : {}) });
}
}
diff --git a/server/host/browser-reclaim.test.ts b/server/host/browser-reclaim.test.ts
new file mode 100644
index 0000000000..94bc3ec13d
--- /dev/null
+++ b/server/host/browser-reclaim.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+
+import { createBrowserReclaim, RECLAIM_ASK_MS, reclaimable, type ReclaimCandidate } from "./browser-reclaim.ts";
+
+const spare: ReclaimCandidate = { session: "bot-a", held: false, working: false, running: true, attached: false, watched: false, turnRunning: false, savesSignIns: true };
+
+describe("reclaimable", () => {
+ it("never a browser a turn holds, a call runs in, that isn't running, or that is the person's own Chrome", () => {
+ for (const thrashing of [false, true]) {
+ expect(reclaimable({ ...spare, held: true }, thrashing)).toBe(false);
+ expect(reclaimable({ ...spare, working: true }, thrashing)).toBe(false);
+ expect(reclaimable({ ...spare, running: false }, thrashing)).toBe(false);
+ expect(reclaimable({ ...spare, attached: true }, thrashing)).toBe(false);
+ expect(reclaimable(spare, thrashing)).toBe(true);
+ }
+ });
+
+ it("a watched one, one of a running turn not used yet, or one losing its sign-ins only once the machine thrashes", () => {
+ for (const keep of [{ watched: true }, { turnRunning: true }, { savesSignIns: false }]) {
+ expect(reclaimable({ ...spare, ...keep }, false)).toBe(false);
+ expect(reclaimable({ ...spare, ...keep }, true)).toBe(true);
+ }
+ });
+});
+
+describe("createBrowserReclaim", () => {
+ it("asks each browser that may go once a minute, logs only a close that worked, and forgets old asks", async () => {
+ let clock = 1_800_000_000_000;
+ const closes: string[] = [], logs: string[] = [];
+ const results = new Map([["bot-a", true], ["bot-b", false]]);
+ const seenBusy: Array<readonly string[]> = [];
+ let candidates: ReclaimCandidate[] = [spare, { ...spare, session: "bot-b" }, { ...spare, session: "bot-held", held: true }];
+ const reclaim = createBrowserReclaim({
+ candidates: (busy) => { seenBusy.push(busy); return candidates; },
+ close: async (session) => { closes.push(session); return results.get(session) ?? false; },
+ log: (line) => logs.push(line), now: () => clock,
+ });
+ expect(reclaim.reclaim({ thrashing: false, busy: ["t1"] })).toBe(2);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(closes).toEqual(["bot-a", "bot-b"]);
+ expect(seenBusy).toEqual([["t1"]]);
+ expect(logs).toEqual(["browser bot-a: closed to free memory, no task was using it"]);
+ // The one whose close failed is not counted again within the minute.
+ clock += RECLAIM_ASK_MS - 1;
+ expect(reclaim.reclaim({ thrashing: false, busy: [] })).toBe(0);
+ expect(reclaim.asked()).toEqual(["bot-a", "bot-b"]);
+ // After it, old asks are forgotten: what still runs may be asked again.
+ clock += 1;
+ candidates = [{ ...spare, session: "bot-b" }];
+ expect(reclaim.reclaim({ thrashing: false, busy: [] })).toBe(1);
+ expect(reclaim.asked()).toEqual(["bot-b"]);
+ });
+});
diff --git a/server/host/browser-reclaim.ts b/server/host/browser-reclaim.ts
new file mode 100644
index 0000000000..c4d29e1a32
--- /dev/null
+++ b/server/host/browser-reclaim.ts
@@ -0,0 +1,64 @@
+// Which bot browsers memory relief may close before their idle time is up (engine-memory.ts `reclaimUnused`), and asking
+// them. Never one a turn holds, one a call runs in, or one attached to the person's own Chrome. Under ordinary shortage
+// also never one a person is watching, one of a bot with a turn running that hasn't used it yet this turn (claims are
+// made on first use), or one whose close would lose its sign-ins (a guest or temporary browser). Once the machine
+// thrashes those go too: the restart that otherwise follows closes every one of them.
+
+export interface ReclaimCandidate {
+ session: string;
+ /** A turn holds it (its claim), or a call runs in it now. */
+ held: boolean;
+ working: boolean;
+ running: boolean;
+ /** It is attached to the person's own Chrome, or is the person's Chrome engine: never closed here. */
+ attached: boolean;
+ /** Someone is watching it live. */
+ watched: boolean;
+ /** A bot with a turn running now uses it. */
+ turnRunning: boolean;
+ /** Its sign-ins are saved when it closes. */
+ savesSignIns: boolean;
+}
+
+export function reclaimable(candidate: ReclaimCandidate, thrashing: boolean): boolean {
+ if (!candidate.running || candidate.held || candidate.working || candidate.attached) return false;
+ if (thrashing) return true;
+ return !candidate.watched && !candidate.turnRunning && candidate.savesSignIns;
+}
+
+/** A browser asked to close this recently is not counted again, whether its close failed or still runs. */
+export const RECLAIM_ASK_MS = 60_000;
+
+export interface BrowserReclaimDeps {
+ /** Every browser this server started, given the threads with a turn running now. */
+ candidates(busy: readonly string[]): ReclaimCandidate[];
+ /** Closes it; true once it is gone. */
+ close(session: string): Promise<boolean>;
+ log?: (line: string) => void;
+ now?: () => number;
+}
+
+export function createBrowserReclaim(deps: BrowserReclaimDeps) {
+ const asked = new Map<string, number>();
+ const now = deps.now ?? Date.now;
+ const log = deps.log ?? ((line: string) => console.info(line));
+ return {
+ /** Asks every browser that may go now to close; how many it asked. */
+ reclaim(pressure: { thrashing: boolean; busy: readonly string[] }): number {
+ const at = now();
+ for (const [session, when] of asked) if (at - when >= RECLAIM_ASK_MS) asked.delete(session);
+ let count = 0;
+ for (const candidate of deps.candidates(pressure.busy)) {
+ if (asked.has(candidate.session) || !reclaimable(candidate, pressure.thrashing)) continue;
+ asked.set(candidate.session, at);
+ count += 1;
+ void deps.close(candidate.session).then((closed) => {
+ if (closed) log(`browser ${candidate.session}: closed to free memory, no task was using it`);
+ }, () => undefined);
+ }
+ return count;
+ },
+ /** Sessions asked within RECLAIM_ASK_MS: for tests. */
+ asked: () => [...asked.keys()],
+ };
+}
diff --git a/server/host/browser.ts b/server/host/browser.ts
index b43fd1e1ae..abc0bf5ee1 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -47,6 +47,7 @@ import { passkeyAnnotation } from "../browser/passkey-notice.ts";
import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";
import type { ChromeRoute } from "../device-links.ts";
import type { EngineBrowsers } from "../engine-memory.ts";
+import { createBrowserReclaim } from "./browser-reclaim.ts";
import { BROWSER_TASKS, processBudget } from "../process-room.ts";
import { idleAfter } from "../drivers/session-idle.ts";
import { augmentedPath } from "../env-path.ts";
@@ -529,6 +530,19 @@ export function createBrowserHost(deps: BrowserHostDeps) {
await sleep(2_000);
}
}
+ // Memory relief's early close of unused browsers (host/browser-reclaim.ts): attached and Chrome-engine ones never.
+ const browserReclaim = createBrowserReclaim({
+ candidates: (busy) => {
+ const busySessions = new Set(busy.flatMap((threadId) => threadBrowser(threadId)?.session ?? []));
+ return [...usedBrowserSessions].map(([session, spec]) => {
+ const working = agentBrowserRuntime.working(session), spare = agentBrowserRuntime.spare(session);
+ return { session, held: !turnResources.free(`browser:${session}`), working, running: browserRunning(session, spec),
+ attached: Boolean(chromeTarget(session, spec)) || attachesToChrome(spec.env), watched: spare === null && !working, turnRunning: busySessions.has(session),
+ savesSignIns: spare?.savesSignIns ?? spec.env.AGENT_BROWSER_RESTORE_SAVE === "auto" };
+ });
+ },
+ close: (session) => { const spec = usedBrowserSessions.get(session); return spec ? browserRuntime.closeUnused(session, spec) : Promise.resolve(false); },
+ });
const engineBrowsers: EngineBrowsers = {
starts: (threadId) => {
const browser = threadBrowser(threadId);
@@ -541,8 +555,10 @@ export function createBrowserHost(deps: BrowserHostDeps) {
},
stopped: (threadId) => {
const browser = threadBrowser(threadId);
- if (browser?.session !== undefined && browser.spec) void closeForMemory(browser.session, browser.spec);
+ return browser?.session !== undefined && browser.spec ? closeForMemory(browser.session, browser.spec) : undefined;
},
+ reclaimUnused: (pressure) => browserReclaim.reclaim(pressure),
+ anyRunning: () => [...usedBrowserSessions].some(([session, spec]) => browserRunning(session, spec)),
};
deps.engineMemory?.useBrowsers(engineBrowsers);
/** A deleted bot's or profile's browser on the new engine, whatever the flag says now. */
diff --git a/src/locales/en.json b/src/locales/en.json
index 5b4144f95f..f45102432f 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10332,6 +10332,8 @@
"chat.notice.botMemoryCap": "{bot} used more memory than this computer allows for one bot ({used} MB of {cap} MB) while memory was running short, so I stopped this task to keep the other bots running. Send the message again to start over; if it keeps happening, give this task less to do at once, or give this computer more memory.",
"chat.notice.memoryReclaimedBrowserDetail": "Ran out of room, so I closed the browser to keep everything else running. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Ran out of room, so I stopped this task to keep everything else running. ({detail})",
+ "chat.notice.memoryReclaimedOnly": "Ran out of room, so I stopped this task to keep everything here from freezing.",
+ "chat.notice.memoryReclaimedOnlyDetail": "Ran out of room, so I stopped this task to keep everything here from freezing. ({detail})",
"chat.notice.outOfProcesses": "There is no room to start another program ({code}), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.",
"server.personFirst.stoppedSeconds": "Stopped a step that had run for {seconds} s, to answer you first",
"server.personFirst.stoppedMinutes": "Stopped a step that had run for {minutes} min, to answer you first",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 6f8cfee6ce..4adf3550a3 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10243,6 +10243,8 @@
"chat.notice.botMemoryCap": "{bot} usou mais memória do que este computador permite para um bot ({used} MB de {cap} MB) enquanto a memória estava acabando, então interrompi esta tarefa para manter os outros bots funcionando. Envie a mensagem de novo para recomeçar; se continuar acontecendo, dê menos trabalho de uma vez a esta tarefa ou mais memória a este computador.",
"chat.notice.memoryReclaimedBrowserDetail": "Faltou memória, então fechei o navegador para manter o restante funcionando. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Faltou memória, então interrompi esta tarefa para manter o restante funcionando. ({detail})",
+ "chat.notice.memoryReclaimedOnly": "Faltou memória, então interrompi esta tarefa para que nada aqui travasse.",
+ "chat.notice.memoryReclaimedOnlyDetail": "Faltou memória, então interrompi esta tarefa para que nada aqui travasse. ({detail})",
"chat.notice.outOfProcesses": "Não há espaço para iniciar outro programa ({code}), então esta tarefa não pôde rodar. Nada foi enviado à IA. Ela começa de novo sozinha quando houver espaço.",
"server.personFirst.stoppedSeconds": "Interrompi um passo que já durava {seconds} s para responder a você primeiro",
"server.runOwner.onlyAskerStops": "Só {name} ou um administrador pode interromper isto.",