Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: preserve fork permissions and reconcile panel state
Zhehui Bi6b9290fde5a7
diff --git a/server/fork-tasks.test.ts b/server/fork-tasks.test.tsindex 1d969d16d7..c19fe28e98 100644--- a/server/fork-tasks.test.ts+++ b/server/fork-tasks.test.ts@@ -72,3 +72,37 @@ it("forks a room conversation into a normal room task", async () => {store.deleteGroupTask(room.id, sourceThreadId);expect(store.groupTaskByThread(room.id, fork!.threadId)).toBeTruthy();});++it("keeps the source thread's effective permissions without inheriting a pending elevation", async () => {+ const store = await freshStore();+ const bot = store.createBot();+ const anchor = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Restricted work" });+ store.patchTask(bot.id, bot.threadId, { approvalMode: "custom", autoApprove: false, alwaysAllow: ["provider-tool:example"] });+ const restricted = store.forkTask(bot.id, bot.threadId, anchor.id)!;+ expect(restricted).toMatchObject({ approvalMode: "custom", autoApprove: false, alwaysAllow: ["provider-tool:example"] });+ expect(restricted.alwaysAllow).not.toBe(store.taskByThread(bot.id, bot.threadId)?.alwaysAllow);++ store.bot(bot.id)!.approvalGrant = {+ requestId: "pending", mode: "full", phase: "prepared", threadId: bot.threadId, threadOnly: true,+ };+ const pending = store.forkTask(bot.id, bot.threadId, anchor.id)!;+ expect(pending).toMatchObject({ approvalMode: "ask", autoApprove: false });+ expect(store.projectBotForTask(bot.id, pending.threadId)?.approvalGrant).toBeUndefined();+});++it("removes copied history when registering the fork fails", async () => {+ const store = await freshStore();+ const bot = store.createBot();+ const anchor = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Keep this atomic" });+ const { createBotFork } = await import("./store-forks.ts");+ const { readMessage } = await import("./message-db.ts");+ let importedThreadId = "";+ expect(() => createBotFork(bot, store.activeTask(bot.id)!, store.activePath(bot.threadId), anchor.id,+ { mode: "ask", alwaysAllow: [] }, (task) => {+ importedThreadId = task.threadId;+ throw new Error("registry unavailable");+ })).toThrow("registry unavailable");+ expect(importedThreadId).not.toBe("");+ expect(readMessage(importedThreadId, anchor.id)).toBeNull();+ expect(store.taskByThread(bot.id, importedThreadId)).toBeUndefined();+});diff --git a/server/index.test.ts b/server/index.test.tsindex 4a1e4e7c3e..dbc750b6f4 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -2975,6 +2975,11 @@ describe("harness HTTP API", () => {}});+ it("marks a DM's canonical thread read without requiring a room task", async () => {+ expect((await api("POST", "/api/groups/test-dm/read", { threadId: "test-dm-thread" })).status).toBe(200);+ expect((await api("POST", "/api/groups/test-dm/read", { threadId: "another-thread" })).status).toBe(404);+ });+it("keeps bot-to-bot channels single-threaded and lets another task start beside an open approval", async () => {const dm = await api("POST", "/api/groups/test-dm/tasks", {});expect(dm.status).toBe(400);diff --git a/server/message-db.ts b/server/message-db.tsindex 605d6ee116..8c74d95d38 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -447,7 +447,7 @@ export function insertMessage(threadId: string, message: Message): void {}/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */-export function importThread(threadId: string, messages: Message[], activeLeafId: string | null, relinked?: ReadonlyArray<{ id: string; parentId: string | null }>, beforeCommit?: () => void): void {+export function importThread(threadId: string, messages: Message[], activeLeafId: string | null, relinked?: ReadonlyArray<{ id: string; parentId: string | null }>): void {transaction((database) => {if (!relinked && (database.prepare("SELECT 1 FROM messages WHERE thread_id = ? LIMIT 1").get(threadId) ||database.prepare("SELECT 1 FROM thread_state WHERE thread_id = ?").get(threadId))) {@@ -461,7 +461,6 @@ export function importThread(threadId: string, messages: Message[], activeLeafIdconst link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");for (const row of relinked ?? []) link.run(row.parentId, threadId, row.id);setActiveLeaf(threadId, activeLeafId);- beforeCommit?.();});}diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 1429f5a61a..2273aa082f 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -298,7 +298,9 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!room) return json(res, 404, { error: "no such room" });const body = await readBody(req);const threadId = body?.threadId ?? room.threadId;- if (typeof threadId !== "string" || !store.groupTaskByThread(room.id, threadId)) {+ if (typeof threadId !== "string" || (room.dm+ ? threadId !== room.threadId+ : !store.groupTaskByThread(room.id, threadId))) {return json(res, 404, { error: "no such channel task" });}sawThread(threadId);diff --git a/server/store-forks.ts b/server/store-forks.tsindex 9d0c8465b9..a9183a0e11 100644--- a/server/store-forks.ts+++ b/server/store-forks.ts@@ -4,6 +4,7 @@ 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";+import type { ApprovalMode } from "../shared/approval-mode.ts";function forkHistory(path: Message[], messageId: string): Message[] | null {const anchor = path.findIndex((message) => message.id === messageId);@@ -11,7 +12,21 @@ function forkHistory(path: Message[], messageId: string): Message[] | null {return structuredClone(path.slice(0, anchor + 1));}-/** Import the copied message path and register the task in the same database transaction. */+/** Commit copied history first; a failed database commit must never leave a visible task without its history. */+function registerImportedFork<T extends { threadId: string }>(task: T, history: Message[], messageId: string,+ register: (task: T) => void): void {+ mdb.importThread(task.threadId, history, messageId);+ try {+ register(task);+ } catch (error) {+ // The registry writer rolls back its in-memory mutation on failure.+ try { mdb.deleteThread(task.threadId); } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], "could not roll back the imported fork");+ }+ throw error;+ }+}+export function createGroupFork(source: GroupTaskRecord, path: Message[], messageId: string,register: (task: GroupTaskRecord) => void): GroupTaskRecord | null {const history = forkHistory(path, messageId);@@ -25,18 +40,23 @@ export function createGroupFork(source: GroupTaskRecord, path: Message[], messagorigin: { threadId: source.threadId, messageId },...(source.pinnedCwd !== undefined ? { pinnedCwd: source.pinnedCwd } : {}),};- mdb.importThread(task.threadId, history, messageId, undefined, () => register(task));+ registerImportedFork(task, history, messageId, register);return task;}export function createBotFork(bot: BotRecord, source: TaskRecord, path: Message[], messageId: string,+ approval: { mode: ApprovalMode; alwaysAllow: 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);+ // A fork starts with the source's effective permissions, including an Ask mask for an unconfirmed grant.+ task.approvalMode = approval.mode;+ task.autoApprove = approval.mode === "auto";+ task.alwaysAllow = structuredClone(approval.alwaysAllow);task.origin = { threadId: source.threadId, messageId };task.lastReadMessageId = messageId;- mdb.importThread(task.threadId, history, messageId, undefined, () => register(task));+ registerImportedFork(task, history, messageId, register);return task;}diff --git a/server/store.ts b/server/store.tsindex 024bc081af..3e718e9c29 100644--- a/server/store.ts+++ b/server/store.ts@@ -2190,7 +2190,9 @@ export class Store {const bot = this.bot(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,+ { 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 });return task;diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsxindex b5d035e3c5..6316936987 100644--- a/src/components/ForkPanel.tsx+++ b/src/components/ForkPanel.tsx@@ -1,5 +1,5 @@import { X } from "lucide-react";-import { useStore } from "@/state/store";+import { currentTaskBot, useStore } from "@/state/store";import { t } from "@/lib/i18n";import { ChatView } from "./ChatView";import { GroupView } from "./GroupView";@@ -10,10 +10,13 @@ export function ForkPanel() {if (!panel) return null;const bot = panel.kind === "bot" ? state.bots.find((candidate) => candidate.id === panel.ownerId) : undefined;const group = panel.kind === "group" ? state.groups.find((candidate) => candidate.id === panel.ownerId) : undefined;- const task = bot?.tasks?.find((candidate) => candidate.threadId === panel.threadId)- ?? group?.tasks?.find((candidate) => candidate.threadId === panel.threadId);- const openedBot = bot && task ? { ...bot, threadId: panel.threadId, messages: panel.messages, activeLeafId: panel.activeLeafId, hasMore: false } : null;- const openedGroup = group && task ? { ...group, threadId: panel.threadId, messages: panel.messages, hasMore: false } : null;+ const botTask = bot?.tasks?.find((candidate) => candidate.threadId === panel.threadId);+ const groupTask = group?.tasks?.find((candidate) => candidate.threadId === panel.threadId);+ const task = botTask ?? groupTask;+ const openedBot = bot && botTask ? { ...currentTaskBot(bot, panel.threadId), messages: panel.messages, activeLeafId: panel.activeLeafId, hasMore: false } : null;+ const openedGroup = group && groupTask ? { ...group, threadId: panel.threadId, messages: panel.messages, hasMore: false,+ working: groupTask.working ?? false, busyBotId: groupTask.busyBotId ?? null,+ 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">@@ -24,6 +27,13 @@ export function ForkPanel() {</div><div className="min-h-0 flex-1">{panel.loading ? <p className="p-4 text-sm text-ink-secondary">{t("chat.loadingFork")}</p>+ : 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 })}>+ {t("chat.retry")}+ </button>+ </div>: openedBot ? <ChatView key={panel.threadId} bot={openedBot} />: openedGroup ? <GroupView key={panel.threadId} group={openedGroup} />: <p className="p-4 text-sm text-ink-secondary">{t("chat.forkUnavailable")}</p>}diff --git a/src/state/fork-panel.test.ts b/src/state/fork-panel.test.tsnew file mode 100644index 0000000000..c16621aa93--- /dev/null+++ b/src/state/fork-panel.test.ts@@ -0,0 +1,47 @@+import { expect, it } from "vitest";+import { addForkOptimistic, reduceForkPanel, removeForkOptimistic, type ForkPanelState } from "./fork-panel";+import type { AppState, Message } from "./store";++const source: Message = { id: "source", role: "user", kind: "text", text: "Start", at: 1, parentId: null };+const panel = (): ForkPanelState => ({+ kind: "bot", ownerId: "bot", threadId: "fork", messages: [source], activeLeafId: source.id,+ loading: false, loadId: "load-1", loadFailed: false,+});+const state = (forkPanel = panel()): AppState => ({+ forkPanel, bots: [{ id: "bot", threadId: "main" }], groups: [],+}) as unknown as AppState;++it("reconciles a send in the fork panel and keeps an off-leaf insertion off the visible path", () => {+ const sent = addForkOptimistic(state(), { type: "send", botId: "bot", threadId: "fork", text: "Continue", sendId: "send-1" });+ expect(sent.forkPanel?.messages.at(-1)?.id).toBe("optimistic-send-1");+ const confirmed: Message = { id: "confirmed", role: "user", kind: "text", text: "Continue", at: 2, parentId: source.id, sendId: "send-1" };+ const arrived = reduceForkPanel(sent, { type: "forkPanelMessage", threadId: "fork", message: confirmed });+ expect(arrived.forkPanel?.messages.map((message) => message.id)).toEqual(["source", "confirmed"]);+ expect(arrived.forkPanel?.activeLeafId).toBe("confirmed");+ const offLeaf: Message = { id: "artifact", role: "bot", kind: "text", text: "Late", at: 3, parentId: source.id };+ const late = reduceForkPanel(arrived, { type: "forkPanelMessage", threadId: "fork", message: offLeaf });+ expect(late.forkPanel?.activeLeafId).toBe("confirmed");+});++it("restores the fork leaf after a failed optimistic send", () => {+ const sent = addForkOptimistic(state(), { type: "send", botId: "bot", threadId: "fork", text: "Continue", sendId: "send-1" });+ const removed = removeForkOptimistic(sent, { type: "optimisticMessageRemoved", threadId: "fork", sendId: "send-1" });+ expect(removed.forkPanel?.messages).toEqual([source]);+ expect(removed.forkPanel?.activeLeafId).toBe(source.id);+});++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);+ const failed = reduceForkPanel(retry, { type: "forkPanelLoadFailed", threadId: "fork", loadId: "load-2" });+ expect(failed.forkPanel).toMatchObject({ loading: false, loadFailed: true });+});++it("prefers a live patch over an older fetched copy while loading", () => {+ const loading = reduceForkPanel(state(), { type: "openForkPanel", kind: "bot", ownerId: "bot", threadId: "fork", loadId: "load-2" });+ const live: Message = { ...source, text: "Updated" };+ const updated = reduceForkPanel(loading, { type: "forkPanelMessage", threadId: "fork", message: live, patch: true });+ const loaded = reduceForkPanel(updated, { type: "forkPanelLoaded", threadId: "fork", loadId: "load-2", messages: [source], activeLeafId: source.id });+ expect(loaded.forkPanel).toMatchObject({ loading: false, activeLeafId: source.id });+ expect(loaded.forkPanel?.messages[0]?.text).toBe("Updated");+});diff --git a/src/state/fork-panel.ts b/src/state/fork-panel.tsindex ba2c6e7afa..f1caa90c76 100644--- a/src/state/fork-panel.ts+++ b/src/state/fork-panel.ts@@ -1,5 +1,6 @@import { api } from "./api";import { loadFullThread } from "./message-history";+import { optimisticMessageId, optimisticUserMessage } from "./optimistic-send";import type { Action, AppState, BotAnnouncement, Group, Message } from "./store";export interface ForkPanelState {@@ -9,12 +10,15 @@ export interface ForkPanelState {messages: Message[];activeLeafId: string | null;loading: boolean;+ loadId: string;+ loadFailed: 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: "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 }| { type: "forkPanelMessage"; threadId: string; message: Message; patch?: true }| { type: "forkPanelActive"; threadId: string; activeLeafId: string }| { type: "closeForkPanel" };@@ -24,17 +28,34 @@ export function reduceForkPanel(state: AppState, action: ForkPanelAction): AppStcase "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 } };+ forkPanel: { kind: action.kind, ownerId: action.ownerId, threadId: action.threadId, messages: [], activeLeafId: null,+ loading: true, loadId: action.loadId ?? "", loadFailed: false } };+ case "forkPanelLoaded": {+ const panel = state.forkPanel;+ if (panel?.threadId !== action.threadId || panel.loadId !== action.loadId) return state;+ const live = new Map(panel.messages.map((message) => [message.id, message]));+ const loaded = new Set(action.messages.map((message) => message.id));+ const messages = [...action.messages.map((message) => live.get(message.id) ?? message),+ ...panel.messages.filter((message) => !loaded.has(message.id))];+ return { ...state, forkPanel: { ...panel, messages, activeLeafId: panel.activeLeafId ?? action.activeLeafId,+ loading: false, loadFailed: false } };+ }+ case "forkPanelLoadFailed":+ return state.forkPanel?.threadId === action.threadId && state.forkPanel.loadId === action.loadId+ ? { ...state, forkPanel: { ...state.forkPanel, loading: false, loadFailed: true } } : state;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 } };+ const optimisticId = action.message.sendId ? optimisticMessageId(action.message.sendId) : null;+ const replacedOptimistic = optimisticId && panel.messages.some((message) => message.id === optimisticId);+ const existing = panel.messages.some((message) => message.id === action.message.id);+ const messages = existing || replacedOptimistic+ ? panel.messages.map((message) => message.id === action.message.id || message.id === optimisticId ? action.message : message)+ : action.patch && !panel.loading ? panel.messages : [...panel.messages, action.message];+ const activeLeafId = replacedOptimistic && panel.activeLeafId === optimisticId ? action.message.id+ : !action.patch && !panel.loading && !existing && (action.message.parentId ?? null) === panel.activeLeafId+ ? action.message.id : panel.activeLeafId;+ return { ...state, forkPanel: { ...panel, messages, activeLeafId } };}case "forkPanelActive":return state.forkPanel?.threadId === action.threadId@@ -44,6 +65,32 @@ export function reduceForkPanel(state: AppState, action: ForkPanelAction): AppSt}}+type ForkSend = Extract<Action, { type: "send" | "sendGroup" }>;+export function addForkOptimistic(state: AppState, action: ForkSend): AppState {+ const panel = state.forkPanel;+ const kind = action.type === "send" ? "bot" : "group";+ const ownerId = action.type === "send" ? action.botId : action.groupId;+ const selectedThreadId = action.type === "send"+ ? state.bots.find((bot) => bot.id === ownerId)?.threadId+ : state.groups.find((group) => group.id === ownerId)?.threadId;+ if (!panel || panel.kind !== kind || panel.ownerId !== ownerId || !action.sendId ||+ (action.threadId ?? selectedThreadId) !== panel.threadId || panel.messages.some((message) => message.sendId === action.sendId)) return state;+ const message = optimisticUserMessage(action.text, action.sendId, action.replyToId, panel.activeLeafId,+ action.type === "sendGroup" ? action.mode ?? "chat" : undefined);+ return { ...state, forkPanel: { ...panel, messages: [...panel.messages, message], activeLeafId: message.id } };+}++export function removeForkOptimistic(state: AppState, action: Extract<Action, { type: "optimisticMessageRemoved" }>): AppState {+ const panel = state.forkPanel;+ const optimisticId = optimisticMessageId(action.sendId);+ if (panel?.threadId !== action.threadId || !panel.messages.some((message) => message.id === optimisticId)) return state;+ const optimistic = panel.messages.find((message) => message.id === optimisticId)!;+ return { ...state, forkPanel: { ...panel,+ messages: panel.messages.filter((message) => message.id !== optimisticId),+ activeLeafId: panel.activeLeafId === optimisticId+ ? action.restoreLeafId ?? optimistic.parentId ?? null : panel.activeLeafId } };+}+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 {@@ -61,7 +108,11 @@ export function runForkEffect(action: ForkEffect, dispatch: (action: Action) =>}const owner = action.kind === "bot" ? "bots" : "groups";void api(`/api/${owner}/${action.ownerId}/read`, { method: "POST", body: JSON.stringify({ threadId: action.threadId }) }).catch(() => {});+ const loadId = action.loadId ?? "";void loadFullThread(action.threadId).then(({ messages, activeLeafId }) => {- rawDispatch({ type: "forkPanelLoaded", threadId: action.threadId, messages, activeLeafId });- }).catch(showError);+ rawDispatch({ type: "forkPanelLoaded", threadId: action.threadId, loadId, messages, activeLeafId });+ }).catch((error) => {+ rawDispatch({ type: "forkPanelLoadFailed", threadId: action.threadId, loadId });+ showError(error);+ });}diff --git a/src/state/read-visible.test.ts b/src/state/read-visible.test.tsnew file mode 100644index 0000000000..568b8695b4--- /dev/null+++ b/src/state/read-visible.test.ts@@ -0,0 +1,26 @@+import { expect, it } from "vitest";+import { markVisibleBotThreadsRead, markVisibleGroupThreadsRead } from "./read-visible";+import type { AppState, BotAnnouncement, Group } from "./store";++it("marks both visible bot threads read while leaving a hidden task unread", () => {+ const bot = { id: "bot", unread: true, tasks: [+ { threadId: "main", unread: true }, { threadId: "fork", unread: true }, { threadId: "hidden", unread: true },+ ] } as unknown as BotAnnouncement;+ const state = { selectedId: "bot", activeView: "chat", bots: [{ id: "bot", threadId: "main" }],+ forkPanel: { kind: "bot", ownerId: "bot", threadId: "fork" } } as unknown as AppState;+ const read: string[] = [];+ markVisibleBotThreadsRead(state, bot, true, (_path, threadId) => read.push(threadId));+ expect(read).toEqual(["main", "fork"]);+ expect(bot.tasks?.map((task) => task.unread)).toEqual([false, false, true]);+ expect(bot.unread).toBe(true);+});++it("marks the main room and its open fork read", () => {+ const group = { id: "room", unread: true } as Partial<Group> & { id: string };+ const state = { selectedId: "room", activeView: "chat", groups: [{ id: "room", threadId: "main" }],+ forkPanel: { kind: "group", ownerId: "room", threadId: "fork" } } as unknown as AppState;+ const read: string[] = [];+ markVisibleGroupThreadsRead(state, group, true, (_path, threadId) => read.push(threadId));+ expect(read).toEqual(["main", "fork"]);+ expect(group.unread).toBe(false);+});diff --git a/src/state/read-visible.ts b/src/state/read-visible.tsnew file mode 100644index 0000000000..1b2bc13757--- /dev/null+++ b/src/state/read-visible.ts@@ -0,0 +1,35 @@+import { botShowsUnread } from "@/lib/bot-unread";+import type { AppState, BotAnnouncement, Group } from "./store";++type SendRead = (path: string, threadId: string) => void;+const sendRead: SendRead = (path, threadId) => {+ void fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});+};++/** The main conversation and its side fork are both visible while the panel is open. */+export function markVisibleBotThreadsRead(state: AppState, bot: BotAnnouncement, focused: boolean, post: SendRead = sendRead): void {+ if (bot.id !== state.selectedId || state.activeView !== "chat" || !focused) return;+ const selected = state.bots.find((candidate) => candidate.id === bot.id);+ const shown = selected?.switchingTo ?? selected?.threadId;+ const panel = state.forkPanel;+ const visibleThreads = [...new Set([shown, panel?.kind === "bot" && panel.ownerId === bot.id ? panel.threadId : undefined])]+ .filter((threadId): threadId is string => Boolean(threadId));+ for (const threadId of visibleThreads) {+ const task = bot.tasks?.find((candidate) => candidate.threadId === threadId);+ if (!task?.unread && (bot.tasks || !bot.unread)) continue;+ if (task) task.unread = false;+ post(`/api/bots/${bot.id}/read`, threadId);+ }+ bot.unread = bot.tasks ? botShowsUnread(bot) : false;+}++export function markVisibleGroupThreadsRead(state: AppState, group: Partial<Group> & { id: string }, focused: boolean,+ post: SendRead = sendRead): void {+ if (!group.unread || group.id !== state.selectedId || state.activeView !== "chat" || !focused) return;+ group.unread = false;+ const shown = state.groups.find((candidate) => candidate.id === group.id)?.threadId;+ const panel = state.forkPanel;+ const visibleThreads = [...new Set([shown, panel?.kind === "group" && panel.ownerId === group.id ? panel.threadId : undefined])]+ .filter((threadId): threadId is string => Boolean(threadId));+ for (const threadId of visibleThreads) post(`/api/groups/${group.id}/read`, threadId);+}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 50364ef4e5..f4a53a505e 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -2,7 +2,7 @@ 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 { addForkOptimistic, reduceForkPanel, removeForkOptimistic, runForkEffect, type ForkPanelAction, type ForkPanelState } from "./fork-panel";import {createContext,useCallback,@@ -56,7 +56,7 @@ import {import type { Routine, RoutineInput, RoutineRun, RoutineRunStatusFilter } from "@/lib/routines";import type { WebhookAttempt, WebhookIngressStatus, WebhookTrigger } from "@/lib/webhooks";import { duplicateBotProfile, restrictedCopyRequest } from "@/lib/bot-duplicate";-import { botShowsUnread } from "@/lib/bot-unread";+import { markVisibleBotThreadsRead, markVisibleGroupThreadsRead } from "./read-visible";import { placeUnreadDivider, threadOpensUnread, threadReadCursor, unreadDividerFor, type UnreadDivider } from "@/lib/unread-divider";import type { ComputerStart } from "@/lib/computer-start";import { parseComputerHelp } from "@/lib/computer-control";@@ -981,7 +981,7 @@ export function reducer(state: AppState, action: Action): AppState {};case "showChat":return state.activeView === "chat" ? state : { ...state, activeView: "chat" };- case "forkMessage": case "openForkPanel": case "forkPanelLoaded":+ case "forkMessage": case "openForkPanel": case "forkPanelLoaded": case "forkPanelLoadFailed":case "forkPanelMessage": case "forkPanelActive": case "closeForkPanel":return reduceForkPanel(state, action);case "showTeamMap":@@ -1286,17 +1286,18 @@ export function reducer(state: AppState, action: Action): AppState {return animated;}case "optimisticMessageRemoved": {+ const panelState = removeForkOptimistic(state, action);const id = optimisticMessageId(action.sendId);const remove = (messages: Message[], optimistic: Message) => messages.filter((message) => message.id !== id).map((message) => message.optimisticThreadOrderAt === optimistic.at? { ...message, optimisticThreadOrderAt: optimistic.optimisticThreadOrderAt }: message);- const bot = state.bots.find((candidate) => candidate.threadId === action.threadId);+ const bot = panelState.bots.find((candidate) => candidate.threadId === action.threadId);if (bot) {const optimistic = bot.messages.find((message) => message.id === id);- if (!optimistic) return state;- const cleared = updateBot(state, bot.id, (current) => ({+ if (!optimistic) return panelState;+ const cleared = updateBot(panelState, bot.id, (current) => ({...current,messages: remove(current.messages, optimistic),activeLeafId: current.activeLeafId === id@@ -1307,12 +1308,12 @@ export function reducer(state: AppState, action: Action): AppState {const kept = cleared.bots.find((candidate) => candidate.id === bot.id)?.messages ?? [];return rewindThreadUpdatedAt(cleared, action.threadId, kept, task?.createdAt ?? 0, bot.hasMore ? optimistic.optimisticThreadOrderAt : undefined);}- const group = state.groups.find((candidate) => candidate.threadId === action.threadId);+ const group = panelState.groups.find((candidate) => candidate.threadId === action.threadId);const optimistic = group?.messages.find((message) => message.id === id);- if (!group || !optimistic) return state;+ if (!group || !optimistic) return panelState;const cleared = {- ...state,- groups: state.groups.map((candidate) => candidate.id === group.id+ ...panelState,+ groups: panelState.groups.map((candidate) => candidate.id === group.id? { ...candidate, messages: remove(candidate.messages, optimistic) }: candidate),};@@ -1676,11 +1677,11 @@ export function reducer(state: AppState, action: Action): AppState {return { ...state, pendingQueued };}case "send": {- const animated = withMascotMotion(+ const animated = addForkOptimistic(withMascotMotion(dismissOnboardingCard(state, action.botId),action.botId,"working",- );+ ), action);if (!action.sendId) return animated;const bot = animated.bots.find((candidate) => candidate.id === action.botId);const threadId = action.threadId ?? bot?.threadId;@@ -1808,10 +1809,11 @@ export function reducer(state: AppState, action: Action): AppState {return { ...state, dataView: action.view };case "sendGroup": {if (!action.sendId) return state;- const group = state.groups.find((candidate) => candidate.id === action.groupId);- if (!group) return state;+ const withPanel = addForkOptimistic(state, action);+ const group = withPanel.groups.find((candidate) => candidate.id === action.groupId);+ if (!group) return withPanel;const threadId: string = action.threadId ?? group.threadId;- if (threadId === group.threadId && group.messages.some((message) => message.sendId === action.sendId)) return state;+ if (threadId === group.threadId && group.messages.some((message) => message.sendId === action.sendId)) return withPanel;const message = optimisticUserMessage(action.text,action.sendId,@@ -1820,7 +1822,7 @@ export function reducer(state: AppState, action: Action): AppState {action.mode ?? "chat",);message.optimisticThreadOrderAt = group.tasks?.find((task) => task.threadId === threadId)?.lastThreadOrderAt;- const stamped = bumpThreadUpdatedAt(state, threadId, message.at, threadId === group.threadId);+ const stamped = bumpThreadUpdatedAt(withPanel, threadId, message.at, threadId === group.threadId);if (threadId !== group.threadId) return stamped;return {...stamped,@@ -2254,6 +2256,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {action = pinBotThreadAction(action, stateRef.current.bots);if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };if (action.type === "botPatched") action = { ...action, bot: withTaskWrites(action.bot) };+ if (action.type === "openForkPanel" && !action.loadId) action = { ...action, loadId: randomUuid() };if ((action.type === "send" || action.type === "sendGroup" || action.type === "editMessage") && !action.sendId) action = { ...action, sendId: randomUuid() };const botBeforeUpdate =action.type === "updateBot" || action.type === "setModel"@@ -2411,7 +2414,11 @@ export function StoreProvider({ children }: { children: ReactNode }) {const threadId =action.threadId ?? stateRef.current.bots.find((bot) => bot.id === action.botId)?.threadId;const sendId = action.sendId ?? randomUuid();- const arrived = () => sendArrived(stateRef.current.bots.find((bot) => bot.id === action.botId && bot.threadId === threadId)?.messages, sendId);+ const arrived = () => {+ const panel = stateRef.current.forkPanel;+ return sendArrived(panel?.kind === "bot" && panel.ownerId === action.botId && panel.threadId === threadId+ ? panel.messages : stateRef.current.bots.find((bot) => bot.id === action.botId && bot.threadId === threadId)?.messages, sendId);+ };void waitForExecutionSettings(botBeforeSend ? [botBeforeSend] : [], threadId).then(() => sendReconciled(() => api(`/api/bots/${action.botId}/messages`, {method: "POST",@@ -2422,6 +2429,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const body = sent.body;if (body?.message && typeof body.threadId === "string") {rawDispatch({ type: "messageAdded", threadId: body.threadId, message: body.message });+ rawDispatch({ type: "forkPanelMessage", threadId: body.threadId, message: body.message });}if (body?.queued &&@@ -2657,8 +2665,13 @@ export function StoreProvider({ children }: { children: ReactNode }) {const threadId =action.threadId ?? stateRef.current.groups.find((group) => group.id === action.groupId)?.threadId;const sendId = action.sendId ?? randomUuid();+ const arrived = () => {+ const panel = stateRef.current.forkPanel;+ return sendArrived(panel?.kind === "group" && panel.ownerId === action.groupId && panel.threadId === threadId+ ? panel.messages : stateRef.current.groups.find((group) => group.id === action.groupId && group.threadId === threadId)?.messages, sendId);+ };void waitForExecutionSettings(executionBotsBeforeAction)- .then(() => api(`/api/groups/${action.groupId}/messages`, {+ .then(() => sendReconciled(() => api(`/api/groups/${action.groupId}/messages`, {method: "POST",body: JSON.stringify({text: action.text,@@ -2667,10 +2680,13 @@ export function StoreProvider({ children }: { children: ReactNode }) {sendId,mode: action.mode ?? "chat", ...(action.mentions?.length ? { mentions: action.mentions } : {}),}),- }))- .then((body) => {+ }), arrived))+ .then((sent) => {+ if (!("body" in sent)) return;+ const body = sent.body;if (body?.message && typeof body.threadId === "string") {rawDispatch({ type: "messageAdded", threadId: body.threadId, message: body.message });+ rawDispatch({ type: "forkPanelMessage", threadId: body.threadId, message: body.message });}if (body?.queued &&@@ -3123,17 +3139,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {break;case "bot": {const bot = frame.bot as BotAnnouncement;- const selected = stateRef.current.bots.find((candidate) => candidate.id === bot.id);- const shown = selected?.switchingTo ?? selected?.threadId;- const panel = stateRef.current.forkPanel;- const readThreadId = panel?.kind === "bot" && panel.ownerId === bot.id ? panel.threadId : shown;- const selectedTask = bot.tasks?.find((task) => task.threadId === readThreadId);- if (bot.id === stateRef.current.selectedId && stateRef.current.activeView === "chat" && document.hasFocus() &&- (selectedTask?.unread || (!bot.tasks && bot.unread))) {- if (selectedTask) selectedTask.unread = false;- bot.unread = botShowsUnread(bot);- fetch(`/api/bots/${bot.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId: readThreadId }) }).catch(() => {});- }+ markVisibleBotThreadsRead(stateRef.current, bot, document.hasFocus());rawDispatch({type: "botPatched",bot: withTaskWrites({ ...bot, ...botPatchQueue.overlayFor(bot.id) }),@@ -3142,12 +3148,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {}case "group": {const group = frame.group as Partial<Group> & { id: string };- if (group.unread && group.id === stateRef.current.selectedId && document.hasFocus()) {- group.unread = false;- const panel = stateRef.current.forkPanel;- const threadId = panel?.kind === "group" && panel.ownerId === group.id ? panel.threadId : undefined;- fetch(`/api/groups/${group.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {});- }+ markVisibleGroupThreadsRead(stateRef.current, group, document.hasFocus());rawDispatch({ type: "groupPatched", group });break;}