Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(waits): keep a fired wait until its follow-up starts
DeryFerd32b5127e9c40
diff --git a/server/waits.test.ts b/server/waits.test.tsindex ff6c42c1a6..3f7b30bf4f 100644--- a/server/waits.test.ts+++ b/server/waits.test.ts@@ -307,7 +307,8 @@ describe("WaitManager", () => {const storedAtFollowUp: number[] = [];h.followUp.mockImplementation(() => { storedAtFollowUp.push(JSON.parse(readFileSync(h.file, "utf8")).waits.length); });const reloaded = h.reload(); h.postOk = true; await reloaded.tick();- expect(storedAtFollowUp).toEqual([0]);+ // The wait goes once its follow-up has started, not before: a refused enqueue has to leave something to retry.+ expect(storedAtFollowUp).toEqual([1]);expect(h.post).toHaveBeenCalledTimes(2);expect(h.posts).toHaveLength(1);expect(h.followUp).toHaveBeenCalledTimes(1);@@ -609,3 +610,52 @@ describe("WaitManager", () => {error.mockRestore();});});++describe("a fired wait whose follow-up cannot start", () => {+ it("keeps the fired result and retries it without asking the condition again", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);+ const h = harness();+ await h.create({ kind: "file_exists", path: "/r.txt" }, { label: "the report", followUp: "Summarise it." });+ // A refused enqueue: the bot is paused, at its cap, or its run was closed.+ h.followUp.mockImplementation(() => { throw new Error("this bot is paused"); });+ h.stamp = { size: 1, mtimeMs: 1 };+ h.advance(5_000);+ await h.manager.tick();+ expect(h.posts.map((notice) => notice.text)).toEqual(["the report: done. /r.txt is there now."]);+ // `list` hides an ended wait; `all` is where a fired one waits for its follow-up.+ expect(h.manager.all()).toHaveLength(1);+ expect(h.manager.all()[0]!.followUpRetryAt).toBeGreaterThan(h.now());+ // The file goes away while the follow-up is still owed: the work was already decided, so it still runs.+ h.stamp = null;+ h.followUp.mockImplementation(() => undefined);+ h.advance(60_000);+ await h.manager.tick();+ expect(h.followUp).toHaveBeenCalledTimes(2);+ expect(h.manager.all()).toEqual([]);+ error.mockRestore();+ });++ it("says the work did not run, in a notice of its own, once the retries are spent", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);+ const h = harness();+ // The host posts one notice per wait id and status, so a second "fired" notice would never reach the chat.+ const seen = new Set<string>();+ h.post.mockImplementation((wait: WaitRecord, notice: WaitNotice) => {+ const key = `${wait.id}:${notice.status}`;+ if (!seen.has(key)) { seen.add(key); h.posts.push(notice); }+ return true;+ });+ await h.create({ kind: "file_exists", path: "/r.txt" }, { label: "the report", followUp: "Summarise it." });+ h.followUp.mockImplementation(() => { throw new Error("this bot is paused"); });+ h.stamp = { size: 1, mtimeMs: 1 };+ for (let attempt = 0; attempt < 6; attempt += 1) {+ h.advance(60_000);+ await h.manager.tick();+ }+ expect(h.posts.map((notice) => notice.status)).toEqual(["fired", "stopped"]);+ expect(h.posts[1]!.text).toContain("its follow-up could not be started");+ expect(h.followUp).toHaveBeenCalledTimes(5);+ expect(h.manager.all()).toEqual([]);+ error.mockRestore();+ });+});diff --git a/server/waits.ts b/server/waits.tsindex 7177a809b9..ec41a1f1d4 100644--- a/server/waits.ts+++ b/server/waits.ts@@ -23,6 +23,9 @@ import {export const WAIT_LIMITS = { perBot: 10, total: 50, perAssignment: 1 } as const;export const WAIT_TICK_MS = 5_000, URL_CHECK_MS = 60_000, URL_BACKOFF_MAX_MS = 15 * 60_000;+/** A follow-up that cannot start is tried again on this cadence, this many times, and then the person is told it never+ * ran: a refused enqueue is a pause, a usage cap or a closed run, none of which asking the condition again would fix. */+export const FOLLOW_UP_RETRY_MS = 60_000, FOLLOW_UP_TRIES = 5;/** A sleeping Cloud wakes this often while a wait is open, to check it; checks pause in between. */export const WAIT_WAKE_MS = 30 * 60_000;export const NO_PROCESS_LIST = "This computer can't list its programs, so a program wait can't work here. Wait for a file or a page instead.";@@ -52,6 +55,9 @@ export interface WaitRecord {createdAt: number; expiresAt: number; nextCheckAt: number; errors: number; cardMessageId?: string;/** Decided and saved first; posted once its chat is free. */ending?: WaitNotice;+ /** A fired wait whose follow-up could not start: when the next attempt is due, and how many have failed. Kept with the+ * decided result, so the retry never asks the condition again. */+ followUpRetryAt?: number; followUpTries?: number;}export interface NewWait {botId: string; threadId: string; label: string; condition: NewWaitCondition; followUp?: string; hours?: number; assignmentId?: string;@@ -101,6 +107,8 @@ const recordSchema = z.object({errors: z.number(),cardMessageId: z.string().optional(),ending: z.object({ status: z.enum(["fired", "expired", "stopped"]), text: z.string() }).optional(),+ followUpRetryAt: z.number().optional(),+ followUpTries: z.number().optional(),});const fileSchema = z.object({ version: z.literal(1), waits: z.array(z.unknown()) });@@ -318,7 +326,7 @@ export class WaitManager {if (this.timer) return;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),+ next: () => this.waits.reduce<number | null>((at, w) => Math.min(at ?? Infinity, w.ending ? (w.followUpRetryAt ?? this.now()) : Math.min(w.nextCheckAt, w.expiresAt)), null),now: this.now,retryMs: WAIT_TICK_MS,onError: (error) => console.error("wait tick failed", error),@@ -389,12 +397,19 @@ export class WaitManager {for (const wait of this.waits.slice()) {if (!wait.ending) continue;+ // A fired wait whose follow-up could not start is parked until its next attempt. The result is already decided,+ // so the condition is not asked again: a file that went away in between cannot lose the work.+ if (wait.followUpRetryAt !== undefined && now < wait.followUpRetryAt) continue;let posted = false;try { posted = this.options.post(wait, wait.ending); } catch (error) { console.error(`wait ${wait.id}: could not post`, error); }if (!posted) continue;const status = wait.ending.status;+ if (status === "fired" && wait.followUp) {+ const outcome = this.startFollowUp(wait, now);+ if (outcome === "retry") continue;+ if (outcome === "gaveup") { this.followUpLost(wait); continue; }+ }this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });- if (status === "fired" && wait.followUp) this.safely(() => this.options.followUp(wait as WaitRecord & { followUp: string }));if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, status === "fired" ? "fired" : "expired"));}} finally {@@ -450,6 +465,34 @@ export class WaitManager {try { run(); } catch (error) { console.error("wait: callback failed", error); }}+ /** Starts a fired wait's follow-up. A refused enqueue is not the end of the work: the wait stays with its decided+ * result and the next attempt is scheduled, so the retry does not depend on the condition still holding. */+ private startFollowUp(wait: WaitRecord, now: number): "started" | "retry" | "gaveup" {+ try {+ this.options.followUp(wait as WaitRecord & { followUp: string });+ return "started";+ } catch (error) {+ console.error(`wait ${wait.id}: could not start the follow-up`, error);+ wait.followUpTries = (wait.followUpTries ?? 0) + 1;+ if (wait.followUpTries >= FOLLOW_UP_TRIES) return "gaveup";+ wait.followUpRetryAt = now + FOLLOW_UP_RETRY_MS;+ try { this.commit(() => {}); } catch (saveError) { console.error(`wait ${wait.id}: could not store its retry`, saveError); }+ return "retry";+ }+ }++ /** The follow-up never started: say so once, in a notice of its own, then let the wait go. The "fired" notice already+ * went out under that status, and the host posts one notice per wait id and status, so this one needs another. */+ private followUpLost(wait: WaitRecord): void {+ try {+ this.options.post(wait, { status: "stopped", text: `${wait.label}: its follow-up could not be started, so the work did not run.` });+ } catch (error) {+ console.error(`wait ${wait.id}: could not post`, error);+ }+ this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });+ if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, "expired"));+ }+private commit(mutate: () => void): void {const before = this.waits.map(cloneWait);const identity = this.waits.slice();