Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Draw hand-off lines between bots on the Team map canvas
AdityaUmale63aa5b0168bc
diff --git a/src/components/TeamCanvas.settle.dom.test.ts b/src/components/TeamCanvas.settle.dom.test.tsindex ddee77e806..c16285bc59 100644--- a/src/components/TeamCanvas.settle.dom.test.ts+++ b/src/components/TeamCanvas.settle.dom.test.ts@@ -14,13 +14,14 @@ const fixture = vi.hoisted(() => {subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },computers: [] as MapComputer[],computersAnswer: true,+ teamMap: { collaborations: [], queued: [], running: [] } as object,};});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/team-map")) return structuredClone(fixture.teamMap);if (path.startsWith("/api/computers/frames")) {if (!fixture.computersAnswer) return new Promise(() => {});return { computers: structuredClone(fixture.computers), configured: true, available: true, now: Date.now() };@@ -72,6 +73,7 @@ beforeEach(() => {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;+ fixture.teamMap = { collaborations: [], queued: [], running: [] };container = document.createElement("div");document.body.append(container);root = createRoot(container);@@ -142,3 +144,20 @@ it("shows the teams anyway when the computers never answer", async () => {await new Promise((resolve) => setTimeout(resolve, 3_000));expect(look()).toContain("cards 5");});++it("draws a line between bots that hand work to each other, labelled with what the hand-off is doing", async () => {+ fixture.computers = [];+ fixture.teamMap = {+ collaborations: [{ groupId: "group", botIds: ["ana", "ben"], lastAt: 1 }],+ queued: [],+ running: [{ sourceBotId: "chief", targetBotId: "cy", threadId: "thread-cy" }],+ };+ fixture.set({ ...initialState, bots: team(false), sections: ["Sales", "Ops"] });+ root.render(createElement(TeamMapPage));+ await watch(200, []);+ const world = container.querySelector("[data-canvas-world]")!;+ const lines = [...world.querySelectorAll<SVGPathElement>("[data-handoff-line]")];+ expect(lines.map((line) => line.dataset.state)).toEqual(["running", "connected"]);+ expect(lines.every((line) => /^M [\d.]+ [\d.]+ C /.test(line.getAttribute("d") ?? ""))).toBe(true);+ expect([...world.querySelectorAll("[data-handoff-label]")].map((label) => label.textContent)).toEqual(["Running"]);+});diff --git a/src/components/TeamCanvas.tsx b/src/components/TeamCanvas.tsxindex 70e9712532..a1bda5ae25 100644--- a/src/components/TeamCanvas.tsx+++ b/src/components/TeamCanvas.tsx@@ -5,9 +5,10 @@ import { teamBotName, useTeamPeople } from "@/state/team-people";import { useShowThreads } from "@/lib/thread-preferences";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { teamMapStatus, type TeamMapSection } from "@/lib/team-map";+import { teamMapStatus, type TeamMapEdge, type TeamMapSection } from "@/lib/team-map";import { COMPUTER_DRAG_TYPE, fitTeams, layoutTeams, orderBots, parseBotOrders, parsePositions, reorderBot, teamSize, zoomAt, type Point, type View } from "@/lib/team-canvas";import { bestColumns, polylinePath, teamGeometry, type TeamGeometry } from "@/lib/team-canvas-computers";+import { botCardBoxes, handoffLines } from "@/lib/team-canvas-handoffs";import { teamComputersFor, type ShownFrame } from "@/lib/map-computers";import { activityPreview, botEngine } from "@/lib/failed-turn";import { computerStepLine } from "@/lib/computer-step";@@ -85,6 +86,7 @@ function BotCard({ bot, selected, moving, connected, tagged = false, sent, onCom</article>;}+const NO_EDGES: TeamMapEdge[] = [];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;@@ -98,7 +100,7 @@ function currentActivity(bot: Bot | undefined, instances: ReturnType<typeof useSreturn 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, settling = false }: {+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, edges = NO_EDGES }: {sections: TeamMapSection<Bot>[];canManage: boolean;onMove: (bot: Bot, destination: string) => Promise<boolean | void>;@@ -124,6 +126,8 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemobottomInset?: number;/** Something that changes the layout, such as the computers drawn beside the bots, is still loading. */settling?: boolean;+ /** Who hands work to whom: each one is drawn as a line between the two cards. */+ edges?: TeamMapEdge[];}) {const { state } = useStore();const viewport = useRef<HTMLDivElement>(null);@@ -160,6 +164,7 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemoreturn { sizes, columns: bestColumns(sizes, { width: Math.round(viewportSize.width / 200) * 200, height: Math.round(viewportSize.height / 200) * 200 }) };}, [geometries, sections, viewportSize]);const tiles = useMemo(() => layoutTeams(sections, positions, columnsFor), [sections, positions, columnsFor]);+ const handoffs = useMemo(() => handoffLines(edges, botCardBoxes(sections, tiles, geometries, botOrders)), [edges, sections, tiles, geometries, botOrders]);const current = useRef({ view, positions, tiles, selectedId: state.selectedId, settingsOpen: state.settingsOpen, bottomInset });current.current = { view, positions, tiles, selectedId: state.selectedId, settingsOpen: state.settingsOpen, bottomInset };@@ -510,6 +515,16 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo</div>}</section>;})}+ {handoffs.length > 0 && <div aria-hidden className="pointer-events-none absolute left-0 top-0">+ <svg className="absolute left-0 top-0 overflow-visible" width={1} height={1}>+ {handoffs.map((line) => <path key={line.key} data-handoff-line data-state={line.state} d={line.path} fill="none" strokeLinecap="round"+ strokeWidth={line.state === "connected" ? 1.5 : 2.25} strokeDasharray={line.state === "connected" ? undefined : "7 5"}+ className={line.state === "running" ? "animate-link-flow stroke-success/80" : line.state === "queued" ? "stroke-warning/80" : "stroke-ink-secondary/35"} />)}+ </svg>+ {handoffs.filter((line) => line.state !== "connected").map((line) => <span key={line.key} data-handoff-label style={{ left: line.label.x, top: line.label.y }}+ className={cn("absolute -translate-x-1/2 -translate-y-1/2 whitespace-nowrap rounded-full bg-panel px-2 py-0.5 text-[11px] font-medium shadow-sm ring-1",+ line.state === "running" ? "text-success ring-success/30" : "text-warning ring-warning/30")}>{line.state === "running" ? t("canvas.edge.running") : t("canvas.edge.queued")}</span>)}+ </div>}</div>{dragged && <div className="pointer-events-none absolute z-40 rounded-xl border border-accent/40 bg-card px-4 py-3 text-[13px] shadow-lg" style={{ left: dragged.point.x + 16, top: dragged.point.y + 16 }}><span className="flex items-center gap-2"><BotAvatar bot={dragged.bot} size={24} animated={false} />{dragged.bot.name}</span>diff --git a/src/components/TeamMapPage.tsx b/src/components/TeamMapPage.tsxindex 579ec0db95..e6c24008f8 100644--- a/src/components/TeamMapPage.tsx+++ b/src/components/TeamMapPage.tsx@@ -389,7 +389,7 @@ export function TeamMapPage() {</div>}<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}+ <TeamCanvas sections={sections} edges={edges} 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 })}diff --git a/src/lib/team-canvas-handoffs.test.ts b/src/lib/team-canvas-handoffs.test.tsnew file mode 100644index 0000000000..c152d07aef--- /dev/null+++ b/src/lib/team-canvas-handoffs.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { botCardBoxes, handoffLines, type CardBox } from "./team-canvas-handoffs";+import { layoutTeams, teamSize } from "./team-canvas";+import type { TeamMapSection } from "./team-map";++const bot = (id: string, chiefOfStaff = false) => ({ id, name: id, chiefOfStaff });+const sales: TeamMapSection = { key: "Sales", name: "Sales", chiefs: [bot("chief", true)], members: [bot("ana"), bot("ben")] };+const ops: TeamMapSection = { key: "Ops", name: "Ops", chiefs: [], members: [bot("cy")] };++describe("botCardBoxes", () => {+ it("places chiefs left of members, each column centred under the team header", () => {+ const tiles = [{ key: "Sales", x: 100, y: 50, ...teamSize(sales) }];+ const boxes = botCardBoxes([sales], tiles, [null], {});+ expect(boxes.get("chief")).toEqual({ x: 120, y: 50 + 64 + 71, width: 236, height: 126 });+ expect(boxes.get("ana")).toEqual({ x: 396, y: 114, width: 236, height: 126 });+ expect(boxes.get("ben")).toEqual({ x: 396, y: 256, width: 236, height: 126 });+ });++ it("follows the person's own card order and a team with members only", () => {+ const tiles = layoutTeams([sales, ops], {});+ const boxes = botCardBoxes([sales, ops], tiles, [null, null], { Sales: ["ben", "ana"] });+ expect(boxes.get("ben")!.y).toBeLessThan(boxes.get("ana")!.y);+ expect(boxes.get("cy")).toMatchObject({ x: tiles[1].x + 20, y: tiles[1].y + 64 });+ });++ it("uses the computer layout's own card spots when a team draws computers", () => {+ const tiles = [{ key: "Ops", x: 10, y: 20, width: 400, height: 300 }];+ const geometry = { width: 400, height: 300, cards: [{ botId: "cy", x: 30, y: 90 }], monitors: [], links: [], tree: [] };+ expect(botCardBoxes([ops], tiles, [geometry], {})).toEqual(new Map([["cy", { x: 40, y: 110, width: 236, height: 126 }]]));+ });+});++describe("handoffLines", () => {+ const box = (x: number, y: number): CardBox => ({ x, y, width: 100, height: 50 });+ const boxes = new Map([["a", box(0, 0)], ["b", box(300, 100)], ["c", box(0, 200)]]);++ it("joins side-by-side cards from the giver's facing edge to the receiver's, labelled mid-way", () => {+ expect(handoffLines([{ sourceBotId: "a", targetBotId: "b", state: "running" }], boxes)).toEqual([{+ key: "a:b", state: "running", path: "M 100 25 C 200 25 200 125 300 125", label: { x: 200, y: 75 },+ }]);+ expect(handoffLines([{ sourceBotId: "b", targetBotId: "a", state: "queued" }], boxes)[0].path).toBe("M 300 125 C 200 125 200 25 100 25");+ });++ it("joins stacked cards bottom to top, and skips bots that are not on the canvas", () => {+ const lines = handoffLines([+ { sourceBotId: "c", targetBotId: "a", state: "connected" },+ { sourceBotId: "a", targetBotId: "hidden", state: "running" },+ ], boxes);+ expect(lines).toEqual([{ key: "c:a", state: "connected", path: "M 50 200 C 50 125 50 125 50 50", label: { x: 50, y: 125 } }]);+ });+});diff --git a/src/lib/team-canvas-handoffs.ts b/src/lib/team-canvas-handoffs.tsnew file mode 100644index 0000000000..dad3fe4d66--- /dev/null+++ b/src/lib/team-canvas-handoffs.ts@@ -0,0 +1,70 @@+import { CARD_HEIGHT, CARD_WIDTH, GAP, HEADER_HEIGHT, TEAM_PADDING, orderBots, type Point, type Tile } from "./team-canvas";+import type { TeamGeometry } from "./team-canvas-computers";+import type { TeamMapEdge, TeamMapSection } from "./team-map";++export interface CardBox extends Point { width: number; height: number }++export interface HandoffLine {+ key: string;+ state: TeamMapEdge["state"];+ path: string;+ /** Where the line's label sits: the middle of the curve. */+ label: Point;+}++/** Spacer between the chiefs column and the members column when a team draws no computers. */+const CHIEF_GAP = 40;++/** Where each bot's card sits on the canvas, in world coordinates, for both team layouts. */+export function botCardBoxes(+ sections: TeamMapSection[],+ tiles: Tile[],+ geometries: Array<TeamGeometry | null>,+ orders: Record<string, string[]>,+): Map<string, CardBox> {+ const boxes = new Map<string, CardBox>();+ const place = (botId: string, x: number, y: number) => boxes.set(botId, { x, y, width: CARD_WIDTH, height: CARD_HEIGHT });+ sections.forEach((section, index) => {+ const tile = tiles[index], geometry = geometries[index];+ if (!tile) return;+ if (geometry) {+ for (const card of geometry.cards) place(card.botId, tile.x + card.x, tile.y + card.y);+ return;+ }+ const content = tile.height - HEADER_HEIGHT - TEAM_PADDING;+ const columns = [section.chiefs, section.members].filter((column) => column.length > 0);+ columns.forEach((column, columnIndex) => {+ const height = column.length * (CARD_HEIGHT + GAP) - GAP;+ const top = tile.y + HEADER_HEIGHT + (content - height) / 2;+ const left = tile.x + TEAM_PADDING + columnIndex * (CARD_WIDTH + CHIEF_GAP);+ orderBots(column, Object.hasOwn(orders, section.key) ? orders[section.key] : []).forEach((bot, row) => place(bot.id, left, top + row * (CARD_HEIGHT + GAP)));+ });+ });+ return boxes;+}++/** A curved line from the bot handing work on to the bot receiving it, edge to facing edge. */+export function handoffLines(edges: TeamMapEdge[], boxes: Map<string, CardBox>): HandoffLine[] {+ return edges.flatMap((edge) => {+ const from = boxes.get(edge.sourceBotId), to = boxes.get(edge.targetBotId);+ if (!from || !to || edge.sourceBotId === edge.targetBotId) return [];+ const sideBySide = from.x + from.width <= to.x || to.x + to.width <= from.x;+ const forward = sideBySide ? from.x < to.x : from.y < to.y;+ const anchor = (box: CardBox, leaving: boolean): Point => {+ const far = leaving === forward;+ return sideBySide+ ? { x: far ? box.x + box.width : box.x, y: box.y + box.height / 2 }+ : { x: box.x + box.width / 2, y: far ? box.y + box.height : box.y };+ };+ const start = anchor(from, true), end = anchor(to, false);+ const bend = sideBySide ? (end.x - start.x) / 2 : (end.y - start.y) / 2;+ const first = sideBySide ? { x: start.x + bend, y: start.y } : { x: start.x, y: start.y + bend };+ const second = sideBySide ? { x: end.x - bend, y: end.y } : { x: end.x, y: end.y - bend };+ return [{+ key: `${edge.sourceBotId}:${edge.targetBotId}`,+ state: edge.state,+ path: `M ${start.x} ${start.y} C ${first.x} ${first.y} ${second.x} ${second.y} ${end.x} ${end.y}`,+ label: { x: (start.x + 3 * first.x + 3 * second.x + end.x) / 8, y: (start.y + 3 * first.y + 3 * second.y + end.y) / 8 },+ }];+ });+}