Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
The server sleeps when nothing is due (#4156)
Milind Sonif707ce0b1f41
diff --git a/scripts/bench-desktop.ts b/scripts/bench-desktop.tsindex 09b122bfac..3fc1346444 100644--- a/scripts/bench-desktop.ts+++ b/scripts/bench-desktop.ts@@ -5,7 +5,8 @@// [--chrome PATH] [--idle-seconds 30] [--bots 150] [--threads 300] [--messages 2000] [--advanced] [--out FILE] [--keep]// [--screenshots DIR]// bundle: the production build's first-load JavaScript and which libraries it pulls in eagerly.-// server: fixture server spawn to /api/health, from source and as the packaged bundle with its compile cache.+// server: fixture server spawn to /api/health, from source and as the packaged bundle with its compile cache; timer+// callbacks and CPU with no page open; child processes each engine-list read (a window focus) starts.// start: page load to the sidebar and the last chat drawn; JavaScript the page downloads.// idle: CPU, timer and frame callbacks, React commits and server work with nothing happening (and the rail's page).// stream: one long streamed reply with tool calls: commits, components rendered per commit, main-thread time per@@ -73,7 +74,7 @@ const STREAM_ENV = {FAKE_CLAUDE_TOOL_CALLS: JSON.stringify(TOOL_CALLS),};-interface Tally { cpu: { user: number; system: number }; memory: { rss: number; heapUsed: number }; fired: Record<string, number>; intervals: Record<string, number>; writes: Record<string, { bytes: number; calls: number }>; fsyncs: number; renames: number }+interface Tally { cpu: { user: number; system: number }; memory: { rss: number; heapUsed: number }; fired: Record<string, number>; intervals: Record<string, number>; writes: Record<string, { bytes: number; calls: number }>; fsyncs: number; renames: number; spawns: number }interface Fixture {url: string; dataDir: string; pid: number; readyMs: number; logPath: string;api(method: string, path: string, body?: unknown): Promise<{ status: number; ms: number; bytes: number; body: any }>;@@ -514,6 +515,24 @@ async function main() {await fixture.close();}const server: Record<string, unknown> = { sourceReadyMs: source, sourceRssMbAt3s: sourceRss };+ {+ log(`server alone: idle ${IDLE_MS / 1000}s, then engine-list reads`);+ const fixture = await startFixture();+ await sleep(10_000);+ const before = await fixture.tally();+ await sleep(IDLE_MS);+ const idle = tallyDelta(before, await fixture.tally());+ Object.assign(server, { idleTimerCallbacksPerSec: round(idle.timerCallbacks / (IDLE_MS / 1000), 2), idleCpuPct: round(idle.cpuMs / IDLE_MS * 100, 2), idleTimers: idle.fired });+ const spawns: number[] = [];+ for (let i = 0; i < 4; i++) {+ const at = (await fixture.tally()).spawns;+ await fixture.api("GET", "/api/instances");+ spawns.push((await fixture.tally()).spawns - at);+ await sleep(4_000);+ }+ server.instancesSpawnsPerRead = spawns;+ await fixture.close();+ }try {const entry = await bundleServer();const cache = join(work, "compile-cache");diff --git a/scripts/testing/bench-server-tally.mjs b/scripts/testing/bench-server-tally.mjsindex e6c89e9c9f..ac55d73332 100644--- a/scripts/testing/bench-server-tally.mjs+++ b/scripts/testing/bench-server-tally.mjs@@ -1,5 +1,6 @@// Loaded with --import into a fixture server that scripts/bench-desktop.ts starts, never into the app: it counts-// timer callbacks and file writes, and on SIGUSR2 writes the running totals, CPU and memory to $OMB_BENCH_TALLY.+// timer callbacks, child processes and file writes, and on SIGUSR2 writes the running totals, CPU and memory to $OMB_BENCH_TALLY.+import childProcess from "node:child_process";import fs from "node:fs";import module from "node:module";import { basename, dirname } from "node:path";@@ -14,6 +15,7 @@ const writes = new Map();const fdPaths = new Map();let fsyncs = 0;let renames = 0;+let spawns = 0;const fileKey = (path) => {const name = basename(String(path))@@ -43,7 +45,7 @@ const siteOf = () => {const wrapTimer = (original, kind) => function (callback, delay, ...args) {if (typeof callback !== "function") return original.call(this, callback, delay, ...args);const ms = Math.round(Number(delay) || 0);- const key = kind === "interval" ? `interval:${ms}:${siteOf()}` : `timeout:${ms < 1000 ? ms : `${Math.round(ms / 1000)}s`}`;+ const key = kind === "interval" ? `interval:${ms}:${siteOf()}` : ms < 1000 ? `timeout:${ms}` : `timeout:${Math.round(ms / 1000)}s:${siteOf()}`;if (kind === "interval") intervals.set(key, (intervals.get(key) ?? 0) + 1);return original.call(this, function (...inner) { countFire(key); return callback.apply(this, inner); }, delay, ...args);};@@ -73,6 +75,10 @@ for (const method of ["write", "writeFile", "appendFile"]) {const original = FileHandle[method];FileHandle[method] = function (data, ...rest) { const path = handlePaths.get(this); if (path) tallyWrite(path, data); return original.call(this, data, ...rest); };}+for (const name of ["spawn", "spawnSync", "execFile", "execFileSync", "exec", "execSync", "fork"]) {+ const original = childProcess[name];+ childProcess[name] = function (...args) { spawns += 1; return original.apply(this, args); };+}module.syncBuiltinESMExports();if (out) {@@ -86,6 +92,7 @@ if (out) {writes: Object.fromEntries(writes),fsyncs,renames,+ spawns,}));});}diff --git a/server/calendar-calls.ts b/server/calendar-calls.tsindex 9f8bfe7932..10119328e4 100644--- a/server/calendar-calls.ts+++ b/server/calendar-calls.ts@@ -5,6 +5,7 @@ import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";+import { startDueTimer, type DueTimer } from "./due-timer.ts";import { nextOccurrence } from "./routines.ts";export type CalendarCallSchedule =@@ -177,7 +178,7 @@ export class CalendarCallManager {private readonly botExists: CalendarCallManagerOptions["botExists"];private readonly onDue: CalendarCallManagerOptions["onDue"];private calls: CalendarCall[] = [];- private timer: ReturnType<typeof setInterval> | null = null;+ private timer: DueTimer | null = null;private ticking = false;constructor(options: CalendarCallManagerOptions) {@@ -321,13 +322,16 @@ export class CalendarCallManager {start(): void {if (this.timer) return;- void this.tick();- this.timer = setInterval(() => void this.tick(), 10_000);- this.timer.unref?.();+ this.timer = startDueTimer({+ run: () => this.tick(),+ next: () => this.calls.reduce<number | null>((at, call) => call.nextRunAt == null ? at : Math.min(at ?? Infinity, call.nextRunAt), null),+ now: this.now,+ onError: (error) => console.error("calendar calls: a scheduler pass failed", error),+ });}stop(): void {- if (this.timer) clearInterval(this.timer);+ this.timer?.stop();this.timer = null;}@@ -377,6 +381,7 @@ export class CalendarCallManager {this.calls = before;throw error;}+ this.timer?.poke();}private save(): void {diff --git a/server/cloud-credit.e2e.test.ts b/server/cloud-credit.e2e.test.tsindex 11742c31cb..b0afc30e4a 100644--- a/server/cloud-credit.e2e.test.ts+++ b/server/cloud-credit.e2e.test.ts@@ -178,7 +178,7 @@ type Instance = { instanceId: string; readOnly?: boolean; trialCredit?: string;type Message = { role: string; kind: string; tool?: { name: string; setup?: boolean; ok?: boolean } };type Bot = { id: string; name: string; busy?: boolean; modelSelection: { instanceId: string; model: string }; messages: Message[] };const SONNET = { instanceId: CLOUD_CREDIT_INSTANCE, model: "claude-sonnet-5" };-const instances = async () => (await api("GET", "/api/instances")).body.instances as Instance[];+const instances = async () => (await api("GET", "/api/instances?fresh=1")).body.instances as Instance[];const credit = async () => (await instances()).find((instance) => instance.instanceId === CLOUD_CREDIT_INSTANCE);const bots = async () => (await api("GET", "/api/bots?messages=20")).body.bots as Bot[];const named = async (name: string) => (await bots()).find((bot) => bot.name === name)!;diff --git a/server/coordinator.ts b/server/coordinator.tsindex de2f6c2c84..020e060d70 100644--- a/server/coordinator.ts+++ b/server/coordinator.ts@@ -193,6 +193,8 @@ export interface Coordinator {continuesAfterRestart(threadId: string): boolean;note(id: string): string | undefined;tick(): void;+ /** How soon the next tick() matters (Runtime.pace). */+ pace(): "busy" | "parked" | "idle";close(): void;progress(threadId: string): void;/** True when a parked assignment took the text as its answer: the host must not start an ordinary turn. */@@ -207,6 +209,8 @@ export interface CoordinatorOptions {runtimeLimits?: Partial<Limits>;log?: (line: string) => void;legacyThreads?: LegacyThreadResolver;+ /** After every write to the assignment store, so a host that ticks only when work is due can tick again. */+ wrote?: () => void;}export function createCoordinator(options: CoordinatorOptions): Coordinator {diff --git a/server/due-timer.test.ts b/server/due-timer.test.tsnew file mode 100644index 0000000000..713b338fcc--- /dev/null+++ b/server/due-timer.test.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { DUE_CLOCK_MS, startDueTimer } from "./due-timer.ts";++describe("startDueTimer", () => {+ beforeEach(() => { vi.useFakeTimers(); });+ afterEach(() => { vi.useRealTimers(); });++ it("runs once at start, then only at the next due time, however far off", async () => {+ const runs: number[] = [];+ let due: number | null = Date.now() + 90 * 60_000;+ const timer = startDueTimer({ run: () => { runs.push(Date.now()); if (Date.now() >= due!) due = null; }, next: () => due });+ const start = Date.now();+ await vi.advanceTimersByTimeAsync(90 * 60_000 - 1);+ expect(runs).toEqual([start]);+ await vi.advanceTimersByTimeAsync(1);+ expect(runs.map((at) => at - start)).toEqual([0, 90 * 60_000]);+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ expect(runs).toHaveLength(2);+ timer.stop();+ });++ it("with many timers and nothing due, wakes once a minute in all and runs nothing", async () => {+ const run = vi.fn();+ const before = vi.getTimerCount();+ const timers = [1, 2, 3, 4].map(() => startDueTimer({ run, next: () => null }));+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ expect(run).toHaveBeenCalledTimes(4);+ expect(vi.getTimerCount() - before).toBe(1);+ for (const timer of timers) timer.stop();+ expect(vi.getTimerCount() - before).toBe(0);+ });++ it("finds work on the wall clock when no timer could have told it: a change it was not told of, or time lost to sleep", async () => {+ const runs: number[] = [];+ let due: number | null = null;+ const timer = startDueTimer({ run: () => { runs.push(Date.now()); due = null; }, next: () => due });+ await vi.advanceTimersByTimeAsync(0);+ due = Date.now();+ await vi.advanceTimersByTimeAsync(DUE_CLOCK_MS - 1);+ expect(runs).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(2);+ expect(runs).toHaveLength(2);+ timer.stop();+ });++ it("brings the run forward when a change makes work due sooner, and never pushes a nearer run back", async () => {+ const runs: number[] = [];+ let due: number | null = null;+ const timer = startDueTimer({ run: () => { runs.push(Date.now()); due = null; }, next: () => due });+ const start = Date.now();+ await vi.advanceTimersByTimeAsync(0);+ due = start + 5_000;+ timer.poke();+ await vi.advanceTimersByTimeAsync(5_000);+ expect(runs.map((at) => at - start)).toEqual([0, 5_000]);+ due = Date.now();+ timer.poke();+ await vi.advanceTimersByTimeAsync(0);+ expect(runs.map((at) => at - start)).toEqual([0, 5_000, 5_000]);+ timer.stop();+ });++ it("retries work still due after a run (waiting on something outside) every retryMs, not in a tight loop", async () => {+ const run = vi.fn();+ const timer = startDueTimer({ run, next: () => Date.now() - 1, retryMs: 5_000 });+ await vi.advanceTimersByTimeAsync(20_000);+ expect(run).toHaveBeenCalledTimes(1 + 4);+ timer.stop();+ });++ it("runs again straight after a run that a change interrupted with work due now", async () => {+ let release!: () => void;+ const calls: number[] = [];+ let due: number | null = null;+ const timer = startDueTimer({+ run: () => { calls.push(Date.now()); if (calls.length === 2) return new Promise<void>((resolve) => { release = resolve; }); due = null; },+ next: () => due,+ });+ await vi.advanceTimersByTimeAsync(0);+ due = Date.now();+ timer.poke();+ await vi.advanceTimersByTimeAsync(0);+ expect(calls).toHaveLength(2);+ timer.poke();+ release();+ await vi.advanceTimersByTimeAsync(0);+ expect(calls).toHaveLength(3);+ timer.stop();+ });+});diff --git a/server/due-timer.ts b/server/due-timer.tsnew file mode 100644index 0000000000..9a489e6331--- /dev/null+++ b/server/due-timer.ts@@ -0,0 +1,103 @@+/** Runs `run` when `next()` says work is due, with no fixed polling. `poke()` after any change that may bring work sooner.+ * A time already past after a run means work is waiting on something outside (a busy bot, a refused start): it is+ * retried every `retryMs`. */+export interface DueTimer {+ poke(): void;+ stop(): void;+}++export interface DueTimerOptions {+ run(): Promise<void> | void;+ /** The earliest time anything is due, null when nothing is. */+ next(): number | null;+ now?: () => number;+ retryMs?: number;+ onError?(error: unknown): void;+}++/** Node's timers stop while macOS sleeps (libuv's monotonic clock), so a timer set for a far time would fire late after a+ * wake. Every due timer looks at the wall clock this often, on one shared interval, and only sets a timer for work due+ * within this time. */+export const DUE_CLOCK_MS = 60_000;++const watchers = new Set<() => void>();+let clock: ReturnType<typeof setInterval> | null = null;++function watchClock(look: () => void): () => void {+ watchers.add(look);+ clock ??= setInterval(() => { for (const watcher of watchers) watcher(); }, DUE_CLOCK_MS);+ clock.unref?.();+ return () => {+ watchers.delete(look);+ if (watchers.size === 0 && clock) {+ clearInterval(clock);+ clock = null;+ }+ };+}++/** Node looks for timed-out connections on every HTTP server every 30 s by default; a minute is enough for requests whose+ * limits are minutes. */+export const IDLE_HTTP_SERVER = { connectionsCheckingInterval: DUE_CLOCK_MS };++export function startDueTimer(options: DueTimerOptions): DueTimer {+ const now = options.now ?? Date.now;+ const retryMs = options.retryMs ?? 10_000;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let firesAt = Infinity;+ let running = false;+ let pokedWhileRunning = false;+ let stopped = false;++ const disarm = () => {+ if (timer) clearTimeout(timer);+ timer = null;+ firesAt = Infinity;+ };+ const arm = (delay: number) => {+ disarm();+ firesAt = now() + delay;+ timer = setTimeout(fire, delay);+ timer.unref?.();+ };+ const dueIn = (): number | null => {+ const at = options.next();+ return at === null ? null : Math.max(0, at - now());+ };+ const poke = () => {+ if (stopped) return;+ if (running) { pokedWhileRunning = true; return; }+ const wait = dueIn();+ if (wait !== null && wait <= DUE_CLOCK_MS && now() + wait < firesAt) arm(wait);+ };+ const fire = () => {+ disarm();+ if (stopped) return;+ running = true;+ pokedWhileRunning = false;+ let done: Promise<void> | void;+ try {+ done = options.run();+ } catch (error) {+ done = Promise.reject(error);+ }+ void Promise.resolve(done).catch((error) => options.onError?.(error)).finally(() => {+ running = false;+ if (stopped) return;+ const wait = dueIn();+ if (wait === 0) arm(pokedWhileRunning ? 0 : retryMs);+ else if (wait !== null && wait <= DUE_CLOCK_MS) arm(wait);+ });+ };++ const unwatch = watchClock(poke);+ fire();+ return {+ poke,+ stop() {+ stopped = true;+ unwatch();+ disarm();+ },+ };+}diff --git a/server/handoff-ticks.test.ts b/server/handoff-ticks.test.tsnew file mode 100644index 0000000000..b59e075820--- /dev/null+++ b/server/handoff-ticks.test.ts@@ -0,0 +1,61 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { createHandoffTicks, HANDOFF_TICK_MS, type HandoffPace } from "./handoff-ticks.ts";++describe("hand-off ticks", () => {+ beforeEach(() => { vi.useFakeTimers(); });+ afterEach(() => { vi.useRealTimers(); });++ it("ticks every 250 ms only while work is moving, rarely while it is parked, and hourly with none", async () => {+ let pace: HandoffPace = "busy";+ const tick = vi.fn();+ const ticks = createHandoffTicks();+ ticks.start({ tick, pace: () => pace });+ await vi.advanceTimersByTimeAsync(1_000);+ expect(tick).toHaveBeenCalledTimes(4);+ pace = "parked";+ await vi.advanceTimersByTimeAsync(250 + 60_000);+ expect(tick).toHaveBeenCalledTimes(5 + 6);+ pace = "idle";+ tick.mockClear();+ await vi.advanceTimersByTimeAsync(HANDOFF_TICK_MS.parked + 3 * 60 * 60_000);+ expect(tick).toHaveBeenCalledTimes(1 + 3);+ ticks.stop();+ });++ it("ticks at once when a write lands while idle, and a kick during busy ticks keeps the 250 ms pace", async () => {+ let pace: HandoffPace = "idle";+ const tick = vi.fn();+ const ticks = createHandoffTicks();+ ticks.kick();+ ticks.start({ tick, pace: () => pace });+ await vi.advanceTimersByTimeAsync(250);+ expect(tick).toHaveBeenCalledTimes(1);+ pace = "busy";+ ticks.kick();+ ticks.kick();+ await vi.advanceTimersByTimeAsync(0);+ expect(tick).toHaveBeenCalledTimes(2);+ ticks.kick();+ await vi.advanceTimersByTimeAsync(249);+ expect(tick).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1);+ expect(tick).toHaveBeenCalledTimes(3);+ ticks.stop();+ ticks.kick();+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ expect(tick).toHaveBeenCalledTimes(3);+ });++ it("keeps ticking after a tick throws", async () => {+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ const tick = vi.fn(() => { throw new Error("boom"); });+ const ticks = createHandoffTicks();+ ticks.start({ tick, pace: () => "idle" });+ await vi.advanceTimersByTimeAsync(750);+ expect(tick).toHaveBeenCalledTimes(3);+ expect(errors).toHaveBeenCalled();+ ticks.stop();+ errors.mockRestore();+ });+});diff --git a/server/handoff-ticks.ts b/server/handoff-ticks.tsnew file mode 100644index 0000000000..976b6a6ad9--- /dev/null+++ b/server/handoff-ticks.ts@@ -0,0 +1,59 @@+export type HandoffPace = "busy" | "parked" | "idle";++/** Busy keeps the hand-off latency people see; parked work only needs its access and time limits rechecked; idle wakes+ * for the daily prune alone. */+export const HANDOFF_TICK_MS: Record<HandoffPace, number> = { busy: 250, parked: 10_000, idle: 60 * 60_000 };++export interface HandoffTicks {+ /** A write that may have made work due: tick now unless a tick is already near. No-op before start(). */+ kick(): void;+ start(options: { tick(): void; pace(): HandoffPace }): void;+ stop(): void;+}++export function createHandoffTicks(): HandoffTicks {+ let options: { tick(): void; pace(): HandoffPace } | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let firesAt = Infinity;+ let ticking = false;++ const arm = (delay: number) => {+ if (timer) clearTimeout(timer);+ firesAt = Date.now() + delay;+ timer = setTimeout(fire, delay);+ timer.unref();+ };+ const fire = () => {+ timer = null;+ firesAt = Infinity;+ if (!options) return;+ ticking = true;+ let pace: HandoffPace = "busy";+ try {+ options.tick();+ pace = options.pace();+ } catch (error) {+ console.error("coordinator:", error);+ } finally {+ ticking = false;+ }+ if (options) arm(HANDOFF_TICK_MS[pace]);+ };++ return {+ kick() {+ if (!options || ticking || firesAt - Date.now() <= HANDOFF_TICK_MS.busy) return;+ arm(0);+ },+ start(next) {+ options = next;+ arm(HANDOFF_TICK_MS.busy);+ },+ stop() {+ options = null;+ if (timer) clearTimeout(timer);+ timer = null;+ firesAt = Infinity;+ },+ };+}diff --git a/server/harness/registry.test.ts b/server/harness/registry.test.tsindex a9d53e7b4c..45346dfa12 100644--- a/server/harness/registry.test.ts+++ b/server/harness/registry.test.ts@@ -10,7 +10,7 @@ import { standalonePlatformKey } from "../engine-standalone.ts";import { findCliCandidates, registerFallbackPathDir, registerPathDir, resetPathCache, resetPathCacheForTests } from "../env-path.ts";import { removeTempDir } from "../testing/cleanup.ts";import { makeFakeDriver } from "../testing/fake-driver.ts";-import { ProviderRegistry, SNAPSHOT_DEADLINE_MS, SNAPSHOT_REUSE_MS } from "./registry.ts";+import { ENGINE_LIST_REUSE_MS, ProviderRegistry, SNAPSHOT_DEADLINE_MS, SNAPSHOT_REUSE_MS } from "./registry.ts";describe("ProviderRegistry", () => {it("creates live instances for known drivers", async () => {@@ -400,6 +400,40 @@ describe("ProviderRegistry", () => {expect(fake.probes).toHaveLength(4);});+ it("answers the engine list from earlier reads, reads again in the background once they are old, and never after forgetSnapshots() or a reload", async () => {+ vi.useFakeTimers();+ try {+ const options: Parameters<typeof makeFakeDriver>[0] = {};+ const fake = makeFakeDriver(options);+ const registry = new ProviderRegistry([fake.driver]);+ await registry.load({ a: { driver: "fake" } });+ const reuse = { ms: ENGINE_LIST_REUSE_MS, changed: vi.fn() };+ await registry.describe({ reuse });+ await vi.advanceTimersByTimeAsync(ENGINE_LIST_REUSE_MS - 1);+ await registry.describe({ reuse });+ expect(fake.probes).toEqual(["a"]);++ options.answer = { state: "unavailable", reason: "signed out" };+ await vi.advanceTimersByTimeAsync(1);+ expect((await registry.describe({ reuse }))[0].snapshot).toEqual({ state: "available", version: "0.0.0-fake" });+ await vi.advanceTimersByTimeAsync(0);+ expect(fake.probes).toEqual(["a", "a"]);+ expect(reuse.changed).toHaveBeenCalledTimes(1);+ expect((await registry.describe({ reuse }))[0].snapshot).toEqual({ state: "unavailable", reason: "signed out" });+ expect(fake.probes).toHaveLength(2);++ registry.forgetSnapshots();+ await registry.describe({ reuse });+ expect(fake.probes).toHaveLength(3);+ await registry.load({ a: { driver: "fake", displayName: "Renamed" } });+ await registry.describe({ reuse });+ expect(fake.probes).toHaveLength(4);+ expect(reuse.changed).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+it("runs a decorator's own check on every read, and probes again after an install, a model refresh or a reload", async () => {const fake = makeFakeDriver();const registry = new ProviderRegistry([fake.driver]);diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex 4b47f52906..ad664f0cc8 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -65,6 +65,8 @@ function cliOfRaw(raw: unknown): string | undefined {export const SNAPSHOT_DEADLINE_MS = 60_000;/** How long a finished status read answers later reads, so a start-up's model lists and engine-list reads probe each CLI once. */export const SNAPSHOT_REUSE_MS = 3_000;+/** How long the engine list people see answers from earlier reads before one is read again in the background. */+export const ENGINE_LIST_REUSE_MS = 60_000;const SNAPSHOT_DEADLINE_REASON = "This engine did not report its status within a minute. Check that its CLI starts in a terminal.";function withinDeadline(read: () => Promise<ProviderSnapshot>): Promise<ProviderSnapshot> {@@ -107,6 +109,8 @@ export class ProviderRegistry {/** Engines the start-up read has not probed yet; null outside that read. */private unread: Set<InstanceId> | null = null;private snapshotGeneration = 0;+ /** Per instance object: settings that reload an engine make a new one, so its status is read afresh. */+ private readsOf = new WeakMap<ProviderInstance, { snapshot: ProviderSnapshot; at: number; generation: number }>();private driversByKind: Map<string, AnyProviderDriver>;private readonly enginesBaseDir: string | undefined;private readonly npmPresent: () => boolean;@@ -395,17 +399,28 @@ export class ProviderRegistry {return isAppStandaloneCopy(cli, this.enginesBaseDir, standaloneLookupPath(this.enginesBaseDir));}- describe(options: { known?: boolean } = {}) {+ /** `reuse`: answer from a status read since the last forgetSnapshots(); one older than `ms` is read again in the background+ * and `changed` runs when that read differs. */+ describe(options: { known?: boolean; reuse?: { ms: number; changed(): void } } = {}) {return this.describeWith((instance) => {const seed = options.known && this.unread?.has(instance.instanceId) ? this.seeds.get(instance.instanceId) : undefined;- return seed ? Promise.resolve(seed) : this.read(instance);+ if (seed) return Promise.resolve(seed);+ const last = options.reuse && this.readsOf.get(instance);+ if (!options.reuse || !last || last.generation !== this.snapshotGeneration) return this.read(instance);+ if (Date.now() - last.at >= options.reuse.ms) {+ const { changed } = options.reuse;+ void this.read(instance).then((snapshot) => { if (JSON.stringify(snapshot) !== JSON.stringify(last.snapshot)) changed(); });+ }+ return Promise.resolve(last.snapshot);});}private async read(instance: ProviderInstance): Promise<ProviderSnapshot> {let snapshot: ProviderSnapshot;+ const generation = this.snapshotGeneration;try {snapshot = await instance.snapshot();+ this.readsOf.set(instance, { snapshot, at: Date.now(), generation });} catch (e) {snapshot = { state: "unavailable", reason: e instanceof Error ? e.message : String(e) };}diff --git a/server/host/devs-reports.ts b/server/host/devs-reports.tsindex 002889a453..d1eacbdd0e 100644--- a/server/host/devs-reports.ts+++ b/server/host/devs-reports.ts@@ -21,6 +21,7 @@ import { versionAtLeast, type BugReportStatus } from "../../shared/devs-report-simport { failedTurnCause } from "../../shared/failed-turn.ts";import type { ResolvedSender } from "../../shared/wire.ts";import { writeFileAtomic } from "../atomic.ts";+import { startDueTimer } from "../due-timer.ts";import type { ProviderSnapshot } from "../contracts.ts";import { buildDevsReport, contactAddress, environmentSecrets, redactReportText, type BotSummary, type DevsReportPayload, type ReportedBot } from "../devs-report.ts";import { BUG_REPORT_STATUS_MAX_IDS, type ReportStatusAnswer, type ReportStatusQuestion, type SendOutcome } from "../devs-report-send.ts";@@ -350,6 +351,7 @@ export function createDevsReports(deps: DevsReportsDeps) {if (outbox.length >= MAX_OUTBOX) return { ok: false, line: fullLine(language), marker: FAILED_MARKER };outbox.push({ messageId: entry.messageId, threadId: entry.threadId, payload, firstAt: now(), attempts: 1,nextAt: now() + (outcome.retryAfterMs ?? RETRY_MS[0]), ...(person ? { person } : {}) });+ timer?.poke();return { ok: false, line: notYetLine(outcome, language), marker: FAILED_MARKER };}@@ -440,6 +442,7 @@ export function createDevsReports(deps: DevsReportsDeps) {const fallingBack = inFlight.has(entry.messageId);const said = await deliver(entry, { bot, summary });if (!fallingBack) told.push({ threadId, messageId: entry.messageId, said, until: now() + LONGEST_WAIT_MS });+ timer?.poke();return { status: 200, text: `${said.ok ? "Sent" : "Not sent"}. Tell the person this line in your reply, word for word: "${said.line}"` };}@@ -454,6 +457,7 @@ export function createDevsReports(deps: DevsReportsDeps) {waiting.push({ messageId: line.id, threadId, at: line.at, text: redact(line.text), words: redact(withoutDevsTags(line.text, botNames())),...(line.sender ? { sender: { name: line.sender.name, ...(line.sender.id ? { id: line.sender.id } : {}) } } : {}) });save();+ timer?.poke();}const unsubscribe = store.onChange((change: StoreChange) => {@@ -467,8 +471,9 @@ export function createDevsReports(deps: DevsReportsDeps) {if (waiting.length + tracked.length !== before) save();}});- const timer = deps.timer === false ? null : setInterval(tick, TICK_MS);- timer?.unref();+ // A waiting @devs line polls whether its turn is still running; otherwise nothing is due before a retry or a status ask.+ const timer = deps.timer === false ? null : startDueTimer({ run: tick, now, retryMs: TICK_MS,+ next: () => waiting.length || told.length ? now() : Math.min(nextAskAt, ...outbox.map((queued) => queued.nextAt)) });return {/** The note on a turn in this conversation while a @devs message waits for its summary (none for a turn without@@ -506,7 +511,7 @@ export function createDevsReports(deps: DevsReportsDeps) {idle: async () => {while (inFlight.size || retrying.size || asking) await Promise.allSettled([...inFlight.values(), asking]).then(() => new Promise((resolve) => setImmediate(resolve)));},- stop() { unsubscribe(); if (timer) clearInterval(timer); },+ stop() { unsubscribe(); timer?.stop(); },};}diff --git a/server/index.ts b/server/index.tsindex 89ed47e333..4835992fe5 100644--- a/server/index.ts+++ b/server/index.ts@@ -240,6 +240,7 @@ import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine }import { chiefEscalationsEnabled, NEEDS_INPUT_GATE, peerApprovalGate, RAISED_GATE } from "./escalations.ts";import { createChiefNotices } from "./host/chief-notices.ts";import { needsInputQuestion } from "./runtime-coordinator.ts";+import { createHandoffTicks } from "./handoff-ticks.ts"; import { IDLE_HTTP_SERVER } from "./due-timer.ts";const SESSION_READ_MAX_CHARS = 8_000;import { personOf, promptWithReply, replyTargetIn, speakerOf, transcriptText, type PersonName, type ReplyTarget } from "./replies.ts";@@ -268,7 +269,7 @@ import {SendSequencer,} from "./send-idempotency.ts";import { EventBus } from "./harness/bus.ts";-import { engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts";+import { ENGINE_LIST_REUSE_MS, engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts";import { ManagedDesktopProviders } from "./managed-desktop.ts";import { mainThread, wasOldestThread } from "./main-thread.ts";import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts"; import { nudgeCloudTeamPolicy, remoteAccessPaths, startCloudTeamPolicy, stopCloudTeamPolicy } from "./cloud-team-policy.ts";@@ -1550,7 +1551,7 @@ bus.attach(registry.instances()); bus.subscribe((event) => savedSteps.observe(evlet companyRuntimeReady!: () => void;const companyRuntimeStarted = new Promise<void>(resolve => { companyRuntimeReady = resolve; });const managedPolicy = new ManagedDesktopPolicy({ onChange: () => {- broadcast({ kind: "config", ...configStatus() });+ registry.forgetSnapshots(); broadcast({ kind: "config", ...configStatus() });resyncOpenCodeProviderKeys();} });onKeyRejectionChange(() => { registry.forgetSnapshots(); broadcast({ kind: "config", ...configStatus() }); });@@ -1570,7 +1571,7 @@ const managedDesktop = new ManagedDesktopProviders({beforeReplace: stopCompanyInstances,migrate: aliases => { store.renameInstances(new Map(aliases.map(({ from, to }) => [from, to]))); },onAvailability: () => {- broadcast({ kind: "config", ...configStatus() });+ registry.forgetSnapshots(); broadcast({ kind: "config", ...configStatus() });resyncOpenCodeProviderKeys();},afterReplace: ids => {@@ -1583,7 +1584,7 @@ const managedDesktop = new ManagedDesktopProviders({const cloudCredit = CLOUD_HOME ? new CloudCreditProvider({registry, dataDirectory: DATA_DIR, credential: trialCreditCredential(),onChange: ids => {- bus.attach(ids.flatMap(id => { const instance = registry.get(id); return instance ? [instance] : []; }));+ registry.forgetSnapshots(); bus.attach(ids.flatMap(id => { const instance = registry.get(id); return instance ? [instance] : []; }));void companyRuntimeStarted.then(() => { broadcast({ kind: "config", ...configStatus() }); return refreshUnsetModelSelections(); }).catch(() => {});},onDefault: (from, to) => void companyRuntimeStarted.then(() => creditMoves?.followDefault(from, to)),@@ -3950,9 +3951,9 @@ const questionRouting = createQuestionRouting({ store, active: () => coordinatoranswerLive: async (threadId, requestId, text) => await answerRequest(threadId, botForThread(store.botByThread(threadId)?.id ?? "", threadId)?.modelSelection.instanceId ?? "", requestId, "answer", text) === "answered", settleSignIns: (node) => signInSettle.answeredElsewhere(node),keptPrivate: (node, requester) => keptPrivate({ child: teamHost.privateTo(node.threadId), parent: teamHost.privateTo(requester.threadId) }),steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused" });-const coordinator: Coordinator = createCoordinator({+const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR,- now: Date.now,+ now: Date.now, wrote: handoffTicks.kick,log: line => console.error("coordinator:", line),legacyThreads: {standingThreadOf: botId => botMainThread(botId) ?? store.bot(botId)?.threadId,@@ -9670,7 +9671,7 @@ ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visibconst RUNTIME_KEEP_MS = 30 * 24 * 60 * 60_000;let runtimePrunedAt = 0;-const roomHandoffTimer = setInterval(() => {+handoffTicks.start({ pace: () => enginesRead || parkedNodesToReconcile.size > 0 ? "busy" : coordinator.pace(), tick: () => {// Recovered reports must see the engine's resume capability before deciding to keep its stored session.if (enginesRead) return;try {@@ -9689,8 +9690,7 @@ const roomHandoffTimer = setInterval(() => {}coordinator.tick();} catch (error) { console.error("coordinator:", error); }-}, 250);-roomHandoffTimer.unref();+} });function reconcileParkedRoots(): void {for (const node of coordinator.active()) reconcileParkedNode(node);@@ -11990,7 +11990,7 @@ function persistMcpServers(next: Record<string, unknown>): void {async function describeInstances() {const configs = providerConfigs();void retryComputerEngineMove();- const read = testedAi.read(), engines = selectableInstances(await registry.describe({ known: true }));+ const read = testedAi.read(), engines = selectableInstances(await registry.describe({ known: true, reuse: { ms: ENGINE_LIST_REUSE_MS, changed: () => broadcast({ kind: "config", ...configStatus() }) } }));await refreshUnsetModelSelections(engines, read);const ownReady = cloudCredit !== null && engines.some(instance => !selectionContext.company(instance.instanceId) && readyToRun(instance, selectionContext));return engines.map((instance) => {@@ -15573,7 +15573,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}};-const server = createServer(handleRequest);+const server = createServer(IDLE_HTTP_SERVER, handleRequest);upgrades.attach(server, handleRequest);moveFreeze.hold(() => calendarCalls.start(), () => calendarCalls.stop());@@ -15673,7 +15673,7 @@ const TUNNEL_SOCKET = process.env.OMB_TUNNEL_SOCKET?.trim() || null;let tunnelListener: ReturnType<typeof createServer> | null = null;if (TUNNEL_SOCKET) {if (process.platform !== "win32") rmSync(TUNNEL_SOCKET, { force: true });- tunnelListener = createServer(gzipTunnelReplies(handleRequest));+ tunnelListener = createServer(IDLE_HTTP_SERVER, gzipTunnelReplies(handleRequest));upgrades.attach(tunnelListener, handleRequest);tunnelListener.listen(TUNNEL_SOCKET, () => {console.log(`openmausbot tunnel listener on ${TUNNEL_SOCKET}`);diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.tsindex 6fc9a52f27..abe7b27761 100644--- a/server/routes/instances.test.ts+++ b/server/routes/instances.test.ts@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";import type { AppConfig } from "../config.ts";import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";-import { ProviderRegistry } from "../harness/registry.ts";+import { ENGINE_LIST_REUSE_MS, ProviderRegistry } from "../harness/registry.ts";import { json, readBody } from "../harness/http.ts";import { ProviderAuthSessions } from "../provider-auth-sessions.ts";import { makeFakeDriver } from "../testing/fake-driver.ts";@@ -41,7 +41,7 @@ async function serve(extra: Partial<InstanceRouteDeps> = {}) {hostedModels: false,providerConfigBusy: { get: () => false, set: () => {} },providerInstancesChanging: new Set<string>(),- describeInstances: () => registry.describe(),+ describeInstances: () => registry.describe({ reuse: { ms: ENGINE_LIST_REUSE_MS, changed: () => {} } }),threadBusy: () => false,botForThread: () => null,activeGroupTurnForBot: () => null,@@ -70,7 +70,7 @@ async function serve(extra: Partial<InstanceRouteDeps> = {}) {await call("GET", "/api/instances");return fake.probes.length;};- return { sign, call, probesAfterList, base };+ return { sign, call, probesAfterList, base, fake };}describe("engine sign-in routes", () => {@@ -103,6 +103,17 @@ describe("engine sign-in routes", () => {});});+describe("the engine list", () => {+ it("answers again from the last status read, and reads every engine again when asked for fresh", async () => {+ const { call, probesAfterList, fake } = await serve();+ expect(await probesAfterList()).toBe(1);+ expect(await probesAfterList()).toBe(1);+ await call("GET", "/api/instances?fresh=1");+ expect(fake.probes).toHaveLength(2);+ expect(await probesAfterList()).toBe(2);+ });+});+describe("an engine's check", () => {it("goes through the server's tested-AI record, so the welcome's test also settles the new-bot default", async () => {const asked: string[] = [];diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex 95def43450..6c0824251e 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -83,6 +83,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {if (method === "GET" && path === "/api/instances") {// Rescan PATH: Windows never pushes PATH changes into a live process, so a CLI installed since launch stays invisible.resetPathCache();+ if (url.searchParams.get("fresh") === "1") registry.forgetSnapshots();return json(res, 200, { instances: await describeInstances() });}const companyMutation = /^\/api\/instances\/(company\.[\w.-]+)(?:\/|$)/.exec(path);diff --git a/server/routine-due.test.ts b/server/routine-due.test.tsindex 6862f4d643..684f491b3e 100644--- a/server/routine-due.test.ts+++ b/server/routine-due.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { CHECK_WAKE_MS, nextDueOf, wakeHoldOf } from "./routine-due.ts";+import { CHECK_WAKE_MS, nextDueOf, schedulerDueOf, wakeHoldOf } from "./routine-due.ts";const MINUTE = 60_000;const NOW = Date.UTC(2026, 9, 24, 9, 0);@@ -51,3 +51,33 @@ describe("wakeHoldOf: the desktop", () => {expect(wakeHoldOf([watch({ checkedAt: NOW, wakeAt: NOW + 25 * MINUTE })], [], NOW, horizon)).toEqual({ hold: true, reason: "due", at: NOW + 25 * MINUTE });});});++describe("schedulerDueOf: when this process's scheduler next has work", () => {+ type Run = Parameters<typeof schedulerDueOf>[1][number];+ const run = (fields: Partial<Run>) => ({ status: "running", ...fields }) as Run;++ it("is null with nothing enabled, queued or limited", () => {+ expect(schedulerDueOf([], [], NOW, NOW)).toBeNull();+ expect(schedulerDueOf([{ enabled: false, nextRunAt: NOW }], [run({ status: "completed" }), run({ startedAt: NOW })], NOW, NOW)).toBeNull();+ });++ it("the next run, a check no sooner than checks may start, and a check's meeting wake", () => {+ expect(schedulerDueOf([{ enabled: true, nextRunAt: NOW + 5 * MINUTE }, { enabled: true, nextRunAt: NOW + 3 * MINUTE }], [], NOW, NOW)).toBe(NOW + 3 * MINUTE);+ expect(schedulerDueOf([watch({ nextRunAt: NOW - MINUTE })], [], NOW, NOW + 2 * MINUTE)).toBe(NOW + 2 * MINUTE);+ expect(schedulerDueOf([watch({ wakeAt: NOW + MINUTE })], [], NOW, NOW)).toBe(NOW + MINUTE);+ expect(schedulerDueOf([{ enabled: true, nextRunAt: null, wakeAt: NOW + MINUTE }], [], NOW, NOW)).toBeNull();+ });++ it("leaves out routines whose target is gone", () => {+ const gone = { enabled: true, nextRunAt: NOW - MINUTE, botId: "gone" };+ expect(schedulerDueOf([gone, { enabled: true, nextRunAt: NOW + MINUTE, botId: "here" }], [], NOW, NOW, (routine) => routine.botId === "gone")).toBe(NOW + MINUTE);+ });++ it("a queued run now or at its retry, and a started run when its active time reaches the limit", () => {+ expect(schedulerDueOf([], [run({ status: "queued" })], NOW, NOW)).toBe(NOW);+ expect(schedulerDueOf([], [run({ status: "queued", retryAt: NOW + MINUTE })], NOW, NOW)).toBe(NOW + MINUTE);+ expect(schedulerDueOf([], [run({ startedAt: NOW - 10 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW + 20 * MINUTE);+ expect(schedulerDueOf([], [run({ status: "waiting", startedAt: NOW - 10 * MINUTE, waitedMs: 5 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW + 25 * MINUTE);+ expect(schedulerDueOf([], [run({ startedAt: NOW - 40 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW);+ });+});diff --git a/server/routine-due.ts b/server/routine-due.tsindex 9f7de220d4..4f9d08df17 100644--- a/server/routine-due.ts+++ b/server/routine-due.ts@@ -1,6 +1,7 @@// When routines next need this machine: the desktop's keep-awake (`wakeHold`) and a Cloud home's sleep check// (server/cloud-power.ts). Pure over RoutineManager's routines and runs.import type { Routine, RoutineRun } from "./routines.ts";+import { activeMs } from "./routine-waits.ts";type Due = Pick<Routine, "enabled" | "nextRunAt" | "checks" | "wakeAt" | "checkedAt">;type Run = Pick<RoutineRun, "status" | "retryAt">;@@ -40,3 +41,22 @@ export function nextDueOf(routines: readonly Due[], runs: readonly Run[], now: nconst due = dueTimes(routines, runs, now, cloudChecksDue(now));return due.length ? Math.min(...due) : null;}++type Started = Run & Pick<RoutineRun, "startedAt" | "timeoutMinutes" | "waitedMs" | "asked">;+/** When this process's scheduler next has work: a routine's next run, or its checks once `checksFrom` has passed; a queued+ * run (now, or its retry); a started run reaching its time limit. `skip` leaves out routines whose target is gone. */+export function schedulerDueOf<R extends Due>(routines: readonly R[], runs: readonly Started[], now: number, checksFrom: number, skip: (routine: R) => boolean = () => false): number | null {+ let at = Infinity;+ for (const routine of routines) {+ if (!routine.enabled || skip(routine)) continue;+ const next = Math.min(routine.nextRunAt ?? Infinity, routine.checks ? routine.wakeAt ?? Infinity : Infinity);+ if (next !== Infinity) at = Math.min(at, routine.checks ? Math.max(next, checksFrom) : next);+ }+ for (const run of runs) {+ if (run.status === "queued") at = Math.min(at, run.retryAt ?? now);+ else if ((run.status === "running" || run.status === "waiting") && run.startedAt != null && run.timeoutMinutes != null) {+ at = Math.min(at, now + Math.max(0, run.timeoutMinutes * 60_000 - activeMs(run, now)));+ }+ }+ return at === Infinity ? null : at;+}diff --git a/server/routine-waits.ts b/server/routine-waits.tsindex 8da8c0831d..cc1d51cbf6 100644--- a/server/routine-waits.ts+++ b/server/routine-waits.ts@@ -57,6 +57,6 @@ export function settleAsk(run: RoutineRun, event: Resolved | undefined, now: num}/** Time the run has worked: waiting on the person never counts toward its limit. */-export function activeMs(run: RoutineRun, now: number): number {+export function activeMs(run: Pick<RoutineRun, "startedAt" | "waitedMs" | "asked">, now: number): number {return now - (run.startedAt ?? now) - (run.waitedMs ?? 0) - (run.asked ? Math.max(0, now - run.asked.since) : 0);}diff --git a/server/routines.test.ts b/server/routines.test.tsindex 23eea4df82..6d06696988 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -3976,3 +3976,28 @@ describe("runs that report into a chat", () => {expect(h.manager.handleRuntimeEvent(event("thread-1", "turn.completed"))).toMatchObject({ id: run.id, status: "completed" });});});++describe("the scheduler wakes only when work is due", () => {+ it("sleeps with nothing due, runs a new routine on its time and stops the run at its limit", async () => {+ vi.useFakeTimers({ now: Date.parse("2026-09-13T08:00:00Z") });+ try {+ const h = harness();+ const manager = new RoutineManager({ ...h.options, now: () => Date.now() });+ const ticks = vi.spyOn(manager, "tick");+ manager.start();+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(ticks).toHaveBeenCalledTimes(1);+ manager.create({ name: "Soon", prompt: "Do it", botId: "maus-1", timeoutMinutes: 5, schedule: { type: "once", at: Date.now() + 30_000 } });+ await vi.advanceTimersByTimeAsync(29_999);+ expect(h.started).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(1);+ expect(h.started).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(h.interruptedTurns).toHaveLength(1);+ expect(manager.listRuns()[0]).toMatchObject({ status: "failed" });+ manager.stop();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/server/routines.ts b/server/routines.tsindex 3475e17297..80507dc1e1 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -6,7 +6,8 @@ import { DATA_DIR } from "./config.ts";import type { RuntimeEvent } from "./contracts.ts";import { writeFileAtomic } from "./atomic.ts";import { redactSecretsInText } from "./redact.ts";-import { activeRunsOf, nextDueOf, wakeHoldOf } from "./routine-due.ts";+import { activeRunsOf, nextDueOf, schedulerDueOf, wakeHoldOf } from "./routine-due.ts";+import { startDueTimer, type DueTimer } from "./due-timer.ts";import type { GroupGoalRunStatus } from "../shared/group-goal-run.ts";import type { RoutineRequestOperation } from "../shared/routine-request.ts";import { intervalAllowsOccurrence, intervalHasRestrictions, isSameLocalDay, latestIntervalOccurrence } from "./routine-intervals.ts";@@ -302,7 +303,7 @@ export class RoutineManager {private runs: RoutineRun[] = [];private routineRequestReceipts: RoutineRequestReceipt[] = [];private webhookRunReceipts: EventRunReceipt[] = [];- private timer: ReturnType<typeof setInterval> | null = null;+ private timer: DueTimer | null = null;private startupRunsQueued = false;private startupLaunchId: string | undefined;private ticking = false;@@ -941,13 +942,12 @@ export class RoutineManager {start() {if (this.closing || this.timer) return;if (!this.startupRunsQueued) this.startupRunsQueued = this.queueStartupRuns();- this.tickInBackground();- this.timer = setInterval(() => this.tickInBackground(), 10_000);- this.timer.unref?.();+ this.timer = startDueTimer({ run: () => this.tick(), now: this.now, onError: (error) => console.error("routines: a scheduler pass failed", error),+ next: () => schedulerDueOf(this.routines, this.runs, this.now(), this.bootedAt + CHECK_BOOT_HOLD_MS, (routine) => this.targetState(routine) === "missing") });}stop() {- if (this.timer) clearInterval(this.timer);+ this.timer?.stop();this.timer = null;}@@ -1468,11 +1468,11 @@ export class RoutineManager {}private emitRoutine(routine: Routine) {- this.options.emit?.({ kind: "routine", routine: this.routineWithHealth(routine) });+ this.timer?.poke(); this.options.emit?.({ kind: "routine", routine: this.routineWithHealth(routine) });}private emitRun(run: RoutineRun) {- this.options.emit?.({ kind: "routine.run", run: cloneRun(run) });+ this.timer?.poke(); this.options.emit?.({ kind: "routine.run", run: cloneRun(run) });this.notifyRunChanged(run);if (run.checkKey && !["queued", "running", "waiting"].includes(run.status)) this.options.checks?.settled(cloneRun(run));if (run.status === "completed" || run.status === "failed") {diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.tsindex 2a8e34d180..c543dd08bf 100644--- a/server/runtime-coordinator.test.ts+++ b/server/runtime-coordinator.test.ts@@ -1610,3 +1610,25 @@ describe("RuntimeCoordinator: who answers a teammate's question", () => {expect(w.coordinator.parkedFor("tester")).toEqual([]);});});++describe("pace: how soon the host must tick", () => {+ it("is busy while a turn runs, parked while the work only waits on the person, idle once done; every write is announced", async () => {+ const host = fakeHost();+ const wrote = vi.fn();+ const w: World = { host, coordinator: new RuntimeCoordinator({ dataDir: ":memory:", host, wrote }), logs: [] };+ expect(w.coordinator.pace()).toBe("idle");+ begun(w, chief, "gen-1");+ expect(wrote).toHaveBeenCalled();+ expect(w.coordinator.pace()).toBe("busy");+ w.coordinator.endTurn("gen-1", { ok: true, text: "", cards: { question: "Approve the key", ids: ["msg-1"] } });+ expect(w.coordinator.pace()).toBe("parked");+ wrote.mockClear();+ expect(w.coordinator.answerRoot("gen-1", "The user approved the key.")).toBe(true);+ expect(wrote).toHaveBeenCalled();+ expect(w.coordinator.pace()).toBe("busy");+ w.coordinator.tick(); await flush();+ w.coordinator.tick(); await flush();+ expect(w.coordinator.node("gen-1")).toMatchObject({ status: "completed" });+ expect(w.coordinator.pace()).toBe("idle");+ });+});diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex d396f832ec..f632d0fd96 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -103,6 +103,16 @@ export function view(a: Assignment, parent?: Assignment): HandoffView {return node;}+function announcingWrites(store: RuntimeStore, wrote: () => void): RuntimeStore {+ const announced = <A extends unknown[], R>(write: (...args: A) => R) => (...args: A): R => {+ const result = write(...args);+ wrote();+ return result;+ };+ return { ...store, insert: announced(store.insert), update: announced(store.update), addInbox: announced(store.addInbox),+ markDelivered: announced(store.markDelivered), prune: announced(store.prune) };+}+/** How often a request that joined another looks at it. */const JOIN_POLL_MS = 1_000;const JOINED_NOTE = "Another teammate asked this a moment ago, so it was answered once, for both of you:";@@ -126,7 +136,8 @@ export class RuntimeCoordinator implements Coordinator {this.legacyThreads = options.legacyThreads;this.now = options.now ?? Date.now;this.log = options.log ?? ((line) => console.error("coordinator:", line));- this.store = openRuntimeStore(options.dataDir === ":memory:" ? ":memory:" : join(options.dataDir, "runtime.db"));+ const store = openRuntimeStore(options.dataDir === ":memory:" ? ":memory:" : join(options.dataDir, "runtime.db"));+ this.store = options.wrote ? announcingWrites(store, options.wrote) : store;this.runtime = new Runtime(this.store, this.runner(), {clock: { now: () => this.now(), monotonic: () => performance.now() },limits: { depth: 4, requests: REQUESTS_PER_ROOT, executions: EXECUTIONS_PER_ROOT, turnStallMs: TURN_STALL_MS, ...options.runtimeLimits },@@ -439,6 +450,11 @@ export class RuntimeCoordinator implements Coordinator {this.runtime.tick();}+ pace(): "busy" | "parked" | "idle" {+ this.ready();+ return this.runtime.pace();+ }+private pruneDaily(): void {const now = this.now();if (this.prunedAt !== undefined && now - this.prunedAt < PRUNE_EVERY_MS) return;diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.tsindex d82b417bf7..6de12de1df 100644--- a/server/runtime/runtime.ts+++ b/server/runtime/runtime.ts@@ -228,6 +228,16 @@ export class Runtime {return { ok: true, assignment: node, duplicate: false };}+ /** How soon the next tick() matters: "busy" while work may move without a call in here (a turn, a queued or resumable+ * assignment, a report to send); "parked" while live assignments only wait on a person, a teammate or a time limit. */+ pace(): "busy" | "parked" | "idle" {+ if (!this.opened) this.open();+ if (this.turns.size > 0 || this.reportDue.size > 0) return "busy";+ const live = this.store.all({ nonTerminal: true });+ if (live.some(n => n.status === "queued" || n.status === "resume" || n.status === "running")) return "busy";+ return live.length > 0 ? "parked" : "idle";+ }+/** Never overlaps itself; does nothing after close(). */tick(): void {if (!this.opened) this.open();diff --git a/server/testing/limit-clock-hooks.mjs b/server/testing/limit-clock-hooks.mjsindex 7281ef2476..3279083674 100644--- a/server/testing/limit-clock-hooks.mjs+++ b/server/testing/limit-clock-hooks.mjs@@ -1,5 +1,5 @@// Loaded with --import in isolated fixtures when OMB_TEST_LIMIT_CLOCK=1: a limit-reset automation starts a second-// after the reset instead of a minute, and routines are checked every 250 ms instead of every 10 s, so a fixture can+// after the reset instead of a minute, and a routine still due is retried every 250 ms instead of every 10 s, so a fixture can// watch one run without waiting. No authorization or dispatch decision changes.import { registerHooks } from 'node:module';@@ -9,7 +9,7 @@ if (!dataDir || dataDir !== process.env.HOME || process.env.OMB_TEST_LIMIT_CLOCK}const seams = new Map([[new URL('../../shared/limit-reset.ts', import.meta.url).href, ['export const AFTER_RESET_MS = 60_000;', 'export const AFTER_RESET_MS = 1_000;']],- [new URL('../routines.ts', import.meta.url).href, ['setInterval(() => this.tickInBackground(), 10_000)', 'setInterval(() => this.tickInBackground(), 250)']],+ [new URL('../routines.ts', import.meta.url).href, ['startDueTimer({ run: () => this.tick(),', 'startDueTimer({ retryMs: 250, run: () => this.tick(),']],]);registerHooks({load(url, context, nextLoad) {diff --git a/server/waits.ts b/server/waits.tsindex f3134803ed..b090f0e24a 100644--- a/server/waits.ts+++ b/server/waits.ts@@ -7,6 +7,7 @@ import { z } from "zod";import { WAIT_HOURS, type WaitKind } from "../shared/waits.ts";import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";+import { startDueTimer, type DueTimer } from "./due-timer.ts";import {expandHome,fetchPageText,@@ -142,7 +143,7 @@ export class WaitManager {private readonly probes: WaitProbes;private readonly options: WaitManagerOptions;private waits: WaitRecord[] = [];- private timer: ReturnType<typeof setInterval> | null = null;+ private timer: DueTimer | null = null;private running = false;private stopped = false;private ticking = false;@@ -287,18 +288,18 @@ export class WaitManager {start(): void {this.stopped = false;if (this.timer) return;- this.runTick();- this.timer = setInterval(() => this.runTick(), WAIT_TICK_MS);- this.timer.unref?.();- }-- private runTick(): void {- this.tick().catch((error) => console.error("wait tick failed", error));+ this.timer = startDueTimer({+ run: () => this.tick(),+ next: () => this.waits.reduce<number | null>((at, w) => Math.min(at ?? Infinity, w.ending ? this.now() : Math.min(w.nextCheckAt, w.expiresAt)), null),+ now: this.now,+ retryMs: WAIT_TICK_MS,+ onError: (error) => console.error("wait tick failed", error),+ });}stop(): void {this.stopped = true;- if (this.timer) clearInterval(this.timer);+ this.timer?.stop();this.timer = null;}@@ -427,6 +428,7 @@ export class WaitManager {try {mutate();this.save();+ this.timer?.poke();} catch (error) {identity.forEach((w, i) => {for (const key of Object.keys(w)) delete (w as unknown as Record<string, unknown>)[key];diff --git a/server/webhook-ingress.ts b/server/webhook-ingress.tsindex 8fe1652b7a..ebddc31186 100644--- a/server/webhook-ingress.ts+++ b/server/webhook-ingress.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { parseJson, type JsonValue } from "./schema.ts";import type { WebhookManager } from "./webhooks.ts";+import { IDLE_HTTP_SERVER } from "./due-timer.ts";export const MAX_WEBHOOK_BODY_BYTES = 256 * 1024;const statusErrorSchema = z.object({ status: z.number().int().optional() });@@ -171,7 +172,7 @@ export async function listenWebhookIngress(const host = options.host ?? "127.0.0.1";const advertised = options.publicBaseUrl === undefined ? undefined : advertisedWebhookBase(options.publicBaseUrl);const handle = createWebhookIngressHandler(manager, options.claimRequest);- const server = createServer((req, res) => {+ const server = createServer(IDLE_HTTP_SERVER, (req, res) => {handle(req, res).catch((error: unknown) => {console.error("webhooks: receiver failed", error);if (res.headersSent) res.destroy();diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex 8a4b9f992c..1062ca3acc 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -337,7 +337,7 @@ export function ModelPicker({if (refreshingRef.current) return;refreshingRef.current = true;setLoadingInstances(true);- void refreshInstances()+ void refreshInstances({ cached: true }).catch(() => {}).finally(() => {refreshingRef.current = false;diff --git a/src/components/onboarding/ConnectAi.tsx b/src/components/onboarding/ConnectAi.tsxindex c96759cbe2..f8c8e30c81 100644--- a/src/components/onboarding/ConnectAi.tsx+++ b/src/components/onboarding/ConnectAi.tsx@@ -51,11 +51,11 @@ export function ConnectAi({ hosted = false, tested }: { hosted?: boolean; testedconst [open, setOpen] = useState<string | null>(null);const latestRequest = useRef(0);- const refresh = useCallback(async () => {+ const refresh = useCallback(async (fresh = true) => {const request = ++latestRequest.current;setChecking(true);try {- const d = await api("/api/instances", { signal: AbortSignal.timeout(10_000) });+ const d = await api(fresh ? "/api/instances?fresh=1" : "/api/instances", { signal: AbortSignal.timeout(10_000) });if (request !== latestRequest.current) return;dispatch({ type: "instances", instances: d.instances ?? [] });setFailed(false);@@ -67,7 +67,7 @@ export function ConnectAi({ hosted = false, tested }: { hosted?: boolean; tested}, [dispatch]);useEffect(() => {- void refresh();+ void refresh(false);return () => {latestRequest.current++;};diff --git a/src/state/engine-setup-lifecycle.test.ts b/src/state/engine-setup-lifecycle.test.tsindex b60a45cb3d..85e7db8355 100644--- a/src/state/engine-setup-lifecycle.test.ts+++ b/src/state/engine-setup-lifecycle.test.ts@@ -14,7 +14,7 @@ it("recovers from offline, detects installation, and becomes ready on focus withlet snapshot: InstanceInfo["snapshot"] = { state: "unavailable", reason: "Fixture CLI missing" };let offline = false;const requests = vi.fn(async (path: string) => {- if (path === "/api/instances") return new Response(JSON.stringify(offline ? { error: "Fixture offline" } : { instances: [{+ if (path.split("?")[0] === "/api/instances") return new Response(JSON.stringify(offline ? { error: "Fixture offline" } : { instances: [{instanceId: "kimi", driverKind: "kimiAgent", displayName: "Kimi", models: { default: "fixture", options: [] }, snapshot,install: { platform: "linux", command: { linux: "fixture-install" }, signInCommand: "fixture-login" },}] }), { status: offline ? 503 : 200 });diff --git a/src/state/store.tsx b/src/state/store.tsxindex 5f35a7c275..fc21f2ce52 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -2090,7 +2090,7 @@ export const StoreContext = createContext<{state: AppState;dispatch: React.Dispatch<Action>;flushBotPatches: (botId: string) => Promise<BotAnnouncement | null>;- refreshInstances: (options?: { reportErrors?: boolean }) => Promise<void>;+ refreshInstances: (options?: { reportErrors?: boolean; cached?: boolean }) => Promise<void>;refreshModels: (instanceId: string) => Promise<void>;} | null>(null);@@ -3299,19 +3299,16 @@ export function StoreProvider({ children }: { children: ReactNode }) {};}, []);- const instanceProbe = useRef<Promise<void> | null>(null);- const refreshInstances = useCallback(async (options?: { reportErrors?: boolean }) => {- const probe = instanceProbe.current ??= api("/api/instances", { timeoutMs: 120_000 }).then(({ instances }) => {+ const instanceProbes = useRef(new Map<string, Promise<void>>());+ const refreshInstances = useCallback(async (options?: { reportErrors?: boolean; cached?: boolean }) => {+ const path = options?.cached ? "/api/instances" : "/api/instances?fresh=1", probes = instanceProbes.current;+ const probe = probes.get(path) ?? api(path, { timeoutMs: 120_000 }).then(({ instances }) => {if (!Array.isArray(instances)) throw new Error(t("engineSetup.invalidStatus"));rawDispatch({ type: "instances", instances });});- try {- await probe;- } catch (error) {- if (options?.reportErrors) throw error;- } finally {- if (instanceProbe.current === probe) instanceProbe.current = null;- }+ probes.set(path, probe);+ await probe.catch((error) => { if (options?.reportErrors) throw error; })+ .finally(() => { if (probes.get(path) === probe) probes.delete(path); });}, []);const refreshModels = useCallback(async (instanceId: string) => {@@ -3325,9 +3322,9 @@ export function StoreProvider({ children }: { children: ReactNode }) {useEffect(() => {const onFocus = () => {const now = Date.now();- if (now - lastFocusProbe.current < 30_000) return; // every engine's CLI runs; a Keychain prompt refocuses the window+ if (now - lastFocusProbe.current < 30_000) return; // a status read can run engine CLIs, and a Keychain prompt refocuses the windowlastFocusProbe.current = now;- void refreshInstances();+ void refreshInstances({ cached: true });};window.addEventListener("focus", onFocus);const onVisible = () => { if (document.visibilityState === "visible") onFocus(); };