Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Simple's sidebar: drag bots to reorder them and into departments (#3906)
Milind Sonie6cc9b5c60d1
diff --git a/docs/verification/README.md b/docs/verification/README.mdindex b6a94475b6..2e6cfecbb9 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -228,7 +228,8 @@ roles and device revocation through the real HTTP API with a stubbed emailservice. It does not drive the People settings UI through `control-omb`.The [sidebar fixture](sidebar.md) checks archive and delete confirmations, their-default focus, keyboard wrapping and focus return against two disposable bots.+default focus, keyboard wrapping and focus return against two disposable bots;+its departments recipe drags bots to reorder them and into new departments.The [sidebar attention geometry fixture](sidebar-attention.md) measures theActive Threads popover's width and inset at each expanded sidebar density in adiff --git a/docs/verification/evidence/simple-sidebar-groups/after-delete-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-delete-simple-daylight.pngnew file mode 100644index 0000000000..08e9f0a11cBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-delete-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-departments-advanced-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-departments-advanced-daylight.pngnew file mode 100644index 0000000000..13deba48e6Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-departments-advanced-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-daylight.pngnew file mode 100644index 0000000000..4dc7465379Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-midnight.png b/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-midnight.pngnew file mode 100644index 0000000000..013833e925Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-departments-simple-midnight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-daylight.pngnew file mode 100644index 0000000000..1604b907ddBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-midnight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-midnight.pngnew file mode 100644index 0000000000..c2cb00c102Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-group-simple-midnight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-into-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-into-simple-daylight.pngnew file mode 100644index 0000000000..fbabd4760cBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-into-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-line-advanced-midnight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-line-advanced-midnight.pngnew file mode 100644index 0000000000..83204d6280Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-line-advanced-midnight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-line-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-line-simple-daylight.pngnew file mode 100644index 0000000000..ba027cf180Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-line-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-out-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-out-simple-daylight.pngnew file mode 100644index 0000000000..fc285daae9Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-out-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-drag-slot-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-drag-slot-simple-daylight.pngnew file mode 100644index 0000000000..0c0153969cBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-drag-slot-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-menu-move-member-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-menu-move-member-simple-daylight.pngnew file mode 100644index 0000000000..157261221aBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-menu-move-member-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-menu-move-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-menu-move-simple-daylight.pngnew file mode 100644index 0000000000..8f3097275dBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-menu-move-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-named-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-named-simple-daylight.pngnew file mode 100644index 0000000000..cd782fc7b1Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-named-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-naming-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-naming-simple-daylight.pngnew file mode 100644index 0000000000..16e04e048dBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-naming-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-rename-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-rename-simple-daylight.pngnew file mode 100644index 0000000000..477312c984Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-rename-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/after-rest-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/after-rest-simple-daylight.pngnew file mode 100644index 0000000000..c02e44047cBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/after-rest-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/before-departments-advanced-daylight.png b/docs/verification/evidence/simple-sidebar-groups/before-departments-advanced-daylight.pngnew file mode 100644index 0000000000..7e0a7f0690Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/before-departments-advanced-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-daylight.pngnew file mode 100644index 0000000000..317c5c6cc5Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-midnight.png b/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-midnight.pngnew file mode 100644index 0000000000..ae3d203f0fBinary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/before-departments-simple-midnight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/before-menu-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/before-menu-simple-daylight.pngnew file mode 100644index 0000000000..2ab73c0df0Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/before-menu-simple-daylight.png differdiff --git a/docs/verification/evidence/simple-sidebar-groups/before-rest-simple-daylight.png b/docs/verification/evidence/simple-sidebar-groups/before-rest-simple-daylight.pngnew file mode 100644index 0000000000..f7da4c4340Binary files /dev/null and b/docs/verification/evidence/simple-sidebar-groups/before-rest-simple-daylight.png differdiff --git a/docs/verification/sidebar.md b/docs/verification/sidebar.mdindex 5c38b71537..39b411c3a2 100644--- a/docs/verification/sidebar.md+++ b/docs/verification/sidebar.md@@ -96,3 +96,38 @@ and `src/lib/notify.test.ts` cover persisted preferences, blocked storage, crossreads after Settings unmounts, and the silent flag sent to the desktop bridge.Actual operating-system sound delivery requires a native Electron smoke test;the isolated browser cannot prove it.++## Departments: dragging bots and naming them in place++Run `node --experimental-strip-types scripts/verify-sidebar-groups.ts`. It+starts a disposable fake-engine server with five bots, puts two of them in a+**Work** department and two in **Home**, and prints the address of the real app+in Advanced mode; add `?mode=simple` to it for Simple mode. Ctrl-C closes both+servers and removes only the fixture data. With `--shots <dir>` it instead+photographs each view below in a headless Chrome with a throwaway profile, from+the page's own drag events, and exits.++1. With no department, Simple's sidebar is unchanged.+2. Drag a bot over the top or bottom quarter of another: a line shows where it+ lands, and dropping saves the order (`PUT /api/bots/order`) for every client.+3. Drag it over the middle of a bot in no department: that row is ringed.+ Dropping shows a new department with both bots and its name field focused,+ "New department" selected. Enter keeps the typed name, or the default when+ it is empty; Escape puts the bots back.+4. Drag a bot over a department's heading to put it at its end, between its+ rows to place it there, and between the rows outside any department to take+ it out. With every bot in a department, a "Remove from department" place+ shows at the top while a bot is dragged.+5. Alt+Up/Down moves the focused row within its list and announces its new+ position. A bot's menu → **Move to department** lists the departments,+ **New department…** and **Remove from department**, for touch and keyboard.+6. A department's ⋯ → **Rename department** edits its name in the heading in+ Simple (Advanced keeps its dialog); **Delete department** says the bots stay.+7. Switch to Advanced: the same departments and order show, and rows drag the+ same way.++`src/lib/sidebar-bot-drop.test.ts` covers where a drop lands,+`src/components/Sidebar.departments.test.ts` the sidebar's wiring, and+`src/components/SidebarSectionHeader.naming.dom.test.ts` the name field. The+headless pictures cannot prove the operating system's own drag image or a drag+between two windows.diff --git a/scripts/testing/sidebar-groups-preview.tsx b/scripts/testing/sidebar-groups-preview.tsxnew file mode 100644index 0000000000..1169634c7d--- /dev/null+++ b/scripts/testing/sidebar-groups-preview.tsx@@ -0,0 +1,17 @@+import { createRoot } from "react-dom/client";+import App from "../../src/App";+import { setAnalyticsEnabled, setEmailGateDone } from "../../src/lib/analytics";+import { setAdvancedMode } from "../../src/lib/interface-mode";+import { markSimpleModePromptSeen } from "../../src/lib/simple-mode-prompt";+import { applySkin, type SkinId } from "../../src/lib/skins";+import "../../src/styles.css";++// Served only by scripts/verify-sidebar-groups.ts: the real app against its disposable fixture. ?mode=simple is Simple+// mode, ?skin= the skin.+const params = new URLSearchParams(location.search);+setAnalyticsEnabled(false);+setEmailGateDone("skipped");+markSimpleModePromptSeen();+setAdvancedMode(params.get("mode") !== "simple");+applySkin((params.get("skin") ?? "daylight") as SkinId);+createRoot(document.getElementById("root")!).render(<App />);diff --git a/scripts/verify-sidebar-groups.ts b/scripts/verify-sidebar-groups.tsnew file mode 100644index 0000000000..87b394fd9d--- /dev/null+++ b/scripts/verify-sidebar-groups.ts@@ -0,0 +1,177 @@+// Departments in the sidebar of the real app, against a disposable fake-engine server: dragging a bot to reorder it,+// onto another bot to start a department named in place, into and out of a department, and a bot's menu.+// Run: node --experimental-strip-types scripts/verify-sidebar-groups.ts [--shots <dir> [--only <view,view>]]+// With --shots it photographs each view with a headless Chrome in a throwaway profile (OMB_CDP_CHROME, else the+// installed Google Chrome) at twice 1280x800 and exits; without, it prints the preview's address and waits. Drags are+// the page's own DragEvents with a DataTransfer, so a view can stop mid-drag to show where the bot would land.+import { spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { setTimeout as delay } from "node:timers/promises";+import { launchVerificationServer, runControlOmb } from "./control-omb.ts";+import { fixtureApi, mountPreview, parkUntilSignal, type MountedPreview } from "./testing/preview-fixture.ts";++const at = process.argv.indexOf("--shots");+const shots = at === -1 ? null : resolve(process.argv[at + 1] ?? "");+const onlyAt = process.argv.indexOf("--only");+const only = onlyAt === -1 ? null : new Set((process.argv[onlyAt + 1] ?? "").split(",").filter(Boolean));+const CHROME = process.env.OMB_CDP_CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";+const [WIDTH, HEIGHT, CLIP] = [1280, 800, 640];+const BOTS: Record<string, string> = { Research: "pink", Inbox: "teal", Writer: "yellow", Travel: "blue", Recipes: "coral" };+const NAMES = Object.keys(BOTS);++type Setup = "plain" | "departments" | "full";+/** Each view: the server's state, the mode, a script run in the page once a bot row shows, and what must show after. */+const VIEWS: Array<{ name: string; setup: Setup; mode: "simple" | "advanced"; act?: string; ready?: string; skins?: string[]; wide?: true }> = [+ { name: "rest-simple", setup: "plain", mode: "simple", skins: ["daylight", "midnight"] },+ { name: "departments-simple", setup: "departments", mode: "simple", skins: ["daylight", "midnight"] },+ { name: "departments-advanced", setup: "departments", mode: "advanced" },+ { name: "menu-simple", setup: "departments", mode: "simple", act: "menu('Inbox')", ready: "[data-bot-menu]" },+ { name: "menu-move-simple", setup: "departments", mode: "simple", act: "menu('Inbox'); await pause(300); document.querySelector('[data-bot-menu-move]').click()", ready: "[data-bot-menu-flyout='move']", skins: ["daylight", "midnight"] },+ { name: "menu-move-member-simple", setup: "departments", mode: "simple", act: "menu('Writer'); await pause(300); document.querySelector('[data-bot-menu-move]').click()", ready: "[data-bot-menu-flyout='move']" },+ { name: "drag-line-simple", setup: "plain", mode: "simple", act: "start('Inbox'); over(row('Travel'), 0.15)", ready: "[data-bot-drop='before']", skins: ["daylight", "midnight"] },+ { name: "drag-group-simple", setup: "plain", mode: "simple", act: "start('Inbox'); over(row('Writer'), 0.5)", ready: "[data-bot-drop='group']", skins: ["daylight", "midnight"] },+ { name: "naming-simple", setup: "plain", mode: "simple", act: "start('Inbox'); over(row('Writer'), 0.5); drop(row('Writer'), 0.5)", ready: "[data-section-name-field]", skins: ["daylight", "midnight"] },+ { name: "named-simple", setup: "plain", mode: "simple", act: "start('Inbox'); over(row('Writer'), 0.5); drop(row('Writer'), 0.5); await pause(300); type('Writing'); enter()", ready: "[data-section='Writing']" },+ { name: "drag-into-simple", setup: "departments", mode: "simple", act: "start('Inbox'); over(header('Work'), 0.5)", ready: "[data-section-drop]", skins: ["daylight", "midnight"] },+ { name: "drag-out-simple", setup: "departments", mode: "simple", act: "start('Travel'); over(row('Inbox'), 0.85)", ready: "[data-bot-drop='after']" },+ { name: "drag-slot-simple", setup: "full", mode: "simple", act: "start('Travel'); await pause(300); over(document.querySelector('[data-bot-drop-slot]'), 0.5)", ready: "[data-bot-drop-slot][class*='border-accent']" },+ { name: "drag-line-advanced", setup: "departments", mode: "advanced", act: "start('Inbox'); over(row('Writer'), 0.85)", ready: "[data-bot-drop='after']", skins: ["midnight"] },+ { name: "rename-simple", setup: "departments", mode: "simple", act: "teamMenu('Work'); await pause(300); item('Rename department').click()", ready: "[data-section-name-field]" },+ { name: "delete-simple", setup: "departments", mode: "simple", act: "teamMenu('Work'); await pause(300); item('Delete department').click()", ready: "[role='dialog'], [role='alertdialog']", wide: true },+];++/** Page helpers the acts above call; bot ids come from the fixture. */+const helpers = (ids: Record<string, string>) => `+ const ids = ${JSON.stringify(ids)};+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));+ const row = (name) => document.querySelector('[data-sidebar-bot-row="' + ids[name] + '"]');+ const header = (name) => document.querySelector('[data-section="' + name + '"]');+ const item = (label) => [...document.querySelectorAll('[role="menuitem"]')].find((node) => node.textContent.trim() === label);+ let dt = null, source = null;+ const fire = (node, type, fraction) => {+ const box = node.getBoundingClientRect();+ node.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: dt, clientX: box.left + box.width / 2, clientY: box.top + box.height * fraction }));+ };+ const start = (name) => { dt = new DataTransfer(); source = row(name); fire(source, "dragstart", 0.5); };+ const over = (node, fraction) => { fire(node, "dragenter", fraction); fire(node, "dragover", fraction); };+ const drop = (node, fraction) => { fire(node, "drop", fraction); fire(source, "dragend", 0.5); };+ const menu = (name) => { const box = row(name).getBoundingClientRect(); row(name).dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: box.left + 60, clientY: box.top + box.height / 2 })); };+ const teamMenu = (name) => { const box = header(name).getBoundingClientRect(); header(name).dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: box.left + 40, clientY: box.bottom })); };+ const type = (text) => {+ const field = document.activeElement;+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(field, text);+ field.dispatchEvent(new Event("input", { bubbles: true }));+ };+ const enter = () => document.activeElement.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+`;++async function openChrome(profile: string) {+ const chrome = spawn(CHROME, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--use-mock-keychain",+ `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"], { stdio: "ignore" });+ let port = "";+ for (let i = 0; i < 100 && !port; i++) {+ await delay(100);+ try { port = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]!.trim(); } catch {}+ }+ if (!port) { chrome.kill(); throw new Error("Chrome did not start"); }+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; webSocketDebuggerUrl: string }>;+ const socket = new WebSocket(targets.find((target) => target.type === "page")!.webSocketDebuggerUrl);+ await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; });+ let next = 0;+ const waiting = new Map<number, { done: (value: any) => void; fail: (error: Error) => void }>();+ socket.onmessage = (event) => {+ const message = JSON.parse(String(event.data));+ const call = waiting.get(message.id);+ if (!call) return;+ waiting.delete(message.id);+ if (message.error) call.fail(new Error(message.error.message)); else call.done(message.result);+ };+ const send = (method: string, params: object = {}) => new Promise<any>((done, fail) => {+ const id = ++next;+ const timer = setTimeout(() => { waiting.delete(id); fail(new Error(`${method} got no answer`)); }, 30_000);+ waiting.set(id, { done: (value) => { clearTimeout(timer); done(value); }, fail: (error) => { clearTimeout(timer); fail(error); } });+ socket.send(JSON.stringify({ id, method, params }));+ });+ const evaluate = async (expression: string) => {+ const result = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });+ if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);+ return result.result?.value;+ };+ const until = async (condition: string, what: string) => {+ const end = Date.now() + 60_000;+ while (!(await evaluate(condition).catch(() => false))) {+ if (Date.now() > end) throw new Error(`${what} never showed`);+ await delay(250);+ }+ };+ return {+ async shoot(url: string, file: string, act: string | undefined, ready: string | undefined, ids: Record<string, string>, width = CLIP) {+ await send("Emulation.setDeviceMetricsOverride", { width: WIDTH, height: HEIGHT, deviceScaleFactor: 2, mobile: false });+ await send("Page.navigate", { url });+ await until(`Boolean(document.querySelector('[data-sidebar-bot-row="${ids.Inbox}"]'))`, `${url}: the bot rows`);+ await delay(900);+ if (act) await evaluate(`(async () => { ${helpers(ids)}\n${act}; })()`);+ if (ready) await until(`Boolean(document.querySelector(${JSON.stringify(ready)}))`, `${url}: ${ready}`);+ await delay(700);+ const { data } = await send("Page.captureScreenshot", { format: "png", clip: { x: 0, y: 0, width, height: HEIGHT, scale: 1 } });+ writeFileSync(file, Buffer.from(data, "base64"));+ },+ close() { socket.close(); chrome.kill(); },+ };+}++const fixture = await launchVerificationServer();+let ui: MountedPreview | undefined;+try {+ const api = fixtureApi(fixture.info.url, { headers: { origin: fixture.info.url } });+ for (const name of NAMES) await runControlOmb(["new-bot", "--name", name, "--url", fixture.info.url]);+ await api("PATCH", "/api/config", { language: "en" });+ const { bots } = await api("GET", "/api/bots?messages=0") as { bots: Array<{ id: string; name: string }> };+ const ids = Object.fromEntries(NAMES.map((name) => [name, bots.find((bot) => bot.name === name)!.id]));+ for (const name of NAMES) await api("PATCH", `/api/bots/${ids[name]}`, { color: BOTS[name] });+ const fleet = bots.map((bot) => bot.id);+ const setUp = async (setup: Setup) => {+ for (const section of (await api("GET", "/api/sidebar-sections")).sections as string[]) {+ await api("DELETE", `/api/sidebar-sections?section=${encodeURIComponent(section)}`);+ }+ await api("PUT", "/api/bots/order", { botIds: fleet });+ if (setup === "plain") return;+ await api("POST", "/api/sidebar-sections", { name: "Work", botIds: [ids.Research, ids.Writer, ...(setup === "full" ? [ids.Inbox] : [])] });+ await api("POST", "/api/sidebar-sections", { name: "Home", botIds: [ids.Travel, ids.Recipes] });+ };+ ui = await mountPreview(fixture, { entry: "/scripts/testing/sidebar-groups-preview.tsx", route: "/__sidebar-groups.html", title: "Isolated sidebar departments", logLevel: "warn" });+ if (!shots) {+ await setUp("departments");+ console.log(JSON.stringify({ ...fixture.info, previewUrl: ui.previewUrl, ids }, null, 2));+ await parkUntilSignal();+ } else {+ mkdirSync(shots, { recursive: true });+ const profile = mkdtempSync(join(tmpdir(), "omb-groups-chrome-"));+ const chrome = await openChrome(profile);+ try {+ for (const view of VIEWS.filter((entry) => !only || only.has(entry.name))) for (const skin of view.skins ?? ["daylight"]) {+ const file = join(shots, `${view.name}-${skin}.png`);+ for (let attempt = 1; ; attempt++) {+ try {+ await setUp(view.setup);+ await chrome.shoot(`${ui.previewUrl}?mode=${view.mode}&skin=${skin}`, file, view.act, view.ready, ids, view.wide ? WIDTH : CLIP);+ break;+ } catch (error) {+ if (attempt === 2) throw error;+ console.error(`retrying ${view.name}-${skin}: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ console.log(file);+ }+ } finally {+ chrome.close();+ await delay(500);+ rmSync(profile, { recursive: true, force: true });+ }+ }+} finally {+ await ui?.close();+ await fixture.close();+}diff --git a/src/components/Sidebar.departments.test.ts b/src/components/Sidebar.departments.test.tsnew file mode 100644index 0000000000..2c6dbfadd3--- /dev/null+++ b/src/components/Sidebar.departments.test.ts@@ -0,0 +1,366 @@+import { Children, isValidElement, type EffectCallback, type ReactElement, type ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Action, AppState, Bot, Group } from "@/state/store";++const fixture = vi.hoisted(() => ({+ values: [] as unknown[], index: 0, advanced: false, phone: false,+ state: {} as AppState, dispatch: vi.fn(), storage: new Map<string, string>(),+ requests: [] as Array<{ path: string; method: string; body: unknown }>,+}));+vi.mock("react", async (original) => ({+ ...await original<typeof import("react")>(),+ useState: (initial: unknown) => {+ const index = fixture.index++;+ if (!(index in fixture.values)) fixture.values[index] = typeof initial === "function" ? (initial as () => unknown)() : initial;+ return [fixture.values[index], (next: unknown) => {+ fixture.values[index] = typeof next === "function" ? (next as (value: unknown) => unknown)(fixture.values[index]) : next;+ }];+ },+ useRef: (initial: unknown) => {+ const index = fixture.index++;+ if (!(index in fixture.values)) fixture.values[index] = { current: initial };+ return fixture.values[index];+ },+ useCallback: (callback: unknown) => callback,+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(),+ useEffect: (_effect: EffectCallback) => {},+ useLayoutEffect: () => {},+}));+vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));+vi.mock("./MenuMotion", () => ({+ useMenuMotion: (open: boolean) => ({ shown: open, closing: false, className: "", exitProps: {} }),+ useHeldMenuMotion: (value: unknown) => ({ shown: value !== null, value, closing: false, className: "", exitProps: {} }),+}));+vi.mock("./DesktopCapabilities", async () => {+ const { initialDesktopCapabilities } = await import("@/lib/desktop");+ return { useDesktopCapabilities: () => ({ capabilities: initialDesktopCapabilities() }) };+});+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.advanced }));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fixture.advanced, setAdvancedMode: () => {} }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) };+});++import { initialState } from "@/state/store";+import { BOTS_SECTION_ID, CHANNELS_SECTION_ID, userSectionId } from "@/lib/sidebar-layout";+import { PHONE_LAYOUT } from "@/lib/use-media-query";+import { BotContextMenu, BotListItem, Sidebar, TeamMenuItems } from "./Sidebar";+import { NEW_DEPARTMENT } from "./SidebarBotDrag";+import { SidebarSectionHeader } from "./SidebarSectionHeader";+import { ConfirmDialog } from "./ConfirmDialog";+import { TeamDialog } from "./TeamDialog";++const bot = (id: string, extra: Partial<Bot> = {}): Bot => ({+ id, threadId: `${id}-thread`, name: id, title: "", description: "", notifications: true,+ color: "green", unread: false, modelSelection: { instanceId: "fake", model: "m" }, messages: [], ...extra,+});+const room: Group = {+ id: "room", threadId: "room-thread", name: "Launch room", memberIds: ["atlas"], messages: [],+ defaultResponder: { kind: "mentions" }, bulletin: "", unread: false, createdAt: 1,+};++type Props = { children?: ReactNode; [key: string]: unknown };+type RowProps = Parameters<typeof BotListItem>[0];+type HeaderProps = Parameters<typeof SidebarSectionHeader>[0];+function nodes(value: ReactNode): ReactElement<Props>[] {+ return Children.toArray(value).flatMap((child) => {+ if (!isValidElement<Props>(child)) return [];+ return [child, ...nodes(child.props.children)];+ });+}+function render() {+ fixture.index = 0;+ const root = Sidebar({ open: false, onClose: () => {} }) as ReactElement<Props>;+ return [root, ...nodes(root.props.children)];+}+const rows = () => render().filter((node) => node.type === BotListItem).map((node) => node.props as unknown as RowProps);+const row = (id: string) => rows().find((props) => props.bot.id === id)!;+const listed = () => rows().map((props) => props.bot.id);+const sections = () => render().map((node) => node.props["data-sidebar-section-id"]).filter(Boolean);+const section = (id: string) => render().find((node) => node.props["data-sidebar-section-id"] === id)!.props as unknown as {+ onDragOver: (event: unknown) => void; onDrop: (event: unknown) => void; children: ReactNode;+};+const headers = () => render().filter((node) => node.type === SidebarSectionHeader).map((node) => node.props as unknown as HeaderProps);+const header = (name: string) => headers().find((props) => props.name === name)!;+const actions = () => fixture.dispatch.mock.calls.map(([action]) => action as Action);++function transfer() {+ const data = new Map<string, string>();+ return { types: [] as string[], effectAllowed: "", dropEffect: "", setData(type: string, value: string) { data.set(type, value); this.types.push(type); }, getData: (type: string) => data.get(type) ?? "" };+}+let carried = transfer();+/** The bot rows a section's drop zone finds under it, each 54px tall from `top`. */+let rowElements: Array<{ dataset: { sidebarBotRow: string }; getBoundingClientRect: () => { top: number; bottom: number; height: number } }> = [];+const laidOut = (...ids: string[]) => {+ rowElements = ids.map((id, index) => ({ dataset: { sidebarBotRow: id }, getBoundingClientRect: () => ({ top: 30 + index * 56, bottom: 84 + index * 56, height: 54 }) }));+};+/** A drag event `offset` pixels into a 54px row. */+const at = (offset = 27) => ({+ dataTransfer: carried, clientY: offset, currentTarget: { getBoundingClientRect: () => ({ top: 0, height: 54 }), querySelectorAll: () => rowElements },+ preventDefault: vi.fn(), stopPropagation: vi.fn(),+});+function drag(id: string) {+ carried = transfer();+ row(id).botDrag!.row(id).onDragStart(at() as never);+}++beforeEach(() => {+ fixture.values = [];+ fixture.advanced = false;+ fixture.phone = false;+ fixture.storage = new Map();+ fixture.requests = [];+ rowElements = [];+ fixture.dispatch.mockClear();+ fixture.state = {+ ...initialState,+ bots: [bot("atlas"), bot("bea"), bot("cleo"), bot("dodo", { section: "Work" }), bot("echo", { section: "Work" })],+ groups: [room],+ sections: ["Work"],+ };+ vi.stubGlobal("window", Object.assign(new EventTarget(), {+ innerWidth: 1280, innerHeight: 800, ogb: undefined, setTimeout, clearTimeout,+ matchMedia: (query: string) => ({ matches: fixture.phone && query === PHONE_LAYOUT, addEventListener() {}, removeEventListener() {} }),+ }));+ vi.stubGlobal("document", { body: {}, querySelector: () => null });+ vi.stubGlobal("requestAnimationFrame", () => 0);+ vi.stubGlobal("fetch", async (path: string, init: RequestInit) => {+ fixture.requests.push({ path, method: init.method ?? "GET", body: init.body ? JSON.parse(String(init.body)) : undefined });+ return new Response(JSON.stringify({ sections: ["Clients"], botIds: [] }), { status: 200 });+ });+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => fixture.storage.get(key) ?? null,+ setItem: (key: string, value: string) => { fixture.storage.set(key, value); },+ removeItem: (key: string) => { fixture.storage.delete(key); },+ });+});+afterEach(() => vi.unstubAllGlobals());++describe("Simple's sidebar before anyone drags", () => {+ it("looks as it did: the same sections and rows, nothing marked, each row ready to drag", () => {+ expect(sections()).toEqual([BOTS_SECTION_ID, CHANNELS_SECTION_ID, userSectionId("Work")]);+ expect(listed()).toEqual(["atlas", "bea", "cleo", "dodo", "echo"]);+ for (const props of rows()) {+ expect(props.botDrop).toBeNull();+ expect(props.botDragging).toBe(false);+ expect(props.botDrag!.row(props.bot.id).draggable).toBe(true);+ }+ expect(headers().every((props) => !props.dropInto && !props.naming)).toBe(true);+ });++ it("leaves rows still on a phone, where the menu moves them", () => {+ fixture.phone = true;+ expect(rows().every((props) => props.botDrag === undefined)).toBe(true);+ });+});++describe("dragging a bot", () => {+ it("shows a line where it lands and saves the new order", () => {+ drag("cleo");+ expect(row("cleo").botDragging).toBe(true);+ row("atlas").botDrag!.row("atlas").onDragOver(at(5) as never);+ expect(row("atlas").botDrop).toBe("before");+ row("atlas").botDrag!.row("atlas").onDrop(at(5) as never);+ expect(actions()).toEqual([{ type: "botsOrdered", botIds: ["cleo", "atlas", "bea"] }]);+ expect(fixture.requests).toEqual([{ path: "/api/bots/order", method: "PUT", body: { botIds: ["cleo", "atlas", "bea"] } }]);+ expect(rows().every((props) => !props.botDrop && !props.botDragging)).toBe(true);+ });++ it("onto the middle of a bot puts both in a new department, named in place, and Enter keeps the name", () => {+ drag("cleo");+ row("atlas").botDrag!.row("atlas").onDragOver(at() as never);+ expect(row("atlas").botDrop).toBe("group");+ row("atlas").botDrag!.row("atlas").onDrop(at() as never);+ expect(actions()).toEqual([]);+ expect(sections()).toEqual([BOTS_SECTION_ID, CHANNELS_SECTION_ID, userSectionId("Work"), userSectionId(NEW_DEPARTMENT)]);+ const naming = header(NEW_DEPARTMENT).naming!;+ expect(naming.value).toBe("New department");+ expect(naming.label).toBe("New department name");+ expect(listed()).toEqual(["bea", "dodo", "echo", "atlas", "cleo"]);+ naming.onCommit(" ");+ expect(actions()).toEqual([+ { type: "updateBot", botId: "atlas", patch: { section: "New department" } },+ { type: "updateBot", botId: "cleo", patch: { section: "New department" } },+ ]);+ expect(sections()).not.toContain(userSectionId(NEW_DEPARTMENT));+ });++ it("gives a new department the first free name, and Escape puts the bots back", () => {+ fixture.state = { ...fixture.state, sections: ["Work", "New department"] };+ drag("cleo");+ row("bea").botDrag!.row("bea").onDrop(at() as never);+ expect(header(NEW_DEPARTMENT).naming!.value).toBe("New department 2");+ drag("atlas");+ const over = at();+ section(userSectionId(NEW_DEPARTMENT)).onDragOver(over as never);+ expect(over.preventDefault).not.toHaveBeenCalled();+ expect(header(NEW_DEPARTMENT).dropInto).toBe(false);+ header(NEW_DEPARTMENT).naming!.onCancel();+ expect(listed()).toEqual(["atlas", "bea", "cleo", "dodo", "echo"]);+ expect(actions()).toEqual([]);+ });++ it("into a department over its heading, or between its rows", () => {+ drag("atlas");+ section(userSectionId("Work")).onDragOver(at() as never);+ expect(header("Work").dropInto).toBe(true);+ section(userSectionId("Work")).onDrop(at() as never);+ expect(actions()).toEqual([{ type: "updateBot", botId: "atlas", patch: { section: "Work" } }, { type: "botsOrdered", botIds: ["dodo", "echo", "atlas"] }]);+ fixture.dispatch.mockClear();+ drag("bea");+ row("echo").botDrag!.row("echo").onDragOver(at(26) as never);+ expect(row("echo").botDrop).toBe("before");+ row("echo").botDrag!.row("echo").onDrop(at(26) as never);+ expect(actions()).toEqual([+ { type: "updateBot", botId: "bea", patch: { section: "Work" } },+ { type: "botsOrdered", botIds: ["dodo", "bea", "echo"] },+ ]);+ });++ it("between rows or under the last one, by the nearest row; over a department's heading, into it", () => {+ drag("atlas");+ laidOut("dodo", "echo");+ section(userSectionId("Work")).onDragOver(at(10) as never);+ expect(header("Work").dropInto).toBe(true);+ section(userSectionId("Work")).onDragOver(at(85) as never);+ expect([header("Work").dropInto, row("echo").botDrop]).toEqual([false, "before"]);+ section(userSectionId("Work")).onDragOver(at(400) as never);+ expect(row("echo").botDrop).toBe("after");+ section(userSectionId("Work")).onDrop(at(85) as never);+ expect(actions()).toEqual([{ type: "updateBot", botId: "atlas", patch: { section: "Work" } }, { type: "botsOrdered", botIds: ["dodo", "atlas", "echo"] }]);+ fixture.dispatch.mockClear();+ drag("cleo");+ laidOut("atlas", "bea", "cleo");+ section(BOTS_SECTION_ID).onDragOver(at(85) as never);+ expect(row("bea").botDrop).toBe("before");+ section(BOTS_SECTION_ID).onDragOver(at(170) as never);+ expect(rows().some((props) => props.botDrop)).toBe(false);+ });++ it("out of a department to the end of the main list, or a place in it", () => {+ drag("echo");+ section(BOTS_SECTION_ID).onDragOver(at() as never);+ expect(row("cleo").botDrop).toBe("after");+ section(BOTS_SECTION_ID).onDrop(at() as never);+ expect(actions()).toEqual([{ type: "updateBot", botId: "echo", patch: { section: "" } }]);+ expect(fixture.requests).toEqual([]);+ fixture.dispatch.mockClear();+ drag("dodo");+ row("bea").botDrag!.row("bea").onDrop(at(50) as never);+ expect(actions()).toEqual([{ type: "updateBot", botId: "dodo", patch: { section: "" } }, { type: "botsOrdered", botIds: ["atlas", "bea", "dodo", "cleo"] }]);+ });++ it("offers a place to drop it out when every row is in a department", () => {+ fixture.state = { ...fixture.state, bots: fixture.state.bots.map((candidate) => ({ ...candidate, section: "Work" })) };+ expect(sections()).not.toContain(BOTS_SECTION_ID);+ drag("dodo");+ expect(sections()[0]).toBe(BOTS_SECTION_ID);+ section(BOTS_SECTION_ID).onDragOver(at() as never);+ expect(render().some((node) => node.props["data-bot-drop-slot"] !== undefined)).toBe(true);+ section(BOTS_SECTION_ID).onDrop(at() as never);+ expect(actions()).toEqual([{ type: "updateBot", botId: "dodo", patch: { section: "" } }]);+ expect(sections()).not.toContain(BOTS_SECTION_ID);+ });++ it("never drops on group chats, and hands a heading's drag to the section order", () => {+ drag("atlas");+ const event = at();+ section(CHANNELS_SECTION_ID).onDragOver(event as never);+ expect(event.preventDefault).not.toHaveBeenCalled();+ section(CHANNELS_SECTION_ID).onDrop(event as never);+ expect(actions()).toEqual([]);+ expect(rows().every((props) => !props.botDragging)).toBe(true);+ });++ it("moves with Alt+Up/Down within its list and says where it went", () => {+ row("bea").botDrag!.step("bea", 1);+ expect(actions()).toEqual([{ type: "botsOrdered", botIds: ["atlas", "cleo", "bea"] }]);+ const live = render().find((node) => node.props["aria-live"] === "polite")!;+ expect(live.props.children).toBe("bea moved to position 3 of 3");+ fixture.dispatch.mockClear();+ row("atlas").botDrag!.step("atlas", -1);+ expect(actions()).toEqual([]);+ });++ it("works the same in Advanced, where the bots' list has a heading", () => {+ fixture.advanced = true;+ drag("dodo");+ row("atlas").botDrag!.row("atlas").onDrop(at() as never);+ expect(header(NEW_DEPARTMENT).naming!.value).toBe("New department");+ });+});++describe("a department's menu in Simple", () => {+ const openMenu = (name: string) => {+ const button = { getBoundingClientRect: () => ({ right: 280, bottom: 300 }), focus: vi.fn(), isConnected: true } as unknown as HTMLButtonElement;+ header(name).onMenu!(button);+ return render().find((node) => node.type === TeamMenuItems)!.props as unknown as Parameters<typeof TeamMenuItems>[0];+ };++ it("renames it in place", async () => {+ openMenu("Work").onRename();+ expect(render().some((node) => node.type === TeamDialog)).toBe(false);+ const naming = header("Work").naming!;+ expect([naming.value, naming.label]).toEqual(["Work", "Rename Work department"]);+ naming.onCommit("Clients");+ await vi.waitFor(() => expect(actions()).toEqual([{ type: "sections", sections: ["Clients"] }]));+ expect(fixture.requests).toEqual([{ path: "/api/sidebar-sections?section=Work", method: "PATCH", body: { name: "Clients" } }]);+ });++ it("deletes it saying the bots stay, out of any department", () => {+ openMenu("Work").onDelete();+ const dialog = render().find((node) => node.type === ConfirmDialog && node.props.open === true)!;+ expect(dialog.props.body).toBe("Its bots and group chats stay, with their conversations, outside any department. The department and its shared instructions are deleted. This cannot be undone.");+ });++ it("keeps Advanced's rename dialog", () => {+ fixture.advanced = true;+ const button = { getBoundingClientRect: () => ({ right: 280, bottom: 300 }), focus: vi.fn(), isConnected: true } as unknown as HTMLButtonElement;+ const work = render().find((node) => node.type === SidebarSectionHeader && (node.props as unknown as HeaderProps).name === "Work")!.props as unknown as HeaderProps;+ work.onContextMenu!({ preventDefault: () => {}, clientX: 10, clientY: 10, currentTarget: { querySelector: () => button } } as never);+ (render().find((node) => node.type === TeamMenuItems)!.props as unknown as Parameters<typeof TeamMenuItems>[0]).onRename();+ expect(render().some((node) => node.type === TeamDialog)).toBe(true);+ expect(header("Work").naming).toBeUndefined();+ });+});++describe("a bot's menu in Simple", () => {+ type MenuProps = Parameters<typeof BotContextMenu>[0];+ const menuProps = (botId: string, extra: Partial<MenuProps> = {}): MenuProps => ({+ menu: { botId, x: 0, y: 0 }, onClose: vi.fn(), onArchive: vi.fn(), onDelete: vi.fn(), onMoveToSection: vi.fn(),+ onNewFolder: vi.fn(), onNewTaskFolder: vi.fn(), onNewSection: vi.fn(), ...extra,+ });+ const open = (props: MenuProps) => {+ fixture.index = 0;+ const tree = nodes(BotContextMenu(props));+ const move = tree.find((node) => node.props["data-bot-menu-move"] !== undefined)!;+ (move.props.onClick as (event: { detail: number }) => void)({ detail: 1 });+ fixture.index = 0;+ const flyout = nodes(BotContextMenu(props)).find((node) => node.props["data-bot-menu-flyout"] === "move")!;+ return nodes(flyout.props.children).filter((node) => node.props.role === "menuitem");+ };+ const label = (node: ReactElement<Props>) => nodes(node.props.children).length+ ? Children.toArray(node.props.children).filter((part) => typeof part === "string").join("") : String(node.props.children);++ it("moves it to a department, a new one or out of one, from Move to department", () => {+ fixture.state = { ...fixture.state, sections: ["Work", "Home"] };+ const props = menuProps("dodo");+ const items = open(props);+ expect(items.map(label)).toEqual(["Work", "Home", "New department…", "Remove from department"]);+ expect(items[0]!.props.disabled).toBe(true);+ (items[1]!.props.onClick as () => void)();+ (items[3]!.props.onClick as () => void)();+ expect(actions()).toEqual([+ { type: "updateBot", botId: "dodo", patch: { section: "Home" } },+ { type: "updateBot", botId: "dodo", patch: { section: "" } },+ ]);+ (items[2]!.props.onClick as () => void)();+ expect(props.onNewSection).toHaveBeenCalledWith("dodo");+ });++ it("offers only New department… to a bot in none, when there are no departments yet", () => {+ fixture.state = { ...fixture.state, sections: [], bots: [bot("atlas"), bot("bea")] };+ expect(open(menuProps("atlas")).map(label)).toEqual(["New department…"]);+ });+});diff --git a/src/components/Sidebar.simple-layout.test.ts b/src/components/Sidebar.simple-layout.test.tsindex e7904a35bb..9f037f5091 100644--- a/src/components/Sidebar.simple-layout.test.ts+++ b/src/components/Sidebar.simple-layout.test.ts@@ -304,7 +304,7 @@ describe("Simple-mode sidebar layout", () => {expect(menu.props.className).toEqual(expect.stringContaining("left-full top-0"));expect(menu.props.className).toEqual(expect.stringContaining("rounded-[var(--radius-menu)]"));const item = (label: string) => nodes(top().props.children).find((node) => node.type === "button" && nodes(node.props.children).concat(node).some((part) => Children.toArray(part.props.children).includes(label)));- expect(item("Create department"), "Simple mode never asks the person to design a department").toBeUndefined();+ expect(item("Create department"), "Simple makes a department from its bots, by dragging one onto another or from a bot's menu").toBeUndefined();expect(item("New chat"), "a new conversation starts from the bot panel").toBeUndefined();expect(item("New bot")).toBeDefined();expect(item("New group chat")).toBeDefined();diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex a73e781ae9..421fa3161f 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -41,20 +41,7 @@ import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { draggedFolder, FOLDER_DRAG_TYPE, moveFolder, placeFolder } from "@/lib/folder-order";import { folderUnreadThreadIds, markFolderRead } from "@/lib/folder-read";import { HelperThreadGroup, orderedThreadList, partitionHelperThreads, SidebarThreadRow, stampClock, threadRecency, threadRowActions, useRelativeNow, useRevealedThreadRow, useSnoozeExpiry, visibleSidebarThreads } from "./SidebarThreadRow";-import {- loadCollapsedSections,- loadSectionOrder,- loadSidebarAttentionPinned,- saveCollapsedSections,- saveSectionOrder,- saveSidebarAttentionPinned,- setSidebarDensity,- toggleCollapsedSection,- useSidebarDensity,- usePinnedCircles,- useUniversalPins,- type SidebarDensity,-} from "@/lib/sidebar-preferences";+import { loadSidebarAttentionPinned, saveSidebarAttentionPinned, setSidebarDensity, useSidebarDensity, usePinnedCircles, useUniversalPins, type SidebarDensity } from "@/lib/sidebar-preferences";import {ATTENTION_SECTION_ID,BOT_CHATS_SECTION_ID,@@ -62,26 +49,19 @@ import {CHANNELS_SECTION_ID,PINNED_SECTION_ID,PINNED_THREADS_SECTION_ID,- SIMPLE_FIXED_SECTION_IDS,TOOLS_SECTION_ID,- keepFixedSectionSlots,- mergeSectionOrder,- moveSection,- orderedSidebarSections,partitionSidebarBots,partitionSidebarGroups,- placeSection,pinnedCircleThreadListVisible,- sameSectionOrder,- sidebarLayoutInteractive,- sidebarSectionCollapsed,sidebarSectionLabel,- simpleSidebarSections,userSectionId,userSectionName,withPrimaryTile,- type SectionDropPlace,} from "@/lib/sidebar-layout";+import { stepKey, type BotDropPlace } from "@/lib/sidebar-bot-drop";+import { BotDropLine, botRowDropClass, useSidebarBotDrag, type BotRowDrag } from "./SidebarBotDrag";+import { useSidebarSections } from "./SidebarSections";+import { departmentNames, moveBotsToSection } from "./bot-sections";import { sidebarSectionAttention } from "@/lib/sidebar-attention";import { botListItemPointerIntent } from "@/lib/sidebar-selection";import { SidebarFooter } from "./SidebarFooter";@@ -683,13 +663,16 @@ export interface BotRowProps {dispatch: Dispatch<Action>;onMenu: (menu: MenuState) => void;renameRequest?: number;+ botDrag?: BotRowDrag;+ botDrop?: BotDropPlace | null;+ botDragging?: boolean;}export function botRowProps(state: AppState,dispatch: Dispatch<Action>,bot: Bot,- layout: Pick<BotRowProps, "density" | "quiet" | "query" | "onMenu" | "renameRequest">,+ layout: Pick<BotRowProps, "density" | "quiet" | "query" | "onMenu" | "renameRequest" | "botDrag" | "botDrop" | "botDragging">,): BotRowProps {const selected = state.activeView === "chat" && state.selectedId === bot.id;const reveal = state.revealThread;@@ -716,7 +699,7 @@ export function useVisibleMessages(bot: Bot): Message[] {export const BotListItem = memo(function BotListItem(props: BotRowProps) {const advanced = useAdvancedMode();- const { bot, selected, deleting, mascotMotion, reveal, pendingQueued, instances, liveCall, density, quiet, query, dispatch, onMenu, renameRequest } = props;+ const { bot, selected, deleting, mascotMotion, reveal, pendingQueued, instances, liveCall, density, quiet, query, dispatch, onMenu, renameRequest, botDrag: drag, botDrop: drop, botDragging: dragging } = props;const showThreads = useShowThreads();const liveMedia = useLiveMedia();const remoteClient = typeof window !== "undefined" && window.ogb?.remoteClient?.active === true;@@ -880,7 +863,8 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {return (<>- <div className={cn("group relative", railTile && "mx-auto w-[54px]")} title={railTile ? botTooltip(bot, instances) : iconOnly ? [bot.name, bot.title?.trim()].filter(Boolean).join(" · ") : undefined}>+ <div className={cn("group relative", railTile && "mx-auto w-[54px]", botRowDropClass(drop, dragging))} data-bot-drop={drop ?? undefined} {...(drag && !renaming ? drag.row(bot.id) : {})}+ title={railTile ? botTooltip(bot, instances) : iconOnly ? [bot.name, bot.title?.trim()].filter(Boolean).join(" · ") : undefined}><BotDropLine place={drop} />{/* Keep this wrapper mounted: replacing it remounts RenameTitle and leaves the row stuck in rename mode. */}<divrole={renaming ? undefined : "button"}@@ -892,13 +876,14 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {: `${bot.name}${bot.title?.trim() ? ` · ${bot.title.trim()}` : ""}${bot.chiefOfStaff ? ` · ${t("sidebar.bot.chiefOfStaff")}` : ""}${onLiveCall ? ` · ${t("call.live.badge")}` : ""}${waiting ? ` · ${t("sidebar.preview.waiting")}` : working ? ` · ${t("chat.activity.working")}` : teammateWait ? ` · ${t("sidebar.preview.waitingOnTeammate")}` : queued ? ` · ${t("task.queued")}` : ""}${unread ? ` · ${t("task.unread")}` : ""}`: undefined}- aria-busy={deleting || undefined}+ aria-busy={deleting || undefined} aria-keyshortcuts={drag ? "Alt+ArrowUp Alt+ArrowDown" : undefined}aria-current={selected && !expanded && !renaming ? "page" : undefined}data-sidebar-bot-row={bot.id}title={renaming ? undefined : tooltip}onClick={onSelect}onKeyDown={(event) => {if (renaming) return;+ if (drag && stepKey(event)) { event.preventDefault(); drag.step(bot.id, stepKey(event)!); return; }if (event.key === "Enter" || event.key === " ") {event.preventDefault();openBot(dispatch, bot, showThreads);@@ -986,16 +971,6 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {teamMenuReturn.current = returnTo;setTeamMenu({ name, x: Math.max(8, Math.min(x, window.innerWidth - 266)), y: Math.max(8, Math.min(y, window.innerHeight - 190)) });};- const renamedTeam = (oldName: string, newName: string) => {- const replace = (ids: string[]) => [...new Set(ids.map(id => id === userSectionId(oldName) ? userSectionId(newName) : id))];- setCollapsedSections(current => { const next = replace(current); saveCollapsedSections(next); return next; });- setSectionOrder(current => { const next = replace(current); saveSectionOrder(next); return next; });- requestAnimationFrame(() => {- const header = [...(sidebarRef.current?.querySelectorAll<HTMLElement>("[data-section]") ?? [])]- .find(element => element.dataset.section === newName);- (header?.querySelector<HTMLElement>("button") ?? header ?? sidebarRef.current)?.focus();- });- };const [deletingTeam, setDeletingTeam] = useState<string | null>(null);const [teamDeletePending, setTeamDeletePending] = useState(false);const teamDeleteRunning = useRef(false);@@ -1048,15 +1023,6 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {const universalPins = useUniversalPins();const [pinnedCircleThreadsCollapsed, setPinnedCircleThreadsCollapsed] = useState(true);const quietRows = density === "compact";- const [collapsedSections, setCollapsedSections] = useState<string[]>(() => loadCollapsedSections());- const [sectionOrder, setSectionOrder] = useState<string[]>(() => loadSectionOrder());- const [draggingSectionId, setDraggingSectionId] = useState<string | null>(null);- const [dropTarget, setDropTarget] = useState<{ id: string; place: SectionDropPlace } | null>(null);- const [reorderAnnouncement, setReorderAnnouncement] = useState("");- const sectionDragRef = useRef<{- from: string | null;- over: { id: string; place: SectionDropPlace } | null;- }>({ from: null, over: null });useEffect(() => {if (density !== "icons") setLastExpandedDensity(density);@@ -1143,6 +1109,9 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {: undefined;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() });const matchingBots = state.bots.filter((b) => !b.hidden)@@ -1157,7 +1126,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {);const visibleGroups = state.groups.filter((g) => !q || g.name.toLowerCase().includes(q) || g.tasks?.some((task) => task.title.toLowerCase().includes(q)));const viewerEmail = useViewerEmail();- const parts = partitionSidebarBots(matchingBots, { universalPins, viewerEmail, welcoming: useWelcomingBot() });+ const parts = partitionSidebarBots(botDrag.preview(matchingBots), { universalPins, viewerEmail, welcoming: useWelcomingBot() });const {primary,unsectionedChief,@@ -1168,7 +1137,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {} = simpleDesk ? withPrimaryTile(parts, myDefaultBot(state.bots, viewerEmail)?.id) : { ...parts, primary: null };const { botChats, sectionedRooms, unsectionedRooms } = partitionSidebarGroups(visibleGroups);- const sectionNames: string[] = (state.sections ?? []).filter((name) => !q || name.toLowerCase().includes(q.toLowerCase()));+ const sectionNames: string[] = [...(state.sections ?? []).filter((name) => !q || name.toLowerCase().includes(q.toLowerCase())), ...botDrag.pending];for (const bot of sectionedBots) {if (!sectionNames.includes(bot.section!)) sectionNames.push(bot.section!);}@@ -1178,91 +1147,25 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {for (const group of sectionedRooms) {if (!sectionNames.includes(group.section!)) sectionNames.push(group.section!);}+ const drops = botDrag.arrange({ enabled: sections.interactive && !phone, main: unsectionedBots, sectioned: sectionedBots, departments: sectionNames, bots: state.bots, taken: departmentNames(state) });const naturalSectionIds = [...(pinnedBots.length > 0 && !universalPins && !simpleDesk ? [PINNED_SECTION_ID] : []),...(unsectionedRooms.length > 0 ? [CHANNELS_SECTION_ID] : []),...(botChats.length > 0 ? [BOT_CHATS_SECTION_ID] : []),- ...(unsectionedBots.length > 0 ? [BOTS_SECTION_ID] : []),+ ...(unsectionedBots.length > 0 || drops.slot ? [BOTS_SECTION_ID] : []),...sectionNames.map(userSectionId),];- const orderedIds = orderedSidebarSections(naturalSectionIds, sectionOrder);- const sectionIds = simple || rail ? simpleSidebarSections(orderedIds) : orderedIds;- const reorderableIds = simple ? sectionIds.filter((id) => !SIMPLE_FIXED_SECTION_IDS.includes(id)) : sectionIds;+ const layout = sections.arrange(naturalSectionIds);+ const sectionIds = layout.sectionIds;const showPinnedCircleThreads = !simpleDesk && pinnedCircleThreadListVisible(pinnedCircles, density, pinnedBots.length);const tiles = simpleDesk && (primary !== null || pinnedBots.length > 0);- const layoutInteractive = sidebarLayoutInteractive(density, q);- const sectionCollapsed = (id: string) =>- sidebarSectionCollapsed(id, collapsedSections, density, q);-- const toggleSection = (id: string) => {- if (!layoutInteractive) return;- const next = toggleCollapsedSection(collapsedSections, id);- setCollapsedSections(next);- saveCollapsedSections(next);- };-- const commitSectionOrder = (visibleOrder: string[]) => {- if (!layoutInteractive) return;- const next = mergeSectionOrder(sectionOrder, visibleOrder);- if (sameSectionOrder(next, sectionOrder)) return;- setSectionOrder(next);- saveSectionOrder(next);- };-- const announceSectionPosition = (id: string, visibleOrder: string[]) => {- const position = visibleOrder.indexOf(id);- if (position < 0) return;- setReorderAnnouncement(- t("sidebar.section.moved", {- name: sectionLabel(id),- position: position + 1,- count: visibleOrder.length,- }),- );- };-- const reorderSections = (id: string, moved: string[]) => {- const next = simple ? simpleSidebarSections(moved) : moved;- if (sameSectionOrder(next, sectionIds)) return;- commitSectionOrder(simple ? keepFixedSectionSlots(orderedIds, next) : next);- announceSectionPosition(id, next);- };- const moveSidebarSection = (id: string, direction: -1 | 1) => reorderSections(id, moveSection(sectionIds, id, direction));-- const resetSectionDrag = () => {- sectionDragRef.current = { from: null, over: null };- setDraggingSectionId(null);- setDropTarget(null);- };-- const updateSectionDropTarget = (event: React.DragEvent<HTMLDivElement>, id: string) => {- if (!layoutInteractive || !sectionDragRef.current.from) return;- event.preventDefault();- event.dataTransfer.dropEffect = "move";- const rect = event.currentTarget.getBoundingClientRect();- const place: SectionDropPlace = event.clientY < rect.top + rect.height / 2 ? "before" : "after";- const next = { id, place };- sectionDragRef.current.over = next;- setDropTarget(next);- };-- const dropSection = (event: React.DragEvent<HTMLDivElement>) => {- if (event.dataTransfer.types.includes(FOLDER_DRAG_TYPE)) return;- event.preventDefault();- const from =- event.dataTransfer.getData("application/x-openmausbot-sidebar-section") ||- event.dataTransfer.getData("text/plain") ||- sectionDragRef.current.from;- const over = sectionDragRef.current.over;- if (from && over) reorderSections(from, placeSection(sectionIds, from, over.id, over.place));- resetSectionDrag();- };+ const { interactive: layoutInteractive, collapsed: sectionCollapsed, toggle: toggleSection } = sections;const archivedBots = state.bots.filter((bot) => bot.hidden && !bot.movedTo);const archivedEntry = remoteClient ? undefined : { count: archivedBots.length, open: () => setArchivedBotsOpen(true) };const attention = crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups);const pinnedThreads = crossBotPinnedThreads(state.bots, state.groups, state.pendingQueued);const pendingBotUndo = teamFeedback?.restoreBot;- const botRow = (bot: Bot) => botRowProps(state, dispatch, bot, { density, quiet: quietRows, query: q, onMenu: setMenu, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0 });+ const botRow = (bot: Bot) => botRowProps(state, dispatch, bot, { density, quiet: quietRows, query: q, onMenu: setMenu, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });const railSearch = () => {if (collapseToIcons) return openCommandPalette();setSearchOpen(true);@@ -1613,8 +1516,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<divkey={id}data-sidebar-section-id={id}- onDragOver={(event) => updateSectionDropTarget(event, id)}- onDrop={dropSection}+ {...drops.zone(id, layout.zone(id))}className={cn("flex flex-col",advanced || simpleDesk ? "gap-0.5" : "gap-1",@@ -1622,9 +1524,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {)}>{rail && index > 0 && <SidebarRailSeparator />}- {dropTarget?.id === id && dropTarget.place === "before" && draggingSectionId !== id && (- <div className="mx-2 h-0.5 rounded-full bg-accent" />- )}+ {layout.dropLine(id, "before")}{density !== "icons" && !headless && (<SidebarSectionHeadername={sectionLabel(id)}@@ -1643,17 +1543,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {collapsed={collapsed}attention={attention}onToggle={layoutInteractive ? () => toggleSection(id) : undefined}- reorderable={layoutInteractive && reorderableIds.length > 1 && reorderableIds.includes(id)}- dragging={draggingSectionId === id}- onDragStart={(event) => {- event.dataTransfer.effectAllowed = "move";- event.dataTransfer.setData("application/x-openmausbot-sidebar-section", id);- event.dataTransfer.setData("text/plain", id);- sectionDragRef.current = { from: id, over: null };- setDraggingSectionId(id);- }}- onDragEnd={resetSectionDrag}- onMove={(direction) => moveSidebarSection(id, direction)}+ {...layout.header(id)} naming={drops.naming(sectionName)} dropInto={drops.into(sectionName)}onDelete={!simple && !remoteClient && sectionName ? () => setDeletingTeam(sectionName) : undefined}/>)}@@ -1662,6 +1552,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {className="mx-3 mb-1 inline-flex h-7 items-center self-start rounded-full bg-raised/50 px-3 text-[13px] font-medium leading-4 text-ink-secondary hover:text-ink">{t("task.queued")} · {queued.length}</button>}{!collapsed && (<>+ {id === BOTS_SECTION_ID && drops.slot}{sectionChiefItems.map((bot) => <BotListItem key={bot.id} {...botRow(bot)} />)}{sectionGroupItems.map((group) => (<GroupListItem@@ -1682,7 +1573,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {listItem={BotListItem}/>) : sectionBotItems.map((bot) => <BotListItem key={bot.id} {...botRow(bot)} />)}- {!remoteClient && sectionName && layoutInteractive && (!simple || sectionChiefItems.length + sectionGroupItems.length + sectionBotItems.length === 0) && (+ {!remoteClient && sectionName && layoutInteractive && !drops.naming(sectionName) && (!simple || sectionChiefItems.length + sectionGroupItems.length + sectionBotItems.length === 0) && (<button onClick={() => setMoveToTeam(sectionName)} aria-label={t(state.bots.some(bot => !bot.hidden && bot.section?.trim() === sectionName) ? "team.manageBotsIn" : "team.addBotsTo", { name: sectionName })}className="mx-3 my-1 flex items-center gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"><Plus size={13} /> {t(state.bots.some(bot => !bot.hidden && bot.section?.trim() === sectionName) ? "team.manageBots" : "team.addBots")}@@ -1690,9 +1581,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {)}</>)}- {dropTarget?.id === id && dropTarget.place === "after" && draggingSectionId !== id && (- <div className="mx-2 h-0.5 rounded-full bg-accent" />- )}+ {layout.dropLine(id, "after")}</div>);})}@@ -1708,7 +1597,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {</div></GlassScroller><p className="sr-only" aria-live="polite" aria-atomic="true">- {reorderAnnouncement}+ {sections.announcement}</p><GlassBar edge="bottom">@@ -1737,6 +1626,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {onNewFolder={setNewFolderBotId}onNewTaskFolder={setNewTaskFolderBotId}onRename={(botId) => setRenameRequest((current) => ({ botId, nonce: (current?.nonce ?? 0) + 1 }))}+ onNewSection={density === "icons" ? undefined : (botId) => botDrag.startNew([botId])}/>{showThreads && newFolderBotId && state.bots.find((bot) => bot.id === newFolderBotId) && <BotProjectDialog bot={state.bots.find((bot) => bot.id === newFolderBotId)!} onClose={() => setNewFolderBotId(null)} />}{showThreads && newTaskFolderBot && <NewTaskFolderDialog bot={newTaskFolderBot} onClose={() => setNewTaskFolderBotId(null)} onReturnFocus={() => {@@ -1758,7 +1648,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {/><OwnerPickerHost />{newTeam && <TeamDialog onClose={() => setNewTeam(false)} />}- {renameTeam && <TeamDialog section={renameTeam} rename onRenamed={renamedTeam} onClose={() => setRenameTeam(null)} />}+ {renameTeam && <TeamDialog section={renameTeam} rename onRenamed={sections.renamed} onClose={() => setRenameTeam(null)} />}{teamMotion.shown && teamMotion.value && createPortal(<div className={cn("fixed inset-0 z-40", teamMotion.closing && "pointer-events-none")} onMouseDown={closeTeamMenu}><div role="menu" aria-label={teamMotion.value.name} style={{ left: teamMotion.value.x, top: teamMotion.value.y }}className={cn("absolute w-[256px] text-ink", MENU_SHEET, teamMotion.className)} {...teamMotion.exitProps}@@ -1768,7 +1658,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {}}><TeamMenuItemsonAddBots={() => { closeTeamMenu(); setMoveToTeam(teamMotion.value!.name); }}- onRename={() => { closeTeamMenu(); setRenameTeam(teamMotion.value!.name); }}+ onRename={() => { closeTeamMenu(); (advanced ? setRenameTeam : botDrag.startRename)(teamMotion.value!.name); }}onShare={() => { closeTeamMenu(); setShareTeam(teamMotion.value!.name); }}onDelete={() => { closeTeamMenu(); setDeletingTeam(teamMotion.value!.name); }}onSetForAll={teamSettingsAllowed === true ? () => { closeTeamMenu(); setTeamSettings(teamMotion.value!.name); } : undefined}@@ -1777,7 +1667,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {</div></div>, document.body)}<ConfirmDialog open={deletingTeam !== null} title={t("team.deleteTitle", { name: deletingTeam ?? "" })}- body={t("team.deleteKeepBotsDescription")} confirmLabel={t("team.delete")} returnFocusRef={sidebarRef}+ body={t(advanced ? "team.deleteKeepBotsDescription" : "team.deleteKeepBotsSimple")} confirmLabel={t("team.delete")} returnFocusRef={sidebarRef}pending={teamDeletePending}onCancel={() => { if (!teamDeleteRunning.current) setDeletingTeam(null); }} onConfirm={() => {const name = deletingTeam;@@ -1796,19 +1686,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {current={sectionPicker ? state.bots.find((b) => b.id === sectionPicker.botId)?.section : undefined}anchor={sectionPicker}onClose={() => setSectionPicker(null)}- onAssign={(section) => {- if (!sectionPicker) return;- if (!remoteClient) {- dispatch({ type: "updateBot", botId: sectionPicker.botId, patch: { section } });- return;- }- void api("/api/sidebar-sections", {- method: "POST",- body: JSON.stringify({ name: section, botIds: [sectionPicker.botId] }),- })- .then(({ bots }) => bots.forEach((bot: Bot) => dispatch({ type: "botPatched", bot })))- .catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }));- }}+ onAssign={(section) => { if (sectionPicker) moveBotsToSection(dispatch, [sectionPicker.botId], section); }}/><RoomContextMenumenu={roomMenu}diff --git a/src/components/SidebarBotDrag.tsx b/src/components/SidebarBotDrag.tsxnew file mode 100644index 0000000000..3cd768aaf4--- /dev/null+++ b/src/components/SidebarBotDrag.tsx@@ -0,0 +1,200 @@+import { useRef, useState, type Dispatch, type DragEvent } from "react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { nextRename } from "@/lib/rename";+import { BOTS_SECTION_ID, userSectionName } from "@/lib/sidebar-layout";+import { BOT_ROW_DRAG_TYPE, botDropPlace, botListOf, planBotDrop, sameBotDrop, stepBot, unusedName, type BotDrop, type BotDropPlace, type BotMove } from "@/lib/sidebar-bot-drop";+import type { Action, Bot } from "@/state/store";+import { moveBotsToSection, renameDepartment, saveBotOrder } from "./bot-sections";++/** The department being named, before it exists. The server trims names and never keeps a control character. */+export const NEW_DEPARTMENT = "\u0000new";++type DropHandlers = { onDragOver: (event: DragEvent<HTMLElement>) => void; onDrop: (event: DragEvent<HTMLElement>) => void };++export type BotRowDrag = {+ row(botId: string): DropHandlers & { draggable: true; onDragStart: (event: DragEvent<HTMLElement>) => void; onDragEnd: () => void };+ step(botId: string, direction: -1 | 1): void;+};++export type SectionNaming = { value: string; label: string; onCommit: (name: string) => void; onCancel: () => void };++type Naming = { kind: "new"; botIds: string[]; name: string } | { kind: "rename"; section: string };++type Arranged = { enabled: boolean; lists: Map<string, string[]>; bots: Bot[]; taken: string[] };++const carries = (event: DragEvent<HTMLElement>) => event.dataTransfer.types.includes(BOT_ROW_DRAG_TYPE);+const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));++export function botRowDropClass(drop: BotDropPlace | null | undefined, dragging: boolean | undefined): string {+ return cn(dragging && "opacity-40", drop === "group" && "rounded-[10px] bg-accent/10 outline outline-2 -outline-offset-2 outline-accent/70");+}++export function BotDropLine({ place }: { place: BotDropPlace | null | undefined }) {+ if (place !== "before" && place !== "after") return null;+ return <span aria-hidden="true" className={cn("pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded-full bg-accent", place === "before" ? "-top-[2px]" : "-bottom-[2px]")} />;+}++/** Dragging bots between the rows outside any department and each department's, onto a bot to start a department,+ * Alt+Up/Down, and the name field a new or renamed department shows in its heading. */+export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onError, onCancelled }: {+ dispatch: Dispatch<Action>;+ announce: (text: string) => void;+ onNamed: (name: string) => void;+ onRenamed: (from: string, to: string) => void;+ onError: (message: string) => void;+ onCancelled: () => void;+}) {+ const [dragging, setDragging] = useState<string | null>(null);+ const [drop, setDrop] = useState<BotDrop | null>(null);+ const [naming, setNaming] = useState<Naming | null>(null);+ const latest = useRef<Arranged>({ enabled: false, lists: new Map(), bots: [], taken: [] });+ const moving = useRef<{ botId: string | null; drop: BotDrop | null }>({ botId: null, drop: null });+ const controller = useRef<BotRowDrag | null>(null);+ const actions = useRef({ dispatch, announce });+ actions.current = { dispatch, announce };++ const show = (next: BotDrop | null) => {+ if (sameBotDrop(moving.current.drop, next)) return;+ moving.current.drop = next;+ setDrop(next);+ };+ const end = () => {+ moving.current = { botId: null, drop: null };+ setDragging(null);+ setDrop(null);+ };+ const startNew = (botIds: string[]) => setNaming({ kind: "new", botIds, name: unusedName(t("sidebar.section.newName"), latest.current.taken) });+ const apply = (botId: string, move: BotMove, keyboard: boolean) => {+ if (move.kind === "group") return startNew(move.botIds);+ const { lists, bots } = latest.current;+ if (botListOf(lists, botId) !== move.section) moveBotsToSection(actions.current.dispatch, [botId], move.section);+ saveBotOrder(actions.current.dispatch, bots, move.order);+ if (!keyboard) return;+ const name = bots.find((bot) => bot.id === botId)?.name ?? "";+ actions.current.announce(t("sidebar.section.moved", { name, position: move.order.indexOf(botId) + 1, count: move.order.length }));+ requestAnimationFrame(() => document.querySelector<HTMLElement>(`[data-sidebar-bot-row="${CSS.escape(botId)}"]`)?.focus());+ };+ const finish = (target: BotDrop | null) => {+ const botId = moving.current.botId;+ end();+ const move = botId && target ? planBotDrop(latest.current.lists, botId, target) : null;+ if (botId && move) apply(botId, move, false);+ };+ const rowDrop = (event: DragEvent<HTMLElement>, botId: string): BotDrop => {+ const box = event.currentTarget.getBoundingClientRect();+ return { kind: "row", botId, place: botDropPlace(event.clientY - box.top, box.height, botListOf(latest.current.lists, botId) === "") };+ };++ controller.current ??= {+ row: (botId) => ({+ draggable: true,+ onDragStart: (event) => {+ if (!latest.current.enabled || botListOf(latest.current.lists, botId) === undefined) return;+ event.stopPropagation();+ event.dataTransfer.effectAllowed = "move";+ event.dataTransfer.setData(BOT_ROW_DRAG_TYPE, botId);+ moving.current = { botId, drop: null };+ setDragging(botId);+ },+ onDragEnd: end,+ onDragOver: (event) => {+ if (!carries(event) || !moving.current.botId) return;+ event.preventDefault();+ event.stopPropagation();+ event.dataTransfer.dropEffect = "move";+ show(botId === moving.current.botId ? null : rowDrop(event, botId));+ },+ onDrop: (event) => {+ if (!carries(event)) return;+ event.preventDefault();+ event.stopPropagation();+ finish(botId === moving.current.botId ? null : rowDrop(event, botId));+ },+ }),+ step: (botId, direction) => {+ const move = latest.current.enabled ? stepBot(latest.current.lists, botId, direction) : null;+ if (move) apply(botId, move, true);+ },+ };++ const finishNaming = (current: Naming, draft: string) => {+ setNaming(null);+ if (current.kind === "new") {+ const name = draft.trim() || current.name;+ moveBotsToSection(dispatch, current.botIds.filter((id) => latest.current.bots.some((bot) => bot.id === id && !bot.hidden)), name);+ onNamed(name);+ return;+ }+ const to = nextRename(current.section, draft);+ if (to) renameDepartment(dispatch, current.section, to).then(() => onRenamed(current.section, to), (cause) => onError(failure(cause)));+ };++ return {+ pending: naming?.kind === "new" ? [NEW_DEPARTMENT] : [],+ preview: <T extends Bot>(bots: T[]): T[] => naming?.kind === "new" ? bots.map((bot) => (naming.botIds.includes(bot.id) ? { ...bot, section: NEW_DEPARTMENT } : bot)) : bots,+ startNew: (botIds: string[]) => startNew(botIds),+ startRename: (section: string) => setNaming({ kind: "rename", section }),+ arrange({ enabled, main, sectioned, departments, bots, taken }: {+ enabled: boolean; main: Bot[]; sectioned: Bot[]; departments: string[]; bots: Bot[]; taken: string[];+ }) {+ const lists = new Map<string, string[]>([["", main.map((bot) => bot.id)]]);+ for (const name of departments) if (name !== NEW_DEPARTMENT) lists.set(name, sectioned.filter((bot) => bot.section === name).map((bot) => bot.id));+ latest.current = { enabled, lists, bots, taken };+ const active = enabled && dragging !== null && botListOf(lists, dragging) !== undefined ? dragging : null;+ const shown = active ? drop : null;+ const mainIds = lists.get("")!.filter((id) => id !== active);+ const listFor = (sectionId: string) => (sectionId === BOTS_SECTION_ID ? "" : userSectionName(sectionId));+ // Between rows, or under the last one, the nearest row places the bot; a department's heading takes it in.+ const zoneDrop = (event: DragEvent<HTMLElement>, list: string): BotDrop => {+ const ids = lists.get(list)!;+ const rows = [...event.currentTarget.querySelectorAll<HTMLElement>("[data-sidebar-bot-row]")]+ .filter((element) => ids.includes(element.dataset.sidebarBotRow ?? "")).map((element) => ({ botId: element.dataset.sidebarBotRow!, box: element.getBoundingClientRect() }));+ if (!rows.length || (list !== "" && event.clientY < rows[0]!.box.top)) return { kind: "end", list };+ const row = rows.find(({ box }) => event.clientY < box.bottom) ?? rows.at(-1)!;+ return { kind: "row", botId: row.botId, place: event.clientY < row.box.top + row.box.height / 2 ? "before" : "after" };+ };+ return {+ row: (botId: string): { botDrag?: BotRowDrag; botDrop?: BotDropPlace | null; botDragging?: boolean } => {+ if (!enabled || botListOf(lists, botId) === undefined) return {};+ const place = shown?.kind === "row" && shown.botId === botId ? shown.place+ : shown?.kind === "end" && shown.list === "" && botId === mainIds.at(-1) ? "after" : null;+ return { botDrag: controller.current!, botDrop: place, botDragging: active === botId };+ },+ into: (name: string | null) => shown?.kind === "end" && name !== null && name !== "" && shown.list === name,+ zone: (sectionId: string, fallback: DropHandlers): DropHandlers => ({+ onDragOver: (event) => {+ if (!carries(event)) return fallback.onDragOver(event);+ const list = listFor(sectionId);+ if (!moving.current.botId || list === null || !lists.has(list)) return show(null);+ event.preventDefault();+ event.dataTransfer.dropEffect = "move";+ const target = zoneDrop(event, list);+ show(target.kind === "row" && target.botId === moving.current.botId ? null : target);+ },+ onDrop: (event) => {+ if (!carries(event)) return fallback.onDrop(event);+ event.preventDefault();+ const list = listFor(sectionId);+ finish(list !== null && lists.has(list) ? zoneDrop(event, list) : null);+ },+ }),+ slot: active !== null && mainIds.length === 0 && botListOf(lists, active) !== ""+ ? <div data-bot-drop-slot="" className={cn("mx-2 flex h-10 items-center justify-center rounded-[10px] border border-dashed text-[13px] leading-[18px]",+ shown?.kind === "end" && shown.list === "" ? "border-accent bg-accent/10 text-ink" : "border-ink/20 text-ink-secondary")}>{t("sidebar.section.removeFromDepartment")}</div>+ : null,+ naming: (name: string | null): SectionNaming | undefined => {+ if (!naming || name === null) return undefined;+ const value = naming.kind === "new" ? (name === NEW_DEPARTMENT ? naming.name : null) : (name === naming.section ? naming.section : null);+ if (value === null) return undefined;+ return {+ value,+ label: naming.kind === "new" ? t("sidebar.section.newContextAria") : t("team.renameAria", { name }),+ onCommit: (draft) => finishNaming(naming, draft),+ onCancel: () => { setNaming(null); onCancelled(); },+ };+ },+ };+ },+ };+}diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsxindex 53e110c91e..42fdf2aab5 100644--- a/src/components/SidebarBotMenu.tsx+++ b/src/components/SidebarBotMenu.tsx@@ -1,6 +1,6 @@import { useEffect, useLayoutEffect, useRef, useState } from "react";import { createPortal } from "react-dom";-import { Archive, BellDot, CheckCheck, ChevronRight, ClipboardCopy, Copy, Crown, FolderOpen, FolderPlus, Loader2, MoreHorizontal, Pencil, Pin, PinOff, SquarePen, Trash2, Users } from "lucide-react";+import { Archive, BellDot, Check, CheckCheck, ChevronRight, ClipboardCopy, Copy, Crown, FolderMinus, FolderOpen, FolderPlus, Loader2, MoreHorizontal, Pencil, Pin, PinOff, SquarePen, Trash2, Users } from "lucide-react";import { api, useStore, openBot, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { useHeldMenuMotion } from "./MenuMotion";@@ -20,6 +20,9 @@ import { submenuIntent, type SubmenuIntent } from "@/lib/submenu-intent";import { useAdvancedMode } from "@/lib/interface-mode";import { useMoveToTeam } from "./MoveToTeam";import type { MenuState } from "./Sidebar";+import { departmentNames, moveBotsToSection } from "./bot-sections";++type Flyout = "more" | "move";export function BotContextMenu({menu,@@ -30,6 +33,7 @@ export function BotContextMenu({onNewFolder,onNewTaskFolder,onRename,+ onNewSection,}: {menu: MenuState | null;onClose: () => void;@@ -39,20 +43,25 @@ export function BotContextMenu({onNewFolder: (botId: string) => void;onNewTaskFolder: (botId: string) => void;onRename?: (botId: string) => void;+ /** Simple: "New department…" names a department in the sidebar, with this bot in it. */+ onNewSection?: (botId: string) => void;}) {const motion = useHeldMenuMotion(menu);const simpleMenu = !useAdvancedMode();const moreRef = useRef<HTMLButtonElement>(null);+ const moveRef = useRef<HTMLButtonElement>(null);const flyoutRef = useRef<HTMLDivElement>(null);const hoveredRow = useRef<Element | null>(null);- const [moreOpen, setMoreOpen] = useState(false);+ const [flyout, setFlyout] = useState<Flyout | null>(null);const [moreEngaged, setMoreEngaged] = useState(false);const moreIntent = useRef<SubmenuIntent | null>(null);moreIntent.current ??= submenuIntent({- open: () => setMoreOpen(true),- close: () => { setMoreOpen(false); setMoreEngaged(false); },+ open: (key) => setFlyout(key as Flyout),+ close: () => { setFlyout(null); setMoreEngaged(false); },submenuBox: () => flyoutRef.current?.getBoundingClientRect() ?? null,});+ const flyoutRow = (key: Flyout | null) => (key === "more" ? moreRef.current : key === "move" ? moveRef.current : null);+ const rowFlyout = (row: Element | null): Flyout | null => (row && row === moreRef.current ? "more" : row && row === moveRef.current ? "move" : null);const more = moreIntent.current;const shown = motion.value;const { state, dispatch } = useStore();@@ -124,16 +133,16 @@ export function BotContextMenu({useEffect(() => {moreIntent.current?.reset();hoveredRow.current = null;- setMoreOpen(false);+ setFlyout(null);setMoreEngaged(false);}, [menu]);useEffect(() => () => moreIntent.current?.reset(), []);useLayoutEffect(() => {- const flyout = flyoutRef.current, row = moreRef.current, sheet = menuRef.current;- if (!moreOpen || !flyout || !row || !sheet) return;- const place = submenuPosition(sheet.getBoundingClientRect(), row.getBoundingClientRect(), { width: flyout.offsetWidth, height: flyout.offsetHeight }, { width: window.innerWidth, height: window.innerHeight });- flyout.style.left = `${place.left}px`;- flyout.style.top = `${place.top}px`;+ const sheetOut = flyoutRef.current, row = flyoutRow(flyout), sheet = menuRef.current;+ if (!sheetOut || !row || !sheet) return;+ const place = submenuPosition(sheet.getBoundingClientRect(), row.getBoundingClientRect(), { width: sheetOut.offsetWidth, height: sheetOut.offsetHeight }, { width: window.innerWidth, height: window.innerHeight });+ sheetOut.style.left = `${place.left}px`;+ sheetOut.style.top = `${place.top}px`;});if (!motion.shown || !bot || !shown) return <>{clearThreads.dialog}{moveToTeam.dialog}</>;@@ -180,12 +189,46 @@ export function BotContextMenu({const divider = (key: string) => <div key={key} role="separator" className={MENU_ITEM_SEPARATOR} />;if (simpleMenu) {- const showMore = (focus: boolean) => {- more.openNow("more");+ const showFlyout = (key: Flyout, focus: boolean) => {+ more.openNow(key);if (focus) requestAnimationFrame(() => flyoutRef.current?.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus());};const copyId = item(<ClipboardCopy size={16} className="text-ink-secondary" />, t("sidebar.copyConversationId"), () => { void copyText(bot.threadId); });- const moveToSection = item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"), () => { onClose(); onMoveToSection(bot.id); });+ const current = bot.section?.trim() ?? "";+ const departments = departmentNames(state);+ const moveItems = [+ ...departments.map((name) => item(+ <span className="flex size-4 shrink-0 items-center justify-center">{name === current && <Check size={15} className="text-accent" />}</span>,+ name, () => moveBotsToSection(dispatch, [bot.id], name), { disabled: name === current },+ )),+ ...(departments.length ? [divider("move-new")] : []),+ ...(onNewSection ? [item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.section.newContext"), () => onNewSection(bot.id))] : []),+ ...(current ? [item(<FolderMinus size={16} className="text-ink-secondary" />, t("sidebar.section.removeFromDepartment"), () => moveBotsToSection(dispatch, [bot.id], ""))] : []),+ ];+ const flyoutButton = (key: Flyout, ref: React.RefObject<HTMLButtonElement | null>, icon: React.ReactNode, label: string) => (+ <button+ key={key}+ ref={ref}+ type="button"+ role="menuitem"+ data-bot-menu-more={key === "more" ? "" : undefined}+ data-bot-menu-move={key === "move" ? "" : undefined}+ aria-haspopup="menu"+ aria-expanded={flyout === key}+ onClick={(event) => (flyout === key ? more.closeNow() : showFlyout(key, event.detail === 0))}+ onKeyDown={(event) => {+ if (event.key !== "ArrowRight") return;+ event.preventDefault();+ showFlyout(key, true);+ }}+ className={cn(MENU_ITEM, "text-ink hover:bg-menu-hover", flyout === key && moreEngaged && "bg-menu-active")}+ >+ {icon}+ <span className="flex-1">{label}</span>+ <ChevronRight size={15} aria-hidden="true" className="text-ink-secondary rtl:-scale-x-100" />+ </button>+ );+ const moveToSection = flyoutButton("move", moveRef, <FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"));const rename = onRename && item(<SquarePen size={16} className="text-ink-secondary" />, t("sidebar.bot.rename"), () => onRename(bot.id));const editProfile = item(<Pencil size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.editProfile"), () => {openForSettings();@@ -214,28 +257,7 @@ export function BotContextMenu({...moveToTeam.items(bot, item),...deleteAll,];- const moreRow = (- <button- key="more"- ref={moreRef}- type="button"- role="menuitem"- data-bot-menu-more=""- aria-haspopup="menu"- aria-expanded={moreOpen}- onClick={(event) => (moreOpen ? more.closeNow() : showMore(event.detail === 0))}- onKeyDown={(event) => {- if (event.key !== "ArrowRight") return;- event.preventDefault();- showMore(true);- }}- className={cn(MENU_ITEM, "text-ink hover:bg-menu-hover", moreOpen && moreEngaged && "bg-menu-active")}- >- <MoreHorizontal size={16} className="text-ink-secondary" />- <span className="flex-1">{t("sidebar.bot.more")}</span>- <ChevronRight size={15} aria-hidden="true" className="text-ink-secondary rtl:-scale-x-100" />- </button>- );+ const moreRow = flyoutButton("more", moreRef, <MoreHorizontal size={16} className="text-ink-secondary" />, t("sidebar.bot.more"));const leave = bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : [item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),<BotDeleteMenuItem key="delete" deleting={deleting} className={MENU_ITEM} onClick={() => { onClose(); onDelete(bot); }} />,@@ -251,14 +273,16 @@ export function BotContextMenu({onPointerOver={(event) => {const row = event.target instanceof Element ? event.target.closest('[role="menuitem"]') : null;if (!row || row === hoveredRow.current) return;- if (hoveredRow.current === moreRef.current) more.leaveRow("more");+ const left = rowFlyout(hoveredRow.current);+ if (left) more.leaveRow(left);hoveredRow.current = row;- const onMore = row === moreRef.current;- more.enterRow(onMore ? "more" : "row", onMore, { x: event.clientX, y: event.clientY });+ const key = rowFlyout(row);+ more.enterRow(key ?? "row", key !== null, { x: event.clientX, y: event.clientY });}}- onPointerMove={(event) => more.move({ x: event.clientX, y: event.clientY }, moreOpen && moreRef.current?.contains(event.target as Node) === true)}+ onPointerMove={(event) => more.move({ x: event.clientX, y: event.clientY }, flyoutRow(flyout)?.contains(event.target as Node) === true)}onPointerLeave={() => {- if (hoveredRow.current === moreRef.current) more.leaveRow("more");+ const left = rowFlyout(hoveredRow.current);+ if (left) more.leaveRow(left);hoveredRow.current = null;more.leaveMenu();}}@@ -283,13 +307,14 @@ export function BotContextMenu({{readError?.botId === bot.id && <p role="alert" className="px-2 py-1.5 text-[12px] text-danger">{readError.message}</p>}</div>,document.body,- )}{moreOpen && createPortal(+ )}{flyout && createPortal(<divref={flyoutRef}data-bot-menu+ data-bot-menu-flyout={flyout}data-sidebarrole="menu"- aria-label={t("sidebar.bot.more")}+ aria-label={flyout === "more" ? t("sidebar.bot.more") : t("sidebar.bot.moveToSection")}onPointerEnter={() => { more.enterSubmenu(); setMoreEngaged(true); }}onPointerLeave={() => setMoreEngaged(false)}onFocus={() => setMoreEngaged(true)}@@ -298,8 +323,9 @@ export function BotContextMenu({if (event.key === "ArrowLeft" || event.key === "Escape") {event.preventDefault();event.stopPropagation();+ const row = flyoutRow(flyout);more.closeNow();- moreRef.current?.focus();+ row?.focus();return;}navigateThreadMenu(event);@@ -307,7 +333,7 @@ export function BotContextMenu({style={{ top: shown.y, left: shown.x }}className={cn("fixed z-40 max-h-[calc(100dvh-16px)] w-max min-w-[180px] max-w-[calc(100vw-16px)] animate-pop-in overflow-y-auto overscroll-contain", MENU_SHEET)}>- {moreItems}+ {flyout === "more" ? moreItems : moveItems}</div>,document.body,)}</>;diff --git a/src/components/SidebarSectionHeader.naming.dom.test.ts b/src/components/SidebarSectionHeader.naming.dom.test.tsnew file mode 100644index 0000000000..d588d9b304--- /dev/null+++ b/src/components/SidebarSectionHeader.naming.dom.test.ts@@ -0,0 +1,78 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { SidebarSectionHeader } from "./SidebarSectionHeader";++let container: HTMLDivElement;+let root: Root;+beforeEach(() => {+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => {+ flushSync(() => root.unmount());+ container.remove();+});++function mount(line: boolean, extra: Partial<Parameters<typeof SidebarSectionHeader>[0]> = {}) {+ const naming = { value: "New department", label: "New department name", onCommit: vi.fn(), onCancel: vi.fn() };+ flushSync(() => root.render(createElement(SidebarSectionHeader, {+ name: "Work", collapsed: false, reorderable: true, dragging: false, line, count: 2, onToggle: () => {}, onMenu: () => {}, naming, ...extra,+ })));+ return { naming, field: container.querySelector<HTMLInputElement>("[data-section-name-field]")! };+}+const key = (field: HTMLInputElement, name: string) => flushSync(() => field.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true })));+const type = (field: HTMLInputElement, text: string) => flushSync(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, text);+ field.dispatchEvent(new Event("input", { bubbles: true }));+});++describe("a department's name field in its heading", () => {+ for (const line of [true, false]) {+ it(`takes focus with the name selected, in place of the name, its menu and its drag (${line ? "Simple" : "Advanced"})`, () => {+ const { field } = mount(line);+ expect(document.activeElement).toBe(field);+ expect([field.selectionStart, field.selectionEnd]).toEqual([0, "New department".length]);+ expect(field.getAttribute("aria-label")).toBe("New department name");+ expect(field.maxLength).toBe(60);+ expect(container.querySelector("[aria-expanded]")).toBeNull();+ expect(container.querySelector("[draggable]")).toBeNull();+ });+ }++ it("keeps what was typed on Enter, once, even when focus leaves after", () => {+ const { naming, field } = mount(true);+ type(field, "Clients");+ key(field, "Enter");+ flushSync(() => field.blur());+ expect(naming.onCommit.mock.calls).toEqual([["Clients"]]);+ expect(naming.onCancel).not.toHaveBeenCalled();+ });++ it("keeps it when focus leaves, and Escape cancels without keeping it", () => {+ const left = mount(true);+ type(left.field, "Home");+ flushSync(() => left.field.blur());+ expect(left.naming.onCommit.mock.calls).toEqual([["Home"]]);+ flushSync(() => root.unmount());+ root = createRoot(container);+ const escaped = mount(true);+ key(escaped.field, "Escape");+ flushSync(() => escaped.field.blur());+ expect(escaped.naming.onCancel).toHaveBeenCalledOnce();+ expect(escaped.naming.onCommit).not.toHaveBeenCalled();+ });++ it("marks a heading a dragged bot would go into", () => {+ mount(true, { naming: undefined, dropInto: true });+ expect(container.querySelector("[data-section-drop]")?.className).toContain("outline-accent/70");+ flushSync(() => root.unmount());+ root = createRoot(container);+ mount(false, { naming: undefined, dropInto: false });+ expect(container.querySelector("[data-section-drop]")).toBeNull();+ });+});diff --git a/src/components/SidebarSectionHeader.tsx b/src/components/SidebarSectionHeader.tsxindex a63a9d5dd1..09f08efb11 100644--- a/src/components/SidebarSectionHeader.tsx+++ b/src/components/SidebarSectionHeader.tsx@@ -1,5 +1,5 @@import { ChevronDown, ChevronRight, GripVertical, MoreHorizontal, Trash2 } from "lucide-react";-import type { DragEvent, KeyboardEvent, MouseEvent } from "react";+import { useEffect, useRef, useState, type DragEvent, type KeyboardEvent, type MouseEvent } from "react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -7,6 +7,7 @@ import {sidebarAttentionLabel,type SidebarSectionAttention,} from "@/lib/sidebar-attention";+import type { SectionNaming } from "./SidebarBotDrag";export function SidebarSectionHeader({name,@@ -14,7 +15,7 @@ export function SidebarSectionHeader({attention,alert,onToggle,- reorderable,+ reorderable: canReorder,dragging,onDragStart,onDragEnd,@@ -26,6 +27,8 @@ export function SidebarSectionHeader({menuOpen = false,lead,count,+ naming,+ dropInto = false,}: {name: string;collapsed: boolean;@@ -46,7 +49,12 @@ export function SidebarSectionHeader({lead?: string;/** How many rows the section holds, shown at rest where the chevron shows on hover (Simple). */count?: number;+ /** A name field in place of the name, for a department being made or renamed. */+ naming?: SectionNaming;+ /** A dragged bot would go into this department. */+ dropInto?: boolean;}) {+ const reorderable = canReorder && !naming;const Chevron = collapsed ? ChevronRight : ChevronDown;const leadLabel = lead ? <span data-department-lead={lead} title={t("owner.departmentLeadAria", { department: name, name: lead })}className="shrink-0 truncate text-[11px] font-normal text-ink-tertiary">{t("owner.departmentLead", { name: lead })}<span className="sr-only">{`, ${t("owner.departmentLeadAria", { department: name, name: lead })}`}</span></span> : null;@@ -69,6 +77,8 @@ export function SidebarSectionHeader({? t("sidebar.section.expand", { name }): t("sidebar.section.collapse", { name });+ const dropMark = dropInto ? "bg-accent/10 outline outline-2 -outline-offset-2 outline-accent/70" : undefined;+if (line) {const tail = (<span aria-hidden="true" className="relative flex size-4 shrink-0 items-center justify-center">@@ -80,14 +90,15 @@ export function SidebarSectionHeader({<divdata-section={name}data-sidebar-section-line=""+ data-section-drop={dropInto ? "" : undefined}tabIndex={onContextMenu ? -1 : undefined}- onContextMenu={onContextMenu}+ onContextMenu={naming ? undefined : onContextMenu}draggable={reorderable || undefined}onDragStart={reorderable ? onDragStart : undefined}onDragEnd={reorderable ? onDragEnd : undefined}- className={cn("group/section flex h-[30px] items-center gap-1.5 rounded-[6px] px-2 pb-1.5 pt-2 hover:bg-raised/50", reorderable && "cursor-grab", dragging && "opacity-40")}+ className={cn("group/section flex h-[30px] items-center gap-1.5 rounded-[6px] px-2 pb-1.5 pt-2 hover:bg-raised/50", reorderable && "cursor-grab", dragging && "opacity-40", naming && "py-0.5", dropMark)}>- {onToggle ? (+ {naming ? <SectionNameField {...naming} /> : onToggle ? (<buttontype="button"onClick={onToggle}@@ -110,7 +121,7 @@ export function SidebarSectionHeader({{tail}</div>)}- {onMenu && (+ {onMenu && !naming && (<buttontype="button"aria-label={t("team.actions", { name })}@@ -128,8 +139,8 @@ export function SidebarSectionHeader({}return (- <div className="flex items-center gap-1 px-2 pb-1" data-section={name} tabIndex={onContextMenu ? -1 : undefined} onContextMenu={onContextMenu}>- {onToggle ? (+ <div className={cn("flex items-center gap-1 rounded-md px-2 pb-1", dropMark)} data-section={name} data-section-drop={dropInto ? "" : undefined} tabIndex={onContextMenu ? -1 : undefined} onContextMenu={naming ? undefined : onContextMenu}>+ {naming ? <SectionNameField {...naming} /> : onToggle ? (<buttontype="button"onClick={onToggle}@@ -154,7 +165,7 @@ export function SidebarSectionHeader({</div>)}{leadLabel}- {onDelete && (+ {onDelete && !naming && (<buttontype="button"onClick={onDelete}@@ -184,6 +195,45 @@ export function SidebarSectionHeader({);}+function SectionNameField({ value, label, onCommit, onCancel }: SectionNaming) {+ const [draft, setDraft] = useState(value);+ const field = useRef<HTMLInputElement>(null);+ const settled = useRef(false);+ // A menu that just closed hands focus back to its opener after this field mounts.+ useEffect(() => {+ field.current?.focus();+ field.current?.select();+ }, []);+ const settle = (save: boolean) => {+ if (settled.current) return;+ settled.current = true;+ if (save) onCommit(draft);+ else onCancel();+ };+ return (+ <input+ ref={field}+ data-section-name-field=""+ value={draft}+ maxLength={60}+ aria-label={label}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => settle(true)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ settle(true);+ } else if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ settle(false);+ }+ }}+ className="h-6 min-w-0 flex-1 rounded-md bg-ink/[0.05] px-1.5 text-[13px] leading-[18px] text-ink outline-none ring-1 ring-accent/60"+ />+ );+}+function SectionAttention({ attention, label, alert }: { attention?: SidebarSectionAttention; label: string; alert?: boolean }) {return (<>diff --git a/src/components/SidebarSectionPicker.tsx b/src/components/SidebarSectionPicker.tsxindex 56ff8816c9..106724d30b 100644--- a/src/components/SidebarSectionPicker.tsx+++ b/src/components/SidebarSectionPicker.tsx@@ -5,6 +5,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useHeldMenuMotion } from "./MenuMotion";import { MENU_HEADING, MENU_ITEM, MENU_ITEM_SEPARATOR, MENU_SHEET } from "./menu-recipe";+import { departmentNames } from "./bot-sections";/** "Move to context": the sidebar sections in use, a field for a new one, and "remove from context". */export function SectionPicker({@@ -42,13 +43,7 @@ export function SectionPicker({};}, [anchor, onClose]);- const sections = [- ...new Set([- ...(state.sections ?? []),- ...state.bots.filter((b) => !b.hidden && b.section).map((b) => b.section!),- ...state.groups.filter((g) => g.section).map((g) => g.section!),- ]),- ];+ const sections = departmentNames(state);const assign = (section: string) => {onAssign(section);diff --git a/src/components/SidebarSections.tsx b/src/components/SidebarSections.tsxnew file mode 100644index 0000000000..83dce2b7bc--- /dev/null+++ b/src/components/SidebarSections.tsx@@ -0,0 +1,123 @@+import { useRef, useState, type DragEvent, type RefObject } from "react";+import { FOLDER_DRAG_TYPE } from "@/lib/folder-order";+import { t } from "@/lib/i18n";+import {+ SIMPLE_FIXED_SECTION_IDS,+ keepFixedSectionSlots,+ mergeSectionOrder,+ moveSection,+ orderedSidebarSections,+ placeSection,+ sameSectionOrder,+ sidebarLayoutInteractive,+ sidebarSectionCollapsed,+ simpleSidebarSections,+ userSectionId,+ type SectionDropPlace,+} from "@/lib/sidebar-layout";+import { loadCollapsedSections, loadSectionOrder, saveCollapsedSections, saveSectionOrder, toggleCollapsedSection, type SidebarDensity } from "@/lib/sidebar-preferences";++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 keeps its fixed lists first and orders only the departments after them. */+export function useSidebarSections({ simple, rail, density, query, label, sidebarRef }: {+ simple: boolean;+ rail: boolean;+ density: SidebarDensity;+ query: string;+ label: (id: string) => string;+ sidebarRef: RefObject<HTMLElement | null>;+}) {+ const [collapsedIds, setCollapsedIds] = useState<string[]>(() => loadCollapsedSections());+ const [savedOrder, setSavedOrder] = useState<string[]>(() => loadSectionOrder());+ const [draggingId, setDraggingId] = useState<string | null>(null);+ const [dropTarget, setDropTarget] = useState<{ id: string; place: SectionDropPlace } | null>(null);+ 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 focusHeader = (name: string) => requestAnimationFrame(() => {+ const header = [...(sidebarRef.current?.querySelectorAll<HTMLElement>("[data-section]") ?? [])].find((element) => element.dataset.section === name);+ (header?.querySelector<HTMLElement>("button") ?? header ?? sidebarRef.current)?.focus();+ });+ const resetDrag = () => {+ drag.current = { from: null, over: null };+ setDraggingId(null);+ setDropTarget(null);+ };++ return {+ interactive,+ announcement,+ announce: setAnnouncement,+ focusHeader,+ collapsed: (id: string) => sidebarSectionCollapsed(id, collapsedIds, density, query),+ toggle: (id: string) => {+ if (!interactive) return;+ const next = toggleCollapsedSection(collapsedIds, id);+ setCollapsedIds(next);+ saveCollapsedSections(next);+ },+ /** A department's new name keeps its place and its collapsed state. */+ renamed: (from: string, to: string) => {+ const replace = (ids: string[]) => [...new Set(ids.map((id) => (id === userSectionId(from) ? userSectionId(to) : id)))];+ setCollapsedIds((current) => { const next = replace(current); saveCollapsedSections(next); return next; });+ setSavedOrder((current) => { const next = replace(current); saveSectionOrder(next); return next; });+ focusHeader(to);+ },+ arrange(natural: string[]) {+ const orderedIds = orderedSidebarSections(natural, savedOrder);+ const sectionIds = simple || rail ? simpleSidebarSections(orderedIds) : orderedIds;+ const reorderableIds = simple ? sectionIds.filter((id) => !SIMPLE_FIXED_SECTION_IDS.includes(id)) : sectionIds;+ const reorder = (id: string, moved: string[]) => {+ const next = simple ? simpleSidebarSections(moved) : moved;+ if (sameSectionOrder(next, sectionIds)) return;+ const merged = mergeSectionOrder(savedOrder, simple ? keepFixedSectionSlots(orderedIds, next) : next);+ if (interactive && !sameSectionOrder(merged, savedOrder)) {+ setSavedOrder(merged);+ saveSectionOrder(merged);+ }+ const position = next.indexOf(id);+ if (position >= 0) setAnnouncement(t("sidebar.section.moved", { name: label(id), position: position + 1, count: next.length }));+ };+ return {+ sectionIds,+ header: (id: string) => ({+ reorderable: interactive && reorderableIds.length > 1 && reorderableIds.includes(id),+ dragging: draggingId === id,+ onDragStart: (event: DragEvent<HTMLElement>) => {+ event.dataTransfer.effectAllowed = "move";+ event.dataTransfer.setData(SECTION_DRAG_TYPE, id);+ event.dataTransfer.setData("text/plain", id);+ drag.current = { from: id, over: null };+ setDraggingId(id);+ },+ onDragEnd: resetDrag,+ onMove: (direction: -1 | 1) => reorder(id, moveSection(sectionIds, id, direction)),+ }),+ zone: (id: string) => ({+ onDragOver: (event: DragEvent<HTMLElement>) => {+ if (!interactive || !drag.current.from) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = "move";+ const rect = event.currentTarget.getBoundingClientRect();+ const over = { id, place: event.clientY < rect.top + rect.height / 2 ? "before" as const : "after" as const };+ drag.current.over = over;+ setDropTarget(over);+ },+ onDrop: (event: DragEvent<HTMLElement>) => {+ if (event.dataTransfer.types.includes(FOLDER_DRAG_TYPE)) return;+ event.preventDefault();+ const from = event.dataTransfer.getData(SECTION_DRAG_TYPE) || event.dataTransfer.getData("text/plain") || drag.current.from;+ const over = drag.current.over;+ if (from && over) reorder(from, placeSection(sectionIds, from, over.id, over.place));+ resetDrag();+ },+ }),+ dropLine: (id: string, place: SectionDropPlace) =>+ dropTarget?.id === id && dropTarget.place === place && draggingId !== id ? <div className="mx-2 h-0.5 rounded-full bg-accent" /> : null,+ };+ },+ };+}diff --git a/src/components/bot-panel/bot-actions.ts b/src/components/bot-panel/bot-actions.tsindex a170cfd2b8..e9dd8e7285 100644--- a/src/components/bot-panel/bot-actions.ts+++ b/src/components/bot-panel/bot-actions.ts@@ -6,22 +6,12 @@ import { botUnreadThreadIds, markBotRead } from "@/lib/folder-read";import { useShowThreads } from "@/lib/thread-preferences";import { api, useStore, type Bot } from "@/state/store";import { announceArchiveNotice, archiveBotWithNotice } from "../bot-archive";+import { moveBotsToSection } from "../bot-sections";import { currentArchivableBot, type BotConfirmKind } from "../Sidebar";-export function teamNames(state: Pick<ReturnType<typeof useStore>["state"], "sections" | "bots" | "groups">): string[] {- return [- ...new Set([- ...(state.sections ?? []),- ...state.bots.filter((b) => !b.hidden && b.section).map((b) => b.section!),- ...state.groups.filter((g) => g.section).map((g) => g.section!),- ]),- ];-}-export function useBotActions(bot: Bot) {const { state, dispatch } = useStore();const showThreads = useShowThreads();- const remoteClient = window.ogb?.remoteClient?.active === true;const [confirm, setConfirm] = useState<BotConfirmKind | null>(null);const [reading, setReading] = useState(false);const [readError, setReadError] = useState<string | null>(null);@@ -84,17 +74,7 @@ export function useBotActions(bot: Bot) {};const moveToTeam = (section: string) => {- if ((bot.section?.trim() ?? "") === section) return;- if (!remoteClient) {- dispatch({ type: "updateBot", botId: bot.id, patch: { section } });- return;- }- void api("/api/sidebar-sections", {- method: "POST",- body: JSON.stringify({ name: section, botIds: [bot.id] }),- })- .then(({ bots }) => bots.forEach((updated: Bot) => dispatch({ type: "botPatched", bot: updated })))- .catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }));+ if ((bot.section?.trim() ?? "") !== section) moveBotsToSection(dispatch, [bot.id], section);};return {diff --git a/src/components/bot-sections.ts b/src/components/bot-sections.tsnew file mode 100644index 0000000000..2fd30b4e31--- /dev/null+++ b/src/components/bot-sections.ts@@ -0,0 +1,42 @@+import type { Dispatch } from "react";+import { api, type Action, type AppState, type Bot } from "@/state/store";++const failure = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));++/** Every department in use, in the order the workspace lists them. */+export function departmentNames(state: Pick<AppState, "sections" | "bots" | "groups">): string[] {+ return [...new Set([+ ...(state.sections ?? []),+ ...state.bots.filter((bot) => !bot.hidden && bot.section).map((bot) => bot.section!),+ ...state.groups.filter((group) => group.section).map((group) => group.section!),+ ])];+}++/** Puts bots in a department, a new one too; `""` takes them out. A remote client's profile patches don't reach the+ * workspace, so it asks for the move in one request. */+export function moveBotsToSection(dispatch: Dispatch<Action>, botIds: string[], section: string): void {+ if (!botIds.length) return;+ if (typeof window === "undefined" || window.ogb?.remoteClient?.active !== true) {+ for (const botId of botIds) dispatch({ type: "updateBot", botId, patch: { section } });+ return;+ }+ void api("/api/sidebar-sections", { method: "POST", body: JSON.stringify({ name: section, botIds }) })+ .then(({ bots }) => bots.forEach((bot: Bot) => dispatch({ type: "botPatched", bot })))+ .catch((cause) => dispatch({ type: "error", message: failure(cause) }));+}++/** Shows `botIds` in this order at once and saves it; every other bot keeps its place in the fleet. */+export function saveBotOrder(dispatch: Dispatch<Action>, bots: readonly Pick<Bot, "id">[], botIds: string[]): void {+ const before = bots.filter((bot) => botIds.includes(bot.id)).map((bot) => bot.id);+ if (before.length === botIds.length && before.every((id, index) => id === botIds[index])) return;+ dispatch({ type: "botsOrdered", botIds });+ void api("/api/bots/order", { method: "PUT", body: JSON.stringify({ botIds }) }).catch((cause) => {+ dispatch({ type: "botsOrdered", botIds: before });+ dispatch({ type: "error", message: failure(cause) });+ });+}++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-bot-drop.test.ts b/src/lib/sidebar-bot-drop.test.tsnew file mode 100644index 0000000000..cf670dd4b9--- /dev/null+++ b/src/lib/sidebar-bot-drop.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";++import { botDropPlace, planBotDrop, stepBot, stepKey, unusedName, type BotLists } from "./sidebar-bot-drop";++const lists: BotLists = new Map([+ ["", ["atlas", "bea", "cleo"]],+ ["Work", ["dodo", "echo"]],+ ["Empty", []],+]);++describe("where a dragged bot lands", () => {+ it("starts a department from the middle half of a row that is in none, and places it above or below otherwise", () => {+ expect([0, 13, 14, 27, 40, 41, 54].map((offset) => botDropPlace(offset, 54, true))).toEqual(["before", "before", "group", "group", "group", "after", "after"]);+ expect([0, 26, 27, 54].map((offset) => botDropPlace(offset, 54, false))).toEqual(["before", "before", "after", "after"]);+ });++ it("reorders within the list, in either direction, and a drop that changes nothing does nothing", () => {+ expect(planBotDrop(lists, "cleo", { kind: "row", botId: "atlas", place: "before" })).toEqual({ kind: "move", section: "", order: ["cleo", "atlas", "bea"] });+ expect(planBotDrop(lists, "atlas", { kind: "row", botId: "bea", place: "after" })).toEqual({ kind: "move", section: "", order: ["bea", "atlas", "cleo"] });+ expect(planBotDrop(lists, "atlas", { kind: "row", botId: "bea", place: "before" })).toBeNull();+ expect(planBotDrop(lists, "bea", { kind: "row", botId: "bea", place: "after" })).toBeNull();+ expect(planBotDrop(lists, "cleo", { kind: "end", list: "" })).toBeNull();+ });++ it("moves a bot into a department between its rows or at its end, and back out between the others", () => {+ expect(planBotDrop(lists, "bea", { kind: "row", botId: "echo", place: "before" })).toEqual({ kind: "move", section: "Work", order: ["dodo", "bea", "echo"] });+ expect(planBotDrop(lists, "bea", { kind: "end", list: "Work" })).toEqual({ kind: "move", section: "Work", order: ["dodo", "echo", "bea"] });+ expect(planBotDrop(lists, "bea", { kind: "end", list: "Empty" })).toEqual({ kind: "move", section: "Empty", order: ["bea"] });+ expect(planBotDrop(lists, "echo", { kind: "row", botId: "atlas", place: "after" })).toEqual({ kind: "move", section: "", order: ["atlas", "echo", "bea", "cleo"] });+ expect(planBotDrop(lists, "echo", { kind: "end", list: "" })).toEqual({ kind: "move", section: "", order: ["atlas", "bea", "cleo", "echo"] });+ });++ it("starts a department with the bot it was dropped on first, only from a row in no department", () => {+ expect(planBotDrop(lists, "cleo", { kind: "row", botId: "atlas", place: "group" })).toEqual({ kind: "group", botIds: ["atlas", "cleo"] });+ expect(planBotDrop(lists, "dodo", { kind: "row", botId: "bea", place: "group" })).toEqual({ kind: "group", botIds: ["bea", "dodo"] });+ expect(planBotDrop(lists, "atlas", { kind: "row", botId: "dodo", place: "group" })).toBeNull();+ });++ it("ignores a bot or a list the sidebar doesn't show as rows", () => {+ expect(planBotDrop(lists, "chief", { kind: "end", list: "Work" })).toBeNull();+ expect(planBotDrop(lists, "atlas", { kind: "row", botId: "chief", place: "before" })).toBeNull();+ expect(planBotDrop(lists, "atlas", { kind: "end", list: "Gone" })).toBeNull();+ });+});++describe("Alt+Up and Alt+Down", () => {+ it("move a bot one place within its own list and stop at either end", () => {+ expect(stepBot(lists, "bea", -1)).toEqual({ kind: "move", section: "", order: ["bea", "atlas", "cleo"] });+ expect(stepBot(lists, "bea", 1)).toEqual({ kind: "move", section: "", order: ["atlas", "cleo", "bea"] });+ expect(stepBot(lists, "dodo", 1)).toEqual({ kind: "move", section: "Work", order: ["echo", "dodo"] });+ expect(stepBot(lists, "atlas", -1)).toBeNull();+ expect(stepBot(lists, "echo", 1)).toBeNull();+ expect(stepBot(lists, "chief", 1)).toBeNull();+ });++ it("are the only keys that move it", () => {+ const key = (key: string, extra: Partial<{ altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean }> = {}) =>+ stepKey({ key, altKey: true, ctrlKey: false, metaKey: false, shiftKey: false, ...extra });+ expect([key("ArrowUp"), key("ArrowDown"), key("ArrowLeft"), key("ArrowUp", { altKey: false }), key("ArrowDown", { shiftKey: true }), key("ArrowUp", { metaKey: true })])+ .toEqual([-1, 1, null, null, null, null]);+ });+});++describe("a new department's name", () => {+ it("is the plain name until a department has it, then the first free number", () => {+ expect(unusedName("New department", ["Work"])).toBe("New department");+ expect(unusedName("New department", ["New department", "New department 2", "New department 4"])).toBe("New department 3");+ });+});diff --git a/src/lib/sidebar-bot-drop.ts b/src/lib/sidebar-bot-drop.tsnew file mode 100644index 0000000000..1082ee5e1c--- /dev/null+++ b/src/lib/sidebar-bot-drop.ts@@ -0,0 +1,77 @@+export const BOT_ROW_DRAG_TYPE = "application/x-openmausbot-sidebar-bot";++/** Where a dragged bot lands against the row under the pointer: above it, below it, or with it in a new department. */+export type BotDropPlace = "before" | "after" | "group";++/** The rows a bot can be dragged among, each in the order shown: the bots in no department under `""`, and each+ * department's under its name. */+export type BotLists = ReadonlyMap<string, readonly string[]>;++export type BotDrop =+ | { kind: "row"; botId: string; place: BotDropPlace }+ | { kind: "end"; list: string };++export type BotMove =+ /** The bot goes to `section` (`""`: no department), and that list's rows take `order`. */+ | { kind: "move"; section: string; order: string[] }+ /** The first bot stays where the second was dropped on it; both start a department. */+ | { kind: "group"; botIds: [string, string] };++/** The middle half of a row starts a department with it, where `canGroup`; the rest places the bot above or below. */+export function botDropPlace(offset: number, height: number, canGroup: boolean): BotDropPlace {+ const fraction = height > 0 ? offset / height : 0.5;+ if (canGroup && fraction > 0.25 && fraction < 0.75) return "group";+ return fraction < 0.5 ? "before" : "after";+}++export function botListOf(lists: BotLists, botId: string): string | undefined {+ for (const [list, ids] of lists) if (ids.includes(botId)) return list;+ return undefined;+}++export function sameBotDrop(a: BotDrop | null, b: BotDrop | null): boolean {+ if (!a || !b) return a === b;+ if (a.kind === "row") return b.kind === "row" && a.botId === b.botId && a.place === b.place;+ return b.kind === "end" && a.list === b.list;+}++function placed(lists: BotLists, botId: string, from: string, to: string, at: (others: string[]) => number): BotMove | null {+ const current = lists.get(to) ?? [];+ const order = current.filter((id) => id !== botId);+ order.splice(at(order), 0, botId);+ if (from === to && order.every((id, index) => id === current[index])) return null;+ return { kind: "move", section: to, order };+}++/** What dropping `botId` there does, or null when it changes nothing. Only a row outside any department starts one. */+export function planBotDrop(lists: BotLists, botId: string, drop: BotDrop): BotMove | null {+ const from = botListOf(lists, botId);+ if (from === undefined) return null;+ if (drop.kind === "end") return lists.has(drop.list) ? placed(lists, botId, from, drop.list, (others) => others.length) : null;+ const to = botListOf(lists, drop.botId);+ if (drop.botId === botId || to === undefined) return null;+ if (drop.place === "group") return to === "" ? { kind: "group", botIds: [drop.botId, botId] } : null;+ return placed(lists, botId, from, to, (others) => others.indexOf(drop.botId) + (drop.place === "after" ? 1 : 0));+}++export function stepBot(lists: BotLists, botId: string, direction: -1 | 1): BotMove | null {+ const from = botListOf(lists, botId);+ if (from === undefined) return null;+ const ids = lists.get(from)!;+ const index = ids.indexOf(botId);+ if (index + direction < 0 || index + direction >= ids.length) return null;+ return placed(lists, botId, from, from, () => index + direction);+}++export function stepKey(event: { key: string; altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean }): -1 | 1 | null {+ if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return null;+ return event.key === "ArrowUp" ? -1 : event.key === "ArrowDown" ? 1 : null;+}++export function unusedName(base: string, taken: readonly string[]): string {+ const used = new Set(taken);+ if (!used.has(base)) return base;+ let n = 2;+ while (used.has(`${base} ${n}`)) n += 1;+ return `${base} ${n}`;+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex ed692621c9..af753de076 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -442,6 +442,7 @@"settings.updates.restartingShort": "Neustart…","common.save": "Speichern","common.cancel": "Abbrechen",+ "team.deleteKeepBotsSimple": "Ihre Bots und Gruppenchats bleiben samt Unterhaltungen erhalten, nur in keiner Abteilung mehr. Die Abteilung und ihre gemeinsamen Anweisungen werden gelöscht. Das lässt sich nicht rückgängig machen.","presetShare.never": "Nie enthalten: Modellwahl, Ordner, wo Bots arbeiten, Freigabestufen, verbundene Apps, MCP-Server und Routinen.","orgLibrary.teamSafety": "Bots, Bilder, gemeinsame Anweisungen, der Chief of Staff, Gruppenchats, Playbooks und Startnotizen werden hinzugefügt. Skills kommen eingeschaltet an und Routinen pausiert. Verbindungen kommen ohne ihre Schlüssel an; schließe sie unter Apps → MCP servers ab. Chatverläufe, Schlüssel und Passwörter, Modellwahl und Computer werden nie mitgenommen.","common.add": "Hinzufügen",@@ -464,6 +465,8 @@"sidebar.section.botChats": "Bot-Threads","sidebar.section.bots": "Bots","sidebar.section.moved": "{name} auf Position {position} von {count} verschoben",+ "sidebar.section.removeFromDepartment": "Aus Abteilung entfernen",+ "sidebar.section.newName": "Neue Abteilung","sidebar.room.renameAria": "{name} umbenennen","sidebar.room.saveChatName": "Threadnamen speichern","sidebar.room.cancelChatRename": "Umbenennen des Threads abbrechen",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 6f70026c7d..e95bca25c4 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1461,6 +1461,7 @@"team.deleteTitle": "Delete {name} department?","team.deleteDescription": "This deletes the empty department and its shared instructions. This cannot be undone.","team.deleteKeepBotsDescription": "Bots and group chats move to General with their conversations intact. The department and its shared instructions are deleted. This cannot be undone.",+ "team.deleteKeepBotsSimple": "Its bots and group chats stay, with their conversations, outside any department. The department and its shared instructions are deleted. This cannot be undone.","team.delete": "Delete department","team.share": "Share department…","team.actions": "Actions for {name} department",@@ -1649,6 +1650,8 @@"sidebar.section.newContext": "New department…","sidebar.section.newContextAria": "New department name","sidebar.section.removeFromContext": "Move to General",+ "sidebar.section.removeFromDepartment": "Remove from department",+ "sidebar.section.newName": "New department","sidebar.room.renameAria": "Rename {name}","sidebar.room.saveChatName": "Save thread name","sidebar.room.saveChannelName": "Save group chat name",diff --git a/src/locales/es.json b/src/locales/es.jsonindex fb03114677..85916db5ad 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -1198,6 +1198,7 @@"team.deleteTitle": "¿Eliminar el departamento {name}?","team.deleteDescription": "Esto elimina el departamento vacío y sus instrucciones compartidas. No se puede deshacer.","team.deleteKeepBotsDescription": "Los bots y los chats de grupo se mueven a General con sus conversaciones intactas. Se eliminan el departamento y sus instrucciones compartidas. No se puede deshacer.",+ "team.deleteKeepBotsSimple": "Sus bots y chats de grupo se quedan, con sus conversaciones, fuera de cualquier departamento. Se eliminan el departamento y sus instrucciones compartidas. No se puede deshacer.","team.delete": "Eliminar departamento","team.share": "Compartir departamento…","teamSettings.menu": "Configurar para todos los bots de este departamento…",@@ -1381,6 +1382,8 @@"sidebar.section.newContext": "Departamento nuevo…","sidebar.section.newContextAria": "Nombre del departamento nuevo","sidebar.section.removeFromContext": "Mover a General",+ "sidebar.section.removeFromDepartment": "Quitar del departamento",+ "sidebar.section.newName": "Departamento nuevo","sidebar.room.renameAria": "Cambiar el nombre de {name}","sidebar.room.saveChatName": "Guardar nombre del hilo","sidebar.room.saveChannelName": "Guardar nombre del chat de grupo",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 0d6fc1154b..0e1145c8b4 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -362,6 +362,7 @@"settings.updates.restartingShort": "Redémarrage…","common.save": "Enregistrer","common.cancel": "Annuler",+ "team.deleteKeepBotsSimple": "Ses bots et ses discussions de groupe restent, avec leurs conversations, hors de tout département. Le département et ses instructions partagées sont supprimés. Cette action est irréversible.","presetShare.never": "Jamais inclus : choix de modèle, dossiers, lieu de travail des bots, niveaux d’approbation, apps connectées, serveurs MCP et routines.","orgLibrary.teamSafety": "Les bots, images, instructions partagées, le chef de cabinet, les chats de groupe, les playbooks et les notes de départ sont ajoutés. Les compétences arrivent activées et les routines en pause. Les connexions arrivent sans leurs clés ; terminez-les dans Apps → MCP servers. L'historique des chats, les clés et mots de passe, les choix de modèle et les ordinateurs ne sont jamais inclus.","common.add": "Ajouter",@@ -383,6 +384,8 @@"sidebar.section.botChats": "Fils entre bots","sidebar.section.bots": "Bots","sidebar.section.moved": "{name} déplacé en position {position} sur {count}",+ "sidebar.section.removeFromDepartment": "Retirer du département",+ "sidebar.section.newName": "Nouveau département","sidebar.room.renameAria": "Renommer {name}","sidebar.room.saveChatName": "Enregistrer le nom du fil","sidebar.room.cancelChatRename": "Annuler le renommage du fil",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 51105eb4e7..acd3996e7b 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -362,6 +362,7 @@"settings.updates.restartingShort": "पुनः आरंभ…","common.save": "सहेजें","common.cancel": "रद्द करें",+ "team.deleteKeepBotsSimple": "इसके बॉट और ग्रुप चैट अपनी बातचीत के साथ बने रहते हैं, बस किसी विभाग में नहीं रहते। विभाग और उसके साझा निर्देश हटा दिए जाते हैं। इसे वापस नहीं किया जा सकता।","presetShare.never": "कभी शामिल नहीं: मॉडल के चुनाव, फ़ोल्डर, बॉट कहाँ काम करते हैं, मंज़ूरी स्तर, जुड़े ऐप, MCP सर्वर और रूटीन।","orgLibrary.teamSafety": "बॉट, तस्वीरें, साझा निर्देश, चीफ़ ऑफ़ स्टाफ़, ग्रुप चैट, प्लेबुक और शुरुआती नोट्स जोड़े जाते हैं। स्किल्स चालू होकर आती हैं और रूटीन रुके हुए। कनेक्शन अपनी कुंजियों के बिना आते हैं; उन्हें ऐप्स → MCP servers में पूरा करें। चैट इतिहास, कुंजियाँ और पासवर्ड, मॉडल के चुनाव और कंप्यूटर कभी शामिल नहीं होते।","common.add": "जोड़ें",@@ -383,6 +384,8 @@"sidebar.section.botChats": "बॉट के थ्रेड","sidebar.section.bots": "बॉट","sidebar.section.moved": "{name} को {count} में से स्थान {position} पर ले जाया गया",+ "sidebar.section.removeFromDepartment": "विभाग से हटाएँ",+ "sidebar.section.newName": "नया विभाग","sidebar.room.renameAria": "{name} का नाम बदलें","sidebar.room.saveChatName": "थ्रेड का नाम सहेजें","sidebar.room.cancelChatRename": "थ्रेड का नाम बदलना रद्द करें",diff --git a/src/locales/it.json b/src/locales/it.jsonindex bf4bd502e8..323c62cc84 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -1321,6 +1321,7 @@"team.deleteTitle": "Eliminare il reparto {name}?","team.deleteDescription": "Elimina il reparto vuoto e le sue istruzioni condivise. Non si può annullare.","team.deleteKeepBotsDescription": "Bot e chat di gruppo passano a General con le conversazioni intatte. Il reparto e le sue istruzioni condivise vengono eliminati. Non si può annullare.",+ "team.deleteKeepBotsSimple": "I suoi bot e le chat di gruppo restano, con le loro conversazioni, fuori da qualsiasi reparto. Il reparto e le sue istruzioni condivise vengono eliminati. Non si può annullare.","team.delete": "Elimina reparto","team.share": "Condividi reparto…","team.actions": "Azioni per il reparto {name}",@@ -1507,6 +1508,8 @@"sidebar.section.newContext": "Nuovo reparto…","sidebar.section.newContextAria": "Nome del nuovo reparto","sidebar.section.removeFromContext": "Sposta in General",+ "sidebar.section.removeFromDepartment": "Togli dal reparto",+ "sidebar.section.newName": "Nuovo reparto","sidebar.room.renameAria": "Rinomina {name}","sidebar.room.saveChatName": "Salva nome del thread","sidebar.room.saveChannelName": "Salva nome della chat di gruppo",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 218c7e62c8..f8c6667cb8 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -1358,6 +1358,7 @@"team.deleteTitle": "部署 {name} を削除しますか?","team.deleteDescription": "空の部署と共有の指示を削除します。取り消せません。","team.deleteKeepBotsDescription": "ボットとグループチャットは、会話を保持したまま「一般」に移動します。部署と共有の指示は削除されます。取り消せません。",+ "team.deleteKeepBotsSimple": "ボットとグループチャットは会話を保ったまま残り、どの部署にも属さなくなります。部署と共有の指示は削除されます。取り消せません。","team.delete": "部署を削除","team.share": "部署を共有…","team.actions": "{name}部署の操作",@@ -1545,6 +1546,8 @@"sidebar.section.newContext": "新しい部署…","sidebar.section.newContextAria": "新しい部署名","sidebar.section.removeFromContext": "一般に移動",+ "sidebar.section.removeFromDepartment": "部署から外す",+ "sidebar.section.newName": "新しい部署","sidebar.room.renameAria": "{name} の名前を変更","sidebar.room.saveChatName": "スレッド名を保存","sidebar.room.saveChannelName": "グループチャット名を保存",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 4f0e4bd6fe..16dbbd61fb 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -1444,6 +1444,7 @@"team.deleteTitle": "{name} 부서를 삭제할까요?","team.deleteDescription": "빈 부서와 그 공유 지침을 삭제해요. 되돌릴 수 없어요.","team.deleteKeepBotsDescription": "봇과 그룹 채팅은 대화를 그대로 유지한 채 일반으로 옮겨져요. 부서와 공유 지침은 삭제돼요. 되돌릴 수 없어요.",+ "team.deleteKeepBotsSimple": "봇과 그룹 채팅은 대화와 함께 그대로 남고, 어느 부서에도 속하지 않게 돼요. 부서와 공유 지침은 삭제돼요. 되돌릴 수 없어요.","team.delete": "부서 삭제","team.share": "부서 공유…","team.actions": "{name} 부서 작업",@@ -1632,6 +1633,8 @@"sidebar.section.newContext": "새 부서…","sidebar.section.newContextAria": "새 부서 이름","sidebar.section.removeFromContext": "일반으로 옮기기",+ "sidebar.section.removeFromDepartment": "부서에서 빼기",+ "sidebar.section.newName": "새 부서","sidebar.room.renameAria": "{name} 이름 바꾸기","sidebar.room.saveChatName": "스레드 이름 저장","sidebar.room.saveChannelName": "그룹 채팅 이름 저장",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 9b35156da8..63d0933da1 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -1351,6 +1351,7 @@"team.deleteTitle": "Usunąć dział {name}?","team.deleteDescription": "Spowoduje to usunięcie pustego działu i jego wspólnych instrukcji. Tej operacji nie można cofnąć.","team.deleteKeepBotsDescription": "Boty i czaty grupowe przenoszą się do działu Ogólny wraz z rozmowami. Dział i jego wspólne instrukcje zostaną usunięte. Tej operacji nie można cofnąć.",+ "team.deleteKeepBotsSimple": "Jego boty i czaty grupowe zostają wraz z rozmowami, ale poza jakimkolwiek działem. Dział i jego wspólne instrukcje zostaną usunięte. Tej operacji nie można cofnąć.","team.delete": "Usuń dział","team.share": "Udostępnij dział…","team.actions": "Działania dla działu {name}",@@ -1538,6 +1539,8 @@"sidebar.section.newContext": "Nowy dział…","sidebar.section.newContextAria": "Nazwa nowego działu","sidebar.section.removeFromContext": "Przenieś do działu Ogólny",+ "sidebar.section.removeFromDepartment": "Usuń z działu",+ "sidebar.section.newName": "Nowy dział","sidebar.room.renameAria": "Zmień nazwę: {name}","sidebar.room.saveChatName": "Zapisz nazwę wątku","sidebar.room.saveChannelName": "Zapisz nazwę czatu grupowego",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 63c61cdb82..610322fa7c 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1257,6 +1257,7 @@"team.deleteTitle": "Excluir o departamento {name}?","team.deleteDescription": "Isto exclui o departamento vazio e as instruções compartilhadas dele. Não dá para desfazer.","team.deleteKeepBotsDescription": "Os bots e os chats em grupo vão para “Geral” com as conversas intactas. O departamento e as instruções compartilhadas dele são excluídos. Não dá para desfazer.",+ "team.deleteKeepBotsSimple": "Os bots e os chats em grupo dele continuam, com as conversas, fora de qualquer departamento. O departamento e as instruções compartilhadas dele são excluídos. Não dá para desfazer.","team.delete": "Excluir departamento","team.share": "Compartilhar departamento…","teamSettings.menu": "Definir para todos os bots deste departamento…",@@ -1442,6 +1443,8 @@"sidebar.section.newContext": "Novo departamento…","sidebar.section.newContextAria": "Nome do novo departamento","sidebar.section.removeFromContext": "Mover para Geral",+ "sidebar.section.removeFromDepartment": "Tirar do departamento",+ "sidebar.section.newName": "Novo departamento","sidebar.room.renameAria": "Renomear {name}","sidebar.room.saveChatName": "Salvar nome da conversa","sidebar.room.saveChannelName": "Salvar nome do chat em grupo",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex c878c3439f..d02c872e11 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -1357,6 +1357,7 @@"team.deleteTitle": "Удалить отдел {name}?","team.deleteDescription": "Будут удалены пустой отдел и его общие инструкции. Это действие нельзя отменить.","team.deleteKeepBotsDescription": "Боты и групповые чаты перейдут в «Общий» вместе со своими переписками. Отдел и его общие инструкции будут удалены. Это действие нельзя отменить.",+ "team.deleteKeepBotsSimple": "Его боты и групповые чаты остаются вместе со своими переписками, но вне отделов. Отдел и его общие инструкции будут удалены. Это действие нельзя отменить.","team.delete": "Удалить отдел","team.share": "Поделиться отделом…","team.actions": "Действия с отделом {name}",@@ -1544,6 +1545,8 @@"sidebar.section.newContext": "Новый отдел…","sidebar.section.newContextAria": "Название нового отдела","sidebar.section.removeFromContext": "Переместить в Общий",+ "sidebar.section.removeFromDepartment": "Убрать из отдела",+ "sidebar.section.newName": "Новый отдел","sidebar.room.renameAria": "Переименовать {name}","sidebar.room.saveChatName": "Сохранить имя потока","sidebar.room.saveChannelName": "Сохранить имя группы",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 5a7a33f861..290018015e 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -911,6 +911,7 @@"team.deleteTitle": "{name} departmanı silinsin mi?","team.deleteDescription": "Bu işlem boş departmanı ve onun paylaşılan talimatlarını siler. Bu işlem geri alınamaz.","team.deleteKeepBotsDescription": "Botlar ve grup sohbetleri, konuşmaları bozulmadan Genel grubuna taşınır. Departman ve paylaşılan talimatları silinir. Bu işlem geri alınamaz.",+ "team.deleteKeepBotsSimple": "Botları ve grup sohbetleri, konuşmalarıyla birlikte kalır ama hiçbir departmanda olmaz. Departman ve paylaşılan talimatları silinir. Bu işlem geri alınamaz.","team.delete": "Departmanı sil","team.share": "Departmanı paylaş…","teamSettings.menu": "Bu departmandaki tüm botlar için ayarla…",@@ -1094,6 +1095,8 @@"sidebar.section.newContext": "Yeni departman…","sidebar.section.newContextAria": "Yeni departman adı","sidebar.section.removeFromContext": "Genel'e taşı",+ "sidebar.section.removeFromDepartment": "Departmandan çıkar",+ "sidebar.section.newName": "Yeni departman","sidebar.room.renameAria": "{name} adını değiştir","sidebar.room.saveChatName": "Konu adını kaydet","sidebar.room.saveChannelName": "Grup sohbeti adını kaydet",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex b5c8d410d4..55e468f69a 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -459,6 +459,7 @@"common.save": "Зберегти","common.cancel": "Скасувати","common.close": "Закрити",+ "team.deleteKeepBotsSimple": "Його боти й групові чати залишаються разом зі своїми розмовами, але поза відділами. Відділ і його спільні інструкції буде видалено. Це не можна скасувати.","presetShare.never": "Ніколи не включаються: вибір моделі, теки, де працюють боти, рівні погодження, підключені застосунки, MCP-сервери та рутини.","orgLibrary.teamSafety": "Додаються боти, зображення, спільні інструкції, керівник апарату, групові чати, плейбуки й стартові нотатки. Навички надходять увімкненими, а рутини — призупиненими. Підключення надходять без ключів; завершіть їх у «Застосунки → MCP servers». Історія чатів, ключі й паролі, вибір моделей і комп’ютери ніколи не включаються.","common.add": "Додати",@@ -486,6 +487,8 @@"sidebar.section.newContext": "Новий відділ…","sidebar.section.newContextAria": "Назва нового відділу","sidebar.section.removeFromContext": "Перемістити в General",+ "sidebar.section.removeFromDepartment": "Прибрати з відділу",+ "sidebar.section.newName": "Новий відділ","sidebar.room.renameAria": "Перейменувати {name}","sidebar.room.saveChatName": "Зберегти назву гілки","sidebar.room.saveChannelName": "Зберегти назву групового чату",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 94c3a0c822..40a94bce2b 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -911,6 +911,7 @@"team.deleteTitle": "Xóa phòng ban {name}?","team.deleteDescription": "Thao tác này sẽ xóa phòng ban trống và các hướng dẫn chia sẻ của phòng ban. Hành động này không thể hoàn tác.","team.deleteKeepBotsDescription": "Các bot và group chat sẽ chuyển sang Chung với các cuộc trò chuyện được giữ nguyên. Phòng ban và các hướng dẫn chia sẻ của phòng ban sẽ bị xóa. Hành động này không thể hoàn tác.",+ "team.deleteKeepBotsSimple": "Các bot và group chat của phòng ban vẫn được giữ cùng các cuộc trò chuyện, chỉ không thuộc phòng ban nào nữa. Phòng ban và các hướng dẫn chia sẻ của phòng ban sẽ bị xóa. Hành động này không thể hoàn tác.","team.delete": "Xóa phòng ban","team.share": "Chia sẻ phòng ban…","teamSettings.menu": "Thiết lập cho tất cả bot trong phòng ban này…",@@ -1094,6 +1095,8 @@"sidebar.section.newContext": "Phòng ban mới…","sidebar.section.newContextAria": "Tên phòng ban mới","sidebar.section.removeFromContext": "Chuyển vào mục Chung",+ "sidebar.section.removeFromDepartment": "Bỏ khỏi phòng ban",+ "sidebar.section.newName": "Phòng ban mới","sidebar.room.renameAria": "Đổi tên {name}","sidebar.room.saveChatName": "Lưu tên đoạn chat","sidebar.room.saveChannelName": "Lưu tên group chat",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 908be73ab3..a22bc67d46 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -775,6 +775,7 @@"team.deleteTitle": "要刪除 {name} 部門嗎?","team.deleteDescription": "這會刪除空白部門及其共用指示,且無法復原。","team.deleteKeepBotsDescription": "機器人與聊天室會移至「一般」,對話完整保留。部門及其共用指示會被刪除,且無法復原。",+ "team.deleteKeepBotsSimple": "其中的機器人與聊天室會連同對話一起保留,只是不再屬於任何部門。部門及其共用指示會被刪除,且無法復原。","team.delete": "刪除部門","team.share": "分享部門…","teamShare.title": "分享 {name}",@@ -927,6 +928,8 @@"sidebar.section.newContext": "新增部門…","sidebar.section.newContextAria": "新部門名稱","sidebar.section.removeFromContext": "移至一般區域",+ "sidebar.section.removeFromDepartment": "移出部門",+ "sidebar.section.newName": "新部門","sidebar.room.renameAria": "重新命名 {name}","sidebar.room.saveChatName": "儲存對話名稱","sidebar.room.saveChannelName": "儲存聊天室名稱",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 79a8a9d37d..8e1476b08d 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -607,6 +607,7 @@"team.deleteAria": "删除 {name} 部门","team.deleteTitle": "要删除 {name} 部门吗?","team.deleteDescription": "这会删除空白部门及其共用指示,且无法复原。",+ "team.deleteKeepBotsSimple": "其中的机器人和群组聊天会连同对话一起保留,只是不再属于任何部门。部门及其共用指示会被删除,且无法复原。","team.delete": "删除部门","presetShare.never": "从不包含:模型选择、文件夹、机器人的工作位置、审批级别、已连接的应用、MCP 服务器和例行任务。","orgLibrary.teamSafety": "会添加机器人、图片、共享指示、幕僚长、群聊、操作手册和初始笔记。技能导入后为开启状态,例行任务为暂停状态。连接不含密钥;请在“应用 → MCP servers”中完成设置。始终不包含聊天记录、密钥和密码、模型选择及电脑。",@@ -645,6 +646,8 @@"sidebar.section.newContext": "添加部门…","sidebar.section.newContextAria": "新部门名称","sidebar.section.removeFromContext": "移至一般区域",+ "sidebar.section.removeFromDepartment": "移出部门",+ "sidebar.section.newName": "新部门","sidebar.room.renameAria": "重命名 {name}","sidebar.room.saveChatName": "保存对话名称","sidebar.room.saveChannelName": "保存群组聊天名称",