Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(sidebar): share 30s relative clock, index drag lists, and skip hidden attention sort
luishron12312edb06d2ce4
diff --git a/src/components/Sidebar.perf-polish.dom.test.ts b/src/components/Sidebar.perf-polish.dom.test.tsnew file mode 100644index 0000000000..ee5fb45988--- /dev/null+++ b/src/components/Sidebar.perf-polish.dom.test.ts@@ -0,0 +1,193 @@+// @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 Bot } from "@/state/store";++const spies = vi.hoisted(() => ({+ botListOfCalls: 0,+ attentionCalls: 0,+}));++vi.mock("./DesktopCapabilities", async () => {+ const { initialDesktopCapabilities } = await import("@/lib/desktop");+ return { useDesktopCapabilities: () => ({ capabilities: initialDesktopCapabilities() }), windowFramed: () => false };+});+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));+vi.mock("./SidebarInboxRow", () => ({ SidebarInboxRow: () => null }));+vi.mock("@/state/api", async (original) => ({ ...await original<typeof import("@/state/api")>(), api: vi.fn(async () => ({})) }));+vi.mock("@/state/inbox", async (original) => {+ const mod = await original<typeof import("@/state/inbox")>();+ return { ...mod, useInboxSupport: () => "yes" as const };+});+vi.mock("@/lib/sidebar-bot-drop", async (original) => {+ const mod = await original<typeof import("@/lib/sidebar-bot-drop")>();+ return {+ ...mod,+ botListOf: (...args: Parameters<typeof mod.botListOf>) => {+ spies.botListOfCalls += 1;+ return mod.botListOf(...args);+ },+ };+});+vi.mock("./SidebarBotActivity", async (original) => {+ const mod = await original<typeof import("./SidebarBotActivity")>();+ return {+ ...mod,+ crossBotAttentionThreads: (...args: Parameters<typeof mod.crossBotAttentionThreads>) => {+ spies.attentionCalls += 1;+ return mod.crossBotAttentionThreads(...args);+ },+ };+});++const { BotThreadList, Sidebar, botRowProps } = await import("./Sidebar");+const { useSidebarBotDrag } = await import("./SidebarBotDrag");+const { attentionHasRunningWork, crossBotAttentionThreads, hasCrossBotRunningWork } = await import("./SidebarBotActivity");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLElement;+let root: Root;++beforeEach(() => {+ localStorage.clear();+ spies.botListOfCalls = 0;+ spies.attentionCalls = 0;+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(async () => { root.unmount(); });+ host.remove();+ vi.restoreAllMocks();+ document.body.innerHTML = "";+});++const makeFleet = (count: number): Bot[] =>+ Array.from({ length: count }, (_, index) => ({+ id: `bot-${index}`,+ threadId: `main-${index}`,+ name: `Bot ${index}`,+ title: "",+ description: "",+ notifications: true,+ color: "green",+ unread: false,+ section: index % 2 === 0 ? `Dept ${index % 5}` : undefined,+ messages: [],+ modelSelection: { instanceId: "fake", model: "test" },+ tasks: [+ { threadId: `main-${index}`, title: `Main ${index}`, createdAt: 10 },+ { threadId: `second-${index}`, title: `Second ${index}`, createdAt: 20 },+ ],+ }));++describe("sidebar rendering and timer polish", () => {+ it("shares a single 30s interval and visibility listener across 8 mounted BotThreadList instances", async () => {+ const intervals = new Set<number>();+ let nextId = 1;+ const setIntervalSpy = vi.spyOn(window, "setInterval").mockImplementation(((_cb: TimerHandler, delay?: number) => {+ const id = nextId++;+ if (delay === 30_000) intervals.add(id);+ return id as unknown as ReturnType<typeof window.setInterval>;+ }) as unknown as typeof window.setInterval);+ vi.spyOn(window, "clearInterval").mockImplementation(((id?: number) => {+ if (typeof id === "number") intervals.delete(id);+ }) as unknown as typeof window.clearInterval);+ let visibilityListeners = 0;+ const origAdd = document.addEventListener.bind(document);+ const origRemove = document.removeEventListener.bind(document);+ vi.spyOn(document, "addEventListener").mockImplementation(((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {+ if (type === "visibilitychange") visibilityListeners += 1;+ origAdd(type, listener, options);+ }) as typeof document.addEventListener);+ vi.spyOn(document, "removeEventListener").mockImplementation(((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {+ if (type === "visibilitychange") visibilityListeners -= 1;+ origRemove(type, listener, options);+ }) as typeof document.removeEventListener);++ const fleet = makeFleet(8);+ await act(async () => {+ root.render(createElement(+ "div",+ null,+ fleet.map((bot) => createElement(BotThreadList, {+ key: bot.id,+ ...botRowProps(initialState, vi.fn(), bot, { density: "comfortable", query: "", onMenu: vi.fn() }),+ selected: false,+ })),+ ));+ });++ const thirtySecCalls = setIntervalSpy.mock.calls.filter((call) => call[1] === 30_000);+ expect(thirtySecCalls).toHaveLength(1);+ expect(intervals.size).toBe(1);+ expect(visibilityListeners).toBe(1);++ await act(async () => { root.render(null); });+ expect(intervals.size).toBe(0);+ expect(visibilityListeners).toBe(0);+ });++ it("registers zero 30s relative-clock intervals and skips crossBotAttentionThreads when Sidebar has no pinned threads and attention panel is unpinned", async () => {+ const thirtySecDelays: number[] = [];+ vi.spyOn(window, "setInterval").mockImplementation(((cb: TimerHandler, delay?: number) => {+ if (delay === 30_000) thirtySecDelays.push(delay);+ return setTimeout(cb as () => void, 1_000_000) as unknown as ReturnType<typeof window.setInterval>;+ }) as unknown as typeof window.setInterval);++ await act(async () => {+ root.render(createElement(StoreProvider, null, createElement(Sidebar, { open: true, onClose: vi.fn() })));+ });++ expect(thirtySecDelays).toHaveLength(0);+ expect(spies.attentionCalls).toBe(0);+ });++ it("indexes bot drag lists in O(1) without calling linear botListOf per row across 40 bots", async () => {+ const fleet = makeFleet(40);+ const departments = ["Dept 0", "Dept 1", "Dept 2", "Dept 3", "Dept 4"];+ const main = fleet.filter((bot) => !bot.section);+ const sectioned = fleet.filter((bot) => Boolean(bot.section));+ let rowDropCount = 0;++ function Harness() {+ const drag = useSidebarBotDrag({+ dispatch: vi.fn(),+ announce: vi.fn(),+ onNamed: vi.fn(),+ onRenamed: vi.fn(),+ onError: vi.fn(),+ onCancelled: vi.fn(),+ });+ const drops = drag.arrange({+ enabled: true,+ main,+ sectioned,+ departments,+ bots: fleet,+ taken: departments,+ });+ rowDropCount = fleet.filter((bot) => Boolean(drops.row(bot.id).botDrag)).length;+ return null;+ }++ await act(async () => { root.render(createElement(Harness)); });+ expect(rowDropCount).toBe(40);+ expect(spies.botListOfCalls).toBe(0);+ });+ it("matches attentionHasRunningWork(crossBotAttentionThreads(...)) via short-circuiting hasCrossBotRunningWork", () => {+ const idleFleet = makeFleet(10);+ expect(hasCrossBotRunningWork(idleFleet, {})).toBe(false);+ expect(hasCrossBotRunningWork(idleFleet, { "second-7": ["q"] })).toBe(+ attentionHasRunningWork(crossBotAttentionThreads(idleFleet, { "second-7": ["q"] })),+ );+ const waitingOnly = idleFleet.map((bot, i) => i === 3 ? { ...bot, tasks: [{ threadId: "main-3", title: "Ask", createdAt: 1, busy: true, activity: "waiting-on-you" as const }] } : bot);+ expect(hasCrossBotRunningWork(waitingOnly, {})).toBe(false);+ const workingFleet = idleFleet.map((bot, i) => i === 5 ? { ...bot, tasks: [{ threadId: "main-5", title: "Work", createdAt: 1, busy: true, activity: "working" as const }] } : bot);+ expect(hasCrossBotRunningWork(workingFleet, {})).toBe(true);+ });+});diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 003aad6f2d..f4527c5242 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -84,7 +84,7 @@ import { isSidebarToggle } from "@/lib/keyboard-shortcuts";import { SidebarRailSeparator, SimpleRailFooter } from "./SidebarSimpleRail";import { useShowThreads } from "@/lib/thread-preferences";import { useBotUnread } from "./unread-notice";-import { attentionHasRunningWork, attentionJumpAction, attentionUnpinAction, crossBotAttentionThreads, crossBotPinnedThreads, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";+import { attentionHasRunningWork, attentionJumpAction, attentionUnpinAction, crossBotAttentionThreads, crossBotPinnedThreads, hasCrossBotRunningWork, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";import { SidebarNoBots, SidebarTileGrid } from "./SidebarTiles";import { BotContextMenu } from "./SidebarBotMenu";export { BotContextMenu };@@ -922,7 +922,6 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =collapseToIcons?: boolean; besidePanel?: boolean;}) {const state = useStoreSelector(sidebarState, sameFields), dispatch = useStoreDispatch();- const now = useRelativeNow();const cloudOwner = useCloudOwner(state.config?.cloudHome === true);const endHowTo = useCallback(() => endCloudHowTo(dispatch), [dispatch]);const showThreads = useShowThreads();@@ -1127,7 +1126,8 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const { interactive: layoutInteractive, collapsed: sectionCollapsed, toggle: toggleSection } = sections;const archivedBots = state.bots.filter((bot) => bot.hidden && !bot.movedTo);const archivedEntry = remoteClient ? undefined : { count: archivedBots.length, open: () => setArchivedBotsOpen(true) };- const attention = crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups);+ const showAttention = (advanced && inboxSupport === "no") || (attentionPinned && density !== "icons");+ const attention = showAttention ? crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups) : [];const pinnedThreads = crossBotPinnedThreads(state.bots, state.groups, state.pendingQueued);const pendingBotUndo = teamFeedback?.restoreBot;const botRow = (bot: Bot) => botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });@@ -1315,7 +1315,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =/></div></div>}- {!q && <TeamSideSwitch compact={density === "icons"} listOnly={phone} />}{!q && <SidebarInboxRow icons={density === "icons"} large={!advanced} running={attentionHasRunningWork(attention)} onOpened={phone ? onClose : undefined} />}+ {!q && <TeamSideSwitch compact={density === "icons"} listOnly={phone} />}{!q && <SidebarInboxRow icons={density === "icons"} large={!advanced} running={showAttention ? attentionHasRunningWork(attention) : hasCrossBotRunningWork(state.bots, state.pendingQueued, state.groups)} onOpened={phone ? onClose : undefined} />}{universalPins && pinnedBots.length > 0 && !simpleDesk && (<divdata-sidebar-universal-pins=""@@ -1350,7 +1350,6 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons ={density !== "icons" && (<SidebarPinnedThreadsPanelentries={pinnedThreads}- now={now}onJump={(entry) => dispatch(attentionJumpAction(entry))}onUnpin={(entry) => dispatch(attentionUnpinAction(entry))}collapsed={sectionCollapsed(PINNED_THREADS_SECTION_ID)}diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsxindex d838d11bf8..0ad497d785 100644--- a/src/components/SidebarBotActivity.tsx+++ b/src/components/SidebarBotActivity.tsx@@ -118,8 +118,16 @@ export function attentionTriggerLabel(count: number): string {return count > 0 ? t("attention.titleCount", { count }) : t("attention.title");}+const taskHasRunningWork = (task: { activity?: Task["activity"]; busy?: boolean; queued?: boolean }): boolean =>+ task.activity === "working" || (task.busy === true && task.activity !== "waiting-on-you") || task.queued === true;+export function attentionHasRunningWork(entries: readonly AttentionThread[]): boolean {- return entries.some((entry) => entry.task.activity === "working" || (entry.task.busy === true && entry.task.activity !== "waiting-on-you") || entry.task.queued === true);+ return entries.some((entry) => taskHasRunningWork(entry.task));+}++export function hasCrossBotRunningWork(bots: Bot[], queued: Record<string, unknown[]>, groups: Group[] = []): boolean {+ return bots.some((bot) => !bot.hidden && sidebarBotActivityTasks(bot, queued, true).some(taskHasRunningWork))+ || groups.some((group) => sidebarGroupActivityTasks(group, bots, queued).some(taskHasRunningWork));}export function attentionRowStatus(task: AttentionThread["task"]): { active: boolean; Icon: LucideIcon; colorClass: string; label: string } {diff --git a/src/components/SidebarBotDrag.tsx b/src/components/SidebarBotDrag.tsxindex 4c28b76a9a..1ccda93e49 100644--- a/src/components/SidebarBotDrag.tsx+++ b/src/components/SidebarBotDrag.tsx@@ -157,8 +157,10 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst movable = enabled && mayMove;const lists = new Map<string, string[]>([["", main.map((bot) => bot.id)]]);for (const name of departments) if (name !== NEW_DEPARTMENT) lists.set(name, sectioned.filter((bot) => bot.section === name).map((bot) => bot.id));+ const listOf = new Map<string, string>();+ for (const [list, ids] of lists) for (const id of ids) listOf.set(id, list);latest.current = { enabled: movable, lists, bots, taken, withinList };- const active = movable && dragging !== null && botListOf(lists, dragging) !== undefined ? dragging : null;+ const active = movable && dragging !== null && listOf.has(dragging) ? dragging : null;const shown = active ? drop : null;const mainIds = lists.get("")!.filter((id) => id !== active);const listFor = (sectionId: string) => (sectionId === BOTS_SECTION_ID ? "" : userSectionName(sectionId));@@ -173,7 +175,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onEr};return {row: (botId: string): { botDrag?: BotRowDrag; botDrop?: BotDropPlace | null; botDragging?: boolean } => {- if (!movable || botListOf(lists, botId) === undefined) return {};+ if (!movable || !listOf.has(botId)) return {};const place = shown?.kind === "row" && shown.botId === botId ? shown.place: shown?.kind === "end" && shown.list === "" && botId === mainIds.at(-1) ? "after" : null;return { botDrag: controller.current!, botDrop: place, botDragging: active === botId };@@ -185,7 +187,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst list = listFor(sectionId);const dragged = moving.current.botId;if (!dragged || list === null || !lists.has(list)) return show(null);- if (withinList && list !== botListOf(lists, dragged)) return show(null);+ if (withinList && list !== listOf.get(dragged)) return show(null);event.preventDefault();event.dataTransfer.dropEffect = "move";const target = zoneDrop(event, list);@@ -198,7 +200,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErfinish(list !== null && lists.has(list) ? zoneDrop(event, list) : null);},}),- slot: active !== null && mainIds.length === 0 && botListOf(lists, active) !== ""+ slot: active !== null && mainIds.length === 0 && listOf.get(active) !== ""? <div data-bot-drop-slot="" className={cn("mx-2 flex h-10 items-center justify-center rounded-[8px] border border-dashed text-[13px] leading-[18px]",shown?.kind === "end" && shown.list === "" ? "border-accent bg-accent/10 text-ink" : "border-ink/20 text-ink-secondary")}>{t("sidebar.section.removeFromDepartment")}</div>: null,diff --git a/src/components/SidebarPinnedThreadsPanel.tsx b/src/components/SidebarPinnedThreadsPanel.tsxindex 49cab81e88..4361a391df 100644--- a/src/components/SidebarPinnedThreadsPanel.tsx+++ b/src/components/SidebarPinnedThreadsPanel.tsx@@ -1,16 +1,18 @@import { ChevronDown, ChevronRight, Pin } from "lucide-react";import { t } from "@/lib/i18n";import { PinnedThreadRows, type AttentionThread } from "./SidebarBotActivity";+import { useRelativeNow } from "./SidebarThreadRow";-export function SidebarPinnedThreadsPanel({ entries, now, onJump, onUnpin, collapsed, onToggle }: {+type PanelProps = {entries: AttentionThread[];- now: number;+ now?: number;onJump: (entry: AttentionThread) => void;onUnpin: (entry: AttentionThread) => void;collapsed: boolean;onToggle?: () => void;-}) {- if (entries.length === 0) return null;+};++function PinnedThreadsBody({ entries, now, onJump, onUnpin, collapsed, onToggle }: PanelProps & { now: number }) {const Chevron = collapsed ? ChevronRight : ChevronDown;return (<section@@ -41,3 +43,13 @@ export function SidebarPinnedThreadsPanel({ entries, now, onJump, onUnpin, colla</section>);}++function LivePinnedThreadsPanel(props: Omit<PanelProps, "now">) {+ return <PinnedThreadsBody {...props} now={useRelativeNow()} />;+}++export function SidebarPinnedThreadsPanel({ now, ...props }: PanelProps) {+ if (props.entries.length === 0) return null;+ if (now !== undefined) return PinnedThreadsBody({ ...props, now });+ return <LivePinnedThreadsPanel {...props} />;+}diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsxindex 3477159e74..2728d62ed4 100644--- a/src/components/SidebarThreadRow.tsx+++ b/src/components/SidebarThreadRow.tsx@@ -184,15 +184,41 @@ export function useRevealedThreadRow(reveal: AppState["revealThread"], currentTh}, [reveal, currentThreadId]);}+type RelativeClock = {+ win: Window & typeof globalThis;+ doc: Document;+ timer: number;+ sync: () => void;+ listeners: Set<(now: number) => void>;+};+let sharedRelativeClock: RelativeClock | null = null;+export function useRelativeNow(): number {const [now, setNow] = useState(() => Date.now());useEffect(() => {- const sync = () => { if (document.visibilityState === "visible") setNow(Date.now()); };- const timer = window.setInterval(sync, 30_000);- document.addEventListener("visibilitychange", sync);+ if (sharedRelativeClock && (sharedRelativeClock.win !== window || sharedRelativeClock.doc !== document)) {+ sharedRelativeClock = null;+ }+ if (!sharedRelativeClock) {+ const listeners = new Set<(next: number) => void>();+ const win = window, doc = document;+ const sync = () => {+ if (doc.visibilityState !== "visible") return;+ const next = Date.now();+ for (const notify of listeners) notify(next);+ };+ sharedRelativeClock = { win, doc, timer: win.setInterval(sync, 30_000), sync, listeners };+ doc.addEventListener("visibilitychange", sync);+ }+ const clock = sharedRelativeClock;+ clock.listeners.add(setNow);return () => {- window.clearInterval(timer);- document.removeEventListener("visibilitychange", sync);+ clock.listeners.delete(setNow);+ if (clock.listeners.size === 0) {+ clock.win.clearInterval(clock.timer);+ clock.doc.removeEventListener("visibilitychange", clock.sync);+ if (sharedRelativeClock === clock) sharedRelativeClock = null;+ }};}, []);return now;