Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(state): retain newly created tasks during reconnect hydration
Sebastian B3c4fd10158ff
diff --git a/src/state/snapshot-navigation.test.ts b/src/state/snapshot-navigation.test.tsindex 69e63a4e80..fe75500c2b 100644--- a/src/state/snapshot-navigation.test.ts+++ b/src/state/snapshot-navigation.test.ts@@ -44,6 +44,7 @@ let root: Root;let container: HTMLDivElement;let snapshot: ReturnType<typeof deferred>;let switchResponse: ReturnType<typeof deferred> | undefined;+let newTaskResponse: ReturnType<typeof deferred> | undefined;let snapshots: number;let sends: unknown[];const shown = () => state.bots[0]!;@@ -51,8 +52,11 @@ 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"] }));+const applySnapshot = async (threadId = "a", taskIds = ["a", "b"]) => {+ const incomingBot = bot(threadId, "snapshot"), incomingRoom = room(threadId, "snapshot");+ incomingBot.tasks = incomingBot.tasks?.filter(task => taskIds.includes(task.threadId));+ incomingRoom.tasks = incomingRoom.tasks?.filter(task => taskIds.includes(task.threadId.slice(5)));+ snapshot.resolve(json({ bots: [incomingBot], groups: [incomingRoom], sections: ["resynced"] }));await vi.waitFor(() => expect(state.sections).toEqual(["resynced"]));};const switchBot = async (threadId: string) => {@@ -65,6 +69,7 @@ beforeEach(async () => {sends = [];snapshot = deferred();switchResponse = undefined;+ newTaskResponse = undefined;localStorage.clear();vi.stubGlobal("EventSource", FixtureEventSource);vi.stubGlobal("fetch", async (path: string, init?: RequestInit) => {@@ -74,6 +79,7 @@ beforeEach(async () => {}const task = path.match(/^\/api\/bots\/bot\/tasks\/([ab])/);if (task) return switchResponse?.promise ?? json({ bot: bot(task[1]!, `fresh-${task[1]}`) });+ if (path === "/api/bots/bot/tasks" || path === "/api/groups/room/tasks") return newTaskResponse?.promise ?? json({});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: [] });@@ -95,6 +101,25 @@ afterEach(() => {});describe("navigation while a reconnect snapshot is in flight", () => {+ it.each(["bot", "group"])("keeps a new %s task entry without restoring tasks omitted by the server", async owner => {+ await resync();+ newTaskResponse = deferred();+ flushSync(() => dispatch(owner === "bot"+ ? { type: "newTask", botId: "bot" }+ : { type: "newGroupTask", groupId: "room" }));+ const createdBot = bot("c", "created"), createdRoom = room("c", "created");+ createdBot.tasks = [...tasks, { threadId: "c", title: "Created", createdAt: 2 }];+ createdRoom.tasks = [...createdRoom.tasks!, { threadId: "room-c", title: "Created", createdAt: 2 }];+ newTaskResponse.resolve(json(owner === "bot" ? { bot: createdBot } : { group: createdRoom }));+ const current = () => owner === "bot" ? shown() : state.groups[0]!;+ await vi.waitFor(() => expect(current().messages[0]?.id).toBe("created"));+ await applySnapshot("a", ["a"]);++ expect(current().threadId).toBe(owner === "bot" ? "c" : "room-c");+ expect(current().messages.map(message => message.id)).toEqual(["created"]);+ expect(current().tasks?.map(task => task.threadId)).toEqual(owner === "bot" ? ["a", "c"] : ["room-a", "room-c"]);+ });+it.each(["b", "a"])("keeps the newer %s transcript and sends to that thread", async target => {await resync();await switchBot("b");diff --git a/src/state/snapshot-navigation.ts b/src/state/snapshot-navigation.tsindex 683b8efb56..2851c8a645 100644--- a/src/state/snapshot-navigation.ts+++ b/src/state/snapshot-navigation.ts@@ -23,11 +23,19 @@ export function navigatedSince(|| (current[owner.threadId] ?? 0) !== (since?.[owner.threadId] ?? 0));}-export function keepBotNavigation(previous: Bot | undefined, incoming: Bot, preserve: boolean): Bot {+function keepNewTasks<T extends { threadId: string }>(previous: T[] | undefined, incoming: T[] | undefined, taskIdsAtStart: ReadonlySet<string> | undefined): T[] | undefined {+ if (!taskIdsAtStart) return incoming;+ const received = new Set(incoming?.map(task => task.threadId));+ const created = previous?.filter(task => !taskIdsAtStart.has(task.threadId) && !received.has(task.threadId)) ?? [];+ return created.length ? [...(incoming ?? []), ...created] : incoming;+}++export function keepBotNavigation(previous: Bot | undefined, incoming: Bot, preserve: boolean, taskIdsAtStart?: ReadonlySet<string>): Bot {if (!preserve || !previous) return incoming;return {...incoming,threadId: previous.threadId,+ tasks: keepNewTasks(previous.tasks, incoming.tasks, taskIdsAtStart),switchingTo: previous.switchingTo,awaitingThreadSnapshot: previous.awaitingThreadSnapshot,messages: previous.messages,@@ -37,11 +45,12 @@ export function keepBotNavigation(previous: Bot | undefined, incoming: Bot, pres};}-export function keepGroupNavigation(previous: Group | undefined, incoming: Group, preserve: boolean): Group {+export function keepGroupNavigation(previous: Group | undefined, incoming: Group, preserve: boolean, taskIdsAtStart?: ReadonlySet<string>): Group {if (!preserve || !previous) return incoming;return {...incoming,threadId: previous.threadId,+ tasks: keepNewTasks(previous.tasks, incoming.tasks, taskIdsAtStart),messages: previous.messages,hasMore: previous.hasMore,pinnedCwd: previous.pinnedCwd,diff --git a/src/state/store.tsx b/src/state/store.tsxindex 2df601d62a..178c88174b 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -666,6 +666,7 @@ export type Action =botQueuedMessages?: AppState["pendingQueued"];preserveNavigation?: boolean;navigationSince?: AppState["transcriptGeneration"];+ taskIdsAtStart?: ReadonlySet<string>;resumeId?: string;}| { type: "botQueues"; queues: AppState["pendingQueued"] }@@ -937,14 +938,14 @@ export function reducer(state: AppState, action: Action): AppState {bots: action.bots.map((bot) => {const previous = state.bots.find((candidate) => candidate.id === bot.id);return keepBotNavigation(previous, previous ? { ...bot, tasks: mergeTaskStamps(previous.tasks, bot.tasks) } : bot,- action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration));+ action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration), action.taskIdsAtStart);}),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 keepGroupNavigation(previous, merged, action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration));+ return keepGroupNavigation(previous, merged, action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration), action.taskIdsAtStart);}),sections: action.sections ?? [],computerControl: action.computerControl,@@ -3088,6 +3089,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const loadAll = async (): Promise<boolean> => {const navigationAtStart = selectionRevision.current;const navigationSince = stateRef.current.transcriptGeneration;+ const taskIdsAtStart = new Set([...stateRef.current.bots, ...stateRef.current.groups].flatMap(owner => owner.tasks?.map(task => task.threadId) ?? []));const since = stateRef.current.liveCallVersion;const seq = nextLiveCallLookup();void api<unknown>("/api/live/call")@@ -3108,6 +3110,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {botQueuedMessages,preserveNavigation: selectionRevision.current !== navigationAtStart,navigationSince,+ taskIdsAtStart,resumeId: readLastConversation() ?? undefined,});});