Skip to content

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

fix: 修正 /fork 的版本选择、重试和焦点

Zhehui Bi5665bf0991f1
diff --git a/server/fork-api.e2e.test.ts b/server/fork-api.e2e.test.ts
index 75188154d5..baec445760 100644
--- a/server/fork-api.e2e.test.ts
+++ b/server/fork-api.e2e.test.ts
@@ -60,6 +60,22 @@ it("forks bot and room conversations through the public API and keeps a fork aft
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("POST", `/api/bots/${bot.id}/messages/${anchor.id}/edit`, {
+ text: "Alternate release plan", threadId: sourceThreadId,
+ })).status).toBe(202);
+ await expect.poll(async () => (await messages(sourceThreadId)).some((message) =>
+ message.role === "user" && message.text === "Alternate release plan"), { timeout: 20_000 }).toBe(true);
+ 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);
+ // Keep the server on the alternate version, as when /active-branch is still in flight.
+ expect(await api("POST", botForkPath, { latest: true, branchLeafId: latest.id })).toMatchObject({
+ status: 201, body: { task: { origin: { threadId: sourceThreadId, messageId: latest.id } } },
+ });
+ const unpinned = await api("POST", botForkPath, { latest: true });
+ expect(unpinned.status).toBe(201);
+ expect(unpinned.body.task.origin.messageId).not.toBe(latest.id);
+ expect(await api("POST", botForkPath, { latest: true, branchLeafId: "missing" })).toMatchObject({
+ status: 404, body: { errorKey: "serverError.forkNoText" },
+ });
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`, {
diff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.ts
index 9b61af2fa0..300f378b9f 100644
--- a/server/fork-tasks.test.ts
+++ b/server/fork-tasks.test.ts
@@ -83,7 +83,11 @@ it("uses the newest text on the selected branch for a fork without an explicit m
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 });
+ const otherBranch = store.appendMessage(threadId, { role: "bot", kind: "text", text: "Another branch", parentId: question.id });
+ const pinned = store.forkTask(bot.id, threadId, undefined, activity.id);
+ expect(pinned?.origin).toEqual({ threadId, messageId: followUp.id });
+ expect(store.activeLeaf(threadId)).toBe(otherBranch.id);
+ expect(store.forkTask(bot.id, threadId, undefined, "unknown-branch")).toBeNull();
expect(store.setActiveLeaf(threadId, reply.id)).toBe(activity.id);
const fork = store.forkTask(bot.id, threadId, undefined);
diff --git a/server/routes/fork-request.ts b/server/routes/fork-request.ts
index b09fa352cc..be334315b1 100644
--- a/server/routes/fork-request.ts
+++ b/server/routes/fork-request.ts
@@ -1,8 +1,16 @@
-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;
+import { userError } from "../user-errors.ts";
+
+export function parseForkRequest(body: unknown, allowBranch = false): { messageId?: string; branchLeafId?: string } | null {
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
+ const keys = Object.keys(body);
+ if (keys.length === 1 && "messageId" in body && typeof body.messageId === "string") return { messageId: body.messageId };
+ if (!("latest" in body) || body.latest !== true) return null;
+ if (keys.length === 1) return {};
+ if (allowBranch && keys.length === 2 && "branchLeafId" in body && typeof body.branchLeafId === "string" && body.branchLeafId) {
+ return { branchLeafId: body.branchLeafId };
+ }
+ return 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" };
+export const FORK_BUSY = userError("serverError.forkBusy");
+export const FORK_NO_TEXT = userError("serverError.forkNoText");
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 7245dbede5..5703b4f30e 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -169,12 +169,12 @@ 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 fork = parseForkRequest(await readBody(req));
+ const fork = parseForkRequest(await readBody(req), true);
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, FORK_BUSY);
- const task = store.forkTask(bot.id, m[2], fork.messageId);
+ const task = store.forkTask(bot.id, m[2], fork.messageId, fork.branchLeafId);
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.ts b/server/store.ts
index ec88d403ff..e787a8de8b 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -45,6 +45,7 @@ import { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
import { buildTask, threadTitleFrom, UNTITLED_THREAD, type NewThreadLevel } from "./task-record.ts";
import { repairLegacyWorkThreads } from "./legacy-work-threads.ts";
import { createBotFork, createGroupFork } from "./store-forks.ts";
+import { branchLeafFrom } from "../shared/conversation-branch.ts";
import { createThreadBotIndex } from "./thread-bot-index.ts";
import { activeGroupTask, groupTaskByThread, groupTasks, migrateGroupTaskRead, mirrorActiveGroupTask, refreshGroupUnread, setGroupTaskRead, syncGroupReadPatch } from "./group-task-state.ts";
export { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
@@ -1104,11 +1105,12 @@ export class Store {
return this.thread(threadId).activeLeafId;
}
- activePath(threadId: string): Message[] {
+ activePath(threadId: string, branchLeafId?: string): Message[] {
const t = this.thread(threadId);
const byId = new Map(t.messages.map((m) => [m.id, m]));
const path: Message[] = [];
- let cur = t.activeLeafId ? byId.get(t.activeLeafId) : undefined;
+ const leafId = branchLeafId ?? t.activeLeafId;
+ let cur = leafId ? byId.get(leafId) : undefined;
while (cur) {
path.push(cur);
cur = cur.parentId ? byId.get(cur.parentId) : undefined;
@@ -1223,18 +1225,7 @@ export class Store {
setActiveLeaf(threadId: string, messageId: string): string | null {
const t = this.thread(threadId);
if (!t.messages.some((m) => m.id === messageId)) return null;
- const newestChild = new Map<string, Message>();
- for (const message of t.messages) {
- if (typeof message.parentId !== "string") continue;
- const previous = newestChild.get(message.parentId);
- if (!previous || message.at >= previous.at) newestChild.set(message.parentId, message);
- }
- let cur = messageId;
- for (;;) {
- const child = newestChild.get(cur);
- if (!child) break;
- cur = child.id;
- }
+ const cur = branchLeafFrom(t.messages, messageId);
t.activeLeafId = cur;
mdb.setActiveLeaf(threadId, cur);
this.emit({ type: "thread", threadId, activeLeafId: cur });
@@ -2153,12 +2144,12 @@ export class Store {
return task;
}
- forkTask(botId: string, sourceThreadId: string, messageId: string | undefined): TaskRecord | null {
+ forkTask(botId: string, sourceThreadId: string, messageId: string | undefined, branchLeafId?: string): TaskRecord | null {
const bot = this.own(botId);
const source = this.taskByThread(botId, sourceThreadId);
if (!bot || !source) return null;
const sourceView = this.projectBotForTask(botId, sourceThreadId)!;
- const task = createBotFork(bot, source, this.activePath(sourceThreadId), messageId,
+ const task = createBotFork(bot, source, this.activePath(sourceThreadId, branchLeafId), messageId,
{ mode: approvalModeFor(sourceView), alwaysAllow: sourceView.alwaysAllow ?? [] },
(created) => this.commitBotChange(bot, "the forked thread", () => { bot.tasks = [created, ...(bot.tasks ?? [])]; }));
if (task) this.emit({ type: "bot", botId });
diff --git a/server/user-errors.ts b/server/user-errors.ts
index 4684cf2d86..18282e91c9 100644
--- a/server/user-errors.ts
+++ b/server/user-errors.ts
@@ -21,6 +21,8 @@ export const USER_ERROR = {
"serverError.model.accountUpdating": "this provider account is being updated — try again shortly",
"serverError.chat.busyEdit": "the thread is working — stop it before editing",
"serverError.chat.busyVersion": "the thread is working — stop it before switching versions",
+ "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.busyFresh": "the thread is working — stop it before starting fresh",
"serverError.chat.questionGone": "this question is no longer available",
"serverError.chat.askerGone": "the bot that asked this question is no longer available",
diff --git a/shared/conversation-branch.ts b/shared/conversation-branch.ts
new file mode 100644
index 0000000000..361ac1f4b8
--- /dev/null
+++ b/shared/conversation-branch.ts
@@ -0,0 +1,13 @@
+type BranchMessage = { id: string; parentId?: string | null; at: number };
+
+export function branchLeafFrom(messages: readonly BranchMessage[], messageId: string): string {
+ const newestChild = new Map<string, BranchMessage>();
+ for (const message of messages) {
+ if (typeof message.parentId !== "string") continue;
+ const previous = newestChild.get(message.parentId);
+ if (!previous || message.at >= previous.at) newestChild.set(message.parentId, message);
+ }
+ let leaf = messageId;
+ for (let child = newestChild.get(leaf); child; child = newestChild.get(leaf)) leaf = child.id;
+ return leaf;
+}
diff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.ts
index 9196e988d2..4e40fd201b 100644
--- a/src/components/Composer.slash.test.ts
+++ b/src/components/Composer.slash.test.ts
@@ -24,7 +24,7 @@ vi.mock("./ModelPicker", () => ({ ModelPicker: () => null }));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
vi.mock("@/lib/use-slash-skills", () => ({
useSlashSkills: (_botId: string | undefined, _threadId: string, active: boolean) =>
- active ? [{ name: "standup", description: "Writes the weekly standup note." }] : [],
+ active ? [{ name: "standup", description: "Writes the weekly standup note." }, { name: "fork-release", description: "Prepares a release." }] : [],
}));
vi.mock("./CallView", () => ({ CallButton: () => null }));
@@ -32,7 +32,7 @@ import { Composer } from "./Composer";
const bot: Bot = {
id: "slash-bot", threadId: "slash-thread", name: "Atlas", title: "", description: "",
- color: "blue", notifications: false, unread: false, busy: false, messages: [],
+ color: "blue", notifications: false, unread: false, busy: false, messages: [], activeLeafId: "visible-leaf",
modelSelection: { instanceId: ENGINE, model: "fake" },
};
const draftId = `bot:${bot.id}:${bot.threadId}`;
@@ -69,22 +69,46 @@ describe("the / menu in the composer", () => {
}
const options = () => [...document.body.querySelectorAll<HTMLElement>('[role="option"]')];
const labels = () => options().map((option) => option.querySelector(".truncate")?.textContent);
+ const press = (input: HTMLTextAreaElement, key: string) => flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })));
it("offers the built-in commands and skills at the start of a message", () => {
fill("/");
- expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/standup"]);
+ expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/fork-release", "/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 })));
+ press(input, "Enter");
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({
- type: "forkMessage", kind: "bot", ownerId: bot.id, threadId: bot.threadId,
+ type: "forkMessage", kind: "bot", ownerId: bot.id, threadId: bot.threadId, branchLeafId: bot.activeLeafId,
}));
+ expect(input.value).toBe("/fork");
+ flushSync(() => dispatch.mock.calls[0]![0].onSuccess());
expect(input.value).toBe("");
});
+ it("chooses the highlighted skill when it also matches a complete /fork", () => {
+ const input = fill("/fork");
+ press(input, "ArrowDown");
+ expect(options().find((option) => option.getAttribute("aria-selected") === "true")?.textContent).toContain("/fork-release");
+ press(input, "Enter");
+ expect(input.value).toBe("/fork-release ");
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("keeps a failed fork command in place and retries it next to the composer", () => {
+ const input = fill("/fork");
+ press(input, "Enter");
+ expect(dispatch.mock.calls[0]![0].onError).toBeTypeOf("function");
+ flushSync(() => dispatch.mock.calls[0]![0].onError("Wait for this conversation to finish."));
+ const failure = container.querySelector('[role="alert"]')!;
+ expect(failure.textContent).toContain("Wait for this conversation to finish.");
+ expect(input.value).toBe("/fork");
+ flushSync(() => failure.querySelector("button")!.click());
+ expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(["forkMessage", "forkMessage"]);
+ });
+
it("completes /fo with Tab and forks on submission", () => {
const input = fill("/fo");
flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true })));
@@ -96,8 +120,8 @@ describe("the / menu in the composer", () => {
it("offers only skills after a space later in the message, and puts the pick in place", () => {
const input = fill("write it up with /");
- expect(labels()).toEqual(["/standup"]);
- flushSync(() => options()[0]!.click());
+ expect(labels()).toEqual(["/fork-release", "/standup"]);
+ flushSync(() => options()[1]!.click());
expect(input.value).toBe("write it up with /standup ");
});
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index fe0ccdee90..b2445b1498 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -1,6 +1,7 @@
import { directMessageSent, roomMessageSent } from "@/lib/product-events";
import { TeamAudienceLabel } from "./TeamSideSwitch";
import { useComposerDictation } from "@/lib/use-composer-dictation";
+import { ComposerForkError, useComposerFork } from "./ComposerFork";
import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";
import { Mic, Square, X } from "lucide-react";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";
@@ -174,7 +175,6 @@ export function Composer({
!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);
@@ -230,6 +230,8 @@ export function Composer({
[text, editText, editAttachments],
);
const { recording, ready: micReady, speechError, toggle: toggleMic, stop: stopDictation } = useComposerDictation({ draftId, text, onText: editText });
+ const fork = useComposerFork({ ownerId: forkOwnerId, kind: group ? "group" : "bot", threadId,
+ branchLeafId: group ? undefined : bot?.activeLeafId ?? undefined, draftId, text, editText, stopDictation });
const micShown = !locked && !busy && micReady;
const [caret, setCaret] = useState(0);
const shellRef = useRef<HTMLDivElement>(null);
@@ -521,7 +523,7 @@ 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 = forkCommand ? { label: t("composer.command.forkDesc"), title: t("composer.command.forkDesc") }
+ const sendNames = fork.command ? { 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";
@@ -554,13 +556,10 @@ export function Composer({
}
};
const send = (followUp: FollowUp | undefined = followUpFor(false)) => {
- 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; } });
+ if (locked || attachmentPending) return;
+ if (fork.command) {
+ setDismissedSlashAt(slash?.start ?? 0);
+ fork.submit();
return;
}
if (
@@ -710,6 +709,7 @@ export function Composer({
</div>
)}
<div className="pointer-events-auto relative w-full">
+ {fork.error && <ComposerForkError message={fork.error} onRetry={() => { inputRef.current?.focus(); send(); }} />}
{failedSends.map((failed) => (
<div
key={failed.id}
@@ -853,7 +853,8 @@ 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 && !(forkCommand && sendsMessage(e.nativeEvent, sendKey))) {
+ const submitsFork = fork.command && commandCandidates[highlight]?.id === "fork" && sendsMessage(e.nativeEvent, sendKey);
+ if (commandPickerOpen && !submitsFork) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const delta = e.key === "ArrowDown" ? 1 : -1;
@@ -981,9 +982,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={!forkCommand && busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}
+ <ComposerSendButton compact={simpleDock} waits={!fork.command && busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}
disabled={attachmentPending} onSend={(alternate) => send(followUpFor(alternate))} onChoose={send}
- menu={!forkCommand && followUpFor(false) ? { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) } : undefined} />
+ menu={!fork.command && followUpFor(false) ? { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) } : undefined} />
)}
</div>
</div>
diff --git a/src/components/ComposerFork.tsx b/src/components/ComposerFork.tsx
new file mode 100644
index 0000000000..a42b627c00
--- /dev/null
+++ b/src/components/ComposerFork.tsx
@@ -0,0 +1,54 @@
+import { useRef, useState } from "react";
+import { draftRevision } from "@/lib/drafts";
+import { t } from "@/lib/i18n";
+import { useStoreDispatch } from "@/state/store-select";
+
+export function useComposerFork({ ownerId, kind, threadId, branchLeafId, draftId, text, editText, stopDictation }: {
+ ownerId?: string;
+ kind: "bot" | "group";
+ threadId: string;
+ branchLeafId?: string;
+ draftId: string;
+ text: string;
+ editText: (text: string) => void;
+ stopDictation: () => void;
+}) {
+ const dispatch = useStoreDispatch();
+ const pending = useRef(false);
+ const [failure, setFailure] = useState<{ draftId: string; revision: number; message: string }>();
+ const command = Boolean(ownerId && /^\/fork\s*$/i.test(text));
+ const error = command && failure?.draftId === draftId && failure.revision === draftRevision(draftId)
+ ? failure.message : undefined;
+
+ function submit() {
+ if (!command || !ownerId || pending.current) return;
+ pending.current = true;
+ stopDictation();
+ const revision = draftRevision(draftId);
+ setFailure(undefined);
+ dispatch({
+ type: "forkMessage", kind, ownerId, threadId, branchLeafId,
+ onSuccess: () => {
+ pending.current = false;
+ if (draftRevision(draftId) === revision) editText("");
+ },
+ onError: (message) => {
+ pending.current = false;
+ setFailure({ draftId, revision, message });
+ },
+ });
+ }
+
+ return { command, error, submit };
+}
+
+export function ComposerForkError({ message, onRetry }: { message: string; onRetry: () => void }) {
+ return (
+ <div role="alert" className="mb-2 flex items-center gap-2 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[13px] text-danger">
+ <span className="min-w-0 flex-1">{message}</span>
+ <button type="button" onClick={onRetry} className="shrink-0 rounded px-2 py-1 font-medium hover:bg-danger/10">
+ {t("chat.retry")}
+ </button>
+ </div>
+ );
+}
diff --git a/src/components/ForkPanel.focus.test.ts b/src/components/ForkPanel.focus.test.ts
new file mode 100644
index 0000000000..874a39b542
--- /dev/null
+++ b/src/components/ForkPanel.focus.test.ts
@@ -0,0 +1,34 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+
+const store = vi.hoisted(() => ({ state: {} as Record<string, unknown>, dispatch: vi.fn() }));
+vi.mock("@/state/store", () => ({ useStore: () => store, currentTaskBot: (bot: object) => bot }));
+vi.mock("./ChatView", () => ({ ChatView: () => createElement("div", { "data-tour": "composer" }, createElement("textarea")) }));
+vi.mock("./GroupView", () => ({ GroupView: () => createElement("div", { "data-tour": "composer" }, createElement("textarea")) }));
+
+import { ForkPanel } from "./ForkPanel";
+
+it.each(["bot", "group"] as const)("moves focus from the source to a newly created %s fork", (kind) => {
+ const input = document.createElement("textarea");
+ const container = document.createElement("div");
+ document.body.append(input, container);
+ const root = createRoot(container);
+ const panel = { kind, ownerId: kind, threadId: "fork", messages: [], loadId: "load", focusComposer: true };
+ const owner = { id: kind, tasks: [{ threadId: "fork", title: "Fork" }] };
+ store.state = { forkPanel: { ...panel, loading: true }, bots: kind === "bot" ? [owner] : [], groups: kind === "group" ? [owner] : [] };
+ input.focus();
+ try {
+ flushSync(() => root.render(createElement(ForkPanel)));
+ expect(document.activeElement).toBe(container.querySelector("aside"));
+ store.state = { ...store.state, forkPanel: { ...panel, loading: false } };
+ flushSync(() => root.render(createElement(ForkPanel)));
+ expect(document.activeElement).toBe(container.querySelector("textarea"));
+ } finally {
+ flushSync(() => root.unmount());
+ input.remove();
+ container.remove();
+ }
+});
diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsx
index 81948eb201..57a4279a3f 100644
--- a/src/components/ForkPanel.tsx
+++ b/src/components/ForkPanel.tsx
@@ -1,4 +1,5 @@
import { X } from "lucide-react";
+import { useLayoutEffect, useRef } from "react";
import { currentTaskBot, useStore } from "@/state/store";
import { t } from "@/lib/i18n";
import { ChatView } from "./ChatView";
@@ -7,6 +8,15 @@ import { GroupView } from "./GroupView";
export function ForkPanel() {
const { state, dispatch } = useStore();
const panel = state.forkPanel;
+ const asideRef = useRef<HTMLElement>(null);
+ const focusedLoad = useRef<string | undefined>(undefined);
+ useLayoutEffect(() => {
+ const aside = asideRef.current;
+ if (!panel?.focusComposer || !aside) return;
+ if (focusedLoad.current === panel.loadId && document.activeElement !== aside) return;
+ focusedLoad.current = panel.loadId;
+ (aside.querySelector<HTMLTextAreaElement>('[data-tour="composer"] textarea:not([disabled])') ?? aside).focus();
+ }, [panel?.focusComposer, panel?.loadId, panel?.loading]);
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;
@@ -19,7 +29,7 @@ export function ForkPanel() {
turnStartedAt: null, pinnedCwd: groupTask.pinnedCwd, pinnedMessageId: groupTask.pinnedMessageId } : 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">
+ <aside ref={asideRef} tabIndex={panel.focusComposer ? -1 : undefined} 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"
@@ -30,7 +40,7 @@ export function ForkPanel() {
: panel.loadFailed ? <div className="flex items-center gap-3 p-4 text-sm text-ink-secondary">
<span>{t("chat.forkUnavailable")}</span>
<button type="button" className="rounded px-2 py-1 text-ink hover:bg-raised"
- onClick={() => dispatch({ type: "openForkPanel", kind: panel.kind, ownerId: panel.ownerId, threadId: panel.threadId })}>
+ onClick={() => dispatch({ type: "openForkPanel", kind: panel.kind, ownerId: panel.ownerId, threadId: panel.threadId, focusComposer: panel.focusComposer })}>
{t("chat.retry")}
</button>
</div>
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 7df6ca3063..3a6524cffe 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2811,6 +2811,7 @@
"composer.command.learnDesc": "Rascunhar uma habilidade reutilizável a partir desta conversa",
"composer.command.setupDesc": "Pedir a este bot que entreviste você e se configure sozinho",
"composer.command.burstDesc": "Executar muitas partes de um trabalho ao mesmo tempo e juntar os resultados",
+ "composer.command.forkDesc": "Criar uma bifurcação a partir da mensagem de texto mais recente",
"burst.title": "Burst: {task}",
"burst.plan": "{count} tarefas · {model} · {parallel} ao mesmo tempo · cerca de {minutes} min",
"burst.moreItems": "+{count} a mais",
@@ -9543,6 +9544,8 @@
"serverError.signIn.tooMany": "Houve muitas tentativas de login sem sucesso a partir do seu endereço. Tente novamente em {seconds} s.",
"serverError.cloud.personal": "O Cloud é pessoal: só os seus dispositivos podem se conectar.",
"serverError.model.botBusy": "O bot está trabalhando. Pare o bot antes de trocar de modelo.",
+ "serverError.forkBusy": "Aguarde esta conversa terminar antes de criar uma bifurcação.",
+ "serverError.forkNoText": "Esta conversa ainda não tem uma mensagem de texto para usar como ponto de partida da bifurcação.",
"serverError.model.accountUpdating": "Esta conta de IA está sendo atualizada. Tente novamente em instantes.",
"serverError.chat.busyEdit": "O bot ainda está trabalhando nesta conversa. Pare o bot antes de editar.",
"serverError.chat.busyVersion": "O bot ainda está trabalhando nesta conversa. Pare o bot antes de trocar de versão.",
diff --git a/src/state/fork-panel.test.ts b/src/state/fork-panel.test.ts
index 490535c8ce..83ad6591c3 100644
--- a/src/state/fork-panel.test.ts
+++ b/src/state/fork-panel.test.ts
@@ -42,6 +42,19 @@ it("removes a failed bot fork send before buffering background thread events", (
expect(removed.forkPanel?.activeLeafId).toBe(source.id);
});
+it("switches to the selected branch in the panel while keeping the source thread selected", () => {
+ const alternate: Message = { ...source, id: "alternate", at: 2 };
+ const answer: Message = { ...source, id: "answer", role: "bot", at: 3, parentId: alternate.id };
+ const start = {
+ ...initialState,
+ bots: [{ id: "bot", threadId: "main", activeLeafId: "main-leaf" }],
+ forkPanel: { ...panel(), messages: [source, alternate, answer] },
+ } as unknown as AppState;
+ const switched = reducer(start, { type: "switchBranch", botId: "bot", threadId: "fork", messageId: alternate.id });
+ expect(switched.forkPanel?.activeLeafId).toBe(answer.id);
+ expect(switched.bots[0]?.activeLeafId).toBe("main-leaf");
+});
+
it("ignores a stale load failure after retrying the same fork", () => {
const retry = reduceForkPanel(state(), { type: "openForkPanel", kind: "bot", ownerId: "bot", threadId: "fork", loadId: "load-2" });
expect(reduceForkPanel(retry, { type: "forkPanelLoadFailed", threadId: "fork", loadId: "load-1" })).toBe(retry);
diff --git a/src/state/fork-panel.ts b/src/state/fork-panel.ts
index bbf4e1fbe9..2c69fe57e8 100644
--- a/src/state/fork-panel.ts
+++ b/src/state/fork-panel.ts
@@ -12,11 +12,12 @@ export interface ForkPanelState {
loading: boolean;
loadId: string;
loadFailed: boolean;
+ focusComposer?: boolean;
}
export type ForkPanelAction =
- | { 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: "forkMessage"; kind: "bot" | "group"; ownerId: string; threadId: string; messageId?: string; branchLeafId?: string; onSuccess?: () => void; onError?: (message: string) => void }
+ | { type: "openForkPanel"; kind: "bot" | "group"; ownerId: string; threadId: string; loadId?: string; focusComposer?: boolean }
| { type: "forkPanelLoaded"; threadId: string; loadId: string; messages: Message[]; activeLeafId: string | null }
| { type: "forkPanelLoadFailed"; threadId: string; loadId: string }
| { type: "forkPanelMessage"; threadId: string; message: Message; patch?: true }
@@ -29,7 +30,7 @@ export function reduceForkPanel(state: AppState, action: ForkPanelAction): AppSt
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, loadId: action.loadId ?? "", loadFailed: false } };
+ loading: true, loadId: action.loadId ?? "", loadFailed: false, focusComposer: action.focusComposer } };
case "forkPanelLoaded": {
const panel = state.forkPanel;
if (panel?.threadId !== action.threadId || panel.loadId !== action.loadId) return state;
@@ -96,15 +97,21 @@ 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 };
+ const latest = action.messageId === undefined;
+ // The visible branch may still be waiting for its separate active-branch request.
+ const body = latest ? { latest: true, branchLeafId: action.branchLeafId } : { 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(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).finally(action.onSettled);
+ dispatch({ type: "openForkPanel", kind: action.kind, ownerId: action.ownerId, threadId: result.task.threadId, focusComposer: latest });
+ action.onSuccess?.();
+ }).catch((error) => {
+ if (action.onError) action.onError(error instanceof Error ? error.message : String(error));
+ else showError(error);
+ });
return;
}
const owner = action.kind === "bot" ? "bots" : "groups";
diff --git a/src/state/snapshot-navigation.ts b/src/state/snapshot-navigation.ts
index c98d5965e7..bd96095210 100644
--- a/src/state/snapshot-navigation.ts
+++ b/src/state/snapshot-navigation.ts
@@ -1,4 +1,14 @@
-import type { Bot, Group, Message } from "./store";
+import { branchLeafFrom } from "../../shared/conversation-branch";
+import type { AppState, Bot, Group, Message } from "./store";
+
+export function switchBotBranch(state: AppState, botId: string, threadId: string, messageId: string): AppState {
+ const panel = state.forkPanel;
+ if (panel?.kind === "bot" && panel.ownerId === botId && panel.threadId === threadId) {
+ return { ...state, forkPanel: { ...panel, activeLeafId: branchLeafFrom(panel.messages, messageId) } };
+ }
+ return { ...state, bots: state.bots.map((bot) => bot.id === botId && bot.threadId === threadId
+ ? { ...bot, activeLeafId: branchLeafFrom(bot.messages, messageId) } : bot) };
+}
// One branch per transcript array and leaf: every sidebar row, the composer and the chat ask for it on each store
// change, and an unchanged transcript keeps the same array (so memos keyed on it hold).
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 2b969ae112..9ad8013c00 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -22,7 +22,7 @@ import type { EngineInstall } from "./engine-install";
import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";
import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";
import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";
-import { hydratedSelectedId, keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";
+import { hydratedSelectedId, keepBotNavigation, keepGroupNavigation, navigatedSince, switchBotBranch, visibleMessages } from "./snapshot-navigation";
export { visibleMessages } from "./snapshot-navigation";
export { awayFromMainThread, botOpensTo, markedThread, openBot, openBotRow, openBotThread, openRoomThread, openThread, visibleNotificationThread, type ThreadTarget } from "./thread-navigation";
import type { TurnDigest } from "../../shared/digest";
@@ -1560,15 +1560,8 @@ function reduceApp(state: AppState, action: Action): AppState {
}));
}
case "switchBranch": {
- const bot = state.bots.find((b) => b.id === action.botId);
- if (!bot) return state;
- let cur = action.messageId;
- for (;;) {
- const children = bot.messages.filter((m) => m.parentId === cur);
- if (!children.length) break;
- cur = children.reduce((a, b) => (b.at >= a.at ? b : a)).id;
- }
- return updateBot(bumpTranscriptGeneration(state, bot.threadId), action.botId, (b) => ({ ...b, activeLeafId: cur }));
+ const threadId = action.threadId ?? state.bots.find((bot) => bot.id === action.botId)?.threadId;
+ return threadId ? switchBotBranch(bumpTranscriptGeneration(state, threadId), action.botId, threadId, action.messageId) : state;
}
case "patchGroup":
return {