Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(rooms): a room turn does not count the computer's sleep as silence
laijsg1e3f3a51a39b3
diff --git a/server/room-turn-timeout.test.ts b/server/room-turn-timeout.test.tsindex c18f2bb83d..fab57d1474 100644--- a/server/room-turn-timeout.test.ts+++ b/server/room-turn-timeout.test.ts@@ -3,8 +3,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { RuntimeEvent } from "./contracts.ts";import {ROOM_TOOL_QUIET_LIMIT_MS,+ ROOM_TURN_CLOCK_LOOK_MS,ROOM_TURN_PROGRESS,RoomTurnDeadline,+ type RoomTurnClock,RoomTurnStallRegistry,effectiveRoomTurnTimeoutMinutes,parseConversationTurnTimeout,@@ -19,6 +21,51 @@ const toolStarted = (itemId: string): RuntimeEvent => ({ ...base, type: "item.stconst toolEnded = (itemId: string): RuntimeEvent => ({ ...base, type: "item.completed", itemType: "tool", itemId, ok: true });const cardOpened: RuntimeEvent = { ...base, type: "request.opened", requestId: "r", requestType: "permission", tool: "Bash", summary: "ls" };const cardResolved: RuntimeEvent = { ...base, type: "request.resolved", requestId: "r", behavior: "allow", source: "user" };+const reply: RuntimeEvent = { ...base, type: "content.delta", streamKind: "assistant_text", delta: "ok" };++/** Timers that keep counting through a sleep, as Node's do on macOS: `sleep` moves the clock on and runs nothing, and+ * `wake` runs what came due meanwhile, the kind named first. */+function sleepingClock() {+ type Timer = { at: number; every?: number; run: () => void };+ let now = 0, nextId = 0;+ const timers = new Map<number, Timer>();+ const add = (timer: Timer) => {+ const id = nextId++;+ timers.set(id, timer);+ return () => { timers.delete(id); };+ };+ const clock: RoomTurnClock = {+ now: () => now,+ after: (ms, run) => add({ at: now + ms, run }),+ every: (ms, run) => add({ at: now + ms, every: ms, run }),+ };+ const fire = (id: number, timer: Timer) => {+ if (timer.every) timer.at = now + timer.every;+ else timers.delete(id);+ timer.run();+ };+ const due = (by: number, kind?: "after" | "every") => [...timers].filter(([, timer]) => timer.at <= by && (kind === undefined || (kind === "every") === Boolean(timer.every)))+ .sort(([leftId, left], [rightId, right]) => left.at - right.at || leftId - rightId);+ return {+ clock,+ advance(ms: number) {+ const end = now + ms;+ for (let next = due(end)[0]; next; next = due(end)[0]) {+ now = next[1].at;+ fire(...next);+ }+ now = end;+ },+ sleep(ms: number) {+ now += ms;+ },+ wake(first: "after" | "every") {+ for (const kind of [first, first === "after" ? "every" : "after"] as const) {+ for (const [id, timer] of due(now, kind)) if (timers.get(id) === timer) fire(id, timer);+ }+ },+ };+}describe("room turn timeout", () => {it("converts configured minutes to milliseconds", () => {@@ -85,17 +132,113 @@ describe("room turn timeout", () => {deadline.stop();});- it("stops a turn whose progress arrives after the limit, before the timer ran", () => {+ it("stops a turn whose progress arrives after the limit, before the timer ran", async () => {vi.useFakeTimers();const onTimeout = vi.fn();const deadline = new RoomTurnDeadline(5, onTimeout);deadline.start();// A stalled event loop delivers the event past the limit, before the timer callback ran.- vi.setSystemTime(Date.now() + 5 * 60_000 + 1);+ await vi.advanceTimersByTimeAsync(5 * 60_000 - 10_000);+ vi.setSystemTime(Date.now() + 10_001);deadline.progress();expect(onTimeout).toHaveBeenCalledOnce();- deadline.stop();+ expect(vi.getTimerCount()).toBe(0);+ });+++ it("does not count a sleep as silence when the engine's next event comes first on waking", () => {+ const time = sleepingClock();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout, time.clock);+ deadline.start();++ time.advance(5 * 60_000 - ROOM_TURN_CLOCK_LOOK_MS);+ time.sleep(2 * 60 * 60_000);+ deadline.observe(reply);+ time.wake("after");+ expect(onTimeout).not.toHaveBeenCalled();++ time.advance(5 * 60_000 - 1);+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(1);+ expect(onTimeout).toHaveBeenCalledOnce();+ });++ for (const first of ["after", "every"] as const) {+ it(`keeps the idle time from before a sleep when the ${first === "after" ? "deadline's own timer" : "clock's look"} runs first on waking`, () => {+ const time = sleepingClock();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout, time.clock);+ deadline.start();++ time.advance(5 * 60_000 - ROOM_TURN_CLOCK_LOOK_MS);+ time.sleep(2 * 60 * 60_000);+ time.wake(first);+ expect(onTimeout).not.toHaveBeenCalled();++ time.advance(ROOM_TURN_CLOCK_LOOK_MS - 1);+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(1);+ expect(onTimeout).toHaveBeenCalledOnce();+ });++ it(`keeps the idle time from before a wait that ends on waking, ${first === "after" ? "before" : "after"} the clock's look`, () => {+ const time = sleepingClock();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout, time.clock);+ deadline.start();++ time.advance(4 * 60_000);+ deadline.setWaiting(true);+ time.advance(10_000);+ time.sleep(2 * 60 * 60_000);+ if (first === "every") time.wake("every");+ deadline.setWaiting(false);+ time.wake("every");+ expect(onTimeout).not.toHaveBeenCalled();++ time.advance(60_000 - 1);+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(1);+ expect(onTimeout).toHaveBeenCalledOnce();+ });+ }++ it("counts the time awake between many short wakes", () => {+ const time = sleepingClock();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout, time.clock);+ deadline.start();++ const wakeOnce = () => {+ time.advance(20_000);+ time.sleep(60 * 60_000);+ time.wake("every");+ };+ for (let wake = 0; wake < 14; wake += 1) wakeOnce();+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(20_000 - 1);+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(1);+ expect(onTimeout).toHaveBeenCalledOnce();+ });++ it("counts a gap between looks too short to be a sleep as silence", () => {+ const time = sleepingClock();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout, time.clock);+ deadline.start();++ time.advance(280_000);+ time.sleep(3 * ROOM_TURN_CLOCK_LOOK_MS);+ time.wake("every");+ expect(onTimeout).not.toHaveBeenCalled();++ time.advance(5 * 60_000 - 280_000 - 3 * ROOM_TURN_CLOCK_LOOK_MS - 1);+ expect(onTimeout).not.toHaveBeenCalled();+ time.advance(1);+ expect(onTimeout).toHaveBeenCalledOnce();});it("can be cancelled when the room turn settles", async () => {@@ -103,12 +246,26 @@ describe("room turn timeout", () => {const onTimeout = vi.fn();const deadline = new RoomTurnDeadline(5, onTimeout);deadline.start();+ deadline.start();deadline.stop();+ deadline.start();+ expect(vi.getTimerCount()).toBe(0);await vi.advanceTimersByTimeAsync(5 * 60_000);expect(onTimeout).not.toHaveBeenCalled();});+ it("leaves no timer behind once it fires", async () => {+ vi.useFakeTimers();+ const onTimeout = vi.fn();+ const deadline = new RoomTurnDeadline(5, onTimeout);+ deadline.start();++ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(onTimeout).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });+it("holds the clock while a human decides and resumes where it left off", async () => {vi.useFakeTimers();const onTimeout = vi.fn();@@ -159,7 +316,8 @@ describe("room turn timeout", () => {deadline.start();// A stalled event loop delivers the card event past the deadline, before the timer callback ran.- vi.setSystemTime(Date.now() + 5 * 60_000 + 1);+ await vi.advanceTimersByTimeAsync(5 * 60_000 - 10_000);+ vi.setSystemTime(Date.now() + 10_001);deadline.setWaiting(true);expect(onTimeout).toHaveBeenCalledOnce();diff --git a/server/room-turn-timeout.ts b/server/room-turn-timeout.tsindex c62b4a52ad..949d8cf07d 100644--- a/server/room-turn-timeout.ts+++ b/server/room-turn-timeout.ts@@ -51,13 +51,45 @@ export function effectiveRoomTurnTimeoutMinutes(/** How long a turn may show nothing while one of its tools runs: as long as an MCP call may be set to take. */export const ROOM_TOOL_QUIET_LIMIT_MS = MAX_MCP_CALL_TIMEOUT_MINUTES * 60_000;+export const ROOM_TURN_CLOCK_LOOK_MS = 5_000;+/** Two looks more than this many periods apart: the process was suspended or its event loop blocked, which no timer can+ * tell apart, and neither is the turn's silence. On macOS (Electron 43) Node's timers and monotonic clock keep counting+ * while the computer sleeps, so a deadline due during the sleep fires the moment it wakes: only the gap between looks+ * tells the sleep apart. */+const SUSPENDED_LOOKS = 3;++export interface RoomTurnClock {+ now(): number;+ /** Returns the cancel. */+ after(ms: number, run: () => void): () => void;+ /** Returns the cancel. */+ every(ms: number, run: () => void): () => void;+}++const systemClock: RoomTurnClock = {+ now: () => Date.now(),+ after: (ms, run) => {+ const timer = setTimeout(run, ms);+ return () => clearTimeout(timer);+ },+ every: (ms, run) => {+ const timer = setInterval(run, ms);+ timer.unref?.();+ return () => clearInterval(timer);+ },+};+/** Stops a turn that shows no progress for the limit, or for ROOM_TOOL_QUIET_LIMIT_MS while a tool runs; the clock- * holds while the turn waits on a person or the computer, and stray ends clamp the count at zero. */+ * holds while the turn waits on a person or the computer, and while the computer sleeps; stray ends clamp the count at+ * zero. */export class RoomTurnDeadline {private limitMs: number;+ private clock: RoomTurnClock;private progressAt = 0;private heldAt = 0;- private timer: ReturnType<typeof setTimeout> | null = null;+ private lookedAt = 0;+ private stopLooking: (() => void) | null = null;+ private cancelTimer: (() => void) | null = null;private openWaits = 0;private runningTools = new Set<string>();private stopped = false;@@ -65,17 +97,22 @@ export class RoomTurnDeadline {private fire: () => void;// No parameter properties: Node's type-stripping cannot transform them.- constructor(minutes: number, fire: () => void) {+ constructor(minutes: number, fire: () => void, clock: RoomTurnClock = systemClock) {this.limitMs = roomTurnTimeoutMs(minutes);this.fire = fire;+ this.clock = clock;}start(): void {- this.progressAt = Date.now();+ if (this.stopped || this.fired || this.stopLooking !== null) return;+ this.progressAt = this.clock.now();+ this.lookedAt = this.progressAt;+ this.stopLooking = this.clock.every(ROOM_TURN_CLOCK_LOOK_MS, () => this.discountSleep());this.arm();}observe(e: RuntimeEvent): void {+ this.discountSleep();if (ROOM_TURN_PROGRESS.has(e.type)) this.progress();if (e.type === "request.opened" || e.type === "turn.wait_started") this.setWaiting(true);else if (e.type === "request.resolved" || e.type === "turn.wait_ended") this.setWaiting(false);@@ -88,15 +125,16 @@ export class RoomTurnDeadline {progress(): void {// A delayed event loop can deliver progress after the limit, before the timer ran: it must not revive an idle turn.- if (this.timer !== null && this.idleMs() >= this.quietLimitMs()) {+ if (this.cancelTimer !== null && this.idleMs() >= this.quietLimitMs()) {this.expired();return;}- this.progressAt = Date.now();+ this.progressAt = this.clock.now();}setWaiting(waiting: boolean): void {if (this.stopped || this.fired) return;+ this.discountSleep();if (waiting) {const wasIdle = this.openWaits === 0;this.openWaits += 1;@@ -106,7 +144,7 @@ export class RoomTurnDeadline {if (this.openWaits === 0) {// The wait paused the clock: idle time from before it still counts, progress during it counts as now.const idleBefore = this.progressAt >= this.heldAt ? 0 : this.heldAt - this.progressAt;- this.progressAt = Date.now() - idleBefore;+ this.progressAt = this.clock.now() - idleBefore;this.arm();}}@@ -114,14 +152,30 @@ export class RoomTurnDeadline {stop(): void {this.stopped = true;- if (this.timer !== null) {- clearTimeout(this.timer);- this.timer = null;- }+ this.release();+ }++ private release(): void {+ this.stopLooking?.();+ this.stopLooking = null;+ this.cancelTimer?.();+ this.cancelTimer = null;+ }++ /** A look late enough moves the turn's progress, and a wait's start, on by the whole gap. */+ private discountSleep(): void {+ if (this.stopLooking === null) return;+ const at = this.clock.now();+ const gapMs = at - this.lookedAt;+ this.lookedAt = at;+ if (gapMs <= SUSPENDED_LOOKS * ROOM_TURN_CLOCK_LOOK_MS) return;+ this.progressAt = Math.min(at, this.progressAt + gapMs);+ if (this.openWaits > 0) this.heldAt = Math.min(at, this.heldAt + gapMs);}private idleMs(): number {- return Date.now() - this.progressAt;+ this.discountSleep();+ return this.clock.now() - this.progressAt;}private quietLimitMs(): number {@@ -129,18 +183,18 @@ export class RoomTurnDeadline {}private hold(): void {- this.heldAt = Date.now();- if (this.timer === null) return;- clearTimeout(this.timer);- this.timer = null;+ this.heldAt = this.clock.now();+ if (this.cancelTimer === null) return;+ this.cancelTimer();+ this.cancelTimer = null;// A delayed event loop can deliver the wait after the deadline: a wait must not revive an idle turn.if (this.idleMs() >= this.quietLimitMs()) this.expired();}private rearm(): void {- if (this.timer === null) return;- clearTimeout(this.timer);- this.timer = null;+ if (this.cancelTimer === null) return;+ this.cancelTimer();+ this.cancelTimer = null;this.arm();}@@ -151,15 +205,16 @@ export class RoomTurnDeadline {this.expired();return;}- this.timer = setTimeout(() => {- this.timer = null;+ this.cancelTimer = this.clock.after(leftMs, () => {+ this.cancelTimer = null;this.arm();- }, leftMs);+ });}private expired(): void {if (this.stopped || this.fired) return;this.fired = true;+ this.release();this.fire();}}