Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Refresh conversation previews when branches change
CI fixture5aebc6688b9c
diff --git a/src/components/Sidebar.conversation-preview.dom.test.ts b/src/components/Sidebar.conversation-preview.dom.test.tsindex 6ea0cbe07c..f43a541688 100644--- a/src/components/Sidebar.conversation-preview.dom.test.ts+++ b/src/components/Sidebar.conversation-preview.dom.test.ts@@ -1,8 +1,8 @@// @vitest-environment happy-dom-import { act, createElement } from "react";+import { act, createElement, Fragment } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { initialState, StoreProvider, type Bot } from "@/state/store";+import { BotEditorStore, initialState, reducer, StoreProvider, type Bot } from "@/state/store";const network = vi.hoisted(() => vi.fn());vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: network }));@@ -77,6 +77,43 @@ it("distinguishes identical titles with their visible conversation lines", asyncexpect(network).toHaveBeenCalledTimes(2);});+it("refreshes cached sidebar and panel previews after switching the active branch", async () => {+ let branch = "Old branch";+ network.mockImplementation(async (path: string) => ({ messages: [{ id: path, role: "bot", kind: "text", text: path.includes("first") ? branch : "Other conversation", at: 10 }] }));+ const first: Bot = { ...bot, threadId: "first", messages: [+ { id: "old", role: "bot", kind: "text", text: "Old branch", at: 10 },+ { id: "new", role: "bot", kind: "text", text: "New branch", at: 11 },+ ], activeLeafId: "old" };+ let state = { ...initialState, bots: [bot] };+ const tree = (current: Bot) => createElement(BotEditorStore, {+ value: { state, dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() },+ children: createElement(Fragment, null,+ createElement(BotThreadList, { ...botRowProps(state, vi.fn(), current, { density: "comfortable", query: "", onMenu: vi.fn() }), selected: true }),+ createElement(BotConversations, { bot: current }),+ ),+ });+ await act(async () => root.render(tree(bot)));+ await visible("first");+ expect(row("first").textContent).toContain("Old branch");+ expect(host.querySelector('[data-conversation="first"]')?.textContent).toContain("Old branch");+ state = { ...state, bots: [first] };+ await act(async () => root.render(tree(first)));+ state = reducer(state, { type: "switchBranch", botId: bot.id, threadId: "first", messageId: "new" });+ branch = "New branch";+ await act(async () => root.render(tree(state.bots[0]!)));+ state = { ...state, bots: [bot] };+ await act(async () => root.render(tree(bot)));+ expect(row("first").textContent).toContain("New branch");+ expect(host.querySelector('[data-conversation="first"]')?.textContent).toContain("New branch");+ expect(network.mock.calls.filter(([path]) => path.includes("/first/"))).toHaveLength(2);+ branch = "Remote branch";+ state = reducer(state, { type: "threadActive", threadId: "first", activeLeafId: "remote" });+ await act(async () => root.render(tree(bot)));+ expect(row("first").textContent).toContain("Remote branch");+ expect(host.querySelector('[data-conversation="first"]')?.textContent).toContain("Remote branch");+ expect(network.mock.calls.filter(([path]) => path.includes("/first/"))).toHaveLength(3);+});+it("limits concurrent requests and drops queued rows when hidden", async () => {const resolve: Array<(value: unknown) => void> = [];network.mockImplementation(() => new Promise((done) => { resolve.push(done); }));diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 89a5e1a620..1e9942c620 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -449,7 +449,7 @@ export function currentArchivableBot(bots: readonly Bot[], id: string): Bot | unconst NO_FOLDERS: BotProject[] = [];-export function BotThreadList({ bot, selected, drafting, query, pendingQueued, routineRuns, reveal, locale, dispatch, instances, activityLabel, hidden = false }: BotRowProps & {+export function BotThreadList({ bot, selected, drafting, query, pendingQueued, routineRuns, transcriptGeneration, reveal, locale, dispatch, instances, activityLabel, hidden = false }: BotRowProps & {activityLabel?: string;hidden?: boolean;}) {@@ -513,7 +513,7 @@ export function BotThreadList({ bot, selected, drafting, query, pendingQueued, r}), [botId, dispatch]);const renderThread = (task: (typeof tasks)[number]) => {const thread = currentTaskBot(bot, task.threadId);- return <SidebarConversationRow key={task.threadId} bot={bot} instances={instances} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && !drafting && task.threadId === bot.threadId} main={task.threadId === bot.mainThreadId} folders={projects}+ return <SidebarConversationRow key={task.threadId} bot={bot} instances={instances} generation={transcriptGeneration?.[task.threadId] ?? 0} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && !drafting && task.threadId === bot.threadId} main={task.threadId === bot.mainThreadId} folders={projects}activityLabel={task.threadId === bot.threadId ? activityLabel : undefined} now={stampClock(threadRecency(task), now)} locale={locale} {...actions}selectMode={bulk.active} checked={selection.has(task.threadId)} onToggleSelect={bulk.toggle} />;};@@ -650,7 +650,7 @@ export interface BotRowProps {deleting: boolean;mascotMotion: AppState["mascotMotion"];reveal: AppState["revealThread"];- pendingQueued: AppState["pendingQueued"]; routineRuns?: AppState["routineRuns"];+ pendingQueued: AppState["pendingQueued"]; routineRuns?: AppState["routineRuns"]; transcriptGeneration?: AppState["transcriptGeneration"];instances: InstanceInfo[];liveCall: AppState["liveCall"];locale: string;@@ -665,7 +665,7 @@ export interface BotRowProps {botDragging?: boolean; /** With the one list on: this page's place, for each row's device mark (place-rows.ts). */ placeHere?: BotHome | null;}-export function botRowProps<State extends Pick<AppState, "activeView" | "selectedId" | "revealThread" | "deletingBots" | "mascotMotion" | "pendingQueued" | "routineRuns" | "instances" | "liveCall" | "config" | "newChat">>(+export function botRowProps<State extends Pick<AppState, "activeView" | "selectedId" | "revealThread" | "deletingBots" | "mascotMotion" | "pendingQueued" | "routineRuns" | "instances" | "liveCall" | "config" | "newChat"> & Partial<Pick<AppState, "transcriptGeneration">>>(state: State,dispatch: Dispatch<Action>,bot: Bot,@@ -680,7 +680,7 @@ export function botRowProps<State extends Pick<AppState, "activeView" | "selectedeleting: state.deletingBots[bot.id] === true,mascotMotion: selected && state.mascotMotion?.botId === bot.id ? state.mascotMotion : null,reveal: reveal && (bot.threadId === reveal.threadId || bot.tasks?.some((task) => task.threadId === reveal.threadId)) ? reveal : null,- pendingQueued: botPendingQueued(bot, state.pendingQueued), routineRuns: botRoutineRuns(bot, state.routineRuns),+ pendingQueued: botPendingQueued(bot, state.pendingQueued), routineRuns: botRoutineRuns(bot, state.routineRuns), transcriptGeneration: state.transcriptGeneration,instances: state.instances,liveCall: state.liveCall,locale: activeLocale(),diff --git a/src/components/SidebarConversationRow.tsx b/src/components/SidebarConversationRow.tsxindex d26878a8f6..86a4bea314 100644--- a/src/components/SidebarConversationRow.tsx+++ b/src/components/SidebarConversationRow.tsx@@ -5,10 +5,10 @@ import { useSidebarRecentMessages } from "./bot-panel/Conversations";import { lastLine } from "./sidebar-preview";import { SidebarThreadRow } from "./SidebarThreadRow";-export function SidebarConversationRow({ bot, instances, ...props }: ComponentProps<typeof SidebarThreadRow> & { bot: Bot; instances: InstanceInfo[] }) {+export function SidebarConversationRow({ bot, instances, generation, ...props }: ComponentProps<typeof SidebarThreadRow> & { bot: Bot; instances: InstanceInfo[]; generation: number }) {const ref = useRef<HTMLDivElement>(null);const onScreen = useOnScreen(ref);- const messages = useSidebarRecentMessages(bot, props.task, onScreen);+ const messages = useSidebarRecentMessages(bot, props.task, onScreen, generation);const preview = messages ? lastLine(currentTaskBot(bot, props.task.threadId), messages, instances, false) : undefined;return <div ref={ref}><SidebarThreadRow {...props} preview={preview} /></div>;}diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsxindex 870d6366e9..aef8012fd4 100644--- a/src/components/bot-panel/Conversations.tsx+++ b/src/components/bot-panel/Conversations.tsx@@ -23,7 +23,7 @@ const fetched = new Map<string, Message[]>();const requests = new Map<string, { promise: Promise<Message[] | undefined>; signal?: AbortSignal; promote?: () => void }>();let generation = 0;-const lineKey = (task: { threadId: string; updatedAt?: number; createdAt?: number }) => `${task.threadId}@${threadRecency(task)}`;+const lineKey = (task: { threadId: string; updatedAt?: number; createdAt?: number }, generation: number) => JSON.stringify([task.threadId, threadRecency(task), generation]);function fetchLine(key: string, signal?: AbortSignal, promote?: () => void): Promise<Message[] | undefined> {const existing = requests.get(key);@@ -39,7 +39,7 @@ function fetchLine(key: string, signal?: AbortSignal, promote?: () => void): Pro}return existing.promise;}- const threadId = key.slice(0, key.lastIndexOf("@"));+ const [threadId] = JSON.parse(key) as [string, number, number];const currentGeneration = generation;const entry = { promise: Promise.resolve<Message[] | undefined>(undefined), signal, promote };entry.promise = api<Page>(`/api/threads/${encodeURIComponent(threadId)}/messages?limit=${LAST_LINE_PAGE}`, signal ? { background: true, signal } : { background: true })@@ -56,10 +56,11 @@ function fetchLine(key: string, signal?: AbortSignal, promote?: () => void): Pro}/** Each listed conversation's newest messages: the open one from the chat, the rest fetched once per change. */-function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updatedAt?: number; createdAt?: number }[]): (threadId: string) => Message[] | undefined {+function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updatedAt?: number; createdAt?: number }[], generations: Record<string, number>): (threadId: string) => Message[] | undefined {const [, settle] = useState(0);const panel = useRef(new Map<string, Message[]>());- const wanted = JSON.stringify(threads.filter((task) => task.threadId !== bot.threadId).map(lineKey));+ const keyFor = (task: { threadId: string; updatedAt?: number; createdAt?: number }) => lineKey(task, generations[task.threadId] ?? 0);+ const wanted = JSON.stringify(threads.filter((task) => task.threadId !== bot.threadId).map(keyFor));useEffect(() => {let active = true;const keys = new Set<string>(JSON.parse(wanted));@@ -77,7 +78,7 @@ function useRecentMessages(bot: Bot, threads: readonly { threadId: string; updatreturn () => { active = false; };}, [wanted]);const open = visibleMessages(bot);- const byThread = new Map(threads.map((task) => [task.threadId, lineKey(task)]));+ const byThread = new Map(threads.map((task) => [task.threadId, keyFor(task)]));return (threadId) => threadId === bot.threadId ? open : panel.current.get(byThread.get(threadId) ?? "") ?? fetched.get(byThread.get(threadId) ?? "");}@@ -125,9 +126,9 @@ function startSidebarLines() {}}-export function useSidebarRecentMessages(bot: Bot, task: { threadId: string; updatedAt?: number; createdAt?: number }, onScreen: boolean): Message[] | undefined {+export function useSidebarRecentMessages(bot: Bot, task: { threadId: string; updatedAt?: number; createdAt?: number }, onScreen: boolean, generation: number): Message[] | undefined {const [, settle] = useState(0);- const key = lineKey(task);+ const key = lineKey(task, generation);useEffect(() => {if (!onScreen || task.threadId === bot.threadId || fetched.has(key)) return;const active = sidebarActive.get(key);@@ -163,7 +164,7 @@ export function forgetConversationLines(): void {}export function BotConversations({ bot }: { bot: Bot }) {- const state = useStoreSelector((s) => ({ instances: s.instances, pendingQueued: s.pendingQueued }), sameFields), dispatch = useStoreDispatch();+ const state = useStoreSelector((s) => ({ instances: s.instances, pendingQueued: s.pendingQueued, transcriptGeneration: s.transcriptGeneration }), sameFields), dispatch = useStoreDispatch();const now = useRelativeNow();const phone = !useMediaQuery(SIDEBAR_INLINE, true);const [query, setQuery] = useState("");@@ -202,7 +203,7 @@ export function BotConversations({ bot }: { bot: Bot }) {const archived = orderedThreadList(threads.filter((task) => isArchived(task) && !kept(task)));const needle = query.trim();const collapsed = conversations.filter((task, index) => index < CONVERSATIONS_SHOWN || task.threadId === bot.threadId || task.threadId === bot.mainThreadId);- const recent = useRecentMessages(bot, [...(needle || expanded ? conversations : collapsed), ...(needle || showEnded ? ended : []), ...(showArchived ? archived : [])]);+ const recent = useRecentMessages(bot, [...(needle || expanded ? conversations : collapsed), ...(needle || showEnded ? ended : []), ...(showArchived ? archived : [])], state.transcriptGeneration);const preview = (threadId: string) => {const messages = recent(threadId);return messages ? lastLine(currentTaskBot(bot, threadId), messages, state.instances, false) : undefined;diff --git a/src/components/sidebar-state.ts b/src/components/sidebar-state.tsindex 7321c764bb..8bee97d1d1 100644--- a/src/components/sidebar-state.ts+++ b/src/components/sidebar-state.ts@@ -6,7 +6,7 @@ const NO_RUNS: NonNullable<AppState["routineRuns"]> = [];/** What the sidebar list draws: a change anywhere else in the store leaves it alone. */export const sidebarState = (s: AppState) => ({- bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, instances: s.instances, config: s.config, selectedId: s.selectedId, newChat: s.newChat,+ bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, transcriptGeneration: s.transcriptGeneration, instances: s.instances, config: s.config, selectedId: s.selectedId, newChat: s.newChat,activeView: s.activeView, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, deletingBots: s.deletingBots, revealThread: s.revealThread,liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, routineRuns: s.routineRuns, hydrated: s.hydrated, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,});diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7d97bc8cdb..ec2a38ba71 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -858,7 +858,6 @@ function dismissOnboardingCard(state: AppState, botId: string): AppState {}export const CLOUD_LINK_SETTINGS = { type: "toggleAppSettings", open: true, section: "cloudAccount", cloudLink: true } as const satisfies Action;-export function reducer(state: AppState, action: Action): AppState { return olderThanHeld(state, action) ? state : capHeldInBackground(reduceApp(state, action), action); }function reduceApp(state: AppState, action: Action): AppState {const [newChatState, newChatOnly] = reduceNewChat(state, action); if (newChatOnly) return newChatState; state = newChatState;@@ -870,7 +869,8 @@ function reduceApp(state: AppState, action: Action): AppState {const buffered = { ...state, backgroundThreadEvents: { ...state.backgroundThreadEvents, [action.threadId]: frames } };return (action.type === "messageAdded" || action.type === "messagePatched") && movesThreadToTop(action.message)? bumpThreadUpdatedAt(buffered, action.threadId, action.message.at, true, action.message.turnCompletedAt ?? action.message.at)- : action.type === "messageAdded" ? bumpThreadUpdatedAt(buffered, action.threadId, action.message.at) : buffered;+ : action.type === "messageAdded" ? bumpThreadUpdatedAt(buffered, action.threadId, action.message.at)+ : action.type === "threadActive" ? bumpTranscriptGeneration(buffered, action.threadId) : buffered;}}if (isNotificationFeedAction(action)) return { ...state, notifications: reduceNotificationFeed(state.notifications, action) };