Skip to content

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

fix: allow client forks and preserve source cwd

Zhehui Bi2cace5e34a90
diff --git a/server/cloud-team.e2e.test.ts b/server/cloud-team.e2e.test.ts
index 2fd7fb8f3d..9307d97d56 100644
--- a/server/cloud-team.e2e.test.ts
+++ b/server/cloud-team.e2e.test.ts
@@ -337,3 +337,24 @@ it("a member's private chat keeps its own folder when the team's bot is given a
expect((await team.as(owner, "PATCH", `/api/bots/${bot.id}`, { cwd: null })).status).toBe(200);
}
}, hostTimeout(120_000));
+
+it("a signed-in member can fork her bot and room conversations, but not another member's private chat", async () => {
+ const own = await newThread(ada, "Ada's fork source");
+ await turn(ada, own, "A forkable question");
+ const ownAnchor = ((await messages(ada, own)).body.messages as Array<{ id: string; role: string; text?: string }>)
+ .find((message) => message.role === "user" && message.text === "A forkable question")!;
+ const botFork = await team.as(ada, "POST", `/api/bots/${bot.id}/tasks/${own}/forks`, { messageId: ownAnchor.id });
+ expect(botFork.status, JSON.stringify(botFork.body)).toBe(201);
+ expect(botFork.body.task.origin).toEqual({ threadId: own, messageId: ownAnchor.id });
+ expect((await team.as(cleo, "POST", `/api/bots/${bot.id}/tasks/${own}/forks`, { messageId: ownAnchor.id })).status).not.toBe(201);
+
+ const roomTask = await team.as(ada, "POST", `/api/groups/${roomId}/tasks`, { title: "Ada's room fork source" });
+ expect(roomTask.status, JSON.stringify(roomTask.body)).toBe(201);
+ const roomSource = roomTask.body.task.threadId as string;
+ await turn(ada, roomSource, "@Scout a room forkable question", roomId);
+ const roomAnchor = ((await messages(ada, roomSource)).body.messages as Array<{ id: string; role: string; text?: string }>)
+ .find((message) => message.role === "user" && message.text === "@Scout a room forkable question")!;
+ const roomFork = await team.as(ada, "POST", `/api/groups/${roomId}/tasks/${roomSource}/forks`, { messageId: roomAnchor.id });
+ expect(roomFork.status, JSON.stringify(roomFork.body)).toBe(201);
+ expect(roomFork.body.task.origin).toEqual({ threadId: roomSource, messageId: roomAnchor.id });
+}, hostTimeout(120_000));
diff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.ts
index b1271c520d..d8e97c297e 100644
--- a/server/fork-tasks.test.ts
+++ b/server/fork-tasks.test.ts
@@ -107,6 +107,17 @@ it("keeps the source thread's effective permissions without inheriting a pending
expect(store.projectBotForTask(bot.id, pending.threadId)?.approvalGrant).toBeUndefined();
});
+it("preserves an explicit no-folder choice when forking a bot conversation", async () => {
+ const store = await freshStore();
+ const bot = store.createBot();
+ const anchor = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "No working folder" });
+ store.patchTask(bot.id, bot.threadId, { cwd: null });
+ const fork = store.forkTask(bot.id, bot.threadId, anchor.id)!;
+ expect(fork.cwd).toBeNull();
+ expect(store.taskByThread(bot.id, fork.threadId)?.cwd).toBeNull();
+ expect(store.pinTaskCwd(bot.id, fork.threadId, join(home, "available-folder"))).toBeNull();
+});
+
it("removes copied history when registering the fork fails", async () => {
const store = await freshStore();
const bot = store.createBot();
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index e0df5603b1..0b3b02ee9d 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -93,6 +93,14 @@ describe("request source for the lockout", () => {
});
describe("scopes", () => {
+ it("lets signed-in clients fork bot and room conversations without opening other task actions", () => {
+ for (const path of ["/api/bots/bot-1/tasks/thread-1/forks", "/api/groups/room-1/tasks/thread-1/forks"]) {
+ expect(requiredScope("POST", path), path).toBe("client");
+ for (const method of ["GET", "PATCH", "DELETE"]) expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");
+ expect(requiredScope("POST", `${path}/extra`)).toBe("admin");
+ }
+ });
+
it("lets a member reach a connection card's authorize, whose handler decides who may sign in, and nothing past it", () => {
for (const [method, path] of [
["POST", "/api/bots/bot-1/connector-cards/card-1/authorize"],
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 777dc4872d..e40e9ffca4 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -358,6 +358,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["DELETE"], path: /^\/api\/bots\/[\w-]+\/queue\/[\w-]+$/ },
{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/queue\/[\w-]+\/steer$/ },
{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/tasks$/ },
+ { methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+\/forks$/ },
{ methods: ["POST", "PATCH", "DELETE"], path: /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+$/ },
{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+\/title$/ },
{ methods: ["PATCH"], path: /^\/api\/bots\/[\w-]+\/profile$/ },
@@ -396,6 +397,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["DELETE"], path: /^\/api\/groups\/[\w-]+\/queue\/[\w-]+$/ },
{ methods: ["POST"], path: /^\/api\/groups\/[\w-]+\/queue\/[\w-]+\/steer$/ },
{ methods: ["POST"], path: /^\/api\/groups\/[\w-]+\/tasks$/ },
+ { methods: ["POST"], path: /^\/api\/groups\/[\w-]+\/tasks\/[\w-]+\/forks$/ },
{ methods: ["POST", "PATCH", "DELETE"], path: /^\/api\/groups\/[\w-]+\/tasks\/[\w-]+$/ },
{ methods: ["PATCH"], path: /^\/api\/groups\/[\w-]+$/ }, // display fields only: see clientGroupPatchViolation
{ methods: ["POST"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/reactions$/ },
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 02649c22f0..a5d950e916 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -34,6 +34,7 @@ import { parseMentionPicks } from "../../shared/room-mentions.ts";
import { sameNameRefusal, sameNameRefusalForBots } from "../same-name-mentions.ts";
import { conversationLanguage } from "../server-lines.ts";
import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";
+import { forkMessageId } from "./fork-request.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { sawThread } from "../thread-presence.ts";
import { readThreadNotifications, type NotificationListed } from "./notifications.ts";
@@ -147,14 +148,12 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
const group = store.group(m[1]);
if (!group || group.dm || !store.groupTaskByThread(group.id, m[2])) return json(res, 404, { error: "no such conversation" });
const body = await readBody(req);
- if (!body || typeof body !== "object" || Array.isArray(body) ||
- Object.keys(body).some((key) => key !== "messageId") || typeof body.messageId !== "string") {
- return json(res, 400, { error: "messageId must be a string" });
- }
+ const messageId = forkMessageId(body);
+ if (messageId === null) return json(res, 400, { error: "messageId must be a string" });
const notYours = cloudThreadRefusal(auth, m[2]);
if (notYours) return json(res, 403, { error: notYours });
if (groupThreadIsWorking(group.id, m[2])) return json(res, 409, { error: "this conversation is running — wait for it to finish" });
- const task = store.forkGroupTask(group.id, m[2], body.messageId);
+ const task = store.forkGroupTask(group.id, m[2], messageId);
if (!task) return json(res, 404, { error: "no such completed message in this conversation" });
if (auth.kind === "session") threadStarters.set(task.threadId, actorKey(auth));
return json(res, 201, { group: own(groupWithThread(store.group(group.id)!)), task });
diff --git a/server/routes/fork-request.ts b/server/routes/fork-request.ts
new file mode 100644
index 0000000000..35782477c4
--- /dev/null
+++ b/server/routes/fork-request.ts
@@ -0,0 +1,6 @@
+export function forkMessageId(body: unknown): string | null {
+ if (!body || typeof body !== "object" || Array.isArray(body) ||
+ Object.keys(body).some((key) => key !== "messageId") ||
+ typeof (body as { messageId?: unknown }).messageId !== "string") return null;
+ return (body as { messageId: string }).messageId;
+}
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 3a9ccec753..58cfc61e21 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -16,6 +16,7 @@ import type { ThreadStarters } from "../thread-starters.ts";
import { titleConversationExcerpt, type ThreadTitleSource } from "../thread-title.ts";
import type { MessagePage } from "./channels.ts";
import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";
+import { forkMessageId } from "./fork-request.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { sawThread } from "../thread-presence.ts";
import { refusalBody, userError } from "../user-errors.ts";
@@ -167,14 +168,12 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
const bot = store.bot(m[1]);
if (!bot || !store.taskByThread(bot.id, m[2])) return json(res, 404, { error: "no such conversation" });
const body = await readBody(req);
- if (!body || typeof body !== "object" || Array.isArray(body) ||
- Object.keys(body).some((key) => key !== "messageId") || typeof body.messageId !== "string") {
- return json(res, 400, { error: "messageId must be a string" });
- }
+ const messageId = forkMessageId(body);
+ if (messageId === null) return json(res, 400, { error: "messageId must be a string" });
const notYours = cloudThreadRefusal(auth, m[2]);
if (notYours) return json(res, 403, { error: notYours });
if (threadBusy(bot.id, m[2])) return json(res, 409, { error: "this conversation is running — wait for it to finish" });
- const task = store.forkTask(bot.id, m[2], body.messageId);
+ const task = store.forkTask(bot.id, m[2], messageId);
if (!task) return json(res, 404, { error: "no such completed message in this conversation" });
if (auth.kind === "session") threadStarters.set(task.threadId, actorKey(auth));
return json(res, 201, { bot: publicBot(store.bot(bot.id)!), task: wireTask(task, store.bot(bot.id)!.modelSelection) });
diff --git a/server/store-forks.ts b/server/store-forks.ts
index 4c1927e398..b27125fb41 100644
--- a/server/store-forks.ts
+++ b/server/store-forks.ts
@@ -49,7 +49,7 @@ export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[
const history = forkHistory(path, messageId);
if (!history) return null;
const task = buildTask(bot, titleFromMessage(history.at(-1)?.text ?? ""), source.projectId, undefined,
- undefined, source.modelSelection, source.cwd ?? undefined);
+ undefined, source.modelSelection, source.cwd);
// A fork starts with the source's effective permissions, including an Ask mask for an unconfirmed grant.
task.approvalMode = approval.mode;
task.autoApprove = approval.mode === "auto";
diff --git a/server/task-record.ts b/server/task-record.ts
index 1308377a23..ded878bb04 100644
--- a/server/task-record.ts
+++ b/server/task-record.ts
@@ -12,7 +12,7 @@ export function threadTitleFrom(title?: string): string {
}
export function buildTask(bot: BotRecord, title?: string, projectId?: string, openedBy?: TaskOpenedBy,
- approvalMode?: "ask" | "full", modelSelection?: ModelSelection, cwd?: string): TaskRecord {
+ approvalMode?: "ask" | "full", modelSelection?: ModelSelection, cwd?: string | null): TaskRecord {
const createdAt = Date.now();
return {
threadId: newId(),
diff --git a/src/components/ChatFindBar.fork.test.ts b/src/components/ChatFindBar.fork.test.ts
index 0cc1a162b9..c774eba23a 100644
--- a/src/components/ChatFindBar.fork.test.ts
+++ b/src/components/ChatFindBar.fork.test.ts
@@ -35,7 +35,9 @@ it("focuses a fork search hit without selecting or switching the main conversati
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Matching");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 250)); });
+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({
+ type: "focusMessage", threadId: "fork", messageId: "copied", matchText: "Matching",
+ }));
expect(fixture.navigate).not.toHaveBeenCalled();
expect(fixture.dispatch).toHaveBeenCalledWith({ type: "focusMessage", threadId: "fork", messageId: "copied", matchText: "Matching" });
await act(async () => root.unmount());