Skip to content

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

Choose which bots move to My Cloud

Milind Sonif3b2357d324d
diff --git a/docs/verification/cloud-send.md b/docs/verification/cloud-send.md
index b71c2c246d..4983acda64 100644
--- a/docs/verification/cloud-send.md
+++ b/docs/verification/cloud-send.md
@@ -124,6 +124,23 @@ at the heavy part, the second saying which computer it waits for.
real store and shows the server's answers read messages.db directly and never
parse a conversation through the store.
+## Moving some bots
+
+```sh
+pnpm exec vitest run server/move-chosen-bots.e2e.test.ts server/cloud-send-scope.test.ts server/bot-moves.test.ts
+node --test electron/bot-move-main.node-test.mjs electron/one-home-check.node-test.mjs
+```
+
+The same two servers, started from the page's own channels. The chosen bot
+arrives with its chats, memory and routine, and what was on here is on there.
+The other bot answers here and nothing freezes; the chosen one refuses a turn
+here and stays as an archived bot that points to My Cloud. A room with a bot left
+behind stays here without the one that went. More bots can go later, and Move
+everything after that carries the rest without archiving on My Cloud the bots
+already there. The unit tests cover any number of bots in one move, a bot still
+answering holding the move, a failed check letting every bot go on here, and My
+Cloud ending bringing the bots back.
+
## The real utility port
```sh
diff --git a/electron/bot-move-main.mjs b/electron/bot-move-main.mjs
new file mode 100644
index 0000000000..8de553c64f
--- /dev/null
+++ b/electron/bot-move-main.mjs
@@ -0,0 +1,167 @@
+// Moving some of this computer's bots to My Cloud, while the rest go on here. This computer stays home, kept there by the
+// switch that keeps its bots here, and never freezes: only the bots that go are held, each by its own hold on this
+// computer's server (server/bot-moves.ts). Moving a bot from My Cloud into a team runs on the same phases (team-move.mjs):
+// here one move carries a whole choice of bots to the "team" My Cloud, with the send kept to those bots (cloud-send.mjs).
+import { randomUUID } from "node:crypto";
+
+import { createTeamMove, parseTeamMoves } from "./team-move.mjs";
+import { QUEUE_POLL_MS, switchOn } from "./one-home.mjs";
+
+export const MY_CLOUD = Object.freeze({ id: "my-cloud", name: "My Cloud" });
+const ID = /^[\w-]{1,128}$/u;
+const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
+const list = (value) => (Array.isArray(value) ? value : []);
+const nap = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
+
+/** The bots a person can choose from: every bot of this computer's but the helper every place has, one that moved, and an
+ * archived one. */
+export const choosable = (bots) => list(bots).filter((bot) => record(bot) && ID.test(bot.id ?? "") && typeof bot.name === "string" && !bot.defaultBot && !bot.hidden && !bot.movedTo);
+
+/**
+ * @param {{
+ * journal: { read(): unknown, write(value: unknown): void },
+ * local: { call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }> },
+ * send: { move(options: { final?: boolean, scope: string }): Promise<unknown>, check(options: { scope: string }): Promise<{ ok: boolean }> },
+ * session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }> }>,
+ * lease?: { take(): Promise<null | { name: string }>, release(): Promise<void> },
+ * ready(): boolean,
+ * lend?(projects: string[]): Promise<unknown>,
+ * onChange?(): void,
+ * sleep?(ms: number): Promise<void>,
+ * now?(): number,
+ * timers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void },
+ * log?(line: string): void,
+ * }} deps `ready`: My Cloud is there to move to. `lease`: one computer at a time runs the heavy part of a move there.
+ */
+export function createBotMove({ journal, local, send, session, lease = null, ready, lend, onChange = () => {}, sleep = nap, now, timers, log = () => {} }) {
+ const moves = () => parseTeamMoves(journal.read()).moves;
+ const note = (id, change) => {
+ const kept = parseTeamMoves(journal.read());
+ journal.write({ ...kept, moves: kept.moves.map((entry) => (entry.bot.id === id ? { ...entry, ...change } : entry)) });
+ };
+ /** My Cloud reaches the folders of the bots that moved through this computer; while lending can't take them yet, a later look does. */
+ let lending = false;
+ async function lendWaiting() {
+ if (lending) return;
+ lending = true;
+ try {
+ for (const move of moves().filter((entry) => Array.isArray(entry.lend) && entry.phase === "done")) {
+ try { if (move.lend.length) await lend?.(move.lend); note(move.bot.id, { lend: undefined }); }
+ catch (error) { log(`bot move: lending waits (${error?.message ?? error})`); }
+ }
+ } finally { lending = false; }
+ }
+
+ function open(move) {
+ let token = null;
+ const current = () => moves().find((entry) => entry.bot.id === move.bot.id) ?? move;
+ const ids = () => list(current().bots).map((bot) => bot.id);
+ /** The chosen bots, named to this computer's server for this run: it keeps them in memory only. */
+ const scope = async () => {
+ if (token) return token;
+ const asked = await local.call("POST", "/api/cloud-send/scope", { v: 1, bots: ids() });
+ if (!asked.ok || typeof asked.body?.scope !== "string") throw Object.assign(new Error("OpenMausBot on this computer did not answer."), { status: asked.status });
+ token = asked.body.scope;
+ return token;
+ };
+ return {
+ engine: {
+ move: async (options) => send.move({ final: options?.final === true, scope: await scope() }),
+ check: async () => send.check({ scope: await scope() }),
+ },
+ /** A hold, or its end, for each bot of the choice; a bot still answering is what the move waits for. */
+ myCloud: {
+ async call(method, _route, body) {
+ if (body?.state === "moving") await lease?.take().catch(() => null);
+ const held = [];
+ for (const id of ids()) {
+ const answer = await local.call(method, `/api/bot-moves/${id}`, body);
+ if (!answer.ok) return answer;
+ held.push(...list(answer.body?.movedTo?.held));
+ }
+ return { ok: true, status: 200, body: { v: 1, released: true, movedTo: { held } } };
+ },
+ },
+ /** Only bots a move would carry go: an untouched one has nothing to carry, and stays here. */
+ async prepare() {
+ const listed = await local.call("GET", `/api/cloud-send?move=1&scope=${await scope()}`);
+ if (!listed.ok) throw Object.assign(new Error("OpenMausBot on this computer did not answer."), { status: listed.status });
+ const carried = new Set(list(listed.body?.items).filter((item) => item?.kind === "bot").map((item) => item.id));
+ const bots = list(current().bots).filter((bot) => carried.has(bot.id));
+ if (!bots.length) throw Object.assign(new Error("These bots have nothing to move yet."), { final: true });
+ return { bots };
+ },
+ team: {
+ /** Waits its turn at My Cloud, behind another computer's move there. */
+ async begin() {
+ for (let other = await lease?.take() ?? null; other; other = await lease.take()) {
+ log(`bot move: waiting for ${other.name || "another computer"} to finish moving to My Cloud`);
+ await sleep(QUEUE_POLL_MS);
+ }
+ return { name: move.bot.name };
+ },
+ /** My Cloud switches on what was on here, and keeps which computer the bots came from. */
+ async done() {
+ const there = await session();
+ const held = list(current().held).filter((key) => typeof key === "string");
+ for (const key of held) {
+ const change = switchOn(key);
+ if (!change) continue;
+ const answer = await there.call(change.method, change.route, change.body);
+ if (!answer.ok && answer.status !== 404) throw Object.assign(new Error(answer.body?.error ?? "My Cloud did not switch on an automation."), { status: answer.status });
+ }
+ const computer = String((await local.call("GET", "/api/cloud-connections").catch(() => null))?.body?.computer?.label ?? "").trim() || "this computer";
+ const webhooks = held.flatMap((key) => (key.startsWith("webhook:") ? [key.slice("webhook:".length)] : []));
+ const arrived = await there.call("POST", "/api/cloud-send/arrived", { v: 1, computer, webhooks });
+ if (!arrived.ok) throw Object.assign(new Error(arrived.body?.error ?? "My Cloud did not finish the move."), { status: arrived.status });
+ const going = new Set(ids());
+ const bots = list((await local.call("GET", "/api/bots?messages=0").catch(() => null))?.body?.bots);
+ note(move.bot.id, { lend: [...new Set(bots.filter((bot) => going.has(bot?.id) && typeof bot.cwd === "string" && bot.cwd).map((bot) => bot.cwd))] });
+ },
+ },
+ close: async () => { await lease?.release().catch(() => {}); },
+ };
+ }
+
+ const engine = createTeamMove({ journal, open, inTeam: () => ready(), onChange: () => onChange(), log, ...(now ? { now } : {}), ...(timers ? { timers } : {}) });
+
+ return {
+ kick: () => engine.kick().finally(lendWaiting),
+ /** Moves this choice of bots for this account; bots already on their way are left out. Null when none is left to move. */
+ start(bots, account = null) {
+ const moving = new Set(moves().filter((move) => move.phase !== "done" && !move.stopped).flatMap((move) => list(move.bots).map((bot) => bot.id)));
+ const fresh = bots.filter((bot) => !moving.has(bot.id));
+ if (!fresh.length) return null;
+ const id = `bots-${randomUUID()}`;
+ void engine.start({ bot: { id, name: fresh[0].name }, team: MY_CLOUD, bots: fresh, account }).finally(lendWaiting).catch((error) => log(`bot move: ${error?.message ?? error}`));
+ return id;
+ },
+ view: () => engine.view(),
+ seen: () => engine.seen(),
+ retry: () => engine.retry(),
+ /** The bots on their way now, by id. */
+ moving: () => moves().filter((move) => move.phase !== "done").flatMap((move) => list(move.bots).map((bot) => bot.id)),
+ /** Everything is moving now instead: a choice still on its way stops, and its bots go on here until that move takes them. */
+ async drop() {
+ for (const move of moves().filter((entry) => entry.phase !== "done")) {
+ for (const bot of list(move.bots)) await local.call("DELETE", `/api/bot-moves/${bot.id}`).catch(() => null);
+ const left = parseTeamMoves(journal.read());
+ journal.write({ ...left, moves: left.moves.filter((entry) => entry.bot.id !== move.bot.id) });
+ }
+ onChange();
+ },
+ /** This account's My Cloud ended: the bots that moved there are here again as they went. */
+ async back(account) {
+ for (const move of moves().filter((entry) => entry.phase === "done" && entry.account === account)) {
+ for (const bot of list(move.bots)) {
+ const answer = await local.call("POST", `/api/bot-moves/${bot.id}`, { v: 1, state: "back", team: MY_CLOUD }).catch(() => null);
+ if (!answer?.ok) { log(`bot move: ${bot.name} comes back later`); return; }
+ }
+ const left = parseTeamMoves(journal.read());
+ journal.write({ ...left, moves: left.moves.filter((entry) => entry.bot.id !== move.bot.id) });
+ }
+ onChange();
+ },
+ close: () => engine.close(),
+ };
+}
diff --git a/electron/bot-move-main.node-test.mjs b/electron/bot-move-main.node-test.mjs
new file mode 100644
index 0000000000..0ff6bc7bea
--- /dev/null
+++ b/electron/bot-move-main.node-test.mjs
@@ -0,0 +1,174 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { choosable, createBotMove, MY_CLOUD } from "./bot-move-main.mjs";
+
+const reply = (status, body = {}) => ({ ok: status < 400, status, body });
+const bots = (count) => Array.from({ length: count }, (_, i) => ({ id: `b${i}`, name: `Bot ${i}` }));
+
+/** This computer's server (each bot holds or goes on as it is told), the send, My Cloud's session, and the clock's timers. */
+function world({ busy = () => null, checks = [], untouched = [], ready = () => true, lease = null, sleep = async () => {} } = {}) {
+ let journal = null, clock = 1_000;
+ const timers = [];
+ const w = {
+ holds: new Map(), calls: [], cloud: [], passes: [], scopes: [],
+ get journal() { return journal; },
+ set journal(value) { journal = structuredClone(value); },
+ advance(ms) { clock += ms; },
+ timers,
+ async tick() { for (const timer of timers.splice(0)) timer.work(); await w.move.kick(); },
+ };
+ const local = {
+ async call(method, route, body) {
+ w.calls.push([method, route, body]);
+ if (route === "/api/cloud-send/scope") { w.scopes.push(body.bots); return reply(200, { v: 1, scope: `scope-${w.scopes.length}` }); }
+ if (route.startsWith("/api/cloud-send?move=1")) return reply(200, { v: 1, items: w.chosen().filter((id) => !untouched.includes(id)).map((id) => ({ key: `bot:${id}`, kind: "bot", id, parts: {} })) });
+ if (route === "/api/cloud-connections") return reply(200, { computer: { label: "MacBook Air" } });
+ if (route === "/api/bots?messages=0") return reply(200, { bots: w.chosen().map((id) => ({ id, cwd: `/work/${id}` })) });
+ const id = /^\/api\/bot-moves\/([\w-]+)$/u.exec(route)?.[1];
+ if (id && method === "DELETE") { w.holds.delete(id); return reply(200, { v: 1, released: true }); }
+ if (id && body.state === "moving") {
+ const who = busy(id);
+ if (who) return reply(409, { busy: who });
+ w.holds.set(id, "moving");
+ return reply(200, { v: 1, movedTo: { held: [`routine:r-${id}`, `webhook:w-${id}`] } });
+ }
+ if (id && body.state === "moved") { w.holds.set(id, "moved"); return reply(200, { v: 1, movedTo: {} }); }
+ if (id && body.state === "back") { w.holds.delete(id); return reply(200, { v: 1, released: true }); }
+ return reply(404);
+ },
+ };
+ w.chosen = () => (journal?.moves ?? []).flatMap((move) => move.bots.map((bot) => bot.id));
+ w.lent = [];
+ w.lendWith = (lender) => { w.lender = lender; };
+ w.move = createBotMove({
+ journal: { read: () => structuredClone(journal), write: (value) => { journal = structuredClone(value); } },
+ local,
+ send: {
+ async move(options) { w.passes.push({ ...options }); },
+ async check(options) { w.passes.push({ check: true, ...options }); const next = checks.shift(); if (next instanceof Error) throw next; return { ok: next ?? true }; },
+ },
+ session: async () => ({ async call(method, route, body) { w.cloud.push([method, route, body]); return reply(200, { v: 1 }); } }),
+ ready, lease, sleep,
+ lend: async (projects) => { (w.lender ?? ((seen) => w.lent.push(seen)))(projects); },
+ now: () => clock,
+ timers: { set: (work, ms) => { const timer = { work, ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } },
+ });
+ return w;
+}
+const settle = async (w) => { await w.move.kick(); await new Promise((resolve) => setImmediate(resolve)); await w.move.kick(); };
+
+test("a choice of bots goes as one move: each is held, what was on here goes on there, and each stays here as the line that opens it", async () => {
+ const w = world();
+ assert.ok(w.move.start(bots(3)));
+ await settle(w);
+ const move = w.journal.moves[0];
+ assert.equal(move.phase, "done", JSON.stringify(move));
+ assert.deepEqual(move.team, MY_CLOUD);
+ assert.deepEqual([...w.holds.values()], ["moved", "moved", "moved"]);
+ assert.deepEqual(w.passes.map((pass) => pass.check ? "check" : pass.final ? "final" : "copy"), ["copy", "final", "check"], "one copy, one final and one check for all of them");
+ assert.ok(w.passes.every((pass) => pass.scope === "scope-1"), "every read of this computer's server is kept to the choice");
+ assert.deepEqual(w.cloud.filter(([method]) => method === "PATCH").map(([, route]) => route).sort(), ["/api/routines/r-b0", "/api/routines/r-b1", "/api/routines/r-b2", "/api/webhooks/w-b0", "/api/webhooks/w-b1", "/api/webhooks/w-b2"]);
+ assert.deepEqual(w.cloud.find(([, route]) => route === "/api/cloud-send/arrived")[2], { v: 1, computer: "MacBook Air", webhooks: ["w-b0", "w-b1", "w-b2"] });
+ assert.deepEqual(w.lent, [["/work/b0", "/work/b1", "/work/b2"]], "My Cloud can reach their folders on this computer");
+ assert.deepEqual(w.move.view(), { bot: { id: move.bot.id, name: "Bot 0" }, team: { id: "my-cloud", name: "My Cloud" }, phase: "done", bots: 3 });
+});
+
+test("while lending can't take the bots' folders yet, a later look does, and the move is done meanwhile", async () => {
+ let refuse = true;
+ const w = world();
+ const lentTo = [];
+ w.lendWith((projects) => { if (refuse) throw new Error("lending is paused"); lentTo.push(projects); });
+ w.move.start(bots(1));
+ await settle(w);
+ assert.equal(w.journal.moves[0].phase, "done");
+ assert.deepEqual(w.journal.moves[0].lend, ["/work/b0"]);
+ refuse = false;
+ await w.move.kick();
+ assert.deepEqual(lentTo, [["/work/b0"]]);
+ assert.equal(w.journal.moves[0].lend, undefined);
+});
+
+test("any number of bots go in one move, and an untouched bot, which a move has nothing to carry of, stays here", async () => {
+ const many = world({ untouched: ["b7"] });
+ many.move.start(bots(1_000));
+ await settle(many);
+ assert.equal(many.journal.moves[0].phase, "done");
+ assert.equal(many.journal.moves[0].bots.length, 999);
+ assert.equal(many.holds.size, 999);
+ assert.equal(many.holds.has("b7"), false);
+ assert.equal(many.passes.length, 3, "still one copy, one final and one check");
+
+ const nothing = world({ untouched: ["b0"] });
+ nothing.move.start(bots(1));
+ await settle(nothing);
+ assert.equal(nothing.journal.moves[0].stopped, true);
+ assert.equal(nothing.holds.size, 0);
+});
+
+test("a bot still answering holds the move for it; the others stay held meanwhile, and the rest of this computer goes on", async () => {
+ let answering = "Bot 1";
+ const w = world({ busy: (id) => (id === "b1" ? answering : null) });
+ w.move.start(bots(3));
+ await settle(w);
+ assert.equal(w.journal.moves[0].phase, "freeze");
+ assert.equal(w.holds.has("b2"), false, "held in turn, as each is free");
+ answering = null;
+ await w.tick();
+ assert.equal(w.journal.moves[0].phase, "done");
+});
+
+test("a check that fails lets every bot of the choice go on here, and the move tries again later from the copy", async () => {
+ const w = world({ checks: [false, false, false] });
+ w.move.start(bots(2));
+ await settle(w);
+ const move = w.journal.moves[0];
+ assert.equal(move.phase, "copy");
+ assert.equal(move.failing, true);
+ assert.ok(move.retryAt > 1_000);
+ assert.equal(w.holds.size, 0, "nothing stays held");
+ assert.equal(w.move.view().phase, "failed");
+});
+
+test("bots already on their way are not moved twice, and My Cloud ending brings the ones that moved back", async () => {
+ const w = world();
+ w.move.start(bots(2), "acct-1");
+ assert.deepEqual(w.move.moving(), ["b0", "b1"]);
+ assert.equal(w.move.start(bots(2)), null, "no bot left to move");
+ await settle(w);
+ assert.deepEqual(w.move.moving(), [], "done");
+ await w.move.back("acct-2");
+ assert.equal(w.holds.size, 2, "another account's Cloud ending says nothing of these");
+ await w.move.back("acct-1");
+ assert.equal(w.holds.size, 0);
+ assert.deepEqual(w.journal.moves, []);
+});
+
+test("Move everything stops a choice still on its way, and its bots go on here until that move takes them", async () => {
+ let answering = "Bot 1";
+ const w = world({ busy: (id) => (id === "b1" ? answering : null) });
+ w.move.start(bots(2));
+ await settle(w);
+ assert.equal(w.holds.get("b0"), "moving");
+ await w.move.drop();
+ assert.equal(w.holds.size, 0);
+ assert.deepEqual(w.journal.moves, []);
+ answering = null;
+});
+
+test("it waits its turn at My Cloud behind another computer's move, and lets go when it is done", async () => {
+ let asks = 0;
+ const released = [];
+ const lease = { take: async () => (++asks < 3 ? { name: "NUC" } : null), release: async () => { released.push(asks); } };
+ const naps = [];
+ const w = world({ lease, sleep: async (ms) => { naps.push(ms); } });
+ w.move.start(bots(1));
+ await settle(w);
+ assert.equal(w.journal.moves[0].phase, "done");
+ assert.deepEqual(naps, [60_000, 60_000]);
+ assert.ok(released.length >= 1);
+});
+
+test("only the bots a person can move are offered: never the helper every place has, an archived one, or one that moved", () => {
+ assert.deepEqual(choosable([{ id: "a", name: "A" }, { id: "d", name: "D", defaultBot: { v: 1 } }, { id: "h", name: "H", hidden: true }, { id: "m", name: "M", movedTo: { state: "moved" } }, { id: "bad id", name: "X" }, null]).map((bot) => bot.id), ["a"]);
+});
diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mts
index 29e8a9469a..5a3455412e 100644
--- a/electron/cloud-send-main.d.mts
+++ b/electron/cloud-send-main.d.mts
@@ -22,14 +22,15 @@ export function installCloudSend(deps: {
patience?: { stallMs?: number; waits?: number[]; blips?: number[] };
space?: { disk(): unknown; grow(sizeGb: number): Promise<unknown> };
move?: () => { view(): unknown; seen(): unknown; retry(): Promise<unknown> } | null;
+ botMove?: () => { view(): unknown; seen(): unknown } | null;
/** The one session every pass of the move uses (move-session.mjs). */
moveSession?: { open(target: CloudTarget): Promise<CloudSendSession> };
}): {
receive(proc: unknown, message: unknown): boolean;
/** This computer's server's private port, asked as a send asks it: another move's sends share it. */
handoff(what: { kind: string; [key: string]: unknown }): Promise<any>;
- move(options?: { final?: boolean }): Promise<CloudSendOutcome>;
- check(): Promise<CloudMoveCheck>;
+ move(options?: { final?: boolean; scope?: string }): Promise<CloudSendOutcome>;
+ check(options?: { scope?: string }): Promise<CloudMoveCheck>;
switches(): Record<string, boolean>;
snapshot(): CloudSendSnapshot;
publish(): void;
diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjs
index c681ffdf80..de090bb93c 100644
--- a/electron/cloud-send-main.mjs
+++ b/electron/cloud-send-main.mjs
@@ -3,7 +3,7 @@
import { readFileSync, renameSync, writeFileSync } from "node:fs";
import { BACKGROUND_HEADERS } from "./cloud-power.mjs";
import { createLoginHandoffClient } from "./cloud-logins.mjs";
-import { MOVE_LINE, TEAM_MOVE_LINE, resultKey } from "./cloud-send-parts.mjs";
+import { BOT_MOVE_LINE, MOVE_LINE, TEAM_MOVE_LINE, resultKey } from "./cloud-send-parts.mjs";
import { createCloudSend, sendNotice } from "./cloud-send.mjs";
const SESSION_LABEL = "Send to My Cloud";
@@ -71,15 +71,17 @@ export async function openOwnerSession(target, fetchImpl, { label = SESSION_LABE
* space?: { disk(): unknown, grow(sizeGb: number): Promise<unknown> },
* move?: () => { view(): unknown, seen(): unknown, retry(): Promise<unknown> } | null,
* teamMove?: () => { view(): unknown, seen(): unknown } | null,
+ * botMove?: () => { view(): unknown, seen(): unknown } | null,
* moveSession?: { open(target: { origin: string, grant(): Promise<{ origin: string, code: string }> }): Promise<any> },
* }} deps `engineWaitMs`: how long a
* move waits for My Cloud's engines (cloud-connections.mjs). `space`: My Cloud's plan disk and the Admin's grow, so a
* move makes room for the files it carries. `move`: the one-time move (one-home.mjs), whose line either page shows.
* `teamMove`: a bot moving from My Cloud into a team (team-move-main.mjs), whose line My Cloud's page shows.
+ * `botMove`: some of this computer's bots moving to My Cloud (bot-move-main.mjs), whose line this computer's page shows.
* `moveSession`: the one session every pass of the move uses (move-session.mjs); without it each pass opens its own.
*/
export function installCloudSend({ ipcMain, cloudPage, server, local, home, cookieFetch, reconnect, power, file, window, localOrigin,
- fetch: fetchImpl = globalThis.fetch, engineWaitMs, patience, space, move = () => null, teamMove = () => null, moveSession = null, t }) {
+ fetch: fetchImpl = globalThis.fetch, engineWaitMs, patience, space, move = () => null, teamMove = () => null, botMove = () => null, moveSession = null, t }) {
const handoff = createLoginHandoffClient();
const pageOf = () => {
const win = window();
@@ -92,8 +94,10 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook
const moving = () => move()?.view() ?? null;
/** The notice either page gets, with the one-time move's line when there is one. */
const notice = (snapshot) => {
- const line = moving(), team = pageOf() === "cloud" ? teamMove()?.view() ?? null : null;
- return { ...sendNotice(snapshot), ...(line ? { move: line } : {}), ...(team ? { teamMove: team } : {}) };
+ const line = moving(), team = pageOf() === "cloud" ? teamMove()?.view() ?? null : null, bots = pageOf() === "local" ? botMove()?.view() ?? null : null;
+ // Being asked which bots go is this computer's page's own.
+ const shown = line?.phase === "choose" && pageOf() !== "local" ? null : line;
+ return { ...sendNotice(snapshot), ...(shown ? { move: shown } : {}), ...(team ? { teamMove: team } : {}), ...(bots ? { botMove: bots } : {}) };
};
const deliver = (snapshot) => {
if (pageOf()) window().webContents.send("cloud-send:notice-changed", notice(snapshot));
@@ -140,6 +144,7 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook
ipcMain.handle("cloud-send:notice", onPage("cloud-send:notice", () => notice(send.snapshot())));
ipcMain.handle("cloud-send:dismiss", onPage("cloud-send:dismiss", (_event, signature) => {
if (String(signature) === TEAM_MOVE_LINE) { teamMove()?.seen(); return notice(send.snapshot()); }
+ if (String(signature) === BOT_MOVE_LINE) { botMove()?.seen(); return notice(send.snapshot()); }
if (String(signature) === MOVE_LINE) {
// The done line says what the move brought; the move's own send result is not said again after it.
move()?.seen();
@@ -157,8 +162,8 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook
handoff: (what) => handoff.request(server(), what),
/** The one-time move to My Cloud (cloud-send.mjs): a pass that carries everything, `final` the one after this computer
* stops, and the check of what arrived. */
- move: (options) => send.send({ reason: "move", final: options?.final === true }),
- check: () => send.check(),
+ move: (options) => send.send({ reason: "move", final: options?.final === true, ...(options?.scope ? { scope: options.scope } : {}) }),
+ check: (options) => send.check(options),
/** Each automation the move carried, and whether it was on here when it went. */
switches: () => send.switches(),
snapshot: () => send.snapshot(),
diff --git a/electron/cloud-send-parts.d.mts b/electron/cloud-send-parts.d.mts
index 1c8b35793d..154d144052 100644
--- a/electron/cloud-send-parts.d.mts
+++ b/electron/cloud-send-parts.d.mts
@@ -37,6 +37,7 @@ export type OffReason = "you" | "removed";
export declare const BOT_PARTS: Readonly<Record<string, readonly string[]>>;
export declare const MOVE_LINE: string;
export declare const TEAM_MOVE_LINE: "team-move";
+export declare const BOT_MOVE_LINE: "bot-move";
export declare const MOVE_BOT_PARTS: Readonly<Record<string, readonly string[]>>;
export declare const AUTOMATION_KINDS: readonly MoveKind[];
export declare const MOVE_KINDS: readonly MoveKind[];
diff --git a/electron/cloud-send-parts.mjs b/electron/cloud-send-parts.mjs
index aa9e308b46..c8bc78bbe5 100644
--- a/electron/cloud-send-parts.mjs
+++ b/electron/cloud-send-parts.mjs
@@ -41,6 +41,7 @@ export const EMPTY = "-";
export const MOVE_LINE = "one-home";
/** What My Cloud's page closes the line of a bot moving into a team by. */
export const TEAM_MOVE_LINE = "team-move";
+export const BOT_MOVE_LINE = "bot-move";
/** Logins and 1Password are compared by when they changed, never by their secrets: two sides that both have one were
* set up on their own, and from then on a change here goes. */
const CONTENT_COMPARED = new Set(["bot", "skill", "setting", ...MOVE_KINDS]);
diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mts
index c10671cfb8..45e37f0590 100644
--- a/electron/cloud-send.d.mts
+++ b/electron/cloud-send.d.mts
@@ -89,6 +89,8 @@ export interface CloudSendNotice {
move?: import("./one-home.mjs").OneHomeView;
/** On My Cloud's page: a bot moving into a team, while its line shows; absent from an older desktop. */
teamMove?: import("./team-move.mjs").TeamMoveView;
+ /** On this computer's page: some of its bots on their way to My Cloud. */
+ botMove?: BotMoveView;
}
export type CloudSendTold = { at: number; reason: string; failed: number; seen: boolean; sent: CloudSendCounts; final?: boolean } & CloudSendFailure;
export interface CloudSendArrived extends CloudSendCounts { chats: { conversations: number; messages: number } }
@@ -117,12 +119,25 @@ export interface CloudSendPageBridge {
teamRetry?(): Promise<import("./team-move.mjs").TeamMoveView | null>;
/** Shows that team's page, where the bot now lives. */
openTeam?(teamId: string): Promise<void>;
+ /** On this computer's page: whether its bots can move to My Cloud now, and which are on their way. */
+ botMoveState?(): Promise<BotMoveState>;
+ /** Moves these bots to My Cloud; the others stay here and go on working. */
+ moveBots?(ids: string[]): Promise<BotMoveState>;
+ /** Moves everything to My Cloud: this computer's one-time move. */
+ moveEverything?(): Promise<BotMoveState>;
+ botMoveRetry?(): Promise<BotMoveView | null>;
+ /** Shows My Cloud in this window. */
+ openMyCloud?(): Promise<void>;
/** The switch "Keep this computer's bots on this computer"; absent from an older desktop. */
keepHere?(): Promise<KeepHereState>;
/** Turns it (a real click on My Cloud's page). */
setKeepHere?(on: boolean): Promise<KeepHereState>;
}
+/** Some of this computer's bots moving to My Cloud (bot-move-main.mjs). `bot`: the first of them, `bots`: how many go. */
+export interface BotMoveView { bot: { id: string; name: string }; team: { id: string; name: string }; phase: "moving" | "failed" | "done"; bots?: number }
+export interface BotMoveState { available: boolean; moving: string[] }
+
/** The switch "Keep this computer's bots on this computer" (one-home-main.mjs). `shown`: this person has a Cloud of their
* own the move applies to; `moved`: this computer's bots live on My Cloud, so turning it on brings them home; `coming`:
* they are on their way, past turning back. */
@@ -212,7 +227,7 @@ export function createCloudSend(deps: {
/** `reason: "move"`: everything this computer has, apps and keys first; `final`: the pass after this computer stopped,
* which carries the sign-ins that refresh themselves and lets go of this computer's copies. */
send(options?: { keys?: string[] | null; force?: string[]; reason?: string; final?: boolean }): Promise<CloudSendOutcome>;
- check(): Promise<CloudMoveCheck>;
+ check(options?: { scope?: string }): Promise<CloudMoveCheck>;
/** Each automation a move carried ("routine:<id>", "call:<id>", "webhook:<id>", "app-event:<id>") and whether it was
* on here when it went. */
switches(): Record<string, boolean>;
diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjs
index b34a53ca88..90efe23eab 100644
--- a/electron/cloud-send.mjs
+++ b/electron/cloud-send.mjs
@@ -32,6 +32,7 @@ const ATTACHMENT_NAMES = 2000;
const ROW_IDS = 10_000;
const ROW_ID_CONVERSATIONS = 200;
const MEMORY_FILES = 100;
+const SCOPED_READ = /^\/api\/cloud-send(?:\?move=1|\/manifest|\/chats(?:\?attachments=1)?|\/files)$/u;
const PICTURE_TYPES = { png: "image/png", jpg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
const VAULT_ID = /^[\w-]{1,128}$/u;
/** Whole sends, which carry the chats too; a send of some items (Use this computer's, one login) never does. */
@@ -213,7 +214,7 @@ const movedResult = () => ({ moved: 0, memory: 0, files: { sent: 0, kept: 0 }, c
export function createCloudSend({ local, cloud, handoff, store, onChange = () => {}, now = Date.now, sleep, patience = {}, engineWaitMs, space, team = null, t = nativeText.englishText.t }) {
let saved = parseSendState(safeRead(store));
let view = { cloud: "none", plan: null, local: null, theirs: null, chats: null };
- let running = null, progress = null, checking = null;
+ let running = null, progress = null, checking = null, localScope = null;
const only = team?.bot ?? null;
/** A route as a move of one bot asks it of either side: kept to that bot. */
const scoped = (route) => (only ? `${route}${route.includes("?") ? "&" : "?"}bot=${only}` : route);
@@ -250,9 +251,11 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>
const publish = () => { const value = snapshot(); try { onChange(value); } catch {} return value; };
const allowed = (route) => LOCAL_ROUTE.test(route.replace(/[?&]bot=[\w-]{1,128}$/u, ""));
+ /** What a move of some bots reads of this computer's server names them. */
+ const chosenOnly = (route) => (localScope && SCOPED_READ.test(route) ? `${route}${route.includes("?") ? "&" : "?"}scope=${localScope}` : route);
async function localJson(route, options) {
if (!allowed(route)) throw new CloudSendError("invalid", "Unsupported local request.");
- const response = await local(route, options);
+ const response = await local(chosenOnly(route), options);
if (!response.ok) throw new CloudSendError("local", "OpenMausBot on this computer did not answer. Try again in a moment.");
return response.json();
}
@@ -331,13 +334,14 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>
/** One send at a time; one asked while another runs waits for it, then runs as it was asked. A move (`reason: "move"`)
* carries everything; its final pass (`final`) carries the sign-ins that refresh themselves too, and this computer lets
* go of each once My Cloud has it. */
- async function send({ keys = null, force = [], reason = "button", final = false } = {}) {
+ async function send({ keys = null, force = [], reason = "button", final = false, scope = null } = {}) {
while (running) await running.promise.catch(() => {});
const origin = cloud.origin();
if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");
- const job = { reason, final: reason === "move" && final === true, promise: null, chats: false };
+ const job = { reason, final: reason === "move" && final === true, scope, promise: null, chats: false };
running = job;
progress = null;
+ localScope = scope;
publish();
job.promise = (async () => {
try { return await sendTo(origin, job, { keys, force: Array.isArray(force) ? force.filter((key) => typeof key === "string") : [], reason }); }
@@ -350,7 +354,7 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>
if (unanswered(error)) view = { ...view, cloud: "unreachable" };
throw error;
}
- finally { running = null; progress = null; publish(); }
+ finally { running = null; progress = null; localScope = null; publish(); }
})();
return job.promise;
}
@@ -395,7 +399,8 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>
if (move) {
await assertTakesMove(session);
// A bot moving into a team carries nothing of the person's: their apps and keys stay.
- if (!team) computer = await moveConnections(origin, session, result, job.final);
+ // A sign-in that refreshes itself stays with the bots that stay: only one place can hold it.
+ if (!team) computer = await moveConnections(origin, session, result, job.final && !job.scope);
}
settleCreating(origin, theirs);
const planned = plan(origin, mine, theirs, force, { everything: move });
@@ -892,19 +897,22 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>
/** What did not arrive of what a move carried (cloud-send-check.mjs `moveCheck`), over one owner session that counts
* as someone using My Cloud; `snapshot().checking` says how far it is. A check that stood still too long fails as
- * unanswered, saying whether it got anywhere (`progressed`). */
- async function check() {
+ * unanswered, saying whether it got anywhere (`progressed`). `scope`: only the bots a move of some of them carries; its
+ * credentials are copies this computer goes on using, and are not checked. */
+ async function check({ scope = null } = {}) {
const origin = cloud.origin();
if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");
const session = await cloud.open({ move: true }).catch((error) => { throw new CloudSendError("session", sentence(error?.message) ?? "This app could not sign in to My Cloud. Try again.", { cause: error }); });
+ localScope = scope;
try {
- return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, patience, takesMove: () => assertTakesMove(session),
+ return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team || scope ? null : handoff, scoped, now, sleep, patience, takesMove: () => assertTakesMove(session),
refuse: (answer, message) => refusedError("unreachable", answer, message), onStep: (value) => { checking = value; publish(); } });
} catch (error) {
if (error?.code === "slow") throw Object.assign(new CloudSendError("unreachable", sentence(error.message) ?? "My Cloud did not answer.", { cause: error.cause }), { progressed: error.progressed === true });
throw error;
} finally {
checking = null;
+ localScope = null;
publish();
try { await session.close(); } catch {}
}
diff --git a/electron/cloud-send.node-test.mjs b/electron/cloud-send.node-test.mjs
index eb08c1c2d4..a017c3fa52 100644
--- a/electron/cloud-send.node-test.mjs
+++ b/electron/cloud-send.node-test.mjs
@@ -203,7 +203,7 @@ function preload({ remote = false, activation = false } = {}) {
}
test("the bridge: either page gets only the move's line and the switch that keeps this computer's bots here; its Try again, moving a bot into a team, and turning that switch go only from the person's click on My Cloud's page", async () => {
- const keys = ["notice", "dismiss", "moveRetry", "teams", "moveToTeam", "moveToTeamCoded", "teamRetry", "openTeam", "teamBring", "teamBringMove", "teamBringStatus", "keepHere", "setKeepHere", "onNotice"];
+ const keys = ["notice", "dismiss", "moveRetry", "teams", "moveToTeam", "moveToTeamCoded", "teamRetry", "openTeam", "teamBring", "teamBringMove", "teamBringStatus", "botMoveState", "moveBots", "moveEverything", "botMoveRetry", "openMyCloud", "keepHere", "setKeepHere", "onNotice"];
const local = preload();
assert.equal(local.bridge.cloudSend, undefined);
assert.equal(local.bridge.cloudLogins, undefined);
diff --git a/electron/main.mjs b/electron/main.mjs
index 3430f8c505..584b7cee2b 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2613,7 +2613,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(
const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });
const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));
const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });
-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });
+const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });
// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.
const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });
const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,
diff --git a/electron/one-home-check.node-test.mjs b/electron/one-home-check.node-test.mjs
index 799c7c04ee..96c15b09ff 100644
--- a/electron/one-home-check.node-test.mjs
+++ b/electron/one-home-check.node-test.mjs
@@ -27,7 +27,7 @@ function cloudLease(now) {
* pass and check, `checks` answering in turn: true, false, an error, or a function of the moment), My Cloud's session,
* the clock and its timers, and My Cloud's lease when `lease` is given (`name` and `id`: this computer as it asks).
*/
-function computer({ clock, checks = [], lease = null, name = "Mac", id = "computer-mac", copy = null }) {
+function computer({ clock, checks = [], lease = null, name = "Mac", id = "computer-mac", copy = null, choosing = null }) {
let journal = null;
const timers = [];
const c = {
@@ -68,6 +68,7 @@ function computer({ clock, checks = [], lease = null, name = "Mac", id = "comput
local,
session,
...(lease ? { lease: createMoveLease({ session, holder: async () => id, label: async () => name, timers: { set: () => null, clear: () => {} } }) } : {}),
+ ...(choosing ? { choosing } : {}),
lastInput: () => 0,
now: () => clock.now,
timers: { set: (work, ms) => { const timer = { work, ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } },
@@ -175,3 +176,22 @@ test("a move that waits for another computer after an earlier failure asks again
assert.deepEqual(nuc.passes, []);
assert.deepEqual(nuc.timers.map((timer) => timer.ms), [QUEUE_POLL_MS]);
});
+
+test("no first move starts while the person is asked which bots go, and it goes on by itself once they say", async () => {
+ const clock = newClock();
+ let asking = true;
+ const c = computer({ clock, choosing: async () => asking });
+ await c.home.kick();
+ assert.equal(c.journal, null, "nothing has started");
+ assert.deepEqual(c.passes, []);
+ assert.equal(c.server.freezes, 0);
+ assert.deepEqual(c.home.view(), { phase: "choose" });
+ asking = false;
+ await c.home.kick();
+ assert.equal(c.journal.phase, "done");
+ assert.deepEqual(c.passes, ["copy", "final"]);
+
+ const failing = computer({ clock, choosing: async () => { throw new Error("this computer's server did not answer"); } });
+ await failing.home.kick();
+ assert.equal(failing.journal.phase, "done", "a question that can't be asked never holds a move back");
+});
diff --git a/electron/one-home-main.d.mts b/electron/one-home-main.d.mts
index 0cd25f7f4e..c3fde29b32 100644
--- a/electron/one-home-main.d.mts
+++ b/electron/one-home-main.d.mts
@@ -22,6 +22,8 @@ export function installOneHome(deps: Omit<SendDeps, "local" | "move" | "moveSess
movedTo?(origin: string): Promise<"deleted" | "ended" | "live" | "unknown" | null>;
reportMoveStatus?(report: import("./move-status.mjs").MoveStatusReport): Promise<boolean>;
pairTeam(teamId: string): Promise<{ origin: string; code: string; expiresAt?: number }> } | null;
+ /** The person is asked which bots go before the first move starts. */
+ chooses?: boolean;
journalFile(): string;
tempRoot(): string;
lend?(projects: string[]): Promise<unknown>;
diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjs
index b295a05ec3..cab71e9502 100644
--- a/electron/one-home-main.mjs
+++ b/electron/one-home-main.mjs
@@ -10,6 +10,7 @@ import { dirname, join } from "node:path";
import { Readable } from "node:stream";
import { installCloudSend, openOwnerSession } from "./cloud-send-main.mjs";
+import { choosable, createBotMove } from "./bot-move-main.mjs";
import { createMoveLease } from "./move-lease.mjs";
import { createMoveSession } from "./move-session.mjs";
import { createMoveStatusReport, moveStatus } from "./move-status.mjs";
@@ -136,7 +137,7 @@ async function answer(response) {
* installCloudSend's.
*/
export function installOneHome({ localRequest: anyServer, clean = null, account, journalFile, tempRoot, lend, phone, openHome, openLocal, restart, version, log = () => {}, journal: kept, keep: keptChoice, openTeam, teamJournal,
- reportTimers, other = () => null, accountsHere = () => 1, t = nativeText.englishText.t, ...sendDeps }) {
+ reportTimers, other = () => null, accountsHere = () => 1, chooses = false, t = nativeText.englishText.t, ...sendDeps }) {
const fetchImpl = sendDeps.fetch ?? globalThis.fetch;
const localRequest = clean ? clean.realCopy(anyServer) : anyServer;
const onOwnCopy = (work) => (clean ? clean.holding(work) : work());
@@ -144,10 +145,11 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,
let lastInput = 0;
const watched = new WeakSet();
let teamMove = null;
+ let botMove = null;
// One owner session for the whole move, every pass and check and the switch: each new one is one of the Admin's codes.
const moveSession = createMoveSession({ open: (target) => openOwnerSession(target, fetchImpl, { label: MOVE_LABEL, background: false }) });
const send = installCloudSend({ ...sendDeps, t, local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(init?.timeoutMs ?? 30_000) }),
- move: () => (home?.view() === null && other()?.view() ? other() : home), teamMove: () => teamMove, moveSession });
+ move: () => (home?.view() === null && other()?.view() ? other() : home), teamMove: () => teamMove, botMove: () => botMove, moveSession });
teamMove = installTeamMove({ t, ipcMain: sendDeps.ipcMain, cloudPage: sendDeps.cloudPage, pageOrigin: sendDeps.pageOrigin, confirmMove: sendDeps.confirmMove, home: sendDeps.home, account: () => account(), fetch: fetchImpl, openTeam,
file: () => join(dirname(journalFile()), "team-move-send.json"), journalFile: () => join(dirname(journalFile()), "team-moves.json"), ...(teamJournal ? { journal: teamJournal } : {}),
onChange: () => send.publish(), log });
@@ -230,10 +232,17 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,
// Two computers moving into one Cloud take turns at the heavy part (server/cloud-send-lease.ts).
const lease = createMoveLease({ session: () => moveSession.open(target()), holder: installation, log,
label: async () => String((await local.json("/api/cloud-connections").catch(() => null))?.computer?.label ?? "") });
+ // The person says which bots go, once, when there is a choice to make.
+ const choice = jsonFile(() => join(dirname(journalFile()), "one-home-choice.json"));
+ const botsHere = async () => choosable((await local.json("/api/bots?messages=0"))?.bots);
+ const cloudTakesBots = () => { const cloud = oneHomeCloud(account()?.state()); return Boolean(cloud?.origin && cloud.moves && !cloud.ended); };
+ botMove = createBotMove({ journal: jsonFile(() => join(dirname(journalFile()), "bot-moves.json")), local, send, session: () => moveSession.open(target()), ready: cloudTakesBots, lend, log, onChange: () => send.publish(),
+ lease: createMoveLease({ session: () => moveSession.open(target()), holder: installation, log, label: async () => String((await local.json("/api/cloud-connections").catch(() => null))?.computer?.label ?? "") }) });
home = createOneHome({
journal,
t,
lease,
+ ...(chooses ? { choosing: async () => choice.read()?.answered !== true && (await botsHere()).length > 1 } : {}),
// Every run starts here: the key watch is set up before any wait asks, so a key pressed since then counts.
cloud: () => {
typed();
@@ -290,22 +299,58 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,
sendDeps.ipcMain.handle("one-home:keep", onPage("one-home:keep", keepState));
sendDeps.ipcMain.handle("one-home:keep-set", onPage("one-home:keep-set", (on) => {
if (on === true && !keepState().shown) throw new Error(t("native.cloud.keepNoCloud"));
+ if (on !== true) void botMove.drop().catch((error) => log(`bot move: ${error?.message ?? error}`));
void home.keep(on === true).catch((error) => log(`one home: ${error?.message ?? error}`));
return keepState();
}));
+ const localPage = (channel, handler) => (event, ...args) => {
+ if (sendDeps.cloudPage(event) !== "local") throw new Error(`${channel} is only available on this computer's page`);
+ return handler(...args);
+ };
+ const botMoveState = () => {
+ const moving = parseJournal(journal.read());
+ return { available: cloudTakesBots() && (!moving || moving.phase === "back"), moving: botMove.moving() };
+ };
+ sendDeps.ipcMain.handle("cloud-send:bot-move-state", localPage("cloud-send:bot-move-state", botMoveState));
+ // The bots come from this computer's own server, never from the page; the page only names which of them.
+ sendDeps.ipcMain.handle("cloud-send:move-bots", localPage("cloud-send:move-bots", async (ids) => {
+ if (!botMoveState().available) throw new Error(t("native.cloud.keepNoCloud"));
+ const asked = new Set(Array.isArray(ids) ? ids.map(String) : []);
+ const bots = (await botsHere()).filter((bot) => asked.has(bot.id)).map((bot) => ({ id: bot.id, name: bot.name }));
+ if (!bots.length) throw new Error(t("teamMove.refused.notABot"));
+ choice.write({ v: 1, answered: true });
+ await home.keep(true);
+ botMove.start(bots, oneHomeCloud(account()?.state())?.account ?? null);
+ return botMoveState();
+ }));
+ sendDeps.ipcMain.handle("cloud-send:move-everything", localPage("cloud-send:move-everything", () => {
+ choice.write({ v: 1, answered: true });
+ void botMove.drop().catch((error) => log(`bot move: ${error?.message ?? error}`));
+ void home.keep(false).catch((error) => log(`one home: ${error?.message ?? error}`));
+ return botMoveState();
+ }));
+ sendDeps.ipcMain.handle("cloud-send:bot-move-retry", localPage("cloud-send:bot-move-retry", () => { void botMove.retry(); return botMove.view(); }));
+ sendDeps.ipcMain.handle("cloud-send:open-my-cloud", localPage("cloud-send:open-my-cloud", () => { openHome?.(); }));
+
return {
...send,
/** The switch "Keep this computer's bots on this computer", as Settings shows it, and the person turning it. */
keep: { state: keepState, set: (on) => home.keep(on === true) },
/** Why the account signed in can't be left now: its move, or a bot of its own moving into a team, is under way. */
- holding: () => { const bot = teamMove.view()?.phase; return home.moving() || (bot && !["done", "failed"].includes(bot)) ? "moving" : null; },
+ holding: () => { const bot = teamMove.view()?.phase; return home.moving() || (bot && !["done", "failed"].includes(bot)) || botMove.moving().length ? "moving" : null; },
/** Goes on with the move, and with any bot moving into a team: at launch, and whenever the MausBot Cloud sign-in changes. */
- kick: () => { void teamMove.kick(); return home.kick(); },
+ kick: () => {
+ void teamMove.kick();
+ void botMove.kick();
+ const cloud = oneHomeCloud(account()?.state());
+ if (cloud?.ended) void botMove.back(cloud.account);
+ return home.kick();
+ },
/** Home is My Cloud: this computer's own server is frozen for good. */
away: () => home.away(),
view: () => home.view(),
- close: () => { teamMove.close(); home.close(); report.close(); void moveSession.end(); },
+ close: () => { teamMove.close(); botMove.close(); home.close(); report.close(); void moveSession.end(); },
/** A bot moving from My Cloud into a team (team-move-main.mjs). */
teamMove,
oneHome: home,
diff --git a/electron/one-home-main.node-test.mjs b/electron/one-home-main.node-test.mjs
index ba48763c05..a22697ff29 100644
--- a/electron/one-home-main.node-test.mjs
+++ b/electron/one-home-main.node-test.mjs
@@ -1,6 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
import { freezeAnswer, installOneHome } from "./one-home-main.mjs";
import nativeText from "./native-text.cjs";
@@ -152,3 +156,39 @@ test("the team bring handlers receive the same dynamic translator as one home",
await assert.rejects(move({}, "atlas-bot-1"), { message: "pt-br:native.teamMove.openTeam" });
} finally { main.close(); }
});
+
+test("a first move waits for the person's choice, asked on this computer's page only; with one bot there is nothing to choose", async () => {
+ const CLOUD = "https://omb-t-1.fly.dev";
+ const folder = mkdtempSync(join(tmpdir(), "omb-move-choice-"));
+ const launch = (bots) => {
+ const handlers = new Map();
+ let kept = null, url = "http://127.0.0.1:4100/";
+ const main = installOneHome({
+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, cloudPage: (event) => event.page ?? null, server: () => null, home: () => ({ origin: CLOUD, grant: async () => ({ origin: CLOUD, code: "x" }) }),
+ cookieFetch: async () => json({}, 401), reconnect: async () => false, power: { asleep: () => false }, file: () => join(folder, "cloud-send.json"),
+ window: () => ({ isDestroyed: () => false, webContents: { on: () => {}, send: () => {}, get mainFrame() { return { url }; } } }), localOrigin: () => "http://127.0.0.1:4100", fetch: async () => json({}, 404),
+ localRequest: async (route) => (route === "/api/bots?messages=0" ? json({ bots }) : json({ frozen: false })),
+ account: () => ({ state: () => ({ status: "connected", account: { id: "acct-1", email: "[email protected]" }, machine: { status: "ready", origin: CLOUD, moves: true } }), pairHome: async () => { throw new Error("not in this test"); } }),
+ journalFile: () => join(folder, `${bots.length}-one-home.json`), tempRoot: () => folder, journal: { read: () => kept, write: (value) => { kept = value; } }, keep: { read: () => null, write: () => {} }, chooses: true,
+ });
+ return { main, ask: (channel, page, ...args) => handlers.get(channel)({ page }, ...args), kept: () => kept, show: (next) => { url = next; } };
+ };
+ const named = (count) => Array.from({ length: count }, (_, i) => ({ id: `b${i}`, name: `Bot ${i}` }));
+ const asked = launch([...named(3), { id: "maus", name: "Maus", defaultBot: { v: 1 } }]);
+ const alone = launch([...named(1), { id: "maus", name: "Maus", defaultBot: { v: 1 } }]);
+ try {
+ await asked.main.kick();
+ assert.equal(asked.kept(), null, "nothing starts by itself");
+ assert.deepEqual(asked.ask("cloud-send:notice", "local").move, { phase: "choose" });
+ asked.show(`${CLOUD}/`);
+ assert.equal(asked.ask("cloud-send:notice", "cloud").move, undefined, "My Cloud's page is not asked");
+ asked.show("http://127.0.0.1:4100/");
+ assert.throws(() => asked.ask("cloud-send:move-everything", "cloud"), /only available on this computer's page/u);
+ asked.ask("cloud-send:move-everything", "local");
+ await asked.main.kick();
+ assert.equal(asked.kept()?.phase, "copy", "Move everything starts the one-time move");
+
+ await alone.main.kick();
+ assert.equal(alone.kept()?.phase, "copy", "with one bot there is nothing to choose");
+ } finally { asked.main.close(); alone.main.close(); rmSync(folder, { recursive: true, force: true }); }
+});
diff --git a/electron/one-home.d.mts b/electron/one-home.d.mts
index 217b99ecf3..7a486d0aa1 100644
--- a/electron/one-home.d.mts
+++ b/electron/one-home.d.mts
@@ -24,6 +24,8 @@ type OneHomePhase =
/** `checking`: the check of what arrived, at its step (`manifest`, `files`, `chats`, `attachments`, `credentials`), with
* `done` of `total` there and how many bots it checks. */
| { phase: "finishing"; checking?: OneHomeChecking; slow?: OneHomeSlow; failing?: OneHomeFailing }
+ /** No move has started: the person is asked which bots go. */
+ | { phase: "choose" }
/** What arrived, checked on both sides; `at`: when the move was done; `phone`: a phone was paired with this computer; `held`: keys a trial's Cloud keeps unused while its Claude credit lasts; `left`: what My Cloud refused for good, which stayed where it was; `stayed`: connectors that work only on this computer (`needs`: a program My Cloud lacks). */
| { phase: "done"; at?: number; counts?: OneHomeCounts; phone: boolean; held: string[]; left?: OneHomeNotCarried[]; stayed?: OneHomeStayed[] }
/** This computer's bots are on their way home from a My Cloud that goes on, because the person keeps them here;
@@ -99,6 +101,8 @@ export function createOneHome(deps: {
release?(): Promise<void>;
/** One computer at a time runs the heavy part of a move into My Cloud: `take()` is null once this one does, else who does. */
lease?: { take(): Promise<null | { name: string }>; release(): Promise<void> };
+ /** True while no first move should start, as the person is asked which bots go. */
+ choosing?(): Promise<boolean>;
lend?(projects: string[]): Promise<unknown>;
phone?: { paired(): boolean; stop(): Promise<void>; start(): Promise<void> };
openHome?(): void;
diff --git a/electron/one-home.mjs b/electron/one-home.mjs
index 4f002e3cf8..14bbd1090e 100644
--- a/electron/one-home.mjs
+++ b/electron/one-home.mjs
@@ -176,6 +176,7 @@ export function arrivedCounts(here, there) {
* session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>, close(): Promise<void> }>,
* release?(): Promise<void>,
* lease?: { take(): Promise<null | { name: string }>, release(): Promise<void> },
+ * choosing?(): Promise<boolean>,
* lend?(projects: string[]): Promise<unknown>,
* phone?: { paired(): boolean, start(): Promise<void> },
* openHome?(): void,
@@ -199,6 +200,7 @@ export function arrivedCounts(here, there) {
* and kept only until it is deleted); null for anything else, and while it can't be asked. `cloud().verified`: the Admin
* answered this sign-in just now (connected). `local.marker()`: this computer's freeze marker. `lease`: one computer at a
* time runs the heavy part of a move into My Cloud (move-lease.mjs); `take()` is null once this one does, else who does.
+ * `choosing`: no first move starts yet, as the person is asked which bots go; the line says so with phase "choose".
*/
export function createOneHome(deps) {
const now = deps.now ?? Date.now;
@@ -211,6 +213,8 @@ export function createOneHome(deps) {
let noted = null, heldOff = false;
/** The other computer whose move into the same Cloud this one waits for (`deps.lease`), by its name ("" without one). */
let queuedFor = null;
+ /** No move has started, and the person is asked first which bots go (`deps.choosing`). */
+ let choosing = false;
const read = () => parseJournal(deps.journal.read());
const kept = () => { try { return parseKeep(deps.keep?.read()).on; } catch { return false; } };
@@ -234,6 +238,7 @@ export function createOneHome(deps) {
* until it is closed, and coming home; `place`, a server of the person's own the move goes to, by its name. Null when
* there is nothing to say. */
function view() {
+ if (choosing && !read() && !kept()) return { phase: "choose" };
if (anotherAccount(read())) return null;
const seen = phaseView(), place = read()?.cloud?.name;
return seen && typeof place === "string" ? { ...seen, place } : seen;
@@ -726,6 +731,9 @@ export function createOneHome(deps) {
// local environment) nothing starts or counts as failing, and it looks again in a minute.
if (deps.ownCopy?.() === false) { noted = "local_unavailable"; if (!heldOff) log("one home: the move waits until this computer's own copy runs"); heldOff = true; later(MINUTE); return; }
heldOff = false;
+ const asks = await deps.choosing?.().catch(() => false) === true;
+ if (asks !== choosing) { choosing = asks; publish(); }
+ if (asks) return;
journal = write({ v: 1, phase: "copy", cloud: { origin: cloud.origin, account: cloud.account, machine: cloud.machine, ...(cloud.id ? { id: cloud.id } : {}), ...(cloud.name ? { name: cloud.name } : {}) },
startedAt: now() });
}
diff --git a/electron/preload.cjs b/electron/preload.cjs
index da01c30ac1..78bee5a11f 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -527,6 +527,12 @@ const bridge = {
teamBringMove: botId => navigator.userActivation?.isActive === true
? ipcRenderer.invoke("cloud-send:team-bring-move", String(botId)) : Promise.reject(new Error("Choose Move to move the bot.")),
teamBringStatus: () => ipcRenderer.invoke("cloud-send:team-bring-status"),
+ // This computer's page: which of its bots move to My Cloud. Main refuses every other page.
+ botMoveState: () => ipcRenderer.invoke("cloud-send:bot-move-state"),
+ moveBots: ids => ipcRenderer.invoke("cloud-send:move-bots", Array.isArray(ids) ? ids.map(String) : []),
+ moveEverything: () => ipcRenderer.invoke("cloud-send:move-everything"),
+ botMoveRetry: () => ipcRenderer.invoke("cloud-send:bot-move-retry"),
+ openMyCloud: () => ipcRenderer.invoke("cloud-send:open-my-cloud"),
// Settings → MausBot Cloud, Advanced: "Keep this computer's bots on this computer".
keepHere: () => ipcRenderer.invoke("one-home:keep"),
setKeepHere: on => isLocalPage || navigator.userActivation?.isActive === true
diff --git a/electron/team-move.mjs b/electron/team-move.mjs
index da0eb15c4b..22d748507f 100644
--- a/electron/team-move.mjs
+++ b/electron/team-move.mjs
@@ -78,7 +78,7 @@ export function createTeamMove(deps) {
const shown = read().moves.filter((move) => !move.told).at(-1);
if (!shown) return null;
const phase = shown.phase === "done" ? "done" : shown.failing ? "failed" : "moving";
- return { bot: { id: shown.bot.id, name: shown.name ?? shown.bot.name }, team: { id: shown.team.id, name: shown.team.name }, phase };
+ return { bot: { id: shown.bot.id, name: shown.name ?? shown.bot.name }, team: { id: shown.team.id, name: shown.team.name }, phase, ...(Array.isArray(shown.bots) ? { bots: shown.bots.length } : {}) };
};
const publish = () => { try { deps.onChange?.(view()); } catch {} };
/** The move of this bot, changed as `change` says; the journal is written before anything acts on it. */
@@ -234,7 +234,7 @@ export function createTeamMove(deps) {
kick,
view,
/** Starts moving a bot into a team; a bot already moving there goes on. */
- start({ bot, team }) {
+ start({ bot, team, ...rest }) {
const journal = read();
const held = journal.moves.find((move) => move.bot.id === bot.id);
if (held && held.phase !== "done" && !held.stopped) {
@@ -242,7 +242,7 @@ export function createTeamMove(deps) {
return kick();
}
const moves = journal.moves.filter((move) => move.bot.id !== bot.id).map((move) => (move.phase === "done" ? { ...move, told: true } : move));
- deps.journal.write({ v: 1, moves: [...moves, { bot, team, phase: "copy", startedAt: now() }] });
+ deps.journal.write({ v: 1, moves: [...moves, { ...rest, bot, team, phase: "copy", startedAt: now() }] });
publish();
return kick();
},
diff --git a/server/bot-moves.test.ts b/server/bot-moves.test.ts
index 7f53d330f1..2ab2a7a14a 100644
--- a/server/bot-moves.test.ts
+++ b/server/bot-moves.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts";
+import { assertBotHere, botMoveRefusal, createBotMoves, MY_CLOUD_TEAM } from "./bot-moves.ts";
import type { BotRecord } from "./store.ts";
import { WaitManager } from "./waits.ts";
@@ -100,3 +100,48 @@ describe("My Cloud holding a bot while it moves into a team", () => {
expect(settled).toEqual([["the report", "cancelled"], ["the invoice", "cancelled"]]);
});
});
+
+describe("a bot moving from this computer to My Cloud", () => {
+ const MY_CLOUD = { id: MY_CLOUD_TEAM, name: "My Cloud" };
+ function here() {
+ const bots = new Map<string, Record<string, unknown>>([["scout", { id: "scout", name: "Scout" }], ["pip", { id: "pip", name: "Pip" }], ["maus", { id: "maus", name: "Maus", defaultBot: { v: 1 } }]]);
+ const groups = [{ id: "both", memberIds: ["scout", "pip"], dm: false }, { id: "alone", memberIds: ["scout", "maus"], dm: false }];
+ const routines = [{ id: "brief", botId: "scout", enabled: true }];
+ const removed: string[] = [];
+ const moves = createBotMoves({
+ store: { bot: (id) => (bots.get(id) as unknown as BotRecord) ?? null, patchBot: (id, patch) => Object.assign(bots.get(id)!, patch) as unknown as BotRecord, groups,
+ patchGroup: (id, patch) => Object.assign(groups.find((group) => group.id === id)!, patch) },
+ routines: () => ({ listRoutines: () => routines as never, update: (id: string, patch: { enabled?: boolean }) => Object.assign(routines.find((routine) => routine.id === id)!, patch) as never, removeForBot: (botId: string) => { removed.push(botId); } }),
+ webhooks: () => null, appEvents: () => null, waits: () => null, busy: () => false,
+ });
+ return { moves, bots, groups, routines, removed };
+ }
+
+ it("keeps its routines here, off, leaves a room some of whose bots stay, and keeps a room all of whose bots left", async () => {
+ const { moves, bots, groups, routines, removed } = here();
+ await moves.hold("scout", MY_CLOUD);
+ moves.moved("scout", MY_CLOUD);
+ expect(removed, "My Cloud ending brings it back with them").toEqual([]);
+ expect(routines[0]!.enabled).toBe(false);
+ expect(bots.get("scout")).toMatchObject({ hidden: true, movedTo: { state: "moved" } });
+ expect(groups.find((group) => group.id === "both")!.memberIds, "the room goes on here without it").toEqual(["pip"]);
+ expect(groups.find((group) => group.id === "alone")!.memberIds, "only the helper every place has is left").toEqual(["scout", "maus"]);
+ });
+
+ it("is here again as it went if My Cloud ends, its automations left off", async () => {
+ const { moves, bots, routines } = here();
+ await moves.hold("scout", MY_CLOUD);
+ moves.moved("scout", MY_CLOUD);
+ expect(moves.back("scout")).toEqual({ released: true });
+ expect(bots.get("scout")).toMatchObject({ hidden: false, movedTo: undefined });
+ expect(routines[0]!.enabled).toBe(false);
+ expect(moves.back("pip"), "a bot that never left has nothing to come back from").toEqual({ released: true });
+ });
+
+ it("a bot that went into a team never comes back this way", async () => {
+ const { moves } = here();
+ await moves.hold("pip", ACME);
+ moves.moved("pip", ACME);
+ expect("refused" in moves.back("pip")).toBe(true);
+ });
+});
diff --git a/server/bot-moves.ts b/server/bot-moves.ts
index 4397d29831..3416159d6d 100644
--- a/server/bot-moves.ts
+++ b/server/bot-moves.ts
@@ -1,16 +1,22 @@
-// My Cloud's side of moving one of its bots into one of its person's teams (electron/team-move.mjs runs the move). While
-// the bot goes it takes no turns here and its automations are off, and which ones were on is kept, so they come back on
-// if the move stops. Once it lives in the team its routines are gone from here (they run there), and the bot stays here
-// archived, with its notes about the person, as the line that opens it in the team.
+// The server's side of moving one of its bots to another home: from My Cloud into one of its person's teams
+// (electron/team-move.mjs runs the move), or from this computer to My Cloud (electron/bot-move-main.mjs). While the bot goes
+// it takes no turns here and its automations are off, and which ones were on is kept, so they come back on if the move
+// stops. Once it lives there the bot stays here archived, as the line that opens it there. Its routines are gone from
+// here when it went into a team; a bot that went to My Cloud keeps them here switched off, and comes back as it was if
+// My Cloud ends.
import type { BotMovedTo } from "../shared/wire.ts";
import type { AppTriggerManager } from "./app-triggers.ts";
import type { RoutineManager } from "./routines.ts";
-import type { BotRecord } from "./store.ts";
+import type { BotRecord, GroupRecord } from "./store.ts";
import type { WaitManager } from "./waits.ts";
import type { WebhookManager } from "./webhooks.ts";
+/** The "team" a bot moving from this computer to My Cloud goes to. */
+export const MY_CLOUD_TEAM = "my-cloud";
+
export interface BotMovesDeps {
- store: { bot(id: string): BotRecord | null | undefined; patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null };
+ store: { bot(id: string): BotRecord | null | undefined; patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null;
+ groups?: ReadonlyArray<Pick<GroupRecord, "id" | "memberIds" | "dm">>; patchGroup?(id: string, patch: { memberIds: string[] }): unknown };
routines(): Pick<RoutineManager, "listRoutines" | "update" | "removeForBot"> | null;
webhooks(): Pick<WebhookManager, "list" | "update"> | null;
appEvents(): Pick<AppTriggerManager, "list" | "update"> | null;
@@ -56,6 +62,15 @@ export function createBotMoves(deps: BotMovesDeps) {
for (const wait of waits?.all() ?? []) if (wait.botId === botId) waits!.cancel(wait.id, botId);
};
+ /** A room some of whose bots stay goes on here without this one; one all of whose bots left is kept as it was. */
+ const leaveRooms = (botId: string) => {
+ for (const room of deps.store.groups ?? []) {
+ if (room.dm || !room.memberIds.includes(botId)) continue;
+ if (room.memberIds.every((id) => id === botId || deps.store.bot(id)?.movedTo || deps.store.bot(id)?.defaultBot)) continue;
+ deps.store.patchGroup?.(room.id, { memberIds: room.memberIds.filter((id) => id !== botId) });
+ }
+ };
+
return {
/** The bot stops here for the move: no turns, its automations off and its waits cancelled. Busy while it answers; a
* bot already moved stays moved. Holding it again keeps what the first hold switched off. */
@@ -96,12 +111,21 @@ export function createBotMoves(deps: BotMovesDeps) {
const held = movedOf(bot);
if (!bot || !held || held.team.id !== team.id) return { refused: "This bot is not moving to that team." };
if (held.state !== "moved") {
- deps.routines()?.removeForBot(botId);
+ if (team.id === MY_CLOUD_TEAM) leaveRooms(botId); else deps.routines()?.removeForBot(botId);
cancelWaits(botId);
deps.store.patchBot(botId, { movedTo: { ...held, state: "moved", at: now() }, hidden: true } as Partial<BotRecord>);
}
return { movedTo: movedOf(deps.store.bot(botId))! };
},
+ /** My Cloud ended: a bot that moved there is here again as it was when it went, its automations left off. */
+ back(botId: string): { released: true } | { refused: string } {
+ const bot = deps.store.bot(botId);
+ const held = movedOf(bot);
+ if (!bot || !held) return { released: true };
+ if (held.team.id !== MY_CLOUD_TEAM) return { refused: botMoveRefusal(bot)! };
+ deps.store.patchBot(botId, { movedTo: undefined, hidden: false } as Partial<BotRecord>);
+ return { released: true };
+ },
};
}
diff --git a/server/cloud-send-chats.ts b/server/cloud-send-chats.ts
index c6fbf1ca5c..1146395968 100644
--- a/server/cloud-send-chats.ts
+++ b/server/cloud-send-chats.ts
@@ -17,6 +17,7 @@ import { addSentChats, attachmentNames, ATTACHMENT_NAME, type ChatStore, type Se
import { threadHeads, threadRowNumbers, threadRowsFrom } from "./message-db.ts";
import { ownerStamp, unstamped, type CloudOwner } from "./cloud-owner-lines.ts";
import { attachmentNamesOf, linkedPath, linksOf, storedRows, threadLinks, type ThreadLinks } from "./cloud-send-rows.ts";
+import { roomGoes } from "./cloud-send-scope.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { RouteContext } from "./routes/table.ts";
import type { BotRecord, GroupRecord, GroupTaskRecord, Message, Store, TaskPatch, TaskRecord } from "./store.ts";
@@ -236,6 +237,8 @@ export interface CloudSendChatsDeps {
approvalSupported?(selection: ModelSelection, mode: ApprovalMode): boolean;
/** A move of this one bot into a team: its conversations only. */
bot?: string;
+ /** A move of only these bots: their conversations, and the rooms that go with all their bots. */
+ scope?: ReadonlySet<string>;
/** This Cloud's owner's person key, as their lines here carry it: a bot moving into a team tells the team whose lines
* become the mover's. */
ownerKey?: string;
@@ -356,9 +359,11 @@ export async function cloudSendChatsRoute(deps: CloudSendChatsDeps, { req, res,
const { store } = deps;
// This computer's side: what each conversation has, and its rows after a point.
if (path === PREFIX && method === "GET") {
- const heads = deps.bot ? chatHeads(store.bots.filter((bot) => bot.id === deps.bot), []) : chatHeads(store.bots, store.groups);
+ const chosen = deps.scope;
+ const rooms = chosen ? store.groups.filter((room) => roomGoes(room, chosen, (id) => store.bot(id))) : store.groups;
+ const heads = deps.bot ? chatHeads(store.bots.filter((bot) => bot.id === deps.bot), []) : chatHeads(chosen ? store.bots.filter((bot) => chosen.has(bot.id)) : store.bots, rooms);
json(res, 200, { v: 1, dataDir: deps.dataDir, ...(deps.bot && deps.ownerKey ? { owner: deps.ownerKey } : {}), conversations: heads.map((head) => ({ ...head, settings: conversationSettings(store, head) })),
- rooms: deps.bot ? [] : emptyRooms(store.groups, heads),
+ rooms: deps.bot ? [] : emptyRooms(rooms, heads),
...(url.searchParams.get("attachments") === "1" ? { attachments: await attachmentSizes(deps.dataDir, heads) } : {}) });
return true;
}
diff --git a/server/cloud-send-manifest.ts b/server/cloud-send-manifest.ts
index adc98f8943..57bf8d3391 100644
--- a/server/cloud-send-manifest.ts
+++ b/server/cloud-send-manifest.ts
@@ -5,6 +5,7 @@ import type { ChatStore } from "./cloud-chat-merge.ts";
import { listBotFiles, type BotFile } from "./cloud-send-files.ts";
import { chatHeads, conversationSettings } from "./cloud-send-chats.ts";
import { attachmentNamesOf } from "./cloud-send-rows.ts";
+import { roomGoes } from "./cloud-send-scope.ts";
import { automationSwitches, routineRunIds, type MoveKindsDeps } from "./cloud-send-kinds.ts";
import { journalIds, memoryFiles, memoryLines, teamsHere } from "./cloud-send-memory.ts";
import type { CloudSendSummary } from "./cloud-send.ts";
@@ -57,6 +58,8 @@ export interface ManifestSources {
/** False: the attachments, or the bot files, are not listed (the desktop's check never reads My Cloud's attachments). */
attachments?: boolean;
files?: boolean;
+ /** A move of only these bots: their conversations, and the rooms that go with all their bots. */
+ scope?: ReadonlySet<string>;
}
function memoryOf(botId: string): CloudSendManifest["memory"] {
@@ -68,9 +71,10 @@ export async function cloudSendManifest(sources: ManifestSources): Promise<Cloud
const { store } = sources;
const sent = [...new Set(summary.items.filter((item) => item.kind === "bot" && item.id).map((item) => item.id!))];
const only = sources.bot;
- const rooms = only === undefined ? store.groups.filter((room) => !room.dm) : [];
+ const chosen = sources.scope;
+ const rooms = only === undefined ? store.groups.filter((room) => !room.dm && (!chosen || roomGoes(room, chosen, (id) => store.bot(id)))) : [];
const counts = sources.heads();
- const conversations: ManifestConversation[] = chatHeads(only === undefined ? store.bots : store.bots.filter((bot) => bot.id === only), rooms).map((head) => ({
+ const conversations: ManifestConversation[] = chatHeads(only !== undefined ? store.bots.filter((bot) => bot.id === only) : chosen ? store.bots.filter((bot) => chosen.has(bot.id)) : store.bots, rooms).map((head) => ({
threadId: head.threadId, ...(head.bot ? { bot: head.bot } : { room: head.room }), rows: counts.get(head.threadId)?.rows ?? 0, newest: head.lastId,
settings: conversationSettings(store, head),
}));
diff --git a/server/cloud-send-rows.ts b/server/cloud-send-rows.ts
index e02ff27521..1fc52a2c98 100644
--- a/server/cloud-send-rows.ts
+++ b/server/cloud-send-rows.ts
@@ -9,6 +9,8 @@ import type { Message } from "./store.ts";
export interface ThreadLinks { ids: string[]; parent: Map<string, string | null>; leaf: string | null }
const BY_ID_CHUNK = 200;
+/** Up to this many conversations are read one by one, by their index, rather than by reading every row. */
+const BY_THREAD_MAX = 500;
/** As the store reads a conversation: a row stored without a parent follows the row before it, and the active leaf is
* the newest row when none was kept. Null when messages.db holds no row of it. */
@@ -58,10 +60,14 @@ export function storedRows(threadId: string, ids: readonly string[], { owners =
* parsed, one at a time. */
export function attachmentNamesOf(threadIds: ReadonlySet<string>, dataDir: string): Set<string> {
const names = new Set<string>();
- const rows = prepared("SELECT thread_id AS threadId, json FROM messages WHERE instr(json, 'attachments') > 0 OR instr(json, '<attached-') > 0").iterate();
- for (const row of rows as Iterable<{ threadId: string; json: string }>) {
- if (!threadIds.has(row.threadId)) continue;
- for (const name of attachmentNames(JSON.parse(row.json) as Message, dataDir)) names.add(name);
- }
+ const add = (rows: Iterable<unknown>) => {
+ for (const row of rows as Iterable<{ threadId: string; json: string }>) {
+ if (!threadIds.has(row.threadId)) continue;
+ for (const name of attachmentNames(JSON.parse(row.json) as Message, dataDir)) names.add(name);
+ }
+ };
+ const naming = "(instr(json, 'attachments') > 0 OR instr(json, '<attached-') > 0)";
+ if (threadIds.size > BY_THREAD_MAX) add(prepared(`SELECT thread_id AS threadId, json FROM messages WHERE ${naming}`).iterate());
+ else for (const threadId of threadIds) add(prepared(`SELECT thread_id AS threadId, json FROM messages WHERE thread_id = ? AND ${naming}`).iterate(threadId));
return names;
}
diff --git a/server/cloud-send-scope.test.ts b/server/cloud-send-scope.test.ts
new file mode 100644
index 0000000000..c501e9a180
--- /dev/null
+++ b/server/cloud-send-scope.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import { cloudSendSummary, type CloudSendSources } from "./cloud-send.ts";
+import { createMoveScopes, moveScopeRoute, roomGoes } from "./cloud-send-scope.ts";
+import type { BotRecord } from "./store.ts";
+
+const bot = (id: string, extra: Partial<BotRecord> = {}) => ({ id, name: id, soul: "Be brief.", threadId: `t-${id}`, ...extra }) as unknown as BotRecord;
+
+function sources(bots: BotRecord[]): CloudSendSources {
+ return { appVersion: "1", bots: () => bots, greetingOnly: () => false, skills: () => [{ name: "notes", sha256: "a".repeat(64), enabled: true }], picture: () => null, logins: () => [], onePassword: () => null, settings: () => ({}),
+ move: { botParts: () => ({}), items: (carried) => [...carried].flatMap((id) => [{ key: `routine:r-${id}`, kind: "routine" as const, label: "r", id: `r-${id}`, bot: id, parts: {} }, { key: `call:c-${id}`, kind: "call" as const, label: "c", id: `c-${id}`, bot: id, parts: {} }]) } };
+}
+
+describe("a move of some bots", () => {
+ it("carries only the chosen bots, their skills and routines, what is the person's own, and no calendar call", () => {
+ const summary = cloudSendSummary(sources([bot("a"), bot("b")]), { move: true, bots: new Set(["a"]) });
+ expect(summary.items.map((item) => item.key)).toEqual(["bot:a", "skill:a:notes", "setting:profile", "setting:language", "routine:r-a"]);
+ });
+
+ it("never carries again a bot that lives elsewhere now, from the server it left", () => {
+ const moved = bot("a", { movedTo: { team: { id: "my-cloud", name: "My Cloud" }, state: "moved", at: 1 }, hidden: true });
+ const held = bot("b", { movedTo: { team: { id: "my-cloud", name: "My Cloud" }, state: "moving", at: 1 } });
+ const keys = (options: Parameters<typeof cloudSendSummary>[1]) => cloudSendSummary(sources([moved, held]), options).items.filter((item) => item.kind === "bot").map((item) => item.id);
+ expect(keys({ move: true, leaving: true }), "one on its way still goes").toEqual(["b"]);
+ expect(keys({ move: true }), "the Cloud a bot left for a team still lists it").toEqual(["a", "b"]);
+ });
+
+ it("takes a room only when every bot in it goes, the helper every place has aside", () => {
+ const helper = (id: string) => (id === "maus" ? { defaultBot: { v: 1 } } : {});
+ expect(roomGoes({ memberIds: ["a", "b"] }, new Set(["a", "b"]), helper)).toBe(true);
+ expect(roomGoes({ memberIds: ["a", "maus"] }, new Set(["a"]), helper)).toBe(true);
+ expect(roomGoes({ memberIds: ["a", "b"] }, new Set(["a"]), helper), "b stays, and works in it here").toBe(false);
+ expect(roomGoes({ memberIds: ["maus"] }, new Set(["a"]), helper), "none of its bots go").toBe(false);
+ });
+
+ it("names any number of bots once, and an answer that names no known choice is never read as all of them", async () => {
+ const scopes = createMoveScopes();
+ const ask = async (body: unknown, method = "POST") => {
+ let answered: { status: number; body: any } | undefined;
+ await moveScopeRoute(scopes, { path: "/api/cloud-send/scope", method, req: { resume() {} } as never, res: { setHeader() {} } as never, json: (_res: unknown, status: number, value: unknown) => { answered = { status, body: value }; }, readBody: async () => body } as never);
+ return answered!;
+ };
+ const many = Array.from({ length: 5_000 }, (_, i) => `bot-${i}`);
+ const first = await ask({ v: 1, bots: many });
+ expect(first.status).toBe(200);
+ expect(scopes.get(first.body.scope)?.size).toBe(5_000);
+ expect(scopes.get("nobody")).toBeNull();
+ expect((await ask({ v: 1, bots: ["bad id"] })).status).toBe(400);
+ for (let i = 0; i < 8; i++) await ask({ v: 1, bots: ["a"] });
+ expect(scopes.get(first.body.scope), "only the latest few are kept").toBeNull();
+ });
+});
diff --git a/server/cloud-send-scope.ts b/server/cloud-send-scope.ts
new file mode 100644
index 0000000000..a2cd5da576
--- /dev/null
+++ b/server/cloud-send-scope.ts
@@ -0,0 +1,42 @@
+// A move of some of this computer's bots: main names them once (POST /api/cloud-send/scope) and every read the move makes
+// of this computer's server carries the answer (`scope=`), so a list of any length never goes in a URL. Kept in memory: main
+// names them again each time a move runs.
+import { randomUUID } from "node:crypto";
+import { z } from "zod";
+
+import type { RouteContext } from "./routes/table.ts";
+
+const KEPT = 8;
+const askSchema = z.object({ v: z.literal(1), bots: z.array(z.string().regex(/^[\w-]{1,128}$/u)).min(1).max(100_000) });
+
+export function createMoveScopes() {
+ const scopes = new Map<string, ReadonlySet<string>>();
+ return {
+ add(bots: readonly string[]): string {
+ const token = randomUUID();
+ scopes.set(token, new Set(bots));
+ for (const old of scopes.keys()) { if (scopes.size <= KEPT) break; scopes.delete(old); }
+ return token;
+ },
+ get: (token: string): ReadonlySet<string> | null => scopes.get(token) ?? null,
+ };
+}
+
+export type MoveScopes = ReturnType<typeof createMoveScopes>;
+
+/** A room goes only with every bot in it (My Cloud has a default bot of its own): one that would leave a bot behind stays
+ * here, where that bot goes on working in it. */
+export function roomGoes(room: { memberIds: readonly string[] }, bots: ReadonlySet<string>, bot: (id: string) => { defaultBot?: unknown } | null | undefined): boolean {
+ return room.memberIds.some((id) => bots.has(id)) && room.memberIds.every((id) => bots.has(id) || Boolean(bot(id)?.defaultBot));
+}
+
+/** False when the path is not this route. */
+export async function moveScopeRoute(scopes: MoveScopes, { req, res, path, method, json, readBody }: RouteContext): Promise<boolean> {
+ if (path !== "/api/cloud-send/scope") return false;
+ res.setHeader("cache-control", "no-store");
+ if (method !== "POST") { req.resume(); json(res, 405, { error: "method not allowed" }); return true; }
+ const asked = askSchema.safeParse(await readBody(req, 8 * 1024 * 1024));
+ if (!asked.success) { json(res, 400, { error: "send { v: 1, bots }" }); return true; }
+ json(res, 200, { v: 1, scope: scopes.add(asked.data.bots) });
+ return true;
+}
diff --git a/server/cloud-send.ts b/server/cloud-send.ts
index 9f82b61d5c..14a34a3cf7 100644
--- a/server/cloud-send.ts
+++ b/server/cloud-send.ts
@@ -94,12 +94,14 @@ export function unused(bot: BotRecord, skills: number, greetingOnly: (threadId:
}
/** `move`: a move's comparison, with what only a move carries. `bot`: a move of that one bot into a team: the bot, its
- * skills, its routines and the library skills it uses, never anything of the person's own. */
-export function cloudSendSummary(sources: CloudSendSources, { move = false, bot: only }: { move?: boolean; bot?: string } = {}): CloudSendSummary {
+ * skills, its routines and the library skills it uses, never anything of the person's own. `bots`: a move of only these of
+ * this computer's bots, which a calendar call stays out of: it runs where it was set up. `leaving`: this server is the one
+ * bots move away from, so one that lives elsewhere now is not carried again. */
+export function cloudSendSummary(sources: CloudSendSources, { move = false, bot: only, bots: chosen, leaving = false }: { move?: boolean; bot?: string; bots?: ReadonlySet<string>; leaving?: boolean } = {}): CloudSendSummary {
const items: CloudSendItem[] = [];
const carried = new Set<string>();
for (const bot of sources.bots()) {
- if (only !== undefined && bot.id !== only) continue;
+ if ((only !== undefined && bot.id !== only) || (chosen && !chosen.has(bot.id)) || (leaving && bot.movedTo?.state === "moved")) continue;
const skills = sources.skills(bot);
if (only === undefined && unused(bot, skills.length, sources.greetingOnly, sources.inRoom, move ? sources.automated : undefined)) continue;
carried.add(bot.id);
@@ -129,6 +131,6 @@ export function cloudSendSummary(sources: CloudSendSources, { move = false, bot:
items.push({ key: itemKey.setting("profile"), kind: "setting", label: "profile",
parts: { name: partHash(profile.name), email: partHash(profile.email), about: partHash(profile.aboutMe) } });
items.push({ key: itemKey.setting("language"), kind: "setting", label: "language", parts: { value: partHash(language) } });
- if (move && sources.move) items.push(...sources.move.items(carried));
+ if (move && sources.move) items.push(...sources.move.items(carried).filter((item) => !chosen || item.kind !== "call"));
return { v: 1, appVersion: sources.appVersion, items };
}
diff --git a/server/index.ts b/server/index.ts
index 2aee79bbd3..74c77bb80d 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12219,7 +12219,7 @@ ROUTES.push(createBotMemoryRoutes({
broadcast({ kind: "config", ...configStatus() });
},
}));
-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
diff --git a/server/move-chosen-bots.e2e.test.ts b/server/move-chosen-bots.e2e.test.ts
new file mode 100644
index 0000000000..b68aa618b2
--- /dev/null
+++ b/server/move-chosen-bots.e2e.test.ts
@@ -0,0 +1,83 @@
+// Moving some of this computer's bots to My Cloud, end to end: this computer's server and a Cloud home with main's own wiring
+// between them, as the page's channels start it. The chosen bot goes with its chats and routine; the other stays and
+// keeps answering here, nothing freezes, and more can move later. Disposable homes; no network.
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+let fx: CloudSendFixture;
+beforeAll(async () => { fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-chosen-${randomBytes(8).toString("hex")}`, env: { OMB_ENVIRONMENT_LABEL: "MacBook Air" } }); }, hostTimeout(90_000));
+afterAll(async () => { await fx?.close(); });
+
+type Side = CloudSendFixture["local"];
+type Bot = { id: string; name: string; threadId: string; hidden?: boolean; movedTo?: { state: string; team: { id: string } } };
+const newBot = async (name: string) => (await fx.local("POST", "/api/bots", { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as Bot;
+const listed = async (side: Side) => (await side("GET", "/api/bots")).body.bots as Bot[];
+const rows = async (side: Side, threadId: string) => ((await side("GET", `/api/threads/${threadId}/messages?limit=500`)).body.messages as Array<{ id: string }>).map((row) => row.id);
+const idle = async () => (await listed(fx.local)).every((entry) => !(entry as Bot & { busy?: boolean }).busy);
+async function turn(bot: Bot, text: string) {
+ const before = (await rows(fx.local, bot.threadId)).length;
+ expect((await fx.local("POST", `/api/bots/${bot.id}/messages`, { text, threadId: bot.threadId })).status).toBe(202);
+ await expect.poll(async () => await idle() && (await rows(fx.local, bot.threadId)).length >= before + 2, { timeout: 60_000, interval: 100 }).toBe(true);
+}
+const moves = () => { const file = join(dirname(fx.journalFile), "bot-moves.json"); return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) as { moves: Array<{ phase: string; error?: string; bots: Bot[] }> } : { moves: [] }; };
+const settled = () => expect.poll(() => moves().moves.every((move) => move.phase === "done"), { timeout: 120_000, interval: 250, message: JSON.stringify(moves()) }).toBe(true);
+
+it("the chosen bot goes with its chats and routine; the other keeps answering here, nothing freezes, and more can go later", async () => {
+ const go = await newBot("Goer"), stay = await newBot("Stayer"), later = await newBot("Later");
+ await turn(go, "Hello there."); await turn(stay, "Hi."); await turn(later, "Hey.");
+ expect((await fx.local("PUT", `/api/bots/${go.id}/memory/file`, { path: "MEMORY.md", text: "Likes short answers.\n" })).status).toBe(200);
+ const made = (await fx.local("POST", "/api/routines", { name: "Daily", prompt: "Report.", botId: go.id, schedule: { type: "daily", time: "09:00", weekdays: [1, 2, 3, 4, 5] }, durationMinutes: 15 })).body;
+ const daily = (made.routine ?? made).id as string;
+ const room = (await fx.local("POST", "/api/groups", { name: "Launch", memberIds: [go.id, stay.id] })).body;
+ const roomId = (room.group ?? room).id as string;
+ fx.account.state = { ...fx.account.state, machine: { status: "ready", origin: fx.cloudBase, moves: true } };
+
+ expect(await fx.call("cloud-send:bot-move-state", "local")).toEqual({ available: true, moving: [] });
+ expect(() => fx.call("cloud-send:bot-move-state", "cloud")).toThrow(/only available on this computer's page/u);
+ await fx.call("cloud-send:move-bots", "local", [go.id]);
+ await settled();
+ expect(moves().moves[0]!.bots.map((bot) => bot.id)).toEqual([go.id]);
+
+ const there = await listed(fx.onCloud);
+ expect(there.map((bot) => bot.id)).toContain(go.id);
+ expect(there.map((bot) => bot.id), "the bot that stays is not on My Cloud").not.toContain(stay.id);
+ expect(await rows(fx.onCloud, go.threadId)).toEqual(await rows(fx.local, go.threadId));
+ expect((await fx.onCloud("GET", `/api/bots/${go.id}/memory/file?path=MEMORY.md`)).body.text, "its memory went with it").toContain("Likes short answers.");
+ const routinesThere = (await fx.onCloud("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean }>;
+ expect(routinesThere.find((routine) => routine.id === daily)?.enabled, "what was on here is on there").toBe(true);
+
+ expect((await fx.local("GET", "/api/move/freeze")).body.frozen, "this computer never froze").toBe(false);
+ expect(existsSync(fx.journalFile) ? JSON.parse(readFileSync(fx.journalFile, "utf8")) : null, "no one-time move ran").toBeNull();
+ await turn(stay, "Still here?");
+ const answer = await fx.local("POST", `/api/bots/${go.id}/messages`, { text: "Are you there?", threadId: go.threadId });
+ expect(answer.status, JSON.stringify(answer.body)).toBe(409);
+ const here = (await listed(fx.local)).find((bot) => bot.id === go.id)!;
+ expect(here).toMatchObject({ hidden: true, movedTo: { state: "moved", team: { id: "my-cloud" } } });
+ const routinesHere = (await fx.local("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean }>;
+ expect(routinesHere.find((routine) => routine.id === daily)?.enabled, "it no longer runs here").toBe(false);
+ const roomHere = ((await fx.local("GET", "/api/bots")).body.groups as Array<{ id: string; memberIds: string[] }>).find((group) => group.id === roomId);
+ expect(roomHere?.memberIds, "the room goes on here without it").toEqual([stay.id]);
+ expect(((await fx.onCloud("GET", "/api/bots")).body.groups as Array<{ id: string }>).map((group) => group.id), "a room with a bot left behind stays").not.toContain(roomId);
+ expect((await fx.call<{ on: boolean }>("one-home:keep", "local")).on, "this computer stays home").toBe(true);
+
+ await fx.call("cloud-send:move-bots", "local", [later.id]);
+ await settled();
+ expect((await listed(fx.onCloud)).map((bot) => bot.id)).toContain(later.id);
+ await expect(fx.call("cloud-send:move-bots", "local", [go.id]), "one that moved can't be chosen again").rejects.toThrow();
+ expect((await listed(fx.local)).find((bot) => bot.id === stay.id)?.movedTo).toBeUndefined();
+}, hostTimeout(300_000));
+
+it("Move everything later carries the rest, without touching the bots that already live on My Cloud", async () => {
+ const before = (await listed(fx.local)).filter((bot) => bot.movedTo?.state === "moved").map((bot) => bot.id);
+ expect(before.length).toBeGreaterThan(0);
+ await fx.call("cloud-send:move-everything", "local");
+ const journal = () => (existsSync(fx.journalFile) ? JSON.parse(readFileSync(fx.journalFile, "utf8")) as { phase?: string } | null : null);
+ await expect.poll(async () => { await fx.oneHome.kick(); return journal()?.phase; }, { timeout: 200_000, interval: 500 }).toBe("done");
+ const there = await listed(fx.onCloud);
+ for (const id of before) expect(there.find((bot) => bot.id === id)?.hidden, "it stays a working bot there, not an archived one").toBeFalsy();
+ expect((await fx.local("GET", "/api/move/freeze")).body.frozen, "now everything has gone").toBe(true);
+}, hostTimeout(300_000));
diff --git a/server/routes/bot-moves.ts b/server/routes/bot-moves.ts
index bb762874fd..5d426d0b92 100644
--- a/server/routes/bot-moves.ts
+++ b/server/routes/bot-moves.ts
@@ -1,6 +1,7 @@
-// POST /api/bot-moves/:bot { state: "moving" | "moved", team } and DELETE /api/bot-moves/:bot: My Cloud holding one of
-// its bots while it moves into one of its person's teams, letting it go on if the move stops, and keeping it as the
-// line that opens it there once it arrived (server/bot-moves.ts). Admin scope: the person's own app runs the move.
+// POST /api/bot-moves/:bot { state: "moving" | "moved" | "back", team } and DELETE /api/bot-moves/:bot: a server holding
+// one of its bots while it moves to another home (a team, or My Cloud), letting it go on if the move stops, keeping it as
+// the line that opens it there once it arrived, and having it back if My Cloud ended (server/bot-moves.ts). Admin scope:
+// the person's own app runs the move.
import { z } from "zod";
import type { BotMoves } from "../bot-moves.ts";
@@ -8,7 +9,7 @@ import { PASS, type RouteHandler } from "./table.ts";
const bodySchema = z.object({
v: z.literal(1),
- state: z.enum(["moving", "moved"]),
+ state: z.enum(["moving", "moved", "back"]),
team: z.object({ id: z.string().regex(/^[\w-]{1,128}$/u), name: z.string().trim().min(1).max(80) }),
});
@@ -23,8 +24,12 @@ export function createBotMoveRoutes({ moves, enabled }: { moves: BotMoves | null
}
if (method !== "POST") return json(res, 405, { error: "method not allowed" });
const parsed = bodySchema.safeParse(await readBody(req, 16 * 1024));
- if (!parsed.success) return json(res, 400, { error: "send { v: 1, state: \"moving\" | \"moved\", team: { id, name } }" });
+ if (!parsed.success) return json(res, 400, { error: "send { v: 1, state: \"moving\" | \"moved\" | \"back\", team: { id, name } }" });
const { state, team } = parsed.data;
+ if (state === "back") {
+ const back = moves.back(bot);
+ return "refused" in back ? json(res, 409, { error: back.refused }) : json(res, 200, { v: 1, released: true });
+ }
const answer = state === "moving" ? await moves.hold(bot, team) : moves.moved(bot, team);
if ("busy" in answer) return json(res, 409, { error: `${answer.busy} is answering. The move goes on once it is done.`, busy: answer.busy });
if ("refused" in answer) return json(res, 409, { error: answer.refused });
diff --git a/server/routes/cloud-send.ts b/server/routes/cloud-send.ts
index fcfb2ec35a..b5c23a4fea 100644
--- a/server/routes/cloud-send.ts
+++ b/server/routes/cloud-send.ts
@@ -13,6 +13,7 @@ import { readAttachment } from "../attachments.ts";
import { arrivedRoute, automationsOffRoute, homeRoute } from "../cloud-send-arrived.ts";
import { moveFilesRoute } from "../cloud-send-files.ts";
import { createMoveLeases, moveLeaseRoute } from "../cloud-send-lease.ts";
+import { createMoveScopes, moveScopeRoute } from "../cloud-send-scope.ts";
import { automatedBot, moveBotParts, moveItems, moveKindsRoute, type MoveKindsDeps } from "../cloud-send-kinds.ts";
import { cloudSendManifest } from "../cloud-send-manifest.ts";
import { moveMemoryRoute, type MoveMemoryDeps } from "../cloud-send-memory.ts";
@@ -77,6 +78,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
};
const move = deps.move;
const leases = createMoveLeases();
+ const scopes = createMoveScopes();
return async (ctx) => {
const { req, res, path, method, url, json, readBody } = ctx;
if (path !== "/api/cloud-send" && !path.startsWith("/api/cloud-send/")) return PASS;
@@ -85,10 +87,14 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
if (deps.refusal && !scoped) { req.resume(); return json(res, 403, deps.refusal); }
// A move of one bot into a team reads that bot only, on both sides.
const bot = scoped ?? (/^[\w-]{1,128}$/u.test(url.searchParams.get("bot") ?? "") ? url.searchParams.get("bot")! : undefined);
- if (deps.chats && await cloudSendChatsRoute({ ...deps.chats, ...(bot ? { bot } : {}) }, ctx)) return;
+ const scopeToken = url.searchParams.get("scope");
+ const scope = scopeToken === null ? undefined : scopes.get(scopeToken);
+ if (scope === null) { req.resume(); return json(res, 409, { error: "This move's bots are no longer known here." }); }
+ if (await moveScopeRoute(scopes, ctx)) return;
+ if (deps.chats && await cloudSendChatsRoute({ ...deps.chats, ...(bot ? { bot } : {}), ...(scope ? { scope } : {}) }, ctx)) return;
if (move && await moveKindsRoute(move, ctx)) return;
if (move && await moveMemoryRoute({ ...move, bot: (id) => move.store.bot(id) ?? undefined }, ctx)) return;
- if (move && await moveFilesRoute({ dataDir: move.dataDir, bots: () => (bot ? move.store.bots.filter((entry) => entry.id === bot) : move.store.bots), owner: move.owner }, ctx)) return;
+ if (move && await moveFilesRoute({ dataDir: move.dataDir, bots: () => (bot ? move.store.bots.filter((entry) => entry.id === bot) : scope ? move.store.bots.filter((entry) => scope.has(entry.id)) : move.store.bots), owner: move.owner }, ctx)) return;
if (move && home && await moveLeaseRoute({ leases, owner: move.owner }, ctx)) return;
if (move && home && await arrivedRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks, owner: move.owner, lineLanguage: deps.lineLanguage ?? (() => deps.config().language), ...(deps.connectionsMoved ? { stayed: deps.connectionsMoved } : {}) }, ctx)) return;
if (move && deps.cloudHome && deps.automations && await automationsOffRoute({ automations: deps.automations, owner: move.owner }, ctx)) return;
@@ -97,9 +103,9 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
if (method !== "GET") return json(res, 405, { error: "method not allowed" });
if (!deps.chats) return json(res, 404, { error: "not found" });
res.setHeader("cache-control", "no-store");
- return json(res, 200, await cloudSendManifest({ summary: () => cloudSendSummary(sources, { move: true, ...(bot ? { bot } : {}) }), store: deps.chats.store, dataDir: deps.chats.dataDir,
+ return json(res, 200, await cloudSendManifest({ summary: () => cloudSendSummary(sources, { move: true, leaving: !home, ...(bot ? { bot } : {}), ...(scope ? { bots: scope } : {}) }), store: deps.chats.store, dataDir: deps.chats.dataDir,
connections: deps.connections ?? (async () => []), heads: threadHeads, ...(move ? { kinds: move, teamMemory: move.teamMemory } : {}), ...(bot ? { bot } : {}),
- attachments: url.searchParams.get("attachments") !== "0", files: url.searchParams.get("files") !== "0" }));
+ attachments: url.searchParams.get("attachments") !== "0", files: url.searchParams.get("files") !== "0", ...(scope ? { scope } : {}) }));
}
if (path === "/api/cloud-send/verify-secrets") {
if (!home || !deps.connectionFingerprints) return json(res, 404, { error: "not found" });
@@ -112,7 +118,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
if (path !== "/api/cloud-send") return PASS;
if (method !== "GET") return json(res, 405, { error: "method not allowed" });
res.setHeader("cache-control", "no-store");
- const summary = cloudSendSummary(sources, { move: url.searchParams.get("move") === "1", ...(bot ? { bot } : {}) });
+ const summary = cloudSendSummary(sources, { move: url.searchParams.get("move") === "1", leaving: !home, ...(bot ? { bot } : {}), ...(scope ? { bots: scope } : {}) });
const item = url.searchParams.get("item");
const items = item === null ? summary.items : summary.items.filter((entry) => entry.key === item || (entry.kind === "skill" && item === `bot:${entry.bot}`));
// `chats: 1`: this server takes chats by row.
diff --git a/src/components/CloudSendStrip.tsx b/src/components/CloudSendStrip.tsx
index 6b5f104e4f..6408025645 100644
--- a/src/components/CloudSendStrip.tsx
+++ b/src/components/CloudSendStrip.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import type { CloudSendNotice, CloudSendPageBridge } from "../../electron/cloud-send.mjs";
import { moveQuietUntil } from "@/lib/cloud-send";
+import { BotMoveLine, MoveChooser } from "./MoveToMyCloud";
import { TeamMoveLine } from "./MoveToTeam";
/** My Cloud's notice from main, kept fresh: undefined until main first answers, null when it can't. */
@@ -40,6 +41,11 @@ export function useMoveQuiet(now: () => number = Date.now): boolean | null {
export function CloudSendStrip({ cloudHome }: { cloudHome: boolean }) {
const bridge = !window.ogb?.remoteClient?.active ? window.ogb?.cloudSendPage : undefined;
const [notice, setNotice] = useCloudSendNotice(bridge);
- if (!bridge || !cloudHome || !notice?.teamMove) return null;
- return <TeamMoveLine move={notice.teamMove} onChange={(next) => setNotice({ ...notice, teamMove: next ?? undefined })} />;
+ const [notNow, setNotNow] = useState(false);
+ if (!bridge || !notice) return null;
+ if (cloudHome) return notice.teamMove ? <TeamMoveLine move={notice.teamMove} onChange={(next) => setNotice({ ...notice, teamMove: next ?? undefined })} /> : null;
+ return <>
+ {notice.move?.phase === "choose" && !notNow && <MoveChooser onClose={() => setNotNow(true)} />}
+ {notice.botMove && <BotMoveLine move={notice.botMove} onChange={(next) => setNotice({ ...notice, botMove: next ?? undefined })} />}
+ </>;
}
diff --git a/src/components/MoveToMyCloud.dom.test.ts b/src/components/MoveToMyCloud.dom.test.ts
new file mode 100644
index 0000000000..fd587d98bd
--- /dev/null
+++ b/src/components/MoveToMyCloud.dom.test.ts
@@ -0,0 +1,131 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ bots: [] as Array<Record<string, unknown>> }));
+vi.mock("@/state/store", () => ({ useStore: () => ({ state: { bots: fixture.bots }, dispatch: () => {} }) }));
+vi.mock("./Avatar", () => ({ BotAvatar: () => null }));
+import { BotMoveLine, MoveChooser, MovedToMyCloudRow, useMoveToMyCloud } from "./MoveToMyCloud";
+
+let container: HTMLDivElement, root: Root;
+const page = { moveBots: vi.fn(async () => ({ available: true, moving: [] })), moveEverything: vi.fn(async () => ({ available: true, moving: [] })), botMoveState: vi.fn(async () => ({ available: true, moving: ["moving-one"] })),
+ openMyCloud: vi.fn(async () => {}), botMoveRetry: vi.fn(async () => null), dismiss: vi.fn(async () => ({})) };
+const onClose = vi.fn();
+const named = (count: number) => Array.from({ length: count }, (_, i) => ({ id: `b${i}`, name: i % 2 ? `Sales ${i}` : `Ops ${i}` }));
+const q = (selector: string) => document.body.querySelector<HTMLElement>(selector);
+const all = (selector: string) => [...document.body.querySelectorAll<HTMLElement>(selector)];
+const click = async (element: HTMLElement | null) => { expect(element).toBeTruthy(); await act(async () => element!.click()); };
+const render = async (bots: Array<Record<string, unknown>>) => { fixture.bots = bots; await act(async () => root.render(createElement(MoveChooser, { onClose }))); };
+async function type(value: string) {
+ const field = q("[data-move-search]") as HTMLInputElement;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, value);
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ window.ogb = { cloudSendPage: page } as never;
+ for (const fn of [page.moveBots, page.moveEverything, onClose]) fn.mockClear();
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); delete (window as { ogb?: unknown }).ogb; });
+
+it("Move everything is one press, and closes the dialog", async () => {
+ await render(named(4));
+ await click(q("[data-move-everything]"));
+ expect(page.moveEverything).toHaveBeenCalledTimes(1);
+ expect(onClose).toHaveBeenCalledTimes(1);
+});
+
+it("moves only the bots ticked, and says how many", async () => {
+ await render(named(4));
+ expect((q("[data-move-chosen]") as HTMLButtonElement).disabled).toBe(true);
+ await click(q('[data-move-bot="b1"]'));
+ expect(q("[data-move-chosen]")!.textContent).toBe("Move 1 bot");
+ await click(q('[data-move-bot="b3"]'));
+ expect(q("[data-move-chosen]")!.textContent).toBe("Move 2 bots");
+ expect(q('[data-move-bot="b3"]')!.getAttribute("aria-checked")).toBe("true");
+ await click(q("[data-move-chosen]"));
+ expect(page.moveBots).toHaveBeenCalledWith(["b1", "b3"]);
+});
+
+it("never offers the helper every place has, an archived bot, or one that moved", async () => {
+ await render([{ id: "a", name: "Ada" }, { id: "d", name: "Maus", defaultBot: { v: 1 } }, { id: "h", name: "Old", hidden: true }, { id: "m", name: "Gone", movedTo: { state: "moved", team: { id: "my-cloud" } } }]);
+ expect(all("[data-move-bot]").map((row) => row.dataset.moveBot)).toEqual(["a"]);
+});
+
+it("with thousands of bots, shows a page at a time, finds any by name, and Select all takes everything found, not only what shows", async () => {
+ await render(named(5_000));
+ expect(all("[data-move-bot]")).toHaveLength(200);
+ expect(q("[data-move-more]")!.textContent).toBe("Show 4800 more");
+ await click(q("[data-move-more]"));
+ expect(all("[data-move-bot]")).toHaveLength(400);
+ await type("sales");
+ expect(all("[data-move-bot]")).toHaveLength(200);
+ await click(q("[data-move-select-all]"));
+ expect(q("[data-move-chosen]")!.textContent).toBe("Move 2500 bots");
+ expect(q("[data-move-select-all]")!.textContent).toBe("Clear");
+ await click(q("[data-move-select-all]"));
+ expect((q("[data-move-chosen]") as HTMLButtonElement).disabled).toBe(true);
+ await type("no such bot");
+ expect(q('[data-move-bots]')!.textContent).toBe("No bots match.");
+});
+
+it("says why when the move could not start, and stays open", async () => {
+ page.moveEverything.mockRejectedValueOnce(new Error("Error invoking remote method 'cloud-send:move-everything': Error: This computer has no My Cloud yet."));
+ await render(named(2));
+ await click(q("[data-move-everything]"));
+ expect(q('[role="alert"]')!.textContent).toBe("This computer has no My Cloud yet.");
+ expect(onClose).not.toHaveBeenCalled();
+});
+
+function Menu({ bot }: { bot: Record<string, unknown> }) {
+ const move = useMoveToMyCloud();
+ const item = (_icon: unknown, label: string, onClick?: () => void) => createElement("button", { key: label, "data-item": "", onClick }, label);
+ return createElement("div", null, ...move.items(bot as never, item as never), move.dialog);
+}
+const menu = async (bot: Record<string, unknown>) => { await act(async () => root.render(createElement(Menu, { bot }))); await act(async () => {}); };
+
+it("a bot's menu offers Move to My Cloud, and it goes after one confirm", async () => {
+ await menu({ id: "ada", name: "Ada" });
+ await click(q("[data-item]"));
+ expect(q("[data-bot-move-confirm]")!.textContent).toContain("Ada's chats, skills, memory and routines go with it");
+ await click(all("button").find((button) => button.textContent === "Move") ?? null);
+ expect(page.moveBots).toHaveBeenCalledWith(["ada"]);
+});
+
+it("a bot's menu leaves it out for the helper, a bot on its way, and when My Cloud can't take bots", async () => {
+ await menu({ id: "maus", name: "Maus", defaultBot: { v: 1 } });
+ expect(q("[data-item]")).toBeNull();
+ await menu({ id: "moving-one", name: "Pip" });
+ expect(q("[data-item]")).toBeNull();
+ page.botMoveState.mockResolvedValueOnce({ available: false, moving: [] });
+ await act(async () => root.unmount());
+ root = createRoot(container);
+ await menu({ id: "ada", name: "Ada" });
+ expect(q("[data-item]")).toBeNull();
+});
+
+it("however many bots moved, the sidebar keeps one row, which opens My Cloud; a bot moved into a team is not on it", async () => {
+ const moved = (id: string, team = "my-cloud") => ({ id, name: id, movedTo: { state: "moved", team: { id: team, name: team } } });
+ await act(async () => root.render(createElement(MovedToMyCloudRow, { bots: [moved("a"), moved("b"), moved("c", "team-acme")] as never })));
+ const row = q("[data-moved-to-my-cloud]");
+ expect(row!.textContent).toBe("2 bots live on My Cloud");
+ await click(row);
+ expect(page.openMyCloud).toHaveBeenCalled();
+});
+
+it("the line says how the move goes, and Try again and Open My Cloud reach main", async () => {
+ const move = (phase: "moving" | "failed" | "done") => ({ bot: { id: "bots-1", name: "Ada" }, team: { id: "my-cloud", name: "My Cloud" }, phase, bots: 12 });
+ const onChange = vi.fn();
+ await act(async () => root.render(createElement(BotMoveLine, { move: move("failed"), onChange })));
+ expect(q("[data-cloud-send-strip-line]")!.textContent).toBe("12 bots couldn't move to My Cloud yet. They're still here, and it tries again by itself.");
+ await click(all("button").find((button) => button.textContent === "Try again") ?? null);
+ expect(page.botMoveRetry).toHaveBeenCalled();
+ await act(async () => root.render(createElement(BotMoveLine, { move: move("done"), onChange })));
+ await click(all("button").find((button) => button.textContent === "Open My Cloud") ?? null);
+ expect(page.openMyCloud).toHaveBeenCalled();
+});
diff --git a/src/components/MoveToMyCloud.tsx b/src/components/MoveToMyCloud.tsx
new file mode 100644
index 0000000000..b464fabe18
--- /dev/null
+++ b/src/components/MoveToMyCloud.tsx
@@ -0,0 +1,165 @@
+// Moving some of this computer's bots to My Cloud, in the desktop app only: the dialog that asks which ones before the first
+// move ("Move everything" as the quick way), a bot's own "Move to My Cloud" in its menu, the line that says how it goes,
+// and the one row the bots that moved leave in the sidebar. Main runs the move (electron/bot-move-main.mjs).
+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { ArrowRightLeft, Check, Cloud, Loader2, X } from "lucide-react";
+import type { BotMoveState, BotMoveView } from "../../electron/cloud-send.mjs";
+import { botMoveLine, chooserBots, filterBots, ipcErrorText, CHOOSER_PAGE, MY_CLOUD_TEAM } from "@/lib/cloud-send";
+import { t } from "@/lib/i18n";
+import { useStore, type Bot } from "@/state/store";
+import { BotAvatar } from "./Avatar";
+import { ConfirmDialog } from "./ConfirmDialog";
+import { NotNowButton, PRIMARY_BUTTON } from "./NoticeCard";
+
+type MenuItem = (icon: ReactNode, label: string, onClick?: () => void, opts?: { disabled?: boolean; hint?: string }) => ReactNode;
+
+const bridge = () => (!window.ogb?.remoteClient?.active ? window.ogb?.cloudSendPage : undefined);
+
+/** Which bots go to My Cloud: any of them, found by name, or everything with one press. */
+export function MoveChooser({ onClose }: { onClose: () => void }) {
+ const { state } = useStore();
+ const bots = useMemo(() => chooserBots(state.bots), [state.bots]);
+ const [query, setQuery] = useState("");
+ const [chosen, setChosen] = useState<ReadonlySet<string>>(new Set());
+ const [shown, setShown] = useState(CHOOSER_PAGE);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const root = useRef<HTMLDivElement>(null);
+ const found = useMemo(() => filterBots(bots, query), [bots, query]);
+ const allFound = found.length > 0 && found.every((bot) => chosen.has(bot.id));
+ useEffect(() => {
+ root.current?.querySelector<HTMLElement>("input")?.focus();
+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); onClose(); } };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [onClose]);
+ const toggle = (id: string) => setChosen((before) => {
+ const next = new Set(before);
+ if (!next.delete(id)) next.add(id);
+ return next;
+ });
+ const toggleFound = () => setChosen((before) => {
+ const next = new Set(before);
+ for (const bot of found) if (allFound) next.delete(bot.id); else next.add(bot.id);
+ return next;
+ });
+ const go = (work: (() => Promise<unknown>) | undefined) => {
+ if (!work) return;
+ setBusy(true);
+ setError(null);
+ void work().then(onClose, (cause: unknown) => setError(ipcErrorText(cause) ?? t("cloudSend.choose.failed"))).finally(() => setBusy(false));
+ };
+ const page = bridge();
+ return createPortal(<div className="ui-scrim fixed inset-0 z-[80] flex items-center justify-center p-4">
+ <div ref={root} role="dialog" aria-modal="true" aria-labelledby="move-chooser-title" data-move-chooser=""
+ className="ui-modal relative flex max-h-[min(640px,calc(100dvh-32px))] w-[min(440px,calc(100vw-32px))] flex-col border-0 p-5 text-ink">
+ <h2 id="move-chooser-title" className="pe-8 text-[17px] font-semibold">{t("cloudSend.choose.title")}</h2>
+ <p className="mt-1 text-[14px] leading-5 text-ink-secondary">{t("cloudSend.choose.line")}</p>
+ <button type="button" disabled={busy} data-move-everything="" className={`${PRIMARY_BUTTON} mt-4 w-full justify-center`}
+ onClick={() => go(page?.moveEverything)}>{t("cloudSend.choose.everything")}</button>
+ <div className="mt-4 flex items-center gap-2">
+ <input type="search" value={query} placeholder={t("cloudSend.choose.search")} aria-label={t("cloudSend.choose.search")} data-move-search=""
+ onChange={(event) => { setQuery(event.target.value); setShown(CHOOSER_PAGE); }} className="min-w-0 flex-1 rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:border-accent focus:outline-none disabled:opacity-50" />
+ <button type="button" data-move-select-all="" disabled={!found.length} onClick={toggleFound} className="ui-button whitespace-nowrap px-2.5 py-1.5 text-[13px]">
+ {t(allFound ? "cloudSend.choose.clear" : "cloudSend.choose.selectAll")}
+ </button>
+ </div>
+ <ul className="mt-2 min-h-[120px] flex-1 overflow-y-auto rounded-md border border-hairline" data-move-bots="">
+ {found.slice(0, shown).map((bot) => {
+ const on = chosen.has(bot.id);
+ return <li key={bot.id}>
+ <button type="button" role="checkbox" aria-checked={on} data-move-bot={bot.id} onClick={() => toggle(bot.id)} className="flex w-full items-center gap-2.5 px-3 py-2 text-start text-[14px] hover:bg-raised">
+ <BotAvatar bot={bot} size={22} animated={false} />
+ <span className="min-w-0 flex-1 truncate" dir="auto">{bot.name}</span>
+ {on && <Check size={15} aria-hidden="true" />}
+ </button>
+ </li>;
+ })}
+ {!found.length && <li className="px-3 py-3 text-[13px] text-ink-tertiary">{t("cloudSend.choose.none")}</li>}
+ {found.length > shown && <li><button type="button" data-move-more="" className="w-full px-3 py-2 text-[13px] text-ink-secondary hover:bg-raised" onClick={() => setShown((count) => count + CHOOSER_PAGE)}>
+ {t("cloudSend.choose.more", { count: found.length - shown })}
+ </button></li>}
+ </ul>
+ <p className="mt-2 text-[12px] text-ink-tertiary">{t("cloudSend.choose.rooms")}</p>
+ {error && <p role="alert" className="mt-2 text-[13px] text-danger">{error}</p>}
+ <button type="button" disabled={busy || !chosen.size} data-move-chosen="" className="ui-button mt-3 w-full justify-center py-1.5 text-[14px]" onClick={() => go(page?.moveBots && (() => page.moveBots!([...chosen])))}>
+ {busy && <Loader2 size={14} aria-hidden="true" className="me-1.5 animate-spin" />}
+ {chosen.size === 1 ? t("cloudSend.choose.moveOne") : t("cloudSend.choose.moveSome", { count: chosen.size })}
+ </button>
+ <div className="mt-1 flex justify-center"><NotNowButton onClick={onClose} /></div>
+ <button type="button" onClick={onClose} aria-label={t("common.close")} className="ui-icon-button absolute end-3 top-3"><X size={16} /></button>
+ </div>
+ </div>, document.body);
+}
+
+/** Whether this computer's bots can move to My Cloud now, read again each time the window is back in front. */
+function useBotMoveState(): BotMoveState | null {
+ const [known, setKnown] = useState<BotMoveState | null>(null);
+ useEffect(() => {
+ const page = bridge();
+ if (!page?.botMoveState) return;
+ let alive = true;
+ const read = () => void page.botMoveState!().then((next) => { if (alive) setKnown(next); }, () => { if (alive) setKnown(null); });
+ read();
+ window.addEventListener("focus", read);
+ return () => { alive = false; window.removeEventListener("focus", read); };
+ }, []);
+ return known;
+}
+
+/** A bot's own "Move to My Cloud", and the one confirm it opens. */
+export function useMoveToMyCloud() {
+ const known = useBotMoveState();
+ const [asked, setAsked] = useState<Bot | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const confirm = () => {
+ const page = bridge();
+ if (!asked || !page?.moveBots) return;
+ setBusy(true);
+ setError(null);
+ void page.moveBots([asked.id]).then(() => setAsked(null), (cause: unknown) => setError(ipcErrorText(cause) ?? t("cloudSend.choose.failed"))).finally(() => setBusy(false));
+ };
+ const names = { bot: asked?.name ?? "" };
+ return {
+ items(bot: Bot, item: MenuItem): ReactNode[] {
+ if (!known?.available || bot.defaultBot || bot.movedTo || known.moving.includes(bot.id)) return [];
+ return [item(<Cloud size={16} className="text-ink-secondary" />, t("cloudSend.botMove.menu"), () => { setError(null); setAsked(bot); })];
+ },
+ dialog: <ConfirmDialog open={asked !== null} tone="neutral" icon={<Cloud size={18} />} title={t("cloudSend.botMove.confirmTitle", names)}
+ body={<span className="flex flex-col gap-2" data-bot-move-confirm="">
+ <span>{t("cloudSend.botMove.confirmBody", names)}</span>
+ {error && <span role="alert" className="text-danger">{error}</span>}
+ </span>}
+ confirmLabel={t("cloudSend.botMove.confirm")} pending={busy} onCancel={() => setAsked(null)} onConfirm={confirm} />,
+ };
+}
+
+/** The one row the bots that moved to My Cloud leave in the sidebar: however many there are, it opens My Cloud. */
+export function MovedToMyCloudRow({ bots }: { bots: readonly Bot[] }) {
+ const moved = bots.filter((bot) => bot.movedTo?.state === "moved" && bot.movedTo.team.id === MY_CLOUD_TEAM);
+ if (!moved.length) return null;
+ const page = bridge();
+ return <div className="flex flex-col px-2 pb-1">
+ <button type="button" data-moved-to-my-cloud={moved.length} disabled={!page?.openMyCloud} onClick={() => { void page?.openMyCloud?.().catch(() => {}); }}
+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-ink-secondary enabled:hover:bg-menu-hover enabled:hover:text-ink">
+ <ArrowRightLeft size={14} aria-hidden="true" className="shrink-0" />
+ <span className="truncate" dir="auto">{moved.length === 1 ? t("cloudSend.botMove.movedOne", { bot: moved[0]!.name }) : t("cloudSend.botMove.movedMany", { count: moved.length })}</span>
+ </button>
+ </div>;
+}
+
+/** How the chosen bots' move goes: on its way, failed (it tries again by itself), or done. */
+export function BotMoveLine({ move, onChange }: { move: BotMoveView; onChange(next: BotMoveView | null): void }) {
+ const page = bridge();
+ const line = botMoveLine(move);
+ const link = "font-medium text-accent-text underline underline-offset-2 hover:text-ink";
+ return <div role="status" data-cloud-send-strip={line.kind} data-bot-move-line={move.phase} className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">
+ {line.kind === "sending" ? <Loader2 size={14} aria-hidden="true" className="animate-spin" /> : <ArrowRightLeft size={14} aria-hidden="true" />}
+ <span dir="auto" data-cloud-send-strip-line>{line.text}</span>
+ {line.kind === "done" && page?.openMyCloud && <button type="button" className={link} onClick={() => { void page.openMyCloud!().catch(() => {}); }}>{t("cloudSend.botMove.open")}</button>}
+ {line.kind === "failed" && page?.botMoveRetry && <button type="button" className={link} onClick={() => { void page.botMoveRetry!().then(onChange).catch(() => {}); }}>{t("cloudSend.strip.retry")}</button>}
+ {line.kind !== "sending" && <button type="button" className="hover:text-ink" onClick={() => { void page?.dismiss("bot-move").then(() => onChange(null)).catch(() => {}); }}>{t("cloudSend.strip.close")}</button>}
+ </div>;
+}
diff --git a/src/components/MoveToTeam.tsx b/src/components/MoveToTeam.tsx
index 3d0702854d..823fa6ebd4 100644
--- a/src/components/MoveToTeam.tsx
+++ b/src/components/MoveToTeam.tsx
@@ -7,7 +7,7 @@ import { ArrowRightLeft, Loader2, Users } from "lucide-react";
import type { TeamMoveView } from "../../electron/team-move.mjs";
import type { Bot } from "@/state/store";
import { ConfirmDialog } from "./ConfirmDialog";
-import { ipcErrorText, teamMoveLine, teamMoveRefusalText } from "@/lib/cloud-send";
+import { ipcErrorText, MY_CLOUD_TEAM, teamMoveLine, teamMoveRefusalText } from "@/lib/cloud-send";
import { t } from "@/lib/i18n";
type Team = { id: string; name: string; ready: boolean };
@@ -81,7 +81,7 @@ export function useMoveToTeam({ blocked }: { blocked: (bot: Bot) => string | und
/** What a bot moved into a team leaves on My Cloud: one line that opens it there. */
export function MovedBotRows({ bots }: { bots: readonly Bot[] }) {
- const moved = bots.filter((bot) => bot.movedTo?.state === "moved");
+ const moved = bots.filter((bot) => bot.movedTo?.state === "moved" && bot.movedTo.team.id !== MY_CLOUD_TEAM);
if (!moved.length) return null;
const page = bridge();
return <div className="flex flex-col px-2 pb-1" data-moved-bots>
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index fdb9e74486..1e0a65817a 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -103,7 +103,7 @@ import { useAdvancedMode } from "@/lib/interface-mode";
import { myDefaultBot, useViewerEmail, useWelcomingBot } from "@/lib/default-bot";
import { PinnedBotRoster, PinnedCircleThreadSection } from "./PinnedCircleThreads";
import { archiveBotWithNotice, onArchiveNotice } from "./bot-archive";
-import { ArchivedBotsPanel, botConfirmProps, type BotConfirmKind } from "./ArchivedBotsPanel"; import { MovedBotRows } from "./MoveToTeam";
+import { ArchivedBotsPanel, botConfirmProps, type BotConfirmKind } from "./ArchivedBotsPanel"; import { MovedBotRows } from "./MoveToTeam"; import { MovedToMyCloudRow } from "./MoveToMyCloud";
import { NewRoomPanel } from "./SidebarNewRoomPanel";
import { SectionPicker } from "./SidebarSectionPicker";
@@ -1490,7 +1490,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
</div>
);
})}
- <MovedBotRows bots={state.bots} /><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />
+ <MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} /><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />
{showPinnedCircleThreads && (
<PinnedCircleThreadSection
bots={pinnedBots}
diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsx
index 2d9b4b1be4..cea3db6dc0 100644
--- a/src/components/SidebarBotMenu.tsx
+++ b/src/components/SidebarBotMenu.tsx
@@ -18,6 +18,7 @@ import { useShowThreads } from "@/lib/thread-preferences";
import { submenuPosition } from "./SidebarPopoverMenu";
import { submenuIntent, type SubmenuIntent } from "@/lib/submenu-intent";
import { useAdvancedMode } from "@/lib/interface-mode";
+import { useMoveToMyCloud } from "./MoveToMyCloud";
import { useMoveToTeam } from "./MoveToTeam";
import type { MenuState } from "./Sidebar";
import { departmentNames, moveBotsToSection, useMayMoveBots } from "./bot-sections";
@@ -72,6 +73,7 @@ export function BotContextMenu({
const member = admin === false;
const mayMove = useMayMoveBots();
const clearThreads = useDeleteAllThreads(simpleMenu), moveToTeam = useMoveToTeam({ blocked: (bot) => (bot.defaultBot ? t("teamMove.blockedDefault", { name: bot.name }) : bot.chiefOfStaff ? t("teamMove.blockedChief") : state.bots.filter((candidate) => !candidate.hidden).length <= 1 ? t("teamMove.blockedLast") : undefined) });
+ const moveToCloud = useMoveToMyCloud();
const remoteClient = window.ogb?.remoteClient?.active === true;
const bot = shown ? state.bots.find((b) => b.id === shown.botId) : undefined;
const team = useTeamPeople();
@@ -149,7 +151,7 @@ export function BotContextMenu({
sheetOut.style.top = `${place.top}px`;
});
- if (!motion.shown || !bot || !shown) return <>{clearThreads.dialog}{moveToTeam.dialog}</>;
+ if (!motion.shown || !bot || !shown) return <>{clearThreads.dialog}{moveToTeam.dialog}{moveToCloud.dialog}</>;
const deleting = state.deletingBots[bot.id] === true;
const engine = state.instances.find((instance) => instance.instanceId === bot.modelSelection.instanceId);
const canCoordinate = engine?.capabilities?.agentsMcp === true;
@@ -261,6 +263,7 @@ export function BotContextMenu({
member ? null : item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () => dispatch({ type: "duplicateBot", botId: bot.id })),
owner,
...moveToTeam.items(bot, item),
+ ...moveToCloud.items(bot, item),
...deleteAll,
];
// Simple view hides the thread list: start one, see them all (the panel's Conversations), and choose the one it opens.
@@ -281,7 +284,7 @@ export function BotContextMenu({
item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),
<BotDeleteMenuItem key="delete" deleting={deleting} className={MENU_ITEM} onClick={() => { onClose(); onDelete(bot); }} />,
];
- return <>{clearThreads.dialog}{moveToTeam.dialog}{createPortal(
+ return <>{clearThreads.dialog}{moveToTeam.dialog}{moveToCloud.dialog}{createPortal(
<div
ref={menuRef}
data-bot-menu
@@ -358,7 +361,7 @@ export function BotContextMenu({
)}</>;
}
- return <>{clearThreads.dialog}{moveToTeam.dialog}{createPortal(
+ return <>{clearThreads.dialog}{moveToTeam.dialog}{moveToCloud.dialog}{createPortal(
<div
ref={menuRef}
data-bot-menu
@@ -421,7 +424,7 @@ export function BotContextMenu({
item(<ClipboardCopy size={16} className="text-ink-secondary" />, t("sidebar.copyConversationId"), () => {
void copyText(bot.threadId);
}),
- divider("d3"), ...moveToTeam.items(bot, item),
+ divider("d3"), ...moveToTeam.items(bot, item), ...moveToCloud.items(bot, item),
...(bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : member ? [] : [
item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),
<BotDeleteMenuItem key="delete" deleting={deleting} className={MENU_ITEM} onClick={() => { onClose(); onDelete(bot); }} />,
diff --git a/src/lib/cloud-send.test.ts b/src/lib/cloud-send.test.ts
index ebcbb3265c..adb91d346b 100644
--- a/src/lib/cloud-send.test.ts
+++ b/src/lib/cloud-send.test.ts
@@ -3,11 +3,42 @@ import { setLocale } from "@/lib/i18n";
import { readFileSync } from "node:fs";
import en from "@/locales/en.json";
import ptBr from "@/locales/pt-br.json";
-import { ipcErrorText, moveLine } from "./cloud-send";
+import { botMoveLine, chooserBots, filterBots, ipcErrorText, moveLine, moveQuietUntil } from "./cloud-send";
beforeEach(() => { setLocale("en"); });
afterEach(() => { setLocale("en"); });
+describe("choosing which bots move", () => {
+ const bot = (id: string, name: string, extra: { hidden?: boolean; defaultBot?: unknown; movedTo?: unknown } = {}) => ({ id, name, ...extra });
+
+ it("offers every bot but the helper every place has, an archived one, or one that moved", () => {
+ expect(chooserBots([bot("a", "Ada"), bot("d", "Maus", { defaultBot: { v: 1 } }), bot("h", "Old", { hidden: true }), bot("m", "Gone", { movedTo: { state: "moved" } })]).map((entry) => entry.id)).toEqual(["a"]);
+ });
+
+ it("finds bots by every word of what is typed, in any case, and finds thousands at once", () => {
+ const bots = Array.from({ length: 50_000 }, (_, i) => bot(`b${i}`, `Sales Bot ${i}`));
+ const started = performance.now();
+ expect(filterBots(bots, " sales 49999 ").map((entry) => entry.id)).toEqual(["b49999"]);
+ expect(performance.now() - started).toBeLessThan(500);
+ expect(filterBots(bots, " ")).toBe(bots);
+ });
+
+ it("says how the chosen bots' move goes, for one bot and for many, in both languages", () => {
+ const move = (phase: "moving" | "failed" | "done", bots?: number) => ({ bot: { id: "bots-1", name: "Ada" }, team: { id: "my-cloud", name: "My Cloud" }, phase, ...(bots ? { bots } : {}) });
+ expect(botMoveLine(move("moving", 1))).toEqual({ kind: "sending", text: "Moving Ada to My Cloud…" });
+ expect(botMoveLine(move("moving", 12)).text).toBe("Moving 12 bots to My Cloud…");
+ expect(botMoveLine(move("done", 12))).toEqual({ kind: "done", text: "12 bots live on My Cloud now." });
+ expect(botMoveLine(move("failed")).kind).toBe("failed");
+ setLocale("pt-br");
+ expect(botMoveLine(move("done", 1)).text).toBe("Ada agora vive no Cloud.");
+ });
+
+ it("says nothing on the move's line while the person is asked, and nothing waits for it", () => {
+ expect(moveLine({ phase: "choose" }, "local")).toBeNull();
+ expect(moveQuietUntil({ phase: "choose" })).toBe(0);
+ });
+});
+
describe("the one-time move's line", () => {
it("never says everything is here when a connector stayed on this computer, and says why", () => {
const done = { phase: "done" as const, phone: false, held: [], counts: { bots: 13, skills: 0, logins: 0, onePassword: false, chats: 0, routines: 0 } };
diff --git a/src/lib/cloud-send.ts b/src/lib/cloud-send.ts
index df3314dc8f..23d1c30ab5 100644
--- a/src/lib/cloud-send.ts
+++ b/src/lib/cloud-send.ts
@@ -1,5 +1,5 @@
// What either page says about the one-time move to My Cloud (electron/one-home.mjs), and what arrived, in words.
-import type { CloudSendCounts } from "../../electron/cloud-send.mjs";
+import type { BotMoveView, CloudSendCounts } from "../../electron/cloud-send.mjs";
import type { OneHomeCounts, OneHomeNotCarried, OneHomeStayed, OneHomeView } from "../../electron/one-home.mjs";
import type { TeamMoveRefusal, TeamMoveRefusalCode, TeamMoveView } from "../../electron/team-move.mjs";
import type { LocaleKey } from "@/locales";
@@ -56,7 +56,7 @@ export const MOVE_QUIET_MS = 5 * 60_000;
/** Until when the corner cards that sell or ask for something (Product Hunt, the star, Cloud offers) wait for the
* one-time move: for good while it goes or brings things home (Infinity), and MOVE_QUIET_MS after it is done. */
export function moveQuietUntil(move: OneHomeView | null | undefined): number {
- if (!move) return 0;
+ if (!move || move.phase === "choose") return 0;
if (move.phase === "done") return move.at ? move.at + MOVE_QUIET_MS : 0;
return Infinity;
}
@@ -93,6 +93,7 @@ function underWayLine(move: OneHomeView, place?: string): string | null {
* computer's bots on their way home and home because the person keeps them here.
* `page`: which page shows it; `reason`: why a failing move failed, in main's words, when it said. */
export function moveLine(move: OneHomeView, page: "local" | "cloud"): { kind: "sending" | "failed" | "done"; text: string; extra: string[]; phone?: true; retry?: true; reason?: string; place?: string } | null {
+ if (move.phase === "choose") return null;
if (move.place) return ownMoveLine(move, move.place, page);
if (move.phase === "done") {
if (page !== "cloud") return null;
@@ -160,6 +161,28 @@ function ownMoveLine(move: OneHomeView, place: string, page: "local" | "cloud"):
return line("sending", chats ? t("cloudSend.move.copyChatsNamed", { place, done: chats.done, total: chats.total }) : t("cloudSend.move.copyNamed", { place }));
}
+/** The "team" a bot that moved from this computer to My Cloud is held for (electron/bot-move-main.mjs). */
+export const MY_CLOUD_TEAM = "my-cloud";
+/** The bots the person can choose to move: as the sidebar has them, but the helper every place has and any that moved. */
+export const chooserBots = <T extends { hidden?: boolean; defaultBot?: unknown; movedTo?: unknown }>(bots: readonly T[]): T[] => bots.filter((bot) => !bot.hidden && !bot.defaultBot && !bot.movedTo);
+/** How many of the choice the list shows at a time, however many bots there are. */
+export const CHOOSER_PAGE = 200;
+/** The bots whose names hold every word of `query`. */
+export function filterBots<T extends { name: string }>(bots: readonly T[], query: string): readonly T[] {
+ const words = query.trim().toLocaleLowerCase(activeLocale()).split(/\s+/u).filter(Boolean);
+ if (!words.length) return bots;
+ return bots.filter((bot) => { const name = bot.name.toLocaleLowerCase(activeLocale()); return words.every((word) => name.includes(word)); });
+}
+
+/** Some of this computer's bots moving to My Cloud, on this computer's page. */
+export function botMoveLine(move: BotMoveView): { kind: "sending" | "failed" | "done"; text: string } {
+ const count = move.bots ?? 1, many = count > 1;
+ const params: Record<string, string | number> = many ? { count } : { bot: move.bot.name };
+ if (move.phase === "done") return { kind: "done", text: t(many ? "cloudSend.botMove.doneMany" : "cloudSend.botMove.done", params) };
+ if (move.phase === "failed") return { kind: "failed", text: t(many ? "cloudSend.botMove.failedMany" : "cloudSend.botMove.failed", params) };
+ return { kind: "sending", text: t(many ? "cloudSend.botMove.movingMany" : "cloudSend.botMove.moving", params) };
+}
+
/** A bot moving from My Cloud into a team, on My Cloud's page: on its way, failed (it is still here, unchanged), or done. */
export function teamMoveLine(move: TeamMoveView): { kind: "sending" | "failed" | "done"; text: string } {
const names = { bot: move.bot.name, team: move.team.name };
diff --git a/src/locales/en.json b/src/locales/en.json
index f1ae9598b6..12e0be5b26 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1365,6 +1365,31 @@
"cloudSend.move.slow": "My Cloud is slow to answer. Your move goes on from where it was at {time}.",
"cloudSend.move.queued": "Waiting for {name} to finish moving to My Cloud. Your bots move right after.",
"cloudSend.move.queuedAny": "Waiting for your other computer to finish moving to My Cloud. Your bots move right after.",
+ "cloudSend.choose.title": "Move your bots to My Cloud",
+ "cloudSend.choose.line": "Choose which bots move. The others stay on this computer and keep working here.",
+ "cloudSend.choose.everything": "Move everything",
+ "cloudSend.choose.moveSome": "Move {count} bots",
+ "cloudSend.choose.moveOne": "Move 1 bot",
+ "cloudSend.choose.search": "Search your bots",
+ "cloudSend.choose.selectAll": "Select all",
+ "cloudSend.choose.clear": "Clear",
+ "cloudSend.choose.none": "No bots match.",
+ "cloudSend.choose.more": "Show {count} more",
+ "cloudSend.choose.rooms": "A room moves when all of its bots do.",
+ "cloudSend.choose.failed": "Couldn't start the move. Try again.",
+ "cloudSend.botMove.menu": "Move to My Cloud",
+ "cloudSend.botMove.confirmTitle": "Move {bot} to My Cloud?",
+ "cloudSend.botMove.confirmBody": "{bot}'s chats, skills, memory and routines go with it, and it works on My Cloud from then on. Your other bots stay on this computer.",
+ "cloudSend.botMove.confirm": "Move",
+ "cloudSend.botMove.moving": "Moving {bot} to My Cloud…",
+ "cloudSend.botMove.movingMany": "Moving {count} bots to My Cloud…",
+ "cloudSend.botMove.done": "{bot} lives on My Cloud now.",
+ "cloudSend.botMove.doneMany": "{count} bots live on My Cloud now.",
+ "cloudSend.botMove.failed": "{bot} couldn't move to My Cloud yet. It's still here, and it tries again by itself.",
+ "cloudSend.botMove.failedMany": "{count} bots couldn't move to My Cloud yet. They're still here, and it tries again by itself.",
+ "cloudSend.botMove.open": "Open My Cloud",
+ "cloudSend.botMove.movedOne": "{bot} lives on My Cloud",
+ "cloudSend.botMove.movedMany": "{count} bots live on My Cloud",
"cloudSend.move.updating": "My Cloud is updating. Your move starts when it's done.",
"cloudSend.move.failing": "Your bots couldn't move to My Cloud yet: {error}",
"cloudSend.move.failingPlain": "Your bots couldn't move to My Cloud yet.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 5d6cdc352e..5ae1a39f01 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -7172,6 +7172,31 @@
"cloudSend.move.slow": "O Cloud está demorando para responder. A mudança continua de onde parou às {time}.",
"cloudSend.move.queued": "Esperando {name} terminar de ir para o Cloud. Seus bots vão logo depois.",
"cloudSend.move.queuedAny": "Esperando seu outro computador terminar de ir para o Cloud. Seus bots vão logo depois.",
+ "cloudSend.choose.title": "Levar seus bots para o Cloud",
+ "cloudSend.choose.line": "Escolha quais bots vão. Os outros ficam neste computador e continuam funcionando aqui.",
+ "cloudSend.choose.everything": "Levar tudo",
+ "cloudSend.choose.moveSome": "Levar {count} bots",
+ "cloudSend.choose.moveOne": "Levar 1 bot",
+ "cloudSend.choose.search": "Buscar seus bots",
+ "cloudSend.choose.selectAll": "Selecionar todos",
+ "cloudSend.choose.clear": "Limpar",
+ "cloudSend.choose.none": "Nenhum bot encontrado.",
+ "cloudSend.choose.more": "Mostrar mais {count}",
+ "cloudSend.choose.rooms": "Uma sala vai quando todos os bots dela vão.",
+ "cloudSend.choose.failed": "Não foi possível iniciar a mudança. Tente de novo.",
+ "cloudSend.botMove.menu": "Levar para o Cloud",
+ "cloudSend.botMove.confirmTitle": "Levar {bot} para o Cloud?",
+ "cloudSend.botMove.confirmBody": "As conversas, skills, memória e rotinas de {bot} vão junto, e a partir daí ele trabalha no Cloud. Seus outros bots ficam neste computador.",
+ "cloudSend.botMove.confirm": "Levar",
+ "cloudSend.botMove.moving": "Levando {bot} para o Cloud…",
+ "cloudSend.botMove.movingMany": "Levando {count} bots para o Cloud…",
+ "cloudSend.botMove.done": "{bot} agora vive no Cloud.",
+ "cloudSend.botMove.doneMany": "{count} bots agora vivem no Cloud.",
+ "cloudSend.botMove.failed": "{bot} ainda não conseguiu ir para o Cloud. Continua aqui, e tenta de novo sozinho.",
+ "cloudSend.botMove.failedMany": "{count} bots ainda não conseguiram ir para o Cloud. Continuam aqui, e a mudança tenta de novo sozinha.",
+ "cloudSend.botMove.open": "Abrir o Cloud",
+ "cloudSend.botMove.movedOne": "{bot} vive no Cloud",
+ "cloudSend.botMove.movedMany": "{count} bots vivem no Cloud",
"cloudSend.move.updating": "O Cloud está sendo atualizado. A mudança começa assim que a atualização terminar.",
"cloudSend.move.failing": "Seus bots ainda não conseguiram ir para o Cloud: {error}",
"cloudSend.move.failingPlain": "Seus bots ainda não conseguiram ir para o Cloud.",