Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(limits): wait for the refused turn's send to return, and leave the settle screen out of what ran
laijsg1fb01192749bb
diff --git a/server/host/dispatch-claims.test.ts b/server/host/dispatch-claims.test.tsnew file mode 100644index 0000000000..2c2bb8ef08--- /dev/null+++ b/server/host/dispatch-claims.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { DispatchClaims } from "./dispatch-claims.ts";++type Claim = { id: string; phase: "setup" | "dispatching" };++const settledYet = async (promise: Promise<void>): Promise<boolean> => {+ let done = false;+ void promise.then(() => { done = true; });+ await new Promise((resolve) => setImmediate(resolve));+ return done;+};++describe("DispatchClaims", () => {+ it("resolves at once when the thread holds no claim", async () => {+ expect(await settledYet(new DispatchClaims<Claim>().released("t1"))).toBe(true);+ });++ it("waits through a phase change of the same claim and resolves when it is cleared", async () => {+ const claims = new DispatchClaims<Claim>();+ claims.set("t1", { id: "c1", phase: "setup" });+ const released = claims.released("t1");+ claims.set("t1", { id: "c1", phase: "dispatching" });+ expect(await settledYet(released)).toBe(false);+ claims.delete("t2");+ expect(await settledYet(released)).toBe(false);+ claims.delete("t1");+ expect(await settledYet(released)).toBe(true);+ });++ it("resolves when another turn's claim replaces it, and then waits on that one only for a new caller", async () => {+ const claims = new DispatchClaims<Claim>();+ claims.set("t1", { id: "c1", phase: "dispatching" });+ const first = claims.released("t1");+ claims.set("t1", { id: "c2", phase: "setup" });+ expect(await settledYet(first)).toBe(true);+ const second = claims.released("t1");+ expect(await settledYet(second)).toBe(false);+ claims.clear();+ expect(await settledYet(second)).toBe(true);+ });+});diff --git a/server/host/dispatch-claims.ts b/server/host/dispatch-claims.tsnew file mode 100644index 0000000000..e19b7011ed--- /dev/null+++ b/server/host/dispatch-claims.ts@@ -0,0 +1,37 @@+/** The direct turns being set up or sent to their engine, by thread. A thread holding a claim reads busy. */+export class DispatchClaims<Claim extends { id: string }> extends Map<string, Claim> {+ private readonly waiting = new Map<string, Array<() => void>>();++ /** Resolves once the claim the thread holds now is gone: cleared, or replaced by another turn's. */+ released(threadId: string): Promise<void> {+ const claim = this.get(threadId);+ if (!claim) return Promise.resolve();+ return new Promise((resolve) => this.waiting.set(claim.id, [...(this.waiting.get(claim.id) ?? []), resolve]));+ }++ override set(threadId: string, claim: Claim): this {+ const before = this.get(threadId);+ super.set(threadId, claim);+ if (before && before.id !== claim.id) this.release(before.id);+ return this;+ }++ override delete(threadId: string): boolean {+ const before = this.get(threadId);+ const deleted = super.delete(threadId);+ if (before) this.release(before.id);+ return deleted;+ }++ override clear(): void {+ const before = [...this.values()];+ super.clear();+ for (const claim of before) this.release(claim.id);+ }++ private release(claimId: string): void {+ const waiters = this.waiting.get(claimId) ?? [];+ this.waiting.delete(claimId);+ for (const resolve of waiters) resolve();+ }+}diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsindex ba7ff61760..008462aec1 100644--- a/server/host/peer-limit-resend.test.ts+++ b/server/host/peer-limit-resend.test.ts@@ -19,6 +19,7 @@ describe("nothingRan", () => {// Some engines send the limit sentence as reply text.expect(nothingRan([{ ...reply, text: LIMIT }], 100, "turn-1", LIMIT)).toBe(true);expect(nothingRan([{ ...reply, kind: "compaction", text: undefined }, failure], 100, "turn-1"), "a summary of earlier context").toBe(true);+ expect(nothingRan([{ ...reply, kind: "screen", text: undefined, turnId: undefined, png: "iVBORw0KGgo=", mime: "image/png" }, failure], 100, "turn-1"), "the screen captured as the turn settled").toBe(true);expect(nothingRan([toolCall, failure], 100, "turn-1")).toBe(false);expect(nothingRan([reply, failure], 100, "turn-1")).toBe(false);expect(nothingRan([{ ...reply, kind: "widget" } as Message], 100, "turn-1")).toBe(false);diff --git a/server/index.ts b/server/index.tsindex c30d6429cb..936668f5b7 100644--- a/server/index.ts+++ b/server/index.ts@@ -333,7 +333,7 @@ import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnseimport { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";import { callTitleExcerpt } from "./thread-title.ts";import { generateThreadTitle } from "./thread-title-generate.ts";-import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";+import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts"; import { DispatchClaims } from "./host/dispatch-claims.ts";import { TurnResources, type TurnOwner } from "./turn-resources.ts";import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.ts";import { endHoldUnlessOn, usbPhoneOffered, usbPhoneTakeoverEnabled } from "./phone-screen/flag.ts"; import { dataPrompts } from "./data-prompt.ts";@@ -1882,7 +1882,7 @@ async function cloudComputerHolders(botId: string): Promise<string[]> {function boatNotConfigured(bot: { name: string }, source: PlaceSource): PlaceUnavailableError {return placeUnavailable("cloud", { state: CLOUD_HOME ? "cc-unavailable" : "cc-needs-key", params: { bot: bot.name }, source }, Boolean(CLOUD_HOME));}-const directTurnDispatchClaims = new Map<string, DirectTurnDispatchClaim>();+const directTurnDispatchClaims = new DispatchClaims<DirectTurnDispatchClaim>();const directTurnGenerationByThread = new Map<string, string>();// Latest direct request per thread, kept past Stop until completion or failure cleanup; unknown continuations deliberately lose proof.const directRequestOwners = new Map<string, {@@ -6677,7 +6677,7 @@ bus.subscribe((event: RuntimeEvent) => {const facts = { ...turnStops.read(event.threadId, event.turnId)?.flags, stopReason: directRequestOwners.get(event.threadId)?.stopped ? "cancelled" : event.stopReason };const held = facts.limit ?? (signedOutStop(facts.stopReason, failureDetail) ? "signed-out" as const : undefined); // a limit or a sign-out: one incident a stretch, the person told by its own noticeconst fileIncident = () => { if (broken && (!held || limitTakeover.firstIncident(broken.id, broken.modelSelection, held, facts.limitResetsAt))) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts, notified: Boolean(held) }); };- let directSettled = () => {}; const settledDirect = new Promise<void>((resolve) => { directSettled = resolve; }); if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal, settledDirect);+ let directSettled = () => {}; const settledDirect = new Promise<void>((resolve) => { directSettled = resolve; }); if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal, Promise.all([settledDirect, directTurnDispatchClaims.released(event.threadId)]));else if (bot && event.ok) quotaSwitch.turnSucceeded(bot, event.threadId);if (bot && event.ok && !stopped && completedTurnId && !routineRun && !coordinator.assignerOf(event.threadId)) askCards.ownQuestion(bot.id, event.threadId, completedTurnId);const lastReported = turnUsage.get(event.threadId);diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex 23aeb6bb4c..c3f1e5eae9 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -301,6 +301,18 @@ describe("quota switch", () => {expect(resend).toHaveBeenCalledTimes(1);});+ it("sends a request again when the screen captured as its refused turn settled is the only row after it", async () => {+ const turn = begin(bot.threadId, { messageId: said("plan the launch") });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ let settle = () => {};+ const failing = ranOut(turn, QUOTA, false, thread(), new Promise<void>((resolve) => { settle = resolve; }));+ store.appendMessage(bot.threadId, { role: "bot", kind: "screen", png: "iVBORw0KGgo=", mime: "image/png" });+ settle();+ expect(await failing).toBeNull();+ expect(thread().modelSelection).toEqual(CODEX);+ expect(resend).toHaveBeenCalledTimes(1);+ });+it("sends a request again when a routine's report landed in the conversation while its refused turn settled", async () => {const turn = begin(bot.threadId, { messageId: said("plan the launch") });coordinator.endTurn(turn.id, { ok: false, text: QUOTA });diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex 828b77a231..fd9c4cc8cc 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -58,8 +58,8 @@ export interface QuotaSwitchDeps {}export interface QuotaSwitch {- /** Never rejects. Nothing moves to a backup before `settled` resolves: until the turn's conversation has settled it- * still reads busy, and a busy conversation's model cannot change. */+ /** Never rejects. Nothing moves to a backup before `settled` resolves: until the turn's conversation has settled, and+ * its send to the engine has returned, it still reads busy, and a busy conversation's model cannot change. */turnFailed(bot: BotRecord, event: SettledTurn, internal: boolean, settled?: Promise<unknown>): Promise<Message | null>;/** Never throws. */turnSucceeded(bot: BotRecord, threadId: string): void;diff --git a/server/turn-outcome.ts b/server/turn-outcome.tsindex 39a1fae34a..ff40b41b5d 100644--- a/server/turn-outcome.ts+++ b/server/turn-outcome.ts@@ -136,13 +136,14 @@ function sentence(text: string): string {/*** True when the failed turn left nothing behind: no tool call, no reply, no file. Its own failure row, the- * engine's limit sentence (`stopError`, sometimes sent as reply text), a summary of the conversation's earlier context- * and the hand-off's request card, written just before the turn (sometimes in the same millisecond), do not count.+ * engine's limit sentence (`stopError`, sometimes sent as reply text), a summary of the conversation's earlier context,+ * the screen captured as the turn settles and the hand-off's request card, written just before the turn (sometimes in+ * the same millisecond), do not count.*/export function nothingRan(rows: readonly Message[], since: number, turnId: string | undefined, stopError?: string): boolean {const said = stopError?.trim();// The turn's digest is written after it ends and only sums it up.- return !rows.some((row) => row.at >= since && row.role === "bot" && row.kind !== "digest" && row.kind !== "compaction" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (+ return !rows.some((row) => row.at >= since && row.role === "bot" && row.kind !== "digest" && row.kind !== "compaction" && row.kind !== "screen" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (row.kind === "activity" ? Boolean(row.tool?.itemId): row.kind === "text" ? Boolean(row.text?.trim()) && row.text!.trim() !== said: true));