Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Sidebar: a dragged bot lands where it was dropped while another bot works (#7237)
Milind Soni69c72c0644c5
diff --git a/src/components/Sidebar.bot-reorder.dom.test.ts b/src/components/Sidebar.bot-reorder.dom.test.tsnew file mode 100644index 0000000000..33736b8fd2--- /dev/null+++ b/src/components/Sidebar.bot-reorder.dom.test.ts@@ -0,0 +1,135 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Bot } from "@/state/store";++const mode = vi.hoisted(() => ({ advanced: false }));+vi.mock("@/lib/interface-mode", async (original) => ({+ ...await original<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => mode.advanced,+}));+vi.mock("@/lib/thread-preferences", async (original) => ({+ ...await original<typeof import("@/lib/thread-preferences")>(), useShowThreads: () => mode.advanced,+}));+vi.mock("./DesktopCapabilities", async (original) => ({+ ...await original<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: false, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true }));++const { Sidebar } = await import("./Sidebar");+const { BotEditorStore, initialState } = await import("@/state/store");+const { setLocale } = await import("@/lib/i18n");+const BOT_TYPE = "application/x-openmausbot-sidebar-bot";++const bot = (id: string, extra: Partial<Bot> = {}): Bot => ({+ id, name: id[0]!.toUpperCase() + id.slice(1), threadId: `${id}-t`, title: "", description: "", color: "green", unread: false,+ notifications: true, messages: [], modelSelection: { instanceId: "test", model: "test" },+ tasks: [{ threadId: `${id}-t`, title: "Chat", createdAt: 1 }], ...extra,+});+const dispatch = vi.fn();+let host: HTMLDivElement;+let root: Root;+const render = (bots: Bot[]) => flushSync(() => root.render(createElement(BotEditorStore, {+ value: { state: { ...initialState, connected: true, bots, selectedId: bots[0]!.id }, dispatch,+ flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} },+ children: createElement(Sidebar, { open: true, onClose: () => {} }),+})));++function dataTransfer() {+ const data = new Map<string, string>();+ return { data, effectAllowed: "all", dropEffect: "none", get types() { return [...data.keys()]; },+ setData: (type: string, value: string) => { data.set(type, value); }, getData: (type: string) => data.get(type) ?? "",+ setDragImage: () => {}, files: [], items: [] };+}+function fire(target: Element, type: string, transfer: ReturnType<typeof dataTransfer>, clientY = 0) {+ const event = new Event(type, { bubbles: true, cancelable: true });+ Object.defineProperty(event, "dataTransfer", { value: transfer });+ Object.defineProperty(event, "clientY", { value: clientY });+ flushSync(() => target.dispatchEvent(event));+ return event;+}+/** The draggable element around a bot's row: the one carrying the drag handlers. */+const dragHost = (id: string) => document.querySelector(`[data-sidebar-bot-row="${id}"]`)?.closest('[draggable="true"]') ?? null;++beforeEach(() => {+ dispatch.mockReset();+ localStorage.clear();+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ setLocale("en");+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+ // Each row 50px tall, one under another, so a drop on a row's lower edge lands after it.+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ const rows = [...document.querySelectorAll('[draggable="true"]')];+ const index = Math.max(0, rows.indexOf(this));+ return { top: index * 50, bottom: index * 50 + 50, height: 50, left: 0, right: 200, width: 200, x: 0, y: index * 50, toJSON: () => ({}) } as DOMRect;+ });+});+afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++const order = () => [...document.querySelectorAll<HTMLElement>("[data-sidebar-bot-row]")].map((row) => row.dataset.sidebarBotRow);+/** Drags `moving` onto the top or bottom edge of `onto`'s row and lets go. */+function dragOnto(moving: string, onto: string, edge: "top" | "bottom") {+ const from = dragHost(moving), target = dragHost(onto);+ expect(from, `${moving} is draggable`).not.toBeNull();+ expect(target, `${onto} is draggable`).not.toBeNull();+ const transfer = dataTransfer();+ fire(from!, "dragstart", transfer);+ expect(transfer.types).toContain(BOT_TYPE);+ const box = target!.getBoundingClientRect();+ const y = edge === "top" ? box.top + 2 : box.bottom - 2;+ fire(target!, "dragover", transfer, y);+ fire(target!, "drop", transfer, y);+ fire(from!, "dragend", transfer);+}+const saved = () => dispatch.mock.calls.map(([action]) => action).filter((action) => action.type === "botsOrdered");++for (const advanced of [false, true]) {+ describe(`dragging a bot in ${advanced ? "Advanced" : "Simple"} mode`, () => {+ beforeEach(() => { mode.advanced = advanced; });++ it("moves it below another bot and saves the order", () => {+ render([bot("alpha"), bot("bravo"), bot("charlie"), bot("delta")]);+ expect(order()).toEqual(["alpha", "bravo", "charlie", "delta"]);+ dragOnto("delta", "bravo", "bottom");+ expect(saved()).toEqual([{ type: "botsOrdered", botIds: ["alpha", "bravo", "delta", "charlie"] }]);+ });++ it("puts a bot dropped above a working one first among the rest, without storing the working one's place", () => {+ // Saved alpha, bravo, charlie, delta; delta is working, so it is drawn first.+ render([bot("alpha"), bot("bravo"), bot("charlie"), bot("delta", { busy: true })]);+ expect(order()).toEqual(["delta", "alpha", "bravo", "charlie"]);+ dragOnto("charlie", "delta", "top");+ expect(saved()).toEqual([{ type: "botsOrdered", botIds: ["charlie", "alpha", "bravo", "delta"] }]);+ });++ it("says only a keyboard move the rows show: Alt+Up past a working bot changes nothing", () => {+ render([bot("alpha"), bot("bravo"), bot("delta", { busy: true })]);+ expect(order()).toEqual(["delta", "alpha", "bravo"]);+ const press = (id: string, key: string) => flushSync(() => document.querySelector(`[data-sidebar-bot-row="${id}"]`)!+ .dispatchEvent(new KeyboardEvent("keydown", { key, altKey: true, bubbles: true, cancelable: true })));+ press("alpha", "ArrowUp");+ expect(saved()).toEqual([]);+ expect(document.body.textContent).not.toContain("moved to position");+ press("alpha", "ArrowDown");+ expect(saved()).toEqual([{ type: "botsOrdered", botIds: ["bravo", "alpha", "delta"] }]);+ expect(document.body.textContent).toContain("Alpha moved to position 3 of 3");+ });++ it("moves a bot below a waiting one's place among the rows as drawn", () => {+ render([bot("alpha"), bot("bravo", { activity: "waiting-on-you" }), bot("charlie"), bot("delta")]);+ expect(order()).toEqual(["bravo", "alpha", "charlie", "delta"]);+ dragOnto("delta", "bravo", "bottom");+ expect(saved()).toEqual([{ type: "botsOrdered", botIds: ["delta", "alpha", "bravo", "charlie"] }]);+ });+ });+}diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex cd214c953d..6a4cdcac98 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -1095,11 +1095,9 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const viewerEmail = useViewerEmail();const parts = partitionSidebarBots(botDrag.preview(matchingBots), { universalPins, viewerEmail, welcoming: useWelcomingBot(), searching: Boolean(q) });const saved = simpleDesk ? withPrimaryTile(parts, myDefaultBot(state.bots, viewerEmail)?.id) : { ...parts, primary: null };- // Shown order only: drag and Alt+Up/Down keep working on the saved order, so a reorder never stores this one.- const { primary, unsectionedChief, pinnedBots, sectionChiefs, sectionedBots, unsectionedBots } = { ...saved, ...activeBotsFirst(saved, (bot) => {- const { waiting, working } = sidebarBotStatus(bot, state.pendingQueued);- return waiting || working;- }) };+ // Shown order only: a drag or Alt+Up/Down moves a bot among the rows as drawn and saves it into the saved order.+ const floats = (bot: Bot) => { const { waiting, working } = sidebarBotStatus(bot, state.pendingQueued); return waiting || working; };+ const { primary, unsectionedChief, pinnedBots, sectionChiefs, sectionedBots, unsectionedBots } = { ...saved, ...activeBotsFirst(saved, floats) };const { botChats, sectionedRooms, unsectionedRooms } = partitionSidebarGroups(visibleGroups);const sectionNames: string[] = [...(state.sections ?? []).filter((name) => !q || name.toLowerCase().includes(q.toLowerCase())), ...botDrag.pending];@@ -1112,7 +1110,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =for (const group of sectionedRooms) {if (!sectionNames.includes(group.section!)) sectionNames.push(group.section!);}- const drops = botDrag.arrange({ enabled: (sections.interactive || density === "icons") && !phone, withinList: density === "icons", main: saved.unsectionedBots, sectioned: saved.sectionedBots, departments: sectionNames, bots: state.bots, taken: departmentNames(state) });+ const drops = botDrag.arrange({ enabled: (sections.interactive || density === "icons") && !phone, withinList: density === "icons", main: saved.unsectionedBots, sectioned: saved.sectionedBots, departments: sectionNames, bots: state.bots, taken: departmentNames(state), floats });const naturalSectionIds = [...(pinnedBots.length > 0 && !universalPins && !simpleDesk ? [PINNED_SECTION_ID] : []),...(unsectionedRooms.length > 0 ? [CHANNELS_SECTION_ID] : []),diff --git a/src/components/SidebarBotDrag.tsx b/src/components/SidebarBotDrag.tsxindex 4c28b76a9a..493c9dd11e 100644--- a/src/components/SidebarBotDrag.tsx+++ b/src/components/SidebarBotDrag.tsx@@ -3,7 +3,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { nextRename } from "@/lib/rename";import { BOTS_SECTION_ID, userSectionName } from "@/lib/sidebar-layout";-import { BOT_ROW_DRAG_TYPE, botDropPlace, botListOf, planBotDrop, sameBotDrop, stepBot, unusedName, type BotDrop, type BotDropPlace, type BotMove } from "@/lib/sidebar-bot-drop";+import { BOT_ROW_DRAG_TYPE, botDropPlace, botListOf, planBotDrop, sameBotDrop, savedPlacement, stepBot, unusedName, type BotDrop, type BotDropPlace, type BotMove } from "@/lib/sidebar-bot-drop";import type { Action, Bot } from "@/state/store";import { moveBotsToSection, renameDepartment, saveBotOrder, useMayMoveBots } from "./bot-sections";@@ -21,8 +21,11 @@ export type SectionNaming = { value: string; label: string; onCommit: (name: strtype Naming = { kind: "new"; botIds: string[]; name: string } | { kind: "rename"; section: string };-type Arranged = { enabled: boolean; lists: Map<string, string[]>; bots: Bot[]; taken: string[]; withinList: boolean };+/** `lists` hold each list's saved order, `shown` the order drawn (working or waiting bots, `floating`, first). */+type Arranged = { enabled: boolean; lists: Map<string, string[]>; shown: Map<string, string[]>; floating: Set<string>; bots: Bot[]; taken: string[]; withinList: boolean };+/** A list as the sidebar draws it: working or waiting bots first, each part in its saved order. */+const drawnOrder = (ids: readonly string[], floating: ReadonlySet<string>) => [...ids.filter((id) => floating.has(id)), ...ids.filter((id) => !floating.has(id))];const carries = (event: DragEvent<HTMLElement>) => event.dataTransfer.types.includes(BOT_ROW_DRAG_TYPE);const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));@@ -51,7 +54,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst [drop, setDrop] = useState<BotDrop | null>(null);const [naming, setNaming] = useState<Naming | null>(null);const mayMove = useMayMoveBots();- const latest = useRef<Arranged>({ enabled: false, lists: new Map(), bots: [], taken: [], withinList: false });+ const latest = useRef<Arranged>({ enabled: false, lists: new Map(), shown: new Map(), floating: new Set(), bots: [], taken: [], withinList: false });const moving = useRef<{ botId: string | null; drop: BotDrop | null }>({ botId: null, drop: null });const controller = useRef<BotRowDrag | null>(null);const actions = useRef({ dispatch, announce });@@ -70,12 +73,16 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst startNew = (botIds: string[]) => setNaming({ kind: "new", botIds, name: unusedName(t("sidebar.section.newName"), latest.current.taken) });const apply = (botId: string, move: BotMove, keyboard: boolean) => {if (move.kind === "group") return startNew(move.botIds);- const { lists, bots } = latest.current;- if (botListOf(lists, botId) !== move.section) moveBotsToSection(actions.current.dispatch, [botId], move.section);- saveBotOrder(actions.current.dispatch, bots, move.order);+ const { lists, shown, bots, floating } = latest.current;+ const order = savedPlacement(lists.get(move.section) ?? [], move.order, botId, (id) => floating.has(id)), after = drawnOrder(order, floating);+ const across = botListOf(lists, botId) !== move.section;+ // Alt+Up/Down past a bot that floats otherwise changes nothing drawn: no move, so nothing to say.+ if (keyboard && !across && after.every((id, index) => id === shown.get(move.section)?.[index])) return;+ if (across) moveBotsToSection(actions.current.dispatch, [botId], move.section);+ saveBotOrder(actions.current.dispatch, bots, order);if (!keyboard) return;const name = bots.find((bot) => bot.id === botId)?.name ?? "";- actions.current.announce(t("sidebar.section.moved", { name, position: move.order.indexOf(botId) + 1, count: move.order.length }));+ actions.current.announce(t("sidebar.section.moved", { name, position: after.indexOf(botId) + 1, count: after.length }));requestAnimationFrame(() => document.querySelector<HTMLElement>(`[data-sidebar-bot-row="${CSS.escape(botId)}"]`)?.focus());};const allowed = (botId: string, move: BotMove | null): BotMove | null => {@@ -88,7 +95,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst finish = (target: BotDrop | null) => {const botId = moving.current.botId;end();- const move = botId && target && latest.current.enabled ? planBotDrop(latest.current.lists, botId, target) : null;+ const move = botId && target && latest.current.enabled ? planBotDrop(latest.current.shown, botId, target) : null;if (botId && move) {const next = allowed(botId, move);if (next) apply(botId, next, false);@@ -129,7 +136,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onEr},}),step: (botId, direction) => {- const move = latest.current.enabled ? stepBot(latest.current.lists, botId, direction) : null;+ const move = latest.current.enabled ? stepBot(latest.current.shown, botId, direction) : null;if (move) apply(botId, move, true);},};@@ -151,16 +158,20 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErpreview: <T extends Bot>(bots: T[]): T[] => naming?.kind === "new" ? bots.map((bot) => (naming.botIds.includes(bot.id) ? { ...bot, section: NEW_DEPARTMENT } : bot)) : bots,startNew: (botIds: string[]) => startNew(botIds),startRename: (section: string) => setNaming({ kind: "rename", section }),- arrange({ enabled, withinList = false, main, sectioned, departments, bots, taken }: {- enabled: boolean; withinList?: boolean; main: Bot[]; sectioned: Bot[]; departments: string[]; bots: Bot[]; taken: string[];+ /** `main` and `sectioned` in their saved order; `floats` says which bots the sidebar draws first in their list. A drop+ * or Alt+Up/Down moves a bot among the rows as drawn, and is saved into the saved order (savedPlacement). */+ arrange({ enabled, withinList = false, main, sectioned, departments, bots, taken, floats }: {+ enabled: boolean; withinList?: boolean; main: Bot[]; sectioned: Bot[]; departments: string[]; bots: Bot[]; taken: string[]; floats?: (bot: Bot) => boolean;}) {const 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));- latest.current = { enabled: movable, lists, bots, taken, withinList };+ const floating = new Set(floats ? [...main, ...sectioned].filter(floats).map((bot) => bot.id) : []);+ const drawn = new Map([...lists].map(([name, ids]) => [name, drawnOrder(ids, floating)]));+ latest.current = { enabled: movable, lists, shown: drawn, floating, bots, taken, withinList };const active = movable && dragging !== null && botListOf(lists, dragging) !== undefined ? dragging : null;const shown = active ? drop : null;- const mainIds = lists.get("")!.filter((id) => id !== active);+ const mainIds = drawn.get("")!.filter((id) => id !== active);const listFor = (sectionId: string) => (sectionId === BOTS_SECTION_ID ? "" : userSectionName(sectionId));// Between rows, or under the last one, the nearest row places the bot; a department's heading takes it in.const zoneDrop = (event: DragEvent<HTMLElement>, list: string): BotDrop => {diff --git a/src/lib/sidebar-bot-drop.test.ts b/src/lib/sidebar-bot-drop.test.tsindex cf670dd4b9..cbc8963097 100644--- a/src/lib/sidebar-bot-drop.test.ts+++ b/src/lib/sidebar-bot-drop.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { botDropPlace, planBotDrop, stepBot, stepKey, unusedName, type BotLists } from "./sidebar-bot-drop";+import { botDropPlace, planBotDrop, savedPlacement, stepBot, stepKey, unusedName, type BotLists } from "./sidebar-bot-drop";const lists: BotLists = new Map([["", ["atlas", "bea", "cleo"]],@@ -67,3 +67,25 @@ describe("a new department's name", () => {expect(unusedName("New department", ["New department", "New department 2", "New department 4"])).toBe("New department 3");});});++describe("saving a move made among the rows as drawn, working or waiting bots first", () => {+ const floating = (...ids: string[]) => (id: string) => ids.includes(id);++ it("keeps the saved order when nothing floats", () => {+ expect(savedPlacement(["atlas", "bea", "cleo"], ["cleo", "atlas", "bea"], "cleo", floating())).toEqual(["cleo", "atlas", "bea"]);+ expect(savedPlacement(["dodo", "echo"], ["dodo", "bea", "echo"], "bea", floating())).toEqual(["dodo", "bea", "echo"]);+ });++ it("puts a bot dropped above a working one first among the bots that do not float", () => {+ // Saved charlie, pepper, bravo, alpha; alpha works, so it is drawn first. Bravo dropped above it goes first of the rest.+ expect(savedPlacement(["charlie", "pepper", "bravo", "alpha"], ["bravo", "alpha", "charlie", "pepper"], "bravo", floating("alpha")))+ .toEqual(["bravo", "charlie", "pepper", "alpha"]);+ });++ it("moves a working bot no further than its drawn neighbours ask, and never stores the drawn order", () => {+ expect(savedPlacement(["a2", "i1", "b", "i2", "i3"], ["a2", "i1", "i2", "b", "i3"], "b", floating("a2", "b"))).toEqual(["a2", "i1", "i2", "b", "i3"]);+ expect(savedPlacement(["atlas", "bea", "cleo"], ["cleo", "bea", "atlas"], "atlas", floating("cleo"))).toEqual(["bea", "atlas", "cleo"]);+ // Two working bots swap: their order among themselves is the person's.+ expect(savedPlacement(["i1", "a1", "i2", "a2"], ["a2", "a1", "i1", "i2"], "a2", floating("a1", "a2"))).toEqual(["i1", "a2", "a1", "i2"]);+ });+});diff --git a/src/lib/sidebar-bot-drop.ts b/src/lib/sidebar-bot-drop.tsindex 1082ee5e1c..1bcf334c2a 100644--- a/src/lib/sidebar-bot-drop.ts+++ b/src/lib/sidebar-bot-drop.ts@@ -54,6 +54,22 @@ export function planBotDrop(lists: BotLists, botId: string, drop: BotDrop): BotMreturn placed(lists, botId, from, to, (others) => others.indexOf(drop.botId) + (drop.place === "after" ? 1 : 0));}+/** The saved order of a list that draws `botId` where `shown` (that list as drawn after the move: working or waiting bots+ * first) has it. The bot goes after the one drawn just above it, moved no further than it takes to stay between the+ * nearest bots drawn around it that `floats` alike; every other bot keeps its saved place, so the drawn order is never+ * stored. */+export function savedPlacement(saved: readonly string[], shown: readonly string[], botId: string, floats: (id: string) => boolean): string[] {+ const order = saved.filter((id) => id !== botId);+ const at = shown.indexOf(botId), above = shown.slice(0, at), below = shown.slice(at + 1);+ const alike = (id: string) => floats(id) === floats(botId);+ let index = above.length ? order.indexOf(above.at(-1)!) + 1 : below.length ? order.indexOf(below[0]!) : order.length;+ const low = above.findLast(alike), high = below.find(alike);+ if (low !== undefined) index = Math.max(index, order.indexOf(low) + 1);+ if (high !== undefined) index = Math.min(index, order.indexOf(high));+ order.splice(index, 0, botId);+ return order;+}+export function stepBot(lists: BotLists, botId: string, direction: -1 | 1): BotMove | null {const from = botListOf(lists, botId);if (from === undefined) return null;