Skip to content

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

Team map: open straight into the settled layout, without the flicker (#6764)

Milind Soni45c8efcd69fc
diff --git a/src/components/TeamCanvas.settle.dom.test.ts b/src/components/TeamCanvas.settle.dom.test.ts
new file mode 100644
index 0000000000..ddee77e806
--- /dev/null
+++ b/src/components/TeamCanvas.settle.dom.test.ts
@@ -0,0 +1,144 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { AppState, Bot } from "@/state/store";
+import type { MapComputer } from "../../shared/map-computer";
+
+const fixture = vi.hoisted(() => {
+ let value: { state: AppState; dispatch: () => void } | null = null;
+ const listeners = new Set<() => void>();
+ return {
+ get value() { return value!; },
+ set(state: AppState) { value = { state, dispatch: () => {} }; for (const listener of listeners) listener(); },
+ subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
+ computers: [] as MapComputer[],
+ computersAnswer: true,
+ };
+});
+
+async function fakeApi(path: string) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ if (path.startsWith("/.well-known/openmausbot/environment")) return { environmentId: "fixture" };
+ if (path.startsWith("/api/team-map")) return { collaborations: [], queued: [], running: [] };
+ if (path.startsWith("/api/computers/frames")) {
+ if (!fixture.computersAnswer) return new Promise(() => {});
+ return { computers: structuredClone(fixture.computers), configured: true, available: true, now: Date.now() };
+ }
+ if (path.startsWith("/api/team-computers")) return { computers: [], configured: true };
+ return {};
+}
+
+vi.mock("@/state/store", async (original) => {
+ const actual = await original<typeof import("@/state/store")>();
+ const { useSyncExternalStore } = await import("react");
+ return { ...actual, api: fakeApi, useStore: () => useSyncExternalStore(fixture.subscribe, () => fixture.value) };
+});
+vi.mock("@/state/api", async (original) => ({ ...await original<object>(), api: fakeApi }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("./DesktopCapabilities", () => ({
+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false } } }),
+ useCaptionChrome: () => ({}),
+}));
+
+const { initialState } = await import("@/state/store");
+const { TeamMapPage } = await import("./TeamMapPage");
+
+const bot = (id: string, section: string, extra: Partial<Bot> = {}): Bot => ({
+ id, threadId: `thread-${id}`, name: id, title: "", description: "", notifications: false, color: "green", unread: false,
+ modelSelection: { instanceId: "fixture", model: "model" }, tasks: [{ threadId: `thread-${id}`, title: "Task", createdAt: 1 }],
+ messages: [], section, ...extra,
+} as Bot);
+const team = (computers: boolean) => [
+ bot("chief", "Sales", { chiefOfStaff: true, ...(computers ? { computer: "cloud" } : {}) }),
+ bot("ana", "Sales"), bot("ben", "Sales"), bot("cy", "Ops"), bot("dee", "Ops"),
+];
+
+const resizeCallbacks = new Set<() => void>();
+class FixtureResizeObserver {
+ constructor(private readonly callback: () => void) {}
+ observe() { resizeCallbacks.add(this.callback); queueMicrotask(this.callback); }
+ unobserve() {}
+ disconnect() { resizeCallbacks.delete(this.callback); }
+}
+const elementRect = HTMLElement.prototype.getBoundingClientRect;
+let container: HTMLDivElement, root: Root;
+
+beforeEach(() => {
+ vi.stubGlobal("ResizeObserver", FixtureResizeObserver);
+ HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) {
+ return this.matches("[data-team-canvas]") ? new DOMRect(0, 0, 1200, 800) : elementRect.call(this);
+ };
+ const stored = new Map([["omb-team-canvas:fixture", JSON.stringify({ Ops: { x: 900, y: 60 } })]]);
+ vi.stubGlobal("localStorage", { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) });
+ fixture.computersAnswer = true;
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ root.unmount();
+ container.remove();
+ HTMLElement.prototype.getBoundingClientRect = elementRect;
+ resizeCallbacks.clear();
+ vi.unstubAllGlobals();
+});
+
+/** What a person could see between two tasks: the world's view, each team's tile, and the cards and screens in them. */
+function look(): string | null {
+ const world = container.querySelector<HTMLElement>("[data-canvas-world]");
+ if (!world || world.style.visibility === "hidden") return null;
+ const tiles = [...container.querySelectorAll<HTMLElement>("section[data-team-key]")]
+ .map((tile) => `${tile.dataset.teamKey}@${tile.style.left},${tile.style.top} ${tile.style.width}x${tile.style.height}`);
+ return [world.style.transform, ...tiles, `cards ${container.querySelectorAll("article").length}`, `screens ${container.querySelectorAll("[data-computer-node]").length}`].join(" | ");
+}
+async function watch(tasks: number, seen: Array<string | null>) {
+ for (let task = 0; task < tasks; task++) {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ const now = look();
+ if (seen.at(-1) !== now) seen.push(now);
+ }
+}
+
+for (const computers of [false, true]) {
+ it(`opens straight into its settled layout${computers ? " with computers shown" : ""}: no earlier view, team spot or card layout is ever on screen`, async () => {
+ fixture.computers = computers ? [{ id: "chief", kind: "bot", name: "chief", botIds: ["chief"], state: "idle" }] : [];
+ fixture.set({ ...initialState, bots: team(computers), sections: ["Sales", "Ops"] });
+ const seen: Array<string | null> = [];
+ root.render(createElement(TeamMapPage));
+ await watch(200, seen);
+ const shown = seen.filter((state): state is string => state !== null);
+ expect(shown).toHaveLength(1);
+ expect(shown[0]).toContain("Ops@900px,60px");
+ expect(shown[0]).toContain(`screens ${computers ? 1 : 0}`);
+ });
+}
+
+it("a bot working in the background remounts no card and moves nothing on the canvas", async () => {
+ fixture.computers = [{ id: "chief", kind: "bot", name: "chief", botIds: ["chief"], state: "idle" }];
+ fixture.set({ ...initialState, bots: team(true), sections: ["Sales", "Ops"] });
+ root.render(createElement(TeamMapPage));
+ const settling: Array<string | null> = [];
+ await watch(200, settling);
+ const cards = [...container.querySelectorAll("article")];
+ const settled = look();
+ const seen: Array<string | null> = [settled];
+ for (let frame = 0; frame < 20; frame++) {
+ fixture.set({ ...fixture.value.state, bots: fixture.value.state.bots.map((item) => item.id === "ana"
+ ? { ...item, busy: true, messages: [...item.messages, { id: `reply-${frame}`, role: "bot", kind: "text", text: "working", at: frame }] } : item) });
+ await watch(3, seen);
+ }
+ expect(seen).toEqual([settled]);
+ expect([...container.querySelectorAll("article")].every((card, index) => card === cards[index])).toBe(true);
+});
+
+it("shows the teams anyway when the computers never answer", async () => {
+ fixture.computersAnswer = false;
+ fixture.set({ ...initialState, bots: team(true), sections: ["Sales", "Ops"] });
+ root.render(createElement(TeamMapPage));
+ const early: Array<string | null> = [];
+ await watch(20, early);
+ expect(early.at(-1)).toBeNull();
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ expect(look()).toContain("cards 5");
+});
diff --git a/src/components/TeamCanvas.tsx b/src/components/TeamCanvas.tsx
index 6890813764..70e9712532 100644
--- a/src/components/TeamCanvas.tsx
+++ b/src/components/TeamCanvas.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import { ArrowRight, BookOpen, Brain, Crown, MessageCircle, Minus, Monitor, MoreHorizontal, Pencil, Plus, Trash2, Users } from "lucide-react";
import { api, openBot, useStore, type Bot } from "@/state/store";
import { teamBotName, useTeamPeople } from "@/state/team-people";
@@ -86,6 +86,8 @@ function BotCard({ bot, selected, moving, connected, tagged = false, sent, onCom
}
const NO_COMPUTERS: MapComputer[] = [];
+/** The longest the teams stay hidden while the saved layout and the computers beside them are still on their way. */
+const SETTLE_LIMIT_MS = 1_500;
/** What the bot is doing right now, in one line: its newest tool step in the open thread, else the working thread's title. */
function currentActivity(bot: Bot | undefined, instances: ReturnType<typeof useStore>["state"]["instances"]): string | undefined {
@@ -96,7 +98,7 @@ function currentActivity(bot: Bot | undefined, instances: ReturnType<typeof useS
return bot.tasks?.find((task) => task.busy && task.threadId !== bot.threadId && task.title.trim())?.title;
}
-export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemory, onEditTeam, onDeleteTeam, onComputer, onComputerDrop, onTeamComputer, teamComputers = {}, connectedBotIds = [], computers = NO_COMPUTERS, computerFrames = {}, onOpenComputer, taggedBotIds = [], sent, bottomInset = 0 }: {
+export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemory, onEditTeam, onDeleteTeam, onComputer, onComputerDrop, onTeamComputer, teamComputers = {}, connectedBotIds = [], computers = NO_COMPUTERS, computerFrames = {}, onOpenComputer, taggedBotIds = [], sent, bottomInset = 0, settling = false }: {
sections: TeamMapSection<Bot>[];
canManage: boolean;
onMove: (bot: Bot, destination: string) => Promise<boolean | void>;
@@ -120,6 +122,8 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
sent?: { botIds: string[]; key: number } | null;
/** Height covered at the bottom (the map composer): fitting keeps the teams above it. */
bottomInset?: number;
+ /** Something that changes the layout, such as the computers drawn beside the bots, is still loading. */
+ settling?: boolean;
}) {
const { state } = useStore();
const viewport = useRef<HTMLDivElement>(null);
@@ -139,6 +143,10 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
const [layoutLoaded, setLayoutLoaded] = useState(false);
const [menuAbove, setMenuAbove] = useState<string | null>(null);
const [viewportSize, setViewportSize] = useState({ width: 0, height: 0 });
+ const [settleLimitReached, setSettleLimitReached] = useState(false);
+ const [settled, setSettled] = useState(false);
+ const ready = settled || settleLimitReached || (layoutLoaded && !settling);
+ if (ready && !settled) setSettled(true);
const geometries = useMemo<Array<TeamGeometry | null>>(() => sections.map((section) => {
if (!computers.length) return null;
const order = Object.hasOwn(botOrders, section.key) ? botOrders[section.key] : [];
@@ -202,13 +210,20 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
if (bounds) setView(fitTeams(current.current.tiles, bounds.width, Math.max(200, bounds.height - current.current.bottomInset)));
}, []);
useEffect(() => {
+ const timer = window.setTimeout(() => setSettleLimitReached(true), SETTLE_LIMIT_MS);
+ return () => window.clearTimeout(timer);
+ }, []);
+ useLayoutEffect(() => {
const element = viewport.current;
if (!element) return;
- let previousSize: { width: number; height: number } | null = null;
+ const first = element.getBoundingClientRect();
+ let previousSize = { width: first.width, height: first.height };
+ setViewportSize(previousSize);
const observer = new ResizeObserver(() => {
const bounds = element.getBoundingClientRect();
+ if (bounds.width === previousSize.width && bounds.height === previousSize.height) return;
setViewportSize({ width: bounds.width, height: bounds.height });
- if (!previousSize) fit();
+ if (!previousSize.width || !previousSize.height) fit();
else {
const card = current.current.settingsOpen ? [...element.querySelectorAll<HTMLElement>("[data-bot-id]")]
.find((node) => node.dataset.botId === current.current.selectedId)?.getBoundingClientRect() : undefined;
@@ -222,7 +237,8 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
return () => observer.disconnect();
}, [fit]);
const teamSizes = JSON.stringify(tiles.map(({ key, width, height }) => [key, width, height]));
- useEffect(() => { fit(); }, [fit, teamSizes, layoutLoaded]);
+ const measured = viewportSize.width > 0 && viewportSize.height > 0;
+ useLayoutEffect(() => { fit(); }, [fit, teamSizes, layoutLoaded, ready, measured]);
useEffect(() => {
const open = viewport.current?.querySelector<HTMLDetailsElement>("details[open]");
const bounds = viewport.current?.getBoundingClientRect();
@@ -408,7 +424,7 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
if (event.key === "-") { event.preventDefault(); zoom(1 / 1.2); }
if (event.key === "0") { event.preventDefault(); fit(); }
}}>
- <div data-canvas-world className="absolute left-0 top-0 origin-top-left" style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }}>
+ <div data-canvas-world className="absolute left-0 top-0 origin-top-left" style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})`, visibility: ready ? undefined : "hidden" }}>
{sections.map((section, index) => {
const tile = tiles[index];
const geometry = geometries[index];
diff --git a/src/components/TeamMapPage.tsx b/src/components/TeamMapPage.tsx
index e8c9e91750..579ec0db95 100644
--- a/src/components/TeamMapPage.tsx
+++ b/src/components/TeamMapPage.tsx
@@ -390,6 +390,7 @@ export function TeamMapPage() {
<div className="relative flex min-h-0 flex-1">
<div className="relative flex min-h-0 min-w-0 flex-1">
<TeamCanvas sections={sections} canManage={!remoteClient && admin !== false} onMove={requestMove} taggedBotIds={taggedBotIds} sent={sent} bottomInset={bots.length ? 96 : 0}
+ settling={!remoteClient && (!computersChoiceLoaded || (showComputers && !mapComputers.answered))}
connectedBotIds={state.settingsOpen ? edges.flatMap((edge) => edge.sourceBotId === state.selectedId ? [edge.targetBotId] : edge.targetBotId === state.selectedId ? [edge.sourceBotId] : []) : []}
onComputer={(bot) => openBotSettings(dispatch, "access", { botId: bot.id })}
computers={showComputers && computersChoiceLoaded && !remoteClient ? mapComputers.computers : undefined} computerFrames={mapComputers.frames}
diff --git a/src/lib/map-computers.ts b/src/lib/map-computers.ts
index 0314fe2b43..ca68cb5a4a 100644
--- a/src/lib/map-computers.ts
+++ b/src/lib/map-computers.ts
@@ -5,6 +5,7 @@ import type { MapComputer, MapComputersPayload } from "../../shared/map-computer
import type { TeamComputers } from "./team-canvas-computers";
export const MAP_COMPUTERS_POLL_MS = 2_000;
+const NO_COMPUTERS: MapComputer[] = [];
export interface ShownFrame {
url: string;
@@ -137,7 +138,7 @@ export function useMapComputers(enabled: boolean) {
};
}, [enabled, show]);
- return { computers: payload?.computers ?? [], configured: payload?.configured ?? null, frames, error };
+ return { computers: payload?.computers ?? NO_COMPUTERS, configured: payload?.configured ?? null, frames, error, answered: payload !== null || error !== null };
}
/** "Show computers", remembered per workspace like the canvas layout; until chosen, on whenever there is a computer to