Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(sidebar): preserve row memoization in BotConversations and BotListItem
luishron123f77b66f994b2
diff --git a/src/components/Sidebar.memo-isolation.dom.test.ts b/src/components/Sidebar.memo-isolation.dom.test.tsnew file mode 100644index 0000000000..21ae09330e--- /dev/null+++ b/src/components/Sidebar.memo-isolation.dom.test.ts@@ -0,0 +1,162 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { initialState, StoreProvider, type AppState, type Bot } from "@/state/store";++const spies = vi.hoisted(() => ({+ titleCalls: [] as string[],+ unreadCalls: [] as string[],+}));++vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));+vi.mock("@/lib/task-title", async (original) => {+ const mod = await original<typeof import("@/lib/task-title")>();+ return {+ ...mod,+ localizedTaskTitle: (title: string) => {+ spies.titleCalls.push(title);+ return mod.localizedTaskTitle(title);+ },+ };+});+vi.mock("./unread-notice", async (original) => {+ const mod = await original<typeof import("./unread-notice")>();+ return {+ ...mod,+ useBotUnread: (bot: Bot) => {+ spies.unreadCalls.push(bot.id);+ return mod.useBotUnread(bot);+ },+ };+});+vi.mock("@/state/api", async (original) => {+ const mod = await original<typeof import("@/state/api")>();+ return {+ ...mod,+ api: vi.fn(async (url: string) => {+ if (url.startsWith("/api/threads/")) {+ return { messages: [{ id: "m-prev", role: "bot", kind: "text", text: "Saved line", at: 500 }] };+ }+ return {};+ }),+ };+});++const { BotConversations, forgetConversationLines, showAllConversations } = await import("./bot-panel/Conversations");+const { BotListItem, botRowProps } = await import("./Sidebar");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLElement;+let root: Root;++beforeEach(() => {+ localStorage.clear();+ forgetConversationLines();+ spies.titleCalls.length = 0;+ spies.unreadCalls.length = 0;+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(async () => { root.unmount(); });+ host.remove();+ document.body.innerHTML = "";+});++const flushMicrotasks = async () => {+ for (let i = 0; i < 4; i++) await Promise.resolve();+};++describe("row memoization in BotConversations and BotListItem", () => {+ it("re-renders only the open conversation row in BotConversations when the active chat streams a new token", async () => {+ const tasks = [+ { threadId: "open", title: "Open chat", createdAt: 1_000, updatedAt: 1_000 },+ ...Array.from({ length: 14 }, (_, index) => ({+ threadId: `peer-${index}`,+ title: `Peer ${index}`,+ createdAt: 900 - index,+ updatedAt: 900 - index,+ })),+ ];+ const bot: Bot = {+ id: "maus", threadId: "open", name: "Maus", title: "", description: "", notifications: true,+ color: "green", unread: false, messages: [{ id: "m-1", role: "bot", kind: "text", text: "Hello", at: 1_000 }],+ modelSelection: { instanceId: "fake", model: "test" },+ tasks,+ };++ showAllConversations("maus");+ await act(async () => {+ root.render(createElement(StoreProvider, null, createElement(BotConversations, { bot })));+ await flushMicrotasks();+ });+ expect(host.querySelectorAll("[data-conversation]")).toHaveLength(15);++ spies.titleCalls.length = 0;+ const nextBot: Bot = {+ ...bot,+ messages: [{ id: "m-1", role: "bot", kind: "text", text: "Hello world", at: 1_000 }],+ };+ await act(async () => {+ root.render(createElement(StoreProvider, null, createElement(BotConversations, { bot: nextBot })));+ });++ expect(spies.titleCalls).toEqual(["Open chat"]);+ });++ it("re-renders only the affected BotListItem out of 40 when pendingQueued or routineRuns changes for one bot", async () => {+ const bots: Bot[] = Array.from({ length: 40 }, (_, index) => ({+ id: `bot-${index}`,+ threadId: `main-${index}`,+ name: `Bot ${index}`,+ title: "",+ description: "",+ notifications: true,+ color: "green",+ unread: false,+ messages: [],+ modelSelection: { instanceId: "fake", model: "test" },+ tasks: [+ { threadId: `main-${index}`, title: `Main ${index}`, createdAt: 10 },+ { threadId: `sub-${index}`, title: `Sub ${index}`, createdAt: 9 },+ ],+ }));+ const dispatch = vi.fn();+ const onMenu = vi.fn();+ const renderFleet = (state: AppState) => createElement(+ StoreProvider,+ null,+ bots.map((candidate) => createElement(BotListItem, {+ key: candidate.id,+ ...botRowProps(state, dispatch, candidate, { density: "comfortable", query: "", onMenu }),+ })),+ );++ const state0: AppState = { ...initialState, bots };+ await act(async () => { root.render(renderFleet(state0)); });+ expect(spies.unreadCalls).toHaveLength(40);++ spies.unreadCalls.length = 0;+ const queuedForZero = [{ id: "q-0", text: "Wait for turn", createdAt: 1 }] as unknown as AppState["pendingQueued"][string];+ const state1: AppState = { ...state0, pendingQueued: { "main-0": queuedForZero } };+ await act(async () => { root.render(renderFleet(state1)); });+ expect(spies.unreadCalls).toEqual(["bot-0"]);++ spies.unreadCalls.length = 0;+ const state2: AppState = {+ ...state1,+ pendingQueued: { "main-0": queuedForZero },+ routineRuns: [{+ id: "run-1", routineId: "rt-1", routineName: "Digest", target: "bot",+ botId: "bot-1", runOn: "maus", scheduledFor: 20, status: "running",+ manual: false, threadId: "sub-1", createdAt: 20,+ }],+ };+ await act(async () => { root.render(renderFleet(state2)); });+ expect(spies.unreadCalls).toEqual(["bot-1"]);+ });+});diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex cd214c953d..003aad6f2d 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -2,7 +2,7 @@ import { OrganizationIdentity } from "./OrganizationIdentity";import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";import { createPortal } from "react-dom";import { Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderInput, FolderPlus, LayoutTemplate, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, Plus, Search, SquarePen, TextQuote, Trash2, Users, X } from "lucide-react";-import { sidebarState } from "./sidebar-state"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";+import { botPendingQueued, botRoutineRuns, sameBotRowProps, sidebarState } from "./sidebar-state"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";import { api, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";import { approvalModeFor } from "../../shared/approval-mode";import { liveActivityLabel, sidebarMessage } from "@/lib/live-activity";@@ -679,7 +679,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: state.pendingQueued, routineRuns: state.routineRuns,+ pendingQueued: botPendingQueued(bot, state.pendingQueued), routineRuns: botRoutineRuns(bot, state.routineRuns),instances: state.instances,liveCall: state.liveCall,locale: activeLocale(),@@ -914,7 +914,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {{showThreads && creatingProject && <BotProjectDialog bot={bot} onClose={() => setCreatingProject(false)} />}</>);-});+}, sameBotRowProps);export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons = false, besidePanel = false }: {open: boolean;diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsxindex c28451a509..7cadda8193 100644--- a/src/components/bot-panel/Conversations.tsx+++ b/src/components/bot-panel/Conversations.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { ChevronDown, ChevronUp, Search, SquarePen } from "lucide-react";import { cn } from "@/lib/cn";@@ -113,13 +113,16 @@ export function BotConversations({ bot }: { bot: Bot }) {const hidden = conversations.length - collapsed.length;const project = bot.projects?.find((folder) => folder.id === bot.tasks?.find((task) => task.threadId === bot.threadId)?.projectId);- const closeOnPhone = () => {- if (phone) dispatch({ type: "toggleSettings", open: false });- };- const select = (task: { threadId: string }) => {- if (task.threadId !== bot.threadId) openBotThread(dispatch, bot, task.threadId, false);+ const latest = useRef({ bot, phone });+ latest.current = { bot, phone };+ const closeOnPhone = useCallback(() => {+ if (latest.current.phone) dispatch({ type: "toggleSettings", open: false });+ }, [dispatch]);+ const select = useCallback((task: { threadId: string }) => {+ const current = latest.current.bot;+ if (task.threadId !== current.threadId) openBotThread(dispatch, current, task.threadId, false);closeOnPhone();- };+ }, [dispatch, closeOnPhone]);const startNew = () => {dispatch({ type: "newTask", botId: bot.id, ...(project ? { projectId: project.id } : {}) });closeOnPhone();diff --git a/src/components/sidebar-state.ts b/src/components/sidebar-state.tsindex 12e49fa3ae..cc72ef4d39 100644--- a/src/components/sidebar-state.ts+++ b/src/components/sidebar-state.ts@@ -1,4 +1,8 @@-import type { AppState } from "@/state/store";+import { sameFields, sameItems } from "@/state/store-select";+import type { AppState, Bot } from "@/state/store";++const NO_QUEUED: AppState["pendingQueued"] = {};+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) => ({@@ -6,3 +10,28 @@ export const sidebarState = (s: AppState) => ({activeView: s.activeView, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, deletingBots: s.deletingBots, revealThread: s.revealThread,liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, routineRuns: s.routineRuns, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,});++export function botPendingQueued(bot: Pick<Bot, "threadId" | "tasks">, pendingQueued: AppState["pendingQueued"]): AppState["pendingQueued"] {+ let scoped: Record<string, AppState["pendingQueued"][string]> | null = null;+ const include = (threadId: string) => {+ const entries = pendingQueued[threadId];+ if (!entries?.length) return;+ (scoped ??= {})[threadId] = entries;+ };+ include(bot.threadId);+ for (const task of bot.tasks ?? []) include(task.threadId);+ return scoped ?? NO_QUEUED;+}++export function botRoutineRuns(bot: Pick<Bot, "id" | "threadId" | "tasks">, routineRuns: AppState["routineRuns"]): AppState["routineRuns"] {+ if (!routineRuns?.length) return NO_RUNS;+ const threadIds = new Set<string>([bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)]);+ const runs = routineRuns.filter((run) => run.botId === bot.id || (run.threadId !== undefined && threadIds.has(run.threadId)));+ return runs.length ? runs : NO_RUNS;+}++export function sameBotRowProps<T extends { pendingQueued: AppState["pendingQueued"]; routineRuns?: AppState["routineRuns"] }>(previous: T, next: T): boolean {+ const { pendingQueued: prevQueued, routineRuns: prevRuns = NO_RUNS, ...prevRest } = previous;+ const { pendingQueued: nextQueued, routineRuns: nextRuns = NO_RUNS, ...nextRest } = next;+ return sameFields(prevRest, nextRest) && sameFields(prevQueued, nextQueued) && sameItems(prevRuns, nextRuns);+}