Skip to content

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

fix(threads): a thread opened from outside work stays with that work (#4303)

Milind Soni73ab955eb4d4
diff --git a/server/index.ts b/server/index.ts
index 1c72b26ee0..db1764172c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1054,7 +1054,7 @@ function guestEngineRefusal(threadId: string): string {
const outsideDrivenThread = (threadId: string) => outsideDriven(threadId, { webhookRun: (id) => activeRoutineRunForThread(id)?.triggerSource === "webhook",
webhookPosted: (id) => store.messagesFor(id).some((line) => line.webhookPost), handedFrom: (id) => coordinator.active().filter((node) => node.threadId === id).flatMap((node) => handedFrom(node.id)) });
/** A guest-driven turn runs in Ask whatever the bot's own level, with no shell. On a Cloud only its owner ever used, only what came in from outside is. */
-function cloudGuestDriven(threadId: string): boolean {
+/** Security: where the confinement rests on the conversation's own records, a thread opened from it would start with none, at the bot's own level. */ const outsideWorkStaysHere = (threadId: string) => cloudGuestDriven(threadId) && (Boolean(CLOUD_TEAM) || cloudHome?.solo() === true); function cloudGuestDriven(threadId: string): boolean {
if (!CLOUD_HOME) return false; if (CLOUD_TEAM) return guestDrivenTurns.has(threadId) || outsideDrivenThread(threadId);
const run = activeRoutineRunForThread(threadId);
const writer = run ? cloudRoutineAuthors?.writer(run.routineId) : undefined;
@@ -14269,7 +14269,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const from = internalSender;
const fromThreadId = internalCapability.threadId;
const owner = connectorThread(from.id, fromThreadId);
- if (!owner) return json(res, 403, { error: "source conversation does not belong to sender" });
+ if (!owner) return json(res, 403, { error: "source conversation does not belong to sender" }); if (outsideWorkStaysHere(fromThreadId)) return json(res, 403, { error: "This work came in from outside, so it can't open a new thread. Finish it here." });
if (
body.depth !== undefined &&
(!Number.isInteger(body.depth) || body.depth < 0 || body.depth !== internalCapability.depth)
diff --git a/server/outside-work-threads.e2e.test.ts b/server/outside-work-threads.e2e.test.ts
new file mode 100644
index 0000000000..8cb744a550
--- /dev/null
+++ b/server/outside-work-threads.e2e.test.ts
@@ -0,0 +1,51 @@
+// A Team Cloud confines what comes in from outside. A thread that work opens must not start free of that: on a bot at Full
+// access it would run with every tool and no approval.
+import { randomBytes } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { launchCloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+it("a confined webhook turn can't open a thread that runs unconfined; a person's own turn still can", async () => {
+ const dump = join(tmpdir(), `outside-work-${randomBytes(6).toString("hex")}.json`);
+ const fx = await launchCloudSendFixture({
+ onePasswordToken: `ops_fake-${randomBytes(8).toString("hex")}`,
+ team: { id: "team-acme-1", name: "Acme", engine: `process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(dump)};` },
+ });
+ try {
+ const team = fx.team!;
+ const ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;
+ const bot = (await team.as(ada, "POST", "/api/bots", { name: "Scout" })).body.bot as { id: string; threadId: string };
+ expect((await team.as(ada, "PATCH", `/api/bots/${bot.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);
+ const hook = (await team.as(ada, "POST", "/api/webhooks", { name: "Inbox", prompt: "Handle the event.", botId: bot.id })).body;
+ const read = () => { try { return JSON.parse(readFileSync(dump, "utf8")); } catch { return null; } };
+ const reached = (marker: string) => expect.poll(() => JSON.stringify(read()?.prompt ?? "").includes(marker), { timeout: hostTimeout(30_000) }).toBe(true);
+ const receiver = team.base.replace(/:(\d+)$/, (_: string, port: string) => `:${Number(port) + 1}`);
+ const delivered = await fetch(`${receiver}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: "webhook-marker" }) });
+ expect(delivered.status).toBe(202);
+ await reached("webhook-marker");
+ expect(read().argv).toContain("--restricted");
+
+ const runs = (await team.as(ada, "GET", "/api/routines")).body.runs as Array<{ webhookId?: string; threadId: string }>;
+ const thread = runs.find((run) => run.webhookId === hook.webhook.id)!.threadId;
+ const open = async (from: string, message: string) => fetch(`${team.base}/api/internal/threads?fromBotId=${bot.id}`, {
+ method: "POST", headers: { authorization: `Bearer ${await team.capability(bot.id, from)}`, "content-type": "application/json" },
+ body: JSON.stringify({ fromBotId: bot.id, fromThreadId: from, title: "Own thread", message }),
+ });
+ const tasks = async () => ((await team.as(ada, "GET", "/api/bots")).body.bots as Array<{ id: string; tasks: unknown[] }>).find((one) => one.id === bot.id)!.tasks.length;
+ const before = await tasks();
+ const refused = await open(thread, "started-from-outside");
+ expect(refused.status).toBe(403);
+ expect(await tasks()).toBe(before);
+ expect(JSON.stringify(read().prompt)).not.toContain("started-from-outside");
+
+ const allowed = await open(bot.threadId, "started-by-a-person");
+ expect(allowed.status).toBe(201);
+ await reached("started-by-a-person");
+ } finally {
+ await fx.close?.();
+ }
+}, hostTimeout(180_000));