Skip to content

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

Make a server of your own your bots' home, as My Cloud is (#3948)

Milind Soni7de00e425848
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 435160783b..d2d108ac12 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -582,9 +582,12 @@ the person's own uses this computer by itself while the desktop app runs and is
signed in as them (`lendAutomatically` in `electron/computer-sharing.mjs`): My
Cloud and each other Cloud the verified session lists as theirs
(`createLendingTarget` in `electron/lending-target.mjs`), never a Team Cloud and
-never a server that only signed in with their account. Other users (desktop only,
-self-hosted, hosted team workspaces) keep computer sharing exactly as before: off
-unless a maintainer sets `features.sharedComputers` by hand.
+never a server that only signed in with their account. A server of the person's
+own that they made their bots' home (**Make <server> my home**, docs/self-hosting.md)
+is lent the same way, last, once the move is done and while that server says it
+is theirs alone. Other users (desktop only, self-hosted, hosted team workspaces)
+keep computer sharing exactly as before: off unless a maintainer sets
+`features.sharedComputers` by hand.
### What each Cloud gets
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 50925ca64f..ee153dbaf9 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -445,7 +445,8 @@ the six-digit code from another desktop app, not a self-hosted server's
Server menu to switch back until the server is updated.
After pairing, **Share this computer?** offers **Choose access** or **Not now**.
-Nothing is shared automatically. In **Settings → Servers → Computer
+Nothing is shared automatically, unless you make the server your bots' home
+(below). In **Settings → Servers → Computer
access**, choose read-only folders and optionally allow edits. Unrestricted
terminal and screen/app control are separate opt-ins, confirmed in a native
dialog. They can access information outside the selected folders. Share only
@@ -454,12 +455,31 @@ A folder read takes a file of up to 2 MiB and a write at most 256 KiB;
transfers do not follow links or delete files. Local screen control also needs OS permissions and a supported
desktop driver. Microphone access is not included.
-**Bring this computer's bots and chats.** Export a backup from this computer in
-**Settings → Backups → Export backup**, then import it on the server in
-**Settings → Backups → Import backup**. API keys, engine sign-ins and paired
-devices stay where they are on both sides; routines arrive paused. An older
-desktop app's **Copy this computer here** is answered with "Update OpenMausBot
-to bring your bots here by itself."
+**Make the server your bots' home.** Bots work together only within one
+place: bots on this computer can't reach bots on the server. To bring them
+together, right-click the server's circle at the window's left edge and choose
+**Make <server> my home**. The app moves this computer's bots, chats, memory,
+skills, logins, apps and keys, and routines there the way it moves them to My
+Cloud: everything is copied while you keep working, then at a quiet moment this
+computer stops for good, the rest goes, both sides are checked, and the server
+switches on what was on here, so no routine ever runs twice. The account area
+says how it goes, and after a day of failing it says the move needs you, with
+Try again. Afterwards the server is what the window opens, and this computer
+works for it by itself as it does for My Cloud: no access dialog, only the
+menu bar's item with Pause.
+
+This is offered only for a server that is yours alone: you paired with it as an
+admin, and its sign-in list names no members and no other admin (Settings →
+People). A server other people sign in to keeps the explicit **Share this
+computer?** flow above, and its bots stay where they are. Both sides need this
+release: an older server says to update it first.
+
+To move by hand instead, export a backup from this computer in **Settings →
+Backups → Export backup**, then import it on the server in **Settings → Backups
+→ Import backup**. API keys, engine sign-ins and paired devices stay where they
+are on both sides; routines arrive paused. An older desktop app's **Copy this
+computer here** is answered with "Update OpenMausBot to bring your bots here by
+itself."
Only conversations you start yourself on that server can use what you share;
other people's bots, routines and webhooks there cannot. Keys and sign-in
diff --git a/docs/verification/README.md b/docs/verification/README.md
index 2e6cfecbb9..28c01cfe95 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -124,6 +124,11 @@ The [move to My Cloud fixture](cloud-send.md) runs this computer's server and a
Cloud home with the desktop's own wiring between them, and runs and checks the
one-time move as main does.
+The [server of the person's own as home fixture](own-home.md) runs this
+computer's server and servers of the person's own with main's wiring for
+**Make <server> my home**: the move, routines that run once, this computer then
+lent to that server by itself, and none of it for a server shared with others.
+
The [MCP sign-in fixture](mcp-sign-in.md) checks remote sign-in, callback URL
paste-back, MCP tools and logout cancellation through the real settings panel
and a synthetic OAuth provider in a disposable workspace.
diff --git a/docs/verification/evidence/own-home/failing-daylight.png b/docs/verification/evidence/own-home/failing-daylight.png
new file mode 100644
index 0000000000..f48e84e130
Binary files /dev/null and b/docs/verification/evidence/own-home/failing-daylight.png differ
diff --git a/docs/verification/evidence/own-home/failing-midnight.png b/docs/verification/evidence/own-home/failing-midnight.png
new file mode 100644
index 0000000000..dacea6cb7a
Binary files /dev/null and b/docs/verification/evidence/own-home/failing-midnight.png differ
diff --git a/docs/verification/evidence/own-home/menu-daylight.png b/docs/verification/evidence/own-home/menu-daylight.png
new file mode 100644
index 0000000000..f8d63e4dab
Binary files /dev/null and b/docs/verification/evidence/own-home/menu-daylight.png differ
diff --git a/docs/verification/evidence/own-home/menu-midnight.png b/docs/verification/evidence/own-home/menu-midnight.png
new file mode 100644
index 0000000000..3b7935554d
Binary files /dev/null and b/docs/verification/evidence/own-home/menu-midnight.png differ
diff --git a/docs/verification/evidence/own-home/moving-daylight.png b/docs/verification/evidence/own-home/moving-daylight.png
new file mode 100644
index 0000000000..5142a45430
Binary files /dev/null and b/docs/verification/evidence/own-home/moving-daylight.png differ
diff --git a/docs/verification/evidence/own-home/moving-midnight.png b/docs/verification/evidence/own-home/moving-midnight.png
new file mode 100644
index 0000000000..ba81ed9e93
Binary files /dev/null and b/docs/verification/evidence/own-home/moving-midnight.png differ
diff --git a/docs/verification/own-home.md b/docs/verification/own-home.md
new file mode 100644
index 0000000000..a305f0c2ad
--- /dev/null
+++ b/docs/verification/own-home.md
@@ -0,0 +1,49 @@
+# A server of the person's own as their bots' home
+
+What it covers: **Make <server> my home** on a server's circle, the one-time move
+of this computer's bots to that server, and this computer then working for it by
+itself; and that none of it happens for a server other people sign in to.
+
+```sh
+pnpm exec vitest run server/own-home.e2e.test.ts server/own-home.test.ts server/move-freeze.test.ts
+node --test electron/own-home-main.node-test.mjs electron/lending-target.node-test.mjs electron/lend-automatically.node-test.mjs electron/one-home-main.node-test.mjs electron/cloud-rail.node-test.mjs electron/home-window.node-test.mjs electron/cloud-connections.node-test.mjs
+```
+
+`scripts/testing/own-home-fixture.ts` starts this computer's server as the
+desktop app starts it, and servers of the person's own (`openmausbot serve`,
+nothing of MausBot Cloud), each paired as a pairing link pairs it, with main's
+own wiring for the move (`electron/own-home-main.mjs`) between them. Its
+requests carry the pairing's session as the window's would. Temp homes and a
+synthetic Claude CLI; no network.
+
+`server/own-home.e2e.test.ts` checks:
+
+- a server paired only with the person (no members, no other admin) says the
+ session is its owner's (`own` on `/api/auth/session`) and that it takes a
+ move; one with a member on its sign-in list says neither, is never offered,
+ refuses **Make … my home** in plain words, and its move routes refuse that
+ session;
+- the move to the person's own server, with the app killed the moment the
+ freeze and the switch would be written down: bots, a chat, a memory note and
+ routines arrive under the same ids, the server switches on only what was on
+ here, the webhook's bot says once (naming the server) that its address
+ changed, this computer is frozen for good and refuses a turn with "This bot
+ lives on <server> now.", its project folder is lent with the server, its
+ phone link stops and the window opens the server;
+- no occurrence of any routine runs on both sides, and the one due right after
+ the move runs on the server only;
+- this computer's real lending (`createComputerSharing` over
+ `createLendingTarget` with the move's `home()`) lends itself to the person's
+ own server with no click and never the terminal, lends nothing to the server
+ it shares with others, and Pause stops it.
+
+The node tests add the rest: a choice is bound to the server's identity, the
+offer needs the server's fresh word that it is the person's alone and no move
+under way, Make … my home is refused on My Cloud, a team's Cloud, a server not
+signed in or too old; every pass goes over the window's sign-in to that server
+only and never signs it out; lending to that server stops once it has other
+people on it or another server answers at its address; while a server of the
+person's own is chosen no move to My Cloud starts; the frozen screen names the
+server and never asks for a MausBot Cloud sign-in; and connected apps through
+MausBot's service stay on this computer (a final, plain reason) when the server
+has no such service, so the move's check still passes.
diff --git a/electron/cloud-connections.mjs b/electron/cloud-connections.mjs
index b2e3c28e9e..fabf986665 100644
--- a/electron/cloud-connections.mjs
+++ b/electron/cloud-connections.mjs
@@ -54,7 +54,8 @@ export function parseConnections(value) {
...(typeof item.account === "string" && item.account.length <= 120 ? { account: item.account } : {}),
...(typeof item.installationId === "string" && INSTALLATION.test(item.installationId) ? { installationId: item.installationId } : {}),
}));
- return { computer: { environmentId, label: label.trim().slice(0, 120) }, connections, engines: strings(value.engines, ENGINE, 200), commands: strings(value.commands, LAUNCHER, 40) };
+ return { computer: { environmentId, label: label.trim().slice(0, 120) }, connections, engines: strings(value.engines, ENGINE, 200), commands: strings(value.commands, LAUNCHER, 40),
+ ...(value.managedApps === false ? { managedApps: false } : {}) };
}
/** This computer's connections, by name only, and the computer they are on. */
@@ -117,8 +118,11 @@ async function letGo(local, target, item, digest) {
* are connected keeps them, and says which apps connected here it lacks (`missing`).
* `here` and `there`: the "composio" connection of this computer and of My Cloud (null when My Cloud has none yet).
*/
-export async function adoptComposioId(target, { local, here, there }) {
+export async function adoptComposioId(target, { local, here, there, managedApps = true }) {
if (here.account && there?.account === here.account) return { shared: true };
+ if (here.mode === "managed" && !managedApps) {
+ throw new ConnectionMoveError("no_service", "Your connected apps stay on this computer: that server has no connected-apps service of its own. Connect them again there in Apps.", true);
+ }
const listed = await local.json("/api/connectors/connected").catch(() => null);
const apps = Object.entries(record(listed?.services) ? listed.services : {}).filter(([slug, state]) => SLUG.test(slug) && record(state) && state.connected === true)
.map(([slug]) => slug).slice(0, 200);
@@ -216,7 +220,7 @@ export async function sendConnections(collected, target, { local, release = true
if (result.kept.length === kept) done(item);
},
async composio(item) {
- const outcome = await adoptComposioId(target, { local, here: item, there: cloud.connections.find((theirs) => theirs.id === "composio") ?? null });
+ const outcome = await adoptComposioId(target, { local, here: item, there: cloud.connections.find((theirs) => theirs.id === "composio") ?? null, managedApps: cloud.managedApps !== false });
if (outcome.kept) {
result.kept.push({ id: item.id, label: item.label });
result.missing.push(...outcome.missing.map((slug) => ({ slug })));
diff --git a/electron/cloud-connections.node-test.mjs b/electron/cloud-connections.node-test.mjs
index fe150b6638..946732356e 100644
--- a/electron/cloud-connections.node-test.mjs
+++ b/electron/cloud-connections.node-test.mjs
@@ -209,6 +209,21 @@ test("connected apps: the same account already, the person's own project, a Clou
assert.deepEqual(keeps.calls[0], ["POST", "/api/cloud-connections/connected-apps", { apiKey: "ck", userId: "u1", apps: ["gmail"] }]);
});
+test("a server of the person's own with no connected-apps service keeps MausBot's connected apps here for good, and still takes their own project", async () => {
+ const here = { id: "composio", kind: "composio", label: "Connected apps", mode: "managed", account: "managed:aaa" };
+ const local = computer({ connections: [here], answers: { composio: { connection: { composio: { apiKey: "ck", userId: "u1" } } } }, connected: { gmail: { connected: true } } });
+ assert.deepEqual(parseConnections({ computer: COMPUTER, connections: [], managedApps: false }).managedApps, false);
+ assert.equal(parseConnections({ computer: COMPUTER, connections: [] }).managedApps, undefined, "an Admin's Cloud says nothing: as before");
+ const garage = cloud();
+ await assert.rejects(adoptComposioId(garage, { local, here, there: null, managedApps: false }), (error) => error.code === "no_service" && error.final === true);
+ assert.deepEqual(garage.calls, [], "nothing asked of it");
+ const listing = { status: 200, body: { computer: { environmentId: "env-garage", label: "Garage server" }, connections: [], engines: [], commands: [], managedApps: false } };
+ const moved = await sendConnections({ computer: COMPUTER, connections: [here] }, { call: async (method, route) => (method === "GET" && route === "/api/cloud-connections" ? { ok: true, ...listing } : { ok: true, status: 200, body: {} }) }, { local, waitMs: 0 });
+ assert.deepEqual(moved.failed.map((failure) => [failure.id, failure.final]), [["composio", true]], "final: the move's check leaves it out");
+ const own = cloud({ reply: () => ({ status: 200, body: { shared: true } }) });
+ assert.deepEqual(await adoptComposioId(own, { local, here: { ...here, mode: "own", account: "own:x" }, there: null, managedApps: false }), { shared: true });
+});
+
test("a Cloud too old for connections says so; one that does not answer, too; this computer must list its own", async () => {
const local = computer({ connections: [] });
const old = { call: async () => ({ ok: false, status: 404, body: {} }) };
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
index a2a9872165..e61e1627b2 100644
--- a/electron/cloud-rail.d.mts
+++ b/electron/cloud-rail.d.mts
@@ -34,6 +34,9 @@ export interface RailPlace {
ended?: true;
/** Its owner may take this Cloud off their list (it ended, or was never paid for): its menu offers Remove from list. */
removable?: true;
+ /** A server of the person's own, theirs alone by its own word, that this computer's bots may move to: its menu offers
+ * Make … my home. */
+ makeHome?: true;
}
/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings, and
* a new organization on the Team plan this account pays for (absent from an older app's main). */
@@ -65,5 +68,5 @@ export type AddCloudView =
};
export declare const RAIL_MIN_PLACES: number;
/** main's own circles: each as the page sees it, plus the Cloud main acts on for it (never sent to a page). */
-export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown }): Array<RailPlace & { cloudId?: string }>;
+export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown; offers?: (entry: any) => boolean }): Array<RailPlace & { cloudId?: string }>;
export declare function addCloudView(state: unknown, offer: import("./cloud-home.mjs").CloudOffer | null): AddCloudView;
diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjs
index 713e733b2f..b276f7f8d8 100644
--- a/electron/cloud-rail.mjs
+++ b/electron/cloud-rail.mjs
@@ -28,7 +28,7 @@ const machineProgress = machine => {
/** One saved place as a circle: what it is, its colour (and who may change it from the rail) and how it is doing, from
* the session's word for it. */
-function circle(entry, { activeId, mine, state }) {
+function circle(entry, { activeId, mine, state, offers }) {
const connected = state?.status === "connected" ? state : null;
const listed = connected?.clouds?.find(cloud => cloud.origin === entry.origin) ?? null;
const kind = entry.origin === mine || entry.home || entry.cloud ? "cloud" : entry.team ? "team" : "server";
@@ -40,7 +40,8 @@ function circle(entry, { activeId, mine, state }) {
const paint = railPaint(placeLook(entry, { clouds: connected?.clouds ?? null, homeOrigin: mine }), color);
return { id: entry.id, name: entry.name, color, kind, opens: true, ...(paint ? { paint } : {}), ...(entry.id === activeId ? { active: true } : {}),
...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}),
- ...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}) };
+ ...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}),
+ ...(kind === "server" && offers(entry) ? { makeHome: true } : {}) };
}
/** My Cloud's saved place that the verified session's list no longer has (its owner removed it from their list, or the Admin
@@ -57,9 +58,10 @@ const unlisted = (entry, { clouds, home, mine }) => Array.isArray(clouds) && (en
* checkout or its setup), never an address. My Cloud's saved place leaves once the session's list doesn't have it (removed
* from the list). Fewer than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window
* as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.
- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any }} input
+ * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs).
+ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean }} input
*/
-export function railPlaces({ saved, home = null, mine = null, state = null }) {
+export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false }) {
const connected = state?.status === "connected" ? state : null;
const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];
const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };
@@ -67,7 +69,7 @@ export function railPlaces({ saved, home = null, mine = null, state = null }) {
const remote = saved.environments.filter(entry => entry.kind !== "local" && entry.origin && !(connected && unlisted(entry, { clouds: connected.clouds, home, mine })))
.map((entry, index) => ({ entry, index }))
.sort((a, b) => rank(a.entry) - rank(b.entry) || order(a.entry) - order(b.entry) || a.index - b.index)
- .map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected }));
+ .map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected, offers }));
const making = otherOwnClouds(clouds).filter(cloud => !cloud.origin && ["checkout", "setting_up"].includes(cloud.status))
.map(cloud => ({ id: `${PENDING}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "cloud", opens: true, progress: cloudSetupProgress(cloud) ?? 0,
...(cloud.status === "checkout" ? { waiting: true } : {}), cloudId: cloud.id }));
@@ -135,9 +137,10 @@ const CHOICES = Object.freeze(["cloud", "link", "address"]);
* page (`lists`) reads the list and opens or adds a place; +'s buying sheet also runs on a page `trusted` vouches for
* (the rail's, or this computer's own). Any other page learns only whether the rail stands beside it (`beside`).
* `places()` is railPlaces' list now; `open(id)` main's own switch; `add` the + sheet's fixed actions; `account()` the
- * MausBot Cloud sign-in; `targets()` the pages told when something changed.
+ * MausBot Cloud sign-in; `targets()` the pages told when something changed; `makeHome(id)` starts the move to a server
+ * of the person's own (own-home-main.mjs `start`).
*/
-export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets }) {
+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null }) {
let sheetOpen = false, sent = "";
const allowed = (channel, handler) => guard((event, ...args) => {
if (!trusted(event)) throw new Error(`${channel} is only available in this app's window`);
@@ -167,6 +170,12 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
const client = account();
return { outcome: client?.hideCloud ? (await client.hideCloud(place.cloudId)).outcome : "unsupported" };
});
+ // Make … my home, from a circle's menu: only a server main listed with it, by main's own word for it.
+ listed("workspaces:make-home", (_event, id) => {
+ const place = places().find(entry => entry.id === plain(id) && entry.makeHome);
+ if (!place || !makeHome) throw new Error("That server can't be your bots' home now.");
+ return makeHome(place.id);
+ });
// A link pasted on +'s sheet goes to main's own Connect dialog, which checks it and names its host before connecting.
listed("workspaces:add", (_event, choice, link) => {
if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error("That isn't something to add here.");
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
index a2ab39ab52..ac60153fe4 100644
--- a/electron/cloud-rail.node-test.mjs
+++ b/electron/cloud-rail.node-test.mjs
@@ -286,6 +286,24 @@ test("Remove from list from a circle's menu: only the rail's own page, only a ci
assert.deepEqual(making.opened, ["cloud:c-b"], "its own screen, never a saved place or an address");
});
+test("Make … my home: only on a server connected by hand that main offers it for, from the rail's own page, by main's own word for it", async () => {
+ const offered = new Set(["vps"]), made = [];
+ const r = rail({ places: () => railPlaces({ saved: saved("home", [{ id: "box", kind: "remote", name: "Box", origin: "https://box.example.test" }]), home: HOME, mine: HOME, state: session(),
+ offers: entry => offered.has(entry.id) || entry.id === "home" || entry.id === "a" || entry.id === "acme" }), makeHome: id => { made.push(id); return { started: true }; } });
+ const places = (await r.call("workspaces:places")).places;
+ assert.deepEqual(places.filter(place => place.makeHome).map(place => place.id), ["vps"], "never My Cloud, another Cloud or a team's, whatever main says");
+ assert.deepEqual(await r.call("workspaces:make-home", "vps"), { started: true });
+ for (const id of ["box", "home", "a", "acme", "https://box.example.test", { toString: () => "vps" }]) {
+ assert.throws(() => r.call("workspaces:make-home", id), /can't be your bots' home/, String(id));
+ }
+ assert.deepEqual(made, ["vps"]);
+ offered.clear();
+ assert.throws(() => r.call("workspaces:make-home", "vps"), /can't be your bots' home/, "no longer offered: refused");
+ r.w.lists = false;
+ assert.throws(() => r.call("workspaces:make-home", "vps"), /only available/, "any other page: refused");
+ assert.throws(() => rail().call("workspaces:make-home", "vps"), /can't be your bots' home/, "a main that offers it nowhere");
+});
+
const PRELOAD = readFileSync(new URL("./preload.cjs", import.meta.url), "utf8");
function preload(origin, { activation = false } = {}) {
let bridge; const invoked = [];
@@ -300,7 +318,7 @@ function preload(origin, { activation = false } = {}) {
test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {
const page = preload(HOME);
- assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "remove", "onChanged"]);
+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "remove", "makeHome", "onChanged"]);
assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);
await page.bridge.workspaces.places();
await page.bridge.cloudAdd.state();
@@ -314,6 +332,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,
await assert.rejects(page.bridge.workspaces.color("rose"), /Choose a color/, "a page changes its place's colour only from the person's click");
await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);
await assert.rejects(page.bridge.workspaces.remove("old"), /Choose Remove from list/, "Remove from list only from the person's click");
+ await assert.rejects(page.bridge.workspaces.makeHome("vps"), /Choose Make my home/, "a move starts only from the person's click");
await page.bridge.workspaces.look();
assert.deepEqual(page.invoked.at(-1), ["workspaces:look"]);
const clicked = preload(HOME, { activation: true });
diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mts
index 7356898c28..b77edb3eba 100644
--- a/electron/cloud-send-main.d.mts
+++ b/electron/cloud-send-main.d.mts
@@ -24,6 +24,8 @@ export function installCloudSend(deps: {
moveSession?: { open(target: CloudTarget): Promise<CloudSendSession> };
}): {
receive(proc: unknown, message: unknown): boolean;
+ /** This computer's server's private port, asked as a send asks it: another move's sends share it. */
+ handoff(what: { kind: string; [key: string]: unknown }): Promise<any>;
move(options?: { final?: boolean }): Promise<CloudSendOutcome>;
check(): Promise<CloudMoveCheck>;
switches(): Record<string, boolean>;
diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjs
index c126555296..3ba6e22cbd 100644
--- a/electron/cloud-send-main.mjs
+++ b/electron/cloud-send-main.mjs
@@ -144,6 +144,8 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook
return {
receive: handoff.receive,
+ /** This computer's server's private port, asked as a send asks it: another move's sends share it. */
+ handoff: (what) => handoff.request(server(), what),
/** The one-time move to My Cloud (cloud-send.mjs): a pass that carries everything, `final` the one after this computer
* stops, and the check of what arrived. */
move: (options) => send.send({ reason: "move", final: options?.final === true }),
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index 2f16416f61..597a107c17 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -119,7 +119,7 @@ export function createComputerSharing(options: {
busy(): boolean;
saveCloud(env: Workspace, input: { folders: unknown; screen?: boolean; internet?: boolean; chrome?: boolean; terminal?: boolean }, version?: number): Promise<CloudLendingState>;
/** The move's project folders, lent to My Cloud with editing; rejects while that can't happen yet. */
- lendProjects(paths: string[]): Promise<void>;
+ lendProjects(paths: string[], place?: { id: string; origin: string; name: string } | null): Promise<void>;
paused(): boolean;
/** Every Cloud stops using this computer, across restarts too, until resume(). */
pause(): void;
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index 50e0e6ef91..5b6ce4bf84 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -328,9 +328,14 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
if (edits) supportsEdits.add(env.id); else supportsEdits.delete(env.id);
return info;
};
+ /** A server of the person's own their bots moved to: lent as their Clouds are, to its one owner's sign-in alone, at the
+ * server the move chose (lending-target.mjs `own:<environment id>`). */
+ const ownHomeId = env => { const current = cloud(env); return current?.origin === env.origin && current.accountId?.startsWith("own:") ? current.accountId.slice(4) : null; };
const cloudIdentity = async env => {
const { auth, info, details, link, chrome: takesChrome, timeouts, edits } = await describe(env);
- if (auth.cloudHome !== true || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) throw Object.assign(new Error("This server is not My Cloud"), { problem: "not-cloud" });
+ const own = ownHomeId(env);
+ if (own !== null && (auth.own !== true || info.environmentId !== own)) throw Object.assign(new Error("This server is not your bots' home any more"), { problem: "not-cloud" });
+ if ((own === null && auth.cloudHome !== true) || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) throw Object.assign(new Error("This server is not My Cloud"), { problem: "not-cloud" });
if (details) supportsDetails.add(env.id); else supportsDetails.delete(env.id);
if (link) supportsLink.add(env.id); else supportsLink.delete(env.id);
if (takesChrome) supportsChrome.add(env.id); else supportsChrome.delete(env.id);
@@ -585,7 +590,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
run(env, grant);
changed();
};
- const automaticPass = async projects => {
+ const automaticPass = async (projects, target) => {
if (closed || paused || !ownClouds().some(verifiedCloud)) return;
const [[homeFolder = null], screenLent, projectFolders] = await Promise.all([
lendable([{ id: randomUUID(), path: home, write: true, home: true }]),
@@ -596,7 +601,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
const kept = records[env.id], current = verifiedCloud(env);
if (closed || paused || !current) continue;
const keptFolders = kept?.cloud?.accountId === current.accountId && Array.isArray(kept.folders) ? await lendable(kept.folders) : [];
- const wanted = automaticGrant({ kept: keptFolders, home: homeFolder, screen: screenLent, projects: env.id === myCloud()?.id ? projectFolders : [], terminal: terminalAccount === current.accountId });
+ const wanted = automaticGrant({ kept: keptFolders, home: homeFolder, screen: screenLent, projects: env.id === (target ?? myCloud())?.id ? projectFolders : [],
+ terminal: terminalAccount === current.accountId });
if (closed || paused || records[env.id] !== kept) continue;
if (!lendsAsWanted(kept, wanted)) lendNow(env, current, kept, wanted);
else if (!running.has(env.id) && validRecord(kept) && cloudLendingVerdict(kept.cloud, cloud(env), env).allow) run(env, kept);
@@ -606,10 +612,10 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
const lentAutomatically = () => new Set(ownClouds().map(env => env.id));
/** One pass at a time: a change while one runs asks for one more after it. */
let passing = Promise.resolve(), passQueued = false;
- const lendAutomatically = (projects = []) => {
+ const lendAutomatically = (projects = [], target = null) => {
if (passQueued && !projects.length) return passing;
passQueued = true;
- passing = passing.then(() => { passQueued = false; return automaticPass(projects); }).catch(() => {});
+ passing = passing.then(() => { passQueued = false; return automaticPass(projects, target); }).catch(() => {});
return passing;
};
return {
@@ -652,12 +658,13 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
/** A server is using this computer now: a job running on it, or its browsing going through this computer. */
busy: () => summary().busy !== null,
saveCloud,
- /** The move's project folders, lent to My Cloud with editing on top of the rest. It throws while lending to My Cloud
- * can't take them yet (paused, or not signed in there), so the move tries again later. */
- async lendProjects(paths) {
- const env = myCloud();
- if (paused || !env || !verifiedCloud(env)) throw new Error("Lending to My Cloud waits until it is signed in and not paused.");
- await lendAutomatically(Array.isArray(paths) ? paths.filter(where => typeof where === "string") : []);
+ /** The move's project folders, lent to the home it went to (My Cloud unless `place` names a server of the person's own)
+ * with editing on top of the rest. It throws while lending there can't take them yet (paused, or not signed in there),
+ * so the move tries again later. */
+ async lendProjects(paths, place = null) {
+ const env = place ?? myCloud();
+ if (paused || !env || !verifiedCloud(env)) throw new Error("Lending to your bots' home waits until it is signed in and not paused.");
+ await lendAutomatically(Array.isArray(paths) ? paths.filter(where => typeof where === "string") : [], env);
if (records[env.id]?.enabled !== true) throw new Error("Lending to My Cloud did not start.");
},
paused: () => paused,
diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjs
index 7f2fc40134..55312aa862 100644
--- a/electron/fixtures/home-window-world.mjs
+++ b/electron/fixtures/home-window-world.mjs
@@ -18,9 +18,9 @@ export const json = (body, status = 200, headers = {}) => new Response(JSON.stri
* sign-in (its power word, wake, pairing code), My Cloud's answers (`cloud`), the window (where it went), the startup
* screen and a manual clock.
*/
-export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null } = {}) {
+export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null, ownMove = null } = {}) {
const w = {
- journal, marker, state, power, clock: 1_000_000, typed: 0, now: () => w.clock,
+ journal, marker, state, power, ownMove, clock: 1_000_000, typed: 0, now: () => w.clock,
cloud: { down: false, signedIn: true, version: "0.1.130", health: 200, wakes: true, ...cloud },
/** The team's Cloud, answering at TEAM; `gone`: the Admin's team pairing says this person is no longer in it. */
team: { down: false, signedIn: true, version: "0.1.130", health: 200, gone: false, ...team },
@@ -76,6 +76,7 @@ export function world({ journal = done(), marker = null, state = connected(), po
w.home = createHomeWindow({
journal: () => w.journal,
frozen: async () => w.marker,
+ ownMove: () => w.ownMove,
account: () => account,
window: () => w.window,
ensureWindow: () => { w.calls.push("ensure"); },
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index a73b3e5ae7..d1e70ae326 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -189,8 +189,10 @@ export function routeOf(url, origin) {
* timers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void, every(work: () => void, ms: number): unknown },
* hosts?(): { clearHostResolverCache(): Promise<void>, resolveHost(host: string, options?: { cacheUsage?: "allowed" | "staleAllowed" | "disallowed" }): Promise<{ endpoints: unknown[] }> } | null,
* readyStore?: { read(): unknown, write(value: unknown): void },
+ * ownMove?(): { phase: string, name: string } | null,
* log?(line: string): void,
- * }} deps `hosts`: the window's Electron session, for its own resolver and host cache. `readyStore`: when My Cloud
+ * }} deps `ownMove()`: the move to a server of the person's own (own-home-main.mjs), whose freeze is never My Cloud's.
+ * `hosts`: the window's Electron session, for its own resolver and host cache. `readyStore`: when My Cloud
* became ready (createReadyClock). `go(url, origin, place)`: main's one way to move the window, to My Cloud or a team's Cloud (`origin`, with the
* `place` it is) or this computer's screen (null). `showLocal(leaving)`: the window as it was before the move (this computer's page, or a saved server it
* shows); `leaving`: it showed a place or this computer's screen until now, so it goes back to this computer's page.
@@ -204,7 +206,7 @@ export function createHomeWindow(deps) {
const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal,
remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },
splash = () => null, lastInput = () => 0, publish = () => {}, rehomed = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,
- now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, log = () => {} } = deps;
+ now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {} } = deps;
let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;
/** My Cloud asked for before the move made it home (`{ open }`), until its page loads or the person goes elsewhere;
* `naming`: since when, and how often, a brand-new My Cloud's name was not found. */
@@ -234,7 +236,8 @@ export function createHomeWindow(deps) {
let frozenCloud = null;
if (!kept) {
const marker = await frozen().catch(() => null);
- if (marker?.frozen) frozenCloud = typeof marker.cloud === "string" ? marker.cloud : true;
+ // A freeze for a server of the person's own names it (`place`): home is that server, shown as any saved server is.
+ if (marker?.frozen && !marker.place) frozenCloud = typeof marker.cloud === "string" ? marker.cloud : true;
}
if (frozenCloud || awayIn(kept)) await restored();
const before = home;
@@ -252,6 +255,8 @@ export function createHomeWindow(deps) {
if (screen) return named(screen);
if (status) return named({ screen: status });
if (home.kind === "signin" && !name) return { screen: "signin" };
+ const own = ownMove();
+ if (own && MOVING.has(own.phase)) return { screen: "moving", name: own.name };
return named({ screen: MOVING.has(parseJournal(journal())?.phase ?? "") ? "moving" : "opening" });
}
const tell = () => { try { publish(view()); } catch {} };
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index 753091c66a..7e5ce905e5 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -37,6 +37,18 @@ test("a frozen copy with its journal lost counts as moved, to the Cloud it names
assert.deepEqual(homeOf({ journal: { ...done(), phase: "freeze" }, frozenCloud: CLOUD, state: connected() }), { kind: "computer" }, "a move under way is not a move done");
});
+test("a server of the person's own their bots moved to is no Cloud: no sign-in, the window shows it as any saved server, and the frozen screen names it", async () => {
+ const garage = "https://garage.example.test";
+ const w = world({ journal: null, marker: { frozen: true, cloud: garage, place: "Garage server" }, state: { status: "signed-out" }, url: `${garage}/` });
+ await w.home.show();
+ assert.deepEqual([w.local, w.went, w.fetched, w.pairs], [[false], [], [], 0], "never the sign-in screen, nor any Cloud or the Admin asked");
+ assert.equal(w.home.cloudOrigin(), null);
+ const moving = world({ journal: null, marker: { frozen: true, cloud: garage, place: "Garage server" }, state: { status: "signed-out" }, ownMove: { phase: "final", name: "Garage server" } });
+ assert.deepEqual(moving.home.view(), { screen: "moving", name: "Garage server" });
+ moving.ownMove = { phase: "copy", name: "Garage server" };
+ assert.deepEqual(moving.home.view(), { screen: "opening" }, "still home here: nothing is stopped yet");
+});
+
test("a sign-in keeps only a path of My Cloud's own", () => {
assert.equal(routeOf(`${CLOUD}/chats/b1?view=2#x`, CLOUD), "/chats/b1?view=2");
assert.equal(routeOf(`${CLOUD}/`, CLOUD), null);
diff --git a/electron/lend-automatically.node-test.mjs b/electron/lend-automatically.node-test.mjs
index 837c77e374..7700205a26 100644
--- a/electron/lend-automatically.node-test.mjs
+++ b/electron/lend-automatically.node-test.mjs
@@ -76,11 +76,11 @@ function session() {
/** This computer lending to every saved place the way main wires it: the session's own Clouds, its home folder, and
* apps and screen while `screen` says so. */
-async function computer(t, { places = [myCloud, clientA, acme], screen = () => false, home, homes = {}, cuaConnection = async () => null, askForScreen } = {}) {
+async function computer(t, { places = [myCloud, clientA, acme], screen = () => false, home, homes = {}, cuaConnection = async () => null, askForScreen, ownHome } = {}) {
const dir = await scratch(t);
const file = path.join(dir, "profile", "computer-sharing.json");
const signedIn = session();
- const target = createLendingTarget({ account: () => signedIn.account, environments: () => places });
+ const target = createLendingTarget({ account: () => signedIn.account, environments: () => places, ...(ownHome ? { ownHome } : {}) });
const summaries = [];
const dials = [];
const make = () => createComputerSharing({
@@ -116,6 +116,45 @@ test("each Cloud of the person's own is lent this computer by itself: the intern
assert.deepEqual(mac.summaries.at(-1).clouds, ["My Cloud"]);
});
+test("a server of the person's own their bots moved to is lent as their Clouds are, only while it is home, says it is theirs alone and is the server the move chose", async t => {
+ const GARAGE = "https://garage.example.test", garage = { id: "garage", kind: "remote", name: "Garage server", origin: GARAGE };
+ const server = cloudHome({ link: false, chrome: false });
+ const answer = server.fetch;
+ let own = true;
+ server.fetch = async (url, init) => (new URL(url).pathname === "/api/auth/session"
+ ? { ok: true, status: 200, headers: { get: () => null }, body: (async function* () { yield Buffer.from(JSON.stringify({ kind: "session", id: server.sessionId, scopes: ["admin", "client"], ...(own ? { own: true } : {}) })); })() }
+ : answer(url, init));
+ let home = null;
+ const mac = await computer(t, { homes: { [GARAGE]: server }, places: [garage], ownHome: () => home });
+ mac.sharing.start();
+ await delay(100);
+ assert.equal(server.connects.length, 0, "connected by hand and not home: never lent by itself");
+ home = { origin: GARAGE, environmentId: server.environmentId };
+ mac.sharing.cloudChanged();
+ await until(() => server.connects.length === 1, "Garage server to be lent this computer, with no click");
+ assert.equal(server.connects[0].terminal, false);
+ assert.deepEqual(mac.summaries.at(-1).clouds, ["Garage server"], "the menu bar says who can use this computer");
+ mac.sharing.pause();
+ assert.equal(mac.summaries.at(-1).paused, true);
+ await mac.sharing.resume();
+ await until(() => server.connects.length === 2, "lent again on Resume");
+
+ own = false;
+ const strangers = mac.restart();
+ strangers.start();
+ await delay(150);
+ assert.equal(server.connects.length, 2, "a server with other people on it now is never lent");
+ assert.match(strangers.cloudState(garage).error ?? "", /not your bots' home any more/u);
+
+ own = true;
+ const chosen = { origin: GARAGE, environmentId: randomUUID() };
+ const elsewhere = await computer(t, { homes: { [GARAGE]: server }, places: [garage], ownHome: () => chosen });
+ elsewhere.sharing.start();
+ await until(() => elsewhere.sharing.cloudState(garage).error, "the lending to be refused");
+ assert.equal(server.connects.length, 2, "another server behind the same address than the one the move chose is never lent");
+ assert.match(elsewhere.sharing.cloudState(garage).error, /not your bots' home any more/u);
+});
+
test("apps and screen are lent once computer control works here, and follow it", async t => {
const homes = { [HOME]: cloudHome() };
let works = false;
diff --git a/electron/lending-target.d.mts b/electron/lending-target.d.mts
index 49314295e4..11e8a4b069 100644
--- a/electron/lending-target.d.mts
+++ b/electron/lending-target.d.mts
@@ -1,10 +1,12 @@
export function createLendingTarget<E extends { origin: string; cloud?: { id: string } }>(deps: {
account: () => { state(): { status: string; message?: string; account?: { id: string } | null; machine?: { origin?: string } | null }; isOwnCloud?(origin: string): boolean } | null | undefined;
environments: () => E[];
+ /** A server of the person's own their bots moved to, while home is there. */
+ ownHome?: () => { origin: string; environmentId: string } | null;
}): {
/** The sign-in as `env`'s lending checks it: another Cloud of the person's own at its own address, else My Cloud. */
cloud(env?: E | null): { status: string; accountId: string | null; origin: string | null } | null;
environment(): E | null;
- /** The saved places of the person's own Clouds, My Cloud first; never a Team Cloud. */
+ /** The saved places of the person's own Clouds, My Cloud first, and a server of theirs that is home; never a Team Cloud. */
places(): E[];
};
diff --git a/electron/lending-target.mjs b/electron/lending-target.mjs
index d73bb0f82c..514ea5defa 100644
--- a/electron/lending-target.mjs
+++ b/electron/lending-target.mjs
@@ -2,8 +2,10 @@
* origin): `cloud(env)` is the sign-in's state as that saved place's lending checks it (another Cloud of the person's own
* at its own address, any other place against My Cloud), `environment()` the saved server that is My Cloud, kept through
* a brief disconnect of the same account, and `places()` the saved servers that are the person's own Clouds, My Cloud
- * first. Security: never a Team Cloud, nor a server that only signed in with their account (`isOwnCloud`). */
-export function createLendingTarget({ account, environments }) {
+ * first. `ownHome()`: a server of the person's own their bots moved to (own-home-main.mjs), lent as their Clouds are, bound
+ * to that server's identity (`own:<environment id>` as its account), last. Security: never a Team Cloud, nor a server that
+ * only signed in with their account (`isOwnCloud`), nor one connected by hand that the person did not make their home. */
+export function createLendingTarget({ account, environments, ownHome = () => null }) {
let lastHome = null;
const mine = () => {
const current = account();
@@ -16,6 +18,8 @@ export function createLendingTarget({ account, environments }) {
return { status: state.status === "signed-out" && state.message === "restoring" ? "restoring" : state.status, accountId, origin };
};
const cloud = (env = null) => {
+ const own = ownHome();
+ if (own && env?.origin === own.origin) return { status: "connected", accountId: `own:${own.environmentId}`, origin: own.origin };
const base = mine();
if (!base || !env?.cloud || base.origin === env.origin) return base;
return account()?.isOwnCloud?.(env.origin) ? { ...base, origin: env.origin } : base;
@@ -29,9 +33,10 @@ export function createLendingTarget({ account, environments }) {
cloud,
environment,
places() {
- const home = environment();
+ const home = environment(), own = ownHome();
const others = environments().filter((entry) => entry.cloud && entry !== home && account()?.isOwnCloud?.(entry.origin));
- return home ? [home, ...others] : others;
+ const theirs = own ? environments().filter((entry) => entry.origin === own.origin && !entry.cloud && !entry.team && !entry.home) : [];
+ return [...(home ? [home] : []), ...others, ...theirs];
},
};
}
diff --git a/electron/lending-target.node-test.mjs b/electron/lending-target.node-test.mjs
index 759c86e3fa..cb13555e1d 100644
--- a/electron/lending-target.node-test.mjs
+++ b/electron/lending-target.node-test.mjs
@@ -51,3 +51,21 @@ test("this computer is lent to the person's own Clouds only, My Cloud first: nev
state = { status: "signed-out", account: null, machine: null, clouds: [] };
assert.deepEqual(target.places(), [], "signed out: no Cloud of anyone's");
});
+
+test("a server of the person's own is lent only while it is their bots' home, bound to that server's identity, after their Clouds", () => {
+ const home = { id: "home", name: "My Cloud", origin: "https://omb-u-1.fly.dev", home: true };
+ const garage = { id: "g", kind: "remote", name: "Garage server", origin: "https://garage.example.test" };
+ const family = { id: "f", kind: "remote", name: "Family server", origin: "https://family.example.test" };
+ const state = { status: "connected", account: { id: "acct-1" }, machine: { status: "ready", origin: home.origin } };
+ let own = null;
+ const target = createLendingTarget({ account: () => ({ state: () => state, isOwnCloud: (origin) => origin === home.origin }), environments: () => [garage, family, home], ownHome: () => own });
+ assert.deepEqual(target.places().map((place) => place.name), ["My Cloud"], "connected by hand, never lent by itself");
+ assert.equal(target.cloud(garage).origin, home.origin, "checked against My Cloud, so no lending of its own ever passes");
+ own = { origin: garage.origin, environmentId: "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f" };
+ assert.deepEqual(target.places().map((place) => place.name), ["My Cloud", "Garage server"]);
+ assert.deepEqual(target.cloud(garage), { status: "connected", accountId: "own:7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f", origin: garage.origin });
+ assert.equal(target.cloud(family).origin, home.origin);
+ own = null;
+ assert.deepEqual(target.places().map((place) => place.name), ["My Cloud"]);
+ assert.notEqual(target.cloud(garage).accountId?.startsWith("own:"), true, "once it isn't home, the lending bound to it ends");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 5b5ef429cf..fb2baf3249 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -103,7 +103,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClou
import { installCloudFiles } from "./cloud-sync-main.mjs";
import { createCloudEntry } from "./cloud-entry.mjs";
import { createLendingTarget } from "./lending-target.mjs"; import { createOpenAtLogin, installOpenAtLogin } from "./open-at-login.mjs";
-import { installOneHome } from "./one-home-main.mjs";
+import { installOneHome } from "./one-home-main.mjs"; import { installOwnHome } from "./own-home-main.mjs";
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
@@ -269,7 +269,7 @@ let desktopDataDirLease = null;
let runningDataDir = null;
let localSwitchInFlight = false;
let managedDesktop = null;
-let cloudAccount = null, updatesConsent = null, desktopPrefs = null;
+let cloudAccount = null, updatesConsent = null, desktopPrefs = null, ownHome = null;
let cloudAccountStarted = Promise.resolve();
let cloudAccountRestoring = false;
let cloudSignInRestored = false;
@@ -1468,7 +1468,7 @@ function sharingController() {
return computerSharing;
}
-const lendingTarget = createLendingTarget({ account: () => cloudAccount, environments: () => environmentsState.environments });
+const lendingTarget = createLendingTarget({ account: () => cloudAccount, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });
/** Apps and screen are lent once computer control works here, or on a Mac that lacks only macOS's permissions, which
* macOS is asked for the first time a Cloud's bot needs them; read from computer control's running state. */
async function lendsScreen() {
@@ -1524,7 +1524,7 @@ function lendingIndicator() {
async function offerComputerSharing(win) {
const env = activeEnvironment(environmentsState);
if (!env || sharingPrompts.has(env.id) || win.isDestroyed()) return;
- if (env.origin === cloudAccount?.homeTarget()?.origin || cloudAccount?.isOwnCloud(env.origin)) return;
+ if (env.origin === cloudAccount?.homeTarget()?.origin || cloudAccount?.isOwnCloud(env.origin) || env.origin === ownHome?.home()?.origin) return;
if (!(await refreshSharedComputersAllowed()) || win.isDestroyed()) return;
sharingPrompts.add(env.id);
try {
@@ -2664,13 +2664,13 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(
const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });
const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));
const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });
-const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog });
+const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } });
// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.
const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });
const homeWindow = createHomeWindow({ journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,
window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), ensureWindow: () => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); },
localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog,
- hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")),
+ hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")), ownMove: () => ownHome?.underWay() ?? null,
remembered: homePlaces.remembered, remember: homePlaces.remember, left: homePlaces.left, drop: homePlaces.drop,
publish: view => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("home:state-changed", view); },
go: (url, origin, place) => { if (place?.kind === "team" || place?.kind === "own") { activatePlace(place); if (place.kind === "team") teamProfileSeeds.opened(place.origin); } else if (origin) activateCloud(origin); else if (activeEnvironment(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(url); },
@@ -2687,7 +2687,7 @@ function showHome(options) {
}
const openOwnCloud = id => showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } });
// The rail and its + (cloud-rail.mjs): its list for this app's page and hosted Clouds' pages only, opened through switchEnvironment.
-const railList = () => railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin(), mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state() });
+const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true }); };
// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.
const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),
args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],
@@ -2698,7 +2698,7 @@ const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, acc
guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),
lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),
targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],
- places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)),
+ places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id),
add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),
run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });
const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,
@@ -2795,7 +2795,7 @@ ipcMain.handle("workspaces:menu", workspaceOnly(async (_event, from) => {
onConnect: () => void workspaceMenuAction(openWorkspaceSettings),
onForget: (id) => void workspaceMenuAction(() => forgetEnvironment(id)),
...cloudMenuOptions(from === "howto" ? "app_howto" : "app_menu"),
- ...(await placesMenuOptions({ homeOrigin: homeWindow.cloudOrigin(), cloud: cloudHomeEntry(), home: oneHome.away(), platform: process.platform, port: SERVER_PORT })),
+ ...(await placesMenuOptions({ homeOrigin: homeWindow.cloudOrigin(), cloud: cloudHomeEntry(), home: oneHome.away() || ownHome?.away() === true, platform: process.platform, port: SERVER_PORT })),
}));
await new Promise((resolve) => menu.popup({ window: mainWindow, callback: resolve }));
} finally {
@@ -3105,8 +3105,8 @@ app.whenReady().then(async () => {
cloudAccountRestoring = true;
cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).finally(() => { cloudAccountRestoring = false; });
}
- void cloudAccountStarted.then(() => { cloudSignInRestored = true; void oneHome.kick(); void homeWindow.refresh(); });
- if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away()) {
+ void cloudAccountStarted.then(() => { cloudSignInRestored = true; void oneHome.kick(); void homeWindow.refresh(); }); void ownHome?.kick();
+ if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away()) {
// Wait until a saved organisation policy is known: it may turn remote access off.
void (managedDesktop?.whenRestored() ?? Promise.resolve())
.then(() => startDesktopCompanion({ waitForHosted: false, remember: false }))
@@ -3156,7 +3156,7 @@ app.whenReady().then(async () => {
return credentials;
}).finally(syncManagedComposioCredentials);
}
- startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => (oneHome.oneHome.busy() && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
+ startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => ((oneHome.oneHome.busy() || ownHome?.busy()) && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
refreshApplicationMenu();
openWindowForLink = () => {
if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: homeWindow.current().kind !== "computer" });
@@ -3195,7 +3195,7 @@ app.on("before-quit", (e) => {
companyBackupSchedule?.close();
orgLibrary?.close();
managedDesktop?.close();
- cloudAccount?.close(); oneHome.close(); homeWindow.close();
+ cloudAccount?.close(); oneHome.close(); ownHome?.close(); homeWindow.close();
companyBackupController?.abort();
computerSharing?.close();
cloudSync.close();
diff --git a/electron/one-home-main.d.mts b/electron/one-home-main.d.mts
index 95b63c43cc..0abefc5e21 100644
--- a/electron/one-home-main.d.mts
+++ b/electron/one-home-main.d.mts
@@ -36,6 +36,8 @@ export function installOneHome(deps: Omit<SendDeps, "local" | "move" | "moveSess
teamJournal?: { read(): unknown; write(value: unknown): void };
/** The waits of the move's report to the Admin (move-status.mjs), setTimeout's by default. */
reportTimers?: { set(work: () => void, ms: number): unknown; clear(timer: unknown): void };
+ /** The move to a server of the person's own: while it is chosen no move to My Cloud starts, and its line is this computer's page's. */
+ other?(): null | { view(): unknown; seen(): unknown; retry(): Promise<unknown>; active(): boolean };
}): ReturnType<typeof installCloudSend> & {
keep: { state(): KeepHereState; set(on: boolean): Promise<void> };
kick(): Promise<void>;
diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjs
index 5157fd04d3..5a3b4626a0 100644
--- a/electron/one-home-main.mjs
+++ b/electron/one-home-main.mjs
@@ -91,15 +91,18 @@ async function answer(response) {
* teamJournal?: { read(): unknown, write(value: unknown): void },
* keep?: { read(): unknown, write(value: unknown): void },
* reportTimers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void },
+ * other?(): null | { view(): unknown, seen(): unknown, retry(): Promise<unknown>, active(): boolean },
* }} deps `localRequest`: this computer's server, as its owner (main adds the owner's header). `account`: the MausBot
* Cloud sign-in (cloud-account.mjs). `journal`: where the move's journal is kept, journalFile by default; `keep`: the
* person's choice to keep this computer's bots here, one-home-keep.json beside it by default. `openTeam`:
* shows a team's page, where a bot moved into it from My Cloud now lives (team-move-main.mjs, whose journal is
* `teamJournal`, team-moves.json beside this one by default). `reportTimers`: the waits of the move's report to the Admin
- * (move-status.mjs), setTimeout's by default. The rest are installCloudSend's.
+ * (move-status.mjs), setTimeout's by default. `other`: the move to a server of the person's own (own-home-main.mjs):
+ * while it is chosen no move to My Cloud starts, and its line is the one this computer's page shows. The rest are
+ * installCloudSend's.
*/
export function installOneHome({ localRequest, account, journalFile, tempRoot, lend, phone, openHome, openLocal, restart, version, log = () => {}, journal: kept, keep: keptChoice, openTeam, teamJournal,
- reportTimers, ...sendDeps }) {
+ reportTimers, other = () => null, ...sendDeps }) {
const fetchImpl = sendDeps.fetch ?? globalThis.fetch;
let home = null;
let lastInput = 0;
@@ -107,8 +110,8 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, l
let teamMove = null;
// One owner session for the whole move, every pass and check and the switch: each new one is one of the Admin's codes.
const moveSession = createMoveSession({ open: (target) => openOwnerSession(target, fetchImpl, { label: MOVE_LABEL, background: false }) });
- const send = installCloudSend({ ...sendDeps, local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(30_000) }), move: () => home, teamMove: () => teamMove,
- moveSession });
+ const send = installCloudSend({ ...sendDeps, local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(30_000) }),
+ move: () => (home?.view() === null && other()?.view() ? other() : home), teamMove: () => teamMove, moveSession });
teamMove = installTeamMove({ ipcMain: sendDeps.ipcMain, cloudPage: sendDeps.cloudPage, home: sendDeps.home, account: () => account(), fetch: fetchImpl, openTeam,
file: () => join(dirname(journalFile()), "team-move-send.json"), journalFile: () => join(dirname(journalFile()), "team-moves.json"), ...(teamJournal ? { journal: teamJournal } : {}),
onChange: () => send.publish(), log });
@@ -191,7 +194,7 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, l
home = createOneHome({
journal,
// Every run starts here: the key watch is set up before any wait asks, so a key pressed since then counts.
- cloud: () => { typed(); return oneHomeCloud(account()?.state()); },
+ cloud: () => { typed(); const cloud = oneHomeCloud(account()?.state()); return cloud && other()?.active() ? { ...cloud, moves: false } : cloud; },
send,
local: {
...local,
diff --git a/electron/one-home-main.node-test.mjs b/electron/one-home-main.node-test.mjs
index ef6f034526..44da4b83e1 100644
--- a/electron/one-home-main.node-test.mjs
+++ b/electron/one-home-main.node-test.mjs
@@ -90,3 +90,31 @@ test("the freeze's answer carries what holds the move, by name or, with none, wh
assert.deepEqual(freezeAnswer({ ok: true, status: 200, body: { frozen: true } }), { frozen: true });
assert.throws(() => freezeAnswer({ ok: false, status: 500, body: {} }), /could not pause/u);
});
+
+test("while a server of the person's own is chosen as home, no move to My Cloud starts, and this computer's page shows that move's line", async () => {
+ const handlers = new Map();
+ const install = (other) => {
+ let kept = null;
+ const main = installOneHome({
+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, cloudPage: () => "local", server: () => null, home: () => null, cookieFetch: async () => json({}, 401),
+ reconnect: async () => false, power: { asleep: () => false }, file: () => "/nonexistent/cloud-send.json", window: () => null, localOrigin: () => "http://127.0.0.1:4100",
+ fetch: async () => json({}, 404), localRequest: async (route) => (route === "/api/move/freeze" ? json({ frozen: false }) : json({}, 404)),
+ account: () => ({ state: () => ({ status: "connected", account: { id: "acct-1" }, machine: { status: "ready", origin: "https://omb-u-1.fly.dev", moves: true } }),
+ pairHome: async () => { throw new Error("no code in this test"); } }),
+ journalFile: () => "/nonexistent/one-home.json", tempRoot: () => "/nonexistent", journal: { read: () => kept, write: (value) => { kept = value; } }, other,
+ });
+ return { main, journal: () => kept };
+ };
+ const own = { active: () => true, view: () => ({ phase: "copy", place: "Garage server" }), seen: () => null, retry: async () => {} };
+ const chosen = install(() => own);
+ try {
+ await chosen.main.kick();
+ assert.equal(chosen.journal(), null, "My Cloud's move never starts");
+ assert.deepEqual((await handlers.get("cloud-send:notice")({})).move, { phase: "copy", place: "Garage server" });
+ } finally { chosen.main.close(); }
+ const none = install(() => null);
+ try {
+ await none.main.kick();
+ assert.equal(none.journal()?.cloud.origin, "https://omb-u-1.fly.dev", "without one, My Cloud's move starts as before");
+ } finally { none.main.close(); }
+});
diff --git a/electron/one-home.d.mts b/electron/one-home.d.mts
index 4444e54866..c8d6118713 100644
--- a/electron/one-home.d.mts
+++ b/electron/one-home.d.mts
@@ -1,5 +1,7 @@
-/** The line either page shows for the one-time move to My Cloud (one-home.mjs). */
-export type OneHomeView =
+/** The line either page shows for the one-time move to My Cloud (one-home.mjs), or to a server of the person's own, named
+ * `place`. */
+export type OneHomeView = OneHomePhase & { place?: string };
+type OneHomePhase =
/** `chats`: conversations gone of those to go; `failing`: it has failed for a day, with why; `updating`: My Cloud is too old
* to take a move and updates first. */
| { phase: "copy"; chats?: { done: number; total: number }; failing?: { error: string | null }; updating?: true }
@@ -20,6 +22,8 @@ export interface OneHomeCounts { bots: number; skills: number; logins: number; o
export interface OneHomeCloud {
origin: string | null; account: string; machine: string | null; ready: boolean; moves: boolean; ended: boolean; paid: boolean;
+ /** A server of the person's own, by the name they know it by: the move's line and the frozen copy say it. */
+ name?: string;
/** The computer an ended Cloud's things come home to, by installation (one-home-main.mjs `installationOf`). */
homecoming?: { installationId: string; name: string };
/** This app's sign-in (the Admin's device id), while connected. */
diff --git a/electron/one-home.mjs b/electron/one-home.mjs
index 81830a7ed5..9d5f56597c 100644
--- a/electron/one-home.mjs
+++ b/electron/one-home.mjs
@@ -189,8 +189,14 @@ export function createOneHome(deps) {
};
/** What the line on either page says: the phase, its progress, who it waits for, a day of failing, the done line
- * until it is closed, and coming home. Null when there is nothing to say. */
+ * until it is closed, and coming home; `place`, a server of the person's own the move goes to, by its name. Null when
+ * there is nothing to say. */
function view() {
+ const seen = phaseView(), place = read()?.cloud?.name;
+ return seen && typeof place === "string" ? { ...seen, place } : seen;
+ }
+
+ function phaseView() {
const journal = read();
if (!journal || journal.paused || (journal.told && journal.phase !== "keeping")) return null;
if (journal.phase === "done") return { phase: "done", ...(Number.isSafeInteger(journal.doneAt) ? { at: journal.doneAt } : {}), ...(journal.counts ? { counts: journal.counts } : {}), phone: journal.phone === true, held: journal.held ?? [] };
@@ -314,7 +320,7 @@ export function createOneHome(deps) {
}
const computer = sentence((await deps.local.json("/api/cloud-connections").catch(() => null))?.computer?.label) ?? "this computer";
const webhooks = Object.keys(switches).flatMap((key) => (key.startsWith("webhook:") ? [key.slice("webhook:".length)] : []));
- const arrived = await session.call("POST", "/api/cloud-send/arrived", { v: 1, computer, webhooks });
+ const arrived = await session.call("POST", "/api/cloud-send/arrived", { v: 1, computer, webhooks, ...(journal.cloud.name ? { place: journal.cloud.name } : {}) });
if (!arrived.ok) throw tagged(sentence(arrived.body?.error) ?? "My Cloud did not finish the move.", "switch_refused", { status: arrived.status });
} catch (error) {
log(`one home: switching over goes on later (${error?.message ?? error})`);
@@ -546,7 +552,7 @@ export function createOneHome(deps) {
// A frozen server with no move under way is one this app no longer knows about: it is never lifted blindly.
noted = await deps.local.frozen().then((frozen) => (frozen ? "frozen_without_move" : null), () => "local_unavailable");
if (noted) { log(`one home: ${noted === "frozen_without_move" ? "this computer is frozen with no move under way" : "this computer's server did not say whether it is frozen"}`); return; }
- journal = write({ v: 1, phase: "copy", cloud: { origin: cloud.origin, account: cloud.account, machine: cloud.machine }, startedAt: now() });
+ journal = write({ v: 1, phase: "copy", cloud: { origin: cloud.origin, account: cloud.account, machine: cloud.machine, ...(cloud.name ? { name: cloud.name } : {}) }, startedAt: now() });
}
if (journal.thaw && !(await thaw(journal))) return;
journal = read() ?? journal;
diff --git a/electron/own-home-main.d.mts b/electron/own-home-main.d.mts
new file mode 100644
index 0000000000..681dae06ee
--- /dev/null
+++ b/electron/own-home-main.d.mts
@@ -0,0 +1,63 @@
+import type { OneHomeView } from "./one-home.mjs";
+
+/** A server of the person's own as their bots' home, chosen once. */
+export interface OwnHomeChoice { v: 1; id: string; origin: string; environmentId: string; name: string; at: number }
+/** A saved place, as main keeps it (environments.cjs). */
+export interface SavedPlace { id: string; kind: string; name: string; origin?: string; home?: true; team?: unknown; cloud?: unknown }
+type Answer = { ok: boolean; status: number; body: any };
+
+export declare const OWNER_KNOWN_MS: number;
+export function parseChoice(value: unknown): OwnHomeChoice | null;
+export function handSaved(entry: unknown): entry is SavedPlace & { kind: "remote"; origin: string };
+export function serverRequests(place: { origin: string }, fetchImpl: typeof fetch): {
+ request(method: string, route: string, init?: RequestInit): Promise<Response>;
+ call(method: string, route: string, body?: unknown): Promise<Answer>;
+ /** The server's word on this window's sign-in there. */
+ who(): Promise<{ signedIn: boolean; own: boolean; environmentId: string | null; takesMove: boolean; status: number }>;
+};
+export function openServerSession(chosen: OwnHomeChoice, fetchImpl: typeof fetch): Promise<{
+ call(method: string, route: string, body?: unknown): Promise<Answer>;
+ upload(route: string, bytes: Uint8Array, type: string): Promise<Answer>;
+ fetch(route: string, init?: RequestInit): Promise<Response>;
+ close(): Promise<void>;
+}>;
+
+export function installOwnHome(deps: {
+ /** This computer's server, as its owner. */
+ localRequest(route: string, init?: RequestInit): Promise<Response>;
+ /** This window's own requests, with its sign-ins. */
+ fetch: typeof fetch;
+ environments(): SavedPlace[];
+ /** This computer's server's private port, which hands a moving secret to main alone. */
+ handoff(what: { kind: string; [key: string]: unknown }): Promise<any>;
+ journal: { read(): unknown; write(value: unknown): void };
+ choice: { read(): unknown; write(value: unknown): void };
+ sendState: { read(): unknown; write(value: unknown): void };
+ /** The move to My Cloud's journal. */
+ cloudJournal(): unknown;
+ lend?(projects: string[], place: SavedPlace | null): Promise<unknown>;
+ phone?: { paired(): boolean; stop(): Promise<void>; start(): Promise<void> };
+ openHome?(place: SavedPlace): void;
+ lastInput?(): number;
+ version?: string;
+ onChange?(): void;
+ now?(): number;
+ log?(line: string): void;
+}): {
+ kick(): Promise<void>;
+ view(): OneHomeView | null;
+ seen(): OneHomeView | null;
+ retry(): Promise<void>;
+ busy(): boolean;
+ away(): boolean;
+ active(): boolean;
+ origin(): string | null;
+ underWay(): { phase: string; name: string } | null;
+ home(): { id: string; origin: string; environmentId: string; name: string } | null;
+ offers(place: unknown): boolean;
+ refresh(): void;
+ start(id: string): Promise<{ started: true }>;
+ close(): void;
+ journal(): unknown;
+ chosen(): OwnHomeChoice | null;
+};
diff --git a/electron/own-home-main.mjs b/electron/own-home-main.mjs
new file mode 100644
index 0000000000..8b126bf10c
--- /dev/null
+++ b/electron/own-home-main.mjs
@@ -0,0 +1,248 @@
+// The one-time move that makes a server of the person's own their only home, as My Cloud is: chosen once on that server's
+// circle ("Make … my home"), then run by one-home.mjs over cloud-send.mjs, which carry everything, stop this computer for
+// good and switch on there what was on here, so no routine ever runs in two places. Every pass goes over this window's own
+// sign-in at that server, as the person's: never a sign-in of its own, and never signed out here.
+//
+// Security: only a server that says this sign-in is its one owner's (server/own-home.ts) is ever chosen or written to, and
+// the choice is bound to that server's identity, so another server behind the same address takes nothing of this
+// computer's and is never lent it.
+import { createCloudSend } from "./cloud-send.mjs";
+import { freezeAnswer } from "./one-home-main.mjs";
+import { awayIn, createOneHome, parseJournal } from "./one-home.mjs";
+
+const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
+const ORIGIN = /^https?:\/\/[^/\s]+$/u;
+const ENVIRONMENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
+/** How long a server's word on who owns it is kept for the rail. */
+export const OWNER_KNOWN_MS = 10 * 60_000;
+/** A chosen move that could not begin (this computer's server did not answer) looks again this often. */
+const START_RETRY_MS = 30_000;
+
+const tagged = (message, code, extra = {}) => Object.assign(new Error(message), { code, ...extra });
+
+async function answer(response) {
+ const text = await response.text();
+ try { return { ok: response.ok, status: response.status, body: text ? JSON.parse(text) : null }; }
+ catch { return { ok: response.ok, status: response.status, body: null }; }
+}
+
+/** The person's choice of home, read back; null when there is none or it is damaged. */
+export function parseChoice(value) {
+ if (!record(value) || value.v !== 1 || typeof value.id !== "string" || typeof value.origin !== "string" || !ORIGIN.test(value.origin)
+ || typeof value.environmentId !== "string" || !ENVIRONMENT_ID.test(value.environmentId) || typeof value.name !== "string" || !value.name.trim()) return null;
+ return value;
+}
+
+/** A saved place that is a server the person connected by hand: never This computer, My Cloud or a team's Cloud. */
+export const handSaved = (entry) => record(entry) && entry.kind === "remote" && typeof entry.origin === "string" && !entry.home && !entry.team && !entry.cloud;
+
+/**
+ * This window's sign-in at a server, as one request after another: the session cookie, same-origin. `who()` is that
+ * server's word on it: its identity, and whether it is this person's own.
+ * @param {{ origin: string }} place
+ * @param {typeof fetch} fetchImpl
+ */
+export function serverRequests(place, fetchImpl) {
+ const request = (method, route, init = {}) => fetchImpl(`${place.origin}${route}`, {
+ method, redirect: "error", credentials: "include", cache: "no-store", signal: AbortSignal.timeout(120_000), ...init,
+ headers: { accept: "application/json", origin: place.origin, ...init.headers },
+ });
+ return {
+ request,
+ call: async (method, route, body) => answer(await request(method, route, body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) })),
+ async who() {
+ const [session, described] = await Promise.all([request("GET", "/api/auth/session").then(answer), request("GET", "/.well-known/openmausbot/environment").then(answer)]);
+ const signedIn = session.ok && session.body?.kind === "session";
+ return { signedIn, own: signedIn && session.body.own === true, environmentId: typeof described.body?.environmentId === "string" ? described.body.environmentId : null,
+ takesMove: Number(described.body?.capabilities?.move) >= 1, status: session.status };
+ },
+ };
+}
+
+/** The move's session at the chosen server: this window's own sign-in, checked to be its owner's, at the server chosen. */
+export async function openServerSession(chosen, fetchImpl) {
+ const server = serverRequests(chosen, fetchImpl);
+ const who = await server.who();
+ if (!who.signedIn) throw tagged(`This app isn't signed in to ${chosen.name}. Open ${chosen.name} in this app, then try again.`, "signed_out", { status: who.status === 403 ? 403 : 401 });
+ if (who.environmentId !== chosen.environmentId) throw tagged(`The server at ${chosen.name}'s address is another one now, so nothing more goes there.`, "other_server");
+ if (!who.own) throw tagged(`${chosen.name} has other people on it now, so your bots can't move there.`, "not_own");
+ return {
+ call: server.call,
+ upload: async (route, bytes, type) => answer(await server.request("POST", route, { headers: { "content-type": type }, body: bytes })),
+ fetch: (route, init = {}) => server.request(init.method ?? "GET", route, { ...init, headers: init.headers ?? {} }),
+ close: async () => {},
+ };
+}
+
+function jsonStore(store) {
+ return { read: () => { try { return store.read(); } catch { return null; } }, write: (value) => store.write(value) };
+}
+
+/**
+ * @param {{
+ * localRequest(route: string, init?: RequestInit): Promise<Response>,
+ * fetch: typeof fetch,
+ * environments(): any[],
+ * handoff(what: { kind: string, [key: string]: unknown }): Promise<any>,
+ * journal: { read(): unknown, write(value: unknown): void },
+ * choice: { read(): unknown, write(value: unknown): void },
+ * sendState: { read(): unknown, write(value: unknown): void },
+ * cloudJournal(): unknown,
+ * lend?(projects: string[], place: any): Promise<unknown>,
+ * phone?: { paired(): boolean, stop(): Promise<void>, start(): Promise<void> },
+ * openHome?(place: any): void,
+ * lastInput?(): number,
+ * version?: string,
+ * onChange?(): void,
+ * now?(): number,
+ * log?(line: string): void,
+ * }} deps `localRequest`: this computer's server, as its owner. `fetch`: this window's own requests, with its sign-ins.
+ * `handoff`: this computer's server's private port, which hands a moving secret to main alone. `cloudJournal()`: the move
+ * to My Cloud's journal: while it is under way or done, no server of the person's own is chosen.
+ */
+export function installOwnHome({ localRequest, fetch: fetchImpl, environments, handoff, journal: journalStore, choice: choiceStore, sendState, cloudJournal, lend, phone, openHome, lastInput,
+ version, onChange = () => {}, now = Date.now, log = () => {} }) {
+ const journal = jsonStore(journalStore), choice = jsonStore(choiceStore);
+ const chosen = () => parseChoice(choice.read());
+ const placeOf = (picked = chosen()) => (picked ? environments().find((entry) => handSaved(entry) && entry.origin === picked.origin) ?? null : null);
+ const owners = new Map();
+
+ const local = {
+ call: async (method, route, body) => answer(await localRequest(route, { method, signal: AbortSignal.timeout(120_000),
+ ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) })),
+ async json(route) {
+ const got = await local.call("GET", route);
+ if (!got.ok) throw new Error("OpenMausBot on this computer did not answer. Try again in a moment.");
+ return got.body;
+ },
+ };
+ const send = createCloudSend({
+ local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(30_000) }),
+ cloud: {
+ origin: () => chosen()?.origin ?? null,
+ asleep: () => false,
+ read: (route) => serverRequests(chosen(), fetchImpl).request("GET", route),
+ open: () => openServerSession(chosen(), fetchImpl),
+ },
+ handoff,
+ store: jsonStore(sendState),
+ onChange: () => onChange(),
+ });
+ /** The chosen server as the move sees a Cloud: always ready, never ended once home is there, since nothing ends it; until
+ * then, a server forgotten in this app ends the move before anything runs there. */
+ const target = () => {
+ const picked = chosen();
+ if (!picked) return null;
+ return { origin: picked.origin, account: `own:${picked.environmentId}`, machine: picked.origin, ready: true, moves: true, paid: false, name: picked.name,
+ ended: !placeOf(picked) && !awayIn(parseJournal(journal.read())) };
+ };
+ const home = createOneHome({
+ journal,
+ cloud: target,
+ send: { move: (options) => send.send({ reason: "move", final: options?.final === true }), check: () => send.check(), switches: () => send.switches(), snapshot: () => send.snapshot() },
+ local: {
+ ...local,
+ freeze: async (origin) => freezeAnswer(await local.call("POST", "/api/move/freeze", { cloud: origin, place: chosen()?.name })),
+ async unfreeze(options) {
+ const got = await local.call("DELETE", "/api/move/freeze", options?.automations === "off" ? { automations: "off" } : undefined);
+ if (!got.ok) throw Object.assign(new Error("OpenMausBot on this computer could not go on again."), { status: got.status });
+ },
+ frozen: async () => (await local.json("/api/move/freeze"))?.frozen === true,
+ },
+ session: () => openServerSession(chosen(), fetchImpl),
+ ...(lend ? { lend: (projects) => lend(projects, placeOf()) } : {}),
+ ...(phone ? { phone } : {}),
+ openHome: () => { const place = placeOf(); if (place) openHome?.(place); },
+ ...(lastInput ? { lastInput } : {}),
+ ...(version ? { version } : {}),
+ onChange: () => onChange(),
+ log,
+ });
+
+ /** The server's own word on whether this window's sign-in there is its one owner's, kept OWNER_KNOWN_MS. */
+ async function owner(place) {
+ try {
+ const who = await serverRequests(place, fetchImpl).who();
+ const known = { own: who.own && who.takesMove && who.environmentId !== null, environmentId: who.environmentId, at: now() };
+ const before = owners.get(place.id);
+ owners.set(place.id, known);
+ if (before?.own !== known.own) onChange();
+ return known;
+ } catch (error) {
+ log(`own home: ${place.name} did not say who owns it (${error?.message ?? error})`);
+ owners.delete(place.id);
+ return { own: false, environmentId: null, at: now() };
+ }
+ }
+ const moving = () => { const kept = parseJournal(journal.read()); return Boolean(kept) && kept.phase !== "back"; };
+ const cloudMoving = () => { const kept = parseJournal(cloudJournal()); return Boolean(kept) && kept.phase !== "back"; };
+ let retry = null;
+ /** Goes on with the move; a choice whose server was forgotten here before anything ran there is let go of, and one whose
+ * move could not begin yet begins once it can. */
+ async function kick() {
+ if (retry) { clearTimeout(retry); retry = null; }
+ await home.kick();
+ const picked = chosen();
+ if (!picked || moving()) return;
+ if (!placeOf(picked)) { choice.write(null); onChange(); return; }
+ retry = setTimeout(() => { retry = null; void kick().catch((error) => log(`own home: ${error?.message ?? error}`)); }, START_RETRY_MS);
+ retry.unref?.();
+ }
+
+ return {
+ kick,
+ view: () => home.view(),
+ seen: () => home.seen(),
+ retry: () => home.retry(),
+ busy: () => home.busy(),
+ /** Home is the chosen server: its switch happened. */
+ away: () => home.away(),
+ /** A server of the person's own is chosen as home: no move to My Cloud starts. */
+ active: () => Boolean(chosen()),
+ /** The chosen server's address while home is there: This computer is no place of its own then. */
+ origin: () => (home.away() ? chosen()?.origin ?? null : null),
+ /** The move under way, by its phase and the server's name: this computer's own screen says it while it is stopped. */
+ underWay() {
+ const kept = parseJournal(journal.read()), picked = chosen();
+ return kept && picked && !awayIn(kept) && kept.phase !== "back" ? { phase: kept.phase, name: picked.name } : null;
+ },
+ /** The chosen server while home is there: this computer is lent to it as it is to My Cloud. */
+ home() {
+ const picked = chosen(), place = placeOf(picked);
+ return picked && place && home.away() ? { id: place.id, origin: picked.origin, environmentId: picked.environmentId, name: place.name } : null;
+ },
+ /** A server whose circle may offer "Make … my home": connected by hand, its own word that it is this person's alone (read
+ * again now and then, `refresh`), and no move under way or done, to it or to My Cloud. */
+ offers(place) {
+ if (!handSaved(place) || moving() || chosen() || cloudMoving()) return false;
+ const known = owners.get(place.id);
+ return Boolean(known?.own) && now() - known.at < OWNER_KNOWN_MS;
+ },
+ /** Asks each server connected by hand who owns it, unless it said so lately. */
+ refresh() {
+ for (const place of environments().filter(handSaved)) {
+ const known = owners.get(place.id);
+ if (!known || now() - known.at >= OWNER_KNOWN_MS) void owner(place);
+ }
+ },
+ /** The person chose this server as their home: asked once more, then the move starts. */
+ async start(id) {
+ const place = environments().find((entry) => entry.id === id && handSaved(entry));
+ if (!place) throw new Error("That server isn't in this app any more.");
+ if (moving() || chosen()) throw new Error("Your bots are already moving.");
+ if (cloudMoving()) throw new Error("Your bots are moving to My Cloud.");
+ const who = await serverRequests(place, fetchImpl).who().catch(() => null);
+ if (!who?.signedIn) throw new Error(`This app isn't signed in to ${place.name}. Open ${place.name} in this app, then try again.`);
+ if (!who.own) throw new Error(`${place.name} has other people on it, so your bots stay here. Only a server that's yours alone can be your bots' home.`);
+ if (!who.takesMove || !who.environmentId) throw new Error(`Update OpenMausBot on ${place.name} first, then try again.`);
+ choice.write({ v: 1, id: place.id, origin: place.origin, environmentId: who.environmentId, name: place.name, at: now() });
+ onChange();
+ void kick().catch((error) => log(`own home: ${error?.message ?? error}`));
+ return { started: true };
+ },
+ close() { if (retry) clearTimeout(retry); retry = null; home.close(); },
+ journal: () => journal.read(),
+ /** The person's choice, as kept. */
+ chosen,
+ };
+}
diff --git a/electron/own-home-main.node-test.mjs b/electron/own-home-main.node-test.mjs
new file mode 100644
index 0000000000..a489fc185a
--- /dev/null
+++ b/electron/own-home-main.node-test.mjs
@@ -0,0 +1,137 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { handSaved, installOwnHome, openServerSession, OWNER_KNOWN_MS, parseChoice } from "./own-home-main.mjs";
+
+const ID = "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f";
+const garage = { id: "g", kind: "remote", name: "Garage server", origin: "https://garage.example.test" };
+const family = { id: "f", kind: "remote", name: "Family server", origin: "https://family.example.test" };
+
+function memory(initial = null) {
+ let value = initial;
+ return { read: () => value, write: (next) => { value = next; } };
+}
+
+/** Servers as their own routes answer this window's sign-in: `own` by their own word, `move` when they take one. */
+function servers(answers) {
+ const asked = [];
+ const fetch = async (url, init) => {
+ const { origin, pathname } = new URL(url);
+ asked.push({ origin, path: pathname, headers: init?.headers ?? {} });
+ const server = answers[origin];
+ if (!server) return new Response("", { status: 502 });
+ if (pathname === "/api/auth/session") return Response.json(server.signedIn === false ? { error: "unauthorized" } : { kind: "session", scopes: ["admin"], ...(server.own ? { own: true } : {}) }, { status: server.signedIn === false ? 401 : 200 });
+ if (pathname === "/.well-known/openmausbot/environment") return Response.json({ environmentId: server.environmentId ?? ID, capabilities: server.move === false ? {} : { move: 1 } });
+ return new Response("", { status: 404 });
+ };
+ return { fetch, asked };
+}
+
+function install({ answers, cloudJournal = null, journal = null, choice = null, now = () => 1_000 }) {
+ const { fetch, asked } = servers(answers);
+ const changes = [];
+ const own = installOwnHome({
+ localRequest: async () => new Response("", { status: 503 }),
+ fetch,
+ environments: () => [garage, family, { id: "home", kind: "remote", name: "My Cloud", origin: "https://omb-u-1.fly.dev", home: true }],
+ handoff: async () => null,
+ journal: memory(journal),
+ choice: memory(choice),
+ sendState: memory(),
+ cloudJournal: () => cloudJournal,
+ onChange: () => changes.push(1),
+ now,
+ });
+ return { own, asked, changes };
+}
+
+test("a choice is kept only whole: the server's address, identity and name", () => {
+ const good = { v: 1, id: "g", origin: garage.origin, environmentId: ID, name: "Garage server", at: 1 };
+ assert.equal(parseChoice(good), good);
+ for (const broken of [{ ...good, origin: "https://garage.example.test/pair" }, { ...good, environmentId: "not-an-id" }, { ...good, name: " " }, { ...good, v: 2 }, null]) {
+ assert.equal(parseChoice(broken), null);
+ }
+});
+
+test("only a server connected by hand can be made home: never This computer, My Cloud or a team's Cloud", () => {
+ assert.equal(handSaved(garage), true);
+ for (const place of [{ id: "local", kind: "local", name: "This computer" }, { ...garage, home: true }, { ...garage, cloud: { id: "c" } }, { ...garage, team: { id: "t" } }]) {
+ assert.equal(handSaved(place), false);
+ }
+});
+
+test("a server's circle offers Make my home only once it said it is this person's alone, while that word is fresh and nothing moves", async () => {
+ let at = 1_000;
+ const { own, changes } = install({ answers: { [garage.origin]: { own: true }, [family.origin]: { own: false } }, now: () => at });
+ assert.equal(own.offers(garage), false, "not asked yet");
+ own.refresh();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.equal(own.offers(garage), true);
+ assert.equal(own.offers(family), false, "others sign in there");
+ assert.ok(changes.length > 0, "the rail hears that its word changed");
+ at += OWNER_KNOWN_MS;
+ assert.equal(own.offers(garage), false, "an old word is asked again first");
+ own.close();
+
+ const moving = install({ answers: { [garage.origin]: { own: true } }, cloudJournal: { v: 1, phase: "copy", cloud: { origin: "https://omb-u-1.fly.dev", account: "acct" } } });
+ moving.own.refresh();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.equal(moving.own.offers(garage), false, "this computer's bots are on their way to My Cloud");
+ moving.own.close();
+});
+
+test("starting asks the server once more, and keeps this computer's bots here when it isn't theirs alone, isn't signed in or is too old", async () => {
+ const cases = [
+ [{ own: false }, "Garage server has other people on it, so your bots stay here."],
+ [{ signedIn: false }, "This app isn't signed in to Garage server."],
+ [{ own: true, move: false }, "Update OpenMausBot on Garage server first"],
+ ];
+ for (const [answer, words] of cases) {
+ const { own } = install({ answers: { [garage.origin]: answer } });
+ await assert.rejects(own.start("g"), (error) => error.message.includes(words));
+ assert.equal(own.chosen(), null);
+ own.close();
+ }
+ const cloud = install({ answers: { [garage.origin]: { own: true } }, cloudJournal: { v: 1, phase: "done", cloud: { origin: "https://omb-u-1.fly.dev", account: "acct" } } });
+ await assert.rejects(cloud.own.start("g"), /moving to My Cloud/u);
+ cloud.own.close();
+ const unknown = install({ answers: {} });
+ await assert.rejects(unknown.own.start("home"), /isn't in this app/u, "My Cloud is never made home this way");
+ unknown.own.close();
+
+ const { own, asked } = install({ answers: { [garage.origin]: { own: true } } });
+ assert.deepEqual(await own.start("g"), { started: true });
+ assert.deepEqual({ ...own.chosen(), at: 0 }, { v: 1, id: "g", origin: garage.origin, environmentId: ID, name: "Garage server", at: 0 });
+ assert.ok(asked.every((ask) => ask.origin === garage.origin && ask.headers.origin === garage.origin), "only that server, same-origin, with the window's sign-in");
+ assert.equal(own.active(), true, "no move to My Cloud starts now");
+ await assert.rejects(own.start("g"), /already moving/u);
+ own.close();
+});
+
+test("each pass goes over the window's sign-in only to the server chosen, while it is still that person's alone, and never signs it out", async () => {
+ const chosen = { v: 1, id: "g", origin: garage.origin, environmentId: ID, name: "Garage server", at: 1 };
+ const session = await openServerSession(chosen, servers({ [garage.origin]: { own: true } }).fetch);
+ await session.close();
+ await assert.rejects(openServerSession(chosen, servers({ [garage.origin]: { own: true, environmentId: "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a" } }).fetch), (error) => error.code === "other_server");
+ await assert.rejects(openServerSession(chosen, servers({ [garage.origin]: { own: false } }).fetch), (error) => error.code === "not_own" && /other people on it now/u.test(error.message));
+ await assert.rejects(openServerSession(chosen, servers({ [garage.origin]: { signedIn: false } }).fetch), (error) => error.code === "signed_out" && error.status === 401);
+ const { fetch, asked } = servers({ [garage.origin]: { own: true } });
+ await (await openServerSession(chosen, fetch)).close();
+ assert.ok(!asked.some((ask) => ask.path === "/api/auth/logout"), "the window's own sign-in stays");
+});
+
+test("while the move goes, this computer's screen names the server; once home is there, This computer is no place of its own", () => {
+ const choice = { v: 1, id: "g", origin: garage.origin, environmentId: ID, name: "Garage server", at: 1 };
+ const cloud = { origin: garage.origin, account: `own:${ID}`, machine: garage.origin, name: "Garage server" };
+ const moving = install({ answers: {}, choice, journal: { v: 1, phase: "final", cloud } });
+ assert.deepEqual(moving.own.underWay(), { phase: "final", name: "Garage server" });
+ assert.equal(moving.own.origin(), null);
+ assert.equal(moving.own.home(), null, "nothing is lent before the switch");
+ moving.own.close();
+ const done = install({ answers: {}, choice, journal: { v: 1, phase: "done", cloud, doneAt: 1 } });
+ assert.equal(done.own.underWay(), null);
+ assert.equal(done.own.origin(), garage.origin);
+ assert.deepEqual(done.own.home(), { id: "g", origin: garage.origin, environmentId: ID, name: "Garage server" });
+ assert.equal(done.own.offers(garage), false);
+ done.own.close();
+});
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 4fd1e8eda6..e356695167 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -148,6 +148,9 @@ const bridge = {
// Remove from list, for a Cloud the window's rail lists as removable, from a click on the rail's own page (main refuses any other page).
remove: (id) => isLocalPage || navigator.userActivation?.isActive === true
? ipcRenderer.invoke("workspaces:remove", String(id)) : Promise.reject(new Error("Choose Remove from list.")),
+ // Make a server of the person's own their bots' home, from a click on the rail's own page (main refuses any other page).
+ makeHome: (id) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:make-home", String(id)) : Promise.reject(new Error("Choose Make my home.")),
onChanged: (cb) => {
const handler = () => cb();
ipcRenderer.on("workspaces:changed", handler);
diff --git a/one-home-preview.html b/one-home-preview.html
new file mode 100644
index 0000000000..7c46999ecc
--- /dev/null
+++ b/one-home-preview.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>One Home Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/one-home-preview.tsx"></script>
+ </body>
+</html>
diff --git a/scripts/testing/own-home-fixture.ts b/scripts/testing/own-home-fixture.ts
new file mode 100644
index 0000000000..a80e96922e
--- /dev/null
+++ b/scripts/testing/own-home-fixture.ts
@@ -0,0 +1,200 @@
+// This computer's server, started as the desktop app starts it (its private port emulated over Node's IPC), and servers of
+// the person's own (`openmausbot serve`, nothing of MausBot Cloud), each paired with this app as a pairing link pairs it.
+// Main's own wiring for the move to such a server (electron/own-home-main.mjs) sits between them, its requests carrying
+// the pairing's session as the window's would. Disposable homes and a synthetic Claude CLI; no network.
+import { randomBytes } from "node:crypto";
+import { spawn, type ChildProcess } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { createLoginHandoffClient } from "../../electron/cloud-logins.mjs";
+import { installOwnHome } from "../../electron/own-home-main.mjs";
+import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";
+import { freePortBlock } from "../../server/testing/ports.ts";
+
+const SERVER_DIR = fileURLToPath(new URL("../../server/", import.meta.url));
+const parse = (text: string) => { try { return JSON.parse(text); } catch { return null; } };
+type Answer = { status: number; body: any };
+type Side = (method: string, path: string, body?: unknown) => Promise<Answer>;
+
+export interface OwnServer {
+ name: string;
+ base: string;
+ dataDir: string;
+ /** This app's sign-in there: a pairing's session, as the window holds it. */
+ token: string;
+ /** A request as that sign-in. */
+ as: Side;
+ /** The saved place this app keeps for it (environments.cjs). */
+ place: { id: string; kind: "remote"; name: string; origin: string };
+}
+
+export interface OwnHomeFixture {
+ root: string;
+ desktopBase: string;
+ desktopDataDir: string;
+ local: Side;
+ /** A server of the person's own, added and paired; `env`: more of its environment (a sign-in list, say). */
+ addServer(name: string, env?: NodeJS.ProcessEnv): Promise<OwnServer>;
+ /** Main's move to a server of the person's own, as the app that is open now runs it. */
+ main: ReturnType<typeof installOwnHome>;
+ /** Its journal, and a look at each write before it lands: throwing there is the app killed. */
+ journalFile: string;
+ beforeJournalWrite: ((value: any) => void) | null;
+ /** What main asked for besides: the project folders lent with the place, the phone link, and the place opened. */
+ spies: { lent: Array<{ projects: string[]; place: string | null }>; phoneStops: number; opened: string[] };
+ /** The app quits or is killed: its main wiring stops, this computer's server is killed, and both start again. */
+ relaunch(options?: { kill?: boolean }): Promise<void>;
+ /** The fetch main's requests go through: the saved places' sign-ins, as the window's session carries them. */
+ windowFetch: typeof fetch;
+ logs(): string;
+ close(): Promise<void>;
+}
+
+export async function launchOwnHomeFixture({ env = {} }: { env?: NodeJS.ProcessEnv } = {}): Promise<OwnHomeFixture> {
+ const root = mkdtempSync(join(tmpdir(), "omb-own-home-"));
+ const children = new Set<ChildProcess>();
+ let logs = "";
+
+ async function start(name: string, own: NodeJS.ProcessEnv, port: number, extra: string[] = [], ipc = false): Promise<ChildProcess> {
+ const home = join(root, name);
+ const dataDir = join(home, ".openmausbot");
+ mkdirSync(dataDir, { recursive: true });
+ const cli = join(home, "fixture-claude.mjs");
+ writeFileSync(cli, `#!/usr/bin/env node
+if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" })); process.exit(0); }
+process.env.FAKE_CLAUDE_VERSION = "2.1.284";
+process.env.FAKE_CLAUDE_FIXTURE_DIR = ${JSON.stringify(home)};
+await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});
+`, { mode: 0o755 });
+ try { readFileSync(join(dataDir, "config.json")); } catch {
+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({ instances: {
+ ...Object.fromEntries(["codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi"].map((id) => [id, { driver: "not-a-real-driver" }])),
+ claude: { driver: "claudeAgent", displayName: "Claude", config: { cli } },
+ } }));
+ }
+ const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;
+ const child = spawn(process.execPath, ["--import", offline, ...extra, join(SERVER_DIR, "index.ts")], {
+ cwd: join(SERVER_DIR, ".."),
+ env: { PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir,
+ OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), ...env, ...own },
+ stdio: ["ignore", "pipe", "pipe", ...(ipc ? ["ipc" as const] : [])],
+ });
+ children.add(child);
+ child.on("close", () => children.delete(child));
+ child.stdout?.on("data", (chunk) => { logs += chunk; });
+ child.stderr?.on("data", (chunk) => { logs += chunk; });
+ const deadline = Date.now() + 30_000;
+ for (;;) {
+ if (child.exitCode !== null) throw new Error(`${name} exited:\n${logs}`);
+ try { if ((await fetch(`http://127.0.0.1:${port}/api/health`)).ok) return child; } catch {}
+ if (Date.now() > deadline) throw new Error(`${name} did not start:\n${logs}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ }
+
+ const parentPort = `data:text/javascript,${encodeURIComponent(`
+ const listeners = [];
+ Object.defineProperty(process, "parentPort", { value: {
+ on(event, listener) { if (event === "message") listeners.push(listener); },
+ postMessage(message) { process.send?.(message); },
+ } });
+ process.on("message", (data) => { for (const listener of listeners) listener({ data }); });
+ process.channel?.unref();
+ `)}`;
+ const capability = randomBytes(32).toString("base64url");
+ const desktopPort = await freePortBlock([0, 1]);
+ const desktopBase = `http://127.0.0.1:${desktopPort}`;
+ const startDesktop = async () => {
+ const child = await start("desktop", { OMB_DESKTOP_PARENT: "1", OMB_ENVIRONMENT_LABEL: "Work laptop" }, desktopPort, ["--import", parentPort], true);
+ child.send({ type: "openmausbot:desktop-mutation-token", token: capability });
+ return child;
+ };
+ let desktop = await startDesktop();
+ const local: Side = async (method, path, body) => {
+ const response = await fetch(`${desktopBase}${path}`, { method, headers: { "x-openmausbot-desktop-owner": capability, ...(body === undefined ? {} : { "content-type": "application/json" }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ return { status: response.status, body: parse(await response.text()) };
+ };
+ const ready = async () => { for (let tries = 0; (await local("GET", "/api/bots")).status !== 200 && tries < 50; tries++) await new Promise((resolve) => setTimeout(resolve, 100)); };
+ await ready();
+
+ const servers: OwnServer[] = [];
+ /** The window's own requests: each saved place's sign-in goes only to that place. */
+ const windowFetch = (async (url: string | URL | Request, init: RequestInit = {}) => {
+ const server = servers.find((candidate) => String(url).startsWith(`${candidate.base}/`));
+ const headers = { ...(init.headers as Record<string, string>), ...(server ? { authorization: `Bearer ${server.token}` } : {}) };
+ return fetch(url, { ...init, headers });
+ }) as typeof fetch;
+
+ async function addServer(name: string, more: NodeJS.ProcessEnv = {}): Promise<OwnServer> {
+ const port = await freePortBlock([0, 1]);
+ const base = `http://127.0.0.1:${port}`;
+ await start(`server-${servers.length + 1}`, { OMB_ENVIRONMENT_LABEL: name, ...more }, port);
+ // `openmausbot pair` on that server, then the link opened in this app: a session of the admin scope.
+ const minted = await fetch(`${base}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: "My desktop" }) });
+ const code = (await minted.json() as { code: string }).code;
+ const paired = await fetch(`${base}/api/auth/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, label: "OpenMausBot app" }) });
+ const token = (await paired.json() as { token: string }).token;
+ if (typeof token !== "string") throw new Error(`could not pair with ${name}`);
+ const as: Side = async (method, path, body) => {
+ const response = await fetch(`${base}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ return { status: response.status, body: parse(await response.text()) };
+ };
+ const server: OwnServer = { name, base, dataDir: join(root, `server-${servers.length + 1}`, ".openmausbot"), token, as,
+ place: { id: `place-${servers.length + 1}`, kind: "remote", name, origin: base } };
+ servers.push(server);
+ return server;
+ }
+
+ const journalFile = join(root, "own-home.json");
+ const file = (name: string) => ({
+ read: () => JSON.parse(readFileSync(join(root, name), "utf8")),
+ write: (value: unknown) => { if (name === "own-home.json") fixture.beforeJournalWrite?.(value); writeFileSync(join(root, `${name}.tmp`), JSON.stringify(value ?? null)); renameSync(join(root, `${name}.tmp`), join(root, name)); },
+ });
+ const fixture = { beforeJournalWrite: null as OwnHomeFixture["beforeJournalWrite"] };
+ const spies: OwnHomeFixture["spies"] = { lent: [], phoneStops: 0, opened: [] };
+ const asks = createLoginHandoffClient();
+ const port = { postMessage: (message: unknown) => { desktop.send(message as object); } };
+ const wire = () => installOwnHome({
+ localRequest: (route, init = {}) => fetch(`${desktopBase}${route}`, { ...init, headers: { ...init.headers as Record<string, string>, "x-openmausbot-desktop-owner": capability } }),
+ fetch: windowFetch,
+ environments: () => servers.map((server) => server.place),
+ handoff: (what) => asks.request(port, what as never),
+ journal: file("own-home.json"),
+ choice: file("own-home-choice.json"),
+ sendState: file("own-home-send.json"),
+ cloudJournal: () => null,
+ lend: async (projects, place) => { spies.lent.push({ projects, place: place?.origin ?? null }); },
+ phone: { paired: () => true, stop: async () => { spies.phoneStops++; }, start: async () => {} },
+ openHome: (place) => { spies.opened.push(place.origin ?? ""); },
+ lastInput: () => 0,
+ version: "0.1.135",
+ log: (line) => { logs += `[main] ${line}\n`; },
+ });
+ let main = wire();
+ const listen = () => { desktop.on("message", (message) => { asks.receive(port, message); }); };
+ listen();
+
+ return {
+ root, desktopBase, desktopDataDir: join(root, "desktop", ".openmausbot"), local, addServer, journalFile, spies, windowFetch, logs: () => logs,
+ get main() { return main; },
+ get beforeJournalWrite() { return fixture.beforeJournalWrite; },
+ set beforeJournalWrite(hook) { fixture.beforeJournalWrite = hook; },
+ async relaunch({ kill = true } = {}) {
+ main.close();
+ await waitForExit(desktop, { signal: kill ? "SIGKILL" : "SIGTERM" });
+ desktop = await startDesktop();
+ await ready();
+ main = wire();
+ listen();
+ },
+ async close() {
+ main.close();
+ for (const child of children) await waitForExit(child, { signal: "SIGTERM" });
+ await removeTempDir(root);
+ },
+ };
+}
diff --git a/server/cloud-connections-host.ts b/server/cloud-connections-host.ts
index cf370c632b..ff893857c1 100644
--- a/server/cloud-connections-host.ts
+++ b/server/cloud-connections-host.ts
@@ -7,11 +7,13 @@ import { answerConnection, connectionFingerprints, highlevelDigest, launchersOnP
import { createConnectionPrompt, type ConnectionPromptBot } from "./cloud-connections-prompt.ts";
import { movedFrom } from "./cloud-send-arrived.ts";
import * as composio from "./composio.ts";
+import { brokerAccess } from "./composio-broker-access.ts";
import { adoptComposioShare, adoptOwnComposio, composioIdentity, composioShareCode } from "./composio-share.ts";
import type { AppConfig } from "./config.ts";
import type { HighLevelService } from "./highlevel/service.ts";
import type { ConnectionHandoffAnswer, ConnectionHandoffWhat } from "./login-handoff.ts";
import type { McpOAuthManager } from "./mcp-oauth.ts";
+import type { RequestAuth } from "./request-auth.ts";
import { isRemoteMcpServer, parseStoredMcpServer, type McpRunsOn } from "./mcp-registry.ts";
import { personalConnectionRefusal, type CloudTeam } from "./cloud-team.ts";
import { createCloudConnectionRoutes } from "./routes/cloud-connections.ts";
@@ -19,6 +21,8 @@ import { createCloudConnectionRoutes } from "./routes/cloud-connections.ts";
export interface CloudConnectionsHostDeps {
/** This server is the person's Cloud home, reached at this public origin. */
cloudHome: { publicOrigin: string; team?: CloudTeam | null } | null;
+ /** A server of one person's own takes that person's connections as a Cloud home does. */
+ ownHome?(auth: RequestAuth): boolean;
config(): AppConfig;
/** This server's own environment id: the computer a server that needs it is marked as running on. */
environmentId: string;
@@ -32,6 +36,8 @@ export interface CloudConnectionsHostDeps {
dataDir?: string;
}
+const managedService = (): boolean => { try { return brokerAccess() !== null; } catch { return false; } };
+
export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {
const label = (process.env.OMB_ENVIRONMENT_LABEL?.trim() || hostname()).slice(0, 120).trim() || "the person's computer";
const computer: McpRunsOn = { environmentId: deps.environmentId, label };
@@ -52,9 +58,11 @@ export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {
fingerprints: (nonce: string) => connectionFingerprints(nonce, sources()),
routes: createCloudConnectionRoutes({
cloudHome: deps.cloudHome !== null,
+ ...(deps.ownHome ? { ownHome: deps.ownHome } : {}),
...(deps.cloudHome?.team ? { personalRefusal: (what: string) => personalConnectionRefusal(deps.cloudHome!.team!, what) } : {}),
async list() {
- return { computer, connections: await connections(), engines: await deps.engines().catch((): string[] => []), commands: commands ??= launchersOnPath() };
+ return { computer, connections: await connections(), engines: await deps.engines().catch((): string[] => []), commands: commands ??= launchersOnPath(),
+ ...(deps.cloudHome === null && !managedService() ? { managedApps: false as const } : {}) };
},
adoptShare: adoptComposioShare,
adoptOwn: (apiKey, userId) => adoptOwnComposio(deps.config(), apiKey, userId),
diff --git a/server/cloud-send-arrived.ts b/server/cloud-send-arrived.ts
index cf4d63f984..93b1056071 100644
--- a/server/cloud-send-arrived.ts
+++ b/server/cloud-send-arrived.ts
@@ -26,8 +26,9 @@ export function movedFrom(dataDir: string): MovedFrom | null {
} catch { return null; }
}
-export const webhookMovedLine = (name: string) =>
- `Now that I live on My Cloud, my webhook "${name}" has a new address. Open Automations, choose Copy address on "${name}", and paste it into the app that sends to it.`;
+/** `place`: the server of the person's own the bot moved to, by the name they know it by; My Cloud without one. */
+export const webhookMovedLine = (name: string, place = "My Cloud") =>
+ `Now that I live on ${place}, my webhook "${name}" has a new address. Open Automations, choose Copy address on "${name}", and paste it into the app that sends to it.`;
export const webhookHomeLine = (name: string) =>
`I'm back on this computer, so my webhook "${name}" has an address here again. Open Automations, choose Copy address on "${name}", and paste it into the app that sends to it.`;
@@ -39,7 +40,8 @@ export interface ArrivedDeps {
owner(auth: RequestAuth): CloudOwner | null;
}
-const arrivedBody = z.object({ v: z.literal(1), computer: z.string().trim().min(1).max(120), webhooks: z.array(z.string().regex(/^[\w-]{1,128}$/u)).max(500) });
+const arrivedBody = z.object({ v: z.literal(1), computer: z.string().trim().min(1).max(120), webhooks: z.array(z.string().regex(/^[\w-]{1,128}$/u)).max(500),
+ place: z.string().trim().min(1).max(120).optional() });
/** False when the path is not this route. */
export async function arrivedRoute(deps: ArrivedDeps, { req, res, path, method, auth, json, readBody }: RouteContext): Promise<boolean> {
@@ -60,7 +62,7 @@ export async function arrivedRoute(deps: ArrivedDeps, { req, res, path, method,
for (const { id } of telling) told.add(id);
// Recorded before the lines go: a move cut short here never has a bot say it twice.
writeFileAtomic(join(deps.dataDir, FILE), JSON.stringify({ computer: body.data.computer, at: kept?.at ?? Date.now(), told: [...told] }), { mode: 0o600 });
- for (const line of telling) deps.store.appendMessage(line.threadId, { role: "bot", kind: "text", text: webhookMovedLine(line.name) });
+ for (const line of telling) deps.store.appendMessage(line.threadId, { role: "bot", kind: "text", text: webhookMovedLine(line.name, body.data.place) });
json(res, 200, { v: 1, told: telling.length });
return true;
}
diff --git a/server/environment.test.ts b/server/environment.test.ts
index 3c75e3228f..0c2e2e9a3c 100644
--- a/server/environment.test.ts
+++ b/server/environment.test.ts
@@ -133,7 +133,9 @@ describe("environment identity", () => {
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true }).capabilities)
.toEqual({ remoteSessions: true, cloudHome: true, move: 1, selfUpdate: "operator", 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 takes a move").not.toHaveProperty("move");
+ 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", emailSignIn: false, jobs: true });
+ 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, fileEdits: true, deviceLink: true, myChromeLink: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
diff --git a/server/environment.ts b/server/environment.ts
index bb59dd765e..c41038fae7 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -38,8 +38,9 @@ export interface EnvironmentDescriptor {
cloudHome?: true;
/** A team's Cloud home: `label` is the team's name. */
cloudTeam?: true;
- /** A Cloud home that takes the one-time move from the person's computer: by-row chats, the manifest, the chats and
- * credentials checks, and lines its owner wrote there stamped as the owner's. */
+ /** A Cloud home, or a server one person owns, that takes the one-time move from that person's computer: by-row chats,
+ * 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;
/** Who can update the server: the desktop app that runs it, or the operator. */
selfUpdate: "desktop-managed" | "operator";
@@ -127,7 +128,7 @@ export function serverVersion(root = SERVER_ROOT): string {
return "unknown";
}
-export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; label?: string }): EnvironmentDescriptor {
+export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor {
return {
environmentId: input.environmentId,
label: input.label?.trim() || process.env.OMB_ENVIRONMENT_LABEL?.trim() || hostname(),
@@ -141,6 +142,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan
...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),
...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: 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 ? { cloudTeam: true as const } : {}),
selfUpdate: input.desktopManaged ? "desktop-managed" : "operator",
emailSignIn: input.emailSignIn === true,
diff --git a/server/index.ts b/server/index.ts
index c830edea76..874af6c009 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -18,7 +18,7 @@ import { RoomContextTracker, roomResetNote } from "./room-context.ts";
import { createRoomTranscript, GROUP_CONTEXT_MESSAGES } from "./host/room-transcript.ts";
import { createRoomSessions } from "./host/room-sessions.ts";
import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerOperation } from "./shared-computers.ts"; import { lentScreenResult } from "./lent-screen-guidance.ts"; import { DeviceLinks } from "./device-links.ts";
-import { cloudHomeLendingRefusal, createCloudRoutineAuthors, ownerOnlyConversation } from "./cloud-lending.ts"; import { assertRoomFolder } from "./room-folder.ts"; import { cloudConnectedAppsBrokerUrl, startCloudHomeConnectedApps, stopCloudHomeConnectedApps } from "./cloud-connected-apps.ts"; import { createTeamConnectionsHost } from "./host/team-connections-host.ts"; import { createCloudLendingTurns } from "./host/cloud-lending-turns.ts"; import { createTeamConnectionRoutes } from "./routes/team-connections.ts";
+import { cloudHomeLendingRefusal, createCloudRoutineAuthors, ownerOnlyConversation } from "./cloud-lending.ts"; import { createOwnHome } from "./own-home.ts"; import { assertRoomFolder } from "./room-folder.ts"; import { cloudConnectedAppsBrokerUrl, startCloudHomeConnectedApps, stopCloudHomeConnectedApps } from "./cloud-connected-apps.ts"; import { createTeamConnectionsHost } from "./host/team-connections-host.ts"; import { createCloudLendingTurns } from "./host/cloud-lending-turns.ts"; import { createTeamConnectionRoutes } from "./routes/team-connections.ts";
import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";
import { SharedComputerControl } from "./shared-computer-control.ts";
import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";
@@ -688,7 +688,7 @@ const CLOUD_TEAM = CLOUD_HOME?.team ?? null, CLOUD_PERSONAL = CLOUD_HOME !== nul
const appLanguage = (): string | undefined => cfg.language ?? CLOUD_TEAM?.language; const personLanguages = createPersonLanguages({ dataDir: DATA_DIR, configured: appLanguage });
if (CLOUD_HOME) repairMovedWorkspacePaths(DATA_DIR);
if (CLOUD_PERSONAL) sessions.requireAdmin(CLOUD_PERSONAL_REFUSAL);
-const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null;
+const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null || ownHome.here();
const CLOUD_HOME_LENDER = "cloud-home";
/** Owner-written routines and owner-started runs: the only routine turns that may use a lent Mac. */
const cloudRoutineAuthors = CLOUD_HOME ? createCloudRoutineAuthors(join(DATA_DIR, "lending-routines.json")) : null;
@@ -851,7 +851,7 @@ function personNameIn(threadId: string): string | undefined {
function sharedMembership(): boolean {
return CLOUD_TEAM !== null || hostedWorkspaceConfiguration()?.portalMembership === true || signInAllowList().members.length > 0;
-}
+} const ownHome = createOwnHome({ dataDir: DATA_DIR, facts: () => ({ managed: CLOUD_HOME !== null || HOSTED_WORKSPACE, shared: sharedMembership(), admins: signInAllowList().admins }) });
/** Everyone is "user" where one person uses the workspace; where several do, each reacts as their own key. */
function reactorFor(auth: RequestAuth): Reactor {
@@ -2880,7 +2880,7 @@ const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, stor
const routineHolds = CLOUD_HOME ? createRoutineHoldsHost({ dataDir: DATA_DIR, store, mcpServers: () => Object.keys(cfg.mcpServers ?? {}).length, log: (line) => console.warn(line),
appsConnected: async () => composio.configured(cfg) ? Object.values(await composio.connectedServices(cfg)).some((service) => service.connected) : false }) : null;
const skillsHost = createSkillsLibraryHost({ store, cfg, appendSkillRequestCard, engineConfig: (instanceId) => providerConfigs()[instanceId], instanceOf: (instanceId) => { const instance = registry.get(instanceId); return instance ? { instanceId, driverKind: instance.driverKind } : undefined; } });
-const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) });
+const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) });
const highlevelHost = createHighLevelHost({ service: highlevel, dataDir: DATA_DIR, bot: (id) => store.bot(id),
inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); } });
const phones = createPhones({
@@ -12365,7 +12365,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") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, 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), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, 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 }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, 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: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
@@ -12754,7 +12754,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// Two public routes come first; everything else needs the loopback owner or a paired session with the right scope.
if (method === "GET" && !path.startsWith("/api/") && !path.startsWith("/.well-known/") && (moveFreeze.screen(path) ? (res.writeHead(302, { location: moveFreeze.screen(path)!, "cache-control": "no-store" }).end(), true) : serveStatic(res, path, STATIC_DIR))) return;
if (method === "GET" && path === "/.well-known/openmausbot/environment") {
- return json(res, 200, environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !HOSTED_WORKSPACE && !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null }));
+ return json(res, 200, environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !HOSTED_WORKSPACE && !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }));
}
const domainCheck = /^\/\.well-known\/openmausbot\/domain-check\/([a-f0-9]{64})$/.exec(path);
if (method === "GET" && domainCheck) {
@@ -12824,7 +12824,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, result.status, { error: result.error });
}
if (CLOUD_TEAM) teamHost.met(result.session);
- const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null });
+ const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() });
if (wantsCookie) {
const previous = browser ? sessions.authenticate(parseCookies(req.headers.cookie).get(SESSION_COOKIE)) : null;
if (previous && previous.id !== result.session.id) sessions.revoke(previous.id);
@@ -12935,7 +12935,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
...(auth.session.email ? { email: auth.session.email } : {}),
...(auth.session.owner ? { owner: auth.session.owner } : {}),
...(HOSTED_WORKSPACE ? { hosted: true } : {}),
- ...(CLOUD_HOME ? { cloudHome: true } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
+ ...(CLOUD_HOME ? { cloudHome: true } : {}), ...(ownHome.owner(auth) ? { own: true } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
...(CLOUD_PERSONAL && !cloudOwnerSession(auth) ? { cloudGuest: true, openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
...(reactorFor(auth).by !== "user" ? { reactor: reactorFor(auth).by } : {}),
},
diff --git a/server/move-freeze.test.ts b/server/move-freeze.test.ts
index 96862fad27..485c1c3453 100644
--- a/server/move-freeze.test.ts
+++ b/server/move-freeze.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL, RAIL_PAGE, switchAutomationsOff, type MoveAutomations } from "./move-freeze.ts";
+import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL, movedRefusal, RAIL_PAGE, switchAutomationsOff, type MoveAutomations } from "./move-freeze.ts";
import type { MoveWait } from "./move-waits.ts";
import { createMoveFreezeRoutes } from "./routes/move-freeze.ts";
import { PASS } from "./routes/table.ts";
@@ -153,6 +153,19 @@ describe("/api/move/freeze", () => {
expect(await ask(route, "POST", "/api/bots/b1/messages")).toBe("pass");
});
+ it("a move to a server of the person's own names it: every refusal says where the bots live now, across a restart too", async () => {
+ const dir = dataDir();
+ const route = createMoveFreezeRoutes({ freeze: createMoveFreeze({ dataDir: dir }), busy: () => null, restart() {} });
+ expect(await ask(route, "POST", undefined, { cloud: "https://garage.example.test", place: "Garage server" })).toEqual({ status: 200, body: { frozen: true } });
+ expect(await ask(route, "GET")).toEqual({ status: 200, body: { frozen: true, cloud: "https://garage.example.test", place: "Garage server" } });
+ expect(await ask(route, "POST", "/api/bots/b1/messages")).toEqual({ status: 409, body: { error: "This bot lives on Garage server now.", code: "moved" } });
+ const relaunched = createMoveFreeze({ dataDir: dir });
+ expect([relaunched.place(), relaunched.refusal()]).toEqual(["Garage server", movedRefusal("Garage server")]);
+ expect(relaunched.unfreeze()).toBe(true);
+ expect([relaunched.place(), movedRefusal(null)]).toEqual([null, MOVED_REFUSAL]);
+ expect(await ask(route, "POST", undefined, { cloud: "https://garage.example.test", place: "x".repeat(121) }), "a name past 120 characters").toMatchObject({ status: 400 });
+ });
+
it("is only for OpenMausBot on this computer, never a paired device", async () => {
const freeze = createMoveFreeze({ dataDir: dataDir() });
const route = createMoveFreezeRoutes({ freeze, busy: () => null, restart() {} });
diff --git a/server/move-freeze.ts b/server/move-freeze.ts
index 0e956c39f8..b1950ca8d3 100644
--- a/server/move-freeze.ts
+++ b/server/move-freeze.ts
@@ -14,6 +14,8 @@ import type { WaitManager } from "./waits.ts";
import type { WebhookManager } from "./webhooks.ts";
export const MOVED_REFUSAL = "This bot lives on My Cloud now.";
+/** Why a frozen copy refuses, naming the server of the person's own its bots moved to (`place`), else My Cloud. */
+export const movedRefusal = (place: string | null): string => (place ? `This bot lives on ${place} now.` : MOVED_REFUSAL);
/** The one page a frozen copy serves: the desktop app's screen while My Cloud can't be opened (electron/home-window.mjs). */
export const HOME_SCREEN = "/home";
/** The desktop window's own rail of places (electron/chrome-rail.mjs): this app's page, beside whichever place is open. */
@@ -66,12 +68,13 @@ export async function switchAutomationsOff(automations: MoveAutomations, only?:
export function createMoveFreeze({ dataDir, exportOnly = false }: { dataDir: string; exportOnly?: boolean }) {
const file = join(dataDir, "moved.json");
let frozen = exportOnly || existsSync(file);
- const named = (): string | null => {
- try { const value: unknown = JSON.parse(readFileSync(file, "utf8")); const cloud = Reflect.get(Object(value), "cloud"); return typeof cloud === "string" ? cloud : null; } catch { return null; }
+ const named = (field: "cloud" | "place"): string | null => {
+ try { const value: unknown = JSON.parse(readFileSync(file, "utf8")); const named = Reflect.get(Object(value), field); return typeof named === "string" ? named : null; } catch { return null; }
};
- let movedTo = frozen && !exportOnly ? named() : null;
+ let movedTo = frozen && !exportOnly ? named("cloud") : null;
+ let place = frozen && !exportOnly ? named("place") : null;
const held: Array<{ start(): void; stop(): void }> = [];
- const refusal = () => (frozen ? (exportOnly ? ENDED_REFUSAL : MOVED_REFUSAL) : null);
+ const refusal = () => (frozen ? (exportOnly ? ENDED_REFUSAL : movedRefusal(place)) : null);
const each = (step: "start" | "stop") => {
for (const work of held) {
try { work[step](); } catch (error) { console.warn(`move freeze: could not ${step} a schedule (${(error as Error).message})`); }
@@ -82,6 +85,8 @@ export function createMoveFreeze({ dataDir, exportOnly = false }: { dataDir: str
frozen: () => frozen,
/** The Cloud this computer's bots moved to, as the freeze named it. */
cloud: () => movedTo,
+ /** The server of the person's own this computer's bots moved to, by the name they know it by; null for My Cloud. */
+ place: () => place,
refusal,
/** Where a page of this computer's frozen copy goes instead: its home screen, never the frozen workspace. The
* window's rail stays the rail: it shows no workspace, only the places main lists. */
@@ -102,11 +107,12 @@ export function createMoveFreeze({ dataDir, exportOnly = false }: { dataDir: str
refuses(method: string, path: string): string | null {
return frozen && !READS.has(method.toUpperCase()) && !STILL_CHANGES.test(path) ? refusal() : null;
},
- freeze(cloud: string | null): void {
+ freeze(cloud: string | null, named: string | null = null): void {
if (frozen) return;
- writeFileAtomic(file, JSON.stringify({ v: 1, at: Date.now(), ...(cloud ? { cloud } : {}) }), { mode: 0o600 });
+ writeFileAtomic(file, JSON.stringify({ v: 1, at: Date.now(), ...(cloud ? { cloud } : {}), ...(named ? { place: named } : {}) }), { mode: 0o600 });
frozen = true;
movedTo = cloud;
+ place = named;
each("stop");
},
/** Deletes this computer's copy of the workspace, credentials included, once the move is long done; only a computer
@@ -125,6 +131,7 @@ export function createMoveFreeze({ dataDir, exportOnly = false }: { dataDir: str
rmSync(file, { force: true });
frozen = false;
movedTo = null;
+ place = null;
each("start");
return true;
},
diff --git a/server/own-home.e2e.test.ts b/server/own-home.e2e.test.ts
new file mode 100644
index 0000000000..52f2e7978c
--- /dev/null
+++ b/server/own-home.e2e.test.ts
@@ -0,0 +1,162 @@
+// A server of the person's own made their bots' home, end to end: this computer's server and two servers of the person's own
+// (scripts/testing/own-home-fixture.ts), one theirs alone and one with other people on it, with main's own wiring for the
+// move (electron/own-home-main.mjs) and this computer's real lending (electron/computer-sharing.mjs). Disposable homes; no
+// network.
+import { mkdirSync, mkdtempSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { createComputerSharing } from "../electron/computer-sharing.mjs";
+import { createLendingTarget } from "../electron/lending-target.mjs";
+import { launchOwnHomeFixture, type OwnHomeFixture, type OwnServer } from "../scripts/testing/own-home-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+import { movedRefusal } from "./move-freeze.ts";
+import { webhookMovedLine } from "./cloud-send-arrived.ts";
+
+let fx: OwnHomeFixture;
+let garage: OwnServer, family: OwnServer;
+
+beforeAll(async () => {
+ fx = await launchOwnHomeFixture();
+ garage = await fx.addServer("Garage server");
+ family = await fx.addServer("Family server", { OMB_SIGNIN_MEMBER_EMAILS: "[email protected]" });
+}, hostTimeout(120_000));
+afterAll(async () => { await fx?.close(); });
+
+type Side = OwnHomeFixture["local"];
+type Row = { id: string; role: string; text?: string };
+type Run = { id: string; routineId: string; scheduledFor: number; createdAt: number; manual?: boolean; triggerSource?: string };
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+const journal = () => { try { return JSON.parse(readFileSync(fx.journalFile, "utf8")) as { phase: string; doneAt?: number } | null; } catch { return null; } };
+async function rows(side: Side, threadId: string): Promise<Row[]> {
+ return ((await side("GET", `/api/threads/${threadId}/messages?limit=500`)).body?.messages ?? []) as Row[];
+}
+const idle = async (side: Side) => (await side("GET", "/api/bots")).body.bots.every((entry: { activity?: string; busy?: boolean }) => entry.activity !== "working" && !entry.busy);
+async function turn(side: Side, bot: { id: string; threadId: string }, text: string) {
+ const before = (await rows(side, bot.threadId)).length;
+ expect((await side("POST", `/api/bots/${bot.id}/messages`, { text, threadId: bot.threadId })).status).toBe(202);
+ await expect.poll(async () => await idle(side) && (await rows(side, bot.threadId)).length >= before + 2, { timeout: 60_000, interval: 100 }).toBe(true);
+}
+const routines = async (side: Side) => (await side("GET", "/api/routines")).body as { routines: Array<{ id: string; enabled: boolean }>; runs: Run[] };
+
+it("only a server that is the person's alone says it is theirs, takes a move and is offered as their bots' home", async () => {
+ expect((await garage.as("GET", "/api/auth/session")).body).toMatchObject({ kind: "session", own: true });
+ expect((await family.as("GET", "/api/auth/session")).body.own, "others sign in there").toBeUndefined();
+ const described = async (server: OwnServer) => ((await (await fetch(`${server.base}/.well-known/openmausbot/environment`)).json()) as { capabilities: { move?: number } }).capabilities;
+ expect((await described(garage)).move).toBe(1);
+ expect((await described(family)).move).toBeUndefined();
+
+ fx.main.refresh();
+ await expect.poll(() => fx.main.offers(garage.place), { timeout: 10_000, interval: 100 }).toBe(true);
+ expect(fx.main.offers(family.place)).toBe(false);
+
+ // Asked anyway, the shared one keeps this computer's bots here, and its move routes refuse this sign-in.
+ await expect(fx.main.start(family.place.id)).rejects.toThrow("Family server has other people on it, so your bots stay here.");
+ expect(fx.main.chosen()).toBeNull();
+ expect((await family.as("POST", "/api/cloud-send/memory", { v: 1, about: "", teams: [] })).status).toBe(403);
+ expect((await family.as("POST", "/api/cloud-send/arrived", { v: 1, computer: "Work laptop", webhooks: [] })).status).toBe(404);
+ expect((await family.as("PUT", "/api/cloud-connections/highlevel", {})).status).toBe(404);
+ // Garage server takes them from this sign-in: a body it can't read is answered as such, never refused.
+ expect((await garage.as("POST", "/api/cloud-send/arrived", { v: 1 })).status).toBe(400);
+}, hostTimeout(60_000));
+
+let scout: { id: string; threadId: string }, ember: { id: string; threadId: string };
+let morning = "", paused = "", soon = "", soonAt = 0;
+let project = "";
+
+it("Make Garage server my home: bots, chats, memory and routines arrive, this computer stops for good, and no routine runs twice", async () => {
+ const { local } = fx;
+ scout = (await local("POST", "/api/bots", { name: "Scout", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot;
+ project = join(fx.root, "desktop", "code", "shop");
+ mkdirSync(project, { recursive: true });
+ expect((await local("PATCH", `/api/bots/${scout.id}`, { soul: "You are Scout.", cwd: project })).status).toBe(200);
+ await turn(local, scout, "Plan the week.");
+ ember = (await local("POST", "/api/bots", { name: "Ember", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot;
+ await turn(local, ember, "Hello Ember.");
+ expect((await local("PUT", `/api/bots/${ember.id}/memory/file`, { path: "MEMORY.md", text: "# Memory\n\n- The person likes short answers.\n" })).status).toBeLessThan(300);
+ const add = async (body: Record<string, unknown>) => { const made = (await local("POST", "/api/routines", body)).body; return (made.routine ?? made).id as string; };
+ morning = await add({ name: "Morning report", prompt: "Report.", botId: scout.id, schedule: { type: "daily", time: "09:00", weekdays: [1, 2, 3, 4, 5] }, durationMinutes: 15 });
+ paused = await add({ name: "Paused one", prompt: "Wait.", botId: scout.id, schedule: { type: "daily", time: "10:00", weekdays: [1] }, durationMinutes: 15 });
+ expect((await local("PATCH", `/api/routines/${paused}`, { enabled: false })).status).toBe(200);
+ soonAt = Date.now() + 120_000;
+ soon = await add({ name: "Soon", prompt: "Say the time.", botId: scout.id, schedule: { type: "interval", everyMinutes: 1_440, anchorAt: soonAt }, durationMinutes: 15 });
+ const webhook = (await local("POST", "/api/webhooks", { name: "Orders", prompt: "File the order.", botId: scout.id })).body;
+ await expect.poll(() => idle(local), { timeout: 60_000, interval: 200 }).toBe(true);
+
+ expect(await fx.main.start(garage.place.id)).toEqual({ started: true });
+ await expect.poll(() => fx.main.view()?.place, { timeout: 10_000, interval: 50 }).toBe("Garage server");
+
+ // The app is killed the moment the freeze and the switch would be written down, and opens again.
+ const killAt = new Set(["freeze", "switch"]);
+ let killed = false;
+ fx.beforeJournalWrite = (value) => { if (value?.phase && killAt.delete(value.phase)) { killed = true; throw new Error("the app was killed"); } };
+ for (let round = 0; round < 240 && journal()?.phase !== "done"; round++) {
+ await fx.main.kick().catch(() => {});
+ if (killed) { killed = false; await fx.relaunch(); continue; }
+ if (journal()?.phase !== "done") await sleep(500);
+ }
+ fx.beforeJournalWrite = null;
+ expect(journal()?.phase, `${JSON.stringify(journal())}\n${fx.logs().split("\n").filter((line) => line.startsWith("[main]")).join("\n")}`).toBe("done");
+ expect(killAt.size, "killed once at each").toBe(0);
+
+ // Home is Garage server: everything is there under the same ids.
+ expect(fx.main.away()).toBe(true);
+ expect(fx.main.home()).toMatchObject({ origin: garage.base, name: "Garage server" });
+ const there = (await garage.as("GET", "/api/bots")).body.bots as Array<{ id: string; name: string; soul?: string; cwd?: string }>;
+ expect(there.find((bot) => bot.id === scout.id)).toMatchObject({ name: "Scout", soul: "You are Scout." });
+ expect(there.find((bot) => bot.id === ember.id)?.name).toBe("Ember");
+ const chat = await rows(garage.as, scout.threadId);
+ expect(chat.some((row) => row.role === "user" && row.text === "Plan the week.")).toBe(true);
+ const memory = (await garage.as("GET", `/api/bots/${ember.id}/memory/file?path=MEMORY.md`)).body;
+ expect(memory?.text).toContain("The person likes short answers.");
+ const told = (await rows(garage.as, scout.threadId)).filter((row) => row.role === "bot" && row.text === webhookMovedLine("Orders", "Garage server"));
+ expect(told, "the webhook's bot says once where it lives now").toHaveLength(1);
+
+ // What was on here is on there, and only that; this computer is stopped for good and says where its bots live.
+ const after = await routines(garage.as);
+ const on = (id: string) => after.routines.find((routine) => routine.id === id)?.enabled;
+ expect([on(morning), on(paused), on(soon)]).toEqual([true, false, true]);
+ const refused = await local("POST", `/api/bots/${scout.id}/messages`, { text: "Still here?", threadId: scout.threadId });
+ expect(refused).toMatchObject({ status: 409, body: { error: movedRefusal("Garage server") } });
+ expect(webhook.webhook.id).toBeTruthy();
+ expect((await local("GET", "/api/move/freeze")).body).toMatchObject({ frozen: true, cloud: garage.base, place: "Garage server" });
+
+ // This computer is lent with Scout's project folder to Garage server, its phone link stops, and the window opens Garage server.
+ expect(fx.spies.lent).toEqual([{ projects: [project], place: garage.base }]);
+ expect(fx.spies.phoneStops).toBe(1);
+ expect(fx.spies.opened).toEqual([garage.base]);
+ expect(fx.main.offers(garage.place), "home is there: nothing more to offer").toBe(false);
+
+ // No occurrence of any routine ran on both sides, and the one due soon ran on Garage server only.
+ await sleep(Math.max(0, soonAt + 25_000 - Date.now()));
+ const [here, home] = [await routines(local), await routines(garage.as)];
+ const occurrences = new Map<string, Set<string>>();
+ for (const run of [...here.runs, ...home.runs]) {
+ if (run.manual || run.triggerSource === "manual") continue;
+ const key = `${run.routineId}@${run.scheduledFor}`;
+ occurrences.set(key, (occurrences.get(key) ?? new Set()).add(run.id));
+ }
+ expect([...occurrences].filter(([, runs]) => runs.size > 1), "an occurrence ran on both sides").toEqual([]);
+ expect(here.runs.filter((run) => run.routineId === soon)).toEqual([]);
+ expect(home.runs.filter((run) => run.routineId === soon && run.scheduledFor === soonAt)).toHaveLength(1);
+}, hostTimeout(900_000));
+
+it("this computer then works for Garage server by itself, and never for the server it shares with others", async () => {
+ const places: Array<{ id: string; name: string; origin: string }> = [garage.place, family.place];
+ const target = createLendingTarget({ account: () => null, environments: () => places, ownHome: () => fx.main.home() });
+ expect(target.places().map((place) => place.origin)).toEqual([garage.base]);
+ expect(target.cloud(family.place)).toBeNull();
+ const lent = mkdtempSync(join(fx.root, "lent-"));
+ const sharing = createComputerSharing({ file: join(fx.root, "computer-sharing.json"), fetch: fx.windowFetch, environments: () => places,
+ home: lent, cloud: target.cloud, myCloud: target.environment, ownClouds: target.places, screen: () => false, cuaConnection: async () => null });
+ try {
+ sharing.start({ maintainer: false });
+ await expect.poll(async () => ((await garage.as("GET", "/api/shared-computers")).body?.computers ?? []).length, { timeout: 30_000, interval: 250 }).toBe(1);
+ expect(sharing.cloudState(garage.place)).toMatchObject({ enabled: true, terminal: false });
+ expect(sharing.state(family.place.id).enabled).toBe(false);
+ expect((await family.as("GET", "/api/shared-computers")).status, "nothing is lent where others sign in").not.toBe(200);
+ // Pause: Garage server stops using this computer, until Resume.
+ sharing.pause();
+ await expect.poll(async () => ((await garage.as("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean; connected?: boolean }) => computer.online !== false && computer.connected !== false).length,
+ { timeout: 30_000, interval: 250 }).toBe(0);
+ } finally { sharing.close(); }
+}, hostTimeout(120_000));
diff --git a/server/own-home.test.ts b/server/own-home.test.ts
new file mode 100644
index 0000000000..013b69e718
--- /dev/null
+++ b/server/own-home.test.ts
@@ -0,0 +1,53 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createOwnHome, oneOwner, ownServerOwner, type OwnServerFacts } from "./own-home.ts";
+import type { RequestAuth } from "./request-auth.ts";
+import type { SessionRecord } from "./sessions.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+const solo: OwnServerFacts = { managed: false, shared: false, admins: [] };
+const session = (scopes: Array<"admin" | "client">, email?: string): RequestAuth => ({
+ kind: "session", via: "cookie", scopes,
+ session: { id: "s1", tokenHash: "0".repeat(64), label: "OpenMausBot app", scopes, createdAt: 1, lastSeenAt: 1, expiresAt: 2, ...(email ? { email } : {}) } as SessionRecord,
+});
+
+describe("a server of one person's own", () => {
+ it("is one nobody else signs in to: never a Cloud, a team's or a hosted workspace, and never with members or a second admin", () => {
+ expect(oneOwner(solo)).toBe(true);
+ expect(oneOwner({ ...solo, admins: ["[email protected]"] })).toBe(true);
+ expect(oneOwner({ ...solo, managed: true })).toBe(false);
+ expect(oneOwner({ ...solo, shared: true })).toBe(false);
+ expect(oneOwner({ ...solo, admins: ["[email protected]", "[email protected]"] })).toBe(false);
+ expect(oneOwner({ ...solo, admins: ["@example.test"] }), "everyone at a domain").toBe(false);
+ });
+
+ it("answers its one owner's admin sign-in only: their paired devices, or their address when the list names one", () => {
+ expect(ownServerOwner(solo, session(["admin", "client"]))).toBe(true);
+ expect(ownServerOwner(solo, session(["client"])), "a device that may only chat").toBe(false);
+ expect(ownServerOwner(solo, { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth), "a program on the server itself").toBe(false);
+ const listed = { ...solo, admins: ["[email protected]"] };
+ expect(ownServerOwner(listed, session(["admin"], "[email protected]"))).toBe(true);
+ expect(ownServerOwner(listed, session(["admin"], "[email protected]"))).toBe(false);
+ expect(ownServerOwner(listed, session(["admin"]))).toBe(true);
+ expect(ownServerOwner({ ...solo, shared: true }, session(["admin"]))).toBe(false);
+ expect(ownServerOwner({ ...solo, managed: true }, session(["admin"]))).toBe(false);
+ });
+
+ it("is that person's home once a move from them arrived, while it stays theirs alone", () => {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-own-home-"));
+ dirs.push(dataDir);
+ let facts = solo;
+ const home = createOwnHome({ dataDir, facts: () => facts });
+ expect(home.takesMove()).toBe(true);
+ expect(home.here()).toBe(false);
+ writeFileSync(join(dataDir, "moved-from.json"), JSON.stringify({ computer: "Work laptop", at: 1, told: [] }));
+ expect(home.here()).toBe(true);
+ facts = { ...solo, shared: true };
+ expect(home.here(), "others sign in now").toBe(false);
+ expect(home.takesMove()).toBe(false);
+ });
+});
diff --git a/server/own-home.ts b/server/own-home.ts
new file mode 100644
index 0000000000..d8ee357c2d
--- /dev/null
+++ b/server/own-home.ts
@@ -0,0 +1,38 @@
+// A server of one person's own (`openmausbot serve` on their VPS or Mac mini) can be their home, as My Cloud is: its owner
+// moves a computer's bots into it, and that computer then works for it. Security: only where nobody else signs in, so no
+// one else's bots or turns ever reach a computer lent this way, and never a Cloud, a team's Cloud or a hosted workspace.
+import { movedFrom } from "./cloud-send-arrived.ts";
+import type { RequestAuth } from "./request-auth.ts";
+
+export interface OwnServerFacts {
+ /** A Cloud home, a team's Cloud or a hosted workspace: MausBot or an organization runs it, never one person. */
+ managed: boolean;
+ /** Others sign in here: a team, an organization's members, or members on the sign-in list. */
+ shared: boolean;
+ /** The sign-in list's admins: addresses, or "@domain" for everyone there. */
+ admins: readonly string[];
+}
+
+/** Nobody but one person signs in here: no members, and at most one admin, named by address. */
+export function oneOwner(facts: OwnServerFacts): boolean {
+ if (facts.managed || facts.shared) return false;
+ return facts.admins.length === 0 || (facts.admins.length === 1 && !facts.admins[0]!.startsWith("@"));
+}
+
+/** The request is that one person's own: an admin session, by the one admin's address when the sign-in list names one. A
+ * paired device carries no address; only an admin pairs one, so it is theirs. */
+export function ownServerOwner(facts: OwnServerFacts, auth: RequestAuth): boolean {
+ if (!oneOwner(facts) || auth.kind !== "session" || !auth.scopes.includes("admin")) return false;
+ const email = auth.session.email?.trim().toLowerCase();
+ return !email || facts.admins.length === 0 || facts.admins[0] === email;
+}
+
+/** `facts()` is read on every ask, so a sign-in list changed in Settings counts at once. `here()`: this server took a move
+ * from its owner (cloud-send-arrived.ts keeps where from), so it is their home and their computers work for it. */
+export function createOwnHome({ facts, dataDir }: { facts(): OwnServerFacts; dataDir: string }) {
+ return {
+ owner: (auth: RequestAuth): auth is Extract<RequestAuth, { kind: "session" }> => ownServerOwner(facts(), auth),
+ takesMove: () => oneOwner(facts()),
+ here: () => oneOwner(facts()) && movedFrom(dataDir) !== null,
+ };
+}
diff --git a/server/remote-sessions.test.ts b/server/remote-sessions.test.ts
index deadc1fc4b..ceedfccd9e 100644
--- a/server/remote-sessions.test.ts
+++ b/server/remote-sessions.test.ts
@@ -189,6 +189,8 @@ describe("before pairing", () => {
selfUpdate: "operator",
emailSignIn: false,
jobs: true,
+ // A server nobody else signs in to can be its owner's bots' home: it takes their move once they pair.
+ move: 1,
});
const refused = await call("/api/bots", { headers: remote("10.0.0.1") });
expect(refused.status).toBe(403);
diff --git a/server/routes/cloud-connections.ts b/server/routes/cloud-connections.ts
index 1d9c0da921..937a683edc 100644
--- a/server/routes/cloud-connections.ts
+++ b/server/routes/cloud-connections.ts
@@ -12,6 +12,7 @@ import type { ShareOutcome } from "../composio-share.ts";
import { parseHighLevelConnection, type HighLevelConnection } from "../highlevel/store.ts";
import { parseMcpOAuthRecord, type McpOAuthRecord } from "../mcp-oauth-store.ts";
import type { McpRunsOn } from "../mcp-registry.ts";
+import type { RequestAuth } from "../request-auth.ts";
import { PASS, type RouteHandler } from "./table.ts";
const SLUG = /^[a-z0-9_][a-z0-9_-]{0,80}$/u;
@@ -30,13 +31,16 @@ export interface ConnectionsAnswer {
engines: string[];
/** Programs a command-line MCP server may start that this server has. */
commands: string[];
+ /** False on a server with no connected-apps service of MausBot's: connected apps through that service can't move here. */
+ managedApps?: false;
}
export type Adopted = { ok: true; outcome: "adopted" | "kept" } | { ok: false; status: number; error: string };
export interface CloudConnectionRouteDeps {
- /** Only a Cloud home takes connections. */
+ /** Only a Cloud home takes connections, and a server of one person's own from that person's session (`ownHome`). */
cloudHome: boolean;
+ ownHome?(auth: RequestAuth): boolean;
/** A Team Cloud: a person's own connections (a share, a sign-in, HighLevel) are refused with one plain line. */
personalRefusal?: (what: string) => string | null;
list(): Promise<ConnectionsAnswer>;
@@ -52,14 +56,14 @@ export interface CloudConnectionRouteDeps {
}
export function createCloudConnectionRoutes(deps: CloudConnectionRouteDeps): RouteHandler {
- return async ({ req, res, url, path, method, json, readBody }) => {
+ return async ({ req, res, url, path, method, auth, json, readBody }) => {
if (path !== "/api/cloud-connections" && !path.startsWith("/api/cloud-connections/")) return PASS;
res.setHeader("cache-control", "no-store");
if (path === "/api/cloud-connections") {
if (method !== "GET") return json(res, 405, { error: "method not allowed" });
return json(res, 200, await deps.list());
}
- if (!deps.cloudHome) return json(res, 404, { error: "not found" });
+ if (!deps.cloudHome && deps.ownHome?.(auth) !== true) return json(res, 404, { error: "not found" });
if (path === "/api/cloud-connections/held-keys") {
if (method !== "PUT") return json(res, 405, { error: "method not allowed" });
const asked = z.object({ for: z.array(z.string().regex(/^[\w.:-]{1,128}$/u)).max(20) }).safeParse(await readBody(req, 4096));
diff --git a/server/routes/cloud-send.ts b/server/routes/cloud-send.ts
index c0feda0056..8c64a43b77 100644
--- a/server/routes/cloud-send.ts
+++ b/server/routes/cloud-send.ts
@@ -32,6 +32,8 @@ export interface CloudSendRouteDeps extends Pick<CloudSendSources, "appVersion"
chats?: CloudSendChatsDeps;
/** This server is the person's own Cloud: it answers what a move asks of the Cloud it moves to. */
cloudHome?: boolean;
+ /** A server of one person's own: it answers that person's session (`ownHome(auth)`) as a Cloud home answers its owner. */
+ ownHome?(auth: RequestAuth): boolean;
/** This server's connections (cloud-connections.ts), by id. */
connections?(): Promise<ReadonlyArray<{ id: string }>>;
connectionFingerprints?(nonce: string): Record<string, string>;
@@ -70,6 +72,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
return async (ctx) => {
const { req, res, path, method, url, json, readBody } = ctx;
if (path !== "/api/cloud-send" && !path.startsWith("/api/cloud-send/")) return PASS;
+ const home = deps.cloudHome === true || deps.ownHome?.(ctx.auth) === true;
const scoped = deps.scope?.(ctx.auth) ?? null;
if (deps.refusal && !scoped) { req.resume(); return json(res, 403, { error: deps.refusal }); }
// A move of one bot into a team reads that bot only, on both sides.
@@ -78,7 +81,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
if (move && await moveKindsRoute(move, ctx)) return;
if (move && await moveMemoryRoute({ ...move, bot: (id) => move.store.bot(id) ?? undefined }, ctx)) return;
if (move && await moveFilesRoute({ dataDir: move.dataDir, bots: () => (bot ? move.store.bots.filter((entry) => entry.id === bot) : move.store.bots), owner: move.owner }, ctx)) return;
- if (move && deps.cloudHome && await arrivedRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks, owner: move.owner }, ctx)) return;
+ if (move && home && await arrivedRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks, owner: move.owner }, ctx)) return;
if (move && deps.cloudHome && deps.automations && await automationsOffRoute({ automations: deps.automations, owner: move.owner }, ctx)) return;
if (move && !deps.cloudHome && await homeRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks }, ctx)) return;
if (path === "/api/cloud-send/manifest") {
@@ -89,7 +92,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
connections: deps.connections ?? (async () => []), heads: threadHeads, ...(move ? { kinds: move, teamMemory: move.teamMemory } : {}), ...(bot ? { bot } : {}) }));
}
if (path === "/api/cloud-send/verify-secrets") {
- if (!deps.cloudHome || !deps.connectionFingerprints) return json(res, 404, { error: "not found" });
+ if (!home || !deps.connectionFingerprints) return json(res, 404, { error: "not found" });
if (method !== "POST") return json(res, 405, { error: "method not allowed" });
const asked = z.object({ nonce: z.string().regex(VERIFY_NONCE) }).safeParse(await readBody(req, 4096));
if (!asked.success) return json(res, 400, { error: "send { nonce }: at least 32 random bytes, base64url" });
diff --git a/server/routes/move-freeze.ts b/server/routes/move-freeze.ts
index 9c55df7804..b93292d72b 100644
--- a/server/routes/move-freeze.ts
+++ b/server/routes/move-freeze.ts
@@ -19,7 +19,7 @@ export interface MoveFreezeRouteDeps {
automationsOff?(): Promise<unknown>;
}
-const freezeBody = z.object({ cloud: z.string().url().max(300).optional() });
+const freezeBody = z.object({ cloud: z.string().url().max(300).optional(), place: z.string().trim().min(1).max(120).optional() });
const thawBody = z.object({ automations: z.literal("off").optional() });
export function createMoveFreezeRoutes({ freeze, busy, restart, automationsOff }: MoveFreezeRouteDeps): RouteHandler {
@@ -36,16 +36,16 @@ export function createMoveFreezeRoutes({ freeze, busy, restart, automationsOff }
if (auth.kind !== "loopback") return json(res, 403, { error: "Only OpenMausBot on this computer can do this." });
if (method === "GET") {
const who = busy();
- const cloud = freeze.cloud();
- return json(res, 200, { frozen: freeze.frozen(), ...(freeze.frozen() && cloud ? { cloud } : {}), ...(who === null ? {} : { busy: who.name, what: who.what }) });
+ const cloud = freeze.cloud(), place = freeze.place();
+ return json(res, 200, { frozen: freeze.frozen(), ...(freeze.frozen() && cloud ? { cloud } : {}), ...(freeze.frozen() && place ? { place } : {}), ...(who === null ? {} : { busy: who.name, what: who.what }) });
}
if (method === "POST") {
const body = freezeBody.safeParse(await readBody(req, 4096));
- if (!body.success) return json(res, 400, { error: "send { cloud }: My Cloud's address" });
+ if (!body.success) return json(res, 400, { error: "send { cloud, place? }: the home's address, and its name when it is a server of the person's own" });
if (!freeze.frozen()) {
const who = busy();
if (who !== null) return json(res, 409, { error: "A bot is still working.", busy: who.name, what: who.what });
- freeze.freeze(body.data.cloud ?? null);
+ freeze.freeze(body.data.cloud ?? null, body.data.place ?? null);
}
return json(res, 200, { frozen: true });
}
diff --git a/src/components/AccountMove.test.ts b/src/components/AccountMove.test.ts
index 4f0f9e822b..4d17245302 100644
--- a/src/components/AccountMove.test.ts
+++ b/src/components/AccountMove.test.ts
@@ -40,6 +40,9 @@ describe("the move's words on the account", () => {
expect(accountMoveWords("sending")).toBe("Moving to My Cloud…");
expect(accountMoveWords("done")).toBeNull();
expect(accountMoveWords(null)).toBeNull();
+ expect(accountMoveWords("failed", "Garage server")).toBe("Garage server move needs you");
+ expect(accountMoveWords("sending", "Garage server")).toBe("Moving to Garage server…");
+ expect(markup(AccountMoveStatus({ kind: "sending", place: "Garage server" }))).toContain("Moving to Garage server…");
});
it("is a button that opens the account menu by the account, and plain words inside a trigger", () => {
@@ -110,6 +113,12 @@ describe("the move's row in the account menu", () => {
expect(rows(line({ phase: "finishing", failing: { error: null } }))[0]!.title).toBe("Your bots couldn't move to My Cloud yet.");
});
+ it("to a server of the person's own: the same rows, named for it", () => {
+ const place = "Garage server";
+ expect(rows(line({ phase: "copy", failing: { error: null }, place }))[0]).toMatchObject({ label: "Try Garage server move again", title: "Your bots couldn't move to Garage server yet." });
+ expect(rows(line({ phase: "copy", place }))[0]).toMatchObject({ label: "Moving to Garage server…", title: "Moving your bots to Garage server…" });
+ });
+
it("failing: the same one row, disabled with a spinner, while Try again runs, and main's words when it did not answer", () => {
const failing = line({ phase: "wait", failing: { error: "My Cloud did not answer." } });
const busy = rows(failing, { retrying: true });
diff --git a/src/components/AccountMove.tsx b/src/components/AccountMove.tsx
index cd7ae54775..e73b6520a5 100644
--- a/src/components/AccountMove.tsx
+++ b/src/components/AccountMove.tsx
@@ -17,16 +17,18 @@ export type AccountMoveKind = AccountMoveLine["kind"];
const pageBridge = () => (!window.ogb?.remoteClient?.active ? window.ogb?.cloudSendPage : undefined);
/** The account's words for the move: it needs the person once it has failed for a day, goes quietly meanwhile, and
- * says nothing once done (its menu row says what arrived). */
-export function accountMoveWords(kind: AccountMoveKind | null): string | null {
- if (kind === "failed") return t("sidebar.account.moveNeedsYou");
- if (kind === "sending") return t("sidebar.account.moving");
+ * says nothing once done (its menu row says what arrived). `place`: the server of their own it goes to, else My Cloud. */
+export function accountMoveWords(kind: AccountMoveKind | null, place?: string): string | null {
+ if (kind === "failed") return place ? t("sidebar.account.moveNeedsYouNamed", { place }) : t("sidebar.account.moveNeedsYou");
+ if (kind === "sending") return place ? t("sidebar.account.movingNamed", { place }) : t("sidebar.account.moving");
return null;
}
+const failingPlain = (place?: string) => (place ? t("cloudSend.move.failingPlainNamed", { place }) : t("cloudSend.move.failingPlain"));
+
/** Why a failing move failed: main's words when Try again went unanswered, else the move's own reason. */
function failingWhy(line: AccountMoveLine, unanswered: string | null): string {
- const plain = t("cloudSend.move.failingPlain");
+ const plain = failingPlain(line.place);
return [unanswered && unanswered !== plain ? unanswered : line.reason, ...line.extra].filter(Boolean).join(" ") || plain;
}
@@ -44,10 +46,10 @@ export function moveMenuItems(line: AccountMoveLine | null, { retrying = false,
if (!line) return [];
if (line.kind === "failed") {
const title = failingWhy(line, unanswered);
- if (!line.retry) return [{ key: "cloud-move", label: t("sidebar.account.moveNeedsYou"), title, icon: <CloudAlert size={16} className="text-warning" />, onSelect: onOpen }];
+ if (!line.retry) return [{ key: "cloud-move", label: accountMoveWords("failed", line.place)!, title, icon: <CloudAlert size={16} className="text-warning" />, onSelect: onOpen }];
return [{
key: "cloud-move",
- label: t("sidebar.account.moveRetry"),
+ label: line.place ? t("sidebar.account.moveRetryNamed", { place: line.place }) : t("sidebar.account.moveRetry"),
title,
icon: retrying ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} className="text-warning" />,
disabled: retrying,
@@ -55,7 +57,7 @@ export function moveMenuItems(line: AccountMoveLine | null, { retrying = false,
onSelect: onRetry,
}];
}
- if (line.kind === "sending") return [{ key: "cloud-move", label: t("sidebar.account.moving"), title: line.text, icon: <Loader2 size={16} className="animate-spin" />, onSelect: onOpen }];
+ if (line.kind === "sending") return [{ key: "cloud-move", label: accountMoveWords("sending", line.place)!, title: line.text, icon: <Loader2 size={16} className="animate-spin" />, onSelect: onOpen }];
return [
{ key: "cloud-move", label: line.text, ...(line.extra.length ? { note: line.extra.join(" ") } : {}), wrap: true, icon: <CloudCheck size={16} />, onSelect: onOpen },
...(line.phone && onPairPhone ? [{ key: "cloud-move-phone", label: t("cloudSend.move.phone"), icon: <Smartphone size={16} />, onSelect: onPairPhone }] : []),
@@ -99,7 +101,7 @@ function useMove(cloudHome: boolean) {
if (store.get().retrying) return;
store.set({ retrying: true, unanswered: null });
void (bridge.moveRetry?.() ?? Promise.resolve(notice)).then((next) => { setNotice(next); store.set(IDLE); })
- .catch((cause: unknown) => { store.set({ retrying: false, unanswered: ipcErrorText(cause) ?? t("cloudSend.move.failingPlain") }); });
+ .catch((cause: unknown) => { store.set({ retrying: false, unanswered: ipcErrorText(cause) ?? failingPlain(line.place) }); });
};
const close = () => { void bridge.dismiss(MOVE_LINE).then(setNotice).catch(() => {}); };
return { line, retrying, unanswered, retry, close };
@@ -109,11 +111,12 @@ function useMove(cloudHome: boolean) {
export function useAccountMove(cloudHome: boolean, { onOpen, onPairPhone }: { onOpen: () => void; onPairPhone?: () => void }): {
kind: AccountMoveKind | null;
items: SidebarMenuItem[];
+ place?: string;
} {
const move = useMove(cloudHome);
if (!move) return { kind: null, items: [] };
const { line, retrying, unanswered, retry, close } = move;
- return { kind: line.kind, items: moveMenuItems(line, { retrying, unanswered, onOpen, onRetry: retry, onPairPhone, onClose: close }) };
+ return { kind: line.kind, items: moveMenuItems(line, { retrying, unanswered, onOpen, onRetry: retry, onPairPhone, onClose: close }), ...(line.place ? { place: line.place } : {}) };
}
/** The line's Try again: what it runs, whether it is running, and why the move failed. */
@@ -124,18 +127,18 @@ export interface AccountMoveRetry {
}
/** The move as Simple's line above the account shows it: its kind, and Try again while the failing move allows one. */
-export function useAccountMoveLine(cloudHome: boolean): { kind: AccountMoveKind | null; retry: AccountMoveRetry | null } {
+export function useAccountMoveLine(cloudHome: boolean): { kind: AccountMoveKind | null; retry: AccountMoveRetry | null; place?: string } {
const move = useMove(cloudHome);
if (!move) return { kind: null, retry: null };
const { line, retrying, unanswered, retry } = move;
- return { kind: line.kind, retry: line.kind === "failed" && line.retry ? { onRetry: retry, retrying, why: failingWhy(line, unanswered) } : null };
+ return { kind: line.kind, retry: line.kind === "failed" && line.retry ? { onRetry: retry, retrying, why: failingWhy(line, unanswered) } : null, ...(line.place ? { place: line.place } : {}) };
}
/** The account's line for the move: amber while it needs the person, quiet while it goes, nothing otherwise. With
* `onOpen` its words are a button that opens the account menu, followed by Try again when `retry` allows one; without,
* words inside a trigger. The words shorten before Try again does. */
-export function AccountMoveStatus({ kind, retry = null, onOpen, className }: { kind: AccountMoveKind | null; retry?: AccountMoveRetry | null; onOpen?: () => void; className?: string }) {
- const words = accountMoveWords(kind);
+export function AccountMoveStatus({ kind, place, retry = null, onOpen, className }: { kind: AccountMoveKind | null; place?: string; retry?: AccountMoveRetry | null; onOpen?: () => void; className?: string }) {
+ const words = accountMoveWords(kind, place);
if (!words) return null;
const Icon = kind === "failed" ? CloudAlert : CloudUpload;
const look = cn("flex min-w-0 items-center gap-1.5 text-start text-[12px] leading-4", kind === "failed" ? "font-medium text-warning" : "text-ink-secondary");
@@ -151,7 +154,7 @@ export function AccountMoveStatus({ kind, retry = null, onOpen, className }: { k
<button
type="button"
data-move-retry
- aria-label={t("sidebar.account.moveRetryName")}
+ aria-label={place ? t("sidebar.account.moveRetryNameNamed", { place }) : t("sidebar.account.moveRetryName")}
aria-busy={retry.retrying || undefined}
aria-disabled={retry.retrying || undefined}
title={retry.why}
diff --git a/src/components/HomeScreen.test.ts b/src/components/HomeScreen.test.ts
index e906ffd3d0..2817cf852d 100644
--- a/src/components/HomeScreen.test.ts
+++ b/src/components/HomeScreen.test.ts
@@ -17,6 +17,8 @@ it("names a team's Cloud on every screen that waits on it, and keeps My Cloud's
expect(homeScreenText({ screen: "plan", machine: "stopped" }).title).toBe("My Cloud isn't running");
expect(homeScreenText({ screen: "waking", name: "Acme" }).title, "only My Cloud is woken").toBe("Waking My Cloud…");
expect(homeScreenText(null).title).toBe("Opening My Cloud…");
+ expect(homeScreenText({ screen: "moving" }).title).toBe("Moving to My Cloud… almost done");
+ expect(homeScreenText({ screen: "moving", name: "Garage server" })).toMatchObject({ title: "Moving to Garage server… almost done", action: null, busy: true });
});
it("while the Admin sets My Cloud up, the screen says so plainly, with its step, and never asks the person to do anything", () => {
diff --git a/src/components/HomeScreen.tsx b/src/components/HomeScreen.tsx
index 1f6a554af7..a45422e752 100644
--- a/src/components/HomeScreen.tsx
+++ b/src/components/HomeScreen.tsx
@@ -36,7 +36,7 @@ export function homeScreenText(view: HomeView | null, now = Date.now()): { title
if (view?.screen === "checkout") return { title: named("cloudHome.checkout", "cloudHome.checkoutNamed"), body: null, reason: null, action: "continue", busy: false };
if (view?.screen === "payment") return { title: named("cloudHome.payment", "cloudHome.paymentNamed"), body: t("cloudHome.paymentBody"), reason: null, action: "card", busy: false };
if (view?.screen === "waking") return { title: t("homeScreen.waking"), body: null, reason: null, action: null, busy: true };
- if (view?.screen === "moving") return { title: t("homeScreen.moving"), body: null, reason: null, action: null, busy: true };
+ if (view?.screen === "moving") return { title: named("homeScreen.moving", "homeScreen.movingNamed"), body: null, reason: null, action: null, busy: true };
return { title: named("homeScreen.opening", "homeScreen.openingNamed"), body: null, reason: null, action: null, busy: true };
}
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
index 6ead2fac4e..41767e56cb 100644
--- a/src/components/PlacesRail.test.ts
+++ b/src/components/PlacesRail.test.ts
@@ -399,3 +399,32 @@ it("a Cloud of the person's own that ended says so on its circle, and its menu o
expect(host.querySelector("[data-rail-menu]"), "removed: the menu closes, and the circle goes with main's next list").toBeNull();
expect(workspaces.places).toHaveBeenCalled();
});
+
+it("a server of the person's own that main offers as home: its menu's one tap starts the move and closes; main's own words when it can't", async () => {
+ const makeHome = vi.fn(async (_id: string): Promise<{ started: true }> => { throw new Error("Error invoking remote method 'workspaces:make-home': Error: Garage server has other people on it, so your bots stay here."); });
+ rail = { places: [
+ place("home", "This computer", { kind: "computer", active: true, paint: { swatch: null } }),
+ place("garage", "Garage server", { kind: "server", makeHome: true, paint: { swatch: null } }),
+ place("office", "Office", { kind: "server", paint: { swatch: null } }),
+ ], add: { cloud: false, link: true, address: false } };
+ Object.assign(window, { ogb: { workspaces: { ...workspaces, makeHome }, cloudAdd, rail: { expand: vi.fn(async () => {}), onSkin: () => () => {} } } });
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const settle = () => act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });
+ const menuOf = async (id: string) => {
+ await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });
+ return host.querySelector(`[data-rail-menu="${id}"]`);
+ };
+ expect((await menuOf("office"))?.querySelector("[data-rail-make-home]"), "not offered: no such choice").toBeNull();
+ await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ const menu = await menuOf("garage");
+ const row = menu!.querySelector("[data-rail-make-home-start]");
+ expect(row?.textContent).toBe("Make Garage server my homeMoves this computer's bots, chats, memory and routines to Garage server, and this computer then works for it.");
+ await click(row);
+ await settle();
+ expect(makeHome).toHaveBeenCalledWith("garage");
+ expect(host.querySelector("[data-rail-menu] [data-rail-make-home] [role='alert']")?.textContent).toBe("Garage server has other people on it, so your bots stay here.");
+ makeHome.mockResolvedValueOnce({ started: true });
+ await click(host.querySelector("[data-rail-menu] [data-rail-make-home-start]"));
+ await settle();
+ expect(host.querySelector("[data-rail-menu]"), "started: the menu closes, and the account says how it goes").toBeNull();
+});
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index 3fb49ee988..c1172eff48 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -1,10 +1,11 @@
// The rail at the window's left edge once a person has two places or more: one tile per Cloud, team's Cloud or server,
// the place on screen marked, ⋯ for the rest past eight, + last. Main lists the places and opens one by its id; the rail
// never names an address. A right-click on a tile (or its row past eight) opens that place's menu: its colour, changed
-// here for every place whatever its server runs, and Remove from list for a Cloud of the person's own that ended or was
-// never paid for (asked first; main takes it off their list on the Admin).
+// here for every place whatever its server runs, Remove from list for a Cloud of the person's own that ended or was
+// never paid for (asked first; main takes it off their list on the Admin), and Make … my home for a server of theirs that
+// main says this computer's bots may move to (one tap: main starts the move).
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";
-import { Laptop, MoreHorizontal, Plus, Search, Server } from "lucide-react";
+import { House, Laptop, Loader2, MoreHorizontal, Plus, Search, Server } from "lucide-react";
import type { CloudSwatch } from "../../electron/cloud-list.mjs";
import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
import { track } from "@/lib/analytics";
@@ -13,7 +14,7 @@ import { cloudColor, cloudColorFill } from "@/lib/cloud-look";
import { activeLocale, t } from "@/lib/i18n";
import { localizedRelativeTime } from "@/lib/memory";
import { useAdvancedMode } from "@/lib/interface-mode";
-import { placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
+import { makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";
import { MENU_ROW, MENU_SHEET } from "./menu-recipe";
import { PlaceAddSheet } from "./PlaceAddSheet";
@@ -149,6 +150,30 @@ function RemoveRow({ place, onRemoved }: { place: RailPlace; onRemoved: () => vo
</div>;
}
+/** Make … my home in a server's menu: one tap starts the move, and the menu closes once main has started it; the account
+ * area then says how it goes. Main's own words when it can't start. */
+function MakeHomeRow({ place, onStarted }: { place: RailPlace; onStarted: () => void }) {
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<string | null>(null);
+ const start = () => {
+ setBusy(true); setSaid(null);
+ void makeHome(place.id).then((outcome) => {
+ setBusy(false);
+ if (outcome === true) onStarted(); else setSaid(outcome);
+ });
+ };
+ return <div data-rail-make-home className="flex flex-col gap-0.5 border-t border-hairline/50 px-0.5 pt-1.5">
+ <button type="button" data-rail-make-home-start className={cn(MENU_ROW, "h-auto min-h-[30px] items-start py-1.5 touch:h-auto")} disabled={busy} aria-busy={busy || undefined} onClick={start}>
+ {busy ? <Loader2 size={15} aria-hidden="true" className="mt-0.5 shrink-0 animate-spin motion-reduce:animate-none" /> : <House size={15} aria-hidden="true" className="mt-0.5 shrink-0" />}
+ <span className="flex min-w-0 flex-col text-start">
+ <span className="text-[13px] text-ink">{t("rail.makeHome", { name: place.name })}</span>
+ <span className="text-[12px] leading-snug text-ink-secondary">{t("rail.makeHomeSub", { name: place.name })}</span>
+ </span>
+ </button>
+ {said && <p role="alert" className="px-1.5 pb-1 text-[12px] text-danger">{said}</p>}
+ </div>;
+}
+
/** A place's own menu on the window's rail: its name and its colour, in the six swatches, saved by main for every place
* whatever its server runs (on the Admin for a Cloud), and Remove from list for a Cloud its owner may take off their list.
* A team member sees who may change its colour. */
@@ -157,8 +182,8 @@ function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onC
const [pending, setPending] = useState<CloudSwatch | null>(null);
const [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);
const ref = useRef<HTMLDivElement>(null);
- useEffect(() => { (ref.current?.querySelector<HTMLElement>("[role='radio'][tabindex='0']") ?? ref.current?.querySelector<HTMLElement>("[data-rail-remove-ask]"))?.focus(); }, []);
- if (!paint && !place.removable) return null;
+ useEffect(() => { (ref.current?.querySelector<HTMLElement>("[role='radio'][tabindex='0']") ?? ref.current?.querySelector<HTMLElement>("[data-rail-remove-ask], [data-rail-make-home-start]"))?.focus(); }, []);
+ if (!paint && !place.removable && !place.makeHome) return null;
const name = place.kind === "computer" ? t("rail.thisComputer") : place.name;
const choose = (swatch: CloudSwatch) => {
if (!paint || paint.locked || pending || swatch === paint.swatch) return;
@@ -181,6 +206,7 @@ function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onC
{note && <p data-rail-menu-note className="px-2 pb-1 text-[12px] text-ink-secondary">{note}</p>}
{outcome === "failed" && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}
</>}
+ {place.makeHome && <MakeHomeRow place={place} onStarted={onClose} />}
{place.removable && <RemoveRow place={place} onRemoved={onClose} />}
</div>;
}
diff --git a/src/components/SidebarFooter.tsx b/src/components/SidebarFooter.tsx
index d59e3f4592..3dde7a39eb 100644
--- a/src/components/SidebarFooter.tsx
+++ b/src/components/SidebarFooter.tsx
@@ -38,7 +38,7 @@ function SimpleSidebarFooter({ owner, archived }: { owner: string | null; archiv
<CloudRoomCard />
<CloudUsageCard />
<SidebarPlaceStatus place={place} className="mb-2 px-1" />
- <AccountMoveStatus kind={move.kind} retry={move.retry} onOpen={openAccount} className="ps-1" />
+ <AccountMoveStatus kind={move.kind} place={move.place} retry={move.retry} onOpen={openAccount} className="ps-1" />
<div className="flex items-center gap-2 not-first:mt-2">
<SidebarProfileMenu simple={account} />
<SidebarConnectApps />
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index 8fb3f96bf2..1081ad8c34 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -674,7 +674,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-[14px] font-medium leading-5 text-ink">{name}</span>
- <AccountMoveStatus kind={move.kind} />
+ <AccountMoveStatus kind={move.kind} place={move.place} />
</span>
{noteworthy && (
<span
diff --git a/src/lib/cloud-send.test.ts b/src/lib/cloud-send.test.ts
index 262131f041..e5f44885b9 100644
--- a/src/lib/cloud-send.test.ts
+++ b/src/lib/cloud-send.test.ts
@@ -17,6 +17,23 @@ describe("the one-time move's line", () => {
expect(moveLine({ phase: "finishing" }, "cloud")).toMatchObject({ kind: "sending", text: "Moving to My Cloud… almost done" });
});
+ it("to a server of the person's own, names it on this computer's page, with Try again after a day of failing, and nowhere else", () => {
+ const place = "Garage server";
+ expect(moveLine({ phase: "copy", place }, "local")).toEqual({ kind: "sending", text: "Moving your bots to Garage server…", extra: [], place });
+ expect(moveLine({ phase: "copy", chats: { done: 3, total: 9 }, place }, "local")?.text).toBe("Moving your bots to Garage server… 3 of 9 chats");
+ expect(moveLine({ phase: "wait", waitingFor: "Scout", place }, "local")?.text).toBe("Moving your bots to Garage server… waiting for Scout to finish");
+ expect(moveLine({ phase: "wait", waitingFor: "", waitingWhat: "sign-in", place }, "local")?.text).toBe("Moving your bots to Garage server… waiting for a sign-in to finish");
+ expect(moveLine({ phase: "wait", waitingFor: "", place }, "local")?.text).toBe("Moving your bots to Garage server… waiting for your bots to finish");
+ expect(moveLine({ phase: "finishing", place }, "local")?.text).toBe("Moving to Garage server… almost done");
+ expect(moveLine({ phase: "copy", updating: true, place }, "local")?.text).toBe("Update OpenMausBot on Garage server. Your bots move there once it's updated.");
+ expect(moveLine({ phase: "copy", failing: { error: "Garage server has other people on it now, so your bots can't move there." }, place }, "local"))
+ .toMatchObject({ kind: "failed", text: "Your bots couldn't move to Garage server yet: Garage server has other people on it now, so your bots can't move there.", retry: true, place });
+ expect(moveLine({ phase: "finishing", failing: { error: null }, place }, "local")).toMatchObject({ kind: "failed", text: "Your bots couldn't move to Garage server yet.", retry: true });
+ expect(moveLine({ phase: "copy", place }, "cloud"), "only this computer's page hears of it").toBeNull();
+ expect(moveLine({ phase: "done", phone: true, held: [], place }, "local"), "once done the window shows Garage server").toBeNull();
+ expect(JSON.stringify(moveLine({ phase: "copy", place }, "local"))).not.toContain("My Cloud");
+ });
+
it("with My Cloud too old to take a move, says it is updating and the move starts after, on either page", () => {
for (const page of ["local", "cloud"] as const) {
expect(moveLine({ phase: "copy", updating: true }, page)).toEqual({ kind: "sending", text: "My Cloud is updating. Your move starts when it's done.", extra: [] });
diff --git a/src/lib/cloud-send.ts b/src/lib/cloud-send.ts
index 1437685254..c0749930f7 100644
--- a/src/lib/cloud-send.ts
+++ b/src/lib/cloud-send.ts
@@ -56,7 +56,8 @@ export function moveQuietUntil(move: OneHomeView | null | undefined): number {
* day (with Try again), what arrived (on My Cloud's page, once), coming home, where the bots came home instead, or this
* computer's bots on their way home and home because the person keeps them here.
* `page`: which page shows it; `reason`: why a failing move failed, in main's words, when it said. */
-export function moveLine(move: OneHomeView, page: "local" | "cloud"): { kind: "sending" | "failed" | "done"; text: string; extra: string[]; phone?: true; retry?: true; reason?: string } | null {
+export function moveLine(move: OneHomeView, page: "local" | "cloud"): { kind: "sending" | "failed" | "done"; text: string; extra: string[]; phone?: true; retry?: true; reason?: string; place?: string } | null {
+ if (move.place) return ownMoveLine(move, move.place, page);
if (move.phase === "done") {
if (page !== "cloud") return null;
const list = move.counts ? arrivedList(move.counts) : [];
@@ -93,6 +94,25 @@ export function moveLine(move: OneHomeView, page: "local" | "cloud"): { kind: "s
return { kind: "sending", text: t(key, chats ? { done: chats.done, total: chats.total } : {}), extra: [] };
}
+/** The move to a server of the person's own, named `place`, on this computer's page: on its way, almost done, waiting for
+ * that server's update, or failing for a day with Try again. Once done the window shows that server, which says nothing
+ * of it here. */
+function ownMoveLine(move: OneHomeView, place: string, page: "local" | "cloud"): ReturnType<typeof moveLine> {
+ if (page !== "local" || !["copy", "wait", "finishing"].includes(move.phase)) return null;
+ const line = (kind: "sending" | "failed", text: string, more: { retry?: true; reason?: string } = {}) => ({ kind, text, extra: [], place, ...more });
+ const failing = "failing" in move ? move.failing : undefined;
+ if (failing) return failing.error ? line("failed", t("cloudSend.move.failingNamed", { place, error: failing.error }), { retry: true, reason: failing.error })
+ : line("failed", t("cloudSend.move.failingPlainNamed", { place }), { retry: true });
+ if (move.phase === "copy" && move.updating) return line("sending", t("cloudSend.move.updatingNamed", { place }));
+ if (move.phase === "finishing") return line("sending", t("cloudSend.move.finishingNamed", { place }));
+ if (move.phase === "wait" && move.waitingFor !== undefined) {
+ return line("sending", move.waitingFor ? t("cloudSend.move.waitingNamed", { place, name: move.waitingFor })
+ : t(move.waitingWhat === "sign-in" ? "cloudSend.move.waitingSignInNamed" : "cloudSend.move.waitingAnyNamed", { place }));
+ }
+ const chats = move.phase === "copy" ? move.chats : undefined;
+ return line("sending", chats ? t("cloudSend.move.copyChatsNamed", { place, done: chats.done, total: chats.total }) : t("cloudSend.move.copyNamed", { place }));
+}
+
/** A bot moving from My Cloud into a team, on My Cloud's page: on its way, failed (it is still here, unchanged), or done. */
export function teamMoveLine(move: TeamMoveView): { kind: "sending" | "failed" | "done"; text: string } {
const names = { bot: move.bot.name, team: move.team.name };
diff --git a/src/lib/places.ts b/src/lib/places.ts
index dcfa376501..f963bd6a95 100644
--- a/src/lib/places.ts
+++ b/src/lib/places.ts
@@ -3,6 +3,8 @@ import type { CloudSwatch } from "../../electron/cloud-list.mjs";
import type { RailPlace, RailState } from "../../electron/cloud-rail.mjs";
import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
import type { CloudRemoveOutcome } from "../../electron/cloud-account.mjs";
+import { ipcErrorText } from "@/lib/cloud-send";
+import { t } from "@/lib/i18n";
const NONE: RailState = { places: [], add: { cloud: false, link: false, address: false } };
let current: RailState = NONE;
@@ -66,6 +68,20 @@ export async function removePlace(id: string): Promise<CloudRemoveOutcome> {
return answer.outcome;
}
+/** Make … my home, from a server's menu: main starts moving this computer's bots there. True once it started, else main's
+ * own words for why not. */
+export async function makeHome(id: string): Promise<true | string> {
+ const start = bridge()?.makeHome;
+ if (!start) return t("rail.makeHomeFailed");
+ try {
+ await start(id);
+ void refreshPlaces();
+ return true;
+ } catch (cause) {
+ return ipcErrorText(cause) ?? t("rail.makeHomeFailed");
+ }
+}
+
/** Whether a rail of places stands beside this page: the window's own (main says so: `beside`), or one drawn on it from a
* list main gave it (two places or more). */
export const railShown = (state: RailState): boolean => state.beside === true || state.places.length > 0;
diff --git a/src/locales/en.json b/src/locales/en.json
index 2e35c03038..8acdc235e7 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -383,6 +383,9 @@
"rail.showSub": "A circle for each place your bots live, at the window's left edge.",
"rail.ended": "{name}: ended",
"rail.remove": "Remove from list",
+ "rail.makeHome": "Make {name} my home",
+ "rail.makeHomeSub": "Moves this computer's bots, chats, memory and routines to {name}, and this computer then works for it.",
+ "rail.makeHomeFailed": "Your bots didn't start moving. Try again in a moment.",
"rail.removeAsk": "Remove “{name}” from your list? You can buy a new Cloud any time.",
"rail.removeYes": "Remove",
"rail.removeNo": "Cancel",
@@ -943,6 +946,15 @@
"cloudSend.move.updating": "My Cloud is updating. Your move starts when it's done.",
"cloudSend.move.failing": "Your bots couldn't move to My Cloud yet: {error}",
"cloudSend.move.failingPlain": "Your bots couldn't move to My Cloud yet.",
+ "cloudSend.move.copyNamed": "Moving your bots to {place}…",
+ "cloudSend.move.copyChatsNamed": "Moving your bots to {place}… {done} of {total} chats",
+ "cloudSend.move.waitingNamed": "Moving your bots to {place}… waiting for {name} to finish",
+ "cloudSend.move.waitingAnyNamed": "Moving your bots to {place}… waiting for your bots to finish",
+ "cloudSend.move.waitingSignInNamed": "Moving your bots to {place}… waiting for a sign-in to finish",
+ "cloudSend.move.finishingNamed": "Moving to {place}… almost done",
+ "cloudSend.move.updatingNamed": "Update OpenMausBot on {place}. Your bots move there once it's updated.",
+ "cloudSend.move.failingNamed": "Your bots couldn't move to {place} yet: {error}",
+ "cloudSend.move.failingPlainNamed": "Your bots couldn't move to {place} yet.",
"cloudSend.move.done": "Everything from this computer is here: {list}.",
"cloudSend.move.doneAll": "Everything from this computer is here.",
"cloudSend.move.phone": "Pair your phone with My Cloud",
@@ -1891,6 +1903,10 @@
"sidebar.account.moveDismiss": "Got it",
"sidebar.account.moveRetry": "Try My Cloud move again",
"sidebar.account.moveRetryName": "Try again to move to My Cloud",
+ "sidebar.account.movingNamed": "Moving to {place}…",
+ "sidebar.account.moveNeedsYouNamed": "{place} move needs you",
+ "sidebar.account.moveRetryNamed": "Try {place} move again",
+ "sidebar.account.moveRetryNameNamed": "Try again to move to {place}",
"sidebar.menu.connectPhone": "Connect your phone",
"sidebar.menu.connectPhone.team": "to {team}",
"sidebar.menu.connectPhone.computer": "to this computer",
@@ -6744,6 +6760,7 @@
"homeScreen.opening": "Opening My Cloud…",
"homeScreen.waking": "Waking My Cloud…",
"homeScreen.moving": "Moving to My Cloud… almost done",
+ "homeScreen.movingNamed": "Moving to {name}… almost done",
"homeScreen.setup": "Setting up My Cloud…",
"homeScreen.setupBody": "This takes about a minute. It opens by itself when it's ready.",
"homeScreen.offline": "Can't reach My Cloud right now.",
diff --git a/src/one-home-preview.tsx b/src/one-home-preview.tsx
new file mode 100644
index 0000000000..533a957c2a
--- /dev/null
+++ b/src/one-home-preview.tsx
@@ -0,0 +1,69 @@
+// Dev-only gallery of bringing the bots together on a server of the person's own, served at /one-home-preview.html; not in
+// the packaged app. It mounts the real rail and account line over fake bridges, with no server behind them.
+// ?state=menu|moving|failing&skin=midnight|daylight&lang=de
+import { StrictMode, useEffect } from "react";
+import { createRoot } from "react-dom/client";
+import type { CloudSendNotice } from "../electron/cloud-send.mjs";
+import type { RailState } from "../electron/cloud-rail.mjs";
+import { PlacesRail } from "@/components/PlacesRail";
+import { SidebarFooter } from "@/components/SidebarFooter";
+import { setLocale } from "@/lib/i18n";
+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
+import { initialState, StoreContext, type AppState } from "@/state/store";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const stateName = params.get("state") ?? "menu";
+const skin = params.get("skin") ?? "midnight";
+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
+setLocale(params.get("lang") ?? "en");
+
+const rail: RailState = { places: [
+ { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true, paint: { swatch: null } },
+ { id: "garage", name: "Garage server", color: "teal", kind: "server", opens: true, makeHome: true, paint: { swatch: "green" } },
+], add: { cloud: true, link: true, address: false } };
+const move = stateName === "failing"
+ ? { phase: "copy" as const, place: "Garage server", failing: { error: "This app isn't signed in to Garage server. Open Garage server in this app, then try again." } }
+ : stateName === "moving" ? { phase: "copy" as const, place: "Garage server", chats: { done: 14, total: 31 } } : null;
+const notice = { ready: true, bots: [], updatedBots: [], skills: 0, logins: 0, onePassword: false, settings: 0, signature: "", dismissed: false, running: false, last: null, whole: null,
+ arrived: { bots: 0, updatedBots: 0, skills: 0, logins: 0, settings: 0, onePassword: false, chats: { conversations: 0, messages: 0 } }, ...(move ? { move } : {}) } as unknown as CloudSendNotice;
+Object.assign(window, { ogb: {
+ workspaces: { places: async () => rail, state: async () => ({ local: true, name: "This computer" }), menu: async () => {}, open: async () => {}, add: async () => {},
+ makeHome: async () => ({ started: true }), onChanged: () => () => {} },
+ rail: { expand: async () => {}, onSkin: () => () => {} },
+ cloudSendPage: { notice: async () => notice, dismiss: async () => notice, moveRetry: async () => notice, onNotice: () => () => {} },
+} });
+
+function Gallery() {
+ const state: AppState = { ...initialState, connected: true, config: { ...initialState.config, profile: { name: "Sam", email: "", aboutMe: "" } } as AppState["config"] };
+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ useEffect(() => {
+ if (stateName !== "menu") return;
+ const timer = setInterval(() => {
+ const circle = document.querySelector('[data-rail-place="garage"]');
+ if (!circle || document.querySelector("[data-rail-menu]")) return;
+ circle.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
+ }, 100);
+ return () => clearInterval(timer);
+ }, []);
+ return (
+ <StoreContext.Provider value={value}>
+ <div className="flex h-screen bg-panel text-ink">
+ <div className="relative flex w-[60px] shrink-0 flex-col items-center border-e border-hairline/60 pt-3"><PlacesRail chrome /></div>
+ <div className="flex w-[280px] shrink-0 flex-col justify-end border-e border-hairline/60 bg-sidebar">
+ <SidebarFooter density="comfortable" simple toolsCollapsed={false} />
+ </div>
+ <div className="flex-1 bg-canvas" />
+ </div>
+ </StoreContext.Provider>
+ );
+}
+
+const realFetch = window.fetch.bind(window);
+window.fetch = async (input, init) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ if (!new URL(url, location.href).pathname.startsWith("/api/")) return realFetch(input, init);
+ return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
+};
+
+createRoot(document.getElementById("root")!).render(<StrictMode><Gallery /></StrictMode>);
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 7cb2ef5627..7a9584dbc1 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -173,6 +173,8 @@ const __APP_VERSION__: string;
/** Remove from list: a Cloud the window's rail lists as `removable`, by its circle's id, once the person said yes on
* the rail's own page (refused on any other page). Absent on an older app. */
remove?: (id: string) => Promise<{ outcome: import("../../electron/cloud-account.mjs").CloudRemoveOutcome }>;
+ /** Make a server of the person's own, which the rail lists with `makeHome`, their bots' home: the move starts. */
+ makeHome?: (id: string) => Promise<{ started: true }>;
/** Main's word that the places or the sign-in changed: read them again. */
onChanged?: (callback: () => void) => () => void;
};