Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
One list: Cloud bots land in a place department and can be dragged anywhere, same list on both pages (#7681)
Milind Soni7227e1367a03
diff --git a/electron/places-together-default.node-test.mjs b/electron/places-together-default.node-test.mjsindex b52669be4d..59679d87f2 100644--- a/electron/places-together-default.node-test.mjs+++ b/electron/places-together-default.node-test.mjs@@ -272,6 +272,63 @@ test("the notice says this computer's workspace now starts with the app only toassert.equal(computerHome.together.state("computer").profileHome, undefined);});+test("both pages hear the same home place, so the one list keeps one order wherever the window is; none with the switch off", () => {+ const computerHome = setup({ deps: { computer: () => "computer:/data" } });+ assert.equal(computerHome.together.state("computer").home, "computer");+ assert.equal(computerHome.together.state("cloud").home, "computer");+ const cloudHome = setup({ deps: { computer: () => "profile:default" } });+ assert.equal(cloudHome.together.state("computer").home, "cloud");+ assert.equal(cloudHome.together.state("cloud").home, "cloud");+ assert.equal(setup({ saved: { v: 1, on: false } }).together.state("computer").home, undefined);+});++test("where the person put bots in the one list is kept for their account, through the switch going off and a restart, and only main's own checks let an entry in", async () => {+ const f = setup();+ f.bots.cloud = [bot("scout", "Scout", { section: "Research" }), bot("nova", "Nova")];+ f.together.state("computer");+ await f.together.refresh("cloud");+ const state = f.together.state("computer");+ assert.deepEqual(state.arranged, [], "nothing moved yet");+ assert.equal(state.other.bots[0].section, "Research", "a row says its department there, for the other page");+ const kept = f.together.arrange("cloud", [+ { key: "cloud:nova", section: "Finance", after: "computer:ledger" },+ { key: "cloud:scout", section: "", after: null },+ { key: "nova", section: "", after: null }, { key: "cloud:x", section: "\u0007", after: null }, { key: "cloud:y", section: "", after: "cloud:y" }, "junk",+ ]);+ assert.deepEqual(kept, [{ key: "cloud:nova", section: "Finance", after: "computer:ledger" }, { key: "cloud:scout", section: "", after: null }], "either page may arrange; a bad entry is dropped");+ assert.deepEqual(f.together.arrange("computer", [{ key: "cloud:scout", section: "Finance", after: "cloud:nova" }]).map((entry) => entry.key), ["cloud:nova", "cloud:scout"], "a later move replaces that bot's entry");+ assert.deepEqual(f.together.state("cloud").arranged, f.together.state("computer").arranged, "both pages hear the same arrangement");+ f.together.set("computer", false);+ assert.equal(f.together.state("computer").arranged, undefined, "off: no arrangement handed out");+ assert.deepEqual(f.together.arrange("computer", [{ key: "cloud:nova", section: "", after: null }]), f.saved.arranged["acct-a"], "nor changed");+ f.together.set("computer", true);+ const restarted = setup({ saved: f.saved });+ assert.deepEqual(restarted.together.state("computer").arranged, [{ key: "cloud:nova", section: "Finance", after: "computer:ledger" }, { key: "cloud:scout", section: "Finance", after: "cloud:nova" }], "kept through off and a restart");+ restarted.cloud.account = "acct-b";+ restarted.together.set("computer", true, { listOnly: true });+ assert.deepEqual(restarted.together.state("computer").arranged, [], "another account has its own");+ assert.deepEqual(f.asked.filter(([, , init]) => init?.method && init.method !== "GET"), [], "nothing is written to either place's server");+});++test("an arrangement keeps one entry per bot, the last one sent, and the same arrangement again writes nothing and tells no page", async () => {+ const f = setup();+ f.together.state("computer");+ f.together.arrange("computer", [{ key: "cloud:nova", section: "", after: null }]);+ const flood = Array.from({ length: 3_000 }, (_, index) => ({ key: "cloud:scout", section: index % 2 ? "Finance" : "", after: null }));+ const kept = f.together.arrange("computer", flood);+ assert.deepEqual(kept.map((entry) => entry.key), ["cloud:nova", "cloud:scout"], "one call repeating a key cannot push every other bot's entry out");+ assert.equal(kept[1].section, "Finance", "the last entry given for a bot wins");+ assert.deepEqual(f.together.arrange("computer", [{ key: "cloud:a", section: "\u0000landing", after: null }]).at(-1), { key: "cloud:a", section: "\u0000landing", after: null }, "the place's own department is kept as its mark");+ const writes = [], changes = f.changes, saved = f.saved;+ const again = setup({ saved, deps: { pref: { read: () => saved, write: (value) => { writes.push(value); } } } });+ again.together.state("computer");+ const before = again.changes;+ assert.deepEqual(again.together.arrange("computer", [{ key: "cloud:nova", section: "", after: null }]), saved.arranged["acct-a"], "a drop where the bot already was");+ assert.deepEqual(writes, [], "writes nothing");+ assert.equal(again.changes, before, "and tells no page");+ assert.ok(f.changes >= changes);+});+test("a switch file that is not JSON at all is off and quiet until the person turns the switch in Settings, which keeps the bad file beside it and writes a good one; a newer version's file stays untouched", async (t) => {const { mkdtempSync, readdirSync, readFileSync: read, rmSync, writeFileSync } = await import("node:fs");const { tmpdir } = await import("node:os");diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex 25a37c0b24..aaee510f39 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -26,6 +26,8 @@ export interface PlaceBotRow {preview?: string;/** The title of the conversation it has open there: its second line while no preview came. */chat?: string;+ /** The department it is in there, if any: where the one list draws it on the other page. */+ section?: string;/** Epoch ms its conversations last moved there (the newest thread's `updatedAt`): Unread's order across places. */lastAt?: number;}@@ -37,9 +39,17 @@ export interface PlacesTogetherState {on: boolean;/** The place whose page asked. */here: BotHome;+ /** While the switch is on: the person's home place (My Cloud once their bots moved there), the same on both pages. The+ * one list shows its bots first and the other place's second, whichever page is open. Absent from older apps: this computer. */+ home?: BotHome;/** The other place's bots while the switch is on. `state`: how that place is doing: asleep, waking and offline keep the* bots it gave last; "signin" is a My Cloud this window has not signed in to yet, which lists none. */- other: { home: BotHome; state: "ready" | "loading" | "asleep" | "waking" | "offline" | "signin"; bots: PlaceBotRow[]; newBot?: boolean } | null;+ other: { home: BotHome; state: "ready" | "loading" | "asleep" | "waking" | "offline" | "signin"; bots: PlaceBotRow[];+ /** That place's departments in its own order, while it said them. */+ sections?: string[]; newBot?: boolean } | null;+ /** While the switch is on: where the person put bots in the one list, kept for their account through restarts and the+ * switch going off. A bot with no entry is where its own place keeps it (home) or in its place's department (other). */+ arranged?: ArrangedBot[];/** This computer's page shows the one-time notice that this is on by default: the person never chose, and has not closed it. */notice?: true;/** With the notice, for a person whose home is My Cloud: this computer's own workspace now starts with the app. */@@ -49,6 +59,15 @@ export interface PlacesTogetherState {commands?: boolean;}+/** One bot's place in the one list: its key (`computer:<id>` or `cloud:<id>`), its department ("" for none, or the mark+ * for the place's own department, src/lib/one-list.ts LANDING_SECTION) and the key of the bot drawn just above it in that+ * list (null at its top). */+export interface ArrangedBot {+ key: string;+ section: string;+ after: string | null;+}+/** `window.ogb.placesTogether`: this computer's page and My Cloud's own page. */export interface PlacesTogetherBridge {state(): Promise<PlacesTogetherState>;@@ -57,6 +76,8 @@ export interface PlacesTogetherBridge {/** Opens the other place at one of its listed bots. False when main does not list that bot. */open(botId: string): Promise<boolean>;onChanged(callback: () => void): () => void;+ /** Keeps where the person moved bots in the one list; what main keeps now. Older apps lack it. */+ arrange?(entries: ArrangedBot[]): Promise<ArrangedBot[]>;/** The other place as the + shows it: how it is doing and the AIs ready there (null while it can't be asked). Null with the switch off. */newBotChoice(): Promise<NewBotChoice | null>;/** Opens the other place, which makes a new bot there by its own rules. False with the switch off, and for a placediff --git a/electron/places-together.mjs b/electron/places-together.mjsindex 705ad89c56..f9a49d2bd4 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -41,6 +41,10 @@ export const PREVIEW_MAX = 300;/** A line another bot sent is stored with this note in front (src/lib/peer-message.ts): never shown as the person's. */const PEER_NOTE = /^\[(?:From @|Message from @|Delegated by @|Thread opened by @)/;const MAX_BOTS = 500;+const MAX_SECTIONS = 200;+const SECTION_MAX = 60;+/** The most bots whose place in the one list is kept for one account. */+const MAX_LAID = 2_000;const ID = /^[\w-]{1,128}$/;const COLOR = /^[\w#(),.% -]{1,64}$/;@@ -135,8 +139,8 @@ export function botRow(bot, home) {const name = text(bot.name, 80);if (!name) return null;const open = Array.isArray(bot.tasks) ? bot.tasks.find((task) => record(task) && task.threadId === bot.threadId) : null;- const title = text(bot.title, 80), chat = text(open?.title, 80), preview = previewOf(bot), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor), tint = look(bot.mascotBodyColor), fur = look(bot.mascotMaterial);- return { home, id: bot.id, threadId: bot.threadId, name, ...(title ? { title } : {}), ...(chat ? { chat } : {}), ...(color ? { color } : {}),+ const title = text(bot.title, 80), chat = text(open?.title, 80), section = sectionName(bot.section), preview = previewOf(bot), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor), tint = look(bot.mascotBodyColor), fur = look(bot.mascotMaterial);+ return { home, id: bot.id, threadId: bot.threadId, name, ...(title ? { title } : {}), ...(chat ? { chat } : {}), ...(section ? { section } : {}), ...(color ? { color } : {}),...(body ? { mascotBody: body } : {}), ...(face ? { mascotFaceColor: face } : {}), ...(tint ? { mascotBodyColor: tint } : {}), ...(fur ? { mascotMaterial: fur } : {}), ...(bot.chiefOfStaff === true ? { chief: true } : {}), ...(preview ? { preview } : {}), ...rowState(bot) };}@@ -154,6 +158,40 @@ export function readyAis(body) {/** Whether a place's `GET /api/bots` answer says its page makes a new bot when the person's other place asks. */export const makesNewBots = (body) => record(body) && record(body.together) && body.together.newBot === true;+/** A department's name as a place's server keeps it (1 to 60 characters, no control character), or "" for none. */+export function sectionName(value) {+ const name = typeof value === "string" ? value.trim() : "";+ return name && name.length <= SECTION_MAX && ![...name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) ? name : "";+}++/** A place's departments in its own order, from its `GET /api/bots` answer: what the one list draws them by on the+ * other page too. */+export function placeSections(body) {+ const names = record(body) && Array.isArray(body.sections) ? body.sections.map(sectionName).filter(Boolean) : [];+ return [...new Set(names)].slice(0, MAX_SECTIONS);+}++/** "The place's own department" as a page sends it (src/lib/one-list.ts LANDING_SECTION): no department name can be it. */+const LANDING_SECTION = "\u0000landing";+/** A bot's key in the one list: its place and its own id there. */+const LAID_KEY = /^(computer|cloud):[\w-]{1,128}$/;++/** Where the person put bots in the one list, as a page sends it: each bot's key, its department ("" for none), and+ * the key of the bot drawn just above it in that list (null at its top). Anything else is dropped. */+export function parseArrangement(entries) {+ if (!Array.isArray(entries)) return [];+ const parsed = entries.slice(0, MAX_LAID).flatMap((entry) => {+ if (!record(entry) || typeof entry.key !== "string" || !LAID_KEY.test(entry.key)) return [];+ const section = entry.section === "" || entry.section === LANDING_SECTION ? entry.section : sectionName(entry.section);+ if (section === "" && entry.section !== "") return [];+ const after = entry.after === null ? null : typeof entry.after === "string" && LAID_KEY.test(entry.after) && entry.after !== entry.key ? entry.after : undefined;+ return after === undefined ? [] : [{ key: entry.key, section, after }];+ });+ // One entry per bot, the last one given: a page repeating a key cannot crowd out every other bot's entry.+ const last = new Map(parsed.map((entry) => [entry.key, entry]));+ return parsed.filter((entry) => last.get(entry.key) === entry);+}+/** A place's `GET /api/bots` answer as rows, in that place's own order. */export function botRows(body, home) {const bots = record(body) && Array.isArray(body.bots) ? body.bots : [];@@ -308,8 +346,8 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca}async function read(home) {- const mine = epoch, last = kept.get(home), said = (entry) => JSON.stringify([entry?.state, entry?.bots, entry?.newBot, entry?.ais]);- const held = (state) => ({ ...last, bots: last?.bots ?? [], state });+ const mine = epoch, last = kept.get(home), said = (entry) => JSON.stringify([entry?.state, entry?.bots, entry?.sections, entry?.newBot, entry?.ais]);+ const held = (state) => ({ ...last, bots: last?.bots ?? [], sections: last?.sections ?? [], state });const signedOut = () => { signIn = true; return { bots: [], state: "signin" }; };let next;try {@@ -323,7 +361,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locaelse if (!response?.ok) { await response?.body?.cancel?.(); next = held("offline"); }else {const body = await response.json(), ais = await aisOf(home, last);- next = ais === "signin" ? signedOut() : { bots: botRows(body, home), state: "ready", newBot: makesNewBots(body), ...ais };+ next = ais === "signin" ? signedOut() : { bots: botRows(body, home), sections: placeSections(body), state: "ready", newBot: makesNewBots(body), ...ais };}}} catch { next = held("offline"); }@@ -387,11 +425,19 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locareturn typeof linked === "string" && linked ? { ...row, address: linked } : row;}+ /** Where this account put bots in the one list, kept beside its switch: a bot's key, its department and the bot above it.+ * Kept through the switch going off, a place asleep or out of reach, and a restart; a bot that is gone keeps its entry+ * too, which costs nothing and brings it back where it was if it returns. */+ function arrangedFor(who) {+ const all = file().kept.arranged;+ return parseArrangement(record(all) && typeof who === "string" && Array.isArray(all[who]) ? all[who] : []);+ }+function otherOf(asking) {const home = otherHome(asking), known = kept.get(home);const state = home === "cloud" && pending?.home === home && (cloud().asleep || known?.state !== "ready") ? "waking": home === "cloud" && cloud().asleep ? "asleep" : known?.state ?? "loading";- return { home, state, bots: (known?.bots ?? []).map((row) => addressed(row)), ...(typeof known?.newBot === "boolean" ? { newBot: known.newBot } : {}) };+ return { home, state, bots: (known?.bots ?? []).map((row) => addressed(row)), ...(known?.sections?.length ? { sections: known.sections } : {}), ...(typeof known?.newBot === "boolean" ? { newBot: known.newBot } : {}) };}return {@@ -417,7 +463,9 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locaif (!active()) return { v: 1, available: available(), on: isOn(), here, other: null, ...notice };watch();void refresh(otherHome(here));- return { v: 1, available: true, on: true, here, other: otherOf(here), ...notice };+ // The person's home place, the same on both pages: the one list puts its bots first wherever the window is.+ const home = String(computer()).startsWith("profile:") ? "cloud" : "computer";+ return { v: 1, available: true, on: true, here, home, other: otherOf(here), arranged: arrangedFor(account()), ...notice };},/** The switch. Off forgets every list. Turned on from Settings on this computer's page, whose words say so, it also* lets My Cloud run commands here (`turnedOn`), so the two places work as one with one switch; the person turns that@@ -484,6 +532,23 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locago(home, "desktop-notifications:open", { botId: row.id, threadId: row.threadId }, OPEN_WAIT_MS);return true;},+ /** The person moved bots in the one list (a drag or Alt+Up/Down, on either page): their entries replace the ones they+ * had. Nothing of either place's own server changes here. What this account has kept now. */+ arrange(asking, entries) {+ sameScope();+ const who = account();+ if (!active() || !who || untouchable()) return arrangedFor(who);+ const next = parseArrangement(entries), keys = new Set(next.map((entry) => entry.key));+ if (!next.length) return arrangedFor(who);+ const { kept } = file();+ const had = arrangedFor(who), before = new Map(had.map((entry) => [entry.key, entry]));+ // The same arrangement again (a drop where the bot already was) writes nothing and tells no page.+ if (next.every((entry) => before.get(entry.key)?.section === entry.section && before.get(entry.key)?.after === entry.after)) return had;+ const merged = [...had.filter((entry) => !keys.has(entry.key)), ...next].slice(-MAX_LAID);+ write({ ...kept, v: 1, arranged: { ...(record(kept.arranged) ? kept.arranged : {}), [who]: merged } });+ tell();+ return merged;+ },/** What the + shows about the other place before a bot is made there: how it is doing, and the AIs ready there* (null while it has not said). The AIs are read with the list's own next read, under the list's rules and its* once-a-minute limit for My Cloud, so opening the + again and again asks nothing more. */@@ -554,6 +619,7 @@ export function installPlacesTogether({ ipcMain, asking, together, rail = () =>return together.set(page, value === true, { listOnly: from === "notice" });});ipcMain.handle("places-together:open", (event, botId) => together.open(side(event), String(botId)));+ ipcMain.handle("places-together:arrange", (event, entries) => together.arrange(side(event), entries));ipcMain.handle("places-together:new-bot-choice", (event) => together.newBotChoice(side(event)));ipcMain.handle("places-together:new-bot", (event) => together.newBot(side(event)));ipcMain.handle("places-together:new-bot-heard", (event) => { side(event); together.newBotHeard(); });diff --git a/electron/places-together.node-test.mjs b/electron/places-together.node-test.mjsindex 59d23dc6e3..f8cafcbd3f 100644--- a/electron/places-together.node-test.mjs+++ b/electron/places-together.node-test.mjs@@ -489,7 +489,7 @@ test("only this computer's page and My Cloud's own page are answered", async ()const handlers = new Map();const f = setup();installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page, together: f.together });- assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard",+ assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:arrange", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard","places-together:notice-shown", "places-together:notice-done", "places-together:commands", "places-together:rail-set"]);for (const [channel, handler] of handlers) assert.throws(() => handler({ page: null }, "nova"), channel === "places-together:rail-set" ? /Only the window's rail/ : /Only this computer's page and My Cloud's page/);assert.equal(handlers.get("places-together:state")({ page: "local" }).here, "computer");@@ -520,7 +520,7 @@ test("main wires it to the one rule for this app's own pages, and the preload ofconst preload = readFileSync(join(HERE, "preload.cjs"), "utf8");assert.match(preload.match(/const REMOTE_SAFE = new Set\(\[([^\]]*)\]\)/)[1], /"placesTogether"/);const bridge = preload.slice(preload.indexOf(" placesTogether: "), preload.indexOf(" twoPlaces: {"));- assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:changed"', '"places-together:changed"',+ assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:arrange"', '"places-together:changed"', '"places-together:changed"','"places-together:notice-shown"', '"places-together:notice-done"', '"places-together:commands"', '"places-together:new-bot-choice"', '"places-together:new-bot"']);});diff --git a/electron/preload.cjs b/electron/preload.cjsindex e1b807f212..48ede65bca 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -649,6 +649,8 @@ const bridge = {? ipcRenderer.invoke("places-together:set", on === true, ...(from === "notice" ? ["notice"] : [])) : Promise.reject(new Error("Turn the switch to list both places' bots.")),open: botId => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("places-together:open", String(botId)) : Promise.reject(new Error("Choose a bot to open it.")),+ // Where the person dragged bots in the one list: main keeps it beside the switch, and checks every entry.+ arrange: entries => ipcRenderer.invoke("places-together:arrange", Array.isArray(entries) ? entries.slice(0, 2000) : []),onChanged: cb => {const handler = () => cb();ipcRenderer.on("places-together:changed", handler);diff --git a/src/components/OtherPlaceBots.dom.test.ts b/src/components/OtherPlaceBots.dom.test.tsindex 3cd1a8f6a7..23ae977fa1 100644--- a/src/components/OtherPlaceBots.dom.test.ts+++ b/src/components/OtherPlaceBots.dom.test.ts@@ -85,10 +85,13 @@ it("a sleeping or unreachable Cloud with nothing kept says so as normal, and theexpect(q("[data-other-place-line]")!.getAttribute("role")).toBe("status");});-it("My Cloud's page lists its own bots only: no line about this computer there, whatever main says", async () => {- for (const power of ["offline", "ready", "loading"] as const) {- said = state({ here: "cloud", other: { home: "computer", state: power, bots: [] } });- await render(createElement(OtherPlaceLine, { key: "line" }));+it("My Cloud's page says so when this computer's bots can't be read, in a line that opens nothing; nothing while they load or are listed", async () => {+ said = state({ here: "cloud", home: "computer", other: { home: "computer", state: "offline", bots: [] } });+ await render(createElement(OtherPlaceLine, { key: "line" }));+ expect(q("[data-other-place-line]")!.textContent).toBe("This computer's bots can't be read right now.");+ expect(q("[data-other-place-line]")!.tagName).toBe("P");+ for (const power of ["ready", "loading"] as const) {+ said = state({ here: "cloud", home: "computer", other: { home: "computer", state: power, bots: power === "ready" ? [row("computer", "git", "Git")] : [] } });await act(async () => changed());expect(q("[data-other-place]")).toBeNull();}@@ -133,7 +136,7 @@ it("My Cloud's page shows the switch only to turn it off: turning it on is thissaid = state({ here: "cloud", on: false, other: null });await render(createElement(SettingsLook.Provider, { key: "switch", value: true }, createElement(PlacesTogetherSwitch)));expect(q("[data-places-together]")).toBeNull();- said = state({ here: "cloud", other: { home: "computer", state: "ready", bots: [] } });+ said = state({ here: "cloud", home: "computer", other: { home: "computer", state: "ready", bots: [] } });await act(async () => changed());expect(q("[data-places-together]")!.getAttribute("data-places-together")).toBe("on");await act(async () => q("[data-places-together] [role=switch]")!.click());diff --git a/src/components/OtherPlaceBots.tsx b/src/components/OtherPlaceBots.tsxindex b33db21a27..a02df14bb5 100644--- a/src/components/OtherPlaceBots.tsx+++ b/src/components/OtherPlaceBots.tsx@@ -1,8 +1,8 @@-// The end of the one list, while "This computer and My Cloud together" is on: the other place's bots are rows among this-// place's own (src/lib/place-rows.ts), so this says something only when that place has no rows to show: My Cloud not+// The end of the one list, while "This computer and My Cloud together" is on: the other place's bots are rows in this+// place's departments (src/lib/one-list.ts), so this says something only when that place has no rows to show: My Cloud not// signed in to yet, or a place that is asleep or can't be reached with nothing kept from before. One quiet line in the// list's secondary text, not a card or a banner; it opens My Cloud where there is something to do there. Nothing while-// the first read is under way, nothing with the switch off, and nothing on My Cloud's page, which lists its own bots only.+// the first read is under way, and nothing with the switch off. On My Cloud's page it speaks of this computer's bots.import { Cloud, CloudMoon, CloudOff, MonitorOff } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";diff --git a/src/components/Sidebar.one-list.dom.test.ts b/src/components/Sidebar.one-list.dom.test.tsindex fe3ebb1797..58bf143bc2 100644--- a/src/components/Sidebar.one-list.dom.test.ts+++ b/src/components/Sidebar.one-list.dom.test.ts@@ -1,11 +1,13 @@// @vitest-environment happy-dom-// The one list in the real Sidebar: with "This computer and My Cloud together" on, the other place's bots are rows among-// this place's own; with it off, or with main never answering, the sidebar is exactly as it was.+// The one list in the real Sidebar: with "This computer and My Cloud together" on, the other place's bots land in a+// department named after their place and can be dragged anywhere from there, and both pages draw the same list; with it+// off, or with main never answering, the sidebar is exactly as it was.import { act, createElement } from "react";+import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Bot } from "@/state/store";-import type { PlaceBotRow, PlacesTogetherState } from "@/lib/places-together";+import type { ArrangedBot, PlaceBotRow, PlacesTogetherState } from "@/lib/places-together";const mode = vi.hoisted(() => ({ advanced: false }));vi.mock("@/lib/interface-mode", async (original) => ({@@ -44,9 +46,12 @@ const page = {set: vi.fn(async () => said()),open: vi.fn(async () => true),onChanged: vi.fn((callback: () => void) => { changed = callback; return () => {}; }),+ arrange: vi.fn(async (entries: ArrangedBot[]) => entries),};+/** This page's store has loaded (its departments are known for sure). */+let hydrated = false;const tree = (bots: Bot[], icons = false) => createElement(BotEditorStore, {- value: { state: { ...initialState, connected: true, bots, selectedId: bots[0]!.id }, dispatch,+ value: { state: { ...initialState, connected: true, bots, selectedId: bots[0]!.id, ...(hydrated ? { hydrated: true as const } : {}) }, dispatch,flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} },children: createElement(Sidebar, { open: true, onClose: () => {}, collapseToIcons: icons }),});@@ -57,6 +62,47 @@ async function render(bots = OWN, icons = false) {const q = (selector: string) => host.querySelector<HTMLElement>(selector);const ids = (selector = "") => [...host.querySelectorAll<HTMLElement>(`${selector} [data-sidebar-bot-row]`)].map((item) => item.dataset.sidebarBotRow);const mark = (id: string) => q(`[data-sidebar-bot-row="${id}"] [data-bot-place]`);+const OWN_BOTS = '[data-sidebar-section-id="builtin:bots"]', MY_CLOUD = '[data-sidebar-section-id="section:My Cloud"]';+/** The list as drawn: each department heading, then its rows by their own ids (a row's place key left out). */+const drawn = () => [...host.querySelectorAll<HTMLElement>("[data-sidebar-section-id] [data-section], [data-sidebar-section-id] [data-sidebar-bot-row]")]+ .map((element) => element.dataset.section ?? element.dataset.sidebarBotRow!.replace(/^(cloud|computer):/, ""));+function transfer() {+ const data = new Map<string, string>();+ return { data, effectAllowed: "all", dropEffect: "none", get types() { return [...data.keys()]; },+ setData: (type: string, value: string) => { data.set(type, value); }, getData: (type: string) => data.get(type) ?? "", setDragImage: () => {}, files: [], items: [] };+}+function fire(target: Element, type: string, carried: ReturnType<typeof transfer>, clientY = 0) {+ const event = new Event(type, { bubbles: true, cancelable: true });+ Object.defineProperty(event, "dataTransfer", { value: carried });+ Object.defineProperty(event, "clientY", { value: clientY });+ flushSync(() => target.dispatchEvent(event));+}+const dragHost = (id: string) => q(`[data-sidebar-bot-row="${id}"]`)?.closest('[draggable="true"]') ?? null;+/** Drags `moving` onto the lower edge of `onto`'s row and lets go. */+/** Each draggable row 50px tall, one under another. */+const rowBoxes = () => vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ const rows = [...document.querySelectorAll('[draggable="true"]')], index = Math.max(0, rows.indexOf(this));+ return { top: index * 50, bottom: index * 50 + 50, height: 50, left: 0, right: 200, width: 200, x: 0, y: index * 50, toJSON: () => ({}) } as DOMRect;+});+/** Drags `moving` onto the middle of `onto`'s row, where a drop starts a department when the page allows it. */+function dragOnto(moving: string, onto: string) {+ const from = dragHost(moving)!, target = dragHost(onto)!, carried = transfer();+ fire(from, "dragstart", carried);+ const box = target.getBoundingClientRect();+ fire(target, "dragover", carried, box.top + box.height / 2);+ fire(target, "drop", carried, box.top + box.height / 2);+ fire(from, "dragend", carried);+}+function dragBelow(moving: string, onto: string) {+ const from = dragHost(moving), target = dragHost(onto), carried = transfer();+ expect(from, `${moving} is draggable`).not.toBeNull();+ expect(target, `${onto} takes a drop`).not.toBeNull();+ fire(from!, "dragstart", carried);+ const box = target!.getBoundingClientRect();+ fire(target!, "dragover", carried, box.bottom - 2);+ fire(target!, "drop", carried, box.bottom - 2);+ fire(from!, "dragend", carried);+}beforeEach(() => {vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);@@ -65,6 +111,7 @@ beforeEach(() => {for (const fn of Object.values(page)) fn.mockClear();answer = async () => said();localStorage.clear();+ hydrated = false;setLocale("en");mode.advanced = false;host = document.createElement("div");@@ -77,6 +124,7 @@ afterEach(async () => {resetPlacesTogetherForTest();resetPlaceRowsForTest();vi.unstubAllGlobals();+ vi.restoreAllMocks();delete (window as { ogb?: unknown }).ogb;});@@ -111,23 +159,26 @@ describe("switch off: nothing changes", () => {});describe("switch on: one list", () => {- it("lists My Cloud's bots in the same list as this computer's, with no group or heading of their own", async () => {+ for (const advanced of [false, true]) it(`${advanced ? "Advanced" : "Simple"}: My Cloud's bots land in a "My Cloud" department after this computer's departments; this computer's bots stay where they were`, async () => {window.ogb = { placesTogether: page } as never;- await render();- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:scout", "cloud:tech"]);+ mode.advanced = advanced;+ await render([...OWN, bot("finn", { section: "Finance" })]);+ expect(ids(OWN_BOTS)).toEqual(["git", "ledger"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:scout", "cloud:tech"]);+ expect(drawn().filter((item) => item !== "Bots")).toEqual(["git", "ledger", "Finance", "finn", "My Cloud", "scout", "tech"]);expect(q('[data-sidebar-section-id="builtin:unread"]')).toBeNull();- expect([...host.querySelectorAll("[data-section]")].map((header) => header.getAttribute("data-section"))).not.toContain("On My Cloud");expect(q("[data-other-place]")).toBeNull();expect(q('[data-sidebar-bot-row="cloud:scout"]')!.textContent).toContain("Open issues");expect(q('[data-sidebar-bot-row="cloud:tech"]')!.textContent).toContain("Deploy passed on staging.");});- it("unread rows of both places keep their places in the one list", async () => {+ it("unread rows of both places keep their places", async () => {window.ogb = { placesTogether: page } as never;const nova = bot("nova", { unread: true, tasks: [{ threadId: "nova-t", title: "Chat", createdAt: 1, updatedAt: 5_000, unread: true }] });answer = async () => said({ other: { home: "cloud", state: "ready", bots: [row("old", { unread: true, lastAt: 1_000 }), row("tech", { unread: true, lastAt: 9_000 })] } });await render([...OWN, nova]);- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "nova", "cloud:old", "cloud:tech"]);+ expect(ids(OWN_BOTS)).toEqual(["git", "ledger", "nova"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:old", "cloud:tech"]);expect(q('[data-sidebar-section-id="builtin:unread"]')).toBeNull();});@@ -135,7 +186,8 @@ describe("switch on: one list", () => {window.ogb = { placesTogether: page } as never;answer = async () => said({ other: { home: "cloud", state: "ready", bots: [row("git", { name: "Git there" })] } });await render();- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:git"]);+ expect(ids(OWN_BOTS)).toEqual(["git", "ledger"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:git"]);expect(q('[data-sidebar-bot-row="cloud:git"]')!.textContent).toContain("Git there");});@@ -226,27 +278,211 @@ describe("switch on: one list", () => {expect(q('[data-sidebar-bot-row="git"]')!.getAttribute("aria-label")).toContain("Lives on this computer");});- it("the rail's two circles: this computer's page has the one list; My Cloud's page lists My Cloud's bots only, as with the switch off", async () => {+ it("dragging a Cloud bot into another department keeps it there through a restart, and My Cloud's page draws the same list; this computer's server never hears of it", async () => {window.ogb = { placesTogether: page } as never;+ const own = [...OWN, bot("finn", { section: "Finance" })];+ const fetched: string[] = [];+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) => { fetched.push(`${init?.method ?? "GET"} ${url} ${String(init?.body ?? "")}`); return new Promise(() => {}); });+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ const rows = [...document.querySelectorAll('[draggable="true"]')], index = Math.max(0, rows.indexOf(this));+ return { top: index * 50, bottom: index * 50 + 50, height: 50, left: 0, right: 200, width: 200, x: 0, y: index * 50, toJSON: () => ({}) } as DOMRect;+ });+ await render(own);+ expect(q('[data-section="Finance"] [aria-haspopup="menu"]')).not.toBeNull();+ dragBelow("cloud:tech", "finn");+ expect(page.arrange).toHaveBeenCalled();+ const kept = page.arrange.mock.calls.at(-1)![0];+ expect(kept).toEqual(expect.arrayContaining([{ key: "cloud:tech", section: "Finance", after: "computer:finn" }]));+ expect(ids('[data-sidebar-section-id="section:Finance"]')).toEqual(["finn", "cloud:tech"]);+ const afterDrag = drawn();+ expect(JSON.stringify(dispatch.mock.calls)).not.toMatch(/cloud:|computer:/);+ expect(fetched.filter((line) => /cloud:|computer:/.test(line))).toEqual([]);+ // A restart: main hands back what it kept.+ const arranged = page.arrange.mock.calls.flatMap(([entries]) => entries);+ vi.restoreAllMocks();+ await act(async () => root.unmount());+ resetPlacesTogetherForTest(); resetPlaceRowsForTest();+ root = createRoot(host);+ answer = async () => said({ arranged });+ await render(own);+ expect(drawn()).toEqual(afterDrag);+ // The window goes to My Cloud's page: the same list, this computer's bots as rows there.+ await act(async () => root.unmount());+ resetPlacesTogetherForTest(); resetPlaceRowsForTest();+ root = createRoot(host);+ answer = async () => said({ here: "cloud", home: "computer", arranged, other: { home: "computer", state: "ready", sections: ["Finance"], bots: [row("git", { home: "computer" }), row("ledger", { home: "computer" }), row("finn", { home: "computer", section: "Finance" })] } });+ await render([bot("maus", { chiefOfStaff: true }), bot("scout", { title: "Open issues" }), bot("tech")]);+ expect(drawn()).toEqual(afterDrag);+ // There, this computer's rows stay where this computer keeps them; My Cloud's own bots are moved through main.+ expect(dragHost("computer:git")).toBeNull();+ expect(dragHost("scout")).not.toBeNull();+ // Its departments are this computer's: their menus belong to this computer's page.+ expect(q('[data-section="Finance"] [aria-haspopup="menu"]')).toBeNull();+ });++ it("before this page's store has loaded, a Cloud bot is drawn in the department it was kept in, and a drag writes only the bot moved", async () => {+ window.ogb = { placesTogether: page } as never;+ rowBoxes();+ const stored: ArrangedBot[] = [{ key: "cloud:scout", section: "Trips", after: null }, { key: "cloud:old", section: "Finance", after: "computer:finn" }];+ answer = async () => said({ arranged: stored, other: { home: "cloud", state: "asleep", bots: [row("scout"), row("tech"), row("old")] } });+ await render([...OWN, bot("finn", { section: "Finance" })]);+ // "Trips" is not among this computer's departments yet: it is drawn as kept, not sent to "My Cloud".+ expect(ids('[data-sidebar-section-id="section:Trips"]')).toEqual(["cloud:scout"]);+ dragBelow("cloud:tech", "finn");+ const sent = page.arrange.mock.calls.flatMap(([entries]) => entries);+ expect(sent.map((entry) => entry.key)).toEqual(["cloud:tech"]);+ // Every other bot's entry is as it was: main's merge leaves it byte for byte.+ const merged = [...stored.filter((entry) => !sent.some((moved) => moved.key === entry.key)), ...sent];+ expect(JSON.stringify(merged.filter((entry) => entry.key !== "cloud:tech"))).toBe(JSON.stringify(stored));+ });++ it("once this page's store has loaded, a Cloud bot kept in a department this computer no longer has goes back to My Cloud's department", async () => {+ window.ogb = { placesTogether: page } as never;+ hydrated = true;+ answer = async () => said({ arranged: [{ key: "cloud:scout", section: "Trips", after: null }] });await render();- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:scout", "cloud:tech"]);+ expect(q('[data-sidebar-section-id="section:Trips"]')).toBeNull();+ expect(ids(MY_CLOUD)).toEqual(["cloud:scout", "cloud:tech"]);+ });++ it("on My Cloud's page while this computer is loading, its own bots stay in the departments they were kept in, and a drag writes only the bot moved", async () => {+ window.ogb = { placesTogether: page } as never;+ rowBoxes();+ const stored: ArrangedBot[] = [{ key: "cloud:scout", section: "Finance", after: null }, { key: "cloud:tech", section: "Finance", after: "cloud:scout" }, { key: "cloud:atlas", section: "", after: null }];+ answer = async () => said({ here: "cloud", home: "computer", arranged: stored, other: { home: "computer", state: "loading", bots: [] } });+ await render([bot("maus", { chiefOfStaff: true }), bot("scout"), bot("tech"), bot("atlas")]);+ expect(ids('[data-sidebar-section-id="section:Finance"]')).toEqual(["scout", "tech"]);+ dragBelow("scout", "tech");+ const sent = page.arrange.mock.calls.flatMap(([entries]) => entries);+ expect(sent.map((entry) => entry.key)).toEqual(["cloud:scout"]);+ expect(JSON.stringify(stored.filter((entry) => entry.key !== "cloud:scout"))).toBe(JSON.stringify([stored[1], stored[2]]));+ });++ it("on My Cloud's page a bot dropped on another never starts a department; on this computer's page it does", async () => {+ window.ogb = { placesTogether: page } as never;+ rowBoxes();+ answer = async () => said({ here: "cloud", home: "computer", other: { home: "computer", state: "ready", bots: [row("git", { home: "computer" })] }, arranged: [{ key: "cloud:scout", section: "", after: null }, { key: "cloud:tech", section: "", after: "cloud:scout" }] });+ await render([bot("maus", { chiefOfStaff: true }), bot("scout"), bot("tech")]);+ dragOnto("tech", "scout");+ expect(q("[data-section-name-field]")).toBeNull();+ vi.restoreAllMocks();await act(async () => root.unmount());resetPlacesTogetherForTest(); resetPlaceRowsForTest();root = createRoot(host);- const cloudBots = [bot("maus", { chiefOfStaff: true }), bot("scout"), bot("atlas")];- const offline = await htmlWith(null, cloudBots);- answer = async () => said({ here: "cloud", other: { home: "computer", state: "ready", bots: [row("git", { home: "computer", unread: true }), row("ledger", { home: "computer" })] } });- const cloudPage = await htmlWith({ placesTogether: page }, cloudBots);- answer = async () => said({ here: "cloud", other: { home: "computer", state: "offline", bots: [] } });- const cloudPageOffline = await htmlWith({ placesTogether: page }, cloudBots);- expect(cloudPage).toBe(offline);- expect(cloudPageOffline).toBe(offline);- expect(cloudPage).not.toContain("computer:");- expect(cloudPage).not.toContain("data-bot-place");- expect(cloudPage).not.toContain("data-other-place");+ rowBoxes();+ answer = async () => said();+ await render();+ dragOnto("ledger", "git");+ expect(q("[data-section-name-field]")).not.toBeNull();+ });++ it("starting a department from Cloud bots: a failed make stores nothing; a department main will not fill is taken away again", async () => {+ window.ogb = { placesTogether: page } as never;+ rowBoxes();+ const calls: string[] = [];+ let make: "fail" | "ok" = "fail";+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {+ calls.push(`${init?.method ?? "GET"} ${url}`);+ if (init?.method === "POST" && make === "fail") return new Response(JSON.stringify({ error: "nope" }), { status: 500, headers: { "content-type": "application/json" } });+ return new Response(JSON.stringify({ sections: [] }), { status: 200, headers: { "content-type": "application/json" } });+ });+ answer = async () => said({ arranged: [{ key: "cloud:scout", section: "", after: "computer:ledger" }, { key: "cloud:tech", section: "", after: "cloud:scout" }] });+ await render();+ const name = async () => { const field = q("[data-section-name-field]")!; await act(async () => { field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); }); await act(async () => { await new Promise((done) => setTimeout(done, 0)); }); };+ dragOnto("cloud:tech", "cloud:scout");+ await name();+ expect(calls.filter((call) => call.startsWith("POST /api/sidebar-sections"))).toHaveLength(1);+ expect(page.arrange).not.toHaveBeenCalled();+ // The make works, but main keeps nothing (here: it hands back what it had): the empty department is deleted again.+ make = "ok";+ page.arrange.mockImplementationOnce(async () => []);+ dragOnto("cloud:tech", "cloud:scout");+ await name();+ await act(async () => { await new Promise((done) => setTimeout(done, 0)); });+ expect(page.arrange).toHaveBeenCalledTimes(1);+ expect(calls.some((call) => call.startsWith("DELETE /api/sidebar-sections?section="))).toBe(true);+ });++ it("home is My Cloud and main's copy of its departments is behind: a drag on this computer's page leaves the \"Design\" entries byte for byte", async () => {+ window.ogb = { placesTogether: page } as never;+ rowBoxes();+ // "Design" was just made on My Cloud's page and the computer's bots dragged into it; main has not read My Cloud since.+ const stored: ArrangedBot[] = [{ key: "computer:git", section: "Design", after: null }, { key: "computer:ledger", section: "Design", after: "computer:git" }];+ answer = async () => said({ here: "computer", home: "cloud", arranged: stored, other: { home: "cloud", state: "ready", sections: ["Research"], bots: [row("scout")] } });+ await render([bot("mausbot", { chiefOfStaff: true }), bot("git"), bot("ledger"), bot("finn")]);+ expect(ids('[data-sidebar-section-id="section:This computer"]')).toEqual(["git", "ledger", "finn"]);+ dragBelow("finn", "git");+ const sent = page.arrange.mock.calls.flatMap(([entries]) => entries);+ expect(sent.map((entry) => entry.key)).toEqual(["computer:finn"]);+ const merged = [...stored.filter((entry) => !sent.some((moved) => moved.key === entry.key)), ...sent];+ expect(JSON.stringify(merged.filter((entry) => entry.key !== "computer:finn"))).toBe(JSON.stringify(stored));+ });++ it("renaming My Cloud's department to a department this computer already has never takes that department away when main will not keep it", async () => {+ window.ogb = { placesTogether: page } as never;+ const calls: string[] = [];+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {+ calls.push(`${init?.method ?? "GET"} ${url}`);+ return new Response(JSON.stringify({ sections: ["Finance"] }), { status: 200, headers: { "content-type": "application/json" } });+ });+ page.arrange.mockImplementation(async () => []);+ await render([...OWN, bot("finn", { section: "Finance" })]);+ await act(async () => q('[data-section="My Cloud"] [aria-haspopup="menu"]')!.click());+ const rename = [...document.body.querySelectorAll<HTMLElement>("[role=menuitem]")].find((item) => item.textContent === "Rename department")!;+ await act(async () => rename.click());+ const field = q("[data-section-name-field]") as HTMLInputElement;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, "Finance");+ field.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => { field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });+ await act(async () => { await new Promise((done) => setTimeout(done, 0)); });+ expect(page.arrange).toHaveBeenCalled();+ expect(calls.filter((call) => call.startsWith("DELETE"))).toEqual([]);+ expect(ids('[data-sidebar-section-id="section:Finance"]')).toContain("finn");+ });++ it("an older app that does not say which place is home leaves My Cloud's page as it was: its own bots only", async () => {+ const cloudBots = [bot("maus", { chiefOfStaff: true }), bot("scout", { section: "Research" }), bot("atlas")];+ const browser = await htmlWith(null, cloudBots);+ answer = async () => said({ here: "cloud", other: { home: "computer", state: "ready", bots: [row("git", { home: "computer" }), row("ledger", { home: "computer" })] } });+ const { arrange: _newer, ...older } = page;+ expect(await htmlWith({ placesTogether: older }, cloudBots)).toBe(browser);+ expect(browser).toContain("Research");+ });++ it("the place's own department, which only the app keeps, offers no menu item that would name it to this computer's server", async () => {+ window.ogb = { placesTogether: page } as never;+ await render([...OWN, bot("finn", { section: "Finance" })]);+ const menuOf = async (name: string) => {+ await act(async () => q(`[data-section="${name}"] [aria-haspopup="menu"]`)!.click());+ const items = [...document.body.querySelectorAll<HTMLElement>("[role=menuitem]")];+ const said = { share: items.some((item) => item.textContent === "Share"), read: items.some((item) => item.hasAttribute("data-team-mark-read") || item.hasAttribute("data-team-pause")), rename: items.some((item) => item.textContent === "Rename department") };+ await act(async () => { document.body.querySelector("[role=menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ return said;+ };+ expect((await menuOf("Finance")).share).toBe(true);+ expect(await menuOf("My Cloud")).toEqual({ share: false, read: false, rename: true });+ });++ it("a new Cloud bot lands in My Cloud's department; one already placed stays put", async () => {+ window.ogb = { placesTogether: page } as never;+ answer = async () => said({ arranged: [{ key: "cloud:scout", section: "", after: "computer:git" }],+ other: { home: "cloud", state: "ready", bots: [row("scout"), row("tech"), row("nova")] } });+ await render();+ expect(ids(OWN_BOTS)).toEqual(["git", "cloud:scout", "ledger"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:tech", "cloud:nova"]);+ });++ it("with My Cloud as home, this computer's bots land in a \"This computer\" department on either page", async () => {+ window.ogb = { placesTogether: page } as never;+ answer = async () => said({ here: "computer", home: "cloud", other: { home: "cloud", state: "ready", bots: [row("scout"), row("tech")] } });+ await render();+ expect(ids(OWN_BOTS)).toEqual(["cloud:scout", "cloud:tech"]);+ expect(ids('[data-sidebar-section-id="section:This computer"]')).toEqual(["git", "ledger"]);});- it("rows of the other place come in at the end and show their marks at once, with the pointer on the list, moving no row", async () => {+ it("rows of the other place come in below this place's own and show their marks at once, with the pointer on the list, moving no row", async () => {window.ogb = { placesTogether: page } as never;let release!: (value: PlacesTogetherState) => void;answer = () => new Promise((resolve) => { release = resolve; });@@ -255,7 +491,8 @@ describe("switch on: one list", () => {const local = ids();await act(async () => release(said({ other: { home: "cloud", state: "ready", bots: [row("tech", { unread: true, lastAt: 9_000 }), row("scout", { working: true })] } })));expect(ids().slice(0, local.length)).toEqual(local);- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:tech", "cloud:scout"]);+ expect(ids(OWN_BOTS)).toEqual(["git", "ledger"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:tech", "cloud:scout"]);expect(q('[data-sidebar-section-id="builtin:unread"]')).toBeNull();// No wait for the list to go quiet: Scout's working mark shows now, in its place.expect(q('[data-sidebar-bot-row="cloud:scout"] [data-testid="working-dot"]')).not.toBeNull();@@ -276,7 +513,7 @@ describe("switch on: one list", () => {window.ogb = { placesTogether: page } as never;answer = async () => said({ other: { home: "cloud", state: "asleep", bots: [row("scout", { working: true }), row("atlas")] } });await render();- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:scout", "cloud:atlas"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:scout", "cloud:atlas"]);expect(mark("cloud:scout")!.getAttribute("data-bot-place")).toBe("cloud-asleep");expect(q('[data-sidebar-bot-row="cloud:scout"] [data-testid="working-dot"]')).toBeNull();});@@ -315,6 +552,7 @@ describe("switch on: one list", () => {expect(ids()).toEqual(["mausbot", "git", "ledger"].filter((id) => q(`[data-sidebar-bot-row="${id}"]`)));expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger"]);await act(async () => release(said()));- expect(ids('[data-sidebar-section-id="builtin:bots"]')).toEqual(["git", "ledger", "cloud:scout", "cloud:tech"]);+ expect(ids(OWN_BOTS)).toEqual(["git", "ledger"]);+ expect(ids(MY_CLOUD)).toEqual(["cloud:scout", "cloud:tech"]);});});diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex a3e2e55ca0..4a5f162314 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -73,7 +73,7 @@ import { SidebarProfileMenu } from "./SidebarProfileMenu";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { GlassBar, GlassScrollFrame, GlassScroller } from "./GlassScrollFrame";import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher"; import { PlaceTint } from "./PlaceTint"; import { ChromeRailToggle } from "./ChromeRailToggle";-import { useCloudOwner } from "./CloudOwner"; import { OtherPlaceLine } from "./OtherPlaceBots"; import { BotPlaceBadge, BotPlaceMark } from "./BotPlaceMark"; import { isPlacedBot, NO_MENU, otherPlaceDispatch, ownRows, placedLine, rowPlaceMark, useOneListHere, useOtherPlaceBots, withOtherPlace } from "@/lib/place-rows"; import type { BotHome } from "@/lib/places-together"; import { NewBotOtherPlaceItem, useNewBotHereLabel } from "./NewBotPlaceItems";+import { useCloudOwner } from "./CloudOwner"; import { OtherPlaceLine } from "./OtherPlaceBots"; import { BotPlaceBadge, BotPlaceMark } from "./BotPlaceMark"; import { isPlacedBot, NO_MENU, otherPlaceDispatch, placedLine, rowPlaceMark, useOneListHere, useOtherPlaceBots } from "@/lib/place-rows"; import { useOneList } from "./one-list-sidebar"; const NO_SECTIONS: string[] = []; import type { BotHome } from "@/lib/places-together"; import { NewBotOtherPlaceItem, useNewBotHereLabel } from "./NewBotPlaceItems";import { SidebarSectionHeader } from "./SidebarSectionHeader";import { NeedsYouButton, OwnerPickerHost } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople"; import { SidebarInboxRow } from "./SidebarInboxRow"; import { TeamSideSwitch, useTeamSideLists } from "./TeamSideSwitch"; import { SidebarActiveThreads } from "./SidebarActiveThreads"; import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned"; import { useInboxSupport } from "@/state/inbox";import { TeamMenuItems } from "./SidebarTeamMenu";@@ -1089,9 +1089,9 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =b.projects?.some((folder) => folder.name.toLowerCase().includes(q)),);const visibleGroups = sideLists.groups.filter((g) => !q || g.name.toLowerCase().includes(q) || g.tasks?.some((task) => task.title.toLowerCase().includes(q)));- const viewerEmail = useViewerEmail(), placed = useOtherPlaceBots(q), placeHere = useOneListHere();- const parts = partitionSidebarBots(botDrag.preview(matchingBots), { universalPins, viewerEmail, welcoming: useWelcomingBot(), searching: Boolean(q) });- const saved = withOtherPlace(simpleDesk ? withPrimaryTile(parts, myDefaultBot(state.bots, viewerEmail)?.id) : { ...parts, primary: null }, placed);+ const viewerEmail = useViewerEmail(), placed = useOtherPlaceBots(q), placeHere = useOneListHere(), oneList = useOneList(matchingBots, placed, state.sections ?? NO_SECTIONS, dispatch, state.hydrated === true);+ const parts = partitionSidebarBots(botDrag.preview(oneList?.bots ?? matchingBots), { universalPins, viewerEmail, welcoming: useWelcomingBot(), searching: Boolean(q) });+ const saved = simpleDesk ? withPrimaryTile(parts, myDefaultBot(state.bots, viewerEmail)?.id) : { ...parts, primary: null };// Rows keep their place while the app is in use: unread, work and a wait on the person show as marks on the row, never// as a move to the top or into an Unread list. Only a pin, a drag, Alt+Up/Down or a move to a department moves a row.const floats = () => false;@@ -1099,8 +1099,8 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const { pinnedBots, filed, unreadBots, unreadCount, sectionChiefs, sectionedBots, unsectionedBots, inPlace } = sidebarBotRows(saved, floats, false);const { botChats, sectionedRooms, unsectionedRooms } = partitionSidebarGroups(visibleGroups);- const sectionNames = sectionsInUse([...(state.sections ?? []).filter((name) => !q || name.toLowerCase().includes(q.toLowerCase())), ...botDrag.pending], [...filed, ...sectionedRooms]);- const drops = botDrag.arrange({ enabled: (sections.interactive || density === "icons") && !phone, withinList: density === "icons", main: ownRows(inPlace.unsectionedBots), sectioned: inPlace.sectionedBots, departments: sectionNames, bots: state.bots, taken: departmentNames(state), floats });+ const sectionNames = sectionsInUse([...(oneList?.sections ?? state.sections ?? []).filter((name) => !q || name.toLowerCase().includes(q.toLowerCase())), ...botDrag.pending], [...filed, ...sectionedRooms]);+ const drops = botDrag.arrange({ enabled: (sections.interactive || density === "icons") && !phone, withinList: density === "icons", main: inPlace.unsectionedBots, sectioned: inPlace.sectionedBots, departments: sectionNames, bots: state.bots, taken: departmentNames(state), floats, route: oneList?.route });const naturalSectionIds = [...(pinnedBots.length > 0 && !universalPins && !simpleDesk ? [PINNED_SECTION_ID] : []),...(unsectionedRooms.length > 0 ? [CHANNELS_SECTION_ID] : []),@@ -1118,7 +1118,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const showAttention = (advanced && inboxSupport === "no") || (attentionPinned && density !== "icons");const attention = showAttention ? crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups) : [];const restoreBot = teamFeedback?.restoreBot, pendingUndo = teamFeedback?.undo ?? (restoreBot ? () => void undoBotArchive(restoreBot) : undefined);- const botRow = (bot: Bot) => isPlacedBot(bot) ? botRowProps(state, otherPlaceDispatch(bot), bot, { density, query: q, onMenu: NO_MENU, placeHere }) : botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, placeHere, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });+ const botRow = (bot: Bot) => isPlacedBot(bot) ? botRowProps(state, otherPlaceDispatch(bot), bot, { density, query: q, onMenu: NO_MENU, placeHere, ...drops.row(bot.id) }) : botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, placeHere, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });const railSearch = () => {if (collapseToIcons) return openCommandPalette();setSearchOpen(true);@@ -1356,7 +1356,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =</div>))}{sectionIds.map((id, index) => {- const sectionName = userSectionName(id);+ const sectionName = userSectionName(id), editable = oneList?.mirror ? null : sectionName;const sectionChiefItems = sectionName? sectionChiefs.filter((bot) => bot.section === sectionName): [];@@ -1404,20 +1404,20 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =<SidebarSectionHeadername={sectionLabel(id)}line={simple} reserveMenu={simple && !remoteClient}- onMenu={simple && !remoteClient && sectionName ? (button) => {+ onMenu={simple && !remoteClient && editable ? (button) => {const rect = button.getBoundingClientRect();- openTeamMenu(sectionName, rect.right - 256, rect.bottom + 4, button);+ openTeamMenu(editable, rect.right - 256, rect.bottom + 4, button);} : undefined}menuOpen={teamMenu !== null && teamMenu.name === sectionName}- onContextMenu={!remoteClient && layoutInteractive && sectionName ? (event) => {+ onContextMenu={!remoteClient && layoutInteractive && editable ? (event) => {event.preventDefault();- openTeamMenu(sectionName, event.clientX, event.clientY, event.currentTarget.querySelector<HTMLElement>("button") ?? event.currentTarget);+ openTeamMenu(editable, event.clientX, event.clientY, event.currentTarget.querySelector<HTMLElement>("button") ?? event.currentTarget);} : undefined}collapsed={collapsed}attention={attention}onToggle={layoutInteractive ? () => toggleSection(id) : undefined}{...layout.header(id)} {...(id === UNREAD_SECTION_ID && { ...(unreadCount > 0 && { count: unreadCount }), reorderable: false })} naming={drops.naming(sectionName)} dropInto={drops.into(sectionName)}- onDelete={!simple && !remoteClient && sectionName ? () => setDeletingTeam(sectionName) : undefined} onShare={!simple && !remoteClient && sectionName ? () => setShareTeam(sectionName) : undefined}+ onDelete={!simple && !remoteClient && editable ? () => setDeletingTeam(editable) : undefined} onShare={!simple && !remoteClient && editable && !oneList?.virtual(editable) ? () => setShareTeam(editable) : undefined}/>)}{collapsed && queued.length > 0 && <button type="button" onClick={() => toggleSection(id)}@@ -1445,8 +1445,8 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =listItem={BotListItem}/>) : sectionBotItems.map((bot) => <BotListItem key={bot.id} {...botRow(bot)} />)}- {!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 })}+ {!remoteClient && editable && layoutInteractive && !drops.naming(sectionName) && (!simple || sectionChiefItems.length + sectionGroupItems.length + sectionBotItems.length === 0) && (+ <button onClick={() => void (oneList?.realize(editable) ?? Promise.resolve()).then(() => setMoveToTeam(editable), () => {})} aria-label={t(state.bots.some(bot => !bot.hidden && bot.section?.trim() === sectionName) ? "team.manageBotsIn" : "team.addBotsTo", { name: editable })}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")}</button>@@ -1509,7 +1509,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =onCancel={cancelConfirm} returnFocusRef={sidebarRef} /><OwnerPickerHost />{newTeam && <TeamDialog onClose={() => setNewTeam(false)} />}- {renameTeam && <TeamDialog section={renameTeam} rename onRenamed={sections.renamed} onClose={() => setRenameTeam(null)} />}+ {renameTeam && <TeamDialog section={renameTeam} rename onRenamed={(from, to) => { oneList?.renamed(from, to); sections.renamed(from, to); }} 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}@@ -1518,13 +1518,13 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =navigateThreadMenu(event);}}><TeamMenuItems- department={teamMotion.value!.name} onRead={closeTeamMenu} onAddBots={() => { closeTeamMenu(); setMoveToTeam(teamMotion.value!.name); }}+ department={oneList?.virtual(teamMotion.value!.name) ? undefined : teamMotion.value!.name} onRead={closeTeamMenu} onAddBots={() => { closeTeamMenu(); const name = teamMotion.value!.name; void (oneList?.realize(name) ?? Promise.resolve()).then(() => setMoveToTeam(name), () => {}); }}onMoveUp={sections.interactive ? () => { layout.header(userSectionId(teamMotion.value!.name)).onMove(-1); } : undefined}onMoveDown={sections.interactive ? () => { layout.header(userSectionId(teamMotion.value!.name)).onMove(1); } : undefined}- onRename={() => { closeTeamMenu(); (advanced ? setRenameTeam : botDrag.startRename)(teamMotion.value!.name); }}- onShare={() => { closeTeamMenu(); setShareTeam(teamMotion.value!.name); }}+ onRename={() => { closeTeamMenu(); (advanced && !oneList?.virtual(teamMotion.value!.name) ? setRenameTeam : botDrag.startRename)(teamMotion.value!.name); }}+ onShare={oneList?.virtual(teamMotion.value!.name) ? undefined : () => { closeTeamMenu(); setShareTeam(teamMotion.value!.name); }}onDelete={() => { closeTeamMenu(); setDeletingTeam(teamMotion.value!.name); }}- onSetForAll={teamSettingsAllowed === true ? () => { closeTeamMenu(); setTeamSettings(teamMotion.value!.name); } : undefined}+ onSetForAll={teamSettingsAllowed === true && !oneList?.virtual(teamMotion.value!.name) ? () => { closeTeamMenu(); setTeamSettings(teamMotion.value!.name); } : undefined}/></div></div>, document.body)}@@ -1536,7 +1536,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =if (!name || teamDeleteRunning.current) return;teamDeleteRunning.current = true;setTeamDeletePending(true);- void api(`/api/sidebar-sections?section=${encodeURIComponent(name)}`, { method: "DELETE" })+ const remove = () => api<{ sections: string[] }>(`/api/sidebar-sections?section=${encodeURIComponent(name)}`, { method: "DELETE" }); void (oneList ? oneList.deleteDepartment(name, remove) : remove()).then(({ sections }) => { dispatch({ type: "sectionDeleted", section: name, sections }); setDeletingTeam(null); }).catch(cause => setTeamFeedback({ error: true, text: cause instanceof Error ? cause.message : String(cause) })).finally(() => { teamDeleteRunning.current = false; setTeamDeletePending(false); });diff --git a/src/components/SidebarBotDrag.tsx b/src/components/SidebarBotDrag.tsxindex 2e602b228f..df96b64dbf 100644--- a/src/components/SidebarBotDrag.tsx+++ b/src/components/SidebarBotDrag.tsx@@ -6,6 +6,7 @@ import { BOTS_SECTION_ID, userSectionName } from "@/lib/sidebar-layout";import { BOT_ROW_DRAG_TYPE, botDropPlace, botListOf, planBotDrop, sameBotDrop, savedPlacement, stepBot, unusedName, type BotDrop, type BotDropPlace, type BotMove } from "@/lib/sidebar-bot-drop";import type { Action, Bot } from "@/state/store";import { moveBotsToSection, renameDepartment, saveBotOrder, useMayMoveBots } from "./bot-sections";+import type { OneListRoute } from "./one-list-sidebar";/** The department being named, before it exists. The server trims names and never keeps a control character. */export const NEW_DEPARTMENT = "\u0000new";@@ -22,7 +23,7 @@ export type SectionNaming = { value: string; label: string; onCommit: (name: strtype Naming = { kind: "new"; botIds: string[]; name: string } | { kind: "rename"; section: string };/** `lists` hold each list's saved order, `shown` the order drawn (working or waiting bots, `floating`, first). */-type Arranged = { enabled: boolean; lists: Map<string, string[]>; shown: Map<string, string[]>; floating: Set<string>; bots: Bot[]; taken: string[]; withinList: boolean };+type Arranged = { enabled: boolean; lists: Map<string, string[]>; shown: Map<string, string[]>; floating: Set<string>; bots: Bot[]; taken: string[]; withinList: boolean; route?: OneListRoute };/** A list as the sidebar draws it: working or waiting bots first, each part in its saved order. */const drawnOrder = (ids: readonly string[], floating: ReadonlySet<string>) => [...ids.filter((id) => floating.has(id)), ...ids.filter((id) => !floating.has(id))];@@ -73,13 +74,19 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst startNew = (botIds: string[]) => setNaming({ kind: "new", botIds, name: unusedName(t("sidebar.section.newName"), latest.current.taken) });const apply = (botId: string, move: BotMove, keyboard: boolean) => {if (move.kind === "group") return startNew(move.botIds);- const { lists, shown, bots, floating } = latest.current;+ const { lists, shown, bots, floating, route } = latest.current;const order = savedPlacement(lists.get(move.section) ?? [], move.order, botId, (id) => floating.has(id)), after = drawnOrder(order, floating);- const across = botListOf(lists, botId) !== move.section;+ const from = botListOf(lists, botId), across = from !== move.section;// Alt+Up/Down past a bot that floats otherwise changes nothing drawn: no move, so nothing to say.if (keyboard && !across && after.every((id, index) => id === shown.get(move.section)?.[index])) return;- if (across) moveBotsToSection(actions.current.dispatch, [botId], move.section);- saveBotOrder(actions.current.dispatch, bots, order);+ // With the one list on, this page's server hears only of its own bots; main keeps where the other place's go, and+ // each list a bot left or joined is written again there, so no bot is kept under one that moved away.+ if (across && (!route || route.server(botId))) moveBotsToSection(actions.current.dispatch, [botId], move.section);+ saveBotOrder(actions.current.dispatch, bots, route ? order.filter((id) => route.server(id)) : order);+ if (route) {+ if (across && from !== undefined) route.place(from, (lists.get(from) ?? []).filter((id) => id !== botId), botId);+ route.place(move.section, order, botId);+ }if (!keyboard) return;const name = bots.find((bot) => bot.id === botId)?.name ?? "";actions.current.announce(t("sidebar.section.moved", { name, position: after.indexOf(botId) + 1, count: after.length }));@@ -103,7 +110,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onEr};const rowDrop = (event: DragEvent<HTMLElement>, botId: string): BotDrop => {const box = event.currentTarget.getBoundingClientRect();- const canGroup = !latest.current.withinList && botListOf(latest.current.lists, botId) === "";+ const canGroup = !latest.current.withinList && botListOf(latest.current.lists, botId) === "" && latest.current.route?.group !== false;return { kind: "row", botId, place: botDropPlace(event.clientY - box.top, box.height, canGroup) };};@@ -144,13 +151,15 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErconst 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);+ const name = draft.trim() || current.name, route = latest.current.route;+ moveBotsToSection(dispatch, current.botIds.filter((id) => (!route || route.server(id)) && latest.current.bots.some((bot) => bot.id === id && !bot.hidden)), name);+ route?.place(name, current.botIds.filter((id) => route.kept(id)));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)));+ const route = latest.current.route, from = current.section;+ if (to) (route ? route.rename(from, to, () => renameDepartment(dispatch, from, to)) : renameDepartment(dispatch, from, to)).then(() => onRenamed(from, to), (cause) => onError(failure(cause)));};return {@@ -160,15 +169,17 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onErstartRename: (section: string) => setNaming({ kind: "rename", section }),/** `main` and `sectioned` in their saved order; `floats` says which bots the sidebar draws first in their list. A drop* or Alt+Up/Down moves a bot among the rows as drawn, and is saved into the saved order (savedPlacement). */- arrange({ enabled, withinList = false, main, sectioned, departments, bots, taken, floats }: {+ arrange({ enabled, withinList = false, main, sectioned, departments, bots, taken, floats, route }: {enabled: boolean; withinList?: boolean; main: Bot[]; sectioned: Bot[]; departments: string[]; bots: Bot[]; taken: string[]; floats?: (bot: Bot) => boolean;+ /** With the one list on: which bots this page's server arranges, which main keeps, and which stay put here. */+ route?: OneListRoute;}) {const movable = enabled && mayMove;const lists = new Map<string, string[]>([["", main.map((bot) => bot.id)]]);for (const name of departments) if (name !== NEW_DEPARTMENT) lists.set(name, sectioned.filter((bot) => bot.section === name).map((bot) => bot.id));const floating = new Set(floats ? [...main, ...sectioned].filter(floats).map((bot) => bot.id) : []);const drawn = new Map([...lists].map(([name, ids]) => [name, drawnOrder(ids, floating)]));- latest.current = { enabled: movable, lists, shown: drawn, floating, bots, taken, withinList };+ latest.current = { enabled: movable, lists, shown: drawn, floating, bots, taken, withinList, route };const listOf = new Map<string, string>();for (const [list, ids] of lists) for (const id of ids) listOf.set(id, list);const active = movable && dragging !== null && listOf.has(dragging) ? dragging : null;@@ -186,7 +197,7 @@ export function useSidebarBotDrag({ dispatch, announce, onNamed, onRenamed, onEr};return {row: (botId: string): { botDrag?: BotRowDrag; botDrop?: BotDropPlace | null; botDragging?: boolean } => {- if (!movable || !listOf.has(botId)) return {};+ if (!movable || !listOf.has(botId) || (route && !route.movable(botId))) 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 };diff --git a/src/components/SidebarTeamMenu.tsx b/src/components/SidebarTeamMenu.tsxindex 3e446157d0..2cb9070339 100644--- a/src/components/SidebarTeamMenu.tsx+++ b/src/components/SidebarTeamMenu.tsx@@ -59,7 +59,9 @@ export function TeamMenuItems({ onAddBots, onRename, onShare, onDelete, onSetForonRead?: () => void;onAddBots: () => void;onRename: () => void;- onShare: () => void;+ /** Absent for a department this computer's server does not have (the one list's place department, which only the app+ * keeps): sharing it would name a department the server lacks. */+ onShare?: () => void;onDelete: () => void;onSetForAll?: () => void;/** Reorder the department where dragging can't: on a phone, or from a menu. */@@ -76,7 +78,7 @@ export function TeamMenuItems({ onAddBots, onRename, onShare, onDelete, onSetFor{department !== undefined && <PauseDepartment name={department} className={cn(item, "disabled:opacity-60")} onDone={onRead ?? (() => {})} />}{onSetForAll && <button type="button" role="menuitem" className={item} onClick={onSetForAll}><SlidersHorizontal size={16} />{t("teamSettings.menu")}</button>}<button type="button" role="menuitem" className={item} onClick={onRename}><SquarePen size={16} />{t("team.rename")}</button>- <button type="button" role="menuitem" className={item} onClick={onShare}><Share2 size={16} />{t("team.shareDepartment")}</button>+ {onShare && <button type="button" role="menuitem" className={item} onClick={onShare}><Share2 size={16} />{t("team.shareDepartment")}</button>}<button type="button" role="menuitem" className={cn(item, "text-danger [&>svg]:text-danger")} onClick={onDelete}><Trash2 size={16} />{t("team.delete")}</button></>);diff --git a/src/components/one-list-sidebar.ts b/src/components/one-list-sidebar.tsnew file mode 100644index 0000000000..6cff3628e8--- /dev/null+++ b/src/components/one-list-sidebar.ts@@ -0,0 +1,108 @@+// The sidebar's side of the one list (src/lib/one-list.ts): the bots laid out in departments for this page, and what a+// drag, a rename or a delete does with a bot or department that main keeps rather than this page's server.+import type { Dispatch } from "react";+import { arrangedEntries, layOneList, leftEntries, placeDepartment, renamedEntries } from "@/lib/one-list";+import { isPlacedBot, oneListOn, type PlacedBot } from "@/lib/place-rows";+import { arrangeOneList, usePlacesTogetherPart, type ArrangedBot, type BotHome, type PlacesTogetherState } from "@/lib/places-together";+import { t } from "@/lib/i18n";+import { api, type Action, type Bot } from "@/state/store";++/** What a drag of the one list does with each bot: this page's server keeps the place of its own bots on the home+ * place's page (`server`); main keeps the other place's (`kept`); a bot of the home place on the other page is drawn+ * where its own place keeps it and is not moved from there (`movable`). */+export interface OneListRoute {+ server(id: string): boolean;+ kept(id: string): boolean;+ movable(id: string): boolean;+ /** `order`: the list's ids as drawn after a move; `moved`: the bot the person moved, when it was one. */+ place(list: string, order: readonly string[], moved?: string): void;+ /** Dropping a bot on another starts a department: not on the other page, which can make no department of the home+ * place's. */+ group: boolean;+ rename(from: string, to: string, onServer: () => Promise<void>): Promise<void>;+}++export interface OneList {+ bots: Bot[];+ sections: string[];+ route: OneListRoute;+ /** The other page: its departments are the home place's, so its own department menus are not offered here. */+ mirror: boolean;+ /** A department only main's entries hold (the place's own department, or one a bot of the other place was put in). */+ virtual(name: string): boolean;+ /** A department of this page's server was renamed: the bots main keeps in it follow. */+ renamed(from: string, to: string): void;+ deleteDepartment(name: string, onServer: () => Promise<{ sections: string[] }>): Promise<{ sections: string[] }>;+ /** Makes a department only main holds a department of this page's server, before bots of its own are added to it. */+ realize(name: string): Promise<void> | null;+}++type View = { here: BotHome; home: BotHome; arranged: readonly ArrangedBot[]; sections: readonly string[]; ready: boolean };+let lastView: { state: PlacesTogetherState | null; text: string; view: View | null } = { state: null, text: "", view: null };+const viewOf = (state: PlacesTogetherState | null): View | null => {+ if (state === lastView.state) return lastView.view;+ const view = oneListOn(state) ? { here: state!.here, home: state!.home ?? "computer", arranged: state!.arranged ?? [], sections: state!.other?.sections ?? [], ready: state!.other?.state === "ready" } : null;+ const text = JSON.stringify(view);+ lastView = { state, text, view: text === lastView.text ? lastView.view : view };+ return lastView.view;+};++/** The one list for this page while it is on; null with it off. `own`: this page's bots as the sidebar shows them (search+ * applied), `placed`: the other place's rows, `ownSections`: this page's server's departments, `loaded`: this page's+ * store has loaded them. */+export function useOneList(own: Bot[], placed: readonly PlacedBot[], ownSections: readonly string[], dispatch: Dispatch<Action>, loaded: boolean): OneList | null {+ const view = usePlacesTogetherPart(viewOf);+ if (!view) return null;+ const { here, home, arranged } = view, mirror = here !== home;+ const keyOf = (id: string) => (id.includes(":") ? id : `${here}:${id}`);+ const kept = (id: string) => id.includes(":") !== mirror;+ const otherPlace = home === "cloud" ? "computer" : "cloud", keptKey = (key: string) => key.startsWith(`${otherPlace}:`);+ const landing = placeDepartment(home === "cloud" ? "computer" : "cloud"), certain = mirror ? view.ready : loaded;+ const laid = layOneList<Bot>({ certain,+ homeBots: mirror ? placed : own, homeSections: mirror ? view.sections : ownSections, otherBots: mirror ? own : placed,+ arranged, keyOf: (bot) => (isPlacedBot(bot) ? bot.id : keyOf(bot.id)), landing,+ });+ const virtual = (name: string) => !mirror && !ownSections.includes(name) && !own.some((bot) => bot.section === name);+ /** A department this page's server lacks is made there first (empty), so the layout, which holds a bot only in a+ * department the home place has or in the place's own, keeps it. */+ const create = (name: string) => api<{ sections: string[] }>("/api/sidebar-sections", { method: "POST", body: JSON.stringify({ name, botIds: [] }) })+ .then(({ sections }) => { dispatch({ type: "sections", sections }); });+ /** A department made for bots main then would not keep is taken away again, and the person is told. */+ const unmake = (name: string) => api<{ sections: string[] }>(`/api/sidebar-sections?section=${encodeURIComponent(name)}`, { method: "DELETE" })+ .then(({ sections }) => { dispatch({ type: "sectionDeleted", section: name, sections }); }, () => {}).then(() => { throw new Error(t("together.switch.failed")); });+ const renamed = (from: string, to: string) => arrangeOneList(renamedEntries(laid.bots, arranged, from, to, kept, keyOf, keptKey, laid.fallback, landing));+ const leave = (name: string) => {+ const moved = leftEntries(laid.bots, arranged, name, kept, keyOf, keptKey, laid.fallback, landing);+ if (moved) arrangeOneList(moved);+ };+ // While the home place's departments are not known for sure, a move writes the moved bot only: every other bot's+ // entry is carried through as it was, never rewritten from a place it is only drawn in for now. A bot drawn where+ // the layout fell back is never written unless it is the one being moved.+ const place = (list: string, order: readonly string[], moved?: string) => arrangeOneList(arrangedEntries(list, order, kept, keyOf, landing)+ .filter((entry) => (moved !== undefined && entry.key === keyOf(moved)) || (!laid.fallback.has(entry.key) && (certain || moved === undefined))));+ const failed = (cause: unknown) => { dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }); };+ return {+ bots: laid.bots, sections: laid.sections, mirror, virtual, renamed,+ route: {+ server: (id) => !mirror && !id.includes(":"),+ kept,+ movable: (id) => !mirror || !id.includes(":"),+ place: (list, order, moved) => {+ if (!(list && list !== landing && virtual(list) && order.some(kept))) return void place(list, order, moved);+ // A failed make stores nothing, so the drop goes back; a department main would not fill is taken away again.+ void create(list).then(() => place(list, order, moved).then((saved) => (saved ? undefined : unmake(list)))).catch(failed);+ },+ group: !mirror,+ // The place's own department, while only main holds it, becomes a department of the new name on this page's+ // server, and every bot drawn in it moves there; new bots of the other place land in the place's own again.+ // Only a department this rename made is taken away again: one of that name that was there before stays.+ rename: (from, to, onServer) => {+ const fresh = virtual(to), refused = () => (fresh ? unmake(to) : Promise.reject(new Error(t("together.switch.failed"))));+ return virtual(from) ? create(to).then(() => renamed(from, to)).then((saved) => (saved ? undefined : refused())) : onServer().then(() => { void renamed(from, to); });+ },+ },+ deleteDepartment: (name, onServer) => (virtual(name) ? Promise.resolve(leave(name)).then(() => ({ sections: [...ownSections] }))+ : onServer().then((answer) => { leave(name); return answer; })),+ realize: (name) => (virtual(name) ? create(name) : null),+ };+}diff --git a/src/components/sidebar-state.ts b/src/components/sidebar-state.tsindex cc72ef4d39..7321c764bb 100644--- a/src/components/sidebar-state.ts+++ b/src/components/sidebar-state.ts@@ -8,7 +8,7 @@ const NO_RUNS: NonNullable<AppState["routineRuns"]> = [];export const sidebarState = (s: AppState) => ({bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, instances: s.instances, config: s.config, selectedId: s.selectedId, newChat: s.newChat,activeView: s.activeView, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, deletingBots: s.deletingBots, revealThread: s.revealThread,- liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, routineRuns: s.routineRuns, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,+ liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, routineRuns: s.routineRuns, hydrated: s.hydrated, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,});export function botPendingQueued(bot: Pick<Bot, "threadId" | "tasks">, pendingQueued: AppState["pendingQueued"]): AppState["pendingQueued"] {diff --git a/src/lib/one-list.test.ts b/src/lib/one-list.test.tsnew file mode 100644index 0000000000..e5a0645114--- /dev/null+++ b/src/lib/one-list.test.ts@@ -0,0 +1,229 @@+import { beforeEach, describe, expect, it } from "vitest";+import type { Bot } from "@/state/store";+import { loadLocale, setLocale } from "./i18n";+import { arrangedEntries, deletedEntries, LANDING_SECTION, layOneList, leftEntries, placeDepartment, renamedEntries } from "./one-list";+import type { ArrangedBot } from "./places-together";++const bot = (id: string, over: Partial<Bot> = {}): Bot => ({ id, name: id, threadId: `${id}-t`, title: "", description: "", color: "green", unread: false,+ notifications: true, messages: [], modelSelection: { instanceId: "here", model: "m" }, ...over });+const keyed = (place: string) => (b: Bot) => (b.id.includes(":") ? b.id : `${place}:${b.id}`);+/** The list as drawn: each department's name, then its bots by key. */+const drawn = (laid: { bots: Bot[]; sections: string[] }, keyOf: (b: Bot) => string) => ["", ...laid.sections].flatMap((section) => {+ const rows = laid.bots.filter((b) => (b.section ?? "") === section).map(keyOf);+ return section ? [`# ${section}`, ...rows] : rows;+});++beforeEach(() => setLocale("en"));+/** My Cloud's bots' keys: what main keeps the place of on this computer's page. */+const cloudKey = (key: string) => key.startsWith("cloud:");+const NOFALL: ReadonlySet<string> = new Set();++// This computer is home: Git Tasks outside any department, Ledger in Finance. My Cloud has Scout and Atlas.+const computer = [bot("git"), bot("ledger", { section: "Finance" })];+const cloud = [bot("scout"), bot("atlas")];+/** This computer's page: its own bots, and My Cloud's as rows. */+const onComputer = (arranged: ArrangedBot[], cloudBots = cloud) => {+ const keyOf = keyed("computer");+ return drawn(layOneList({ certain: true, homeBots: computer, homeSections: ["Finance"], otherBots: cloudBots.map((b) => bot(`cloud:${b.id}`, b.section ? { section: b.section } : {})), arranged, keyOf, landing: placeDepartment("cloud") }), keyOf);+};+/** My Cloud's page: this computer's bots as rows (each saying its department there), and its own. */+const onCloud = (arranged: ArrangedBot[], cloudBots = cloud) => {+ const keyOf = keyed("cloud");+ return drawn(layOneList({ certain: true, homeBots: computer.map((b) => bot(`computer:${b.id}`, b.section ? { section: b.section } : {})), homeSections: ["Finance"], otherBots: cloudBots, arranged, keyOf, landing: placeDepartment("cloud") }), keyOf);+};++describe("the one list's departments", () => {+ it("the other place's bots land in a department named after their place, after the home place's departments", () => {+ expect(onComputer([])).toEqual(["computer:git", "# Finance", "computer:ledger", "# My Cloud", "cloud:scout", "cloud:atlas"]);+ expect(placeDepartment("computer")).toBe("This computer");+ });++ it("their own department there does not count here: until moved, they are in their place's department", () => {+ expect(onComputer([], [bot("scout", { section: "Research" }), bot("atlas")])).toEqual(["computer:git", "# Finance", "computer:ledger", "# My Cloud", "cloud:scout", "cloud:atlas"]);+ });++ it("a bot dragged anywhere stays there, among the home place's bots too, in the order it was put", () => {+ const arranged: ArrangedBot[] = [+ { key: "cloud:atlas", section: "Finance", after: null },+ { key: "cloud:scout", section: "", after: "computer:git" },+ ];+ expect(onComputer(arranged)).toEqual(["computer:git", "cloud:scout", "# Finance", "cloud:atlas", "computer:ledger"]);+ });++ it("both pages draw the same list: the home place's departments and order, and the other place's bots where they were put", () => {+ for (const arranged of [[], [{ key: "cloud:atlas", section: "Finance", after: "computer:ledger" }, { key: "cloud:scout", section: "", after: null }]] as ArrangedBot[][]) {+ expect(onCloud(arranged)).toEqual(onComputer(arranged));+ }+ });++ it("a new bot of the other place lands in the place's department; a bot already placed is never pulled back there", () => {+ const arranged: ArrangedBot[] = [{ key: "cloud:scout", section: "Finance", after: null }];+ expect(onComputer(arranged, [...cloud, bot("nova")])).toEqual(["computer:git", "# Finance", "cloud:scout", "computer:ledger", "# My Cloud", "cloud:atlas", "cloud:nova"]);+ });++ it("a bot placed under one that left its department, or is gone, goes to the end of its department; a chain of moved bots keeps its order", () => {+ const arranged: ArrangedBot[] = [+ { key: "cloud:atlas", section: "", after: "cloud:scout" },+ { key: "cloud:scout", section: "", after: "computer:ledger" },+ ];+ expect(onComputer(arranged)).toEqual(["computer:git", "cloud:scout", "cloud:atlas", "# Finance", "computer:ledger"]);+ expect(onComputer([{ key: "cloud:scout", section: "", after: "cloud:gone" }])).toEqual(["computer:git", "cloud:scout", "# Finance", "computer:ledger", "# My Cloud", "cloud:atlas"]);+ });++ it("a pinned bot or a Chief outside any department stays where its own page draws it and is not laid out", () => {+ const keyOf = keyed("cloud");+ const laid = layOneList({ certain: true, homeBots: [], homeSections: [], otherBots: [bot("maus", { chiefOfStaff: true }), bot("pin", { pinned: true }), bot("scout")], arranged: [], keyOf, landing: "My Cloud" });+ expect(laid.bots.map((b) => [b.id, b.section ?? ""])).toEqual([["maus", ""], ["pin", ""], ["scout", "My Cloud"]]);+ });++ it("pinned bots keep their own order across departments, as with the switch off", () => {+ const home = [bot("a", { section: "A" }), bot("p1", { pinned: true, section: "B" }), bot("p2", { pinned: true, section: "A" }), bot("p3", { pinned: true })];+ const laid = layOneList({ certain: true, homeBots: home, homeSections: ["A", "B"], otherBots: [], arranged: [], keyOf: keyed("computer"), landing: "My Cloud" });+ expect(laid.bots.filter((b) => b.pinned).map((b) => b.id)).toEqual(["p1", "p2", "p3"]);+ expect(laid.bots.filter((b) => b.pinned).every((b, index) => b === home.filter((h) => h.pinned)[index])).toBe(true);+ });++ it("a row that did not move is the same value from one layout to the next, so it is not drawn again", () => {+ const rows = cloud.map((b) => bot(`cloud:${b.id}`));+ const lay = () => layOneList({ certain: true, homeBots: computer, homeSections: ["Finance"], otherBots: rows, arranged: [], keyOf: keyed("computer"), landing: "My Cloud" }).bots;+ lay().forEach((b, index) => expect(b).toBe(lay()[index]));+ });+});++describe("what main keeps when bots move", () => {+ const keyOf = (id: string) => (id.includes(":") ? id : `computer:${id}`);+ const kept = (id: string) => id.includes(":");++ it("every bot main keeps in the list is written with the bot drawn just above it; this page's own bots are not", () => {+ expect(arrangedEntries("Finance", ["cloud:atlas", "ledger", "cloud:scout"], kept, keyOf)).toEqual([+ { key: "cloud:atlas", section: "Finance", after: null },+ { key: "cloud:scout", section: "Finance", after: "computer:ledger" },+ ]);+ expect(arrangedEntries("", ["git", "ledger"], kept, keyOf)).toEqual([]);+ });++ it("a deleted department sends its bots to the end of the list outside any department", () => {+ expect(deletedEntries(["cloud:atlas", "cloud:nova"], ["computer:git", "cloud:scout"])).toEqual([+ { key: "cloud:atlas", section: "", after: "cloud:scout" },+ { key: "cloud:nova", section: "", after: "cloud:atlas" },+ ]);+ expect(deletedEntries([], ["computer:git"])).toBeNull();+ });++ /** This computer's page laid out with `arranged`, as the sidebar holds it. */+ const laidOut = (arranged: ArrangedBot[], homeSections = ["Finance"]) => layOneList({ certain: true, homeBots: computer, homeSections,+ otherBots: cloud.map((b) => bot(`cloud:${b.id}`)), arranged, keyOf: keyed("computer"), landing: "My Cloud" }).bots;++ it("renaming the place's department moves every Cloud bot drawn in it, also the ones only there by landing", () => {+ // No bot was ever moved: both are in "My Cloud" by landing, and both follow the rename.+ expect(renamedEntries(laidOut([]), [], "My Cloud", "Trips", kept, keyOf, cloudKey, NOFALL, "My Cloud")).toEqual([+ { key: "cloud:scout", section: "Trips", after: null },+ { key: "cloud:atlas", section: "Trips", after: "cloud:scout" },+ ]);+ // One was put there by hand, one landed: still both, in the order drawn, never split.+ const some: ArrangedBot[] = [{ key: "cloud:atlas", section: LANDING_SECTION, after: null }];+ expect(renamedEntries(laidOut(some), some, "My Cloud", "Trips", kept, keyOf, cloudKey, NOFALL, "My Cloud").map((entry) => [entry.key, entry.section])).toEqual([["cloud:atlas", "Trips"], ["cloud:scout", "Trips"]]);+ // Once "Trips" is made on this computer's server (the rename does that first), no bot is left behind in "My Cloud".+ const renamed = [...some, ...renamedEntries(laidOut(some), some, "My Cloud", "Trips", kept, keyOf, cloudKey, NOFALL, "My Cloud")];+ const keyOfBot = keyed("computer");+ expect(drawn(layOneList({ certain: true, homeBots: computer, homeSections: ["Finance", "Trips"], otherBots: cloud.map((b) => bot(`cloud:${b.id}`)), arranged: renamed, keyOf: keyOfBot, landing: "My Cloud" }), keyOfBot))+ .toEqual(["computer:git", "# Finance", "computer:ledger", "# Trips", "cloud:atlas", "cloud:scout"]);+ expect(renamedEntries(laidOut([]), [], "Finance", "Money", kept, keyOf, cloudKey, NOFALL, "My Cloud")).toEqual([]);+ });+});++describe("while the home place's departments are not known yet", () => {+ // The app is starting, or the place is loading, asleep or out of reach: no rows and no departments of it are here.+ const stored: ArrangedBot[] = [{ key: "cloud:atlas", section: "Finance", after: null }, { key: "cloud:scout", section: "Trips", after: null }];++ it("every Cloud bot is drawn under the department it was kept in, on this computer's page while its store loads", () => {+ const keyOf = keyed("computer");+ const lay = (certain: boolean) => drawn(layOneList({ certain, homeBots: [], homeSections: [], otherBots: cloud.map((b) => bot(`cloud:${b.id}`)), arranged: stored, keyOf, landing: "My Cloud" }), keyOf);+ expect(lay(false)).toEqual(["# Trips", "cloud:scout", "# Finance", "cloud:atlas"]);+ // Once the departments are known for sure, one the home place lacks sends its bot back to the place's own.+ expect(lay(true)).toEqual(["# My Cloud", "cloud:scout", "cloud:atlas"]);+ });++ it("on My Cloud's page while this computer is loading, asleep or out of reach, too", () => {+ const keyOf = keyed("cloud");+ const lay = (certain: boolean) => drawn(layOneList({ certain, homeBots: [], homeSections: [], otherBots: cloud, arranged: stored, keyOf, landing: "My Cloud" }), keyOf);+ expect(lay(false)).toEqual(["# Trips", "cloud:scout", "# Finance", "cloud:atlas"]);+ expect(lay(true)).toEqual(["# My Cloud", "cloud:scout", "cloud:atlas"]);+ });++ it("a rename while the Cloud is asleep, or while a search hides its bots, still carries every bot kept in that department", () => {+ const keyOf = (id: string) => (id.includes(":") ? id : `computer:${id}`), kept = (id: string) => id.includes(":");+ // Asleep: no Cloud bot is drawn at all; a search: only Scout is.+ expect(renamedEntries(computer, stored, "Finance", "Money", kept, keyOf, cloudKey, NOFALL, "My Cloud")).toEqual([{ key: "cloud:atlas", section: "Money", after: null }]);+ const searched = [bot("cloud:scout", { section: "Finance" })];+ expect(renamedEntries(searched, [...stored, { key: "cloud:nova", section: "Finance", after: "cloud:atlas" }], "Finance", "Money", kept, keyOf, cloudKey, NOFALL, "My Cloud")).toEqual([+ { key: "cloud:scout", section: "Money", after: null },+ { key: "cloud:atlas", section: "Money", after: null },+ { key: "cloud:nova", section: "Money", after: "cloud:atlas" },+ ]);+ });+});++describe("departments that change elsewhere, and the language", () => {+ it("a Cloud bot kept in a department the home place no longer has goes back to the place's own department", () => {+ // "Trips" was renamed or deleted on the Team map, in another window or on a phone: no department of that name is drawn.+ expect(onComputer([{ key: "cloud:atlas", section: "Trips", after: null }])).toEqual(["computer:git", "# Finance", "computer:ledger", "# My Cloud", "cloud:scout", "cloud:atlas"]);+ expect(onCloud([{ key: "cloud:atlas", section: "Trips", after: null }])).toEqual(onComputer([{ key: "cloud:atlas", section: "Trips", after: null }]));+ // While the home place has it, the bot stays there.+ const keyOf = keyed("computer");+ expect(drawn(layOneList({ certain: true, homeBots: computer, homeSections: ["Finance", "Trips"], otherBots: [bot("cloud:atlas")], arranged: [{ key: "cloud:atlas", section: "Trips", after: null }], keyOf, landing: "My Cloud" }), keyOf))+ .toEqual(["computer:git", "# Finance", "computer:ledger", "# Trips", "cloud:atlas"]);+ });++ it("the place's own department is kept as a mark, drawn in the person's language; one kept under its name before still reads as it", async () => {+ // Home is My Cloud: this computer's bots land in "This computer".+ const keyOf = keyed("cloud");+ const arranged: ArrangedBot[] = [{ key: "computer:git", section: LANDING_SECTION, after: null }, { key: "computer:ledger", section: "This computer", after: "computer:git" }];+ const lay = (landing: string) => drawn(layOneList({ certain: true, homeBots: [], homeSections: [], otherBots: [bot("computer:ledger"), bot("computer:git")], arranged, keyOf, landing }), keyOf);+ expect(lay(placeDepartment("computer"))).toEqual(["# This computer", "computer:git", "computer:ledger"]);+ await loadLocale("pt-br");+ const there = placeDepartment("computer");+ expect(there).not.toBe("This computer");+ // Another language: the marked bot follows the name; the one kept as text goes back to the place's own department.+ expect(lay(there)).toEqual([`# ${there}`, "computer:git", "computer:ledger"]);+ expect(arrangedEntries(there, ["computer:git"], (id) => id.includes(":"), (id) => id, there)).toEqual([{ key: "computer:git", section: LANDING_SECTION, after: null }]);+ });+});++describe("a place the layout only fell back to is never written", () => {+ const keyOf = (id: string) => (id.includes(":") ? id : `computer:${id}`), kept = (id: string) => id.includes(":");+ // "Design" is on the home place, but main's copy of its departments is behind: Atlas is drawn in "My Cloud" for now.+ const stored: ArrangedBot[] = [{ key: "cloud:atlas", section: "Design", after: null }];+ const laid = () => layOneList({ certain: true, homeBots: computer, homeSections: ["Finance"], otherBots: cloud.map((b) => bot(`cloud:${b.id}`)), arranged: stored, keyOf: keyed("computer"), landing: "My Cloud" });++ it("the layout says which bots it fell back for", () => {+ expect([...laid().fallback]).toEqual(["cloud:atlas"]);+ expect(laid().bots.find((b) => b.id === "cloud:atlas")!.section).toBe("My Cloud");+ });++ it("deleting or renaming the place's department leaves such a bot's entry alone", () => {+ const { bots, fallback } = laid();+ expect(leftEntries(bots, stored, "My Cloud", kept, keyOf, cloudKey, fallback, "My Cloud")!.map((entry) => entry.key)).toEqual(["cloud:scout"]);+ expect(renamedEntries(bots, stored, "My Cloud", "Trips", kept, keyOf, cloudKey, fallback, "My Cloud").map((entry) => entry.key)).toEqual(["cloud:scout"]);+ });+});++describe("a delete or rename reaches every Cloud bot kept in that department, and only those", () => {+ const keyOf = (id: string) => (id.includes(":") ? id : `computer:${id}`), kept = (id: string) => id.includes(":");+ const stored: ArrangedBot[] = [{ key: "cloud:atlas", section: "Finance", after: "computer:ledger" }, { key: "cloud:nova", section: "Finance", after: "cloud:atlas" }];++ it("a delete with the Cloud asleep (none drawn) or a search hiding some still sends them all out of the department", () => {+ expect(leftEntries(computer, stored, "Finance", kept, keyOf, cloudKey, NOFALL, "My Cloud")).toEqual([+ { key: "cloud:atlas", section: "", after: "computer:git" },+ { key: "cloud:nova", section: "", after: "cloud:atlas" },+ ]);+ const searched = [bot("git"), bot("cloud:atlas", { section: "Finance" })];+ expect(leftEntries(searched, stored, "Finance", kept, keyOf, cloudKey, NOFALL, "My Cloud")!.map((entry) => [entry.key, entry.section])).toEqual([["cloud:atlas", ""], ["cloud:nova", ""]]);+ });++ it("an entry left over for one of this computer's own bots is not renamed or moved", () => {+ const withOwn: ArrangedBot[] = [...stored, { key: "computer:old", section: "Finance", after: null }];+ expect(renamedEntries(computer, withOwn, "Finance", "Money", kept, keyOf, cloudKey, NOFALL, "My Cloud").map((entry) => entry.key)).toEqual(["cloud:atlas", "cloud:nova"]);+ expect(leftEntries(computer, withOwn, "Finance", kept, keyOf, cloudKey, NOFALL, "My Cloud")!.map((entry) => entry.key)).toEqual(["cloud:atlas", "cloud:nova"]);+ });+});diff --git a/src/lib/one-list.ts b/src/lib/one-list.tsnew file mode 100644index 0000000000..7f62972183--- /dev/null+++ b/src/lib/one-list.ts@@ -0,0 +1,149 @@+// Where each bot sits in the one list (src/lib/place-rows.ts), the same on both pages. The person's home place keeps its+// own departments and order on its own server, as ever. The other place's bots first land in a department named after+// their place ("My Cloud", or "This computer" when home is My Cloud), after the home place's departments; from there the+// person drags them anywhere, among the home place's bots too. Main keeps where they were put, for the signed-in account,+// beside the switch (electron/places-together.mjs `arranged`): never in either place's own server, and kept through a+// restart and the switch going off. A bot with no entry yet, a new one, lands in the place's department; a bot the person+// placed stays where they put it.+//+// Both pages lay the list out with the same inputs. On the home place's page, its bots are this page's own and the other+// place's come as rows; on the other page it is the other way round, with each home row saying its department there.+import type { Bot } from "@/state/store";+import { t } from "./i18n";+import type { ArrangedBot, BotHome } from "./places-together";++/** The department the other place's bots land in until the person moves them: the place's own name, in the person's+ * language when drawn. */+export const placeDepartment = (home: BotHome): string => t(home === "cloud" ? "cloudSetup.myCloud" : "place.local");++/** How main keeps "the place's own department": a mark no department name can be (a server name has no control+ * character), so a change of language never splits it. An entry kept before this, under the department's name as text,+ * still reads the same while that is its name. */+export const LANDING_SECTION = "\u0000landing";++export interface OneListInput<B extends Bot> {+ /** The home place's bots in its own order, each in its own department (`section`). A pinned bot or a Chief outside any+ * department is left where it comes, as for the other place. */+ homeBots: readonly B[];+ /** The home place's departments in its own order. */+ homeSections: readonly string[];+ /** The other place's bots in that place's order. A pinned bot or a Chief outside any department stays where its own+ * page draws it (a tile, the pinned list) and is not laid out here. */+ otherBots: readonly B[];+ /** Where the person put bots, from main. */+ arranged: readonly ArrangedBot[];+ /** A bot's key in the one list: its place and its own id there. */+ keyOf: (bot: B) => string;+ /** Where a bot of the other place with no entry lands. */+ landing: string;+ /** The home place's departments are known for sure (its page's store has loaded; on the other page, that place is+ * ready). Only then does a bot kept in a department the home place lacks go back to the place's own: while they are+ * not known yet (the app starting, a place loading, asleep or out of reach), every bot is drawn where it was kept. */+ certain: boolean;+}++/** A bot in a given department, kept while both stay the same so a row that did not move is not drawn again. */+const filedCopies = new WeakMap<object, Map<string, object>>();+function filed<B extends Bot>(bot: B, section: string): B {+ if ((bot.section ?? "") === section) return bot;+ let copies = filedCopies.get(bot);+ if (!copies) filedCopies.set(bot, (copies = new Map()));+ let copy = copies.get(section) as B | undefined;+ if (!copy) copies.set(section, (copy = { ...bot, section: section || undefined }));+ return copy;+}++/** Stays where its own page draws it: a pinned bot, or a Chief outside any department. */+export const pageLevel = (bot: Bot): boolean => Boolean(bot.pinned) || (Boolean(bot.chiefOfStaff) && !bot.section);++/** The one list's bots in order, each in its department, and the departments in order: the home place's, then any other+ * a bot was put in (the place's department among them). Each department's bots keep the relative order given here. */+export function layOneList<B extends Bot>({ homeBots, homeSections, otherBots, arranged, keyOf, landing, certain }: OneListInput<B>): { bots: B[]; sections: string[]; fallback: ReadonlySet<string> } {+ const lists = new Map<string, string[]>(), byKey = new Map<string, B>(), sectionOf = new Map<string, string>();+ const list = (section: string) => { let ids = lists.get(section); if (!ids) lists.set(section, (ids = [])); return ids; };+ const kept: B[] = [];+ for (const bot of homeBots) {+ // Pinned bots are one list drawn across departments, in their own order: they are left as they come.+ if (pageLevel(bot)) { kept.push(bot); continue; }+ const key = keyOf(bot), section = bot.section ?? "";+ byKey.set(key, bot); sectionOf.set(key, section); list(section).push(key);+ }+ const entries = new Map(arranged.map((entry) => [entry.key, entry]));+ // A department the home place no longer has (renamed or deleted elsewhere: the Team map, another window, a phone) holds+ // nothing here: its bots go back to the place's own department, never to a department of a name the server lacks.+ const known = new Set(["", landing, ...homeSections, ...homeBots.map((bot) => bot.section ?? "")]);+ const sectionFor = (entry: ArrangedBot | undefined) => (!entry ? undefined : entry.section === LANDING_SECTION ? landing : !certain || known.has(entry.section) ? entry.section : undefined);+ let waiting: Array<{ key: string; section: string; after: string | null | undefined }> = [];+ /** Bots kept somewhere the layout could not draw them, shown in the place's own department instead: never written+ * from where they are drawn, so main's list being behind can never cost the person where they put them. */+ const fallback = new Set<string>();+ for (const bot of otherBots) {+ if (pageLevel(bot)) { kept.push(bot); continue; }+ const key = keyOf(bot), entry = entries.get(key), section = sectionFor(entry);+ byKey.set(key, bot);+ if (entry && section === undefined) fallback.add(key);+ waiting.push(section !== undefined ? { key, section, after: entry!.after } : { key, section: landing, after: undefined });+ }+ // A bot goes in right under the bot it was put under, once that one is in place; at the top for none. One whose bot+ // above is gone, or now in another department, goes at the end of its department, as does a new one.+ for (let moved = true; moved && waiting.length;) {+ moved = false;+ waiting = waiting.filter((bot) => {+ if (bot.after === undefined) return true;+ const ids = list(bot.section);+ const at = bot.after === null ? -1 : ids.indexOf(bot.after);+ if (bot.after !== null && at < 0) {+ if (sectionOf.has(bot.after) || !waiting.some((other) => other.key === bot.after)) bot.after = undefined;+ return true;+ }+ ids.splice(at + 1, 0, bot.key); sectionOf.set(bot.key, bot.section); moved = true;+ return false;+ });+ }+ for (const bot of waiting) { list(bot.section).push(bot.key); sectionOf.set(bot.key, bot.section); }+ const bots: B[] = [];+ for (const [section, ids] of lists) for (const key of ids) bots.push(filed(byKey.get(key)!, section));+ return { bots: [...kept, ...bots], sections: [...new Set([...homeSections, ...[...lists.keys()].filter(Boolean)])], fallback };+}++/** Each bot moved into or out of `list`, and every bot of that list main keeps, as main keeps them: its department, and+ * the bot drawn just above it. `order` is the list's ids as drawn after the move; `kept` says which ids main keeps the+ * place of; `keyOf` names them. Every kept bot of the list is written again, so no entry is left pointing at a bot that+ * moved away. */+export function arrangedEntries(list: string, order: readonly string[], kept: (id: string) => boolean, keyOf: (id: string) => string, landing?: string): ArrangedBot[] {+ const section = list === landing ? LANDING_SECTION : list;+ return order.flatMap((id, index) => (kept(id) ? [{ key: keyOf(id), section, after: index > 0 ? keyOf(order[index - 1]!) : null }] : []));+}++/** Which of the bots drawn, and which entries main keeps, a rename or a delete of `name` is about: the other place's bots+ * drawn in it (in the order drawn), except any only drawn there because its own department could not be (`fallback`),+ * and every entry of the other place's (`keptKey`) whose kept department is `name`, drawn or not (its place asleep, or a+ * search hiding it). */+function inDepartment(bots: readonly Bot[], arranged: readonly ArrangedBot[], name: string, kept: (id: string) => boolean, keyOf: (id: string) => string, keptKey: (key: string) => boolean, fallback: ReadonlySet<string>, landing?: string) {+ const drawn = bots.filter((bot) => !pageLevel(bot) && (bot.section ?? "") === name && !fallback.has(keyOf(bot.id))).map((bot) => bot.id);+ const keys = new Set(drawn.filter(kept).map(keyOf));+ const stored = arranged.filter((entry) => keptKey(entry.key) && !keys.has(entry.key) && (entry.section === name || (name === landing && entry.section === LANDING_SECTION)));+ return { drawn, stored };+}++/** A department renamed: every bot of the other place in it follows (inDepartment), the drawn ones in the order drawn.+ * `bots` is the list as laid out (layOneList). */+export function renamedEntries(bots: readonly Bot[], arranged: readonly ArrangedBot[], from: string, to: string, kept: (id: string) => boolean, keyOf: (id: string) => string, keptKey: (key: string) => boolean, fallback: ReadonlySet<string>, landing?: string): ArrangedBot[] {+ const { drawn, stored } = inDepartment(bots, arranged, from, kept, keyOf, keptKey, fallback, landing), section = to === landing ? LANDING_SECTION : to;+ return [...arrangedEntries(to, drawn, kept, keyOf, landing), ...stored.map((entry) => ({ ...entry, section }))];+}++/** A department deleted: every bot of the other place in it (inDepartment) goes to the end of the list outside any+ * department. Null when none was. */+export function leftEntries(bots: readonly Bot[], arranged: readonly ArrangedBot[], name: string, kept: (id: string) => boolean, keyOf: (id: string) => string, keptKey: (key: string) => boolean, fallback: ReadonlySet<string>, landing?: string): ArrangedBot[] | null {+ const { drawn, stored } = inDepartment(bots, arranged, name, kept, keyOf, keptKey, fallback, landing);+ return deletedEntries([...drawn.filter(kept).map(keyOf), ...stored.map((entry) => entry.key)], bots.filter((bot) => !pageLevel(bot) && !bot.section).map((bot) => keyOf(bot.id)));+}++/** A department deleted: its bots kept by main (`members`, in the order drawn) go to the end of the list outside any+ * department, as a deleted department's own bots leave it. `mainOrder` is that list's keys as drawn now. */+export function deletedEntries(members: readonly string[], mainOrder: readonly string[]): ArrangedBot[] | null {+ if (!members.length) return null;+ const order = [...mainOrder.filter((key) => !members.includes(key)), ...members];+ return members.map((key) => ({ key, section: "", after: order[order.indexOf(key) - 1] ?? null }));+}diff --git a/src/lib/place-rows.test.ts b/src/lib/place-rows.test.tsindex 0de341580e..38f8656756 100644--- a/src/lib/place-rows.test.ts+++ b/src/lib/place-rows.test.ts@@ -4,9 +4,8 @@ import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Bot } from "@/state/store";import { setLocale } from "./i18n";-import { isPlacedBot, otherPlaceDispatch, useOtherPlaceBots, ownRows, placedBot, placedLine, placeMark, placeOfHome, resetPlaceRowsForTest, withOtherPlace, type Place } from "./place-rows";+import { isPlacedBot, otherPlaceDispatch, useOtherPlaceBots, placedBot, placedLine, placeMark, placeOfHome, resetPlaceRowsForTest, type Place } from "./place-rows";import { resetPlacesTogetherForTest, type PlaceBotRow, type PlacesTogetherState } from "./places-together";-import { partitionSidebarBots, sidebarBotRows } from "./sidebar-layout";const row = (home: "computer" | "cloud", id: string, over: Partial<PlaceBotRow> = {}): PlaceBotRow => ({ home, id, threadId: `t-${id}`, name: id, color: "blue", ...over });const own = (id: string, over: Partial<Bot> = {}): Bot => ({ id, name: id, threadId: `${id}-t`, title: "", description: "", color: "green", unread: false,@@ -37,6 +36,11 @@ describe("a row of the other place as a bot of the one list", () => {expect(placedBot(row("cloud", "x", { color: "url(javascript:1)" }), "ready").color).toBe("green");});+ it("carries its department there, so the other page draws a bot of the home place in it", () => {+ expect(placedBot(row("computer", "ledger", { section: "Finance" }), "ready").section).toBe("Finance");+ expect("section" in placedBot(row("computer", "git"), "ready")).toBe(false);+ });+it("shows its title as its second line in Simple, and nothing in Advanced, whose row shows it as the role", () => {const bot = placedBot(row("cloud", "nova", { title: "Research" }), "ready");expect(placedLine(bot, false)).toBe("Research");@@ -76,48 +80,6 @@ describe("a row of the other place as a bot of the one list", () => {});});-describe("one list: the other place's rows among this place's own", () => {- const list = (bots: Bot[], placed: Bot[]) => {- const parts = withOtherPlace(partitionSidebarBots(bots), placed.filter(isPlacedBot));- return sidebarBotRows(parts, (bot) => Boolean(bot.busy) || bot.activity === "waiting-on-you");- };-- it("joins the main list after this place's own, and working bots of either place float to the top together", () => {- const placed = [placedBot(row("cloud", "scout"), "ready"), placedBot(row("cloud", "atlas", { working: true }), "ready")];- const rows = list([own("chief", { chiefOfStaff: true }), own("git"), own("ledger", { busy: true })], placed);- expect(rows.unsectionedBots.map((bot) => bot.id)).toEqual(["ledger", "cloud:atlas", "git", "cloud:scout"]);- });-- it("this place's Chief keeps its place; the other place's Chief is a row, so both are listed", () => {- const parts = withOtherPlace(partitionSidebarBots([own("chief", { chiefOfStaff: true }), own("git")]), [placedBot(row("cloud", "maus", { chief: true }), "ready")]);- expect(parts.unsectionedChief?.id).toBe("chief");- expect(parts.unsectionedBots.map((bot) => bot.id)).toEqual(["git", "cloud:maus"]);- });-- it("unread rows of both places go into one Unread group, newest first, by each row's own time", () => {- const placed = [placedBot(row("cloud", "old", { unread: true, lastAt: 100 }), "ready"), placedBot(row("cloud", "new", { unread: true, lastAt: 900 }), "ready"), placedBot(row("cloud", "read"), "ready")];- const mid = own("mid", { unread: true, messages: [{ id: "m", role: "bot", kind: "text", text: "hi", at: 500 } as Bot["messages"][number]] });- const rows = list([mid, own("quiet")], placed);- expect(rows.unreadBots.map((bot) => bot.id)).toEqual(["cloud:new", "mid", "cloud:old"]);- expect(rows.unreadCount).toBe(3);- expect(rows.unsectionedBots.map((bot) => bot.id)).toEqual(["quiet", "cloud:read"]);- });-- it("a drag or Alt+Up/Down arranges and saves this place's own rows only", () => {- const placed = placedBot(row("cloud", "scout"), "ready");- const rows = list([own("a"), own("b")], [placed]);- expect(rows.inPlace.unsectionedBots.map((bot) => bot.id)).toEqual(["a", "b", "cloud:scout"]);- expect(ownRows(rows.inPlace.unsectionedBots).map((bot) => bot.id)).toEqual(["a", "b"]);- const plain = [own("a")];- expect(ownRows(plain)).toBe(plain);- });-- it("with no rows of the other place, the parts are handed back as they were", () => {- const parts = partitionSidebarBots([own("a")]);- expect(withOtherPlace(parts, [])).toBe(parts);- });-});-describe("what a row of the other place does", () => {it("choosing it opens its bot where it lives, by its own id there, once per click; nothing else is sent anywhere", async () => {const open = vi.fn(async () => true);diff --git a/src/lib/place-rows.ts b/src/lib/place-rows.tsindex 3d1fbe4d2d..893c88c523 100644--- a/src/lib/place-rows.ts+++ b/src/lib/place-rows.ts@@ -1,11 +1,10 @@// One list of bots: with "This computer and My Cloud together" on (electron/places-together.mjs), the other place's bots-// sit among this page's own, in the same list, Unread and order, instead of in a group of their own. A row of the other-// place becomes a Bot-shaped value the sidebar places and draws like any other. Its id is its place's key and its own id+// sit among this page's own, in its departments and order (src/lib/one-list.ts lays them out). A row of the other place+// becomes a Bot-shaped value the sidebar places and draws like any other. Its id is its place's key and its own id// (`cloud:scout`), so two bots with one id in two places never meet, and nothing that writes to this place's server is// ever handed one: what such a row sends is either "open it", which main does where the bot lives, or dropped.//-// The one list is this computer's page's: the page the rail's first circle opens. My Cloud's page, opened from its own-// circle, lists My Cloud's bots only, as it does with the switch off, so the rail still shows the Cloud on its own.+// Both pages draw it, the same way: this computer's page, and My Cloud's own page, which lists this computer's bots.//// Everything here is keyed by a place, not by "My Cloud": today the places are this computer and My Cloud, and a// person's own always-on machine (a server of their own, or a computer at home) is meant to join the same list later@@ -78,6 +77,8 @@ export function placedBot(row: PlaceBotRow, health: PlaceHealth, place: Place =// No engine of this place: no model badge, and nothing here runs it.modelSelection: { instanceId: "", model: "" },messages: [],+ // Its department there: the one list draws a bot of the home place in it on the other page too.+ ...(row.section ? { section: row.section } : {}),placedFrom: { place, id: row.id, health, ...(row.preview ? { preview: row.preview } : {}), ...(row.chat ? { chat: row.chat } : {}) },...(row.lastAt !== undefined ? { lastAt: row.lastAt } : {}),};@@ -98,8 +99,10 @@ let lastList: readonly PlacedBot[] = NONE;* asleep, waking or can't be reached: a read never takes rows away to put them back. */let lastRows: { home: BotHome; rows: PlaceBotRow[] } | null = null;-/** The one list is on for this page: the switch is on, main lists the other place, and this is this computer's page. */-export const oneListOn = (state: PlacesTogetherState | null): boolean => state?.on === true && state.other !== null && state.here === "computer";+/** The one list is on for this page: the switch is on and main lists the other place. On My Cloud's page only from an+ * app that says which place is home (and keeps where bots are moved): with an older one, that page lists its own bots+ * only, as it did before. */+export const oneListOn = (state: PlacesTogetherState | null): boolean => state?.on === true && state.other !== null && (state.here === "computer" || state.home !== undefined);function placedList(state: PlacesTogetherState | null): readonly PlacedBot[] {if (state === lastState) return lastList;@@ -134,19 +137,6 @@ export function useOtherPlaceBots(query: string): readonly PlacedBot[] {/** The last search's rows, kept while the list and the words stay the same (no hook: the sidebar calls this on every draw). */let lastSearch: { all: readonly PlacedBot[]; query: string; found: readonly PlacedBot[] } = { all: NONE, query: "", found: NONE };-// Rows of the other place come in after this page's own and keep their place, like every row: unread and work show as-// marks on the row as soon as the other place says so, never as a move.-/** The sidebar's parts with the other place's rows after this place's own in the main list: the busy-first order and- * Unread then take every row the same way. Departments, pins and tiles stay this place's own. */-export function withOtherPlace<T extends { unsectionedBots: Bot[] }>(parts: T, placed: readonly PlacedBot[]): T {- return placed.length ? { ...parts, unsectionedBots: [...parts.unsectionedBots, ...placed] } : parts;-}--/** This place's own rows only: what a drag or Alt+Up/Down arranges and saves to this place's server. */-export function ownRows<T extends object>(bots: T[]): T[] {- return bots.some(isPlacedBot) ? bots.filter((bot) => !isPlacedBot(bot)) : bots;-}-const openers = new Map<string, Dispatch<Action>>();/** What a row of the other place does with what its row would send this place's store: choosing it opens its bot where@@ -214,8 +204,7 @@ export function placeMark(place: Place, health: PlaceHealth, working: boolean, nreturn mark(device.icon, kind === "my-cloud" ? t("together.mark.livesCloud") : kind === "this-computer" ? t("together.mark.livesComputer") : t("together.mark.livesOn", { place: place.label }), "hover");}-/** This page's place while the one list is on; null while it is off, in a browser, on My Cloud's page and on any other- * place's page. */+/** This page's place while the one list is on; null while it is off, in a browser, and on any other place's page. */const hereOf = (state: PlacesTogetherState | null): BotHome | null => (oneListOn(state) ? state!.here : null);/** The mark a row draws, given this page's place while the one list is on (`here`, from useOneListHere once for thediff --git a/src/lib/places-together.ts b/src/lib/places-together.tsindex 2a8c92a4a9..0ea03975b7 100644--- a/src/lib/places-together.ts+++ b/src/lib/places-together.ts@@ -1,9 +1,9 @@// This computer and My Cloud together (electron/places-together.mjs), as a page sees it: the other place's bots, listed// beside its own. Every row carries its `home`, and ids are unique only within a place, so rows are keyed by home and id.import { useEffect, useState, useSyncExternalStore } from "react";-import type { BotHome, PlaceBotRow, PlacesTogetherState } from "../../electron/places-together.mjs";+import type { ArrangedBot, BotHome, PlaceBotRow, PlacesTogetherState } from "../../electron/places-together.mjs";-export type { BotHome, PlaceBotRow, PlacesTogetherState };+export type { ArrangedBot, BotHome, PlaceBotRow, PlacesTogetherState };/** A bot's key in a list that holds both places: ids are unique only within one. */export const placedKey = (home: BotHome, id: string): string => `${home}:${id}`;@@ -98,6 +98,17 @@ export async function setTogetherCommands(on: boolean): Promise<boolean> {return now;}+/** Keeps where the person moved bots in the one list. The list shows it at once; main's answer then stands. Whether main+ * kept every entry. */+export function arrangeOneList(entries: readonly ArrangedBot[]): Promise<boolean> {+ const page = bridge();+ if (!page?.arrange || !entries.length || !known?.on) return Promise.resolve(!entries.length);+ const keys = new Set(entries.map((entry) => entry.key));+ publish({ ...known, arranged: [...(known.arranged ?? []).filter((entry) => !keys.has(entry.key)), ...entries] });+ const same = (a: ArrangedBot, b: ArrangedBot) => a.key === b.key && a.section === b.section && a.after === b.after;+ return page.arrange([...entries]).then((kept) => { read(); return entries.every((entry) => kept.some((had) => same(had, entry))); }, () => { read(); return false; });+}+/** Opens one of the other place's bots there. */export function openOtherPlaceBot(id: string): void {void bridge()?.open(id).catch(() => {});diff --git a/src/together-preview.tsx b/src/together-preview.tsxindex b9d18fee0b..493cd82fdd 100644--- a/src/together-preview.tsx+++ b/src/together-preview.tsx@@ -1,10 +1,13 @@// Dev-only gallery of "This computer and My Cloud together" on by default, served at /together-preview.html; not in the// packaged app. It mounts the real rail, sidebar and notice over fake bridges, with no server behind them.// ?view=before|after|notice|notice-cloud-home|notice-off|rail-before|rail-after|rail-cloud-home&mode=simple|advanced&skin=midnight|daylight&lang=pt-br+// The one list: ?page=cloud (My Cloud's own page), ?home=cloud (the person's home is My Cloud),+// ?other=asleep|waking|offline|signin (the other place lists no rows and says why), and ?arranged=1 (the person dragged+// Scout under Git Tasks and Atlas into Finance).import { StrictMode, useEffect } from "react";import { createRoot } from "react-dom/client";import type { RailState } from "../electron/cloud-rail.mjs";-import type { PlaceBotRow, PlacesTogetherState } from "../electron/places-together.mjs";+import type { BotHome, PlaceBotRow, PlacesTogetherState } from "../electron/places-together.mjs";import { PlacesRail } from "@/components/PlacesRail";import { Sidebar } from "@/components/Sidebar";import { TogetherNotice } from "@/components/TogetherNotice";@@ -28,28 +31,37 @@ const here = (id: string, name: string, color: string, title: string, line: striid, name, color, threadId: `${id}-main`, mainThreadId: `${id}-main`, busy: false, activity: "idle",tasks: [{ threadId: `${id}-main`, title, createdAt: AT, updatedAt: AT + 5 * 60_000 }], messages: [said(`${id}-1`, 5, line)], ...over,}) as Bot;-const bots: Bot[] = [- here("mausbot", "MausBot", "violet", "Today", "Your week is planned; three things need you.", { chiefOfStaff: true } as Partial<Bot>),- here("ledger", "Ledger", "orange", "Invoices", "The March invoices are filed in your Drive."),+const page: BotHome = params.get("page") === "cloud" ? "cloud" : "computer", homePlace: BotHome = params.get("home") === "cloud" ? "cloud" : "computer";+const otherState = (["asleep", "waking", "offline", "signin"] as const).find((name) => name === params.get("other")) ?? null;+// Each place's own bots: the page's are its store, the other place's come as rows. Each place has its own MausBot: the+// tile on its own page, and a row (first, as main lists it) among its rows on the other page.+const chief = here("mausbot", "MausBot", "violet", "Today", "Your week is planned; three things need you.", { chiefOfStaff: true } as Partial<Bot>);+const computerBots: Bot[] = [+ here("ledger", "Ledger", "orange", "Invoices", "The March invoices are filed in your Drive.", { section: "Finance" }),here("git", "Git Tasks", "teal", "Release notes", "Release notes drafted from the last 40 commits."),];-const row = (id: string, name: string, color: string, over: Partial<PlaceBotRow> = {}): PlaceBotRow => ({ home: "cloud", id, threadId: `${id}-main`, name, color, lastAt: AT + 20 * 60_000, ...over });-const cloudRows: PlaceBotRow[] = [- row("scout", "Scout", "blue", { preview: "Found four flats under budget near the park.", chat: "Flat hunt" }),- row("atlas", "Atlas", "green", { preview: "Booked: the 9:40 train to Leeds on Friday.", chat: "Trip", unread: true }),+const cloudBots: Bot[] = [+ here("scout", "Scout", "blue", "Flat hunt", "Found four flats under budget near the park."),+ here("atlas", "Atlas", "green", "Trip", "Booked: the 9:40 train to Leeds on Friday.", { unread: true }),];+const bots: Bot[] = [chief, ...(page === "cloud" ? cloudBots : computerBots)];+const rowOf = (home: BotHome, bot: Bot): PlaceBotRow => ({ home, id: bot.id, threadId: bot.threadId, name: bot.name, color: bot.color, lastAt: AT + 20 * 60_000,+ preview: (bot.messages[0] as { text: string }).text, chat: bot.tasks?.[0]?.title, ...(bot.section ? { section: bot.section } : {}), ...(bot.unread ? { unread: true as const } : {}), ...(bot.chiefOfStaff ? { chief: true as const } : {}) });+const otherHome: BotHome = page === "cloud" ? "computer" : "cloud";+const otherRows: PlaceBotRow[] = otherState ? [] : [chief, ...(page === "cloud" ? computerBots : cloudBots)].map((bot) => rowOf(otherHome, bot));const joined = !["before", "rail-before"].includes(view) && view !== "notice-off";const together: PlacesTogetherState = joined- ? { v: 1, available: true, on: true, here: "computer", other: { home: "cloud", state: "ready", bots: cloudRows, newBot: true }, ...(view.startsWith("notice") ? { notice: true, commands: false, ...(view === "notice-cloud-home" ? { profileHome: true as const } : {}) } : {}) }- : { v: 1, available: true, on: false, here: "computer", other: null, ...(view === "notice-off" ? { notice: true, commands: false } : {}) };+ ? { v: 1, available: true, on: true, here: page, home: homePlace, arranged: params.get("arranged") ? [{ key: "cloud:scout", section: "", after: "computer:git" }, { key: "cloud:atlas", section: "Finance", after: "computer:ledger" }] : [],+ other: { home: otherHome, state: otherState ?? "ready", bots: otherRows, ...(page === "cloud" ? { sections: ["Finance"] } : {}), newBot: true }, ...(view.startsWith("notice") ? { notice: true, commands: false, ...(view === "notice-cloud-home" ? { profileHome: true as const } : {}) } : {}) }+ : { v: 1, available: true, on: false, here: page, other: null, ...(view === "notice-off" ? { notice: true, commands: false } : {}) };-const cloudHome = view === "rail-cloud-home";+const cloudHome = view === "rail-cloud-home" || homePlace === "cloud";const rail: RailState = { places: cloudHome ? [- { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true, active: true, paint: { swatch: null }, together: true },- { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, together: true },+ { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true, ...(page === "computer" ? { active: true } : {}), paint: { swatch: null }, together: true },+ { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, ...(page === "cloud" ? { active: true } : {}), paint: { swatch: "violet" }, together: true },] : [- { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true, paint: { swatch: null }, ...(view === "rail-before" ? {} : { together: joined }) },- { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, ...(view === "rail-before" ? {} : { together: joined }) },+ { id: "local", name: "This computer", color: null, kind: "computer", opens: true, ...(page === "computer" ? { active: true } : {}), paint: { swatch: null }, ...(view === "rail-before" ? {} : { together: joined }) },+ { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, ...(page === "cloud" ? { active: true } : {}), paint: { swatch: "violet" }, ...(view === "rail-before" ? {} : { together: joined }) },], add: { cloud: true, link: true, address: false } };let state = together;@@ -64,11 +76,11 @@ Object.assign(window, { ogb: {} });function Gallery() {- const state: AppState = { ...initialState, bots, selectedId: "ledger", connected: true, config: { ...initialState.config, profile: { name: "Sam", email: "", aboutMe: "" } } as AppState["config"] };+ const state: AppState = { ...initialState, bots, sections: page === "cloud" ? [] : ["Finance"], selectedId: page === "cloud" ? "atlas" : "ledger", connected: true, config: { ...initialState.config, profile: { name: "Sam", email: "", aboutMe: "" } } as AppState["config"] };const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };useEffect(() => {if (!view.startsWith("rail-")) return;- const id = cloudHome ? "profile:default" : "local";+ const id = view === "rail-cloud-home" ? "profile:default" : "local";const timer = setInterval(() => {const circle = document.querySelector(`[data-rail-place="${id}"]`);if (!circle || document.querySelector("[data-rail-menu]")) return;