Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud rail: a Cloud that isn't running shows its state and never hangs; Remove from list (#3908)
Milind Soni8c960af7b8bd
diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjsindex c399b0105e..8f9692c10a 100644--- a/electron/cloud-account-clouds.node-test.mjs+++ b/electron/cloud-account-clouds.node-test.mjs@@ -19,7 +19,8 @@ const grant = (origin) => ({ cloudContractVersion: 1, origin, code: "ABCD-EFGH-Jasync 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" }], organization: () => [404, { error: "not_found" }] };+ pairing: () => [200, grant(HOME)], add: () => [404, { error: "not_found" }], patch: () => [404, { error: "not_found" }], organization: () => [404, { error: "not_found" }],+ hide: () => [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;@@ -32,6 +33,7 @@ async function admin(t) {if (req.url === "/api/cloud/desktop/clouds" && req.method === "POST") return send(f.add(parsed));if (req.url === "/api/cloud/desktop/organizations" && req.method === "POST") return send(f.organization(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.startsWith("/api/cloud/desktop/clouds/") && req.url.endsWith("/hide") && req.method === "POST") return send(f.hide(decodeURIComponent(req.url.slice("/api/cloud/desktop/clouds/".length, -"/hide".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" }]);});@@ -219,6 +221,32 @@ test("a Cloud's colour is the Admin's: PATCH with the swatch, then the session rawait assert.rejects(f.client.setCloudColor("../c-a", "blue"), /Invalid Cloud color/);});+test("Remove from list: only a Cloud the session says is removable is asked about, by its id, then the session is read again; the Admin's no, a Cloud gone and an older Admin are said plainly", async t => {+ const f = await admin(t);+ const ENDED = entry({ id: "c-old", name: "Old Cloud", status: "ended", origin: "https://omb-c-old.fly.dev", deleteAfter: NOW + 2 * 86400_000, removable: true });+ f.session = { ...f.session, clouds: [PRIMARY, entry(), ENDED, entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "owner", origin: TEAM, status: "ended", removable: true })] };+ const state = await f.client.start();+ assert.deepEqual(state.clouds.map(cloud => [cloud.id, cloud.removable ?? false, cloud.deleteAfter ?? null]),+ [["c-home", false, null], ["c-a", false, null], ["c-old", true, NOW + 2 * 86400_000], ["c-team", false, null]], "a team's Cloud is never removable here, whatever an Admin says");+ // Never asked about a Cloud the session doesn't say is removable: a running one, a team's, or one not listed.+ for (const id of ["c-a", "c-team", "c-home", "c-gone"]) assert.deepEqual(await f.client.hideCloud(id), { outcome: "unsupported" }, id);+ assert.equal(f.requests.some(row => row.route.endsWith("/hide")), false, "none of those reached the Admin");+ await assert.rejects(f.client.hideCloud("../c-old"), /Invalid Cloud to remove/);+ f.hide = (id) => { f.session = { ...f.session, clouds: f.session.clouds.filter(cloud => cloud.id !== id) }; return [200, { cloudContractVersion: 1, hidden: true }]; };+ const reads = () => f.requests.filter(row => row.route === "/api/cloud/desktop/session").length, before = reads();+ assert.deepEqual(await f.client.hideCloud("c-old"), { outcome: "removed" });+ assert.deepEqual(f.requests.find(row => row.route.endsWith("/hide")), { route: "/api/cloud/desktop/clouds/c-old/hide", method: "POST", body: {} });+ assert.equal(reads(), before + 1, "the session is read again, so every list here follows the Admin");+ assert.deepEqual(f.client.state().clouds.map(cloud => cloud.id), ["c-home", "c-a", "c-team"]);+ const again = (answer) => { f.session = { ...f.session, clouds: [PRIMARY, ENDED] }; f.hide = () => answer; return f.client.refresh().then(() => f.client.hideCloud("c-old")); };+ assert.deepEqual(await again([409, { error: "not_removable", errorDescription: "Only a Cloud of your own that has ended…" }]), { outcome: "refused" });+ assert.deepEqual(await again([404, { error: "not_found", errorDescription: "There is no such Cloud on your account." }]), { outcome: "gone" });+ for (const answer of [[404, { error: "Not found." }], [405, { error: "invalid_method" }], [501, { error: "unsupported" }]]) {+ assert.deepEqual(await again(answer), { outcome: "unsupported" }, JSON.stringify(answer));+ }+ assert.deepEqual(await again([500, { error: "server_error" }]), { outcome: "failed" });+});+const PLAN = "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", ORGANIZATION = "3c4d5e6f-7a8b-4c9d-8e1f-2a3b4c5d6e7f";test("a new organization on the Team plan this account pays for: its name and swatch go to the Admin, nothing opens, and the session is read again", async t => {const f = await admin(t);diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex 2279d44db7..b6b931633c 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -1,3 +1,6 @@+/** Remove from list's answer: done (`removed`), refused by the Admin now, the Cloud no longer theirs (`gone`), an Admin+ * without it (`unsupported`), or no answer (`failed`). */+export type CloudRemoveOutcome = "removed" | "refused" | "gone" | "unsupported" | "failed";export interface CloudAccountState {status: "signed-out" | "connecting" | "connected" | "reauth-required" | "unavailable";message?: string;@@ -279,6 +282,8 @@ export interface CloudAccountClient {addOrganization(input: { name: string; color?: import("./cloud-list.mjs").CloudSwatch | null }): Promise<OrganizationAddResult>;/** 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" }>;+ /** Remove from list: one of the person's own Clouds the session says is `removable` leaves their list on the Admin. */+ hideCloud(cloudId: string): Promise<{ outcome: CloudRemoveOutcome }>;/** 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. */diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex 042af41a67..31af07c70d 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -741,6 +741,26 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (grant === signedIn) await refresh().catch(() => {});return { outcome: "saved" };},+ /** Remove from list (POST clouds/:id/hide, contract v1): one of the person's own Clouds the verified session says they may+ * take off their list (`removable`: it ended, or was never paid for). Only the list changes on the Admin; its files still go+ * when they were going to. `removed` once the Admin did (the session is read again, so every list here follows); `refused`+ * when it says that Cloud can't be removed now; `gone` when it is not theirs any more; `unsupported` from an Admin without+ * Remove from list (whose session never says `removable`). */+ async hideCloud(cloudId) {+ if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId)) throw new Error("Invalid Cloud to remove.");+ const signedIn = grant;+ if (!signedIn || state().status !== "connected") return { outcome: "failed" };+ if (!value.clouds?.some(cloud => cloud.id === cloudId && cloud.removable === true)) return { outcome: "unsupported" };+ try { await request(`clouds/${encodeURIComponent(cloudId)}/hide`, { method: "POST", body: {}, token: signedIn.token }); } catch (error) {+ if (signInEnded(error)) { await refresh().catch(() => {}); return { outcome: "failed" }; }+ if (!error?.opaque && error?.code === "not_removable") { await refresh().catch(() => {}); return { outcome: "refused" }; }+ if (!error?.opaque && error?.code === "not_found") { await refresh().catch(() => {}); return { outcome: "gone" }; }+ if ([404, 405, 501].includes(error?.status)) return { outcome: "unsupported" };+ return { outcome: "failed" };+ }+ if (grant === signedIn) await refresh().catch(() => {});+ return { outcome: "removed" };+ },/** 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;diff --git a/electron/cloud-first-open.node-test.mjs b/electron/cloud-first-open.node-test.mjsindex 0023afbbcb..a16b230452 100644--- a/electron/cloud-first-open.node-test.mjs+++ b/electron/cloud-first-open.node-test.mjs@@ -158,11 +158,15 @@ test("a payment the Admin is still confirming shows the setup screen too, at its});test("nothing to open (no Cloud, or not signed in): asking says so, as before, and the window stays where it is", async () => {- for (const state of [{ status: "connected", account: ACCOUNT }, { status: "signed-out" }, ready({ status: "stopped" })]) {+ for (const state of [{ status: "connected", account: ACCOUNT }, { status: "signed-out" }]) {const w = world({ state });await assert.rejects(w.home.openCloud(), /not ready/);assert.deepEqual([w.went, w.fetched, w.home.asking()], [[], [], false], JSON.stringify(state));}+ // A Cloud the Admin says isn't running is something to say, on this computer's screen: never looked up, never dialled.+ const w = world({ state: ready({ status: "stopped" }) });+ await w.home.openCloud();+ assert.deepEqual([w.home.view(), w.went, w.fetched, w.home.asking()], [{ screen: "plan", machine: "stopped" }, [[SCREEN, null]], [], true]);});test("going somewhere else from the setup screen lets My Cloud go: the Server menu's choice stands when it becomes ready", async () => {diff --git a/electron/cloud-list.d.mts b/electron/cloud-list.d.mtsindex 9918b410e8..e328962bb8 100644--- a/electron/cloud-list.d.mts+++ b/electron/cloud-list.d.mts@@ -25,7 +25,16 @@ export interface CloudListEntry {lastSeenAt?: number;/** The OpenMausBot version it runs, for an update reminder. */version?: string;+ /** Ended, stopped or with a payment problem, its files still kept: when they are deleted (ms). */+ deleteAfter?: number;+ /** Its owner may take it off their list (one of their own, in no team, that ended or was never paid for): the Admin's word. */+ removable?: true;+ /** A Ready Cloud whose plan sleeps: whether it is asleep now. */+ power?: import("./cloud-power.mjs").CloudPower;}+/** What this app says of a listed Cloud it doesn't open: ended, its checkout not finished, a payment problem, or being set up. */+export type CloudState = "ended" | "checkout" | "payment" | "setup";+export declare function cloudState(cloud: Pick<CloudListEntry, "status"> | null | undefined): CloudState | null;/*** The account's own plan's renewal, as the Admin says it for the account that pays (display only): a free trial (`trial`), its* renewal off (`cancelled`), when it renews (`renewsAt`) or, once cancelled, ends (`endsAt`; null: the end of the period paiddiff --git a/electron/cloud-list.mjs b/electron/cloud-list.mjsindex 440fc348eb..8af4fda7bf 100644--- a/electron/cloud-list.mjs+++ b/electron/cloud-list.mjs@@ -18,6 +18,8 @@ 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" });+/** The statuses of a Cloud that isn't running: its files' day and Remove from list are said only for these. */+const DEAD = Object.freeze(["ended", "stopped", "payment_problem"]);/** 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 });@@ -57,9 +59,23 @@ function parseCloudEntry(input) {const version = typeof input.version === "string" && VERSION.test(input.version) ? input.version : null;// Additive (Oct 30): as `cloud.power`, for a Ready Cloud whose plan sleeps; this app never reaches one the Admin says is asleep.const power = input.status === "ready" ? parseCloudPower(input.power) : null;+ // Additive (Oct 30): when a Cloud that isn't running has its kept files deleted, and whether its owner may take it off their+ // list (an Admin with Remove from list says so only for one of their own, in no team, that ended or was never paid for).+ const deleteAfter = DEAD.includes(input.status) && Number.isSafeInteger(input.deleteAfter) && input.deleteAfter > 0 ? input.deleteAfter : null;+ const removable = input.removable === true && DEAD.includes(input.status) && managed && input.role === "owner" && teamId === 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 } : {}), ...(power ? { power } : {}) };+ primary: input.primary, managed, ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}), ...(power ? { power } : {}),+ ...(deleteAfter ? { deleteAfter } : {}), ...(removable ? { removable: true } : {}) };+}++/** What this app says of a listed Cloud it doesn't open, on this computer's own screen (never by its address): it has ended+ * (stopped too), its checkout wasn't finished, its payment has a problem, or it is being set up. Null for one that opens:+ * ready, or offline (its own screen then says it doesn't answer). */+export function cloudState(cloud) {+ const status = cloud?.status;+ return status === "ended" || status === "stopped" ? "ended" : status === "checkout" ? "checkout" : status === "payment_problem" ? "payment"+ : status === "setting_up" ? "setup" : null;}/** An OpenMausBot release as the Admin names it ("0.1.130"), or null: anything else is no version at all. */diff --git a/electron/cloud-list.node-test.mjs b/electron/cloud-list.node-test.mjsindex 3a0dc937e9..a1661a713d 100644--- a/electron/cloud-list.node-test.mjs+++ b/electron/cloud-list.node-test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { cloudMachine, cloudSetupProgress, listedColors, MAX_CLOUDS, olderRelease, otherOwnClouds, ownCloudPlaces, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion, signedInServers, swatchColor } from "./cloud-list.mjs";+import { cloudMachine, cloudSetupProgress, cloudState, listedColors, MAX_CLOUDS, olderRelease, otherOwnClouds, ownCloudPlaces, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion, signedInServers, swatchColor } from "./cloud-list.mjs";import environments from "./environments.cjs";import { createHomePlaces } from "./home-places.mjs";@@ -40,6 +40,24 @@ test("each Cloud's `power` as the Admin says it of a Ready Cloud whose plan sleeassert.equal(parseCloudList([cloud({ status: "stopped", power })])[0].power, undefined, "only a Ready Cloud sleeps or wakes");});+test("a Cloud that isn't running: the day its kept files go, and whether its owner may take it off their list, only as the Admin says it of one that fits", () => {+ const day = 1_762_000_000_000;+ const [ended] = parseCloudList([cloud({ status: "ended", deleteAfter: day, removable: true })]);+ assert.deepEqual([ended.deleteAfter, ended.removable], [day, true]);+ assert.deepEqual(parseCloudList([cloud({ status: "payment_problem", removable: true })])[0].removable, true, "never paid for");+ for (const [over, why] of [+ [{ status: "ready", deleteAfter: day, removable: true }, "a running Cloud has neither"], [{ status: "checkout", origin: null, removable: true }, "a checkout that can still be paid"],+ [{ status: "ended", removable: "yes" }, "only true"], [{ status: "ended", role: "admin", removable: true }, "not their own"],+ [{ status: "ended", teamId: "team-acme", removable: true }, "a team's Cloud"], [{ status: "ended", deleteAfter: -5 }, "a malformed day"],+ [{ status: "ended", deleteAfter: "soon" }, "a malformed day"],+ ]) {+ const [read] = parseCloudList([cloud(over)]);+ assert.deepEqual([read.deleteAfter, read.removable], [undefined, undefined], why);+ }+ assert.deepEqual(["ended", "stopped", "checkout", "payment_problem", "setting_up", "ready", "offline", undefined].map(status => cloudState(status ? { status } : null)),+ ["ended", "ended", "checkout", "payment", "setup", null, null, null], "what this app says of each: a Cloud that opens says nothing");+});+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" } });diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mtsindex 457c94c557..a2a9872165 100644--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@ -30,6 +30,10 @@ export interface RailPlace {/** Its colour is changed from the rail (a right-click on its circle): the swatch it shows, and why only its admins or a* sign-in may change it, if so. None for a Cloud still being made. */paint?: { swatch: import("./cloud-list.mjs").CloudSwatch | null; locked?: "member" | "signed-out" };+ /** A Cloud of the person's own that has ended (or stopped): it opens its own screen, never its address. */+ ended?: true;+ /** Its owner may take this Cloud off their list (it ended, or was never paid for): its menu offers Remove from list. */+ removable?: true;}/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings, and* a new organization on the Team plan this account pays for (absent from an older app's main). */@@ -60,5 +64,6 @@ export type AddCloudView =};};export declare const RAIL_MIN_PLACES: number;-export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown }): RailPlace[];+/** main's own circles: each as the page sees it, plus the Cloud main acts on for it (never sent to a page). */+export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown }): Array<RailPlace & { cloudId?: string }>;export declare function addCloudView(state: unknown, offer: import("./cloud-home.mjs").CloudOffer | null): AddCloudView;diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex d7eea260cc..713e733b2f 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -5,9 +5,10 @@// Security: the list carries names, colours and states, never an address, and goes only to the rail's own page, this// app's. No place's page reads it, not even this computer's or a Cloud's: a server the person connected by hand runs a// page anyone may have written, and would learn the names of the person's other places. A page learns only that the-// rail stands beside it. A circle names a saved place by its id; main opens only an id it listed itself.+// rail stands beside it. A circle names a saved place by its id; main opens or removes only an id it listed itself, and+// the Cloud it acts on is main's own word for that circle (`cloudId`, which the page never sees).import environments from "./environments.cjs";-import { cleanCloudListName, CLOUD_SWATCHES, cloudSetupProgress, olderRelease, otherOwnClouds, ownCloud, signedInServers, stepProgress, swatchColor } from "./cloud-list.mjs";+import { cleanCloudListName, CLOUD_SWATCHES, cloudSetupProgress, cloudState, olderRelease, otherOwnClouds, ownCloud, signedInServers, stepProgress, swatchColor } from "./cloud-list.mjs";import { machineSetup } from "./cloud-home.mjs";import { listedLook, placeLook, railPaint, SIGNED_IN } from "./place-look.mjs";@@ -38,17 +39,24 @@ function circle(entry, { activeId, mine, state }) {const color = environments.ENTRY_COLORS.includes(entry.color) ? entry.color : listed ? swatchColor(listed.color) : null;const paint = railPaint(placeLook(entry, { clouds: connected?.clouds ?? null, homeOrigin: mine }), color);return { id: entry.id, name: entry.name, color, kind, opens: true, ...(paint ? { paint } : {}), ...(entry.id === activeId ? { active: true } : {}),- ...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}) };+ ...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}),+ ...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}) };}+/** My Cloud's saved place that the verified session's list no longer has (its owner removed it from their list, or the Admin+ * lists nothing at its address any more): no circle, unless it is home. An Admin without the list leaves it as it was. */+const unlisted = (entry, { clouds, home, mine }) => Array.isArray(clouds) && (entry.home === true || entry.origin === mine) && entry.origin !== home+ && !clouds.some(cloud => cloud.origin === entry.origin);+/*** 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 in all, This computer counted while it is one: no rail at all, the window as it was, unless- * the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.+ * nothing to open. A Cloud of theirs the Admin is still making (no address yet) is there too: it opens its own screen (its+ * checkout or its setup), never an address. My Cloud's saved place leaves once the session's list doesn't have it (removed+ * from the list). Fewer than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window+ * as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.* @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any }} input*/export function railPlaces({ saved, home = null, mine = null, state = null }) {@@ -56,13 +64,13 @@ export function railPlaces({ saved, home = null, mine = null, 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)+ const remote = saved.environments.filter(entry => entry.kind !== "local" && entry.origin && !(connected && unlisted(entry, { clouds: connected.clouds, home, mine }))).map((entry, index) => ({ entry, index })).sort((a, b) => rank(a.entry) - rank(b.entry) || order(a.entry) - order(b.entry) || a.index - b.index).map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected }));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 } : {}) }));+ .map(cloud => ({ id: `${PENDING}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "cloud", opens: true, progress: cloudSetupProgress(cloud) ?? 0,+ ...(cloud.status === "checkout" ? { waiting: true } : {}), cloudId: cloud.id }));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, paint: railPaint(listedLook(cloud), swatchColor(cloud.color)),@@ -118,6 +126,8 @@ export function createAddedCloudNotice({ Notification, focused, sheetOpen, open,}const plain = value => (typeof value === "string" ? value : "");+/** A circle as the rail's page sees it: never the Cloud's id, which only main acts on. */+const seen = ({ cloudId: _cloudId, ...place }) => place;const CHOICES = Object.freeze(["cloud", "link", "address"]);/**@@ -142,12 +152,20 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes// +'s choices: main's, and a new organization while this account runs a Team plan's organizations (unless the Admin has// turned adding them off).const choices = () => { const organizations = account()?.state().organizations; return { ...add.choices(), organization: Boolean(organizations) && organizations.blocked !== "off" }; };- ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places(), add: choices() }+ ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places().map(seen), add: choices() }: { places: [], add: { cloud: false, link: false, address: false, organization: false }, ...(beside() ? { beside: true } : {}) })));+ // A Cloud the Admin is still making has no saved place: its own screen opens, by main's word for which Cloud it is.listed("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);+ return place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id);+ });+ // Remove from list, from a circle's menu (the page asked the person first): only a Cloud main listed as removable.+ listed("workspaces:remove", async (_event, id) => {+ const place = places().find(entry => entry.id === plain(id) && entry.removable && entry.cloudId);+ if (!place) throw new Error("That place isn't here any more.");+ const client = account();+ return { outcome: client?.hideCloud ? (await client.hideCloud(place.cloudId)).outcome : "unsupported" };});// A link pasted on +'s sheet goes to main's own Connect dialog, which checks it and names its host before connecting.listed("workspaces:add", (_event, choice, link) => {diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex 5852ccba16..a2ab39ab52 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -58,15 +58,15 @@ test("a Cloud of your own is a rail even alone, for its +; otherwise one placeassert.deepEqual(railPlaces({ saved: { activeId: "local", environments: [] }, home: null, state: null }), [], "This computer alone: no rail");});-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", () => {+test("a Cloud being set up shows how far it is, one at checkout waits, one the Admin is still making opens its own screen, 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, paint: { swatch: "green" }, 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 },- ]);+ { id: "pending:c-b", name: "Client B", color: "purple", kind: "cloud", opens: true, progress: 0, waiting: true, cloudId: "c-b" },+ { id: "pending:c-c", name: "Client C", color: "teal", kind: "cloud", opens: true, progress: 0.4, cloudId: "c-c" },+ ], "each opens its own screen (its checkout, its setup), never an address; main keeps which Cloud it is");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);@@ -234,6 +234,58 @@ test("“{name}” is ready, once per Cloud this app bought, unless its sheet shassert.equal(shown.length, 1);});+test("a Cloud of your own that ended is marked, and its menu offers Remove from list only when the Admin says so; a running Cloud or a team's never does", () => {+ const OLD = "https://omb-c-old.fly.dev";+ const withOld = (over = {}) => saved("home", [{ id: "old", kind: "remote", name: "Old", origin: OLD, cloud: { id: "c-old", role: "owner" } }, ...(over.extra ?? [])]);+ const clouds = parseCloudList([PRIMARY, entry(), entry({ id: "c-old", name: "Old", color: null, status: "ended", origin: OLD, deleteAfter: 1_800_000_000_000, removable: true }),+ entry({ id: "c-team", name: "Acme", color: "amber", teamId: "team-acme", role: "owner", origin: TEAM, status: "ended", removable: true })]);+ const places = railPlaces({ saved: withOld(), home: HOME, mine: HOME, state: session({ clouds }) });+ assert.deepEqual(places.find(place => place.id === "old"), { id: "old", name: "Old", color: null, kind: "cloud", opens: true, paint: { swatch: null }, ended: true, removable: true, cloudId: "c-old" });+ assert.equal(places.find(place => place.id === "a").removable, undefined, "a running Cloud: never");+ assert.deepEqual([places.find(place => place.id === "acme").removable, places.find(place => place.id === "acme").ended], [undefined, undefined], "a team's Cloud is its team's");+ const older = railPlaces({ saved: withOld(), home: HOME, mine: HOME, state: session({ clouds: parseCloudList([PRIMARY, entry({ id: "c-old", name: "Old", status: "ended", origin: OLD })]) }) });+ assert.deepEqual([older.find(place => place.id === "old").ended, older.find(place => place.id === "old").removable], [true, undefined], "an Admin without Remove from list: marked, nothing to remove");+});++test("My Cloud that ended and was removed from the list leaves the rail; while it is listed it is a circle that opens its own screen", () => {+ const OLD = "https://omb-u-old.fly.dev";+ const before = { activeId: "local", environments: [{ id: "mine", kind: "remote", name: "My Cloud", origin: OLD, home: true }, { id: "a", kind: "remote", name: "Client A", origin: CLIENT_A, cloud: { id: "c-a", role: "owner" } }] };+ const ended = entry({ id: "c-home", name: "My Cloud", color: null, origin: OLD, primary: true, status: "ended", deleteAfter: 1_800_000_000_000, removable: true });+ const listed = railPlaces({ saved: before, home: null, mine: OLD, state: session({ machine: { status: "stopped", origin: OLD }, teams: [], clouds: parseCloudList([ended, entry()]) }) });+ assert.deepEqual(listed.map(place => [place.id, place.ended ?? false, place.removable ?? false]), [["local", false, false], ["mine", true, true], ["a", false, false]]);+ assert.equal(listed.find(place => place.id === "mine").cloudId, "c-home");+ const removed = railPlaces({ saved: before, home: null, mine: OLD, state: session({ machine: { status: "stopped", origin: OLD }, teams: [], clouds: parseCloudList([entry()]) }) });+ assert.deepEqual(removed.map(place => place.id), ["local", "a"], "the session no longer lists it: no circle, though its machine still keeps its files");+ const unknown = railPlaces({ saved: before, home: null, mine: OLD, state: session({ machine: { status: "stopped", origin: OLD }, teams: [], clouds: undefined }) });+ assert.deepEqual(unknown.map(place => place.id), ["local", "mine", "a"], "an Admin without the list: as it was");+ assert.deepEqual(railPlaces({ saved: before, home: null, mine: OLD, state: { status: "unavailable" } }).map(place => place.id), ["local", "mine", "a"], "the Admin can't be asked: as saved");+});++test("Remove from list from a circle's menu: only the rail's own page, only a circle main listed as removable, and by main's own word for the Cloud", async () => {+ const OLD = "https://omb-c-old.fly.dev", hidden = [];+ const clouds = parseCloudList([PRIMARY, entry(), entry({ id: "c-old", name: "Old", status: "ended", origin: OLD, removable: true })]);+ const savedOld = saved("home", [{ id: "old", kind: "remote", name: "Old", origin: OLD, cloud: { id: "c-old", role: "owner" } }]);+ const account = { state: () => session({ clouds }), offer: async () => null, hideCloud: async (id) => { hidden.push(id); return { outcome: "removed" }; } };+ const installed = rail({ places: () => railPlaces({ saved: savedOld, home: HOME, mine: HOME, state: session({ clouds }) }), account: () => account });+ const listedPlaces = (await installed.call("workspaces:places")).places;+ assert.equal(JSON.stringify(listedPlaces).includes("c-old"), false, "the page never sees which Cloud it is");+ assert.equal(listedPlaces.find(place => place.id === "old").removable, true);+ assert.deepEqual(await installed.call("workspaces:remove", "old"), { outcome: "removed" });+ assert.deepEqual(hidden, ["c-old"], "main's own word for the circle's Cloud");+ for (const id of ["a", "home", "acme", "c-old", "pending:c-old", { toString: () => "old" }]) {+ await assert.rejects(installed.call("workspaces:remove", id), /isn't here/, String(id));+ }+ assert.deepEqual(hidden, ["c-old"], "nothing else was asked");+ installed.w.lists = false;+ assert.throws(() => installed.call("workspaces:remove", "old"), /only available/, "any other page: refused");+ const older = rail({ places: () => railPlaces({ saved: savedOld, home: HOME, mine: HOME, state: session({ clouds }) }), account: () => ({ state: () => session({ clouds }), offer: async () => null }) });+ assert.deepEqual(await older.call("workspaces:remove", "old"), { outcome: "unsupported" }, "a main without Remove from list says so");+ // A Cloud still being made opens its own screen, by main's word for which Cloud it is.+ const making = rail({ places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds: parseCloudList([PRIMARY, entry({ id: "c-b", status: "checkout", origin: null })]) }) }) });+ await making.call("workspaces:open", "pending:c-b");+ assert.deepEqual(making.opened, ["cloud:c-b"], "its own screen, never a saved place or an address");+});+const PRELOAD = readFileSync(new URL("./preload.cjs", import.meta.url), "utf8");function preload(origin, { activation = false } = {}) {let bridge; const invoked = [];@@ -248,7 +300,7 @@ function preload(origin, { activation = false } = {}) {test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {const page = preload(HOME);- assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "onChanged"]);+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "remove", "onChanged"]);assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);await page.bridge.workspaces.places();await page.bridge.cloudAdd.state();@@ -261,6 +313,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await assert.rejects(page.bridge.cloudAdd.organization("Client B", "rose"), /Create organization/);await assert.rejects(page.bridge.workspaces.color("rose"), /Choose a color/, "a page changes its place's colour only from the person's click");await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);+ await assert.rejects(page.bridge.workspaces.remove("old"), /Choose Remove from list/, "Remove from list only from the person's click");await page.bridge.workspaces.look();assert.deepEqual(page.invoked.at(-1), ["workspaces:look"]);const clicked = preload(HOME, { activation: true });diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjsnew file mode 100644index 0000000000..7f2fc40134--- /dev/null+++ b/electron/fixtures/home-window-world.mjs@@ -0,0 +1,122 @@+// The window onto My Cloud with fakes on every side (home-window.mjs): the world each home-window test runs in, shared by+// home-window.node-test.mjs and home-window-states.node-test.mjs.+import { createHomeWindow } from "../home-window.mjs";++export const CLOUD = "https://omb-t-1.fly.dev";+export const TEAM = "https://omb-u-acme.fly.dev";+export const ACME = { id: "team-acme", name: "Acme", role: "member", machine: { status: "ready", origin: TEAM } };+export const CLIENT = "https://omb-c-a.fly.dev";+export 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 };+export const LOCAL = "http://127.0.0.1:8799";+export const ACCOUNT = { id: "acct-1", email: "[email protected]" };+export const connected = (machine = {}) => ({ status: "connected", account: ACCOUNT, machine: { status: "ready", origin: CLOUD, ...machine } });+export const done = (cloud = {}) => ({ v: 1, phase: "done", cloud: { origin: CLOUD, account: ACCOUNT.id, machine: CLOUD, ...cloud }, doneAt: 1 });+export const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });++/**+ * The window onto My Cloud with fakes on every side: the journal, this computer's freeze marker, the MausBot Cloud+ * sign-in (its power word, wake, pairing code), My Cloud's answers (`cloud`), the window (where it went), the startup+ * screen and a manual clock.+ */+export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null } = {}) {+ 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 },+ /** 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: [], rehomes: [], rehomeThrows: false,+ url, timers: [], intervals: [],+ /** Remove from list on the Admin: each Cloud asked about, and what the Admin answers (`removed` takes it off the session's list). */+ hides: [], removeAnswer: "removed",+ /** A page whose load never finishes, by its address (the place answered the look, then nothing). */+ stall: () => false,+ };+ const timers = {+ set: (work, ms) => { const timer = { work, at: w.clock + ms }; w.timers.push(timer); return timer; },+ clear: (timer) => { w.timers = w.timers.filter((entry) => entry !== timer); w.intervals = w.intervals.filter((entry) => entry !== timer); },+ every: (work, ms) => { const timer = { work, ms }; w.intervals.push(timer); return timer; },+ };+ const contents = { id: 7, mainFrame: { get url() { return w.url; } }, getURL: () => w.url, reload: () => { w.reloads++; } };+ w.contents = contents;+ w.window = { isDestroyed: () => false, webContents: contents };+ const account = {+ state: () => w.state,+ power: () => w.power,+ powerOf: (origin) => (origin === CLOUD ? w.power : (w.state?.clouds ?? []).find((cloud) => cloud.origin === origin)?.power ?? null),+ 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(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 };+ },+ async pairTeam(id) {+ w.teamPairs.push(id);+ if (w.team.gone || !(w.state?.teams ?? []).some((team) => team.id === id)) throw Object.assign(new Error("You're no longer in Acme."), { gone: true });+ if (w.state?.status !== "connected" || w.team.down) throw new Error("Cloud request failed.");+ return { origin: TEAM, code: "TTTT-EEEE-AAAA", expiresAt: w.clock + 60_000 };+ },+ signInAgain: async () => { w.signIns.push("again"); },+ begin: async () => { w.signIns.push("begin"); },+ async hideCloud(cloudId) {+ w.hides.push(cloudId);+ if (w.removeAnswer === "removed") w.state = { ...w.state, clouds: (w.state?.clouds ?? []).filter((cloud) => cloud.id !== cloudId) };+ return { outcome: w.removeAnswer };+ },+ };+ w.home = createHomeWindow({+ journal: () => w.journal,+ frozen: async () => w.marker,+ account: () => account,+ window: () => w.window,+ ensureWindow: () => { w.calls.push("ensure"); },+ localOrigin: () => LOCAL,+ cookieFetch: async (url, init) => {+ 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(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([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" || place?.kind === "own" ? [url, origin, place.id] : [url, origin]); w.url = url; if (w.stall(url)) await new Promise(() => {}); },+ 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); 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),+ rehomed: (home) => { w.rehomes.push(home); if (w.rehomeThrows) throw new Error("listener broke"); },+ now: w.now,+ timers,+ });+ w.later = async (ms) => {+ w.clock += ms;+ const due = w.timers.filter((timer) => timer.at <= w.clock);+ w.timers = w.timers.filter((timer) => timer.at > w.clock);+ for (const timer of due) timer.work();+ await new Promise((resolve) => setImmediate(resolve));+ await new Promise((resolve) => setImmediate(resolve));+ };+ w.tick = async () => { for (const timer of w.intervals) timer.work(); for (let i = 0; i < 5; i++) await new Promise((resolve) => setImmediate(resolve)); };+ return w;+}diff --git a/electron/home-window-states.node-test.mjs b/electron/home-window-states.node-test.mjsnew file mode 100644index 0000000000..eec59ba65b--- /dev/null+++ b/electron/home-window-states.node-test.mjs@@ -0,0 +1,121 @@+// This computer's screen for a Cloud the Admin's list says isn't running (home-window.mjs `cloudScreen`): what it is in plain+// words, never its address looked up, a page that never loads turned into the offline screen with Try again, and Remove from+// list from that screen.+import assert from "node:assert/strict";+import test from "node:test";++import { cloudScreen, HOME_SCREEN_PATH, installHomeWindowIpc, OPEN_MS } from "./home-window.mjs";+import { CLIENT, CLIENT_A, CLOUD, connected, LOCAL, world } from "./fixtures/home-window-world.mjs";++const ENDED_HOME = { ...CLIENT_A, id: "c-home", name: "My Cloud", color: null, origin: CLOUD, primary: true, status: "ended", deleteAfter: 1_900_000_000_000, removable: true };+test("My Cloud that ended, asked for before the move: its own screen with the day its files go and Remove from list; its address is never looked up", async () => {+ const w = world({ journal: null, state: { ...connected({ status: "stopped", hold: { until: 1_900_000_000_000 } }), clouds: [ENDED_HOME, CLIENT_A] }, url: `${LOCAL}/` });+ await w.home.openCloud();+ assert.deepEqual(w.home.view(), { screen: "ended", name: "My Cloud", deleteAt: 1_900_000_000_000, removable: true });+ assert.deepEqual(w.went, [[`${LOCAL}${HOME_SCREEN_PATH}`, null]], "this computer's own screen, never My Cloud's address");+ assert.deepEqual([w.fetched, w.pairs, w.wakes], [[], 0, 0], "nothing dials it, pairs with it or wakes it");+ assert.equal(w.home.asking(), true, "This computer still leaves the screen");+ assert.equal(w.timers.length, 0, "nothing to look again for: the session's word moves it");+ // Its checkout left unpaid, or its payment: each its own screen, and still nothing looked up.+ for (const [status, screen] of [["checkout", "checkout"], ["payment_problem", "payment"], ["stopped", "ended"]]) {+ const other = world({ journal: null, state: { ...connected({ status: "stopped" }), clouds: [{ ...ENDED_HOME, status, removable: undefined, deleteAfter: undefined }] }, url: `${LOCAL}/` });+ await other.home.openCloud();+ assert.deepEqual(other.home.view(), { screen, name: "My Cloud" }, status);+ assert.deepEqual([other.fetched, other.pairs], [[], 0], status);+ }+ // An Admin without the list: the machine's word, still never its address.+ const older = world({ journal: null, state: connected({ status: "stopped" }), url: `${LOCAL}/` });+ await older.home.openCloud();+ assert.deepEqual([older.home.view(), older.fetched], [{ screen: "plan", machine: "stopped" }, []]);+ // Removed from the list (its machine still keeps its files): a saved entry asked for is simply this computer, never dialled.+ const removed = world({ journal: null, state: { ...connected({ status: "stopped" }), clouds: [CLIENT_A] }, url: `${LOCAL}/` });+ await removed.home.openCloud();+ assert.deepEqual([removed.went, removed.fetched, removed.pairs, removed.home.asking()], [[], [], 0, false]);+ // Once My Cloud is home, its list's word too.+ const home = world({ state: { ...connected({ status: "stopped" }), clouds: [ENDED_HOME] } });+ await home.home.show();+ assert.deepEqual([home.home.view().screen, home.fetched], ["ended", []]);+});++test("another Cloud of the person's own that isn't running shows what it is, never its address: ended, its checkout not finished, its payment", async () => {+ for (const [status, screen] of [["ended", "ended"], ["stopped", "ended"], ["checkout", "checkout"], ["payment_problem", "payment"]]) {+ const w = world({ state: { ...connected(), clouds: [{ ...CLIENT_A, status, ...(status === "checkout" ? { origin: null } : {}) }] } });+ await w.home.show({ place: { cloud: "c-a" } });+ assert.deepEqual(w.home.view(), { screen, name: "Client A" }, status);+ assert.deepEqual([w.fetched, w.ownPairs, w.pairs], [[], [], 0], status);+ assert.deepEqual(w.went, [[`${LOCAL}${HOME_SCREEN_PATH}`, null]], status);+ assert.deepEqual(w.remembers, [{ cloud: "c-a" }], status);+ }+ assert.deepEqual(cloudScreen({ ...CLIENT_A, status: "setting_up", setup: { step: "starting" } }), { screen: "setup", step: "starting" }, "being set up: its setup, as before");+ for (const status of ["ready", "offline"]) assert.equal(cloudScreen({ ...CLIENT_A, status }), null, `${status}: it opens`);+ // The running one opens as always.+ const w = world({ state: { ...connected(), clouds: [CLIENT_A] } });+ await w.home.show({ place: { cloud: "c-a" } });+ assert.deepEqual(w.went.at(-1), [CLIENT, CLIENT, "c-a"]);+});++test("a Cloud that answers the look but whose page never loads is the offline screen after OPEN_MS, with Try again: never an endless spinner", async () => {+ const w = world({ state: { ...connected(), clouds: [CLIENT_A] } });+ w.stall = (url) => url.startsWith(CLIENT);+ const shown = w.home.show({ place: { cloud: "c-a" } });+ for (let i = 0; i < 10; i++) await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(w.went.at(-1), [CLIENT, CLIENT, "c-a"], "it went there");+ assert.deepEqual(w.home.view(), { screen: "opening", name: "Client A" });+ await w.later(OPEN_MS);+ for (let i = 0; i < 10; i++) await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(w.home.view(), { screen: "offline", name: "Client A" });+ await shown;+ assert.deepEqual(w.went.at(-1), [`${LOCAL}${HOME_SCREEN_PATH}`, null], "this computer's screen says so");+ w.stall = () => false;+ await w.later(2_000);+ assert.deepEqual(w.went.at(-1), [CLIENT, CLIENT, "c-a"], "and it looks again by itself");+ // My Cloud too: a load that never finishes is the offline screen, never a spinner that goes on.+ const mine = world();+ mine.stall = (url) => url.startsWith(CLOUD);+ const opening = mine.home.show();+ for (let i = 0; i < 10; i++) await new Promise((resolve) => setImmediate(resolve));+ await mine.later(OPEN_MS);+ for (let i = 0; i < 10; i++) await new Promise((resolve) => setImmediate(resolve));+ assert.equal(mine.home.view().screen, "offline");+ await opening;+});++test("Remove from list on this computer's screen: the Admin first, then the window goes on without that Cloud; the Admin's no keeps the screen", async () => {+ const w = world({ journal: null, state: { ...connected({ status: "stopped" }), clouds: [ENDED_HOME, CLIENT_A] }, url: `${LOCAL}/` });+ await w.home.openCloud();+ w.url = `${LOCAL}${HOME_SCREEN_PATH}`;+ w.removeAnswer = "refused";+ assert.equal(await w.home.remove(), "refused");+ assert.equal(w.home.view().screen, "ended", "refused: the screen stays");+ w.removeAnswer = "removed";+ assert.equal(await w.home.remove(), "removed");+ assert.deepEqual(w.hides, ["c-home", "c-home"]);+ assert.deepEqual([w.local.at(-1), w.home.asking()], [true, false], "this computer's own page again");+ assert.deepEqual(w.fetched, [], "still nothing looked up");+ // Removed elsewhere (the rail's menu, another device) while its screen shows: the window leaves that screen.+ const elsewhere = world({ journal: null, state: { ...connected({ status: "stopped" }), clouds: [ENDED_HOME, CLIENT_A] }, url: `${LOCAL}/` });+ await elsewhere.home.openCloud();+ elsewhere.url = `${LOCAL}${HOME_SCREEN_PATH}`;+ elsewhere.state = { ...elsewhere.state, clouds: [CLIENT_A] };+ await elsewhere.home.changed();+ assert.deepEqual([elsewhere.local.at(-1), elsewhere.home.asking(), elsewhere.fetched], [true, false, []]);+ // Another Cloud of their own: out of the switcher at once, and the window goes home.+ const other = world({ state: { ...connected(), clouds: [{ ...CLIENT_A, status: "ended", removable: true }] } });+ await other.home.show({ place: { cloud: "c-a" } });+ assert.equal(await other.home.remove(), "removed");+ assert.deepEqual([other.hides, other.dropped], [["c-a"], ["c-a"]]);+ assert.deepEqual(other.went.at(-1), [CLOUD, CLOUD], "My Cloud, home");+ // Nothing is asked of a Cloud the session doesn't say may be removed, or from any other screen.+ const kept = world({ state: { ...connected(), clouds: [{ ...CLIENT_A, status: "ended" }] } });+ await kept.home.show({ place: { cloud: "c-a" } });+ assert.equal(await kept.home.remove(), "unsupported");+ const running = world({ state: { ...connected(), clouds: [{ ...CLIENT_A, removable: true }] } });+ await running.home.show({ place: { cloud: "c-a" } });+ assert.equal(await running.home.remove(), "unsupported");+ assert.deepEqual([kept.hides, running.hides], [[], []]);+ // Only this computer's screen asks.+ const handlers = new Map();+ installHomeWindowIpc({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler), on: () => {} }, homeWindow: w.home, cloudPage: () => null });+ w.url = `${CLOUD}/`;+ assert.throws(() => handlers.get("home:remove")({ sender: w.contents, senderFrame: w.contents.mainFrame }), /only available/);+});diff --git a/electron/home-window.d.mts b/electron/home-window.d.mtsindex e31d56f3ff..91857e26d1 100644--- a/electron/home-window.d.mts+++ b/electron/home-window.d.mts@@ -7,7 +7,11 @@ export type HomeView = { name?: string } & (| { screen: "setup"; step?: import("./cloud-home.mjs").CloudSetupStep; slow?: true }| { screen: "offline"; reason?: string }| { screen: "signin"; other?: true }- | { screen: "plan"; machine: "stopped" | "payment-problem" | "failed" });+ | { screen: "plan"; machine: "stopped" | "payment-problem" | "failed" }+ /** A Cloud the session's list says isn't running, so nothing looks up its address: it has ended (`deleteAt`: when its kept+ * files are deleted), its checkout wasn't finished, or its payment has a problem; `removable` while its owner may take it+ * off their list. */+ | { screen: "ended" | "checkout" | "payment"; deleteAt?: number; removable?: true });/** The window onto My Cloud once it is the person's home (preload `home`). */export interface HomeBridge {@@ -16,6 +20,8 @@ export interface HomeBridge {onState(callback: (view: HomeView) => void): () => void;/** This computer's screen only: look again now. */retry(): Promise<HomeView>;+ /** This computer's screen only, once the person said yes there: the Cloud it shows leaves their list (absent: an older app). */+ remove?(): Promise<import("./cloud-account.mjs").CloudRemoveOutcome>;/** This device's MausBot Cloud sign-in, again; on My Cloud's page only from the person's click. */signIn(): Promise<void>;/** My Cloud's own page only: its session ended, so the app signs it in again by itself. */@@ -31,9 +37,12 @@ export type HomePlace = { kind: "cloud"; origin: string } | { kind: "team" | "owexport 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;+/** This computer's screen for a listed Cloud that isn't running (or its setup's step); null for one that opens. */+export declare function cloudScreen(cloud: import("./cloud-list.mjs").CloudListEntry | null | undefined): HomeView | null;export declare const HOME_SCREEN_PATH: string;export declare const LOOK_MS: number;+export declare const OPEN_MS: number;export declare const RETRY_MS: readonly number[];export declare const QUIET_MS: number;export declare const VERSION_EVERY_MS: number;@@ -60,6 +69,8 @@ type Timers = { set(work: () => void, ms: number): unknown; clear(timer: unknownexport interface HomeWindow {show(options?: { open?: "phone" | null; place?: HomeAsk }): Promise<unknown>;openCloud(open?: "phone" | null): Promise<unknown>;+ /** Remove from list from this computer's screen: the Cloud it shows leaves the person's list. */+ remove(): Promise<import("./cloud-account.mjs").CloudRemoveOutcome>;asking(): boolean;refresh(): Promise<Home>;view(): HomeView;@@ -88,7 +99,8 @@ 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(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;+ pairTeam?(teamId: string): Promise<{ origin: string; code: string; expiresAt: number }>; signInAgain(): Promise<unknown>; begin(): Promise<unknown>;+ hideCloud?(cloudId: string): Promise<{ outcome: import("./cloud-account.mjs").CloudRemoveOutcome }> } | null;restored?(): Promise<unknown>;window(): WindowLike | null;ensureWindow(): void;diff --git a/electron/home-window.mjs b/electron/home-window.mjsindex 9581692530..a73b3e5ae7 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -9,13 +9,16 @@// 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 { cloudMachine, cloudState, otherOwnClouds } from "./cloud-list.mjs";import { asleepAnswer, BACKGROUND_HEADERS, openSleepingCloud, SIGNED_IN_MS } from "./cloud-power.mjs";import { awayIn, parseJournal } from "./one-home.mjs";export const HOME_SCREEN_PATH = "/home";/** The look at an awake My Cloud before the window moves there: under 3 s, so the offline screen shows within 3 s. */export const LOOK_MS = 2_500;+/** A place whose page hasn't loaded this long after the window went there (it answered the look, then nothing) is the+ * offline screen, with Try again: never an endless spinner. */+export const OPEN_MS = 30_000;export const RETRY_MS = Object.freeze([2_000, 4_000, 8_000, 15_000, 30_000]);/** A brand-new Cloud's name can be missing for minutes after the Admin says it is ready: a resolver that was asked while* it was set up keeps that "no such name" (RFC 2308 negative caching; Chromium's own host cache does too). For a Cloud@@ -46,6 +49,8 @@ export function splashText(status, name = null) {return name ? `${status === "waking" ? "Waking" : "Opening"} ${name}…` : SPLASH_TEXT[status];}const PLAN_PROBLEMS = new Set(["stopped", "payment-problem", "failed"]);+/** The screens of a listed Cloud that isn't running (`cloudScreen`): nothing to look again for, the session's word moves them. */+const NOT_RUNNING = new Set(["ended", "checkout", "payment"]);const MOVING = new Set(["freeze", "final", "check"]);const DEFAULT_TIMERS = {set: (work, ms) => { const timer = setTimeout(work, ms); timer.unref?.(); return timer; },@@ -79,6 +84,18 @@ export function homeOf({ journal = null, frozenCloud = null, state = null }) {/** 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";+/**+ * This computer's screen for a Cloud the session's list says isn't running, so its address is never looked up: it has ended+ * (stopped too; `deleteAt`, when its kept files are deleted), its checkout wasn't finished, or its payment has a problem, each+ * named and with Remove from list while its owner may (`removable`); or its setup's step. Null for one that opens.+ */+export function cloudScreen(cloud) {+ const state = cloudState(cloud);+ if (!state) return null;+ if (state === "setup") return { screen: "setup", ...(cloud.setup?.step ? { step: cloud.setup.step } : {}) };+ return { screen: state, name: cloud.name, ...(state === "ended" && cloud.deleteAfter ? { deleteAt: cloud.deleteAfter } : {}), ...(cloud.removable ? { removable: true } : {}) };+}+/** 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) {@@ -314,6 +331,19 @@ export function createHomeWindow(deps) {const signInNeeded = () => ["reauth-required", "signed-out"].includes(state()?.status);/** This device has no MausBot Cloud sign-in to pair a team with (homeOf's rule for My Cloud). */const signedOut = () => { const current = state(); return !current?.account?.id || ["signed-out", "connecting"].includes(current.status); };+ /** The session's list's word for My Cloud (the account's primary Cloud), else null: an older Admin, or one it doesn't list. */+ const myListed = () => { const current = state(); return current?.status === "connected" && Array.isArray(current.clouds) ? current.clouds.find((cloud) => cloud.primary) ?? null : null; };+ /** My Cloud's own screen while the session says it isn't running: its list's word (`cloudScreen`) when the Admin sends a list+ * (none for a My Cloud off it: its owner removed it from their list), else its machine's (an older Admin). Null while it+ * runs or is set up: those open as before. */+ function myCloudScreen() {+ const current = state();+ if (current?.status !== "connected") return null;+ if (Array.isArray(current.clouds)) { const listed = cloudScreen(myListed()); return listed && listed.screen !== "setup" ? listed : null; }+ return current.machine && PLAN_PROBLEMS.has(current.machine.status) ? { screen: "plan", machine: current.machine.status } : null;+ }+ /** The session says My Cloud isn't running (its screen says so, or it was removed from the list): never looked up then. */+ const notRunning = () => Boolean(myCloudScreen()) || (state()?.status === "connected" && PLAN_PROBLEMS.has(state().machine?.status));async function answers(origin) {try {@@ -382,6 +412,9 @@ export function createHomeWindow(deps) {opening = place;const client = account();const machine = otherPlace(place) ? place.machine : state()?.status === "connected" ? state().machine : null;+ // My Cloud the session's list says isn't running: its own screen, never its address, and nothing to look again for.+ const listed = place.kind === "cloud" ? cloudScreen(myListed()) : null;+ if (listed && NOT_RUNNING.has(listed.screen)) { clearRetry(); return toScreen(listed); }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;}@@ -422,7 +455,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 = 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);+ // A page that never finishes loading is the offline screen after OPEN_MS, which looks again by itself and has Try again.+ let slow = null;+ const loaded = await Promise.race([Promise.resolve(go(cloudHomeConnectUrl({ origin, grant }, now(), open === "phone" ? "phone" : null), origin, place)).then(() => true, () => true),+ new Promise((done) => { slow = timers.set(() => done(false), OPEN_MS); })]);+ timers.clear(slow);+ if (!loaded) { log(`home: ${otherPlace(place) ? place.name : "My Cloud"} didn't load in ${OPEN_MS / 1000} s`); return offline(token); }if (place.kind === "cloud") { clearRenewal(); power.woke(); }else if (place.kind === "team") renewLater(place, grant || !session?.expiresAt ? TEAM_RENEW_MS : session.expiresAt - now() - TEAM_RENEW_EARLY_MS);else clearRenewal();@@ -447,6 +485,9 @@ export function createHomeWindow(deps) {// 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" }); }+ // Another Cloud of their own that the session's list says isn't running: its own screen, never its address.+ const listed = target.kind === "own" ? cloudScreen(otherOwnClouds(state()?.clouds).find((cloud) => cloud.id === target.id)) : null;+ if (listed && NOT_RUNNING.has(listed.screen)) { clearRetry(); return toScreen(listed); }const setup = machineSetup(target.machine);if (setup) { clearRetry(); return toScreen({ screen: "setup", ...setup }); }if (!target.origin) { toScreen({ screen: "plan", machine: target.machine?.status ?? "stopped" }); later(); return; }@@ -456,10 +497,12 @@ export function createHomeWindow(deps) {opening = null;clearRenewal();if (current.kind === "computer" && asked) {- const setup = cloudSetupOf(state()), mine = readyCloudOrigin(state());- if (setup || mine) ensureWindow();+ const setup = cloudSetupOf(state()), mine = readyCloudOrigin(state()), stopped = setup || mine ? null : myCloudScreen();+ if (setup || mine || stopped) ensureWindow();if (setup) { clearRetry(); return toScreen({ screen: "setup", ...setup }); }if (mine) return connect({ kind: "cloud", origin: mine }, token, open ?? asked.open);+ // Not running (it ended, its checkout wasn't finished, a payment problem): its own screen, never its address.+ if (stopped) { clearRetry(); return toScreen(stopped); }asked = null; naming = null;}if (current.kind === "computer") {@@ -528,10 +571,25 @@ export function createHomeWindow(deps) {* home it opens as a saved server, and while the Admin sets it up the setup screen shows until it opens by itself. */async openCloud(open = null) {if ((await refresh()).kind !== "computer") return show({ place: "cloud", open });- if (!cloudSetupOf(state()) && !readyCloudOrigin(state())) throw new Error("My Cloud is not ready to connect yet.");+ if (!cloudSetupOf(state()) && !readyCloudOrigin(state()) && !notRunning()) throw new Error("My Cloud is not ready to connect yet.");asked = { open };return show({ place: "cloud", open });},+ /** Remove from list, from this computer's screen (its own button, once the person said yes there): the Cloud the screen+ * shows leaves their list on the Admin (cloud-account.mjs hideCloud), and the window goes where it would without it.+ * Answers the outcome; nothing is asked of a Cloud the session doesn't say is `removable`. */+ async remove() {+ const own = opening?.kind === "own" ? opening : null, cloudId = own ? own.id : myListed()?.id ?? null;+ const cloud = cloudId ? (state()?.clouds ?? []).find((entry) => entry.id === cloudId) ?? null : null;+ if (!cloud?.removable || !screen?.removable) return "unsupported";+ const client = account();+ const outcome = client?.hideCloud ? (await client.hideCloud(cloudId).catch(() => ({ outcome: "failed" }))).outcome : "unsupported";+ if (outcome !== "removed" && outcome !== "gone") return outcome;+ if (own) { if (opening === own) opening = null; drop(own); } else { asked = null; naming = null; }+ screen = null; status = null; clearRetry();+ await show({ place: "cloud" });+ return outcome;+ },/** My Cloud is asked for and not open yet: the window shows this computer's screen for it. */asking: () => Boolean(asked),refresh,@@ -631,6 +689,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:remove", from("home:remove", screenPage, () => homeWindow.remove()));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; } });diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjsindex d32035ae34..e00e123e85 100644--- a/electron/home-window.node-test.mjs+++ b/electron/home-window.node-test.mjs@@ -9,18 +9,8 @@ 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";--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 } });-const done = (cloud = {}) => ({ v: 1, phase: "done", cloud: { origin: CLOUD, account: ACCOUNT.id, machine: CLOUD, ...cloud }, doneAt: 1 });-const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });+import { 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";+import { ACCOUNT, ACME, CLIENT, CLIENT_A, CLOUD, connected, done, LOCAL, TEAM, world } from "./fixtures/home-window-world.mjs";test("home is My Cloud only once the move switched and the same account is signed in; anything else is this computer or the sign-in screen", () => {assert.deepEqual(homeOf({}), { kind: "computer" }, "no Cloud: nothing changes");@@ -55,104 +45,6 @@ test("a sign-in keeps only a path of My Cloud's own", () => {assert.equal(routeOf("not a url", CLOUD), null);});-/**- * The window onto My Cloud with fakes on every side: the journal, this computer's freeze marker, the MausBot Cloud- * 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 = {}, 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 },- /** 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: [], rehomes: [], rehomeThrows: false,- url, timers: [], intervals: [],- };- const timers = {- set: (work, ms) => { const timer = { work, at: w.clock + ms }; w.timers.push(timer); return timer; },- clear: (timer) => { w.timers = w.timers.filter((entry) => entry !== timer); w.intervals = w.intervals.filter((entry) => entry !== timer); },- every: (work, ms) => { const timer = { work, ms }; w.intervals.push(timer); return timer; },- };- const contents = { id: 7, mainFrame: { get url() { return w.url; } }, getURL: () => w.url, reload: () => { w.reloads++; } };- w.contents = contents;- w.window = { isDestroyed: () => false, webContents: contents };- const account = {- state: () => w.state,- power: () => w.power,- powerOf: (origin) => (origin === CLOUD ? w.power : (w.state?.clouds ?? []).find((cloud) => cloud.origin === origin)?.power ?? null),- 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(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 };- },- async pairTeam(id) {- w.teamPairs.push(id);- if (w.team.gone || !(w.state?.teams ?? []).some((team) => team.id === id)) throw Object.assign(new Error("You're no longer in Acme."), { gone: true });- if (w.state?.status !== "connected" || w.team.down) throw new Error("Cloud request failed.");- return { origin: TEAM, code: "TTTT-EEEE-AAAA", expiresAt: w.clock + 60_000 };- },- signInAgain: async () => { w.signIns.push("again"); },- begin: async () => { w.signIns.push("begin"); },- };- w.home = createHomeWindow({- journal: () => w.journal,- frozen: async () => w.marker,- account: () => account,- window: () => w.window,- ensureWindow: () => { w.calls.push("ensure"); },- localOrigin: () => LOCAL,- cookieFetch: async (url, init) => {- 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(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([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" || 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); 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),- rehomed: (home) => { w.rehomes.push(home); if (w.rehomeThrows) throw new Error("listener broke"); },- now: w.now,- timers,- });- w.later = async (ms) => {- w.clock += ms;- const due = w.timers.filter((timer) => timer.at <= w.clock);- w.timers = w.timers.filter((timer) => timer.at > w.clock);- for (const timer of due) timer.work();- await new Promise((resolve) => setImmediate(resolve));- await new Promise((resolve) => setImmediate(resolve));- };- w.tick = async () => { for (const timer of w.intervals) timer.work(); for (let i = 0; i < 5; i++) await new Promise((resolve) => setImmediate(resolve)); };- return w;-}test("no Cloud: the window is this computer's as before, and nothing asks any Cloud or the Admin", async () => {const w = world({ journal: null, state: { status: "signed-out" }, url: `${LOCAL}/` });diff --git a/electron/preload.cjs b/electron/preload.cjsindex 8aa18ea818..432da6a24f 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -145,6 +145,9 @@ const bridge = {// The colour of a place the window's rail lists, from a click on the rail's own page (main refuses any other page).recolor: (id, swatch) => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("workspaces:recolor", String(id), swatch === null ? null : String(swatch)) : Promise.reject(new Error("Choose a color.")),+ // Remove from list, for a Cloud the window's rail lists as removable, from a click on the rail's own page (main refuses any other page).+ remove: (id) => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("workspaces:remove", String(id)) : Promise.reject(new Error("Choose Remove from list.")),onChanged: (cb) => {const handler = () => cb();ipcRenderer.on("workspaces:changed", handler);@@ -530,6 +533,7 @@ const bridge = {return () => ipcRenderer.removeListener("home:state-changed", handler);},retry: () => ipcRenderer.invoke("home:retry"),+ remove: () => ipcRenderer.invoke("home:remove"),signIn: () => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("home:sign-in") : Promise.reject(new Error("Choose Sign in to sign in again.")),repair: () => ipcRenderer.invoke("home:repair"),diff --git a/src/components/HomeScreen.dom.test.ts b/src/components/HomeScreen.dom.test.tsnew file mode 100644index 0000000000..08d742da57--- /dev/null+++ b/src/components/HomeScreen.dom.test.ts@@ -0,0 +1,66 @@+// @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 { HomeBridge, HomeView } from "../../electron/home-window.mjs";+import { setLocale } from "@/lib/i18n";+import { HomeScreen } from "./HomeScreen";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement, root: Root | null = null;+const settle = () => act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });+function bridgeOf(view: HomeView, remove?: HomeBridge["remove"]) {+ return { state: vi.fn(async () => view), onState: vi.fn(() => () => {}), retry: vi.fn(async () => view), signIn: vi.fn(async () => {}), repair: vi.fn(async () => {}),+ ...(remove ? { remove } : {}) } satisfies HomeBridge;+}+async function mount(bridge: HomeBridge, manage?: () => Promise<void>) {+ root = createRoot(host);+ await act(async () => { root!.render(createElement(HomeScreen, { bridge, ...(manage ? { manage } : {}) })); });+ await settle();+}+const click = async (selector: string) => { const element = host.querySelector<HTMLElement>(selector); expect(element, selector).toBeTruthy(); await act(async () => { element!.click(); }); await settle(); };+beforeEach(() => { setLocale("en"); host = document.createElement("div"); document.body.append(host); Object.assign(window, { ogb: {} }); });+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });++it("an ended Cloud: Buy again on the Cloud page, and Remove from list asked first in plain words; the Admin's no is said", async () => {+ const remove = vi.fn(async () => "refused" as const), manage = vi.fn(async () => {});+ await mount(bridgeOf({ screen: "ended", name: "My Cloud", deleteAt: Date.now() + 2 * 86_400_000, removable: true }, remove), manage);+ expect(host.querySelector("[data-home-screen]")?.getAttribute("data-home-screen")).toBe("ended");+ expect(host.querySelector("[role='status'] span"), "no spinner for a Cloud that isn't running").toBeNull();+ expect(host.querySelector("[data-home-action='buy']")?.textContent).toBe("Buy again");+ await click("[data-home-action='buy']");+ expect(manage).toHaveBeenCalledTimes(1);+ await click("[data-home-remove-ask]");+ expect(host.querySelector("[data-home-remove] [role='alertdialog'] p")?.textContent).toBe("Remove “My Cloud” from your list? You can buy a new Cloud any time.");+ expect(remove, "nothing removed before the person says yes").not.toHaveBeenCalled();+ await click("[data-home-remove-confirm]");+ expect(remove).toHaveBeenCalledTimes(1);+ expect(host.querySelector("[data-home-remove] [role='alert']")?.textContent).toBe("It can't be removed right now: it is running again, or still has a plan.");+});++it("Remove from list shows only where the Admin says so and the app can; a Cloud that didn't answer offers Try again", async () => {+ await mount(bridgeOf({ screen: "ended", name: "Old" }), async () => {});+ expect(host.querySelector("[data-home-remove]"), "not removable: no such choice").toBeNull();+ await act(async () => root?.unmount());+ await mount(bridgeOf({ screen: "ended", name: "Old", removable: true }), async () => {});+ expect(host.querySelector("[data-home-remove]"), "an older app without the channel: no such choice").toBeNull();+ await act(async () => root?.unmount());+ const offline = bridgeOf({ screen: "offline", name: "Acme" });+ await mount(offline);+ expect(host.querySelector("[role='status'] span"), "no spinner going on for ever").toBeNull();+ const retried = offline.retry.mock.calls.length;+ await click("[data-home-action='retry']");+ expect(host.querySelector("[data-home-action='retry']")?.textContent).toBe("Try again");+ expect(offline.retry.mock.calls.length).toBe(retried + 1);+});++it("a checkout that wasn't finished continues where this app keeps its page, else on the Cloud page", async () => {+ const reopen = vi.fn(async () => false), manage = vi.fn(async () => {});+ Object.assign(window, { ogb: { cloudAdd: { reopen } } });+ await mount(bridgeOf({ screen: "checkout", name: "Client B" }), manage);+ await click("[data-home-action='continue']");+ expect([reopen.mock.calls.length, manage.mock.calls.length]).toEqual([1, 1]);+ reopen.mockResolvedValue(true);+ await click("[data-home-action='continue']");+ expect([reopen.mock.calls.length, manage.mock.calls.length]).toEqual([2, 1]);+});diff --git a/src/components/HomeScreen.test.ts b/src/components/HomeScreen.test.tsindex 7a0a62230b..e906ffd3d0 100644--- a/src/components/HomeScreen.test.ts+++ b/src/components/HomeScreen.test.ts@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { beforeEach, expect, it } from "vitest";import { setLocale } from "@/lib/i18n";import { CloudSetupSteps } from "./CloudSetupSteps";-import { homeScreenText } from "./HomeScreen";+import { homeDay, homeScreenText } from "./HomeScreen";beforeEach(() => setLocale("en"));@@ -29,3 +29,21 @@ it("while the Admin sets My Cloud up, the screen says so plainly, with its step,expect(steps).toMatch(/aria-current="step"[^>]*>Checking it's ready</);for (const words of Object.values(setup)) expect(String(words)).not.toMatch(/Server menu|choose it again|DNS|resolv|ERR_/i);});++it("a Cloud that isn't running says what it is in plain words with its one action; one that doesn't answer says Try again, with no endless spinner", () => {+ const now = new Date(2026, 9, 30, 12).getTime(), day = new Date(2026, 10, 1, 9).getTime();+ expect(homeScreenText({ screen: "ended", name: "My Cloud", deleteAt: day }, now))+ .toEqual({ title: "My Cloud has ended.", body: "Its files are deleted on November 1.", reason: null, action: "buy", busy: false });+ expect(homeScreenText({ screen: "ended" }).title).toBe("This Cloud has ended.");+ expect(homeScreenText({ screen: "ended", name: "Old" }).body, "its files' day only when the Admin names it").toBeNull();+ expect(homeScreenText({ screen: "checkout", name: "Client B" })).toEqual({ title: "The checkout for Client B wasn't finished.", body: null, reason: null, action: "continue", busy: false });+ expect(homeScreenText({ screen: "checkout" }).title).toBe("This checkout wasn't finished.");+ expect(homeScreenText({ screen: "payment", name: "Client B" }))+ .toEqual({ title: "The payment for Client B didn't go through.", body: "Update your card to keep using it.", reason: null, action: "card", busy: false });+ expect(homeScreenText({ screen: "offline", name: "Acme" })).toMatchObject({ title: "Can't reach Acme right now.", action: "retry", busy: false });+ expect(homeScreenText({ screen: "offline" })).toMatchObject({ title: "Can't reach My Cloud right now.", action: "retry", busy: false });+ expect(homeDay(new Date(2027, 0, 5).getTime(), now), "another year is named").toBe("January 5, 2027");+ for (const screen of ["ended", "checkout", "payment"] as const) {+ for (const words of Object.values(homeScreenText({ screen, name: "Client B", deleteAt: day }, now))) expect(String(words)).not.toMatch(/—|\bVM\b|engine|ctx|server/i);+ }+});diff --git a/src/components/HomeScreen.tsx b/src/components/HomeScreen.tsxindex 470d905b66..1f6a554af7 100644--- a/src/components/HomeScreen.tsx+++ b/src/components/HomeScreen.tsx@@ -1,5 +1,5 @@import { useEffect, useState } from "react";-import { t } from "@/lib/i18n";+import { activeLocale, t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import type { HomeView, HomeBridge } from "../../electron/home-window.mjs";import { CloudSetupSteps } from "./CloudSetupSteps";@@ -10,24 +10,70 @@ const MACHINE: Record<string, LocaleKey> = {failed: "cloudHome.failed",};+/** What the screen's one button does: sign in again, open the Plan page, look again, or, for a Cloud that isn't running, buy+ * it again, continue its checkout or update the card (each on the Cloud page in the browser, or its checkout reopened). */+export type HomeAction = "sign-in" | "manage" | "retry" | "buy" | "continue" | "card";++/** A day as this person reads it: "November 1", with the year once it isn't this one. */+export function homeDay(at: number, now = Date.now()): string {+ const year = new Date(at).getFullYear() !== new Date(now).getFullYear();+ return new Intl.DateTimeFormat(activeLocale(), { day: "numeric", month: "long", ...(year ? { year: "numeric" } : {}) }).format(new Date(at));+}+/** The words for what the window is waiting on, and whether the person has anything to press. */-export function homeScreenText(view: HomeView | null): { title: string; body: string | null; reason: string | null; action: "sign-in" | "manage" | null; busy: boolean } {+export function homeScreenText(view: HomeView | null, now = Date.now()): { title: string; body: string | null; reason: string | null; action: HomeAction | null; busy: boolean } {// A team's Cloud is named; My Cloud keeps its own words.const name = view?.name ?? null;const named = (plain: LocaleKey, withName: LocaleKey) => (name ? t(withName, { name }) : t(plain));if (view?.screen === "setup") return { title: named("homeScreen.setup", "homeScreen.setupNamed"), body: t(view.slow ? "cloudHome.slow" : "homeScreen.setupBody"), reason: null, action: null, busy: true };- if (view?.screen === "offline") return { title: named("homeScreen.offline", "homeScreen.offlineNamed"), body: t("homeScreen.offlineBack"), reason: view.reason ?? null, action: null, busy: true };+ // It didn't answer: said once, with Try again, never a spinner that goes on for ever (it still looks again by itself).+ if (view?.screen === "offline") return { title: named("homeScreen.offline", "homeScreen.offlineNamed"), body: t("homeScreen.offlineBack"), reason: view.reason ?? null, action: "retry", busy: false };if (view?.screen === "signin") return { title: named("homeScreen.signIn", "homeScreen.signInNamed"), body: t(view.other ? "homeScreen.signInOther" : "homeScreen.signInEnded"), reason: null, action: "sign-in", busy: false };if (view?.screen === "plan") return { title: named("homeScreen.plan", "homeScreen.planNamed"), body: t(MACHINE[view.machine] ?? "cloudHome.failed"), reason: null, action: view.machine === "failed" ? null : "manage", busy: false };+ // A Cloud the Admin's list says isn't running: what it is in plain words, with its one fitting action.+ if (view?.screen === "ended") return { title: named("cloudHome.ended", "cloudHome.endedNamed"), body: view.deleteAt ? t("cloudHome.endedFiles", { date: homeDay(view.deleteAt, now) }) : null,+ reason: null, action: "buy", busy: false };+ if (view?.screen === "checkout") return { title: named("cloudHome.checkout", "cloudHome.checkoutNamed"), body: null, reason: null, action: "continue", busy: false };+ if (view?.screen === "payment") return { title: named("cloudHome.payment", "cloudHome.paymentNamed"), body: t("cloudHome.paymentBody"), reason: null, action: "card", busy: false };if (view?.screen === "waking") return { title: t("homeScreen.waking"), body: null, reason: null, action: null, busy: true };if (view?.screen === "moving") return { title: t("homeScreen.moving"), body: null, reason: null, action: null, busy: true };return { title: named("homeScreen.opening", "homeScreen.openingNamed"), body: null, reason: null, action: null, busy: true };}+const BUTTON: Record<Exclude<HomeAction, "sign-in" | "manage">, LocaleKey> = {+ retry: "cloudHome.tryAgain", buy: "cloudHome.buyAgain", continue: "cloudHome.continue", card: "cloudHome.updateCard",+};++/** Remove from list on this screen: asked first, in plain words; then the window goes on without that Cloud. */+function RemoveFromList({ name, remove }: { name: string; remove: () => Promise<string> }) {+ const [asking, setAsking] = useState(false);+ const [busy, setBusy] = useState(false);+ const [said, setSaid] = useState<"refused" | "failed" | null>(null);+ const confirm = () => {+ setBusy(true); setSaid(null);+ void remove().then((outcome) => { setBusy(false); if (outcome !== "removed" && outcome !== "gone") { setAsking(false); setSaid(outcome === "refused" ? "refused" : "failed"); } },+ () => { setBusy(false); setAsking(false); setSaid("failed"); });+ };+ return <div data-home-remove className="flex flex-col items-start gap-2">+ {asking+ ? <div role="alertdialog" aria-label={t("rail.remove")} className="flex flex-col gap-2 rounded-xl border border-hairline/70 bg-card/70 px-4 py-3">+ <p className="text-[13px] leading-relaxed text-ink">{t("rail.removeAsk", { name })}</p>+ <div className="flex gap-2">+ <button type="button" data-home-remove-confirm className="ui-button ui-button-primary" disabled={busy} onClick={confirm}>{t("rail.removeYes")}</button>+ <button type="button" className="ui-button" disabled={busy} onClick={() => setAsking(false)}>{t("rail.removeNo")}</button>+ </div>+ </div>+ : <button type="button" data-home-remove-ask className="text-[13px] text-ink-secondary underline-offset-2 hover:text-ink hover:underline" onClick={() => { setSaid(null); setAsking(true); }}>{t("rail.remove")}</button>}+ {said && <p role="alert" className="text-[13px] text-danger">{t(said === "refused" ? "rail.removeRefused" : "rail.removeFailed")}</p>}+ </div>;+}+/**- * This computer's own screen in the desktop window while My Cloud can't be shown yet (it is home, or it was asked for- * while the Admin sets it up): why, and nothing to do but wait, except Sign in when this device's sign-in has ended. It- * looks again by itself (main's timer), when the network comes back and when the window comes to the front.+ * This computer's own screen in the desktop window while a place can't be shown (My Cloud once it is home, or asked for while+ * the Admin sets it up, a team's Cloud, or another Cloud of the person's own): why, in plain words, and at most one thing to+ * press: Sign in when this device's sign-in has ended, Try again when it didn't answer, or, for a Cloud that isn't running,+ * Buy again, Continue or Update your card, with Remove from list for one its owner may take off their list. It looks again by+ * itself (main's timer), when the network comes back and when the window comes to the front.*/export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: () => Promise<void> }) {const [view, setView] = useState<HomeView | null>(null);@@ -44,6 +90,14 @@ export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: ()}, [bridge]);const text = homeScreenText(view);const act = (action: () => Promise<unknown>) => { setFailed(false); void action().catch(() => setFailed(true)); };+ // Its checkout's page again when this app keeps it (the Cloud it is buying), else the Cloud page, where it can be paid.+ const reopen = window.ogb?.cloudAdd?.reopen;+ const run: Partial<Record<HomeAction, () => Promise<unknown>>> = {+ retry: () => bridge.retry().then((next) => setView(next)),+ ...(manage ? { manage, buy: manage, card: manage, continue: async () => { if (!(reopen && await reopen().catch(() => false))) await manage(); } } : {}),+ };+ const button = text.action && text.action !== "sign-in" && text.action !== "manage" ? text.action : null;+ const removable = (view?.screen === "ended" || view?.screen === "payment") && view.removable === true && typeof bridge.remove === "function";return (<main data-home-screen={view?.screen ?? "opening"} className="flex min-h-screen items-center justify-center bg-app px-6 text-ink" style={{ WebkitAppRegion: "drag" } as React.CSSProperties}><div className="flex w-full max-w-[420px] flex-col items-start gap-3" style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>@@ -56,6 +110,9 @@ export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: (){text.reason && <p data-home-reason className="text-[13px] leading-relaxed text-ink-secondary">{text.reason}</p>}{text.action === "sign-in" && <button type="button" className="ui-button ui-button-primary mt-2" onClick={() => act(() => bridge.signIn())}>{t("homeScreen.signInButton")}</button>}{text.action === "manage" && manage && <button type="button" className="ui-button mt-2" onClick={() => act(manage)}>{t("cloudAccount.manageInBrowser")}</button>}+ {button && run[button] && <button type="button" data-home-action={button} className={button === "retry" ? "ui-button mt-2" : "ui-button ui-button-primary mt-2"}+ onClick={() => act(run[button]!)}>{t(BUTTON[button])}</button>}+ {removable && <RemoveFromList name={view.name ?? t("cloudSetup.myCloud")} remove={() => bridge.remove!()} />}{failed && <p role="alert" className="text-[13px] text-danger">{t("cloudAccount.actionFailed")}</p>}</div></main>diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.tsindex f8acbf9502..799dd5c510 100644--- a/src/components/PlacesRail.test.ts+++ b/src/components/PlacesRail.test.ts@@ -364,3 +364,37 @@ it("a right-click on a circle opens its place's menu: its colour, saved by mainawait act(async () => { locked!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });expect(host.querySelector("[data-rail-menu]")).toBeNull();});++it("a Cloud of the person's own that ended says so on its circle, and its menu offers Remove from list, asked first; once removed the menu closes", async () => {+ const remove = vi.fn(async (_id: string) => ({ outcome: "refused" as const }) as { outcome: "removed" | "refused" | "gone" | "unsupported" | "failed" });+ rail = { places: [+ place("home", "My Cloud", { active: true, paint: { swatch: null } }),+ place("old", "Old Cloud", { ended: true, removable: true, paint: { swatch: null } }),+ place("a", "Client A", { paint: { swatch: "green" } }),+ ], add: { cloud: false, link: false, address: false } };+ Object.assign(window, { ogb: { workspaces: { ...workspaces, remove }, cloudAdd, rail: { expand: vi.fn(async () => {}), onSkin: () => () => {} } } });+ await mount(createElement(PlacesRail, { chrome: true }));+ const settle = () => act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });+ const menuOf = async (id: string) => {+ await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });+ return host.querySelector(`[data-rail-menu="${id}"]`);+ };+ expect(host.querySelector('[data-rail-place="old"]')?.getAttribute("aria-label")).toBe("Old Cloud: ended");+ expect(host.querySelector('[data-rail-place="old"] [data-rail-ended]'), "dimmed, as a Cloud that isn't running").toBeTruthy();+ expect((await menuOf("a"))?.querySelector("[data-rail-remove]"), "a running Cloud: no such choice").toBeNull();+ await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ const menu = await menuOf("old");+ await click(menu!.querySelector("[data-rail-remove-ask]"));+ expect(menu!.querySelector("[data-rail-remove] [role='alertdialog'] p")?.textContent).toBe("Remove “Old Cloud” from your list? You can buy a new Cloud any time.");+ expect(remove).not.toHaveBeenCalled();+ await click(menu!.querySelector("[data-rail-remove-confirm]"));+ await settle();+ expect(remove).toHaveBeenCalledWith("old");+ expect(host.querySelector("[data-rail-menu] [role='alert']")?.textContent, "the Admin's no, said plainly").toBe("It can't be removed right now: it is running again, or still has a plan.");+ remove.mockResolvedValueOnce({ outcome: "removed" });+ await click(host.querySelector("[data-rail-menu] [data-rail-remove-ask]"));+ await click(host.querySelector("[data-rail-menu] [data-rail-remove-confirm]"));+ await settle();+ expect(host.querySelector("[data-rail-menu]"), "removed: the menu closes, and the circle goes with main's next list").toBeNull();+ expect(workspaces.places).toHaveBeenCalled();+});diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsxindex f70cc557ff..b10161d396 100644--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@ -1,7 +1,8 @@// 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. A right-click on a circle (or its row past eight) opens that place's menu: its colour, changed-// here for every place whatever its server runs.+// here for every place whatever its server runs, and Remove from list for a Cloud of the person's own that ended or was+// never paid for (asked first; main takes it off their list on the Admin).import { useEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";import { Laptop, MoreHorizontal, Plus, Search, Server } from "lucide-react";import type { CloudSwatch } from "../../electron/cloud-list.mjs";@@ -12,7 +13,7 @@ import { cloudColor, cloudColorFill } from "@/lib/cloud-look";import { activeLocale, t } from "@/lib/i18n";import { localizedRelativeTime } from "@/lib/memory";import { useAdvancedMode } from "@/lib/interface-mode";-import { placeInitials, recolorPlace, usePlaces, type RailPlace } from "@/lib/places";+import { placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";import { useDesktopCapabilities } from "./DesktopCapabilities";import { MENU_ROW, MENU_SHEET } from "./menu-recipe";import { PlaceAddSheet } from "./PlaceAddSheet";@@ -30,6 +31,7 @@ export function placeLabel(place: RailPlace, now = Date.now()): string {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 });+ if (place.ended) return t("rail.ended", { 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;@@ -69,8 +71,8 @@ function ProgressRing({ value = 0, waiting = false }: { value?: number; waiting?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")}+ return <span aria-hidden="true" data-rail-offline={place.offline ? "" : undefined} data-rail-ended={place.ended ? "" : undefined}+ className={cn("grid shrink-0 place-items-center rounded-full font-semibold leading-none", color ? "text-white" : "bg-raised text-ink", (place.offline || place.ended) && "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>;@@ -78,10 +80,11 @@ export function PlaceMark({ place, size = CIRCLE }: { place: RailPlace; size?: n/** A place's menu opens where it was asked for: beside its circle, or its row past eight. */type MenuAt = { place: RailPlace; from: HTMLElement };-/** The right-click (or the keyboard's menu key) on a place with a colour to show opens its menu; elsewhere, nothing. */+/** The right-click (or the keyboard's menu key) on a place with a colour to show, or one to remove from the list, opens its+ * menu; elsewhere, nothing. */const menuOpener = (place: RailPlace, onMenu: (at: MenuAt) => void) => (event: ReactMouseEvent<HTMLElement>) => {event.preventDefault();- if (place.paint) onMenu({ place, from: event.currentTarget });+ if (place.paint || place.removable) onMenu({ place, from: event.currentTarget });};/** How far down the rail an element of it sits, in the rail's own units (offsets, not the screen's: the rail's page@@ -110,22 +113,51 @@ function PlaceCircle({ place, calm, canPair, onOpen, onMenu }: { place: RailPlac</button>;}+/** Remove from list in a place's menu: asked first, in plain words; once main took it off the list, the menu closes and the+ * circle goes with main's next list. */+function RemoveRow({ place, onRemoved }: { place: RailPlace; onRemoved: () => void }) {+ const [asking, setAsking] = useState(false);+ const [busy, setBusy] = useState(false);+ const [said, setSaid] = useState<"refused" | "failed" | null>(null);+ const confirm = () => {+ setBusy(true); setSaid(null);+ void removePlace(place.id).then((outcome) => {+ setBusy(false);+ if (outcome === "removed" || outcome === "gone") { onRemoved(); return; }+ setAsking(false); setSaid(outcome === "refused" ? "refused" : "failed");+ });+ };+ return <div data-rail-remove className="flex flex-col gap-1.5 border-t border-hairline/50 px-0.5 pt-1.5">+ {asking+ ? <div role="alertdialog" aria-label={t("rail.remove")} className="flex flex-col gap-2 px-1.5 pb-1">+ <p className="text-[12px] leading-snug text-ink">{t("rail.removeAsk", { name: place.name })}</p>+ <div className="flex gap-2">+ <button type="button" data-rail-remove-confirm className="ui-button ui-button-primary" disabled={busy} onClick={confirm}>{t("rail.removeYes")}</button>+ <button type="button" className="ui-button" disabled={busy} onClick={() => setAsking(false)}>{t("rail.removeNo")}</button>+ </div>+ </div>+ : <button type="button" data-rail-remove-ask className={MENU_ROW} onClick={() => { setSaid(null); setAsking(true); }}>{t("rail.remove")}</button>}+ {said && <p role="alert" className="px-1.5 pb-1 text-[12px] text-danger">{t(said === "refused" ? "rail.removeRefused" : "rail.removeFailed")}</p>}+ </div>;+}+/** A place's own menu on the window's rail: its name and its colour, in the six swatches, saved by main for every place- * whatever its server runs (on the Admin for a Cloud). A team member sees who may change it. */+ * whatever its server runs (on the Admin for a Cloud), and Remove from list for a Cloud its owner may take off their list.+ * A team member sees who may change its colour. */function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onClose: () => void }) {const paint = place.paint;const [pending, setPending] = useState<CloudSwatch | null>(null);const [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);const ref = useRef<HTMLDivElement>(null);- useEffect(() => { ref.current?.querySelector<HTMLElement>("[role='radio'][tabindex='0']")?.focus(); }, []);- if (!paint) return null;+ useEffect(() => { (ref.current?.querySelector<HTMLElement>("[role='radio'][tabindex='0']") ?? ref.current?.querySelector<HTMLElement>("[data-rail-remove-ask]"))?.focus(); }, []);+ if (!paint && !place.removable) return null;const name = place.kind === "computer" ? t("rail.thisComputer") : place.name;const choose = (swatch: CloudSwatch) => {- if (paint.locked || pending || swatch === paint.swatch) return;+ if (!paint || paint.locked || pending || swatch === paint.swatch) return;setPending(swatch); setOutcome(null);void recolorPlace(place.id, swatch).then((answer) => { setPending(null); setOutcome(answer); if (answer === "saved") onClose(); });};- const note = paint.locked === "member" || outcome === "refused" ? t("placeLook.member") : paint.locked === "signed-out" ? t("placeLook.signedOut")+ const note = paint?.locked === "member" || outcome === "refused" ? t("placeLook.member") : paint?.locked === "signed-out" ? t("placeLook.signedOut"): outcome === "unsupported" ? t("placeLook.unsupported") : null;return <div ref={ref} role="dialog" aria-label={name} data-rail-menu={place.id} className={cn("absolute left-full z-50 ml-2 w-72", MENU_SHEET)} style={{ top }}onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }}>@@ -133,12 +165,15 @@ function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onC<PlaceMark place={place} size={22} /><span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink">{name}</span></div>- <p className="px-2 pt-1 text-[12px] text-ink-secondary">{t("placeLook.title")}</p>- <div className="px-2 pb-1.5 pt-0.5">- <SwatchRadios value={pending ?? paint.swatch} onChange={choose} label={t("placeLook.aria", { name })} disabled={Boolean(paint.locked)} offset="menu" none />- </div>- {note && <p data-rail-menu-note className="px-2 pb-1 text-[12px] text-ink-secondary">{note}</p>}- {outcome === "failed" && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}+ {paint && <>+ <p className="px-2 pt-1 text-[12px] text-ink-secondary">{t("placeLook.title")}</p>+ <div className="px-2 pb-1.5 pt-0.5">+ <SwatchRadios value={pending ?? paint.swatch} onChange={choose} label={t("placeLook.aria", { name })} disabled={Boolean(paint.locked)} offset="menu" none />+ </div>+ {note && <p data-rail-menu-note className="px-2 pb-1 text-[12px] text-ink-secondary">{note}</p>}+ {outcome === "failed" && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}+ </>}+ {place.removable && <RemoveRow place={place} onRemoved={onClose} />}</div>;}diff --git a/src/lib/places.ts b/src/lib/places.tsindex fe129f7927..dcfa376501 100644--- a/src/lib/places.ts+++ b/src/lib/places.ts@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";import type { CloudSwatch } from "../../electron/cloud-list.mjs";import type { RailPlace, RailState } from "../../electron/cloud-rail.mjs";import type { PlaceColorOutcome } from "../../electron/place-look.mjs";+import type { CloudRemoveOutcome } from "../../electron/cloud-account.mjs";const NONE: RailState = { places: [], add: { cloud: false, link: false, address: false } };let current: RailState = NONE;@@ -54,6 +55,17 @@ export async function recolorPlace(id: string, swatch: CloudSwatch | null): Promreturn answer.outcome;}+/** Remove from list, from a circle's menu once the person said yes: main takes that Cloud off their list on the Admin, and+ * the circle goes with main's next list. An older app (no such channel) answers `unsupported`. */+export async function removePlace(id: string): Promise<CloudRemoveOutcome> {+ const remove = bridge()?.remove;+ if (!remove) return "unsupported";+ const answer = await remove(id).catch(() => null);+ if (!answer) return "failed";+ if (answer.outcome === "removed" || answer.outcome === "gone") void refreshPlaces();+ return answer.outcome;+}+/** Whether a rail of places stands beside this page: the window's own (main says so: `beside`), or one drawn on it from a* list main gave it (two places or more). */export const railShown = (state: RailState): boolean => state.beside === true || state.places.length > 0;diff --git a/src/locales/en.json b/src/locales/en.jsonindex e36705e8e8..f79b602319 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -361,6 +361,13 @@"rail.hide": "Hide your computers","rail.show": "Show your computers","rail.showSub": "A circle for each place your bots live, at the window's left edge.",+ "rail.ended": "{name}: ended",+ "rail.remove": "Remove from list",+ "rail.removeAsk": "Remove “{name}” from your list? You can buy a new Cloud any time.",+ "rail.removeYes": "Remove",+ "rail.removeNo": "Cancel",+ "rail.removeRefused": "It can't be removed right now: it is running again, or still has a plan.",+ "rail.removeFailed": "It wasn't removed. Check your connection and try again.","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}",@@ -990,6 +997,18 @@"cloudHome.failed": "The Cloud could not be set up yet. It is being retried automatically; your Plan page shows the details.","cloudHome.failedRetry": "The Cloud could not be set up yet. Nothing was lost; it is tried again automatically at {time}, and your Plan page shows the details.","cloudHome.slow": "This is taking longer than usual. Setup is still going; you can keep using this computer meanwhile.",+ "cloudHome.ended": "This Cloud has ended.",+ "cloudHome.endedNamed": "{name} has ended.",+ "cloudHome.endedFiles": "Its files are deleted on {date}.",+ "cloudHome.buyAgain": "Buy again",+ "cloudHome.checkout": "This checkout wasn't finished.",+ "cloudHome.checkoutNamed": "The checkout for {name} wasn't finished.",+ "cloudHome.continue": "Continue",+ "cloudHome.payment": "This Cloud's payment didn't go through.",+ "cloudHome.paymentNamed": "The payment for {name} didn't go through.",+ "cloudHome.paymentBody": "Update your card to keep using it.",+ "cloudHome.updateCard": "Update your card",+ "cloudHome.tryAgain": "Try again","cloudHome.step.reserving": "Reserving your machine","cloudHome.step.storage": "Preparing storage","cloudHome.step.starting": "Starting the Cloud",diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 0473aec740..7cb2ef5627 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -170,6 +170,9 @@ const __APP_VERSION__: string;/** The colour of a place the window's rail lists, by its circle's id, from the person's click on the rail's own* page (refused on any other page). */recolor?: (id: string, swatch: import("../../electron/cloud-list.mjs").CloudSwatch | null) => Promise<{ outcome: import("../../electron/place-look.mjs").PlaceColorOutcome; look: import("../../electron/place-look.mjs").PlaceLook | null }>;+ /** Remove from list: a Cloud the window's rail lists as `removable`, by its circle's id, once the person said yes on+ * the rail's own page (refused on any other page). Absent on an older app. */+ remove?: (id: string) => Promise<{ outcome: import("../../electron/cloud-account.mjs").CloudRemoveOutcome }>;/** Main's word that the places or the sign-in changed: read them again. */onChanged?: (callback: () => void) => () => void;};