Skip to content

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

feat(cloud): a rail of Clouds, + to buy or add your own server, and each place's colour (#3725)

Milind Sonia354545f95a4
diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdx
index e2a41b21dc..486ba6ea7e 100644
--- a/apps/docs/content/docs/security/analytics.mdx
+++ b/apps/docs/content/docs/security/analytics.mdx
@@ -163,6 +163,9 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `cloud_dialog_view` | The Add a Cloud dialog reaches a step | `view`: `received`, `starting`, `ready` |
| `cloud_signin` | Signing in to MausBot Cloud inside the Add a Cloud dialog takes a step | `step`: `code_sent` (a sign-in code was emailed), `signed_in`, `browser` (Continue in browser); `source`: as for `cloud_dialog_shown` |
| `cloud_checkout_opened` | A Cloud checkout opens in the browser | `plan`: Cloud plan; `trial`: true/false; `source`: as for `cloud_dialog_shown` |
+| `cloud_add_another` | Buying another Cloud, for someone who has one, takes a step | `step`: `plan` (a plan chosen), `checkout_opened`, `ready`; `plan`: Cloud plan, for `plan` and `checkout_opened` |
+| `rail_place_opened` | You open a place from the rail of Clouds at the window's left edge | `kind`: `computer`, `cloud`, `team`, `server` |
+| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead) |
| `cloud_setup_started` | A new Cloud starts its first job | none |
| `cloud_intent_submitted` | You tell a new Cloud what to do first | `idea`: `digest`, `watch`, `research`, `plan`, or none for your own words; `edited`: true/false |
| `cloud_intent_skipped` | You skip that question | none |
diff --git a/docs/analytics.md b/docs/analytics.md
index e0548745c9..9fe4ffc8da 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -159,6 +159,9 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `cloud_dialog_view` | The Add a Cloud dialog reaches a step | `view`: `received`, `starting`, `ready` |
| `cloud_signin` | Signing in to MausBot Cloud inside the Add a Cloud dialog takes a step | `step`: `code_sent` (a sign-in code was emailed), `signed_in`, `browser` (Continue in browser); `source`: as for `cloud_dialog_shown` |
| `cloud_checkout_opened` | A Cloud checkout opens in the browser | `plan`: Cloud plan; `trial`: true/false; `source`: as for `cloud_dialog_shown` |
+| `cloud_add_another` | Buying another Cloud, for someone who has one, takes a step | `step`: `plan` (a plan chosen), `checkout_opened`, `ready`; `plan`: Cloud plan, for `plan` and `checkout_opened` |
+| `rail_place_opened` | You open a place from the rail of Clouds at the window's left edge | `kind`: `computer`, `cloud`, `team`, `server` |
+| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead) |
| `cloud_setup_started` | A new Cloud starts its first job | none |
| `cloud_intent_submitted` | You tell a new Cloud what to do first | `idea`: `digest`, `watch`, `research`, `plan`, or none for your own words; `edited`: true/false |
| `cloud_intent_skipped` | You skip that question | none |
diff --git a/docs/pr-screenshots/cloud-rail/add-name-colour-light.png b/docs/pr-screenshots/cloud-rail/add-name-colour-light.png
new file mode 100644
index 0000000000..2f614789e6
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/add-name-colour-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/add-own-server-dark.png b/docs/pr-screenshots/cloud-rail/add-own-server-dark.png
new file mode 100644
index 0000000000..260c61eeb9
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/add-own-server-dark.png differ
diff --git a/docs/pr-screenshots/cloud-rail/add-sheet-light.png b/docs/pr-screenshots/cloud-rail/add-sheet-light.png
new file mode 100644
index 0000000000..b63962378c
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/add-sheet-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/color-light.png b/docs/pr-screenshots/cloud-rail/color-light.png
new file mode 100644
index 0000000000..0247abdcd9
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/color-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/color-member-dark.png b/docs/pr-screenshots/cloud-rail/color-member-dark.png
new file mode 100644
index 0000000000..8e5a59c2af
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/color-member-dark.png differ
diff --git a/docs/pr-screenshots/cloud-rail/connect-server-light.png b/docs/pr-screenshots/cloud-rail/connect-server-light.png
new file mode 100644
index 0000000000..07f7ad31a2
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/connect-server-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/rail-light.png b/docs/pr-screenshots/cloud-rail/rail-light.png
new file mode 100644
index 0000000000..40a8c7d310
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/rail-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/rail-simple-dark.png b/docs/pr-screenshots/cloud-rail/rail-simple-dark.png
new file mode 100644
index 0000000000..ad3caa1b82
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/rail-simple-dark.png differ
diff --git a/docs/pr-screenshots/cloud-rail/servers-dark.png b/docs/pr-screenshots/cloud-rail/servers-dark.png
new file mode 100644
index 0000000000..d1ce3f30d6
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/servers-dark.png differ
diff --git a/docs/verification/README.md b/docs/verification/README.md
index 308aafd97b..233688f13e 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -146,6 +146,10 @@ Admin server, including cancellation, revocation and unchanged normal startup.
The [personal Cloud account smoke](cloud-account.md) checks optional browser
sign-in, server-verified Pro status and sign-out in a disposable Electron profile.
+The [rail of Clouds](cloud-rail.md) checks the session's list of Clouds, which
+pages may read the rail, opening a place by its id, and buying another Cloud,
+with a loopback Admin and the real app in a disposable preview.
+
The [embedded server recovery smoke](desktop-server-recovery.md) crashes real
Electron-owned fixture servers, verifies bounded recovery and private access,
and proves quit cancels recovery without replaying an interrupted fixture turn.
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
new file mode 100644
index 0000000000..1b187de72e
--- /dev/null
+++ b/docs/verification/cloud-rail.md
@@ -0,0 +1,77 @@
+# The rail of Clouds and its +
+
+Once a person has two places or more (their Clouds, their teams' Clouds,
+servers they connected by hand), a narrow rail of circles at the window's left
+edge switches between them, and + buys another Cloud or adds a server of
+their own. With one place there is no rail, and the window looks as before.
+Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
+
+## Contract
+
+- The desktop session may list every Cloud of the person's (`clouds`, at most
+ 20, contract v1 `CloudEntry`). An older Admin sends none, and the session's
+ `cloud` and `teams` say everything exactly as before.
+- Each Cloud the person owns besides My Cloud is a saved place of its own,
+ named and coloured by the Admin, opened like a team's Cloud: the window pairs
+ it through the Admin's `pairing` with that Cloud's id and takes only a grant
+ for its own address. My Cloud stays the one home.
+- The rail's list carries names, colours and states, never an address, and goes
+ only to this app's own page and to pages of Clouds MausBot runs that the
+ verified session lists. A server's own page gets none; its switcher stays the
+ native Server menu. A circle opens only a place main listed, by its id, and
+ only from the person's click.
+- Buying another Cloud sends the plan, a name and a swatch to the Admin, which
+ answers with a checkout this app opens in the browser; the sheet then follows
+ the payment and the setup. An Admin that sells one Cloud per account (no
+ `clouds`, `canAdd` false, or no such route) is the calm "One Cloud per
+ account for now".
+- The place on screen tints the top of its sidebar in its colour, faintly
+ (`.place-tint`, stronger in dark skins, a thin line with reduced
+ transparency, none with forced colours); no colour, no tint. Settings →
+ Appearance changes it with the same six swatches: a Cloud's on the Admin
+ (`PATCH /api/cloud/desktop/clouds/:id`, its owner or its team's admins; a
+ member sees it locked), a server connected by hand on this computer. An
+ Admin without that route changes nothing and says so.
+- The person's own servers and computers that signed in with their account come
+ in the same list (`managed: false`, on a server, with or without an address).
+ They are never a Cloud of theirs to pair with or lend to: the rail shows them
+ with a server mark, offline with when they were last seen, one already
+ connected here as that saved place, one reachable but not connected with its
+ pairing steps, and one only reachable on its own network with nothing to
+ open.
+
+## Automated fixtures
+
+```sh
+node --test electron/cloud-list.node-test.mjs electron/cloud-account-clouds.node-test.mjs electron/cloud-rail.node-test.mjs electron/home-window.node-test.mjs electron/place-look.node-test.mjs
+pnpm exec vitest run src/components/PlacesRail.test.ts src/components/cloud-buy/AddCloudFlow.test.ts src/components/PlaceLookCard.test.ts
+```
+
+The account tests answer as a loopback Admin, with and without `clouds`. The
+rail tests load the production preload and check which page gets the list,
+which ids open, and that a circle, +, checkout and a colour change act only
+from a click. The colour tests check who may change a place's colour and where
+it is kept, that nothing is saved when the Admin refuses, and that the tint
+follows at once.
+
+## Rendered workflow
+
+```sh
+node --experimental-strip-types scripts/verify-cloud-rail.ts --shots .omb-scratch/verify-evidence/cloud-rail
+```
+
+It starts a disposable fake-engine server with three bots and the real app in
+a Vite preview (`scripts/testing/rail-preview.tsx`), answering the desktop
+bridge a hosted Cloud's page gets: six places, one being set up, one that needs
+its owner, eleven for the list past eight. A headless Chrome in a throwaway
+profile photographs the rail in Advanced and Simple mode (with the place's
+tint), the list past eight, +'s two choices, the steps for a server of one's
+own, the plans, the name and colour of a new Cloud and its setup, the person's
+signed-in servers and the steps to connect one, and the colour in Settings for
+an admin and for a team member, each in the Daylight and Midnight skins.
+`--only rail,look-settings` limits it to some views. Without `--shots` it
+prints the preview's address and waits for Ctrl-C.
+
+This is not production qualification: the places and the purchase are the
+preview's fixtures, and no Admin, browser checkout or desktop window is
+involved.
diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjs
new file mode 100644
index 0000000000..45a478df40
--- /dev/null
+++ b/electron/cloud-account-clouds.node-test.mjs
@@ -0,0 +1,206 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createServer } from "node:http";
+
+import { createCloudAccountClient } from "./cloud-account.mjs";
+
+const accessToken = `omc_${"T".repeat(43)}`;
+const NOW = 1_800_000_000_000;
+const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", TEAM = "https://omb-t-acme.fly.dev";
+const CHECKOUT = "https://test.checkout.dodopayments.com/session/cks_new";
+const entry = (over = {}) => ({ id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A,
+ teamId: null, seats: null, renewsAt: null, cancelAtPeriodEnd: false, primary: false, ...over });
+const PRIMARY = entry({ id: "c-home", name: "My Cloud", color: null, origin: HOME, primary: true });
+const paid = { plan: "pro", tier: "pro", status: "active", expiresAt: NOW + 30 * 86400_000, version: 1 };
+const grant = (origin) => ({ cloudContractVersion: 1, origin, code: "ABCD-EFGH-JK23", expiresAt: NOW + 60_000 });
+
+/** A fake Admin: the session says `f.session`, pairing answers `f.pairing(body)`, adding a Cloud answers `f.add(body)`. */
+async function admin(t) {
+ const f = { requests: [], browsers: [], timer: null, delay: null,
+ session: { cloud: { state: "ready", origin: HOME, pairingAvailable: true } },
+ pairing: () => [200, grant(HOME)], add: () => [404, { error: "not_found" }], patch: () => [404, { error: "not_found" }] };
+ const server = createServer(async (req, res) => {
+ let body = ""; for await (const chunk of req) body += chunk;
+ const parsed = body ? JSON.parse(body) : undefined;
+ f.requests.push({ route: req.url, method: req.method, body: parsed });
+ const send = ([status, data]) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(data)); };
+ if (req.headers.authorization !== `Bearer ${accessToken}`) return send([401, { error: "invalid_token" }]);
+ if (req.url === "/api/cloud/desktop/session") return send([200, { cloudContractVersion: 1, expiresAt: NOW + 86400_000, device: { id: "device-1" },
+ account: { id: "acct-1", email: "[email protected]" }, entitlement: paid, ...f.session }]);
+ if (req.url === "/api/cloud/desktop/pairing" && req.method === "POST") return send(f.pairing(parsed));
+ if (req.url === "/api/cloud/desktop/clouds" && req.method === "POST") return send(f.add(parsed));
+ if (req.url.startsWith("/api/cloud/desktop/clouds/") && req.method === "PATCH") return send(f.patch(decodeURIComponent(req.url.slice("/api/cloud/desktop/clouds/".length)), parsed));
+ if (req.url === "/api/public/config") return send([200, { plans: [{ tier: "pro", price: { currency: "USD", interval: "month", amount: 4900 } }], trial: { days: 7 } }]);
+ send([404, { error: "not_found" }]);
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ f.origin = `http://127.0.0.1:${server.address().port}`;
+ const saved = { origin: f.origin, token: accessToken, expiresAt: NOW + 86400_000, device: { id: "device-1" }, account: { id: "acct-1", email: "[email protected]" } };
+ f.client = createCloudAccountClient({ origin: f.origin, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.fixture", now: () => NOW,
+ store: { read: async () => saved, write: async () => {} }, openBrowser: async url => { f.browsers.push(url); },
+ setTimer: (callback, delay) => { f.timer = callback; f.delay = delay; return 1; }, clearTimer: () => { f.timer = null; f.delay = null; } });
+ t.after(async () => { f.client.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
+ return f;
+}
+
+test("an Admin without the list of Clouds: the session reads exactly as before, nothing to add, no other Cloud to pair", async t => {
+ const f = await admin(t);
+ const state = await f.client.start();
+ assert.equal(state.status, "connected");
+ for (const key of ["clouds", "addCloud", "adding"]) assert.equal(state[key], undefined, key);
+ assert.equal(f.client.isOwnCloud(HOME), true, "My Cloud is the person's own");
+ assert.equal(f.client.isOwnCloud(CLIENT_A), false);
+ await assert.rejects(f.client.pairHome("c-a"), error => error.gone === true);
+ assert.equal(f.requests.some(row => row.route.endsWith("/pairing")), false, "never asked");
+ assert.deepEqual(await f.client.pairHome(), { origin: HOME, code: "ABCD-EFGH-JK23", expiresAt: NOW + 60_000 });
+ assert.deepEqual(f.requests.at(-1).body, {}, "My Cloud's pairing sends the same empty body an older Admin knows");
+ assert.deepEqual(await f.client.addCloud({ tier: "pro", name: "Client B" }), { outcome: "unsupported" });
+ assert.equal(f.requests.some(row => row.route.endsWith("/clouds")), false);
+});
+
+test("the session's Clouds: each other own Cloud pairs with its id, and only a grant for its own address is taken", async t => {
+ const f = await admin(t);
+ f.session = { ...f.session, clouds: [PRIMARY, entry(), entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM })], canAdd: true };
+ const state = await f.client.start();
+ assert.deepEqual(state.clouds.map(cloud => cloud.id), ["c-home", "c-a", "c-team"]);
+ assert.deepEqual(state.addCloud, { canAdd: true });
+ assert.equal(state.latestVersion, undefined, "no newest release named: none");
+ f.session = { ...f.session, latestVersion: "0.1.130" };
+ assert.equal((await f.client.refresh()).latestVersion, "0.1.130");
+ f.session = { ...f.session, latestVersion: "<script>" };
+ assert.equal((await f.client.refresh()).latestVersion, undefined);
+ assert.deepEqual([HOME, CLIENT_A, TEAM, "https://evil.example.test", null].map(origin => f.client.isOwnCloud(origin)), [true, true, false, false, false], "a team's Cloud is not the person's own");
+ f.pairing = body => [200, grant(body?.cloudId === "c-a" ? CLIENT_A : HOME)];
+ assert.deepEqual(await f.client.pairHome("c-a"), { origin: CLIENT_A, code: "ABCD-EFGH-JK23", expiresAt: NOW + 60_000 });
+ assert.deepEqual(f.requests.at(-1).body, { cloudId: "c-a" });
+ f.pairing = () => [200, grant(HOME)];
+ await assert.rejects(f.client.pairHome("c-a"), /Invalid Cloud pairing response/, "a grant for another address is never taken");
+ await assert.rejects(f.client.pairHome("c-team"), error => error.gone === true, "a team's Cloud pairs through its team, never here");
+ f.pairing = () => [404, { error: "not_found" }];
+ await assert.rejects(f.client.pairHome("c-a"), error => error.gone === true && /no longer one of your Clouds/.test(error.message));
+ f.pairing = () => [409, { error: "not_running" }];
+ await assert.rejects(f.client.pairHome("c-a"), /isn't running right now/);
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ status: "setting_up", origin: null })] };
+ await f.client.refresh();
+ await assert.rejects(f.client.pairHome("c-a"), /isn't ready to open yet/);
+ assert.equal(f.delay, 15_000, "a Cloud of theirs being set up is checked every 15 s");
+});
+
+test("buying another Cloud: the plan, the name and the swatch go to the Admin, its own checkout opens, and the session is followed every 3 s", async t => {
+ const f = await admin(t);
+ f.session = { ...f.session, clouds: [PRIMARY] };
+ await f.client.start();
+ await assert.rejects(f.client.addCloud({ tier: "pro", name: "" }), /Invalid Cloud/);
+ await assert.rejects(f.client.addCloud({ tier: "pro", name: "Client B", color: "url(x)" }), /Invalid Cloud/);
+ await assert.rejects(f.client.addCloud({ tier: "pro", interval: "week", name: "Client B" }), /Invalid Cloud/);
+ f.add = () => [200, { cloudId: "c-b", checkoutUrl: "https://evil.example.test/pay" }];
+ assert.deepEqual(await f.client.addCloud({ tier: "pro", name: "Client B", color: "rose" }), { outcome: "failed" }, "only Dodo's own checkout ever opens");
+ assert.deepEqual(f.browsers, []);
+ f.add = () => [200, { cloudContractVersion: 1, cloudId: "c-b", checkoutUrl: CHECKOUT }];
+ const opened = await f.client.addCloud({ tier: "pro", name: " Client B ", color: "rose" });
+ assert.equal(opened.outcome, "opened");
+ assert.deepEqual(f.requests.at(-1).body, { tier: "pro", interval: "month", name: "Client B", color: "rose" });
+ assert.deepEqual(f.browsers, [CHECKOUT]);
+ assert.deepEqual(opened.state.adding, { cloudId: "c-b", name: "Client B", color: "rose", tier: "pro", startedAt: NOW, link: true });
+ assert.equal(JSON.stringify(opened.state).includes(CHECKOUT), false, "the checkout page stays in main");
+ assert.equal(f.client.addLink(), CHECKOUT);
+ assert.equal(f.delay, 3_000);
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ id: "c-b", name: "Client B", status: "checkout", origin: null })] };
+ f.timer(); await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(f.delay, 3_000, "still waiting for the payment");
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ id: "c-b", name: "Client B", status: "setting_up", origin: null })] };
+ await f.client.refresh();
+ assert.equal(f.delay, 15_000, "paid: setting up");
+ assert.equal(await f.client.reopenAdd(), true);
+ assert.deepEqual(f.browsers, [CHECKOUT, CHECKOUT], "Reopen opens the same page, never a new one");
+ f.client.addDone();
+ assert.equal(f.client.state().adding.done, true);
+});
+
+test("the Admin's word on adding: a cap or another open checkout, too many at once, or an Admin without the route", async t => {
+ const f = await admin(t);
+ f.session = { ...f.session, clouds: [PRIMARY], canAdd: false, addBlocked: "cap" };
+ await f.client.start();
+ assert.deepEqual(f.client.state().addCloud, { canAdd: false, blocked: "cap" });
+ assert.deepEqual(await f.client.addCloud({ tier: "pro", name: "Client B" }), { outcome: "blocked", blocked: "cap" }, "the session's word: nothing is asked");
+ assert.equal(f.requests.some(row => row.route.endsWith("/clouds")), false);
+ f.session = { ...f.session, canAdd: undefined, addBlocked: undefined };
+ await f.client.refresh();
+ for (const [answer, outcome] of [
+ [[409, { error: "checkout_conflict", addBlocked: "cap" }], { outcome: "blocked", blocked: "cap" }],
+ [[503, { error: "temporarily_unavailable", addBlocked: "signups_closed", interval: 60 }], { outcome: "blocked", blocked: "signups_closed" }],
+ [[429, { error: "rate_limited", addBlocked: "rate", interval: 600 }], { outcome: "blocked", blocked: "rate" }],
+ [[409, { error: "blocked", addBlocked: "mystery" }], { outcome: "blocked", blocked: "cap" }],
+ [[429, { error: "rate_limited" }], { outcome: "blocked", blocked: "rate" }],
+ [[503, { error: "temporarily_unavailable" }], { outcome: "failed" }],
+ [[404, { error: "not_found" }], { outcome: "unsupported" }],
+ [[500, { error: "oops" }], { outcome: "failed" }],
+ ]) {
+ f.add = () => answer;
+ assert.deepEqual(await f.client.addCloud({ tier: "pro", name: "Client B" }), outcome, JSON.stringify(answer));
+ }
+ assert.deepEqual(f.browsers, []);
+ assert.equal(f.client.state().adding, undefined, "no checkout kept from a refusal that names none");
+});
+
+test("another Cloud's checkout still open: the Admin's page for it is kept here to reopen or copy, never opened by itself", async t => {
+ const f = await admin(t);
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ id: "c-b", name: "Client B", status: "checkout", origin: null, color: "violet" })] };
+ await f.client.start();
+ assert.equal(await f.client.reopenAdd(), false, "watched, with no page of its own yet");
+ f.add = () => [409, { error: "checkout_conflict", addBlocked: "checkout_open", checkoutUrl: CHECKOUT }];
+ assert.deepEqual(await f.client.addCloud({ tier: "max", name: "Client C" }), { outcome: "blocked", blocked: "checkout_open" });
+ assert.deepEqual(f.browsers, [], "the person asked for another Cloud, not this one: nothing opens by itself");
+ assert.deepEqual(f.client.state().adding, { cloudId: "c-b", name: "Client B", color: "violet", tier: "pro", startedAt: NOW, link: true });
+ assert.equal(f.client.addLink(), CHECKOUT);
+ assert.equal(await f.client.reopenAdd(), true);
+ assert.deepEqual(f.browsers, [CHECKOUT]);
+ const fresh = await admin(t);
+ fresh.session = { ...fresh.session, clouds: [PRIMARY] };
+ await fresh.client.start();
+ fresh.add = () => [409, { error: "checkout_conflict", addBlocked: "checkout_open", checkoutUrl: "https://evil.example.test/pay" }];
+ assert.deepEqual(await fresh.client.addCloud({ tier: "pro", name: "Client B" }), { outcome: "blocked", blocked: "checkout_open" });
+ assert.equal(fresh.client.state().adding, undefined, "only Dodo's own checkout page is ever kept");
+});
+
+test("a Cloud waiting at checkout that this app did not open (it restarted mid-checkout) is followed as its own, at the usual pace", async t => {
+ const f = await admin(t);
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ id: "c-b", name: "Client B", status: "checkout", origin: null, color: "violet" })] };
+ const state = await f.client.start();
+ assert.deepEqual(state.adding, { cloudId: "c-b", name: "Client B", color: "violet", tier: "pro", startedAt: NOW });
+ assert.equal(f.delay, 60_000, "a checkout this app did not open is not polled every few seconds");
+ assert.equal(await f.client.reopenAdd(), false, "no page kept here to reopen");
+});
+
+test("a Cloud's colour is the Admin's: PATCH with the swatch, then the session read again; someone else's say, an older Admin and a signed-in server are said plainly", async t => {
+ const f = await admin(t);
+ const MINI = entry({ id: "s-mini", name: "Mac mini", runsOn: "server", managed: false, status: "ready", origin: "https://mini.example.ts.net" });
+ f.session = { ...f.session, clouds: [PRIMARY, entry(), MINI] };
+ await f.client.start();
+ assert.equal(f.client.isOwnCloud("https://mini.example.ts.net"), false, "a server that only signed in is no Cloud of theirs");
+ f.patch = (id, body) => {
+ f.session = { ...f.session, clouds: [PRIMARY, entry({ color: body.color }), MINI] };
+ return [200, { cloudContractVersion: 1, cloud: entry({ color: body.color }) }];
+ };
+ const reads = () => f.requests.filter(row => row.route === "/api/cloud/desktop/session").length, before = reads();
+ assert.deepEqual(await f.client.setCloudColor("c-a", "rose"), { outcome: "saved" });
+ assert.deepEqual(f.requests.find(row => row.method === "PATCH"), { route: "/api/cloud/desktop/clouds/c-a", method: "PATCH", body: { color: "rose" } });
+ assert.equal(reads(), before + 1, "the session is read again, so every place follows the Admin");
+ assert.equal(f.client.state().clouds.find(cloud => cloud.id === "c-a").color, "rose");
+ await f.client.setCloudColor("c-home", null);
+ assert.deepEqual(f.requests.at(-2).body, { color: null }, "none: the plain look");
+ f.patch = () => [403, { error: "forbidden" }];
+ assert.deepEqual(await f.client.setCloudColor("c-a", "blue"), { outcome: "refused" });
+ for (const status of [404, 405, 501]) {
+ f.patch = () => [status, { error: "not_found" }];
+ assert.deepEqual(await f.client.setCloudColor("c-a", "blue"), { outcome: "unsupported" }, String(status));
+ }
+ f.patch = () => [500, { error: "server_error" }];
+ assert.deepEqual(await f.client.setCloudColor("c-a", "blue"), { outcome: "failed" });
+ const patches = f.requests.filter(row => row.method === "PATCH").length;
+ assert.deepEqual(await f.client.setCloudColor("s-mini", "blue"), { outcome: "unsupported" }, "a server that only signed in has no Cloud colour to change");
+ assert.deepEqual(await f.client.setCloudColor("c-gone", "blue"), { outcome: "unsupported" });
+ assert.equal(f.requests.filter(row => row.method === "PATCH").length, patches, "neither was asked");
+ await assert.rejects(f.client.setCloudColor("c-a", "chartreuse"), /Invalid Cloud color/);
+ await assert.rejects(f.client.setCloudColor("../c-a", "blue"), /Invalid Cloud color/);
+});
diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mts
index 8d82ec2c35..2ffb0e85e0 100644
--- a/electron/cloud-account.d.mts
+++ b/electron/cloud-account.d.mts
@@ -21,6 +21,17 @@ export interface CloudAccountState {
machine?: import("./cloud-home.mjs").CloudMachine;
/** Connected: the teams this account is in, each with its Cloud; absent while it is in none. */
teams?: import("./cloud-home.mjs").CloudTeam[];
+ /** Connected to an Admin that lists every Cloud of the person's (contract v1 `clouds`): each of them, My Cloud first.
+ * Absent from an older Admin, whose `machine` and `teams` say everything. */
+ clouds?: import("./cloud-list.mjs").CloudListEntry[];
+ /** With `clouds`: whether the Admin opens another Cloud's checkout now, and why not. */
+ addCloud?: { canAdd: true } | { canAdd: false; blocked: CloudAddBlock };
+ /** The newest OpenMausBot release the Admin knows, while it follows releases (with `clouds`); absent otherwise. */
+ latestVersion?: string;
+ /** Another Cloud this app is buying (in the last 24 hours): its id, name, swatch and plan, when its checkout opened,
+ * whether main keeps that page (`link`), and `done` once it was opened or announced. */
+ /** `cloudId` null: a checkout the Admin said is still open, before the session lists its Cloud. */
+ adding?: { cloudId: string | null; name: string; color: import("./cloud-list.mjs").CloudSwatch | null; tier: string | null; startedAt: number; link?: true; done?: true };
/** A payment OMB Cloud received and is still linking to this account. */
purchase?: import("./cloud-home.mjs").CloudPurchase;
/** Connected: the free trial on this account's Cloud, when the Admin says (display only). */
@@ -55,6 +66,15 @@ export type CloudSignInVerify =
| { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> };
/** How the Cloud is shown in this app's switcher and Settings → Servers. */
export interface CloudHomeLook { name: string; color: import("./cloud-buy.mjs").CloudColor }
+/** Why the Admin opens no other Cloud's checkout now (contract v1 `addBlocked`). */
+export type CloudAddBlock = "cap" | "checkout_open" | "rate" | "signups_closed";
+export declare const ADD_BLOCKS: readonly CloudAddBlock[];
+/** What buying another Cloud did: `opened` its checkout in the browser; `unsupported` (this Admin sells one Cloud per
+ * account); `blocked` with the Admin's reason; or `failed` (nothing was opened). */
+export type CloudAddResult =
+ | { outcome: "opened"; state: CloudAccountState }
+ | { outcome: "unsupported" | "failed" }
+ | { outcome: "blocked"; blocked: CloudAddBlock };
/** What opening a checkout did: `opened` in the browser; `signing-in` (signed
* out, the browser signs in first); `conflict` (the account changed, now read
* again); `rate-limited`; or `failed` (nothing was opened). */
@@ -212,7 +232,21 @@ export interface CloudAccountClient {
/** Asks the Admin to start a sleeping Cloud (POST /api/cloud/desktop/wake), then reads the session again. */
wakeHome(): Promise<"awake" | "waking" | null>;
setWaking(on: boolean): void;
- pairHome(): Promise<import("./cloud-home.mjs").CloudHomeGrant>;
+ /** My Cloud's one-time code, or (`cloudId`) another Cloud of the person's own that the verified session lists, its
+ * grant for that Cloud's own address only. Rejects with `gone: true` once that Cloud is no longer theirs. */
+ pairHome(cloudId?: string | null): Promise<import("./cloud-home.mjs").CloudHomeGrant>;
+ /** `origin` is a Cloud the person owns (My Cloud or another of theirs), by the verified session only. */
+ isOwnCloud(origin: string | null | undefined): boolean;
+ /** Buys another Cloud (POST /api/cloud/desktop/clouds): its checkout opens in the browser. */
+ addCloud(input: { tier: string; interval?: "month" | "year"; name: string; color?: import("./cloud-list.mjs").CloudSwatch | null }): Promise<CloudAddResult>;
+ /** A Cloud's colour on the Admin (PATCH /api/cloud/desktop/clouds/:id), for its owner or its team's Super admin and Admins. */
+ setCloudColor(cloudId: string, color: import("./cloud-list.mjs").CloudSwatch | null): Promise<{ outcome: "saved" | "refused" | "unsupported" | "failed" }>;
+ /** That checkout's page again (never a new one); false when none is kept. */
+ reopenAdd(): Promise<boolean>;
+ /** Main only (the clipboard): that checkout's page, or null. */
+ addLink(): string | null;
+ /** The Cloud being bought was opened or announced: that purchase is over. */
+ addDone(): void;
/** A one-time code for a team's Cloud, signed by the Admin with this person's membership (POST
* /api/cloud/desktop/teams/<id>/pairing). Rejects with `gone: true` once they are no longer in the team. */
pairTeam(teamId: string): Promise<import("./cloud-home.mjs").CloudHomeGrant>;
diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjs
index 2ab8ea9df6..077360d1b9 100644
--- a/electron/cloud-account.mjs
+++ b/electron/cloud-account.mjs
@@ -1,5 +1,6 @@
import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managed-desktop.mjs";
import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";
+import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, otherOwnClouds, ownCloud, parseCloudList, releaseVersion } from "./cloud-list.mjs";
import { planTeam, teamPlan } from "./cloud-team-plan.mjs";
import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";
@@ -34,6 +35,9 @@ export const UPGRADE_SOURCES = Object.freeze(["app_usage", "app_settings"]);
const UPGRADE_TIERS = Object.freeze(["starter", "personal", "pro", "max"]);
const UPGRADE_REFUSALS = Object.freeze(["payment_failed", "not_subscribed", "already_on_plan", "plan_change_unavailable", "confirmation_required", "price_changed", "rate_limited"]);
const CONFIRMATION = /^[A-Za-z0-9_-]{43}$/;
+/** Why the Admin won't open another Cloud's checkout now (POST clouds, 409 `addBlocked`; contract v1). */
+export const ADD_BLOCKS = Object.freeze(["cap", "checkout_open", "rate", "signups_closed"]);
+const ADD_INTERVALS = Object.freeze(["month", "year"]);
const CHECKOUT_ORIGIN = "https://checkout.dodopayments.com", TEST_CHECKOUT_ORIGIN = "https://test.checkout.dodopayments.com";
/** Only Dodo's own HTTPS checkout origin, with no credentials and no fragment; anything else is never opened. Staging's
* Admin sells in Dodo's test mode, so its checkouts are only Dodo's test page. */
@@ -65,6 +69,12 @@ function planHint(value) {
/** Only the Admin's own JSON "invalid_token" ends a sign-in; a 401/403 page from Cloudflare or a proxy does not. */
const signInEnded = error => [401, 403].includes(error?.status) && error.code === "invalid_token";
const sameHint = (left, right) => (left?.tier ?? null) === (right?.tier ?? null) && (left?.active ?? null) === (right?.active ?? null);
+/** Whether the Admin opens another Cloud's checkout for this account now, as its session says (`canAdd` and
+ * `addBlocked`, both optional): without its word the answer is yes, and POST clouds says otherwise. */
+function addOffer(result) {
+ if (result?.canAdd !== false) return { canAdd: true };
+ return { canAdd: false, blocked: ADD_BLOCKS.includes(result.addBlocked) ? result.addBlocked : "cap" };
+}
export function createCloudAccountClient({ store, openBrowser, platform, deviceName, appVersion,
origin = CLOUD_ORIGIN, fixture = false, fetch: fetcher = globalThis.fetch, now = Date.now, onState = () => {},
@@ -78,6 +88,8 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
let offerCache = null, offerPending = null, waking = false;
/** The checkout this app opened, its address kept here for Reopen and Copy link: never published, never asked for again. */
let opened = null;
+ /** Another Cloud this app is buying (POST clouds): its id, name, colour and plan, and its checkout page, kept like `opened`'s. */
+ let adding = null;
/** An email code on its way: the attempt the Admin answered, kept in main only. */
let emailed = null;
const newerPlans = new Set();
@@ -88,9 +100,11 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
};
const checkout = () => opened && now() - opened.startedAt < CHECKOUT_KEPT_MS
? { plan: opened.plan, startedAt: opened.startedAt, ...(opened.signIn ? { signIn: true } : {}), ...(opened.url ? { link: true } : {}), ...(opened.done ? { done: true } : {}) } : null;
+ const buying = () => adding && now() - adding.startedAt < CHECKOUT_KEPT_MS
+ ? { cloudId: adding.cloudId, name: adding.name, color: adding.color, tier: adding.tier, startedAt: adding.startedAt, ...(adding.url ? { link: true } : {}), ...(adding.done ? { done: true } : {}) } : null;
const withCheckout = current => {
- const open = checkout(), shown = waking && current.status === "connected" ? { ...current, waking: true } : current;
- const next = open ? { ...shown, checkout: open } : shown;
+ const open = checkout(), add = buying(), shown = waking && current.status === "connected" ? { ...current, waking: true } : current;
+ const next = { ...shown, ...(open ? { checkout: open } : {}), ...(add ? { adding: add } : {}) };
return staging ? { ...next, staging: true } : next;
};
const state = () => {
@@ -102,6 +116,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
return structuredClone(withCheckout(value));
};
const watching = () => Boolean(opened && now() - opened.startedAt < CHECKOUT_WATCH_MS);
+ const watchingAdd = () => Boolean(adding && !adding.done && now() - adding.startedAt < CHECKOUT_WATCH_MS);
const publish = next => { value = next; onState(state()); return state(); };
const record = (saved, hint) => ({ ...saved, ...(hint ? { planHint: hint } : {}) });
const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; };
@@ -132,7 +147,8 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, opaque: true });
throw new Error("Invalid Cloud response.");
}
- if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, code: data?.error, interval: data?.interval });
+ if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, code: data?.error, interval: data?.interval, blocked: data?.addBlocked,
+ ...(typeof data?.checkoutUrl === "string" ? { checkoutUrl: data.checkoutUrl } : {}) });
return data;
}
function identity(result) {
@@ -177,10 +193,14 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
const machine = current.status === "connected" ? current.machine : undefined;
return machine?.origin && CLOUD_MACHINE_CONNECTABLE.includes(machine.status) ? { origin: machine.origin } : null;
}
+ function otherOwnCloud(cloudId) {
+ const current = state();
+ return current.status === "connected" ? otherOwnClouds(current.clouds).find(cloud => cloud.id === cloudId) ?? null : null;
+ }
function forget({ quiet = false } = {}) {
if (clearing) return clearing;
const previous = grant ?? issued ?? cleanup, stamp = reset();
- grant = null; issued = null; cleanup = previous; cleanupNeeded = true; plan = null; savedHint = null; opened = null;
+ grant = null; issued = null; cleanup = previous; cleanupNeeded = true; plan = null; savedHint = null; opened = null; adding = null;
if (!quiet) publish({ status: "signed-out" });
const operation = (async () => {
const [persisted, revoked] = await Promise.allSettled([Promise.resolve().then(() => store.write(null)), previous ? revoke(previous) : Promise.resolve()]);
@@ -208,6 +228,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
const purchase = parseCloudPurchase(result.cloud?.purchase);
const trial = parseCloudTrial(result.cloud?.trial), credit = parseCloudCredit(result.cloud?.credit), offer = parseCloudOffer(result.offer);
const usage = access.status === "active" ? parseCloudUsage(result.cloud?.usage) : null;
+ const clouds = parseCloudList(result.clouds), more = clouds ? addOffer(result) : null, latest = clouds ? releaseVersion(result.latestVersion) : null;
const hint = access.plan === "pro" ? { ...(access.tier ? { tier: access.tier } : {}), active: access.status === "active" } : null;
if (next.expiresAt !== previous.expiresAt) {
const replacement = { ...previous, expiresAt: next.expiresAt };
@@ -225,13 +246,22 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
if (!opened && offer?.checkout && offer.checkout.openUntil > now() && access.status !== "active") {
opened = { plan: offer.checkout.plan, source: null, startedAt: now() };
}
+ // Another Cloud at checkout with none kept here (this app restarted mid-checkout, or it was bought elsewhere): watched
+ // as this app's own, so "ready" is said for it too.
+ const waitingCloud = otherOwnClouds(clouds).find(cloud => cloud.status === "checkout");
+ if (!adding && waitingCloud) adding = { cloudId: waitingCloud.id, name: waitingCloud.name, color: waitingCloud.color, tier: waitingCloud.tier, startedAt: now(), url: null };
+ // A checkout kept from the Admin's "one is still open" answer, before the session listed its Cloud: that Cloud now.
+ else if (adding && adding.cloudId === null && waitingCloud) adding = { ...adding, cloudId: waitingCloud.id, name: waitingCloud.name, color: waitingCloud.color, tier: waitingCloud.tier ?? adding.tier };
verifiedUntil = Math.min(grant.expiresAt, now() + STEADY_MS,
access.status === "active" && access.expiresAt !== null ? access.expiresAt : Infinity);
publish({ ...view("connected"), entitlement: access, ...(machine ? { machine } : {}), ...(teams.length ? { teams } : {}), ...(purchase ? { purchase } : {}),
- ...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}), verifiedAt: now(), verifiedUntil });
+ ...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}),
+ ...(clouds ? { clouds, addCloud: more } : {}), ...(latest ? { latestVersion: latest } : {}), verifiedAt: now(), verifiedUntil });
const planCloud = teamPlan(value) ? planTeam(value)?.machine ?? null : machine;
- const settingUp = planCloud?.status === "provisioning" || (access.status === "active" && !planCloud) || Boolean(purchase);
- const delay = watching() && planCloud?.status !== "ready" ? WATCH_REFRESH_MS : settingUp ? SETUP_REFRESH_MS : awaitingWake() ? ASLEEP_REFRESH_MS : REFRESH_MS;
+ const settingUp = planCloud?.status === "provisioning" || (access.status === "active" && !planCloud) || Boolean(purchase) || otherOwnClouds(clouds).some(cloud => cloud.status === "setting_up");
+ const added = adding ? clouds?.find(cloud => cloud.id === adding.cloudId) ?? null : null;
+ const paying = watchingAdd() && Boolean(adding.url) && (!added || added.status === "checkout");
+ const delay = (watching() && planCloud?.status !== "ready") || paying ? WATCH_REFRESH_MS : settingUp ? SETUP_REFRESH_MS : awaitingWake() ? ASLEEP_REFRESH_MS : REFRESH_MS;
schedule(refresh, Math.min(delay, verifiedUntil - now()));
} catch (error) {
if (!current(stamp)) return state();
@@ -526,9 +556,26 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
if (!disk || !Number.isSafeInteger(disk.gb) || !Number.isSafeInteger(disk.maxGb) || disk.gb < 1 || disk.maxGb < disk.gb) throw new Error("Invalid Cloud disk response.");
return { supported: true, disk: { gb: disk.gb, maxGb: disk.maxGb } };
},
- /** The code goes to main only, for one navigation, and is not kept. */
- async pairHome() {
- const target = homeTarget(), current = grant;
+ /** The code goes to main only, for one navigation, and is not kept. `cloudId`: another Cloud of the person's own
+ * that the verified session lists (the Admin answers 404 once it is not theirs any more: `gone`); none is My Cloud,
+ * which an older Admin pairs from the same empty body. The grant must be for that Cloud's own address. */
+ async pairHome(cloudId = null) {
+ const current = grant;
+ if (cloudId !== null) {
+ const cloud = otherOwnCloud(cloudId);
+ if (!current || !cloud) throw Object.assign(new Error("That Cloud is no longer one of yours."), { gone: true });
+ if (!cloud.origin || !["ready", "offline"].includes(cloud.status)) throw new Error(`${cloud.name} isn't ready to open yet.`);
+ let result;
+ try { result = await request("pairing", { method: "POST", body: { cloudId }, token: current.token }); } catch (error) {
+ if (error?.status === 404 && !error.opaque) { void refresh().catch(() => {}); throw Object.assign(new Error(`${cloud.name} is no longer one of your Clouds.`), { gone: true }); }
+ if (error?.status === 409) throw new Error(`${cloud.name} isn't running right now.`);
+ throw error;
+ }
+ const pairing = parsePairingGrant(result, cloud.origin, now());
+ if (!pairing) throw new Error("Invalid Cloud pairing response.");
+ return pairing;
+ }
+ const target = homeTarget();
if (!target || !current) throw new Error("My Cloud is not ready to connect yet.");
let result;
try { result = await request("pairing", { method: "POST", body: {}, token: current.token }); } catch (error) {
@@ -539,6 +586,87 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
if (!pairing) throw new Error("Invalid Cloud pairing response.");
return pairing;
},
+ /** `origin` is the address of a Cloud the person owns (My Cloud or another of theirs), by the verified session only. */
+ isOwnCloud(origin) {
+ const current = state();
+ if (typeof origin !== "string" || !origin || current.status !== "connected") return false;
+ return current.machine?.origin === origin || (current.clouds ?? []).some(cloud => ownCloud(cloud) && cloud.origin === origin);
+ },
+ /** Buys another Cloud (POST clouds; contract v1): the plan, how often it is paid, its name and its swatch. The
+ * Admin's checkout opens in the browser and its page is kept here for Reopen and Copy link, as the first Cloud's is;
+ * the session is then read every few seconds until the Cloud is paid for. `unsupported`: this Admin sells one Cloud
+ * per account; `blocked` with the Admin's reason. */
+ async addCloud({ tier, interval = "month", name, color = null } = {}) {
+ const cleanName = cleanCloudListName(name);
+ if (typeof tier !== "string" || !TIER.test(tier) || !ADD_INTERVALS.includes(interval) || !cleanName || !(color === null || CLOUD_SWATCHES.includes(color))) {
+ throw new Error("Invalid Cloud to add.");
+ }
+ const signedIn = grant;
+ if (!signedIn || state().status !== "connected") return { outcome: "failed" };
+ if (!value.clouds) return { outcome: "unsupported" };
+ if (value.addCloud?.canAdd === false) return { outcome: "blocked", blocked: value.addCloud.blocked };
+ let result;
+ try { result = await request("clouds", { method: "POST", body: { tier, interval, name: cleanName, ...(color ? { color } : {}) }, token: signedIn.token }); } catch (error) {
+ if (signInEnded(error)) { await refresh().catch(() => {}); return { outcome: "failed" }; }
+ // The Admin's own reason wins, whatever the status (409 cap or open checkout, 429 rate, 503 sign-ups closed).
+ const blocked = !error?.opaque && ADD_BLOCKS.includes(error?.blocked) ? error.blocked : null;
+ if (blocked === "checkout_open") {
+ // Another Cloud's checkout is still open: its page is kept here, as one this app opened, to reopen or copy.
+ const open = checkoutDestination(error.checkoutUrl, { fixture, staging });
+ const listed = otherOwnClouds(value.clouds).find(cloud => cloud.status === "checkout") ?? null;
+ if (open && grant === signedIn) {
+ adding = { cloudId: listed?.id ?? null, name: listed?.name ?? cleanName, color: listed ? listed.color : color, tier: listed?.tier ?? tier, startedAt: now(), url: open };
+ publish(value);
+ schedule(refresh, WATCH_REFRESH_MS);
+ }
+ }
+ if (blocked) return { outcome: "blocked", blocked };
+ if (!error?.opaque && error?.status === 409) return { outcome: "blocked", blocked: "cap" };
+ if (!error?.opaque && error?.status === 429) return { outcome: "blocked", blocked: "rate" };
+ if ([404, 405, 501].includes(error?.status)) return { outcome: "unsupported" };
+ return { outcome: "failed" };
+ }
+ const destination = checkoutDestination(result?.checkoutUrl, { fixture, staging });
+ if ((result?.cloudContractVersion !== undefined && result.cloudContractVersion !== 1) || typeof result?.cloudId !== "string" || !CLOUD_ID.test(result.cloudId) || !destination) return { outcome: "failed" };
+ if (grant !== signedIn) return { outcome: "failed" };
+ await openBrowser(destination);
+ adding = { cloudId: result.cloudId, name: cleanName, color, tier, startedAt: now(), url: destination };
+ publish(value);
+ schedule(refresh, WATCH_REFRESH_MS);
+ return { outcome: "opened", state: state() };
+ },
+ /** A Cloud's colour (PATCH clouds/:id, contract v1), which only its owner or its team's Super admin and Admins
+ * change: `saved` once the Admin keeps it (the session is read again, so every place follows); `refused` when the
+ * Admin says it is someone else's to change; `unsupported` from an Admin without the route or the list. */
+ async setCloudColor(cloudId, color) {
+ if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId) || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error("Invalid Cloud color.");
+ const signedIn = grant;
+ if (!signedIn || state().status !== "connected") return { outcome: "failed" };
+ if (!value.clouds?.some(cloud => cloud.id === cloudId && cloud.managed !== false)) return { outcome: "unsupported" };
+ try { await request(`clouds/${encodeURIComponent(cloudId)}`, { method: "PATCH", body: { color }, token: signedIn.token }); } catch (error) {
+ if (signInEnded(error)) { await refresh().catch(() => {}); return { outcome: "failed" }; }
+ if (!error?.opaque && error?.status === 403) return { outcome: "refused" };
+ if ([404, 405, 501].includes(error?.status)) return { outcome: "unsupported" };
+ return { outcome: "failed" };
+ }
+ if (grant === signedIn) await refresh().catch(() => {});
+ return { outcome: "saved" };
+ },
+ /** The Cloud being bought's checkout, again: the same page while it is kept here; false when there is none. */
+ async reopenAdd() {
+ const kept = adding;
+ if (!kept?.url) return false;
+ await openBrowser(kept.url);
+ if (adding !== kept) return false;
+ adding = { ...kept, startedAt: now() };
+ publish(value);
+ schedule(refresh, WATCH_REFRESH_MS);
+ return true;
+ },
+ /** For main's clipboard only: that checkout's page. */
+ addLink: () => (adding?.url && now() - adding.startedAt < CHECKOUT_KEPT_MS ? adding.url : null),
+ /** The Cloud this app bought was opened or announced: that purchase is over. */
+ addDone() { if (adding && !adding.done) { adding = { ...adding, done: true }; publish(value); } },
/** A one-time code for a team's Cloud, signed by the Admin with this person's membership: main only, for one
* navigation. The Admin answers 404 once they are no longer in the team (`gone`), 409 while its Cloud isn't running. */
async pairTeam(teamId) {
diff --git a/electron/cloud-buy.mjs b/electron/cloud-buy.mjs
index 23d3e0e575..d0f677c180 100644
--- a/electron/cloud-buy.mjs
+++ b/electron/cloud-buy.mjs
@@ -108,7 +108,7 @@ export function createCloudLook({ store, accountId, homeEntry, saveEntry }) {
/** openmausbot://cloud, the same with or without a checkout waiting: the sheet while a purchase made here is under way
* (a checkout opened in the last day, a payment being linked, setup), else Settings, which signs in or opens the Cloud. */
export function cloudLinkOpensSheet(state) {
- return Boolean((state?.checkout && !state.checkout.done) || state?.purchase || state?.machine?.status === "provisioning");
+ return Boolean((state?.checkout && !state.checkout.done) || (state?.adding && !state.adding.done) || state?.purchase || state?.machine?.status === "provisioning");
}
/** Paid, and the Cloud still being made: a payment linked, no machine yet, or one setting up. */
diff --git a/electron/cloud-home.mjs b/electron/cloud-home.mjs
index f74153c609..0cb5d90b1a 100644
--- a/electron/cloud-home.mjs
+++ b/electron/cloud-home.mjs
@@ -13,7 +13,7 @@ const ADMIN_STATES = Object.freeze({
const CODE = /^[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}$/;
const MAX_GRANT_MS = 10 * 60_000;
-function homeOrigin(value) {
+export function homeOrigin(value) {
if (typeof value !== "string" || value.length > 300) return null;
try {
const url = new URL(value);
diff --git a/electron/cloud-list.d.mts b/electron/cloud-list.d.mts
new file mode 100644
index 0000000000..c6135e5e13
--- /dev/null
+++ b/electron/cloud-list.d.mts
@@ -0,0 +1,47 @@
+export type CloudListStatus = "checkout" | "setting_up" | "ready" | "stopped" | "payment_problem" | "ended" | "offline";
+/** The Admin's six colour swatches. */
+export type CloudSwatch = "blue" | "green" | "amber" | "rose" | "violet" | "slate";
+/** One Cloud of the verified session's `clouds` (contract v1), as this app reads it: never an address a page gave. */
+export interface CloudListEntry {
+ id: string;
+ name: string;
+ color: CloudSwatch | null;
+ role: "owner" | "admin" | "member";
+ tier: string | null;
+ /** Where it runs: MausBot Cloud, or a server of the person's own. */
+ runsOn: "cloud" | "server";
+ status: CloudListStatus;
+ origin: string | null;
+ /** A Team or Business Cloud: the team behind its People. */
+ teamId: string | null;
+ /** The account's oldest open Cloud of its own: My Cloud. */
+ primary: boolean;
+ /** False for a server or computer of the person's own that signed in with their account (absent: MausBot runs or
+ * manages it). */
+ managed: boolean;
+ /** While it is set up: the step it is at and how far along it is (0 to 1), when the Admin says. */
+ setup?: { step?: import("./cloud-home.mjs").CloudSetupStep; progress?: number };
+ /** When the Admin last heard from it (ms). */
+ lastSeenAt?: number;
+ /** The OpenMausBot version it runs, for an update reminder. */
+ version?: string;
+}
+export declare const MAX_CLOUDS: number;
+export declare const CLOUD_LIST_STATUSES: readonly CloudListStatus[];
+export declare const CLOUD_SWATCH_COLORS: Readonly<Record<CloudSwatch, import("./cloud-buy.mjs").CloudColor | null>>;
+export declare const CLOUD_SWATCHES: readonly CloudSwatch[];
+export declare const CLOUD_ID: RegExp;
+export declare const CLOUD_NAME_LIMIT: number;
+export declare function cleanCloudListName(value: unknown): string | null;
+export declare function ownCloud(cloud: CloudListEntry | null | undefined): boolean;
+export declare function signedInServers(clouds: CloudListEntry[] | null | undefined): CloudListEntry[];
+export declare function releaseVersion(value: unknown): string | null;
+export declare function olderRelease(version: unknown, latest: unknown): boolean;
+export declare function parseCloudList(input: unknown): CloudListEntry[] | null;
+export declare function otherOwnClouds(clouds: CloudListEntry[] | null | undefined): CloudListEntry[];
+export declare function cloudMachine(cloud: CloudListEntry | null | undefined): import("./cloud-home.mjs").CloudMachine | null;
+export declare function stepProgress(step: unknown): number;
+export declare function cloudSetupProgress(cloud: CloudListEntry | null | undefined): number | null;
+export declare function swatchColor(swatch: unknown): import("./cloud-buy.mjs").CloudColor | null;
+export declare function listedColors(clouds: CloudListEntry[] | null | undefined): Array<{ home?: true; teamId?: string; color: import("./cloud-buy.mjs").CloudColor | null }>;
+export declare function ownCloudPlaces(clouds: CloudListEntry[] | null | undefined): Array<{ id: string; role: string; name: string; color: import("./cloud-buy.mjs").CloudColor | null; origin: string }>;
diff --git a/electron/cloud-list.mjs b/electron/cloud-list.mjs
new file mode 100644
index 0000000000..727076a8a3
--- /dev/null
+++ b/electron/cloud-list.mjs
@@ -0,0 +1,138 @@
+// The verified session's `clouds` (contract v1, additive): every Cloud this person owns and every team's Cloud they are
+// in, the account's primary Cloud first. Only the Admin lists a Cloud; a page never names one.
+import { CLOUD_SETUP_STEPS, homeOrigin } from "./cloud-home.mjs";
+import environments from "./environments.cjs";
+
+export const MAX_CLOUDS = 20;
+export const CLOUD_LIST_STATUSES = Object.freeze(["checkout", "setting_up", "ready", "stopped", "payment_problem", "ended", "offline"]);
+/** The Admin's colour swatches, and the saved colour (environments.cjs ENTRY_COLORS) each is shown in here; slate is
+ * the plain one. */
+export const CLOUD_SWATCH_COLORS = Object.freeze({ blue: "blue", green: "teal", amber: "yellow", rose: "red", violet: "purple", slate: null });
+export const CLOUD_SWATCHES = Object.freeze(Object.keys(CLOUD_SWATCH_COLORS));
+export const CLOUD_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
+export const CLOUD_NAME_LIMIT = 40;
+const TEAM_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+const TIER = /^[a-z][a-z0-9-]{0,23}$/;
+const RUNS_ON = Object.freeze(["cloud", "server"]);
+const VERSION = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,39}$/;
+/** Each status as the app's machine summary (cloud-home.mjs CLOUD_MACHINE_STATUSES) reads it; a Cloud still at checkout
+ * has none yet, and one offline is opened, so its own screen says it does not answer. */
+const MACHINE_STATUS = Object.freeze({ setting_up: "provisioning", ready: "ready", stopped: "stopped", payment_problem: "payment-problem", ended: "stopped", offline: "ready" });
+/** How far along each setup step is, for an Admin that names the step only. */
+const STEP_PROGRESS = Object.freeze({ reserving: 0.15, storage: 0.4, starting: 0.65, checking: 0.9 });
+
+const record = value => Boolean(value) && typeof value === "object" && !Array.isArray(value);
+
+/** A Cloud's name as the Admin keeps it: 1 to 40 characters, spaces folded, nothing a page could take for markup. */
+export function cleanCloudListName(value) {
+ if (typeof value !== "string") return null;
+ const name = value.replace(/\s+/g, " ").trim();
+ return name && [...name].length <= CLOUD_NAME_LIMIT && !/[\p{Cc}<>]/u.test(name) ? name : null;
+}
+
+function setupOf(input) {
+ if (!record(input)) return null;
+ const step = CLOUD_SETUP_STEPS.includes(input.step) ? input.step : null;
+ const progress = typeof input.progress === "number" && Number.isFinite(input.progress) ? Math.max(0, Math.min(1, input.progress)) : null;
+ return step || progress !== null ? { ...(step ? { step } : {}), ...(progress !== null ? { progress } : {}) } : null;
+}
+
+/** One Cloud, or null when anything the app acts on is malformed (never trusted in part); a malformed colour, tier,
+ * setup, last-seen time or version is simply left out, and a field this app doesn't know is ignored. `managed: false`
+ * (absent means MausBot runs or manages it) is a server or computer of the person's own that signed in with their
+ * account: always on a server of theirs, and with no address while it is only reachable on its own network. */
+function parseCloudEntry(input) {
+ if (!record(input) || typeof input.id !== "string" || !CLOUD_ID.test(input.id)) return null;
+ const name = cleanCloudListName(input.name);
+ if (!name || !environments.TEAM_ROLES.includes(input.role) || !CLOUD_LIST_STATUSES.includes(input.status) || !RUNS_ON.includes(input.runsOn) || typeof input.primary !== "boolean") return null;
+ if (input.managed !== undefined && typeof input.managed !== "boolean") return null;
+ const managed = input.managed !== false;
+ if (!managed && input.runsOn !== "server") return null;
+ const origin = input.origin === null || input.origin === undefined ? null : homeOrigin(input.origin);
+ if ((input.origin !== null && input.origin !== undefined && !origin) || (managed && ["ready", "offline"].includes(input.status) && !origin)) return null;
+ const teamId = input.teamId === null || input.teamId === undefined ? null : typeof input.teamId === "string" && TEAM_ID.test(input.teamId) ? input.teamId : undefined;
+ if (teamId === undefined) return null;
+ const setup = input.status === "setting_up" ? setupOf(input.setup) : null;
+ const lastSeenAt = typeof input.lastSeenAt === "number" && Number.isSafeInteger(input.lastSeenAt) && input.lastSeenAt > 0 ? input.lastSeenAt : null;
+ const version = typeof input.version === "string" && VERSION.test(input.version) ? input.version : null;
+ return { id: input.id, name, color: Object.hasOwn(CLOUD_SWATCH_COLORS, input.color) ? input.color : null, role: input.role,
+ tier: typeof input.tier === "string" && TIER.test(input.tier) ? input.tier : null, runsOn: input.runsOn, status: input.status, origin, teamId,
+ primary: input.primary, managed, ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}) };
+}
+
+/** An OpenMausBot release as the Admin names it ("0.1.130"), or null: anything else is no version at all. */
+export const releaseVersion = value => (typeof value === "string" && VERSION.test(value) ? value : null);
+
+/** Whether `version` is an older release than `latest`, compared number by number; false when either isn't plain
+ * numbers (a build of its own), so no reminder is ever guessed. */
+export function olderRelease(version, latest) {
+ const parts = text => (typeof text === "string" && /^\d+(?:\.\d+){1,3}$/.test(text) ? text.split(".").map(Number) : null);
+ const a = parts(version), b = parts(latest);
+ if (!a || !b) return false;
+ for (let at = 0; at < Math.max(a.length, b.length); at++) if ((a[at] ?? 0) !== (b[at] ?? 0)) return (a[at] ?? 0) < (b[at] ?? 0);
+ return false;
+}
+
+/** A Cloud this person owns that is no team's: a world of their own. Never a server that only signed in with their
+ * account (`managed: false`): MausBot neither runs nor vouches for it, so it is no Cloud of theirs to pair or lend to. */
+export const ownCloud = cloud => Boolean(cloud) && cloud.teamId === null && cloud.role === "owner" && cloud.managed !== false;
+
+/** The person's own servers and computers that signed in with their account: in the rail, each one theirs to connect. */
+export const signedInServers = clouds => (Array.isArray(clouds) ? clouds.filter(cloud => cloud.managed === false) : []);
+
+/**
+ * The session's list, at most MAX_CLOUDS, each Cloud once; null when the Admin sends none (it predates many Clouds, and
+ * the session's `cloud` and `teams` say everything). At most one Cloud is primary, and only one of the person's own.
+ */
+export function parseCloudList(input) {
+ if (!Array.isArray(input)) return null;
+ const clouds = [], seen = new Set();
+ let primary = false;
+ for (const entry of input.slice(0, MAX_CLOUDS)) {
+ const cloud = parseCloudEntry(entry);
+ if (!cloud || seen.has(cloud.id)) continue;
+ seen.add(cloud.id);
+ const first = cloud.primary && !primary && ownCloud(cloud);
+ if (first) primary = true;
+ clouds.push(first === cloud.primary ? cloud : { ...cloud, primary: false });
+ }
+ return clouds;
+}
+
+/** Every Cloud of the person's own besides the primary (My Cloud): each a place of its own, as a team's Cloud is. */
+export function otherOwnClouds(clouds) {
+ return Array.isArray(clouds) ? clouds.filter(cloud => ownCloud(cloud) && !cloud.primary) : [];
+}
+
+/** The Cloud as the app's machine summary (cloud-home.mjs parseCloudSummary's shape); null while it is still at checkout. */
+export function cloudMachine(cloud) {
+ const status = cloud ? MACHINE_STATUS[cloud.status] : undefined;
+ if (!status) return null;
+ return { status, ...(cloud.origin ? { origin: cloud.origin } : {}), ...(status === "provisioning" && cloud.setup?.step ? { setup: { step: cloud.setup.step } } : {}) };
+}
+
+/** How far along a setup step is (0 to 1). */
+export const stepProgress = step => (Object.hasOwn(STEP_PROGRESS, step) ? STEP_PROGRESS[step] : 0);
+
+/** How far a Cloud being set up is (0 to 1), from the Admin's progress or else its step; 0 while it waits for its
+ * payment, null once it is not being set up. */
+export function cloudSetupProgress(cloud) {
+ if (cloud?.status === "checkout") return 0;
+ if (cloud?.status !== "setting_up") return null;
+ return cloud.setup?.progress ?? stepProgress(cloud.setup?.step);
+}
+
+/** The colour a Cloud is shown in here: its swatch's, or none (slate, or no colour chosen). */
+export const swatchColor = swatch => (Object.hasOwn(CLOUD_SWATCH_COLORS, swatch) ? CLOUD_SWATCH_COLORS[swatch] : null);
+
+/** The colour the Admin keeps for My Cloud (`home`) and each team's Cloud, where one was chosen there (environments.cjs
+ * withListedColors): the person's other Clouds take theirs with the rest of their saved place. */
+export function listedColors(clouds) {
+ return Array.isArray(clouds) ? clouds.filter(cloud => cloud.color !== null && cloud.managed !== false && (cloud.primary || cloud.teamId !== null))
+ .map(cloud => ({ ...(cloud.primary ? { home: true } : { teamId: cloud.teamId }), color: swatchColor(cloud.color) })) : [];
+}
+
+/** A Cloud of the person's own besides My Cloud, as a saved place (environments.cjs withOwnCloud): its id, name, colour and address. */
+export function ownCloudPlaces(clouds) {
+ return otherOwnClouds(clouds).filter(cloud => cloud.origin).map(cloud => ({ id: cloud.id, role: cloud.role, name: cloud.name, color: swatchColor(cloud.color), origin: cloud.origin }));
+}
diff --git a/electron/cloud-list.node-test.mjs b/electron/cloud-list.node-test.mjs
new file mode 100644
index 0000000000..c65ce8389c
--- /dev/null
+++ b/electron/cloud-list.node-test.mjs
@@ -0,0 +1,154 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { cloudMachine, cloudSetupProgress, listedColors, MAX_CLOUDS, olderRelease, otherOwnClouds, ownCloudPlaces, parseCloudList, releaseVersion, signedInServers, swatchColor } from "./cloud-list.mjs";
+import environments from "./environments.cjs";
+import { createHomePlaces } from "./home-places.mjs";
+
+const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", CLIENT_B = "https://omb-c-b.fly.dev", TEAM = "https://omb-t-acme.fly.dev";
+const cloud = (over = {}) => ({ id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A,
+ teamId: null, seats: null, renewsAt: null, cancelAtPeriodEnd: false, primary: false, ...over });
+const primary = cloud({ id: "c-home", name: "My Cloud", color: null, origin: HOME, primary: true });
+
+test("the session's Clouds are read strictly: a malformed one is left out whole, never trusted in part; a malformed extra is simply dropped", () => {
+ assert.equal(parseCloudList(undefined), null, "an Admin without the list: everything as before");
+ for (const none of [null, {}, "x", 3]) assert.equal(parseCloudList(none), null, String(none));
+ assert.deepEqual(parseCloudList([]), []);
+ assert.deepEqual(parseCloudList([primary, cloud()]), [
+ { id: "c-home", name: "My Cloud", color: null, role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: HOME, teamId: null, primary: true, managed: true },
+ { id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A, teamId: null, primary: false, managed: true },
+ ]);
+ for (const bad of [
+ { id: "" }, { id: "../x" }, { name: "" }, { name: "x".repeat(41) }, { name: "<b>" }, { role: "boss" }, { status: "sleeping" }, { runsOn: "moon" },
+ { primary: "yes" }, { origin: "http://omb-c-a.fly.dev" }, { origin: `${CLIENT_A}/path` }, { origin: "https://[email protected]" }, { origin: null },
+ { status: "offline", origin: null }, { teamId: "../team" }, { teamId: 7 },
+ ]) assert.deepEqual(parseCloudList([cloud(bad)]), [], JSON.stringify(bad));
+ const [shown] = parseCloudList([cloud({ color: "url(x)", tier: "PRO!", name: " Client A " })]);
+ assert.deepEqual([shown.color, shown.tier, shown.name], [null, null, "Client A"], "a malformed colour or tier is none; the name is folded");
+ assert.deepEqual(parseCloudList([cloud({ status: "setting_up", origin: null, setup: { step: "storage", progress: 2 } })])[0].setup, { step: "storage", progress: 1 });
+ assert.equal(parseCloudList([cloud({ status: "setting_up", origin: null, setup: { step: "dreaming" } })])[0].setup, undefined);
+ assert.equal(parseCloudList([cloud({ status: "ready", setup: { step: "storage" } })])[0].setup, undefined, "only while it is set up");
+});
+
+test("a server or computer of the person's own that signed in with their account: read with or without an address, and never a Cloud of theirs", () => {
+ const mini = cloud({ id: "s-mini", name: "Mac mini", color: null, tier: null, runsOn: "server", managed: false, status: "offline", origin: null,
+ lastSeenAt: 1_761_000_000_000, version: "0.1.118", kind: "desktop", reachable: { via: "tailscale" } });
+ assert.deepEqual(parseCloudList([mini]), [{ id: "s-mini", name: "Mac mini", color: null, role: "owner", tier: null, runsOn: "server", status: "offline", origin: null,
+ teamId: null, primary: false, managed: false, lastSeenAt: 1_761_000_000_000, version: "0.1.118" }], "only reachable on its own network; fields this app doesn't know are ignored");
+ assert.equal(parseCloudList([{ ...mini, status: "ready", origin: "https://mini.example.ts.net" }])[0].origin, "https://mini.example.ts.net");
+ for (const bad of [{ managed: "false" }, { managed: 0 }, { managed: null }, { managed: false, runsOn: "cloud" }]) {
+ assert.deepEqual(parseCloudList([cloud(bad)]), [], `${JSON.stringify(bad)}: whether MausBot vouches for it is never guessed`);
+ }
+ const [loose] = parseCloudList([{ ...mini, lastSeenAt: "yesterday", version: "<b>1</b>" }]);
+ assert.deepEqual([loose.lastSeenAt, loose.version], [undefined, undefined], "a malformed last-seen time or version is left out");
+ assert.deepEqual(parseCloudList([{ ...mini, lastSeenAt: null, version: null }])[0], parseCloudList([{ ...mini, lastSeenAt: undefined, version: undefined }])[0]);
+ assert.equal(parseCloudList([cloud({ managed: true })])[0].managed, true);
+ assert.equal(parseCloudList([cloud({ status: "offline", origin: null })]).length, 0, "a Cloud MausBot runs still needs its address");
+ const list = parseCloudList([primary, mini, { ...mini, id: "s-vps", name: "VPS", status: "ready", origin: "https://vps.example.com", primary: true }]);
+ assert.deepEqual(list.map(entry => entry.primary), [true, false, false], "never My Cloud");
+ assert.deepEqual([otherOwnClouds(list), ownCloudPlaces(list)], [[], []], "nor another Cloud of theirs: nothing pairs with it by id or lends to it");
+ assert.deepEqual(signedInServers(list).map(entry => entry.id), ["s-mini", "s-vps"]);
+});
+
+test("the Admin's colour for My Cloud and each team's Cloud, once one was chosen there; the person's other Clouds take theirs with their place", () => {
+ const list = parseCloudList([{ ...primary, color: "rose" }, cloud({ color: "amber" }), cloud({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM, color: "slate" }),
+ cloud({ id: "c-t2", name: "Beta", teamId: "team-beta", role: "admin", origin: "https://omb-t-beta.fly.dev", color: null })]);
+ assert.deepEqual(listedColors(list), [{ home: true, color: "red" }, { teamId: "team-acme", color: null }], "slate is none; a team's Cloud with no colour chosen is not listed");
+ assert.deepEqual(listedColors(null), []);
+});
+
+test("at most twenty Clouds, each once, and one primary only, of the person's own", () => {
+ const many = Array.from({ length: 25 }, (_, n) => cloud({ id: `c-${n}`, name: `Cloud ${n}`, origin: `https://omb-c-${n}.fly.dev` }));
+ assert.equal(parseCloudList(many).length, MAX_CLOUDS);
+ assert.equal(parseCloudList([cloud(), cloud({ name: "Again" })]).length, 1, "the same id twice is read once");
+ const twice = parseCloudList([primary, cloud({ primary: true })]);
+ assert.deepEqual(twice.map(entry => entry.primary), [true, false]);
+ assert.deepEqual(parseCloudList([cloud({ teamId: "team-acme", role: "member", primary: true, origin: TEAM })]).map(entry => entry.primary), [false], "a team's Cloud is never My Cloud");
+});
+
+test("another Cloud of the person's own is a place of its own, read as the app's machine summary; a team's Cloud and My Cloud are not", () => {
+ const list = parseCloudList([primary, cloud(), cloud({ id: "c-team", name: "Acme", teamId: "team-acme", role: "admin", origin: TEAM }), cloud({ id: "c-b", name: "Client B", status: "setting_up", origin: null, setup: { step: "starting" } })]);
+ assert.deepEqual(otherOwnClouds(list).map(entry => entry.id), ["c-a", "c-b"]);
+ assert.deepEqual(ownCloudPlaces(list), [{ id: "c-a", role: "owner", name: "Client A", color: "teal", origin: CLIENT_A }], "only one with an address is a saved place");
+ assert.deepEqual(cloudMachine(list[1]), { status: "ready", origin: CLIENT_A });
+ assert.deepEqual(cloudMachine(list[3]), { status: "provisioning", setup: { step: "starting" } });
+ assert.equal(cloudMachine({ ...list[1], status: "checkout" }), null);
+ assert.deepEqual(cloudMachine({ ...list[1], status: "ended" }), { status: "stopped", origin: CLIENT_A });
+ assert.deepEqual(cloudMachine({ ...list[1], status: "offline" }), { status: "ready", origin: CLIENT_A }, "its own screen says it doesn't answer");
+ assert.deepEqual([cloudSetupProgress(list[3]), cloudSetupProgress({ status: "checkout" }), cloudSetupProgress(list[1])], [0.65, 0, null]);
+ assert.equal(cloudSetupProgress({ status: "setting_up", setup: { progress: 0.3, step: "starting" } }), 0.3, "the Admin's progress wins over the step");
+ assert.deepEqual(["blue", "green", "amber", "rose", "violet", "slate", "chartreuse"].map(swatchColor), ["blue", "teal", "yellow", "red", "purple", null, null]);
+});
+
+test("each other own Cloud is one saved place, named and coloured by the Admin; one hand-saved at its address becomes it; My Cloud's and a team's never do", () => {
+ const home = { id: "home", kind: "remote", name: "Studio", origin: HOME, home: true, color: "purple" };
+ const team = { id: "team", kind: "remote", name: "Acme", origin: TEAM, team: { id: "team-acme", role: "member" } };
+ const typed = { id: "typed", kind: "remote", name: "omb-c-b.fly.dev", origin: CLIENT_B, microphone: true };
+ let ids = 0;
+ const state = { environments: [home, team, typed], activeId: "home" };
+ const next = environments.reconcileOwnClouds(state, [
+ { id: "c-a", role: "owner", name: "Client A", color: "teal", origin: CLIENT_A },
+ { id: "c-b", role: "owner", name: "Client B", color: null, origin: CLIENT_B },
+ { id: "c-x", role: "owner", name: "Not mine", color: "red", origin: HOME },
+ { id: "c-y", role: "owner", name: "Not a team's", color: "red", origin: TEAM },
+ ], () => `new-${++ids}`, HOME);
+ assert.deepEqual(next.environments, [home, team,
+ { id: "typed", kind: "remote", name: "Client B", origin: CLIENT_B, microphone: true, cloud: { id: "c-b", role: "owner" } },
+ { id: "new-1", kind: "remote", origin: CLIENT_A, name: "Client A", color: "teal", cloud: { id: "c-a", role: "owner" } }]);
+ assert.equal(environments.reconcileOwnClouds(next, [
+ { id: "c-a", role: "owner", name: "Client A", color: "teal", origin: CLIENT_A }, { id: "c-b", role: "owner", name: "Client B", color: null, origin: CLIENT_B },
+ ], () => "unused", HOME), next, "the same list again changes nothing");
+ assert.equal(environments.reconcileOwnClouds(next, null, () => "unused", HOME), next, "an Admin without the list changes nothing");
+ const renamed = environments.reconcileOwnClouds({ ...next, activeId: "new-1" }, [{ id: "c-a", role: "owner", name: "Acme Client", color: "red", origin: CLIENT_A }], () => "unused", HOME);
+ assert.deepEqual(renamed.environments.map(entry => [entry.name, entry.color ?? null]), [["Studio", "purple"], ["Acme", null], ["Acme Client", "red"]], "Client B is gone; Client A follows the Admin");
+ assert.equal(renamed.activeId, "new-1");
+ const gone = environments.reconcileOwnClouds(renamed, [], () => "unused", HOME);
+ assert.equal(gone.activeId, "home", "the Cloud on screen is gone: My Cloud again");
+ const parsed = environments.parseEnvironments(environments.serializeEnvironments(next));
+ assert.deepEqual(parsed.environments.find(entry => entry.id === "new-1").cloud, { id: "c-a", role: "owner" }, "kept across launches");
+ assert.equal(environments.parseEnvironments({ version: 2, environments: [{ ...home, cloud: { id: "c-a", role: "owner" } }], activeId: "home" }).environments[0].cloud, undefined, "My Cloud's entry is never another Cloud's");
+});
+
+test("the switcher lists another own Cloud like a team's: no Forget, the window titled by its name", () => {
+ const entry = { id: "a", kind: "remote", name: "Client A", origin: CLIENT_A, cloud: { id: "c-a", role: "owner" } };
+ const state = { environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }, entry], activeId: "a" };
+ const menu = environments.workspaceMenuTemplate(state, { onSwitch() {}, onConnect() {}, onForget() {}, homeOrigin: HOME });
+ assert.deepEqual(menu.map(item => item.id), ["workspace-home", "workspace-a"]);
+ const before = environments.workspaceMenuTemplate(state, { onSwitch() {}, onConnect() {}, onForget() {} });
+ assert.equal(before.some(item => item.id === "workspace-forget"), false);
+ assert.equal(environments.workspaceWindowTitle(state, null, HOME), "OpenMausBot — Client A");
+});
+
+test("home places: the session's other Clouds become saved places, one remembered is opened next time, and one the session drops is forgotten", () => {
+ const w = { saved: null, state: { environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }], activeId: "home" }, persisted: [], ids: 0 };
+ const places = createHomePlaces({ store: { read: () => w.saved, write: value => { w.saved = value; } }, environments: () => w.state,
+ persist: next => { w.persisted.push(next); w.state = next; }, makeId: () => `id-${++w.ids}`, homeOrigin: () => HOME });
+ const session = clouds => ({ status: "connected", account: { id: "acct-1" }, clouds: parseCloudList(clouds) });
+ places.sync({ status: "connected", account: { id: "acct-1" } });
+ assert.deepEqual(w.persisted, [], "an older Admin's session lists no Clouds: nothing changes");
+ places.sync(session([primary, cloud()]));
+ assert.deepEqual(w.state.environments.map(entry => [entry.name, entry.cloud?.id ?? null, entry.color ?? null]), [["My Cloud", null, null], ["Client A", "c-a", "teal"]]);
+ places.remember({ cloud: "c-a" });
+ assert.deepEqual(w.saved, { cloud: "c-a" });
+ assert.deepEqual(places.remembered(), { cloud: "c-a", name: "Client A", origin: CLIENT_A });
+ places.remember({ team: "team-acme" });
+ assert.deepEqual(w.saved, { team: "team-acme" }, "a team instead");
+ places.remember({ cloud: "c-a" });
+ w.state = { ...w.state, activeId: "id-1" };
+ places.drop({ kind: "own", id: "c-a", name: "Client A" });
+ assert.deepEqual(w.state.environments.map(entry => entry.name), ["My Cloud"]);
+ assert.equal(w.state.activeId, "home");
+ assert.equal(places.remembered(), null);
+ assert.equal(places.line(), null, "a Cloud of their own leaving says nothing");
+ places.sync(session([primary, cloud()]));
+ places.remember({ cloud: "c-a" });
+ places.sync(session([primary]));
+ assert.equal(places.remembered(), null, "listed no more: forgotten");
+ assert.deepEqual(w.state.environments.map(entry => entry.name), ["My Cloud"]);
+});
+
+test("a release older than the newest one, compared number by number; nothing is guessed for a build of its own", () => {
+ assert.deepEqual([["0.1.118", "0.1.130"], ["0.1.130", "0.1.130"], ["0.2.0", "0.1.130"], ["0.1", "0.1.1"], ["0.1.9", "0.1.10"]].map(([a, b]) => olderRelease(a, b)), [true, false, false, true, true]);
+ for (const [a, b] of [["0.1.118-dev", "0.1.130"], ["0.1.118", null], [null, "0.1.130"], ["main", "0.1.130"], ["0.1.118", "latest"]]) assert.equal(olderRelease(a, b), false, `${a} ${b}`);
+ assert.deepEqual(["0.1.130", null, "", "<b>", 7].map(releaseVersion), ["0.1.130", null, null, null, null]);
+});
diff --git a/electron/cloud-plan-ipc.mjs b/electron/cloud-plan-ipc.mjs
index d01686e1dc..8ada665e46 100644
--- a/electron/cloud-plan-ipc.mjs
+++ b/electron/cloud-plan-ipc.mjs
@@ -1,14 +1,25 @@
import { cloudPlanSnapshot, UPGRADE_SOURCES } from "./cloud-account.mjs";
+/** Another Cloud of the person's own, as its page may see its plan: its tier and whether it runs, from the session's list. */
+export function otherCloudSnapshot(cloud) {
+ const runs = ["ready", "setting_up", "offline"].includes(cloud.status);
+ return { status: runs ? "paid" : "attention", ...(cloud.tier ? { tier: cloud.tier } : {}) };
+}
+
// Security: an upgrade goes only to a plan the verified session lists, and only with the confirmation main kept from its
-// own preview; a page never holds it.
-export function installCloudPlanIpc({ ipcMain, pageSender, account, client, notices, homePage }) {
- ipcMain.handle("cloud-plan:state", event => pageSender("cloud-plan:state", () => {
- const state = account()?.state();
- return { ...cloudPlanSnapshot(state, { notice: notices().due(state) }), ...(homePage(event) ? { home: true } : {}) };
- })(event));
+// own preview; a page never holds it. Upgrading is My Cloud's alone: another Cloud of the person's (`otherCloud(event)`,
+// its page) reads its own plan, never My Cloud's.
+export function installCloudPlanIpc({ ipcMain, pageSender, account, client, notices, homePage, otherCloud = () => null }) {
+ ipcMain.handle("cloud-plan:state", event => {
+ const other = otherCloud(event);
+ if (other) return { ...otherCloudSnapshot(other), ...(homePage(event) ? { home: true } : {}) };
+ return pageSender("cloud-plan:state", () => {
+ const state = account()?.state();
+ return { ...cloudPlanSnapshot(state, { notice: notices().due(state) }), ...(homePage(event) ? { home: true } : {}) };
+ })(event);
+ });
ipcMain.handle("cloud-plan:notice-seen", pageSender("cloud-plan:notice-seen", () => { notices().seen(account()?.state()); }));
- ipcMain.handle("cloud-plan:manage", pageSender("cloud-plan:manage", async () => { await client().openDashboard(); }));
+ ipcMain.handle("cloud-plan:manage", event => (otherCloud(event) ? client().openDashboard().then(() => {}) : pageSender("cloud-plan:manage", async () => { await client().openDashboard(); })(event)));
const upgradeArgs = (plan, source) => {
const offered = client().state().usage?.upgrades ?? [];
if (typeof plan !== "string" || !UPGRADE_SOURCES.includes(source) || !offered.some(entry => entry.tier === plan)) throw new Error("Choose a plan to move to.");
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
new file mode 100644
index 0000000000..813714fc57
--- /dev/null
+++ b/electron/cloud-rail.d.mts
@@ -0,0 +1,57 @@
+/** A circle of the rail: a place the window can show, by its saved id (`local` for this computer). Names, colours and
+ * states only: never an address. */
+export interface RailPlace {
+ id: string;
+ name: string;
+ color: import("./cloud-buy.mjs").CloudColor | null;
+ /** This computer, a Cloud of the person's own (My Cloud included), a team's Cloud, or a server they connected by hand. */
+ kind: "computer" | "cloud" | "team" | "server";
+ /** False while there is nothing to open yet (a Cloud being made, with no address). */
+ opens: boolean;
+ active?: true;
+ /** Being set up, 0 to 1 (0 while it waits for its payment). */
+ progress?: number;
+ /** Waiting for its payment. */
+ waiting?: true;
+ /** Something needs the person there (a payment problem on a Cloud they own). */
+ attention?: true;
+ /** A server or computer of the person's own that signed in with their account. */
+ server?: true;
+ /** Not heard from in the last few minutes. */
+ offline?: true;
+ /** When the Admin last heard from it (ms). */
+ lastSeenAt?: number;
+ /** Signed in, but only reachable on its own network: nothing to open from here. */
+ ownNetwork?: true;
+ /** Signed in and reachable, but not connected to this app yet: a click shows how to connect it. */
+ pairs?: true;
+ /** It runs an older release than the newest the Admin names: time to update it. */
+ update?: { version: string; latest: string };
+}
+/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings. */
+export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean }
+export interface RailState { places: RailPlace[]; add: RailAddChoices }
+/** Buying another Cloud as a page sees it: what the sheet says, never the account, an address or the checkout page. */
+export type AddCloudView =
+ | { signedIn: false }
+ | {
+ signedIn: true;
+ /** The person has a Cloud of their own already (else + buys their first, in this computer's own sheet). */
+ hasCloud: boolean;
+ /** The Admin lists every Cloud of theirs (else it sells one Cloud per account). */
+ supported: boolean;
+ canAdd: boolean;
+ blocked?: import("./cloud-account.mjs").CloudAddBlock;
+ offer: import("./cloud-home.mjs").CloudOffer | null;
+ /** How many Clouds of their own they have: the next one is suggested as "Cloud {count + 1}". */
+ count: number;
+ home?: { name: string; color: import("./cloud-buy.mjs").CloudColor | null };
+ adding?: {
+ name: string; color: import("./cloud-list.mjs").CloudSwatch | null; tier: string | null; startedAt: number;
+ status: "checkout" | "setting_up" | "ready" | "problem"; progress?: number; link?: true; done?: true;
+ };
+ };
+export declare const RAIL_MIN_PLACES: number;
+export declare function hostedCloudOrigin(origin: unknown, input: { state: unknown; mine?: string | null }): boolean;
+export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown }): RailPlace[];
+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
new file mode 100644
index 0000000000..5b55d90e1d
--- /dev/null
+++ b/electron/cloud-rail.mjs
@@ -0,0 +1,189 @@
+// The rail of places at the left of the window (the renderer's PlacesRail) and its +: main builds the list, says who
+// may read it, and does what a circle or + asks through main's own switch and dialogs.
+//
+// Security: the list carries names, colours and states, never an address, and goes only to this app's own page and to
+// pages of Clouds MausBot runs that the verified session lists (the person's own Clouds and their teams' Clouds). A
+// server the person connected by hand, or a Cloud on a server of their own, runs a page anyone may have written, so it
+// would learn the names of the person's other places; it gets none, and the native Server menu stays its switcher. A
+// circle names a saved place by its id; main opens only an id it listed itself.
+import environments from "./environments.cjs";
+import { cleanCloudListName, CLOUD_SWATCHES, cloudSetupProgress, olderRelease, otherOwnClouds, ownCloud, signedInServers, stepProgress, swatchColor } from "./cloud-list.mjs";
+import { machineSetup } from "./cloud-home.mjs";
+
+export const RAIL_MIN_PLACES = 2;
+const PENDING = "pending:";
+const SIGNED_IN = "signed-in:";
+
+/** A server or computer of the person's own that signed in with their account, as its circle says it: online while the
+ * Admin heard from it in the last few minutes, else offline since when it was last seen; and an older release than the
+ * newest one, while the Admin names that (`latest`; none while it doesn't follow releases). */
+const serverState = (listed, latest = null) => ({ server: true, ...(listed.status !== "ready" ? { offline: true } : {}), ...(listed.lastSeenAt ? { lastSeenAt: listed.lastSeenAt } : {}),
+ ...(listed.version && latest && olderRelease(listed.version, latest) ? { update: { version: listed.version, latest } } : {}) });
+
+/** A Cloud's address is one MausBot runs for this person: My Cloud (`mine`), or a Cloud the verified session lists on
+ * MausBot Cloud. Without the session's list of Clouds (an older Admin), a team's Cloud it lists, all of which MausBot runs. */
+export function hostedCloudOrigin(origin, { state, mine = null }) {
+ if (typeof origin !== "string" || !origin) return false;
+ if (origin === mine) return true;
+ const connected = state?.status === "connected" ? state : null;
+ if (!connected) return false;
+ if (Array.isArray(connected.clouds)) return connected.clouds.some(cloud => cloud.origin === origin && cloud.runsOn === "cloud");
+ return (connected.teams ?? []).some(team => team?.machine?.origin === origin);
+}
+
+const machineProgress = machine => {
+ const setup = machineSetup(machine);
+ return setup ? stepProgress(setup.step) : null;
+};
+
+/** One saved place as a circle: what it is, its colour and how it is doing, from the session's word for it. */
+function circle(entry, { activeId, mine, state }) {
+ 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";
+ const team = entry.team ? connected?.teams?.find(candidate => candidate?.id === entry.team.id) ?? null : null;
+ const machine = entry.origin === mine ? connected?.machine ?? null : team?.machine ?? null;
+ const progress = listed ? cloudSetupProgress(listed) : machineProgress(machine);
+ const problem = listed ? listed.status === "payment_problem" && listed.role === "owner" : entry.origin === mine && machine?.status === "payment-problem";
+ const color = environments.ENTRY_COLORS.includes(entry.color) ? entry.color : listed ? swatchColor(listed.color) : null;
+ return { id: entry.id, name: entry.name, color, kind, opens: true, ...(entry.id === activeId ? { active: true } : {}),
+ ...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}) };
+}
+
+/**
+ * The circles, in the Server menu's order: This computer while it is a place (before the move made My Cloud home, `home`
+ * null), My Cloud, the person's other Clouds and their teams' Clouds in the session's order, then servers saved by hand.
+ * A server of theirs that signed in with their account comes next: one saved here already is that saved place (online
+ * or not), one not connected to this app yet shows how to connect it, and one only reachable on its own network has
+ * nothing to open. A Cloud of theirs the Admin is still making (no address yet) is there too, not yet to open. Fewer
+ * than RAIL_MIN_PLACES places besides this computer: no rail at all, the window as it was.
+ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any }} input
+ */
+export function railPlaces({ saved, home = null, mine = null, state = null }) {
+ 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; };
+ const rank = entry => (entry.origin === mine || entry.home ? 0 : environments.listedPlace(entry) ? 1 : 2);
+ const remote = saved.environments.filter(entry => entry.kind !== "local" && entry.origin)
+ .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 }));
+ 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: false, progress: cloudSetupProgress(cloud) ?? 0,
+ ...(cloud.status === "checkout" ? { waiting: true } : {}) }));
+ const savedOrigins = new Set(saved.environments.map(entry => entry.origin).filter(Boolean));
+ const servers = signedInServers(clouds).filter(cloud => !cloud.origin || !savedOrigins.has(cloud.origin))
+ .map(cloud => ({ id: `${SIGNED_IN}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "server", opens: false,
+ ...(cloud.origin ? { pairs: true } : { ownNetwork: true }), ...serverState(cloud, connected?.latestVersion ?? null) }));
+ const places = [...remote, ...servers, ...making];
+ if (places.length < RAIL_MIN_PLACES) return [];
+ return home ? places : [{ id: environments.LOCAL_ID, name: "This computer", color: null, kind: "computer", opens: true, ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];
+}
+
+/** What buying another Cloud looks like from a page: no account, address or checkout page, only what the sheet says. */
+export function addCloudView(state, offer) {
+ const connected = state?.status === "connected" ? state : null;
+ if (!connected) return { signedIn: false };
+ const clouds = Array.isArray(connected.clouds) ? connected.clouds : null;
+ const owned = clouds ? clouds.filter(ownCloud) : [];
+ const has = Boolean(connected.machine) || owned.length > 0;
+ const home = clouds?.find(cloud => cloud.primary) ?? null;
+ const adding = connected.adding ?? null, listed = adding ? clouds?.find(cloud => cloud.id === adding.cloudId) ?? null : null;
+ const status = !listed || listed.status === "checkout" ? "checkout" : ["ready", "offline"].includes(listed.status) && listed.origin ? "ready"
+ : listed.status === "setting_up" || listed.status === "ready" ? "setting_up" : "problem";
+ return {
+ signedIn: true, hasCloud: has, supported: Boolean(clouds),
+ canAdd: Boolean(clouds) && connected.addCloud?.canAdd !== false,
+ ...(connected.addCloud?.canAdd === false ? { blocked: connected.addCloud.blocked } : {}),
+ offer: offer ?? null, count: Math.max(owned.length, has ? 1 : 0),
+ ...(home ? { home: { name: home.name, color: swatchColor(home.color) } } : {}),
+ ...(adding ? { adding: { name: adding.name, color: adding.color, tier: adding.tier, startedAt: adding.startedAt, status,
+ ...(listed && cloudSetupProgress(listed) !== null ? { progress: cloudSetupProgress(listed) } : {}), ...(adding.link ? { link: true } : {}), ...(adding.done ? { done: true } : {}) } } : {}),
+ };
+}
+
+/**
+ * "“{name}” is ready", once per Cloud this app bought, unless its sheet shows it in the focused window; a click opens it.
+ */
+export function createAddedCloudNotice({ Notification, focused, sheetOpen, open, shown = () => {} }) {
+ const announced = new Set();
+ return state => {
+ const adding = state?.status === "connected" ? state.adding : null;
+ const listed = adding && !adding.done ? state.clouds?.find(cloud => cloud.id === adding.cloudId) ?? null : null;
+ if (!listed || !["ready", "offline"].includes(listed.status) || !listed.origin || announced.has(adding.cloudId)) return false;
+ announced.add(adding.cloudId);
+ if ((focused() && sheetOpen()) || !Notification.isSupported()) return false;
+ const note = new Notification({ title: `“${listed.name}” is ready`, body: "Click to open it." });
+ note.on("click", () => open(adding.cloudId));
+ note.show();
+ shown();
+ return true;
+ };
+}
+
+const plain = value => (typeof value === "string" ? value : "");
+const CHOICES = Object.freeze(["cloud", "link", "address"]);
+
+/**
+ * The rail's and +'s channels, each behind main's window guard (`guard`) and allowed only on a page `trusted` vouches
+ * for (this app's own, or a hosted Cloud's). `places()` is railPlaces' list now; `open(id)` main's own switch; `add`
+ * the + sheet's fixed actions; `account()` the MausBot Cloud sign-in.
+ */
+export function installCloudRail({ ipcMain, guard, trusted, places, open, add, account, clipboard, openCloud, window }) {
+ 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`);
+ return handler(event, ...args);
+ });
+ const handle = (channel, handler) => ipcMain.handle(channel, allowed(channel, handler));
+ const view = async () => addCloudView(account()?.state() ?? null, account() ? await account().offer().catch(() => null) : null);
+ ipcMain.handle("workspaces:places", guard((event) => (trusted(event) ? { places: places(), add: add.choices() } : { places: [], add: { cloud: false, link: false, address: false } })));
+ handle("workspaces:open", (_event, id) => {
+ const place = places().find(entry => entry.id === plain(id) && entry.opens);
+ if (!place) throw new Error("That place isn't here any more.");
+ return open(place.id);
+ });
+ handle("workspaces:add", (_event, choice) => {
+ if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error("That isn't something to add here.");
+ return add.run(choice);
+ });
+ handle("cloud-add:state", () => view());
+ handle("cloud-add:start", async (_event, tier, name, color) => {
+ const client = account();
+ if (!client) throw new Error("Sign in to MausBot Cloud first.");
+ const plans = (await client.offer().catch(() => null))?.plans ?? [];
+ const cleanName = cleanCloudListName(plain(name)), swatch = CLOUD_SWATCHES.includes(color) ? color : null;
+ if (!plans.some(plan => plan.tier === plain(tier)) || !cleanName) throw new Error("Choose a plan and a name to continue.");
+ const result = await client.addCloud({ tier: plain(tier), interval: "month", name: cleanName, color: swatch });
+ return result.outcome === "blocked" ? { outcome: "blocked", blocked: result.blocked } : { outcome: result.outcome };
+ });
+ handle("cloud-add:reopen", () => account()?.reopenAdd() ?? false);
+ handle("cloud-add:copy-link", () => {
+ const url = account()?.addLink() ?? null;
+ if (url) clipboard.writeText(url);
+ return Boolean(url);
+ });
+ handle("cloud-add:open", async () => {
+ const adding = account()?.state().adding;
+ if (!adding) throw new Error("There is no new Cloud to open.");
+ await openCloud(adding.cloudId);
+ account()?.addDone();
+ });
+ handle("cloud-add:interest", () => account()?.interest("another_cloud"));
+ handle("cloud-add:sheet", (event, on) => {
+ sheetOpen = on === true;
+ const page = event?.sender;
+ if (sheetOpen && typeof page?.once === "function") for (const done of ["did-navigate", "destroyed"]) page.once(done, () => { sheetOpen = false; });
+ });
+ return {
+ sheetOpen: () => sheetOpen,
+ /** The places or the sign-in changed: the page that shows the rail reads it again (a signal only, never the list). */
+ changed() {
+ const key = JSON.stringify([places(), add.choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null]);
+ if (key === sent) return;
+ sent = key;
+ const win = window();
+ if (win && !win.isDestroyed()) win.webContents.send("workspaces:changed");
+ },
+ };
+}
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
new file mode 100644
index 0000000000..5bc804bf21
--- /dev/null
+++ b/electron/cloud-rail.node-test.mjs
@@ -0,0 +1,239 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import vm from "node:vm";
+
+import { parseCloudList } from "./cloud-list.mjs";
+import { addCloudView, createAddedCloudNotice, hostedCloudOrigin, installCloudRail, railPlaces } from "./cloud-rail.mjs";
+import { otherCloudSnapshot } from "./cloud-plan-ipc.mjs";
+
+const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", TEAM = "https://omb-t-acme.fly.dev", VPS = "https://bots.example.test", OWN = "https://mini.tail1234.ts.net";
+const LOCAL = "http://127.0.0.1:8799";
+const entry = (over = {}) => ({ id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A,
+ teamId: null, primary: false, ...over });
+const PRIMARY = entry({ id: "c-home", name: "My Cloud", color: null, origin: HOME, primary: true });
+const saved = (activeId = "home", extra = []) => ({ activeId, environments: [
+ { id: "home", kind: "remote", name: "Studio", origin: HOME, home: true, color: "purple" },
+ { id: "vps", kind: "remote", name: "Office", origin: VPS },
+ { id: "acme", kind: "remote", name: "Acme", origin: TEAM, team: { id: "team-acme", role: "member" } },
+ { id: "a", kind: "remote", name: "Client A", origin: CLIENT_A, color: "teal", cloud: { id: "c-a", role: "owner" } },
+ { id: "lab", kind: "local", name: "Lab", dataDir: "/Users/person/lab" },
+ ...extra,
+] });
+const session = (over = {}) => ({ status: "connected", account: { id: "acct-1" }, machine: { status: "ready", origin: HOME },
+ teams: [{ id: "team-acme", name: "Acme", role: "member", machine: { status: "ready", origin: TEAM } }],
+ clouds: parseCloudList([PRIMARY, entry(), entry({ id: "c-team", name: "Acme", color: "amber", teamId: "team-acme", role: "member", origin: TEAM })]), ...over });
+
+test("the rail: My Cloud, the person's Clouds and teams' Clouds in the session's order, then servers saved by hand; names, colours and states, never an address", () => {
+ const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session() });
+ assert.deepEqual(places, [
+ { id: "home", name: "Studio", color: "purple", kind: "cloud", opens: true, active: true },
+ { id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true },
+ { id: "acme", name: "Acme", color: "yellow", kind: "team", opens: true },
+ { id: "vps", name: "Office", color: null, kind: "server", opens: true },
+ ]);
+ for (const origin of [HOME, CLIENT_A, TEAM, VPS, "/Users/person/lab"]) assert.equal(JSON.stringify(places).includes(origin), false, origin);
+ const before = railPlaces({ saved: saved("local"), home: null, mine: HOME, state: session() });
+ assert.deepEqual(before[0], { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true }, "before the move, this computer is a place too");
+ assert.equal(before.length, 5);
+});
+
+test("one place, or none: no rail, the window as it was", () => {
+ const alone = { activeId: "home", environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }] };
+ assert.deepEqual(railPlaces({ saved: alone, home: HOME, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }) }), []);
+ assert.deepEqual(railPlaces({ saved: alone, home: null, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }) }), [], "this computer and My Cloud are still one Cloud");
+ assert.deepEqual(railPlaces({ saved: { activeId: "local", environments: [] }, state: null }), []);
+ const two = railPlaces({ saved: { activeId: "home", environments: [alone.environments[0], { id: "vps", kind: "remote", name: "Office", origin: VPS }] }, home: HOME, mine: HOME, state: null });
+ assert.deepEqual(two.map(place => place.id), ["home", "vps"], "a server saved by hand is a place");
+});
+
+test("a Cloud being set up shows how far it is, one at checkout waits, one the Admin is still making is shown but not opened, and a payment problem needs its owner", () => {
+ const clouds = parseCloudList([PRIMARY, entry({ status: "setting_up", setup: { progress: 0.4 } }), entry({ id: "c-b", name: "Client B", color: "violet", status: "checkout", origin: null }),
+ entry({ id: "c-c", name: "Client C", status: "setting_up", origin: null, setup: { step: "storage" } }), entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM, status: "payment_problem" })]);
+ const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds }) });
+ assert.deepEqual(places.find(place => place.id === "a"), { id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true, progress: 0.4 });
+ assert.deepEqual(places.slice(-2), [
+ { id: "pending:c-b", name: "Client B", color: "purple", kind: "cloud", opens: false, progress: 0, waiting: true },
+ { id: "pending:c-c", name: "Client C", color: "teal", kind: "cloud", opens: false, progress: 0.4 },
+ ]);
+ assert.equal(places.find(place => place.id === "acme").attention, undefined, "a member can't fix a team's payment");
+ const owner = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds: parseCloudList([PRIMARY, entry({ status: "payment_problem" })]) }) });
+ assert.equal(owner.find(place => place.id === "a").attention, true);
+ const older = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds: undefined, machine: { status: "payment-problem", origin: HOME } }) });
+ assert.equal(older.find(place => place.id === "home").attention, true, "an older Admin: My Cloud's own word");
+ const settingUp = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds: undefined, teams: [{ id: "team-acme", name: "Acme", role: "member", machine: { status: "provisioning", origin: TEAM, setup: { step: "starting" } } }] }) });
+ assert.equal(settingUp.find(place => place.id === "acme").progress, 0.65);
+});
+
+test("a server of the person's own that signed in with their account: one saved here is that place, online or not; one not connected yet shows how; one only on its own network opens nothing", () => {
+ const RENDER = "https://render.example.test";
+ const clouds = parseCloudList([PRIMARY, entry(),
+ entry({ id: "s-mini", name: "Mac mini", color: null, tier: null, runsOn: "server", managed: false, status: "offline", origin: null, lastSeenAt: 1_761_000_000_000 }),
+ entry({ id: "s-office", name: "Office box", color: null, tier: null, runsOn: "server", managed: false, status: "ready", origin: VPS }),
+ entry({ id: "s-render", name: "Render VPS", color: "rose", tier: null, runsOn: "server", managed: false, status: "offline", origin: RENDER, lastSeenAt: 1_761_000_100_000 })]);
+ const state = session({ clouds });
+ const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state });
+ assert.deepEqual(places.find(place => place.id === "vps"), { id: "vps", name: "Office", color: null, kind: "server", opens: true, server: true },
+ "saved by hand at its address: the same circle, marked as theirs, online, opening as it always did");
+ assert.deepEqual(places.slice(-2), [
+ { id: "signed-in:s-mini", name: "Mac mini", color: null, kind: "server", opens: false, ownNetwork: true, server: true, offline: true, lastSeenAt: 1_761_000_000_000 },
+ { id: "signed-in:s-render", name: "Render VPS", color: "red", kind: "server", opens: false, pairs: true, server: true, offline: true, lastSeenAt: 1_761_000_100_000 },
+ ]);
+ assert.equal(places.length, 6, "one circle per server");
+ for (const origin of [VPS, RENDER]) assert.equal(JSON.stringify(places).includes(origin), false, origin);
+ assert.deepEqual([VPS, RENDER].map(origin => hostedCloudOrigin(origin, { state, mine: HOME })), [false, false], "its page never reads the rail");
+ const alone = { activeId: "home", environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }] };
+ assert.equal(railPlaces({ saved: alone, home: HOME, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY, clouds[2]]) }) }).length, 2, "it counts as a place");
+ assert.equal(places.some(place => place.update), false, "no newest release named (the Admin doesn't follow releases): no reminder");
+ const behind = parseCloudList([PRIMARY, entry({ id: "s-mini", name: "Mac mini", runsOn: "server", managed: false, status: "ready", origin: null, version: "0.1.118" }),
+ entry({ id: "s-new", name: "New box", runsOn: "server", managed: false, status: "ready", origin: null, version: "0.1.130" }),
+ entry({ id: "s-dev", name: "Dev box", runsOn: "server", managed: false, status: "ready", origin: null, version: "0.1.118-dev" })]);
+ const reminded = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds: behind, latestVersion: "0.1.130" }) });
+ assert.deepEqual(reminded.filter(place => place.update).map(place => [place.id, place.update]), [["signed-in:s-mini", { version: "0.1.118", latest: "0.1.130" }]],
+ "only one on an older numbered release");
+ const r = rail({ places: () => places });
+ assert.throws(() => r.call("workspaces:open", "signed-in:s-render"), /isn't here/, "nothing opens one main can't pair with yet");
+ assert.throws(() => r.call("workspaces:open", "signed-in:s-mini"), /isn't here/);
+});
+
+test("only Clouds MausBot runs for this person may read the rail: My Cloud, their Clouds and their teams' on MausBot Cloud; never a server of their own or one typed in", () => {
+ const state = session({ clouds: parseCloudList([PRIMARY, entry(), entry({ id: "c-own", name: "Mini", origin: OWN, runsOn: "server" }),
+ entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM })]) });
+ assert.deepEqual([HOME, CLIENT_A, TEAM, OWN, VPS, null].map(origin => hostedCloudOrigin(origin, { state, mine: HOME })), [true, true, true, false, false, false]);
+ assert.equal(hostedCloudOrigin(TEAM, { state: session({ clouds: undefined }), mine: HOME }), true, "an older Admin lists teams' Clouds, all MausBot's");
+ assert.equal(hostedCloudOrigin(CLIENT_A, { state: session({ clouds: undefined }), mine: HOME }), false);
+ assert.equal(hostedCloudOrigin(TEAM, { state: session({ clouds: parseCloudList([PRIMARY]) }), mine: HOME }), false, "with the list, a Cloud it doesn't list is none of theirs");
+ assert.equal(hostedCloudOrigin(HOME, { state: { status: "unavailable" }, mine: HOME }), true, "My Cloud while a check fails");
+ assert.equal(hostedCloudOrigin(CLIENT_A, { state: { status: "unavailable", clouds: state.clouds }, mine: HOME }), false);
+});
+
+function rail(over = {}) {
+ const handlers = new Map(), opened = [], ran = [], sent = [];
+ const w = { trusted: true, state: session(), offer: { recommended: "pro", plans: [{ tier: "pro", amount: 4900 }] }, added: [] };
+ const account = { state: () => w.state, offer: async () => w.offer, addCloud: async (input) => { w.added.push(input); return { outcome: "opened", state: w.state }; },
+ reopenAdd: async () => true, addLink: () => "https://test.checkout.dodopayments.com/x", addDone: () => { w.done = true; }, interest: async () => {} };
+ const installed = installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler, trusted: () => w.trusted,
+ places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: w.state }), open: id => opened.push(id), account: () => account,
+ add: { choices: () => ({ cloud: true, link: true, address: false }), run: choice => ran.push(choice) }, clipboard: { writeText: text => sent.push(text) },
+ openCloud: async id => opened.push(`cloud:${id}`), window: () => ({ isDestroyed: () => false, webContents: { send: (channel) => sent.push(channel) } }), ...over });
+ return { handlers, opened, ran, sent, w, installed, call: (channel, ...args) => handlers.get(channel)({ sender: {} }, ...args) };
+}
+
+test("the rail's channels: the list only for a page main vouches for, a circle only by an id main listed, + only its fixed choices", async () => {
+ const r = rail();
+ assert.deepEqual((await r.call("workspaces:places")).places.map(place => place.id), ["home", "a", "acme", "vps"]);
+ r.w.trusted = false;
+ assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false } }, "a server's own page learns nothing");
+ assert.throws(() => r.call("workspaces:open", "a"), /only available/);
+ assert.throws(() => r.call("workspaces:add", "link"), /only available/);
+ r.w.trusted = true;
+ r.call("workspaces:open", "a");
+ assert.throws(() => r.call("workspaces:open", "https://evil.example.test"), /isn't here/);
+ assert.throws(() => r.call("workspaces:open", "lab"), /isn't here/, "a local environment is the Server menu's, not the rail's");
+ r.call("workspaces:add", "link");
+ assert.throws(() => r.call("workspaces:add", "address"), /isn't something/, "not offered here");
+ assert.throws(() => r.call("workspaces:add", "javascript:alert(1)"), /isn't something/);
+ assert.deepEqual([r.opened, r.ran], [["a"], ["link"]]);
+ r.installed.changed(); r.installed.changed();
+ assert.deepEqual(r.sent, ["workspaces:changed"], "a signal only, and once per change");
+});
+
+test("buying another Cloud from a page: the plan must be on sale, the name is checked, and the page gets only what the sheet says", async () => {
+ const r = rail();
+ await assert.rejects(r.call("cloud-add:start", "max", "Client B", "rose"), /Choose a plan/);
+ await assert.rejects(r.call("cloud-add:start", "pro", " ", "rose"), /Choose a plan/);
+ assert.deepEqual(await r.call("cloud-add:start", "pro", "Client B", "url(x)"), { outcome: "opened" });
+ assert.deepEqual(r.w.added, [{ tier: "pro", interval: "month", name: "Client B", color: null }], "an unknown swatch is none");
+ assert.equal(await r.call("cloud-add:copy-link"), true);
+ assert.deepEqual(r.sent, ["https://test.checkout.dodopayments.com/x"]);
+ r.w.state = session({ adding: { cloudId: "c-a", name: "Client A", color: "green", tier: "pro", startedAt: 1, link: true } });
+ await r.call("cloud-add:open");
+ assert.deepEqual(r.opened, ["cloud:c-a"]);
+ assert.equal(r.w.done, true);
+ const view = await r.call("cloud-add:state");
+ assert.equal(JSON.stringify(view).includes("acct-1"), false, "never the account");
+ assert.deepEqual({ ...view, offer: undefined }, { signedIn: true, hasCloud: true, supported: true, canAdd: true, offer: undefined, count: 2,
+ home: { name: "My Cloud", color: null }, adding: { name: "Client A", color: "green", tier: "pro", startedAt: 1, status: "ready", link: true } });
+ r.w.trusted = false;
+ for (const channel of ["cloud-add:state", "cloud-add:start", "cloud-add:open", "cloud-add:copy-link", "cloud-add:interest"]) assert.throws(() => r.call(channel), /only available/, channel);
+});
+
+test("what the add sheet says: an older Admin is one Cloud for now, the Admin's cap says why, and a new Cloud's setup is followed", () => {
+ assert.deepEqual(addCloudView({ status: "signed-out" }, null), { signedIn: false });
+ const older = addCloudView(session({ clouds: undefined }), null);
+ assert.deepEqual([older.supported, older.canAdd, older.hasCloud, older.count], [false, false, true, 1]);
+ const capped = addCloudView(session({ addCloud: { canAdd: false, blocked: "cap" } }), null);
+ assert.deepEqual([capped.canAdd, capped.blocked], [false, "cap"]);
+ const none = addCloudView({ status: "connected", account: { id: "x" }, clouds: [] }, null);
+ assert.equal(none.hasCloud, false, "no Cloud yet: + buys the first one on this computer's own sheet");
+ const adding = (status, extra = {}) => addCloudView(session({ clouds: parseCloudList([PRIMARY, entry({ id: "c-b", status, origin: status === "ready" ? CLIENT_A : null, ...extra })]),
+ adding: { cloudId: "c-b", name: "Client B", color: "rose", tier: "pro", startedAt: 5 } }), null).adding;
+ assert.deepEqual(adding("checkout"), { name: "Client B", color: "rose", tier: "pro", startedAt: 5, status: "checkout", progress: 0 });
+ assert.deepEqual(adding("setting_up", { setup: { progress: 0.5 } }), { name: "Client B", color: "rose", tier: "pro", startedAt: 5, status: "setting_up", progress: 0.5 });
+ assert.equal(adding("ready").status, "ready");
+ assert.equal(adding("payment_problem").status, "problem");
+});
+
+test("another Cloud's page reads its own plan: its tier, and whether it runs", () => {
+ assert.deepEqual(otherCloudSnapshot(entry()), { status: "paid", tier: "pro" });
+ assert.deepEqual(otherCloudSnapshot(entry({ status: "payment_problem", tier: null })), { status: "attention" });
+});
+
+test("“{name}” is ready, once per Cloud this app bought, unless its sheet shows it in the focused window; a click opens it", () => {
+ const shown = [], opened = [];
+ class FakeNotification { static isSupported() { return true; } constructor(options) { this.options = options; shown.push(this); } on(_event, handler) { this.click = handler; } show() {} }
+ let sheet = false;
+ const notice = createAddedCloudNotice({ Notification: FakeNotification, focused: () => true, sheetOpen: () => sheet, open: id => opened.push(id) });
+ const state = status => session({ clouds: parseCloudList([PRIMARY, entry({ id: "c-b", name: "Client B", status, origin: status === "ready" ? CLIENT_A : null })]),
+ adding: { cloudId: "c-b", name: "Client B", color: null, tier: "pro", startedAt: 1 } });
+ assert.equal(notice(state("setting_up")), false);
+ assert.equal(notice(state("ready")), true);
+ assert.equal(shown[0].options.title, "“Client B” is ready");
+ shown[0].click();
+ assert.deepEqual(opened, ["c-b"]);
+ assert.equal(notice(state("ready")), false, "once");
+ sheet = true;
+ const quiet = createAddedCloudNotice({ Notification: FakeNotification, focused: () => true, sheetOpen: () => sheet, open: () => {} });
+ assert.equal(quiet(state("ready")), false, "the sheet in the focused window says it itself");
+ assert.equal(shown.length, 1);
+});
+
+const PRELOAD = readFileSync(new URL("./preload.cjs", import.meta.url), "utf8");
+function preload(origin, { activation = false } = {}) {
+ let bridge; const invoked = [];
+ vm.runInNewContext(PRELOAD, {
+ process: { platform: "darwin", argv: [`--omb-local-origin=${LOCAL}`, "--omb-company-desktop=1"] },
+ location: { origin }, navigator: { userActivation: { isActive: activation } }, TextEncoder, localStorage: { getItem: () => null }, queueMicrotask,
+ require: () => ({ webUtils: {}, contextBridge: { exposeInMainWorld: (_name, value) => { bridge = value; } },
+ ipcRenderer: { on() {}, removeListener() {}, send() {}, sendSync: () => null, invoke: (...args) => { invoked.push(args); return Promise.resolve(); } } }),
+ });
+ return { bridge, invoked };
+}
+
+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", "onChanged"]);
+ assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet"]);
+ await page.bridge.workspaces.places();
+ await page.bridge.cloudAdd.state();
+ await assert.rejects(page.bridge.workspaces.open("a"), /Choose a place/);
+ await assert.rejects(page.bridge.workspaces.add("link"), /Choose what to add/);
+ await assert.rejects(page.bridge.cloudAdd.start("pro", "Client B", "rose"), /Continue to checkout/);
+ await assert.rejects(page.bridge.cloudAdd.reopen(), /Reopen checkout/);
+ await assert.rejects(page.bridge.cloudAdd.copyLink(), /Copy link/);
+ await assert.rejects(page.bridge.cloudAdd.open(), /Open/);
+ 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 page.bridge.workspaces.look();
+ assert.deepEqual(page.invoked.at(-1), ["workspaces:look"]);
+ const clicked = preload(HOME, { activation: true });
+ await clicked.bridge.workspaces.open({ toString: () => "a" });
+ await clicked.bridge.workspaces.add("link");
+ await clicked.bridge.cloudAdd.start("pro", "Client B", null);
+ await clicked.bridge.workspaces.color("rose");
+ await clicked.bridge.workspaces.color(null);
+ assert.deepEqual(clicked.invoked, [["workspaces:open", "a"], ["workspaces:add", "link"], ["cloud-add:start", "pro", "Client B", null], ["workspaces:color", "rose"], ["workspaces:color", null]]);
+ assert.equal(page.bridge.cloudAccount, undefined, "never the account bridge");
+ const local = preload(LOCAL);
+ await local.bridge.workspaces.open("a");
+ assert.deepEqual(local.invoked, [["workspaces:open", "a"]], "this app's own page needs no click check");
+});
diff --git a/electron/environments.cjs b/electron/environments.cjs
index 51acbab89d..70c2c03a5f 100644
--- a/electron/environments.cjs
+++ b/electron/environments.cjs
@@ -10,8 +10,13 @@ const TEAM_ROLE_LABELS = Object.freeze({ owner: "Super admin", admin: "Admin", m
const teamRoleLabel = (role) => TEAM_ROLE_LABELS[role] ?? TEAM_ROLE_LABELS.member;
const cleanTeam = (value) => (value && typeof value === "object" && typeof value.id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value.id) && TEAM_ROLES.includes(value.role)
? { id: value.id, role: value.role } : null);
-/** My Cloud first, then each team, then saved servers. */
-const placeRank = (entry, homeOrigin) => (entry.origin === homeOrigin ? 0 : entry.team ? 1 : 2);
+/** A Cloud of the person's own besides My Cloud is listed by the verified session too (`cloud`: its id and their role). */
+const cleanCloud = (value) => (value && typeof value === "object" && typeof value.id === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value.id) && TEAM_ROLES.includes(value.role)
+ ? { id: value.id, role: value.role } : null);
+/** A place the Admin lists and removes: a team's Cloud, or another Cloud of the person's own. */
+const listedPlace = (entry) => Boolean(entry?.team || entry?.cloud);
+/** My Cloud first, then each Cloud and team, then saved servers. */
+const placeRank = (entry, homeOrigin) => (entry.origin === homeOrigin ? 0 : listedPlace(entry) ? 1 : 2);
function normalizeOrigin(input) {
if (typeof input !== "string") return null;
@@ -79,7 +84,7 @@ function workspaceSummary(state) {
function workspaceWindowTitle(state, companion, homeOrigin = null) {
if (companion) return `OpenMausBot — Connected to: ${companion.serverName} (${new URL(companion.endpoint).host})`;
const active = activeEnvironment(state);
- if (active?.team) return `OpenMausBot — ${active.name}`;
+ if (listedPlace(active)) return `OpenMausBot — ${active.name}`;
if (active && active.kind !== "local" && active.origin !== homeOrigin) return `OpenMausBot — Hosted: ${active.name} (${new URL(active.origin).host})`;
if (active && homeOrigin && active.origin === homeOrigin && otherPlaces(state, homeOrigin) > 0) return `OpenMausBot — ${active.name}`;
return "OpenMausBot";
@@ -113,7 +118,7 @@ function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddClou
return [
...(places ? [{ id: "workspace-places", label: places, enabled: false }, { type: "separator" }] : []),
{ id: "workspace-local", label: "This computer", type: "radio", checked: !active, click: () => onSwitch(LOCAL_ID) },
- ...[...state.environments].sort((a, b) => Boolean(b.team) - Boolean(a.team)).map((entry) => {
+ ...[...state.environments].sort((a, b) => listedPlace(b) - listedPlace(a)).map((entry) => {
const icon = iconFor && cleanColor(entry.color) ? iconFor(entry.color) : null;
const status = Object.hasOwn(sublabels, entry.id) ? sublabels[entry.id] : entry.team ? teamRoleLabel(entry.team.role) : null;
return {
@@ -126,13 +131,13 @@ function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddClou
...(onAddCloud ? [{ id: "workspace-add-cloud", label: "Add a Cloud…", sublabel: "Keeps your bots running 24/7", click: onAddCloud }] : []),
{ type: "separator" },
{ id: "workspace-connect", label: "Connect to a server…", click: onConnect },
- ...(active && !active.team ? [{ id: "workspace-forget", label: `Forget “${active.name}”…`, click: () => onForget(active.id) }] : []),
+ ...(active && !listedPlace(active) ? [{ id: "workspace-forget", label: `Forget “${active.name}”…`, click: () => onForget(active.id) }] : []),
];
}
-/** Once My Cloud is the person's home: My Cloud, each team's Cloud (with this person's role), then the other saved
- * servers, each a whole place of its own; this computer is not one of them, and nothing here sends or copies. A team is
- * the Admin's to list and remove, so it has no Forget. */
+/** Once My Cloud is the person's home: My Cloud, each Cloud of theirs and each team's Cloud (with this person's role),
+ * then the other saved servers, each a whole place of its own; this computer is not one of them, and nothing here sends
+ * or copies. A Cloud or a team is the Admin's to list and remove, so it has no Forget. */
function homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldSublabels, homeOrigin }) {
const active = activeEnvironment(state);
const places = state.environments.filter((entry) => entry.kind !== "local").sort((a, b) => placeRank(a, homeOrigin) - placeRank(b, homeOrigin));
@@ -145,7 +150,7 @@ function homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldS
...(icon ? { icon } : {}), type: "radio", checked: entry.id === state.activeId, click: () => onSwitch(entry.id),
};
}),
- ...(active && active.origin !== homeOrigin && !active.team ? [{ type: "separator" }, { id: "workspace-forget", label: `Forget “${active.name}”…`, click: () => onForget(active.id) }] : []),
+ ...(active && active.origin !== homeOrigin && !listedPlace(active) ? [{ type: "separator" }, { id: "workspace-forget", label: `Forget “${active.name}”…`, click: () => onForget(active.id) }] : []),
];
}
@@ -192,8 +197,43 @@ function reconcileTeams(state, teams, makeId, homeOrigin = null) {
let next = kept.length === state.environments.length ? state : { ...state, environments: kept };
for (const team of teams) next = withTeam(next, { id: team?.id, role: team?.role, name: team?.name, origin: team?.machine?.origin }, makeId);
if (next === state) return { state, left };
- const activeId = next.environments.some((entry) => entry.id === next.activeId) ? next.activeId : next.environments.find((entry) => entry.origin === homeOrigin)?.id ?? LOCAL_ID;
- return { state: activeId === next.activeId ? next : { ...next, activeId }, left };
+ return { state: withActiveKept(next, homeOrigin), left };
+}
+
+/** The place on screen that is gone: My Cloud is active again (or this computer, without one). */
+function withActiveKept(state, homeOrigin) {
+ const activeId = state.environments.some((entry) => entry.id === state.activeId) ? state.activeId : state.environments.find((entry) => entry.origin === homeOrigin)?.id ?? LOCAL_ID;
+ return activeId === state.activeId ? state : { ...state, activeId };
+}
+
+/** Another Cloud of the person's own as a saved place: listed once at its address, under the name and colour the Admin
+ * keeps for it (`color` undefined keeps the saved one; null is none). A server saved by hand at that address becomes the
+ * Cloud's entry; My Cloud's entry and a team's never do. The same state when nothing changes. */
+function withOwnCloud(state, cloud, makeId) {
+ const origin = normalizeOrigin(cloud?.origin), owner = cleanCloud(cloud), name = cleanName(cloud?.name, "");
+ if (!origin || !owner || !name) return state;
+ const existing = state.environments.find((entry) => entry.origin === origin);
+ if (existing?.home || existing?.team) return state;
+ const color = cloud.color === undefined ? cleanColor(existing?.color) : cleanColor(cloud.color);
+ if (existing && existing.name === name && existing.cloud?.id === owner.id && existing.cloud?.role === owner.role && (cleanColor(existing.color) ?? null) === (color ?? null)) return state;
+ const { color: _old, ...rest } = existing ?? { id: makeId(), kind: "remote", origin };
+ const next = { ...rest, name, ...(color ? { color } : {}), cloud: owner };
+ return { ...state, environments: existing ? state.environments.map((entry) => (entry === existing ? next : entry)) : [...state.environments, next] };
+}
+
+/** The person's other own Clouds the verified session lists (cloud-list.mjs ownCloudPlaces), as saved places: one the
+ * session no longer lists is gone. Null (an Admin without the list, or no verified word) changes nothing. */
+function reconcileOwnClouds(state, clouds, makeId, homeOrigin = null) {
+ if (!Array.isArray(clouds)) return state;
+ const wanted = new Map();
+ for (const cloud of clouds) {
+ const owner = cleanCloud(cloud), origin = normalizeOrigin(cloud?.origin);
+ if (owner && origin && !wanted.has(origin)) wanted.set(origin, cloud);
+ }
+ const kept = state.environments.filter((entry) => !entry.cloud || wanted.get(entry.origin)?.id === entry.cloud.id);
+ let next = kept.length === state.environments.length ? state : { ...state, environments: kept };
+ for (const cloud of wanted.values()) next = withOwnCloud(next, cloud, makeId);
+ return next === state ? state : withActiveKept(next, homeOrigin);
}
function botList(names, shown = 2) {
@@ -309,8 +349,9 @@ function parseEnvironments(raw) {
seen.add(id);
seen.add(origin);
const color = cleanColor(entry?.color), team = entry?.home === true ? null : cleanTeam(entry?.team);
+ const cloud = entry?.home === true || team ? null : cleanCloud(entry?.cloud);
environments.push({ id, kind: "remote", name: cleanName(entry?.name, nameFromOrigin(origin)), origin, ...(entry?.microphone === true ? { microphone: true } : {}),
- ...(color ? { color } : {}), ...(entry?.home === true ? { home: true } : {}), ...(team ? { team } : {}) });
+ ...(color ? { color } : {}), ...(entry?.home === true ? { home: true } : {}), ...(team ? { team } : {}), ...(cloud ? { cloud } : {}) });
}
const activeId = typeof value?.activeId === "string" && environments.some((e) => e.id === value.activeId) ? value.activeId : LOCAL_ID;
return { environments, activeId };
@@ -334,6 +375,29 @@ function withEnvironment(state, input, makeId) {
return { ...state, environments };
}
+/** One saved place's colour as the person chose it, or none (`color` null); a colour this app doesn't draw changes
+ * nothing, and neither does this computer. The same state when it is that colour already. */
+function withPlaceColor(state, id, color) {
+ const existing = state.environments.find((entry) => entry.id === id);
+ if (!existing || existing.kind === "local" || (color !== null && !cleanColor(color)) || (cleanColor(existing.color) ?? null) === color) return state;
+ const { color: _old, ...rest } = existing;
+ const next = color ? { ...rest, color } : rest;
+ return { ...state, environments: state.environments.map((entry) => (entry === existing ? next : entry)) };
+}
+
+/** The colours the Admin keeps for My Cloud (`home`) and team Clouds (`teamId`), on their saved places: once a colour
+ * was chosen there it is the one everywhere (none for slate); before that, what this app saved stays. */
+function withListedColors(state, looks, homeOrigin = null) {
+ let next = state;
+ for (const look of Array.isArray(looks) ? looks : []) {
+ const entry = next.environments.find((candidate) => (look?.home === true
+ ? candidate.kind !== "local" && (candidate.home === true || (homeOrigin !== null && candidate.origin === homeOrigin))
+ : typeof look?.teamId === "string" && candidate.team?.id === look.teamId));
+ if (entry) next = withPlaceColor(next, entry.id, cleanColor(look.color));
+ }
+ return next;
+}
+
/** A saved server's name and colour, as its owner chose them (the Cloud's own setup); an invalid colour is left as it was. */
function withEnvironmentLook(state, origin, { name, color } = {}) {
const key = normalizeOrigin(origin);
@@ -411,8 +475,11 @@ module.exports = {
ENTRY_COLORS,
TEAM_ROLES,
teamRoleLabel,
+ listedPlace,
reconcileTeams,
+ reconcileOwnClouds,
withTeam,
+ withOwnCloud,
LOCAL_ID,
activeEnvironment,
activeLocalDataDir,
@@ -429,6 +496,8 @@ module.exports = {
withActive,
withEnvironment,
withEnvironmentLook,
+ withListedColors,
+ withPlaceColor,
withLocalEnvironment,
withMicrophone,
withoutEnvironment,
diff --git a/electron/home-places.mjs b/electron/home-places.mjs
index 4ce1b3ca3a..6ae8c1aacc 100644
--- a/electron/home-places.mjs
+++ b/electron/home-places.mjs
@@ -1,9 +1,13 @@
-// The places one window can show besides My Cloud: each team the verified session lists. Main keeps them as saved
-// places (environments.cjs `team` entries, so the window's navigation rules know their addresses) and here what else
-// the switcher needs: the place to open next time, and the one line waiting for the next page (a team this person is
-// no longer in). Nothing here comes from a page: the list of teams is the Admin's session's, read by main. Who can see a
-// team's private chats is said by the team's own page, in the chat (T2's TeamPrivateChatsLine), not here.
+// The places one window can show besides My Cloud: each team the verified session lists, and each other Cloud of the
+// person's own it lists. Main keeps them as saved places (environments.cjs `team` and `cloud` entries, so the window's
+// navigation rules know their addresses) and here what else the switcher needs: the place to open next time, and the one
+// line waiting for the next page (a team this person is no longer in). Nothing here comes from a page: the lists are the
+// Admin's session's, read by main. Who can see a team's private chats is said by the team's own page, in the chat (T2's
+// TeamPrivateChatsLine), not here.
import environments from "./environments.cjs";
+import { listedColors, ownCloudPlaces } from "./cloud-list.mjs";
+
+const idOf = (value) => (typeof value === "string" && value ? value : null);
/**
* @param {{
@@ -13,8 +17,8 @@ import environments from "./environments.cjs";
* makeId(): string,
* homeOrigin(): string | null,
* log?(line: string): void,
- * }} deps `store`: this app's home-place.json (`{ team }`); `environments()` / `persist()`: the saved places and their
- * file; `homeOrigin()`: My Cloud's verified origin, the place the window falls back to.
+ * }} deps `store`: this app's home-place.json (`{ team }` or `{ cloud }`); `environments()` / `persist()`: the saved
+ * places and their file; `homeOrigin()`: My Cloud's verified origin, the place the window falls back to.
*/
export function createHomePlaces({ store, environments: read, persist, makeId, homeOrigin, log = () => {} }) {
let cached = null;
@@ -22,53 +26,61 @@ export function createHomePlaces({ store, environments: read, persist, makeId, h
function load() {
try {
const record = store.read();
- return { team: typeof record?.team === "string" ? record.team : null };
- } catch { return { team: null }; }
+ const team = idOf(record?.team);
+ return { team, cloud: team ? null : idOf(record?.cloud) };
+ } catch { return { team: null, cloud: null }; }
}
const current = () => (cached ??= load());
function save(next) {
cached = next;
- try { store.write(next); } catch (error) { log(`home places: could not save (${error?.message ?? error})`); }
+ try { store.write(next.cloud ? { cloud: next.cloud } : { team: next.team }); } catch (error) { log(`home places: could not save (${error?.message ?? error})`); }
}
- const entryOf = (id) => read().environments.find((entry) => entry.team?.id === id) ?? null;
+ const entryOf = (key, id) => read().environments.find((entry) => entry[key]?.id === id) ?? null;
const places = {
- /** The team shown last time, as saved: its id, and its name and address while it is still a saved place. */
+ /** The team or Cloud shown last time, as saved: its id, and its name and address while it is still a saved place. */
remembered() {
- const id = current().team;
- if (!id) return null;
- const entry = entryOf(id);
- return entry ? { team: id, name: entry.name, origin: entry.origin } : { team: id };
+ const { team, cloud } = current(), key = team ? "team" : cloud ? "cloud" : null;
+ if (!key) return null;
+ const id = team ?? cloud, entry = entryOf(key, id);
+ return entry ? { [key]: id, name: entry.name, origin: entry.origin } : { [key]: id };
},
- /** What the window opens next time: a team (`{ team }`), or My Cloud (null). */
+ /** What the window opens next time: a team (`{ team }`), another Cloud (`{ cloud }`), or My Cloud (null). */
remember(place) {
- const team = typeof place?.team === "string" ? place.team : null;
- if (team !== current().team) save({ ...current(), team });
+ const team = idOf(place?.team), cloud = team ? null : idOf(place?.cloud);
+ if (team !== current().team || cloud !== current().cloud) save({ team, cloud });
},
/** The team shown is no longer this person's: said once, on the next page that asks. */
left(name) {
if (typeof name === "string" && name && !pending.includes(name)) pending.push(name);
},
- /** The Admin refused the person's pairing with a team (404: they were removed): the team leaves the switcher now,
- * not at the next session check, the window falls back to My Cloud, and the one line waits for its page. */
+ /** The Admin refused the person's pairing with a team (404: they were removed) or one of their Clouds (404: it is
+ * gone): it leaves the switcher now, not at the next session check, and the window falls back to My Cloud; a team
+ * leaves the one line for its page. */
drop(place) {
- const state = read(), entry = state.environments.find((candidate) => candidate.team?.id === place?.id) ?? null;
+ const key = place?.kind === "own" ? "cloud" : "team";
+ const state = read(), entry = state.environments.find((candidate) => candidate[key]?.id === place?.id) ?? null;
if (entry) {
const kept = state.environments.filter((candidate) => candidate !== entry);
const activeId = state.activeId !== entry.id ? state.activeId : kept.find((candidate) => candidate.origin === homeOrigin())?.id ?? environments.LOCAL_ID;
persist({ ...state, environments: kept, activeId });
}
- places.left(entry?.name ?? place?.name);
- if (current().team === place?.id) places.remember(null);
+ if (key === "team") places.left(entry?.name ?? place?.name);
+ if (current()[key] === place?.id) places.remember(null);
},
- /** The MausBot Cloud sign-in changed: a connected session's teams are the saved team places (one it no longer
- * lists is gone, with its name for the line); anything else changes nothing. */
+ /** The MausBot Cloud sign-in changed: a connected session's teams and other Clouds are the saved places of theirs
+ * (one it no longer lists is gone; a team with its name for the line), in the colours the Admin keeps for them;
+ * anything else changes nothing. An Admin that lists no Clouds leaves the Cloud places as they were. */
sync(state) {
if (state?.status !== "connected") return;
const teams = Array.isArray(state.teams) ? state.teams : [];
- const { state: next, left } = environments.reconcileTeams(read(), teams, makeId, homeOrigin());
+ const { state: withTeams, left } = environments.reconcileTeams(read(), teams, makeId, homeOrigin());
+ const clouds = Array.isArray(state.clouds) ? ownCloudPlaces(state.clouds) : null;
+ const owned = environments.reconcileOwnClouds(withTeams, clouds, makeId, homeOrigin());
+ const next = clouds ? environments.withListedColors(owned, listedColors(state.clouds), homeOrigin()) : owned;
if (next !== read()) persist(next);
for (const name of left) places.left(name);
if (current().team && !teams.some((team) => team?.id === current().team)) places.remember(null);
+ if (current().cloud && clouds && !clouds.some((cloud) => cloud.id === current().cloud)) places.remember(null);
},
/** The one line for the next page, served once: a team this person is no longer in. */
line() {
diff --git a/electron/home-window.d.mts b/electron/home-window.d.mts
index 358822043a..58c67b5476 100644
--- a/electron/home-window.d.mts
+++ b/electron/home-window.d.mts
@@ -25,11 +25,12 @@ export interface HomeBridge {
}
export type Home = { kind: "computer" } | { kind: "cloud"; origin: string } | { kind: "signin"; other?: true };
-/** A place the window shows: My Cloud, or a team's Cloud from the verified session. */
-export type HomePlace = { kind: "cloud"; origin: string } | { kind: "team"; id: string; name: string; role: string | null; origin: string };
-/** What to open: My Cloud, a team's Cloud, or (null) the place remembered from last time. */
-export type HomeAsk = "cloud" | { team: string; name?: string } | null;
-export type RememberedPlace = { team: string; name?: string; origin?: string } | null;
+/** A place the window shows: My Cloud, or a team's Cloud or another Cloud of the person's own (`own`), from the verified session. */
+export type HomePlace = { kind: "cloud"; origin: string } | { kind: "team" | "own"; id: string; name: string; role: string | null; origin: string };
+/** What to open: My Cloud, a team's Cloud, another Cloud of the person's own, or (null) the place remembered from last time. */
+export type HomeAsk = "cloud" | { team: string; name?: string } | { cloud: string; name?: string } | null;
+export type RememberedPlace = (({ team: string } | { cloud: string }) & { name?: string; origin?: string }) | null;
+export declare function otherPlace(place: unknown): boolean;
export declare const HOME_SCREEN_PATH: string;
export declare const LOOK_MS: number;
@@ -48,7 +49,7 @@ export declare const NAME_RETRY_MS: readonly number[];
export function nameNotFound(code: number): boolean;
export function createReadyClock(input?: { store?: { read(): unknown; write(value: unknown): void } | null; now?(): number }): { seen(state: unknown): void; fresh(origin: string | null): boolean };
export function splashText(status: "opening" | "waking", name?: string | null): string;
-export function placeOf(input: { ask?: HomeAsk; remembered?: RememberedPlace; state?: any }): { kind: "cloud"; left?: string | null } | { kind: "team"; id: string; name: string; role: string | null; origin: string | null; machine: any };
+export function placeOf(input: { ask?: HomeAsk; remembered?: RememberedPlace; state?: any }): { kind: "cloud"; left?: string | null } | { kind: "team" | "own"; id: string; name: string; role: string | null; origin: string | null; machine: any };
export function homeOf(input: { journal?: any; frozenCloud?: string | true | null; state?: any }): Home;
export function routeOf(url: string, origin: string): string | null;
@@ -86,7 +87,7 @@ export interface HomeWindow {
export function createHomeWindow(deps: {
journal(): unknown;
frozen(): Promise<{ frozen: boolean; cloud?: string } | null>;
- account(): { state(): any; power(): any; wakeHome(): Promise<unknown>; setWaking(on: boolean): void; pairHome(): Promise<{ origin: string; code: string; expiresAt: number }>;
+ account(): { state(): any; power(): any; wakeHome(): Promise<unknown>; setWaking(on: boolean): void; pairHome(cloudId?: string | null): Promise<{ origin: string; code: string; expiresAt: number }>;
pairTeam?(teamId: string): Promise<{ origin: string; code: string; expiresAt: number }>; signInAgain(): Promise<unknown>; begin(): Promise<unknown> } | null;
restored?(): Promise<unknown>;
window(): WindowLike | null;
@@ -97,9 +98,9 @@ export function createHomeWindow(deps: {
go(url: string, origin: string | null, place: HomePlace | null): unknown;
showLocal(leaving: boolean): unknown;
remembered?(): RememberedPlace;
- remember?(place: { team: string } | null): void;
+ remember?(place: { team: string } | { cloud: string } | null): void;
left?(name: string): void;
- drop?(place: { id: string; name: string }): void;
+ drop?(place: { kind: "team" | "own"; id: string; name: string }): void;
splash?(): { status(text: string): void } | null;
lastInput?(): number;
publish?(view: HomeView): void;
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 28668754ac..171a1f71e3 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -9,6 +9,7 @@
// shown place's verified origin, nothing else. A team is only ever one the Admin's session lists, paired through the
// Admin's team pairing (its claims are the Admin's), never an address a page supplied.
import { cloudHomeConnectUrl, cloudSetupOf, cloudUnreachableText, machineSetup, readyCloudOrigin } from "./cloud-home.mjs";
+import { cloudMachine, otherOwnClouds } from "./cloud-list.mjs";
import { asleepAnswer, BACKGROUND_HEADERS, openSleepingCloud, SIGNED_IN_MS } from "./cloud-power.mjs";
import { awayIn, parseJournal } from "./one-home.mjs";
@@ -75,15 +76,30 @@ export function homeOf({ journal = null, frozenCloud = null, state = null }) {
return { kind: "cloud", origin };
}
+/** A place besides My Cloud: a team's Cloud, or another Cloud of the person's own (`own`), each the session's. */
+export const otherPlace = (place) => place?.kind === "team" || place?.kind === "own";
+
+/** Another Cloud of the person's own, asked for (`{ cloud }`) or remembered: the session's word, as placeOf reads a team. One
+ * the connected session no longer lists is simply My Cloud again; while the Admin can't be asked it opens as it was saved. */
+function ownPlaceOf(asked, remembered, state) {
+ const id = asked.cloud, cloud = otherOwnClouds(state?.clouds).find((entry) => entry.id === id) ?? null;
+ if (cloud) return { kind: "own", id, name: cloud.name, role: cloud.role, origin: cloud.origin, machine: cloudMachine(cloud) };
+ if (state?.status === "connected") return { kind: "cloud" };
+ const kept = remembered?.cloud === id ? remembered : asked;
+ return kept?.origin ? { kind: "own", id, name: kept.name ?? "the Cloud", role: null, origin: kept.origin, machine: null } : { kind: "cloud" };
+}
+
/**
- * The place a window is asked for. `ask`: "cloud" for My Cloud, `{ team }` for a team's Cloud, or nothing for the place
- * remembered from last time (`remembered`). A team is read from the verified session (`state.teams`); one the connected
- * session no longer lists is gone, and the answer is My Cloud with the team's name in `left`, so the window can say so
- * once. While the Admin can't be asked, a remembered team opens as it was saved, on the window's own session.
- * @returns {{ kind: "cloud", left?: string | null } | { kind: "team", id: string, name: string, role: string | null, origin: string | null, machine: any }}
+ * The place a window is asked for. `ask`: "cloud" for My Cloud, `{ team }` for a team's Cloud, `{ cloud }` for another
+ * Cloud of the person's own, or nothing for the place remembered from last time (`remembered`). A team is read from the
+ * verified session (`state.teams`); one the connected session no longer lists is gone, and the answer is My Cloud with
+ * the team's name in `left`, so the window can say so once. While the Admin can't be asked, a remembered team opens as
+ * it was saved, on the window's own session.
+ * @returns {{ kind: "cloud", left?: string | null } | { kind: "team" | "own", id: string, name: string, role: string | null, origin: string | null, machine: any }}
*/
export function placeOf({ ask = null, remembered = null, state = null }) {
const asked = ask ?? remembered;
+ if (asked && asked !== "cloud" && typeof asked.cloud === "string") return ownPlaceOf(asked, remembered, state);
const id = asked && asked !== "cloud" && typeof asked.team === "string" ? asked.team : null;
if (!id) return { kind: "cloud" };
const team = (Array.isArray(state?.teams) ? state.teams : []).find((entry) => entry?.id === id) ?? null;
@@ -132,7 +148,7 @@ export function routeOf(url, origin) {
* @param {{
* journal(): unknown,
* frozen(): Promise<{ frozen: boolean, cloud?: string } | null>,
- * account(): { state(): any, power(): any, wakeHome(): Promise<unknown>, setWaking(on: boolean): void, pairHome(): Promise<{ origin: string, code: string, expiresAt: number }>,
+ * account(): { state(): any, power(): any, wakeHome(): Promise<unknown>, setWaking(on: boolean): void, pairHome(cloudId?: string | null): Promise<{ origin: string, code: string, expiresAt: number }>,
* pairTeam?(teamId: string): Promise<{ origin: string, code: string, expiresAt: number }>, signInAgain(): Promise<unknown>, begin(): Promise<unknown> } | null,
* restored?(): Promise<unknown>,
* window(): { isDestroyed(): boolean, webContents: { id: number, getURL(): string, reload(): void } } | null,
@@ -140,12 +156,12 @@ export function routeOf(url, origin) {
* localOrigin(): string,
* cookieFetch: typeof fetch,
* power: { asleep(): boolean, hold(): void, woke(): void },
- * go(url: string, origin: string | null, place: { kind: "cloud", origin: string } | { kind: "team", id: string, name: string, role: string | null, origin: string } | null): Promise<unknown>,
+ * go(url: string, origin: string | null, place: { kind: "cloud", origin: string } | { kind: "team" | "own", id: string, name: string, role: string | null, origin: string } | null): Promise<unknown>,
* showLocal(leaving: boolean): unknown,
- * remembered?(): { team: string, name?: string, origin?: string } | null,
- * remember?(place: { team: string } | null): void,
+ * remembered?(): ({ team: string } | { cloud: string }) & { name?: string, origin?: string } | null,
+ * remember?(place: { team: string } | { cloud: string } | null): void,
* left?(name: string): void,
- * drop?(place: { id: string, name: string }): void,
+ * drop?(place: { kind: "team" | "own", id: string, name: string }): void,
* splash?(): { status(text: string): void } | null,
* lastInput?(): number,
* publish?(view: unknown): void,
@@ -161,13 +177,13 @@ export function routeOf(url, origin) {
* `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.
* `frozen()`: this computer's server's freeze marker. `splash()`: the startup screen while it is up. `remembered()`: the
- * team shown last time, with its name and origin as saved; `remember(place)`: what to open next time; `left(name)`: the
- * team shown is no longer this person's, so the window says so once; `drop(place)`: the Admin said so (404 on its team
- * pairing), so the team leaves the switcher now, with that line.
+ * team or other Cloud shown last time, with its name and origin as saved; `remember(place)`: what to open next time;
+ * `left(name)`: the team shown is no longer this person's, so the window says so once; `drop(place)`: the Admin said so
+ * (404 on its pairing), so the team (with that line) or the Cloud leaves the switcher now.
*/
export function createHomeWindow(deps) {
const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal,
- remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { left(place.name); remember(null); },
+ remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },
splash = () => null, lastInput = () => 0, publish = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,
now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, log = () => {} } = deps;
let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;
@@ -183,11 +199,11 @@ export function createHomeWindow(deps) {
const wanted = (token) => token === opens;
const cloudOrigin = () => (home.kind === "cloud" ? home.origin : null);
/** The origin of the place on screen, or on its way: a team's Cloud while one is shown, else My Cloud. */
- const placeOrigin = () => (shown?.kind === "team" ? (signedOut() ? null : shown.origin) : cloudOrigin());
- const teamName = () => (opening?.kind === "team" ? opening.name : null);
- const pair = (place) => (place.kind === "team" ? account()?.pairTeam?.(place.id) : account()?.pairHome());
- /** The same team still the place on screen (a newer show() replaces the object, not the team). */
- const still = (place) => shown?.kind === "team" && shown.id === place.id && shown.origin === place.origin;
+ const placeOrigin = () => (otherPlace(shown) ? (signedOut() ? null : shown.origin) : cloudOrigin());
+ const teamName = () => (otherPlace(opening) ? opening.name : null);
+ const pair = (place) => (place.kind === "team" ? account()?.pairTeam?.(place.id) : place.kind === "own" ? account()?.pairHome(place.id) : account()?.pairHome());
+ /** The same place still the one on screen (a newer show() replaces the object, not the place). */
+ const still = (place) => shown?.kind === place.kind && shown.id === place.id && shown.origin === place.origin;
const clearRenewal = () => { if (renewal) timers.clear(renewal); renewal = null; };
async function refresh() {
@@ -252,7 +268,7 @@ export function createHomeWindow(deps) {
/** The place didn't answer: this computer's screen says so, with the Admin's reason for My Cloud, and looks again by itself. */
function offline(token) {
if (!wanted(token)) return;
- const reason = opening?.kind === "team" ? null : cloudUnreachableText(state(), cloudOrigin());
+ const reason = otherPlace(opening) ? null : cloudUnreachableText(state(), cloudOrigin());
toScreen({ screen: "offline", ...(reason ? { reason } : {}) });
later();
}
@@ -340,7 +356,7 @@ export function createHomeWindow(deps) {
function gone(place) {
drop(place);
clearRenewal();
- if (shown?.kind === "team" && shown.id === place.id) shown = null;
+ if (shown?.kind === place.kind && shown.id === place.id) shown = null;
return show({ place: "cloud" });
}
@@ -356,7 +372,7 @@ export function createHomeWindow(deps) {
clearRetry();
opening = place;
const client = account();
- const machine = place.kind === "team" ? place.machine : state()?.status === "connected" ? state().machine : null;
+ const machine = otherPlace(place) ? place.machine : state()?.status === "connected" ? state().machine : null;
if (machine && (PLAN_PROBLEMS.has(machine.status) || (place.kind === "team" && machine.hold))) {
toScreen({ screen: "plan", machine: PLAN_PROBLEMS.has(machine.status) ? machine.status : "stopped" }); later(); return;
}
@@ -374,7 +390,7 @@ export function createHomeWindow(deps) {
if (naming) await forgetNames();
const look = await answers(origin);
if (look === "no") return unreachable(place, token);
- if (look === "asleep" && place.kind === "team") return offline(token);
+ if (look === "asleep" && otherPlace(place)) return offline(token);
if (look === "asleep") { power.hold(); asleep = true; say("waking"); }
}
let session = null;
@@ -386,7 +402,7 @@ export function createHomeWindow(deps) {
if (!signedIn) {
try { grant = await pair(place); } catch (error) {
if (error?.gone && wanted(token)) return gone(place);
- log(`home: no sign-in code for ${place.kind === "team" ? place.name : "My Cloud"} (${error?.message ?? error})`);
+ log(`home: no sign-in code for ${otherPlace(place) ? place.name : "My Cloud"} (${error?.message ?? error})`);
}
if (!wanted(token)) return;
if (!grant) {
@@ -395,11 +411,12 @@ export function createHomeWindow(deps) {
}
}
// My Cloud opened before the move made it home is a saved server the window shows, as the Server menu opens one.
- const asHome = place.kind === "team" || home.kind !== "computer";
+ const asHome = otherPlace(place) || home.kind !== "computer";
screen = null; status = null; tries = 0; away = asHome; shown = asHome ? place : null;
await go(cloudHomeConnectUrl({ origin, grant }, now(), open === "phone" ? "phone" : null), origin, place);
if (place.kind === "cloud") { clearRenewal(); power.woke(); }
- else renewLater(place, grant || !session?.expiresAt ? TEAM_RENEW_MS : session.expiresAt - now() - TEAM_RENEW_EARLY_MS);
+ else if (place.kind === "team") renewLater(place, grant || !session?.expiresAt ? TEAM_RENEW_MS : session.expiresAt - now() - TEAM_RENEW_EARLY_MS);
+ else clearRenewal();
tell();
} finally {
if (handoff) timers.clear(handoff);
@@ -407,18 +424,19 @@ export function createHomeWindow(deps) {
}
/** Shows the window onto the person's home. `open: "phone"` opens My Cloud's Settings on its phone pairing. `place`:
- * "cloud" for My Cloud, `{ team }` for a team's Cloud, else the place remembered from last time. */
+ * "cloud" for My Cloud, `{ team }` for a team's Cloud, `{ cloud }` for another of the person's own, else the place
+ * remembered from last time. */
async function show({ open = null, place = null } = {}) {
const token = ++opens;
const current = await refresh();
if (!wanted(token)) return;
const target = placeOf({ ask: place, remembered: remembered(), state: state() });
if (target.kind === "cloud" && target.left) { left(target.left); remember(null); }
- if (target.kind === "team") {
+ if (otherPlace(target)) {
ensureWindow();
opening = target;
- // Chosen is remembered at once, so the screen's own retry (and the next launch) asks for the same team.
- remember({ team: target.id });
+ // Chosen is remembered at once, so the screen's own retry (and the next launch) asks for the same place.
+ remember(target.kind === "own" ? { cloud: target.id } : { team: target.id });
if (signedOut()) { clearRetry(); return toScreen({ screen: "signin" }); }
const setup = machineSetup(target.machine);
if (setup) { clearRetry(); return toScreen({ screen: "setup", ...setup }); }
@@ -459,7 +477,7 @@ export function createHomeWindow(deps) {
let grant = null;
try { grant = await pair(place); } catch (error) {
if (error?.gone) return gone(place);
- log(`home: could not sign in to ${place.kind === "team" ? place.name : "My Cloud"} again (${error?.message ?? error})`);
+ log(`home: could not sign in to ${otherPlace(place) ? place.name : "My Cloud"} again (${error?.message ?? error})`);
}
if (placeOrigin() !== origin) return;
if (!grant) return signInNeeded() ? toScreen({ screen: "signin" }) : offline(++opens);
@@ -479,7 +497,7 @@ export function createHomeWindow(deps) {
/** A newer page reloads at a quiet moment; an asleep My Cloud is never asked (that would start it). */
async function watchVersion() {
const origin = placeOrigin();
- if (!origin || !shows(origin) || (shown?.kind !== "team" && power.asleep())) return;
+ if (!origin || !shows(origin) || (!otherPlace(shown) && power.asleep())) return;
const current = await version(origin);
if (!current) return;
if (!loaded) { loaded = current; return; }
@@ -515,7 +533,7 @@ export function createHomeWindow(deps) {
placeOrigin,
/** Home as last worked out. */
current: () => home,
- /** The place the window was last sent to: My Cloud, or a team's Cloud (`{ kind: "team", id, name, origin }`). */
+ /** The place the window was last sent to: My Cloud, or a team's or another own Cloud (`{ kind: "team" | "own", id, name, origin }`). */
shown: () => shown,
/** The person asked again (the screen's timer, back online, or the window focused). */
retry: () => show(),
@@ -554,7 +572,7 @@ export function createHomeWindow(deps) {
else if (!(at === localOrigin() && new URL(url).pathname === HOME_SCREEN_PATH)) letAskGo();
}
// The window went to another server (the Server menu): the team it showed is no longer the place on screen.
- if (shown?.kind === "team" && ![shown.origin, localOrigin()].includes(originOf(url))) { shown = null; clearRenewal(); }
+ if (otherPlace(shown) && ![shown.origin, localOrigin()].includes(originOf(url))) { shown = null; clearRenewal(); }
const origin = placeOrigin();
if (!origin || originOf(url) !== origin) return;
const at = new URL(url);
@@ -569,7 +587,7 @@ export function createHomeWindow(deps) {
if (!at || (at !== place && (home.kind !== "computer" || at !== mine))) return false;
if (at !== place) asked ??= { open: null };
const token = ++opens;
- void unreachable(shown?.kind === "team" && at === place ? shown : { kind: "cloud", origin: at }, token, nameNotFound(code));
+ void unreachable(otherPlace(shown) && at === place ? shown : { kind: "cloud", origin: at }, token, nameNotFound(code));
return true;
},
/** `event` came from the shown place's own page in this window (My Cloud's while it is home, or a team's Cloud's). */
@@ -602,7 +620,7 @@ export function installHomeWindowIpc({ ipcMain, homeWindow, cloudPage }) {
const screenPage = (event) => homeWindow.screenPage(event);
ipcMain.handle("home:state", from("home:state", screenPage, () => homeWindow.view()));
ipcMain.handle("home:retry", from("home:retry", screenPage, () => homeWindow.retry().then(() => homeWindow.view())));
- ipcMain.handle("home:sign-in", from("home:sign-in", (event) => screenPage(event) || cloudPage(event) === "cloud", () => homeWindow.signIn()));
+ ipcMain.handle("home:sign-in", from("home:sign-in", (event) => screenPage(event) || cloudPage(event) === "cloud" || (homeWindow.homePage(event) && homeWindow.shown()?.kind === "own"), () => homeWindow.signIn()));
ipcMain.handle("home:repair", from("home:repair", (event) => homeWindow.homePage(event), () => homeWindow.repair()));
ipcMain.on("home:page", (event) => { try { event.returnValue = homeWindow.homePage(event); } catch { event.returnValue = false; } });
ipcMain.on("home:updating", (event) => { try { event.returnValue = homeWindow.updating(event); } catch { event.returnValue = false; } });
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index 216a2d0de8..3c60139f19 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -6,6 +6,7 @@ import vm from "node:vm";
import { cloudPlanSnapshot } from "./cloud-account.mjs";
import { installCloudPlanIpc } from "./cloud-plan-ipc.mjs";
import { cloudPageSenderAllowed, myCloudOrigin } from "./cloud-home.mjs";
+import { otherOwnClouds } from "./cloud-list.mjs";
import environments from "./environments.cjs";
import localOrigin from "./local-origin.cjs";
import { createHomeWindow, HOME_SCREEN_PATH, homeOf, installHomeWindowIpc, LOOK_MS, placeOf, QUIET_MS, routeOf, SPLASH_TEXT, splashText, TEAM_RENEW_EARLY_MS, TEAM_RENEW_MS, TEAM_RENEW_RETRY_MS, UPDATING_MS } from "./home-window.mjs";
@@ -13,6 +14,8 @@ import { createHomeWindow, HOME_SCREEN_PATH, homeOf, installHomeWindowIpc, LOOK_
const CLOUD = "https://omb-t-1.fly.dev";
const TEAM = "https://omb-u-acme.fly.dev";
const ACME = { id: "team-acme", name: "Acme", role: "member", machine: { status: "ready", origin: TEAM } };
+const CLIENT = "https://omb-c-a.fly.dev";
+const CLIENT_A = { id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT, teamId: null, primary: false };
const LOCAL = "http://127.0.0.1:8799";
const ACCOUNT = { id: "acct-1", email: "[email protected]" };
const connected = (machine = {}) => ({ status: "connected", account: ACCOUNT, machine: { status: "ready", origin: CLOUD, ...machine } });
@@ -57,13 +60,15 @@ test("a sign-in keeps only a path of My Cloud's own", () => {
* 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.
*/
-function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, splash = true, url = "", remembered = null } = {}) {
+function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null } = {}) {
const w = {
journal, marker, state, power, 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 },
- went: [], calls: [], fetched: [], pairs: 0, teamPairs: [], wakes: 0, waking: [], splash: [], published: [], local: [], reloads: 0, signIns: [],
+ /** Another Cloud of the person's own, answering at CLIENT; `gone`: the Admin's pairing says it is no longer theirs. */
+ client: { down: false, signedIn: true, version: "0.1.130", health: 200, gone: false, ...client },
+ went: [], calls: [], fetched: [], pairs: 0, teamPairs: [], ownPairs: [], wakes: 0, waking: [], splash: [], published: [], local: [], reloads: 0, signIns: [],
remembered, remembers: [], left: [], dropped: [], redeemed: [],
url, timers: [], intervals: [],
};
@@ -80,7 +85,13 @@ function world({ journal = done(), marker = null, state = connected(), power = n
power: () => w.power,
async wakeHome() { w.wakes++; await w.cloud.wakeGate; if (w.cloud.wakes) w.power = { ...w.power, state: "awake" }; return "awake"; },
setWaking: (on) => w.waking.push(on),
- async pairHome() {
+ async pairHome(cloudId = null) {
+ if (cloudId) {
+ w.ownPairs.push(cloudId);
+ if (w.client.gone) throw Object.assign(new Error("Client A is no longer one of your Clouds."), { gone: true });
+ if (w.client.down) throw new Error("Cloud request failed.");
+ return { origin: CLIENT, code: "CCCC-LLLL-AAAA", expiresAt: w.clock + 60_000 };
+ }
w.pairs++;
if (w.state?.status !== "connected" || w.cloud.down) throw new Error("My Cloud is not ready to connect yet.");
return { origin: CLOUD, code: "AAAA-BBBB-CCCC", expiresAt: w.clock + 60_000 };
@@ -102,26 +113,27 @@ function world({ journal = done(), marker = null, state = connected(), power = n
ensureWindow: () => { w.calls.push("ensure"); },
localOrigin: () => LOCAL,
cookieFetch: async (url, init) => {
- const atTeam = String(url).startsWith(TEAM), server = atTeam ? w.team : w.cloud;
- w.fetched.push([String(url).replace(atTeam ? TEAM : CLOUD, atTeam ? "team:" : ""), init?.headers?.["x-omb-background"] ?? null]);
+ const atClient = String(url).startsWith(CLIENT), atTeam = String(url).startsWith(TEAM), server = atClient ? w.client : atTeam ? w.team : w.cloud;
+ const base = atClient ? CLIENT : atTeam ? TEAM : CLOUD;
+ w.fetched.push([String(url).replace(base, atClient ? "client:" : atTeam ? "team:" : ""), init?.headers?.["x-omb-background"] ?? null]);
if (server.down) throw new TypeError("fetch failed");
- const route = String(url).replace(atTeam ? TEAM : CLOUD, "");
+ const route = String(url).replace(base, "");
if (route === "/api/health") return new Response("", { status: server.health, headers: server.health === 503 ? { "x-omb-cloud-power": "asleep" } : {} });
if (route === "/api/auth/session") return server.signedIn ? json({ kind: "session", ...(server.expiresAt ? { expiresAt: server.expiresAt } : {}) }) : json({ error: "sign in" }, 401);
if (route === "/api/auth/pair" && init?.method === "POST") {
- w.redeemed.push([atTeam ? "team" : "cloud", JSON.parse(init.body)]);
+ w.redeemed.push([atClient ? "client" : atTeam ? "team" : "cloud", JSON.parse(init.body)]);
return server.redeems === false ? json({ error: "invalid code" }, 400) : json({ kind: "session" });
}
if (route === "/.well-known/openmausbot/environment") return json({ version: server.version });
return json({}, 404);
},
power: { asleep: () => w.power?.state === "asleep", hold: () => { w.power = { state: "asleep", since: 1 }; }, woke: () => w.calls.push("woke") },
- go: async (url, origin, place) => { w.went.push(place?.kind === "team" ? [url, origin, place.id] : [url, origin]); w.url = url; },
+ go: async (url, origin, place) => { w.went.push(place?.kind === "team" || place?.kind === "own" ? [url, origin, place.id] : [url, origin]); w.url = url; },
showLocal: (leaving) => { w.local.push(leaving); if (leaving) w.url = `${LOCAL}/`; },
remembered: () => w.remembered,
remember: (place) => { w.remembers.push(place); w.remembered = place ? { ...place, name: ACME.name, origin: TEAM } : null; },
left: (name) => w.left.push(name),
- drop: (place) => { w.dropped.push(place.id); w.left.push(place.name); w.remembered = null; },
+ drop: (place) => { w.dropped.push(place.id); if (place.kind !== "own") w.left.push(place.name); w.remembered = null; },
splash: () => (splash ? { status: (text) => w.splash.push(text) } : null),
lastInput: () => w.typed,
publish: (view) => w.published.push(view),
@@ -486,11 +498,11 @@ function pageIpc(overrides = {}) {
entitlement: { plan: "pro", tier: "max", status: "active", expiresAt: 1, version: 1 }, machine: { status: "ready", origin: CLOUD } };
const context = vm.createContext({
ipcMain: { handle: (channel, handler) => handlers.set(channel, handler), on: () => {} },
- senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed, cloudPageSenderAllowed,
+ senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed, cloudPageSenderAllowed, otherOwnClouds,
activeEnvironment: environments.activeEnvironment, rendererOrigin: () => LOCAL, desktopRemoteAccess: false,
mainWindow: { isDestroyed: () => false, webContents: cloudContents },
environmentsState: { environments: [{ id: "cloud", name: "My Cloud", origin: CLOUD }], activeId: "cloud" },
- cloudAccount: { homeTarget: () => ({ origin: CLOUD }), state: () => account }, cloudPlanSnapshot, installCloudPlanIpc, myCloudOrigin, rememberedHome: null,
+ cloudAccount: { homeTarget: () => ({ origin: CLOUD }), state: () => account, isOwnCloud: (origin) => origin === CLOUD }, cloudPlanSnapshot, installCloudPlanIpc, myCloudOrigin, rememberedHome: null,
cloudTrialNotices: () => ({ due: () => null, seen: (...args) => { calls.push(["notice-seen", ...args]); } }),
ensureCloudAccount: () => ({ openDashboard: async () => { calls.push(["dashboard"]); return account; }, state: () => account,
upgradePreview: async (...args) => { calls.push(["upgrade-preview", ...args]); return { outcome: "failed" }; },
@@ -549,7 +561,7 @@ test("Settings on the person's own Cloud shows the plan read only, says when it
for (const channel of ["cloud-plan:state", "cloud-plan:manage", "cloud-plan:notice-seen"]) assert.throws(() => ipc.handlers.get(channel)(sender), /only available/);
}
let current = { status: "reauth-required", message: "expired", account: ipc.account.account, lastPlan: { tier: "max", active: true } };
- ipc.context.cloudAccount = { homeTarget: () => null, state: () => current };
+ ipc.context.cloudAccount = { homeTarget: () => null, state: () => current, isOwnCloud: () => false };
assert.throws(() => ipc.handlers.get("cloud-plan:state")(event), /only available/);
ipc.context.rememberedHome = { accountId: "a1", origin: CLOUD };
assert.deepEqual(plain(await ipc.handlers.get("cloud-plan:state")(event)), { status: "signin", tier: "max", home: true });
@@ -810,3 +822,40 @@ test("the usage meter's Upgrade: only from the person's click, only to a plan th
}
assert.equal(ipc.calls.length, 2);
});
+
+test("another Cloud of the person's own is the place asked for by its id, from the session's list; one it no longer lists is simply My Cloud again", () => {
+ const state = { ...connected(), clouds: [{ ...CLIENT_A, id: "c-home", name: "My Cloud", origin: CLOUD, primary: true }, CLIENT_A] };
+ assert.deepEqual(placeOf({ ask: { cloud: "c-a" }, state }), { kind: "own", id: "c-a", name: "Client A", role: "owner", origin: CLIENT, machine: { status: "ready", origin: CLIENT } });
+ assert.deepEqual(placeOf({ remembered: { cloud: "c-a", name: "Client A", origin: CLIENT }, state }).kind, "own");
+ assert.deepEqual(placeOf({ ask: { cloud: "c-home" }, state }), { kind: "cloud" }, "My Cloud is never another Cloud");
+ assert.deepEqual(placeOf({ ask: { cloud: "c-a" }, state: connected() }), { kind: "cloud" }, "not listed (or an older Admin): My Cloud, nothing said");
+ assert.deepEqual(placeOf({ remembered: { cloud: "c-a", name: "Client A", origin: CLIENT }, state: { status: "unavailable" } }),
+ { kind: "own", id: "c-a", name: "Client A", role: null, origin: CLIENT, machine: null }, "while the Admin can't be asked, as it was saved");
+ assert.deepEqual(placeOf({ ask: { cloud: "c-a" }, state: { ...state, clouds: [{ ...CLIENT_A, status: "setting_up", origin: null, setup: { step: "storage" } }] } }).machine,
+ { status: "provisioning", setup: { step: "storage" } });
+});
+
+test("choosing another Cloud of the person's own opens it through the Admin's pairing for that Cloud, at its own address, remembered for next time; no team renewal", async () => {
+ const w = world({ state: { ...connected(), clouds: [CLIENT_A] }, client: { signedIn: false } });
+ await w.home.show({ place: { cloud: "c-a" } });
+ assert.deepEqual(w.ownPairs, ["c-a"]);
+ assert.equal(w.pairs, 0, "never My Cloud's pairing");
+ assert.deepEqual(w.went, [[`${CLIENT}/pair#code=CCCC-LLLL-AAAA`, CLIENT, "c-a"]]);
+ assert.deepEqual(w.fetched, [["client:/api/health", "1"], ["client:/api/auth/session", null]], "a look at that Cloud only");
+ assert.deepEqual(w.remembers, [{ cloud: "c-a" }]);
+ assert.equal(w.home.placeOrigin(), CLIENT);
+ assert.equal(w.timers.length, 0, "its session lasts as My Cloud's does: nothing to renew");
+ assert.deepEqual(w.home.view(), { screen: "opening", name: "Client A" });
+});
+
+test("another Cloud the Admin says is no longer theirs is dropped at once and My Cloud opens, with no line; one being set up shows its setup with its name", async () => {
+ const w = world({ state: { ...connected(), clouds: [CLIENT_A] }, client: { signedIn: false, gone: true } });
+ await w.home.show({ place: { cloud: "c-a" } });
+ assert.deepEqual(w.dropped, ["c-a"]);
+ assert.deepEqual(w.left, [], "a Cloud of their own leaving is no team they were removed from");
+ assert.deepEqual(w.went.at(-1), [CLOUD, CLOUD], "My Cloud");
+ const setup = world({ state: { ...connected(), clouds: [{ ...CLIENT_A, status: "setting_up", setup: { step: "starting" } }] } });
+ await setup.home.show({ place: { cloud: "c-a" } });
+ assert.deepEqual(setup.home.view(), { screen: "setup", step: "starting", name: "Client A" });
+ assert.deepEqual(setup.ownPairs, [], "never paired while it is set up");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 95b75743b4..0212c539ef 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -105,7 +105,8 @@ import { installUseMyComputer } from "./use-my-computer.mjs";
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
-import { createHomePlaces } from "./home-places.mjs";
+import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, hostedCloudOrigin, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { otherOwnClouds } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs";
+import { createWindowStateFile } from "./window-state-file.mjs";
import { createEnvironmentsFile } from "./environments-file.mjs";
import { createOrgLibrary } from "./org-library.mjs";
import { createCompanyBackups } from "./company-backups.mjs";
@@ -123,7 +124,7 @@ const { desktopViewerUrl, sameDesktopViewerOrigin } = require("./desktop-viewer.
const { createDesktopWorkspaceManager } = require("./desktop-workspace.cjs");
const { createTrustedApprovalModeCoordinator } = require("./approval-trusted-mode.cjs");
const { DESKTOP_MUTATION_HEADER, desktopServerHeaders } = require("./desktop-server-auth.cjs");
-const { MIN_BOUNDS, normalizeUnreadCount, parseWindowState, resolveWindowState } = require("./window-state.cjs");
+const { MIN_BOUNDS, normalizeUnreadCount, resolveWindowState } = require("./window-state.cjs");
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// vite binds IPv4; a bare "localhost" can resolve to ::1.
@@ -153,63 +154,7 @@ const serverUnavailableWindows = new WeakSet();
let unreadCount = 0;
let unreadOverlayIcon = null;
-function windowStateFile() {
- return path.join(app.getPath("userData"), "window-state.json");
-}
-
-function readWindowState() {
- try {
- return parseWindowState(fs.readFileSync(windowStateFile(), "utf8"));
- } catch {
- return null;
- }
-}
-
-function writeWindowState(win) {
- if (!win || win.isDestroyed()) return;
- const file = windowStateFile();
- const temporary = `${file}.${process.pid}.tmp`;
- try {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- fs.writeFileSync(
- temporary,
- JSON.stringify({ bounds: win.getNormalBounds(), maximized: win.isMaximized() }),
- { mode: 0o600 },
- );
- fs.renameSync(temporary, file);
- } catch (error) {
- try {
- fs.rmSync(temporary, { force: true });
- } catch {}
- slog(`window state save failed: ${error?.message ?? error}`);
- }
-}
-
-function installWindowStatePersistence(win) {
- let timer = null;
- const flush = () => {
- if (timer) clearTimeout(timer);
- timer = null;
- writeWindowState(win);
- };
- const schedule = () => {
- if (timer) clearTimeout(timer);
- timer = setTimeout(flush, 250);
- timer.unref?.();
- };
- win.on("resize", schedule);
- win.on("move", schedule);
- const pushMaximized = () => {
- try {
- if (!win.isDestroyed()) win.webContents.send("window:maximized-changed", win.isMaximized());
- } catch {}
- };
- win.on("maximize", pushMaximized);
- win.on("unmaximize", pushMaximized);
- win.on("maximize", schedule);
- win.on("unmaximize", schedule);
- win.on("close", flush);
-}
+const windowStateFile = createWindowStateFile({ file: () => path.join(app.getPath("userData"), "window-state.json"), log: message => slog(message) });
function applyUnreadBadge(win = mainWindow) {
const count = normalizeUnreadCount(unreadCount);
@@ -883,7 +828,7 @@ function ensureCloudAccount() {
rememberCloudHome(state);
rememberedHome = rememberedCloudHome(rememberedHome, state);
sendUpdaterState();
- cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); } catch {}
+ cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); rail.changed(); } catch {}
void includedX.onState(state); void includedPages.onState(state); updatesConsent?.accountChanged(state);
refreshCloudMenus();
announceCloudReady(state);
@@ -1481,7 +1426,7 @@ ipcMain.on("desktop:unread-count", (event, value) => {
applyUnreadBadge(sender);
});
-const { LOCAL_ID, activeEnvironment, activeRemote, allowedOrigins, bootEnvironmentDir, otherPlaces, parseHostedWorkspaceLink, startupEnvironmentDir, withActive, withEnvironment, withEnvironmentLook, withLocalEnvironment, withMicrophone, withoutEnvironment, withTeam, placesMenuOptions, workspaceMenuTemplate, workspaceNavigationAllowed, workspaceSenderAllowed, workspaceSummary, workspaceWindowTitle } = environmentsModule;
+const { LOCAL_ID, activeEnvironment, activeRemote, allowedOrigins, bootEnvironmentDir, otherPlaces, parseHostedWorkspaceLink, startupEnvironmentDir, withActive, withEnvironment, withEnvironmentLook, withLocalEnvironment, withMicrophone, withPlaceColor, withoutEnvironment, withOwnCloud, withTeam, placesMenuOptions, workspaceMenuTemplate, workspaceNavigationAllowed, workspaceSenderAllowed, workspaceSummary, workspaceWindowTitle } = environmentsModule;
let environmentsState = { environments: [], activeId: LOCAL_ID };
let computerSharing;
const sharingPrompts = new Set();
@@ -1555,7 +1500,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) return;
+ if (env.origin === cloudAccount?.homeTarget()?.origin || cloudAccount?.isOwnCloud(env.origin)) return;
if (!(await refreshSharedComputersAllowed()) || win.isDestroyed()) return;
sharingPrompts.add(env.id);
try {
@@ -1605,6 +1550,7 @@ function persistEnvironments(next) {
environmentsState = next;
refreshApplicationMenu();
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.setTitle(workspaceWindowTitle(environmentsState, desktopRemoteAccess, homeWindow.cloudOrigin()));
+ try { rail.changed(); } catch {}
}
async function workspaceMenuAction(action) {
@@ -1725,7 +1671,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId) {
async function switchEnvironment(id) {
if ((id === environmentsState.activeId && !homeWindow.asking()) || (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id))) return;
const entry = environmentsState.environments.find((candidate) => candidate.id === id);
- if (entry?.team) return void await showHome({ place: { team: entry.team.id, name: entry.name } });
+ if (entry?.team || entry?.cloud) return void await showHome({ place: entry.team ? { team: entry.team.id, name: entry.name } : { cloud: entry.cloud.id, name: entry.name } });
homePlaces.remember(null);
if (entry?.kind === "local") return await switchLocalEnvironmentTo(entry.dataDir, entry.id);
if (id === LOCAL_ID && (runningDataDir ?? desktopDataDir()) !== desktopDataDir()) {
@@ -1916,9 +1862,9 @@ function activateCloud(origin) {
if (!entry) throw new Error("My Cloud could not be added to Servers.");
persistEnvironments(withActive(next, entry.id)); cloudAccount?.checkoutDone();
}
-/** A team's Cloud listed under Servers as the Admin names it (never a page), and the server this window shows. */
-function activateTeam(place) {
- const next = withTeam(environmentsState, place, () => randomUUID());
+/** A team's or another own Cloud listed under Servers as the Admin names it (never a page), and the server this window shows. */
+function activatePlace(place) {
+ const next = place.kind === "own" ? withOwnCloud(environmentsState, { ...place, role: place.role ?? "owner", color: undefined }, () => randomUUID()) : withTeam(environmentsState, place, () => randomUUID());
const entry = next.environments.find((candidate) => candidate.origin === place.origin);
if (!entry) throw new Error(`${place.name} could not be added to Servers.`);
persistEnvironments(withActive(next, entry.id));
@@ -2052,7 +1998,7 @@ function createWindow({ deferNavigation = false } = {}) {
const waitsForSkinSync = process.platform === "win32";
const primary = screen.getPrimaryDisplay();
const displays = [primary, ...screen.getAllDisplays().filter((display) => display.id !== primary.id)];
- const restored = resolveWindowState(readWindowState(), displays.map((display) => display.workArea));
+ const restored = resolveWindowState(windowStateFile.read(), displays.map((display) => display.workArea));
const win = new BrowserWindow({
...restored.bounds,
minWidth: MIN_BOUNDS.width,
@@ -2096,7 +2042,7 @@ function createWindow({ deferNavigation = false } = {}) {
win.once("show", clearSkinSyncFallback);
win.once("closed", clearSkinSyncFallback);
}
- installWindowStatePersistence(win);
+ windowStateFile.install(win);
applyUnreadBadge(win);
if (restored.maximized && !startupScreen) win.maximize();
win.once("closed", () => {
@@ -2673,7 +2619,13 @@ const cloudPageSender = (channel, handler) => (event) => {
if (!asking) throw new Error(`${channel} is only available in this app's window`);
return handler(asking === "cloud");
};
-const updaterPageAllowed = event => cloudPageAsking(event) !== null;
+/** The page of another Cloud of the person's own, open as this window's active server: that Cloud, as the session lists it. */
+const ownCloudPage = event => {
+ const origin = activeEnvironment(environmentsState)?.origin, contents = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null;
+ if (!origin || origin === myCloud() || !cloudAccount?.isOwnCloud(origin) || !cloudPageSenderAllowed(event, { contents, homeOrigin: origin, activeOrigin: origin })) return null;
+ return otherOwnClouds(cloudAccount.state().clouds).find(cloud => cloud.origin === origin) ?? null;
+};
+const updaterPageAllowed = event => cloudPageAsking(event) !== null || ownCloudPage(event) !== null;
const updaterPageOffered = event => {
if (updaterPageAllowed(event)) return true;
if (desktopRemoteAccess || cloudSignInRestored) return false;
@@ -2684,7 +2636,7 @@ ipcMain.on("update:offered", event => {
try { event.returnValue = updaterPageOffered(event) === true; } catch { event.returnValue = false; }
});
ipcMain.handle("cloud-lending:open", cloudPageSender("cloud-lending:open", () => openLendingSettings()));
-installCloudPlanIpc({ ipcMain, pageSender: cloudPageSender, account: () => cloudAccount, client: () => ensureCloudAccount(), notices: () => cloudTrialNotices(), homePage: event => homeWindow.homePage(event) });
+installCloudPlanIpc({ ipcMain, pageSender: cloudPageSender, account: () => cloudAccount, client: () => ensureCloudAccount(), notices: () => cloudTrialNotices(), homePage: event => homeWindow.homePage(event), otherCloud: ownCloudPage });
const savedWorkspace = id => {
const env = environmentsState.environments.find(entry => entry.id === id);
@@ -2706,7 +2658,7 @@ const homeWindow = createHomeWindow({ journal: oneHome.journal, frozen: oneHome.
hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")),
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") { activateTeam(place); teamProfileSeeds.opened(place.origin); } else if (origin) activateCloud(origin); else if (activeEnvironment(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(url); },
+ 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); },
showLocal: leaving => {
if (!mainWindow || mainWindow.isDestroyed()) return createWindow();
if (!leaving) return;
@@ -2718,6 +2670,19 @@ installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking });
function showHome(options) {
return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));
}
+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 rail = installCloudRail({ ipcMain, guard: workspaceOnly, clipboard, window: () => mainWindow, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),
+ trusted: event => senderIsLocal(event) || hostedCloudOrigin(activeEnvironment(environmentsState)?.origin, { state: desktopRemoteAccess ? null : cloudAccount?.state(), mine: myCloud() }),
+ places: () => railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin(), mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state() }),
+ open: id => workspaceMenuAction(() => switchEnvironment(id)),
+ add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),
+ run: choice => (choice === "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,
+ open: id => { if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });
+// The page's own place's colour (place-look.mjs): the Admin's for a Cloud, this app's for a server connected by hand.
+installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => activeEnvironment(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),
+ setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)) });
ipcMain.handle("sharing:state", localWorkspaceOnly("sharing:state", async (_event, id) => {
await requireSharedComputers();
return sharingController().state(savedWorkspace(id).id);
diff --git a/electron/place-look.d.mts b/electron/place-look.d.mts
new file mode 100644
index 0000000000..a1621bbcc7
--- /dev/null
+++ b/electron/place-look.d.mts
@@ -0,0 +1,24 @@
+/** The colour of the place a page shows, as that page sees it: never the Cloud's id. */
+export interface PlaceLook {
+ name: string;
+ color: import("./cloud-buy.mjs").CloudColor | null;
+ /** The swatch it is offered as; null for none (or a colour no swatch has). */
+ swatch: import("./cloud-list.mjs").CloudSwatch | null;
+ /** Where a change goes: the Admin (every app of theirs follows), this app, or nowhere from here. */
+ change: "admin" | "local" | null;
+ /** Why it can't be changed here: only its Super admin and Admins may, or the MausBot Cloud sign-in is away. */
+ reason?: "member" | "signed-out";
+}
+export type PlaceColorOutcome = "saved" | "refused" | "unsupported" | "failed";
+export declare function swatchOf(color: unknown): import("./cloud-list.mjs").CloudSwatch | null;
+export declare function listedCloudOf(entry: any, session?: { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null }): import("./cloud-list.mjs").CloudListEntry | null;
+export declare function placeLook(entry: any, session?: { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null }): (PlaceLook & { cloudId?: string }) | null;
+export declare function pageLook(look: (PlaceLook & { cloudId?: string }) | null): PlaceLook | null;
+export declare function installPlaceLook(deps: {
+ ipcMain: { handle(channel: string, handler: (...args: any[]) => unknown): void };
+ guard: (handler: (...args: any[]) => unknown) => (...args: any[]) => unknown;
+ place: () => any;
+ session: () => { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null };
+ setColor: (cloudId: string, swatch: import("./cloud-list.mjs").CloudSwatch | null) => Promise<{ outcome: PlaceColorOutcome }>;
+ save: (id: string, color: import("./cloud-buy.mjs").CloudColor | null) => void;
+}): { look(): (PlaceLook & { cloudId?: string }) | null };
diff --git a/electron/place-look.mjs b/electron/place-look.mjs
new file mode 100644
index 0000000000..fea53c2a3c
--- /dev/null
+++ b/electron/place-look.mjs
@@ -0,0 +1,76 @@
+// The colour of the place a page shows: drawn faintly at the top of its sidebar and on its circle in the rail, and
+// changed from its own Settings. A Cloud's colour (My Cloud, another of the person's own, a team's) is the Admin's, so
+// every app of theirs follows it: its owner or its team's Super admin and Admins change it there; everyone else sees it.
+// A server the person connected by hand keeps the colour this app saved for it, and so does a Cloud an older Admin
+// keeps no colour for. A page learns and changes only the colour of the place it is; this computer's own page has none.
+import environments from "./environments.cjs";
+import { CLOUD_SWATCH_COLORS, CLOUD_SWATCHES, swatchColor } from "./cloud-list.mjs";
+
+/** The swatch a saved colour is offered as (CLOUD_SWATCH_COLORS the other way); null for none, or a colour no swatch has. */
+export function swatchOf(color) {
+ if (!environments.ENTRY_COLORS.includes(color)) return null;
+ return CLOUD_SWATCHES.find(swatch => CLOUD_SWATCH_COLORS[swatch] === color) ?? null;
+}
+
+/** The session's own word for a saved place: another Cloud of the person's by its id, a team's Cloud by its team, My
+ * Cloud as the account's primary one. Null for a server connected by hand, or without the session's list. */
+export function listedCloudOf(entry, { clouds = null, homeOrigin = null } = {}) {
+ if (!Array.isArray(clouds) || !entry) return null;
+ if (entry.cloud) return clouds.find(cloud => cloud.id === entry.cloud.id && cloud.managed !== false) ?? null;
+ if (entry.team) return clouds.find(cloud => cloud.teamId === entry.team.id && cloud.managed !== false) ?? null;
+ if (entry.home === true || (homeOrigin !== null && entry.origin === homeOrigin)) return clouds.find(cloud => cloud.primary) ?? null;
+ return null;
+}
+
+/**
+ * A saved place's colour, and where a change of it goes: `admin` (the Admin keeps it, and this person owns that Cloud
+ * or is its team's Super admin or Admin), `local` (this app keeps it: a server connected by hand, or a Cloud an older
+ * Admin lists no colours for), or none, with why: a team member's, or another Cloud of theirs while the sign-in is
+ * away. Null for this computer and for no place. `cloudId` stays in main.
+ */
+export function placeLook(entry, { clouds = null, homeOrigin = null } = {}) {
+ if (!entry || entry.kind === "local" || typeof entry.origin !== "string" || !entry.origin) return null;
+ const color = environments.ENTRY_COLORS.includes(entry.color) ? entry.color : null;
+ const base = { name: entry.name, color, swatch: swatchOf(color) };
+ const mine = entry.home === true || (homeOrigin !== null && entry.origin === homeOrigin);
+ if (!mine && !entry.team && !entry.cloud) return { ...base, change: "local" };
+ const listed = listedCloudOf(entry, { clouds, homeOrigin });
+ const role = listed?.role ?? entry.team?.role ?? entry.cloud?.role ?? "owner";
+ if (role === "member") return { ...base, change: null, reason: "member" };
+ if (listed) return { ...base, change: "admin", cloudId: listed.id };
+ // Another Cloud of the person's own is listed whenever the sign-in is: a colour saved here alone would be undone.
+ if (entry.cloud) return { ...base, change: null, reason: "signed-out" };
+ return { ...base, change: "local" };
+}
+
+/** What the page sees of it: never the Cloud's id. */
+export function pageLook(look) {
+ if (!look) return null;
+ const { cloudId: _id, ...seen } = look;
+ return seen;
+}
+
+/**
+ * The page's own place's colour (`workspaces:look`) and its change (`workspaces:color`, a swatch or null for none),
+ * each behind main's window guard. `place()`: the saved place on screen, which the guard made sure the asking page is;
+ * `session()`: the verified session's Clouds and My Cloud's address; `setColor(cloudId, swatch)`: the Admin's change
+ * (cloud-account.mjs setCloudColor); `save(id, color)`: this app's saved place, at once, so its circle and the top of
+ * its sidebar follow before the session is read again.
+ */
+export function installPlaceLook({ ipcMain, guard, place, session, setColor, save }) {
+ const look = () => placeLook(place(), session());
+ ipcMain.handle("workspaces:look", guard(() => pageLook(look())));
+ ipcMain.handle("workspaces:color", guard(async (_event, swatch) => {
+ if (!(swatch === null || CLOUD_SWATCHES.includes(swatch))) throw new Error("Choose one of the colors.");
+ const entry = place(), current = placeLook(entry, session());
+ if (!current) throw new Error("This place has no color to change.");
+ if (!current.change) return { outcome: "refused", look: pageLook(current) };
+ if (current.change === "admin") {
+ const result = await setColor(current.cloudId, swatch);
+ if (result?.outcome !== "saved") return { outcome: result?.outcome === "refused" || result?.outcome === "unsupported" ? result.outcome : "failed", look: pageLook(look()) };
+ }
+ save(entry.id, swatchColor(swatch));
+ return { outcome: "saved", look: pageLook(look()) };
+ }));
+ return { look };
+}
diff --git a/electron/place-look.node-test.mjs b/electron/place-look.node-test.mjs
new file mode 100644
index 0000000000..317d6d5a7f
--- /dev/null
+++ b/electron/place-look.node-test.mjs
@@ -0,0 +1,101 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { listedColors, parseCloudList } from "./cloud-list.mjs";
+import environments from "./environments.cjs";
+import { createHomePlaces } from "./home-places.mjs";
+import { installPlaceLook, pageLook, placeLook, swatchOf } from "./place-look.mjs";
+
+const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", TEAM = "https://omb-t-acme.fly.dev", VPS = "https://bots.example.test";
+const cloud = (over = {}) => ({ id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A, teamId: null, primary: false, ...over });
+const CLOUDS = parseCloudList([cloud({ id: "c-home", name: "My Cloud", color: null, origin: HOME, primary: true }), cloud(),
+ cloud({ id: "c-acme", name: "Acme", color: "amber", teamId: "team-acme", role: "admin", origin: TEAM })]);
+const home = { id: "home", kind: "remote", name: "Studio", origin: HOME, home: true, color: "purple" };
+const own = { id: "a", kind: "remote", name: "Client A", origin: CLIENT_A, color: "teal", cloud: { id: "c-a", role: "owner" } };
+const team = (role = "admin") => ({ id: "acme", kind: "remote", name: "Acme", origin: TEAM, team: { id: "team-acme", role } });
+const typed = { id: "vps", kind: "remote", name: "Office", origin: VPS };
+
+test("who changes a place's colour, and where it is kept: the Admin for a Cloud its owner or team admin opens, this app for a server connected by hand", () => {
+ const session = { clouds: CLOUDS, homeOrigin: HOME };
+ assert.deepEqual(placeLook(home, session), { name: "Studio", color: "purple", swatch: "violet", change: "admin", cloudId: "c-home" }, "My Cloud: the account's primary Cloud");
+ assert.deepEqual(placeLook(own, session), { name: "Client A", color: "teal", swatch: "green", change: "admin", cloudId: "c-a" });
+ assert.deepEqual(placeLook(team("admin"), session), { name: "Acme", color: null, swatch: null, change: "admin", cloudId: "c-acme" });
+ assert.deepEqual(placeLook(typed, session), { name: "Office", color: null, swatch: null, change: "local" });
+ assert.deepEqual(placeLook({ ...typed, color: "orange" }, session).swatch, null, "a colour no swatch has is shown, and none of the six is ticked");
+ const member = parseCloudList([...CLOUDS.slice(0, 2), cloud({ id: "c-acme", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM })]);
+ assert.deepEqual(placeLook(team("admin"), { clouds: member, homeOrigin: HOME }), { name: "Acme", color: null, swatch: null, change: null, reason: "member" }, "the Admin's role is the word");
+ assert.deepEqual(placeLook(team("member"), { clouds: null, homeOrigin: HOME }), { name: "Acme", color: null, swatch: null, change: null, reason: "member" }, "an older Admin: the team's role");
+ assert.deepEqual(placeLook(team("owner"), { clouds: null, homeOrigin: HOME }).change, "local", "an older Admin keeps no colours: this app does");
+ assert.deepEqual(placeLook(home, { clouds: null, homeOrigin: HOME }).change, "local");
+ assert.deepEqual(placeLook(own, { clouds: null, homeOrigin: HOME }), { name: "Client A", color: "teal", swatch: "green", change: null, reason: "signed-out" },
+ "another Cloud of theirs while the sign-in is away: a colour saved here alone would be undone");
+ assert.deepEqual(placeLook({ ...home, home: undefined }, session).cloudId, "c-home", "My Cloud by its address too");
+ for (const none of [null, undefined, { id: "local", kind: "local", name: "This computer" }, { id: "lab", kind: "local", name: "Lab", dataDir: "/x" }]) assert.equal(placeLook(none, session), null);
+ assert.deepEqual(pageLook(placeLook(own, session)), { name: "Client A", color: "teal", swatch: "green", change: "admin" }, "the page never sees the Cloud's id");
+ assert.deepEqual(["blue", "teal", "yellow", "red", "purple", "orange", null, "url(x)"].map(swatchOf), ["blue", "green", "amber", "rose", "violet", null, null, null]);
+});
+
+function ipc({ entry, clouds = CLOUDS, answer = { outcome: "saved" } } = {}) {
+ const handlers = new Map(), asked = [], saved = [];
+ let state = { activeId: entry?.id ?? "local", environments: entry ? [entry] : [] };
+ installPlaceLook({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler,
+ place: () => state.environments.find(candidate => candidate.id === state.activeId) ?? null, session: () => ({ clouds, homeOrigin: HOME }),
+ setColor: async (id, swatch) => { asked.push([id, swatch]); return answer; },
+ save: (id, color) => { saved.push([id, color]); state = environments.withPlaceColor(state, id, color); } });
+ return { asked, saved, call: (channel, ...args) => handlers.get(channel)({ sender: {} }, ...args) };
+}
+
+test("a page changes only its own place's colour: a Cloud's on the Admin first, then here at once; a member's, an older Admin's and a failure change nothing", async () => {
+ const admin = ipc({ entry: own });
+ assert.deepEqual(await admin.call("workspaces:look"), { name: "Client A", color: "teal", swatch: "green", change: "admin" });
+ assert.deepEqual(await admin.call("workspaces:color", "rose"), { outcome: "saved", look: { name: "Client A", color: "red", swatch: "rose", change: "admin" } });
+ assert.deepEqual([admin.asked, admin.saved], [[["c-a", "rose"]], [["a", "red"]]]);
+ assert.deepEqual((await admin.call("workspaces:color", "slate")).look.color, null, "slate is the plain one: no colour, the look of today");
+ await assert.rejects(admin.call("workspaces:color", "chartreuse"), /Choose one of the colors/);
+ await assert.rejects(admin.call("workspaces:color", { toString: () => "rose" }), /Choose one of the colors/);
+
+ const member = ipc({ entry: team("member"), clouds: null });
+ assert.deepEqual(await member.call("workspaces:color", "rose"), { outcome: "refused", look: { name: "Acme", color: null, swatch: null, change: null, reason: "member" } });
+ assert.deepEqual([member.asked, member.saved], [[], []], "a member's choice reaches neither the Admin nor this app");
+
+ for (const outcome of ["refused", "unsupported", "failed"]) {
+ const refused = ipc({ entry: own, answer: { outcome } });
+ assert.deepEqual((await refused.call("workspaces:color", "rose")).outcome, outcome);
+ assert.deepEqual(refused.saved, [], `${outcome}: nothing saved here, so nothing shows a colour the Admin doesn't keep`);
+ }
+
+ const local = ipc({ entry: typed });
+ assert.deepEqual(await local.call("workspaces:color", "amber"), { outcome: "saved", look: { name: "Office", color: "yellow", swatch: "amber", change: "local" } });
+ assert.deepEqual([local.asked, local.saved], [[], [["vps", "yellow"]]], "a server connected by hand: this app's own");
+
+ const computer = ipc({ entry: null });
+ assert.equal(await computer.call("workspaces:look"), null, "this computer's page has no colour");
+ await assert.rejects(computer.call("workspaces:color", "rose"), /no color/);
+});
+
+test("a saved place's colour: set, cleared to none, an unknown one ignored; the Admin's for My Cloud and teams once chosen there", () => {
+ const state = { activeId: "home", environments: [home, own, team("member"), typed, { id: "local", kind: "local", name: "Lab", dataDir: "/x" }] };
+ const red = environments.withPlaceColor(state, "vps", "red");
+ assert.equal(red.environments.find(entry => entry.id === "vps").color, "red");
+ assert.equal(environments.withPlaceColor(red, "vps", "red"), red, "the same state when nothing changes");
+ assert.equal(Object.hasOwn(environments.withPlaceColor(red, "vps", null).environments.find(entry => entry.id === "vps"), "color"), false);
+ for (const [id, color] of [["vps", "chartreuse"], ["local", "red"], ["gone", "red"]]) assert.equal(environments.withPlaceColor(state, id, color), state, `${id} ${color}`);
+
+ const looks = listedColors(parseCloudList([cloud({ id: "c-home", name: "My Cloud", color: "rose", origin: HOME, primary: true }),
+ cloud({ id: "c-acme", name: "Acme", color: "slate", teamId: "team-acme", role: "member", origin: TEAM })]));
+ const listed = environments.withListedColors({ ...state, environments: state.environments.map(entry => (entry.id === "acme" ? { ...entry, color: "blue" } : entry)) }, looks, HOME);
+ assert.deepEqual(listed.environments.map(entry => [entry.id, entry.color ?? null]), [["home", "red"], ["a", "teal"], ["acme", null], ["vps", null], ["local", null]]);
+ assert.equal(environments.withListedColors(state, listedColors(parseCloudList([cloud({ id: "c-home", name: "My Cloud", color: null, origin: HOME, primary: true })])), HOME), state,
+ "none chosen on the Admin yet: the colour picked when the Cloud was set up stays");
+});
+
+test("home places: the session's colours reach the saved places, and a team member sees the colour its admins chose", () => {
+ let state = { activeId: "home", environments: [home, team("member")] };
+ const places = createHomePlaces({ store: { read: () => ({}), write() {} }, environments: () => state, persist: next => { state = next; }, makeId: () => "new", homeOrigin: () => HOME });
+ places.sync({ status: "connected", teams: [{ id: "team-acme", name: "Acme", role: "member", machine: { status: "ready", origin: TEAM } }],
+ clouds: parseCloudList([cloud({ id: "c-home", name: "My Cloud", color: "green", origin: HOME, primary: true }), cloud({ id: "c-acme", name: "Acme", color: "violet", teamId: "team-acme", role: "member", origin: TEAM })]) });
+ assert.deepEqual(state.environments.map(entry => [entry.id, entry.color]), [["home", "teal"], ["acme", "purple"]]);
+ const before = state;
+ places.sync({ status: "connected", teams: [{ id: "team-acme", name: "Acme", role: "member", machine: { status: "ready", origin: TEAM } }] });
+ assert.equal(state, before, "an older Admin lists no colours: the saved ones stay");
+});
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 8cd6526141..80f72b1a59 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -38,7 +38,7 @@ ipcRenderer.on("app:open-settings", (_event, section) => {
// The full bridge goes only to the local server's UI; a remote page gets the safe subset, and main enforces the same rule.
const localOrigin = process.argv.find((arg) => arg.startsWith("--omb-local-origin="))?.slice("--omb-local-origin=".length) ?? null;
const isLocalPage = !localOrigin || location.origin === localOrigin;
-const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "cloudLending", "cloudPlan", "cloudSendPage", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls"]);
+const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "cloudAdd", "cloudLending", "cloudPlan", "cloudSendPage", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "onOpenAppSettings", "exportDiagnostics", "openLogsFolder", "openAtLogin"];
function updaterOffered() {
@@ -101,11 +101,41 @@ const bridge = {
platform: process.platform,
/** This app's version, and whether this page is this app's own (served by this computer, not a server from the Server menu). */
app: { version: appVersion, ownPage: isLocalPage },
- // Safe on a cloud page: the person chooses in a native menu; no direct switching, saved-list reads, host files or secrets.
+ // Safe on a cloud page: the person chooses in a native menu, or a circle of the rail main listed (only for this app's
+ // page and a hosted Cloud's, never addresses), and only from their click; no saved-list reads, host files or secrets.
workspaces: {
state: () => ipcRenderer.invoke("workspaces:state"),
menu: (options) => ipcRenderer.invoke("workspaces:menu", ...(options?.from === "howto" ? ["howto"] : [])),
line: () => ipcRenderer.invoke("workspaces:line"),
+ places: () => ipcRenderer.invoke("workspaces:places"),
+ open: (id) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:open", String(id)) : Promise.reject(new Error("Choose a place to open it.")),
+ add: (choice) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:add", String(choice)) : Promise.reject(new Error("Choose what to add.")),
+ // The colour of the place this page is (never another's): read, and changed only from the person's click.
+ look: () => ipcRenderer.invoke("workspaces:look"),
+ color: (swatch) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:color", swatch === null ? null : String(swatch)) : Promise.reject(new Error("Choose a color.")),
+ onChanged: (cb) => {
+ const handler = () => cb();
+ ipcRenderer.on("workspaces:changed", handler);
+ return () => ipcRenderer.removeListener("workspaces:changed", handler);
+ },
+ },
+ // Buying another Cloud from the rail's +, on this app's page or a hosted Cloud's: plain words in, what the sheet says
+ // out; the account, the token and the checkout page stay in main. Only from the person's click where it opens anything.
+ cloudAdd: {
+ state: () => ipcRenderer.invoke("cloud-add:state"),
+ start: (tier, name, color) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("cloud-add:start", String(tier), String(name), color === null ? null : String(color)) : Promise.reject(new Error("Choose Continue to checkout.")),
+ reopen: () => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("cloud-add:reopen") : Promise.reject(new Error("Choose Reopen checkout.")),
+ copyLink: () => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("cloud-add:copy-link") : Promise.reject(new Error("Choose Copy link.")),
+ open: () => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("cloud-add:open") : Promise.reject(new Error("Choose Open to open it.")),
+ interest: () => ipcRenderer.invoke("cloud-add:interest"),
+ sheet: (open) => ipcRenderer.invoke("cloud-add:sheet", open === true),
},
getCapabilities: () => ipcRenderer.invoke("desktop:capabilities"),
onCapabilitiesChanged: (cb) => {
diff --git a/electron/updater.test.mjs b/electron/updater.test.mjs
index 33284daa0e..9bf6a43718 100644
--- a/electron/updater.test.mjs
+++ b/electron/updater.test.mjs
@@ -7,12 +7,14 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { cloudTarget } from "./cloud-account.mjs";
import { myCloudOrigin, rememberedCloudHome, savedCloudHomeOrigin } from "./cloud-home.mjs";
import { cloudPageSenderAllowed } from "./cloud-home.mjs";
+import { otherOwnClouds, ownCloud } from "./cloud-list.mjs";
import environments from "./environments.cjs";
import localOriginModule from "./local-origin.cjs";
const LOCAL = "http://127.0.0.1:8799";
const CLOUD = "https://home-7f3k2.fly.dev";
const OTHER = "https://bots.example.test";
+const OWN = "https://omb-c-a.fly.dev";
const fixture = vi.hoisted(() => ({ autoUpdater: null, handlers: new Map() }));
@@ -44,11 +46,11 @@ function mainRule() {
const signIn = { options: null, state: { status: "signed-out", message: "restoring" } };
const context = vm.createContext({
ipcMain: { handle: () => {}, on: (channel, listener) => listeners.set(channel, listener) },
- senderIsLocal: localOriginModule.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed, cloudPageSenderAllowed, myCloudOrigin,
+ senderIsLocal: localOriginModule.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed, cloudPageSenderAllowed, myCloudOrigin, otherOwnClouds,
activeEnvironment: environments.activeEnvironment, rendererOrigin: () => LOCAL, desktopRemoteAccess: false,
mainWindow: window,
environmentsState: { environments: [], activeId: environments.LOCAL_ID },
- cloudAccount: { homeTarget: () => ({ origin: CLOUD }), state: () => ({ status: "connected", account: { id: "a1" } }) },
+ cloudAccount: { homeTarget: () => ({ origin: CLOUD }), state: () => ({ status: "connected", account: { id: "a1" } }), isOwnCloud: () => false },
rememberedHome: null, savedCloudHomeOrigin, cloudSignInRestored: true,
// ensureCloudAccount's world: a packaged app, and a sign-in client whose state the test sets.
app: { isPackaged: true, getPath: () => "/unused", getVersion: () => "1.0.0" }, process: { platform: "darwin", env: {} }, cloudTarget,
@@ -61,6 +63,7 @@ function mainRule() {
return {
homeTarget: () => (signIn.state.status === "connected" ? { origin: signIn.state.machine.origin } : null),
state: () => signIn.state,
+ isOwnCloud: (origin) => signIn.state.status === "connected" && (signIn.state.clouds ?? []).some(cloud => ownCloud(cloud) && cloud.origin === origin),
};
},
});
@@ -68,7 +71,8 @@ function mainRule() {
const show = (shown, activeId = environments.LOCAL_ID) => {
window.webContents = shown.webContents;
context.environmentsState = {
- environments: [{ id: "cloud", name: "My Cloud", origin: CLOUD }, { id: "vps", name: "VPS", origin: OTHER }],
+ environments: [{ id: "cloud", name: "My Cloud", origin: CLOUD }, { id: "vps", name: "VPS", origin: OTHER },
+ { id: "own", name: "Client A", origin: OWN, cloud: { id: "c-a", role: "owner" } }],
activeId,
};
};
@@ -195,6 +199,22 @@ it("another server's page never gets the update bridge; My Cloud's does, even wh
expect("updater" in bridgeFor(CLOUD).bridge).toBe(false);
});
+it("another Cloud of the person's own gets the update bridge as My Cloud's page does; a server only signed in with their account does not", () => {
+ const rule = mainRule();
+ const has = (origin, activeId) => {
+ rule.show(page(origin), activeId);
+ return "updater" in bridgeFor(origin, { rule }).bridge;
+ };
+ rule.show(page(CLOUD), "cloud");
+ rule.launching();
+ const cloud = (over) => ({ id: "c-a", name: "Client A", color: null, role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: OWN, teamId: null, primary: false, managed: true, ...over });
+ rule.signedIn({ status: "connected", account: { id: "a1" }, machine: { origin: CLOUD, status: "ready" }, clouds: [cloud({ id: "c-home", origin: CLOUD, primary: true }), cloud()] });
+ expect(has(OWN, "own")).toBe(true);
+ expect(has(OTHER, "vps")).toBe(false);
+ rule.signedIn({ status: "connected", account: { id: "a1" }, machine: { origin: CLOUD, status: "ready" }, clouds: [cloud({ id: "c-home", origin: CLOUD, primary: true }), cloud({ runsOn: "server", managed: false })] });
+ expect(has(OWN, "own")).toBe(false);
+});
+
it("a downloaded update installs when the app quits, except a system package, which is the person's to install", async () => {
const platform = Object.getOwnPropertyDescriptor(process, "platform");
const resourcesPath = process.resourcesPath;
@@ -324,12 +344,12 @@ it("My Cloud's page reads and drives the update channels, and another server's p
const cloud = page(CLOUD);
rule.show(cloud, "cloud");
for (const channel of handlers.keys()) expect(() => handlers.get(channel)(cloud.event), channel).not.toThrow();
- rule.context.cloudAccount = { homeTarget: () => null, state: () => ({ status: "unavailable", account: { id: "a1" } }) };
+ rule.context.cloudAccount = { homeTarget: () => null, state: () => ({ status: "unavailable", account: { id: "a1" } }), isOwnCloud: () => false };
rule.context.rememberedHome = { accountId: "a1", origin: CLOUD };
expect(() => handlers.get("update:get-state")(cloud.event)).not.toThrow();
rule.context.rememberedHome = { accountId: "someone-else", origin: CLOUD };
expect(() => handlers.get("update:get-state")(cloud.event)).toThrow(/only available/);
- rule.context.cloudAccount = { homeTarget: () => ({ origin: CLOUD }), state: () => ({ status: "connected", account: { id: "a1" } }) };
+ rule.context.cloudAccount = { homeTarget: () => ({ origin: CLOUD }), state: () => ({ status: "connected", account: { id: "a1" } }), isOwnCloud: () => false };
rule.context.desktopRemoteAccess = { endpoint: "https://companion.example.test" };
for (const channel of handlers.keys()) expect(() => handlers.get(channel)(cloud.event), channel).toThrow(/only available/);
diff --git a/electron/window-state-file.mjs b/electron/window-state-file.mjs
new file mode 100644
index 0000000000..9bc0b2d013
--- /dev/null
+++ b/electron/window-state-file.mjs
@@ -0,0 +1,58 @@
+// The main window's size and place across launches: window-state.json under userData (window-state.cjs reads it).
+import fs from "node:fs";
+import path from "node:path";
+import { createRequire } from "node:module";
+
+const require = createRequire(import.meta.url);
+const { parseWindowState } = require("./window-state.cjs");
+
+/** `file()`: where it is kept; `log`: main's log line. */
+export function createWindowStateFile({ file, log = () => {} }) {
+ function read() {
+ try {
+ return parseWindowState(fs.readFileSync(file(), "utf8"));
+ } catch {
+ return null;
+ }
+ }
+ function write(win) {
+ if (!win || win.isDestroyed()) return;
+ const target = file();
+ const temporary = `${target}.${process.pid}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(temporary, JSON.stringify({ bounds: win.getNormalBounds(), maximized: win.isMaximized() }), { mode: 0o600 });
+ fs.renameSync(temporary, target);
+ } catch (error) {
+ try { fs.rmSync(temporary, { force: true }); } catch {}
+ log(`window state save failed: ${error?.message ?? error}`);
+ }
+ }
+ /** Saves the window a quarter second after it moves or resizes, and as it closes; tells its page when it is maximized. */
+ function install(win) {
+ let timer = null;
+ const flush = () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ write(win);
+ };
+ const schedule = () => {
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(flush, 250);
+ timer.unref?.();
+ };
+ win.on("resize", schedule);
+ win.on("move", schedule);
+ const pushMaximized = () => {
+ try {
+ if (!win.isDestroyed()) win.webContents.send("window:maximized-changed", win.isMaximized());
+ } catch {}
+ };
+ win.on("maximize", pushMaximized);
+ win.on("unmaximize", pushMaximized);
+ win.on("maximize", schedule);
+ win.on("unmaximize", schedule);
+ win.on("close", flush);
+ }
+ return { read, write, install };
+}
diff --git a/scripts/testing/rail-preview.tsx b/scripts/testing/rail-preview.tsx
new file mode 100644
index 0000000000..7a69e7ab88
--- /dev/null
+++ b/scripts/testing/rail-preview.tsx
@@ -0,0 +1,109 @@
+import { createRoot } from "react-dom/client";
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import type { AddCloudView, RailPlace, RailState } from "../../electron/cloud-rail.mjs";
+import type { PlaceLook } from "../../electron/place-look.mjs";
+import App from "../../src/App";
+import { setAnalyticsEnabled, setEmailGateDone } from "../../src/lib/analytics";
+import { setAdvancedMode } from "../../src/lib/interface-mode";
+import { markSimpleModePromptSeen } from "../../src/lib/simple-mode-prompt";
+import { applySkin, type SkinId } from "../../src/lib/skins";
+import "../../src/styles.css";
+
+// Served only by scripts/verify-cloud-rail.ts: the real app, as a Cloud's page in the desktop window sees it, with the
+// desktop bridge a hosted Cloud's page gets (its rail and add-a-Cloud sheet answered here). ?skin= picks the skin,
+// ?mode=simple Simple mode, ?sheet=add|server|cloud|name|connect opens +'s sheet there (?adding=setting_up: a Cloud
+// being bought; connect: a signed-in server's), ?places=many the list past eight (?more opens it), ?places=servers the
+// person's own servers that signed in. ?look=<colour>|none is the place's colour (its tint), ?member a team's Cloud
+// its member is on, ?settings=look Settings → Appearance at the place's colour.
+const params = new URLSearchParams(location.search);
+setAnalyticsEnabled(false);
+setEmailGateDone("skipped");
+markSimpleModePromptSeen();
+setAdvancedMode(params.get("mode") !== "simple");
+applySkin((params.get("skin") ?? "midnight") as SkinId);
+
+const place = (id: string, name: string, extra: Partial<RailPlace> = {}): RailPlace => ({ id, name, color: null, kind: "cloud", opens: true, ...extra });
+const FEW: RailPlace[] = [
+ place("home", "My Cloud", { color: "blue", active: true }),
+ place("a", "Client A", { color: "teal" }),
+ place("b", "Bakery", { color: "orange", attention: true }),
+ place("acme", "Acme team", { kind: "team", color: "purple" }),
+ place("pending:c", "Client C", { color: "red", opens: false, progress: 0.55 }),
+ place("mini", "Mac mini", { kind: "server" }),
+];
+const SERVERS: RailPlace[] = [
+ place("home", "My Cloud", { color: "blue", active: true }),
+ place("a", "Client A", { color: "teal" }),
+ place("acme", "Acme team", { kind: "team", color: "purple" }),
+ place("vps", "Office", { kind: "server", server: true }),
+ place("signed-in:s-mini", "Mac mini", { kind: "server", opens: false, ownNetwork: true, server: true, offline: true, lastSeenAt: Date.now() - 2 * 3_600_000 }),
+ place("signed-in:s-render", "Render VPS", { kind: "server", color: "red", opens: false, pairs: true, server: true }),
+];
+const MANY = [...FEW, ...["Delta", "Echo Studio", "Fable", "Gamma Ltd", "Harbor"].map((name, n) => place(`x${n}`, name, { color: (["teal", "yellow", "red", "purple", "blue"] as const)[n] }))];
+const member = params.has("member");
+const SWATCH: Record<string, CloudSwatch> = { blue: "blue", teal: "green", yellow: "amber", red: "rose", purple: "violet" };
+const COLOR: Record<CloudSwatch, PlaceLook["color"]> = { blue: "blue", green: "teal", amber: "yellow", rose: "red", violet: "purple", slate: null };
+const tint = params.get("look") ?? (member ? "purple" : "blue");
+const color = tint === "none" ? null : (tint as PlaceLook["color"]);
+const listed = params.get("places") === "many" ? MANY : params.get("places") === "servers" ? SERVERS : FEW;
+// The place on screen wears the colour its tint is drawn in.
+const rail: RailState = { places: listed.map(({ active: _active, ...entry }) => (entry.id === (member ? "acme" : "home") ? { ...entry, color, active: true as const } : entry)),
+ add: { cloud: true, link: true, address: false } };
+let look: PlaceLook = { name: member ? "Acme team" : "My Cloud", color, swatch: color ? SWATCH[color] ?? null : null,
+ change: member ? null : "admin", ...(member ? { reason: "member" as const } : {}) };
+let openSettings: ((section?: string) => void) | null = null;
+const offer = { recommended: "pro", refundDays: 14, plans: [
+ { tier: "starter", label: "Starter", amount: 1500, allowances: { cpus: 2, cpuKind: "shared" as const, memoryMb: 2048, diskGb: 10, maxDiskGb: 20, computers: 15, computerHours: 100, voiceCharacters: 30_000, sleeps: true as const } },
+ { tier: "pro", label: "Pro", amount: 4900, allowances: { cpus: 4, cpuKind: "shared" as const, memoryMb: 4096, diskGb: 10, maxDiskGb: 100, computers: 15, computerHours: 300, voiceCharacters: 60_000 } },
+ { tier: "max", label: "Max", amount: 9900, allowances: { cpus: 8, cpuKind: "shared" as const, memoryMb: 8192, diskGb: 10, maxDiskGb: 100, computers: 15, computerHours: 800, voiceCharacters: 180_000 } },
+] };
+const adding = params.get("adding") === "setting_up"
+ ? { adding: { name: "Client C", color: "rose" as const, tier: "pro", startedAt: Date.now(), status: "setting_up" as const, progress: 0.55, link: true as const } } : {};
+const addView: AddCloudView = { signedIn: true, hasCloud: true, supported: true, canAdd: true, offer, count: 3, home: { name: "My Cloud", color: "blue" }, ...adding };
+const ok = async () => {};
+Object.assign(window, { ogb: {
+ platform: "darwin",
+ app: { version: "0.1.130", ownPage: false },
+ getCapabilities: async () => ({ host: { platform: "darwin", label: "macOS", session: "unknown", packaged: true }, windowChrome: "mac-inset",
+ screenPreview: { available: false, interaction: "none" }, dictation: { available: false, engine: "none", onDevice: false },
+ localComputer: { available: false, support: "unsupported", enabled: false, status: "unavailable" } }),
+ onCapabilitiesChanged: () => () => {},
+ onOpenAppSettings: (callback: (section?: string) => void) => { openSettings = callback; return () => {}; },
+ applySkin: ok, setUnreadCount: () => {}, permStatus: async () => ({}),
+ workspaces: {
+ state: async () => ({ local: false, name: "My Cloud", origin: "https://omb-u-1.fly.dev", color: "blue" }),
+ menu: ok, line: async () => null, places: async () => rail, open: ok, add: ok, onChanged: () => () => {},
+ look: async () => look,
+ color: async (swatch: CloudSwatch) => { look = { ...look, swatch, color: COLOR[swatch] }; return { outcome: "saved", look }; },
+ },
+ cloudAdd: { state: async () => addView, start: async () => ({ outcome: "opened" }), reopen: async () => true, copyLink: async () => true, open: ok, interest: ok, sheet: ok },
+} });
+
+createRoot(document.getElementById("root")!).render(<App />);
+
+// The macOS window's traffic lights, drawn where the system draws them, so the picture shows what sits beside them.
+const lights = document.createElement("div");
+lights.setAttribute("aria-hidden", "true");
+lights.style.cssText = "position:fixed;left:16px;top:17px;display:flex;gap:8px;z-index:100;pointer-events:none";
+for (const color of ["#ff5f57", "#febc2e", "#28c840"]) {
+ const dot = document.createElement("span");
+ dot.style.cssText = `width:12px;height:12px;border-radius:50%;background:${color};display:block`;
+ lights.append(dot);
+}
+document.body.append(lights);
+
+const click = (selector: string) => new Promise<void>((resolve) => {
+ const tick = () => { const target = document.querySelector<HTMLElement>(selector); if (target) { target.click(); resolve(); } else setTimeout(tick, 100); };
+ tick();
+});
+const sheet = params.get("sheet");
+if (sheet === "connect") void click('[data-rail-place="signed-in:s-render"]');
+else if (sheet) void click("[data-rail-add]").then(() => (sheet === "server" ? click('[data-place-add-choice="server"]') : sheet === "add" ? undefined : click('[data-place-add-choice="cloud"]')))
+ .then(() => (sheet === "name" ? click("[data-plan-buy='pro']") : undefined));
+if (params.get("settings") === "look") {
+ const opened = () => new Promise<void>((resolve) => { const tick = () => { if (openSettings) { openSettings(); resolve(); } else setTimeout(tick, 100); }; tick(); });
+ void opened().then(() => click('[data-settings-section="appearance"]'))
+ .then(() => new Promise<void>((resolve) => setTimeout(resolve, 300)))
+ .then(() => document.querySelector("[data-place-look]")?.closest(".rounded-xl")?.scrollIntoView({ block: "center" }));
+}
+if (params.has("more")) void click("[data-rail-more-button]");
diff --git a/scripts/verify-cloud-rail.ts b/scripts/verify-cloud-rail.ts
new file mode 100644
index 0000000000..0856f4199c
--- /dev/null
+++ b/scripts/verify-cloud-rail.ts
@@ -0,0 +1,109 @@
+// The rail of Clouds and its + sheet in the real app, as a Cloud's page in the desktop window shows them, against a
+// disposable fake-engine server; the desktop bridge's rail and add-a-Cloud answers are the preview's own fixtures.
+// Run: node --experimental-strip-types scripts/verify-cloud-rail.ts [--shots <dir> [--only <view,view>]]
+// With --shots it photographs each view in a light and a dark skin with a headless Chrome in a throwaway profile
+// (OMB_CDP_CHROME, else the installed Google Chrome) and exits; without, it prints the preview's address and waits.
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { launchVerificationServer, runControlOmb } from "./control-omb.ts";
+import { mountPreview, parkUntilSignal, type MountedPreview } from "./testing/preview-fixture.ts";
+
+const at = process.argv.indexOf("--shots");
+const shots = at === -1 ? null : resolve(process.argv[at + 1] ?? "");
+const onlyAt = process.argv.indexOf("--only");
+const only = onlyAt === -1 ? null : new Set((process.argv[onlyAt + 1] ?? "").split(",").filter(Boolean));
+const CHROME = process.env.OMB_CDP_CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+/** Each view: its query, what must be on screen before the picture, and the window's height. */
+const VIEWS: Array<{ name: string; query: string; ready: string; height?: number }> = [
+ { name: "rail", query: "", ready: "[data-places-rail]" },
+ { name: "rail-simple", query: "mode=simple", ready: "[data-places-rail]" },
+ { name: "rail-many", query: "places=many&more=1", ready: "[data-rail-more] li" },
+ { name: "add-sheet", query: "sheet=add", ready: "[data-place-add='choose']" },
+ { name: "add-own-server", query: "sheet=server", ready: "[data-place-add='own-server']" },
+ { name: "add-buy-cloud", query: "sheet=cloud", ready: "[data-plan-buy]", height: 900 },
+ { name: "add-name-colour", query: "sheet=name", ready: "[data-cloud-add='extra-name']" },
+ { name: "add-setting-up", query: "sheet=cloud&adding=setting_up", ready: "[data-cloud-add='extra-starting']" },
+ { name: "rail-servers", query: "places=servers&look=teal", ready: "[data-rail-server]" },
+ { name: "connect-server", query: "places=servers&sheet=connect", ready: "[data-place-add='connect-server']" },
+ { name: "look-settings", query: "look=teal&settings=look", ready: "[data-place-look='admin']" },
+ { name: "look-member", query: "member=1&settings=look", ready: "[data-place-look='locked']" },
+];
+const SKINS = [{ id: "daylight", look: "light" }, { id: "midnight", look: "dark" }];
+
+/** One page of a headless Chrome over the DevTools protocol: navigate, wait for a selector, photograph. */
+async function openChrome(profile: string) {
+ const chrome = spawn(CHROME, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--use-mock-keychain",
+ `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"], { stdio: "ignore" });
+ let port = "";
+ for (let i = 0; i < 100 && !port; i++) {
+ await delay(100);
+ try { port = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]!.trim(); } catch {}
+ }
+ if (!port) { chrome.kill(); throw new Error("Chrome did not start"); }
+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; webSocketDebuggerUrl: string }>;
+ const socket = new WebSocket(targets.find((target) => target.type === "page")!.webSocketDebuggerUrl);
+ await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; });
+ let next = 0;
+ const waiting = new Map<number, { done: (value: any) => void; fail: (error: Error) => void }>();
+ socket.onmessage = (event) => {
+ const message = JSON.parse(String(event.data));
+ const call = waiting.get(message.id);
+ if (!call) return;
+ waiting.delete(message.id);
+ if (message.error) call.fail(new Error(message.error.message)); else call.done(message.result);
+ };
+ const send = (method: string, params: object = {}) => new Promise<any>((done, fail) => {
+ const id = ++next;
+ waiting.set(id, { done, fail });
+ socket.send(JSON.stringify({ id, method, params }));
+ });
+ const evaluate = async (expression: string) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true })).result?.value;
+ return {
+ async shoot(url: string, ready: string, file: string, height = 800) {
+ await send("Emulation.setDeviceMetricsOverride", { width: 1280, height, deviceScaleFactor: 2, mobile: false });
+ await send("Page.navigate", { url });
+ const end = Date.now() + 60_000;
+ const condition = `Boolean(document.querySelector(${JSON.stringify(ready)}) && document.querySelector("[data-sidebar-bot-row], [data-sidebar-hero]"))`;
+ while (!(await evaluate(condition).catch(() => false))) {
+ if (Date.now() > end) throw new Error(`${url}: ${ready} never showed (${await evaluate("document.querySelector('main')?.textContent?.slice(0, 120) ?? ''")})`);
+ await delay(250);
+ }
+ await delay(900);
+ const { data } = await send("Page.captureScreenshot", { format: "png" });
+ writeFileSync(file, Buffer.from(data, "base64"));
+ },
+ close() { socket.close(); chrome.kill(); },
+ };
+}
+
+const fixture = await launchVerificationServer();
+let ui: MountedPreview | undefined;
+try {
+ for (const name of ["Chief of Staff", "Research", "Inbox"]) await runControlOmb(["new-bot", "--name", name, "--url", fixture.info.url]);
+ ui = await mountPreview(fixture, { entry: "/scripts/testing/rail-preview.tsx", route: "/__cloud-rail.html", title: "Isolated rail of Clouds", logLevel: "warn" });
+ if (!shots) {
+ console.log(JSON.stringify({ ...fixture.info, previewUrl: ui.previewUrl }, null, 2));
+ await parkUntilSignal();
+ } else {
+ mkdirSync(shots, { recursive: true });
+ const profile = mkdtempSync(join(tmpdir(), "omb-rail-chrome-"));
+ const chrome = await openChrome(profile);
+ try {
+ for (const view of VIEWS.filter((entry) => !only || only.has(entry.name))) for (const skin of SKINS) {
+ const file = join(shots, `${view.name}-${skin.look}.png`);
+ await chrome.shoot(`${ui.previewUrl}?skin=${skin.id}${view.query ? `&${view.query}` : ""}`, view.ready, file, view.height);
+ console.log(file);
+ }
+ } finally {
+ chrome.close();
+ await delay(500);
+ rmSync(profile, { recursive: true, force: true });
+ }
+ }
+} finally {
+ await ui?.close();
+ await fixture.close();
+}
diff --git a/src/App.tsx b/src/App.tsx
index c7a39bf16d..2e89e9bc80 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -34,6 +34,7 @@ import { HomeLine } from "@/components/HomeLine";
import { useTeamChats } from "@/state/team-chats";
import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";
import { CloudAddDialog } from "@/components/CloudAddDialog";
+import { PlacesRail } from "@/components/PlacesRail";
import { CloudHowTo } from "@/components/CloudHowTo";
import { DesktopCapabilitiesProvider, useCaptionChrome, useDesktopCapabilities, WindowDragStrip } from "@/components/DesktopCapabilities";
import { WindowCaptionButtons } from "@/components/WindowCaptionButtons";
@@ -314,6 +315,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
className="absolute inset-0 z-30 bg-black/50 md:hidden"
/>
)}
+ {!calendarFocus && <PlacesRail />}
{!calendarFocus && <Sidebar
collapseToIcons={collapseSidebar}
open={drawerOpen}
diff --git a/src/components/CloudAddDialog.tsx b/src/components/CloudAddDialog.tsx
index 7eca7bfbe4..2ba8f0f001 100644
--- a/src/components/CloudAddDialog.tsx
+++ b/src/components/CloudAddDialog.tsx
@@ -12,6 +12,7 @@ import { cloudAddView, offerPlan, sameTerms, startedSleeps, type CloudAddView, t
import { t } from "@/lib/i18n";
import { welcomeOnScreen } from "@/lib/onboarding";
import { useStore } from "@/state/store";
+import { AddCloudFlow } from "./cloud-buy/AddCloudFlow";
import { ChooseScreen } from "./cloud-buy/ChooseScreen";
import { OneCloudScreen, StatusScreen } from "./cloud-buy/OneCloudScreen";
import { PayScreen } from "./cloud-buy/PayScreen";
@@ -130,6 +131,7 @@ export function CloudAddDialog({ now = Date.now }: { now?: () => number }) {
const [, setTick] = useState(0);
const [arrived, setArrived] = useState(false);
const [terms, setTerms] = useState(false);
+ const [extraWide, setExtraWide] = useState(false);
const open = Boolean(request && bridge);
const profileEmail = state.config?.profile?.email?.trim() || null;
// Over the welcome flow the sheet is as good as closed for "ready": main notifies, and nothing switches the window away.
@@ -263,6 +265,12 @@ export function CloudAddDialog({ now = Date.now }: { now?: () => number }) {
return () => window.removeEventListener("blur", stop);
}, [counting]);
if (!open || !view || !request || !bridge || view.kind === "settings") return null;
+ if (view.kind === "has-cloud" && account?.status === "connected" && account.clouds && window.ogb?.cloudAdd
+ && (account.addCloud?.canAdd !== false || (account.adding && !account.adding.done))) {
+ return <CloudAddSheet kind={extraWide ? "offer" : "has-cloud"} staging={account.staging === true} onClose={close}>
+ <AddCloudFlow onClose={close} onFirstCloud={() => {}} onWide={setExtraWide} />
+ </CloudAddSheet>;
+ }
const offerShown = offer ?? null;
const planNow = () => view.kind === "waiting" && !chosen ? view.plan : offerShown ? offerPlan(offerShown, chosen).tier : null;
diff --git a/src/components/DesktopWorkspaceSwitcher.tsx b/src/components/DesktopWorkspaceSwitcher.tsx
index 1538bcb88b..c3c28ed814 100644
--- a/src/components/DesktopWorkspaceSwitcher.tsx
+++ b/src/components/DesktopWorkspaceSwitcher.tsx
@@ -6,6 +6,7 @@ import type { Action } from "@/state/store";
import type { CloudPlanSnapshot } from "../../electron/cloud-account.mjs";
import { cloudColor } from "@/lib/cloud-look";
import { t } from "@/lib/i18n";
+import { railShown, usePlaces } from "@/lib/places";
import { CloudTile } from "./cloud-buy/parts";
import { SIMPLE_RAIL_BUTTON } from "./SidebarSimpleTop";
@@ -59,8 +60,11 @@ export function useWorkspacePlace({ cloudHome = false, howTo = false, onMenuClos
const [error, setError] = useState("");
useEffect(() => {
let alive = true;
- void bridge?.state().then((state) => { if (alive) setCurrent(state); }).catch(() => {});
- return () => { alive = false; };
+ const read = () => void bridge?.state().then((state) => { if (alive) setCurrent(state); }).catch(() => {});
+ read();
+ // Main's word that a place changed (its colour, say): the switcher's dot follows.
+ const off = bridge?.onChanged?.(read);
+ return () => { alive = false; off?.(); };
}, [bridge]);
const power = useCloudPower(cloudHome || current?.home === true);
const onLine = power.sleeps === null ? "" : t(power.sleeps ? "cloudSetup.sleepsWhenIdle" : "cloudSetup.alwaysOn");
@@ -74,9 +78,19 @@ export function useWorkspacePlace({ cloudHome = false, howTo = false, onMenuClos
return { bridge, current, cloudHome, open, error, onLine, waking, openMenu, switchable: Boolean(bridge) && current?.home !== true };
}
-export function DesktopWorkspaceSwitcher({ compact = false, inline = false, pill = false, rail = false, cloudHome = false, owner = null, howTo = false, onMenuClosed }: {
+type SwitcherProps = {
compact?: boolean; inline?: boolean; pill?: boolean; rail?: boolean; cloudHome?: boolean; owner?: string | null; howTo?: boolean; onMenuClosed?: () => void;
-}) {
+};
+
+/** The place on screen and the native Server menu; where the rail of places shows (two places or more, a wide window), the
+ * rail switches instead. */
+export function DesktopWorkspaceSwitcher(props: SwitcherProps) {
+ const besideRail = railShown(usePlaces());
+ const switcher = <Switcher {...props} />;
+ return besideRail ? <div data-switcher-beside-rail className="contents md:hidden">{switcher}</div> : switcher;
+}
+
+function Switcher({ compact = false, inline = false, pill = false, rail = false, cloudHome = false, owner = null, howTo = false, onMenuClosed }: SwitcherProps) {
const { bridge, current, open, error, onLine, waking, openMenu } = useWorkspacePlace({ cloudHome, howTo, onMenuClosed });
const withPower = (name: string) => (onLine ? `${name} · ${onLine}` : name);
// This window's home is My Cloud: it opens nothing else, so there is nothing to switch.
diff --git a/src/components/PlaceAddSheet.tsx b/src/components/PlaceAddSheet.tsx
new file mode 100644
index 0000000000..a58ff62572
--- /dev/null
+++ b/src/components/PlaceAddSheet.tsx
@@ -0,0 +1,132 @@
+// + at the end of the rail: one sheet, two choices. Buy a Cloud (the buying sheet: another Cloud right here, or the
+// first one on this computer's own sheet) or add a server of the person's own through today's pairing link.
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { Check, Cloud, Copy, Server, X } from "lucide-react";
+import type { RailAddChoices } from "../../electron/cloud-rail.mjs";
+import { track } from "@/lib/analytics";
+import { cn } from "@/lib/cn";
+import { useCopyFeedback } from "@/lib/copy-text";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { AddCloudFlow } from "./cloud-buy/AddCloudFlow";
+import { BackLink, Heading } from "./cloud-buy/parts";
+
+/** The commands a server of the person's own runs to be reached from this app. */
+export const OWN_SERVER_INSTALL = "npx openmausbot start";
+export const OWN_SERVER_PAIR = "npx openmausbot pair --label \"My desktop\"";
+
+export interface OwnServerStep { key: string; title: LocaleKey; detail: LocaleKey; command?: string }
+/** What a server of the person's own takes, step by step. `managed`: one command from MausBot Cloud that installs and
+ * connects it by itself; without it, today's install, then its pairing link pasted here. `installed`: it runs
+ * OpenMausBot already (it signed in with the person's account), so only its pairing link is left. */
+export function ownServerSteps(managed: { command: string } | null = null, { installed = false }: { installed?: boolean } = {}): OwnServerStep[] {
+ if (managed) return [{ key: "install", title: "rail.step1", detail: "rail.step1Sub", command: managed.command }];
+ const steps: OwnServerStep[] = [
+ { key: "install", title: "rail.step1", detail: "rail.step1Sub", command: OWN_SERVER_INSTALL },
+ { key: "pair", title: "rail.step2", detail: "rail.step2Sub", command: OWN_SERVER_PAIR },
+ { key: "connect", title: "rail.step3", detail: "rail.step3Sub" },
+ ];
+ return installed ? steps.filter((step) => step.key !== "install") : steps;
+}
+
+function Command({ text }: { text: string }) {
+ const { state, copy } = useCopyFeedback(text);
+ return <div className="mt-2 flex items-center gap-2 rounded-lg border border-hairline bg-app py-1.5 pe-1.5 ps-3">
+ <code data-own-server-command className="min-w-0 flex-1 select-all break-words font-mono text-[13px] text-ink">{text}</code>
+ <button type="button" onClick={copy} className="ui-button inline-flex shrink-0 items-center gap-1.5 px-2.5 py-1 text-[12px]">
+ {state === "copied" ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}
+ {t(state === "copied" ? "rail.copied" : "rail.copy")}
+ </button>
+ </div>;
+}
+
+/** Install OpenMausBot there, open its pairing window, paste its link: the pasted link and the typed address are main's
+ * own Connect dialogs, as the Server menu opens them. `connect`: a server of theirs that signed in with their account,
+ * not connected to this app yet. */
+export function OwnServerSteps({ choices, onBack, onChoose, managed = null, connect = null }: {
+ choices: RailAddChoices; onBack: (() => void) | null; onChoose: (choice: "link" | "address") => void; managed?: { command: string } | null; connect?: { name: string } | null;
+}) {
+ const steps = ownServerSteps(managed, { installed: Boolean(connect) });
+ return <div data-place-add={connect ? "connect-server" : "own-server"} className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ {onBack && <div><BackLink label={t("rail.back")} onClick={onBack} /></div>}
+ <Heading title={connect ? t("rail.connectTitle", { name: connect.name }) : t("rail.own")} sub={t(connect ? "rail.connectLede" : "rail.ownLede")} />
+ <ol className="flex flex-col gap-3">
+ {steps.map((step, index) => <li key={step.key} className="grid grid-cols-[26px_minmax(0,1fr)] gap-3">
+ <span aria-hidden="true" className="grid size-[26px] place-items-center rounded-full bg-accent/12 text-[13px] font-semibold text-accent-text">{index + 1}</span>
+ <div className="min-w-0">
+ <p className="text-[14px] font-semibold text-ink">{t(step.title)}</p>
+ <p className="text-[13px] leading-relaxed text-ink-secondary">{t(step.detail)}</p>
+ {step.command && <Command text={step.command} />}
+ {step.key === "connect" && <div className="mt-2.5 flex flex-wrap gap-2">
+ {choices.link && <button type="button" data-autofocus className="ui-button ui-button-primary" onClick={() => onChoose("link")}>{t("rail.paste")}</button>}
+ {choices.address && <button type="button" className="ui-button" onClick={() => onChoose("address")}>{t("rail.address")}</button>}
+ </div>}
+ </div>
+ </li>)}
+ </ol>
+ </div>;
+}
+
+function Choice({ icon, title, sub, onClick, kind }: { icon: ReactNode; title: string; sub: string; onClick: () => void; kind: string }) {
+ return <button type="button" data-place-add-choice={kind} onClick={onClick}
+ className="flex min-w-0 flex-1 flex-col items-start gap-2 rounded-2xl border border-hairline bg-card p-5 text-start transition-colors hover:border-accent/60 hover:bg-raised focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
+ <span aria-hidden="true" className="grid size-9 place-items-center rounded-[10px] bg-accent/12 text-accent-text">{icon}</span>
+ <span className="text-[15px] font-semibold text-ink">{title}</span>
+ <span className="text-[13px] leading-snug text-ink-secondary">{sub}</span>
+ </button>;
+}
+
+const FOCUSABLE = "button:not([disabled]):not([tabindex='-1']), input:not([disabled]):not([tabindex='-1']), [href], [tabindex='0']";
+
+/** The sheet over the app, like the buying sheet's: Escape and Close close it, Tab stays in it, focus goes back after. */
+export function RailSheet({ wide = false, focusKey, onClose, children }: { wide?: boolean; focusKey: string; onClose: () => void; children: ReactNode }) {
+ const sheet = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const opener = document.activeElement as HTMLElement | null;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") { event.preventDefault(); onClose(); return; }
+ if (event.key !== "Tab") return;
+ const controls = [...(sheet.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])];
+ if (!controls.length) return;
+ event.preventDefault();
+ const at = controls.indexOf(document.activeElement as HTMLElement);
+ controls[at === -1 ? 0 : (at + (event.shiftKey ? -1 : 1) + controls.length) % controls.length]!.focus();
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => { window.removeEventListener("keydown", onKey, true); if (opener?.isConnected) opener.focus(); };
+ }, [onClose]);
+ useEffect(() => {
+ if (sheet.current?.contains(document.activeElement) && document.activeElement !== sheet.current) return;
+ (sheet.current?.querySelector<HTMLElement>("[data-autofocus]") ?? sheet.current?.querySelector<HTMLElement>("#cloud-add-title"))?.focus();
+ }, [focusKey]);
+ return <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4 sm:p-6" onMouseDown={(event) => event.target === event.currentTarget && onClose()}>
+ <div ref={sheet} role="dialog" aria-modal="true" aria-labelledby="cloud-add-title" data-place-add-sheet tabIndex={-1}
+ className={cn("animate-pop-in relative max-h-full w-full overflow-y-auto overscroll-contain rounded-2xl border border-hairline/70 bg-panel shadow-2xl outline-none", wide ? "max-w-[900px]" : "max-w-[560px]")}>
+ <button type="button" onClick={onClose} aria-label={t("cloudAdd.close")} className="ui-icon-button absolute end-3.5 top-3.5 z-10"><X size={18} /></button>
+ {children}
+ </div>
+ </div>;
+}
+
+export function PlaceAddSheet({ choices, connect = null, onClose }: { choices: RailAddChoices; connect?: { name: string } | null; onClose: () => void }) {
+ const server = choices.link || choices.address;
+ const [view, setView] = useState<"choose" | "cloud" | "server">(connect ? "server" : choices.cloud && server ? "choose" : choices.cloud ? "cloud" : "server");
+ const [wide, setWide] = useState(false);
+ const workspaces = window.ogb?.workspaces;
+ const choose = (choice: "cloud" | "link" | "address") => {
+ track("rail_add", { step: choice });
+ onClose();
+ void workspaces?.add?.(choice).catch(() => {});
+ };
+ return <RailSheet wide={view === "cloud" && wide} focusKey={view} onClose={onClose}>
+ {view === "choose" && <div data-place-add="choose" className="flex flex-col gap-5 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("rail.add")} />
+ <div className="flex flex-col gap-3 sm:flex-row">
+ <Choice kind="cloud" icon={<Cloud size={19} />} title={t("rail.buy")} sub={t("rail.buySub")} onClick={() => setView("cloud")} />
+ <Choice kind="server" icon={<Server size={19} />} title={t("rail.own")} sub={t("rail.ownSub")} onClick={() => setView("server")} />
+ </div>
+ </div>}
+ {view === "server" && <OwnServerSteps choices={choices} onBack={choices.cloud && !connect ? () => setView("choose") : null} onChoose={choose} connect={connect} />}
+ {view === "cloud" && <AddCloudFlow onClose={onClose} onFirstCloud={() => choose("cloud")} onWide={setWide} onBack={server ? () => setView("choose") : null} />}
+ </RailSheet>;
+}
diff --git a/src/components/PlaceLookCard.test.ts b/src/components/PlaceLookCard.test.ts
new file mode 100644
index 0000000000..5da71c0f43
--- /dev/null
+++ b/src/components/PlaceLookCard.test.ts
@@ -0,0 +1,93 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { PlaceLook } from "../../electron/place-look.mjs";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root | null = null;
+beforeEach(() => { host = document.createElement("div"); document.body.append(host); });
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); vi.resetModules(); });
+
+const look = (over: Partial<PlaceLook> = {}): PlaceLook => ({ name: "Client A", color: "teal", swatch: "green", change: "admin", ...over });
+
+/** The page's bridge, and the card and tint as a fresh page loads them (the look is shared across the page). */
+async function page(start: PlaceLook | null, answer: (swatch: string | null) => { outcome: string; look: PlaceLook | null } = (swatch) => ({ outcome: "saved", look: look({ swatch: swatch as never, color: swatch === "rose" ? "red" : null }) })) {
+ vi.resetModules();
+ let changed: () => void = () => {};
+ const workspaces = { look: vi.fn(async () => start), color: vi.fn(async (swatch: string | null) => answer(swatch)), onChanged: vi.fn((callback: () => void) => { changed = callback; return () => {}; }) };
+ Object.assign(window, { ogb: { workspaces } });
+ const { setLocale } = await import("@/lib/i18n");
+ setLocale("en");
+ const { PlaceLookCard } = await import("./PlaceLookCard");
+ const { PlaceTint } = await import("./PlaceTint");
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement("div", null, createElement(PlaceTint), createElement(PlaceLookCard))); });
+ await act(async () => { await Promise.resolve(); });
+ return { workspaces, changed: () => changed() };
+}
+const swatch = (name: string) => host.querySelector(`[data-swatch="${name}"]`) as HTMLButtonElement;
+
+it("the tint: a place's colour in the skin's own tone; no colour, or one this app doesn't draw, leaves the sidebar as it was", async () => {
+ const { placeTint } = await import("@/lib/place-look");
+ expect(placeTint("teal")).toEqual({ "--place-tint": "var(--identity-teal)" });
+ expect(placeTint("orange")).toEqual({ "--place-tint": "var(--identity-orange)" });
+ for (const none of [null, undefined, "", "slate", "url(x)", "teal;background:red"]) expect(placeTint(none)).toBeNull();
+ await page(look({ color: null, swatch: "slate" }));
+ expect(host.querySelector("[data-place-tint]")).toBeNull();
+});
+
+it("choosing a swatch saves it through main, and the tint follows at once", async () => {
+ const { workspaces } = await page(look());
+ expect(host.querySelector("[data-place-tint]")?.getAttribute("style")).toContain("var(--identity-teal)");
+ expect(swatch("green").getAttribute("aria-checked")).toBe("true");
+ expect(host.textContent).toContain("Client A shows in this color at the top of the sidebar and on its circle at the window's left edge.");
+ await act(async () => { swatch("rose").click(); await Promise.resolve(); });
+ await act(async () => { await Promise.resolve(); });
+ expect(workspaces.color).toHaveBeenCalledWith("rose");
+ expect(swatch("rose").getAttribute("aria-checked")).toBe("true");
+ expect(host.querySelector("[data-place-tint]")?.getAttribute("style")).toContain("var(--identity-red)");
+ await act(async () => { swatch("rose").click(); await Promise.resolve(); });
+ expect(workspaces.color).toHaveBeenCalledTimes(1);
+});
+
+it("a team member sees the team's colour and who may change it, and their click changes nothing", async () => {
+ const { workspaces } = await page(look({ name: "Acme", change: null, reason: "member" }));
+ expect([...host.querySelectorAll("[data-swatch]")].every((button) => (button as HTMLButtonElement).disabled)).toBe(true);
+ expect(host.querySelector('[data-place-look="locked"]')?.textContent).toContain("Only its admins can change its color.");
+ await act(async () => { swatch("rose").click(); await Promise.resolve(); });
+ expect(workspaces.color).not.toHaveBeenCalled();
+ expect(host.querySelector("[data-place-tint]")?.getAttribute("style"), "they still see it").toContain("var(--identity-teal)");
+});
+
+it("the Admin's refusal, an Admin without the route, and a failure: said plainly, and the colour stays", async () => {
+ for (const [outcome, words] of [["refused", "Only its admins can change its color."], ["unsupported", "This Cloud's color can't be changed from the app yet."], ["failed", "The color wasn't saved. Try again."]] as const) {
+ await act(async () => root?.unmount());
+ await page(look(), () => ({ outcome, look: look() }));
+ await act(async () => { swatch("rose").click(); await Promise.resolve(); });
+ await act(async () => { await Promise.resolve(); });
+ expect(host.textContent).toContain(words);
+ expect(swatch("green").getAttribute("aria-checked")).toBe("true");
+ }
+});
+
+it("this computer's own page, an older app or a browser: no card, no tint", async () => {
+ await page(null);
+ expect(host.innerHTML).toBe("<div></div>");
+ await act(async () => root?.unmount());
+ vi.resetModules();
+ Object.assign(window, { ogb: { workspaces: { state: vi.fn() } } });
+ const { PlaceLookCard } = await import("./PlaceLookCard");
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement(PlaceLookCard)); });
+ expect(host.innerHTML).toBe("");
+});
+
+it("main's word that the place changed (another window, the Admin): the card and tint read it again", async () => {
+ const { workspaces, changed } = await page(look());
+ workspaces.look.mockResolvedValueOnce(look({ color: "purple", swatch: "violet" }));
+ await act(async () => { changed(); await Promise.resolve(); });
+ await act(async () => { await Promise.resolve(); });
+ expect(swatch("violet").getAttribute("aria-checked")).toBe("true");
+ expect(host.querySelector("[data-place-tint]")?.getAttribute("style")).toContain("var(--identity-purple)");
+});
diff --git a/src/components/PlaceLookCard.tsx b/src/components/PlaceLookCard.tsx
new file mode 100644
index 0000000000..7dc249a9ec
--- /dev/null
+++ b/src/components/PlaceLookCard.tsx
@@ -0,0 +1,32 @@
+import { useState } from "react";
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
+import { t } from "@/lib/i18n";
+import { choosePlaceColor, usePlaceLook } from "@/lib/place-look";
+import { Card } from "./SettingsPrimitives";
+import { SwatchRadios } from "./SwatchRadios";
+
+/** The colour of the place on screen, where it is changed, in the six swatches the rail's circles use: a Cloud's is
+ * the Admin's, so every app of theirs follows. A team member sees it and who may change it. Nothing on this computer's
+ * own page, which has no colour. */
+export function PlaceLookCard() {
+ const look = usePlaceLook();
+ const [pending, setPending] = useState<CloudSwatch | null>(null);
+ const [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);
+ if (!look) return null;
+ const locked = look.change === null;
+ const choose = (swatch: CloudSwatch) => {
+ if (locked || pending || swatch === look.swatch) return;
+ setPending(swatch); setOutcome(null);
+ void choosePlaceColor(swatch).then((answer) => { setPending(null); setOutcome(answer); });
+ };
+ const note = look.reason === "member" || outcome === "refused" ? t("placeLook.member") : look.reason === "signed-out" ? t("placeLook.signedOut")
+ : outcome === "unsupported" ? t("placeLook.unsupported") : null;
+ return <Card title={t("placeLook.title")} subtitle={t("placeLook.sub", { name: look.name })}>
+ <div data-place-look={look.change ?? "locked"} className="flex flex-col gap-3">
+ <SwatchRadios value={pending ?? look.swatch} onChange={choose} label={t("placeLook.aria", { name: look.name })} disabled={locked} offset="card" />
+ {note && <p className="text-[13px] text-ink-secondary">{note}</p>}
+ {outcome === "failed" && <p role="alert" className="text-[13px] text-danger">{t("placeLook.failed")}</p>}
+ </div>
+ </Card>;
+}
diff --git a/src/components/PlaceTint.tsx b/src/components/PlaceTint.tsx
new file mode 100644
index 0000000000..4ec11ddb13
--- /dev/null
+++ b/src/components/PlaceTint.tsx
@@ -0,0 +1,9 @@
+import type { CSSProperties } from "react";
+import { placeTint, usePlaceLook } from "@/lib/place-look";
+
+/** The place's colour, faint, across the top of the sidebar and under everything there, so people can tell their
+ * places apart at a glance. Without a colour there is none, and the sidebar looks as it always did. */
+export function PlaceTint() {
+ const tint = placeTint(usePlaceLook()?.color);
+ return tint ? <div aria-hidden="true" data-place-tint className="place-tint pointer-events-none absolute inset-x-0 top-0" style={tint as CSSProperties} /> : null;
+}
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
new file mode 100644
index 0000000000..491da2d110
--- /dev/null
+++ b/src/components/PlacesRail.test.ts
@@ -0,0 +1,191 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { RailPlace, RailState } from "../../electron/cloud-rail.mjs";
+import { setLocale } from "@/lib/i18n";
+import { placeInitials, refreshPlaces } from "@/lib/places";
+
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("./cloud-buy/CloudMascotScene", () => ({ CloudMascotScene: () => null }));
+const { PlacesRail, matchingPlaces, placeLabel, shownPlaces } = await import("./PlacesRail");
+const { DesktopWorkspaceSwitcher } = await import("./DesktopWorkspaceSwitcher");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const place = (id: string, name: string, extra: Partial<RailPlace> = {}): RailPlace => ({ id, name, color: null, kind: "cloud", opens: true, ...extra });
+const PLACES: RailPlace[] = [
+ place("home", "My Cloud", { color: "purple", active: true }),
+ place("a", "Client A", { color: "teal" }),
+ place("acme", "Acme", { kind: "team", attention: true }),
+ place("pending:c-b", "Client B", { opens: false, progress: 0, waiting: true }),
+ place("c", "Client C", { progress: 0.4 }),
+ place("vps", "Office", { kind: "server" }),
+];
+let host: HTMLDivElement, root: Root | null = null;
+let rail: RailState;
+const workspaces = { state: vi.fn(async () => ({ local: false, name: "My Cloud" })), menu: vi.fn(async () => {}), places: vi.fn(async () => rail),
+ open: vi.fn(async () => {}), add: vi.fn(async () => {}), onChanged: vi.fn(() => () => {}) };
+const cloudAdd = { state: vi.fn(async () => ({ signedIn: true, hasCloud: true, supported: false, canAdd: false, offer: null, count: 1, home: { name: "My Cloud", color: null } })),
+ start: vi.fn(), reopen: vi.fn(), copyLink: vi.fn(), open: vi.fn(), interest: vi.fn(async () => {}), sheet: vi.fn(async () => {}) };
+async function mount(element: ReturnType<typeof createElement>) {
+ root = createRoot(host);
+ await act(async () => { await refreshPlaces(); root!.render(element); });
+ await act(async () => { await Promise.resolve(); });
+}
+const click = async (element: Element | null | undefined) => { expect(element).toBeTruthy(); await act(async () => { (element as HTMLElement).click(); await Promise.resolve(); }); };
+beforeEach(() => {
+ setLocale("en");
+ rail = { places: PLACES, add: { cloud: true, link: true, address: false } };
+ Object.assign(window, { ogb: { workspaces, cloudAdd } });
+ vi.clearAllMocks();
+ host = document.createElement("div"); document.body.append(host);
+});
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); document.body.innerHTML = ""; });
+
+it("a circle per place, with its initials on its colour; the place on screen is marked, one that needs the person has a dot, one being set up a ring", async () => {
+ await mount(createElement(PlacesRail));
+ const circles = [...host.querySelectorAll("[data-rail-place]")];
+ expect(circles.map((circle) => circle.textContent)).toEqual(["MC", "CA", "A", "CB", "CC", "O"]);
+ expect(host.querySelector('[data-rail-place="home"]')?.getAttribute("aria-current")).toBe("page");
+ expect(host.querySelector('[data-rail-place="home"] span')?.getAttribute("style")).toContain("var(--identity-purple)");
+ expect(host.querySelector('[data-rail-place="acme"] [data-rail-dot]')).toBeTruthy();
+ expect(host.querySelector('[data-rail-place="pending:c-b"] [data-rail-ring]')?.getAttribute("data-rail-ring")).toBe("waiting");
+ expect(host.querySelector('[data-rail-place="c"] [data-rail-ring]')?.getAttribute("data-rail-ring")).toBe("40");
+ expect(host.querySelector('[data-rail-place="c"]')?.getAttribute("aria-label")).toBe("Client C: setting up");
+ expect(host.querySelector('[data-rail-place="pending:c-b"]')?.getAttribute("aria-label")).toBe("Client B: waiting for payment");
+ expect(host.querySelector("[data-rail-more-button]")).toBeNull();
+ expect(host.querySelector("[data-rail-add]")?.getAttribute("aria-label")).toBe("Add a Cloud or your own server");
+});
+
+it("a click opens the place through main by its id; the one on screen and one not ready yet open nothing", async () => {
+ await mount(createElement(PlacesRail));
+ await click(host.querySelector('[data-rail-place="a"]'));
+ await click(host.querySelector('[data-rail-place="home"]'));
+ await click(host.querySelector('[data-rail-place="pending:c-b"]'));
+ expect(workspaces.open.mock.calls).toEqual([["a"]]);
+});
+
+it("one place or none, an older app, or a browser: no rail, and the switcher stays", async () => {
+ rail = { places: [], add: { cloud: true, link: true, address: true } };
+ await mount(createElement("div", null, createElement(PlacesRail), createElement(DesktopWorkspaceSwitcher, { inline: true })));
+ expect(host.querySelector("[data-places-rail]")).toBeNull();
+ expect(host.querySelector("[data-switcher-beside-rail]")).toBeNull();
+ expect(host.querySelector('[data-workspace-switcher="inline"]')).toBeTruthy();
+});
+
+it("beside the rail, the switcher at the top of the sidebar steps aside on a wide window", async () => {
+ await mount(createElement("div", null, createElement(PlacesRail), createElement(DesktopWorkspaceSwitcher, { inline: true })));
+ expect(host.querySelector("[data-places-rail]")?.className).toContain("md:flex");
+ expect(host.querySelector("[data-switcher-beside-rail]")?.className).toContain("md:hidden");
+});
+
+it("past eight places, ⋯ opens every place, searchable; the place on screen stays among the circles", async () => {
+ const many = Array.from({ length: 11 }, (_, n) => place(`p${n}`, `Client ${String.fromCharCode(65 + n)}`, n === 9 ? { active: true } : {}));
+ rail = { places: many, add: { cloud: true, link: true, address: false } };
+ expect(shownPlaces(many).map((entry) => entry.id)).toEqual(["p0", "p1", "p2", "p3", "p4", "p5", "p6", "p9"]);
+ expect(shownPlaces(PLACES)).toEqual(PLACES);
+ await mount(createElement(PlacesRail));
+ expect(host.querySelectorAll("[data-rail-place]")).toHaveLength(8);
+ await click(host.querySelector("[data-rail-more-button]"));
+ const list = host.querySelector("[data-rail-more]")!;
+ expect(list.querySelectorAll("li")).toHaveLength(11);
+ const input = list.querySelector("input")!;
+ await act(async () => {
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ setValue.call(input, "client k");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect([...list.querySelectorAll("li")].map((row) => row.textContent)).toEqual(["CKClient K"]);
+ await act(async () => { input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });
+ expect(workspaces.open.mock.calls).toEqual([["p10"]]);
+ expect(matchingPlaces(many, "zzz")).toEqual([]);
+});
+
+it("+ offers buying a Cloud or adding the person's own server; the server's three steps end in main's own pairing-link dialog", async () => {
+ await mount(createElement(PlacesRail));
+ await click(host.querySelector("[data-rail-add]"));
+ const sheet = document.querySelector("[data-place-add-sheet]")!;
+ expect([...sheet.querySelectorAll("[data-place-add-choice]")].map((choice) => choice.getAttribute("data-place-add-choice"))).toEqual(["cloud", "server"]);
+ await click(sheet.querySelector('[data-place-add-choice="server"]'));
+ const steps = document.querySelector('[data-place-add="own-server"]')!;
+ expect([...steps.querySelectorAll("[data-own-server-command]")].map((code) => code.textContent)).toEqual(["npx openmausbot start", 'npx openmausbot pair --label "My desktop"']);
+ expect(steps.textContent).toContain("Paste pairing link");
+ expect(steps.textContent).not.toContain("Enter its address instead");
+ await click([...steps.querySelectorAll("button")].find((button) => button.textContent === "Paste pairing link"));
+ expect(workspaces.add.mock.calls).toEqual([["link"]]);
+ expect(document.querySelector("[data-place-add-sheet]")).toBeNull();
+});
+
+it("Buy a Cloud, for someone whose Admin sells one Cloud per account: the calm word, never an error", async () => {
+ await mount(createElement(PlacesRail));
+ await click(host.querySelector("[data-rail-add]"));
+ await click(document.querySelector('[data-place-add-choice="cloud"]'));
+ await act(async () => { await Promise.resolve(); });
+ const flow = document.querySelector('[data-cloud-add="extra-one"]')!;
+ expect(flow.textContent).toContain("One Cloud per account for now");
+ expect(flow.textContent).toContain("You have My Cloud.");
+ expect(cloudAdd.sheet).toHaveBeenCalledWith(true);
+});
+
+it("a circle's letters and words", () => {
+ expect(["Client A", "Acme", " my cloud ", "Ünïcode Øne", "😀 Fun"].map(placeInitials)).toEqual(["CA", "A", "MC", "ÜØ", "😀F"]);
+ expect(placeLabel(place("local", "This computer", { kind: "computer" }))).toBe("This computer");
+ expect(placeLabel(place("x", "Acme", { attention: true }))).toBe("Acme: needs you");
+});
+
+it("a server of the person's own that signed in: a small server mark, the offline look with when it was last seen, and nothing to open when only its own network reaches it", async () => {
+ const now = Date.UTC(2026, 9, 28, 12);
+ const servers = [
+ place("home", "My Cloud", { active: true }),
+ place("vps", "Office", { kind: "server", server: true }),
+ place("signed-in:s-mini", "Mac mini", { kind: "server", opens: false, ownNetwork: true, server: true, offline: true, lastSeenAt: now - 2 * 3_600_000 }),
+ place("signed-in:s-render", "Render VPS", { kind: "server", opens: false, pairs: true, server: true }),
+ ];
+ expect(placeLabel(servers[1]!)).toBe("Office, your own server");
+ expect(placeLabel(servers[2]!, now)).toBe("Mac mini, your own server: offline, last seen 2 hours ago · Only reachable on its own network");
+ expect(placeLabel({ ...servers[2]!, lastSeenAt: undefined, ownNetwork: undefined })).toBe("Mac mini, your own server: offline");
+ expect(placeLabel(servers[3]!)).toBe("Render VPS, your own server: connect it to this app");
+ expect(placeLabel(place("s", "Mac mini", { kind: "server", server: true, update: { version: "0.1.118", latest: "0.1.130" } })))
+ .toBe("Mac mini, your own server · on 0.1.118, 0.1.130 is out");
+ rail = { places: servers, add: { cloud: true, link: true, address: false } };
+ await mount(createElement(PlacesRail));
+ expect(host.querySelector('[data-rail-place="vps"] [data-rail-server]')).toBeTruthy();
+ expect(host.querySelector("[data-rail-update]"), "no reminder without a newer release").toBeNull();
+ expect(host.querySelector('[data-rail-place="home"] [data-rail-server]')).toBeNull();
+ const mini = host.querySelector('[data-rail-place="signed-in:s-mini"]')!;
+ expect(mini.querySelector("[data-rail-offline]")?.className).toContain("grayscale");
+ expect(mini.getAttribute("aria-disabled")).toBe("true");
+ expect(mini.getAttribute("title")).toContain("Only reachable on its own network");
+ await click(mini);
+ expect(document.querySelector("[data-place-add-sheet]")).toBeNull();
+ await click(host.querySelector('[data-rail-place="vps"]'));
+ expect(workspaces.open.mock.calls, "one saved by hand opens as it always did").toEqual([["vps"]]);
+ await click(host.querySelector('[data-rail-place="signed-in:s-render"]'));
+ expect(workspaces.open.mock.calls).toHaveLength(1);
+ const connect = document.querySelector('[data-place-add="connect-server"]')!;
+ expect(connect.textContent).toContain("Connect Render VPS");
+ expect([...connect.querySelectorAll("[data-own-server-command]")].map((code) => code.textContent), "it runs OpenMausBot already: only its pairing link is left").toEqual(['npx openmausbot pair --label "My desktop"']);
+ await click([...connect.querySelectorAll("button")].find((button) => button.textContent === "Paste pairing link"));
+ expect(workspaces.add.mock.calls).toEqual([["link"]]);
+});
+
+it("where no pairing link can be pasted here, a signed-in server not connected yet opens nothing", async () => {
+ rail = { places: [place("home", "My Cloud", { active: true }), place("signed-in:s-render", "Render VPS", { kind: "server", opens: false, pairs: true, server: true })],
+ add: { cloud: true, link: false, address: false } };
+ await mount(createElement(PlacesRail));
+ const render = host.querySelector('[data-rail-place="signed-in:s-render"]')!;
+ expect(render.getAttribute("aria-disabled")).toBe("true");
+ await click(render);
+ expect(document.querySelector("[data-place-add-sheet]")).toBeNull();
+});
+
+it("a server of the person's own on an older release than the newest has a quiet reminder; a payment problem's dot comes first", async () => {
+ rail = { places: [place("home", "My Cloud", { active: true }),
+ place("s-mini", "Mac mini", { kind: "server", server: true, update: { version: "0.1.118", latest: "0.1.130" } }),
+ place("s-old", "Old box", { kind: "server", server: true, attention: true, update: { version: "0.1.100", latest: "0.1.130" } })], add: { cloud: true, link: true, address: false } };
+ await mount(createElement(PlacesRail));
+ expect(host.querySelector('[data-rail-place="s-mini"] [data-rail-update]')).toBeTruthy();
+ expect(host.querySelector('[data-rail-place="s-mini"]')?.getAttribute("title")).toContain("on 0.1.118, 0.1.130 is out");
+ expect(host.querySelector('[data-rail-place="s-old"] [data-rail-update]')).toBeNull();
+ expect(host.querySelector('[data-rail-place="s-old"] [data-rail-dot]')).toBeTruthy();
+});
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
new file mode 100644
index 0000000000..6c57f2d66a
--- /dev/null
+++ b/src/components/PlacesRail.tsx
@@ -0,0 +1,166 @@
+// The rail at the window's left edge once a person has two places or more: one circle 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.
+import { useEffect, useRef, useState, type CSSProperties } from "react";
+import { Laptop, MoreHorizontal, Plus, Search, Server } from "lucide-react";
+import { track } from "@/lib/analytics";
+import { cn } from "@/lib/cn";
+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, railShown, usePlaces, type RailPlace } from "@/lib/places";
+import { useDesktopCapabilities } from "./DesktopCapabilities";
+import { MENU_ROW, MENU_SHEET } from "./menu-recipe";
+import { PlaceAddSheet } from "./PlaceAddSheet";
+
+/** Circles before ⋯ opens the searchable list of every place. */
+export const RAIL_SHOWN = 8;
+const CIRCLE = 38;
+
+/** A circle's words for its tooltip and a screen reader: the place, and what it is doing now. A server of the person's
+ * own that signed in with their account says so, whether it is online, and why there is nothing to open when it is only
+ * reachable on its own network. */
+export function placeLabel(place: RailPlace, now = Date.now()): string {
+ const name = place.kind === "computer" ? t("rail.thisComputer") : place.server ? t("rail.ownServer", { name: place.name }) : place.name;
+ if (place.waiting) return t("rail.waiting", { name });
+ if (place.progress !== undefined) return t("rail.settingUp", { name });
+ if (place.attention) return t("rail.attention", { name });
+ const status = place.offline
+ ? place.lastSeenAt ? t("rail.lastSeen", { name, when: localizedRelativeTime(place.lastSeenAt, activeLocale(), now) }) : t("rail.offline", { name })
+ : place.pairs ? t("rail.notConnected", { name }) : name;
+ return [status, place.update && t("rail.update", place.update), place.ownNetwork && t("rail.ownNetwork")].filter(Boolean).join(" · ");
+}
+
+/** Whether a circle does anything: opens its place, or, for a server of the person's own not connected yet, shows how
+ * to connect it (only where a pairing link can be pasted). */
+export const placeActs = (place: RailPlace, canPair: boolean): boolean => place.opens || (place.pairs === true && canPair);
+
+/** The circles before ⋯: every place up to RAIL_SHOWN; past that the first ones, with the place on screen always among them. */
+export function shownPlaces(places: RailPlace[], limit = RAIL_SHOWN): RailPlace[] {
+ if (places.length <= limit) return places;
+ const first = places.slice(0, limit - 1), active = places.find((place) => place.active);
+ return [...first, active && !first.includes(active) ? active : places[limit - 1]!];
+}
+
+/** Places whose name has every word typed, in the rail's order. */
+export function matchingPlaces(places: RailPlace[], query: string): RailPlace[] {
+ const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
+ return places.filter((place) => {
+ const name = (place.kind === "computer" ? t("rail.thisComputer") : place.name).toLocaleLowerCase();
+ return words.every((word) => name.includes(word));
+ });
+}
+
+function ProgressRing({ value = 0, waiting = false }: { value?: number; waiting?: boolean }) {
+ const box = CIRCLE + 8, radius = box / 2 - 1.5, around = 2 * Math.PI * radius;
+ const shown = waiting ? 0.28 : Math.max(0.06, Math.min(1, value));
+ return <svg aria-hidden="true" data-rail-ring={waiting ? "waiting" : Math.round(value * 100)} width={box} height={box} viewBox={`0 0 ${box} ${box}`}
+ className={cn("pointer-events-none absolute -left-1 -top-1 -rotate-90", waiting && "animate-spin [animation-duration:2.4s] motion-reduce:animate-none")}>
+ <circle cx={box / 2} cy={box / 2} r={radius} fill="none" stroke="var(--color-hairline)" strokeWidth={2} />
+ <circle cx={box / 2} cy={box / 2} r={radius} fill="none" stroke="var(--color-accent)" strokeWidth={2} strokeLinecap="round" strokeDasharray={`${shown * around} ${around}`}
+ className="transition-[stroke-dasharray] duration-500 motion-reduce:transition-none" />
+ </svg>;
+}
+
+export function PlaceMark({ place, size = CIRCLE }: { place: RailPlace; size?: number }) {
+ const color = cloudColor(place.color);
+ return <span aria-hidden="true" data-rail-offline={place.offline ? "" : undefined}
+ className={cn("grid shrink-0 place-items-center rounded-full font-semibold leading-none", color ? "text-white" : "bg-raised text-ink", place.offline && "opacity-55 grayscale")}
+ style={{ width: size, height: size, fontSize: Math.round(size * 0.36), ...(color ? { background: cloudColorFill(color) } : {}) }}>
+ {place.kind === "computer" ? <Laptop size={Math.round(size * 0.46)} strokeWidth={1.75} /> : placeInitials(place.name)}
+ </span>;
+}
+
+function PlaceCircle({ place, calm, canPair, onOpen }: { place: RailPlace; calm: boolean; canPair: boolean; onOpen: (place: RailPlace) => void }) {
+ const label = placeLabel(place), acts = placeActs(place, canPair);
+ return <button type="button" aria-label={label} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true}
+ data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts && !place.active) onOpen(place); }}
+ className={cn("relative shrink-0 rounded-full transition-[box-shadow,opacity] duration-150 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-focus",
+ place.active ? cn("ring-2 ring-offset-2 ring-offset-panel", calm ? "ring-ink/45" : "ring-ink/75")
+ : acts ? "hover:ring-2 hover:ring-ink/15 hover:ring-offset-2 hover:ring-offset-panel" : cn("cursor-default", !place.offline && "opacity-75"))}>
+ <PlaceMark place={place} />
+ {place.progress !== undefined && <ProgressRing value={place.progress} waiting={place.waiting === true} />}
+ {place.attention && <span aria-hidden="true" data-rail-dot className="absolute -right-0.5 -top-0.5 size-3 rounded-full border-2 border-panel bg-danger" />}
+ {place.update && !place.attention && <span aria-hidden="true" data-rail-update className="absolute -right-0.5 -top-0.5 size-3 rounded-full border-2 border-panel bg-accent" />}
+ {place.server && <span aria-hidden="true" data-rail-server className="absolute -bottom-0.5 -right-0.5 grid size-4 place-items-center rounded-full border border-hairline bg-panel text-ink-secondary">
+ <Server size={9} strokeWidth={2.25} />
+ </span>}
+ </button>;
+}
+
+/** Every place, searchable: ⋯ once there are more than RAIL_SHOWN. */
+function MorePlaces({ places, canPair, onOpen, onClose }: { places: RailPlace[]; canPair: boolean; onOpen: (place: RailPlace) => void; onClose: () => void }) {
+ const [query, setQuery] = useState("");
+ const found = matchingPlaces(places, query);
+ return <div role="dialog" aria-label={t("rail.search")} data-rail-more className={cn("absolute bottom-0 left-full z-50 ml-2 w-64", MENU_SHEET)}
+ onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }}>
+ <label className="flex h-8 items-center gap-2 rounded-md bg-ink/[0.05] px-2">
+ <Search size={14} aria-hidden="true" className="shrink-0 text-ink-secondary" />
+ <input autoFocus value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("rail.search")} aria-label={t("rail.search")}
+ onKeyDown={(event) => { if (event.key === "Enter" && found[0] && placeActs(found[0], canPair)) { onOpen(found[0]); onClose(); } }}
+ className="w-full bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-tertiary" />
+ </label>
+ <ul className="max-h-72 overflow-y-auto">
+ {found.map((place) => <li key={place.id}>
+ <button type="button" disabled={!placeActs(place, canPair)} aria-current={place.active ? "page" : undefined} onClick={() => { onOpen(place); onClose(); }} className={cn(MENU_ROW, "h-9")}>
+ <PlaceMark place={place} size={22} />
+ <span className="min-w-0 flex-1 truncate">{placeLabel(place)}</span>
+ </button>
+ </li>)}
+ </ul>
+ {found.length === 0 && <p className="px-2 py-1.5 text-[12px] text-ink-tertiary">{t("rail.noMatch")}</p>}
+ </div>;
+}
+
+export function PlacesRail() {
+ const state = usePlaces();
+ const calm = !useAdvancedMode();
+ const { capabilities } = useDesktopCapabilities();
+ const [more, setMore] = useState(false);
+ const [adding, setAdding] = useState(false);
+ const [connecting, setConnecting] = useState<string | null>(null);
+ const moreRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!more) return;
+ const away = (event: MouseEvent) => { if (!moreRef.current?.contains(event.target as Node)) setMore(false); };
+ window.addEventListener("mousedown", away);
+ return () => window.removeEventListener("mousedown", away);
+ }, [more]);
+ if (!railShown(state)) return null;
+ const bridge = window.ogb?.workspaces;
+ const open = (place: RailPlace) => {
+ if (!place.opens) { if (place.pairs) setConnecting(place.name); return; }
+ track("rail_place_opened", { kind: place.kind });
+ void bridge?.open?.(place.id).catch(() => {});
+ };
+ const macInset = capabilities.windowChrome === "mac-inset";
+ const draggable = macInset || capabilities.windowChrome === "win-caption";
+ // SAFETY: Electron's -webkit-app-region is not in React's CSSProperties type; the renderer accepts it as an inline style.
+ const drag = draggable ? ({ WebkitAppRegion: "drag" } as CSSProperties) : undefined;
+ const noDrag = draggable ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;
+ const shown = shownPlaces(state.places);
+ const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair;
+ return <nav aria-label={t("rail.label")} data-places-rail style={drag}
+ className={cn("relative hidden w-16 shrink-0 flex-col items-center bg-panel md:flex", calm ? "border-r border-ink/[0.04]" : "border-r border-hairline/50")}>
+ {/* The macOS traffic lights sit over the rail's top; nothing here takes a click before they end. */}
+ <div aria-hidden="true" className={macInset ? "h-[52px] shrink-0" : "h-3 shrink-0"} />
+ <ul className="flex min-h-0 flex-col items-center gap-2.5 overflow-y-auto px-1 py-1" style={noDrag}>
+ {shown.map((place) => <li key={place.id} className="flex"><PlaceCircle place={place} calm={calm} canPair={canPair} onOpen={open} /></li>)}
+ </ul>
+ <div className="relative mt-2.5 flex flex-col items-center gap-2.5 pb-3" style={noDrag} ref={moreRef}>
+ {state.places.length > RAIL_SHOWN && <button type="button" aria-label={t("rail.more", { count: state.places.length })} title={t("rail.more", { count: state.places.length })}
+ aria-haspopup="dialog" aria-expanded={more} data-rail-more-button onClick={() => setMore(!more)}
+ className="grid size-[38px] place-items-center rounded-full text-ink-secondary hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus aria-expanded:bg-ink/[0.06]">
+ <MoreHorizontal size={18} aria-hidden="true" />
+ </button>}
+ {more && <MorePlaces places={state.places} canPair={canPair} onOpen={open} onClose={() => setMore(false)} />}
+ {canAdd && <button type="button" aria-label={t("rail.add")} title={t("rail.add")} aria-haspopup="dialog" data-rail-add onClick={() => { track("rail_add", { step: "opened" }); setAdding(true); }}
+ className="grid size-[38px] place-items-center rounded-full border border-dashed border-ink/25 text-ink-secondary hover:border-ink/40 hover:bg-ink/[0.04] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
+ <Plus size={18} aria-hidden="true" />
+ </button>}
+ </div>
+ {adding && <PlaceAddSheet choices={state.add} onClose={() => setAdding(false)} />}
+ {connecting !== null && <PlaceAddSheet choices={state.add} connect={{ name: connecting }} onClose={() => setConnecting(null)} />}
+ </nav>;
+}
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 04492d617a..c894a3cfad 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -26,6 +26,7 @@ import { BuiltInBrowserRow } from "./BrowserSettingsRows";
import { LoginsSettings } from "./LoginsSettings";
import { RemoteComputerSection } from "./RemoteComputerSection";
import { ConnectedWorkspacesSettings } from "./ConnectedWorkspacesSettings";
+import { PlaceLookCard } from "./PlaceLookCard";
import { OrganizationSettings } from "./OrganizationSettings";
import { CloudAccountSettings } from "./CloudAccountSettings";
import { ProSettingsCard } from "./ProIntroduction";
@@ -78,7 +79,7 @@ export const SECTIONS: Array<{
keywords: string[];
}> = [
{ id: "general", group: "you", labelKey: "settings.section.general", icon: User, keywords: ["profile", "name", "email", "about me", "about", "suggestions", "suggested", "memory", "analytics", "updates", "product updates", "newsletter", "email updates", "effort", "new bots", "reasoning", "threads", "parallel", "concurrency", "cleanup", "retention", "event log", "event-log", "log size", "automatic recovery", "backup model", "fallback", "routines", "conversation", "schedule", "usage", "limit", "plan", "upgrade", "cloud desktop hours", "storage"] },
- { id: "appearance", group: "you", labelKey: "settings.section.appearance", icon: Palette, keywords: ["skin", "theme", "appearance", "chat width", "width", "wide", "full width", "bubble", "bubbles", "tools", "tool calls", "threads", "show threads", "hide threads", "sidebar", "density", "compact", "comfortable", "avatars", "display", "run", "this run", "run card", "commands", "notifications", "sound", "sounds", "mute", "silent", "chime", "pinned", "circles", "universal", "groups", "top", "send", "enter", "return", "shift+enter", "ctrl+enter", "cmd+enter", "⌘+enter", "new line", "keyboard", "ime", "japanese", "message color", "my messages", "toolbar", "tools layout", "footer", "routines", "triggers", "team map"] },
+ { id: "appearance", group: "you", labelKey: "settings.section.appearance", icon: Palette, keywords: ["skin", "theme", "appearance", "chat width", "width", "wide", "full width", "bubble", "bubbles", "tools", "tool calls", "threads", "show threads", "hide threads", "sidebar", "density", "compact", "comfortable", "avatars", "display", "run", "this run", "run card", "commands", "notifications", "sound", "sounds", "mute", "silent", "chime", "pinned", "circles", "universal", "groups", "top", "send", "enter", "return", "shift+enter", "ctrl+enter", "cmd+enter", "⌘+enter", "new line", "keyboard", "ime", "japanese", "message color", "my messages", "toolbar", "tools layout", "footer", "routines", "triggers", "team map", "color", "cloud color", "server color", "tint"] },
{ id: "companion", group: "you", labelKey: "settings.section.companion", icon: TabletSmartphone, keywords: ["companion", "device", "phone", "desktop", "client", "host", "pair", "pairing", "mobile", "https", "secure", "tailscale", "wifi", "remote", "advanced", "domain", "dns", "self-hosted", "server", "caddy"] },
{ id: "engines", group: "ai", labelKey: "settings.section.engines", icon: Terminal, keywords: ["models", "model providers", "engines", "claude", "codex", "grok", "providers", "cli", "sign in", "subscription"] },
{ id: "connections", group: "ai", labelKey: "settings.section.connections", icon: KeyRound, keywords: ["keys", "api", "api key", "api keys", "connections", "composio", "box", "xai", "mistral", "cerebras", "meta", "muse", "vps", "router", "openrouter", "base url", "openai", "anthropic", "groq", "opencode", "deepseek", "provider", "lm studio", "lmstudio", "llm studio", "llmstudio", "bionic"] },
@@ -362,6 +363,7 @@ export function SettingsModal() {
<Card title={t("settings.skin.title")} subtitle={t("settings.skin.subtitle")}>
<SkinPicker />
</Card>
+ <PlaceLookCard />
{remoteActive && <AdvancedModeRow />}
{remoteActive && <LanguageRow />}
<FontRow />
diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsx
index ee65bc7f5e..bc8cb41418 100644
--- a/src/components/SettingsSimplePages.tsx
+++ b/src/components/SettingsSimplePages.tsx
@@ -22,6 +22,7 @@ import { SettingRow, SettingsDisclosureRow, SettingsGroup, SettingsRows } from "
import { UsageSection } from "./UsageSection";
import { PlanUsageSummary } from "./PlanUsage";
import { SkinPicker } from "./SkinPicker";
+import { PlaceLookCard } from "./PlaceLookCard";
import { ProfileSummaryRow } from "./ProfileSettings";
import { ImportSettings } from "./ImportSettings";
import { NotificationRows } from "./NotificationSettingsRows";
@@ -95,6 +96,7 @@ export function SimpleLooksPage({ onBack }: { onBack: () => void }) {
<>
<div><button type="button" className="ui-button" onClick={onBack}>{t("settings.simple.looks.back")}</button></div>
<div data-settings-block="looks"><SkinPicker /></div>
+ <PlaceLookCard />
</>
);
}
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index f54f192da2..a257eab960 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -90,7 +90,7 @@ import { PhoneHero } from "./SidebarPhoneHero";
import { SidebarProfileMenu } from "./SidebarProfileMenu";
import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
import { GlassBar, GlassScrollFrame, GlassScroller } from "./GlassScrollFrame";
-import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher";
+import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher"; import { railShown, usePlaces } from "@/lib/places"; import { PlaceTint } from "./PlaceTint";
import { useCloudOwner } from "./CloudOwner";
import { SidebarSectionHeader } from "./SidebarSectionHeader";
import { NeedsYouButton, OwnerFace, OwnerPickerHost, pickOwnerOf } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople";
@@ -1138,7 +1138,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
}
};
- const macInset = capabilities.windowChrome === "mac-inset";
+ const macInset = capabilities.windowChrome === "mac-inset", railBeside = railShown(usePlaces());
const browser = capabilities.host.label === "Browser";
const draggableChrome = macInset || capabilities.windowChrome === "win-caption";
// SAFETY: Electron's -webkit-app-region is not in React's CSSProperties type; the renderer accepts it as an inline
@@ -1393,7 +1393,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
open ? "max-md:translate-x-0" : "max-md:-translate-x-full",
)}
>
- <GlassScrollFrame className="flex-1" fade>
+ <GlassScrollFrame className="flex-1" fade><PlaceTint />
<GlassBar edge="top">
<div
data-sidebar-top-row
@@ -1408,7 +1408,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
<div className="shrink-0" style={windowNoDragStyle}><SidebarProfileMenu iconOnly circle /></div>
) : macInset ? (
// The macOS 26 traffic lights span 16-76px; nothing clickable starts before 88px.
- <div aria-hidden="true" data-traffic-light-space className={density === "icons" ? "h-5 w-full" : "w-[72px] shrink-0"} />
+ <div aria-hidden="true" data-traffic-light-space className={density === "icons" ? "h-5 w-full" : railBeside ? "w-[72px] shrink-0 md:w-3" : "w-[72px] shrink-0"} />
) : browser ? (
<div className={cn("flex shrink-0 items-center gap-2", density !== "icons" && "mr-3", simpleDesk && "mt-1")}>
<span className="size-3 rounded-full bg-[#ff5f57]" />
diff --git a/src/components/SwatchRadios.tsx b/src/components/SwatchRadios.tsx
new file mode 100644
index 0000000000..470c4ac700
--- /dev/null
+++ b/src/components/SwatchRadios.tsx
@@ -0,0 +1,28 @@
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import { cn } from "@/lib/cn";
+import { CLOUD_SWATCH_LABEL, CLOUD_SWATCH_ORDER, swatchFill } from "@/lib/cloud-extra";
+import { t } from "@/lib/i18n";
+
+/** The six swatches a Cloud's colour is chosen from, as one radio group: arrow keys move the choice, Tab leaves it.
+ * `value` null: none of them yet (the first one takes the focus). `offset`: the surface the ring sits on. */
+export function SwatchRadios({ value, onChange, label, disabled = false, offset = "panel" }: {
+ value: CloudSwatch | null; onChange: (swatch: CloudSwatch) => void; label: string; disabled?: boolean; offset?: "panel" | "card";
+}) {
+ const focusable = value ?? CLOUD_SWATCH_ORDER[0];
+ return <div role="radiogroup" aria-label={label} aria-disabled={disabled || undefined} className="flex flex-wrap gap-2.5">
+ {CLOUD_SWATCH_ORDER.map((option) => <button key={option} type="button" role="radio" aria-checked={option === value} aria-label={t(CLOUD_SWATCH_LABEL[option])}
+ title={t(CLOUD_SWATCH_LABEL[option])} data-swatch={option} disabled={disabled} onClick={() => onChange(option)}
+ onKeyDown={(event) => {
+ const delta = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
+ if (!delta) return;
+ event.preventDefault();
+ const next = CLOUD_SWATCH_ORDER[(CLOUD_SWATCH_ORDER.indexOf(option) + delta + CLOUD_SWATCH_ORDER.length) % CLOUD_SWATCH_ORDER.length]!;
+ onChange(next);
+ (event.currentTarget.parentElement?.querySelector(`[data-swatch="${next}"]`) as HTMLElement | null)?.focus();
+ }}
+ tabIndex={option === focusable ? 0 : -1}
+ className={cn("size-8 rounded-full border border-ink/10 transition-[box-shadow] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus disabled:cursor-default",
+ option === value && cn("ring-2 ring-ink/70 ring-offset-2", offset === "card" ? "ring-offset-card" : "ring-offset-panel"), disabled && option !== value && "opacity-50")}
+ style={{ background: swatchFill(option) }} />)}
+ </div>;
+}
diff --git a/src/components/cloud-buy/AddCloudFlow.test.ts b/src/components/cloud-buy/AddCloudFlow.test.ts
new file mode 100644
index 0000000000..0c59a6a416
--- /dev/null
+++ b/src/components/cloud-buy/AddCloudFlow.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { CLOUD_SWATCH_COLORS } from "../../../electron/cloud-list.mjs";
+import type { AddCloudView } from "../../../electron/cloud-rail.mjs";
+import { addCloudScreen, addCloudStop, SWATCH_COLOR, swatchFill } from "@/lib/cloud-extra";
+import { setLocale } from "@/lib/i18n";
+
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("./CloudMascotScene", () => ({ CloudMascotScene: () => null }));
+const { AddCloudFlow } = await import("./AddCloudFlow");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const NOW = 1_800_000_000_000;
+const OFFER = { recommended: "pro", plans: [{ tier: "starter", label: "Starter", amount: 1500 }, { tier: "pro", label: "Pro", amount: 4900 }] };
+const base = (extra: Partial<Extract<AddCloudView, { signedIn: true }>> = {}): AddCloudView =>
+ ({ signedIn: true, hasCloud: true, supported: true, canAdd: true, offer: OFFER, count: 1, home: { name: "My Cloud", color: null }, ...extra });
+const adding = (status: "checkout" | "setting_up" | "ready" | "problem", extra = {}) => ({ name: "Client B", color: "rose" as const, tier: "pro", startedAt: NOW, status, link: true as const, ...extra });
+
+it("each screen follows the Admin's word first: a Cloud being bought shows how it is going, until it was opened", () => {
+ const at = (view: AddCloudView | null | undefined, ui = {}) => addCloudScreen(view, { now: NOW, ...ui }).kind;
+ expect([at(undefined), at(null), at({ signedIn: false }), at(base({ hasCloud: false }))]).toEqual(["checking", "unreachable", "first", "first"]);
+ expect(at(base({ supported: false, canAdd: false }))).toBe("stop");
+ expect(addCloudScreen(base({ supported: false, canAdd: false }), { now: NOW })).toEqual({ kind: "stop", reason: "one", home: "My Cloud" });
+ expect(addCloudScreen(base({ canAdd: false, blocked: "cap" }), { now: NOW })).toMatchObject({ reason: "one" });
+ expect(addCloudScreen(base({ canAdd: false, blocked: "signups_closed" }), { now: NOW })).toMatchObject({ reason: "signups_closed" });
+ expect(at(base())).toBe("choose");
+ expect(addCloudScreen(base(), { now: NOW, tier: "pro" })).toMatchObject({ kind: "name", plan: { tier: "pro" } });
+ expect(at(base(), { tier: "enterprise" })).toBe("choose");
+ expect(at(base(), { failed: true })).toBe("error");
+ expect(at(base({ offer: null }))).toBe("unreachable");
+ expect(addCloudScreen(base({ adding: adding("checkout") }), { now: NOW + 31 * 60_000 })).toMatchObject({ kind: "waiting", late: true });
+ expect([at(base({ adding: adding("checkout") })), at(base({ adding: adding("setting_up") })), at(base({ adding: adding("ready") })), at(base({ adding: adding("problem") }))])
+ .toEqual(["waiting", "starting", "ready", "problem"]);
+ expect(at(base({ adding: adding("ready", { done: true }) })), "opened: the purchase is over").toBe("choose");
+ expect(["cap", "mystery", "rate", "checkout_open"].map(addCloudStop)).toEqual(["one", "one", "rate", "checkout_open"]);
+});
+
+it("every Admin swatch is drawn in the colour main saves for it", () => {
+ expect(SWATCH_COLOR).toEqual(CLOUD_SWATCH_COLORS);
+ expect(swatchFill("green")).toBe("var(--identity-teal)");
+ expect(swatchFill("slate")).toBe("var(--color-raised)");
+});
+
+let host: HTMLDivElement, root: Root | null = null;
+let view: AddCloudView;
+const bridge = { state: vi.fn(async () => view), start: vi.fn(async () => ({ outcome: "opened" as const })), reopen: vi.fn(async () => true), copyLink: vi.fn(async () => true),
+ open: vi.fn(async () => {}), interest: vi.fn(async () => {}), sheet: vi.fn(async () => {}) };
+const flush = () => act(async () => { await Promise.resolve(); await Promise.resolve(); });
+const click = async (element: Element | null | undefined) => { expect(element).toBeTruthy(); await act(async () => { (element as HTMLElement).click(); }); await flush(); };
+const buttonNamed = (name: string) => [...host.querySelectorAll("button")].find((button) => button.textContent?.trim().startsWith(name));
+beforeEach(() => {
+ setLocale("en");
+ vi.clearAllMocks();
+ view = base();
+ Object.assign(window, { ogb: { cloudAdd: bridge, workspaces: { onChanged: () => () => {} } } });
+ host = document.createElement("div"); document.body.append(host);
+});
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });
+async function mount(props: Partial<Parameters<typeof AddCloudFlow>[0]> = {}) {
+ const done = { closed: 0, first: 0 };
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement(AddCloudFlow, { onClose: () => { done.closed++; }, onFirstCloud: () => { done.first++; }, now: () => NOW, ...props })); });
+ await flush();
+ return done;
+}
+
+it("a plan, then its name and colour, then the Admin's checkout; the sheet then follows the payment, the setup and the ready Cloud", async () => {
+ await mount();
+ expect(host.querySelector("[data-cloud-add='offer']")).toBeTruthy();
+ expect(host.textContent, "another Cloud has no free trial").not.toContain("Free for");
+ await click(host.querySelector("[data-plan-buy='pro']"));
+ expect(host.querySelector("[data-cloud-add='extra-name']")?.textContent).toContain("Name your new Cloud");
+ expect((host.querySelector("input") as HTMLInputElement).placeholder).toBe("Cloud 2");
+ await click(host.querySelector("[data-swatch='violet']"));
+ expect(host.querySelector("[data-swatch='violet']")?.getAttribute("aria-checked")).toBe("true");
+ bridge.start.mockImplementationOnce(async () => { view = base({ adding: adding("checkout") }); return { outcome: "opened" as const }; });
+ await click(buttonNamed("Continue to checkout"));
+ await flush();
+ expect(bridge.start.mock.calls).toEqual([["pro", "Cloud 2", "violet"]]);
+ expect(host.querySelector("[data-cloud-add='extra-waiting']")?.textContent).toContain("Waiting for your payment");
+ await click(buttonNamed("Reopen checkout"));
+ expect(bridge.reopen).toHaveBeenCalledTimes(1);
+ view = base({ adding: adding("ready") });
+ await click(buttonNamed("Copy link"));
+ expect(bridge.copyLink).toHaveBeenCalledTimes(1);
+});
+
+it("another Cloud's checkout still open: the sheet follows that one, with its page to reopen, and sign-ups closed is said calmly", async () => {
+ await mount();
+ await click(host.querySelector("[data-plan-buy='pro']"));
+ bridge.start.mockImplementationOnce(async () => { view = base({ adding: adding("checkout", { name: "Client B" }) }); return { outcome: "blocked", blocked: "checkout_open" } as never; });
+ await click(buttonNamed("Continue to checkout"));
+ await flush();
+ expect(host.querySelector("[data-cloud-add='extra-waiting']")?.textContent).toContain("Waiting for your payment");
+ await click(buttonNamed("Reopen checkout"));
+ expect(bridge.reopen).toHaveBeenCalledTimes(1);
+ await act(async () => root?.unmount()); root = null;
+ view = base();
+ bridge.start.mockResolvedValueOnce({ outcome: "blocked", blocked: "signups_closed" } as never);
+ await mount();
+ await click(host.querySelector("[data-plan-buy='pro']"));
+ await click(buttonNamed("Continue to checkout"));
+ expect(host.querySelector("[data-cloud-add='extra-signups_closed']")?.textContent).toContain("New Clouds can't be bought right now.");
+});
+
+it("the Cloud bought is ready: Open opens it and closes the sheet", async () => {
+ view = base({ adding: adding("ready") });
+ const done = await mount();
+ expect(host.querySelector("[data-cloud-add='extra-ready']")?.textContent).toContain("Client B is ready");
+ await click(buttonNamed("Open Client B"));
+ expect(bridge.open).toHaveBeenCalledTimes(1);
+ expect(done.closed).toBe(1);
+});
+
+it("the Admin refusing to add (its cap) is the calm one-Cloud word; no Cloud of their own yet is this computer's own sheet", async () => {
+ bridge.start.mockResolvedValueOnce({ outcome: "blocked", blocked: "cap" } as never);
+ await mount();
+ await click(host.querySelector("[data-plan-buy='starter']"));
+ await click(buttonNamed("Continue to checkout"));
+ expect(host.querySelector("[data-cloud-add='extra-one']")?.textContent).toContain("One Cloud per account for now");
+ await click(buttonNamed("Email me when I can add another"));
+ expect(bridge.interest).toHaveBeenCalledTimes(1);
+ expect(host.textContent).toContain("We'll email you");
+ await act(async () => root?.unmount()); root = null;
+ view = base({ hasCloud: false });
+ const done = await mount();
+ expect(done.first).toBe(1);
+});
diff --git a/src/components/cloud-buy/AddCloudFlow.tsx b/src/components/cloud-buy/AddCloudFlow.tsx
new file mode 100644
index 0000000000..a5cb663ccf
--- /dev/null
+++ b/src/components/cloud-buy/AddCloudFlow.tsx
@@ -0,0 +1,188 @@
+// Buying another Cloud, for someone who has one: a plan, then its name and colour, then the Admin's checkout in the
+// browser; the sheet follows the payment and the setup by itself and opens the new Cloud. Without an Admin that sells more
+// than one Cloud per account it says so calmly. Main keeps the checkout page and the account; the page sees only this.
+import { useEffect, useRef, useState } from "react";
+import { Copy, ExternalLink, Loader2 } from "lucide-react";
+import type { CloudOfferPlan } from "../../../electron/cloud-home.mjs";
+import type { CloudSwatch } from "../../../electron/cloud-list.mjs";
+import type { AddCloudView } from "../../../electron/cloud-rail.mjs";
+import { track } from "@/lib/analytics";
+import { cn } from "@/lib/cn";
+import { addCloudScreen, addCloudStop, CLOUD_LIST_NAME_LIMIT, DEFAULT_SWATCH, swatchFill, type AddCloudScreen, type AddCloudStop } from "@/lib/cloud-extra";
+import { offerPlanLabel, usd } from "@/lib/cloud-plan";
+import { t } from "@/lib/i18n";
+import { placeInitials } from "@/lib/places";
+import { SwatchRadios } from "../SwatchRadios";
+import { ChooseScreen } from "./ChooseScreen";
+import { BackLink, Checklist, FIELD, Heading, PRIMARY_WIDE, ProgressBar } from "./parts";
+
+const POLL_MS = 3_000;
+const STOP_LINE: Record<Exclude<AddCloudStop, "one">, Parameters<typeof t>[0]> = {
+ signups_closed: "cloudBuy.extra.signupsClosed", checkout_open: "cloudBuy.extra.checkoutOpen", rate: "cloudAdd.rateLimited",
+};
+
+function NameScreen({ plan, name, color, busy, suggested, onName, onColor, onBack, onContinue }: {
+ plan: CloudOfferPlan; name: string; color: CloudSwatch; busy: boolean; suggested: string;
+ onName: (value: string) => void; onColor: (value: CloudSwatch) => void; onBack: () => void; onContinue: () => void;
+}) {
+ const shown = name.trim().replace(/\s+/g, " ") || suggested;
+ return <form data-cloud-add="extra-name" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7" onSubmit={(event) => { event.preventDefault(); onContinue(); }}>
+ <div><BackLink label={t("cloudBuy.back")} onClick={onBack} /></div>
+ <Heading title={t("cloudBuy.extra.nameTitle")} sub={t("cloudBuy.extra.nameSub")} />
+ <label className="flex flex-col gap-1.5 text-[13px] font-medium text-ink">{t("cloudBuy.setup.name")}
+ <input data-autofocus value={name} maxLength={CLOUD_LIST_NAME_LIMIT} placeholder={suggested} disabled={busy} onChange={(event) => onName(event.target.value)} className={FIELD} />
+ </label>
+ <div className="flex flex-col gap-1.5">
+ <span aria-hidden="true" className="text-[13px] font-medium text-ink">{t("cloudBuy.setup.color")}</span>
+ <SwatchRadios value={color} onChange={onColor} label={t("cloudBuy.setup.color")} disabled={busy} />
+ </div>
+ <div className="flex items-center gap-3 rounded-xl border border-hairline/70 bg-card/70 px-4 py-3">
+ <span aria-hidden="true" className={cn("grid size-10 shrink-0 place-items-center rounded-full text-[14px] font-semibold", color === "slate" ? "bg-raised text-ink" : "text-white")}
+ style={color === "slate" ? undefined : { background: swatchFill(color) }}>{placeInitials(shown)}</span>
+ <span className="min-w-0">
+ <span className="block truncate text-[14px] font-semibold text-ink">{shown}</span>
+ <span className="block text-[13px] text-ink-secondary">{t("cloudBuy.pay.planPaid", { plan: offerPlanLabel(plan), price: usd(plan.amount / 100) })}</span>
+ </span>
+ </div>
+ <p className="text-[13px] leading-relaxed text-ink-secondary">{t("cloudBuy.card.paid", { price: usd(plan.amount / 100) })}</p>
+ <button type="submit" className={PRIMARY_WIDE} disabled={busy}>
+ {busy && <Loader2 size={15} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}{t("cloudBuy.extra.continue")}
+ </button>
+ </form>;
+}
+
+function Stop({ reason, home, busy, interest, onInterest, onClose }: {
+ reason: AddCloudStop; home: string | null; busy: boolean; interest: "sent" | "failed" | null; onInterest: () => void; onClose: () => void;
+}) {
+ return <div data-cloud-add={`extra-${reason}`} className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ {reason === "one"
+ ? <Heading title={t("cloudBuy.one.title")} sub={t("cloudBuy.one.sub", { name: home ?? t("cloudSetup.myCloud") })} />
+ : <><Heading title={t("cloudAdd.title")} /><p role="status" className="text-[14px] leading-relaxed text-ink">{t(STOP_LINE[reason])}</p></>}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ {reason === "one" && interest !== "sent" && <button type="button" className="ui-button" disabled={busy} onClick={onInterest}>{t("cloudBuy.one.email")}</button>}
+ <button type="button" data-autofocus className="ui-button ui-button-primary" onClick={onClose}>{t("cloudAdd.close")}</button>
+ </div>
+ <div aria-live="polite" className="text-[13px] empty:-mt-4">
+ {interest === "sent" && <p className="text-ink-secondary">{t("cloudBuy.one.thanks")}</p>}
+ {interest === "failed" && <p role="alert" className="text-danger">{t("cloudBuy.one.failed")}</p>}
+ </div>
+ </div>;
+}
+
+/** `onFirstCloud`: there is no Cloud of the person's own yet, so this computer's own sheet buys the first (with its sign-in
+ * and trial). `onWide`: the plan cards want the wide sheet. `onBack`: back to +'s two choices. */
+export function AddCloudFlow({ onClose, onFirstCloud, onWide = () => {}, onBack = null, now = Date.now }: {
+ onClose: () => void; onFirstCloud: () => void; onWide?: (wide: boolean) => void; onBack?: (() => void) | null; now?: () => number;
+}) {
+ const bridge = window.ogb?.cloudAdd;
+ const [view, setView] = useState<AddCloudView | null | undefined>(undefined);
+ const [tier, setTier] = useState<string | null>(null);
+ const [name, setName] = useState("");
+ const [color, setColor] = useState<CloudSwatch>(DEFAULT_SWATCH);
+ const [busy, setBusy] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [stop, setStop] = useState<AddCloudStop | null>(null);
+ const [note, setNote] = useState<"copied" | "pay-failed" | "open-failed" | null>(null);
+ const [interest, setInterest] = useState<"sent" | "failed" | null>(null);
+ const root = useRef<HTMLDivElement>(null);
+ const read = () => bridge?.state().then(setView, () => setView(null)) ?? Promise.resolve(setView(null));
+ useEffect(() => {
+ void read();
+ const off = window.ogb?.workspaces?.onChanged?.(() => void read());
+ void bridge?.sheet(true).catch(() => {});
+ return () => { off?.(); void bridge?.sheet(false).catch(() => {}); };
+ }, []);
+ const screen: AddCloudScreen = addCloudScreen(view, { now: now(), tier, failed, stop });
+ const following = screen.kind === "waiting" || screen.kind === "starting";
+ useEffect(() => {
+ if (!following) return;
+ const timer = setInterval(() => void read(), POLL_MS);
+ return () => clearInterval(timer);
+ }, [following]);
+ useEffect(() => { onWide(screen.kind === "choose"); }, [screen.kind]);
+ useEffect(() => {
+ if (screen.kind === "first") onFirstCloud();
+ if (screen.kind === "ready") track("cloud_add_another", { step: "ready" });
+ }, [screen.kind]);
+ useEffect(() => {
+ if (root.current?.contains(document.activeElement)) return;
+ (root.current?.querySelector<HTMLElement>("[data-autofocus]") ?? root.current?.querySelector<HTMLElement>("#cloud-add-title"))?.focus();
+ }, [screen.kind]);
+ const count = view && view.signedIn ? view.count : 1;
+ const suggested = t("cloudBuy.extra.defaultName", { number: count + 1 });
+ const act = (step: () => Promise<unknown>, fail: () => void) => {
+ if (busy) return;
+ setBusy(true); setNote(null);
+ void step().catch(fail).finally(() => setBusy(false));
+ };
+ const start = () => act(async () => {
+ if (screen.kind !== "name" || !bridge) return;
+ const result = await bridge.start(screen.plan.tier, name.trim().replace(/\s+/g, " ") || suggested, color);
+ if (result.outcome === "opened") { track("cloud_add_another", { step: "checkout_opened", plan: screen.plan.tier }); setTier(null); await read(); return; }
+ // Another Cloud's checkout still open: main keeps its page, and the sheet follows that one (Reopen, Copy link).
+ if (result.outcome === "blocked") { setStop(addCloudStop(result.blocked)); if (result.blocked === "checkout_open") await read(); }
+ else if (result.outcome === "unsupported") setStop("one");
+ else setFailed(true);
+ }, () => setFailed(true));
+ const body = (() => {
+ switch (screen.kind) {
+ case "checking": case "first": return <div data-cloud-add="extra-checking" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("cloudAdd.title")} />
+ <p role="status" className="flex items-center gap-2 text-[13px] text-ink-secondary"><Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />{t("cloudAdd.checking")}</p>
+ </div>;
+ case "unreachable": case "error": return <div data-cloud-add={`extra-${screen.kind}`} className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("cloudAdd.title")} />
+ <p role="alert" className="text-[14px] leading-relaxed text-ink">{t(screen.kind === "error" ? "cloudAdd.failed" : "cloudAdd.unreachable")}</p>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <button type="button" className="ui-button" onClick={onClose}>{t("cloudAdd.close")}</button>
+ <button type="button" data-autofocus className="ui-button ui-button-primary" onClick={() => { setFailed(false); setView(undefined); void read(); }}>{t("cloudAdd.tryAgain")}</button>
+ </div>
+ </div>;
+ case "stop": return <Stop reason={screen.reason} home={screen.home} busy={busy} interest={interest} onClose={onClose}
+ onInterest={() => act(async () => { await bridge?.interest(); setInterest("sent"); }, () => setInterest("failed"))} />;
+ case "choose": return <div>
+ {onBack && <div className="px-7 pt-5"><BackLink label={t("rail.back")} onClick={onBack} /></div>}
+ <ChooseScreen offer={screen.offer} now={now()} busy={busy} signedOut={false} notice={null} onSignIn={() => {}}
+ onStart={(chosen) => { track("cloud_add_another", { step: "plan", plan: chosen }); setTier(chosen); }} />
+ </div>;
+ case "name": return <NameScreen plan={screen.plan} name={name} color={color} busy={busy} suggested={suggested} onName={setName} onColor={setColor}
+ onBack={() => setTier(null)} onContinue={start} />;
+ case "waiting": return <div data-cloud-add={screen.late ? "extra-waiting-late" : "extra-waiting"} className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={screen.late ? t("cloudBuy.pay.lateTitle") : t("cloudAdd.browserTitle")} sub={screen.late ? t("cloudBuy.extra.lateSub") : t("cloudBuy.pay.sub")} />
+ <Checklist items={[
+ { key: "payment", state: "now", title: t("cloudBuy.pay.waiting"), detail: screen.adding.name },
+ { key: "setup", state: "next", title: t("cloudBuy.pay.setup"), detail: t("cloudBuy.pay.setupHint") },
+ ]} />
+ {screen.adding.link && <div className="flex flex-wrap items-center gap-2">
+ <button type="button" data-autofocus className={screen.late ? "ui-button ui-button-primary" : "ui-button"} disabled={busy}
+ onClick={() => act(async () => { if (!(await bridge?.reopen())) setNote("pay-failed"); }, () => setNote("pay-failed"))}>
+ <ExternalLink size={14} aria-hidden="true" />{t("cloudAdd.reopenCheckout")}</button>
+ <button type="button" className="ui-button" disabled={busy}
+ onClick={() => act(async () => setNote((await bridge?.copyLink()) ? "copied" : "pay-failed"), () => setNote("pay-failed"))}>
+ <Copy size={14} aria-hidden="true" />{t("cloudBuy.pay.copy")}</button>
+ </div>}
+ <div aria-live="polite" className="text-[13px] empty:-mt-4">
+ {note === "copied" && <p className="text-ink-secondary">{t("cloudBuy.pay.copied")}</p>}
+ {note === "pay-failed" && <p role="alert" className="text-danger">{t("cloudBuy.pay.failed")}</p>}
+ </div>
+ </div>;
+ case "starting": return <div data-cloud-add="extra-starting" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("cloudBuy.extra.setupTitle", { name: screen.adding.name })} sub={t("cloudBuy.extra.setupSub")} />
+ <ProgressBar value={screen.adding.progress ?? 0} label={t("cloudBuy.setup.progress")} />
+ <div className="flex justify-end"><button type="button" data-autofocus className="ui-button" onClick={onClose}>{t("cloudAdd.close")}</button></div>
+ </div>;
+ case "ready": return <div data-cloud-add="extra-ready" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("cloudBuy.ready.title", { name: screen.adding.name })} sub={t("cloudBuy.extra.readySub")} />
+ <button type="button" data-autofocus className={PRIMARY_WIDE} disabled={busy}
+ onClick={() => act(async () => { await bridge?.open(); onClose(); }, () => setNote("open-failed"))}>{t("cloudBuy.setup.open", { name: screen.adding.name })}</button>
+ {note === "open-failed" && <p role="alert" className="text-[13px] text-danger">{t("cloudBuy.openFailed", { name: screen.adding.name })}</p>}
+ </div>;
+ case "problem": return <div data-cloud-add="extra-problem" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7">
+ <Heading title={t("cloudAdd.title")} />
+ <p role="alert" className="text-[14px] leading-relaxed text-ink">{t("cloudBuy.extra.problem", { name: screen.adding.name })}</p>
+ <div className="flex justify-end"><button type="button" data-autofocus className="ui-button ui-button-primary" onClick={onClose}>{t("cloudAdd.close")}</button></div>
+ </div>;
+ }
+ })();
+ return <div ref={root} data-add-cloud-flow={screen.kind} className="contents">{body}</div>;
+}
diff --git a/src/lib/cloud-extra.ts b/src/lib/cloud-extra.ts
new file mode 100644
index 0000000000..d16161d1fe
--- /dev/null
+++ b/src/lib/cloud-extra.ts
@@ -0,0 +1,72 @@
+import type { CloudOffer, CloudOfferPlan } from "../../electron/cloud-home.mjs";
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import type { AddCloudView } from "../../electron/cloud-rail.mjs";
+import type { CloudColor } from "../../electron/cloud-buy.mjs";
+import type { LocaleKey } from "@/locales";
+import { cloudColorFill } from "@/lib/cloud-look";
+import { CHECKOUT_WAIT_MS } from "@/lib/cloud-plan";
+
+/** A Cloud's name as the Admin keeps it: up to 40 characters. */
+export const CLOUD_LIST_NAME_LIMIT = 40;
+/** The colour each Admin swatch is drawn in here (electron/cloud-list.mjs CLOUD_SWATCH_COLORS); slate is the plain one. */
+export const SWATCH_COLOR = { blue: "blue", green: "teal", amber: "yellow", rose: "red", violet: "purple", slate: null } as const satisfies Record<CloudSwatch, CloudColor | null>;
+export function swatchFill(swatch: CloudSwatch): string {
+ const color = SWATCH_COLOR[swatch];
+ return color ? cloudColorFill(color) : "var(--color-raised)";
+}
+
+/** The Admin's swatches in the order the sheet offers them, each with the name of the colour this app draws it in. */
+export const CLOUD_SWATCH_LABEL = {
+ blue: "cloudBuy.color.blue", green: "cloudBuy.color.teal", amber: "cloudBuy.color.yellow", rose: "cloudBuy.color.red", violet: "cloudBuy.color.purple", slate: "cloudBuy.color.slate",
+} as const satisfies Record<CloudSwatch, LocaleKey>;
+export const CLOUD_SWATCH_ORDER = Object.keys(CLOUD_SWATCH_LABEL) as CloudSwatch[];
+export const DEFAULT_SWATCH: CloudSwatch = "blue";
+
+type Adding = Extract<AddCloudView, { signedIn: true }>["adding"] & {};
+/** Why the sheet can't sell another Cloud now: one Cloud per account (an older Admin, or its cap), new Clouds closed,
+ * another one's checkout still open, or too many checkouts at once. */
+export type AddCloudStop = "one" | "signups_closed" | "checkout_open" | "rate";
+
+/** Each screen of buying another Cloud, from the sheet's own steps and the Admin's word, which wins: a Cloud being bought
+ * shows how it is going until it was opened. */
+export type AddCloudScreen =
+ | { kind: "checking" }
+ | { kind: "first" }
+ | { kind: "stop"; reason: AddCloudStop; home: string | null }
+ | { kind: "unreachable" }
+ | { kind: "error" }
+ | { kind: "choose"; offer: CloudOffer }
+ | { kind: "name"; plan: CloudOfferPlan }
+ | { kind: "waiting"; adding: Adding; late: boolean }
+ | { kind: "starting"; adding: Adding }
+ | { kind: "ready"; adding: Adding }
+ | { kind: "problem"; adding: Adding };
+
+export function addCloudScreen(view: AddCloudView | null | undefined, { now, tier = null, failed = false, stop = null }: {
+ now: number; tier?: string | null; failed?: boolean; stop?: AddCloudStop | null;
+}): AddCloudScreen {
+ if (view === undefined) return { kind: "checking" };
+ if (view === null) return { kind: "unreachable" };
+ if (!view.signedIn || !view.hasCloud) return { kind: "first" };
+ const adding = view.adding && !view.adding.done ? view.adding : null;
+ if (adding) {
+ if (adding.status === "ready") return { kind: "ready", adding };
+ if (adding.status === "setting_up") return { kind: "starting", adding };
+ if (adding.status === "problem") return { kind: "problem", adding };
+ return { kind: "waiting", adding, late: now - adding.startedAt >= CHECKOUT_WAIT_MS };
+ }
+ const home = view.home?.name ?? null;
+ if (!view.supported) return { kind: "stop", reason: "one", home };
+ const blocked = stop ?? (view.canAdd ? null : view.blocked === "cap" || !view.blocked ? "one" : view.blocked);
+ if (blocked) return { kind: "stop", reason: blocked, home };
+ if (failed) return { kind: "error" };
+ if (!view.offer?.plans.length) return { kind: "unreachable" };
+ const plan = tier ? view.offer.plans.find((entry) => entry.tier === tier) : undefined;
+ return plan ? { kind: "name", plan } : { kind: "choose", offer: view.offer };
+}
+
+/** The Admin's refusal, in the sheet's words: its cap is one Cloud per account for now. */
+export function addCloudStop(blocked: string): AddCloudStop {
+ return blocked === "signups_closed" || blocked === "checkout_open" || blocked === "rate" ? blocked : "one";
+}
+
diff --git a/src/lib/place-look.ts b/src/lib/place-look.ts
new file mode 100644
index 0000000000..f555170659
--- /dev/null
+++ b/src/lib/place-look.ts
@@ -0,0 +1,65 @@
+import { useEffect, useState } from "react";
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import type { PlaceColorOutcome, PlaceLook } from "../../electron/place-look.mjs";
+import { cloudColor } from "@/lib/cloud-look";
+
+let current: PlaceLook | null = null;
+let started = false;
+const listeners = new Set<(look: PlaceLook | null) => void>();
+
+function bridge() {
+ const workspaces = typeof window === "undefined" || window.ogb?.remoteClient?.active ? undefined : window.ogb?.workspaces;
+ return workspaces?.look ? workspaces : undefined;
+}
+
+function publish(next: PlaceLook | null) {
+ current = next;
+ for (const listener of listeners) listener(current);
+}
+
+/** Main's word on this page's place again (its colour changed, or the window came back). */
+export function refreshPlaceLook(): Promise<void> {
+ const workspaces = bridge();
+ if (!workspaces?.look) return Promise.resolve();
+ return workspaces.look().then((next) => publish(next ?? null), () => {});
+}
+
+function start() {
+ if (started) return;
+ started = true;
+ bridge()?.onChanged?.(() => void refreshPlaceLook());
+ window.addEventListener("focus", () => void refreshPlaceLook());
+ void refreshPlaceLook();
+}
+
+/** The colour of the place this page is, and whether it can be changed here: none in a browser, on an older app and on
+ * this computer's own page. The sidebar's tint and Settings read the same one. */
+export function usePlaceLook(): PlaceLook | null {
+ const [look, setLook] = useState<PlaceLook | null>(current);
+ useEffect(() => {
+ if (!bridge()) return;
+ listeners.add(setLook);
+ start();
+ setLook(current);
+ return () => { listeners.delete(setLook); };
+ }, []);
+ return look;
+}
+
+/** The person chose a swatch: main saves it (on the Admin for a Cloud) and answers the place's look, which the tint and
+ * the rail's circle follow at once. */
+export async function choosePlaceColor(swatch: CloudSwatch | null): Promise<PlaceColorOutcome> {
+ const workspaces = bridge();
+ if (!workspaces?.color) return "failed";
+ const answer = await workspaces.color(swatch).catch(() => null);
+ if (!answer) return "failed";
+ publish(answer.look ?? current);
+ return answer.outcome;
+}
+
+/** The sidebar's tint for a place's colour: that colour in the skin's own tone (styles.css .place-tint fades it out);
+ * none without a colour, so the sidebar looks as it always did. */
+export function placeTint(color: unknown): { "--place-tint": string } | null {
+ const known = cloudColor(color);
+ return known ? { "--place-tint": `var(--identity-${known})` } : null;
+}
diff --git a/src/lib/places.ts b/src/lib/places.ts
new file mode 100644
index 0000000000..7b735c975a
--- /dev/null
+++ b/src/lib/places.ts
@@ -0,0 +1,56 @@
+import { useEffect, useState } from "react";
+import type { RailPlace, RailState } from "../../electron/cloud-rail.mjs";
+
+const NONE: RailState = { places: [], add: { cloud: false, link: false, address: false } };
+let current: RailState = NONE;
+let started = false;
+const listeners = new Set<(state: RailState) => void>();
+
+function bridge() {
+ const workspaces = typeof window === "undefined" || window.ogb?.remoteClient?.active ? undefined : window.ogb?.workspaces;
+ return workspaces?.places ? workspaces : undefined;
+}
+
+/** Main's list again (it changed, or the window came back): every rail and switcher on the page sees the same one. */
+export function refreshPlaces(): Promise<void> {
+ const workspaces = bridge();
+ if (!workspaces?.places) return Promise.resolve();
+ return workspaces.places().then((next) => {
+ current = next && Array.isArray(next.places) ? next : NONE;
+ for (const listener of listeners) listener(current);
+ }, () => {});
+}
+
+function start() {
+ if (started) return;
+ started = true;
+ bridge()?.onChanged?.(() => void refreshPlaces());
+ window.addEventListener("focus", () => void refreshPlaces());
+ void refreshPlaces();
+}
+
+/** The rail's places as main lists them for this page: none in a browser, on an older app, on a server's own page, or with
+ * fewer than two places. */
+export function usePlaces(): RailState {
+ const [state, setState] = useState<RailState>(current);
+ useEffect(() => {
+ if (!bridge()) return;
+ listeners.add(setState);
+ start();
+ setState(current);
+ return () => { listeners.delete(setState); };
+ }, []);
+ return state;
+}
+
+/** Whether the rail shows on this page: main lists places only when there are at least two. */
+export const railShown = (state: RailState): boolean => state.places.length > 0;
+
+/** A circle's letters: the first of up to two words, so "Client A" is CA and "Acme" is A. */
+export function placeInitials(name: string): string {
+ const words = name.trim().split(/\s+/).filter(Boolean);
+ const first = (word: string | undefined) => (word ? Array.from(word)[0] ?? "" : "");
+ return (first(words[0]) + (words.length > 1 ? first(words[1]) : "")).toLocaleUpperCase();
+}
+
+export type { RailPlace, RailState };
diff --git a/src/locales/de.json b/src/locales/de.json
index 6499f73e4e..cbca973e8d 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2479,5 +2479,57 @@
"place.action.addBoatKey": "Boat verbinden",
"place.view.vm.short": "Getrennt von deinem Bildschirm",
"place.view.browserOff.short": "Ausgeschaltet",
- "place.view.browserOff.line": "Der eigene Browser des Bots ist ausgeschaltet, daher kann er keine Webseiten öffnen."
+ "place.view.browserOff.line": "Der eigene Browser des Bots ist ausgeschaltet, daher kann er keine Webseiten öffnen.",
+ "cloudBuy.color.slate": "Schiefer",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Benenne deine neue Cloud",
+ "cloudBuy.extra.nameSub": "Sie bekommt eigene Bots, Personen, Apps und einen eigenen Tarif.",
+ "cloudBuy.extra.continue": "Weiter zur Bezahlung",
+ "cloudBuy.extra.setupTitle": "{name} wird eingerichtet",
+ "cloudBuy.extra.setupSub": "Etwa 2 Minuten. Arbeite ruhig weiter; wir sagen dir Bescheid, wenn sie bereit ist.",
+ "cloudBuy.extra.readySub": "Sie hat eigene Bots, Personen, Apps und einen eigenen Tarif. Wechsle jederzeit am linken Fensterrand zu ihr.",
+ "cloudBuy.extra.lateSub": "Wenn du bezahlt hast, erscheint sie hier in wenigen Minuten. Wenn nicht, öffne den Bezahlvorgang erneut.",
+ "cloudBuy.extra.problem": "Die Zahlung für {name} ist nicht durchgegangen. Aktualisiere sie auf deiner Tarifseite.",
+ "cloudBuy.extra.signupsClosed": "Neue Clouds können gerade nicht gekauft werden. Versuche es später noch einmal.",
+ "cloudBuy.extra.checkoutOpen": "Ein Bezahlvorgang für eine weitere Cloud ist bereits offen. Schließe ihn zuerst in deinem Browser ab.",
+ "rail.label": "Wo deine Bots leben",
+ "rail.thisComputer": "Dieser Computer",
+ "rail.settingUp": "{name}: wird eingerichtet",
+ "rail.waiting": "{name}: wartet auf Zahlung",
+ "rail.attention": "{name}: braucht dich",
+ "rail.more": "Alle {count} anzeigen",
+ "rail.search": "Cloud finden",
+ "rail.noMatch": "Keine Treffer.",
+ "rail.add": "Cloud oder eigenen Server hinzufügen",
+ "rail.buy": "Cloud kaufen",
+ "rail.buySub": "Eine neue Cloud mit eigenen Bots, Personen, Apps und Tarif, immer an.",
+ "rail.own": "Eigenen Server hinzufügen",
+ "rail.ownSub": "Einen gemieteten im Netz, einen Mac mini zu Hause oder einen Computer in deinem Tailscale-Netzwerk.",
+ "rail.ownLede": "Installiere dort OpenMausBot, und diese App öffnet ihn wie eine Cloud. Seine Bots bleiben auf ihm.",
+ "rail.step1": "Installiere OpenMausBot darauf",
+ "rail.step1Sub": "In einem Terminal dort, mit Node 24 oder neuer:",
+ "rail.step2": "Ein Kopplungsfenster öffnen",
+ "rail.step2Sub": "Führe das dort aus. Es gibt einen Kopplungslink für diese App aus:",
+ "rail.step3": "Hier verbinden",
+ "rail.step3Sub": "Kopiere den ausgegebenen Link und füge ihn hier ein.",
+ "rail.paste": "Kopplungslink einfügen",
+ "rail.address": "Stattdessen Adresse eingeben",
+ "rail.copy": "Kopieren",
+ "rail.copied": "Kopiert",
+ "rail.back": "Zurück",
+ "rail.ownServer": "{name}, dein eigener Server",
+ "rail.offline": "{name}: offline",
+ "rail.lastSeen": "{name}: offline, zuletzt gesehen {when}",
+ "rail.notConnected": "{name}: mit dieser App verbinden",
+ "rail.ownNetwork": "Nur im eigenen Netzwerk erreichbar",
+ "rail.update": "auf {version}, {latest} ist erschienen",
+ "rail.connectTitle": "{name} verbinden",
+ "rail.connectLede": "Er ist schon mit deinem Konto angemeldet. Öffne darauf ein Kopplungsfenster und füge den Link, den es ausgibt, hier ein.",
+ "placeLook.title": "Farbe",
+ "placeLook.sub": "{name} erscheint in dieser Farbe oben in der Seitenleiste und auf dem Kreis am linken Fensterrand.",
+ "placeLook.aria": "Farbe von {name}",
+ "placeLook.member": "Nur die Admins können die Farbe ändern.",
+ "placeLook.signedOut": "Melde dich bei MausBot Cloud an, um die Farbe zu ändern.",
+ "placeLook.unsupported": "Die Farbe dieser Cloud lässt sich in der App noch nicht ändern.",
+ "placeLook.failed": "Die Farbe wurde nicht gespeichert. Versuche es noch einmal."
}
diff --git a/src/locales/en.json b/src/locales/en.json
index d4d4c86bee..05c2297eab 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -259,6 +259,58 @@
"cloudBuy.one.email": "Email me when I can add another",
"cloudBuy.one.thanks": "Thanks. We'll email you when you can add another Cloud.",
"cloudBuy.one.failed": "Couldn't reach MausBot Cloud, so nothing was saved. Try again.",
+ "cloudBuy.color.slate": "Slate",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Name your new Cloud",
+ "cloudBuy.extra.nameSub": "It gets its own bots, people, apps and plan.",
+ "cloudBuy.extra.continue": "Continue to checkout",
+ "cloudBuy.extra.setupTitle": "Setting up {name}",
+ "cloudBuy.extra.setupSub": "About 2 minutes. Keep working if you like; we'll tell you when it's ready.",
+ "cloudBuy.extra.readySub": "It has its own bots, people, apps and plan. Switch to it from the left edge of the window any time.",
+ "cloudBuy.extra.lateSub": "If you paid, it shows up here within a few minutes. If not, reopen checkout.",
+ "cloudBuy.extra.problem": "The payment for {name} didn't go through. Update it on your Plan page.",
+ "cloudBuy.extra.signupsClosed": "New Clouds can't be bought right now. Try again later.",
+ "cloudBuy.extra.checkoutOpen": "A checkout for another Cloud is already open. Finish it in your browser first.",
+ "rail.label": "Where your bots live",
+ "rail.thisComputer": "This computer",
+ "rail.settingUp": "{name}: setting up",
+ "rail.waiting": "{name}: waiting for payment",
+ "rail.attention": "{name}: needs you",
+ "rail.more": "Show all {count}",
+ "rail.search": "Find a Cloud",
+ "rail.noMatch": "Nothing matches.",
+ "rail.add": "Add a Cloud or your own server",
+ "rail.buy": "Buy a Cloud",
+ "rail.buySub": "A new Cloud with its own bots, people, apps and plan, always on.",
+ "rail.own": "Add your own server",
+ "rail.ownSub": "One you rent online, a Mac mini at home, or a computer on your Tailscale network.",
+ "rail.ownLede": "Install OpenMausBot there, and this app opens it like a Cloud. Its bots stay on it.",
+ "rail.step1": "Install OpenMausBot on it",
+ "rail.step1Sub": "In a terminal there, with Node 24 or newer:",
+ "rail.step2": "Open a pairing window",
+ "rail.step2Sub": "Run this there. It prints a pairing link for this app:",
+ "rail.step3": "Connect it here",
+ "rail.step3Sub": "Copy the link it printed, then paste it here.",
+ "rail.paste": "Paste pairing link",
+ "rail.address": "Enter its address instead",
+ "rail.copy": "Copy",
+ "rail.copied": "Copied",
+ "rail.back": "Back",
+ "rail.ownServer": "{name}, your own server",
+ "rail.offline": "{name}: offline",
+ "rail.lastSeen": "{name}: offline, last seen {when}",
+ "rail.notConnected": "{name}: connect it to this app",
+ "rail.ownNetwork": "Only reachable on its own network",
+ "rail.update": "on {version}, {latest} is out",
+ "rail.connectTitle": "Connect {name}",
+ "rail.connectLede": "It's signed in to your account already. Open a pairing window on it, then paste the link it prints here.",
+ "placeLook.title": "Color",
+ "placeLook.sub": "{name} shows in this color at the top of the sidebar and on its circle at the window's left edge.",
+ "placeLook.aria": "Color of {name}",
+ "placeLook.member": "Only its admins can change its color.",
+ "placeLook.signedOut": "Sign in to MausBot Cloud to change its color.",
+ "placeLook.unsupported": "This Cloud's color can't be changed from the app yet.",
+ "placeLook.failed": "The color wasn't saved. Try again.",
"cloudBuy.team.setupTitle": "Setting up your team's Cloud",
"cloudBuy.team.setupSub": "About 2 minutes. Keep working if you like; you can open it here once it's ready.",
"cloudBuy.team.unnamed": "your team's Cloud",
diff --git a/src/locales/es.json b/src/locales/es.json
index b26c94babb..3c2dd72815 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -227,6 +227,58 @@
"cloudBuy.one.email": "Avisarme por correo cuando pueda añadir otra",
"cloudBuy.one.thanks": "Gracias. Te avisaremos por correo cuando puedas añadir otra Cloud.",
"cloudBuy.one.failed": "No se pudo conectar con MausBot Cloud, así que no se guardó nada. Inténtalo de nuevo.",
+ "cloudBuy.color.slate": "Pizarra",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Ponle nombre a tu nueva Cloud",
+ "cloudBuy.extra.nameSub": "Tendrá sus propios bots, personas, apps y plan.",
+ "cloudBuy.extra.continue": "Continuar al pago",
+ "cloudBuy.extra.setupTitle": "Configurando {name}",
+ "cloudBuy.extra.setupSub": "Unos 2 minutos. Puedes seguir trabajando; te avisaremos cuando esté lista.",
+ "cloudBuy.extra.readySub": "Tiene sus propios bots, personas, apps y plan. Cambia a ella desde el borde izquierdo de la ventana cuando quieras.",
+ "cloudBuy.extra.lateSub": "Si ya pagaste, aparecerá aquí en unos minutos. Si no, vuelve a abrir el pago.",
+ "cloudBuy.extra.problem": "El pago de {name} no se completó. Actualízalo en tu página del plan.",
+ "cloudBuy.extra.signupsClosed": "Ahora mismo no se pueden comprar Clouds nuevas. Inténtalo más tarde.",
+ "cloudBuy.extra.checkoutOpen": "Ya hay un pago abierto para otra Cloud. Termínalo primero en tu navegador.",
+ "rail.label": "Dónde viven tus bots",
+ "rail.thisComputer": "Este equipo",
+ "rail.settingUp": "{name}: configurándose",
+ "rail.waiting": "{name}: esperando el pago",
+ "rail.attention": "{name}: te necesita",
+ "rail.more": "Ver todos ({count})",
+ "rail.search": "Buscar una Cloud",
+ "rail.noMatch": "No hay coincidencias.",
+ "rail.add": "Añadir una Cloud o tu propio servidor",
+ "rail.buy": "Comprar una Cloud",
+ "rail.buySub": "Una Cloud nueva con sus propios bots, personas, apps y plan, siempre encendida.",
+ "rail.own": "Añadir tu propio servidor",
+ "rail.ownSub": "Uno que alquilas en internet, un Mac mini en casa o un equipo de tu red de Tailscale.",
+ "rail.ownLede": "Instala OpenMausBot allí y esta app lo abrirá como una Cloud. Sus bots se quedan en él.",
+ "rail.step1": "Instala OpenMausBot en él",
+ "rail.step1Sub": "En una terminal allí, con Node 24 o posterior:",
+ "rail.step2": "Abre una ventana de vinculación",
+ "rail.step2Sub": "Ejecuta esto allí. Muestra un enlace de vinculación para esta app:",
+ "rail.step3": "Conéctalo aquí",
+ "rail.step3Sub": "Copia el enlace que mostró y pégalo aquí.",
+ "rail.paste": "Pegar enlace de vinculación",
+ "rail.address": "Escribir su dirección",
+ "rail.copy": "Copiar",
+ "rail.copied": "Copiado",
+ "rail.back": "Atrás",
+ "rail.ownServer": "{name}, tu propio servidor",
+ "rail.offline": "{name}: sin conexión",
+ "rail.lastSeen": "{name}: sin conexión, visto por última vez {when}",
+ "rail.notConnected": "{name}: conéctalo a esta app",
+ "rail.ownNetwork": "Solo accesible desde su propia red",
+ "rail.update": "en {version}, ya salió {latest}",
+ "rail.connectTitle": "Conectar {name}",
+ "rail.connectLede": "Ya inició sesión con tu cuenta. Abre una ventana de vinculación en él y pega aquí el enlace que muestre.",
+ "placeLook.title": "Color",
+ "placeLook.sub": "{name} se muestra en este color en la parte superior de la barra lateral y en su círculo del borde izquierdo de la ventana.",
+ "placeLook.aria": "Color de {name}",
+ "placeLook.member": "Solo sus administradores pueden cambiar su color.",
+ "placeLook.signedOut": "Inicia sesión en MausBot Cloud para cambiar su color.",
+ "placeLook.unsupported": "El color de esta Cloud aún no se puede cambiar desde la app.",
+ "placeLook.failed": "No se guardó el color. Inténtalo de nuevo.",
"cloudBuy.staging": "Staging",
"cloudBuy.stagingHint": "Esta app usa la versión de staging de MausBot Cloud: pagos y Clouds de prueba, no reales.",
"cloudNotice.signIn.title": "Vuelve a iniciar sesión para acceder a la Cloud",
diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.ts
index d6a632d127..719ca9fd8c 100644
--- a/src/locales/everyday-words.test.ts
+++ b/src/locales/everyday-words.test.ts
@@ -10,6 +10,8 @@ const EVERYDAY_PREFIXES: Record<string, readonly string[]> = {
],
"notifications and alerts": ["attention.", "notifications.", "error.", "readyBots.", "app.loading."],
"the sidebar and the switcher": ["sidebar."],
+ "the rail of Clouds and its +": ["rail."],
+ "a place's color, in Settings": ["placeLook."],
"the bot panel": [
"botPanel.", "botSettings.simple.", "botAccess.tools.", "botAccess.browser.", "memory.learnFromRooms.", "memory.upkeep.",
],
@@ -62,7 +64,8 @@ type Word = { word: string; pattern: RegExp; say: string };
const INTERNAL_WORDS: readonly Word[] = [
{ word: "engine", pattern: /\bengines?\b/i, say: "AI" },
{ word: "instance", pattern: /\binstances?\b/i, say: "AI account" },
- { word: "server", pattern: /(?<!(?:Discord|Slack|MCP) )\bservers?\b/i, say: "the app, or the Cloud when it is hosted" },
+ // "Your own server" is the person's own word for a computer they run OpenMausBot on (the rail's +).
+ { word: "server", pattern: /(?<!(?:Discord|Slack|MCP|own) )\bservers?\b/i, say: "the app, the Cloud when it is hosted, or your own server" },
{ word: "Composio", pattern: /composio/i, say: "connected apps" },
{ word: "Cloud computer", pattern: /\bcloud computers?\b/i, say: "cloud desktop" },
{ word: "VPS", pattern: /\bVPS\b/, say: "your own machine" },
@@ -118,7 +121,7 @@ describe("everyday screens", () => {
"Start the cloud computer", "Self-hosted VPS", "Create Local VM", "Choose a workspace",
]) expect(wordsIn(bad), bad).not.toEqual([]);
for (const good of [
- "Switch this bot to another AI", "Pick a Discord server", "Post in your Slack servers", "Copy to {server}",
+ "Switch this bot to another AI", "Pick a Discord server", "Post in your Slack servers", "Copy to {server}", "Add your own server",
"Run `openmausbot server start`", "Open the Cloud", "Start the cloud desktop", "Your MCP servers", "Add MCP server", "Private desktop",
]) expect(wordsIn(good), good).toEqual([]);
});
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 46adfacfb3..c29acfc456 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -2461,5 +2461,57 @@
"place.action.addBoatKey": "Connecter Boat",
"place.view.vm.short": "Séparé de votre écran",
"place.view.browserOff.short": "Désactivé",
- "place.view.browserOff.line": "Le navigateur du bot est désactivé : il ne peut pas ouvrir de pages web."
+ "place.view.browserOff.line": "Le navigateur du bot est désactivé : il ne peut pas ouvrir de pages web.",
+ "cloudBuy.color.slate": "Ardoise",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Nommez votre nouveau Cloud",
+ "cloudBuy.extra.nameSub": "Il a ses propres bots, personnes, apps et forfait.",
+ "cloudBuy.extra.continue": "Continuer vers le paiement",
+ "cloudBuy.extra.setupTitle": "Configuration de {name}",
+ "cloudBuy.extra.setupSub": "Environ 2 minutes. Continuez à travailler si vous voulez ; nous vous préviendrons quand il sera prêt.",
+ "cloudBuy.extra.readySub": "Il a ses propres bots, personnes, apps et forfait. Passez-y à tout moment depuis le bord gauche de la fenêtre.",
+ "cloudBuy.extra.lateSub": "Si vous avez payé, il apparaîtra ici d'ici quelques minutes. Sinon, rouvrez le paiement.",
+ "cloudBuy.extra.problem": "Le paiement de {name} n'a pas abouti. Mettez-le à jour sur votre page de forfait.",
+ "cloudBuy.extra.signupsClosed": "Impossible d'acheter de nouveaux Clouds pour le moment. Réessayez plus tard.",
+ "cloudBuy.extra.checkoutOpen": "Un paiement pour un autre Cloud est déjà ouvert. Terminez-le d'abord dans votre navigateur.",
+ "rail.label": "Où vivent vos bots",
+ "rail.thisComputer": "Cet ordinateur",
+ "rail.settingUp": "{name} : configuration en cours",
+ "rail.waiting": "{name} : en attente du paiement",
+ "rail.attention": "{name} : a besoin de vous",
+ "rail.more": "Tout afficher ({count})",
+ "rail.search": "Trouver un Cloud",
+ "rail.noMatch": "Aucun résultat.",
+ "rail.add": "Ajouter un Cloud ou votre propre serveur",
+ "rail.buy": "Acheter un Cloud",
+ "rail.buySub": "Un nouveau Cloud avec ses propres bots, personnes, apps et forfait, toujours allumé.",
+ "rail.own": "Ajouter votre propre serveur",
+ "rail.ownSub": "Un serveur loué en ligne, un Mac mini à la maison ou un ordinateur de votre réseau Tailscale.",
+ "rail.ownLede": "Installez-y OpenMausBot, et cette app l'ouvre comme un Cloud. Ses bots restent dessus.",
+ "rail.step1": "Installez OpenMausBot dessus",
+ "rail.step1Sub": "Dans un terminal sur place, avec Node 24 ou plus récent :",
+ "rail.step2": "Ouvrez une fenêtre d'appairage",
+ "rail.step2Sub": "Lancez ceci là-bas. Il affiche un lien d'appairage pour cette app :",
+ "rail.step3": "Connectez-le ici",
+ "rail.step3Sub": "Copiez le lien affiché, puis collez-le ici.",
+ "rail.paste": "Coller le lien d'appairage",
+ "rail.address": "Saisir son adresse à la place",
+ "rail.copy": "Copier",
+ "rail.copied": "Copié",
+ "rail.back": "Retour",
+ "rail.ownServer": "{name}, votre propre serveur",
+ "rail.offline": "{name} : hors ligne",
+ "rail.lastSeen": "{name} : hors ligne, vu pour la dernière fois {when}",
+ "rail.notConnected": "{name} : connectez-le à cette app",
+ "rail.ownNetwork": "Accessible uniquement depuis son propre réseau",
+ "rail.update": "en {version}, {latest} est disponible",
+ "rail.connectTitle": "Connecter {name}",
+ "rail.connectLede": "Il est déjà connecté à votre compte. Ouvrez-y une fenêtre d'appairage, puis collez ici le lien qu'il affiche.",
+ "placeLook.title": "Couleur",
+ "placeLook.sub": "{name} s'affiche dans cette couleur en haut de la barre latérale et sur son cercle, au bord gauche de la fenêtre.",
+ "placeLook.aria": "Couleur de {name}",
+ "placeLook.member": "Seuls ses administrateurs peuvent changer sa couleur.",
+ "placeLook.signedOut": "Connectez-vous à MausBot Cloud pour changer sa couleur.",
+ "placeLook.unsupported": "La couleur de ce Cloud ne peut pas encore être changée depuis l'app.",
+ "placeLook.failed": "La couleur n'a pas été enregistrée. Réessayez."
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index a3abd85d74..d3e1cecc3e 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -2461,5 +2461,57 @@
"place.action.addBoatKey": "Boat कनेक्ट करें",
"place.view.vm.short": "आपकी स्क्रीन से अलग",
"place.view.browserOff.short": "बंद है",
- "place.view.browserOff.line": "बॉट का अपना ब्राउज़र बंद है, इसलिए वह वेब पेज नहीं खोल सकता।"
+ "place.view.browserOff.line": "बॉट का अपना ब्राउज़र बंद है, इसलिए वह वेब पेज नहीं खोल सकता।",
+ "cloudBuy.color.slate": "स्लेट",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "अपने नए Cloud को नाम दें",
+ "cloudBuy.extra.nameSub": "इसके अपने बॉट, लोग, ऐप्स और प्लान होंगे।",
+ "cloudBuy.extra.continue": "चेकआउट पर जाएँ",
+ "cloudBuy.extra.setupTitle": "{name} सेट हो रहा है",
+ "cloudBuy.extra.setupSub": "लगभग 2 मिनट। चाहें तो काम जारी रखें; तैयार होते ही हम आपको बता देंगे।",
+ "cloudBuy.extra.readySub": "इसके अपने बॉट, लोग, ऐप्स और प्लान हैं। विंडो के बाएँ किनारे से कभी भी इस पर जाएँ।",
+ "cloudBuy.extra.lateSub": "अगर आपने भुगतान कर दिया है, तो यह कुछ ही मिनटों में यहाँ दिखेगा। नहीं तो चेकआउट फिर से खोलें।",
+ "cloudBuy.extra.problem": "{name} का भुगतान पूरा नहीं हुआ। इसे अपने प्लान पेज पर अपडेट करें।",
+ "cloudBuy.extra.signupsClosed": "अभी नए Cloud नहीं खरीदे जा सकते। बाद में फिर कोशिश करें।",
+ "cloudBuy.extra.checkoutOpen": "दूसरे Cloud का एक चेकआउट पहले से खुला है। पहले उसे अपने ब्राउज़र में पूरा करें।",
+ "rail.label": "आपके बॉट कहाँ रहते हैं",
+ "rail.thisComputer": "यही कंप्यूटर",
+ "rail.settingUp": "{name}: सेट हो रहा है",
+ "rail.waiting": "{name}: भुगतान का इंतज़ार",
+ "rail.attention": "{name}: आपकी ज़रूरत है",
+ "rail.more": "सभी {count} दिखाएँ",
+ "rail.search": "Cloud खोजें",
+ "rail.noMatch": "कुछ नहीं मिला।",
+ "rail.add": "Cloud या अपना सर्वर जोड़ें",
+ "rail.buy": "Cloud खरीदें",
+ "rail.buySub": "अपने बॉट, लोग, ऐप्स और प्लान वाला नया Cloud, हमेशा चालू।",
+ "rail.own": "अपना सर्वर जोड़ें",
+ "rail.ownSub": "ऑनलाइन किराए का, घर पर रखा Mac mini, या आपके Tailscale नेटवर्क का कोई कंप्यूटर।",
+ "rail.ownLede": "वहाँ OpenMausBot इंस्टॉल करें, और यह ऐप उसे Cloud की तरह खोलेगा। उसके बॉट उसी पर रहते हैं।",
+ "rail.step1": "उस पर OpenMausBot इंस्टॉल करें",
+ "rail.step1Sub": "वहाँ के टर्मिनल में, Node 24 या उससे नए वर्शन के साथ:",
+ "rail.step2": "पेयरिंग विंडो खोलें",
+ "rail.step2Sub": "इसे वहाँ चलाएँ। यह इस ऐप के लिए एक पेयरिंग लिंक दिखाता है:",
+ "rail.step3": "इसे यहाँ जोड़ें",
+ "rail.step3Sub": "दिखाया गया लिंक कॉपी करें, फिर उसे यहाँ पेस्ट करें।",
+ "rail.paste": "पेयरिंग लिंक पेस्ट करें",
+ "rail.address": "इसके बजाय पता डालें",
+ "rail.copy": "कॉपी",
+ "rail.copied": "कॉपी हुआ",
+ "rail.back": "वापस",
+ "rail.ownServer": "{name}, आपका अपना सर्वर",
+ "rail.offline": "{name}: ऑफ़लाइन",
+ "rail.lastSeen": "{name}: ऑफ़लाइन, आखिरी बार {when} देखा गया",
+ "rail.notConnected": "{name}: इसे इस ऐप से जोड़ें",
+ "rail.ownNetwork": "सिर्फ़ उसके अपने नेटवर्क पर पहुँचा जा सकता है",
+ "rail.update": "{version} पर है, {latest} आ गया है",
+ "rail.connectTitle": "{name} जोड़ें",
+ "rail.connectLede": "यह आपके खाते से पहले ही साइन इन है। उस पर पेयरिंग विंडो खोलें, फिर उसका दिखाया गया लिंक यहाँ पेस्ट करें।",
+ "placeLook.title": "रंग",
+ "placeLook.sub": "{name} साइडबार के ऊपर और विंडो के बाएँ किनारे पर अपने गोले में इसी रंग में दिखता है।",
+ "placeLook.aria": "{name} का रंग",
+ "placeLook.member": "इसका रंग सिर्फ़ इसके एडमिन बदल सकते हैं।",
+ "placeLook.signedOut": "इसका रंग बदलने के लिए MausBot Cloud में साइन इन करें।",
+ "placeLook.unsupported": "इस Cloud का रंग अभी ऐप से नहीं बदला जा सकता।",
+ "placeLook.failed": "रंग सेव नहीं हुआ। फिर कोशिश करें।"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index e912d91f2b..dfba584c87 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -231,6 +231,58 @@
"cloudBuy.one.email": "Scrivimi quando posso aggiungerne un altro",
"cloudBuy.one.thanks": "Grazie. Ti scriviamo quando potrai aggiungere un altro Cloud.",
"cloudBuy.one.failed": "MausBot Cloud non è raggiungibile, quindi non abbiamo salvato nulla. Riprova.",
+ "cloudBuy.color.slate": "Ardesia",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Dai un nome al tuo nuovo Cloud",
+ "cloudBuy.extra.nameSub": "Avrà i suoi bot, le sue persone, le sue app e il suo piano.",
+ "cloudBuy.extra.continue": "Continua al pagamento",
+ "cloudBuy.extra.setupTitle": "Configurazione di {name}",
+ "cloudBuy.extra.setupSub": "Circa 2 minuti. Continua pure a lavorare: ti avvisiamo quando è pronto.",
+ "cloudBuy.extra.readySub": "Ha i suoi bot, le sue persone, le sue app e il suo piano. Passaci quando vuoi dal bordo sinistro della finestra.",
+ "cloudBuy.extra.lateSub": "Se hai pagato, compare qui entro pochi minuti. Altrimenti, riapri il pagamento.",
+ "cloudBuy.extra.problem": "Il pagamento di {name} non è andato a buon fine. Aggiornalo nella pagina del piano.",
+ "cloudBuy.extra.signupsClosed": "Al momento non si possono acquistare nuovi Cloud. Riprova più tardi.",
+ "cloudBuy.extra.checkoutOpen": "C'è già un pagamento aperto per un altro Cloud. Prima completalo nel browser.",
+ "rail.label": "Dove vivono i tuoi bot",
+ "rail.thisComputer": "Questo computer",
+ "rail.settingUp": "{name}: in configurazione",
+ "rail.waiting": "{name}: in attesa del pagamento",
+ "rail.attention": "{name}: ha bisogno di te",
+ "rail.more": "Mostra tutti ({count})",
+ "rail.search": "Trova un Cloud",
+ "rail.noMatch": "Nessun risultato.",
+ "rail.add": "Aggiungi un Cloud o il tuo server",
+ "rail.buy": "Compra un Cloud",
+ "rail.buySub": "Un nuovo Cloud con i suoi bot, le sue persone, le sue app e il suo piano, sempre acceso.",
+ "rail.own": "Aggiungi il tuo server",
+ "rail.ownSub": "Uno che affitti online, un Mac mini a casa o un computer della tua rete Tailscale.",
+ "rail.ownLede": "Installa lì OpenMausBot e questa app lo apre come un Cloud. I suoi bot restano lì.",
+ "rail.step1": "Installa OpenMausBot",
+ "rail.step1Sub": "In un terminale lì, con Node 24 o più recente:",
+ "rail.step2": "Apri una finestra di abbinamento",
+ "rail.step2Sub": "Esegui questo lì. Stampa un link di abbinamento per questa app:",
+ "rail.step3": "Collegalo qui",
+ "rail.step3Sub": "Copia il link che ha stampato, poi incollalo qui.",
+ "rail.paste": "Incolla il link di abbinamento",
+ "rail.address": "Inserisci invece il suo indirizzo",
+ "rail.copy": "Copia",
+ "rail.copied": "Copiato",
+ "rail.back": "Indietro",
+ "rail.ownServer": "{name}, il tuo server",
+ "rail.offline": "{name}: offline",
+ "rail.lastSeen": "{name}: offline, visto l'ultima volta {when}",
+ "rail.notConnected": "{name}: collegalo a questa app",
+ "rail.ownNetwork": "Raggiungibile solo dalla sua rete",
+ "rail.update": "su {version}, è uscita la {latest}",
+ "rail.connectTitle": "Collega {name}",
+ "rail.connectLede": "Ha già effettuato l'accesso con il tuo account. Aprici una finestra di abbinamento, poi incolla qui il link che mostra.",
+ "placeLook.title": "Colore",
+ "placeLook.sub": "{name} appare in questo colore in cima alla barra laterale e nel suo cerchio sul bordo sinistro della finestra.",
+ "placeLook.aria": "Colore di {name}",
+ "placeLook.member": "Solo i suoi amministratori possono cambiarne il colore.",
+ "placeLook.signedOut": "Accedi a MausBot Cloud per cambiarne il colore.",
+ "placeLook.unsupported": "Il colore di questo Cloud non si può ancora cambiare dall'app.",
+ "placeLook.failed": "Il colore non è stato salvato. Riprova.",
"cloudBuy.team.setupTitle": "Preparazione del Cloud del tuo team",
"cloudBuy.team.setupSub": "Circa 2 minuti. Puoi continuare a lavorare; quando è pronto lo apri da qui.",
"cloudBuy.team.unnamed": "il Cloud del tuo team",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 0467eef53d..5fd2e04493 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -237,6 +237,58 @@
"cloudBuy.one.email": "追加できるようになったらメールで知らせる",
"cloudBuy.one.thanks": "ありがとうございます。Cloudを追加できるようになりましたらメールでお知らせします。",
"cloudBuy.one.failed": "MausBot Cloudに接続できなかったため、何も保存されませんでした。もう一度お試しください。",
+ "cloudBuy.color.slate": "スレート",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "新しいCloudに名前を付ける",
+ "cloudBuy.extra.nameSub": "専用のボット、メンバー、アプリ、プランを持ちます。",
+ "cloudBuy.extra.continue": "支払いへ進む",
+ "cloudBuy.extra.setupTitle": "{name}を準備中",
+ "cloudBuy.extra.setupSub": "約2分かかります。作業を続けてかまいません。準備ができたらお知らせします。",
+ "cloudBuy.extra.readySub": "専用のボット、メンバー、アプリ、プランがあります。ウィンドウの左端からいつでも切り替えられます。",
+ "cloudBuy.extra.lateSub": "支払いが済んでいれば、数分以内にここに表示されます。済んでいなければ、支払い画面をもう一度開いてください。",
+ "cloudBuy.extra.problem": "{name}の支払いが完了しませんでした。プランページで支払い情報を更新してください。",
+ "cloudBuy.extra.signupsClosed": "現在、新しいCloudは購入できません。しばらくしてからもう一度お試しください。",
+ "cloudBuy.extra.checkoutOpen": "別のCloudの支払い画面がすでに開いています。先にブラウザで完了してください。",
+ "rail.label": "ボットの居場所",
+ "rail.thisComputer": "このコンピューター",
+ "rail.settingUp": "{name}: 準備中",
+ "rail.waiting": "{name}: 支払い待ち",
+ "rail.attention": "{name}: 対応が必要です",
+ "rail.more": "すべて表示({count})",
+ "rail.search": "Cloudを探す",
+ "rail.noMatch": "一致するものはありません。",
+ "rail.add": "Cloudまたは自分のサーバーを追加",
+ "rail.buy": "Cloudを購入",
+ "rail.buySub": "専用のボット、メンバー、アプリ、プランを持つ新しいCloud。常に稼働します。",
+ "rail.own": "自分のサーバーを追加",
+ "rail.ownSub": "オンラインで借りたもの、自宅のMac mini、またはTailscaleネットワーク上のコンピューター。",
+ "rail.ownLede": "そこにOpenMausBotをインストールすると、このアプリでCloudのように開けます。ボットはそのサーバーに置かれたままです。",
+ "rail.step1": "OpenMausBotをインストール",
+ "rail.step1Sub": "そのコンピューターのターミナルで、Node 24以降を使って:",
+ "rail.step2": "ペアリング画面を開く",
+ "rail.step2Sub": "そこでこれを実行します。このアプリ用のペアリングリンクが表示されます:",
+ "rail.step3": "ここで接続",
+ "rail.step3Sub": "表示されたリンクをコピーして、ここに貼り付けます。",
+ "rail.paste": "ペアリングリンクを貼り付け",
+ "rail.address": "代わりにアドレスを入力",
+ "rail.copy": "コピー",
+ "rail.copied": "コピーしました",
+ "rail.back": "戻る",
+ "rail.ownServer": "{name}(自分のサーバー)",
+ "rail.offline": "{name}: オフライン",
+ "rail.lastSeen": "{name}: オフライン(最終確認 {when})",
+ "rail.notConnected": "{name}: このアプリに接続する",
+ "rail.ownNetwork": "そのネットワーク内からのみ接続できます",
+ "rail.update": "{version} を実行中、{latest} が公開されています",
+ "rail.connectTitle": "{name} を接続",
+ "rail.connectLede": "すでにあなたのアカウントでサインインしています。そこでペアリング画面を開き、表示されたリンクをここに貼り付けてください。",
+ "placeLook.title": "色",
+ "placeLook.sub": "{name} は、サイドバーの上部とウィンドウ左端の丸にこの色で表示されます。",
+ "placeLook.aria": "{name} の色",
+ "placeLook.member": "色を変更できるのは管理者だけです。",
+ "placeLook.signedOut": "色を変更するには MausBot Cloud にサインインしてください。",
+ "placeLook.unsupported": "この Cloud の色は、まだアプリから変更できません。",
+ "placeLook.failed": "色を保存できませんでした。もう一度お試しください。",
"cloudBuy.team.setupTitle": "チームの Cloud を設定しています",
"cloudBuy.team.setupSub": "所要時間は約2分です。そのまま作業を続けても構いません。準備が整ったら、ここから開けます。",
"cloudBuy.team.unnamed": "チームの Cloud",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 217baefb5a..73327f89b6 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -237,6 +237,58 @@
"cloudBuy.one.email": "Powiadom mnie e-mailem, gdy będzie można dodać kolejną",
"cloudBuy.one.thanks": "Dziękujemy. Wyślemy ci e-mail, gdy będzie można dodać kolejną Chmurę.",
"cloudBuy.one.failed": "Nie udało się połączyć z MausBot Cloud, więc nic nie zapisano. Spróbuj ponownie.",
+ "cloudBuy.color.slate": "Łupkowy",
+ "cloudBuy.extra.defaultName": "Chmura {number}",
+ "cloudBuy.extra.nameTitle": "Nazwij nową Chmurę",
+ "cloudBuy.extra.nameSub": "Będzie mieć własne boty, osoby, aplikacje i plan.",
+ "cloudBuy.extra.continue": "Przejdź do płatności",
+ "cloudBuy.extra.setupTitle": "Konfigurowanie: {name}",
+ "cloudBuy.extra.setupSub": "Około 2 minut. Możesz dalej pracować; damy znać, gdy będzie gotowa.",
+ "cloudBuy.extra.readySub": "Ma własne boty, osoby, aplikacje i plan. Przełączaj się na nią w dowolnej chwili przy lewej krawędzi okna.",
+ "cloudBuy.extra.lateSub": "Jeśli zapłacono, pojawi się tu w ciągu kilku minut. Jeśli nie, otwórz płatność ponownie.",
+ "cloudBuy.extra.problem": "Płatność za {name} nie przeszła. Zaktualizuj ją na stronie planu.",
+ "cloudBuy.extra.signupsClosed": "Nowych Chmur nie można teraz kupić. Spróbuj później.",
+ "cloudBuy.extra.checkoutOpen": "Płatność za inną Chmurę jest już otwarta. Najpierw dokończ ją w przeglądarce.",
+ "rail.label": "Gdzie mieszkają twoje boty",
+ "rail.thisComputer": "Ten komputer",
+ "rail.settingUp": "{name}: konfigurowanie",
+ "rail.waiting": "{name}: czeka na płatność",
+ "rail.attention": "{name}: potrzebuje ciebie",
+ "rail.more": "Pokaż wszystkie ({count})",
+ "rail.search": "Znajdź Chmurę",
+ "rail.noMatch": "Brak wyników.",
+ "rail.add": "Dodaj Chmurę lub własny serwer",
+ "rail.buy": "Kup Chmurę",
+ "rail.buySub": "Nowa Chmura z własnymi botami, osobami, aplikacjami i planem, zawsze włączona.",
+ "rail.own": "Dodaj własny serwer",
+ "rail.ownSub": "Wynajęty w sieci, Mac mini w domu albo komputer w twojej sieci Tailscale.",
+ "rail.ownLede": "Zainstaluj tam OpenMausBot, a ta aplikacja otworzy go jak Chmurę. Jego boty zostają na nim.",
+ "rail.step1": "Zainstaluj na nim OpenMausBot",
+ "rail.step1Sub": "W terminalu na nim, z Node 24 lub nowszym:",
+ "rail.step2": "Otwórz okno parowania",
+ "rail.step2Sub": "Uruchom to tam. Wyświetli link do parowania dla tej aplikacji:",
+ "rail.step3": "Połącz tutaj",
+ "rail.step3Sub": "Skopiuj wyświetlony link, a potem wklej go tutaj.",
+ "rail.paste": "Wklej link do parowania",
+ "rail.address": "Zamiast tego wpisz adres",
+ "rail.copy": "Kopiuj",
+ "rail.copied": "Skopiowano",
+ "rail.back": "Wstecz",
+ "rail.ownServer": "{name}, twój własny serwer",
+ "rail.offline": "{name}: offline",
+ "rail.lastSeen": "{name}: offline, ostatnio widziany {when}",
+ "rail.notConnected": "{name}: połącz go z tą aplikacją",
+ "rail.ownNetwork": "Dostępny tylko w swojej sieci",
+ "rail.update": "na {version}, dostępna jest {latest}",
+ "rail.connectTitle": "Połącz {name}",
+ "rail.connectLede": "Jest już zalogowany na Twoje konto. Otwórz na nim okno parowania, a potem wklej tutaj link, który wyświetli.",
+ "placeLook.title": "Kolor",
+ "placeLook.sub": "{name} ma ten kolor na górze paska bocznego i w swoim kółku przy lewej krawędzi okna.",
+ "placeLook.aria": "Kolor: {name}",
+ "placeLook.member": "Kolor mogą zmienić tylko administratorzy.",
+ "placeLook.signedOut": "Zaloguj się do MausBot Cloud, aby zmienić kolor.",
+ "placeLook.unsupported": "Koloru tej Chmury nie można jeszcze zmienić w aplikacji.",
+ "placeLook.failed": "Nie zapisano koloru. Spróbuj ponownie.",
"cloudBuy.team.setupTitle": "Konfigurowanie Chmury twojego zespołu",
"cloudBuy.team.setupSub": "Około 2 minut. Możesz pracować dalej; otworzysz ją tutaj, gdy będzie gotowa.",
"cloudBuy.team.unnamed": "Chmura twojego zespołu",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 53db7c0615..6368fbaaf2 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -227,6 +227,58 @@
"cloudBuy.one.email": "Receber um e-mail quando eu puder adicionar outro",
"cloudBuy.one.thanks": "Obrigado. Enviaremos um e-mail quando você puder adicionar outro Cloud.",
"cloudBuy.one.failed": "Não foi possível acessar o MausBot Cloud, então nada foi salvo. Tente novamente.",
+ "cloudBuy.color.slate": "Ardósia",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Dê um nome ao seu novo Cloud",
+ "cloudBuy.extra.nameSub": "Ele terá seus próprios bots, pessoas, apps e plano.",
+ "cloudBuy.extra.continue": "Continuar para o pagamento",
+ "cloudBuy.extra.setupTitle": "Configurando {name}",
+ "cloudBuy.extra.setupSub": "Cerca de 2 minutos. Pode continuar trabalhando; avisamos quando estiver pronto.",
+ "cloudBuy.extra.readySub": "Ele tem seus próprios bots, pessoas, apps e plano. Mude para ele pela borda esquerda da janela quando quiser.",
+ "cloudBuy.extra.lateSub": "Se você pagou, ele aparece aqui em alguns minutos. Se não, abra o pagamento de novo.",
+ "cloudBuy.extra.problem": "O pagamento de {name} não foi concluído. Atualize-o na sua página do plano.",
+ "cloudBuy.extra.signupsClosed": "Não é possível comprar novos Clouds agora. Tente mais tarde.",
+ "cloudBuy.extra.checkoutOpen": "Já existe um pagamento aberto para outro Cloud. Termine-o primeiro no seu navegador.",
+ "rail.label": "Onde seus bots vivem",
+ "rail.thisComputer": "Este computador",
+ "rail.settingUp": "{name}: configurando",
+ "rail.waiting": "{name}: aguardando pagamento",
+ "rail.attention": "{name}: precisa de você",
+ "rail.more": "Mostrar todos ({count})",
+ "rail.search": "Encontrar um Cloud",
+ "rail.noMatch": "Nada encontrado.",
+ "rail.add": "Adicionar um Cloud ou seu próprio servidor",
+ "rail.buy": "Comprar um Cloud",
+ "rail.buySub": "Um novo Cloud com seus próprios bots, pessoas, apps e plano, sempre ligado.",
+ "rail.own": "Adicionar seu próprio servidor",
+ "rail.ownSub": "Um que você aluga online, um Mac mini em casa ou um computador na sua rede Tailscale.",
+ "rail.ownLede": "Instale o OpenMausBot lá, e este app o abre como um Cloud. Os bots dele ficam nele.",
+ "rail.step1": "Instale o OpenMausBot nele",
+ "rail.step1Sub": "Em um terminal lá, com Node 24 ou mais recente:",
+ "rail.step2": "Abra uma janela de pareamento",
+ "rail.step2Sub": "Rode isto lá. Ele mostra um link de pareamento para este app:",
+ "rail.step3": "Conecte aqui",
+ "rail.step3Sub": "Copie o link que ele mostrou e cole aqui.",
+ "rail.paste": "Colar link de pareamento",
+ "rail.address": "Digitar o endereço",
+ "rail.copy": "Copiar",
+ "rail.copied": "Copiado",
+ "rail.back": "Voltar",
+ "rail.ownServer": "{name}, seu próprio servidor",
+ "rail.offline": "{name}: offline",
+ "rail.lastSeen": "{name}: offline, visto pela última vez {when}",
+ "rail.notConnected": "{name}: conecte-o a este app",
+ "rail.ownNetwork": "Acessível só pela própria rede",
+ "rail.update": "na {version}, a {latest} já saiu",
+ "rail.connectTitle": "Conectar {name}",
+ "rail.connectLede": "Ele já está conectado à sua conta. Abra uma janela de pareamento nele e cole aqui o link que ele mostrar.",
+ "placeLook.title": "Cor",
+ "placeLook.sub": "{name} aparece nesta cor no topo da barra lateral e no círculo dele na borda esquerda da janela.",
+ "placeLook.aria": "Cor de {name}",
+ "placeLook.member": "Só os administradores podem mudar a cor.",
+ "placeLook.signedOut": "Entre no MausBot Cloud para mudar a cor.",
+ "placeLook.unsupported": "A cor deste Cloud ainda não pode ser mudada pelo app.",
+ "placeLook.failed": "A cor não foi salva. Tente de novo.",
"cloudBuy.staging": "Homologação",
"cloudBuy.stagingHint": "Este app usa o MausBot Cloud de homologação: pagamentos e Clouds de teste, não reais.",
"cloudNotice.signIn.title": "Entre novamente para acessar o Cloud",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 8e0faf0a6a..168f84bb35 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -237,6 +237,58 @@
"cloudBuy.one.email": "Прислать мне письмо, когда можно будет добавить ещё один",
"cloudBuy.one.thanks": "Спасибо. Мы напишем вам, когда можно будет добавить ещё один Cloud.",
"cloudBuy.one.failed": "Не удалось связаться с MausBot Cloud, поэтому ничего не сохранено. Попробуйте ещё раз.",
+ "cloudBuy.color.slate": "Сланцевый",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Назовите новый Cloud",
+ "cloudBuy.extra.nameSub": "У него будут свои боты, люди, приложения и тариф.",
+ "cloudBuy.extra.continue": "Перейти к оплате",
+ "cloudBuy.extra.setupTitle": "Настраиваем {name}",
+ "cloudBuy.extra.setupSub": "Около 2 минут. Можете продолжать работу — мы сообщим, когда всё будет готово.",
+ "cloudBuy.extra.readySub": "У него свои боты, люди, приложения и тариф. Переключайтесь на него в любой момент у левого края окна.",
+ "cloudBuy.extra.lateSub": "Если вы оплатили, он появится здесь в течение нескольких минут. Если нет, откройте оплату повторно.",
+ "cloudBuy.extra.problem": "Оплата за {name} не прошла. Обновите её на странице тарифа.",
+ "cloudBuy.extra.signupsClosed": "Сейчас новые Cloud купить нельзя. Попробуйте позже.",
+ "cloudBuy.extra.checkoutOpen": "Оплата другого Cloud уже открыта. Сначала завершите её в браузере.",
+ "rail.label": "Где живут ваши боты",
+ "rail.thisComputer": "Этот компьютер",
+ "rail.settingUp": "{name}: настраивается",
+ "rail.waiting": "{name}: ждёт оплаты",
+ "rail.attention": "{name}: нужно ваше внимание",
+ "rail.more": "Показать все ({count})",
+ "rail.search": "Найти Cloud",
+ "rail.noMatch": "Ничего не найдено.",
+ "rail.add": "Добавить Cloud или свой сервер",
+ "rail.buy": "Купить Cloud",
+ "rail.buySub": "Новый Cloud со своими ботами, людьми, приложениями и тарифом, всегда включён.",
+ "rail.own": "Добавить свой сервер",
+ "rail.ownSub": "Арендованный в сети, Mac mini дома или компьютер в вашей сети Tailscale.",
+ "rail.ownLede": "Установите туда OpenMausBot, и это приложение откроет его как Cloud. Его боты останутся на нём.",
+ "rail.step1": "Установите на него OpenMausBot",
+ "rail.step1Sub": "В терминале на нём, с Node 24 или новее:",
+ "rail.step2": "Откройте окно сопряжения",
+ "rail.step2Sub": "Выполните это там. Команда выведет ссылку сопряжения для этого приложения:",
+ "rail.step3": "Подключите его здесь",
+ "rail.step3Sub": "Скопируйте выведенную ссылку и вставьте её сюда.",
+ "rail.paste": "Вставить ссылку сопряжения",
+ "rail.address": "Ввести адрес вместо этого",
+ "rail.copy": "Копировать",
+ "rail.copied": "Скопировано",
+ "rail.back": "Назад",
+ "rail.ownServer": "{name}, ваш собственный сервер",
+ "rail.offline": "{name}: не в сети",
+ "rail.lastSeen": "{name}: не в сети, последний раз был в сети {when}",
+ "rail.notConnected": "{name}: подключите его к этому приложению",
+ "rail.ownNetwork": "Доступен только из своей сети",
+ "rail.update": "версия {version}, вышла {latest}",
+ "rail.connectTitle": "Подключить {name}",
+ "rail.connectLede": "Он уже вошёл в ваш аккаунт. Откройте на нём окно сопряжения и вставьте сюда ссылку, которую он выведет.",
+ "placeLook.title": "Цвет",
+ "placeLook.sub": "{name} отображается этим цветом вверху боковой панели и в своём кружке у левого края окна.",
+ "placeLook.aria": "Цвет: {name}",
+ "placeLook.member": "Цвет могут менять только администраторы.",
+ "placeLook.signedOut": "Войдите в MausBot Cloud, чтобы изменить цвет.",
+ "placeLook.unsupported": "Цвет этого Cloud пока нельзя изменить в приложении.",
+ "placeLook.failed": "Цвет не сохранён. Попробуйте ещё раз.",
"cloudBuy.team.setupTitle": "Настройка Cloud вашей команды",
"cloudBuy.team.setupSub": "Около 2 минут. При желании продолжайте работу — когда облако будет готово, его можно будет открыть здесь.",
"cloudBuy.team.unnamed": "облако вашей команды",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index b6394dbe5f..13c7f16f54 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -4932,5 +4932,57 @@
"computer.problem.localNotReady": "Botlar bu bilgisayarı henüz kullanamaz. OpenMausBot'u yeniden başlatıp tekrar deneyin.",
"computer.problem.localNeedsApp": "Bir botun bu bilgisayarı kullanmasına yalnızca buradaki OpenMausBot uygulaması izin verebilir. Kullanmak için uygulamayı burada açın.",
"computer.problem.localWindows": "Botlar şu anda bu PC'yi kullanamıyor. OpenMausBot'u yeniden başlatın; işe yaramazsa Ayarlar → Tanılama'yı açın.",
- "computer.problem.localMac": "Botlar bu Mac'i henüz kullanamaz. Sistem Ayarları → Gizlilik ve Güvenlik'te Ekran Kaydı ve Erişilebilirlik altında OpenMausBot'a izin verildiğini kontrol edin, sonra yeniden başlatın."
+ "computer.problem.localMac": "Botlar bu Mac'i henüz kullanamaz. Sistem Ayarları → Gizlilik ve Güvenlik'te Ekran Kaydı ve Erişilebilirlik altında OpenMausBot'a izin verildiğini kontrol edin, sonra yeniden başlatın.",
+ "cloudBuy.color.slate": "Arduvaz",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Yeni Cloud'unuza ad verin",
+ "cloudBuy.extra.nameSub": "Kendi botları, kişileri, uygulamaları ve planı olur.",
+ "cloudBuy.extra.continue": "Ödemeye devam et",
+ "cloudBuy.extra.setupTitle": "{name} kuruluyor",
+ "cloudBuy.extra.setupSub": "Yaklaşık 2 dakika. İsterseniz çalışmaya devam edin; hazır olunca size haber veririz.",
+ "cloudBuy.extra.readySub": "Kendi botları, kişileri, uygulamaları ve planı var. Pencerenin sol kenarından istediğiniz zaman ona geçin.",
+ "cloudBuy.extra.lateSub": "Ödeme yaptıysanız birkaç dakika içinde burada görünür. Yapmadıysanız ödeme sayfasını yeniden açın.",
+ "cloudBuy.extra.problem": "{name} için ödeme gerçekleşmedi. Plan sayfanızda güncelleyin.",
+ "cloudBuy.extra.signupsClosed": "Şu anda yeni Cloud satın alınamıyor. Daha sonra tekrar deneyin.",
+ "cloudBuy.extra.checkoutOpen": "Başka bir Cloud için açık bir ödeme zaten var. Önce tarayıcınızda tamamlayın.",
+ "rail.label": "Botlarınızın yaşadığı yerler",
+ "rail.thisComputer": "Bu bilgisayar",
+ "rail.settingUp": "{name}: kuruluyor",
+ "rail.waiting": "{name}: ödeme bekleniyor",
+ "rail.attention": "{name}: size ihtiyaç var",
+ "rail.more": "Tümünü göster ({count})",
+ "rail.search": "Cloud bul",
+ "rail.noMatch": "Eşleşen yok.",
+ "rail.add": "Cloud veya kendi sunucunuzu ekleyin",
+ "rail.buy": "Cloud satın al",
+ "rail.buySub": "Kendi botları, kişileri, uygulamaları ve planı olan yeni bir Cloud, her zaman açık.",
+ "rail.own": "Kendi sunucunuzu ekleyin",
+ "rail.ownSub": "Çevrimiçi kiraladığınız biri, evdeki bir Mac mini ya da Tailscale ağınızdaki bir bilgisayar.",
+ "rail.ownLede": "Oraya OpenMausBot'u kurun; bu uygulama onu bir Cloud gibi açar. Botları onun üzerinde kalır.",
+ "rail.step1": "Üzerine OpenMausBot'u kurun",
+ "rail.step1Sub": "Oradaki bir terminalde, Node 24 veya daha yenisiyle:",
+ "rail.step2": "Bir eşleştirme penceresi açın",
+ "rail.step2Sub": "Bunu orada çalıştırın. Bu uygulama için bir eşleştirme bağlantısı yazdırır:",
+ "rail.step3": "Buraya bağlayın",
+ "rail.step3Sub": "Yazdırdığı bağlantıyı kopyalayın, sonra buraya yapıştırın.",
+ "rail.paste": "Eşleştirme bağlantısını yapıştır",
+ "rail.address": "Bunun yerine adresini girin",
+ "rail.copy": "Kopyala",
+ "rail.copied": "Kopyalandı",
+ "rail.back": "Geri",
+ "rail.ownServer": "{name}, kendi sunucunuz",
+ "rail.offline": "{name}: çevrimdışı",
+ "rail.lastSeen": "{name}: çevrimdışı, en son {when} görüldü",
+ "rail.notConnected": "{name}: bu uygulamaya bağlayın",
+ "rail.ownNetwork": "Yalnızca kendi ağından erişilebilir",
+ "rail.update": "{version} sürümünde, {latest} çıktı",
+ "rail.connectTitle": "Bağla: {name}",
+ "rail.connectLede": "Hesabınızla zaten oturum açmış durumda. Üzerinde bir eşleştirme penceresi açın, sonra yazdırdığı bağlantıyı buraya yapıştırın.",
+ "placeLook.title": "Renk",
+ "placeLook.sub": "{name}, kenar çubuğunun üstünde ve pencerenin sol kenarındaki dairesinde bu renkte görünür.",
+ "placeLook.aria": "{name} rengi",
+ "placeLook.member": "Rengi yalnızca yöneticileri değiştirebilir.",
+ "placeLook.signedOut": "Rengini değiştirmek için MausBot Cloud'da oturum açın.",
+ "placeLook.unsupported": "Bu Cloud'un rengi henüz uygulamadan değiştirilemez.",
+ "placeLook.failed": "Renk kaydedilmedi. Yeniden deneyin."
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index ddd9b349ca..0b54de0fa7 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -2906,5 +2906,57 @@
"place.action.addBoatKey": "Підключити Boat",
"place.view.vm.short": "Окремо від вашого екрана",
"place.view.browserOff.short": "Вимкнено",
- "place.view.browserOff.line": "Власний браузер бота вимкнено, тож він не може відкривати вебсторінки."
+ "place.view.browserOff.line": "Власний браузер бота вимкнено, тож він не може відкривати вебсторінки.",
+ "cloudBuy.color.slate": "Сланцевий",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Назвіть новий Cloud",
+ "cloudBuy.extra.nameSub": "У нього будуть власні боти, люди, застосунки й план.",
+ "cloudBuy.extra.continue": "Перейти до оплати",
+ "cloudBuy.extra.setupTitle": "Налаштовуємо {name}",
+ "cloudBuy.extra.setupSub": "Приблизно 2 хвилини. Можете працювати далі — ми повідомимо, коли все буде готово.",
+ "cloudBuy.extra.readySub": "У нього власні боти, люди, застосунки й план. Перемикайтеся на нього будь-коли біля лівого краю вікна.",
+ "cloudBuy.extra.lateSub": "Якщо ви оплатили, він з'явиться тут за кілька хвилин. Якщо ні, знову відкрийте оплату.",
+ "cloudBuy.extra.problem": "Оплата за {name} не пройшла. Оновіть її на сторінці плану.",
+ "cloudBuy.extra.signupsClosed": "Зараз нові Cloud купити не можна. Спробуйте пізніше.",
+ "cloudBuy.extra.checkoutOpen": "Оплата іншого Cloud уже відкрита. Спершу завершіть її в браузері.",
+ "rail.label": "Де живуть ваші боти",
+ "rail.thisComputer": "Цей комп'ютер",
+ "rail.settingUp": "{name}: налаштовується",
+ "rail.waiting": "{name}: чекає на оплату",
+ "rail.attention": "{name}: потрібна ваша увага",
+ "rail.more": "Показати всі ({count})",
+ "rail.search": "Знайти Cloud",
+ "rail.noMatch": "Нічого не знайдено.",
+ "rail.add": "Додати Cloud або власний сервер",
+ "rail.buy": "Купити Cloud",
+ "rail.buySub": "Новий Cloud із власними ботами, людьми, застосунками й планом, завжди увімкнений.",
+ "rail.own": "Додати власний сервер",
+ "rail.ownSub": "Орендований в інтернеті, Mac mini вдома або комп'ютер у вашій мережі Tailscale.",
+ "rail.ownLede": "Установіть туди OpenMausBot, і цей застосунок відкриватиме його як Cloud. Його боти залишаться на ньому.",
+ "rail.step1": "Установіть на нього OpenMausBot",
+ "rail.step1Sub": "У терміналі на ньому, з Node 24 або новішим:",
+ "rail.step2": "Відкрийте вікно прив'язки",
+ "rail.step2Sub": "Виконайте це там. Команда виведе посилання прив'язки для цього застосунку:",
+ "rail.step3": "Під'єднайте його тут",
+ "rail.step3Sub": "Скопіюйте виведене посилання й вставте його сюди.",
+ "rail.paste": "Вставити посилання прив'язки",
+ "rail.address": "Натомість ввести адресу",
+ "rail.copy": "Копіювати",
+ "rail.copied": "Скопійовано",
+ "rail.back": "Назад",
+ "rail.ownServer": "{name}, ваш власний сервер",
+ "rail.offline": "{name}: не в мережі",
+ "rail.lastSeen": "{name}: не в мережі, востаннє в мережі {when}",
+ "rail.notConnected": "{name}: під’єднайте його до цього застосунку",
+ "rail.ownNetwork": "Доступний лише з власної мережі",
+ "rail.update": "версія {version}, вийшла {latest}",
+ "rail.connectTitle": "Під’єднати {name}",
+ "rail.connectLede": "Він уже ввійшов у ваш обліковий запис. Відкрийте на ньому вікно прив'язки й вставте сюди посилання, яке він виведе.",
+ "placeLook.title": "Колір",
+ "placeLook.sub": "{name} показується цим кольором угорі бічної панелі та у своєму кружечку біля лівого краю вікна.",
+ "placeLook.aria": "Колір: {name}",
+ "placeLook.member": "Колір можуть змінювати лише адміністратори.",
+ "placeLook.signedOut": "Увійдіть у MausBot Cloud, щоб змінити колір.",
+ "placeLook.unsupported": "Колір цього Cloud поки не можна змінити в застосунку.",
+ "placeLook.failed": "Колір не збережено. Спробуйте ще раз."
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 5eecedca0c..81ff0124c2 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -4932,5 +4932,57 @@
"computer.problem.localNotReady": "Bot chưa dùng được máy tính này. Hãy khởi động lại OpenMausBot rồi thử lại.",
"computer.problem.localNeedsApp": "Chỉ ứng dụng OpenMausBot trên máy tính này mới cho bot dùng nó được. Hãy mở ứng dụng ở đây để dùng.",
"computer.problem.localWindows": "Hiện bot không dùng được PC này. Hãy khởi động lại OpenMausBot, nếu vẫn không được thì mở Cài đặt → Chẩn đoán.",
- "computer.problem.localMac": "Bot chưa dùng được máy Mac này. Hãy kiểm tra OpenMausBot đã được cho phép ở Ghi màn hình và Trợ năng trong Cài đặt hệ thống → Quyền riêng tư & Bảo mật, rồi khởi động lại."
+ "computer.problem.localMac": "Bot chưa dùng được máy Mac này. Hãy kiểm tra OpenMausBot đã được cho phép ở Ghi màn hình và Trợ năng trong Cài đặt hệ thống → Quyền riêng tư & Bảo mật, rồi khởi động lại.",
+ "cloudBuy.color.slate": "Xám đá",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "Đặt tên cho Cloud mới",
+ "cloudBuy.extra.nameSub": "Cloud này có bot, thành viên, ứng dụng và gói riêng.",
+ "cloudBuy.extra.continue": "Tiếp tục thanh toán",
+ "cloudBuy.extra.setupTitle": "Đang thiết lập {name}",
+ "cloudBuy.extra.setupSub": "Khoảng 2 phút. Bạn cứ tiếp tục làm việc; chúng tôi sẽ báo khi Cloud sẵn sàng.",
+ "cloudBuy.extra.readySub": "Cloud này có bot, thành viên, ứng dụng và gói riêng. Chuyển sang nó bất cứ lúc nào từ cạnh trái cửa sổ.",
+ "cloudBuy.extra.lateSub": "Nếu bạn đã thanh toán, nó sẽ hiện ở đây trong vài phút. Nếu chưa, hãy mở lại trang thanh toán.",
+ "cloudBuy.extra.problem": "Thanh toán cho {name} không thành công. Hãy cập nhật trên trang gói của bạn.",
+ "cloudBuy.extra.signupsClosed": "Hiện chưa thể mua Cloud mới. Hãy thử lại sau.",
+ "cloudBuy.extra.checkoutOpen": "Đã có một trang thanh toán cho Cloud khác đang mở. Hãy hoàn tất nó trong trình duyệt trước.",
+ "rail.label": "Nơi các bot của bạn sống",
+ "rail.thisComputer": "Máy tính này",
+ "rail.settingUp": "{name}: đang thiết lập",
+ "rail.waiting": "{name}: đang chờ thanh toán",
+ "rail.attention": "{name}: cần bạn",
+ "rail.more": "Hiện tất cả ({count})",
+ "rail.search": "Tìm Cloud",
+ "rail.noMatch": "Không có kết quả.",
+ "rail.add": "Thêm Cloud hoặc máy chủ của riêng bạn",
+ "rail.buy": "Mua Cloud",
+ "rail.buySub": "Một Cloud mới với bot, thành viên, ứng dụng và gói riêng, luôn bật.",
+ "rail.own": "Thêm máy chủ của riêng bạn",
+ "rail.ownSub": "Một máy chủ bạn thuê trực tuyến, một Mac mini ở nhà hoặc một máy tính trong mạng Tailscale của bạn.",
+ "rail.ownLede": "Cài OpenMausBot ở đó, và ứng dụng này sẽ mở nó như một Cloud. Bot của nó vẫn ở trên đó.",
+ "rail.step1": "Cài OpenMausBot lên đó",
+ "rail.step1Sub": "Trong terminal ở đó, với Node 24 trở lên:",
+ "rail.step2": "Mở cửa sổ ghép nối",
+ "rail.step2Sub": "Chạy lệnh này ở đó. Nó in ra một liên kết ghép nối cho ứng dụng này:",
+ "rail.step3": "Kết nối tại đây",
+ "rail.step3Sub": "Sao chép liên kết nó in ra, rồi dán vào đây.",
+ "rail.paste": "Dán liên kết ghép nối",
+ "rail.address": "Nhập địa chỉ thay vào đó",
+ "rail.copy": "Sao chép",
+ "rail.copied": "Đã sao chép",
+ "rail.back": "Quay lại",
+ "rail.ownServer": "{name}, máy chủ của riêng bạn",
+ "rail.offline": "{name}: ngoại tuyến",
+ "rail.lastSeen": "{name}: ngoại tuyến, thấy lần cuối {when}",
+ "rail.notConnected": "{name}: kết nối nó với ứng dụng này",
+ "rail.ownNetwork": "Chỉ truy cập được từ mạng riêng của nó",
+ "rail.update": "đang ở {version}, đã có {latest}",
+ "rail.connectTitle": "Kết nối {name}",
+ "rail.connectLede": "Nó đã đăng nhập bằng tài khoản của bạn. Hãy mở cửa sổ ghép nối trên đó, rồi dán liên kết nó in ra vào đây.",
+ "placeLook.title": "Màu",
+ "placeLook.sub": "{name} hiện màu này ở đầu thanh bên và trên vòng tròn của nó ở cạnh trái cửa sổ.",
+ "placeLook.aria": "Màu của {name}",
+ "placeLook.member": "Chỉ quản trị viên mới đổi được màu này.",
+ "placeLook.signedOut": "Đăng nhập MausBot Cloud để đổi màu này.",
+ "placeLook.unsupported": "Chưa thể đổi màu của Cloud này từ ứng dụng.",
+ "placeLook.failed": "Chưa lưu được màu. Hãy thử lại."
}
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 80056ec2f1..c258f1fe37 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4316,5 +4316,57 @@
"computer.problem.localNotReady": "機器人目前還無法使用這台電腦。請重新啟動 OpenMausBot 後再試一次。",
"computer.problem.localNeedsApp": "只有這台電腦上的 OpenMausBot 應用程式能讓機器人使用它。請在這裡開啟應用程式來使用。",
"computer.problem.localWindows": "機器人目前無法使用這台 PC。請重新啟動 OpenMausBot;若仍無法解決,請開啟「設定 → 診斷」。",
- "computer.problem.localMac": "機器人目前還無法使用這台 Mac。請到「系統設定 → 隱私權與安全性」確認 OpenMausBot 已在「螢幕錄製」和「輔助使用」中獲得允許,然後重新啟動它。"
+ "computer.problem.localMac": "機器人目前還無法使用這台 Mac。請到「系統設定 → 隱私權與安全性」確認 OpenMausBot 已在「螢幕錄製」和「輔助使用」中獲得允許,然後重新啟動它。",
+ "cloudBuy.color.slate": "石板灰",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "為新的 Cloud 命名",
+ "cloudBuy.extra.nameSub": "它會有自己的機器人、成員、應用程式和方案。",
+ "cloudBuy.extra.continue": "前往付款",
+ "cloudBuy.extra.setupTitle": "正在設定 {name}",
+ "cloudBuy.extra.setupSub": "大約 2 分鐘。你可以繼續工作,準備好後我們會通知你。",
+ "cloudBuy.extra.readySub": "它有自己的機器人、成員、應用程式和方案。隨時都能從視窗左側切換過去。",
+ "cloudBuy.extra.lateSub": "如果你已付款,幾分鐘內就會顯示在這裡。如果還沒有,請重新開啟付款頁面。",
+ "cloudBuy.extra.problem": "{name} 的付款沒有成功。請在方案頁面更新付款資訊。",
+ "cloudBuy.extra.signupsClosed": "目前無法購買新的 Cloud。請稍後再試。",
+ "cloudBuy.extra.checkoutOpen": "另一個 Cloud 的付款頁面已經開啟。請先在瀏覽器中完成付款。",
+ "rail.label": "你的機器人在哪裡",
+ "rail.thisComputer": "這台電腦",
+ "rail.settingUp": "{name}:設定中",
+ "rail.waiting": "{name}:等待付款",
+ "rail.attention": "{name}:需要你處理",
+ "rail.more": "顯示全部({count})",
+ "rail.search": "尋找 Cloud",
+ "rail.noMatch": "沒有符合的項目。",
+ "rail.add": "新增 Cloud 或你自己的伺服器",
+ "rail.buy": "購買 Cloud",
+ "rail.buySub": "全新的 Cloud,擁有自己的機器人、成員、應用程式和方案,隨時在線。",
+ "rail.own": "新增你自己的伺服器",
+ "rail.ownSub": "線上租用的伺服器、家裡的 Mac mini,或你 Tailscale 網路中的電腦。",
+ "rail.ownLede": "在那裡安裝 OpenMausBot,這個 App 就能像 Cloud 一樣開啟它。它的機器人會留在上面。",
+ "rail.step1": "在上面安裝 OpenMausBot",
+ "rail.step1Sub": "在那台電腦的終端機中,使用 Node 24 或更新版本:",
+ "rail.step2": "開啟配對視窗",
+ "rail.step2Sub": "在那裡執行這個指令。它會顯示這個 App 的配對連結:",
+ "rail.step3": "在這裡連線",
+ "rail.step3Sub": "複製它顯示的連結,然後貼到這裡。",
+ "rail.paste": "貼上配對連結",
+ "rail.address": "改為輸入位址",
+ "rail.copy": "複製",
+ "rail.copied": "已複製",
+ "rail.back": "返回",
+ "rail.ownServer": "{name}(你自己的伺服器)",
+ "rail.offline": "{name}:離線",
+ "rail.lastSeen": "{name}:離線,上次在線於{when}",
+ "rail.notConnected": "{name}:將它連線到這個 App",
+ "rail.ownNetwork": "只能從它自己的網路連線",
+ "rail.update": "目前是 {version},{latest} 已推出",
+ "rail.connectTitle": "連線 {name}",
+ "rail.connectLede": "它已經用你的帳號登入。在它上面開啟配對視窗,再把它顯示的連結貼到這裡。",
+ "placeLook.title": "顏色",
+ "placeLook.sub": "{name} 會以這個顏色顯示在側邊欄頂端,以及視窗左側它的圓圈上。",
+ "placeLook.aria": "{name} 的顏色",
+ "placeLook.member": "只有管理員可以更改顏色。",
+ "placeLook.signedOut": "登入 MausBot Cloud 才能更改顏色。",
+ "placeLook.unsupported": "目前還無法在 App 中更改這個 Cloud 的顏色。",
+ "placeLook.failed": "顏色沒有儲存。請再試一次。"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 837ab82ccc..d1fd7039a9 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -3304,5 +3304,57 @@
"place.action.addBoatKey": "连接 Boat",
"place.view.vm.short": "与你的屏幕分开",
"place.view.browserOff.short": "已关闭",
- "place.view.browserOff.line": "机器人自己的浏览器已关闭,因此无法打开网页。"
+ "place.view.browserOff.line": "机器人自己的浏览器已关闭,因此无法打开网页。",
+ "cloudBuy.color.slate": "石板灰",
+ "cloudBuy.extra.defaultName": "Cloud {number}",
+ "cloudBuy.extra.nameTitle": "为新的 Cloud 命名",
+ "cloudBuy.extra.nameSub": "它会有自己的机器人、成员、应用和方案。",
+ "cloudBuy.extra.continue": "前往付款",
+ "cloudBuy.extra.setupTitle": "正在设置 {name}",
+ "cloudBuy.extra.setupSub": "大约 2 分钟。你可以继续工作,准备好后我们会通知你。",
+ "cloudBuy.extra.readySub": "它有自己的机器人、成员、应用和方案。随时都可以从窗口左侧切换过去。",
+ "cloudBuy.extra.lateSub": "如果你已付款,几分钟内就会显示在这里。如果还没有,请重新打开付款页面。",
+ "cloudBuy.extra.problem": "{name} 的付款没有成功。请在方案页面更新付款信息。",
+ "cloudBuy.extra.signupsClosed": "目前无法购买新的 Cloud。请稍后再试。",
+ "cloudBuy.extra.checkoutOpen": "另一个 Cloud 的付款页面已经打开。请先在浏览器中完成付款。",
+ "rail.label": "你的机器人在哪里",
+ "rail.thisComputer": "这台电脑",
+ "rail.settingUp": "{name}:设置中",
+ "rail.waiting": "{name}:等待付款",
+ "rail.attention": "{name}:需要你处理",
+ "rail.more": "显示全部({count})",
+ "rail.search": "查找 Cloud",
+ "rail.noMatch": "没有匹配的项目。",
+ "rail.add": "添加 Cloud 或你自己的服务器",
+ "rail.buy": "购买 Cloud",
+ "rail.buySub": "全新的 Cloud,拥有自己的机器人、成员、应用和方案,始终在线。",
+ "rail.own": "添加你自己的服务器",
+ "rail.ownSub": "在线租用的服务器、家里的 Mac mini,或你 Tailscale 网络中的电脑。",
+ "rail.ownLede": "在那里安装 OpenMausBot,这个应用就能像 Cloud 一样打开它。它的机器人会留在上面。",
+ "rail.step1": "在上面安装 OpenMausBot",
+ "rail.step1Sub": "在那台电脑的终端中,使用 Node 24 或更新版本:",
+ "rail.step2": "打开配对窗口",
+ "rail.step2Sub": "在那里运行这个命令。它会显示这个应用的配对链接:",
+ "rail.step3": "在这里连接",
+ "rail.step3Sub": "复制它显示的链接,然后粘贴到这里。",
+ "rail.paste": "粘贴配对链接",
+ "rail.address": "改为输入地址",
+ "rail.copy": "复制",
+ "rail.copied": "已复制",
+ "rail.back": "返回",
+ "rail.ownServer": "{name}(你自己的服务器)",
+ "rail.offline": "{name}:离线",
+ "rail.lastSeen": "{name}:离线,上次在线于{when}",
+ "rail.notConnected": "{name}:将它连接到这个应用",
+ "rail.ownNetwork": "只能从它自己的网络访问",
+ "rail.update": "当前为 {version},{latest} 已发布",
+ "rail.connectTitle": "连接 {name}",
+ "rail.connectLede": "它已经用你的账号登录。在它上面打开配对窗口,再把它显示的链接粘贴到这里。",
+ "placeLook.title": "颜色",
+ "placeLook.sub": "{name} 会以这个颜色显示在侧边栏顶部,以及窗口左侧它的圆圈上。",
+ "placeLook.aria": "{name} 的颜色",
+ "placeLook.member": "只有管理员可以更改颜色。",
+ "placeLook.signedOut": "登录 MausBot Cloud 才能更改颜色。",
+ "placeLook.unsupported": "暂时还无法在应用中更改这个 Cloud 的颜色。",
+ "placeLook.failed": "颜色没有保存。请重试。"
}
diff --git a/src/styles.css b/src/styles.css
index b7e5bf4108..02242e03ea 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1519,6 +1519,22 @@ body {
backdrop-filter: none;
mask-image: none;
}
+/* The colour of the place on screen (PlaceTint), faint, from the very top of the sidebar to just below its head, under
+ everything there: the head's words and controls stay on what is still almost the plain panel. Dark skins take a
+ little more of it to show at all. Reduced transparency: a thin solid line at the top instead; forced colours: none. */
+.place-tint {
+ height: calc(var(--glass-top, 48px) + 16px);
+ background: linear-gradient(to bottom, color-mix(in srgb, var(--place-tint) var(--place-tint-strength, 16%), transparent), transparent);
+}
+@container style(--code-color-scheme: dark) {
+ .place-tint { --place-tint-strength: 26%; }
+}
+@media (prefers-reduced-transparency: reduce) {
+ .place-tint { height: 3px; background: var(--place-tint); }
+}
+@media (forced-colors: active) {
+ .place-tint { display: none; }
+}
/* The frame publishes its bars' heights. Rows rest clear of the glass,
keyboard focus scrolls them clear, and the scrollbar runs only between the
bars (a bar over it would swallow the drag). */
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 9a5d5b2c10..b79fff24d5 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -163,6 +163,33 @@ const __APP_VERSION__: string;
menu: (options?: { from?: "howto" }) => Promise<void>;
/** One plain line for the next page, served once: a team this person is no longer in. */
line?: () => Promise<{ kind: "left"; name: string } | null>;
+ /** The rail's circles, for this app's page and a hosted Cloud's only (empty elsewhere, and with fewer than two
+ * places). Absent on an older app. */
+ places?: () => Promise<import("../../electron/cloud-rail.mjs").RailState>;
+ /** Opens a circle main listed, by its id, through main's own switch: only from the person's click. */
+ open?: (id: string) => Promise<unknown>;
+ /** +'s fixed choices: buy a Cloud (this computer's own sheet), paste a server's pairing link, or type its address. */
+ add?: (choice: "cloud" | "link" | "address") => Promise<unknown>;
+ /** The colour of the place this page is, and whether it can be changed here (null on this computer's page).
+ * Absent on an older app. */
+ look?: () => Promise<import("../../electron/place-look.mjs").PlaceLook | null>;
+ /** That place's colour, from the person's click: one of the six swatches, or null for none. */
+ color?: (swatch: import("../../electron/cloud-list.mjs").CloudSwatch | null) => Promise<{ outcome: import("../../electron/place-look.mjs").PlaceColorOutcome; look: import("../../electron/place-look.mjs").PlaceLook | null }>;
+ /** Main's word that the places or the sign-in changed: read them again. */
+ onChanged?: (callback: () => void) => () => void;
+ };
+ /** Buying another Cloud from the rail's +, on this app's page or a hosted Cloud's; absent on an older app. */
+ cloudAdd?: {
+ state(): Promise<import("../../electron/cloud-rail.mjs").AddCloudView>;
+ /** Opens that plan's checkout in the browser, for a Cloud of this name and swatch; only from the person's click. */
+ start(tier: string, name: string, color: import("../../electron/cloud-list.mjs").CloudSwatch | null): Promise<{ outcome: "opened" | "unsupported" | "failed" } | { outcome: "blocked"; blocked: import("../../electron/cloud-account.mjs").CloudAddBlock }>;
+ reopen(): Promise<boolean>;
+ copyLink(): Promise<boolean>;
+ /** Opens the Cloud just bought, once it is ready. */
+ open(): Promise<void>;
+ interest(): Promise<void>;
+ /** The sheet is open on this page (main then says "ready" here, not with a notification). */
+ sheet(open: boolean): Promise<void>;
};
/** Saved servers and the active one (desktop Server menu). Present on
* the local server's UI; a remote server's page sees a reduced bridge. */