Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Room order: save one at a time, never restore an old order, keep rows mounted
AdityaUmale0e4a0ccbe662
diff --git a/server/store-reorder-groups.test.ts b/server/store-reorder-groups.test.tsnew file mode 100644index 0000000000..7ffd0a8415--- /dev/null+++ b/server/store-reorder-groups.test.ts@@ -0,0 +1,28 @@+import { rmSync } from "node:fs";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { DATA_DIR } from "./config.ts";+import type { ModelSelection } from "./contracts.ts";+import { Store } from "./store.ts";++const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });++describe("reordering rooms", () => {+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));++ it("leaves the rooms as they were when the new order cannot be saved", () => {+ const store = new Store(selection);+ const bot = store.createBot({ name: "Ada" });+ for (const name of ["One", "Two", "Three"]) store.createGroup(name, [bot.id]);+ const before = store.groups.map((group) => group.id), wanted = [...before].reverse();+ const file = (store as unknown as { groupsFile: { write: (text: string) => void } }).groupsFile;+ const write = vi.spyOn(file, "write").mockImplementation(() => { throw new Error("disk full"); });+ try {+ expect(() => store.reorderGroups(wanted)).toThrow("disk full");+ expect(store.groups.map((group) => group.id)).toEqual(before);+ } finally {+ write.mockRestore();+ }+ expect(store.reorderGroups(wanted)?.map((group) => group.id)).toEqual(wanted);+ });+});diff --git a/server/store.ts b/server/store.tsindex 8a82668901..99e58ec3e7 100644--- a/server/store.ts+++ b/server/store.ts@@ -1979,8 +1979,8 @@ export class Store {}reorderGroups(groupIds: string[]): GroupRecord[] | null {- if (!reorderInPlace(this.groups, groupIds)) return null;- this.saveGroups(this.groups, false); this.emit({ type: "groups.order" }); return this.groups;+ const next = [...this.groups]; if (!reorderInPlace(next, groupIds)) return null; // saved before the live list changes+ this.saveGroups(next, false); this.groups.splice(0, this.groups.length, ...next); this.emit({ type: "groups.order" }); return this.groups;}deleteProject(botId: string, projectId: string): BotRecord | null {diff --git a/src/components/SidebarRoomDrag.test.ts b/src/components/SidebarRoomDrag.test.tsnew file mode 100644index 0000000000..8ccae7c604--- /dev/null+++ b/src/components/SidebarRoomDrag.test.ts@@ -0,0 +1,72 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({+ calls: [] as { body: string; settle: (error?: Error) => void }[],+ api: vi.fn(),+}));+vi.mock("@/state/store", () => ({ api: fixture.api }));++const { saveRoomOrder } = await import("./SidebarRoomDrag");++const rooms = (...ids: string[]) => ids.map((id) => ({ id }));+const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve(); };+const orders = (dispatch: ReturnType<typeof vi.fn>) =>+ dispatch.mock.calls.map(([action]) => action).filter((action) => action.type === "groupsOrdered").map((action) => action.groupIds);++describe("saveRoomOrder", () => {+ beforeEach(() => {+ fixture.calls = [];+ fixture.api.mockReset();+ fixture.api.mockImplementation((_path: string, init: { body: string }) => new Promise<void>((resolve, reject) => {+ fixture.calls.push({ body: init.body, settle: (error) => (error ? reject(error) : resolve()) });+ }));+ });++ it("saves one order at a time, in the order asked", async () => {+ const dispatch = vi.fn();+ saveRoomOrder(dispatch, rooms("a", "b", "c"), ["b", "a", "c"]);+ saveRoomOrder(dispatch, rooms("b", "a", "c"), ["c", "b", "a"]);+ await flush();+ expect(fixture.calls.map((call) => JSON.parse(call.body).groupIds)).toEqual([["b", "a", "c"]]);+ fixture.calls[0]!.settle();+ await flush();+ expect(fixture.calls.map((call) => JSON.parse(call.body).groupIds)).toEqual([["b", "a", "c"], ["c", "b", "a"]]);+ fixture.calls[1]!.settle();+ await flush();+ expect(orders(dispatch)).toEqual([["b", "a", "c"], ["c", "b", "a"]]);+ });++ it("keeps a newer saved order when an older save fails", async () => {+ const dispatch = vi.fn();+ saveRoomOrder(dispatch, rooms("a", "b", "c"), ["b", "a", "c"]);+ saveRoomOrder(dispatch, rooms("b", "a", "c"), ["c", "b", "a"]);+ await flush();+ fixture.calls[0]!.settle(new Error("offline"));+ await flush();+ fixture.calls[1]!.settle();+ await flush();+ // The second order is what the server now holds, so nothing older is put back.+ expect(orders(dispatch)).toEqual([["b", "a", "c"], ["c", "b", "a"], ["c", "b", "a"]]);+ expect(dispatch).toHaveBeenCalledWith({ type: "error", message: "offline" });+ });++ it("puts back the order the server last confirmed when the last save fails", async () => {+ const dispatch = vi.fn();+ saveRoomOrder(dispatch, rooms("a", "b", "c"), ["b", "a", "c"]);+ saveRoomOrder(dispatch, rooms("b", "a", "c"), ["c", "b", "a"]);+ await flush();+ fixture.calls[0]!.settle();+ await flush();+ fixture.calls[1]!.settle(new Error("offline"));+ await flush();+ expect(orders(dispatch).at(-1)).toEqual(["b", "a", "c"]);+ expect(dispatch).toHaveBeenLastCalledWith({ type: "error", message: "offline" });+ });++ it("does nothing when the order did not change", () => {+ const dispatch = vi.fn();+ saveRoomOrder(dispatch, rooms("a", "b"), ["a", "b"]);+ expect(dispatch).not.toHaveBeenCalled();+ expect(fixture.api).not.toHaveBeenCalled();+ });+});diff --git a/src/components/SidebarRoomDrag.tsx b/src/components/SidebarRoomDrag.tsxindex ba6aac751a..b843db902d 100644--- a/src/components/SidebarRoomDrag.tsx+++ b/src/components/SidebarRoomDrag.tsx@@ -4,20 +4,35 @@ import { t } from "@/lib/i18n";import { stepKey } from "@/lib/sidebar-bot-drop";import { planRoomDrop, ROOM_ROW_DRAG_TYPE, roomDropPlace, stepRoom, type RoomDropPlace } from "@/lib/sidebar-room-drop";import { api, type Action, type Group } from "@/state/store";+import { reorderIfMoved } from "../../shared/bot-order";import { useMayMoveBots } from "./bot-sections";import { BotDropLine, botRowDropClass } from "./SidebarBotDrag";const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));+/** Room-order saves run one at a time, in the order asked, so the server ends on the last order asked for. Once the+ * last one settles after any failed, the rooms go back to the order the server confirmed (never an older one). */+const roomOrder = { saves: Promise.resolve(), pending: 0, failed: false, cause: undefined as unknown, confirmed: [] as { id: string }[] };+/** Saves the rooms' new order: shown at once, then stored on the server (every client gets it); put back on failure. */export function saveRoomOrder(dispatch: Dispatch<Action>, groups: readonly Pick<Group, "id">[], groupIds: string[]): void {const before = groups.filter((group) => groupIds.includes(group.id)).map((group) => group.id);if (before.length === groupIds.length && before.every((id, index) => id === groupIds[index])) return;+ if (!roomOrder.pending) roomOrder.confirmed = groups.map(({ id }) => ({ id }));+ roomOrder.pending += 1;dispatch({ type: "groupsOrdered", groupIds });- void api("/api/groups/order", { method: "PUT", body: JSON.stringify({ groupIds }) }).catch((cause) => {- dispatch({ type: "groupsOrdered", groupIds: before });- dispatch({ type: "error", message: failure(cause) });- });+ roomOrder.saves = roomOrder.saves+ .then(() => api("/api/groups/order", { method: "PUT", body: JSON.stringify({ groupIds }) }))+ .then(+ () => { roomOrder.confirmed = reorderIfMoved(roomOrder.confirmed, groupIds) ?? roomOrder.confirmed; },+ (cause: unknown) => { roomOrder.failed = true; roomOrder.cause = cause; },+ )+ .finally(() => {+ if (--roomOrder.pending || !roomOrder.failed) return;+ roomOrder.failed = false;+ dispatch({ type: "groupsOrdered", groupIds: roomOrder.confirmed.map(({ id }) => id) });+ dispatch({ type: "error", message: failure(roomOrder.cause) });+ });}type RowHandlers = {@@ -126,13 +141,14 @@ export function useSidebarRoomDrag({ dispatch, announce, enabled, groups }: {if (items.length > 1) latest.current.lists.push(items.map((item) => item.id));return items;},- /** A room's row (and its open thread list) inside its drop target while rooms may move; the row alone otherwise.- * The target lays its children out like the sidebar list around it, so nothing moves on screen. */+ /** A room's row (and its open thread list) inside its drop target, which takes drags only while rooms may move.+ * The target is always there, so the row is not remounted when moving turns on or off, and it lays its children out+ * like the sidebar list around it, so nothing moves on screen. */wrap(groupId: string, item: ReactElement): ReactElement {- if (!latest.current.enabled || !listOf(groupId)) return item;- const place = drop?.groupId === groupId ? drop.place : null;+ const on = latest.current.enabled && Boolean(listOf(groupId));+ const place = on && drop?.groupId === groupId ? drop.place : null;return (- <div key={groupId} className={cn("relative flex flex-col [gap:inherit]", botRowDropClass(place, dragging === groupId))} {...row(groupId)}>+ <div key={groupId} className={cn("relative flex flex-col [gap:inherit]", botRowDropClass(place, on && dragging === groupId))} {...(on ? row(groupId) : {})}><BotDropLine place={place} />{item}</div>