Skip to content

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

fix(state): preserve navigation during reconnect hydration

Sebastian B1d917caaf09a
diff --git a/src/state/snapshot-navigation.test.ts b/src/state/snapshot-navigation.test.ts
new file mode 100644
index 0000000000..69e63a4e80
--- /dev/null
+++ b/src/state/snapshot-navigation.test.ts
@@ -0,0 +1,154 @@
+// @vitest-environment happy-dom
+import { createElement, type Dispatch } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { StoreProvider, useStore, type Action, type AppState, type Bot, type Group, type Message } from "./store";
+
+class FixtureEventSource {
+ static current: FixtureEventSource;
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string }) => void) | null = null;
+ constructor() { FixtureEventSource.current = this; }
+ close() {}
+ send(frame: object) { this.onmessage?.({ data: JSON.stringify(frame) }); }
+}
+
+const line = (id: string): Message => ({ id, at: 1, role: "user", kind: "text", text: id, parentId: null });
+const tasks = ["a", "b"].map(threadId => ({ threadId, title: threadId, createdAt: 1 }));
+const bot = (threadId: string, id = threadId): Bot => ({
+ id: "bot", threadId, name: "Fixture", title: "", description: "", notifications: false,
+ unread: false, color: "green", modelSelection: { instanceId: "fake", model: "fixture" },
+ tasks, messages: [line(id)], activeLeafId: id,
+});
+const room = (threadId: string, id = threadId): Group => ({
+ id: "room", threadId: `room-${threadId}`, name: "Fixture room", memberIds: [],
+ defaultResponder: { kind: "mentions" }, bulletin: "", unread: false, createdAt: 1,
+ tasks: tasks.map(task => ({ ...task, threadId: `room-${task.threadId}` })), messages: [line(id)],
+});
+const json = (body: unknown) => new Response(JSON.stringify(body));
+const deferred = () => {
+ let resolve!: (response: Response) => void;
+ const promise = new Promise<Response>(done => { resolve = done; });
+ return { promise, resolve };
+};
+
+let state!: AppState;
+let dispatch!: Dispatch<Action>;
+function Probe() {
+ ({ state, dispatch } = useStore());
+ return null;
+}
+let root: Root;
+let container: HTMLDivElement;
+let snapshot: ReturnType<typeof deferred>;
+let switchResponse: ReturnType<typeof deferred> | undefined;
+let snapshots: number;
+let sends: unknown[];
+const shown = () => state.bots[0]!;
+const resync = async () => {
+ FixtureEventSource.current.send({ kind: "hello", resumed: false, cursor: "fixture:0" });
+ await vi.waitFor(() => expect(snapshots).toBe(2));
+};
+const applySnapshot = async (threadId = "a") => {
+ snapshot.resolve(json({ bots: [bot(threadId, "snapshot")], groups: [room(threadId, "snapshot")], sections: ["resynced"] }));
+ await vi.waitFor(() => expect(state.sections).toEqual(["resynced"]));
+};
+const switchBot = async (threadId: string) => {
+ flushSync(() => dispatch({ type: "switchTask", botId: "bot", threadId }));
+ await vi.waitFor(() => expect(shown().messages[0]?.id).toBe(`fresh-${threadId}`));
+};
+
+beforeEach(async () => {
+ snapshots = 0;
+ sends = [];
+ snapshot = deferred();
+ switchResponse = undefined;
+ localStorage.clear();
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", async (path: string, init?: RequestInit) => {
+ if (path.startsWith("/api/bots?")) {
+ snapshots++;
+ return snapshots === 1 ? json({ bots: [bot("a")], groups: [room("a")] }) : snapshot.promise;
+ }
+ const task = path.match(/^\/api\/bots\/bot\/tasks\/([ab])/);
+ if (task) return switchResponse?.promise ?? json({ bot: bot(task[1]!, `fresh-${task[1]}`) });
+ if (path.startsWith("/api/groups/room/tasks/room-b")) return json({ group: room("b", "fresh-room-b") });
+ if (path === "/api/bots/bot/messages" || path === "/api/groups/room/messages") sends.push(JSON.parse(String(init?.body)));
+ if (path === "/api/instances") return json({ instances: [] });
+ if (path === "/api/routines") return json({ routines: [], runs: [] });
+ if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });
+ return json({});
+ });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ FixtureEventSource.current.send({ kind: "hello", resumed: false, cursor: "fixture:0" });
+ await vi.waitFor(() => expect(state.hydrated).toBe(true));
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe("navigation while a reconnect snapshot is in flight", () => {
+ it.each(["b", "a"])("keeps the newer %s transcript and sends to that thread", async target => {
+ await resync();
+ await switchBot("b");
+ if (target === "a") await switchBot("a");
+ await applySnapshot();
+
+ expect(shown().threadId).toBe(target);
+ expect(shown().messages.map(message => message.id)).toEqual([`fresh-${target}`]);
+ expect(shown().activeLeafId).toBe(`fresh-${target}`);
+ FixtureEventSource.current.send({ kind: "bot", bot: bot("a", "stale-frame") });
+ flushSync(() => dispatch({ type: "send", botId: "bot", text: "Next", sendId: "next" }));
+ await vi.waitFor(() => expect(sends).toHaveLength(1));
+ expect(sends[0]).toMatchObject({ threadId: target, text: "Next" });
+ });
+
+ it("keeps a pending switch until its own response arrives", async () => {
+ await resync();
+ switchResponse = deferred();
+ flushSync(() => dispatch({ type: "switchTask", botId: "bot", threadId: "b" }));
+ await applySnapshot();
+
+ expect(shown().switchingTo).toBe("b");
+ switchResponse.resolve(json({ bot: bot("b", "fresh-b") }));
+ await vi.waitFor(() => expect(shown().threadId).toBe("b"));
+ expect(shown().messages.map(message => message.id)).toEqual(["fresh-b"]);
+ });
+
+ it("keeps the room thread opened after the request started", async () => {
+ await resync();
+ flushSync(() => dispatch({ type: "switchGroupTask", groupId: "room", threadId: "room-b" }));
+ await vi.waitFor(() => expect(state.groups[0]?.threadId).toBe("room-b"));
+ await applySnapshot();
+
+ expect(state.groups[0]?.threadId).toBe("room-b");
+ expect(state.groups[0]?.messages.map(message => message.id)).toEqual(["fresh-room-b"]);
+ flushSync(() => dispatch({ type: "sendGroup", groupId: "room", text: "Next", sendId: "next" }));
+ await vi.waitFor(() => expect(sends).toHaveLength(1));
+ expect(sends[0]).toMatchObject({ threadId: "room-b", text: "Next" });
+ });
+
+ it("accepts the server's thread when navigation did not change", async () => {
+ await resync();
+ await applySnapshot("b");
+ expect(shown().threadId).toBe("b");
+ expect(shown().messages.map(message => message.id)).toEqual(["snapshot"]);
+ expect(state.groups[0]?.threadId).toBe("room-b");
+ });
+
+ it("refreshes an unchanged conversation while another owner switches threads", async () => {
+ await resync();
+ flushSync(() => dispatch({ type: "switchGroupTask", groupId: "room", threadId: "room-b" }));
+ await vi.waitFor(() => expect(state.groups[0]?.threadId).toBe("room-b"));
+ await applySnapshot();
+ expect(shown().messages.map(message => message.id)).toEqual(["snapshot"]);
+ expect(state.groups[0]?.messages.map(message => message.id)).toEqual(["fresh-room-b"]);
+ });
+});
diff --git a/src/state/snapshot-navigation.ts b/src/state/snapshot-navigation.ts
new file mode 100644
index 0000000000..683b8efb56
--- /dev/null
+++ b/src/state/snapshot-navigation.ts
@@ -0,0 +1,54 @@
+import type { Bot, Group, Message } from "./store";
+
+export function visibleMessages(bot: Pick<Bot, "messages" | "activeLeafId">): Message[] {
+ const leafId = bot.activeLeafId;
+ if (!leafId) return bot.messages;
+ const byId = new Map(bot.messages.map((m) => [m.id, m]));
+ if (!byId.has(leafId)) return bot.messages;
+ const path: Message[] = [];
+ let cur = byId.get(leafId);
+ while (cur) {
+ path.push(cur);
+ cur = cur.parentId ? byId.get(cur.parentId) : undefined;
+ }
+ return path.reverse();
+}
+
+export function navigatedSince(
+ owner: Pick<Bot, "threadId" | "switchingTo"> | undefined,
+ since: Readonly<Record<string, number>> | undefined,
+ current: Readonly<Record<string, number>>,
+): boolean {
+ return owner !== undefined && (owner.switchingTo !== undefined
+ || (current[owner.threadId] ?? 0) !== (since?.[owner.threadId] ?? 0));
+}
+
+export function keepBotNavigation(previous: Bot | undefined, incoming: Bot, preserve: boolean): Bot {
+ if (!preserve || !previous) return incoming;
+ return {
+ ...incoming,
+ threadId: previous.threadId,
+ switchingTo: previous.switchingTo,
+ awaitingThreadSnapshot: previous.awaitingThreadSnapshot,
+ messages: previous.messages,
+ hasMore: previous.hasMore,
+ activeLeafId: previous.activeLeafId,
+ pinnedMessageId: previous.pinnedMessageId,
+ };
+}
+
+export function keepGroupNavigation(previous: Group | undefined, incoming: Group, preserve: boolean): Group {
+ if (!preserve || !previous) return incoming;
+ return {
+ ...incoming,
+ threadId: previous.threadId,
+ messages: previous.messages,
+ hasMore: previous.hasMore,
+ pinnedCwd: previous.pinnedCwd,
+ pinnedMessageId: previous.pinnedMessageId,
+ usage: previous.usage,
+ memberContext: previous.memberContext,
+ busyBotId: previous.busyBotId,
+ turnStartedAt: previous.turnStartedAt,
+ };
+}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index d26f85bdeb..2df601d62a 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -24,6 +24,8 @@ import { patchGroupTask } from "./thread-edits";
import { optimisticMessageId, optimisticUserMessage } from "./optimistic-send";
import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";
import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";
+import { keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";
+export { visibleMessages } from "./snapshot-navigation";
export { awayFromMainThread, botOpensTo, openBot, openBotThread, openNotificationTarget, openThread, visibleNotificationThread, type ThreadTarget } from "./thread-navigation";
import type { TurnDigest } from "../../shared/digest";
import type { ToolScope } from "../../shared/tool-scope";
@@ -420,20 +422,6 @@ function openedUnreadDivider(state: AppState, threadId: string, unread: boolean,
return messageId ? { threadId, messageId } : null;
}
-export function visibleMessages(bot: Pick<Bot, "messages" | "activeLeafId">): Message[] {
- const leafId = bot.activeLeafId;
- if (!leafId) return bot.messages;
- const byId = new Map(bot.messages.map((m) => [m.id, m]));
- if (!byId.has(leafId)) return bot.messages;
- const path: Message[] = [];
- let cur = byId.get(leafId);
- while (cur) {
- path.push(cur);
- cur = cur.parentId ? byId.get(cur.parentId) : undefined;
- }
- return path.reverse();
-}
-
import type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary } from "./config-status";
export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary };
@@ -676,6 +664,8 @@ export type Action =
sections?: string[];
computerControl: Record<string, ComputerControlState>;
botQueuedMessages?: AppState["pendingQueued"];
+ preserveNavigation?: boolean;
+ navigationSince?: AppState["transcriptGeneration"];
resumeId?: string;
}
| { type: "botQueues"; queues: AppState["pendingQueued"] }
@@ -946,14 +936,15 @@ export function reducer(state: AppState, action: Action): AppState {
...state,
bots: action.bots.map((bot) => {
const previous = state.bots.find((candidate) => candidate.id === bot.id);
- return previous ? { ...bot, tasks: mergeTaskStamps(previous.tasks, bot.tasks) } : bot;
+ return keepBotNavigation(previous, previous ? { ...bot, tasks: mergeTaskStamps(previous.tasks, bot.tasks) } : bot,
+ action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration));
}),
groups: action.groups.map((group) => {
const previous = state.groups.find((candidate) => candidate.id === group.id);
const merged = previous ? { ...group, tasks: mergeTaskStamps(previous.tasks, group.tasks) } : group;
// The wire carries an explicitly-cleared description as null; client state keeps it absent.
if (merged.description === null) merged.description = undefined;
- return merged;
+ return keepGroupNavigation(previous, merged, action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration));
}),
sections: action.sections ?? [],
computerControl: action.computerControl,
@@ -2164,7 +2155,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
tasks: bot.tasks?.map((task) => ({ ...task, ...taskPatchFields(taskWrites.get(task.threadId)?.patch ?? {}) })),
});
const [state, rawDispatch] = useReducer(reducer, initialState, restoreBotSettingsSection);
- const stateRef = useRef(state);
+ const stateRef = useRef(state), selectionRevision = useRef(0);
stateRef.current = state;
const showThreads = useShowThreads();
const showThreadsRef = useRef(showThreads);
@@ -2206,7 +2197,6 @@ export function StoreProvider({ children }: { children: ReactNode }) {
const dispatch = useMemo(() => {
const navigation = new Map<string, number>();
- let selectionRevision = 0;
const roomAnswer = roomAnswers(() => stateRef.current, rawDispatch);
const olderPagesInFlight = new Set<string>();
let creatingBot = false;
@@ -2313,7 +2303,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
};
const wrapped: React.Dispatch<Action> = (action) => {
- if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles"].includes(action.type)) selectionRevision++;
+ if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles"].includes(action.type)) selectionRevision.current++;
// Pin before any await or optimistic state change.
action = pinBotThreadAction(action, stateRef.current.bots);
if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };
@@ -2878,7 +2868,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
case "switchTask": {
const revision = (navigation.get(action.botId) ?? 0) + 1;
navigation.set(action.botId, revision);
- const selectedAtStart = selectionRevision;
+ const selectedAtStart = selectionRevision.current;
const ready = action.type === "newTask"
? botPatchQueue.flush(action.botId)
: Promise.resolve();
@@ -2889,7 +2879,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
if (action.type === "newTask") action.onCreated?.();
if (!r?.bot || navigation.get(action.botId) !== revision) return;
const selectsAfterCreation = action.type === "newTask" && action.cwd !== undefined;
- if (selectsAfterCreation && selectionRevision !== selectedAtStart) return;
+ if (selectsAfterCreation && selectionRevision.current !== selectedAtStart) return;
dispatch({ type: "taskSwitched", bot: r.bot });
if (selectsAfterCreation) rawDispatch({ type: "select", id: action.botId });
})
@@ -3096,6 +3086,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {
for (const key of keys) refreshState(key).version += 1;
};
const loadAll = async (): Promise<boolean> => {
+ const navigationAtStart = selectionRevision.current;
+ const navigationSince = stateRef.current.transcriptGeneration;
const since = stateRef.current.liveCallVersion;
const seq = nextLiveCallLookup();
void api<unknown>("/api/live/call")
@@ -3114,6 +3106,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {
sections: sections ?? [],
computerControl: computerControl ?? {},
botQueuedMessages,
+ preserveNavigation: selectionRevision.current !== navigationAtStart,
+ navigationSince,
resumeId: readLastConversation() ?? undefined,
});
});