Skip to content

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

feat: 支持用 /fork 创建会话分支

Zhehui Bi8c020f09ba0e
diff --git a/server/fork-api.e2e.test.ts b/server/fork-api.e2e.test.ts
index 3237520fdc..75188154d5 100644
--- a/server/fork-api.e2e.test.ts
+++ b/server/fork-api.e2e.test.ts
@@ -22,11 +22,25 @@ it("forks bot and room conversations through the public API and keeps a fork aft
try {
const bot = (await runControlOmb(["new-bot", "--name", "Fork Tester", "--url", url]) as any).bot;
const sourceThreadId = bot.activeTaskId as string;
+ const botForkPath = `/api/bots/${bot.id}/tasks/${sourceThreadId}/forks`;
+ const blankThread = await api("POST", `/api/bots/${bot.id}/tasks`, { select: false });
+ expect(blankThread.status).toBe(201);
+ expect(await api("POST", `/api/bots/${bot.id}/tasks/${blankThread.body.task.threadId}/forks`, { latest: true })).toMatchObject({
+ status: 404, body: { errorKey: "serverError.forkNoText" },
+ });
+ for (const invalid of [{}, { latest: false }, { latest: true, messageId: "ambiguous" }]) {
+ expect((await api("POST", botForkPath, invalid)).status).toBe(400);
+ }
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")!;
+ 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 transcript = await messages(sourceThreadId);
+ const anchor = transcript.find((message) => message.role === "user" && message.text === "Plan the release")!;
+ const latest = transcript.findLast((message) => message.role === "bot" && message.kind === "text")!;
const notificationsBeforeFork = (await api("GET", "/api/notifications")).body.notifications.map((entry: { id: string }) => entry.id);
- const forked = await api("POST", `/api/bots/${bot.id}/tasks/${sourceThreadId}/forks`, { messageId: anchor.id });
+ const latestFork = await api("POST", botForkPath, { latest: true });
+ expect(latestFork).toMatchObject({ status: 201, body: { task: { origin: { threadId: sourceThreadId, messageId: latest.id } } } });
+ const forked = await api("POST", botForkPath, { messageId: anchor.id });
expect(forked.status).toBe(201);
expect((await api("GET", "/api/notifications")).body.notifications.map((entry: { id: string }) => entry.id)).toEqual(notificationsBeforeFork);
const forkThreadId = forked.body.task.threadId as string;
@@ -62,12 +76,17 @@ it("forks bot and room conversations through the public API and keeps a fork aft
const room = (await runControlOmb(["new-channel", "--name", "Fork Room", "--members", bot.id, "--url", url]) as any).channel;
const roomThreadId = room.activeTaskId as string;
+ const roomForkPath = `/api/groups/${room.id}/tasks/${roomThreadId}/forks`;
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 });
+ const roomFork = await api("POST", roomForkPath, { messageId: roomAnchor.id });
expect(roomFork.status).toBe(201);
expect(roomFork.body.task.origin).toEqual({ threadId: roomThreadId, messageId: roomAnchor.id });
+ const roomLatest = (await messages(roomThreadId)).findLast((message) => message.role === "bot" && message.kind === "text")!;
+ expect(await api("POST", roomForkPath, { latest: true })).toMatchObject({
+ status: 201, body: { task: { origin: { threadId: roomThreadId, messageId: roomLatest.id } } },
+ });
expect((await api("POST", `/api/groups/${room.id}/read`)).status).toBe(200);
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);
diff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.ts
index d8e97c297e..9b61af2fa0 100644
--- a/server/fork-tasks.test.ts
+++ b/server/fork-tasks.test.ts
@@ -74,6 +74,23 @@ it("forks a room conversation into a normal room task", async () => {
expect(store.groupTaskByThread(room.id, fork!.threadId)).toBeTruthy();
});
+it("uses the newest text on the selected branch for a fork without an explicit message", async () => {
+ const store = await freshStore();
+ const bot = store.createBot();
+ const { threadId } = store.createTask(bot.id)!;
+ expect(store.forkTask(bot.id, threadId, undefined)).toBeNull();
+ const question = store.appendMessage(threadId, { role: "user", kind: "text", text: "First question" });
+ const reply = store.appendMessage(threadId, { role: "bot", kind: "text", text: "First answer" });
+ const followUp = store.appendMessage(threadId, { role: "user", kind: "text", text: "Follow up on the first answer" });
+ const activity = store.appendMessage(threadId, { role: "bot", kind: "activity" });
+ store.appendMessage(threadId, { role: "bot", kind: "text", text: "Another branch", parentId: question.id });
+ expect(store.setActiveLeaf(threadId, reply.id)).toBe(activity.id);
+
+ const fork = store.forkTask(bot.id, threadId, undefined);
+ expect(fork?.origin).toEqual({ threadId, messageId: followUp.id });
+ expect(store.activePath(fork!.threadId).map((message) => message.id)).toEqual([question.id, reply.id, followUp.id]);
+});
+
it("keeps a background room fork unread when the shown conversation is read", async () => {
const store = await freshStore();
const room = store.createGroup("Review", [store.createBot().id]);
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index d50261c8e0..7054f8ad23 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -37,7 +37,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 { FORK_BUSY, FORK_NO_TEXT, parseForkRequest } from "./fork-request.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { sawThread } from "../thread-presence.ts";
import { readThreadNotifications, type NotificationListed } from "./notifications.ts";
@@ -155,14 +155,13 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
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);
- const messageId = forkMessageId(body);
- if (messageId === null) return json(res, 400, { error: "messageId must be a string" });
+ const fork = parseForkRequest(await readBody(req));
+ if (!fork) return json(res, 400, { error: "Provide a string messageId or set latest to true" });
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], messageId);
- if (!task) return json(res, 404, { error: "no such completed message in this conversation" });
+ if (groupThreadIsWorking(group.id, m[2])) return json(res, 409, FORK_BUSY);
+ const task = store.forkGroupTask(group.id, m[2], fork.messageId);
+ if (!task) return json(res, 404, fork.messageId === undefined ? FORK_NO_TEXT : { 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 } satisfies RoomTaskCreateResponse);
}
diff --git a/server/routes/fork-request.ts b/server/routes/fork-request.ts
index 35782477c4..b09fa352cc 100644
--- a/server/routes/fork-request.ts
+++ b/server/routes/fork-request.ts
@@ -1,6 +1,8 @@
-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;
+export function parseForkRequest(body: unknown): { messageId?: string } | null {
+ if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).length !== 1) return null;
+ if ("messageId" in body && typeof body.messageId === "string") return { messageId: body.messageId };
+ return "latest" in body && body.latest === true ? {} : null;
}
+
+export const FORK_BUSY = { error: "this conversation is running — wait for it to finish", errorKey: "serverError.forkBusy" };
+export const FORK_NO_TEXT = { error: "This conversation has no text message to fork from yet.", errorKey: "serverError.forkNoText" };
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index b21b2a27be..7245dbede5 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -16,7 +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 { FORK_BUSY, FORK_NO_TEXT, parseForkRequest } from "./fork-request.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { madeThread, sawThread } from "../thread-presence.ts";
import { refusalBody, userError } from "../user-errors.ts";
@@ -169,14 +169,13 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
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);
- const messageId = forkMessageId(body);
- if (messageId === null) return json(res, 400, { error: "messageId must be a string" });
+ const fork = parseForkRequest(await readBody(req));
+ if (!fork) return json(res, 400, { error: "Provide a string messageId or set latest to true" });
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], messageId);
- if (!task) return json(res, 404, { error: "no such completed message in this conversation" });
+ if (threadBusy(bot.id, m[2])) return json(res, 409, FORK_BUSY);
+ const task = store.forkTask(bot.id, m[2], fork.messageId);
+ if (!task) return json(res, 404, fork.messageId === undefined ? FORK_NO_TEXT : { 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) } satisfies TaskResponse);
}
diff --git a/server/store-forks.ts b/server/store-forks.ts
index 60c92b508e..ed7dbb3a40 100644
--- a/server/store-forks.ts
+++ b/server/store-forks.ts
@@ -6,10 +6,11 @@ import { buildTask } from "./task-record.ts";
import { titleFromMessage } from "./thread-title.ts";
import type { ApprovalMode } from "../shared/approval-mode.ts";
-function forkHistory(path: Message[], messageId: string): Message[] | null {
- 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));
+function forkHistory(path: Message[], sourceMessageId: string | undefined) {
+ const anchor = path.findLastIndex((message) => message.kind === "text" && (message.role === "user" || message.role === "bot")
+ && (sourceMessageId === undefined || message.id === sourceMessageId));
+ if (anchor < 0) return null;
+ return { history: structuredClone(path.slice(0, anchor + 1)), messageId: path[anchor]!.id };
}
function registerImportedFork<T extends { threadId: string }>(task: T, history: Message[], messageId: string,
@@ -25,10 +26,11 @@ function registerImportedFork<T extends { threadId: string }>(task: T, history:
}
}
-export function createGroupFork(source: GroupTaskRecord, path: Message[], messageId: string,
+export function createGroupFork(source: GroupTaskRecord, path: Message[], sourceMessageId: string | undefined,
register: (task: GroupTaskRecord) => void): GroupTaskRecord | null {
- const history = forkHistory(path, messageId);
- if (!history) return null;
+ const fork = forkHistory(path, sourceMessageId);
+ if (!fork) return null;
+ const { history, messageId } = fork;
const createdAt = Date.now();
const task: GroupTaskRecord = {
threadId: newId(),
@@ -43,11 +45,12 @@ export function createGroupFork(source: GroupTaskRecord, path: Message[], messag
return task;
}
-export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[], messageId: string,
+export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[], sourceMessageId: string | undefined,
approval: { mode: ApprovalMode; alwaysAllow: string[] },
register: (task: TaskRecord) => void): TaskRecord | null {
- const history = forkHistory(path, messageId);
- if (!history) return null;
+ const fork = forkHistory(path, sourceMessageId);
+ if (!fork) return null;
+ const { history, messageId } = fork;
const task = buildTask(bot, titleFromMessage(history.at(-1)?.text ?? ""), source.projectId, undefined,
undefined, source.modelSelection, source.cwd);
// A fork starts with the source's effective permissions, including an Ask mask for an unconfirmed grant.
diff --git a/server/store.ts b/server/store.ts
index e345bd4272..ec88d403ff 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -967,7 +967,7 @@ export class Store {
return task;
}
- forkGroupTask(groupId: string, sourceThreadId: string, messageId: string): GroupTaskRecord | null {
+ forkGroupTask(groupId: string, sourceThreadId: string, messageId: string | undefined): GroupTaskRecord | null {
const group = this.group(groupId);
const source = this.groupTaskByThread(groupId, sourceThreadId);
if (!group || !source) return null;
@@ -2153,7 +2153,7 @@ export class Store {
return task;
}
- forkTask(botId: string, sourceThreadId: string, messageId: string): TaskRecord | null {
+ forkTask(botId: string, sourceThreadId: string, messageId: string | undefined): TaskRecord | null {
const bot = this.own(botId);
const source = this.taskByThread(botId, sourceThreadId);
if (!bot || !source) return null;
diff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.ts
index 93e57f76af..9196e988d2 100644
--- a/src/components/Composer.slash.test.ts
+++ b/src/components/Composer.slash.test.ts
@@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Bot } from "@/state/store";
import { restoreComposerDraft } from "@/lib/drafts";
+const dispatch = vi.hoisted(() => vi.fn());
const ENGINE = "claude-3f0c2b1e-9d1a-4c55-8a51-0a3a6f1e2b7c";
vi.mock("@/state/store", async (importOriginal) => {
const original = await importOriginal<typeof import("@/state/store")>();
@@ -14,7 +15,7 @@ vi.mock("@/state/store", async (importOriginal) => {
state: { ...original.initialState, bots: [bot], instances: [{
instanceId: ENGINE, driverKind: "claudeAgent", displayName: "Claude", capabilities: { agentsMcp: true },
}] },
- dispatch: vi.fn(),
+ dispatch,
}) };
});
vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
@@ -41,6 +42,7 @@ describe("the / menu in the composer", () => {
let container: HTMLDivElement;
beforeEach(() => {
+ dispatch.mockClear();
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
restoreComposerDraft(draftId, { text: "", attachments: [] });
@@ -70,7 +72,26 @@ describe("the / menu in the composer", () => {
it("offers the built-in commands and skills at the start of a message", () => {
fill("/");
- expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/standup"]);
+ expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/standup"]);
+ });
+
+ it("submits a complete /fork as a fork action instead of a message", () => {
+ const input = fill("/fork");
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({
+ type: "forkMessage", kind: "bot", ownerId: bot.id, threadId: bot.threadId,
+ }));
+ expect(input.value).toBe("");
+ });
+
+ it("completes /fo with Tab and forks on submission", () => {
+ const input = fill("/fo");
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })));
+ expect(input.value.trim()).toBe("/fork");
+ expect(dispatch).not.toHaveBeenCalled();
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "forkMessage" }));
});
it("offers only skills after a space later in the message, and puts the pick in place", () => {
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index e89c4eae91..fe0ccdee90 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -173,6 +173,8 @@ export function Composer({
draftId,
!group && bot && !state.config?.team ? `bot:${bot.id}` : undefined,
);
+ const forkOwnerId = singleRow || group?.dm || !threadId ? undefined : group?.id ?? bot?.id;
+ const forkCommand = forkOwnerId && /^\/fork\s*$/i.test(text), forkPending = useRef(false);
const attachmentPending = useDraftAttachmentPending(draftId);
const failedSends = useFailedComposerSends(draftId); const picks = mentionPicksFor(draftId);
const [channelMode, setChannelMode] = useComposerChannelMode(draftId);
@@ -326,9 +328,10 @@ export function Composer({
label: "/setup",
description: t("composer.command.setupDesc"),
}, { kind: "command", id: "burst", label: "/burst", description: t("composer.command.burstDesc") });
- available.push(...skillSlashCommands(slashSkills));
+ if (builtIns && forkOwnerId) available.push({ kind: "command", id: "fork", label: "/fork", description: t("composer.command.forkDesc") });
+ available.push(...skillSlashCommands(slashSkills).filter((command) => !(builtIns && forkOwnerId && command.id === "fork")));
return available.filter((command) => slashCommandMatches(command, slash.query));
- }, [slash, dismissedSlashAt, group, bot, canLearn, state.instances, locale, slashSkills]);
+ }, [slash, dismissedSlashAt, group, bot, canLearn, state.instances, locale, slashSkills, forkOwnerId]);
const commandPickerOpen = commandCandidates.length > 0;
const mention = mentionQueryAt(text, caret); const teammates = useTeammates(); const viewer = useViewerEmail();
@@ -518,7 +521,8 @@ export function Composer({
// A one-to-one bot at work: Enter does the chosen follow-up and Ctrl/⌘ with it the other one. Rooms keep their own queue.
const followUpFor = (alternate: boolean) => resolveFollowUp({ running: busy && !group && Boolean(bot), alternate, preferred: followUpDefault, canSteer }) ?? undefined;
const steersNow = group ? canSteer : followUpFor(false) === "steer";
- const sendNames = sendLabels({ simple: !advanced, busy, canSteer: steersNow, name: busyName, sendLabel });
+ const sendNames = forkCommand ? { label: t("composer.command.forkDesc"), title: t("composer.command.forkDesc") }
+ : sendLabels({ simple: !advanced, busy, canSteer: steersNow, name: busyName, sendLabel });
const retryFailedSend = (failed: FailedComposerSend) => {
const failedMode = failed.channelMode ?? "chat";
if (failed.requestText.includes("<attached-image ") && !imageTargetsSupport(failed.requestText, failedMode)) {
@@ -550,7 +554,15 @@ export function Composer({
}
};
const send = (followUp: FollowUp | undefined = followUpFor(false)) => {
- if (locked || attachmentPending) return;
+ if (locked || attachmentPending || (forkCommand && forkPending.current)) return;
+ if (forkCommand && forkOwnerId) {
+ forkPending.current = true;
+ stopDictation();
+ editText("");
+ dispatch({ type: "forkMessage", kind: group ? "group" : "bot", ownerId: forkOwnerId, threadId,
+ onSettled: () => { forkPending.current = false; } });
+ return;
+ }
if (
attachments.some((attachment) => attachment.kind === "image") &&
!imageTargetsSupport(effectiveText, effectiveChannelMode)
@@ -841,7 +853,7 @@ export function Composer({
onKeyDown={(e) => {
// An input method's confirming Enter and arrows pick its own candidates, not a mention or command.
if (imeComposing(e.nativeEvent)) return;
- if (commandPickerOpen) {
+ if (commandPickerOpen && !(forkCommand && sendsMessage(e.nativeEvent, sendKey))) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const delta = e.key === "ArrowDown" ? 1 : -1;
@@ -969,9 +981,9 @@ export function Composer({
{callShown && bot && !group && <CallButton bot={bot} placement="composer" fill={advanced || singleRow ? undefined : slot.fill} ink={slot.ink} inverse={singleRow} modeMenu={!stacked} />}
{callShown && group && !advanced && <GroupCallButton group={group} members={members ?? []} placement="composer" fill={slot.fill} ink={slot.ink} />}
{hasContent && !locked && (
- <ComposerSendButton compact={simpleDock} waits={busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}
+ <ComposerSendButton compact={simpleDock} waits={!forkCommand && busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}
disabled={attachmentPending} onSend={(alternate) => send(followUpFor(alternate))} onChoose={send}
- menu={followUpFor(false) && { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) }} />
+ menu={!forkCommand && followUpFor(false) ? { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) } : undefined} />
)}
</div>
</div>
diff --git a/src/components/SlashCommandMenu.tsx b/src/components/SlashCommandMenu.tsx
index 9433b576ae..c1e02c2ec9 100644
--- a/src/components/SlashCommandMenu.tsx
+++ b/src/components/SlashCommandMenu.tsx
@@ -1,5 +1,5 @@
import type { RefObject } from "react";
-import { BookOpen, Sparkles, Target } from "lucide-react";
+import { BookOpen, GitFork, Sparkles, Target } from "lucide-react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import type { ComposerSlashCommand } from "@/lib/composer-commands";
@@ -45,6 +45,8 @@ export function SlashCommandMenu({ listRef, motion, commands, highlight, onPick,
<Sparkles size={15} aria-hidden="true" />
) : command.id === "goal" ? (
<Target size={15} aria-hidden="true" />
+ ) : command.id === "fork" ? (
+ <GitFork size={15} aria-hidden="true" />
) : (
<BookOpen size={15} aria-hidden="true" />
)}
diff --git a/src/lib/composer-commands.ts b/src/lib/composer-commands.ts
index cc7fe82147..618f6a82b0 100644
--- a/src/lib/composer-commands.ts
+++ b/src/lib/composer-commands.ts
@@ -1,6 +1,6 @@
import { blankCode, offersSkillCommand } from "../../shared/skill-command";
-export type ComposerSlashCommandId = "goal" | "learn" | "setup" | "burst";
+export type ComposerSlashCommandId = "goal" | "learn" | "setup" | "burst" | "fork";
export type ComposerSlashCommand =
| { kind: "command"; id: ComposerSlashCommandId; label: `/${ComposerSlashCommandId}`; description: string }
diff --git a/src/locales/en.json b/src/locales/en.json
index b40b7035e4..36145201e8 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2997,6 +2997,7 @@
"composer.command.learnDesc": "Draft a reusable skill from this conversation",
"composer.command.setupDesc": "Have this bot interview you and set itself up",
"composer.command.burstDesc": "Run many parts of a job at once, then merge the results",
+ "composer.command.forkDesc": "Fork from the latest text message",
"burst.title": "Burst: {task}",
"burst.plan": "{count} tasks · {model} · {parallel} at once · about {minutes} min",
"burst.moreItems": "+{count} more",
@@ -9629,6 +9630,8 @@
"serverError.model.botBusy": "the bot is working — stop it before changing models",
"serverError.model.accountUpdating": "this provider account is being updated — try again shortly",
"serverError.chat.busyEdit": "the thread is working — stop it before editing",
+ "serverError.forkBusy": "Wait for this conversation to finish before forking it.",
+ "serverError.forkNoText": "This conversation has no text message to fork from yet.",
"serverError.chat.busyVersion": "the thread is working — stop it before switching versions",
"serverError.chat.busyFresh": "the thread is working — stop it before starting fresh",
"serverError.chat.questionGone": "this question is no longer available",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index faf8fa8ac1..888d32cc57 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -10145,6 +10145,9 @@
"announcements.title": "公告",
"announcements.new": "新公告",
"composer.command.burstDesc": "同時執行一項工作的多個部分,再彙整結果",
+ "composer.command.forkDesc": "從最新一則文字訊息建立分支",
+ "serverError.forkBusy": "請等目前對話執行結束後再建立分支。",
+ "serverError.forkNoText": "目前對話還沒有可用來建立分支的文字訊息。",
"burst.title": "平行處理:{task}",
"burst.plan": "{count} 個任務 · {model} · 同時 {parallel} 個 · 約 {minutes} 分鐘",
"burst.moreItems": "還有 {count} 個",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index d3e18a45bc..4b7b1a0a55 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -10011,6 +10011,9 @@
"server.burst.partFailed": "未完成({reason})",
"server.burst.partsHeader": "这次并行处理的各部分结果(按完成顺序):{task}",
"composer.command.burstDesc": "同时运行一项工作的多个部分,然后汇总结果",
+ "composer.command.forkDesc": "从最新一条文本消息创建分支",
+ "serverError.forkBusy": "请等当前会话运行结束后再创建分支。",
+ "serverError.forkNoText": "当前会话还没有可用来创建分支的文本消息。",
"burst.title": "并行处理:{task}",
"burst.plan": "{count} 个任务 · {model} · 同时 {parallel} 个 · 约 {minutes} 分钟",
"burst.moreItems": "还有 {count} 个",
diff --git a/src/state/fork-panel.ts b/src/state/fork-panel.ts
index f1caa90c76..bbf4e1fbe9 100644
--- a/src/state/fork-panel.ts
+++ b/src/state/fork-panel.ts
@@ -15,7 +15,7 @@ export interface ForkPanelState {
}
export type ForkPanelAction =
- | { type: "forkMessage"; kind: "bot" | "group"; ownerId: string; threadId: string; messageId: string }
+ | { type: "forkMessage"; kind: "bot" | "group"; ownerId: string; threadId: string; messageId?: string; onSettled?: () => void }
| { type: "openForkPanel"; kind: "bot" | "group"; ownerId: string; threadId: string; loadId?: string }
| { type: "forkPanelLoaded"; threadId: string; loadId: string; messages: Message[]; activeLeafId: string | null }
| { type: "forkPanelLoadFailed"; threadId: string; loadId: string }
@@ -96,14 +96,15 @@ export function runForkEffect(action: ForkEffect, dispatch: (action: Action) =>
rawDispatch: (action: Action) => void, showError: (error: unknown) => void): void {
if (action.type === "forkMessage") {
const owner = action.kind === "bot" ? "bots" : "groups";
+ const body = action.messageId === undefined ? { latest: true } : { messageId: action.messageId };
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 }) },
+ { method: "POST", body: JSON.stringify(body) },
).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);
+ }).catch(showError).finally(action.onSettled);
return;
}
const owner = action.kind === "bot" ? "bots" : "groups";