Skip to content

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

feat(sidebar): keep one department order on the server, shown by every client

Bugfixer 213a7a61beec9
diff --git a/companion/src/routes.ts b/companion/src/routes.ts
index 46a6ce67ec..da3a6a2c49 100644
--- a/companion/src/routes.ts
+++ b/companion/src/routes.ts
@@ -107,6 +107,8 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [
{ method: "PUT", path: /^\/api\/bots\/order$/ },
// Can only file visible bots; cannot alter execution policy.
{ method: "POST", path: /^\/api\/sidebar-sections$/ },
+ // Display order only; the harness accepts just the departments the device can see.
+ { method: "PUT", path: /^\/api\/sidebar-sections\/order$/ },
{ method: "POST", path: /^\/api\/bots\/[\w-]+\/messages$/ },
{ method: "PATCH", path: /^\/api\/bots\/[\w-]+\/cards\/[\w-]+$/ },
{ method: "POST", path: /^\/api\/bots\/[\w-]+\/respond$/ },
diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.ts
index 281f7c423e..a9ce7ce4bf 100644
--- a/companion/test/routes.test.ts
+++ b/companion/test/routes.test.ts
@@ -50,6 +50,7 @@ describe("what the app may do", () => {
["DELETE", "/api/bots/bot_123"],
["PUT", "/api/bots/order"],
["POST", "/api/sidebar-sections"],
+ ["PUT", "/api/sidebar-sections/order"],
["POST", "/api/bots/bot_123/messages"],
["PATCH", "/api/bots/bot_123/cards/msg_2"],
["POST", "/api/bots/bot_123/respond"],
diff --git a/server/index.test.ts b/server/index.test.ts
index 7648df1e02..a01a1d17f2 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -5021,6 +5021,43 @@ describe("harness HTTP API", () => {
}
});
+ it("stores the department order: a partial, stable reorder every client reads back and is sent live", async () => {
+ const made = ["Order fixture A", "Order fixture B", "Order fixture C"];
+ const mine = (names: string[]) => names.filter((name) => made.includes(name));
+ const listed = async () => mine((await api("GET", "/api/sidebar-sections")).body.sections);
+ try {
+ for (const name of made) expect((await api("POST", "/api/sidebar-sections", { name, botIds: [] })).status).toBe(200);
+ expect(await listed()).toEqual(made);
+
+ const stream = await openSse(`${BASE}/api/events`);
+ try {
+ await stream.until((frame) => frame.kind === "hello");
+ const moved = await api("PUT", "/api/sidebar-sections/order", { sections: ["Order fixture C", "Order fixture A"] });
+ expect(moved.status).toBe(200);
+ expect(mine(moved.body.sections)).toEqual(["Order fixture C", "Order fixture B", "Order fixture A"]);
+ const frame = await stream.until((candidate) => candidate.kind === "sections" && mine(candidate.sections ?? [])[0] === "Order fixture C");
+ expect(frame.sections).toEqual(moved.body.sections);
+ } finally {
+ stream.close();
+ }
+ expect(await listed()).toEqual(["Order fixture C", "Order fixture B", "Order fixture A"]);
+ // A late device's first offer of its old order does not undo the order someone set.
+ const offered = await api("PUT", "/api/sidebar-sections/order", { sections: ["Order fixture A", "Order fixture C"], first: true });
+ expect(offered.status).toBe(200);
+ expect(mine(offered.body.sections)).toEqual(["Order fixture C", "Order fixture B", "Order fixture A"]);
+
+ const invalid = { status: 400, body: { error: "sections must be a non-empty array of distinct department names" } };
+ expect(await api("PUT", "/api/sidebar-sections/order", { sections: ["Order fixture A", "Order fixture A"] })).toMatchObject(invalid);
+ expect(await api("PUT", "/api/sidebar-sections/order", { sections: [] })).toMatchObject(invalid);
+ expect(await api("PUT", "/api/sidebar-sections/order", { sections: ["Order fixture A"], extra: true })).toMatchObject(invalid);
+ expect(await api("PUT", "/api/sidebar-sections/order", { sections: ["Order fixture A", "Nowhere"] }))
+ .toMatchObject({ status: 400, body: { error: "unknown department: Nowhere" } });
+ expect(await listed()).toEqual(["Order fixture C", "Order fixture B", "Order fixture A"]);
+ } finally {
+ for (const name of made) await api("DELETE", `/api/sidebar-sections?section=${encodeURIComponent(name)}`);
+ }
+ });
+
it("rejects a sidebar section Chief collision without changing any bot", async () => {
const incumbent = (await api("POST", "/api/bots")).body.bot;
const incoming = (await api("POST", "/api/bots")).body.bot;
diff --git a/server/index.ts b/server/index.ts
index 6062126e74..7531c8e88a 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12038,7 +12038,7 @@ ROUTES.push(createBotMemoryRoutes({
}));
const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : desktopMainMover(auth, { desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) ? thisComputerOwner(cfg.profile?.name) : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)), computer: !CLOUD_HOME, mcp: (id) => mcpServersHere(cfg, id), arrivals: arrivalsFile(DATA_DIR), stays: (id) => staysOnCloud(store.bot(id), { logins: logins.changes().length, secrets: logins.listSecrets(TEAM_READER).length, onePassword: logins.onePasswordConnectedAt() !== null, mcpServers: Object.keys(cfg.mcpServers ?? {}) }), lapseCheckMs: 15_000, log: (line) => console.error(line) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: personLanguages.forPlace, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, changes: { bots: () => store.bots, instances: () => cfg.instances ?? {}, mcpServers: () => cfg.mcpServers, skills: (bot) => listSkills(bot.id).map((skill) => ({ name: skill.name, enabled: skill.enabled, text: readSkillFile(bot.id, skill.name) })) }, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
-const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId, typing) => { if (!store.botByThread(threadId)) return; if (typing) enginePrestart.typedIn(threadId); sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
+const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, visibleFor: (auth) => visibleTo(viewerFor(auth)), renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId, typing) => { if (!store.botByThread(threadId)) return; if (typing) enginePrestart.typedIn(threadId); sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); const githubSignInCards = createGithubSignInCards({ store, signIn: githubSignIn, team: Boolean(CLOUD_TEAM), turnPerson: (threadId, generation) => teamConnections.turnPerson(threadId, generation), language: threadLanguage, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), resume: (threadId, resumeKey) => void maybeResumeConnectors(threadId, resumeKey), release: (threadId, messageId) => releaseCardNode(threadId, messageId, "The connection request was dismissed") }); provideGithubSignInCards(githubSignInCards); ROUTES.push(createGitCredentialRoutes({ port: PORT, enabled: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !CLOUD_TEAM && !botBox.enabled() }));
ROUTES.push(createRoomHoldRoutes({
diff --git a/server/routes/sidebar-sections.ts b/server/routes/sidebar-sections.ts
index c8e60ec930..050f302627 100644
--- a/server/routes/sidebar-sections.ts
+++ b/server/routes/sidebar-sections.ts
@@ -1,6 +1,8 @@
import { z } from "zod";
import type { WireBot } from "../../shared/wire.ts";
+import type { VisibleSet } from "../bot-visibility.ts";
+import type { RequestAuth } from "../request-auth.ts";
import type { BotRecord, Store } from "../store.ts";
import type { TeamComputers } from "../team-computers.ts";
import { USER_ERROR, userError, type UserErrorKey } from "../user-errors.ts";
@@ -9,6 +11,8 @@ import { PASS, type RouteHandler } from "./table.ts";
const STORE_REFUSALS: readonly UserErrorKey[] = ["serverError.department.notFound", "serverError.department.nameRule",
"serverError.department.duplicate", "serverError.department.renameBusy", "serverError.department.emptyFirst", "serverError.department.deleteBusy", "serverError.department.generalChief"];
+const ORDER_INVALID = "sections must be a non-empty array of distinct department names";
+
export function storeRefusal(error: string): { error: string; errorKey?: UserErrorKey } {
const key = STORE_REFUSALS.find((candidate) => USER_ERROR[candidate] === error);
return key ? userError(key) : { error };
@@ -20,6 +24,8 @@ export interface SidebarSectionRouteDeps {
maxBots: number;
assertTeamComputerChangeIdle(before: BotRecord, after: BotRecord): void;
wireBot(bot: BotRecord): WireBot;
+ /** The same filter the live department list (the `sections` frame) applies to this caller. */
+ visibleFor(auth: RequestAuth): Pick<VisibleSet, "sections">;
/** A department was renamed (`to`) or deleted (null): what is kept about it by name follows. */
renamed?(from: string, to: string | null): void;
}
@@ -32,10 +38,25 @@ export function createSidebarSectionRoutes(deps: SidebarSectionRouteDeps): Route
botIds: z.array(z.string().regex(/^[\w-]+$/)).max(MAX_WORKSPACE_BOTS).default([]),
}).strict();
- return async ({ req, res, url, path, method, json, readBody }) => {
+ return async ({ req, res, url, path, method, auth, json, readBody }) => {
if (path === "/api/sidebar-sections" && method === "GET") {
return json(res, 200, { sections: store.sections });
}
+ // The department order is one list every client shows (the desktop sidebar, a phone). A reorder names only the
+ // departments it moves; the rest keep their places. `first` is a device offering the order it showed before the
+ // order was shared: it applies only while nobody has set one.
+ if (path === "/api/sidebar-sections/order" && method === "PUT") {
+ const parsed = z.object({ sections: z.array(z.string().min(1)).min(1), first: z.boolean().optional() }).strict().safeParse(await readBody(req));
+ if (!parsed.success || new Set(parsed.data.sections).size !== parsed.data.sections.length) return json(res, 400, { error: ORDER_INVALID });
+ // A hidden department gets the same answer as a missing one, so the list cannot probe the workspace.
+ const visible = deps.visibleFor(auth);
+ const shown = new Set(visible.sections(store.sections));
+ const unknown = parsed.data.sections.find((name) => !shown.has(name));
+ if (unknown !== undefined) return json(res, 400, { error: `unknown department: ${unknown}` });
+ const sections = store.reorderSections(parsed.data.sections, parsed.data.first);
+ if (!sections) return json(res, 400, { error: ORDER_INVALID });
+ return json(res, 200, { sections: visible.sections(sections) });
+ }
if (path === "/api/sidebar-sections" && (method === "PATCH" || method === "DELETE")) {
const section = url.searchParams.get("section")?.trim();
if (!section) return json(res, 400, { error: "Choose a named department" });
diff --git a/server/section-context.test.ts b/server/section-context.test.ts
index 72861f0727..2e427bb3b1 100644
--- a/server/section-context.test.ts
+++ b/server/section-context.test.ts
@@ -6,6 +6,7 @@ import {
readSections,
ensureSections,
changeEmptySection,
+ reorderSectionNames,
sectionContextKey,
sectionContextLabel,
sectionContextSystemPrompt,
@@ -83,4 +84,23 @@ describe("section context", () => {
expect(readSections()).toEqual(["Other"]);
expect(readSectionContext("Other")?.text).toBe("Keep this");
});
+
+ it("saves a new department order: the named ones swap the places they hold, the rest stay put", () => {
+ ensureSections(["Sales", "Ops", "Design", "Legal"]);
+ expect(reorderSectionNames(["Legal", "Ops"])).toBe(true);
+ expect(readSections()).toEqual(["Sales", "Legal", "Design", "Ops"]);
+ for (const refused of [[], ["Sales", "Sales"], ["Sales", "Nowhere"]]) expect(reorderSectionNames(refused), refused.join()).toBeNull();
+ // An order that is already shown changes nothing.
+ expect(reorderSectionNames(["Sales", "Legal"])).toBe(false);
+ expect(readSections()).toEqual(["Sales", "Legal", "Design", "Ops"]);
+ });
+
+ it("takes a device's first offer of its own department order only while nobody has set one", () => {
+ ensureSections(["Sales", "Ops"]);
+ expect(reorderSectionNames(["Ops", "Sales"], true)).toBe(true);
+ expect(reorderSectionNames(["Sales", "Ops"], true)).toBe(false);
+ expect(readSections()).toEqual(["Ops", "Sales"]);
+ expect(reorderSectionNames(["Sales", "Ops"])).toBe(true);
+ expect(readSections()).toEqual(["Sales", "Ops"]);
+ });
});
diff --git a/server/section-context.ts b/server/section-context.ts
index 482c8a21f1..fb8b48bd3b 100644
--- a/server/section-context.ts
+++ b/server/section-context.ts
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
import { join } from "node:path";
import { z } from "zod";
+import { reorderNamesIfMoved } from "../shared/bot-order.ts";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
import { renamePublishedTeam } from "./published-teams.ts";
@@ -23,6 +24,8 @@ interface SectionContextFile {
contexts: Record<string, SectionContextRecord>;
/** Stable memory ownership survives renames; deleting a label retires its key. */
memoryKeys: Record<string, string>;
+ /** Someone has set the department order, so a device's first offer of its own order no longer applies. */
+ ordered?: true;
}
const sectionContextRecordSchema = z.object({ text: z.string(), updatedAt: z.number().finite() });
@@ -30,6 +33,7 @@ const sectionContextFileSchema = z.object({
version: z.literal(1),
sections: z.array(z.string()).optional(),
memoryKeys: z.record(z.string(), z.string().min(1)).optional(),
+ ordered: z.literal(true).optional(),
contexts: z.record(
z.string(),
sectionContextRecordSchema,
@@ -64,7 +68,7 @@ function loadFile(forWrite = false): SectionContextFile {
}
const memoryKeys: Record<string, string> = Object.create(null);
for (const [name, key] of Object.entries((input as { memoryKeys?: Record<string, string> }).memoryKeys ?? {})) memoryKeys[name] = key;
- return { version: 1, memoryKeys, sections: [...new Set([
+ return { version: 1, memoryKeys, ...(candidate.data.ordered ? { ordered: true } : {}), sections: [...new Set([
...(candidate.data.sections ?? []), ...Object.keys(contexts),
].map(sectionContextKey).filter(Boolean))], contexts };
} catch {
@@ -106,6 +110,19 @@ export function ensureSections(names: (string | undefined)[]): string[] {
return added;
}
+/** Saves a new department order, the same on every device: the named departments take, in the order given, the places
+ * they already hold together, and every other one keeps its place. With `first`, only a workspace whose order nobody
+ * has set yet takes it. Whether the order changed; null, and nothing changes, for an empty list, a repeated name or a
+ * name that is not a department. */
+export function reorderSectionNames(names: readonly string[], first = false): boolean | null {
+ const data = loadFile(true);
+ if (!names.length || new Set(names).size !== names.length || names.some((name) => !data.sections.includes(name))) return null;
+ const sections = reorderNamesIfMoved(data.sections, names);
+ if ((first && data.ordered) || !sections) return false;
+ saveFile({ ...data, sections, ordered: true });
+ return true;
+}
+
export function changeEmptySection(name: string, nextName: string | null): void {
const data = loadFile(true);
const index = data.sections.indexOf(name);
diff --git a/server/store.ts b/server/store.ts
index 8bd2ccc0b8..610959f168 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -6,7 +6,7 @@ import { commitRegistryChange, deferrablePatch, keptRevocation, saveRegistryFor,
import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts"; import { dropRetiredApps } from "./retired-apps.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 { grantNewDepartments } from "./department-grants.ts";
+import { ensureSections, readSections, changeEmptySection, reorderSectionNames } from "./section-context.ts"; import { grantNewDepartments } from "./department-grants.ts";
import type { TeamComputers } from "./team-computers.ts";
import { removeBotFolder, soulFile, soulHash, writeSoulMirror } from "./bot-folder.ts";
import type { BotProfilePatch } from "./bot-profile.ts";
@@ -653,8 +653,8 @@ export class Store {
this.registry.writeGroups(groups);
}
- get sections(): string[] { return readSections(); }
-
+ get sections(): string[] { return readSections(); } /** A stable partial reorder of the departments (reorderSectionNames); null, and nothing changes, for a refused list. */
+ reorderSections(names: readonly string[], first = false): string[] | null { const changed = reorderSectionNames(names, first); if (changed === null) return null; if (changed) this.emit({ type: "sections" }); return this.sections; }
private rememberSections(names: (string | undefined)[]) {
try {
const added = ensureSections(names); // a name an older save left unregistered at startup is not a new department
diff --git a/shared/bot-order.test.ts b/shared/bot-order.test.ts
index 1a040880c1..602e48336e 100644
--- a/shared/bot-order.test.ts
+++ b/shared/bot-order.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { reorderIfMoved, reorderInPlace, reorderStable } from "./bot-order.ts";
+import { reorderIfMoved, reorderInPlace, reorderNamesStable, reorderStable } from "./bot-order.ts";
const items = (...ids: string[]) => ids.map((id) => ({ id }));
const ids = (list: ReadonlyArray<{ id: string }>) => list.map((item) => item.id);
@@ -59,3 +59,9 @@ describe("reorderIfMoved", () => {
expect(reorderIfMoved(list, ["ghost"])).toBeNull();
});
});
+
+describe("reorderNamesStable", () => {
+ it("reorders plain names the same way, ignoring names it does not have", () => {
+ expect(reorderNamesStable(["a", "b", "c", "d"], ["d", "ghost", "b"])).toEqual(["a", "d", "c", "b"]);
+ });
+});
diff --git a/shared/bot-order.ts b/shared/bot-order.ts
index 7a5364e904..3684368008 100644
--- a/shared/bot-order.ts
+++ b/shared/bot-order.ts
@@ -26,3 +26,14 @@ export function reorderIfMoved<T extends { id: string }>(items: readonly T[], id
const next = reorderStable(items, ids);
return next.some((item, index) => item !== items[index]) ? next : null;
}
+
+/** reorderStable for plain names, such as the departments or the sidebar's section ids. */
+export function reorderNamesStable(names: readonly string[], order: readonly string[]): string[] {
+ return reorderStable(names.map((id) => ({ id })), order).map((item) => item.id);
+}
+
+/** reorderIfMoved for plain names: the reordered list, or null when no name moved. */
+export function reorderNamesIfMoved(names: readonly string[], order: readonly string[]): string[] | null {
+ const next = reorderNamesStable(names, order);
+ return next.some((name, index) => name !== names[index]) ? next : null;
+}
diff --git a/src/components/Sidebar.simple-layout.test.ts b/src/components/Sidebar.simple-layout.test.ts
index e23775c329..c23d3663f5 100644
--- a/src/components/Sidebar.simple-layout.test.ts
+++ b/src/components/Sidebar.simple-layout.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AppState, Bot, Group } from "@/state/store";
const fixture = vi.hoisted(() => ({
- values: [] as unknown[], index: 0, effects: [] as EffectCallback[], advanced: false,
+ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], advanced: false, owner: true,
state: {} as AppState, dispatch: vi.fn(), storage: new Map<string, string>(),
}));
vi.mock("react", async (original) => ({
@@ -26,7 +26,7 @@ vi.mock("react", async (original) => ({
useLayoutEffect: () => {},
}));
vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));
-vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.owner }));
vi.mock("./MenuMotion", () => ({
useMenuMotion: (open: boolean) => ({ shown: open, closing: false, className: "", exitProps: {} }),
useHeldMenuMotion: (value: unknown) => ({ shown: value !== null, value, closing: false, className: "", exitProps: {} }),
@@ -88,6 +88,7 @@ const labelled = (tree: ReactElement<Props>[], label: string) => tree.some((node
beforeEach(() => {
fixture.values = [];
fixture.advanced = false;
+ fixture.owner = true;
fixture.storage = new Map();
fixture.dispatch.mockClear();
fixture.state = {
@@ -211,6 +212,9 @@ describe("Simple-mode sidebar layout", () => {
});
it("starts from the shared order for the departments, and a Simple move is saved for Simple only", () => {
+ // This device's own department order: a person who may not change the workspace's (an owner's departments follow
+ // the workspace's order instead; SidebarSections.test.ts).
+ fixture.owner = false;
fixture.state = { ...fixture.state, sections: ["Work", "Home"] };
const saved = [userSectionId("Home"), CHANNELS_SECTION_ID, BOTS_SECTION_ID, userSectionId("Work")];
fixture.storage.set(SIDEBAR_SECTION_ORDER_KEY, JSON.stringify(saved));
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index a3e2e55ca0..ce67bc8a9c 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -63,7 +63,7 @@ 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 { departmentNames, moveBotsToSection, useDepartmentOrder } from "./bot-sections";
import { sidebarSectionAttention } from "@/lib/sidebar-attention";
import { botListItemPointerIntent } from "@/lib/sidebar-selection";
import { SidebarFooter } from "./SidebarFooter";
@@ -1073,7 +1073,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
: undefined;
const q = query.trim().toLowerCase();
- const sections = useSidebarSections({ simple, rail, density, query: q, label: sectionLabel, sidebarRef });
+ const sections = useSidebarSections({ simple, rail, density, query: q, label: sectionLabel, sidebarRef, departments: useDepartmentOrder(state.sections, dispatch) });
const botDrag = useSidebarBotDrag({ dispatch, announce: sections.announce, onNamed: sections.focusHeader, onRenamed: sections.renamed,
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 });
diff --git a/src/components/SidebarSections.test.ts b/src/components/SidebarSections.test.ts
new file mode 100644
index 0000000000..be482932d0
--- /dev/null
+++ b/src/components/SidebarSections.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment happy-dom
+import { createElement, createRef } 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 { BOTS_SECTION_ID, userSectionId } from "@/lib/sidebar-layout";
+import { SIDEBAR_SECTION_ORDER_KEY } from "@/lib/sidebar-preferences";
+import { useSidebarSections } from "./SidebarSections";
+import type { DepartmentOrder } from "./bot-sections";
+
+const [sales, ops] = [userSectionId("Sales"), userSectionId("Ops")];
+let root: Root;
+let shown: ReturnType<ReturnType<typeof useSidebarSections>["arrange"]>;
+
+function Probe({ departments, simple = false }: { departments: DepartmentOrder | null; simple?: boolean }) {
+ const sections = useSidebarSections({ simple, rail: false, density: "comfortable", query: "", label: (id) => id, sidebarRef: createRef(), departments });
+ shown = sections.arrange([BOTS_SECTION_ID, sales, ops]);
+ return null;
+}
+
+const render = (departments: DepartmentOrder | null, simple = false) => flushSync(() => root.render(createElement(Probe, { departments, simple })));
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+beforeEach(() => {
+ localStorage.clear();
+ // This device had put Ops first, with the bots between the two departments.
+ localStorage.setItem(SIDEBAR_SECTION_ORDER_KEY, JSON.stringify([ops, BOTS_SECTION_ID, sales]));
+ root = createRoot(document.createElement("div"));
+});
+afterEach(() => root.unmount());
+
+describe("the sidebar's departments", () => {
+ it("follow the workspace's order, the same on every device, while the built-in sections keep this device's places", () => {
+ render({ order: ["Sales", "Ops"], save: vi.fn(async () => true), offer: vi.fn() });
+ expect(shown.sectionIds).toEqual([sales, BOTS_SECTION_ID, ops]);
+ });
+
+ it("save a move for every device", () => {
+ const save = vi.fn(async () => true);
+ render({ order: ["Sales", "Ops"], save, offer: vi.fn() });
+ // Up past the bots, then past Sales.
+ flushSync(() => shown.header(ops).onMove(-1));
+ expect(shown.sectionIds).toEqual([sales, ops, BOTS_SECTION_ID]);
+ flushSync(() => shown.header(ops).onMove(-1));
+ expect(save).toHaveBeenLastCalledWith(["Ops", "Sales"]);
+ });
+
+ it("offer this device's order to the workspace once, so the first device to update keeps its departments where they were", async () => {
+ const save = vi.fn(async () => true);
+ const offer = vi.fn();
+ render({ order: ["Sales", "Ops"], save, offer });
+ await settle();
+ render({ order: ["Sales", "Ops"], save, offer });
+ await settle();
+ expect(offer).toHaveBeenCalledTimes(1);
+ expect(offer).toHaveBeenCalledWith(["Ops", "Sales"]);
+ expect(save).not.toHaveBeenCalled();
+ });
+
+ it("follow the workspace's order in Simple too, and a Simple move saves it for every device", () => {
+ const save = vi.fn(async () => true);
+ render({ order: ["Sales", "Ops"], save, offer: vi.fn() }, true);
+ expect(shown.sectionIds.filter((id) => id !== BOTS_SECTION_ID)).toEqual([sales, ops]);
+ flushSync(() => shown.header(ops).onMove(-1));
+ expect(save).toHaveBeenLastCalledWith(["Ops", "Sales"]);
+ });
+
+ it("stay in this device's order for a person who may not change the workspace's", () => {
+ render(null);
+ expect(shown.sectionIds).toEqual([ops, BOTS_SECTION_ID, sales]);
+ });
+});
diff --git a/src/components/SidebarSections.tsx b/src/components/SidebarSections.tsx
index 3cc00ef5a9..89f602870f 100644
--- a/src/components/SidebarSections.tsx
+++ b/src/components/SidebarSections.tsx
@@ -1,7 +1,9 @@
-import { useRef, useState, type DragEvent, type RefObject } from "react";
+import { useEffect, useRef, useState, type DragEvent, type RefObject } from "react";
+import type { DepartmentOrder } from "./bot-sections";
import { FOLDER_DRAG_TYPE } from "@/lib/folder-order";
import { t } from "@/lib/i18n";
import {
+ departmentsIn,
mergeSectionOrder,
moveSection,
orderedSidebarSections,
@@ -11,6 +13,7 @@ import {
sidebarSectionCollapsed,
simpleOrderedSections,
userSectionId,
+ withDepartmentOrder,
type SectionDropPlace,
} from "@/lib/sidebar-layout";
import {
@@ -27,14 +30,17 @@ import {
const SECTION_DRAG_TYPE = "application/x-openmausbot-sidebar-section";
/** The sidebar's sections on this device: which are collapsed, their saved order, and dragging or Alt+Up/Down a
- * heading to reorder them. Simple and Advanced each keep their own order, so a move in one leaves the other as it was. */
-export function useSidebarSections({ simple, rail, density, query, label, sidebarRef }: {
+ * heading to reorder them. Simple and Advanced each keep their own order, so a move in one leaves the other as it was.
+ * With `departments`, the departments among them follow the workspace's order, the same on every device, and a move
+ * saves it there; the built-in sections keep this device's places. */
+export function useSidebarSections({ simple, rail, density, query, label, sidebarRef, departments = null }: {
simple: boolean;
rail: boolean;
density: SidebarDensity;
query: string;
label: (id: string) => string;
sidebarRef: RefObject<HTMLElement | null>;
+ departments?: DepartmentOrder | null;
}) {
const [collapsedIds, setCollapsedIds] = useState<string[]>(() => loadCollapsedSections());
const [savedOrder, setSavedOrder] = useState<string[]>(() => loadSectionOrder());
@@ -44,6 +50,18 @@ export function useSidebarSections({ simple, rail, density, query, label, sideba
const [announcement, setAnnouncement] = useState("");
const drag = useRef<{ from: string | null; over: { id: string; place: SectionDropPlace } | null }>({ from: null, over: null });
const interactive = sidebarLayoutInteractive(density, query);
+ const ownOrder = simple || rail;
+ const shared = (ids: string[]) => (departments ? withDepartmentOrder(ids, departments.order) : ids);
+
+ // Once per start: the order this device shows (Simple's in Simple or the rail) is offered to the workspace, which
+ // takes it only while nobody has set one, so the first device to update keeps its departments where they were.
+ const offered = useRef(false);
+ useEffect(() => {
+ if (!departments || offered.current || departments.order.length < 2) return;
+ offered.current = true;
+ const advanced = orderedSidebarSections(departments.order.map(userSectionId), savedOrder);
+ departments.offer(departmentsIn(ownOrder ? simpleOrderedSections(advanced, simpleOrder) : advanced));
+ }, [departments, savedOrder, simpleOrder, ownOrder]);
const focusHeader = (name: string) => requestAnimationFrame(() => {
const header = [...(sidebarRef.current?.querySelectorAll<HTMLElement>("[data-section]") ?? [])].find((element) => element.dataset.section === name);
@@ -76,9 +94,8 @@ export function useSidebarSections({ simple, rail, density, query, label, sideba
focusHeader(to);
},
arrange(natural: string[]) {
- const orderedIds = orderedSidebarSections(natural, savedOrder);
- const ownOrder = simple || rail;
- const sectionIds = ownOrder ? simpleOrderedSections(orderedIds, simpleOrder) : orderedIds;
+ const orderedIds = shared(orderedSidebarSections(natural, savedOrder));
+ const sectionIds = ownOrder ? shared(simpleOrderedSections(orderedIds, simpleOrder)) : orderedIds;
const reorder = (id: string, next: string[]) => {
if (sameSectionOrder(next, sectionIds)) return;
const saved = ownOrder ? simpleOrder : savedOrder;
@@ -87,6 +104,7 @@ export function useSidebarSections({ simple, rail, density, query, label, sideba
(ownOrder ? setSimpleOrder : setSavedOrder)(merged);
(ownOrder ? saveSimpleSectionOrder : saveSectionOrder)(merged);
}
+ if (interactive && departments) void departments.save(departmentsIn(next).filter((name) => departments.order.includes(name)));
const position = next.indexOf(id);
if (position >= 0) setAnnouncement(t("sidebar.section.moved", { name: label(id), position: position + 1, count: next.length }));
};
diff --git a/src/components/bot-sections.ts b/src/components/bot-sections.ts
index 4f29e7afea..03c128e286 100644
--- a/src/components/bot-sections.ts
+++ b/src/components/bot-sections.ts
@@ -1,5 +1,6 @@
import type { Dispatch } from "react";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
+import { reorderNamesIfMoved } from "../../shared/bot-order";
import { api, type Action, type AppState, type Bot } from "@/state/store";
const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));
@@ -43,6 +44,45 @@ export function saveBotOrder(dispatch: Dispatch<Action>, bots: readonly Pick<Bot
});
}
+/** The workspace's department order and its save, for a person who may move bots; null keeps the order this device's own. */
+export function useDepartmentOrder(sections: readonly string[] | undefined, dispatch: Dispatch<Action>): DepartmentOrder | null {
+ // Only once the answer is known: a member must not offer or move the workspace's order while it is being looked up.
+ if (useOwnerOrAdmin() !== true) return null;
+ const order = sections ?? [];
+ return { order, save: (names: string[]) => saveDepartmentOrder(dispatch, order, names), offer: offerDepartmentOrder };
+}
+
+export interface DepartmentOrder {
+ order: readonly string[];
+ save(names: string[]): Promise<boolean>;
+ /** This device's own order, taken only by a workspace whose order nobody has set. */
+ offer(names: string[]): void;
+}
+
+function offerDepartmentOrder(names: string[]): void {
+ // Quiet: an older server without the shared order leaves this device's order as it was.
+ api("/api/sidebar-sections/order", { method: "PUT", body: JSON.stringify({ sections: names, first: true }) }).catch(() => undefined);
+}
+
+let departmentOrderRequest = 0;
+
+/** Shows the departments `names` in this order at once and saves it for every device; every other department keeps
+ * its place. True once the workspace has it. A refused save is undone only while no newer move has been made. */
+export async function saveDepartmentOrder(dispatch: Dispatch<Action>, sections: readonly string[], names: string[]): Promise<boolean> {
+ if (!reorderNamesIfMoved(sections, names)) return true;
+ const before = sections.filter((name) => names.includes(name));
+ const request = ++departmentOrderRequest;
+ dispatch({ type: "sectionsOrdered", sections: names });
+ try {
+ await api("/api/sidebar-sections/order", { method: "PUT", body: JSON.stringify({ sections: names }) });
+ return true;
+ } catch (cause) {
+ if (request === departmentOrderRequest) dispatch({ type: "sectionsOrdered", sections: before });
+ dispatch({ type: "error", message: failure(cause) });
+ return false;
+ }
+}
+
export async function renameDepartment(dispatch: Dispatch<Action>, from: string, to: string): Promise<void> {
const { sections } = await api(`/api/sidebar-sections?section=${encodeURIComponent(from)}`, { method: "PATCH", body: JSON.stringify({ name: to }) });
dispatch({ type: "sections", sections });
diff --git a/src/lib/sidebar-layout.test.ts b/src/lib/sidebar-layout.test.ts
index 706b98a9ad..3de169b9d5 100644
--- a/src/lib/sidebar-layout.test.ts
+++ b/src/lib/sidebar-layout.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
activeBotsFirst,
+ departmentsIn,
BOT_CHATS_SECTION_ID,
BOTS_SECTION_ID,
CHANNELS_SECTION_ID,
@@ -28,6 +29,7 @@ import {
unreadSinceByBot,
userSectionId,
userSectionName,
+ withDepartmentOrder,
withPrimaryTile,
withUnreadSection,
} from "./sidebar-layout";
@@ -461,3 +463,11 @@ describe("the unread section", () => {
expect(sidebarSectionLabel(UNREAD_SECTION_ID)).toBe("Unread");
});
});
+
+describe("the workspace's department order", () => {
+ it("fills the places departments hold with the workspace's order and leaves the rest alone", () => {
+ const ids = [userSectionId("Ops"), BOTS_SECTION_ID, userSectionId("Sales"), userSectionId("Local only")];
+ expect(withDepartmentOrder(ids, ["Sales", "Gone", "Ops"])).toEqual([userSectionId("Sales"), BOTS_SECTION_ID, userSectionId("Ops"), userSectionId("Local only")]);
+ expect(departmentsIn(ids)).toEqual(["Ops", "Sales", "Local only"]);
+ });
+});
diff --git a/src/lib/sidebar-layout.ts b/src/lib/sidebar-layout.ts
index 95e9ad680d..3576dfd9ee 100644
--- a/src/lib/sidebar-layout.ts
+++ b/src/lib/sidebar-layout.ts
@@ -5,6 +5,7 @@ import type { LocaleKey } from "@/locales";
import type { DefaultBotFields } from "../../shared/default-bot";
import { hiddenFromSidebar, someoneElsesDefaultBot } from "./default-bot";
import { botShowsUnread } from "./bot-unread";
+import { reorderNamesStable } from "../../shared/bot-order";
export const PINNED_SECTION_ID = "builtin:pinned";
export const UNREAD_SECTION_ID = "builtin:unread";
@@ -343,6 +344,17 @@ export function mergeSectionOrder(
return result;
}
+/** The departments in the workspace's order, the same on every device: the places they hold in `ids` are filled in
+ * `departments` order. Built-in sections, and a department the workspace does not list, keep their places. */
+export function withDepartmentOrder(ids: SidebarSectionId[], departments: readonly string[]): SidebarSectionId[] {
+ return reorderNamesStable(ids, departments.map(userSectionId));
+}
+
+/** The departments in `ids`, by name, in that order. */
+export function departmentsIn(ids: readonly SidebarSectionId[]): string[] {
+ return ids.flatMap((id) => userSectionName(id) ?? []);
+}
+
export function sameSectionOrder(a: SidebarSectionId[], b: SidebarSectionId[]): boolean {
return a.length === b.length && a.every((id, index) => id === b[index]);
}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 62933b8de9..26344c0685 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -11,7 +11,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 { reorderIfMoved } from "../../shared/bot-order";
+import { reorderIfMoved, reorderNamesIfMoved } 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";
@@ -590,7 +590,7 @@ export type Action =
resumeId?: string;
}
| { type: "botQueues"; queues: AppState["pendingQueued"] }
- | { type: "sections"; sections: string[] }
+ | { type: "sections"; sections: string[] } | { type: "sectionsOrdered"; sections: 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 }
@@ -920,8 +920,8 @@ function reduceApp(state: AppState, action: Action): AppState {
bots: state.bots.map(bot => bot.section === action.section ? { ...bot, section: undefined } : bot),
groups: state.groups.map(group => group.section === action.section ? { ...group, section: undefined } : group),
};
- case "sections":
- return { ...state, sections: action.sections };
+ case "sections": return { ...state, sections: action.sections };
+ case "sectionsOrdered": { const sections = reorderNamesIfMoved(state.sections ?? [], action.sections); return sections ? { ...state, sections } : state; }
// 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; }