Skip to content

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

refactor: 拆分会话分叉与历史加载逻辑

Zhehui Bi2b7aa35500b3
diff --git a/server/store-forks.ts b/server/store-forks.ts
new file mode 100644
index 0000000000..9d0c8465b9
--- /dev/null
+++ b/server/store-forks.ts
@@ -0,0 +1,42 @@
+import type { GroupTask as GroupTaskRecord } from "../shared/wire.ts";
+import { newId } from "./contracts.ts";
+import * as mdb from "./message-db.ts";
+import type { BotRecord, Message, TaskRecord } from "./store.ts";
+import { buildTask } from "./task-record.ts";
+import { titleFromMessage } from "./thread-title.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));
+}
+
+/** Import the copied message path and register the task in the same database transaction. */
+export function createGroupFork(source: GroupTaskRecord, path: Message[], messageId: string,
+ register: (task: GroupTaskRecord) => void): GroupTaskRecord | null {
+ const history = forkHistory(path, 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: source.threadId, messageId },
+ ...(source.pinnedCwd !== undefined ? { pinnedCwd: source.pinnedCwd } : {}),
+ };
+ mdb.importThread(task.threadId, history, messageId, undefined, () => register(task));
+ return task;
+}
+
+export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[], messageId: string,
+ register: (task: TaskRecord) => void): TaskRecord | null {
+ const history = forkHistory(path, messageId);
+ if (!history) return null;
+ const task = buildTask(bot, titleFromMessage(history.at(-1)?.text ?? ""), source.projectId, undefined,
+ undefined, source.modelSelection, source.cwd ?? undefined);
+ task.origin = { threadId: source.threadId, messageId };
+ task.lastReadMessageId = messageId;
+ mdb.importThread(task.threadId, history, messageId, undefined, () => register(task));
+ return task;
+}
diff --git a/server/store.ts b/server/store.ts
index e62d1a588c..024bc081af 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -42,7 +42,10 @@ import { initialGreetingMessage } from "./initial-greeting.ts"; import { createD
import { appsFromCreator } from "./inherited-apps.ts";
import { ThreadCache, type ThreadState } from "./thread-cache.ts";
import { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
+import { buildTask, threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
+import { createBotFork, createGroupFork } from "./store-forks.ts";
export { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
+export { threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
export type {
BotActivity, GroupDefaultResponder, OptionCardData,
SecretRequestCardData, Surface, TaskClosedBy, TaskOpenedBy, TaskUsage,
@@ -138,14 +141,6 @@ export type StoreChange =
| { type: "group"; groupId: string }
| { type: "group.deleted"; groupId: string };
-export const UNTITLED_THREAD = "New thread";
-
-/** Every title (a bot's or a person's) passes through here, so equality tells a machine-made title from a rename. */
-const TASK_TITLE_MAX = 80;
-export function threadTitleFrom(title?: string): string {
- return title?.trim().slice(0, TASK_TITLE_MAX) || UNTITLED_THREAD;
-}
-
export function titleFromLlm(raw: string): string | null {
const line = raw
.trim()
@@ -1019,21 +1014,9 @@ export class Store {
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 });
+ const task = createGroupFork(source, this.activePath(sourceThreadId), messageId,
+ (created) => this.commitGroupChange(group, "the forked thread", () => { group.tasks = [created, ...(group.tasks ?? [])]; }));
+ if (task) this.emit({ type: "group", groupId });
return task;
}
@@ -1176,13 +1159,6 @@ 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) {
@@ -2201,7 +2177,7 @@ export class Store {
const bot = this.bot(botId);
if (!bot) return null;
if (projectId !== undefined && !this.project(botId, projectId)) return null;
- const task = this.buildTask(bot, title, projectId, openedBy, approvalMode, modelSelection, cwd);
+ const task = buildTask(bot, title, projectId, openedBy, approvalMode, modelSelection, cwd);
this.commitBotChange(bot, "the new thread", () => {
bot.tasks = [task, ...(bot.tasks ?? [])];
if (activate) this.mirrorActiveTask(bot, task);
@@ -2214,41 +2190,12 @@ export class Store {
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 });
+ const task = createBotFork(bot, source, this.activePath(sourceThreadId), messageId,
+ (created) => this.commitBotChange(bot, "the forked thread", () => { bot.tasks = [created, ...(bot.tasks ?? [])]; }));
+ if (task) 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();
- return {
- threadId: newId(),
- title: threadTitleFrom(title),
- createdAt,
- updatedAt: createdAt,
- ...(cwd !== undefined ? { cwd } : {}),
- ...(projectId ? { projectId } : {}),
- ...(openedBy ? { openedBy: structuredClone(openedBy) } : {}),
- resumeCursors: {},
- ...(modelSelection && !sameModelSelection(modelSelection, bot.modelSelection) ? { modelSelection: structuredClone(modelSelection) } : {}),
- approvalMode: approvalMode ?? approvalModeFor(bot),
- autoApprove: approvalMode ? false : Boolean(bot.autoApprove),
- alwaysAllow: approvalMode ? [] : [...(bot.alwaysAllow ?? [])],
- unread: false,
- activity: "idle",
- busy: false,
- };
- }
-
setTaskOpenedBy(botId: string, threadId: string, openedBy: TaskOpenedBy): TaskRecord | null {
const bot = this.bot(botId);
const task = this.taskByThread(botId, threadId);
@@ -2328,7 +2275,7 @@ export class Store {
const doomed = new Set(deleted);
mdb.deleteThreads(deleted, () => this.commitBotChange(bot, "the thread deletion", () => {
const kept = bot.tasks!.filter((t) => !doomed.has(t.threadId));
- const visible = nextOpenThread(kept) ?? this.buildTask(bot);
+ const visible = nextOpenThread(kept) ?? buildTask(bot);
bot.tasks = kept.includes(visible) ? kept : [visible, ...kept];
if (doomed.has(bot.threadId) || this.taskByThread(botId, bot.threadId)?.routineRunId) this.mirrorActiveTask(bot, visible);
bot.unread = bot.tasks.some(taskCountsAsBotUnread);
diff --git a/server/task-record.ts b/server/task-record.ts
new file mode 100644
index 0000000000..768f299b05
--- /dev/null
+++ b/server/task-record.ts
@@ -0,0 +1,35 @@
+import { approvalModeFor } from "../shared/approval-mode.ts";
+import { sameModelSelection } from "../shared/thread-model.ts";
+import type { TaskOpenedBy } from "../shared/wire.ts";
+import { newId, type ModelSelection } from "./contracts.ts";
+import type { BotRecord, TaskRecord } from "./store.ts";
+
+export const UNTITLED_THREAD = "New thread";
+const TASK_TITLE_MAX = 80;
+
+/** Every title (a bot's or a person's) passes through here, so equality tells a machine-made title from a rename. */
+export function threadTitleFrom(title?: string): string {
+ return title?.trim().slice(0, TASK_TITLE_MAX) || UNTITLED_THREAD;
+}
+
+export function buildTask(bot: BotRecord, title?: string, projectId?: string, openedBy?: TaskOpenedBy,
+ approvalMode?: "ask" | "full", modelSelection?: ModelSelection, cwd?: string): TaskRecord {
+ const createdAt = Date.now();
+ return {
+ threadId: newId(),
+ title: threadTitleFrom(title),
+ createdAt,
+ updatedAt: createdAt,
+ ...(cwd !== undefined ? { cwd } : {}),
+ ...(projectId ? { projectId } : {}),
+ ...(openedBy ? { openedBy: structuredClone(openedBy) } : {}),
+ resumeCursors: {},
+ ...(modelSelection && !sameModelSelection(modelSelection, bot.modelSelection) ? { modelSelection: structuredClone(modelSelection) } : {}),
+ approvalMode: approvalMode ?? approvalModeFor(bot),
+ autoApprove: approvalMode ? false : Boolean(bot.autoApprove),
+ alwaysAllow: approvalMode ? [] : [...(bot.alwaysAllow ?? [])],
+ unread: false,
+ activity: "idle",
+ busy: false,
+ };
+}
diff --git a/shared/task-provenance.ts b/shared/task-provenance.ts
new file mode 100644
index 0000000000..cd728f904b
--- /dev/null
+++ b/shared/task-provenance.ts
@@ -0,0 +1,29 @@
+/** The bot that opened a thread on itself or a teammate. */
+export interface TaskOpenedBy {
+ botId: string;
+ name: string;
+ delegationId?: string;
+ /** What kind of conversation the opener made this: "pair" is the one
+ * durable conversation between two bots; "work" closes itself once its
+ * result has been reported. */
+ kind?: "pair" | "work";
+ /** The opener's own conversation this "work" thread was opened from.
+ * Everything that conversation later sends this bot continues here. */
+ threadId?: string;
+ /** A parallel room job's thread: `threadId` is the room thread it came from, and the member must stay in that room. */
+ roomLane?: true;
+ at: number;
+}
+
+/** The bot that closed a thread it opened (or one of its own). */
+export interface TaskClosedBy {
+ botId: string;
+ name: string;
+ at: number;
+}
+
+/** The completed message whose visible history seeded an independent conversation. */
+export interface ForkOrigin {
+ threadId: string;
+ messageId: string;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index 9770725606..a35750ad32 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -33,10 +33,12 @@ import type { WebhookAttempt, WebhookTrigger } from "./webhooks.ts";
import type { PublishedPageCard } from "./published-page.ts";
import type { InboxItem, InboxTask } from "./inbox.ts";
import type { LiveCallRecord, LiveCallState } from "./live-call-wire.ts";
+import type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
/** What a team bot's main chat is called, beside each person's own chats. */
export const SHARED_CHAT_TITLE = "Shared chat";
export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
+export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
/** Reasoning-effort levels, ascending: a union of what any engine accepts;
* each driver declares the subset its CLI will take. */
@@ -82,30 +84,6 @@ export type MausExpression = string;
* never counts as busy. */
export type BotActivity = "working" | "waiting-on-you" | "idle" | "no-signal" | "dead" | "parked.computer";
-/** The bot that opened a thread on itself or a teammate. */
-export interface TaskOpenedBy {
- botId: string;
- name: string;
- delegationId?: string;
- /** What kind of conversation the opener made this: "pair" is the one
- * durable conversation between two bots; "work" closes itself once its
- * result has been reported. */
- kind?: "pair" | "work";
- /** The opener's own conversation this "work" thread was opened from.
- * Everything that conversation later sends this bot continues here. */
- threadId?: string;
- /** A parallel room job's thread: `threadId` is the room thread it came from, and the member must stay in that room. */
- roomLane?: true;
- at: number;
-}
-
-/** The bot that closed a thread it opened (or one of its own). */
-export interface TaskClosedBy {
- botId: string;
- name: string;
- at: number;
-}
-
/** What a task has spent, banked once per settled turn. */
export interface TaskUsage {
input: number;
@@ -132,13 +110,7 @@ export interface BotMovedTo {
at: number;
}
-/** One task = one conversation with its own context, thread and provider
- * session. */
-export interface ForkOrigin {
- threadId: string;
- messageId: string;
-}
-
+/** One task = one conversation with its own context, thread and provider session. */
export interface WireTask extends InboxTask {
/** Outstanding handoffs, not an active provider turn. */
waitingForTeammates?: boolean;
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 2f6f5d7ebc..3ceee8dcb3 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -3,12 +3,11 @@ import { useAdvancedMode } from "@/lib/interface-mode";
import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
import { ThreadLinkContext } from "@/components/ThreadLinkMenu";
import { useShowThreads } from "@/lib/thread-preferences";
-import { AlertTriangle, ChevronLeft, ChevronRight, Copy, Monitor, RefreshCw, Reply, Square, Webhook } from "lucide-react";
+import { AlertTriangle, ChevronLeft, ChevronRight, Monitor, RefreshCw, Square, Webhook } from "lucide-react";
import { WorkingDots } from "@/components/WorkingIndicator";
-import { ACTION_ICON, ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction, type MessageMenuItem } from "@/components/MessageActions";
-import { copyText } from "@/lib/copy-text";
+import { ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction } from "@/components/MessageActions";
import { ReactAction, ReactionChips } from "@/components/Reactions";
-import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu";
+import { replyAndCopy, useBotMessageMenu, userMessageMenu } from "@/components/message-menu";
import { forkMessageItem, ForkLinks } from "@/components/ForkMessage";
import { useSpeech } from "@/lib/tts/useSpeech";
import { localSystemVoiceActive } from "@/lib/local-voice";
@@ -299,14 +298,6 @@ export function FailedTurnRow({ tool, engine, onRetry, botId, threadId, messageA
export { MessageBoundary };
-/** Simple mode keeps a message's Reply and Copy in its "…" menu, beside the one reaction button. */
-function replyAndCopy(onReply: () => void, text: string): MessageMenuItem[] {
- return [
- { key: "reply", icon: <Reply {...ACTION_ICON} />, label: t("chat.reply"), onSelect: onReply },
- ...(text.trim() ? [{ key: "copy", icon: <Copy {...ACTION_ICON} />, label: t("chat.copyMessage"), onSelect: () => { void copyText(text); } }] : []),
- ];
-}
-
const Bubble = memo(function Bubble({
message,
emerging = false,
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 116e89ff3e..82aaee8847 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -74,7 +74,7 @@ import { ActivityRun } from "./ActivityRun";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
import { useLiveToolIds } from "@/hooks/use-live-tool-ids";
-import { roomNeedsSetup } from "@/lib/room-setup";
+import { roomNeedsSetup, setupResponderMode, type RoomResponderMode } from "@/lib/room-setup";
import { useComposerDockPad } from "@/lib/composer-dock";
import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";
import { awaitedMemberId, showWorkingDots } from "@/lib/turn-tail";
@@ -525,12 +525,6 @@ export const Transcript = memo(function Transcript({
);
});
-type RoomResponderMode = "lead" | "everyone" | "mentions" | "auto";
-
-function setupResponderMode(responder: GroupDefaultResponder): RoomResponderMode {
- return responder.kind === "member" ? "lead" : responder.kind;
-}
-
function RoomSetup({ group, members }: { group: Group; members: Bot[] }) {
const { state, dispatch } = useStore();
const jevOn = jevRoomRoutingOn(state.config);
diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsx
index c65facc95b..c6132e5771 100644
--- a/src/components/message-menu.tsx
+++ b/src/components/message-menu.tsx
@@ -1,4 +1,4 @@
-import { Code, Copy, Eye, Pencil, Pin, PinOff, RefreshCw, Square, Volume2 } from "lucide-react";
+import { Code, Copy, Eye, Pencil, Pin, PinOff, RefreshCw, Reply, Square, Volume2 } from "lucide-react";
import { copyText } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import type { ConfigStatus, Group, Message, useStore } from "@/state/store";
@@ -7,6 +7,14 @@ import { useSpeakAction } from "@/components/SpeakButton";
export type PinAction = { pinned: boolean; onToggle: () => void; hint?: string };
+/** Simple mode keeps Reply and Copy in the message's actions menu. */
+export function replyAndCopy(onReply: () => void, text: string): MessageMenuItem[] {
+ return [
+ { key: "reply", icon: <Reply {...ACTION_ICON} />, label: t("chat.reply"), onSelect: onReply },
+ ...(text.trim() ? [{ key: "copy", icon: <Copy {...ACTION_ICON} />, label: t("chat.copyMessage"), onSelect: () => { void copyText(text); } }] : []),
+ ];
+}
+
export function roomPin(group: Group, message: Message, dispatch: ReturnType<typeof useStore>["dispatch"]): PinAction | undefined {
if (window.ogb?.remoteClient?.active) return undefined;
const pinned = group.pinnedMessageId === message.id;
diff --git a/src/lib/room-setup.ts b/src/lib/room-setup.ts
index 65c398ee05..fa3e7a5a98 100644
--- a/src/lib/room-setup.ts
+++ b/src/lib/room-setup.ts
@@ -1,4 +1,10 @@
-import type { Group } from "@/state/store";
+import type { Group, GroupDefaultResponder } from "@/state/store";
+
+export type RoomResponderMode = "lead" | "everyone" | "mentions" | "auto";
+
+export function setupResponderMode(responder: GroupDefaultResponder): RoomResponderMode {
+ return responder.kind === "member" ? "lead" : responder.kind;
+}
type RoomSetupFields = {
setupPending?: boolean;
diff --git a/src/state/fork-panel.ts b/src/state/fork-panel.ts
new file mode 100644
index 0000000000..ba2c6e7afa
--- /dev/null
+++ b/src/state/fork-panel.ts
@@ -0,0 +1,67 @@
+import { api } from "./api";
+import { loadFullThread } from "./message-history";
+import type { Action, AppState, BotAnnouncement, Group, Message } from "./store";
+
+export interface ForkPanelState {
+ kind: "bot" | "group";
+ ownerId: string;
+ threadId: string;
+ messages: Message[];
+ activeLeafId: string | null;
+ loading: boolean;
+}
+
+export type ForkPanelAction =
+ | { 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" };
+
+export function reduceForkPanel(state: AppState, action: ForkPanelAction): AppState {
+ switch (action.type) {
+ 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;
+ }
+}
+
+type ForkEffect = Extract<Action, { type: "forkMessage" | "openForkPanel" }>;
+export function runForkEffect(action: ForkEffect, dispatch: (action: Action) => void,
+ rawDispatch: (action: Action) => void, showError: (error: unknown) => void): void {
+ if (action.type === "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);
+ return;
+ }
+ const owner = action.kind === "bot" ? "bots" : "groups";
+ void api(`/api/${owner}/${action.ownerId}/read`, { method: "POST", body: JSON.stringify({ threadId: action.threadId }) }).catch(() => {});
+ void loadFullThread(action.threadId).then(({ messages, activeLeafId }) => {
+ rawDispatch({ type: "forkPanelLoaded", threadId: action.threadId, messages, activeLeafId });
+ }).catch(showError);
+}
diff --git a/src/state/message-history.ts b/src/state/message-history.ts
new file mode 100644
index 0000000000..771e818c48
--- /dev/null
+++ b/src/state/message-history.ts
@@ -0,0 +1,66 @@
+import { placeUnreadDivider } from "@/lib/unread-divider";
+import { api } from "./api";
+import { visibleMessages } from "./snapshot-navigation";
+import type { Action, AppState, Message } from "./store";
+
+export const MESSAGE_PAGE_SIZE = 200;
+type OlderMessages = Extract<Action, { type: "olderMessages" }>;
+type LoadOlderMessages = Extract<Action, { type: "loadOlderMessages" }>;
+
+export function reduceOlderMessages(state: AppState, action: OlderMessages): AppState {
+ const { [action.threadId]: _done, ...loadingOlder } = state.loadingOlder;
+ if ((state.transcriptGeneration[action.threadId] ?? 0) !== action.generation) return { ...state, loadingOlder };
+ const prepend = <T extends { messages: Message[]; threadId: string; hasMore?: boolean }>(owner: T): T => {
+ const held = new Set(owner.messages.map((message) => message.id));
+ return {
+ ...owner,
+ // A page that raced an edit can overlap held rows; the held copy is newer.
+ messages: [...action.messages.filter((message) => !held.has(message.id)), ...owner.messages],
+ hasMore: action.hasMore,
+ };
+ };
+ const bots = state.bots.map((bot) => (bot.threadId === action.threadId ? prepend(bot) : bot));
+ const groups = state.groups.map((group) => (group.threadId === action.threadId ? prepend(group) : group));
+ const owner = [...bots, ...groups].find((candidate) => candidate.threadId === action.threadId);
+ const unreadDivider = placeUnreadDivider(state.unreadDivider, action.threadId, owner ? visibleMessages(owner) : [], action.hasMore);
+ return { ...state, loadingOlder, bots, groups, unreadDivider };
+}
+
+export function loadOlderPage(action: LoadOlderMessages, current: AppState, inFlight: Set<string>,
+ dispatch: (action: Action) => void, showError: (error: unknown) => void): void {
+ // current is the pre-dispatch state; the reducer's loading flag has not reached the ref yet.
+ if (inFlight.has(action.threadId)) return;
+ inFlight.add(action.threadId);
+ const owner = [...current.bots, ...current.groups].find((candidate) => candidate.threadId === action.threadId);
+ const before = owner?.messages[0]?.id;
+ const generation = current.transcriptGeneration[action.threadId] ?? 0;
+ if (!before) {
+ inFlight.delete(action.threadId);
+ dispatch({ type: "olderMessages", threadId: action.threadId, generation, messages: [], hasMore: false });
+ return;
+ }
+ void api<{ messages: Message[]; hasMore?: boolean }>(
+ `/api/threads/${action.threadId}/messages?limit=${MESSAGE_PAGE_SIZE}&before=${encodeURIComponent(before)}`,
+ ).finally(() => inFlight.delete(action.threadId)).then((page) => dispatch({
+ type: "olderMessages", threadId: action.threadId, generation, messages: page.messages ?? [], hasMore: Boolean(page.hasMore),
+ })).catch((error) => {
+ dispatch({ type: "olderMessages", threadId: action.threadId, generation, messages: [], hasMore: true });
+ showError(error);
+ });
+}
+
+export async function loadFullThread(threadId: string): Promise<{ messages: Message[]; activeLeafId: string | null }> {
+ 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/${threadId}/messages?limit=${MESSAGE_PAGE_SIZE}${before ? `&before=${encodeURIComponent(before)}` : ""}`,
+ );
+ messages.unshift(...page.messages);
+ activeLeafId = page.activeLeafId;
+ if (!page.hasMore || !page.messages.length) break;
+ before = page.messages[0]!.id;
+ }
+ return { messages, activeLeafId };
+}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 510276ed4b..0d2b2703ac 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -1,5 +1,8 @@
import { cloudAsleep, onCloudPower } from "../lib/cloud-power";
import { api, ApiError, retryRequest, snapshotArrays } from "./api";
+import { loadOlderPage, MESSAGE_PAGE_SIZE, reduceOlderMessages } from "./message-history";
+export { MESSAGE_PAGE_SIZE } from "./message-history";
+import { reduceForkPanel, runForkEffect, type ForkPanelAction, type ForkPanelState } from "./fork-panel";
import {
createContext,
useCallback,
@@ -583,7 +586,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;
+ forkPanel: ForkPanelState | 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;
@@ -698,12 +701,7 @@ 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" }
+ | ForkPanelAction
| { type: "switchGroupTask"; groupId: string; threadId: string }
| { type: "renameGroupTask"; groupId: string; threadId: string; title: string }
| { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean; title: string }
@@ -951,26 +949,8 @@ export function reducer(state: AppState, action: Action): AppState {
return state.loadingOlder[action.threadId]
? state
: { ...state, loadingOlder: { ...state.loadingOlder, [action.threadId]: true } };
- case "olderMessages": {
- const { [action.threadId]: _done, ...loadingOlder } = state.loadingOlder;
- if ((state.transcriptGeneration[action.threadId] ?? 0) !== action.generation) {
- return { ...state, loadingOlder };
- }
- const prepend = <T extends { messages: Message[]; threadId: string; hasMore?: boolean }>(owner: T): T => {
- const held = new Set(owner.messages.map((message) => message.id));
- return {
- ...owner,
- // A page that raced an edit can overlap held rows; the held copy is newer.
- messages: [...action.messages.filter((message) => !held.has(message.id)), ...owner.messages],
- hasMore: action.hasMore,
- };
- };
- const bots = state.bots.map((bot) => (bot.threadId === action.threadId ? prepend(bot) : bot));
- const groups = state.groups.map((group) => (group.threadId === action.threadId ? prepend(group) : group));
- const owner = [...bots, ...groups].find((candidate) => candidate.threadId === action.threadId);
- const unreadDivider = placeUnreadDivider(state.unreadDivider, action.threadId, owner ? visibleMessages(owner) : [], action.hasMore);
- return { ...state, loadingOlder, bots, groups, unreadDivider };
- }
+ case "olderMessages":
+ return reduceOlderMessages(state, action);
case "sectionDeleted":
return {
...state, sections: action.sections,
@@ -1001,27 +981,9 @@ 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 "forkMessage": case "openForkPanel": case "forkPanelLoaded":
+ case "forkPanelMessage": case "forkPanelActive": case "closeForkPanel":
+ return reduceForkPanel(state, action);
case "showTeamMap":
case "showFiles": case "showWebPanel":
return {
@@ -1953,7 +1915,6 @@ export const initialState: AppState = {
export { api, ApiError, liveCallFromFrame, nextLiveCallLookup };
/** Messages per snapshot thread and per scrollback page: the server's own page maximum. */
-export const MESSAGE_PAGE_SIZE = 200;
export const SWITCH_MESSAGE_COUNT = 80;
type TrustedApprovalBridge = {
@@ -2346,33 +2307,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
) rawDispatch(action);
switch (action.type) {
case "loadOlderMessages": {
- // The guard, not the reducer flag: stateRef still holds the pre-dispatch state.
- if (olderPagesInFlight.has(action.threadId)) break;
- olderPagesInFlight.add(action.threadId);
- const current = stateRef.current;
- const owner = [...current.bots, ...current.groups].find((candidate) => candidate.threadId === action.threadId);
- const before = owner?.messages[0]?.id;
- const generation = current.transcriptGeneration[action.threadId] ?? 0;
- if (!before) {
- olderPagesInFlight.delete(action.threadId);
- rawDispatch({ type: "olderMessages", threadId: action.threadId, generation, messages: [], hasMore: false });
- break;
- }
- api<{ messages: Message[]; hasMore?: boolean }>(
- `/api/threads/${action.threadId}/messages?limit=${MESSAGE_PAGE_SIZE}&before=${encodeURIComponent(before)}`,
- )
- .finally(() => olderPagesInFlight.delete(action.threadId))
- .then((page) => rawDispatch({
- type: "olderMessages",
- threadId: action.threadId,
- generation,
- messages: page.messages ?? [],
- hasMore: Boolean(page.hasMore),
- }))
- .catch((error) => {
- rawDispatch({ type: "olderMessages", threadId: action.threadId, generation, messages: [], hasMore: true });
- showError(error);
- });
+ loadOlderPage(action, stateRef.current, olderPagesInFlight, rawDispatch, showError);
break;
}
case "notice":
@@ -2883,40 +2818,8 @@ 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);
+ case "forkMessage": case "openForkPanel": {
+ runForkEffect(action, dispatch, rawDispatch, showError);
break;
}
case "renameTask":