Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Stopping one hand-off leaves the teammate's other work, and other requests, alone
luishron123424d72f18fab
diff --git a/server/handoff-stop.e2e.test.ts b/server/handoff-stop.e2e.test.tsnew file mode 100644index 0000000000..4133206857--- /dev/null+++ b/server/handoff-stop.e2e.test.ts@@ -0,0 +1,77 @@+// The person stops one teammate's work on their request, end to end on the scripted engine. Other work waiting in that+// teammate's thread still runs to the end, and another request in the same words, open in another conversation, can still+// hand the teammate work afterwards: the stop holds only for the request it stopped.+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { request } from "../scripts/mcp-server.ts";+import { readHandoffs } from "./testing/handoff-rows.ts";++const SETTLED = "Your downstream room requests have settled.";+const LINE = "JOB: find out where my mail lives";++it("stops one hand-off and leaves the next request in that teammate's thread going", async () => {+ const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;+ const post = (path: string) => request(path, { method: "POST", body: "{}" }, session.info.url)+ .then((body: any) => ({ status: 200, body }), (error: { status?: number }) => ({ status: error.status }));+ const api = (path: string) => request(path, {}, session.info.url) as Promise<any>;+ try {+ const asker = (await cli("new-bot", "--name", "Post")).bot;+ const research = (await cli("new-bot", "--name", "Research")).bot;+ const { task: second } = await request(`/api/bots/${asker.id}/tasks`, { method: "POST", body: JSON.stringify({ title: "Second chat" }) }, session.info.url) as any;+ const planPath = join(session.info.dataDir, "room-plan.json");+ const started = join(session.info.dataDir, "research-started");+ const ask = (message: string, { expectError = false, rework = false } = {}) => ({ arguments: { bot_ids: [research.id], message, thread: "standing", ...(rework ? { rework } : {}) }, expectError });+ writeFileSync(planPath, JSON.stringify({+ [asker.id]: { script: [+ { key: "P1", match: [LINE], steps: [ask("P-ASK: look up the mail host"), ask("Q-ASK: look up the web host")], reply: "P1: asked Research twice." },+ { key: "P2", match: [LINE], steps: [ask("L-ASK: look up the chat host")], reply: "P2: asked Research." },+ { key: "P-BACK", match: [SETTLED, "Q-ASK: web.example.test"], steps: [ask("P-AGAIN: please still look up the mail host", { expectError: true, rework: true })], reply: "P-BACK: Research was stopped." },+ { key: "L-BACK", match: [SETTLED, "L-ASK: chat.example.test"], steps: [ask("L2-ASK: and the DNS host", { rework: true })], reply: "L-BACK: asked Research again." },+ { key: "L2-DONE", match: [SETTLED, "L2-ASK: dns.example.test"], reply: "L2-DONE: all hosts found." },+ ] },+ [research.id]: { script: [+ { key: "P-ASK", match: ["P-ASK"], readyFile: started, delayMs: 30_000, reply: "P-ASK late: imap.example.test" },+ { key: "Q-ASK", match: ["Q-ASK"], reply: "Q-ASK: web.example.test" },+ { key: "L-ASK", match: ["L-ASK"], delayMs: 5_000, reply: "L-ASK: chat.example.test" },+ { key: "L2-ASK", match: ["L2-ASK"], reply: "L2-ASK: dns.example.test" },+ ] },+ }));+ const evidence = (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];+ const said = async (threadId: string, text: string) => ((await api(`/api/threads/${threadId}/messages`)).messages as any[]).some((row) => row.text === text);+ const step = (key: string) => evidence().find((turn) => turn.planKey === key)?.evidence.find((entry: any) => entry.step)?.response.result;+ const handoff = (text: string) => readHandoffs(session.info.dataDir).find((node) => node.parentId && node.text.includes(text));++ // One request hands Research two pieces of work in the one thread Post has with it: the second waits behind the first.+ await cli("send", "--bot", asker.id, "--task", asker.activeTaskId, "--text", LINE);+ await expect.poll(() => existsSync(started), { timeout: 20_000 }).toBe(true);+ await expect.poll(() => handoff("Q-ASK")?.status, { timeout: 20_000 }).toBe("queued");+ const first = handoff("P-ASK")!;+ expect(first.status).toBe("running");+ expect(handoff("Q-ASK")!.threadId).toBe(first.threadId);+ // Another request in the same words, in another conversation, has Research working too.+ await cli("send", "--bot", asker.id, "--task", second.threadId, "--text", LINE);+ await expect.poll(() => handoff("L-ASK")?.status, { timeout: 20_000 }).toBe("running");+ expect(handoff("L-ASK")!.rootId).not.toBe(first.rootId);++ expect(await post(`/api/threads/${asker.activeTaskId}/job/as_missing/stop`)).toEqual({ status: 404 });+ expect(await post(`/api/threads/${asker.activeTaskId}/job/${first.id}/stop`)).toEqual({ status: 200, body: { ok: true, outcome: "stopped" } });+ expect(handoff("P-ASK")!.status).toBe("cancelled");+ expect(handoff("Q-ASK")!.status).not.toBe("cancelled");+ expect(handoff("L-ASK")!.status).toBe("running");++ // The work waiting behind it runs to the end; then the stopped request does not get the same work back.+ await expect.poll(() => said(asker.activeTaskId, "P-BACK: Research was stopped."), { timeout: 30_000 }).toBe(true);+ expect(handoff("Q-ASK")).toMatchObject({ status: "completed", threadId: first.threadId });+ expect(JSON.stringify(step("P-BACK"))).toContain("The person stopped this teammate's work on this request.");+ // The other request, in the same words and open before the stop, still hands Research more.+ await expect.poll(() => said(second.threadId, "L2-DONE: all hosts found."), { timeout: 30_000 }).toBe(true);+ expect(step("L-BACK").isError).toBeFalsy();+ expect(handoff("L2-ASK")?.status).toBe("completed");+ } finally {+ await session.close();+ }+}, 120_000);diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.tsindex b2f05ade9a..e08386e101 100644--- a/server/runtime-coordinator.test.ts+++ b/server/runtime-coordinator.test.ts@@ -987,6 +987,70 @@ describe("RuntimeCoordinator: the person stops one hand-off", () => {});});+describe("RuntimeCoordinator: one stopped hand-off, and the rest of its teammate's work", () => {+ const holdAll: Script = () => "hold";+ const asker: RoomAddress = { botId: "tester", threadId: "tester-chat" };+ /** Like the real host: an aborted teammate turn stops that teammate's whole thread, with no cause of its own. */+ const hostStopsThreadOnAbort = (w: World, id: string) => {+ const run = w.host.runs.find(r => r.node.id === id)!;+ run.signal.addEventListener("abort", () => w.coordinator.stopAwaitingDirect(run.node.threadId), { once: true });+ };++ it("leaves another request queued in the same teammate thread to run to the end", async () => {+ const w = world(holdAll);+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Build it");+ const { node: second } = send(w, asker, "gen-2", undefined, builder, "Build the other one");+ w.coordinator.tick();+ expect(w.coordinator.node(first.id)?.status).toBe("running");+ expect(w.coordinator.node(second.id)?.status).toBe("queued");+ hostStopsThreadOnAbort(w, first.id);++ expect(w.coordinator.stopHandoff(first.id)).toBe("stopped");+ expect(w.coordinator.node(first.id)?.status).toBe("cancelled");+ expect(w.coordinator.node(second.id)?.status).not.toBe("cancelled");+ await flush();+ w.coordinator.tick();+ expect(w.coordinator.node(second.id)?.status).toBe("running");+ await w.host.release(second.id, { ok: true, text: "built the other one" });+ expect(w.coordinator.node(second.id)).toMatchObject({ status: "completed", result: "built the other one" });+ expect(w.coordinator.node("gen-2")?.status).not.toBe("cancelled");+ });++ it("holds only against the request it stopped, never another open request in the same words", () => {+ const w = world(holdAll);+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Build it");+ begun(w, asker, "gen-2");+ w.coordinator.tick();+ expect(w.coordinator.node("gen-1")?.text).toBe(w.coordinator.node("gen-2")?.text);+ w.coordinator.stopHandoff(first.id);+ expect(send(w, asker, "gen-2", undefined, { botId: "builder", threadId: "builder-other" }, "Build it").node).toMatchObject({ botId: "builder", status: "queued" });+ });++ it("holds through that request's own hand-offs, and lets a request the person makes after it through", () => {+ const w = world(holdAll);+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Build it");+ const { node: t } = send(w, chief, "gen-1", undefined, tester, "Test it");+ w.coordinator.tick();+ w.coordinator.stopHandoff(first.id);+ expect(() => w.coordinator.enqueue(tester, "gen-1", t.id, { botId: "builder", threadId: "builder-other" }, "Build it for the tests", {}))+ .toThrow("The person stopped this teammate's work on this request.");+ expect(send(w, { botId: "chief", threadId: "chief-2" }, "gen-3", undefined, builder, "Build it").node).toMatchObject({ botId: "builder" });+ });++ it("is forgotten after a day", () => {+ let now = 1_000_000;+ const host = fakeHost(holdAll);+ const w: World = { host, coordinator: new RuntimeCoordinator({ dataDir: ":memory:", host, now: () => now, log: () => {} }), logs: [] };+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Build it");+ w.coordinator.tick();+ w.coordinator.stopHandoff(first.id);+ now += 24 * 60 * 60_000;+ expect(() => send(w, chief, "gen-1", undefined, builder, "Build it again", { rework: true })).toThrow(/stopped this teammate's work/);+ now += 1;+ expect(send(w, chief, "gen-1", undefined, builder, "Build it again", { rework: true }).node).toMatchObject({ botId: "builder" });+ });+});+describe("RuntimeCoordinator: a stop the person made is remembered", () => {const tick = () => sleep(2);diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex 4a6b29583a..54c0351631 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -157,9 +157,11 @@ export class RuntimeCoordinator implements Coordinator {private readonly now: () => number;private readonly log: (line: string) => void;/** The person's stops, remembered: which bots' work on which request they stopped, and when. */- private readonly stops: Array<{ at: number; request: string; bots: Set<string> }> = [];+ private readonly stops: Array<{ at: number; request: string; bots: Set<string>; rootId?: string }> = [];/** The cause of the stop running now, if any (stopFor). */private stopCause: string | undefined;+ /** A single hand-off is being stopped (stopHandoff): its thread's other work is not part of that stop. */+ private stoppingHandoff = false;private opened = false;private prunedAt: number | undefined;@@ -458,6 +460,9 @@ export class RuntimeCoordinator implements Coordinator {/** With no reason given, the stop is the person's, unless it is part of a stop already under way: see stopFor. */stopAwaitingDirect(threadId: string, reason?: string): void {this.ready();+ // The host stops a teammate's whole thread when one of its turns is aborted; when that turn is one hand-off the person+ // stopped, the runtime already ends that hand-off and what it handed on, and other requests queued there go on.+ if (reason === undefined && this.stoppingHandoff) return;const cause = reason ?? this.stopCause ?? STOPPED_BY_USER;const stopping = cause === STOPPED_BY_USER ? this.live().filter(n => n.assignee.destination.threadId === threadId) : [];const trees = stopping.map(n => ({ root: this.store.get(n.rootId), work: this.subtree(n).filter(a => !isTerminal(a)) }));@@ -472,8 +477,10 @@ export class RuntimeCoordinator implements Coordinator {if (isTerminal(n)) return "ended";const root = this.store.get(n.rootId);const work = this.subtree(n).filter(a => !isTerminal(a));- this.stopFor(STOPPED_BY_USER, () => this.runtime.cancel(id, STOPPED_BY_USER, "stopped"));- if (root) this.rememberStop(root, work);+ const outer = this.stoppingHandoff;+ this.stoppingHandoff = true;+ try { this.stopFor(STOPPED_BY_USER, () => this.runtime.cancel(id, STOPPED_BY_USER, "stopped")); } finally { this.stoppingHandoff = outer; }+ if (root) this.rememberStop(root, work, true);return "stopped";}@@ -487,19 +494,21 @@ export class RuntimeCoordinator implements Coordinator {}/** The person's stop, remembered (scoped to that request): the bots whose work on it the stop ended don't take the same- * request from another bot again, unless the person asked again after the stop. In memory only, for a day. */- private rememberStop(root: Assignment, work: readonly Assignment[]): void {+ * request from another bot again, unless the person asked again after the stop. In memory only, for a day. A `scoped`+ * stop holds for that one request's tree only, never for another request in the same words. */+ private rememberStop(root: Assignment, work: readonly Assignment[], scoped = false): void {const request = requestKey(root);const bots = new Set(work.filter(a => this.store.get(a.id)?.status === "cancelled").map(a => a.assignee.botId));const at = this.now();while (this.stops.length && at - this.stops[0]!.at > STOP_MEMORY_MS) this.stops.shift();- if (request && bots.size) this.stops.push({ at, request, bots });+ if (request && bots.size) this.stops.push({ at, request, bots, ...(scoped ? { rootId: root.id } : {}) });}/** Work for `root`'s request was stopped for `botId`, and this request is not one the person made after that stop. */private stoppedFor(root: Assignment, botId: string): boolean {const request = requestKey(root);- return request !== "" && this.stops.some(stop => stop.request === request && stop.bots.has(botId) && root.createdAt <= stop.at && this.now() - stop.at <= STOP_MEMORY_MS);+ return request !== "" && this.stops.some(stop => stop.bots.has(botId) && this.now() - stop.at <= STOP_MEMORY_MS+ && (stop.rootId !== undefined ? stop.rootId === root.id : stop.request === request && root.createdAt <= stop.at));}activeDirect(threadId: string): boolean {