Skip to content

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

feat: 支持从消息分叉会话

Zhehui Bi2885bcbf457d
diff --git a/docs/verification/evidence/conversation-fork/after.png b/docs/verification/evidence/conversation-fork/after.png
new file mode 100644
index 0000000000..2dc05c5ae7
Binary files /dev/null and b/docs/verification/evidence/conversation-fork/after.png differ
diff --git a/docs/verification/evidence/conversation-fork/before.png b/docs/verification/evidence/conversation-fork/before.png
new file mode 100644
index 0000000000..1c521aa56c
Binary files /dev/null and b/docs/verification/evidence/conversation-fork/before.png differ
diff --git a/server/fork-api.e2e.test.ts b/server/fork-api.e2e.test.ts
new file mode 100644
index 0000000000..d8f3b488eb
--- /dev/null
+++ b/server/fork-api.e2e.test.ts
@@ -0,0 +1,80 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+
+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
+
+it("forks bot and room conversations through the public API and keeps a fork after source deletion", async () => {
+ const fixture = await launchVerificationServer();
+ const dump = join(fixture.info.dataDir, "fake-claude-dump.json");
+ const { url } = fixture.info;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(url + path, {
+ method,
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+ const messages = async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as Array<{ id: string; role: string; kind: string; text?: string }>;
+
+ try {
+ const bot = (await runControlOmb(["new-bot", "--name", "Fork Tester", "--url", url]) as any).bot;
+ const sourceThreadId = bot.activeTaskId as string;
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Plan the release", threadId: sourceThreadId })).status).toBe(202);
+ await expect.poll(async () => (await messages(sourceThreadId)).some((message) => message.role === "bot" && message.kind === "text" && message.text?.includes("hello from fake claude")), { timeout: 20_000 }).toBe(true);
+ const anchor = (await messages(sourceThreadId)).find((message) => message.role === "user" && message.text === "Plan the release")!;
+ const forked = await api("POST", `/api/bots/${bot.id}/tasks/${sourceThreadId}/forks`, { messageId: anchor.id });
+ expect(forked.status).toBe(201);
+ const forkThreadId = forked.body.task.threadId as string;
+ expect(forked.body.task.origin).toEqual({ threadId: sourceThreadId, messageId: anchor.id });
+ expect(forked.body.task.unread).toBe(false);
+ const sourceMessages = await messages(sourceThreadId);
+ expect((await messages(forkThreadId)).map((message) => message.id)).toEqual(sourceMessages.slice(0, sourceMessages.findIndex((message) => message.id === anchor.id) + 1).map((message) => message.id));
+ expect((await api("GET", `/api/search?q=Plan%20the%20release&threadId=${forkThreadId}`)).body.hits.some((hit: { messageId: string }) => hit.messageId === anchor.id)).toBe(true);
+ expect((await api("POST", `/api/bots/${bot.id}/tasks/${sourceThreadId}/forks`, { messageId: "missing" })).status).toBe(404);
+ const uploaded = await fetch(url + "/api/attachments", { method: "POST", headers: { "content-type": "image/png" }, body: PNG });
+ expect(uploaded.status).toBe(201);
+ const imagePath = (await uploaded.json() as { path: string }).path;
+ const repliesBeforeImage = (await messages(sourceThreadId)).filter((message) => message.role === "bot" && message.kind === "text").length;
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: `Image\n<attached-image path="${imagePath}" name="dot.png" />`, threadId: sourceThreadId })).status).toBe(202);
+ await expect.poll(async () => (await messages(sourceThreadId)).filter((message) => message.role === "bot" && message.kind === "text").length, { timeout: 20_000 }).toBeGreaterThan(repliesBeforeImage);
+ await expect.poll(async () => (await api("GET", "/api/bots?messages=0")).body.bots.find((candidate: any) => candidate.id === bot.id)?.busy, { timeout: 20_000 }).toBe(false);
+ const imageMessage = (await messages(sourceThreadId)).find((message) => message.role === "user" && message.text?.includes("dot.png"))!;
+ const imageFork = await api("POST", `/api/bots/${bot.id}/tasks/${sourceThreadId}/forks`, { messageId: imageMessage.id });
+ expect(imageFork.status).toBe(201);
+ expect((await api("DELETE", `/api/bots/${bot.id}/tasks/${sourceThreadId}`)).status).toBe(200);
+ expect((await messages(forkThreadId)).some((message) => message.id === anchor.id)).toBe(true);
+ const inheritedImage = await fetch(url + `/api/threads/${imageFork.body.task.threadId}/messages/${imageMessage.id}/file`, {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: imagePath }),
+ });
+ const imageBytes = Buffer.from(await inheritedImage.arrayBuffer());
+ expect(inheritedImage.status, imageBytes.toString()).toBe(200);
+ expect(imageBytes).toEqual(PNG);
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Continue the fork", threadId: forkThreadId })).status).toBe(202);
+ await expect.poll(async () => (await messages(forkThreadId)).some((message) => message.role === "bot" && message.text?.includes("hello from fake claude")), { timeout: 20_000 }).toBe(true);
+ const prompt = JSON.stringify(JSON.parse(readFileSync(dump, "utf8")).prompt);
+ expect(prompt).toContain("Plan the release");
+ expect(prompt).toContain("Continue the fork");
+
+ const room = (await runControlOmb(["new-channel", "--name", "Fork Room", "--members", bot.id, "--url", url]) as any).channel;
+ const roomThreadId = room.activeTaskId as string;
+ expect((await api("POST", `/api/groups/${room.id}/messages`, { text: "Room question", threadId: roomThreadId })).status).toBe(202);
+ await expect.poll(async () => (await messages(roomThreadId)).some((message) => message.role === "bot" && message.kind === "text"), { timeout: 20_000 }).toBe(true);
+ const roomAnchor = (await messages(roomThreadId)).find((message) => message.role === "user" && message.text === "Room question")!;
+ const roomFork = await api("POST", `/api/groups/${room.id}/tasks/${roomThreadId}/forks`, { messageId: roomAnchor.id });
+ expect(roomFork.status).toBe(201);
+ expect(roomFork.body.task.origin).toEqual({ threadId: roomThreadId, messageId: roomAnchor.id });
+ expect((await api("POST", `/api/groups/${room.id}/read`, { threadId: roomFork.body.task.threadId })).status).toBe(200);
+ expect((await api("DELETE", `/api/groups/${room.id}/tasks/${roomThreadId}`)).status).toBe(200);
+ expect((await messages(roomFork.body.task.threadId)).some((message) => message.id === roomAnchor.id)).toBe(true);
+ expect((await api("POST", `/api/groups/${room.id}/messages`, { text: "Continue the room fork", threadId: roomFork.body.task.threadId })).status).toBe(202);
+ await expect.poll(async () => (await messages(roomFork.body.task.threadId)).some((message) => message.role === "bot" && message.kind === "text"), { timeout: 20_000 }).toBe(true);
+ const roomPrompt = JSON.stringify(JSON.parse(readFileSync(dump, "utf8")).prompt);
+ expect(roomPrompt).toContain("Room question");
+ expect(roomPrompt).toContain("Continue the room fork");
+ } finally {
+ await fixture.close();
+ }
+}, 90_000);
diff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.ts
new file mode 100644
index 0000000000..1d969d16d7
--- /dev/null
+++ b/server/fork-tasks.test.ts
@@ -0,0 +1,74 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+
+let home: string;
+
+async function freshStore() {
+ home = mkdtempSync(join(tmpdir(), "omb-fork-tasks-"));
+ vi.resetModules();
+ vi.stubEnv("HOME", home);
+ vi.stubEnv("USERPROFILE", home);
+ const { Store } = await import("./store.ts");
+ return new Store(() => ({ instanceId: "claude", model: "m" }));
+}
+
+afterEach(async () => {
+ const { closeMessageDb } = await import("./message-db.ts");
+ closeMessageDb();
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+});
+
+it("forks a bot conversation at a completed message and keeps it after deleting the source", async () => {
+ const store = await freshStore();
+ const bot = store.createBot();
+ const sourceThreadId = bot.threadId;
+ store.appendMessage(sourceThreadId, { role: "user", kind: "text", text: "First question" });
+ const answer = store.appendMessage(sourceThreadId, { role: "bot", kind: "text", text: "First answer" });
+ const expectedHistory = store.activePath(sourceThreadId).map((message) => [message.id, message.text]);
+ store.appendMessage(sourceThreadId, { role: "user", kind: "text", text: "Unrelated follow-up" });
+
+ const fork = store.forkTask(bot.id, sourceThreadId, answer.id);
+ expect(fork).toMatchObject({ origin: { threadId: sourceThreadId, messageId: answer.id }, unread: false, lastReadMessageId: answer.id });
+ expect(store.bot(bot.id)?.threadId).toBe(sourceThreadId);
+ expect(store.activePath(fork!.threadId).map((message) => [message.id, message.text])).toEqual(expectedHistory);
+
+ store.appendMessage(sourceThreadId, { role: "bot", kind: "text", text: "Source changed" });
+ store.patchMessage(sourceThreadId, answer.id, { text: "Edited after the fork" });
+ expect(store.activePath(fork!.threadId).map((message) => [message.id, message.text])).toEqual(expectedHistory);
+ const nested = store.forkTask(bot.id, fork!.threadId, answer.id);
+ expect(nested?.origin).toEqual({ threadId: fork!.threadId, messageId: answer.id });
+ store.deleteTask(bot.id, sourceThreadId);
+ expect(store.taskByThread(bot.id, fork!.threadId)).toBeTruthy();
+ expect(store.activePath(fork!.threadId).map((message) => [message.id, message.text])).toEqual(expectedHistory);
+ store.appendMessage(fork!.threadId, { role: "user", kind: "text", text: "Independent follow-up" });
+ expect(store.activePath(fork!.threadId).at(-1)?.text).toBe("Independent follow-up");
+ const { closeMessageDb } = await import("./message-db.ts");
+ closeMessageDb();
+ const { Store } = await import("./store.ts");
+ const reopened = new Store(() => ({ instanceId: "claude", model: "m" }));
+ expect(reopened.taskByThread(bot.id, fork!.threadId)?.origin).toEqual({ threadId: sourceThreadId, messageId: answer.id });
+ expect(reopened.activePath(fork!.threadId).map((message) => message.text)).toEqual([...expectedHistory.map(([, text]) => text), "Independent follow-up"]);
+});
+
+it("forks a room conversation into a normal room task", async () => {
+ const store = await freshStore();
+ const bot = store.createBot();
+ const room = store.createGroup("Review", [bot.id]);
+ const sourceThreadId = room.threadId;
+ const anchor = store.appendMessage(sourceThreadId, { role: "user", kind: "text", text: "Review this" });
+ const reply = store.appendMessage(sourceThreadId, { role: "bot", kind: "text", text: "Review complete" });
+
+ const fork = store.forkGroupTask(room.id, sourceThreadId, anchor.id);
+ expect(fork?.origin).toEqual({ threadId: sourceThreadId, messageId: anchor.id });
+ expect(store.group(room.id)?.threadId).toBe(sourceThreadId);
+ expect(store.groupTasks(room.id).map((task) => task.threadId)).toContain(fork!.threadId);
+ expect(store.activePath(fork!.threadId).map((message) => message.id)).toEqual([anchor.id]);
+ const replyFork = store.forkGroupTask(room.id, sourceThreadId, reply.id);
+ expect(store.activePath(replyFork!.threadId).map((message) => message.id)).toEqual([anchor.id, reply.id]);
+ expect(store.forkGroupTask(room.id, sourceThreadId, "missing")).toBeNull();
+ store.deleteGroupTask(room.id, sourceThreadId);
+ expect(store.groupTaskByThread(room.id, fork!.threadId)).toBeTruthy();
+});
diff --git a/server/message-db.ts b/server/message-db.ts
index 8c74d95d38..605d6ee116 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -447,7 +447,7 @@ export function insertMessage(threadId: string, message: Message): void {
}
/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */
-export function importThread(threadId: string, messages: Message[], activeLeafId: string | null, relinked?: ReadonlyArray<{ id: string; parentId: string | null }>): void {
+export function importThread(threadId: string, messages: Message[], activeLeafId: string | null, relinked?: ReadonlyArray<{ id: string; parentId: string | null }>, beforeCommit?: () => void): void {
transaction((database) => {
if (!relinked && (database.prepare("SELECT 1 FROM messages WHERE thread_id = ? LIMIT 1").get(threadId) ||
database.prepare("SELECT 1 FROM thread_state WHERE thread_id = ?").get(threadId))) {
@@ -461,6 +461,7 @@ export function importThread(threadId: string, messages: Message[], activeLeafId
const link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");
for (const row of relinked ?? []) link.run(row.parentId, threadId, row.id);
setActiveLeaf(threadId, activeLeafId);
+ beforeCommit?.();
});
}
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 802672862e..1429f5a61a 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -41,7 +41,7 @@ export type MessagePage = { messages: Array<Message | Record<string, unknown>>;
export interface ChannelRouteDeps {
store: Pick<Store,
| "group" | "groupTaskByThread" | "bot" | "switchGroupTask" | "patchGroupTask" | "patchGroup" | "messagesFor" | "groupTasks" | "deleteGroupTasks" | "deleteGroup"
- | "createGroupTask" | "appendMessage">;
+ | "createGroupTask" | "forkGroupTask" | "appendMessage">;
cfg: Pick<AppConfig, "budgets">;
/** What people's lines are called in this conversation (replies.ts PersonName). */
userName(threadId: string): PersonName;
@@ -137,6 +137,24 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
let m: RegExpMatchArray | null = null;
const routines = deps.routines();
+ m = path.match(/^\/api\/groups\/([\w-]+)\/tasks\/([\w-]+)\/forks$/);
+ if (m && method === "POST") {
+ 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 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);
+ 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 });
+ }
+
m = path.match(/^\/api\/groups\/([\w-]+)\/tasks$/);
if (m && method === "POST") {
const body = await readBody(req);
@@ -278,15 +296,20 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (m && method === "POST") {
const room = store.group(m[1]);
if (!room) return json(res, 404, { error: "no such room" });
- sawThread(room.threadId);
- deps.threadRead?.(auth, room.threadId);
+ const body = await readBody(req);
+ const threadId = body?.threadId ?? room.threadId;
+ if (typeof threadId !== "string" || !store.groupTaskByThread(room.id, threadId)) {
+ return json(res, 404, { error: "no such channel task" });
+ }
+ sawThread(threadId);
+ deps.threadRead?.(auth, threadId);
const personal = deps.personMarkRoom?.(auth, room, false);
if (personal) {
- readThreadNotifications(room.threadId, broadcast, notificationListed(auth));
+ readThreadNotifications(threadId, broadcast, notificationListed(auth));
return json(res, 200, { group: personal });
}
- const group = store.patchGroup(room.id, { unread: false, ...readCursor(room.threadId) })!;
- readThreadNotifications(room.threadId, broadcast, notificationListed(auth));
+ const group = store.patchGroup(room.id, { unread: false, ...(threadId === room.threadId ? readCursor(threadId) : {}) })!;
+ readThreadNotifications(threadId, broadcast, notificationListed(auth));
broadcast({ kind: "group", group: publicGroupState(group) });
return json(res, 200, { group: own(publicGroupState(group)) });
}
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 7b8f58fb5c..e85bc0e3e7 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -28,7 +28,7 @@ export interface TaskRouteDeps {
store: Pick<Store,
| "bot" | "bots" | "taskByThread" | "project" | "projectBotForTask" | "patchTask" | "patchProject" | "tasks"
| "switchTaskModel" | "switchTask" | "retitleTask" | "reorderProjects" | "refreshTaskPermissions" | "messagesTail"
- | "messagesFor" | "deleteTasks" | "deleteProject" | "createTask" | "createProject">;
+ | "messagesFor" | "deleteTasks" | "deleteProject" | "createTask" | "forkTask" | "createProject">;
/** On a Cloud home only the owner changes how a bot asks for approval. */
cloudHome: boolean;
/** The desktop app owns this server, so a loopback caller is its owner. */
@@ -162,6 +162,24 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
return json(res, method === "POST" ? 201 : 200, { project, bot: publicBot(bot) });
}
+ m = path.match(/^\/api\/bots\/([\w-]+)\/tasks\/([\w-]+)\/forks$/);
+ if (m && method === "POST") {
+ 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 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);
+ 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) });
+ }
+
m = path.match(/^\/api\/bots\/([\w-]+)\/tasks$/);
if (m && method === "POST") {
const body = await readBody(req);
diff --git a/server/store.ts b/server/store.ts
index 71601fd75c..e62d1a588c 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -1015,6 +1015,28 @@ export class Store {
return task;
}
+ forkGroupTask(groupId: string, sourceThreadId: string, messageId: string): GroupTaskRecord | null {
+ const group = this.group(groupId);
+ const source = this.groupTaskByThread(groupId, sourceThreadId);
+ if (!group || !source) return null;
+ const history = this.forkHistory(sourceThreadId, messageId);
+ if (!history) return null;
+ const createdAt = Date.now();
+ const task: GroupTaskRecord = {
+ threadId: newId(),
+ title: titleFromMessage(history.at(-1)?.text ?? ""),
+ createdAt,
+ updatedAt: createdAt,
+ origin: { threadId: sourceThreadId, messageId },
+ ...(source.pinnedCwd !== undefined ? { pinnedCwd: source.pinnedCwd } : {}),
+ };
+ mdb.importThread(task.threadId, history, messageId, undefined, () => this.commitGroupChange(group, "the forked thread", () => {
+ group.tasks = [task, ...(group.tasks ?? [])];
+ }));
+ this.emit({ type: "group", groupId });
+ return task;
+ }
+
switchGroupTask(groupId: string, threadId: string): GroupRecord | null {
const group = this.group(groupId);
const task = group?.tasks?.find((candidate) => candidate.threadId === threadId);
@@ -1154,6 +1176,13 @@ export class Store {
return path.reverse();
}
+ private forkHistory(threadId: string, messageId: string): Message[] | null {
+ const path = this.activePath(threadId);
+ const anchor = path.findIndex((message) => message.id === messageId);
+ if (anchor < 0 || path[anchor]?.kind !== "text" || !["user", "bot"].includes(path[anchor]!.role)) return null;
+ return structuredClone(path.slice(0, anchor + 1));
+ }
+
markTerminalAssistantMessage(threadId: string, turnId: string): Message | null {
const path = this.activePath(threadId);
for (let i = path.length - 1; i >= 0; i -= 1) {
@@ -2181,6 +2210,23 @@ export class Store {
return task;
}
+ forkTask(botId: string, sourceThreadId: string, messageId: string): TaskRecord | null {
+ const bot = this.bot(botId);
+ const source = this.taskByThread(botId, sourceThreadId);
+ if (!bot || !source) return null;
+ const history = this.forkHistory(sourceThreadId, messageId);
+ if (!history) return null;
+ const task = this.buildTask(bot, titleFromMessage(history.at(-1)?.text ?? ""), source.projectId, undefined,
+ undefined, source.modelSelection, source.cwd ?? undefined);
+ task.origin = { threadId: sourceThreadId, messageId };
+ task.lastReadMessageId = messageId;
+ mdb.importThread(task.threadId, history, messageId, undefined, () => this.commitBotChange(bot, "the forked thread", () => {
+ bot.tasks = [task, ...(bot.tasks ?? [])];
+ }));
+ this.emit({ type: "bot", botId });
+ return task;
+ }
+
private buildTask(bot: BotRecord, title?: string, projectId?: string, openedBy?: TaskOpenedBy, approvalMode?: "ask" | "full",
modelSelection?: ModelSelection, cwd?: string): TaskRecord {
const createdAt = Date.now();
diff --git a/shared/wire.ts b/shared/wire.ts
index bffaf851be..9770725606 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -134,10 +134,17 @@ export interface BotMovedTo {
/** One task = one conversation with its own context, thread and provider
* session. */
+export interface ForkOrigin {
+ threadId: string;
+ messageId: string;
+}
+
export interface WireTask extends InboxTask {
/** Outstanding handoffs, not an active provider turn. */
waitingForTeammates?: boolean;
threadId: string;
+ /** The completed message whose visible history seeded this conversation. */
+ origin?: ForkOrigin;
title: string;
createdAt: number;
/** The first message already drove a title attempt for this thread, so a
@@ -817,6 +824,8 @@ export type GroupDefaultResponder =
/** One independent conversation inside a user-created channel. */
export interface GroupTask {
threadId: string;
+ /** The completed message whose visible history seeded this conversation. */
+ origin?: ForkOrigin;
title: string;
createdAt: number;
pinnedCwd?: string | null;
diff --git a/src/App.tsx b/src/App.tsx
index 901f22964d..881779fd10 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -16,6 +16,7 @@ import { parseComputerHelp } from "@/lib/computer-control";
import { Sidebar } from "@/components/Sidebar";
import { ChatView } from "@/components/ChatView";
import { GroupView } from "@/components/GroupView";
+import { ForkPanel } from "@/components/ForkPanel";
import { SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";
import { preloadConnectedApps } from "@/lib/connected-apps";
import {
@@ -149,7 +150,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const notificationFeed = useNotificationFeed() && !remoteClient;
const advanced = useAdvancedMode();
const roomPanelOpen = useRoomPanelShown({ group, state, simple: !advanced && !remoteClient });
- const sidePanelOpen = (Boolean(bot) && (state.settingsOpen || state.computerOpen || state.inspectorOpen || state.activityOpen)) || roomPanelOpen || (notificationFeed && state.notificationsOpen) || inboxShown;
+ const sidePanelOpen = (Boolean(bot) && (state.settingsOpen || state.computerOpen || state.inspectorOpen || state.activityOpen)) || Boolean(state.forkPanel) || roomPanelOpen || (notificationFeed && state.notificationsOpen) || inboxShown;
const collapseSidebar = sidePanelOpen && !sidebarAndPanelFit;
const calendarFocus = state.activeView === "routines" && state.routinesFocus.view === "calendar";
const notificationTray = notificationFeed && !calendarFocus;
@@ -419,10 +420,11 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
/>
)
)}
- {roomPanelOpen && group && (
+ {state.forkPanel && <ForkPanel />}
+ {!state.forkPanel && roomPanelOpen && group && (
<RoomPanel key={`room:${group.id}`} group={group} overlay={notificationFeed && state.notificationsOpen && !twoSidePanelsFit} />
)}
- {!remoteClient && state.inspectorOpen && bot && <InspectorPanel key={bot.threadId} bot={bot} />}
+ {!remoteClient && !state.forkPanel && state.inspectorOpen && bot && <InspectorPanel key={bot.threadId} bot={bot} />}
{!remoteClient && state.activityOpen && bot && <ActivityPanel key={`activity:${bot.id}`} bot={bot} />}
{inboxShown && <InboxPanel />}
{notificationTray && state.notificationsOpen && <NotificationsPanel />}
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index e4c00cc6ac..2f6f5d7ebc 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -9,6 +9,7 @@ import { ACTION_ICON, ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions,
import { copyText } from "@/lib/copy-text";
import { ReactAction, ReactionChips } from "@/components/Reactions";
import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu";
+import { forkMessageItem, ForkLinks } from "@/components/ForkMessage";
import { useSpeech } from "@/lib/tts/useSpeech";
import { localSystemVoiceActive } from "@/lib/local-voice";
import { computerStartLine, useScreensWhile } from "@/lib/computer-start";
@@ -342,6 +343,10 @@ const Bubble = memo(function Bubble({
onReply: (message: Message) => void;
}) {
const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer } = useChatRows(), busy = onRegenerate || versions ? use(ChatBusyContext) : false;
+ const { state } = useStore();
+ const sourceBusy = state.bots.find((candidate) => candidate.id === botId)?.tasks?.find((task) => task.threadId === threadId)?.busy ?? false;
+ const forkAction = message.kind === "text" && !message.id.startsWith("optimistic-")
+ ? [forkMessageItem({ kind: "bot", ownerId: botId, threadId, messageId: message.id }, dispatch, sourceBusy)] : [];
const remoteClient = window.ogb?.remoteClient?.active === true;
const peer = peerLine(message) ?? peerRequest(message, botId);
const user = message.role === "user" && !peer;
@@ -420,7 +425,7 @@ const Bubble = memo(function Bubble({
const togglePin = () =>
dispatch({ type: "updateTask", botId, threadId, patch: { pinnedMessageId: pinned ? "" : message.id } });
const botActions = !user && (
- <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={simple ? [...replyAndCopy(() => onReply(message), text), ...botMenu] : botMenu}>
+ <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={simple ? [...replyAndCopy(() => onReply(message), text), ...botMenu, ...forkAction] : [...botMenu, ...forkAction]}>
{!simple && <ReplyAction onReply={() => onReply(message)} />}
{canReact && !peer && <ReactAction threadId={threadId} message={message} />}
{!simple && text && <CopyButton text={text} className={messageActionClass} />}
@@ -445,6 +450,7 @@ const Bubble = memo(function Bubble({
? () => onStartEdit(message.id) : undefined,
pin: remoteClient ? undefined : { pinned, onToggle: togglePin },
}),
+ ...forkAction,
]}
>
{!simple && <ReplyAction onReply={() => onReply(message)} />}
@@ -573,6 +579,7 @@ const Bubble = memo(function Bubble({
</span>
</div>
<ReactionChips threadId={threadId} message={message} bots={bots} align={user ? "end" : "start"} canReact={canReact} />
+ <ForkLinks kind="bot" ownerId={botId} threadId={threadId} messageId={message.id} />
{forks.length > 1 && (
<div className="mt-1 flex items-center gap-0.5 pr-1 text-[12px] text-ink-secondary">
<button
diff --git a/src/components/ForkMessage.tsx b/src/components/ForkMessage.tsx
new file mode 100644
index 0000000000..d4eb4ae9f0
--- /dev/null
+++ b/src/components/ForkMessage.tsx
@@ -0,0 +1,37 @@
+import { GitFork } from "lucide-react";
+import type { Dispatch } from "react";
+import { ACTION_ICON, type MessageMenuItem } from "./MessageActions";
+import { t } from "@/lib/i18n";
+import { useStore, type Action } from "@/state/store";
+
+type Owner = { kind: "bot" | "group"; ownerId: string; threadId: string; messageId: string };
+
+export function forkMessageItem(owner: Owner, dispatch: Dispatch<Action>, disabled: boolean): MessageMenuItem {
+ return {
+ key: "fork-conversation",
+ icon: <GitFork {...ACTION_ICON} />,
+ label: t("chat.forkConversation"),
+ disabled,
+ onSelect: () => dispatch({ type: "forkMessage", ...owner }),
+ };
+}
+
+export function ForkLinks(owner: Owner) {
+ const { state, dispatch } = useStore();
+ const tasks = owner.kind === "bot"
+ ? state.bots.find((bot) => bot.id === owner.ownerId)?.tasks
+ : state.groups.find((group) => group.id === owner.ownerId)?.tasks;
+ const forks = tasks?.filter((task) => task.origin?.threadId === owner.threadId && task.origin.messageId === owner.messageId) ?? [];
+ if (!forks.length) return null;
+ return (
+ <div className="mt-1 flex flex-wrap gap-1" data-testid="fork-links">
+ {forks.map((fork) => (
+ <button key={fork.threadId} type="button"
+ className="rounded-full border border-hairline px-2 py-0.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"
+ onClick={() => dispatch({ type: "openForkPanel", kind: owner.kind, ownerId: owner.ownerId, threadId: fork.threadId })}>
+ <GitFork size={12} className="mr-1 inline" />{t("chat.openFork", { title: fork.title })}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsx
new file mode 100644
index 0000000000..b5d035e3c5
--- /dev/null
+++ b/src/components/ForkPanel.tsx
@@ -0,0 +1,33 @@
+import { X } from "lucide-react";
+import { useStore } from "@/state/store";
+import { t } from "@/lib/i18n";
+import { ChatView } from "./ChatView";
+import { GroupView } from "./GroupView";
+
+export function ForkPanel() {
+ const { state, dispatch } = useStore();
+ const panel = state.forkPanel;
+ if (!panel) return null;
+ const bot = panel.kind === "bot" ? state.bots.find((candidate) => candidate.id === panel.ownerId) : undefined;
+ const group = panel.kind === "group" ? state.groups.find((candidate) => candidate.id === panel.ownerId) : undefined;
+ const task = bot?.tasks?.find((candidate) => candidate.threadId === panel.threadId)
+ ?? group?.tasks?.find((candidate) => candidate.threadId === panel.threadId);
+ const openedBot = bot && task ? { ...bot, threadId: panel.threadId, messages: panel.messages, activeLeafId: panel.activeLeafId, hasMore: false } : null;
+ const openedGroup = group && task ? { ...group, threadId: panel.threadId, messages: panel.messages, hasMore: false } : null;
+
+ return (
+ <aside aria-label={t("chat.forkPanel")} className="relative flex h-full w-[min(48vw,640px)] min-w-[360px] flex-col border-l border-hairline bg-app">
+ <div className="flex items-center justify-between border-b border-hairline px-4 py-2 text-sm font-medium text-ink">
+ <span className="truncate">{task?.title ?? t("chat.forkPanel")}</span>
+ <button type="button" aria-label={t("chat.closeForkPanel")} className="rounded p-1 text-ink-secondary hover:bg-raised hover:text-ink"
+ onClick={() => dispatch({ type: "closeForkPanel" })}><X size={16} /></button>
+ </div>
+ <div className="min-h-0 flex-1">
+ {panel.loading ? <p className="p-4 text-sm text-ink-secondary">{t("chat.loadingFork")}</p>
+ : openedBot ? <ChatView key={panel.threadId} bot={openedBot} />
+ : openedGroup ? <GroupView key={panel.threadId} group={openedGroup} />
+ : <p className="p-4 text-sm text-ink-secondary">{t("chat.forkUnavailable")}</p>}
+ </div>
+ </aside>
+ );
+}
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 79d825a924..116e89ff3e 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -39,6 +39,7 @@ import { CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyActio
import { ReactAction, ReactionChips, useCanReact } from "./Reactions";
import { ClusterLabel } from "./RoomClusterLabel";
import { roomPin, useBotMessageMenu, userMessageMenu } from "./message-menu";
+import { forkMessageItem, ForkLinks } from "./ForkMessage";
import { RawMarkdownView, RawToggleAction } from "./RawMarkdownToggle";
import { SpeakButton } from "./SpeakButton";
import { useSpeech } from "@/lib/tts/useSpeech";
@@ -171,6 +172,8 @@ function RoomTextMessage({
const speakerBot = members.find((member) => member.id === m.from?.botId);
const botText = rawText; const teammates = useTeammates(); const peers = useMemo(() => [...members, ...teammates.peers], [members, teammates]);
const pin = roomPin(group, m, dispatch);
+ const forkAction = !group.dm && m.kind === "text" && !m.id.startsWith("optimistic-")
+ ? [forkMessageItem({ kind: "group", ownerId: group.id, threadId: group.threadId, messageId: m.id }, dispatch, roomThreadWorking(group, group.threadId))] : [];
const botMenu = useBotMessageMenu({
text: botText,
botId: speakerBot?.id,
@@ -187,7 +190,7 @@ function RoomTextMessage({
const blocks = useMemo(() => simple && !user && !viewRaw && botText.trim() ? splitReplyBlocks(botText) : null, [simple, user, viewRaw, botText]);
const tabled = Boolean(blocks?.some((block) => block.kind === "table"));
const botActions = !user && (
- <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={botMenu}>
+ <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={[...botMenu, ...forkAction]}>
<ReplyAction onReply={() => onReply(m)} />
{canReact && m.from && <ReactAction threadId={group.threadId} message={m} />}
{botText && <CopyButton text={botText} className={messageActionClass} />}
@@ -200,7 +203,7 @@ function RoomTextMessage({
{speaker && <div className="mb-0.5 px-1 text-[12px] font-medium text-ink-secondary">{speaker}</div>}
<div className={cn("flex w-full items-end gap-1.5", user ? "justify-end" : "justify-start")}>
{user && (
- <MessageActions side="user" menu={userMessageMenu({ messageId: m.id, pin })}>
+ <MessageActions side="user" menu={[...userMessageMenu({ messageId: m.id, pin }), ...forkAction]}>
<ReplyAction onReply={() => onReply(m)} />
{Boolean(display.trim()) && <CopyButton text={display} className={messageActionClass} />}
</MessageActions>
@@ -298,6 +301,7 @@ function RoomTextMessage({
</span>
</div>
<ReactionChips threadId={group.threadId} message={m} bots={members} align={user ? "end" : "start"} canReact={canReact} />
+ <ForkLinks kind="group" ownerId={group.id} threadId={group.threadId} messageId={m.id} />
{!user && m.routedBy && <RoutedByLine routedBy={m.routedBy} />}
</div>
);
diff --git a/src/locales/en.json b/src/locales/en.json
index 1354da1a07..05a77e4c78 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2537,6 +2537,11 @@
"chat.claudeUpdate.tryAgain": "Try updating again",
"chat.send": "Send",
"chat.editMessage": "Edit message",
+ "chat.forkConversation": "Fork conversation from here",
+ "chat.forkPanel": "Forked conversation",
+ "chat.closeForkPanel": "Close forked conversation",
+ "chat.loadingFork": "Loading conversation…",
+ "chat.forkUnavailable": "Conversation unavailable.",
"chat.reply": "Reply",
"chat.replyToMessage": "Reply to message",
"chat.react": "Add reaction",
@@ -2590,6 +2595,7 @@
"chat.openConversationWith": "Open the conversation with {name}",
"chat.handoffDoneWhen": "Done when: {criteria}",
"chat.openThread": "Open #{title}",
+ "chat.openFork": "Open fork: {title}",
"chat.openThreadOn": "Open #{title} on {name}",
"chat.sentDirectly": "Sent to {name} directly: it isn't in this room.",
"chat.sentDirectlyNotInRoom": "Sent to {name} directly: it isn't in {room}.",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 425207c199..89ac87477a 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -2366,6 +2366,11 @@
"chat.claudeUpdate.tryAgain": "重新尝试更新",
"chat.send": "发送",
"chat.editMessage": "编辑消息",
+ "chat.forkConversation": "从此处分叉会话",
+ "chat.forkPanel": "分叉会话",
+ "chat.closeForkPanel": "关闭分叉会话",
+ "chat.loadingFork": "正在加载会话…",
+ "chat.forkUnavailable": "会话不可用。",
"chat.reply": "回复",
"chat.replyToMessage": "回复消息",
"chat.react": "添加表情回应",
@@ -2418,6 +2423,7 @@
"chat.openConversationWith": "打开与 {name} 的对话",
"chat.handoffDoneWhen": "完成标准:{criteria}",
"chat.openThread": "打开 #{title}",
+ "chat.openFork": "打开分叉会话:{title}",
"chat.openThreadOn": "在 {name} 上打开 #{title}",
"chat.sentDirectly": "已直接发给 {name}:它不在这个群组聊天中。",
"chat.sentDirectlyNotInRoom": "已直接发给 {name}:它不在「{room}」。",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index f45cebd9f5..510276ed4b 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -195,6 +195,7 @@ export interface Group extends Pick<WireGroup, "memberContext" | "queue"> {
export interface GroupTask {
threadId: string;
+ origin?: import("../../shared/wire").ForkOrigin;
title: string;
createdAt: number;
pinnedCwd?: string | null;
@@ -218,6 +219,7 @@ export interface ModelSelection {
export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks"> {
waitingForTeammates?: boolean; sharedChat?: true;
threadId: string;
+ origin?: import("../../shared/wire").ForkOrigin;
routineRunId?: string;
projectId?: string;
title: string;
@@ -581,6 +583,7 @@ export interface AppState {
botCreationPending: boolean;
computerOpen: boolean;
inspectorOpen: boolean;
+ forkPanel: { kind: "bot" | "group"; ownerId: string; threadId: string; messages: Message[]; activeLeafId: string | null; loading: boolean } | null;
activityOpen: boolean;
/** Shared across bots. Unpinned, it closes on a chat switch and when another side panel opens; pinned, it stays open. */
notificationsOpen: boolean;
@@ -695,6 +698,12 @@ export type Action =
}
| { type: "deleteGroup"; groupId: string }
| { type: "newGroupTask"; groupId: string }
+ | { type: "forkMessage"; kind: "bot" | "group"; ownerId: string; threadId: string; messageId: string }
+ | { type: "openForkPanel"; kind: "bot" | "group"; ownerId: string; threadId: string }
+ | { type: "forkPanelLoaded"; threadId: string; messages: Message[]; activeLeafId: string | null }
+ | { type: "forkPanelMessage"; threadId: string; message: Message; patch?: true }
+ | { type: "forkPanelActive"; threadId: string; activeLeafId: string }
+ | { type: "closeForkPanel" }
| { type: "switchGroupTask"; groupId: string; threadId: string }
| { type: "renameGroupTask"; groupId: string; threadId: string; title: string }
| { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean; title: string }
@@ -992,6 +1001,27 @@ export function reducer(state: AppState, action: Action): AppState {
};
case "showChat":
return state.activeView === "chat" ? state : { ...state, activeView: "chat" };
+ case "forkMessage":
+ return state;
+ case "openForkPanel":
+ return { ...state, settingsOpen: false, computerOpen: false, inspectorOpen: false, activityOpen: false,
+ forkPanel: { kind: action.kind, ownerId: action.ownerId, threadId: action.threadId, messages: [], activeLeafId: null, loading: true } };
+ case "forkPanelLoaded":
+ if (state.forkPanel?.threadId !== action.threadId) return state;
+ return { ...state, forkPanel: { ...state.forkPanel, messages: [...action.messages, ...state.forkPanel.messages.filter((message) => !action.messages.some((loaded) => loaded.id === message.id))], activeLeafId: state.forkPanel.activeLeafId ?? action.activeLeafId, loading: false } };
+ case "forkPanelMessage": {
+ const panel = state.forkPanel;
+ if (panel?.threadId !== action.threadId) return state;
+ const messages = panel.messages.some((message) => message.id === action.message.id)
+ ? panel.messages.map((message) => message.id === action.message.id ? action.message : message)
+ : action.patch ? panel.messages : [...panel.messages, action.message];
+ return { ...state, forkPanel: { ...panel, messages, activeLeafId: action.patch ? panel.activeLeafId : action.message.id } };
+ }
+ case "forkPanelActive":
+ return state.forkPanel?.threadId === action.threadId
+ ? { ...state, forkPanel: { ...state.forkPanel, activeLeafId: action.activeLeafId } } : state;
+ case "closeForkPanel":
+ return state.forkPanel ? { ...state, forkPanel: null } : state;
case "showTeamMap":
case "showFiles": case "showWebPanel":
return {
@@ -1086,6 +1116,7 @@ export function reducer(state: AppState, action: Action): AppState {
unreadDivider: openedUnreadDivider(state, room.threadId, room.unread, room.messages, room.lastReadMessageId, room.hasMore),
activeView: "chat",
selectedId: action.id,
+ forkPanel: null,
groups: state.groups.map((g) => (g.id === action.id ? { ...g, unread: false } : g)),
};
}
@@ -1099,6 +1130,7 @@ export function reducer(state: AppState, action: Action): AppState {
: state.unreadDivider,
activeView: "chat",
selectedId: action.id,
+ forkPanel: null,
},
action.id,
"switch",
@@ -1723,7 +1755,7 @@ export function reducer(state: AppState, action: Action): AppState {
})), threadId, message.at, true);
}
case "switchGroupTask":
- return state.selectedId === action.groupId && state.activeView === "chat" ? closeTrayUnlessShown(state, action.groupId, action.threadId) : state;
+ return state.selectedId === action.groupId && state.activeView === "chat" ? { ...closeTrayUnlessShown(state, action.groupId, action.threadId), forkPanel: null } : state;
case "newGroupTask":
return state.selectedId === action.groupId && state.activeView === "chat" ? closeUnpinnedTray(state) : state;
case "deleteTask":
@@ -1734,7 +1766,7 @@ export function reducer(state: AppState, action: Action): AppState {
return action.cwd !== undefined ? state : { ...closeUnpinnedTray(state), selectedId: action.botId, activeView: "chat" };
case "switchTask": {
const { [action.threadId]: _old, ...backgroundThreadEvents } = state.backgroundThreadEvents;
- return updateBot({ ...closeTrayUnlessShown(state, action.botId, action.threadId), backgroundThreadEvents, selectedId: action.botId, activeView: "chat", revealThread: { threadId: action.threadId, nonce: (state.revealThread?.nonce ?? 0) + 1 } }, action.botId,
+ return updateBot({ ...closeTrayUnlessShown(state, action.botId, action.threadId), backgroundThreadEvents, selectedId: action.botId, forkPanel: null, activeView: "chat", revealThread: { threadId: action.threadId, nonce: (state.revealThread?.nonce ?? 0) + 1 } }, action.botId,
(bot) => ({ ...bot, switchingTo: action.threadId }));
}
case "switchTaskFailed":
@@ -1881,6 +1913,7 @@ export const initialState: AppState = {
botCreationPending: false,
computerOpen: false,
inspectorOpen: false,
+ forkPanel: null,
activityOpen: false,
notificationsOpen: false,
notificationsPinned: false,
@@ -2850,6 +2883,42 @@ export function StoreProvider({ children }: { children: ReactNode }) {
});
break;
}
+ case "forkMessage": {
+ const owner = action.kind === "bot" ? "bots" : "groups";
+ void api<{ bot?: BotAnnouncement; group?: Partial<Group> & { id: string }; task: { threadId: string } }>(
+ `/api/${owner}/${action.ownerId}/tasks/${action.threadId}/forks`,
+ { method: "POST", body: JSON.stringify({ messageId: action.messageId }) },
+ ).then((result) => {
+ if (result.bot) dispatch({ type: "botPatched", bot: result.bot });
+ if (result.group) dispatch({ type: "groupPatched", group: result.group });
+ dispatch({ type: "openForkPanel", kind: action.kind, ownerId: action.ownerId, threadId: result.task.threadId });
+ }).catch(showError);
+ break;
+ }
+ case "openForkPanel": {
+ if (action.kind === "bot") {
+ void api(`/api/bots/${action.ownerId}/read`, { method: "POST", body: JSON.stringify({ threadId: action.threadId }) }).catch(() => {});
+ } else {
+ void api(`/api/groups/${action.ownerId}/read`, { method: "POST", body: JSON.stringify({ threadId: action.threadId }) }).catch(() => {});
+ }
+ const load = async () => {
+ const messages: Message[] = [];
+ let before: string | undefined;
+ let activeLeafId: string | null = null;
+ for (;;) {
+ const page = await api<{ messages: Message[]; hasMore?: boolean; activeLeafId: string | null }>(
+ `/api/threads/${action.threadId}/messages?limit=200${before ? `&before=${encodeURIComponent(before)}` : ""}`,
+ );
+ messages.unshift(...page.messages);
+ activeLeafId = page.activeLeafId;
+ if (!page.hasMore || !page.messages.length) break;
+ before = page.messages[0]!.id;
+ }
+ rawDispatch({ type: "forkPanelLoaded", threadId: action.threadId, messages, activeLeafId });
+ };
+ void load().catch(showError);
+ break;
+ }
case "renameTask":
api(`/api/bots/${action.botId}/tasks/${action.threadId}`, {
method: "PATCH",
@@ -3127,6 +3196,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
break;
case "message": {
rawDispatch({ type: "messageAdded", threadId: frame.threadId, message: frame.message as Message });
+ rawDispatch({ type: "forkPanelMessage", threadId: frame.threadId, message: frame.message as Message });
if (frame.message?.role === "user" && typeof frame.message.queueId === "string") {
rawDispatch({
type: "consumePendingQueued",
@@ -3142,20 +3212,24 @@ export function StoreProvider({ children }: { children: ReactNode }) {
}
case "message.patch":
rawDispatch({ type: "messagePatched", threadId: frame.threadId, message: frame.message as Message });
+ rawDispatch({ type: "forkPanelMessage", threadId: frame.threadId, message: frame.message as Message, patch: true });
break;
case "thread":
rawDispatch({ type: "threadActive", threadId: frame.threadId, activeLeafId: frame.activeLeafId });
+ rawDispatch({ type: "forkPanelActive", threadId: frame.threadId, activeLeafId: frame.activeLeafId });
break;
case "bot": {
const bot = frame.bot as BotAnnouncement;
const selected = stateRef.current.bots.find((candidate) => candidate.id === bot.id);
const shown = selected?.switchingTo ?? selected?.threadId;
- const selectedTask = bot.tasks?.find((task) => task.threadId === shown);
+ const panel = stateRef.current.forkPanel;
+ const readThreadId = panel?.kind === "bot" && panel.ownerId === bot.id ? panel.threadId : shown;
+ const selectedTask = bot.tasks?.find((task) => task.threadId === readThreadId);
if (bot.id === stateRef.current.selectedId && stateRef.current.activeView === "chat" && document.hasFocus() &&
(selectedTask?.unread || (!bot.tasks && bot.unread))) {
if (selectedTask) selectedTask.unread = false;
bot.unread = botShowsUnread(bot);
- fetch(`/api/bots/${bot.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId: shown }) }).catch(() => {});
+ fetch(`/api/bots/${bot.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId: readThreadId }) }).catch(() => {});
}
rawDispatch({
type: "botPatched",
@@ -3167,7 +3241,9 @@ export function StoreProvider({ children }: { children: ReactNode }) {
const group = frame.group as Partial<Group> & { id: string };
if (group.unread && group.id === stateRef.current.selectedId && document.hasFocus()) {
group.unread = false;
- fetch(`/api/groups/${group.id}/read`, { method: "POST" }).catch(() => {});
+ const panel = stateRef.current.forkPanel;
+ const threadId = panel?.kind === "group" && panel.ownerId === group.id ? panel.threadId : undefined;
+ fetch(`/api/groups/${group.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});
}
rawDispatch({ type: "groupPatched", group });
break;