Skip to content

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

Stop a room's turn once per stopId, so a resent Stop leaves the next turn running

milind-sonib597535c5ddb
diff --git a/server/room-stop-id.e2e.test.ts b/server/room-stop-id.e2e.test.ts
new file mode 100644
index 0000000000..3d0af13317
--- /dev/null
+++ b/server/room-stop-id.e2e.test.ts
@@ -0,0 +1,85 @@
+// Real server, the repository's fake ACP engine holding a room's first turn until it is stopped.
+import { spawn, type ChildProcess } from "node:child_process";
+import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, it } from "vitest";
+import { launchVerificationServer, verificationServerEnvironment } from "../scripts/control-omb.ts";
+import { waitForExit } from "./testing/cleanup.ts";
+import { openSse } from "./testing/sse.ts";
+
+it("stops a room's turn once per stopId: a resent Stop leaves the turn that started since running", async () => {
+ const fixture = await launchVerificationServer();
+ const { dataDir, url, logPath } = fixture.info;
+ const held = join(dataDir, "first-prompt-held");
+ const gate = join(dataDir, "second-prompt-gate");
+ const secondStarted = join(dataDir, "second-prompt-started");
+ let server: ChildProcess | undefined;
+ let stream: Awaited<ReturnType<typeof openSse>> | undefined;
+ const api = async (method: string, path: string, body?: unknown, status = 200) => {
+ const response = await fetch(url + path, {
+ method, headers: { "content-type": "application/json", origin: url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),
+ });
+ const value = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);
+ return value;
+ };
+ const messages = async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
+ try {
+ await waitForExit(fixture.child, { signal: "SIGTERM" });
+ const configPath = join(dataDir, "config.json");
+ const config = JSON.parse(readFileSync(configPath, "utf8"));
+ config.instances.droid = {
+ driver: "droidAgent", displayName: "Droid fixture",
+ config: { cli: fileURLToPath(new URL("./testing/fake-acp-cli.ts", import.meta.url)) },
+ environment: {
+ FACTORY_API_KEY: "fixture-only", FAKE_ACP_MODE: "echo-gated", FAKE_ACP_GATE_FILE: gate, FAKE_ACP_STARTED_FILE: secondStarted,
+ FAKE_ACP_HANG_ON: "Hold this one", FAKE_ACP_HANG_ONCE_FILE: held, FAKE_ACP_CANCEL_STOP_REASON: "end_turn",
+ },
+ };
+ writeFileSync(configPath, JSON.stringify(config));
+ const log = openSync(logPath, "a", 0o600);
+ server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {
+ cwd: fileURLToPath(new URL("..", import.meta.url)),
+ env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), stdio: ["ignore", log, log],
+ });
+ closeSync(log);
+ await expect.poll(async () => {
+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }
+ }, { timeout: 20_000 }).toBe(true);
+ stream = await openSse(`${url}/api/events`, { origin: url });
+
+ const droid = ((await api("GET", "/api/instances")).instances as any[]).find((instance) => instance.instanceId === "droid");
+ const { bot } = await api("POST", "/api/bots", { name: "Stopper", modelSelection: { instanceId: "droid", model: droid.models.default } }, 201);
+ const { group } = await api("POST", "/api/groups", { name: "Stop room", memberIds: [bot.id] }, 201);
+ await api("PATCH", `/api/groups/${group.id}/setup`, { action: "complete", cwd: null, bulletin: "", defaultResponder: { kind: "member", botId: bot.id } });
+ const threadId = group.threadId;
+ await api("POST", `/api/groups/${group.id}/messages`, { threadId, text: "Hold this one, please." }, 202);
+ await expect.poll(() => existsSync(held), { timeout: 20_000 }).toBe(true);
+ const first = (await stream.until((frame) => frame.kind === "runtime" && frame.event?.type === "turn.started" && frame.event.threadId === threadId)).event.turnId;
+
+ const stopId = "stop_room_0123456789abcdef";
+ await api("POST", `/api/groups/${group.id}/interrupt`, { threadId, stopId });
+ await stream.until((frame) => frame.kind === "runtime" && frame.event?.type === "turn.completed" && frame.event.turnId === first);
+ await expect.poll(async () => (await api("GET", "/api/bots")).groups.find((room: any) => room.id === group.id)?.working ?? false, { timeout: 20_000 }).toBe(false);
+
+ await api("POST", `/api/groups/${group.id}/messages`, { threadId, text: "Second message" }, 202);
+ await expect.poll(() => existsSync(secondStarted), { timeout: 20_000 }).toBe(true);
+ const second = (await stream.until((frame) => frame.kind === "runtime" && frame.event?.type === "turn.started"
+ && frame.event.threadId === threadId && frame.event.turnId !== first)).event.turnId;
+
+ // The phone's connection died before it read the answer, so it sends the same Stop again.
+ expect(await api("POST", `/api/groups/${group.id}/interrupt`, { threadId, stopId })).toEqual({ ok: true });
+ writeFileSync(gate, "go");
+ const done = await stream.until((frame) => frame.kind === "runtime" && frame.event?.type === "turn.completed" && frame.event.turnId === second);
+ expect(done.event.stopReason, "the resent Stop cancelled the second turn").not.toBe("cancelled");
+ await expect.poll(async () => (await messages(threadId)).some((message) => message.kind === "text" && /^echo: .*Second message/s.test(message.text ?? "")), { timeout: 20_000 }).toBe(true);
+
+ expect(await api("POST", `/api/groups/${group.id}/interrupt`, { threadId, stopId: "not an id" }, 400)).toEqual({ error: "stopId must be a client-generated id" });
+ } finally {
+ stream?.close();
+ if (server) await waitForExit(server, { signal: "SIGTERM" });
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 8b8338f6fc..7b49f0c4fb 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -25,7 +25,7 @@ import { clientGroupPatchViolation, requestSource, type RequestAuth } from "../r
import type { RoomContextTracker } from "../room-context.ts";
import { parseConversationTurnTimeout } from "../room-turn-timeout.ts";
import type { RoutineManager } from "../routines.ts";
-import { acceptedSendMatch, parseSendId, sendFingerprint, type SendSequencer } from "../send-idempotency.ts";
+import { acceptedSendMatch, parseSendId, parseStopId, sendFingerprint, StopReceipts, type SendSequencer } from "../send-idempotency.ts";
import type { SkillReview } from "../skill-review.ts";
import { assertWithinBudget } from "../spend.ts";
import type { BotRecord, GroupRecord, GroupTaskPatch, Message, Store } from "../store.ts";
@@ -109,6 +109,8 @@ export interface ChannelRouteDeps {
const createGroupTaskRequestSchema = z.object({ title: z.string().optional() });
+type StopAnswer = { status: 200 | 403 | 409; body: { ok: true } | { error: string; code?: "stop_not_yours" } };
+
export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
const {
store, cfg, broadcast, notificationListed, actorKey, threadStarters, phoneSecretSubmissions, sendSequencer, roomMemberContexts, skillReview,
@@ -119,6 +121,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
stagedSkillCleanupsForThread, rejectDeletedThreadSkillStages,
} = deps; const owners = routeRunOwners(deps.runOwners, deps.runActor);
const DESKTOP_MANAGED = deps.desktopManaged;
+ const roomStops = new StopReceipts<StopAnswer>();
const deleteRefusal = (auth: RequestAuth, groupId: string, threadId: string): { status: 403 | 404 | 409; error: string } | null => {
if (phoneSecretSubmissions.hasThread(threadId)) {
return { status: 409, error: "this task is securely saving a credential — try again when it finishes" };
@@ -634,43 +637,48 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (body.threadId !== undefined && (typeof body.threadId !== "string" || !/^[\w-]+$/.test(body.threadId))) {
return json(res, 400, { error: "threadId must be a task id" });
}
- if (body.threadId !== undefined) {
- const ownsThread = group.dm
- ? body.threadId === group.threadId
- : Boolean(store.groupTaskByThread(group.id, body.threadId));
- if (!ownsThread) {
- return json(res, 409, { error: "the channel switched tasks before it could be interrupted" });
+ const stopId = parseStopId(body.stopId);
+ if (stopId === null) return json(res, 400, { error: "stopId must be a client-generated id" });
+ const answer = await roomStops.run(stopId && `${group.id}:${stopId}`, async (): Promise<StopAnswer> => {
+ if (body.threadId !== undefined) {
+ const ownsThread = group.dm
+ ? body.threadId === group.threadId
+ : Boolean(store.groupTaskByThread(group.id, body.threadId));
+ if (!ownsThread) {
+ return { status: 409, body: { error: "the channel switched tasks before it could be interrupted" } };
+ }
}
- }
- const activeOperations = [...(groupTurnOperations.get(group.id) ?? [])]
- .filter((operation) => !operation.cancelled);
- const targetThreadIds = body.threadId !== undefined
- ? [body.threadId]
- : activeOperations.length > 0
- ? [...new Set(activeOperations.map((operation) => operation.threadId))]
- : [group.threadId];
- const interruptTargets = targetThreadIds.map((threadId) => {
- const speaker = groupSpeakers.get(threadId);
- const busy = speaker
- ? store.bot(speaker.botId)
- : threadId === group.threadId && group.busyBotId
- ? store.bot(group.busyBotId)
- : undefined;
- return {
- threadId,
- instance: busy ? runningTurnInstance(busy, threadId) : undefined,
- };
+ const activeOperations = [...(groupTurnOperations.get(group.id) ?? [])]
+ .filter((operation) => !operation.cancelled);
+ const targetThreadIds: string[] = body.threadId !== undefined
+ ? [body.threadId]
+ : activeOperations.length > 0
+ ? [...new Set(activeOperations.map((operation) => operation.threadId))]
+ : [group.threadId];
+ const interruptTargets = targetThreadIds.map((threadId) => {
+ const speaker = groupSpeakers.get(threadId);
+ const busy = speaker
+ ? store.bot(speaker.botId)
+ : threadId === group.threadId && group.busyBotId
+ ? store.bot(group.busyBotId)
+ : undefined;
+ return {
+ threadId,
+ instance: busy ? runningTurnInstance(busy, threadId) : undefined,
+ };
+ });
+ const refusal = targetThreadIds.map((threadId) => owners.stopRefusal(auth, threadId)).find(Boolean);
+ if (refusal) return { status: 403, body: { error: refusal, code: "stop_not_yours" } };
+ // Abort every queued operation before the first provider round trip, so none begins while Stop awaits.
+ for (const { threadId } of interruptTargets) cancelGroupTurnOperations(group.id, threadId);
+ for (const { threadId, instance } of interruptTargets) {
+ revokeInternalCapabilitiesForThread(threadId);
+ await instance?.adapter.interruptTurn(threadId).catch(() => {});
+ closeOpenApprovals(threadId);
+ }
+ return { status: 200, body: { ok: true } };
});
- const refusal = targetThreadIds.map((threadId) => owners.stopRefusal(auth, threadId)).find(Boolean);
- if (refusal) return json(res, 403, { error: refusal, code: "stop_not_yours" });
- // Abort every queued operation before the first provider round trip, so none begins while Stop awaits.
- for (const { threadId } of interruptTargets) cancelGroupTurnOperations(group.id, threadId);
- for (const { threadId, instance } of interruptTargets) {
- revokeInternalCapabilitiesForThread(threadId);
- await instance?.adapter.interruptTurn(threadId).catch(() => {});
- closeOpenApprovals(threadId);
- }
- return json(res, 200, { ok: true });
+ return json(res, answer.status, answer.body);
}
return PASS;
};
diff --git a/server/send-idempotency.test.ts b/server/send-idempotency.test.ts
index 161c613fcd..7367f4c8e9 100644
--- a/server/send-idempotency.test.ts
+++ b/server/send-idempotency.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import { acceptedSendMatch, parseSendId, sendFingerprint, SendSequencer } from "./send-idempotency.ts";
+import { acceptedSendMatch, parseSendId, parseStopId, sendFingerprint, SendSequencer, StopReceipts } from "./send-idempotency.ts";
import type { Message } from "./store.ts";
function userMessage(overrides: Partial<Message> = {}): Message {
@@ -110,3 +110,45 @@ describe("send idempotency", () => {
await expect(sequencer.run("same-error", "one", secondWork)).resolves.toBe(2);
});
});
+
+describe("stop receipts", () => {
+ it("reads a stopId like a sendId, and refuses a malformed one", () => {
+ expect(parseStopId(undefined)).toBeUndefined();
+ expect(parseStopId("stop_1234567890123456")).toBe("stop_1234567890123456");
+ expect(parseStopId("short")).toBeNull();
+ expect(parseStopId(42)).toBeNull();
+ });
+
+ it("stops once per key and gives every resend the first answer, while running and after", async () => {
+ const receipts = new StopReceipts<{ status: number }>();
+ let release!: () => void;
+ const stop = vi.fn(() => new Promise<{ status: number }>((resolve) => { release = () => resolve({ status: 200 }); }));
+ const first = receipts.run("room:stop_1", stop);
+ const resent = receipts.run("room:stop_1", stop);
+ release();
+ expect(await first).toEqual({ status: 200 });
+ expect(await resent).toEqual({ status: 200 });
+ expect(await receipts.run("room:stop_1", stop)).toEqual({ status: 200 });
+ expect(stop).toHaveBeenCalledTimes(1);
+ const unkeyed = vi.fn(async () => ({ status: 200 }));
+ await receipts.run("room:stop_2", unkeyed);
+ await receipts.run(undefined, unkeyed);
+ await receipts.run(undefined, unkeyed);
+ expect(unkeyed).toHaveBeenCalledTimes(3);
+ });
+
+ it("forgets an answer after keepMs, past max, and when the stop threw", async () => {
+ let now = 0;
+ const receipts = new StopReceipts<number>({ keepMs: 1_000, max: 2, now: () => now });
+ let calls = 0;
+ const stop = async () => ++calls;
+ expect(await receipts.run("a", stop)).toBe(1);
+ now = 1_000;
+ expect(await receipts.run("a", stop)).toBe(2);
+ await receipts.run("b", stop);
+ await receipts.run("c", stop);
+ expect(await receipts.run("a", stop)).toBe(5);
+ await expect(receipts.run("d", async () => { throw new Error("offline"); })).rejects.toThrow("offline");
+ expect(await receipts.run("d", stop)).toBe(6);
+ });
+});
diff --git a/server/send-idempotency.ts b/server/send-idempotency.ts
index d52e4f673d..77be39e1a8 100644
--- a/server/send-idempotency.ts
+++ b/server/send-idempotency.ts
@@ -68,3 +68,44 @@ export class SendSequencer {
export function sendFingerprint(text: string, replyToId?: string, channelMode?: "chat" | "goal"): string {
return JSON.stringify([text, replyToId ?? null, channelMode ?? null]);
}
+
+/** A Stop's `stopId`: the same client-generated form as a `sendId`. Null when one is sent but malformed. */
+export function parseStopId(value: unknown): string | undefined | null {
+ if (value === undefined) return undefined;
+ const parsed = sendIdSchema.safeParse(value);
+ return parsed.success && parsed.data !== undefined ? parsed.data : null;
+}
+
+/** One answer per Stop. A phone resends a POST when its pooled connection dies, so a Stop it resends must not stop the
+ * turn that started after the first one did: every resend of a key within `keepMs` gets the first one's answer. An
+ * attempt that throws keeps no answer, so its resend runs again. */
+export class StopReceipts<T> {
+ private readonly receipts = new Map<string, { at: number; answer: Promise<T> }>();
+ private readonly keepMs: number;
+ private readonly max: number;
+ private readonly now: () => number;
+
+ constructor(options: { keepMs?: number; max?: number; now?: () => number } = {}) {
+ this.keepMs = options.keepMs ?? 10 * 60_000;
+ this.max = options.max ?? 1_000;
+ this.now = options.now ?? Date.now;
+ }
+
+ run(key: string | undefined, stop: () => Promise<T>): Promise<T> {
+ if (!key) return stop();
+ const now = this.now();
+ for (const [old, receipt] of this.receipts) {
+ if (now - receipt.at < this.keepMs) break;
+ this.receipts.delete(old);
+ }
+ const kept = this.receipts.get(key);
+ if (kept) return kept.answer;
+ const entry = { at: now, answer: stop() };
+ this.receipts.set(key, entry);
+ if (this.receipts.size > this.max) this.receipts.delete(this.receipts.keys().next().value!);
+ entry.answer.catch(() => {
+ if (this.receipts.get(key) === entry) this.receipts.delete(key);
+ });
+ return entry.answer;
+ }
+}