Skip to content

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

feat(desktop): the rail of places as the window's own chrome, on every place (#3739)

Milind Soni178a3227d38d
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index 63b38f8d36..7b510d751a 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -1,9 +1,18 @@
# The rail of Clouds and its +
-Once a person has two places or more (their Clouds, their teams' Clouds,
-servers they connected by hand), a narrow rail of circles at the window's left
-edge switches between them, and + buys another Cloud or adds a server of
-their own. With one place there is no rail, and the window looks as before.
+Once a person has two places or more in all (This computer counts while it is
+a place; their Clouds, their teams' Clouds, servers they connected by hand), a
+narrow rail of circles at the window's left edge switches between them, and +
+buys another Cloud or adds a server of their own. With one place there is no
+rail, and the window looks as before.
+
+The rail is the window's own chrome, not a page's: this app's page `/rail` in a
+view of its own at the left edge (electron/chrome-rail.mjs), beside whichever
+place's page the window shows, at every width and on every place, whatever that
+server runs. The page beside it moves over by the rail's width (the app's
+preload, at any zoom). The rail's sheets cover the window while open. The place
+on screen is named under its circle, and beside the rail the sidebar's switcher
+and the profile menu's Switch to… step aside.
Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
## Contract
@@ -16,10 +25,10 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
it through the Admin's `pairing` with that Cloud's id and takes only a grant
for its own address. My Cloud stays the one home.
- The rail's list carries names, colours and states, never an address, and goes
- only to this app's own page and to pages of Clouds MausBot runs that the
- verified session lists. A server's own page gets none; its switcher stays the
- native Server menu. A circle opens only a place main listed, by its id, and
- only from the person's click.
+ only to the rail's own page. No place's page reads it, not even this
+ computer's or a Cloud's; a page learns only that the rail stands beside it. A
+ circle opens only a place main listed, by its id, through main's own switch,
+ and only from the person's click.
- Buying another Cloud sends the plan, a name and a swatch to the Admin, which
answers with a checkout this app opens in the browser; the sheet then follows
the payment and the setup. An Admin that sells one Cloud per account (no
@@ -32,6 +41,13 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
(`PATCH /api/cloud/desktop/clouds/:id`, its owner or its team's admins; a
member sees it locked), a server connected by hand on this computer. An
Admin without that route changes nothing and says so.
+- The window's own rail changes the colour of every place it lists, whatever
+ that place's server runs (an older server's page has no such setting): a
+ right-click on a circle, or on its row past eight, opens that place's menu
+ with the six swatches. The same rules decide where it is kept
+ (`workspaces:recolor`, the rail's own page only, an id main listed); a
+ signed-in server not connected here is changed on the Admin. This computer
+ keeps today's look and has no menu.
- A workspace may also have a banner picture, kept on its own server beside its
other pictures (`GET`, `PUT` and `DELETE /api/workspace/banner`; changing it
is an admin's, seeing it anyone's signed in there). The app shrinks it to
@@ -50,8 +66,8 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
## Automated fixtures
```sh
-node --test electron/cloud-list.node-test.mjs electron/cloud-account-clouds.node-test.mjs electron/cloud-rail.node-test.mjs electron/home-window.node-test.mjs electron/place-look.node-test.mjs
-pnpm exec vitest run src/components/PlacesRail.test.ts src/components/cloud-buy/AddCloudFlow.test.ts src/components/PlaceLookCard.test.ts
+node --test electron/cloud-list.node-test.mjs electron/cloud-account-clouds.node-test.mjs electron/cloud-rail.node-test.mjs electron/chrome-rail.node-test.mjs electron/home-window.node-test.mjs electron/place-look.node-test.mjs
+pnpm exec vitest run src/components/PlacesRail.test.ts src/components/ChromeRail.test.ts src/components/cloud-buy/AddCloudFlow.test.ts src/components/PlaceLookCard.test.ts
pnpm exec vitest run server/workspace-banner.test.ts server/routes/workspace-banner.test.ts server/workspace-banner.e2e.test.ts src/lib/place-banner.test.ts src/components/PlacePicture.test.ts
```
@@ -59,11 +75,12 @@ The account tests answer as a loopback Admin, with and without `clouds`. The
rail tests load the production preload and check which page gets the list,
which ids open, and that a circle, +, checkout and a colour change act only
from a click. The colour tests check who may change a place's colour and where
-it is kept, that nothing is saved when the Admin refuses, and that the tint
-follows at once. The banner tests run pictures a real encoder made, carrying
-EXIF, ICC, XMP and text, through the server's checks, and a real Team Cloud
-where its Super admin sets the banner, a member sees it but can't change it,
-and a signed-out request gets nothing.
+it is kept, from its own page and from the rail's menu, that nothing is saved
+when the Admin refuses, and that the tint follows at once. The banner tests
+run pictures a real encoder made, carrying EXIF, ICC, XMP and text, through
+the server's checks, and a real Team Cloud where its Super admin sets the
+banner, a member sees it but can't change it, and a signed-out request gets
+nothing.
## Rendered workflow
@@ -78,10 +95,10 @@ its owner, eleven for the list past eight. A headless Chrome in a throwaway
profile photographs the rail in Advanced and Simple mode (with the place's
tint), the list past eight, +'s two choices, the steps for a server of one's
own, the plans, the name and colour of a new Cloud and its setup, the person's
-signed-in servers and the steps to connect one, the colour in Settings for an
-admin and for a team member, and a banner picture (drawn by the script and kept
-through the fixture server's own route) in the sidebar and in Settings, each in
-the Daylight and Midnight skins.
+signed-in servers and the steps to connect one, the colour in Settings and in
+a circle's own menu for an admin and for a team member, and a banner picture
+(drawn by the script and kept through the fixture server's own route) in the
+sidebar and in Settings, each in the Daylight and Midnight skins.
`--only rail,look-settings` limits it to some views. Without `--shots` it
prints the preview's address and waits for Ctrl-C.
diff --git a/electron/chrome-rail.d.mts b/electron/chrome-rail.d.mts
new file mode 100644
index 0000000000..b7bea37079
--- /dev/null
+++ b/electron/chrome-rail.d.mts
@@ -0,0 +1,20 @@
+export declare const CHROME_RAIL_WIDTH: number;
+export declare const CHROME_RAIL_PATH: string;
+export interface ChromeRail {
+ attach(window: unknown): void;
+ refresh(): void;
+ expand(on: boolean): void;
+ owns(event: unknown): boolean;
+ shown(): boolean;
+ expanded(): boolean;
+ send(channel: string, ...values: unknown[]): void;
+ install(ipcMain: { handle(channel: string, handler: (...args: any[]) => unknown): void }): void;
+}
+export declare function createChromeRail(deps: {
+ createView: (options: object) => any;
+ preload: string;
+ args: () => string[];
+ url: () => string;
+ wanted: () => boolean;
+ log?: (line: string) => void;
+}): ChromeRail;
diff --git a/electron/chrome-rail.mjs b/electron/chrome-rail.mjs
new file mode 100644
index 0000000000..98acc9c74c
--- /dev/null
+++ b/electron/chrome-rail.mjs
@@ -0,0 +1,103 @@
+// The rail of places as the window's own chrome: this app's small page in a view of its own at the window's left edge,
+// beside whichever place's page the window shows. Every place gets it, whatever that server runs, and no place's page
+// ever reads the list of places: the rail's page is this app's own, and only main switches places.
+//
+// The page beside it leaves the rail its width: main tells each of its documents how wide the rail is (`rail:beside`),
+// and the app's preload, which every page in the window gets, moves the page over by that much at any zoom. The rail's
+// sheets (+, the list past eight) open over the whole window: while one is open the view covers the window,
+// transparent but for the sheet, and goes back to its strip when it closes.
+
+export const CHROME_RAIL_WIDTH = 64;
+export const CHROME_RAIL_PATH = "/rail";
+
+/**
+ * @param {{
+ * createView: (options: object) => any,
+ * preload: string,
+ * args: () => string[],
+ * url: () => string,
+ * wanted: () => boolean,
+ * log?: (line: string) => void,
+ * }} deps `url()`: the rail's page on this app's own server; `wanted()`: whether the window has two places or more to
+ * show it for (railPlaces); `args()`: the preload's arguments, as the window's own page gets them.
+ */
+export function createChromeRail({ createView, preload, args, url, wanted, log = () => {} }) {
+ let view = null, win = null, shown = false, expanded = false;
+ const alive = () => Boolean(win && !win.isDestroyed());
+ const layout = () => {
+ if (!view || !shown || !alive()) return;
+ const [width, height] = win.getContentSize();
+ view.setBounds({ x: 0, y: 0, width: expanded ? width : Math.min(CHROME_RAIL_WIDTH, width), height });
+ };
+ const page = () => (alive() && !win.webContents.isDestroyed() ? win.webContents : null);
+ /** The page beside the rail moves over by its width (0: it has the whole window again). */
+ const tellPage = () => page()?.send("rail:beside", shown ? CHROME_RAIL_WIDTH : 0);
+ const ensureView = () => {
+ if (view) return view;
+ view = createView({ webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false, preload, additionalArguments: args() } });
+ view.setBackgroundColor?.("#00000000");
+ const contents = view.webContents;
+ contents.setWindowOpenHandler(() => ({ action: "deny" }));
+ const stay = (event, target) => { if (target !== url()) event.preventDefault(); };
+ contents.on("will-navigate", stay);
+ contents.on("will-redirect", stay);
+ contents.on("render-process-gone", () => { log("chrome rail: its page went away; loading it again"); void contents.loadURL(url()).catch(() => {}); });
+ void contents.loadURL(url()).catch((error) => log(`chrome rail: ${error?.message ?? error}`));
+ return view;
+ };
+ const rail = {
+ /** The window the rail stands beside: its size moves the rail, and each of its documents gets the room again. */
+ attach(next) {
+ win = next;
+ shown = false; expanded = false;
+ win.on("resize", layout);
+ // Each new document is told again, once it is ready.
+ win.webContents.on("dom-ready", () => { if (shown) tellPage(); });
+ win.once("closed", () => {
+ if (view && !view.webContents.isDestroyed()) view.webContents.close?.({ waitForBeforeUnload: false });
+ view = null; win = null; shown = false; expanded = false;
+ });
+ rail.refresh();
+ },
+ /** Shown while there are two places or more (railPlaces), hidden otherwise: the page then has the whole window. */
+ refresh() {
+ const on = alive() && wanted();
+ if (on === shown) { layout(); return; }
+ shown = on;
+ if (on) {
+ win.contentView.addChildView(ensureView());
+ layout();
+ tellPage();
+ } else {
+ expanded = false;
+ if (view) win.contentView.removeChildView(view);
+ tellPage();
+ }
+ },
+ /** A sheet of the rail's is open: the view covers the window until it closes. */
+ expand(on) {
+ const was = expanded;
+ expanded = on === true && shown;
+ layout();
+ // The keyboard goes with the sheet, and back to the page once it closes.
+ if (expanded) view?.webContents.focus();
+ else if (was) page()?.focus?.();
+ },
+ /** The rail's own page asks (never a place's page). */
+ owns: (event) => Boolean(view && event?.sender === view.webContents && event.senderFrame === view.webContents.mainFrame),
+ shown: () => shown,
+ expanded: () => expanded,
+ /** The rail's page asks for the whole window while a sheet of its own is open, and gives it back after. */
+ install(ipcMain) {
+ ipcMain.handle("rail:expand", (event, on) => {
+ if (!rail.owns(event)) throw new Error("rail:expand is only available to the window's rail");
+ rail.expand(on === true);
+ });
+ },
+ /** Tells the rail's page something (the places changed, the skin of the page beside it). */
+ send(channel, ...values) {
+ if (view && !view.webContents.isDestroyed()) view.webContents.send(channel, ...values);
+ },
+ };
+ return rail;
+}
diff --git a/electron/chrome-rail.node-test.mjs b/electron/chrome-rail.node-test.mjs
new file mode 100644
index 0000000000..5fd088bbf3
--- /dev/null
+++ b/electron/chrome-rail.node-test.mjs
@@ -0,0 +1,154 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import vm from "node:vm";
+
+import { CHROME_RAIL_WIDTH, createChromeRail } from "./chrome-rail.mjs";
+
+const RAIL = "http://127.0.0.1:8799/rail";
+
+function world({ wanted = true } = {}) {
+ const page = Object.assign(new EventEmitter(), { mainFrame: { id: "page-frame" }, told: [], destroyed: false,
+ send(channel, value) { if (channel === "rail:beside") this.told.push(value); }, isDestroyed() { return this.destroyed; } });
+ const children = [];
+ const win = Object.assign(new EventEmitter(), { webContents: page, size: [1440, 900], destroyed: false,
+ getContentSize() { return this.size; }, isDestroyed() { return this.destroyed; },
+ contentView: { addChildView: (view) => children.push(view), removeChildView: (view) => children.splice(children.indexOf(view), 1) } });
+ const made = [];
+ const createView = (options) => {
+ const contents = Object.assign(new EventEmitter(), { mainFrame: { id: "rail-frame" }, loaded: [], sent: [], focused: 0, closed: false, opener: null,
+ loadURL(url) { this.loaded.push(url); return Promise.resolve(); }, setWindowOpenHandler(handler) { this.opener = handler; },
+ send(channel, ...values) { this.sent.push([channel, ...values]); }, focus() { this.focused++; }, isDestroyed() { return this.closed; }, close() { this.closed = true; } });
+ const view = { options, webContents: contents, bounds: null, background: null, setBounds(bounds) { this.bounds = bounds; }, setBackgroundColor(color) { this.background = color; } };
+ made.push(view);
+ return view;
+ };
+ const state = { wanted };
+ const rail = createChromeRail({ createView, preload: "/app/preload.cjs", args: () => ["--omb-local-origin=http://127.0.0.1:8799", "--omb-company-desktop=1"], url: () => RAIL, wanted: () => state.wanted });
+ return { rail, win, page, children, made, state, settle: () => new Promise((resolve) => setImmediate(resolve)) };
+}
+
+test("two places or more: the rail's own page in a view at the window's left edge, and the page beside it moves over", async () => {
+ const w = world();
+ w.rail.attach(w.win);
+ await w.settle();
+ assert.equal(w.made.length, 1);
+ const [view] = w.made;
+ assert.deepEqual(w.children, [view]);
+ assert.deepEqual(view.bounds, { x: 0, y: 0, width: CHROME_RAIL_WIDTH, height: 900 });
+ assert.equal(view.background, "#00000000", "transparent where the rail draws nothing");
+ assert.deepEqual(view.webContents.loaded, [RAIL]);
+ assert.deepEqual(view.options.webPreferences, { contextIsolation: true, sandbox: true, nodeIntegration: false, preload: "/app/preload.cjs",
+ additionalArguments: ["--omb-local-origin=http://127.0.0.1:8799", "--omb-company-desktop=1"] });
+ assert.deepEqual(w.page.told, [CHROME_RAIL_WIDTH], "the page beside it is told how wide the rail is");
+ w.win.size = [1000, 700];
+ w.win.emit("resize");
+ assert.deepEqual(view.bounds, { x: 0, y: 0, width: CHROME_RAIL_WIDTH, height: 700 }, "the rail follows the window's height");
+ assert.equal(w.rail.shown(), true);
+});
+
+test("a sheet of the rail's covers the whole window until it closes; only the rail's page may ask", async () => {
+ const w = world();
+ const handlers = new Map();
+ w.rail.install({ handle: (channel, handler) => handlers.set(channel, handler) });
+ w.rail.attach(w.win);
+ const [view] = w.made;
+ const fromRail = { sender: view.webContents, senderFrame: view.webContents.mainFrame };
+ handlers.get("rail:expand")(fromRail, true);
+ assert.deepEqual(view.bounds, { x: 0, y: 0, width: 1440, height: 900 });
+ assert.equal(view.webContents.focused, 1, "the sheet takes the keyboard");
+ handlers.get("rail:expand")(fromRail, false);
+ assert.deepEqual(view.bounds, { x: 0, y: 0, width: CHROME_RAIL_WIDTH, height: 900 });
+ for (const event of [{ sender: w.page, senderFrame: w.page.mainFrame }, { sender: view.webContents, senderFrame: { id: "an-iframe" } }, {}]) {
+ assert.throws(() => handlers.get("rail:expand")(event, true), /only available to the window's rail/);
+ }
+ assert.equal(w.rail.owns(fromRail), true);
+ assert.equal(w.rail.owns({ sender: w.page, senderFrame: w.page.mainFrame }), false, "a place's page is never the rail");
+});
+
+test("each new document beside the rail is told again; with fewer than two places the rail goes and the page has the window", async () => {
+ const w = world();
+ w.rail.attach(w.win);
+ w.page.emit("dom-ready");
+ assert.deepEqual(w.page.told, [CHROME_RAIL_WIDTH, CHROME_RAIL_WIDTH], "the next server's page moves over too");
+ w.state.wanted = false;
+ w.rail.refresh();
+ assert.deepEqual(w.children, []);
+ assert.deepEqual(w.page.told.at(-1), 0, "the room is given back");
+ w.page.emit("dom-ready");
+ assert.equal(w.page.told.length, 3, "a page with no rail beside it is told nothing more");
+ w.rail.expand(true);
+ assert.equal(w.rail.expanded(), false, "nothing to cover while there is no rail");
+ w.state.wanted = true;
+ w.rail.refresh();
+ assert.equal(w.made.length, 1, "the same page comes back");
+ assert.deepEqual(w.children, [w.made[0]]);
+});
+
+test("the rail's page stays this app's rail: no other page, no new window; the window closing closes it", async () => {
+ const w = world();
+ w.rail.attach(w.win);
+ const contents = w.made[0].webContents;
+ for (const [target, kept] of [[RAIL, true], ["https://evil.example.test/", false], ["http://127.0.0.1:8799/", false]]) {
+ let prevented = false;
+ contents.emit("will-navigate", { preventDefault: () => { prevented = true; } }, target);
+ assert.equal(prevented, !kept, target);
+ }
+ assert.deepEqual(contents.opener({ url: "https://evil.example.test/" }), { action: "deny" });
+ w.win.emit("closed");
+ assert.equal(contents.closed, true);
+ assert.equal(w.rail.shown(), false);
+});
+
+test("nothing to show: no view is made at all", () => {
+ const w = world({ wanted: false });
+ w.rail.attach(w.win);
+ assert.deepEqual([w.made.length, w.children.length, w.page.told.length], [0, 0, 0]);
+});
+
+/** The app's preload in a page of the window, with what the room needs of the page: its document, size and zoom. */
+function pageWithPreload(origin = "https://bots.example.test", pathname = "/") {
+ const listeners = new Map(), handlers = new Map();
+ const head = { children: [], append(node) { this.children.push(node); node.isConnected = true; } };
+ const document = { documentElement: { style: { zoom: "" } }, head, createElement: () => ({ textContent: "", isConnected: false, remove() { head.children.splice(head.children.indexOf(this), 1); this.isConnected = false; } }) };
+ const frame = { zoom: 1 };
+ vm.runInNewContext(readFileSync(new URL("./preload.cjs", import.meta.url), "utf8"), {
+ process: { platform: "darwin", argv: ["--omb-local-origin=http://127.0.0.1:8799", "--omb-company-desktop=1"] },
+ location: { origin, pathname }, navigator: { userActivation: { isActive: false } }, TextEncoder, localStorage: { getItem: () => null }, queueMicrotask, document,
+ window: { addEventListener: (type, listener) => listeners.set(type, listener) },
+ require: () => ({ webUtils: {}, webFrame: { getZoomFactor: () => frame.zoom }, contextBridge: { exposeInMainWorld() {} },
+ ipcRenderer: { on: (channel, handler) => handlers.set(channel, handler), removeListener() {}, send() {}, sendSync: () => null, invoke: () => Promise.resolve() } }),
+ });
+ return { head, frame, root: document.documentElement, tell: (width) => handlers.get("rail:beside")({}, width), resize: () => listeners.get("resize")() };
+}
+
+test("every page beside the rail, from any server, moves over by the rail's width at any zoom, and back when it goes", () => {
+ const page = pageWithPreload();
+ page.tell(CHROME_RAIL_WIDTH);
+ assert.equal(page.head.children.length, 1);
+ assert.match(page.head.children[0].textContent, /padding-left: 64px !important/);
+ page.frame.zoom = 1.25;
+ page.resize();
+ assert.match(page.head.children[0].textContent, /padding-left: 51\.2px !important/, "zoomed in, the same 64 points on screen");
+ page.tell("9999");
+ assert.match(page.head.children[0].textContent, /padding-left: 160px/, "never more than 200 points, whatever is sent");
+ page.tell(0);
+ assert.equal(page.head.children.length, 0, "the page has the whole window again");
+});
+
+test("the rail's own page keeps its size at any zoom of this app's page (Chromium shares a host's zoom); no other page is touched", () => {
+ const rail = pageWithPreload("http://127.0.0.1:8799", "/rail");
+ rail.frame.zoom = 1.25;
+ rail.resize();
+ assert.equal(rail.root.style.zoom, "0.8", "zoomed in, the rail takes the zoom back out");
+ rail.frame.zoom = 1;
+ rail.resize();
+ assert.equal(rail.root.style.zoom, "");
+ for (const [origin, pathname] of [["http://127.0.0.1:8799", "/"], ["https://bots.example.test", "/rail"]]) {
+ const page = pageWithPreload(origin, pathname);
+ page.frame.zoom = 1.25;
+ page.resize();
+ assert.equal(page.root.style.zoom, "", `${origin}${pathname} keeps its zoom`);
+ }
+});
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
index 813714fc57..0d412f569d 100644
--- a/electron/cloud-rail.d.mts
+++ b/electron/cloud-rail.d.mts
@@ -27,10 +27,14 @@ export interface RailPlace {
pairs?: true;
/** It runs an older release than the newest the Admin names: time to update it. */
update?: { version: string; latest: string };
+ /** 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 this computer, and for a Cloud still being made. */
+ paint?: { swatch: import("./cloud-list.mjs").CloudSwatch | null; locked?: "member" | "signed-out" };
}
/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings. */
export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean }
-export interface RailState { places: RailPlace[]; add: RailAddChoices }
+/** `beside`: a place's page, which never reads the list, learns that the window's rail stands beside it. */
+export interface RailState { places: RailPlace[]; add: RailAddChoices; beside?: true }
/** Buying another Cloud as a page sees it: what the sheet says, never the account, an address or the checkout page. */
export type AddCloudView =
| { signedIn: false }
@@ -52,6 +56,5 @@ export type AddCloudView =
};
};
export declare const RAIL_MIN_PLACES: number;
-export declare function hostedCloudOrigin(origin: unknown, input: { state: unknown; mine?: string | null }): boolean;
export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown }): RailPlace[];
export declare function addCloudView(state: unknown, offer: import("./cloud-home.mjs").CloudOffer | null): AddCloudView;
diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjs
index 5b55d90e1d..0d9ebac9e7 100644
--- a/electron/cloud-rail.mjs
+++ b/electron/cloud-rail.mjs
@@ -1,18 +1,18 @@
-// The rail of places at the left of the window (the renderer's PlacesRail) and its +: main builds the list, says who
-// may read it, and does what a circle or + asks through main's own switch and dialogs.
+// The rail of places at the left of the window (the renderer's PlacesRail, drawn by the window's own chrome rail page,
+// chrome-rail.mjs) and its +: main builds the list, says who may read it, and does what a circle or + asks through
+// main's own switch and dialogs.
//
-// Security: the list carries names, colours and states, never an address, and goes only to this app's own page and to
-// pages of Clouds MausBot runs that the verified session lists (the person's own Clouds and their teams' Clouds). A
-// server the person connected by hand, or a Cloud on a server of their own, runs a page anyone may have written, so it
-// would learn the names of the person's other places; it gets none, and the native Server menu stays its switcher. A
-// circle names a saved place by its id; main opens only an id it listed itself.
+// 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.
import environments from "./environments.cjs";
import { cleanCloudListName, CLOUD_SWATCHES, cloudSetupProgress, olderRelease, otherOwnClouds, ownCloud, signedInServers, stepProgress, swatchColor } from "./cloud-list.mjs";
import { machineSetup } from "./cloud-home.mjs";
+import { listedLook, placeLook, railPaint, SIGNED_IN } from "./place-look.mjs";
export const RAIL_MIN_PLACES = 2;
const PENDING = "pending:";
-const SIGNED_IN = "signed-in:";
/** A server or computer of the person's own that signed in with their account, as its circle says it: online while the
* Admin heard from it in the last few minutes, else offline since when it was last seen; and an older release than the
@@ -20,23 +20,13 @@ const SIGNED_IN = "signed-in:";
const serverState = (listed, latest = null) => ({ server: true, ...(listed.status !== "ready" ? { offline: true } : {}), ...(listed.lastSeenAt ? { lastSeenAt: listed.lastSeenAt } : {}),
...(listed.version && latest && olderRelease(listed.version, latest) ? { update: { version: listed.version, latest } } : {}) });
-/** A Cloud's address is one MausBot runs for this person: My Cloud (`mine`), or a Cloud the verified session lists on
- * MausBot Cloud. Without the session's list of Clouds (an older Admin), a team's Cloud it lists, all of which MausBot runs. */
-export function hostedCloudOrigin(origin, { state, mine = null }) {
- if (typeof origin !== "string" || !origin) return false;
- if (origin === mine) return true;
- const connected = state?.status === "connected" ? state : null;
- if (!connected) return false;
- if (Array.isArray(connected.clouds)) return connected.clouds.some(cloud => cloud.origin === origin && cloud.runsOn === "cloud");
- return (connected.teams ?? []).some(team => team?.machine?.origin === origin);
-}
-
const machineProgress = machine => {
const setup = machineSetup(machine);
return setup ? stepProgress(setup.step) : null;
};
-/** One saved place as a circle: what it is, its colour and how it is doing, from the session's word for it. */
+/** One saved place as a circle: what it is, its colour (and who may change it from the rail) and how it is doing, from
+ * the session's word for it. */
function circle(entry, { activeId, mine, state }) {
const connected = state?.status === "connected" ? state : null;
const listed = connected?.clouds?.find(cloud => cloud.origin === entry.origin) ?? null;
@@ -46,7 +36,8 @@ function circle(entry, { activeId, mine, state }) {
const progress = listed ? cloudSetupProgress(listed) : machineProgress(machine);
const problem = listed ? listed.status === "payment_problem" && listed.role === "owner" : entry.origin === mine && machine?.status === "payment-problem";
const color = environments.ENTRY_COLORS.includes(entry.color) ? entry.color : listed ? swatchColor(listed.color) : null;
- return { id: entry.id, name: entry.name, color, kind, opens: true, ...(entry.id === activeId ? { active: true } : {}),
+ 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) : {}) };
}
@@ -56,7 +47,7 @@ function circle(entry, { activeId, mine, state }) {
* A server of theirs that signed in with their account comes next: one saved here already is that saved place (online
* or not), one not connected to this app yet shows how to connect it, and one only reachable on its own network has
* nothing to open. A Cloud of theirs the Admin is still making (no address yet) is there too, not yet to open. Fewer
- * than RAIL_MIN_PLACES places besides this computer: no rail at all, the window as it was.
+ * than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window as it was.
* @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any }} input
*/
export function railPlaces({ saved, home = null, mine = null, state = null }) {
@@ -73,11 +64,11 @@ export function railPlaces({ saved, home = null, mine = null, state = null }) {
...(cloud.status === "checkout" ? { waiting: true } : {}) }));
const savedOrigins = new Set(saved.environments.map(entry => entry.origin).filter(Boolean));
const servers = signedInServers(clouds).filter(cloud => !cloud.origin || !savedOrigins.has(cloud.origin))
- .map(cloud => ({ id: `${SIGNED_IN}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "server", opens: false,
+ .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)),
...(cloud.origin ? { pairs: true } : { ownNetwork: true }), ...serverState(cloud, connected?.latestVersion ?? null) }));
const places = [...remote, ...servers, ...making];
- if (places.length < RAIL_MIN_PLACES) return [];
- return home ? places : [{ id: environments.LOCAL_ID, name: "This computer", color: null, kind: "computer", opens: true, ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];
+ const all = home ? places : [{ id: environments.LOCAL_ID, name: "This computer", color: null, kind: "computer", opens: true, ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];
+ return all.length < RAIL_MIN_PLACES ? [] : all;
}
/** What buying another Cloud looks like from a page: no account, address or checkout page, only what the sheet says. */
@@ -125,25 +116,32 @@ const plain = value => (typeof value === "string" ? value : "");
const CHOICES = Object.freeze(["cloud", "link", "address"]);
/**
- * The rail's and +'s channels, each behind main's window guard (`guard`) and allowed only on a page `trusted` vouches
- * for (this app's own, or a hosted Cloud's). `places()` is railPlaces' list now; `open(id)` main's own switch; `add`
- * the + sheet's fixed actions; `account()` the MausBot Cloud sign-in.
+ * The rail's and +'s channels, each behind main's guard (`guard`: the window's page, or the rail's own). Only the rail's
+ * page (`lists`) reads the list and opens or adds a place; +'s buying sheet also runs on a page `trusted` vouches for
+ * (the rail's, or this computer's own). Any other page learns only whether the rail stands beside it (`beside`).
+ * `places()` is railPlaces' list now; `open(id)` main's own switch; `add` the + sheet's fixed actions; `account()` the
+ * MausBot Cloud sign-in; `targets()` the pages told when something changed.
*/
-export function installCloudRail({ ipcMain, guard, trusted, places, open, add, account, clipboard, openCloud, window }) {
+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets }) {
let sheetOpen = false, sent = "";
const allowed = (channel, handler) => guard((event, ...args) => {
if (!trusted(event)) throw new Error(`${channel} is only available in this app's window`);
return handler(event, ...args);
});
const handle = (channel, handler) => ipcMain.handle(channel, allowed(channel, handler));
+ const listed = (channel, handler) => ipcMain.handle(channel, guard((event, ...args) => {
+ if (!lists(event)) throw new Error(`${channel} is only available in this app's window`);
+ return handler(event, ...args);
+ }));
const view = async () => addCloudView(account()?.state() ?? null, account() ? await account().offer().catch(() => null) : null);
- ipcMain.handle("workspaces:places", guard((event) => (trusted(event) ? { places: places(), add: add.choices() } : { places: [], add: { cloud: false, link: false, address: false } })));
- handle("workspaces:open", (_event, id) => {
+ ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places(), add: add.choices() }
+ : { places: [], add: { cloud: false, link: false, address: false }, ...(beside() ? { beside: true } : {}) })));
+ 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);
});
- handle("workspaces:add", (_event, choice) => {
+ listed("workspaces:add", (_event, choice) => {
if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error("That isn't something to add here.");
return add.run(choice);
});
@@ -165,7 +163,7 @@ export function installCloudRail({ ipcMain, guard, trusted, places, open, add, a
});
handle("cloud-add:open", async () => {
const adding = account()?.state().adding;
- if (!adding) throw new Error("There is no new Cloud to open.");
+ if (!adding?.cloudId) throw new Error("There is no new Cloud to open.");
await openCloud(adding.cloudId);
account()?.addDone();
});
@@ -182,8 +180,7 @@ export function installCloudRail({ ipcMain, guard, trusted, places, open, add, a
const key = JSON.stringify([places(), add.choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null]);
if (key === sent) return;
sent = key;
- const win = window();
- if (win && !win.isDestroyed()) win.webContents.send("workspaces:changed");
+ for (const target of targets()) if (target && !target.isDestroyed()) target.send("workspaces:changed");
},
};
}
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
index 5bc804bf21..eabba7a18f 100644
--- a/electron/cloud-rail.node-test.mjs
+++ b/electron/cloud-rail.node-test.mjs
@@ -4,10 +4,10 @@ import test from "node:test";
import vm from "node:vm";
import { parseCloudList } from "./cloud-list.mjs";
-import { addCloudView, createAddedCloudNotice, hostedCloudOrigin, installCloudRail, railPlaces } from "./cloud-rail.mjs";
+import { addCloudView, createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs";
import { otherCloudSnapshot } from "./cloud-plan-ipc.mjs";
-const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", TEAM = "https://omb-t-acme.fly.dev", VPS = "https://bots.example.test", OWN = "https://mini.tail1234.ts.net";
+const HOME = "https://omb-u-1a2b3c4d5e6f.fly.dev", CLIENT_A = "https://omb-c-a.fly.dev", TEAM = "https://omb-t-acme.fly.dev", VPS = "https://bots.example.test";
const LOCAL = "http://127.0.0.1:8799";
const entry = (over = {}) => ({ id: "c-a", name: "Client A", color: "green", role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: CLIENT_A,
teamId: null, primary: false, ...over });
@@ -27,31 +27,35 @@ const session = (over = {}) => ({ status: "connected", account: { id: "acct-1" }
test("the rail: My Cloud, the person's Clouds and teams' Clouds in the session's order, then servers saved by hand; names, colours and states, never an address", () => {
const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session() });
assert.deepEqual(places, [
- { id: "home", name: "Studio", color: "purple", kind: "cloud", opens: true, active: true },
- { id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true },
- { id: "acme", name: "Acme", color: "yellow", kind: "team", opens: true },
- { id: "vps", name: "Office", color: null, kind: "server", opens: true },
- ]);
+ { id: "home", name: "Studio", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, active: true },
+ { id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true, paint: { swatch: "green" } },
+ { id: "acme", name: "Acme", color: "yellow", kind: "team", opens: true, paint: { swatch: "amber", locked: "member" } },
+ { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null } },
+ ], "each colour changed from the rail, but a team's by its admins alone");
for (const origin of [HOME, CLIENT_A, TEAM, VPS, "/Users/person/lab"]) assert.equal(JSON.stringify(places).includes(origin), false, origin);
const before = railPlaces({ saved: saved("local"), home: null, mine: HOME, state: session() });
- assert.deepEqual(before[0], { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true }, "before the move, this computer is a place too");
+ assert.deepEqual(before[0], { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true }, "before the move, this computer is a place too, in today's look");
assert.equal(before.length, 5);
});
test("one place, or none: no rail, the window as it was", () => {
const alone = { activeId: "home", environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }] };
assert.deepEqual(railPlaces({ saved: alone, home: HOME, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }) }), []);
- assert.deepEqual(railPlaces({ saved: alone, home: null, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }) }), [], "this computer and My Cloud are still one Cloud");
+ assert.deepEqual(railPlaces({ saved: alone, home: null, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }) }).map(place => place.id), ["local", "home"],
+ "before the move, This computer and My Cloud are two places: two circles");
assert.deepEqual(railPlaces({ saved: { activeId: "local", environments: [] }, state: null }), []);
const two = railPlaces({ saved: { activeId: "home", environments: [alone.environments[0], { id: "vps", kind: "remote", name: "Office", origin: VPS }] }, home: HOME, mine: HOME, state: null });
assert.deepEqual(two.map(place => place.id), ["home", "vps"], "a server saved by hand is a place");
+ const typed = { activeId: "local", environments: [{ id: "vps", kind: "remote", name: "Office", origin: VPS }] };
+ assert.deepEqual(railPlaces({ saved: typed, home: null, state: null }).map(place => place.id), ["local", "vps"], "This computer and one server: two circles");
+ assert.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", () => {
const clouds = parseCloudList([PRIMARY, entry({ status: "setting_up", setup: { progress: 0.4 } }), entry({ id: "c-b", name: "Client B", color: "violet", status: "checkout", origin: null }),
entry({ id: "c-c", name: "Client C", status: "setting_up", origin: null, setup: { step: "storage" } }), entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM, status: "payment_problem" })]);
const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session({ clouds }) });
- assert.deepEqual(places.find(place => place.id === "a"), { id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true, progress: 0.4 });
+ assert.deepEqual(places.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 },
@@ -73,15 +77,14 @@ test("a server of the person's own that signed in with their account: one saved
entry({ id: "s-render", name: "Render VPS", color: "rose", tier: null, runsOn: "server", managed: false, status: "offline", origin: RENDER, lastSeenAt: 1_761_000_100_000 })]);
const state = session({ clouds });
const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state });
- assert.deepEqual(places.find(place => place.id === "vps"), { id: "vps", name: "Office", color: null, kind: "server", opens: true, server: true },
+ assert.deepEqual(places.find(place => place.id === "vps"), { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null }, server: true },
"saved by hand at its address: the same circle, marked as theirs, online, opening as it always did");
assert.deepEqual(places.slice(-2), [
- { id: "signed-in:s-mini", name: "Mac mini", color: null, kind: "server", opens: false, ownNetwork: true, server: true, offline: true, lastSeenAt: 1_761_000_000_000 },
- { id: "signed-in:s-render", name: "Render VPS", color: "red", kind: "server", opens: false, pairs: true, server: true, offline: true, lastSeenAt: 1_761_000_100_000 },
+ { id: "signed-in:s-mini", name: "Mac mini", color: null, kind: "server", opens: false, paint: { swatch: null }, ownNetwork: true, server: true, offline: true, lastSeenAt: 1_761_000_000_000 },
+ { id: "signed-in:s-render", name: "Render VPS", color: "red", kind: "server", opens: false, paint: { swatch: "rose" }, pairs: true, server: true, offline: true, lastSeenAt: 1_761_000_100_000 },
]);
assert.equal(places.length, 6, "one circle per server");
for (const origin of [VPS, RENDER]) assert.equal(JSON.stringify(places).includes(origin), false, origin);
- assert.deepEqual([VPS, RENDER].map(origin => hostedCloudOrigin(origin, { state, mine: HOME })), [false, false], "its page never reads the rail");
const alone = { activeId: "home", environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME, home: true }] };
assert.equal(railPlaces({ saved: alone, home: HOME, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY, clouds[2]]) }) }).length, 2, "it counts as a place");
assert.equal(places.some(place => place.update), false, "no newest release named (the Admin doesn't follow releases): no reminder");
@@ -96,37 +99,32 @@ test("a server of the person's own that signed in with their account: one saved
assert.throws(() => r.call("workspaces:open", "signed-in:s-mini"), /isn't here/);
});
-test("only Clouds MausBot runs for this person may read the rail: My Cloud, their Clouds and their teams' on MausBot Cloud; never a server of their own or one typed in", () => {
- const state = session({ clouds: parseCloudList([PRIMARY, entry(), entry({ id: "c-own", name: "Mini", origin: OWN, runsOn: "server" }),
- entry({ id: "c-team", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM })]) });
- assert.deepEqual([HOME, CLIENT_A, TEAM, OWN, VPS, null].map(origin => hostedCloudOrigin(origin, { state, mine: HOME })), [true, true, true, false, false, false]);
- assert.equal(hostedCloudOrigin(TEAM, { state: session({ clouds: undefined }), mine: HOME }), true, "an older Admin lists teams' Clouds, all MausBot's");
- assert.equal(hostedCloudOrigin(CLIENT_A, { state: session({ clouds: undefined }), mine: HOME }), false);
- assert.equal(hostedCloudOrigin(TEAM, { state: session({ clouds: parseCloudList([PRIMARY]) }), mine: HOME }), false, "with the list, a Cloud it doesn't list is none of theirs");
- assert.equal(hostedCloudOrigin(HOME, { state: { status: "unavailable" }, mine: HOME }), true, "My Cloud while a check fails");
- assert.equal(hostedCloudOrigin(CLIENT_A, { state: { status: "unavailable", clouds: state.clouds }, mine: HOME }), false);
-});
-
function rail(over = {}) {
const handlers = new Map(), opened = [], ran = [], sent = [];
- const w = { trusted: true, state: session(), offer: { recommended: "pro", plans: [{ tier: "pro", amount: 4900 }] }, added: [] };
+ const w = { trusted: true, lists: true, beside: true, state: session(), offer: { recommended: "pro", plans: [{ tier: "pro", amount: 4900 }] }, added: [] };
const account = { state: () => w.state, offer: async () => w.offer, addCloud: async (input) => { w.added.push(input); return { outcome: "opened", state: w.state }; },
reopenAdd: async () => true, addLink: () => "https://test.checkout.dodopayments.com/x", addDone: () => { w.done = true; }, interest: async () => {} };
const installed = installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler, trusted: () => w.trusted,
+ lists: () => w.lists, beside: () => w.beside,
places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: w.state }), open: id => opened.push(id), account: () => account,
add: { choices: () => ({ cloud: true, link: true, address: false }), run: choice => ran.push(choice) }, clipboard: { writeText: text => sent.push(text) },
- openCloud: async id => opened.push(`cloud:${id}`), window: () => ({ isDestroyed: () => false, webContents: { send: (channel) => sent.push(channel) } }), ...over });
+ openCloud: async id => opened.push(`cloud:${id}`), targets: () => [{ isDestroyed: () => false, send: (channel) => sent.push(`page:${channel}`) }, null,
+ { isDestroyed: () => false, send: (channel) => sent.push(`rail:${channel}`) }], ...over });
return { handlers, opened, ran, sent, w, installed, call: (channel, ...args) => handlers.get(channel)({ sender: {} }, ...args) };
}
-test("the rail's channels: the list only for a page main vouches for, a circle only by an id main listed, + only its fixed choices", async () => {
+test("the rail's channels: the list only for the rail's own page, a circle only by an id main listed, + only its fixed choices", async () => {
const r = rail();
assert.deepEqual((await r.call("workspaces:places")).places.map(place => place.id), ["home", "a", "acme", "vps"]);
- r.w.trusted = false;
- assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false } }, "a server's own page learns nothing");
+ r.w.lists = false;
+ assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false }, beside: true },
+ "a place's page, this computer's and a Cloud's included, learns only that the rail stands beside it");
+ r.w.beside = false;
+ assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false } });
assert.throws(() => r.call("workspaces:open", "a"), /only available/);
assert.throws(() => r.call("workspaces:add", "link"), /only available/);
- r.w.trusted = true;
+ assert.equal(typeof await r.call("cloud-add:state"), "object", "+'s buying sheet still runs on a page main vouches for (this computer's own)");
+ r.w.lists = true;
r.call("workspaces:open", "a");
assert.throws(() => r.call("workspaces:open", "https://evil.example.test"), /isn't here/);
assert.throws(() => r.call("workspaces:open", "lab"), /isn't here/, "a local environment is the Server menu's, not the rail's");
@@ -135,7 +133,7 @@ test("the rail's channels: the list only for a page main vouches for, a circle o
assert.throws(() => r.call("workspaces:add", "javascript:alert(1)"), /isn't something/);
assert.deepEqual([r.opened, r.ran], [["a"], ["link"]]);
r.installed.changed(); r.installed.changed();
- assert.deepEqual(r.sent, ["workspaces:changed"], "a signal only, and once per change");
+ assert.deepEqual(r.sent, ["page:workspaces:changed", "rail:workspaces:changed"], "a signal only, to the page and the rail, and once per change");
});
test("buying another Cloud from a page: the plan must be on sale, the name is checked, and the page gets only what the sheet says", async () => {
@@ -212,7 +210,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", "onChanged"]);
+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "onChanged"]);
assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet"]);
await page.bridge.workspaces.places();
await page.bridge.cloudAdd.state();
@@ -223,6 +221,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,
await assert.rejects(page.bridge.cloudAdd.copyLink(), /Copy link/);
await assert.rejects(page.bridge.cloudAdd.open(), /Open/);
await assert.rejects(page.bridge.workspaces.color("rose"), /Choose a color/, "a page changes its place's colour only from the person's click");
+ await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);
await page.bridge.workspaces.look();
assert.deepEqual(page.invoked.at(-1), ["workspaces:look"]);
const clicked = preload(HOME, { activation: true });
diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjs
index 6659690c56..941c4837dd 100644
--- a/electron/desktop-prefs.node-test.mjs
+++ b/electron/desktop-prefs.node-test.mjs
@@ -285,7 +285,7 @@ test("production wiring: main answers this computer's page, My Cloud's own page
navigateMainWindow: async url => { calls.push(["navigate", url]); return loads; },
senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed,
mainWindow: { webContents: contents }, environmentsState: { environments: [{ id: "vps", name: "VPS", origin: VPS }], activeId: "vps" },
- BrowserWindow: { getAllWindows: () => windows },
+ BrowserWindow: { getAllWindows: () => windows }, chromeRail: { send: (...told) => sent.push(["rail", ...told]) },
rendererOrigin: () => LOCAL, cloudAccountRestored: async () => calls.push("restored"), cloudOffersReady: async () => { calls.push("offers"); return true; },
cloudPageAsking: event => event.verifiedCloud ? "cloud" : null,
serverReady: true, LOCAL_ID: "local", switchEnvironment: id => switched(id),
@@ -305,7 +305,7 @@ test("production wiring: main answers this computer's page, My Cloud's own page
assert.equal(await options.cloudOffered(), true);
assert.deepEqual(calls, ["restored", "offers"]);
options.languageChanged("en", windows[0].webContents);
- assert.deepEqual(sent, [["home", "desktop-language:changed", "en"]], "every other open window hears the pick");
+ assert.deepEqual(sent, [["home", "desktop-language:changed", "en"], ["rail", "desktop-language:changed", "en"]], "every other open window hears the pick, and the window's rail");
const navigate = main.slice(main.indexOf("function navigateMainWindow(url) {"), main.indexOf("\n}\n", main.indexOf("function navigateMainWindow(url) {")) + 3);
const load = vm.runInNewContext(`${navigate}; navigateMainWindow`, { mainWindow: { isDestroyed: () => false, loadURL: async url => { if (url.endsWith("fail")) throw new Error("ERR_CONNECTION_REFUSED"); } } });
assert.equal(await load(`${LOCAL}/ok`), true); assert.equal(await load(`${LOCAL}/fail`), false, "a failed load answers false, never throws");
diff --git a/electron/main.mjs b/electron/main.mjs
index 0212c539ef..330cabab86 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -105,7 +105,7 @@ import { installUseMyComputer } from "./use-my-computer.mjs";
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
-import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, hostedCloudOrigin, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { otherOwnClouds } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs";
+import { createHomePlaces } from "./home-places.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { otherOwnClouds } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";
import { createWindowStateFile } from "./window-state-file.mjs";
import { createEnvironmentsFile } from "./environments-file.mjs";
import { createOrgLibrary } from "./org-library.mjs";
@@ -297,7 +297,7 @@ const serverSupervisor = createServerSupervisor({
serverStartConflictOnly = false;
slog(`server ready pid=${proc.pid} port=${SERVER_PORT}`);
void readCloudOfferBrand();
- syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted();
+ syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); railChanged();
reportOwnListeners(proc);
orgLibrary?.runtimeReady();
if (managedDesktop) void managedDesktop.refresh().catch(() => {});
@@ -828,7 +828,7 @@ function ensureCloudAccount() {
rememberCloudHome(state);
rememberedHome = rememberedCloudHome(rememberedHome, state);
sendUpdaterState();
- cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); rail.changed(); } catch {}
+ cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); } catch {}
void includedX.onState(state); void includedPages.onState(state); updatesConsent?.accountChanged(state);
refreshCloudMenus();
announceCloudReady(state);
@@ -1550,7 +1550,7 @@ function persistEnvironments(next) {
environmentsState = next;
refreshApplicationMenu();
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.setTitle(workspaceWindowTitle(environmentsState, desktopRemoteAccess, homeWindow.cloudOrigin()));
- try { rail.changed(); } catch {}
+ try { railChanged(); } catch {}
}
async function workspaceMenuAction(action) {
@@ -2015,7 +2015,7 @@ function createWindow({ deferNavigation = false } = {}) {
...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],
},
});
- mainWindow = win; hiddenStart = false;
+ mainWindow = win; hiddenStart = false; chromeRail.attach(win);
win.on("show", () => desktopTray?.windowShown(win));
win.on("focus", () => { if (cloudAccount?.checkoutPending()) void cloudAccount.refresh().catch(() => {}); });
win.on("close", (event) => {
@@ -2317,12 +2317,14 @@ ipcMain.handle("desktop:reveal-file", localOnly("desktop:reveal-file", async (_e
ipcMain.handle("desktop:open-logs", localOrHome("desktop:open-logs", () => openLogsFolder(LOG_DIR, { open: (folder) => shell.openPath(folder) })));
ipcMain.handle("desktop:skin", (event, skin) => {
if (!isKnownSkin(skin)) return false;
+ if (chromeRail.owns(event)) return true;
try {
const { color } = skinChrome(skin);
const win = BrowserWindow.fromWebContents(event.sender) ?? mainWindow;
if (win && !win.isDestroyed()) {
try { win.setBackgroundColor(color); } catch {}
}
+ if (mainWindow && event.sender === mainWindow.webContents) chromeRail.send("rail:skin", skin);
} catch {}
return true;
});
@@ -2672,17 +2674,27 @@ function showHome(options) {
}
const openOwnCloud = id => showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } });
// The rail and its + (cloud-rail.mjs): its list for this app's page and hosted Clouds' pages only, opened through switchEnvironment.
-const rail = installCloudRail({ ipcMain, guard: workspaceOnly, clipboard, window: () => mainWindow, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),
- trusted: event => senderIsLocal(event) || hostedCloudOrigin(activeEnvironment(environmentsState)?.origin, { state: desktopRemoteAccess ? null : cloudAccount?.state(), mine: myCloud() }),
- places: () => railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin(), mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state() }),
- open: id => workspaceMenuAction(() => switchEnvironment(id)),
+const railList = () => railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin(), mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state() });
+// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.
+const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog,
+ args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],
+ url: () => `${rendererOrigin()}${CHROME_RAIL_PATH}`, wanted: () => !desktopRemoteAccess && serverReady && railList().length > 0 });
+chromeRail.install(ipcMain);
+function railChanged() { chromeRail.refresh(); rail.changed(); }
+const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),
+ guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),
+ lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),
+ targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],
+ places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)),
add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),
run: choice => (choice === "link" ? addServerFromClipboard() : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });
const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,
open: id => { if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });
-// The page's own place's colour (place-look.mjs): the Admin's for a Cloud, this app's for a server connected by hand.
+// A place's colour (place-look.mjs): the Admin's for a Cloud, this app's for a server connected by hand; changed on the
+// place's own page or from the window's rail, whatever that server runs.
installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => activeEnvironment(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),
- setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)) });
+ setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)),
+ rail: { owns: event => chromeRail.owns(event), places: railList, saved: id => environmentsState.environments.find(entry => entry.id === id && entry.kind !== "local") ?? null } });
ipcMain.handle("sharing:state", localWorkspaceOnly("sharing:state", async (_event, id) => {
await requireSharedComputers();
return sharingController().state(savedWorkspace(id).id);
@@ -3020,6 +3032,7 @@ app.whenReady().then(async () => {
updatesConsent = registerDesktopPrefs({ ipcMain, cloudAccount: () => cloudAccount, ...jsonFile(path.join(app.getPath("userData"), "desktop-prefs.json")), localConfig: jsonFile(path.join(desktopDataDir(), "config.json")).read, cloudOffered: () => cloudAccountRestored().then(cloudOffersReady),
languageChanged: (language, sender) => {
for (const win of BrowserWindow.getAllWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);
+ chromeRail.send("desktop-language:changed", language);
},
page: event => senderIsLocal(event) ? "local" : cloudPageAsking(event) ?? (workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin()) ? "server" : null) });
// Before the window, so the harness has the CUA descriptor on first render.
diff --git a/electron/place-look.d.mts b/electron/place-look.d.mts
index a1621bbcc7..fa2a8cf7b6 100644
--- a/electron/place-look.d.mts
+++ b/electron/place-look.d.mts
@@ -13,6 +13,9 @@ export type PlaceColorOutcome = "saved" | "refused" | "unsupported" | "failed";
export declare function swatchOf(color: unknown): import("./cloud-list.mjs").CloudSwatch | null;
export declare function listedCloudOf(entry: any, session?: { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null }): import("./cloud-list.mjs").CloudListEntry | null;
export declare function placeLook(entry: any, session?: { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null }): (PlaceLook & { cloudId?: string }) | null;
+export declare const SIGNED_IN: string;
+export declare function listedLook(cloud: import("./cloud-list.mjs").CloudListEntry | null | undefined): (PlaceLook & { cloudId?: string }) | null;
+export declare function railPaint(look: PlaceLook | null, color: unknown): { swatch: import("./cloud-list.mjs").CloudSwatch | null; locked?: "member" | "signed-out" } | null;
export declare function pageLook(look: (PlaceLook & { cloudId?: string }) | null): PlaceLook | null;
export declare function installPlaceLook(deps: {
ipcMain: { handle(channel: string, handler: (...args: any[]) => unknown): void };
@@ -21,4 +24,5 @@ export declare function installPlaceLook(deps: {
session: () => { clouds?: import("./cloud-list.mjs").CloudListEntry[] | null; homeOrigin?: string | null };
setColor: (cloudId: string, swatch: import("./cloud-list.mjs").CloudSwatch | null) => Promise<{ outcome: PlaceColorOutcome }>;
save: (id: string, color: import("./cloud-buy.mjs").CloudColor | null) => void;
+ rail?: { owns(event: unknown): boolean; places(): Array<{ id: string; paint?: unknown }>; saved(id: string): any };
}): { look(): (PlaceLook & { cloudId?: string }) | null };
diff --git a/electron/place-look.mjs b/electron/place-look.mjs
index fea53c2a3c..3a2b264900 100644
--- a/electron/place-look.mjs
+++ b/electron/place-look.mjs
@@ -3,9 +3,14 @@
// every app of theirs follows it: its owner or its team's Super admin and Admins change it there; everyone else sees it.
// A server the person connected by hand keeps the colour this app saved for it, and so does a Cloud an older Admin
// keeps no colour for. A page learns and changes only the colour of the place it is; this computer's own page has none.
+// The window's own rail changes the colour of any place it lists (a right-click on its circle), whatever that place's
+// server runs: the same rules, from this app's own page.
import environments from "./environments.cjs";
import { CLOUD_SWATCH_COLORS, CLOUD_SWATCHES, swatchColor } from "./cloud-list.mjs";
+/** The rail's id for a server of the person's own that signed in with their account and is not saved here. */
+export const SIGNED_IN = "signed-in:";
+
/** The swatch a saved colour is offered as (CLOUD_SWATCH_COLORS the other way); null for none, or a colour no swatch has. */
export function swatchOf(color) {
if (!environments.ENTRY_COLORS.includes(color)) return null;
@@ -43,6 +48,17 @@ export function placeLook(entry, { clouds = null, homeOrigin = null } = {}) {
return { ...base, change: "local" };
}
+/** A server of the person's own that signed in with their account, not saved here: its colour is the Admin's. */
+export function listedLook(cloud) {
+ if (!cloud) return null;
+ const swatch = CLOUD_SWATCHES.includes(cloud.color) ? cloud.color : null;
+ const base = { name: cloud.name, color: swatchColor(swatch), swatch };
+ return cloud.role === "member" ? { ...base, change: null, reason: "member" } : { ...base, change: "admin", cloudId: cloud.id };
+}
+
+/** What the rail's circle says of a look: the swatch of the colour it shows, and why only others change it, if so. */
+export const railPaint = (look, color) => (look ? { swatch: swatchOf(color), ...(look.change ? {} : { locked: look.reason ?? "member" }) } : null);
+
/** What the page sees of it: never the Cloud's id. */
export function pageLook(look) {
if (!look) return null;
@@ -55,22 +71,34 @@ export function pageLook(look) {
* each behind main's window guard. `place()`: the saved place on screen, which the guard made sure the asking page is;
* `session()`: the verified session's Clouds and My Cloud's address; `setColor(cloudId, swatch)`: the Admin's change
* (cloud-account.mjs setCloudColor); `save(id, color)`: this app's saved place, at once, so its circle and the top of
- * its sidebar follow before the session is read again.
+ * its sidebar follow before the session is read again. `rail`: the window's own rail, which changes the colour of any
+ * place it lists with a colour to show (`workspaces:recolor`, its circle's id and a swatch): `owns(event)` its page
+ * asks, `places()` railPlaces' list now, `saved(id)` that saved place.
*/
-export function installPlaceLook({ ipcMain, guard, place, session, setColor, save }) {
+export function installPlaceLook({ ipcMain, guard, place, session, setColor, save, rail = null }) {
const look = () => placeLook(place(), session());
- ipcMain.handle("workspaces:look", guard(() => pageLook(look())));
- ipcMain.handle("workspaces:color", guard(async (_event, swatch) => {
+ /** `entry`'s place (none: a server of theirs only the Admin lists) takes `swatch`; `now()` is its look at each step. */
+ const recolor = async (entry, now, swatch) => {
if (!(swatch === null || CLOUD_SWATCHES.includes(swatch))) throw new Error("Choose one of the colors.");
- const entry = place(), current = placeLook(entry, session());
+ const current = now();
if (!current) throw new Error("This place has no color to change.");
if (!current.change) return { outcome: "refused", look: pageLook(current) };
if (current.change === "admin") {
const result = await setColor(current.cloudId, swatch);
- if (result?.outcome !== "saved") return { outcome: result?.outcome === "refused" || result?.outcome === "unsupported" ? result.outcome : "failed", look: pageLook(look()) };
+ if (result?.outcome !== "saved") return { outcome: result?.outcome === "refused" || result?.outcome === "unsupported" ? result.outcome : "failed", look: pageLook(now()) };
}
- save(entry.id, swatchColor(swatch));
- return { outcome: "saved", look: pageLook(look()) };
- }));
+ if (entry) save(entry.id, swatchColor(swatch));
+ return { outcome: "saved", look: pageLook(now()) };
+ };
+ ipcMain.handle("workspaces:look", guard(() => pageLook(look())));
+ ipcMain.handle("workspaces:color", guard((_event, swatch) => recolor(place(), look, swatch)));
+ if (rail) ipcMain.handle("workspaces:recolor", (event, id, swatch) => {
+ if (!rail.owns(event)) throw new Error("workspaces:recolor is only available to the window's rail");
+ if (!rail.places().some(listed => listed.id === id && listed.paint)) return Promise.reject(new Error("That place isn't here any more."));
+ const entry = rail.saved(id);
+ const now = () => (entry ? placeLook(rail.saved(id) ?? entry, session())
+ : listedLook(session().clouds?.find(cloud => `${SIGNED_IN}${cloud.id}` === id && cloud.managed === false) ?? null));
+ return recolor(entry, now, swatch);
+ });
return { look };
}
diff --git a/electron/place-look.node-test.mjs b/electron/place-look.node-test.mjs
index 317d6d5a7f..004f7ed262 100644
--- a/electron/place-look.node-test.mjs
+++ b/electron/place-look.node-test.mjs
@@ -3,6 +3,7 @@ import test from "node:test";
import { listedColors, parseCloudList } from "./cloud-list.mjs";
import environments from "./environments.cjs";
+import { railPlaces } from "./cloud-rail.mjs";
import { createHomePlaces } from "./home-places.mjs";
import { installPlaceLook, pageLook, placeLook, swatchOf } from "./place-look.mjs";
@@ -73,6 +74,33 @@ test("a page changes only its own place's colour: a Cloud's on the Admin first,
await assert.rejects(computer.call("workspaces:color", "rose"), /no color/);
});
+test("the window's rail changes the colour of any place it lists, whatever its server runs: this app's for a server connected by hand, the Admin's for a Cloud and a signed-in server; never from a page, never an unlisted place", async () => {
+ const handlers = new Map(), asked = [], saved = [], RAIL = { id: "rail" };
+ const clouds = parseCloudList([CLOUDS[0], CLOUDS[1], cloud({ id: "c-acme", name: "Acme", teamId: "team-acme", role: "member", origin: TEAM }),
+ cloud({ id: "s-mini", name: "Mac mini", color: null, tier: null, runsOn: "server", managed: false, status: "ready", origin: null })]);
+ let state = { activeId: "home", environments: [home, own, team("member"), typed] };
+ const listed = () => railPlaces({ saved: state, home: null, mine: HOME, state: { status: "connected", clouds } });
+ installPlaceLook({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler,
+ place: () => state.environments.find(candidate => candidate.id === state.activeId) ?? null, session: () => ({ clouds, homeOrigin: HOME }),
+ setColor: async (id, swatch) => { asked.push([id, swatch]); return { outcome: "saved" }; },
+ save: (id, color) => { saved.push([id, color]); state = environments.withPlaceColor(state, id, color); },
+ rail: { owns: event => event.sender === RAIL, places: listed, saved: id => state.environments.find(entry => entry.id === id && entry.kind !== "local") ?? null } });
+ const recolor = (sender, ...args) => handlers.get("workspaces:recolor")({ sender }, ...args);
+ assert.deepEqual(await recolor(RAIL, "vps", "amber"), { outcome: "saved", look: { name: "Office", color: "yellow", swatch: "amber", change: "local" } },
+ "a server connected by hand, whatever release it runs: this app keeps it");
+ assert.deepEqual(listed().find(place => place.id === "vps").paint, { swatch: "amber" }, "its circle follows");
+ assert.equal((await recolor(RAIL, "a", "rose")).outcome, "saved");
+ assert.equal((await recolor(RAIL, "signed-in:s-mini", "blue")).outcome, "saved");
+ assert.deepEqual(asked, [["c-a", "rose"], ["s-mini", "blue"]], "a Cloud's and a signed-in server's on the Admin");
+ assert.deepEqual(saved, [["vps", "yellow"], ["a", "red"]], "a signed-in server not saved here has nothing here to change");
+ assert.deepEqual(await recolor(RAIL, "acme", "rose"), { outcome: "refused", look: { name: "Acme", color: null, swatch: null, change: null, reason: "member" } });
+ assert.equal(asked.length, 2, "a member's choice reaches nobody");
+ assert.throws(() => recolor({ id: "page" }, "vps", "rose"), /only available to the window's rail/, "no place's page, not even this computer's");
+ await assert.rejects(recolor(RAIL, "somewhere", "rose"), /isn't here/);
+ await assert.rejects(recolor(RAIL, "local", "rose"), /isn't here/, "this computer keeps today's look");
+ await assert.rejects(recolor(RAIL, "vps", "chartreuse"), /Choose one of the colors/);
+});
+
test("a saved place's colour: set, cleared to none, an unknown one ignored; the Admin's for My Cloud and teams once chosen there", () => {
const state = { activeId: "home", environments: [home, own, team("member"), typed, { id: "local", kind: "local", name: "Lab", dataDir: "/x" }] };
const red = environments.withPlaceColor(state, "vps", "red");
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 80f72b1a59..1876fbc56a 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -1,5 +1,5 @@
// contextIsolation stays on: the renderer sees only window.ogb, never Node or ipcRenderer.
-const { contextBridge, ipcRenderer, webUtils } = require("electron");
+const { contextBridge, ipcRenderer, webFrame, webUtils } = require("electron");
// Sandboxed preloads get Electron's restricted `require`, which cannot load sibling CommonJS files.
const desktopRemoteClient = process.argv.includes("--openmausbot-remote-client");
@@ -38,6 +38,29 @@ ipcRenderer.on("app:open-settings", (_event, section) => {
// The full bridge goes only to the local server's UI; a remote page gets the safe subset, and main enforces the same rule.
const localOrigin = process.argv.find((arg) => arg.startsWith("--omb-local-origin="))?.slice("--omb-local-origin=".length) ?? null;
const isLocalPage = !localOrigin || location.origin === localOrigin;
+
+// The window's own rail of places stands at its left edge (electron/chrome-rail.mjs): main says how wide, and every page
+// beside it, whatever server it comes from, moves over by that much, at any zoom (a zoom change resizes the page).
+let railBeside = 0, railRoom = null;
+function leaveRailRoom() {
+ if (typeof document === "undefined" || !document.documentElement) return;
+ const zoom = Number(webFrame?.getZoomFactor?.()) || 1;
+ if (!railBeside) { railRoom?.remove(); railRoom = null; return; }
+ railRoom ??= document.createElement("style");
+ railRoom.textContent = `html { box-sizing: border-box !important; padding-left: ${Math.round((railBeside / zoom) * 100) / 100}px !important; }`;
+ if (!railRoom.isConnected) (document.head ?? document.documentElement).append(railRoom);
+}
+ipcRenderer.on("rail:beside", (_event, width) => { railBeside = Math.max(0, Math.min(200, Number(width) || 0)); leaveRailRoom(); });
+// The rail's own page keeps its size whatever the zoom of this app's page: Chromium gives every page of a host the same
+// zoom, the rail's included, so the rail takes it back out and stays as wide as its strip.
+function railKeepsItsSize() {
+ if (!isLocalPage || location.pathname !== "/rail" || typeof document === "undefined" || !document.documentElement) return;
+ const zoom = Number(webFrame?.getZoomFactor?.()) || 1;
+ document.documentElement.style.zoom = zoom === 1 ? "" : String(Math.round((1 / zoom) * 10000) / 10000);
+}
+if (typeof window !== "undefined") {
+ for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });
+}
const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "cloudAdd", "cloudLending", "cloudPlan", "cloudSendPage", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "onOpenAppSettings", "exportDiagnostics", "openLogsFolder", "openAtLogin"];
@@ -116,12 +139,25 @@ const bridge = {
look: () => ipcRenderer.invoke("workspaces:look"),
color: (swatch) => isLocalPage || navigator.userActivation?.isActive === true
? ipcRenderer.invoke("workspaces:color", swatch === null ? null : String(swatch)) : Promise.reject(new Error("Choose a color.")),
+ // 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.")),
onChanged: (cb) => {
const handler = () => cb();
ipcRenderer.on("workspaces:changed", handler);
return () => ipcRenderer.removeListener("workspaces:changed", handler);
},
},
+ // The window's own rail (this app's page at /rail, beside every place's page): while a sheet of its own is open it
+ // covers the window; the skin of the page beside it comes from main.
+ rail: {
+ expand: (on) => ipcRenderer.invoke("rail:expand", on === true),
+ onSkin: (cb) => {
+ const handler = (_event, skin) => cb(String(skin));
+ ipcRenderer.on("rail:skin", handler);
+ return () => ipcRenderer.removeListener("rail:skin", handler);
+ },
+ },
// Buying another Cloud from the rail's +, on this app's page or a hosted Cloud's: plain words in, what the sheet says
// out; the account, the token and the checkout page stay in main. Only from the person's click where it opens anything.
cloudAdd: {
diff --git a/scripts/testing/rail-preview.tsx b/scripts/testing/rail-preview.tsx
index 7a69e7ab88..2a7257776f 100644
--- a/scripts/testing/rail-preview.tsx
+++ b/scripts/testing/rail-preview.tsx
@@ -14,7 +14,8 @@ import "../../src/styles.css";
// ?mode=simple Simple mode, ?sheet=add|server|cloud|name|connect opens +'s sheet there (?adding=setting_up: a Cloud
// being bought; connect: a signed-in server's), ?places=many the list past eight (?more opens it), ?places=servers the
// person's own servers that signed in. ?look=<colour>|none is the place's colour (its tint), ?member a team's Cloud
-// its member is on, ?settings=look Settings → Appearance at the place's colour.
+// its member is on, ?settings=look Settings → Appearance at the place's colour, ?menu=<id> that circle's own menu (a
+// right-click: its colour).
const params = new URLSearchParams(location.search);
setAnalyticsEnabled(false);
setEmailGateDone("skipped");
@@ -47,7 +48,10 @@ const tint = params.get("look") ?? (member ? "purple" : "blue");
const color = tint === "none" ? null : (tint as PlaceLook["color"]);
const listed = params.get("places") === "many" ? MANY : params.get("places") === "servers" ? SERVERS : FEW;
// The place on screen wears the colour its tint is drawn in.
-const rail: RailState = { places: listed.map(({ active: _active, ...entry }) => (entry.id === (member ? "acme" : "home") ? { ...entry, color, active: true as const } : entry)),
+// Every place but one still being made has its colour changed from its circle; a team's member only sees it.
+const painted = (entry: RailPlace): RailPlace => (entry.opens || entry.server ? { ...entry, paint: { swatch: entry.color ? SWATCH[entry.color] ?? null : null,
+ ...(member && entry.id === "acme" ? { locked: "member" as const } : {}) } } : entry);
+const rail: RailState = { places: listed.map(({ active: _active, ...entry }) => painted(entry.id === (member ? "acme" : "home") ? { ...entry, color, active: true as const } : entry)),
add: { cloud: true, link: true, address: false } };
let look: PlaceLook = { name: member ? "Acme team" : "My Cloud", color, swatch: color ? SWATCH[color] ?? null : null,
change: member ? null : "admin", ...(member ? { reason: "member" as const } : {}) };
@@ -74,6 +78,10 @@ Object.assign(window, { ogb: {
state: async () => ({ local: false, name: "My Cloud", origin: "https://omb-u-1.fly.dev", color: "blue" }),
menu: ok, line: async () => null, places: async () => rail, open: ok, add: ok, onChanged: () => () => {},
look: async () => look,
+ recolor: async (id: string, swatch: CloudSwatch) => {
+ rail.places = rail.places.map((entry) => (entry.id === id ? { ...entry, color: COLOR[swatch], paint: { swatch } } : entry));
+ return { outcome: "saved", look: null };
+ },
color: async (swatch: CloudSwatch) => { look = { ...look, swatch, color: COLOR[swatch] }; return { outcome: "saved", look }; },
},
cloudAdd: { state: async () => addView, start: async () => ({ outcome: "opened" }), reopen: async () => true, copyLink: async () => true, open: ok, interest: ok, sheet: ok },
@@ -107,3 +115,8 @@ if (params.get("settings") === "look") {
.then(() => document.querySelector("[data-place-look]")?.closest(".rounded-xl")?.scrollIntoView({ block: "center" }));
}
if (params.has("more")) void click("[data-rail-more-button]");
+const menu = params.get("menu");
+if (menu) {
+ const opened = () => { const circle = document.querySelector(`[data-rail-place="${menu}"]`); if (circle) circle.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); else setTimeout(opened, 100); };
+ opened();
+}
diff --git a/scripts/verify-cloud-rail.ts b/scripts/verify-cloud-rail.ts
index cb093d5c61..b247e296d2 100644
--- a/scripts/verify-cloud-rail.ts
+++ b/scripts/verify-cloud-rail.ts
@@ -31,6 +31,8 @@ const VIEWS: Array<{ name: string; query: string; ready: string; height?: number
{ name: "connect-server", query: "places=servers&sheet=connect", ready: "[data-place-add='connect-server']" },
{ name: "look-settings", query: "look=teal&settings=look", ready: "[data-place-look='admin']" },
{ name: "look-member", query: "member=1&settings=look", ready: "[data-place-look='locked']" },
+ { name: "rail-colour", query: "places=servers&look=teal&menu=vps", ready: "[data-rail-menu='vps']" },
+ { name: "rail-colour-member", query: "member=1&menu=acme", ready: "[data-rail-menu-note]" },
// The workspace's banner picture, kept on the fixture server first (each view after it shows it).
{ name: "banner", query: "", ready: "[data-place-banner] img", banner: true },
{ name: "banner-simple", query: "mode=simple", ready: "[data-place-banner] img", banner: true },
diff --git a/server/move-freeze.test.ts b/server/move-freeze.test.ts
index 033b09dd6a..40150b62ca 100644
--- a/server/move-freeze.test.ts
+++ b/server/move-freeze.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL } from "./move-freeze.ts";
+import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL, RAIL_PAGE } from "./move-freeze.ts";
import type { MoveWait } from "./move-waits.ts";
import { createMoveFreezeRoutes } from "./routes/move-freeze.ts";
import { PASS } from "./routes/table.ts";
@@ -66,7 +66,7 @@ describe("this computer's copy, frozen at the move", () => {
expect(freeze.cloud()).toBeNull();
freeze.freeze("https://omb-t-1.fly.dev");
for (const path of ["/", "/settings", "/desktop-viewer", "/pair", "/chats/b1"]) expect(freeze.screen(path), path).toBe(HOME_SCREEN);
- for (const path of [HOME_SCREEN, "/assets/index-1a2b.js", "/favicon.svg", "/manifest.webmanifest"]) expect(freeze.screen(path), path).toBeNull();
+ for (const path of [HOME_SCREEN, RAIL_PAGE, "/assets/index-1a2b.js", "/favicon.svg", "/manifest.webmanifest"]) expect(freeze.screen(path), path).toBeNull();
expect(freeze.cloud()).toBe("https://omb-t-1.fly.dev");
expect(createMoveFreeze({ dataDir: dir }).cloud(), "after a restart too").toBe("https://omb-t-1.fly.dev");
freeze.unfreeze();
diff --git a/server/move-freeze.ts b/server/move-freeze.ts
index 444231fc11..6e111c0b7b 100644
--- a/server/move-freeze.ts
+++ b/server/move-freeze.ts
@@ -15,6 +15,8 @@ import type { WebhookManager } from "./webhooks.ts";
export const MOVED_REFUSAL = "This bot lives on My Cloud now.";
/** The one page a frozen copy serves: the desktop app's screen while My Cloud can't be opened (electron/home-window.mjs). */
export const HOME_SCREEN = "/home";
+/** The desktop window's own rail of places (electron/chrome-rail.mjs): this app's page, beside whichever place is open. */
+export const RAIL_PAGE = "/rail";
/** A path whose last part has an extension is a file of the page (a script, a picture), never a page. */
const FILE = /\.[A-Za-z0-9]+$/u;
export const ENDED_REFUSAL = "My Cloud has ended. It is open only so you can take your things home.";
@@ -77,9 +79,10 @@ export function createMoveFreeze({ dataDir, exportOnly = false }: { dataDir: str
/** The Cloud this computer's bots moved to, as the freeze named it. */
cloud: () => movedTo,
refusal,
- /** Where a page of this computer's frozen copy goes instead: its home screen, never the frozen workspace. */
+ /** Where a page of this computer's frozen copy goes instead: its home screen, never the frozen workspace. The
+ * window's rail stays the rail: it shows no workspace, only the places main lists. */
screen(path: string): string | null {
- if (!frozen || exportOnly || path === HOME_SCREEN || FILE.test(path)) return null;
+ if (!frozen || exportOnly || path === HOME_SCREEN || path === RAIL_PAGE || FILE.test(path)) return null;
return HOME_SCREEN;
},
/** Starts it now unless this server is frozen; a freeze stops it, and lifting the freeze starts it again. */
diff --git a/src/components/ChromeRail.test.ts b/src/components/ChromeRail.test.ts
new file mode 100644
index 0000000000..0c96cf5a4b
--- /dev/null
+++ b/src/components/ChromeRail.test.ts
@@ -0,0 +1,30 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let root: Root | null = null;
+afterEach(async () => { await act(async () => root?.unmount()); root = null; document.body.innerHTML = ""; });
+
+it("the window's own rail wears the skin of the page beside it, never keeping it as its own choice", async () => {
+ let skinOf: (skin: string) => void = () => {};
+ const places = { places: [{ id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true }, { id: "vps", name: "Office", color: null, kind: "server", opens: true }],
+ add: { cloud: false, link: true, address: false } };
+ const applySkin = vi.fn(async () => true);
+ Object.assign(window, { ogb: { applySkin, workspaces: { places: vi.fn(async () => places), open: vi.fn(), add: vi.fn(), onChanged: () => () => {} },
+ rail: { expand: vi.fn(async () => {}), onSkin: (callback: (skin: string) => void) => { skinOf = callback; return () => {}; } } } });
+ const { ChromeRail } = await import("./ChromeRail");
+ const { refreshPlaces } = await import("@/lib/places");
+ const host = document.createElement("div"); document.body.append(host);
+ root = createRoot(host);
+ await act(async () => { await refreshPlaces(); root!.render(createElement(ChromeRail)); });
+ await act(async () => { await Promise.resolve(); });
+ expect(host.querySelectorAll("[data-rail-place]")).toHaveLength(2);
+ act(() => skinOf("midnight"));
+ expect(document.documentElement.dataset.skin).toBe("midnight");
+ act(() => skinOf("<b>"));
+ expect(document.documentElement.dataset.skin).toBe("midnight");
+ expect(applySkin, "the page's choice, never sent back to main as this one's").not.toHaveBeenCalled();
+});
diff --git a/src/components/ChromeRail.tsx b/src/components/ChromeRail.tsx
new file mode 100644
index 0000000000..9a58011a43
--- /dev/null
+++ b/src/components/ChromeRail.tsx
@@ -0,0 +1,18 @@
+import { useEffect, useState } from "react";
+import { setLocale } from "@/lib/i18n";
+import { effectiveLanguage, useLanguageChoice } from "@/lib/language-preference";
+import { wearSkin } from "@/lib/skins";
+import { DesktopCapabilitiesProvider } from "./DesktopCapabilities";
+import { PlacesRail } from "./PlacesRail";
+
+/** The window's own rail of places (main's chrome-rail.mjs): this app's page in a narrow view at the window's left edge,
+ * beside whichever place's page the window shows, in the skin and language of the app. Its sheets cover the window
+ * while open (main widens the view for them). */
+export function ChromeRail() {
+ const language = effectiveLanguage(useLanguageChoice(), undefined);
+ const [, setEpoch] = useState(0);
+ useEffect(() => { setLocale(language || globalThis.navigator?.language); setEpoch((epoch) => epoch + 1); }, [language]);
+ // The page beside the rail chose its skin: the rail wears the same one.
+ useEffect(() => window.ogb?.rail?.onSkin(wearSkin), []);
+ return <DesktopCapabilitiesProvider><div data-chrome-rail className="h-full"><PlacesRail chrome /></div></DesktopCapabilitiesProvider>;
+}
diff --git a/src/components/DesktopWorkspaceSwitcher.tsx b/src/components/DesktopWorkspaceSwitcher.tsx
index c3c28ed814..b62708e6a4 100644
--- a/src/components/DesktopWorkspaceSwitcher.tsx
+++ b/src/components/DesktopWorkspaceSwitcher.tsx
@@ -82,12 +82,12 @@ type SwitcherProps = {
compact?: boolean; inline?: boolean; pill?: boolean; rail?: boolean; cloudHome?: boolean; owner?: string | null; howTo?: boolean; onMenuClosed?: () => void;
};
-/** The place on screen and the native Server menu; where the rail of places shows (two places or more, a wide window), the
- * rail switches instead. */
+/** The place on screen and the native Server menu; where a rail of places stands beside the page, the rail switches
+ * instead: the window's own rail at every width, one drawn on the page on a wide window. */
export function DesktopWorkspaceSwitcher(props: SwitcherProps) {
- const besideRail = railShown(usePlaces());
+ const places = usePlaces();
const switcher = <Switcher {...props} />;
- return besideRail ? <div data-switcher-beside-rail className="contents md:hidden">{switcher}</div> : switcher;
+ return railShown(places) ? <div data-switcher-beside-rail className={places.beside ? "hidden" : "contents md:hidden"}>{switcher}</div> : switcher;
}
function Switcher({ compact = false, inline = false, pill = false, rail = false, cloudHome = false, owner = null, howTo = false, onMenuClosed }: SwitcherProps) {
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
index 491da2d110..73c919b56c 100644
--- a/src/components/PlacesRail.test.ts
+++ b/src/components/PlacesRail.test.ts
@@ -189,3 +189,63 @@ it("a server of the person's own on an older release than the newest has a quiet
expect(host.querySelector('[data-rail-place="s-old"] [data-rail-update]')).toBeNull();
expect(host.querySelector('[data-rail-place="s-old"] [data-rail-dot]')).toBeTruthy();
});
+
+it("the window's own rail: drawn at every width, the place on screen named under its circle, and its sheets cover the window while open", async () => {
+ const expand = vi.fn(async () => {});
+ Object.assign(window, { ogb: { workspaces, cloudAdd, rail: { expand, onSkin: () => () => {} } } });
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const nav = host.querySelector("[data-places-rail]")!;
+ expect(nav.className).toContain("flex h-full");
+ expect(nav.className, "never hidden on a narrow window").not.toContain("hidden");
+ expect([...host.querySelectorAll("[data-rail-caption]")].map((caption) => caption.textContent)).toEqual(["My Cloud"]);
+ expect(expand.mock.calls.at(-1)).toEqual([false]);
+ await click(host.querySelector("[data-rail-add]"));
+ expect(expand.mock.calls.at(-1), "+'s sheet covers the window").toEqual([true]);
+ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ await act(async () => { await Promise.resolve(); });
+ expect(expand.mock.calls.at(-1), "and gives it back once closed").toEqual([false]);
+});
+
+it("beside the window's own rail (main says so; the page never reads the list), the sidebar's switcher and Switch to… step aside at every width", async () => {
+ rail = { places: [], add: { cloud: false, link: false, address: false }, beside: true };
+ await mount(createElement("div", null, createElement(PlacesRail), createElement(DesktopWorkspaceSwitcher, { inline: true })));
+ expect(host.querySelector("[data-places-rail]"), "no rail drawn on the page itself").toBeNull();
+ expect(host.querySelector("[data-switcher-beside-rail]")?.className).toBe("hidden");
+ const { placeMenuItems } = await import("./SidebarProfileMenu");
+ const place = { bridge: workspaces, current: { local: false, name: "Office" }, cloudHome: false, onLine: "", openMenu: () => {}, switchable: true } as never;
+ expect(placeMenuItems(place, { owner: null, onCloudSettings: () => {} }).map((item) => item.key)).toEqual(["place", "switch-place"]);
+ expect(placeMenuItems(place, { owner: null, onCloudSettings: () => {}, besideRail: true }).map((item) => item.key), "one switcher: the rail").toEqual(["place"]);
+});
+
+it("a right-click on a circle opens its place's menu: its colour, saved by main whatever its server runs; a member sees who may change it; this computer has none", async () => {
+ const expand = vi.fn(async () => {});
+ const recolor = vi.fn(async () => ({ outcome: "saved" as const, look: null }));
+ rail = { places: [
+ place("local", "This computer", { kind: "computer", active: true }),
+ place("vps", "Office", { kind: "server", paint: { swatch: null } }),
+ place("acme", "Acme", { kind: "team", color: "purple", paint: { swatch: "violet", locked: "member" } }),
+ ], add: { cloud: false, link: true, address: false } };
+ Object.assign(window, { ogb: { workspaces: { ...workspaces, recolor }, cloudAdd, rail: { expand, onSkin: () => () => {} } } });
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const settle = () => act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });
+ const menuOf = async (id: string) => {
+ await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });
+ return host.querySelector(`[data-rail-menu="${id}"]`);
+ };
+ expect(await menuOf("local"), "this computer keeps today's look: no menu").toBeNull();
+ expect(expand.mock.calls.at(-1), "nor anything covering the window").toEqual([false]);
+ const menu = await menuOf("vps");
+ expect(menu?.getAttribute("aria-label")).toBe("Office");
+ expect(expand.mock.calls.at(-1), "the menu covers the window while open").toEqual([true]);
+ await click(menu!.querySelector("[data-swatch='green']"));
+ await settle();
+ expect(recolor).toHaveBeenCalledWith("vps", "green");
+ expect(host.querySelector("[data-rail-menu]"), "saved: the menu closes, and the circle follows main's list").toBeNull();
+ expect(expand.mock.calls.at(-1)).toEqual([false]);
+ const locked = await menuOf("acme");
+ expect(locked?.querySelector("[data-rail-menu-note]")?.textContent).toBe("Only its admins can change its color.");
+ expect([...locked!.querySelectorAll<HTMLButtonElement>("[data-swatch]")].every((swatch) => swatch.disabled), "a member sees it, and can't change it").toBe(true);
+ expect(locked!.querySelector("[aria-checked='true']")?.getAttribute("data-swatch")).toBe("violet");
+ await act(async () => { locked!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(host.querySelector("[data-rail-menu]")).toBeNull();
+});
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index 6c57f2d66a..3424296c09 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -1,18 +1,22 @@
// The rail at the window's left edge once a person has two places or more: one circle per Cloud, team's Cloud or server,
// the place on screen marked, ⋯ for the rest past eight, + last. Main lists the places and opens one by its id; the rail
-// never names an address.
-import { useEffect, useRef, useState, type CSSProperties } from "react";
+// 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.
+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";
+import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
import { track } from "@/lib/analytics";
import { cn } from "@/lib/cn";
import { cloudColor, cloudColorFill } from "@/lib/cloud-look";
import { activeLocale, t } from "@/lib/i18n";
import { localizedRelativeTime } from "@/lib/memory";
import { useAdvancedMode } from "@/lib/interface-mode";
-import { placeInitials, railShown, usePlaces, type RailPlace } from "@/lib/places";
+import { placeInitials, recolorPlace, usePlaces, type RailPlace } from "@/lib/places";
import { useDesktopCapabilities } from "./DesktopCapabilities";
import { MENU_ROW, MENU_SHEET } from "./menu-recipe";
import { PlaceAddSheet } from "./PlaceAddSheet";
+import { SwatchRadios } from "./SwatchRadios";
/** Circles before ⋯ opens the searchable list of every place. */
export const RAIL_SHOWN = 8;
@@ -72,10 +76,27 @@ export function PlaceMark({ place, size = CIRCLE }: { place: RailPlace; size?: n
</span>;
}
-function PlaceCircle({ place, calm, canPair, onOpen }: { place: RailPlace; calm: boolean; canPair: boolean; onOpen: (place: RailPlace) => void }) {
+/** 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. */
+const menuOpener = (place: RailPlace, onMenu: (at: MenuAt) => void) => (event: ReactMouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ if (place.paint) 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
+ * takes out the zoom it shares with this app's page). */
+export function topWithin(element: HTMLElement, rail: HTMLElement): number {
+ let top = 0;
+ for (let at: HTMLElement | null = element; at && at !== rail; at = at.offsetParent as HTMLElement | null) top += at.offsetTop;
+ for (let up = element.parentElement; up && up !== rail; up = up.parentElement) top -= up.scrollTop;
+ return top;
+}
+
+function PlaceCircle({ place, calm, canPair, onOpen, onMenu }: { place: RailPlace; calm: boolean; canPair: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void }) {
const label = placeLabel(place), acts = placeActs(place, canPair);
return <button type="button" aria-label={label} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true}
- data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts && !place.active) onOpen(place); }}
+ data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts && !place.active) onOpen(place); }} onContextMenu={menuOpener(place, onMenu)}
className={cn("relative shrink-0 rounded-full transition-[box-shadow,opacity] duration-150 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-focus",
place.active ? cn("ring-2 ring-offset-2 ring-offset-panel", calm ? "ring-ink/45" : "ring-ink/75")
: acts ? "hover:ring-2 hover:ring-ink/15 hover:ring-offset-2 hover:ring-offset-panel" : cn("cursor-default", !place.offline && "opacity-75"))}>
@@ -89,8 +110,40 @@ function PlaceCircle({ place, calm, canPair, onOpen }: { place: RailPlace; calm:
</button>;
}
+/** 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. */
+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;
+ const name = place.kind === "computer" ? t("rail.thisComputer") : place.name;
+ const choose = (swatch: CloudSwatch) => {
+ if (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")
+ : 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(); } }}>
+ <div className="flex items-center gap-2 px-2 pt-1">
+ <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)} />
+ </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>}
+ </div>;
+}
+
/** Every place, searchable: ⋯ once there are more than RAIL_SHOWN. */
-function MorePlaces({ places, canPair, onOpen, onClose }: { places: RailPlace[]; canPair: boolean; onOpen: (place: RailPlace) => void; onClose: () => void }) {
+function MorePlaces({ places, canPair, onOpen, onMenu, onClose }: { places: RailPlace[]; canPair: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void; onClose: () => void }) {
const [query, setQuery] = useState("");
const found = matchingPlaces(places, query);
return <div role="dialog" aria-label={t("rail.search")} data-rail-more className={cn("absolute bottom-0 left-full z-50 ml-2 w-64", MENU_SHEET)}
@@ -103,7 +156,8 @@ function MorePlaces({ places, canPair, onOpen, onClose }: { places: RailPlace[];
</label>
<ul className="max-h-72 overflow-y-auto">
{found.map((place) => <li key={place.id}>
- <button type="button" disabled={!placeActs(place, canPair)} aria-current={place.active ? "page" : undefined} onClick={() => { onOpen(place); onClose(); }} className={cn(MENU_ROW, "h-9")}>
+ <button type="button" disabled={!placeActs(place, canPair)} aria-current={place.active ? "page" : undefined} onClick={() => { onOpen(place); onClose(); }}
+ onContextMenu={menuOpener(place, (menu) => { onClose(); onMenu(menu); })} className={cn(MENU_ROW, "h-9")}>
<PlaceMark place={place} size={22} />
<span className="min-w-0 flex-1 truncate">{placeLabel(place)}</span>
</button>
@@ -113,21 +167,31 @@ function MorePlaces({ places, canPair, onOpen, onClose }: { places: RailPlace[];
</div>;
}
-export function PlacesRail() {
+/** `chrome`: the window's own rail (ChromeRail), drawn whatever the window's width, whose sheets ask main for the whole
+ * window while open. Without it, a rail drawn on a page from a list main gave that page: wide windows only. */
+export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
const state = usePlaces();
const calm = !useAdvancedMode();
const { capabilities } = useDesktopCapabilities();
const [more, setMore] = useState(false);
const [adding, setAdding] = useState(false);
const [connecting, setConnecting] = useState<string | null>(null);
+ const [menu, setMenu] = useState<{ place: RailPlace; top: number } | null>(null);
const moreRef = useRef<HTMLDivElement>(null);
+ const menuRef = useRef<HTMLDivElement>(null);
+ const navRef = useRef<HTMLElement>(null);
useEffect(() => {
- if (!more) return;
- const away = (event: MouseEvent) => { if (!moreRef.current?.contains(event.target as Node)) setMore(false); };
+ if (!more && !menu) return;
+ const away = (event: MouseEvent) => {
+ if (!moreRef.current?.contains(event.target as Node)) setMore(false);
+ if (!menuRef.current?.contains(event.target as Node)) setMenu(null);
+ };
window.addEventListener("mousedown", away);
return () => window.removeEventListener("mousedown", away);
- }, [more]);
- if (!railShown(state)) return null;
+ }, [more, menu]);
+ const covering = more || adding || connecting !== null || menu !== null;
+ useEffect(() => { if (chrome) void window.ogb?.rail?.expand(covering)?.catch(() => {}); }, [chrome, covering]);
+ if (!state.places.length) return null;
const bridge = window.ogb?.workspaces;
const open = (place: RailPlace) => {
if (!place.opens) { if (place.pairs) setConnecting(place.name); return; }
@@ -141,12 +205,23 @@ export function PlacesRail() {
const noDrag = draggable ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;
const shown = shownPlaces(state.places);
const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair;
- return <nav aria-label={t("rail.label")} data-places-rail style={drag}
- className={cn("relative hidden w-16 shrink-0 flex-col items-center bg-panel md:flex", calm ? "border-r border-ink/[0.04]" : "border-r border-hairline/50")}>
+ // The menu opens next to the circle or row it was asked from (measured now, while that row is there), within the rail.
+ const openMenu = ({ place, from }: MenuAt) => {
+ const nav = navRef.current;
+ setMenu({ place, top: nav ? Math.max(8, Math.min(topWithin(from, nav) - 6, nav.clientHeight - 200)) : 8 });
+ };
+ return <nav ref={navRef} aria-label={t("rail.label")} data-places-rail style={drag}
+ className={cn("relative w-16 shrink-0 flex-col items-center bg-panel", chrome ? "flex h-full" : "hidden md:flex", calm ? "border-r border-ink/[0.04]" : "border-r border-hairline/50")}>
{/* The macOS traffic lights sit over the rail's top; nothing here takes a click before they end. */}
<div aria-hidden="true" className={macInset ? "h-[52px] shrink-0" : "h-3 shrink-0"} />
<ul className="flex min-h-0 flex-col items-center gap-2.5 overflow-y-auto px-1 py-1" style={noDrag}>
- {shown.map((place) => <li key={place.id} className="flex"><PlaceCircle place={place} calm={calm} canPair={canPair} onOpen={open} /></li>)}
+ {shown.map((place) => <li key={place.id} className="flex flex-col items-center">
+ <PlaceCircle place={place} calm={calm} canPair={canPair} onOpen={open} onMenu={openMenu} />
+ {/* The place on screen, named: a server's own page may name it nowhere. */}
+ {place.active && <span aria-hidden="true" data-rail-caption className="mt-1 line-clamp-2 w-[60px] break-words text-center text-[11px] leading-tight text-ink-secondary">
+ {place.kind === "computer" ? t("rail.thisComputer") : place.name}
+ </span>}
+ </li>)}
</ul>
<div className="relative mt-2.5 flex flex-col items-center gap-2.5 pb-3" style={noDrag} ref={moreRef}>
{state.places.length > RAIL_SHOWN && <button type="button" aria-label={t("rail.more", { count: state.places.length })} title={t("rail.more", { count: state.places.length })}
@@ -154,12 +229,16 @@ export function PlacesRail() {
className="grid size-[38px] place-items-center rounded-full text-ink-secondary hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus aria-expanded:bg-ink/[0.06]">
<MoreHorizontal size={18} aria-hidden="true" />
</button>}
- {more && <MorePlaces places={state.places} canPair={canPair} onOpen={open} onClose={() => setMore(false)} />}
+ {more && <MorePlaces places={state.places} canPair={canPair} onOpen={open} onMenu={openMenu} onClose={() => setMore(false)} />}
{canAdd && <button type="button" aria-label={t("rail.add")} title={t("rail.add")} aria-haspopup="dialog" data-rail-add onClick={() => { track("rail_add", { step: "opened" }); setAdding(true); }}
className="grid size-[38px] place-items-center rounded-full border border-dashed border-ink/25 text-ink-secondary hover:border-ink/40 hover:bg-ink/[0.04] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
<Plus size={18} aria-hidden="true" />
</button>}
</div>
+ {/* The list is read again while it is open: the menu shows the place as main lists it now. */}
+ {menu && <div ref={menuRef} style={noDrag}>
+ <PlaceMenu key={menu.place.id} place={state.places.find((entry) => entry.id === menu.place.id) ?? menu.place} top={menu.top} onClose={() => setMenu(null)} />
+ </div>}
{adding && <PlaceAddSheet choices={state.add} onClose={() => setAdding(false)} />}
{connecting !== null && <PlaceAddSheet choices={state.add} connect={{ name: connecting }} onClose={() => setConnecting(null)} />}
</nav>;
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index a97fd0183e..8214e437e8 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -31,6 +31,7 @@ import { CloudTile } from "./cloud-buy/parts";
import { usageBridge } from "./CloudUsageMeter";
import { useCloudPlanSnapshot } from "./CloudTrialNotice";
import type { WorkspacePlace } from "./DesktopWorkspaceSwitcher";
+import { railShown, usePlaces } from "@/lib/places";
import { useAutomationsNeedYou } from "./SidebarFooterNav";
import { useCloudFilesReady } from "@/lib/cloud-files";
import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
@@ -350,9 +351,11 @@ export function accountLabel(name: string, { automationsNeedYou, update }: { aut
return [name, automationsNeedYou ? t("sidebar.account.automationsNeedYou") : "", update ?? ""].filter(Boolean).join(" · ");
}
-export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current" | "cloudHome" | "onLine" | "openMenu" | "switchable">, { owner, onCloudSettings }: {
+/** `besideRail`: the window's rail of places stands beside the page and switches places, so Switch to… isn't offered twice. */
+export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current" | "cloudHome" | "onLine" | "openMenu" | "switchable">, { owner, onCloudSettings, besideRail = false }: {
owner: string | null;
onCloudSettings: () => void;
+ besideRail?: boolean;
}): SidebarMenuItem[] {
const here = <Check size={15} aria-hidden="true" className="shrink-0 text-ink-secondary" />;
if (!place.switchable) {
@@ -365,7 +368,7 @@ export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current"
: current?.local === false || (place.cloudHome && !current) ? <Cloud size={16} /> : <Laptop size={16} />;
return [
...(current ? [{ key: "place", label: current.name, ...(place.cloudHome && place.onLine ? { subtitle: place.onLine } : {}), icon, trailing: here, onSelect: place.openMenu }] : []),
- { key: "switch-place", label: t("sidebar.menu.switchTo"), icon: <ArrowLeftRight size={16} />, onSelect: place.openMenu },
+ ...(besideRail ? [] : [{ key: "switch-place", label: t("sidebar.menu.switchTo"), icon: <ArrowLeftRight size={16} />, onSelect: place.openMenu }]),
];
}
@@ -549,6 +552,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
const name = profileLabel(profile);
const connectTo = (destination: PhoneDestination) => selectPhoneDestination(destination, { bridge: cloudPhone.bridge, dispatch });
const remote = window.ogb?.remoteClient?.active === true;
+ const besideRail = railShown(usePlaces());
const filesReady = useCloudFilesReady();
const cloudAccount = !remote && Boolean(window.ogb?.cloudAccount || (window.ogb?.cloudPlan && state.config?.cloudHome === true));
@@ -575,7 +579,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
onFiles: filesReady ? () => dispatch({ type: "showFiles" }) : undefined,
archived: account.archived,
}),
- places: placeMenuItems(account.place, { owner: account.owner, onCloudSettings: () => dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" }) }),
+ places: placeMenuItems(account.place, { owner: account.owner, besideRail, onCloudSettings: () => dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" }) }),
} } : {}),
onUsage: () => dispatch({ type: "toggleAppSettings", open: true, section: "usage" }),
onSettings: () => dispatch({ type: "toggleAppSettings" }),
diff --git a/src/lib/places.ts b/src/lib/places.ts
index 7b735c975a..fe129f7927 100644
--- a/src/lib/places.ts
+++ b/src/lib/places.ts
@@ -1,5 +1,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";
const NONE: RailState = { places: [], add: { cloud: false, link: false, address: false } };
let current: RailState = NONE;
@@ -43,8 +45,18 @@ export function usePlaces(): RailState {
return state;
}
-/** Whether the rail shows on this page: main lists places only when there are at least two. */
-export const railShown = (state: RailState): boolean => state.places.length > 0;
+/** A place's colour, chosen in its menu on the window's rail: main saves it (on the Admin for a Cloud) whatever that
+ * place's server runs, and the circle shows it once the list is read again. */
+export async function recolorPlace(id: string, swatch: CloudSwatch | null): Promise<PlaceColorOutcome> {
+ const answer = await bridge()?.recolor?.(id, swatch).catch(() => null);
+ if (!answer) return "failed";
+ if (answer.outcome === "saved") 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;
/** A circle's letters: the first of up to two words, so "Client A" is CA and "Acme" is A. */
export function placeInitials(name: string): string {
diff --git a/src/lib/skins.ts b/src/lib/skins.ts
index d94debdd81..49e94702c2 100644
--- a/src/lib/skins.ts
+++ b/src/lib/skins.ts
@@ -125,6 +125,14 @@ function followSystem(follow: boolean): void {
}
}
+/** Wears a skin another page chose, without keeping it as this page's own choice or telling the app (the window's rail
+ * wearing the skin of the page beside it). */
+export function wearSkin(value: unknown): void {
+ if (!isSkinId(value)) return;
+ document.documentElement.dataset.skin = value;
+ for (const listener of listeners) listener();
+}
+
export function applySkinChoice(choice: SkinChoice): void {
try {
getStore()?.setItem(KEY, choice);
diff --git a/src/main.tsx b/src/main.tsx
index 5d2bb29da3..15a20c7b99 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -23,6 +23,12 @@ applyChatWidth(readChatWidth());
async function chooseRoot(): Promise<React.ReactNode> {
const home = window.ogb?.home;
if (location.pathname === "/home" && home) return <HomeScreen bridge={home} manage={window.ogb?.cloudPlan?.manage} />;
+ // The window's own rail of places (electron/chrome-rail.mjs): see-through but for the rail and its open sheets.
+ if (location.pathname === "/rail" && window.ogb?.rail) {
+ document.documentElement.style.background = document.body.style.background = "transparent";
+ const { ChromeRail } = await import("./components/ChromeRail");
+ return <ChromeRail />;
+ }
if (location.pathname === "/pair") {
const signIn = takeBrowserSignInFromLocation();
if (signIn) {
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index b79fff24d5..64e874d4ba 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -155,6 +155,9 @@ const __APP_VERSION__: string;
cancel(): Promise<void>;
onState(callback: (state: CompanyBackupState) => void): () => void;
};
+ /** The window's own rail of places (its page at /rail): a sheet of its own covers the window while open; the skin
+ * of the page beside it comes from main. */
+ rail?: { expand(on: boolean): Promise<void>; onSkin(callback: (skin: string) => void): () => void };
workspaces?: {
/** `color`: a saved server's colour name (its owner chose it while setting the Cloud up); `home`: this window's
* home is this Cloud, so there is nothing to switch to. */
@@ -175,6 +178,9 @@ const __APP_VERSION__: string;
look?: () => Promise<import("../../electron/place-look.mjs").PlaceLook | null>;
/** That place's colour, from the person's click: one of the six swatches, or null for none. */
color?: (swatch: import("../../electron/cloud-list.mjs").CloudSwatch | null) => Promise<{ outcome: import("../../electron/place-look.mjs").PlaceColorOutcome; look: import("../../electron/place-look.mjs").PlaceLook | null }>;
+ /** 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 }>;
/** Main's word that the places or the sign-in changed: read them again. */
onChanged?: (callback: () => void) => () => void;
};