Skip to content

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

One-on-one goal: a turn that keeps losing its slot ends blocked at the wait cap (#3967)

Caleb Arumugam7eaaac9c7e62
diff --git a/server/host/one-on-one-goals.test.ts b/server/host/one-on-one-goals.test.ts
new file mode 100644
index 0000000000..7118ee8976
--- /dev/null
+++ b/server/host/one-on-one-goals.test.ts
@@ -0,0 +1,136 @@
+// A one-on-one goal's step against fake deps. The chat looks free, yet startTurn keeps refusing the
+// turn as busy: the step retries, and once the retries have filled the wait cap the run ends blocked,
+// as a busy wait does, instead of spinning forever. A lost race followed by a busy chat shares that one
+// cap. A single lost race still retries, and the goal finishes on the done marker.
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { HostTurnResult } from "../coordinator.ts";
+import { GROUP_GOAL_CONTROL_CLOSE, GROUP_GOAL_CONTROL_OPEN, GROUP_GOAL_MAX_TURNS, GROUP_GOAL_WAIT_MAX_MS, type GoalRunEnd } from "../group-goal-run.ts";
+import type { BotRecord, Message, TaskRecord } from "../store.ts";
+import type { LiveGoalRun } from "./goal-cards.ts";
+import { createGoalTurns, type GoalLeadTurn } from "./goal-turns.ts";
+import { createOneOnOneGoals } from "./one-on-one-goals.ts";
+
+// A one-second cap: the real half hour is thousands of retries, each a timer round of its own.
+vi.mock("../group-goal-run.ts", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../group-goal-run.ts")>()),
+ GROUP_GOAL_WAIT_MAX_MS: 1_000,
+}));
+
+const DONE = `${GROUP_GOAL_CONTROL_OPEN}{"status":"completed","detail":"Done."}${GROUP_GOAL_CONTROL_CLOSE}`;
+const refused = (code: string) => Object.assign(new Error("this thread is already working"), { code });
+
+/** A goal in a chat whose startTurn is scripted; the real goal-turns hold the lead, so a reply can be filled in. */
+function goalChat(startTurn: (call: number, lead: GoalLeadTurn, settle: (outcome: HostTurnResult) => void) => Promise<unknown>, canStart: () => boolean = () => true) {
+ const run: LiveGoalRun = {
+ runId: "r",
+ cardMessageId: "card",
+ goal: "Fix the build",
+ coordinatorBotId: "b",
+ coordinatorName: "Solo",
+ turnCount: 0,
+ maxTurns: GROUP_GOAL_MAX_TURNS,
+ startedAt: 0,
+ finished: false,
+ };
+ const finished: Array<{ status: GoalRunEnd; detail: string }> = [];
+ const ends: Array<string | undefined> = [];
+ const turns = createGoalTurns({ retireProviderTurn() {} });
+ let lead!: GoalLeadTurn;
+ let starts = 0;
+ let botChanged: ((change: { type: "bot"; botId: string }) => void) | undefined;
+ createOneOnOneGoals({
+ store: {
+ bot: () => ({ id: "b", name: "Solo" } as BotRecord),
+ taskByThread: () => ({} as TaskRecord),
+ appendMessage: () => ({ id: "m1" } as Message),
+ onChange: (listener) => { botChanged = listener as typeof botChanged; return () => {}; },
+ titleTaskFromFirstMessage: () => null,
+ },
+ cards: {
+ start: () => run,
+ progress: () => {},
+ // As the real cards do, keep the first end; the run's own cleanup reports a second one.
+ finish: (_threadId, _run, status, detail) => {
+ if (run.finished) return;
+ run.finished = true;
+ finished.push({ status, detail });
+ },
+ },
+ turns: {
+ ...turns,
+ begin: (threadId) => (lead = turns.begin(threadId)),
+ end: (threadId, turn, outcome) => {
+ ends.push(outcome);
+ turns.end(threadId, turn, outcome);
+ },
+ },
+ canStart,
+ isUnattended: () => false,
+ startTurn: (_botId, _text, opts) => startTurn(++starts, lead, opts.onSettled),
+ }).start("b", "t", "Fix the build");
+ // The store's change event for the bot, as the real store fires it when the bot's turn ends.
+ return { run, finished, ends, starts: () => starts, botChanged: () => botChanged?.({ type: "bot", botId: "b" }) };
+}
+
+describe("a one-on-one goal whose turn keeps losing its slot", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it.each(["thread_busy", "thread_limit"])("ends blocked once the %s retries fill the wait cap, instead of retrying forever", async (code) => {
+ vi.useFakeTimers();
+ const chat = goalChat(() => Promise.reject(refused(code)));
+ await vi.advanceTimersByTimeAsync(GROUP_GOAL_WAIT_MAX_MS + 1_000);
+ expect(chat.finished).toEqual([
+ { status: "blocked", detail: expect.stringMatching(/^Solo stayed busy for \d+ minutes? — send the goal again when they are free\.$/) },
+ ]);
+ expect(chat.run.turnCount).toBe(0);
+ const starts = chat.starts();
+ expect(starts).toBeGreaterThan(1);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(chat.starts()).toBe(starts);
+ expect(new Set(chat.ends)).toEqual(new Set(["busy"]));
+ });
+
+ it("shares one wait cap between a lost slot and the busy wait after it", async () => {
+ vi.useFakeTimers();
+ let busy = false;
+ const chat = goalChat(() => { busy = true; return Promise.reject(refused("thread_busy")); }, () => !busy);
+ // Without one shared cap the busy wait would start its own full cap after the lost slot.
+ await vi.advanceTimersByTimeAsync(GROUP_GOAL_WAIT_MAX_MS - 1);
+ expect(chat.finished).toEqual([]);
+ await vi.advanceTimersByTimeAsync(101);
+ expect(chat.finished).toEqual([{ status: "blocked", detail: expect.stringMatching(/^Solo stayed busy/) }]);
+ expect(chat.starts()).toBe(1);
+ expect(chat.run.turnCount).toBe(0);
+ });
+
+ it("starts the turn when the chat frees up just before the shared cap runs out", async () => {
+ vi.useFakeTimers();
+ let busy = false;
+ const chat = goalChat(async (call, lead, settle) => {
+ if (call === 1) { busy = true; throw refused("thread_busy"); }
+ lead.assistantItems.push(DONE);
+ settle({ ok: true, text: "" });
+ }, () => !busy);
+ await vi.advanceTimersByTimeAsync(GROUP_GOAL_WAIT_MAX_MS - 300);
+ busy = false;
+ chat.botChanged();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(chat.starts()).toBe(2);
+ expect(chat.run.turnCount).toBe(1);
+ expect(chat.finished).toEqual([{ status: "completed", detail: "Done." }]);
+ });
+
+ it("retries one lost race and finishes on the done marker", async () => {
+ vi.useFakeTimers();
+ const chat = goalChat(async (call, lead, settle) => {
+ if (call === 1) throw refused("thread_busy");
+ lead.assistantItems.push(DONE);
+ settle({ ok: true, text: "" });
+ });
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(chat.starts()).toBe(2);
+ expect(chat.run.turnCount).toBe(1);
+ expect(chat.finished).toEqual([{ status: "completed", detail: "Done." }]);
+ });
+});
diff --git a/server/host/one-on-one-goals.ts b/server/host/one-on-one-goals.ts
index 9202d2817d..d91bdb4b29 100644
--- a/server/host/one-on-one-goals.ts
+++ b/server/host/one-on-one-goals.ts
@@ -58,9 +58,10 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {
return deps.canStart(botId, threadId) ? "ready" : null;
}
- function waitUntilFree(goal: LiveGoal, bot: BotRecord, threadId: string): Promise<Availability> {
+ function waitUntilFree(goal: LiveGoal, bot: BotRecord, threadId: string, remainingMs: number): Promise<Availability> {
const now = availability(goal, bot.id, threadId);
if (now) return Promise.resolve(now);
+ if (remainingMs <= 0) return Promise.resolve("timed_out");
deps.cards.progress(threadId, goal.run, `${bot.name} is finishing what it is doing. This goal will continue when it is free.`);
return new Promise((resolve) => {
let settled = false;
@@ -70,7 +71,7 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {
};
const poll = setInterval(check, 1_000);
poll.unref?.();
- const cap = setTimeout(() => done("timed_out"), GROUP_GOAL_WAIT_MAX_MS);
+ const cap = setTimeout(() => done("timed_out"), remainingMs);
cap.unref?.();
const unsubscribe = store.onChange((change) => {
if ((change.type === "bot" || change.type === "bot.deleted") && change.botId === bot.id) check();
@@ -90,15 +91,18 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {
async function step(goal: LiveGoal, threadId: string, request: { id: string; origin: WorkOrigin }, bot: BotRecord, instructions: string): Promise<GoalStepResult> {
const { run } = goal;
+ const stayedBusy = (): GoalStepResult => {
+ const minutes = Math.max(1, Math.round(GROUP_GOAL_WAIT_MAX_MS / 60_000));
+ return { ran: false, replyText: "", outcome: "busy", stopReason: `${bot.name} stayed busy for ${minutes} minute${minutes === 1 ? "" : "s"}` };
+ };
+ // One wait cap for the whole step: the busy wait and the lost-slot retries share it, so neither restarts the clock.
+ const deadline = Date.now() + GROUP_GOAL_WAIT_MAX_MS;
for (;;) {
if (goal.cancelled || run.turnCount >= run.maxTurns) return { ran: false, replyText: "" };
- const free = await waitUntilFree(goal, bot, threadId);
+ const free = await waitUntilFree(goal, bot, threadId, deadline - Date.now());
if (free === "cancelled") return { ran: false, replyText: "", outcome: "cancelled" };
if (free === "unavailable") return { ran: false, replyText: "", outcome: "unavailable", stopReason: `${bot.name} is no longer available` };
- if (free === "timed_out") {
- const minutes = Math.max(1, Math.round(GROUP_GOAL_WAIT_MAX_MS / 60_000));
- return { ran: false, replyText: "", outcome: "busy", stopReason: `${bot.name} stayed busy for ${minutes} minute${minutes === 1 ? "" : "s"}` };
- }
+ if (free === "timed_out") return stayedBusy();
let settle!: (outcome: HostTurnResult) => void;
const settled = new Promise<HostTurnResult>((resolve) => { settle = resolve; });
const lead = deps.turns.begin(threadId);
@@ -118,6 +122,8 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {
const message = error instanceof Error ? error.message : String(error);
if (code === "thread_busy" || code === "thread_limit") {
outcome = "busy";
+ // The chat looked free but the turn kept losing its slot; past the wait cap the run ends blocked, as a busy wait does.
+ if (Date.now() + LOST_RACE_RETRY_MS >= deadline) return stayedBusy();
await new Promise((resolve) => setTimeout(resolve, LOST_RACE_RETRY_MS));
continue;
}