Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Sidebar: drag rooms into order inside their list
AdityaUmale7e0449849ef1
diff --git a/server/bot-visibility.test.ts b/server/bot-visibility.test.tsindex fd7b441082..3ad8fd5665 100644--- a/server/bot-visibility.test.ts+++ b/server/bot-visibility.test.ts@@ -233,6 +233,7 @@ describe("live frames for a member", () => {expect(frameForMember({ kind: "sections", sections: ["Ops", "People"] }, ctx, seen())).toEqual({ kind: "sections", sections: ["Ops"] });expect(frameForMember({ kind: "bot.queued", queues: { "t-pub": [1], "t-hr": [2] } }, ctx, seen())).toEqual({ kind: "bot.queued", queues: { "t-pub": [1] } });expect(frameForMember({ kind: "bots.order", botIds: ["hr", "pub", "corp"] }, ctx, seen())).toEqual({ kind: "bots.order", botIds: ["pub", "corp"] });+ expect(frameForMember({ kind: "groups.order", groupIds: ["room-mixed", "room-pub"] }, ctx, seen())).toEqual({ kind: "groups.order", groupIds: ["room-pub"] });const config = { kind: "config", membership: {} };expect(frameForMember(config, ctx, seen())).toBe(config);expect(frameForMember({ kind: "bot", bot: { id: "corp", visibility: { people: ["@example.test"] } } }, ctx, seen()))diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex 80b1a34f92..2e29f0159d 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -543,6 +543,10 @@ export function frameForMember(payload: Record<string, unknown>, ctx: FrameConteconst botIds = Array.isArray(payload.botIds) ? payload.botIds.filter((id): id is string => typeof id === "string") : [];return { ...payload, botIds: botIds.filter((id) => visible.bot(id)) };}+ case "groups.order": {+ const groupIds = Array.isArray(payload.groupIds) ? payload.groupIds.filter((id): id is string => typeof id === "string") : [];+ return { ...payload, groupIds: groupIds.filter((id) => visible.group(id)) };+ }case "message":case "message.patch":case "thread":diff --git a/server/index.test.ts b/server/index.test.tsindex 275dabd568..84676da23b 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -4892,6 +4892,47 @@ describe("harness HTTP API", () => {}});+ it("stores the room order: a partial, stable reorder every client reads back", async () => {+ const bot = (await api("POST", "/api/bots")).body.bot;+ const room = async (name: string) => (await api("POST", "/api/groups", { name, memberIds: [bot.id] })).body.group;+ const first = await room("Room one"), second = await room("Room two"), third = await room("Room three");+ const mine = new Set([first.id, second.id, third.id]);+ const listed = async () => ((await api("GET", "/api/bots?messages=0")).body.groups as { id: string }[]).map((group) => group.id).filter((id) => mine.has(id));+ try {+ const start = await listed();+ expect(start).toHaveLength(3);+ const wanted = [...start].reverse();++ const stream = await openSse(`${BASE}/api/events`);+ try {+ await stream.until((frame) => frame.kind === "hello");+ const full = await api("PUT", "/api/groups/order", { groupIds: wanted });+ expect(full.status).toBe(200);+ expect(full.body.groupIds.filter((id: string) => mine.has(id))).toEqual(wanted);+ const frame = await stream.until((candidate) => candidate.kind === "groups.order");+ expect(frame.groupIds).toEqual(full.body.groupIds);+ } finally {+ stream.close();+ }+ expect(await listed()).toEqual(wanted);++ // Listing two rooms moves only those two, into the positions they already share.+ const partial = await api("PUT", "/api/groups/order", { groupIds: [wanted[2], wanted[0]] });+ expect(partial.status).toBe(200);+ expect(await listed()).toEqual([wanted[2], wanted[1], wanted[0]]);++ expect(await api("PUT", "/api/groups/order", { groupIds: [first.id, first.id] })).toMatchObject({ status: 400, body: { error: "groupIds must be a non-empty array of distinct room ids" } });+ expect(await api("PUT", "/api/groups/order", { groupIds: [] })).toMatchObject({ status: 400 });+ expect(await api("PUT", "/api/groups/order", { groupIds: "nope" })).toMatchObject({ status: 400 });+ expect(await api("PUT", "/api/groups/order", { groupIds: [first.id], extra: true })).toMatchObject({ status: 400 });+ expect(await api("PUT", "/api/groups/order", { groupIds: [first.id, "room-nope"] })).toMatchObject({ status: 400, body: { error: "unknown room: room-nope" } });+ expect(await listed()).toEqual([wanted[2], wanted[1], wanted[0]]);+ } finally {+ for (const group of [first, second, third]) await api("DELETE", `/api/groups/${group.id}`);+ await api("DELETE", `/api/bots/${bot.id}`);+ }+ });+it("words a new bot's refused department access by key, keeping its English", async () => {expect(await api("POST", "/api/bots", { settings: { managedSections: ["Nowhere"] } })).toEqual({ status: 400,body: { error: "Only a Chief may manage existing additional departments", errorKey: "serverError.department.chiefOnlyExtra" } });diff --git a/server/index.ts b/server/index.tsindex 1fc7c3e634..b6f1a2ccce 100644--- a/server/index.ts+++ b/server/index.ts@@ -591,6 +591,7 @@ import { createTeamOwnerRoutes } from "./routes/team-owners.ts";import { createBotSettingsRoutes } from "./routes/bot-settings.ts";import { createBotPatchRoutes } from "./routes/bot-patch.ts";import { createBotOrderRoutes } from "./routes/bot-order.ts";+import { createGroupOrderRoutes } from "./routes/group-order.ts";import { createBotLifecycleRoutes } from "./routes/bot-lifecycle.ts";import { createBotSkillsRoutes } from "./routes/bot-skills.ts";import { createSkillShareRoutes } from "./routes/skill-share.ts";@@ -4543,9 +4544,8 @@ store.onChange((change) => {if (bot) for (const group of store.groups.filter((candidate) => candidate.memberIds.includes(bot.id))) settleRoomFloor(group);break;}- case "bots.order":- broadcast({ kind: "bots.order", botIds: store.bots.map((bot) => bot.id) });- break;+ case "bots.order": broadcast({ kind: "bots.order", botIds: store.bots.map((bot) => bot.id) }); break;+ case "groups.order": broadcast({ kind: "groups.order", groupIds: store.groups.map((group) => group.id) }); break;case "bot.deleted":sentThreads.delete(change.botId);try { commandAllowlist.clear(change.botId); mcpServersHost.botDeleted(change.botId); logins.forgetBot(change.botId); }@@ -12147,7 +12147,7 @@ ROUTES.push(createBotSettingsRoutes({requestedTaskBot, threadBusy, activeGroupTurnForBot, checkedModelSelection, engineSwitchNeedsAsk, readCursor,canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread,}));-ROUTES.push(createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);+ROUTES.push(createGroupOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)) }), createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);ROUTES.push(createBotPatchRoutes({store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,routines: () => routines, activeVpsThreads,diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 63fce1c056..fd96910081 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -165,7 +165,7 @@ describe("scopes", () => {["POST", "/api/webhooks"], ["POST", "/api/webhooks/w/rotate"], ["POST", "/api/bots/x/skills"], ["PATCH", "/api/bots/x/skills/s"],["PATCH", "/api/bots/x/model"], ["PATCH", "/api/groups/g/setup"], ["POST", "/api/teams/import"], ["GET", "/api/teams/scout"],["POST", "/api/team-library/github"], ["GET", "/api/setup-import/grok"],- ["GET", "/api/bots/x/memory"], ["PUT", "/api/bots/x/memory"], ["PUT", "/api/section-context"], ["GET", "/api/threads/t/events"],+ ["GET", "/api/bots/x/memory"], ["PUT", "/api/bots/x/memory"], ["PUT", "/api/section-context"], ["PUT", "/api/groups/order"], ["GET", "/api/threads/t/events"],["GET", "/api/mcp/servers"], ["POST", "/api/mcp/servers"], ["GET", "/api/bots/x/mcp-servers"], ["POST", "/api/connectors/slack/authorize"],["POST", "/api/bots/x/slack-management"], ["GET", "/api/bots/x/slack-management/extra"],["PUT", "/api/config"], ["POST", "/api/auth/pairing"], ["GET", "/api/auth/sessions"], ["DELETE", "/api/auth/sessions/abc"],diff --git a/server/routes/group-order.ts b/server/routes/group-order.tsnew file mode 100644index 0000000000..03d231e122--- /dev/null+++ b/server/routes/group-order.ts@@ -0,0 +1,35 @@+import type { VisibleSet } from "../bot-visibility.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { Store } from "../store.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface GroupOrderRouteDeps {+ store: Pick<Store, "group" | "groups" | "reorderGroups">;+ /** The same filter the room listing applies to this caller. */+ visibleFor(auth: RequestAuth): VisibleSet;+}++const INVALID = "groupIds must be a non-empty array of distinct room ids";++/** The order rooms are listed in the sidebar, the same on every client. A reorder names only the rooms it moves+ * (shared/bot-order.ts): they take the places they already hold together, and every other room keeps its place. */+export function createGroupOrderRoutes(deps: GroupOrderRouteDeps): RouteHandler {+ const { store, visibleFor } = deps;+ return async ({ req, res, path, method, auth, json, readBody }) => {+ if (path !== "/api/groups/order" || method !== "PUT") return PASS;+ const body = await readBody(req);+ const groupIds: unknown = body && typeof body === "object" && !Array.isArray(body) && Object.keys(body).every((key) => key === "groupIds")+ ? (body as { groupIds?: unknown }).groupIds : undefined;+ if (!Array.isArray(groupIds) || !groupIds.length || groupIds.some((id) => typeof id !== "string" || !id) || new Set(groupIds).size !== groupIds.length) {+ return json(res, 400, { error: INVALID });+ }+ // A hidden room gets the same answer as a missing one, so the id list cannot probe the workspace.+ const visible = visibleFor(auth);+ for (const id of groupIds as string[]) {+ if (!store.group(id) || !visible.group(id)) return json(res, 400, { error: `unknown room: ${id}` });+ }+ const groups = store.reorderGroups(groupIds as string[]);+ if (!groups) return json(res, 400, { error: INVALID });+ return json(res, 200, { groupIds: groups.filter((group) => visible.group(group.id)).map((group) => group.id) });+ };+}diff --git a/server/store.ts b/server/store.tsindex 478ee93708..8a82668901 100644--- a/server/store.ts+++ b/server/store.ts@@ -4,7 +4,7 @@ import { join } from "node:path"; import { isDeepStrictEqual } from "node:util";import { OwnedFile, writeFileAtomic } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts"; import { discardNativeLog } from "./drivers/native.ts";import { commitRegistryChange, keptRevocation, saveRegistryFor, touchesPermissions } from "./registry-save.ts";import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts"; import { dropRetiredApps } from "./retired-apps.ts";-import { reorderStable } from "../shared/bot-order.ts"; import { trimOutboundPolicy } from "../shared/outbound.ts";+import { reorderInPlace } from "../shared/bot-order.ts"; import { trimOutboundPolicy } from "../shared/outbound.ts";import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts"; import { reshowWhenMoved } from "../shared/default-bot.ts";import { ensureSections, readSections, changeEmptySection } from "./section-context.ts";import type { TeamComputers } from "./team-computers.ts";@@ -132,8 +132,8 @@ export type StoreChange =| { type: "thread.deleted"; threadId: string }| { type: "bot"; botId: string }| { type: "bot.deleted"; botId: string }- /** The fleet was reordered as a whole; the broadcast carries every id in its new place. */- | { type: "bots.order" }+ /** The fleet or the rooms were reordered as a whole; the broadcast carries every id in its new place. */+ | { type: "bots.order" } | { type: "groups.order" }| { type: "group"; groupId: string }| { type: "group.deleted"; groupId: string };@@ -1969,20 +1969,20 @@ export class Store {return bot.projects;}- /** A stable partial reorder of the fleet (shared/bot-order.ts): the listed bots take, in the order given, the positions+ /** A stable partial reorder of the fleet, or with reorderGroups of the rooms (shared/bot-order.ts): the listed bots take, in the order given, the positions* they already share; every other bot stays put. Empty, repeated or unknown ids change nothing and give null. */reorderBots(botIds: string[]): BotRecord[] | null {- if (!botIds.length || new Set(botIds).size !== botIds.length) return null;- const byId = new Map(this.bots.map((bot) => [bot.id, bot]));- if (botIds.some((id) => !byId.has(id))) return null;- const next = reorderStable(this.bots, botIds);- // Mutate in place: schedulers and other consumers hold this array and its records.- this.bots.splice(0, this.bots.length, ...next);+ if (!reorderInPlace(this.bots, botIds)) return null;this.saveBots();this.emit({ type: "bots.order" });return this.bots;}+ 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;+ }+deleteProject(botId: string, projectId: string): BotRecord | null {const bot = this.bot(botId);if (!bot || !this.project(botId, projectId)) return null;diff --git a/shared/bot-order.test.ts b/shared/bot-order.test.tsindex 0601b2d646..1a040880c1 100644--- a/shared/bot-order.test.ts+++ b/shared/bot-order.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { reorderStable } from "./bot-order.ts";+import { reorderIfMoved, reorderInPlace, reorderStable } from "./bot-order.ts";const items = (...ids: string[]) => ids.map((id) => ({ id }));const ids = (list: ReadonlyArray<{ id: string }>) => list.map((item) => item.id);@@ -31,3 +31,31 @@ describe("reorderStable", () => {expect(ids(reorderStable(items("a", "b"), ["a", "b"]))).toEqual(["a", "b"]);});});++describe("reorderInPlace", () => {+ it("reorders the same array, keeping its records", () => {+ const list = items("a", "b", "c");+ const [a, , c] = list;+ expect(reorderInPlace(list, ["c", "a"])).toBe(true);+ expect(ids(list)).toEqual(["c", "b", "a"]);+ expect(list[0]).toBe(c);+ expect(list[2]).toBe(a);+ });++ it("refuses an empty list, a repeated id or one it does not have, and leaves the array alone", () => {+ const list = items("a", "b");+ expect(reorderInPlace(list, [])).toBe(false);+ expect(reorderInPlace(list, ["b", "b"])).toBe(false);+ expect(reorderInPlace(list, ["b", "ghost"])).toBe(false);+ expect(ids(list)).toEqual(["a", "b"]);+ });+});++describe("reorderIfMoved", () => {+ it("gives the new order, or null when nothing moved", () => {+ const list = items("a", "b", "c");+ expect(ids(reorderIfMoved(list, ["c", "a"])!)).toEqual(["c", "b", "a"]);+ expect(reorderIfMoved(list, ["a", "c"])).toBeNull();+ expect(reorderIfMoved(list, ["ghost"])).toBeNull();+ });+});diff --git a/shared/bot-order.ts b/shared/bot-order.tsindex a924285b1c..7a5364e904 100644--- a/shared/bot-order.ts+++ b/shared/bot-order.ts@@ -10,3 +10,19 @@ export function reorderStable<T extends { id: string }>(items: readonly T[], idsslots.forEach((slot, index) => { out[slot] = moved[index]!; });return out;}++/** Reorders `items` itself the same way (the server's schedulers and other readers hold the array and its records).+ * False, and nothing changes, for an empty list, a repeated id or an id it does not have. */+export function reorderInPlace<T extends { id: string }>(items: T[], ids: readonly string[]): boolean {+ if (!ids.length || new Set(ids).size !== ids.length) return false;+ const known = new Set(items.map((item) => item.id));+ if (ids.some((id) => !known.has(id))) return false;+ items.splice(0, items.length, ...reorderStable(items, ids));+ return true;+}++/** The reordered list, or null when no item moved (a client then keeps its state as it is). */+export function reorderIfMoved<T extends { id: string }>(items: readonly T[], ids: readonly string[]): T[] | null {+ const next = reorderStable(items, ids);+ return next.some((item, index) => item !== items[index]) ? next : null;+}diff --git a/shared/wire.ts b/shared/wire.tsindex bc741e3934..3ccba62992 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -989,8 +989,8 @@ export type ServerFrame =/** A bot's data sheet changed. Whole sheet each time. */| DataBroadcast| { kind: "bot.deleted"; botId: string }- /** The whole fleet in its new order (PUT /api/bots/order); a member is sent only the bots they see. */- | { kind: "bots.order"; botIds: string[] }+ /** The whole fleet (PUT /api/bots/order) or every room (PUT /api/groups/order) in its new order; a member is sent only the ones they see. */+ | { kind: "bots.order"; botIds: string[] } | { kind: "groups.order"; groupIds: string[] }| { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }/** A job is waiting for the phone whose registry key this is; it polls now. */| { kind: "device.job"; phone: string; id: string }diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 5d6f964ea1..24d7aff825 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -62,6 +62,7 @@ import {} from "@/lib/sidebar-layout";import { stepKey, type BotDropPlace } from "@/lib/sidebar-bot-drop";import { BotDropLine, botRowDropClass, useSidebarBotDrag, type BotRowDrag } from "./SidebarBotDrag";+import { useSidebarRoomDrag } from "./SidebarRoomDrag";import { useSidebarSections } from "./SidebarSections";import { departmentNames, moveBotsToSection } from "./bot-sections";import { sidebarSectionAttention } from "@/lib/sidebar-attention";@@ -1085,7 +1086,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const q = query.trim().toLowerCase();const sections = useSidebarSections({ simple, rail, density, query: q, label: sectionLabel, sidebarRef });const botDrag = useSidebarBotDrag({ dispatch, announce: sections.announce, onNamed: sections.focusHeader, onRenamed: sections.renamed,- onError: (text) => setTeamFeedback({ error: true, text }), onCancelled: () => sidebarRef.current?.focus() });+ onError: (text) => setTeamFeedback({ error: true, text }), onCancelled: () => sidebarRef.current?.focus() }), roomDrag = useSidebarRoomDrag({ dispatch, announce: sections.announce, enabled: (sections.interactive || density === "icons") && !phone && !q, groups: state.groups });const sideLists = useTeamSideLists(state), matchingBots = sideLists.bots.filter((b) => !b.hidden)@@ -1392,14 +1393,13 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const sectionChiefItems = sectionName? sectionChiefs.filter((bot) => bot.section === sectionName): [];- const sectionGroupItems =- id === CHANNELS_SECTION_ID+ const sectionGroupItems = roomDrag.list(id === CHANNELS_SECTION_ID? unsectionedRooms: id === BOT_CHATS_SECTION_ID? botChats: sectionName? sectionedRooms.filter((group) => group.section === sectionName)- : [];+ : []);const sectionBotItems =id === PINNED_SECTION_ID? pinnedBots@@ -1459,7 +1459,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =<>{id === BOTS_SECTION_ID && drops.slot}{sectionChiefItems.map((bot) => <BotListItem key={bot.id} {...botRow(bot)} />)}- {sectionGroupItems.map((group) => (+ {sectionGroupItems.map((group) => roomDrag.wrap(group.id, (<GroupListItemkey={group.id}group={group}@@ -1467,7 +1467,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =query={q}onMenu={setRoomMenu}/>- ))}+ )))}{id === PINNED_SECTION_ID ? (<PinnedBotRosterbots={sectionBotItems}diff --git a/src/components/SidebarRoomDrag.tsx b/src/components/SidebarRoomDrag.tsxnew file mode 100644index 0000000000..ba6aac751a--- /dev/null+++ b/src/components/SidebarRoomDrag.tsx@@ -0,0 +1,142 @@+import { useRef, useState, type Dispatch, type DragEvent, type KeyboardEvent, type PointerEvent, type ReactElement } from "react";+import { cn } from "@/lib/cn";+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 { useMayMoveBots } from "./bot-sections";+import { BotDropLine, botRowDropClass } from "./SidebarBotDrag";++const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));++/** 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;+ 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) });+ });+}++type RowHandlers = {+ draggable: true;+ onPointerDown: (event: PointerEvent<HTMLElement>) => void;+ onDragStart: (event: DragEvent<HTMLElement>) => void;+ onDragEnd: () => void;+ onDragOver: (event: DragEvent<HTMLElement>) => void;+ onDrop: (event: DragEvent<HTMLElement>) => void;+ onKeyDown: (event: KeyboardEvent<HTMLElement>) => void;+};++/** True when the event comes from this room's own row button, not its thread list or another control. */+const onRoomRow = (target: EventTarget, groupId: string) =>+ target instanceof Element && target.closest("[data-sidebar-group-row]")?.getAttribute("data-sidebar-group-row") === groupId;++/** Dragging a room up or down inside the sidebar list it is in (a department, Rooms, Bot chats), and Alt+Up/Down on+ * its row. Owners and admins only, and not while a search hides some rooms. Call it once per draw, before `list`+ * names the rooms each list shows (in order) and `wrap` puts each room's row in its drop target. */+export function useSidebarRoomDrag({ dispatch, announce, enabled, groups }: {+ dispatch: Dispatch<Action>;+ announce: (text: string) => void;+ enabled: boolean;+ groups: Group[];+}) {+ const mayMove = useMayMoveBots();+ const [dragging, setDragging] = useState<string | null>(null);+ const [drop, setDrop] = useState<{ groupId: string; place: RoomDropPlace } | null>(null);+ const latest = useRef<{ enabled: boolean; lists: string[][]; groups: Group[] }>({ enabled: false, lists: [], groups: [] });+ latest.current = { enabled: enabled && mayMove, lists: [], groups };+ const actions = useRef({ dispatch, announce });+ actions.current = { dispatch, announce };+ const controller = useRef<{ row(groupId: string): RowHandlers; listOf(groupId: string): string[] | undefined } | null>(null);++ if (!controller.current) {+ const rows = new Map<string, RowHandlers>();+ const moving = { from: null as string | null, grabbed: null as string | null };+ const listOf = (groupId: string) => latest.current.lists.find((ids) => ids.includes(groupId));+ const end = () => {+ moving.from = null;+ setDragging(null);+ setDrop(null);+ };+ const apply = (groupId: string, order: string[] | null, keyboard: boolean) => {+ if (!order || !latest.current.enabled) return;+ saveRoomOrder(actions.current.dispatch, latest.current.groups, order);+ if (!keyboard) return;+ const name = latest.current.groups.find((group) => group.id === groupId)?.name ?? "";+ actions.current.announce(t("sidebar.section.moved", { name, position: order.indexOf(groupId) + 1, count: order.length }));+ requestAnimationFrame(() => document.querySelector<HTMLElement>(`[data-sidebar-group-row="${CSS.escape(groupId)}"]`)?.focus());+ };+ // Only a room from the same list may land on a row; any other drag (a bot, a thread, a file) is left alone.+ const placeOver = (event: DragEvent<HTMLElement>, groupId: string): RoomDropPlace | null => {+ const from = moving.from;+ if (!from || !event.dataTransfer.types.includes(ROOM_ROW_DRAG_TYPE) || !listOf(groupId)?.includes(from)) return null;+ const box = event.currentTarget.getBoundingClientRect();+ return roomDropPlace(event.clientY - box.top, box.height);+ };+ const row = (groupId: string): RowHandlers => ({+ draggable: true,+ onPointerDown: (event) => { moving.grabbed = onRoomRow(event.target, groupId) ? groupId : null; },+ onDragStart: (event) => {+ if (event.target !== event.currentTarget) return; // a thread row or an image inside drags itself+ // The room moves only when it is picked up by its own row, not by its open thread list.+ if (!latest.current.enabled || moving.grabbed !== groupId || !listOf(groupId)) return event.preventDefault();+ event.stopPropagation();+ event.dataTransfer.effectAllowed = "move";+ event.dataTransfer.setData(ROOM_ROW_DRAG_TYPE, groupId);+ moving.from = groupId;+ setDragging(groupId);+ },+ onDragEnd: end,+ onDragOver: (event) => {+ const place = placeOver(event, groupId);+ if (!place) return;+ event.preventDefault();+ event.stopPropagation();+ event.dataTransfer.dropEffect = "move";+ setDrop((shown) => (shown?.groupId === groupId && shown.place === place ? shown : { groupId, place }));+ },+ onDrop: (event) => {+ const place = placeOver(event, groupId), from = moving.from, list = listOf(groupId);+ if (!place || !from || !list) return;+ event.preventDefault();+ event.stopPropagation();+ end();+ apply(from, planRoomDrop(list, from, groupId, place), false);+ },+ onKeyDown: (event) => {+ const step = stepKey(event), list = listOf(groupId);+ if (!step || !list || !onRoomRow(event.target, groupId)) return;+ event.preventDefault();+ apply(groupId, stepRoom(list, groupId, step), true);+ },+ });+ controller.current = {+ row: (groupId) => rows.get(groupId) ?? rows.set(groupId, row(groupId)).get(groupId)!,+ listOf,+ };+ }+ const { row, listOf } = controller.current;++ return {+ /** Names the rooms one list shows, in the order shown; returns them unchanged. */+ list<T extends Pick<Group, "id">>(items: T[]): T[] {+ 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. */+ wrap(groupId: string, item: ReactElement): ReactElement {+ if (!latest.current.enabled || !listOf(groupId)) return item;+ const place = drop?.groupId === groupId ? drop.place : null;+ return (+ <div key={groupId} className={cn("relative flex flex-col [gap:inherit]", botRowDropClass(place, dragging === groupId))} {...row(groupId)}>+ <BotDropLine place={place} />+ {item}+ </div>+ );+ },+ };+}diff --git a/src/lib/sidebar-room-drop.test.ts b/src/lib/sidebar-room-drop.test.tsnew file mode 100644index 0000000000..a1411875a1--- /dev/null+++ b/src/lib/sidebar-room-drop.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { planRoomDrop, roomDropPlace, stepRoom } from "./sidebar-room-drop";++const rooms = ["a", "b", "c", "d"];++describe("room drops", () => {+ it("lands in the upper or lower half of the row under the pointer", () => {+ expect(roomDropPlace(4, 40)).toBe("before");+ expect(roomDropPlace(20, 40)).toBe("after");+ expect(roomDropPlace(4, 0)).toBe("before");+ });++ it("moves a room before or after another in the same list", () => {+ expect(planRoomDrop(rooms, "d", "a", "before")).toEqual(["d", "a", "b", "c"]);+ expect(planRoomDrop(rooms, "a", "c", "after")).toEqual(["b", "c", "a", "d"]);+ expect(planRoomDrop(rooms, "a", "d", "after")).toEqual(["b", "c", "d", "a"]);+ });++ it("does nothing for a drop that changes nothing or leaves the list", () => {+ expect(planRoomDrop(rooms, "a", "a", "before")).toBeNull();+ expect(planRoomDrop(rooms, "a", "b", "before")).toBeNull();+ expect(planRoomDrop(rooms, "b", "a", "after")).toBeNull();+ expect(planRoomDrop(rooms, "x", "a", "before")).toBeNull();+ expect(planRoomDrop(rooms, "a", "x", "before")).toBeNull();+ });++ it("steps a room one place up or down, stopping at either end", () => {+ expect(stepRoom(rooms, "b", -1)).toEqual(["b", "a", "c", "d"]);+ expect(stepRoom(rooms, "b", 1)).toEqual(["a", "c", "b", "d"]);+ expect(stepRoom(rooms, "a", -1)).toBeNull();+ expect(stepRoom(rooms, "d", 1)).toBeNull();+ expect(stepRoom(rooms, "x", 1)).toBeNull();+ });+});diff --git a/src/lib/sidebar-room-drop.ts b/src/lib/sidebar-room-drop.tsnew file mode 100644index 0000000000..242266a276--- /dev/null+++ b/src/lib/sidebar-room-drop.ts@@ -0,0 +1,28 @@+export const ROOM_ROW_DRAG_TYPE = "application/x-openmausbot-sidebar-room";++/** Where a dragged room lands against the room row under the pointer. */+export type RoomDropPlace = "before" | "after";++export function roomDropPlace(offset: number, height: number): RoomDropPlace {+ return height > 0 && offset / height >= 0.5 ? "after" : "before";+}++const same = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((id, index) => id === b[index]);++/** `list` (the rooms one sidebar list shows, in order) with `roomId` dropped before or after `targetId`; null when+ * either is not in the list or nothing would move. A room only moves inside the list it is in. */+export function planRoomDrop(list: readonly string[], roomId: string, targetId: string, place: RoomDropPlace): string[] | null {+ if (roomId === targetId || !list.includes(roomId) || !list.includes(targetId)) return null;+ const rest = list.filter((id) => id !== roomId);+ const at = rest.indexOf(targetId) + (place === "after" ? 1 : 0);+ const next = [...rest.slice(0, at), roomId, ...rest.slice(at)];+ return same(next, list) ? null : next;+}++/** `list` with `roomId` moved one place up (-1) or down (1); null at either end. */+export function stepRoom(list: readonly string[], roomId: string, direction: -1 | 1): string[] | null {+ const index = list.indexOf(roomId);+ const target = index < 0 ? undefined : list[index + direction];+ if (target === undefined) return null;+ return planRoomDrop(list, roomId, target, direction === -1 ? "before" : "after");+}diff --git a/src/state/store.test.ts b/src/state/store.test.tsindex ec2cd5b576..cfb43a603b 100644--- a/src/state/store.test.ts+++ b/src/state/store.test.ts@@ -3256,6 +3256,24 @@ describe("a routine's answer and its broadcast", () => {});});+describe("room order from the server", () => {+ const room = (id: string): Group => ({ id, threadId: `${id}-thread`, name: id, memberIds: [], createdAt: 1, messages: [] } as unknown as Group);+ const hydrated = reducer(initialState, { type: "hydrate", bots: [], groups: [room("a"), room("b"), room("c")], computerControl: {} });+ const ids = (state: AppState) => state.groups.map((candidate) => candidate.id);++ it("applies a groups.order frame as a stable partial reorder", () => {+ expect(ids(reducer(hydrated, { type: "groupsOrdered", groupIds: ["c", "b", "a"] }))).toEqual(["c", "b", "a"]);+ const partial = reducer(hydrated, { type: "groupsOrdered", groupIds: ["c", "a"] });+ expect(ids(partial)).toEqual(["c", "b", "a"]);+ expect(partial.groups[0]).toBe(hydrated.groups[2]);+ });++ it("ignores ids it does not know and leaves an unchanged order alone", () => {+ expect(ids(reducer(hydrated, { type: "groupsOrdered", groupIds: ["ghost", "b", "a"] }))).toEqual(["b", "a", "c"]);+ expect(reducer(hydrated, { type: "groupsOrdered", groupIds: ["a", "b", "c"] })).toBe(hydrated);+ });+});+describe("fleet order from the server", () => {const bot = (id: string): Bot => ({id,diff --git a/src/state/store.tsx b/src/state/store.tsxindex f1f4ab7af2..170f816fc4 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -5,7 +5,7 @@ import { createAppStore } from "./app-store"; import { readOneBot } from "./bot-import { flushSync } from "react-dom";import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, ResolvedSender, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";import { movesThreadToTop } from "../../shared/wire"; import type { DefaultBotFields } from "../../shared/default-bot";-import { reorderStable } from "../../shared/bot-order";+import { reorderIfMoved } from "../../shared/bot-order";import { withOneChief } from "../../shared/bot-owner";import { DATA_ROUTES, type DataSheet, type DataTable } from "../../shared/data-surface";import type { NotificationLogEntry } from "../../shared/notification";@@ -621,7 +621,7 @@ export type Action =}| { type: "botQueues"; queues: AppState["pendingQueued"] }| { type: "sections"; sections: string[] }- | { type: "botsOrdered"; botIds: string[] }+ | { type: "botsOrdered"; botIds: string[] } | { type: "groupsOrdered"; groupIds: string[] }| { type: "sectionDeleted"; section: string; sections: string[] }| { type: "showRoutines"; section?: "schedule" | "logs"; view?: "calendar" | "list"; botId?: string; routineId?: string; runStatus?: RoutineRunStatusFilter }| { type: "showTeamMap" } | { type: "showPublishedApps" } | { type: "showWebPanel"; id: string }@@ -947,11 +947,9 @@ export function reducer(state: AppState, action: Action): AppState {};case "sections":return { ...state, sections: action.sections };- case "botsOrdered": {- // The server's fleet order (PUT /api/bots/order): a stable partial reorder, so the sidebar shows what a phone just did.- const bots = reorderStable(state.bots, action.botIds);- return bots.every((bot, index) => bot === state.bots[index]) ? state : { ...state, bots };- }+ // The server's fleet or room order (PUT /api/bots/order, /api/groups/order): a stable partial reorder, so the sidebar shows what a phone just did.+ case "botsOrdered": { const bots = reorderIfMoved(state.bots, action.botIds); return bots ? { ...state, bots } : state; }+ case "groupsOrdered": { const groups = reorderIfMoved(state.groups, action.groupIds); return groups ? { ...state, groups } : state; }case "botQueues":return reconcileSnapshotQueues(replaceBotQueues(state, action.queues), [...state.bots, ...state.groups]);case "showRoutines":@@ -3104,6 +3102,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {case "bots.order":rawDispatch({ type: "botsOrdered", botIds: frame.botIds });break;+ case "groups.order": rawDispatch({ type: "groupsOrdered", groupIds: frame.groupIds }); break;case "bot.queued":rawDispatch({ type: "botQueues", queues: frame.queues });break;