Skip to content

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

Move back, server side: a bot can come back from My Cloud to this computer

milind-soni5f3f5d141adc
diff --git a/electron/cloud-send-parts.d.mts b/electron/cloud-send-parts.d.mts
index 8c26f4fec3..e56b115d5e 100644
--- a/electron/cloud-send-parts.d.mts
+++ b/electron/cloud-send-parts.d.mts
@@ -9,6 +9,8 @@ export interface SendItem {
id?: string;
bot?: string;
parts: Record<string, string>;
+ /** Of a bot coming back to the side that lists it: the other side's is newer, and goes. */
+ returning?: true;
}
/** `chats`: the server takes chats by row (server/cloud-send-chats.ts). `vault`: it takes saved Vault secrets by id. */
export interface SendSummary { v: 1; appVersion: string | null; items: SendItem[]; chats?: true; vault?: true }
diff --git a/electron/cloud-send-parts.mjs b/electron/cloud-send-parts.mjs
index d1b8c660e5..edc1b49243 100644
--- a/electron/cloud-send-parts.mjs
+++ b/electron/cloud-send-parts.mjs
@@ -77,6 +77,7 @@ export function parseSendSummary(value) {
...(typeof item.id === "string" && item.id.length <= 300 ? { id: item.id } : {}),
...(typeof item.bot === "string" && /^[\w-]{1,128}$/u.test(item.bot) ? { bot: item.bot } : {}),
parts,
+ ...(item.returning === true ? { returning: true } : {}),
});
}
return { v: 1, appVersion: typeof value.appVersion === "string" ? value.appVersion.slice(0, 40) : null, items, ...(value.chats === 1 ? { chats: true } : {}), ...(value.vault === 1 ? { vault: true } : {}) };
@@ -120,13 +121,15 @@ export function planSend({ local, cloud, sent = {}, off = {}, force = [] }) {
continue;
}
const parts = [], differs = [];
+ // What the other side kept of a bot coming back to it (server/cloud-send.ts `returning`) is older than this side's.
+ const returning = theirs.returning === true;
for (const [part, mine] of Object.entries(item.parts)) {
const cloudHash = theirs.parts[part] ?? EMPTY;
const pair = Array.isArray(last?.[part]) ? last[part] : null;
- if (mine === cloudHash || (!pair && !CONTENT_COMPARED.has(item.kind) && cloudHash !== EMPTY)) {
+ if (mine === cloudHash || (!returning && !pair && !CONTENT_COMPARED.has(item.kind) && cloudHash !== EMPTY)) {
if (!pair || pair[0] !== mine || pair[1] !== cloudHash) (baseline[item.key] ??= {})[part] = [mine, cloudHash];
- } else if (pair && mine === pair[0]) continue;
- else if ((pair && cloudHash === pair[1]) || (cloudHash === EMPTY && mine !== EMPTY) || forced.has(item.key)) parts.push(part);
+ } else if (!returning && pair && mine === pair[0]) continue;
+ else if (returning || (pair && cloudHash === pair[1]) || (cloudHash === EMPTY && mine !== EMPTY) || forced.has(item.key)) parts.push(part);
else differs.push(part);
}
settled({ ...base, state: parts.length ? "to-update" : differs.length ? "differs" : "on-both",
diff --git a/packages/phone-protocol/src/environment.ts b/packages/phone-protocol/src/environment.ts
index 00d70bff14..cf04efaac1 100644
--- a/packages/phone-protocol/src/environment.ts
+++ b/packages/phone-protocol/src/environment.ts
@@ -40,6 +40,9 @@ export interface EnvironmentDescriptor {
* the manifest, the chats and credentials checks, and lines its owner wrote there stamped as the owner's. Whether a
* session is that person, /api/auth/session says (`own`). */
move?: 1;
+ /** A person's own Cloud home, or a desktop's own server, that moves one bot back to where it came from: a returning
+ * hold, the arrival that makes it live there, and a hold that lapses (server/bot-moves.ts). */
+ moveBack?: 1;
/** Who can update the server: the desktop app that runs it, or the operator. */
selfUpdate: "desktop-managed" | "operator";
/** For an operator's server: how it was installed, so a client offers the update command that fits it. */
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index d15ea03232..82d85409c3 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -127,6 +127,7 @@ export const VITEST_SUBSETS = {
"server/host/brief-words.test.ts",
"server/host/lending-lifts.test.ts",
"server/lent-folders.e2e.test.ts",
+ "server/move-back.e2e.test.ts",
"server/move-chosen-bots.e2e.test.ts",
"server/one-home-keep.e2e.test.ts",
"server/one-home-outdated.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 2d12905090..8cb96a702c 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -267,6 +267,7 @@ describe("CI outputs", () => {
"server/host/brief-words.test.ts",
"server/host/lending-lifts.test.ts",
"server/lent-folders.e2e.test.ts",
+ "server/move-back.e2e.test.ts",
"server/move-chosen-bots.e2e.test.ts",
"server/one-home-keep.e2e.test.ts",
"server/one-home-outdated.e2e.test.ts",
diff --git a/server/bot-moves.test.ts b/server/bot-moves.test.ts
index f7d38b00e2..fdaf89184d 100644
--- a/server/bot-moves.test.ts
+++ b/server/bot-moves.test.ts
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { assertBotHere, botMoveRefusal, createBotMoves, MY_CLOUD_TEAM } from "./bot-moves.ts";
+import { assertBotHere, botMoveRefusal, COMPUTER_TEAM_PREFIX, createBotMoves, MY_CLOUD_TEAM, personalTeam } from "./bot-moves.ts";
+import { arrivalsFile } from "./move-back.ts";
import type { BotRecord } from "./store.ts";
import { WaitManager } from "./waits.ts";
@@ -152,3 +153,209 @@ it("a bot that lives in another of the person's places takes no turn here, and s
expect(() => assertBotHere(standIn)).toThrow(/lives on My Cloud/);
expect(botMoveRefusal({ name: "Scout" })).toBeNull();
});
+
+describe("a bot coming back from My Cloud to this computer, and going there again", () => {
+ const MY_CLOUD = { id: MY_CLOUD_TEAM, name: "My Cloud" };
+ const LAPTOP = { id: `${COMPUTER_TEAM_PREFIX}inst-1`, name: "MacBook Air" };
+ const MINUTE = 60_000;
+
+ /** One place's server: a stub of Scout (or Scout live), its routines, webhook and app event, the MCP servers it has. */
+ function place({ computer = true, scout = "stub" as "stub" | "live" | "none", createdAt = 0, busy = false } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-move-back-"));
+ dirs.push(dir);
+ let clock = 10 * MINUTE;
+ const bots = new Map<string, Record<string, unknown>>();
+ if (scout === "stub") bots.set("scout", { id: "scout", name: "Scout", createdAt, hidden: true, mcpServers: ["notes"], movedTo: { team: computer ? MY_CLOUD : LAPTOP, state: "moved", at: 1, held: ["routine:brief"] } });
+ if (scout === "live") bots.set("scout", { id: "scout", name: "Scout", createdAt, mcpServers: ["notes"] });
+ bots.set("pip", { id: "pip", name: "Pip", createdAt: 0 });
+ const routines = [{ id: "brief", name: "Morning brief", botId: "scout", enabled: false }, { id: "weekly", name: "Weekly", botId: "scout", enabled: false }];
+ const hooks = [{ id: "orders", name: "Orders", botId: "scout", enabled: false }];
+ const events = [{ id: "mail", name: "New mail", botId: "scout", enabled: false }];
+ const removed: string[] = [];
+ const deps = {
+ store: { bot: (id: string) => (bots.get(id) as unknown as BotRecord) ?? null, patchBot: (id: string, patch: object) => Object.assign(bots.get(id)!, patch) as unknown as BotRecord,
+ get bots() { return [...bots.values()] as unknown as BotRecord[]; } },
+ 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: () => ({ list: () => hooks as never, update: (id: string, patch: unknown) => Object.assign(hooks.find((hook) => hook.id === id)!, patch as object) as never }),
+ appEvents: () => ({ list: () => events as never, update: async (id: string, patch: unknown) => Object.assign(events.find((event) => event.id === id)!, patch as object) as never }),
+ waits: () => null, busy: () => busy, now: () => clock, computer,
+ mcp: () => ({ all: ["notes", "shell", "docs"], command: ["notes", "shell"] }),
+ arrivals: arrivalsFile(dir),
+ stays: () => ({ logins: 2, secrets: 1, onePassword: true, connections: ["linear"] }),
+ };
+ const moves = createBotMoves(deps);
+ return { moves, bots, routines, hooks, events, removed, dir, tick: (ms: number) => { clock += ms; }, again: () => createBotMoves(deps) };
+ }
+ const scoutOf = (bots: Map<string, Record<string, unknown>>) => bots.get("scout") as Record<string, any>;
+ const live = (bot: Record<string, any>) => !bot.movedTo && bot.hidden !== true && botMoveRefusal(bot as never) === null;
+
+ it("holds the stub as returning: hidden, no turns, keeps what it had; stopped, it is the stub it was, nothing switched on", async () => {
+ const { moves, bots, routines } = place();
+ const held = await moves.hold("scout", MY_CLOUD, { back: true });
+ expect(held).toMatchObject({ movedTo: { team: MY_CLOUD, state: "moving", back: true, had: { mcp: ["notes"] }, held: ["routine:brief"] } });
+ expect(scoutOf(bots).hidden).toBe(true);
+ expect(() => assertBotHere(scoutOf(bots) as never)).toThrow("Scout is coming here from My Cloud. It's ready here in a moment.");
+ expect(await moves.hold("scout", MY_CLOUD), "no forward hold of a bot that is coming here").toEqual({ refused: "Scout is coming here from My Cloud. It's ready here in a moment." });
+ expect(await moves.release("scout")).toEqual({ released: true });
+ expect(scoutOf(bots)).toMatchObject({ hidden: true, movedTo: { team: MY_CLOUD, state: "moved", held: ["routine:brief"] } });
+ expect(scoutOf(bots).movedTo.back).toBeUndefined();
+ expect(routines.every((routine) => !routine.enabled), "the bot lives on My Cloud: nothing of it runs here").toBe(true);
+ });
+
+ it("refuses a live bot with the same id, and only takes a bot the move just made as its first arrival", async () => {
+ const here = place({ scout: "live", createdAt: 0 });
+ here.tick(60 * MINUTE);
+ expect(await here.moves.hold("scout", MY_CLOUD, { back: true })).toEqual({ refused: "Scout is already here.", here: true });
+ expect(await here.moves.hold("scout", MY_CLOUD, { back: true, arrival: true }), "an older bot is the person's own").toEqual({ refused: "Scout is already here.", here: true });
+ expect(live(scoutOf(here.bots))).toBe(true);
+ const fresh = place({ scout: "live", createdAt: 9 * MINUTE });
+ expect(await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true })).toMatchObject({ movedTo: { back: true, arrival: true, had: { mcp: [] } } });
+ expect(scoutOf(fresh.bots).hidden).toBe(true);
+ // Stopped, a first arrival is the line of where it lives, never deleted and never live here.
+ expect(await fresh.moves.release("scout")).toEqual({ released: true });
+ expect(scoutOf(fresh.bots)).toMatchObject({ hidden: true, movedTo: { team: MY_CLOUD, state: "moved" } });
+ expect((await fresh.moves.hold("scout", MY_CLOUD, { back: true }) as { movedTo: object }).movedTo, "the next try takes its line as returning").toMatchObject({ back: true });
+ expect(await place({ scout: "none" }).moves.hold("scout", MY_CLOUD, { back: true })).toEqual({ refused: "This bot is no longer here." });
+ expect(await place().moves.hold("scout", { id: "team-other", name: "Other" }, { back: true }), "a stub of another place").toEqual({ refused: "Scout lives in My Cloud now." });
+ });
+
+ it("arrives on this computer: live, routines that were on there on, webhooks, app events and new command MCP servers off, said once and the same when asked again", async () => {
+ const { moves, bots, routines, hooks, events, again } = place();
+ await moves.hold("scout", MY_CLOUD, { back: true });
+ // What the move sent while it came: the Cloud's newer tools, and its archived switch, which waits for the arrival.
+ Object.assign(scoutOf(bots), { mcpServers: ["notes", "shell", "docs"] });
+ scoutOf(bots).movedTo = { ...scoutOf(bots).movedTo, archived: false };
+ const on = ["routine:brief", "webhook:orders", "app-event:mail", "routine:elsewhere"];
+ const answer = await moves.arrived("scout", MY_CLOUD, on);
+ expect(answer).toEqual({ arrived: { v: 1, from: MY_CLOUD, hold: 10 * MINUTE, at: 10 * MINUTE, place: "computer",
+ on: { routines: [{ id: "brief", name: "Morning brief" }], webhooks: [], appEvents: [] },
+ offHere: { webhooks: [{ id: "orders", name: "Orders" }], appEvents: [{ id: "mail", name: "New mail" }], mcpServers: ["shell"] } } });
+ expect(live(scoutOf(bots))).toBe(true);
+ expect(scoutOf(bots).mcpServers, "the command server it did not use here stays off; the remote one stays on").toEqual(["notes", "docs"]);
+ expect([on.length, routines.map((routine) => routine.enabled), hooks[0]!.enabled, events[0]!.enabled]).toEqual([4, [true, false], false, false]);
+ expect(await moves.arrived("scout", MY_CLOUD, on), "asked again").toEqual(answer);
+ expect(await again().arrived("scout", MY_CLOUD, []), "after a restart, from what was kept").toEqual(answer);
+ expect(moves.state("scout")).toEqual({ movedTo: null, holding: false, arrived: (answer as { arrived: unknown }).arrived });
+ expect(await moves.arrived("pip", MY_CLOUD, []), "a bot that is not coming").toEqual({ refused: "This bot is not coming here." });
+ });
+
+ it("finishes an arrival a crash cut short, from what it kept first", async () => {
+ const { moves, bots, routines } = place();
+ await moves.hold("scout", MY_CLOUD, { back: true });
+ // The facts were kept and the routine switched on, then the server stopped before the bot was let go of.
+ const first = await moves.arrived("scout", MY_CLOUD, ["routine:brief"]);
+ scoutOf(bots).movedTo = { team: MY_CLOUD, state: "moving", at: 10 * MINUTE, back: true, had: { mcp: ["notes"] } };
+ scoutOf(bots).hidden = true;
+ routines[0]!.enabled = false;
+ expect(await moves.arrived("scout", MY_CLOUD, ["routine:weekly"]), "the same arrival, done the same way").toEqual(first);
+ expect([live(scoutOf(bots)), routines.map((routine) => routine.enabled)]).toEqual([true, [true, false]]);
+ });
+
+ it("an arriving bot with every MCP server on gets none new when it used every one here, and all command ones off when it is new here", async () => {
+ const stub = place();
+ delete scoutOf(stub.bots).mcpServers;
+ await stub.moves.hold("scout", MY_CLOUD, { back: true });
+ expect((await stub.moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual([]);
+ expect(scoutOf(stub.bots).mcpServers).toBeUndefined();
+ const fresh = place({ scout: "live", createdAt: 10 * MINUTE });
+ delete scoutOf(fresh.bots).mcpServers;
+ await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true });
+ expect((await fresh.moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual(["notes", "shell"]);
+ expect(scoutOf(fresh.bots).mcpServers).toEqual(["docs"]);
+ });
+
+ it("on My Cloud, a bot leaving for a computer keeps its routines there, off, and the answer says what stays; going there again switches on all that was on", async () => {
+ const cloud = place({ computer: false, scout: "live" });
+ cloud.routines[0]!.enabled = true;
+ cloud.hooks[0]!.enabled = true;
+ const held = await cloud.moves.hold("scout", LAPTOP, { lapse: true });
+ expect(held).toMatchObject({ movedTo: { team: LAPTOP, state: "moving", held: ["routine:brief", "webhook:orders"], lapseAt: 40 * MINUTE } });
+ expect(cloud.moves.moved("scout", LAPTOP)).toEqual({ movedTo: { team: LAPTOP, state: "moved", at: 10 * MINUTE, held: ["routine:brief", "webhook:orders"] },
+ stays: { logins: 2, secrets: 1, onePassword: true, connections: ["linear"] } });
+ expect([cloud.removed, cloud.routines.map((routine) => routine.enabled)], "kept, off").toEqual([[], [false, false]]);
+ expect(cloud.moves.back("scout"), "a computer's line comes back if the person wants it").toEqual({ released: true });
+
+ const again = place({ computer: false });
+ await again.moves.hold("scout", LAPTOP, { back: true });
+ const arrived = await again.moves.arrived("scout", LAPTOP, ["routine:brief", "webhook:orders", "app-event:mail"]);
+ expect(arrived).toMatchObject({ arrived: { place: "cloud", on: { routines: [{ id: "brief" }], webhooks: [{ id: "orders" }], appEvents: [{ id: "mail" }] }, offHere: { webhooks: [], appEvents: [], mcpServers: [] } } });
+ expect([again.routines[0]!.enabled, again.hooks[0]!.enabled, again.events[0]!.enabled, live(scoutOf(again.bots))]).toEqual([true, true, true, true]);
+ });
+
+ it("a lapsing hold not renewed lets the bot go on where it is, as it was; renewed, it holds; one that moved never lapses", async () => {
+ const cloud = place({ computer: false, scout: "live" });
+ cloud.routines[0]!.enabled = true;
+ await cloud.moves.hold("scout", LAPTOP, { lapse: true });
+ cloud.tick(29 * MINUTE);
+ expect(await cloud.moves.sweep()).toEqual([]);
+ expect((await cloud.moves.hold("scout", LAPTOP, { lapse: true }) as { movedTo: { lapseAt: number } }).movedTo.lapseAt, "renewed").toBe(69 * MINUTE);
+ cloud.tick(29 * MINUTE);
+ expect(await cloud.moves.sweep()).toEqual([]);
+ cloud.tick(2 * MINUTE);
+ expect(await cloud.moves.sweep()).toEqual(["scout"]);
+ expect([live(scoutOf(cloud.bots)), cloud.routines[0]!.enabled], "working on My Cloud again, its routine back on").toEqual([true, true]);
+ expect(cloud.moves.moved("scout", LAPTOP), "the switch after a lapse finds no hold").toEqual({ refused: "This bot is not moving to that team." });
+
+ const plain = place({ computer: false, scout: "live" });
+ await plain.moves.hold("scout", ACME);
+ plain.tick(10 * 60 * MINUTE);
+ expect(await plain.moves.sweep(), "a hold that did not ask to lapse holds").toEqual([]);
+
+ const moved = place({ computer: false, scout: "live" });
+ await moved.moves.hold("scout", LAPTOP, { lapse: true });
+ moved.moves.moved("scout", LAPTOP);
+ moved.tick(60 * MINUTE);
+ expect(await moved.moves.sweep()).toEqual([]);
+ expect(scoutOf(moved.bots).movedTo.state).toBe("moved");
+
+ const back = place();
+ await back.moves.hold("scout", MY_CLOUD, { back: true, lapse: true });
+ back.tick(31 * MINUTE);
+ expect(await back.moves.sweep()).toEqual(["scout"]);
+ expect(scoutOf(back.bots)).toMatchObject({ hidden: true, movedTo: { state: "moved" } });
+ });
+
+ it("remembers what the stub used here across a stopped try, so command servers new here still arrive off after an undo", async () => {
+ const { moves, bots } = place();
+ await moves.hold("scout", MY_CLOUD, { back: true });
+ scoutOf(bots).mcpServers = ["notes", "shell", "docs"];
+ await moves.release("scout");
+ expect((await moves.hold("scout", MY_CLOUD, { back: true }) as { movedTo: object }).movedTo).toMatchObject({ had: { mcp: ["notes"] } });
+ expect((await moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual(["shell"]);
+ const fresh = place({ scout: "live", createdAt: 10 * MINUTE });
+ await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true });
+ scoutOf(fresh.bots).mcpServers = ["shell"];
+ await fresh.moves.release("scout");
+ expect((await fresh.moves.hold("scout", MY_CLOUD, { back: true }) as { movedTo: object }).movedTo, "a first arrival had none here").toMatchObject({ had: { mcp: [] } });
+ });
+
+ it("a hold past its time no longer holds before the sweep has run: no switch, no arrival, and holding again is a new hold", async () => {
+ const cloud = place({ computer: false, scout: "live" });
+ cloud.routines[0]!.enabled = true;
+ const first = await cloud.moves.hold("scout", LAPTOP, { lapse: true }) as { movedTo: { at: number; lapseAt: number } };
+ expect(cloud.moves.nextLapseAt(), "a sleeping Cloud wakes for it").toBe(first.movedTo.lapseAt);
+ cloud.tick(31 * MINUTE);
+ expect(cloud.moves.state("scout")).toMatchObject({ holding: false });
+ expect(cloud.moves.moved("scout", LAPTOP)).toEqual({ refused: "This bot is not moving to that team." });
+ const again = await cloud.moves.hold("scout", LAPTOP, { lapse: true }) as { movedTo: { at: number } };
+ expect(again.movedTo.at, "a new hold, so the move copies again what the bot did meanwhile").toBe(41 * MINUTE);
+ expect(cloud.routines[0]!.enabled, "switched back on and off again by the new hold").toBe(false);
+ const here = place();
+ await here.moves.hold("scout", MY_CLOUD, { back: true, lapse: true });
+ here.tick(31 * MINUTE);
+ expect(await here.moves.arrived("scout", MY_CLOUD, [])).toEqual({ refused: "This bot is not coming here from there." });
+ expect(live(scoutOf(here.bots))).toBe(false);
+ expect(place().moves.nextLapseAt()).toBeNull();
+ });
+
+ it("waits for a turn going on My Cloud before it holds the bot there", async () => {
+ const cloud = place({ computer: false, scout: "live", busy: true });
+ expect(await cloud.moves.hold("scout", LAPTOP, { lapse: true })).toEqual({ busy: "Scout" });
+ expect(scoutOf(cloud.bots).movedTo).toBeUndefined();
+ });
+
+ it("a computer team is a place of the person's own; a team's own id never is", () => {
+ expect([personalTeam(MY_CLOUD_TEAM), personalTeam("computer-inst-1"), personalTeam("computer-"), personalTeam("0b6f8e52-9d6c-4f0e-8f43-2f0c3cf8c1d2")]).toEqual([true, true, false, false]);
+ });
+});
diff --git a/server/bot-moves.ts b/server/bot-moves.ts
index 9eae457e86..6b7934877d 100644
--- a/server/bot-moves.ts
+++ b/server/bot-moves.ts
@@ -1,11 +1,21 @@
// 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.
+// (electron/team-move.mjs runs the move), from this computer to My Cloud (electron/bot-move-main.mjs), or from My Cloud to
+// one of the person's computers. 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 a place of the person's
+// own (My Cloud, or one of their computers) keeps them here switched off, and comes back as it was if My Cloud ends.
+//
+// A bot coming back to a place it left is held there too ("returning"): its line stays hidden and takes no turns, but a
+// move compares it, so what it has here is brought up to date rather than made again beside it, and the newer side wins.
+// Stopped, it is the line it was. Arrived, it is live here again: routines that were on there are on, and on a computer a
+// webhook or app event stays off, as does an MCP server that runs a command here the bot did not use here before
+// (move-back.ts keeps what was done, to be told). A bot is never live in two places and nothing of it is deleted.
+//
+// A hold that asks to lapse (`lapse`) lets the bot go on by itself unless it is held again within HOLD_LAPSE_MS: the
+// computer that runs a move may sleep half-way, and the bot then goes on working where it is.
import type { BotMovedTo } from "../shared/wire.ts";
import type { AppTriggerManager } from "./app-triggers.ts";
+import type { Arrivals, ArrivedFacts, MovedAutomation, StaysOnCloud } from "./move-back.ts";
import type { RoutineManager } from "./routines.ts";
import type { BotRecord, GroupRecord } from "./store.ts";
import type { WaitManager } from "./waits.ts";
@@ -13,10 +23,19 @@ 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";
+/** The "team" a bot moving from My Cloud to one of the person's computers goes to: `computer-<installation>`, as several
+ * computers share one Cloud. A team's own id is the Admin's UUID, never this shape. */
+export const COMPUTER_TEAM_PREFIX = "computer-";
+/** A place of the person's own: My Cloud, or one of their computers. */
+export const personalTeam = (id: string) => id === MY_CLOUD_TEAM || (id.startsWith(COMPUTER_TEAM_PREFIX) && id.length > COMPUTER_TEAM_PREFIX.length);
+/** How long a hold that asked to lapse holds without being asked again. */
+export const HOLD_LAPSE_MS = 30 * 60_000;
+/** A first arrival is held as one only while it is this new: the move made it moments before. */
+export const ARRIVAL_WINDOW_MS = 10 * 60_000;
export interface BotMovesDeps {
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 };
+ bots?: readonly BotRecord[]; 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;
@@ -24,17 +43,44 @@ export interface BotMovesDeps {
/** A turn or a routine run of this bot is going. */
busy(botId: string): boolean;
now?: () => number;
+ /** This server is one of the person's computers, not My Cloud: what arrives here keeps webhooks, app events and new
+ * command MCP servers off. */
+ computer?: boolean;
+ /** The MCP servers this server mounts for the bot, and which run a command here (move-back.ts mcpServersHere). */
+ mcp?(botId: string): { all: string[]; command: string[] };
+ /** Where what each arrival did is kept (move-back.ts arrivalsFile). */
+ arrivals?: Arrivals;
+ /** What My Cloud keeps of the person's when this bot leaves it for a computer. */
+ stays?(botId: string): StaysOnCloud;
+ /** How often lapsing holds are looked at; none: only when sweep() is called. */
+ lapseCheckMs?: number;
+ log?(line: string): void;
}
type Team = BotMovedTo["team"];
-/** What the move switched off here, by key ("routine:<id>"), to switch back on if it stops. */
-type Held = BotMovedTo & { held?: string[] };
+/** What the move switched off here, by key ("routine:<id>"), to switch back on if it stops; the rest is the server's own
+ * and never read by a phone. */
+type Held = BotMovedTo & {
+ held?: string[];
+ /** A lapsing hold lets the bot go on by itself at this time unless it is held again first. */
+ lapseAt?: number;
+ /** The bot is coming back here: hidden, no turns, compared by the move. */
+ back?: true;
+ /** A first arrival this move made here: stopped, it is the line of where it lives. */
+ arrival?: true;
+ /** What this place had of it before it came back: the MCP servers it used here (null: every one). */
+ had?: { mcp: string[] | null };
+ /** The archived switch the move sent while it came back, set once it arrived. */
+ archived?: boolean;
+};
+type HoldAnswer = { movedTo: Held } | { busy: string } | { refused: string; here?: true };
/** Why this bot takes no turn here, or null. */
export function botMoveRefusal(bot: Pick<BotRecord, "name"> & { movedTo?: BotMovedTo; home?: BotRecord["home"] } | null | undefined): string | null {
if (bot?.home) return `${bot.name} lives on ${bot.home.placeName}: its turns run there, not here.`;
const moved = bot?.movedTo;
if (!moved) return null;
+ if ((moved as Held).back) return `${bot!.name} is coming here from ${moved.team.name}. It's ready here in a moment.`;
return moved.state === "moved" ? `${bot!.name} lives in ${moved.team.name} now.` : `${bot!.name} is moving to ${moved.team.name}. It's ready there in a moment.`;
}
@@ -57,11 +103,18 @@ export function createBotMoves(deps: BotMovesDeps) {
else if (kind === "webhook") deps.webhooks()?.update(id, { enabled: on });
else if (kind === "app-event") await deps.appEvents()?.update(id, { enabled: on });
}
+ /** Each kind's keeper is there to switch these back on: none is dropped unswitched while the server starts. */
+ const ready = (keys: readonly string[]) => keys.every((key) => (key.startsWith("routine:") ? deps.routines() : key.startsWith("webhook:") ? deps.webhooks()
+ : key.startsWith("app-event:") ? deps.appEvents() : true) !== null);
const movedOf = (bot: BotRecord | null | undefined): Held | undefined => (bot as (BotRecord & { movedTo?: Held }) | null | undefined)?.movedTo;
const cancelWaits = (botId: string) => {
const waits = deps.waits();
for (const wait of waits?.all() ?? []) if (wait.botId === botId) waits!.cancel(wait.id, botId);
};
+ const lapsing = (lapse: boolean) => (lapse ? { lapseAt: now() + HOLD_LAPSE_MS } : {});
+ /** A lapsing hold past its time no longer holds, whether or not the sweep has let the bot go yet. */
+ const lapsed = (held: Held | undefined) => held?.state === "moving" && held.lapseAt !== undefined && held.lapseAt <= now();
+ const set = (botId: string, movedTo: Held | undefined, more: Partial<BotRecord> = {}) => deps.store.patchBot(botId, { movedTo, ...more } as Partial<BotRecord>);
/** 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) => {
@@ -72,62 +125,178 @@ export function createBotMoves(deps: BotMovesDeps) {
}
};
- return {
+ /** The bot comes back here: its line is held as returning; a bot live here with this id is not taken over. */
+ function holdReturning(bot: BotRecord, held: Held | undefined, team: Team, lapse: boolean, arrival: boolean): HoldAnswer {
+ if (held?.back) {
+ if (held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
+ const { lapseAt: _lapse, ...kept } = held;
+ const next: Held = { ...kept, ...lapsing(lapse) };
+ set(bot.id, next);
+ return { movedTo: next };
+ }
+ if (held?.state === "moved") {
+ if (held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
+ const { lapseAt: _lapse, ...kept } = held;
+ const next: Held = { ...kept, state: "moving", at: now(), back: true, had: held.had ?? { mcp: bot.mcpServers ? [...bot.mcpServers] : null }, ...lapsing(lapse) };
+ set(bot.id, next, { hidden: true });
+ return { movedTo: next };
+ }
+ if (held) return { refused: botMoveRefusal(bot)! };
+ // Security: only a bot the move made here moments ago is taken as its arrival; any other bot with this id is the
+ // person's own, which the move never hides.
+ const fresh = arrival && Number.isFinite(bot.createdAt) && now() - bot.createdAt >= 0 && now() - bot.createdAt <= ARRIVAL_WINDOW_MS;
+ if (!fresh) return { refused: `${bot.name} is already here.`, here: true };
+ const next: Held = { team, state: "moving", at: now(), back: true, arrival: true, had: { mcp: [] }, ...lapsing(lapse) };
+ set(bot.id, next, { hidden: true });
+ cancelWaits(bot.id);
+ return { movedTo: next };
+ }
+
+ /** The automations of this bot, of one kind, by id and name. */
+ const named = (list: ReadonlyArray<{ id: string; name: string; botId: string }> | undefined, botId: string, keys: Set<string>, kind: string): MovedAutomation[] =>
+ (list ?? []).filter((entry) => entry.botId === botId && keys.has(`${kind}:${entry.id}`)).map((entry) => ({ id: entry.id, name: entry.name }));
+
+ /** What arriving does here, decided once and kept before any of it is done. */
+ function arrivalFacts(bot: BotRecord, held: Held, on: readonly string[]): ArrivedFacts {
+ const keys = new Set(on);
+ const routines = named(deps.routines()?.listRoutines(), bot.id, keys, "routine");
+ const webhooks = named(deps.webhooks()?.list(), bot.id, keys, "webhook");
+ const appEvents = named(deps.appEvents()?.list(), bot.id, keys, "app-event");
+ let mcpServers: string[] = [];
+ if (deps.computer && deps.mcp) {
+ const here = deps.mcp(bot.id);
+ const uses = (list: readonly string[] | null) => (list === null ? here.command : here.command.filter((name) => list.includes(name)));
+ const before = new Set(uses(held.had?.mcp ?? null));
+ mcpServers = uses(bot.mcpServers ?? null).filter((name) => !before.has(name));
+ }
+ const computer = deps.computer === true;
+ return { v: 1, from: held.team, hold: held.at, at: now(), place: computer ? "computer" : "cloud",
+ on: { routines, webhooks: computer ? [] : webhooks, appEvents: computer ? [] : appEvents },
+ offHere: { webhooks: computer ? webhooks : [], appEvents: computer ? appEvents : [], mcpServers } };
+ }
+
+ const moves = {
/** 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. */
- async hold(botId: string, team: Team): Promise<{ movedTo: Held } | { busy: string } | { refused: string }> {
+ * bot already moved stays moved. Holding it again keeps what the first hold switched off, and renews a lapsing hold.
+ * `back`: it is coming back here instead (holdReturning). */
+ async hold(botId: string, team: Team, { lapse = false, back = false, arrival = false }: { lapse?: boolean; back?: boolean; arrival?: boolean } = {}): Promise<HoldAnswer> {
const bot = deps.store.bot(botId);
if (!bot) return { refused: "This bot is no longer here." };
if (bot.defaultBot) return { refused: `${bot.name} stays here: everyone on a team gets their own.` };
- const held = movedOf(bot);
+ // Past its time, a hold is let go of first: holding again is a new hold, with a new `at`.
+ if (lapsed(movedOf(bot)) && ready(movedOf(bot)!.held ?? [])) await moves.release(botId);
+ const held = movedOf(deps.store.bot(botId) ?? bot);
+ if (back) return holdReturning(deps.store.bot(botId) ?? bot, held, team, lapse, arrival);
+ if (held?.back) return { refused: botMoveRefusal(bot)! };
if (held?.state === "moved") return held.team.id === team.id ? { movedTo: held } : { refused: botMoveRefusal(bot)! };
if (held && held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
if (!held && deps.busy(botId)) return { busy: bot.name };
const off = held?.held ?? [];
- const next: Held = { team, state: "moving", at: held?.at ?? now(), held: off };
- deps.store.patchBot(botId, { movedTo: next } as Partial<BotRecord>);
+ const next: Held = { team, state: "moving", at: held?.at ?? now(), held: off, ...lapsing(lapse) };
+ set(botId, next);
for (const automation of automations(botId)) {
if (!automation.on) continue;
// Kept before it is switched off, so a stop half-way still switches it back on.
if (!off.includes(automation.key)) off.push(automation.key);
- deps.store.patchBot(botId, { movedTo: { ...next, held: [...off] } } as Partial<BotRecord>);
+ set(botId, { ...next, held: [...off] });
await switchTo(automation.key, false);
}
cancelWaits(botId);
return { movedTo: movedOf(deps.store.bot(botId))! };
},
- /** The move stopped before the bot arrived: it is here again as it was, its automations back on. */
+ /** The move stopped before the bot arrived: it is here again as it was, its automations back on. A bot that was coming
+ * back is the line of where it lives again, nothing of it switched on: it is live there. */
async release(botId: string): Promise<{ released: true } | { refused: string }> {
const bot = deps.store.bot(botId);
const held = movedOf(bot);
if (!bot || !held) return { released: true };
if (held.state === "moved") return { refused: botMoveRefusal(bot)! };
+ if (held.back) {
+ // What it had here before stays known, so a later try still tells what is new here.
+ const { back: _back, arrival: _arrival, archived: _archived, lapseAt: _lapse, ...kept } = held;
+ set(botId, { ...kept, state: "moved" }, { hidden: true });
+ return { released: true };
+ }
for (const key of held.held ?? []) await switchTo(key, true);
- deps.store.patchBot(botId, { movedTo: undefined } as Partial<BotRecord>);
+ set(botId, undefined);
return { released: true };
},
- /** The bot lives in the team now: archived here as the line that opens it there, its routines and waits gone from here. */
- moved(botId: string, team: Team): { movedTo: Held } | { refused: string } {
+ /** The bot lives in the team now: archived here as the line that opens it there, its routines and waits gone from here.
+ * One that went to a place of the person's own keeps its routines here, off; leaving My Cloud for a computer, the
+ * answer says what My Cloud keeps of the person's. */
+ moved(botId: string, team: Team): { movedTo: Held; stays?: StaysOnCloud } | { refused: string } {
const bot = deps.store.bot(botId);
const held = movedOf(bot);
- if (!bot || !held || held.team.id !== team.id) return { refused: "This bot is not moving to that team." };
+ if (!bot || !held || held.back || held.team.id !== team.id || lapsed(held)) return { refused: "This bot is not moving to that team." };
if (held.state !== "moved") {
- if (team.id === MY_CLOUD_TEAM) leaveRooms(botId); else deps.routines()?.removeForBot(botId);
+ if (personalTeam(team.id)) leaveRooms(botId); else deps.routines()?.removeForBot(botId);
cancelWaits(botId);
- deps.store.patchBot(botId, { movedTo: { ...held, state: "moved", at: now() }, hidden: true } as Partial<BotRecord>);
+ const { lapseAt: _lapse, ...kept } = held;
+ set(botId, { ...kept, state: "moved", at: now() }, { hidden: true });
}
- return { movedTo: movedOf(deps.store.bot(botId))! };
+ const stays = team.id.startsWith(COMPUTER_TEAM_PREFIX) ? deps.stays?.(botId) : undefined;
+ return { movedTo: movedOf(deps.store.bot(botId))!, ...(stays ? { stays } : {}) };
+ },
+ /** The bot that was coming back is here: live again, as the move made it. `on`: what was on where it came from (the
+ * hold's `held` there). Asked again, the same answer. */
+ async arrived(botId: string, team: Team, on: readonly string[]): Promise<{ arrived: ArrivedFacts } | { refused: string }> {
+ const bot = deps.store.bot(botId);
+ if (!bot) return { refused: "This bot is no longer here." };
+ const held = movedOf(bot);
+ const kept = deps.arrivals?.get(botId) ?? null;
+ if (!held) return kept && kept.from.id === team.id ? { arrived: kept } : { refused: "This bot is not coming here." };
+ if (!held.back || held.team.id !== team.id || lapsed(held)) return { refused: "This bot is not coming here from there." };
+ // Kept before anything is done: a server stopped half-way does the rest, the same way, when asked again.
+ const facts = kept && kept.from.id === team.id && kept.hold === held.at ? kept : arrivalFacts(bot, held, on);
+ if (facts !== kept) deps.arrivals?.put(botId, facts);
+ if (facts.offHere.mcpServers.length) {
+ const off = new Set(facts.offHere.mcpServers);
+ deps.store.patchBot(botId, { mcpServers: (bot.mcpServers ?? deps.mcp?.(botId).all ?? []).filter((name) => !off.has(name)) });
+ }
+ for (const routine of facts.on.routines) await switchTo(`routine:${routine.id}`, true);
+ for (const hook of facts.on.webhooks) await switchTo(`webhook:${hook.id}`, true);
+ for (const trigger of facts.on.appEvents) await switchTo(`app-event:${trigger.id}`, true);
+ set(botId, undefined, { hidden: held.archived ?? false });
+ return { arrived: facts };
},
/** 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>);
+ if (!personalTeam(held.team.id)) return { refused: botMoveRefusal(bot)! };
+ set(botId, undefined, { hidden: false });
return { released: true };
},
+ /** The bot's hold, or its line, as this server keeps it (`holding`: a hold or line that still holds), and what its last
+ * arrival here did. */
+ state(botId: string): { movedTo: Held | null; holding: boolean; arrived: ArrivedFacts | null } | null {
+ const bot = deps.store.bot(botId);
+ const held = movedOf(bot);
+ return bot ? { movedTo: held ?? null, holding: Boolean(held) && !lapsed(held), arrived: deps.arrivals?.get(botId) ?? null } : null;
+ },
+ /** When the first lapsing hold here runs out, so a sleeping Cloud wakes to let its bot go on; null when none. */
+ nextLapseAt(): number | null {
+ const times = (deps.store.bots ?? []).map((bot) => movedOf(bot)).filter((held) => held?.state === "moving" && held.lapseAt !== undefined).map((held) => held!.lapseAt!);
+ return times.length ? Math.min(...times) : null;
+ },
+ /** Lapsing holds not renewed in time let their bots go on, as a stopped move does. The ids let go of. */
+ async sweep(): Promise<string[]> {
+ const gone: string[] = [];
+ for (const bot of deps.store.bots ?? []) {
+ const held = movedOf(bot);
+ if (!lapsed(held) || !ready(held!.held ?? [])) continue;
+ await moves.release(bot.id);
+ deps.log?.(`bot move: ${bot.name} was held for a move that did not go on, and goes on here`);
+ gone.push(bot.id);
+ }
+ return gone;
+ },
+ close() { if (timer) clearInterval(timer); },
};
+ const timer = deps.lapseCheckMs ? setInterval(() => { void moves.sweep().catch((error) => deps.log?.(`bot move: ${(error as Error)?.message ?? error}`)); }, deps.lapseCheckMs) : null;
+ timer?.unref?.();
+ return moves;
}
export type BotMoves = ReturnType<typeof createBotMoves>;
diff --git a/server/cloud-owner-lines.ts b/server/cloud-owner-lines.ts
index 11f1d33c0c..2dbf5adc66 100644
--- a/server/cloud-owner-lines.ts
+++ b/server/cloud-owner-lines.ts
@@ -7,8 +7,9 @@ import { answeredByPerson } from "./cloud-lending.ts";
import { routinePrompt } from "./routine-execution.ts";
import { WEBHOOK_EVENT_DATA } from "./webhooks.ts";
-/** My Cloud's owner as the owner's own session is: their person key, and the name their lines read as. */
-export interface CloudOwner { person: string; name: string }
+/** My Cloud's owner as the owner's own session is: their person key, and the name their lines read as. `here`: the person on
+ * their own computer, whose app moves a bot into it (move-back.ts): nothing is stamped with it. */
+export interface CloudOwner { person: string; name: string; here?: true }
/** Security invariant: only a user line nobody else's words or no automation made. A peer's ask or aside, a line a
* script or an outside interface relayed, and a routine's, webhook's or app event's own prompt are never the owner's,
diff --git a/server/cloud-send-chats.ts b/server/cloud-send-chats.ts
index 1146395968..dd997b3ec8 100644
--- a/server/cloud-send-chats.ts
+++ b/server/cloud-send-chats.ts
@@ -244,6 +244,9 @@ export interface CloudSendChatsDeps {
ownerKey?: string;
}
+/** Whose rows arriving lines become: none on the person's own computer, where their lines name nobody. */
+const stamping = (owner: CloudOwner | null): CloudOwner | null => (owner?.here ? null : owner);
+
const ownerOf = (store: Pick<ChatStore, "bots" | "groups">, threadId: string) => {
const bot = store.bots.find((candidate) => candidate.threadId === threadId || (candidate.tasks ?? []).some((task) => task.threadId === threadId));
return { bot, room: bot ? undefined : store.groups.find((candidate) => roomThreads(candidate).includes(threadId)) };
@@ -392,6 +395,8 @@ export async function cloudSendChatsRoute(deps: CloudSendChatsDeps, { req, res,
if (!owner) { json(res, 403, { error: "Only My Cloud's owner can say which of its lines are theirs." }); return true; }
const parsed = idsSchema.safeParse(await readBody(req, 2 * 1024 * 1024));
if (!parsed.success) { json(res, 400, { error: `send { v: 1, conversations: [{ threadId, ids }] }, at most ${VERIFY_IDS} ids of each` }); return true; }
+ // On the person's own computer their lines name nobody: nothing is stamped.
+ if (owner.here) { json(res, 200, { v: 1, stamped: 0 }); return true; }
const { stamped, threads } = stampHeld(store, parsed.data.conversations, owner);
for (const threadId of threads) deps.stamped?.(threadId);
json(res, 200, { v: 1, stamped });
@@ -454,7 +459,7 @@ export async function cloudSendChatsRoute(deps: CloudSendChatsDeps, { req, res,
}
for (const room of store.groups) if (room.busyBotId) for (const threadId of [room.threadId, ...(room.tasks ?? []).map((task) => task.threadId)]) busy.add(threadId);
const result = addSentChats(store, deps.dataDir, parsed.data.dataDir, parsed.data.conversations as unknown as SentConversation[],
- { busy: (threadId) => busy.has(threadId), owner: deps.owner?.(auth) ?? null });
+ { busy: (threadId) => busy.has(threadId), owner: stamping(deps.owner?.(auth) ?? null) });
json(res, 200, result);
return true;
}
diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.ts
index 6b009e7e7d..351d078a16 100644
--- a/server/cloud-send-files.ts
+++ b/server/cloud-send-files.ts
@@ -31,7 +31,8 @@ export interface BotFile { path: string; size: number; sha256: string }
export interface MoveFilesDeps {
dataDir: string;
- bots(): ReadonlyArray<{ id: string }>;
+ /** `movedTo.back`: the bot is coming back here (bot-moves.ts), and what it kept here gives way to what arrives. */
+ bots(): ReadonlyArray<{ id: string; movedTo?: { at: number } }>;
owner(auth: RequestAuth): CloudOwner | null;
}
@@ -155,13 +156,26 @@ async function readPart(dataDir: string, { path, offset, length }: z.infer<typeo
} finally { await handle.close(); }
}
+/** Where a bot coming back keeps the files it had here that a newer one took the place of. */
+export const SET_ASIDE_DIR = "move-back-kept";
+
+/** The file at `path` moved to `<dataDir>/move-back-kept/<hold>/<path>`; false when that could not be done. */
+async function setAside(dataDir: string, path: string, hold: string): Promise<boolean> {
+ const aside = `${SET_ASIDE_DIR}/${hold}/${path}`;
+ if (!(await realFolders(dataDir, aside))) return false;
+ if (await lstat(join(dataDir, aside)).catch(() => null)) return false;
+ try { await rename(join(dataDir, path), join(dataDir, aside)); return true; } catch { return false; }
+}
+
/** One part of a file: 200 `{ received }` until the last, then 201 `{ stored }`, or 409 `{ conflict }` when the path holds a
* file the move may not replace; 409 `{ received }` when the part does not start where My Cloud's copy ends. */
async function takePart(deps: MoveFilesDeps, req: IncomingMessage, query: z.infer<typeof putSchema>): Promise<{ status: number; body: Record<string, unknown> }> {
const { path, size, sha256, offset, mode, expect } = query;
const botId = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path)?.[1];
if (!movedFilePath(path) || !botId) return { status: 400, body: { error: "not a bot file a move carries" } };
- if (!deps.bots().some((bot) => bot.id === botId)) return { status: 409, body: { error: "This file's bot is not on My Cloud yet." } };
+ const bot = deps.bots().find((candidate) => candidate.id === botId);
+ if (!bot) return { status: 409, body: { error: "This file's bot is not on My Cloud yet." } };
+ const returning = (bot.movedTo as { back?: true; at: number } | undefined)?.back === true ? bot.movedTo!.at : null;
const partial = partialPath(deps.dataDir, sha256, size);
await mkdir(staging(deps.dataDir), { recursive: true, mode: 0o700 });
const held = (await stat(partial).catch(() => null))?.size ?? 0;
@@ -180,6 +194,13 @@ async function takePart(deps: MoveFilesDeps, req: IncomingMessage, query: z.infe
const there = await lstat(target).catch(() => null);
if (there && !there.isFile()) return { status: 409, body: { conflict: true } };
if (there && await sha256Of(target) === sha256) { await unlink(partial).catch(() => {}); return { status: 201, body: { stored: false } }; }
+ // The bot is coming back: the file it kept here is older than the one that arrives, which takes its place; the kept one
+ // is set aside under the data folder, never deleted.
+ if (there && returning !== null && await setAside(deps.dataDir, path, `${botId}-${returning}`)) {
+ await link(partial, target);
+ await unlink(partial).catch(() => {});
+ return { status: 201, body: { stored: true, setAside: true } };
+ }
if (mode === "replace" && there && expect && await sha256Of(target) === expect) {
const placed = join(staging(deps.dataDir), `${randomUUID()}.placing`);
await link(partial, placed);
diff --git a/server/cloud-send-kinds.ts b/server/cloud-send-kinds.ts
index ab1fa28f7d..9ffcca0acc 100644
--- a/server/cloud-send-kinds.ts
+++ b/server/cloud-send-kinds.ts
@@ -292,6 +292,15 @@ function applyBotFields(deps: MoveKindsDeps, id: string, raw: unknown, source: A
}
if (Object.hasOwn(fields, "chiefOfStaff") && fields.chiefOfStaff !== true) patch.chiefOfStaff = fields.chiefOfStaff ?? undefined;
if (fields.chiefOfStaff === true) delete patch.hidden;
+ // A bot coming back here (bot-moves.ts) stays hidden until it arrived: its archived switch waits on its hold till then.
+ // It never takes this place's Chief's crown or MausBot mark: those stay where they are (a Chief does not move back).
+ const coming = (bot.movedTo as { back?: true } | undefined)?.back === true;
+ if (coming) {
+ if (Object.hasOwn(patch, "hidden")) (patch as Record<string, unknown>).movedTo = { ...bot.movedTo, archived: patch.hidden === true };
+ for (const key of ["hidden", "chiefOfStaff", "managedSections"] as const) delete patch[key];
+ deps.store.patchBot(id, patch);
+ return;
+ }
deps.store.patchBot(id, patch);
// A MausBot arriving where the person's own MausBot stays (takeArrivingDefaultBot) doesn't take the crown from this
// place's Chief, whichever bot that is, also when a later pass sends its Chief fields without its MausBot mark.
@@ -327,7 +336,7 @@ function adoptRoutine(deps: MoveKindsDeps, raw: unknown, runs: unknown, from: st
held.runs.push(...arriving.filter((run) => !have.has(run.id)));
return [adopted];
});
- if (adopted) deps.ownRoutine?.(adopted, owner.person);
+ if (adopted && !owner.here) deps.ownRoutine?.(adopted, owner.person);
deps.arrived?.();
}
diff --git a/server/cloud-send.test.ts b/server/cloud-send.test.ts
index 38849443c3..c975279e77 100644
--- a/server/cloud-send.test.ts
+++ b/server/cloud-send.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { BOT_PARTS, EMPTY, PICTURE_PART, itemKey } from "../electron/cloud-send-parts.mjs";
+import { BOT_PARTS, EMPTY, PICTURE_PART, itemKey, parseSendSummary, planSend } from "../electron/cloud-send-parts.mjs";
import { botParts, cloudSendSummary, partHash, unused, type CloudSendSources } from "./cloud-send.ts";
import { keptBotIds } from "./routes/bots-create.ts";
import type { BotRecord } from "./store.ts";
@@ -110,3 +110,29 @@ describe("a bot sent from the person's other computer keeps its id", () => {
expect(keptBotIds({ id: "ember-0002-4eea-ac52" }, here)).toEqual({ id: "ember-0002-4eea-ac52" });
});
});
+
+describe("a bot coming back to the place it left", () => {
+ const stub = (movedTo: object) => bot({ hidden: true, title: "Old title", movedTo } as Partial<BotRecord>);
+ const routine = { key: "routine:r1", kind: "routine" as const, label: "Daily", id: "r1", bot: "ember-0001", parts: { def: "aaa" } };
+ const move = { items: () => [routine], botParts: () => ({ archived: "x" }) };
+
+ it("is listed where it comes to while it is held as returning, marked with its skills and routines; as a stub it is not", () => {
+ const leaving = (movedTo: object) => cloudSendSummary(sources({ bots: () => [stub(movedTo)], move }), { move: true, leaving: true });
+ expect(leaving({ team: { id: "my-cloud", name: "My Cloud" }, state: "moved", at: 1 }).items.filter((item) => item.kind === "bot")).toEqual([]);
+ const coming = leaving({ team: { id: "my-cloud", name: "My Cloud" }, state: "moving", at: 1, back: true });
+ expect(coming.items.filter((item) => item.bot === "ember-0001" || item.key === itemKey.bot("ember-0001")).map((item) => [item.key, item.returning])).toEqual([
+ [itemKey.bot("ember-0001"), true], [itemKey.skill("ember-0001", "weekly-summary"), true], ["routine:r1", true]]);
+ expect(cloudSendSummary(sources({ move }), { move: true }).items.some((item) => item.returning), "a bot that is not coming back is not marked").toBe(false);
+ });
+
+ it("takes what the place it comes from has, over what its line kept, even where an earlier send left both agreeing", () => {
+ const there = { v: 1 as const, appVersion: "x", items: [{ key: itemKey.bot("ember-0001"), kind: "bot", label: "Ember", parts: { title: "new", soul: "same", archived: EMPTY } }, { ...routine, parts: { def: "bbb" } }] };
+ const here = parseSendSummary({ v: 1, appVersion: "x", items: [{ key: itemKey.bot("ember-0001"), kind: "bot", label: "Ember", parts: { title: "old", soul: "same", archived: "hid" }, returning: true },
+ { ...routine, returning: true }] });
+ const sent = { [itemKey.bot("ember-0001")]: { title: ["new", "old"] as [string, string] } };
+ const plan = planSend({ local: there as never, cloud: here, sent });
+ expect(plan.rows.map((row) => [row.key, row.state, row.parts])).toEqual([[itemKey.bot("ember-0001"), "to-update", ["title", "archived"]], ["routine:r1", "to-update", ["def"]]]);
+ const plain = planSend({ local: there as never, cloud: parseSendSummary({ ...here, items: here!.items.map(({ returning: _returning, ...item }) => item) }), sent });
+ expect(plain.rows[0]!.state, "without the mark, the line's own values are kept").toBe("differs");
+ });
+});
diff --git a/server/cloud-send.ts b/server/cloud-send.ts
index fda0b0ca50..b19fec6a3d 100644
--- a/server/cloud-send.ts
+++ b/server/cloud-send.ts
@@ -18,6 +18,9 @@ export interface CloudSendItem {
id?: string;
bot?: string;
parts: Record<string, string>;
+ /** Of a bot coming back here (server/bot-moves.ts "returning"), or one of its own: a move sends what the other side
+ * has of it, which is newer than what this line kept. */
+ returning?: true;
}
export interface CloudSendSummary { v: 1; appVersion: string; items: CloudSendItem[] }
@@ -98,26 +101,30 @@ 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. `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. */
+ * bots move away from, so one that lives elsewhere now is not carried again. A bot coming back here is listed, marked
+ * `returning`, with its skills and automations. */
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>();
+ const carried = new Set<string>(), returning = new Set<string>();
+ const marked = (list: CloudSendItem[]) => list.map((item) => (item.bot && returning.has(item.bot) ? { ...item, returning: true as const } : item));
for (const bot of sources.bots()) {
if ((only !== undefined && bot.id !== only) || (chosen && !chosen.has(bot.id)) || (leaving && bot.movedTo?.state === "moved")) continue;
+ const back = (bot.movedTo as { back?: true } | undefined)?.back === true;
const skills = sources.skills(bot);
- if (only === undefined && unused(bot, skills.length, sources.greetingOnly, sources.inRoom, move ? sources.automated : undefined)) continue;
+ if (only === undefined && !back && unused(bot, skills.length, sources.greetingOnly, sources.inRoom, move ? sources.automated : undefined)) continue;
carried.add(bot.id);
+ if (back) returning.add(bot.id);
const parts: Record<string, string> = { ...botParts(bot, sources.picture), ...(move && sources.move ? sources.move.botParts(bot) : {}) };
if (only !== undefined) for (const part of TEAM_HELD_PARTS) delete parts[part];
- items.push({ key: itemKey.bot(bot.id), kind: "bot", label: bot.name, id: bot.id, parts });
+ items.push({ key: itemKey.bot(bot.id), kind: "bot", label: bot.name, id: bot.id, parts, ...(back ? { returning: true as const } : {}) });
for (const skill of skills) {
items.push({ key: itemKey.skill(bot.id, skill.name), kind: "skill", label: skill.name, id: skill.name, bot: bot.id,
- parts: { text: skill.sha256.slice(0, 24) || EMPTY, on: skill.enabled ? "on" : "off" } });
+ parts: { text: skill.sha256.slice(0, 24) || EMPTY, on: skill.enabled ? "on" : "off" }, ...(back ? { returning: true as const } : {}) });
}
}
if (only !== undefined) {
const bot = sources.bots().find((candidate) => candidate.id === only);
- if (move && sources.move && bot) items.push(...sources.move.items(carried, bot));
+ if (move && sources.move && bot) items.push(...marked(sources.move.items(carried, bot)));
return { v: 1, appVersion: sources.appVersion, items };
}
for (const login of sources.logins()) {
@@ -138,6 +145,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).filter((item) => !chosen || item.kind !== "call"));
+ if (move && sources.move) items.push(...marked(sources.move.items(carried).filter((item) => !chosen || item.kind !== "call")));
return { v: 1, appVersion: sources.appVersion, items };
}
diff --git a/server/environment.test.ts b/server/environment.test.ts
index b74ce741b3..e09c3abc91 100644
--- a/server/environment.test.ts
+++ b/server/environment.test.ts
@@ -123,7 +123,7 @@ describe("environment identity", () => {
label: "cab mini",
platform: process.platform,
version: "0.1.99",
- capabilities: { remoteSessions: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true },
+ capabilities: { remoteSessions: true, moveBack: 1, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true },
});
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false }).capabilities.selfUpdate).toBe("operator");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true }).capabilities, "the desktop updates its own server").not.toHaveProperty("install");
@@ -138,16 +138,19 @@ describe("environment identity", () => {
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: false }).capabilities)
.not.toHaveProperty("sharedComputers");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities)
- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, mcpCaller: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, mcpCaller: true, moveBack: 1, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true }).capabilities)
- .toEqual({ remoteSessions: true, cloudHome: true, move: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, cloudHome: true, move: 1, moveBack: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: false }).capabilities).not.toHaveProperty("cloudHome");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true }).capabilities, "only a Cloud home, or a server one person owns, takes a move").not.toHaveProperty("move");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, ownHome: true }).capabilities).toEqual({ remoteSessions: true, move: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });
+ // A bot moves back only to or from a person's own Cloud or their desktop's own server; a team's Cloud and a server one
+ // person runs by hand never offer it.
+ expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true, cloudTeam: true }).capabilities).not.toHaveProperty("moveBack");
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, ownHome: false }).capabilities).not.toHaveProperty("move");
// A lent computer may lend its internet connection only to a Cloud home that lends at all.
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true, sharedComputers: true }).capabilities)
- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, lentMcp: true, mcpCaller: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, lentMcp: true, mcpCaller: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, moveBack: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities).not.toHaveProperty("deviceLink");
});
diff --git a/server/environment.ts b/server/environment.ts
index eb5a31ac1f..48f3c7b184 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -142,6 +142,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan
...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const, computerAsks: true as const } : {}),
...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),
...(input.ownHome === true && input.cloudHome !== true ? { move: 1 as const } : {}),
+ ...((input.cloudHome === true && input.cloudTeam !== true) || input.desktopManaged ? { moveBack: 1 as const } : {}),
...(input.cloudHome === true && input.cloudTeam === true ? { cloudTeam: true as const } : {}),
selfUpdate: input.desktopManaged ? "desktop-managed" : "operator",
...(input.desktopManaged ? {} : { install: serverInstall() }),
diff --git a/server/index.ts b/server/index.ts
index c0cc5e72dd..c60e02c974 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -572,7 +572,7 @@ import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret
// Keep these two last, so loading the route table leaves module start-up order as is.
import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";
import { holdBodyDeadline } from "./body-deadline.ts";
-import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { followRoomMentions } from "./host/bot-link-rooms.ts"; import { standInAmong, standInWriteRefusal } from "./host/stand-in-guard.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage, pagesAccess, pagesNotOffered } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
+import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { followRoomMentions } from "./host/bot-link-rooms.ts"; import { standInAmong, standInWriteRefusal } from "./host/stand-in-guard.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage, pagesAccess, pagesNotOffered } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { arrivalsFile, desktopMainMover, mcpServersHere, staysOnCloud, thisComputerOwner } from "./move-back.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";
import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";
import { createBotMemoryRoutes } from "./routes/bot-memory.ts"; import { createBotLibraryRoutes } from "./routes/bot-library.ts";
@@ -12037,7 +12037,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 || 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: personLanguages.forPlace, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, changes: { bots: () => store.bots, instances: () => cfg.instances ?? {}, mcpServers: () => cfg.mcpServers, skills: (bot) => listSkills(bot.id).map((skill) => ({ name: skill.name, enabled: skill.enabled, text: readSkillFile(bot.id, skill.name) })) }, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);
+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : desktopMainMover(auth, { desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) ? thisComputerOwner(cfg.profile?.name) : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)), computer: !CLOUD_HOME, mcp: (id) => mcpServersHere(cfg, id), arrivals: arrivalsFile(DATA_DIR), stays: (id) => staysOnCloud(store.bot(id), { logins: logins.changes().length, secrets: logins.listSecrets(TEAM_READER).length, onePassword: logins.onePasswordConnectedAt() !== null, mcpServers: Object.keys(cfg.mcpServers ?? {}) }), lapseCheckMs: 15_000, log: (line) => console.error(line) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: personLanguages.forPlace, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, changes: { bots: () => store.bots, instances: () => cfg.instances ?? {}, mcpServers: () => cfg.mcpServers, skills: (bot) => listSkills(bot.id).map((skill) => ({ name: skill.name, enabled: skill.enabled, text: readSkillFile(bot.id, skill.name) })) }, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (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), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
@@ -15117,7 +15117,7 @@ restoreChannelMessages();
if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), bootedFromSleep: startedFromSleep, onBootWakeRequest: (at) => cloudHealth?.speed.wakeRequest(at), onWoke: createWokeNotifier({ adminOrigin: CLOUD_HOME.adminOrigin, machineId: CLOUD_HOME.machineId, secret: CLOUD_HOME.bootstrapSecret, log: (line) => console.warn(line) }), probes: {
turn: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking), run: () => Boolean(routines?.hasActiveRuns()), handoff: () => coordinator.pace() === "busy",
- liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt(), checkBacks.nextDueAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },
+ liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt(), checkBacks.nextDueAt(), botMoves?.nextLapseAt() ?? null].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },
maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));
botLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });
diff --git a/server/move-back.e2e.test.ts b/server/move-back.e2e.test.ts
new file mode 100644
index 0000000000..3b9465134a
--- /dev/null
+++ b/server/move-back.e2e.test.ts
@@ -0,0 +1,201 @@
+// A bot moving back from My Cloud to this computer, server side, end to end: this computer's server and a Cloud home, with
+// the test standing in for the app's main process (which a later change drives the move from), doing each step it will:
+// hold the bot's line here as returning, hold the bot on My Cloud with a lapsing hold, carry its fields, a routine, a
+// webhook and a file into this computer over the app's own capability, then switch: My Cloud keeps its line, this computer
+// makes it live. Each place is killed at the move's crash points. Then the bot goes to My Cloud again. Disposable homes; no
+// network.
+import { createHash, randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } 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 { parseSendSummary, planSend } from "../electron/cloud-send-parts.mjs";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+let fx: CloudSendFixture;
+beforeAll(async () => { fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-back-${randomBytes(8).toString("hex")}`, env: { OMB_ENVIRONMENT_LABEL: "MacBook Air" } }); }, hostTimeout(90_000));
+afterAll(async () => { await fx?.close(); });
+
+const MY_CLOUD = { id: "my-cloud", name: "My Cloud" };
+const LAPTOP = { id: "computer-inst-macbook", name: "MacBook Air" };
+type Side = CloudSendFixture["local"];
+type Bot = { id: string; name: string; title?: string; threadId: string; hidden?: boolean; movedTo?: { state: string; team: { id: string }; back?: boolean; archived?: boolean; lapseAt?: number } };
+const botOn = async (side: Side, id: string) => ((await side("GET", "/api/bots")).body.bots as Bot[]).find((bot) => bot.id === id);
+const live = (bot: Bot | undefined) => Boolean(bot && !bot.movedTo && !bot.hidden);
+/** The bot is live in exactly one of the two places, and that place is `where`. */
+async function liveOnlyOn(id: string, where: "computer" | "cloud") {
+ const [here, there] = [await botOn(fx.local, id), await botOn(fx.onCloud, id)];
+ expect([live(here), live(there)], JSON.stringify({ here: here?.movedTo, there: there?.movedTo })).toEqual(where === "computer" ? [true, false] : [false, true]);
+}
+const routinesOn = async (side: Side) => (await side("GET", "/api/routines")).body.routines as Array<{ id: string; botId: string; enabled: boolean }>;
+const hooksOn = async (side: Side) => (await side("GET", "/api/webhooks")).body.webhooks as Array<{ id: string; botId: string; enabled: boolean }>;
+const move = (side: Side, id: string, body: Record<string, unknown>) => side("POST", `/api/bot-moves/${id}`, { v: 1, ...body });
+/** One item, read from My Cloud and written here, as the move carries it. */
+async function carry(key: string) {
+ const held = await fx.onCloud("GET", `/api/cloud-send/kind?key=${encodeURIComponent(key)}`);
+ expect(held.status, JSON.stringify(held.body)).toBe(200);
+ return fx.local("PUT", "/api/cloud-send/kind", { v: 1, key, dataDir: held.body.dataDir, record: held.body.record, ...(held.body.runs ? { runs: held.body.runs } : {}) });
+}
+/** A bot file sent into this computer's server as main sends it: the app's capability, no page. */
+async function sendFile(path: string, text: string, headers: Record<string, string> = { "x-openmausbot-desktop-owner": fx.ownerCapability }) {
+ const bytes = Buffer.from(text);
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
+ const query = new URLSearchParams({ path, size: String(bytes.length), sha256, offset: "0", mode: "new" });
+ const response = await fetch(`${fx.desktopBase}/api/cloud-send/files?${query}`, { method: "POST", headers: { ...headers, "content-type": "application/octet-stream" }, body: bytes });
+ return { status: response.status, body: await response.json().catch(() => null) };
+}
+const moves = () => { const file = join(dirname(fx.journalFile), "bot-moves.json"); return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) as { moves: Array<{ phase: string }> } : { moves: [] }; };
+
+let rover: Bot;
+
+it("this computer's server takes a move's writes only from the app's own main process, and both places say they move bots back", async () => {
+ for (const side of [fx.local, fx.onCloud]) expect((await side("GET", "/.well-known/openmausbot/environment")).body.capabilities.moveBack).toBe(1);
+ const write = { v: 1, key: "routine:nothing-here", dataDir: "/x", record: {} };
+ const page = { "x-openmausbot-desktop-owner": fx.ownerCapability, origin: fx.desktopBase, "sec-fetch-site": "same-origin", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors" };
+ const put = async (headers: Record<string, string>) => {
+ const response = await fetch(`${fx.desktopBase}/api/cloud-send/kind`, { method: "PUT", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify(write) });
+ return { status: response.status, body: await response.json().catch(() => null) };
+ };
+ expect(await put(page), "the app's own page is a renderer, not main").toMatchObject({ status: 403, body: { error: "Only My Cloud's owner can move things into it." } });
+ expect((await put({})).status, "a program on this computer without the app's capability").toBe(403);
+ expect((await put({ "x-openmausbot-desktop-owner": "not-the-capability" })).status).toBe(403);
+ expect((await sendFile("workspaces/nobody/a.txt", "x", page)).status, "files too").toBe(403);
+ // Main's own call gets past the owner check, to the item itself.
+ expect(await fx.local("PUT", "/api/cloud-send/kind", write)).toMatchObject({ status: 400 });
+ // My Cloud takes nothing from a program on its own machine: only from its owner's session.
+ const onCloudLoopback = await fetch(`${fx.cloudBase}/api/cloud-send/kind`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(write) });
+ expect(onCloudLoopback.status).toBe(403);
+}, hostTimeout(60_000));
+
+it("a bot that went to My Cloud comes back: its line here is brought up to date, never made again; it is live in one place at every step, also across crashes", async () => {
+ rover = (await fx.local("POST", "/api/bots", { name: "Rover", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as Bot;
+ expect((await fx.local("PATCH", `/api/bots/${rover.id}`, { soul: "You are Rover." })).status).toBe(200);
+ fx.account.state = { ...fx.account.state, machine: { status: "ready", origin: fx.cloudBase, moves: true } };
+ await fx.call("cloud-send:move-bots", "local", [rover.id]);
+ await expect.poll(() => moves().moves.length > 0 && moves().moves.every((entry) => entry.phase === "done"), { timeout: 120_000, interval: 250, message: JSON.stringify(moves()) }).toBe(true);
+ await liveOnlyOn(rover.id, "cloud");
+
+ // What it did on My Cloud since: a new title, a routine that is on and a webhook.
+ expect((await fx.onCloud("PATCH", `/api/bots/${rover.id}`, { title: "Field reporter" })).status).toBe(200);
+ const made = (await fx.onCloud("POST", "/api/routines", { name: "Evening", prompt: "Report.", botId: rover.id, schedule: { type: "daily", time: "18:00", weekdays: [1, 2, 3, 4, 5] }, durationMinutes: 15 })).body;
+ const evening = (made.routine ?? made).id as string;
+ const hooked = (await fx.onCloud("POST", "/api/webhooks", { name: "Orders", prompt: "File it.", botId: rover.id })).body;
+ const orders = (hooked.webhook ?? hooked).id as string;
+
+ // Crash before the copy: this computer held its line as returning, then the app was killed. The move stops: the line is
+ // what it was, and the bot never stopped working on My Cloud.
+ expect(await move(fx.local, rover.id, { state: "returning", team: MY_CLOUD })).toMatchObject({ status: 200, body: { movedTo: { state: "moving", back: true } } });
+ await fx.relaunch({ kill: true });
+ expect((await fx.local("GET", `/api/bot-moves/${rover.id}`)).body.movedTo).toMatchObject({ back: true });
+ expect((await fx.local("DELETE", `/api/bot-moves/${rover.id}`)).status).toBe(200);
+ expect(await botOn(fx.local, rover.id)).toMatchObject({ hidden: true, movedTo: { state: "moved", team: MY_CLOUD } });
+ await liveOnlyOn(rover.id, "cloud");
+
+ // Returning, the line is compared, not made again, and what My Cloud has wins over what it kept.
+ expect((await move(fx.local, rover.id, { state: "returning", team: MY_CLOUD })).status).toBe(200);
+ const here = parseSendSummary((await fx.local("GET", "/api/cloud-send?move=1")).body);
+ const there = parseSendSummary((await fx.onCloud("GET", "/api/cloud-send?move=1")).body);
+ expect(here?.items.find((item) => item.key === `bot:${rover.id}`)).toMatchObject({ returning: true });
+ const plan = planSend({ local: there, cloud: here });
+ const row = plan.rows.find((entry) => entry.key === `bot:${rover.id}`);
+ expect(row?.state, "brought up to date, so never a second bot of the same id").toBe("to-update");
+ expect(row?.parts).toEqual(expect.arrayContaining(["title", "archived"]));
+ expect((await fx.local("POST", "/api/bots", { id: rover.id, threadId: rover.threadId, name: "Rover" })).status, "made again, it would be refused").toBe(409);
+
+ // My Cloud holds it, with a hold that lapses unless renewed; its routine and webhook go off there.
+ const holding = await move(fx.onCloud, rover.id, { state: "moving", team: LAPTOP, lapse: true });
+ expect(holding.status, JSON.stringify(holding.body)).toBe(200);
+ expect(holding.body.movedTo.held).toEqual(expect.arrayContaining([`routine:${evening}`, `webhook:${orders}`]));
+ expect(holding.body.movedTo.lapseAt).toBeGreaterThan(Date.now() + 25 * 60_000);
+
+ // The copy, over the app's own capability: its fields (its archived switch waits for the arrival), routine, webhook and a
+ // file its old line kept here, which gives way to the newer one and is kept aside.
+ expect((await fx.local("PATCH", `/api/bots/${rover.id}`, { title: "Field reporter" })).status).toBe(200);
+ const others = async () => ((await fx.local("GET", "/api/bots")).body.bots as Array<Bot & Record<string, unknown>>).filter((bot) => bot.id !== rover.id)
+ .map((bot) => [bot.id, bot.hidden ?? false, bot.chiefOfStaff ?? false, Boolean(bot.defaultBot)]);
+ const before = await others();
+ expect((await carry(`bot:${rover.id}`)).status).toBe(200);
+ expect(await others(), "a bot coming back changes none of this computer's other bots").toEqual(before);
+ expect(await botOn(fx.local, rover.id), "still hidden while it comes").toMatchObject({ hidden: true, movedTo: { back: true } });
+ expect((await fx.local("PUT", "/api/cloud-send/kind", { v: 1, key: `bot:${rover.id}`, dataDir: "/omb-data", record: { hidden: false } })).status).toBe(200);
+ expect(await botOn(fx.local, rover.id), "a shown switch waits for the arrival").toMatchObject({ hidden: true, movedTo: { back: true, archived: false } });
+ expect((await carry(`routine:${evening}`)).status).toBe(200);
+ expect((await carry(`webhook:${orders}`)).status).toBe(200);
+ const notes = `workspaces/${rover.id}/notes.md`;
+ mkdirSync(join(fx.desktopDataDir, "workspaces", rover.id), { recursive: true });
+ writeFileSync(join(fx.desktopDataDir, notes), "old notes\n");
+ expect(await sendFile(notes, "newer notes from My Cloud\n")).toMatchObject({ status: 201, body: { stored: true, setAside: true } });
+ expect(readFileSync(join(fx.desktopDataDir, notes), "utf8")).toBe("newer notes from My Cloud\n");
+ const returningAt = (await botOn(fx.local, rover.id))!.movedTo as unknown as { at: number };
+ expect(readFileSync(join(fx.desktopDataDir, "move-back-kept", `${rover.id}-${returningAt.at}`, notes), "utf8")).toBe("old notes\n");
+ expect((await routinesOn(fx.local)).find((routine) => routine.id === evening)?.enabled, "nothing runs here before the switch").toBe(false);
+
+ // Crash after the copy, before the switch: both places are killed. The move stops: My Cloud lets the bot go on, its
+ // routine and webhook on again; this computer's line is a line again.
+ await fx.relaunch({ kill: true, cloud: {} });
+ expect((await fx.onCloud("GET", `/api/bot-moves/${rover.id}`)).body.movedTo).toMatchObject({ state: "moving", lapseAt: holding.body.movedTo.lapseAt });
+ expect((await fx.onCloud("DELETE", `/api/bot-moves/${rover.id}`)).status).toBe(200);
+ expect((await fx.local("DELETE", `/api/bot-moves/${rover.id}`)).status).toBe(200);
+ await liveOnlyOn(rover.id, "cloud");
+ expect((await routinesOn(fx.onCloud)).find((routine) => routine.id === evening)?.enabled).toBe(true);
+ expect((await hooksOn(fx.onCloud)).find((hook) => hook.id === orders)?.enabled).toBe(true);
+ expect(await botOn(fx.local, rover.id)).toMatchObject({ hidden: true, movedTo: { state: "moved" } });
+
+ // Again, to the end: hold both, the switch on My Cloud first, then a crash, then the arrival here.
+ expect((await move(fx.local, rover.id, { state: "returning", team: MY_CLOUD })).status).toBe(200);
+ const held = (await move(fx.onCloud, rover.id, { state: "moving", team: LAPTOP, lapse: true })).body.movedTo.held as string[];
+ expect((await carry(`bot:${rover.id}`)).status).toBe(200);
+ const switched = await move(fx.onCloud, rover.id, { state: "moved", team: LAPTOP });
+ expect(switched.status, JSON.stringify(switched.body)).toBe(200);
+ expect(switched.body.stays, "what stays on My Cloud: counts and names, never a value").toMatchObject({ logins: expect.any(Number), secrets: expect.any(Number), onePassword: expect.any(Boolean), connections: expect.any(Array) });
+ await fx.relaunch({ kill: true });
+ // Between the two switch steps the bot is live nowhere: paused, never in both.
+ expect([live(await botOn(fx.local, rover.id)), live(await botOn(fx.onCloud, rover.id))]).toEqual([false, false]);
+ const arrived = await move(fx.local, rover.id, { state: "arrived", team: MY_CLOUD, on: held });
+ expect(arrived.status, JSON.stringify(arrived.body)).toBe(200);
+ expect(arrived.body.arrived).toMatchObject({ place: "computer", from: MY_CLOUD, on: { routines: [{ id: evening, name: "Evening" }], webhooks: [] }, offHere: { webhooks: [{ id: orders, name: "Orders" }] } });
+ expect((await move(fx.local, rover.id, { state: "arrived", team: MY_CLOUD, on: held })).body, "asked again, the same").toEqual(arrived.body);
+ expect((await fx.local("GET", `/api/bot-moves/${rover.id}`)).body.arrived).toEqual(arrived.body.arrived);
+ await liveOnlyOn(rover.id, "computer");
+ expect(await botOn(fx.local, rover.id)).toMatchObject({ title: "Field reporter" });
+ expect((await routinesOn(fx.local)).find((routine) => routine.id === evening)?.enabled, "routines run here now").toBe(true);
+ expect((await hooksOn(fx.local)).find((hook) => hook.id === orders)?.enabled, "a webhook nobody can reach here stays off").toBe(false);
+ const cloudCopy = await botOn(fx.onCloud, rover.id);
+ expect(cloudCopy).toMatchObject({ hidden: true, movedTo: { state: "moved", team: LAPTOP } });
+ expect((await routinesOn(fx.onCloud)).find((routine) => routine.id === evening)?.enabled, "kept on My Cloud, off").toBe(false);
+ expect((await fx.onCloud("POST", `/api/bots/${rover.id}/messages`, { text: "Still there?", threadId: rover.threadId })).status).toBe(409);
+ expect((await fx.local("POST", `/api/bots/${rover.id}/messages`, { text: "Welcome back.", threadId: rover.threadId })).status).toBe(202);
+}, hostTimeout(400_000));
+
+it("goes to My Cloud a second time: its line there comes back to life instead of a stub in both places", async () => {
+ await expect.poll(async () => !(await botOn(fx.local, rover.id) as Bot & { busy?: boolean })?.busy, { timeout: 60_000, interval: 100 }).toBe(true);
+ expect(await move(fx.onCloud, rover.id, { state: "returning", team: LAPTOP })).toMatchObject({ status: 200, body: { movedTo: { back: true } } });
+ expect(parseSendSummary((await fx.onCloud("GET", "/api/cloud-send?move=1")).body)?.items.find((item) => item.key === `bot:${rover.id}`)).toMatchObject({ returning: true });
+ const held = await move(fx.local, rover.id, { state: "moving", team: MY_CLOUD, lapse: true });
+ expect(held.status, JSON.stringify(held.body)).toBe(200);
+ const on = held.body.movedTo.held as string[];
+ const arrived = await move(fx.onCloud, rover.id, { state: "arrived", team: LAPTOP, on });
+ expect(arrived.status, JSON.stringify(arrived.body)).toBe(200);
+ expect(arrived.body.arrived).toMatchObject({ place: "cloud", offHere: { webhooks: [], appEvents: [], mcpServers: [] } });
+ expect((await move(fx.local, rover.id, { state: "moved", team: MY_CLOUD })).status).toBe(200);
+ await liveOnlyOn(rover.id, "cloud");
+ expect((await routinesOn(fx.onCloud)).find((routine) => routine.botId === rover.id && routine.enabled), "what ran here runs there").toBeTruthy();
+}, hostTimeout(120_000));
+
+it("a bot born on My Cloud arrives here held from its first write; a stopped first arrival is the line of where it lives, and a bot of the person's here is never taken", async () => {
+ const nova = (await fx.onCloud("POST", "/api/bots", { name: "Nova", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as Bot;
+ const mine = (await fx.local("POST", "/api/bots", { name: "Mine", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as Bot;
+ expect(await move(fx.local, mine.id, { state: "returning", team: MY_CLOUD }), "a live bot of the same id here").toMatchObject({ status: 409, body: { here: true } });
+ expect(live(await botOn(fx.local, mine.id))).toBe(true);
+ const made = await fx.local("POST", "/api/bots", { id: nova.id, threadId: nova.threadId, name: "Nova", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ const arriving = await move(fx.local, nova.id, { state: "returning", team: MY_CLOUD, arrival: true });
+ expect(arriving.status, JSON.stringify(arriving.body)).toBe(200);
+ expect(await botOn(fx.local, nova.id)).toMatchObject({ hidden: true, movedTo: { back: true, arrival: true } });
+ await liveOnlyOn(nova.id, "cloud");
+ expect((await fx.local("DELETE", `/api/bot-moves/${nova.id}`)).status).toBe(200);
+ expect(await botOn(fx.local, nova.id), "kept, as the line of where it lives").toMatchObject({ hidden: true, movedTo: { state: "moved", team: MY_CLOUD } });
+ await liveOnlyOn(nova.id, "cloud");
+ expect(await move(fx.local, nova.id, { state: "returning", team: MY_CLOUD }), "the next try takes that line").toMatchObject({ status: 200, body: { movedTo: { back: true } } });
+ expect((await fx.local("DELETE", `/api/bot-moves/${nova.id}`)).status).toBe(200);
+}, hostTimeout(60_000));
diff --git a/server/move-back.ts b/server/move-back.ts
new file mode 100644
index 0000000000..59b87f3066
--- /dev/null
+++ b/server/move-back.ts
@@ -0,0 +1,87 @@
+// A bot coming back from one of the person's places to another: from My Cloud to this computer, or to My Cloud again
+// after it went from there (server/bot-moves.ts holds it on both sides). This keeps what the arriving side says about it
+// afterwards (which routines are on, what stayed off here and why), who may write a move into this computer, and what the
+// Cloud keeps of the person's when one of its bots leaves for a computer.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { writeFileAtomic } from "./atomic.ts";
+import type { CloudOwner } from "./cloud-owner-lines.ts";
+import { customMcpServers, type AppConfig } from "./config.ts";
+import type { RequestAuth } from "./request-auth.ts";
+import type { BotRecord } from "./store.ts";
+
+/** A routine, webhook or app event by its id and name. */
+export interface MovedAutomation { id: string; name: string }
+
+/** What the arriving side did when a bot came back, kept so the person can be told it afterwards. */
+export interface ArrivedFacts {
+ v: 1;
+ /** Where it came from: My Cloud, or one of the person's computers. */
+ from: { id: string; name: string };
+ /** When the hold that brought it began, so a second ask for the same arrival answers the same. */
+ hold: number;
+ at: number;
+ /** "computer": this computer took it; "cloud": My Cloud took it again. */
+ place: "computer" | "cloud";
+ /** What was on there and is on here now. */
+ on: { routines: MovedAutomation[]; webhooks: MovedAutomation[]; appEvents: MovedAutomation[] };
+ /** What was on there and stays off here: a webhook no one can reach on a computer, an app event this computer may not
+ * be connected for, and an MCP server that runs a command here the bot did not use here before. */
+ offHere: { webhooks: MovedAutomation[]; appEvents: MovedAutomation[]; mcpServers: string[] };
+}
+
+/** What My Cloud keeps of the person's when one of its bots goes to a computer: nothing of it is sent or changed. Counts and
+ * names only, never a value. */
+export interface StaysOnCloud { logins: number; secrets: number; onePassword: boolean; connections: string[] }
+
+const FILE = "bot-arrivals.json";
+const KEPT = 50;
+
+/** The facts of each bot's last arrival here, in `<dataDir>/bot-arrivals.json`. */
+export function arrivalsFile(dataDir: string) {
+ const path = join(dataDir, FILE);
+ const read = (): Record<string, ArrivedFacts> => {
+ try {
+ const raw = JSON.parse(readFileSync(path, "utf8")) as unknown;
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, ArrivedFacts> : {};
+ } catch { return {}; }
+ };
+ return {
+ get: (botId: string): ArrivedFacts | null => read()[botId] ?? null,
+ put(botId: string, facts: ArrivedFacts): void {
+ const all = { ...read(), [botId]: facts };
+ const kept = Object.entries(all).sort(([, a], [, b]) => b.at - a.at).slice(0, KEPT);
+ writeFileAtomic(path, JSON.stringify(Object.fromEntries(kept)), { mode: 0o600 });
+ },
+ };
+}
+export type Arrivals = ReturnType<typeof arrivalsFile>;
+
+/** The app's own main process on this computer, asking its own server: the desktop's capability (request-auth.ts), from
+ * no browser page and no paired phone, on a server the desktop runs and nobody else signs in to. Security: this is the
+ * only caller besides My Cloud's owner that may write a move into a server; a renderer, a bot's shell, the network and a
+ * shared or hosted workspace never are. */
+export function desktopMainMover(auth: RequestAuth, place: { desktopManaged: boolean; managed: boolean }): boolean {
+ return place.desktopManaged && !place.managed && auth.kind === "loopback" && auth.desktopMain === true && auth.trust !== "service"
+ && auth.companionDevice === undefined;
+}
+
+/** The person on their own computer, as a move into it names them: nothing they wrote is stamped with it (`here`). */
+export const thisComputerOwner = (name: string | undefined): CloudOwner => ({ person: "this-computer", name: name?.trim() || "User", here: true });
+
+/** The MCP servers this server would mount for the bot, and which of them run a command on this machine. */
+export function mcpServersHere(cfg: AppConfig, botId: string): { all: string[]; command: string[] } {
+ const servers = customMcpServers(cfg, undefined, botId);
+ const all = Object.keys(servers);
+ return { all, command: all.filter((name) => "command" in servers[name]!) };
+}
+
+/** What My Cloud keeps when this bot leaves it for a computer: the person's logins, secrets and 1Password, and the
+ * connections the bot uses here, which a computer has only once the person connects them there. */
+export function staysOnCloud(bot: Pick<BotRecord, "mcpServers" | "connectorTools"> | null | undefined, held: {
+ logins: number; secrets: number; onePassword: boolean; mcpServers: readonly string[];
+}): StaysOnCloud {
+ const mcp = bot?.mcpServers ?? held.mcpServers;
+ return { logins: held.logins, secrets: held.secrets, onePassword: held.onePassword, connections: [...new Set([...mcp, ...Object.keys(bot?.connectorTools ?? {})])].sort() };
+}
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index d9cd85c85f..9f293f93e2 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -29,6 +29,7 @@ import {
serializeSessionCookie,
sessionCookieName,
} from "./request-auth.ts";
+import { desktopMainMover } from "./move-back.ts";
import { SESSION_TTL_MS, SessionRegistry } from "./sessions.ts";
import { webSessionHeaders } from "../companion/src/session-route.ts";
@@ -789,7 +790,23 @@ describe("loopback trust: owner on one person's machine, service on a shared wor
it("ignores service trust while the desktop capability is in force", () => {
expect(check("PUT", "/api/config", { trust: "service", desktopToken: "owner-token", headers: { "x-openmausbot-desktop-owner": "owner-token" } }).auth)
- .toEqual({ kind: "loopback", scopes: ["admin", "client"] });
+ .toEqual({ kind: "loopback", scopes: ["admin", "client"], desktopMain: true });
+ });
+
+ it("marks the desktop app's own main process apart from its pages, a paired phone and any other program here", () => {
+ const desktop = { desktopToken: "owner-token" };
+ const main = check("PUT", "/api/cloud-send/kind", { ...desktop, headers: { "x-openmausbot-desktop-owner": "owner-token", "sec-fetch-mode": "cors" } }).auth;
+ expect(main).toEqual({ kind: "loopback", scopes: ["admin", "client"], desktopMain: true });
+ const page = check("PUT", "/api/cloud-send/kind", { ...desktop, headers: { "x-openmausbot-desktop-owner": "owner-token", origin: "http://127.0.0.1:8799", "sec-fetch-site": "same-origin", "sec-fetch-dest": "empty" } }).auth;
+ expect(page).toEqual({ kind: "loopback", scopes: ["admin", "client"] });
+ expect(check("GET", "/api/cloud-send", desktop).auth, "a program here without the capability").toEqual({ kind: "loopback", scopes: ["admin", "client"] });
+ expect(check("PUT", "/api/cloud-send/kind", desktop).auth, "and it may not write").toBeNull();
+ expect(check("GET", "/api/cloud-send", { headers: { "x-openmausbot-desktop-owner": "owner-token" } }).auth, "no desktop on this server").toEqual({ kind: "loopback", scopes: ["admin", "client"] });
+ const place = { desktopManaged: true, managed: false };
+ expect(desktopMainMover(main!, place)).toBe(true);
+ expect([desktopMainMover(page!, place), desktopMainMover(main!, { desktopManaged: false, managed: false }), desktopMainMover(main!, { desktopManaged: true, managed: true })]).toEqual([false, false, false]);
+ expect(desktopMainMover({ ...main!, companionDevice: "phone-1" } as never, place), "a paired phone never is").toBe(false);
+ expect(desktopMainMover({ kind: "loopback", scopes: ["client"], trust: "service", desktopMain: true } as never, place), "nor a shared workspace's program").toBe(false);
});
it("defaults to service on a hosted workspace, owner elsewhere, and lets the operator choose", () => {
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 76d0610b4b..0aed1cd807 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -18,6 +18,8 @@ export type RequestAuth =
kind: "loopback"; scopes: readonly Scope[]; trust?: "service";
/** Set only on the verified companion-token path: the sidecar's id for the phone that authenticated. */
companionDevice?: string;
+ /** Set only when the desktop's capability came from no browser page: the app's own main process (move-back.ts). */
+ desktopMain?: true;
}
| { kind: "session"; session: SessionRecord; via: "bearer" | "cookie" | "ticket"; scopes: readonly Scope[] };
@@ -746,7 +748,7 @@ export function resolveRequestAuth(req: IncomingMessage, options: ResolveOptions
}
return { auth: { kind: "loopback", scopes: SERVICE_SCOPES, trust: "service" }, status: 401, error: "" };
}
- return { auth: { kind: "loopback", scopes: LOOPBACK_SCOPES }, status: 401, error: "" };
+ return { auth: { kind: "loopback", scopes: LOOPBACK_SCOPES, ...(desktopOwner && !fromBrowser(req) ? { desktopMain: true as const } : {}) }, status: 401, error: "" };
}
if (proxied) {
diff --git a/server/routes/bot-moves.ts b/server/routes/bot-moves.ts
index 5d426d0b92..112590880e 100644
--- a/server/routes/bot-moves.ts
+++ b/server/routes/bot-moves.ts
@@ -1,38 +1,57 @@
-// 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.
+// POST /api/bot-moves/:bot { state, team } and DELETE /api/bot-moves/:bot: a server holding one of its bots while it moves
+// to another home (a team, My Cloud, or one of the person's computers), 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). A bot coming
+// back is held as "returning" where it comes to and made live there by "arrived"; GET says how the server keeps the bot
+// and what its last arrival did. Admin scope: the person's own app runs the move.
import { z } from "zod";
import type { BotMoves } from "../bot-moves.ts";
import { PASS, type RouteHandler } from "./table.ts";
-const bodySchema = z.object({
- v: z.literal(1),
- 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) }),
-});
+const team = z.object({ id: z.string().regex(/^[\w-]{1,128}$/u), name: z.string().trim().min(1).max(80) });
+// New states, not new fields on old ones: an older server answers 400 rather than holding the bot the old way.
+const bodySchema = z.discriminatedUnion("state", [
+ z.object({ v: z.literal(1), state: z.literal("moving"), team, lapse: z.boolean().optional() }),
+ z.object({ v: z.literal(1), state: z.literal("returning"), team, lapse: z.boolean().optional(), arrival: z.boolean().optional() }),
+ z.object({ v: z.literal(1), state: z.literal("moved"), team }),
+ z.object({ v: z.literal(1), state: z.literal("arrived"), team, on: z.array(z.string().regex(/^(?:routine|call|webhook|app-event):[\w-]{1,128}$/u)).max(2_000) }),
+ z.object({ v: z.literal(1), state: z.literal("back"), team }),
+]);
export function createBotMoveRoutes({ moves, enabled }: { moves: BotMoves | null; enabled: boolean }): RouteHandler {
return async ({ req, res, path, method, json, readBody }) => {
const bot = /^\/api\/bot-moves\/([\w-]{1,128})$/u.exec(path)?.[1];
if (!bot) return PASS;
if (!enabled || !moves) { req.resume(); return json(res, 404, { error: "Bots move into a team from My Cloud." }); }
+ if (method === "GET") {
+ const state = moves.state(bot);
+ return state ? json(res, 200, { v: 1, ...state }) : json(res, 404, { error: "This bot is no longer here." });
+ }
if (method === "DELETE") {
const released = await moves.release(bot);
return "refused" in released ? json(res, 409, { error: released.refused }) : json(res, 200, { v: 1, released: true });
}
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\" | \"back\", team: { id, name } }" });
- const { state, team } = parsed.data;
- if (state === "back") {
+ const parsed = bodySchema.safeParse(await readBody(req, 512 * 1024));
+ if (!parsed.success) return json(res, 400, { error: "send { v: 1, state: \"moving\" | \"returning\" | \"moved\" | \"arrived\" | \"back\", team: { id, name } }" });
+ const body = parsed.data;
+ if (body.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);
+ // `held: false`: no hold holds the bot any more (it lapsed, or was let go of); the move holds it again from the copy.
+ const notHeld = () => (moves.state(bot)?.holding ? {} : { held: false });
+ if (body.state === "arrived") {
+ const arrived = await moves.arrived(bot, body.team, body.on);
+ return "refused" in arrived ? json(res, 409, { error: arrived.refused, ...notHeld() }) : json(res, 200, { v: 1, ...arrived });
+ }
+ if (body.state === "moved") {
+ const moved = moves.moved(bot, body.team);
+ return "refused" in moved ? json(res, 409, { error: moved.refused, ...notHeld() }) : json(res, 200, { v: 1, ...moved });
+ }
+ const answer = await moves.hold(bot, body.team, { lapse: body.lapse === true, back: body.state === "returning", arrival: body.state === "returning" && body.arrival === true });
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 });
+ if ("refused" in answer) return json(res, 409, { error: answer.refused, ...(answer.here ? { here: true } : {}) });
return json(res, 200, { v: 1, movedTo: answer.movedTo });
};
}