Skip to content

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

Stop one hand-off without stopping the conversation that made it

luishron12395a52f147599
diff --git a/server/coordinator.ts b/server/coordinator.ts
index b9d6bc593d..fef96e072d 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -229,6 +229,9 @@ export interface Coordinator {
liveEdges(): LiveHandoffEdge[];
/** The conversation stopped: its work and everything that work handed out end, and nothing resumes it. */
stopAwaitingDirect(threadId: string, reason?: string): void;
+ /** The person stopped one hand-off, not the conversation that made it: that work and everything it handed on end as the
+ * person's stop, and its requester hears it was stopped and goes on. Undefined for no such hand-off. */
+ stopHandoff(id: string): "stopped" | "ended" | undefined;
/** The next start goes on with this thread's turn, so a shutdown's "cut" line would be false. */
continuesAfterRestart(threadId: string): boolean;
note(id: string): string | undefined;
diff --git a/server/index.ts b/server/index.ts
index e8a0b63a98..b1341fa8f1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -11983,7 +11983,7 @@ ROUTES.push(createThreadRoutes({
companionMutationToken: () => companionMutationToken,
cliOwnerToken: () => cliOwnerToken,
pageSize, messagePage, messagePageBefore, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,
- botComputerControlSnapshot: sharedVm.botSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,
+ botComputerControlSnapshot: sharedVm.botSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, stopRefusal: (auth, threadId) => runOwners.stopRefusal(threadId, runActor(auth)), memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,
uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),
attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),
keptAttachments: CLOUD_TEAM ? undefined : keptAttachments,
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 123904a2fa..8db2bfe55d 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -352,6 +352,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/evidence(?:\.tar|\/[A-Za-z0-9-]{8,64}\/step-\d{6,12}\.jpg)?$/ },
{ methods: ["GET", "POST"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/file$/ },
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/job$/ },
+ { methods: ["POST"], path: /^\/api\/threads\/[\w-]+\/job\/[\w-]+\/stop$/ },
{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/messages$/ },
// Only says whether a line is a stop, so the Team map knows where an @everyone line goes (routes/stop-line.ts).
{ methods: ["POST"], path: /^\/api\/stop-line$/ },
diff --git a/server/routes/jobs.test.ts b/server/routes/jobs.test.ts
index d63567d96b..a36587635f 100644
--- a/server/routes/jobs.test.ts
+++ b/server/routes/jobs.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { VisibleSet } from "../bot-visibility.ts";
import { DATA_DIR } from "../config.ts";
import type { ModelSelection } from "../contracts.ts";
+import type { HandoffView } from "../coordinator.ts";
import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
import { requiredScope } from "../request-auth.ts";
@@ -24,6 +25,7 @@ afterEach(async () => {
interface Fixture {
store: Store; rows: Assignment[]; reads: number; hidden: Set<string>; subscribers: () => number; failing?: boolean;
session?: { live: boolean };
+ nodes?: Map<string, Partial<HandoffView>>; stops?: string[]; refusal?: string;
}
async function serve(f: Fixture, recheckMs = 60_000): Promise<string> {
@@ -43,7 +45,17 @@ async function serve(f: Fixture, recheckMs = 60_000): Promise<string> {
f.reads += 1;
if (f.failing) throw new Error("runtime.db is not readable");
return { scopes: f.rows.filter((row) => !row.parentId).map((row) => row.id), rows: f.rows };
+ },
+ node: (id) => f.nodes?.get(id) as HandoffView | undefined,
+ stopHandoff: (id) => {
+ const node = f.nodes?.get(id);
+ if (!node?.parentId) return undefined;
+ if (node.status === "completed" || node.status === "cancelled") return "ended";
+ f.stops?.push(id);
+ node.status = "cancelled";
+ return "stopped";
} },
+ stopRefusal: () => f.refusal ?? null,
groupThreadIsWorking: () => false,
viewerFor: () => ({ kind: "all" }),
visibleTo: () => ({ thread: (threadId: string) => !f.hidden.has(threadId) }) as VisibleSet,
@@ -195,3 +207,74 @@ describe("GET /api/threads/:id/job", () => {
await expect.poll(() => f.subscribers()).toBe(0);
});
});
+
+describe("POST /api/threads/:id/job/:assignmentId/stop", () => {
+ /** The person's turn in their chat handed work to a helper, which handed some on. */
+ const handedOut = () => {
+ const f = fixture();
+ f.stops = [];
+ f.nodes = new Map<string, Partial<HandoffView>>([
+ ["root", { id: "root", rootId: "root", threadId: f.threadId, botId: f.botId, status: "source" }],
+ ["as-help", { id: "as-help", rootId: "root", parentId: "root", threadId: "helper-work", botId: "helper", status: "running" }],
+ ["as-deep", { id: "as-deep", rootId: "root", parentId: "as-help", threadId: "scout-work", botId: "scout", status: "queued" }],
+ ["as-room", { id: "as-room", rootId: "root", parentId: "root", threadId: "room-1", groupId: "g1", botId: "helper", status: "running" }],
+ ["other", { id: "other", rootId: "other", threadId: "elsewhere", botId: "helper", status: "source" }],
+ ["as-other", { id: "as-other", rootId: "other", parentId: "other", threadId: "helper-work", botId: "helper", status: "running" }],
+ ]);
+ return f;
+ };
+ const post = async (base: string, path: string) => {
+ const response = await fetch(`${base}${path}`, { method: "POST" });
+ return { status: response.status, body: await response.json() as any };
+ };
+
+ it("is a client action, like stopping the conversation", () => {
+ expect(requiredScope("POST", "/api/threads/thread-1/job/as-1/stop")).toBe("client");
+ });
+
+ it("stops a hand-off this conversation made, a deeper one included, and says when it had already ended", async () => {
+ const f = handedOut();
+ const base = await serve(f);
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-deep/stop`)).toEqual({ status: 200, body: { ok: true, outcome: "stopped" } });
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toEqual({ status: 200, body: { ok: true, outcome: "stopped" } });
+ expect(f.stops).toEqual(["as-deep", "as-help"]);
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toEqual({ status: 200, body: { ok: true, outcome: "already-ended" } });
+ expect(f.stops).toEqual(["as-deep", "as-help"]);
+ });
+
+ it("finds nothing to stop outside this conversation's hand-offs: its own turn, room work, another conversation's, an unknown id", async () => {
+ const f = handedOut();
+ const base = await serve(f);
+ for (const id of ["root", "as-room", "as-other", "missing"]) {
+ expect(await post(base, `/api/threads/${f.threadId}/job/${id}/stop`)).toMatchObject({ status: 404 });
+ }
+ expect(await post(base, "/api/threads/elsewhere/job/as-help/stop")).toMatchObject({ status: 404 });
+ expect(f.stops).toEqual([]);
+ });
+
+ it("finds nothing where the reader may not open the conversation or the helper's thread", async () => {
+ const f = handedOut();
+ const base = await serve(f);
+ f.hidden.add("helper-work");
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toMatchObject({ status: 404 });
+ f.hidden.clear();
+ f.hidden.add(f.threadId);
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toMatchObject({ status: 404 });
+ expect(f.stops).toEqual([]);
+ });
+
+ it("refuses a reader who may not stop this conversation's work, with the code the client knows", async () => {
+ const f = handedOut();
+ f.refusal = "Only Ana can stop this request.";
+ const base = await serve(f);
+ expect(await post(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toEqual({ status: 403, body: { error: "Only Ana can stop this request.", code: "stop_not_yours" } });
+ expect(f.stops).toEqual([]);
+ });
+
+ it("leaves other methods and paths to the routes after it", async () => {
+ const f = handedOut();
+ const base = await serve(f);
+ expect(await get(base, `/api/threads/${f.threadId}/job/as-help/stop`)).toEqual({ status: 404, body: { from: "inline routes" } });
+ expect(await post(base, `/api/threads/${f.threadId}/stop`)).toEqual({ status: 404, body: { from: "inline routes" } });
+ });
+});
diff --git a/server/routes/jobs.ts b/server/routes/jobs.ts
index b5f0fbb076..3756425880 100644
--- a/server/routes/jobs.ts
+++ b/server/routes/jobs.ts
@@ -16,7 +16,9 @@ const SETTLE_MS = 150;
export interface JobRouteDeps {
store: Pick<Store, "bot" | "botByThread" | "groupByThread" | "taskByThread" | "groupTaskByThread" | "onChange">;
- coordinator: Pick<Coordinator, "job">;
+ coordinator: Pick<Coordinator, "job" | "node" | "stopHandoff">;
+ /** Why this reader may not stop this conversation's work (a shared conversation's request is its asker's), or null. */
+ stopRefusal?(auth: RequestAuth, threadId: string): string | null;
groupThreadIsWorking(groupId: string, threadId: string): boolean;
viewerFor(auth: RequestAuth): Viewer;
visibleTo(viewer: Viewer): VisibleSet;
@@ -61,7 +63,35 @@ export function createJobRoutes(deps: JobRouteDeps): RouteHandler {
});
};
- return async ({ res, url, path, method, auth, json }) => {
+ /** A hand-off made under this conversation's own turns, deeper ones included; never a turn that runs in it. */
+ const handedOutFrom = (threadId: string, id: string) => {
+ const node = coordinator.node(id);
+ if (!node?.parentId || node.groupId || node.threadId === threadId) return undefined;
+ let parent = coordinator.node(node.parentId);
+ for (let hops = 0; parent && hops < 64; hops++) {
+ if (parent.threadId === threadId) return node;
+ parent = parent.parentId ? coordinator.node(parent.parentId) : undefined;
+ }
+ return undefined;
+ };
+
+ const stop: RouteHandler = async ({ path, method, auth, res, json }) => {
+ const m = /^\/api\/threads\/([\w-]+)\/job\/([\w-]+)\/stop$/.exec(path);
+ if (!m || method !== "POST") return PASS;
+ const [, threadId, id] = m as unknown as [string, string, string];
+ const visible = deps.visibleTo(deps.viewerFor(auth));
+ const node = visible.thread(threadId) ? handedOutFrom(threadId, id) : undefined;
+ if (!node || !visible.thread(node.threadId)) return json(res, 404, { error: "no such hand-off in this conversation" });
+ const notYours = deps.stopRefusal?.(auth, threadId);
+ if (notYours) return json(res, 403, { error: notYours, code: "stop_not_yours" });
+ const outcome = coordinator.stopHandoff(id);
+ if (!outcome) return json(res, 404, { error: "no such hand-off in this conversation" });
+ return json(res, 200, { ok: true, outcome: outcome === "ended" ? "already-ended" : "stopped" });
+ };
+
+ return async (ctx) => {
+ const { res, url, path, method, auth, json } = ctx;
+ if (path.endsWith("/stop")) return stop(ctx);
const m = /^\/api\/threads\/([\w-]+)\/job$/.exec(path);
if (!m || method !== "GET") return PASS;
const threadId = m[1]!;
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 8f3937b4db..ffb09384c7 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -39,7 +39,8 @@ export interface ThreadRouteDeps {
store: Pick<Store,
| "activeLeaf" | "activePath" | "bot" | "botByThread" | "bots" | "groupByThread" | "groupTaskByThread" | "groups" | "messagesFor"
| "onChange" | "sections" | "taskByThread" | "tasks">;
- coordinator: Pick<Coordinator, "job">;
+ coordinator: Pick<Coordinator, "job" | "node" | "stopHandoff">;
+ stopRefusal?(auth: RequestAuth, threadId: string): string | null;
groupThreadIsWorking(groupId: string, threadId: string): boolean;
/** What people's lines are called in this conversation (replies.ts PersonName). */
userName(threadId: string): PersonName;
@@ -96,7 +97,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
const cursor = shown.tasks?.find((task) => task.threadId === threadId)?.lastReadMessageId;
return { ...shown, ...(tail !== undefined && limit !== undefined && tail < limit ? heldTail((size) => messagePage(threadId, size), tail, limit, cursor) : messagePage(threadId, limit)) };
};
- const jobs = createJobRoutes({ store, coordinator: deps.coordinator, groupThreadIsWorking: deps.groupThreadIsWorking, viewerFor, visibleTo, sessions });
+ const jobs = createJobRoutes({ store, coordinator: deps.coordinator, groupThreadIsWorking: deps.groupThreadIsWorking, viewerFor, visibleTo, sessions, ...(deps.stopRefusal ? { stopRefusal: deps.stopRefusal } : {}) });
const handle = async ({ req, res, url, path, method, auth, json, readBody }: RouteContext): Promise<unknown> => {
let m: RegExpMatchArray | null = null;
const member = auth.kind === "session" && auth.session.membershipAuthority === "team" ? auth.session.email : undefined;
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index 38d191215f..b2f05ade9a 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -920,6 +920,73 @@ describe("RuntimeCoordinator: stops", () => {
});
});
+describe("RuntimeCoordinator: the person stops one hand-off", () => {
+ const holdAll: Script = () => "hold";
+
+ it("ends that teammate's work and what it handed on, aborts its turn, and leaves its siblings and requester going", async () => {
+ const w = world(holdAll);
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ const { node: t } = send(w, chief, "gen-1", undefined, tester, "Test it");
+ w.coordinator.tick();
+ const { node: deeper } = w.coordinator.enqueue(builder, "gen-1", b.id, { botId: "scout", threadId: "scout-work" }, "Find the spec", {});
+ expect(w.coordinator.node(deeper.id)).toMatchObject({ parentId: b.id, botId: "scout" });
+
+ expect(w.coordinator.stopHandoff(b.id)).toBe("stopped");
+ expect(w.coordinator.node(b.id)).toMatchObject({ status: "cancelled", result: "Stopped by user" });
+ expect(w.coordinator.node(deeper.id)?.status).toBe("cancelled");
+ expect(w.host.runs.find(r => r.node.id === b.id)!.signal.aborted).toBe(true);
+ expect(w.coordinator.node(t.id)?.status).toBe("running");
+ expect(w.host.runs.find(r => r.node.id === t.id)!.signal.aborted).toBe(false);
+ expect(w.coordinator.node("gen-1")?.status).toBe("source");
+ await flush();
+ expect(w.host.reports.map(r => r.child.id)).toContain(b.id);
+ });
+
+ it("lets the requester go on with what it has once its other work is back", async () => {
+ const w = world(holdAll);
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ w.coordinator.tick();
+ ended(w, "gen-1");
+ expect(w.coordinator.stopHandoff(b.id)).toBe("stopped");
+ await flush();
+ w.coordinator.tick();
+ const resume = w.host.runs.find(r => r.node.id === "gen-1")!;
+ expect(resume.resumed).toBe(true);
+ expect(resume.text).toContain(`report on assignment ${b.id}`);
+ });
+
+ it("stops a hand-off that has not started yet", () => {
+ const w = world(holdAll);
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ expect(w.coordinator.stopHandoff(b.id)).toBe("stopped");
+ expect(w.coordinator.node(b.id)?.status).toBe("cancelled");
+ w.coordinator.tick();
+ expect(w.host.runs.filter(r => r.node.id === b.id)).toEqual([]);
+ });
+
+ it("is remembered as the person's stop for that request", () => {
+ const w = world(holdAll);
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ w.coordinator.tick();
+ w.coordinator.stopHandoff(b.id);
+ expect(() => send(w, chief, "gen-1", undefined, builder, "Build it after all", { rework: true })).toThrow("The person stopped this teammate's work on this request.");
+ expect(send(w, chief, "gen-1", undefined, tester, "Test it").node).toMatchObject({ botId: "tester", status: "queued" });
+ });
+
+ it("answers ended for work already over, and nothing for a person's own turn or an unknown id", async () => {
+ const w = world();
+ const { node: b } = send(w, chief, "gen-1", undefined, builder, "Build it");
+ w.coordinator.tick();
+ await flush();
+ expect(w.coordinator.node(b.id)?.status).toBe("completed");
+ expect(w.coordinator.stopHandoff(b.id)).toBe("ended");
+ expect(w.coordinator.node(b.id)?.status).toBe("completed");
+ expect(w.coordinator.stopHandoff("gen-1")).toBeUndefined();
+ expect(w.coordinator.node("gen-1")?.status).not.toBe("cancelled");
+ expect(w.coordinator.stopHandoff("as_missing")).toBeUndefined();
+ });
+});
+
describe("RuntimeCoordinator: a stop the person made is remembered", () => {
const tick = () => sleep(2);
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index e9ad64cee8..4a6b29583a 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -465,6 +465,18 @@ export class RuntimeCoordinator implements Coordinator {
for (const { root, work } of trees) if (root) this.rememberStop(root, work);
}
+ stopHandoff(id: string): "stopped" | "ended" | undefined {
+ this.ready();
+ const n = this.store.get(id);
+ if (!n?.parentId) return undefined;
+ 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);
+ return "stopped";
+ }
+
/** Runs a stop with its cause. A teammate's turn it ends stops that teammate's thread as well (the host's abort handler
* calls stopAwaitingDirect with no reason), and that is still this stop: a cut the system made (a waiting line going
* first, a restart, a deleted conversation) is never remembered as the person's stop. */