Skip to content

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

This Mac on the rail: a fresh place on this computer for Cloud owners

milind-sonie527aded812a
diff --git a/docs/pr-screenshots/rail-this-mac/1-my-cloud-with-this-mac-on-the-rail.png b/docs/pr-screenshots/rail-this-mac/1-my-cloud-with-this-mac-on-the-rail.png
new file mode 100644
index 0000000000..bb46da0afb
Binary files /dev/null and b/docs/pr-screenshots/rail-this-mac/1-my-cloud-with-this-mac-on-the-rail.png differ
diff --git a/docs/pr-screenshots/rail-this-mac/2-this-mac-fresh.png b/docs/pr-screenshots/rail-this-mac/2-this-mac-fresh.png
new file mode 100644
index 0000000000..4d0ba1836e
Binary files /dev/null and b/docs/pr-screenshots/rail-this-mac/2-this-mac-fresh.png differ
diff --git a/docs/pr-screenshots/rail-this-mac/3-back-on-my-cloud.png b/docs/pr-screenshots/rail-this-mac/3-back-on-my-cloud.png
new file mode 100644
index 0000000000..2f3ec4b2db
Binary files /dev/null and b/docs/pr-screenshots/rail-this-mac/3-back-on-my-cloud.png differ
diff --git a/docs/pr-screenshots/rail-this-mac/4-this-mac-again.png b/docs/pr-screenshots/rail-this-mac/4-this-mac-again.png
new file mode 100644
index 0000000000..89f6f69b80
Binary files /dev/null and b/docs/pr-screenshots/rail-this-mac/4-this-mac-again.png differ
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index 6e9d8daefb..433adb7365 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -86,6 +86,39 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
pairing steps, and one only reachable on its own network with nothing to
open.
+## This Mac, once My Cloud is home
+
+Once a person's bots moved to My Cloud, this computer's own copy is frozen and
+is never a place again. The rail then shows This Mac (This PC on Windows and
+Linux) first, beside My Cloud: a separate place on this computer, with its own
+bots. A click starts it fresh in a folder of its own beside the data folder
+(`~/.openmausbot-profiles/default`, a profile by its stable id; more profiles
+would be more folders there), on the same address, one server at a time, as a
+local environment switch does. Nothing moves either way, the frozen copy keeps
+its marker and its bots, and the move's code never reaches the profile. A line
+on its page says the bots from before are on My Cloud and that an older copy
+comes in from Settings → Backups. My Cloud on the rail goes back; the profile
+keeps running, so This Mac is one click again. Every launch opens My Cloud.
+This computer stays lent to My Cloud throughout: lending follows the sign-in,
+and only the clean workspace for nobody who can reach the bots stops it. People
+with no Cloud see no change.
+
+```sh
+node --test electron/clean-workspace.node-test.mjs electron/home-window-profile.node-test.mjs electron/home-window-clean.node-test.mjs electron/cloud-rail.node-test.mjs electron/lending-target.node-test.mjs
+pnpm exec vitest run src/components/PlacesRail.test.ts src/components/HomeLine.test.ts
+OMB_UI_E2E=1 pnpm exec vitest run scripts/testing/rail-profile-ui.e2e.test.ts
+```
+
+`scripts/testing/rail-profile-ui.e2e.test.ts` runs main's own handlers in a
+headless Chrome (`launchHomeWorld` with `profiles`): My Cloud a real Cloud-mode
+server with the bots, this computer its real frozen server until This Mac
+restarts it on the profile's folder, the rail's own page in a tab of its own,
+and this computer really lent to My Cloud on the window's session. It clicks
+This Mac on the rail (an empty place, the line, the marker untouched), then My
+Cloud (the Cloud's bots), then This Mac again (what was made there is still
+there, with no restart), watching the lent link every 50 ms all the while: it
+never drops. Each picture is the rail beside the page, as the window shows them.
+
## Automated fixtures
```sh
diff --git a/electron/clean-workspace.d.mts b/electron/clean-workspace.d.mts
index 9d703ce190..d06c276d85 100644
--- a/electron/clean-workspace.d.mts
+++ b/electron/clean-workspace.d.mts
@@ -1,10 +1,17 @@
export function cleanWorkspaceDir(dataDir: string): string;
+/** The folder beside the data folder that holds one folder per profile, each named by its id. */
+export function profilesDir(dataDir: string): string;
+export function profileDir(dataDir: string, id: string): string;
+export declare const DEFAULT_PROFILE: "default";
export function cleanWorkspaceConfig(language?: string | null, now?: Date): { language?: string; onboarding: { completedAt: string; version: number; hintsSeen: string[] } };
export interface CleanWorkspace {
active(): boolean;
+ stranded(): boolean;
+ profile(): string | null;
ownCopy(): boolean;
marker(): { frozen: boolean; cloud?: string; place?: string };
enter(): Promise<boolean>;
+ open(id?: string): Promise<boolean>;
leave(): Promise<boolean>;
holding<T>(work: () => Promise<T>): Promise<T>;
realCopy(request: (route: string, init?: RequestInit) => Promise<Response>): (route: string, init?: RequestInit) => Promise<Response>;
diff --git a/electron/clean-workspace.mjs b/electron/clean-workspace.mjs
index 6916a333f2..182112b854 100644
--- a/electron/clean-workspace.mjs
+++ b/electron/clean-workspace.mjs
@@ -7,6 +7,10 @@
// and no page of it can show. It sits beside the data folder, not in it: a move carries that folder and forgetting the frozen
// copy empties it, and neither ever reaches this one. Nothing made here is merged anywhere.
//
+// A person signed in to the Cloud their bots moved to can open a workspace of this computer's own from the rail too: a
+// profile, one folder per profile under one folder beside the data folder, named by its stable id. It is fresh, the same
+// swap opens it, and this computer stays lent to their Cloud while it runs, since that account is the one lending answers to.
+//
// Security: the move's code knows one server, this computer's own copy. A top-up, a send or a lift pointed at the clean
// workspace would upload it over the person's Cloud or report a freeze lifted that wasn't, so while the clean workspace runs
// `realCopy` answers only what the copy's own files can say, and refuses the rest; `holding` brings the copy back first for
@@ -24,6 +28,11 @@ const NO_MOVE_POPUP = "grok-move-2026-11";
const CLEAN = "clean-workspace";
export const cleanWorkspaceDir = (dataDir) => `${dataDir}-clean`;
+export const profilesDir = (dataDir) => `${dataDir}-profiles`;
+/** The profile the rail calls This Mac (or This PC). */
+export const DEFAULT_PROFILE = "default";
+const PROFILE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+export const profileDir = (dataDir, id) => path.join(profilesDir(dataDir), id);
/** A clean workspace's first config: never the new-user setup, which would read as the person's bots being gone. Connecting
* an AI isn't part of this: the page's line offers it while none works (HomeLine). */
@@ -46,7 +55,12 @@ export function cleanWorkspaceConfig(language = null, now = new Date()) {
*/
export function createCleanWorkspace({ dataDir, running, swap, allowed = () => true, changed = () => {}, log = () => {}, fs = nodeFs, t = nativeText.englishText.t }) {
const folder = () => cleanWorkspaceDir(dataDir());
- const active = () => running() === folder();
+ const stranded = () => running() === folder();
+ const profile = () => {
+ const dir = running();
+ return typeof dir === "string" && path.dirname(dir) === profilesDir(dataDir()) && PROFILE_ID.test(path.basename(dir)) ? path.basename(dir) : null;
+ };
+ const active = () => stranded() || profile() !== null;
let held = 0, swapping = false;
/** This computer's own copy is the server that answers now: not the clean workspace, and not on its way between them. */
const ownCopy = () => !active() && !swapping;
@@ -85,11 +99,16 @@ export function createCleanWorkspace({ dataDir, running, swap, allowed = () => t
}
return {
+ /** The clean workspace or a profile runs, not this computer's own copy. */
active,
+ /** The clean workspace for nobody here who can reach the bots runs: nothing is lent from it. */
+ stranded,
+ /** The id of the profile that runs, or null. */
+ profile,
ownCopy,
marker,
/** Opens the clean workspace; true once it runs. False when it can't, and the window says why as before. A named local
- * environment the person chose is no frozen copy, so it stays. */
+ * environment the person chose is no frozen copy, so it stays, and so does a profile. */
enter: () => inTurn(async () => {
if (active()) return true;
if (!allowed() || held > 0) return false;
@@ -97,6 +116,15 @@ export function createCleanWorkspace({ dataDir, running, swap, allowed = () => t
try { seed(folder()); } catch (error) { log(`clean workspace: could not set it up (${error?.message ?? error})`); return false; }
return swapTo(folder());
}),
+ /** Opens profile `id`, set up fresh the first time; true once it runs. */
+ open: (id = DEFAULT_PROFILE) => inTurn(async () => {
+ if (!PROFILE_ID.test(id)) return false;
+ if (profile() === id) return true;
+ if (!allowed() || held > 0) return false;
+ const dir = profileDir(dataDir(), id);
+ try { seed(dir); } catch (error) { log(`profile ${id}: could not set it up (${error?.message ?? error})`); return false; }
+ return swapTo(dir);
+ }),
leave,
/** Runs `work` on this computer's own copy, its server back first, and nothing opens the clean workspace meanwhile. */
async holding(work) {
diff --git a/electron/clean-workspace.node-test.mjs b/electron/clean-workspace.node-test.mjs
index f54bebc973..a976a3d8d9 100644
--- a/electron/clean-workspace.node-test.mjs
+++ b/electron/clean-workspace.node-test.mjs
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { cleanWorkspaceConfig, cleanWorkspaceDir, createCleanWorkspace } from "./clean-workspace.mjs";
+import { cleanWorkspaceConfig, cleanWorkspaceDir, createCleanWorkspace, DEFAULT_PROFILE, profileDir, profilesDir } from "./clean-workspace.mjs";
import { cloudLendingVerdict } from "./computer-sharing.mjs";
import { createLendingTarget } from "./lending-target.mjs";
import { installOneHome } from "./one-home-main.mjs";
@@ -275,7 +275,7 @@ test("no lending from the clean workspace: nothing is lent or asked while it run
const w = computer(t);
const env = { id: "c", origin: CLOUD, cloud: { id: "c" } };
const state = { status: "connected", account: owner, machine: { status: "ready", origin: CLOUD } };
- const target = createLendingTarget({ account: () => (w.clean.active() ? null : { state: () => state, isOwnCloud: () => true, ownClouds: () => [] }), environments: () => [env] });
+ const target = createLendingTarget({ account: () => ({ state: () => state, isOwnCloud: () => true, ownClouds: () => [] }), clean: w.clean, environments: () => [env] });
const grant = { accountId: owner.id, origin: CLOUD };
assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true });
await w.clean.enter();
@@ -285,3 +285,59 @@ test("no lending from the clean workspace: nothing is lent or asked while it run
await w.clean.leave();
assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true });
});
+
+test("a profile sits in a folder of its own, by its stable id, under one folder beside the data folder: never in the frozen copy's", () => {
+ assert.equal(profilesDir("/Users/a/.openmausbot"), "/Users/a/.openmausbot-profiles");
+ assert.equal(profileDir("/Users/a/.openmausbot", DEFAULT_PROFILE), join("/Users/a/.openmausbot-profiles", "default"));
+});
+
+test("This Mac's profile opens fresh on its own folder, and the frozen copy stays frozen: its marker, its bots and its config untouched", async (t) => {
+ const w = computer(t);
+ w.write("config.json", JSON.stringify({ language: "pt-BR", providers: { key: "secret-of-the-frozen-copy" } }));
+ w.write("bots.json", JSON.stringify([{ id: "nova" }]));
+ const dir = profileDir(w.dataDir, DEFAULT_PROFILE);
+ assert.equal(await w.clean.open(), true);
+ assert.deepEqual(w.swaps, [dir]);
+ assert.deepEqual([w.clean.active(), w.clean.profile(), w.clean.stranded(), w.clean.ownCopy()], [true, DEFAULT_PROFILE, false, false]);
+ assert.equal(w.changes, 1, "lending looks again");
+ const config = JSON.parse(readFileSync(join(dir, "config.json"), "utf8"));
+ assert.deepEqual(Object.keys(config).sort(), ["language", "onboarding"], "fresh: nothing of the frozen copy's but its language");
+ assert.equal(existsSync(join(dir, "bots.json")), false);
+ assert.deepEqual(JSON.parse(readFileSync(join(w.dataDir, "moved.json"), "utf8")), { v: 1, at: 1, cloud: CLOUD }, "never unfrozen");
+ assert.equal(readFileSync(join(w.dataDir, "bots.json"), "utf8"), JSON.stringify([{ id: "nova" }]));
+ assert.equal(JSON.parse(readFileSync(join(w.dataDir, "config.json"), "utf8")).providers.key, "secret-of-the-frozen-copy");
+ assert.equal(existsSync(w.cleanDir), false, "the workspace for nobody signed in is another folder");
+ assert.equal(await w.clean.open(DEFAULT_PROFILE), true);
+ assert.deepEqual(w.swaps, [dir], "open already: no second start");
+ writeFileSync(join(dir, "config.json"), JSON.stringify({ theirs: true }));
+ assert.equal(await w.clean.leave(), true);
+ assert.equal(w.running, w.dataDir);
+ assert.equal(await w.clean.open(), true);
+ assert.deepEqual(JSON.parse(readFileSync(join(dir, "config.json"), "utf8")), { theirs: true }, "what they made there stays");
+});
+
+test("a profile id is a folder name and nothing else, and the move's code never reaches a profile", async (t) => {
+ const w = computer(t);
+ for (const id of ["../.openmausbot", "", "Work", "a/b", "."]) assert.equal(await w.clean.open(id), false, id);
+ assert.deepEqual(w.swaps, []);
+ await w.clean.open();
+ const request = w.clean.realCopy(w.request);
+ assert.deepEqual(await (await request("/api/move/freeze")).json(), { frozen: true, cloud: CLOUD }, "the frozen copy's own marker");
+ await assert.rejects(request("/api/move/freeze", { method: "DELETE" }), (error) => error.code === "clean-workspace");
+ await assert.rejects(request("/api/bots"), (error) => error.code === "clean-workspace");
+ assert.deepEqual(w.requests, []);
+});
+
+test("lending goes on from a profile: the sign-in alone decides, and only the workspace for nobody who can reach the bots stops it", async (t) => {
+ const w = computer(t);
+ const env = { id: "c", origin: CLOUD, cloud: { id: "c" } };
+ let state = { status: "connected", account: owner, machine: { status: "ready", origin: CLOUD } };
+ const target = createLendingTarget({ account: () => ({ state: () => state, isOwnCloud: () => true }), clean: w.clean, environments: () => [env] });
+ const grant = { accountId: owner.id, origin: CLOUD };
+ await w.clean.open();
+ assert.equal(target.environment(), env);
+ assert.deepEqual(target.places(), [env]);
+ assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true });
+ state = { status: "signed-out", account: null, machine: null };
+ assert.notDeepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true }, "signed out: nothing is lent, profile or not");
+});
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
index e40148f8ba..f50ff6652f 100644
--- a/electron/cloud-rail.d.mts
+++ b/electron/cloud-rail.d.mts
@@ -7,6 +7,8 @@ export interface RailPlace {
/** This computer, a Cloud of the person's own (My Cloud included), a team's Cloud, a server they connected by hand, or an
* account signed in here with no place of its own to show. */
kind: "computer" | "cloud" | "team" | "server" | "account";
+ /** A workspace of this computer's own, by its profile id, once My Cloud is home: the default one is This Mac (or This PC). */
+ profile?: string;
/** With several accounts signed in here: which group it is in (a divider stands between groups). None with one account. */
group?: string;
/** With several accounts signed in here: the address of the account it belongs to. Only the rail's own page gets this. */
@@ -77,6 +79,7 @@ export type AddCloudView =
};
};
export declare const RAIL_MIN_PLACES: number;
+export declare const PROFILE_PLACE: "profile:";
/** main's own circles: each as the page sees it, plus the Cloud main acts on for it (never sent to a page). */
-export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown; offers?: (entry: any) => boolean; waiting?: (id: string) => boolean }): Array<RailPlace & { cloudId?: string }>;
+export declare function railPlaces(input: { saved: { environments: any[]; activeId: string }; home?: string | null; mine?: string | null; state?: unknown; offers?: (entry: any) => boolean; waiting?: (id: string) => boolean; accounts?: any[]; profiles?: Array<{ id: string; active?: boolean }> }): Array<RailPlace & { cloudId?: string }>;
export declare function addCloudView(state: unknown, offer: import("./cloud-home.mjs").CloudOffer | null): AddCloudView;
diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjs
index 4ba4a17aad..99b8a6a5a9 100644
--- a/electron/cloud-rail.mjs
+++ b/electron/cloud-rail.mjs
@@ -17,6 +17,8 @@ import { withAccounts } from "./rail-accounts.mjs";
export const RAIL_MIN_PLACES = 2;
const PENDING = "pending:";
+/** A circle for a workspace of this computer's own (a profile, clean-workspace.mjs), by the profile's id. */
+export const PROFILE_PLACE = "profile:";
/** 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
@@ -63,10 +65,11 @@ const unlisted = (entry, { clouds, home, mine }) => Array.isArray(clouds) && (en
* as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.
* `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs). `waiting(id)`: inbox lines
* wait in that place, and the window shows another (place-inbox-watch.mjs). `accounts`: the other accounts signed in on this
- * device, each with its places as they were kept: grouped by account after these (withAccounts).
- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean, accounts?: any[] }} input
+ * device, each with its places as they were kept: grouped by account after these (withAccounts). `profiles`: once My Cloud is
+ * home, the workspaces of this computer's own it may open instead (`active`: the one on screen), first, as This computer was.
+ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean, accounts?: any[], profiles?: Array<{ id: string, active?: boolean }> }} input
*/
-export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [] }) {
+export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [], profiles = [] }) {
const connected = state?.status === "connected" ? state : null;
const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];
const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };
@@ -84,7 +87,9 @@ export function railPlaces({ saved, home = null, mine = null, state = null, offe
...(cloud.origin ? { pairs: true } : { ownNetwork: true }), ...serverState(cloud, connected?.latestVersion ?? null) }));
const places = [...remote, ...servers, ...making];
const computer = environments.savedPlace(saved, environments.LOCAL_ID), color = computer.color ?? null;
- const all = home ? places : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),
+ const own = profiles.map(profile => ({ id: `${PROFILE_PLACE}${profile.id}`, name: computer.name, color: null, kind: "computer", profile: profile.id, opens: true,
+ ...(profile.active ? { active: true } : {}) }));
+ const all = home ? [...own, ...places] : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),
...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}), ...(waiting(computer.id) ? { attention: true } : {}) }, ...places];
if (accounts.length) return withAccounts(all, { saved, accounts, email: state?.account?.email ?? null });
return all.length < (clouds.some(ownCloud) ? 1 : RAIL_MIN_PLACES) ? [] : all;
@@ -145,8 +150,9 @@ const CHOICES = Object.freeze(["cloud", "link", "address"]);
* `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; `makeHome(id)` starts the move to a server
* of the person's own (own-home-main.mjs `start`). `switchAccount(id)`: that account becomes the one in use (cloud-accounts.mjs).
+ * `openProfile(id)`: the window shows that workspace of this computer's own (home-window.mjs `openProfile`).
*/
-export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null, switchAccount = null, t = nativeText.englishText.t }) {
+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null, switchAccount = null, openProfile = null, t = nativeText.englishText.t }) {
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`);
@@ -164,7 +170,12 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places().map(seen), add: choices() }
: { places: [], add: { cloud: false, link: false, address: false, organization: false }, ...(beside() ? { beside: true } : {}) })));
// A Cloud the Admin is still making has no saved place: its own screen opens, by main's word for which Cloud it is.
- const opening = place => (place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id));
+ const opening = place => {
+ if (place.id.startsWith(PENDING)) return openCloud(place.cloudId);
+ if (!place.profile) return open(place.id);
+ if (!openProfile) throw new Error(t("native.places.noLongerHere"));
+ return openProfile(place.profile);
+ };
// A place of another account: that account becomes the one in use first, and nothing moves if it can't. By then the place is
// listed as that account's own; an account with no place of its own is simply where the window goes.
const switchingTo = async place => {
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
index e59d40c474..e546b97b55 100644
--- a/electron/cloud-rail.node-test.mjs
+++ b/electron/cloud-rail.node-test.mjs
@@ -376,3 +376,31 @@ test("a place with inbox lines waiting says so on its circle, this computer's to
assert.equal(places.find(place => place.id === "vps").attention, undefined);
assert.equal(railPlaces({ saved: saved("home"), mine: HOME, state: session() }).find(place => place.id === "a").attention, undefined, "with nothing to say, nothing fires");
});
+
+test("once My Cloud is home, This Mac is a circle of its own, first, by its profile id: the frozen copy is never a place again", () => {
+ const places = railPlaces({ saved: saved("home"), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }] });
+ assert.deepEqual(places.map(place => place.id), ["profile:default", "home", "a", "acme", "vps"]);
+ assert.deepEqual(places[0], { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true });
+ assert.equal(places.some(place => place.id === "local"), false, "nothing opens the frozen copy");
+ assert.equal(places.find(place => place.id === "home").active, true, "My Cloud is the place on screen");
+ const shown = railPlaces({ saved: saved("local"), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default", active: true }] });
+ assert.deepEqual(shown.filter(place => place.active).map(place => place.id), ["profile:default"]);
+ 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]) }), profiles: [{ id: "default" }] }).map(place => place.id),
+ ["profile:default", "home"], "My Cloud and This Mac: a rail of two");
+ assert.deepEqual(railPlaces({ saved: alone, home: null, mine: HOME, state: session({ teams: [], clouds: parseCloudList([PRIMARY]) }), profiles: [] }).map(place => place.id), ["local", "home"],
+ "before the move nothing changes: This computer is the place it always was");
+ assert.deepEqual(railPlaces({ saved: { activeId: "local", environments: [] }, home: null, state: null }), [], "no Cloud: no rail, as before");
+});
+
+test("a profile's circle opens it by main's own word for it: only one main listed, and never through the switch to the frozen copy", async () => {
+ const profiles = [];
+ const r = rail({ places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }] }), openProfile: id => { profiles.push(id); } });
+ await r.call("workspaces:open", "profile:default");
+ assert.deepEqual([profiles, r.opened], [["default"], []]);
+ assert.throws(() => r.call("workspaces:open", "profile:work"), /isn't here/);
+ assert.throws(() => r.call("workspaces:open", "local"), /isn't here/);
+ const older = rail({ places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }] }) });
+ assert.throws(() => older.call("workspaces:open", "profile:default"), /isn't here/, "a main with no profiles opens none");
+ assert.deepEqual(older.opened, []);
+});
diff --git a/electron/home-window-profile.node-test.mjs b/electron/home-window-profile.node-test.mjs
new file mode 100644
index 0000000000..2388df2415
--- /dev/null
+++ b/electron/home-window-profile.node-test.mjs
@@ -0,0 +1,92 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ACCOUNT, CLOUD, connected, LOCAL, world } from "./fixtures/home-window-world.mjs";
+
+// This Mac on the rail while My Cloud is home (clean-workspace.mjs `open`): the window shows a profile of this computer's own,
+// My Cloud is one click away, and a launch still opens My Cloud.
+function profiles() {
+ const side = { running: "copy", opened: [], enters: 0, leaves: 0, fails: false,
+ active: () => side.running !== "copy",
+ profile: () => (side.running.startsWith("profile:") ? side.running.slice("profile:".length) : null),
+ open: async (id) => { side.opened.push(id); if (side.fails) return false; side.running = `profile:${id}`; return true; },
+ enter: async () => { side.enters++; if (side.running === "copy") side.running = "clean"; return true; },
+ leave: async () => { side.leaves++; side.running = "copy"; return true; } };
+ return side;
+}
+
+test("This Mac from the rail: the profile opens on this computer's page, and My Cloud is one click back with the profile still running", async () => {
+ const clean = profiles(), w = world({ clean });
+ await w.home.show();
+ assert.deepEqual(w.went, [[CLOUD, CLOUD]]);
+ w.url = `${CLOUD}/`;
+ assert.equal(await w.home.openProfile("default"), true);
+ assert.deepEqual(clean.opened, ["default"]);
+ assert.deepEqual(w.local, [true], "the window leaves My Cloud for this computer's page");
+ assert.equal(w.home.profile(), "default");
+ assert.equal(w.home.cloudOrigin(), CLOUD, "My Cloud is still home");
+ await w.home.show({ place: "cloud" });
+ assert.deepEqual(w.went, [[CLOUD, CLOUD], [CLOUD, CLOUD]]);
+ assert.equal(w.home.profile(), null);
+ assert.equal(clean.leaves, 0, "the profile keeps running, so This Mac is one click again");
+ assert.equal(clean.profile(), "default");
+ assert.equal(await w.home.openProfile("default"), true);
+ assert.deepEqual(w.local, [true, true]);
+ assert.deepEqual(clean.opened, ["default", "default"]);
+});
+
+test("the default stays My Cloud: a launch after using This Mac opens My Cloud, never the profile", async () => {
+ const clean = profiles(), w = world({ clean });
+ await w.home.show();
+ await w.home.openProfile("default");
+ const next = world({ clean });
+ await next.home.show();
+ assert.deepEqual(next.went, [[CLOUD, CLOUD]]);
+ assert.deepEqual(next.local, []);
+ assert.equal(next.home.profile(), null);
+});
+
+test("it stays on screen through the sign-in's changes and the window's own retries, until the person picks a place", async () => {
+ const clean = profiles(), w = world({ clean });
+ await w.home.show();
+ w.url = `${CLOUD}/`;
+ await w.home.openProfile("default");
+ for (const again of [() => w.home.changed(), () => w.home.retry(), () => w.home.show()]) await again();
+ assert.deepEqual(w.went, [[CLOUD, CLOUD]], "nothing pulls the window back to My Cloud");
+ assert.equal(w.local[0], true);
+ assert.ok(w.local.length > 1 && w.local.slice(1).every((leaving) => leaving === false), "and nothing reloads the page it is on");
+ assert.equal(w.home.profile(), "default");
+});
+
+test("only while My Cloud is home: signed out, another account or a computer that never moved never opens it from here", async () => {
+ for (const setup of [{ state: { status: "signed-out" } }, { state: { ...connected(), account: { id: "acct-2", email: "[email protected]" } } }, { journal: null }]) {
+ const clean = profiles(), w = world({ clean, ...setup });
+ await w.home.show();
+ assert.equal(await w.home.openProfile("default"), false, JSON.stringify(setup));
+ assert.deepEqual(clean.opened, [], JSON.stringify(setup));
+ }
+ assert.equal(await world({ clean: null }).home.openProfile("default"), false, "an app with no profiles");
+});
+
+test("a profile that can't open leaves the window on My Cloud", async () => {
+ const clean = profiles(), w = world({ clean });
+ clean.fails = true;
+ await w.home.show();
+ assert.equal(await w.home.openProfile("default"), false);
+ assert.equal(new URL(w.url).origin, CLOUD);
+ assert.deepEqual(w.local, []);
+ assert.equal(w.home.profile(), null);
+});
+
+test("signing out from the profile ends it as the place on screen: the next sign-in opens My Cloud", async () => {
+ const clean = profiles(), w = world({ clean });
+ await w.home.show();
+ await w.home.openProfile("default");
+ w.state = { status: "signed-out" };
+ await w.home.changed();
+ assert.equal(w.home.profile(), null);
+ w.state = { status: "connected", account: ACCOUNT, machine: { status: "ready", origin: CLOUD } };
+ await w.home.changed();
+ assert.deepEqual(w.went.at(-1), [CLOUD, CLOUD]);
+ assert.equal(new URL(w.url).origin === LOCAL, false);
+});
diff --git a/electron/home-window.d.mts b/electron/home-window.d.mts
index a51e6e8bef..37d10df3f4 100644
--- a/electron/home-window.d.mts
+++ b/electron/home-window.d.mts
@@ -74,6 +74,8 @@ type Timers = { set(work: () => void, ms: number): unknown; clear(timer: unknown
export interface HomeWindow {
show(options?: { open?: "phone" | null; place?: HomeAsk }): Promise<unknown>;
+ openProfile(id: string): Promise<boolean>;
+ profile(): string | null;
cancel(): void;
openCloud(open?: "phone" | null): Promise<unknown>;
/** Remove from list from this computer's screen: the Cloud it shows leaves the person's list. */
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 518de42979..2df2c74225 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -238,6 +238,9 @@ export function createHomeWindow(deps) {
now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {}, t = nativeText.englishText.t } = deps;
let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;
let recovering = null;
+ /** The profile (clean-workspace.mjs) the person opened from the rail while My Cloud is home, until they pick a place. Never
+ * remembered: each launch opens My Cloud. */
+ let profileShown = null;
/** My Cloud asked for before the move made it home (`{ open }`), until its page loads or the person goes elsewhere;
* `naming`: since when, and how often, a brand-new My Cloud's name was not found. */
let asked = null, naming = null;
@@ -519,10 +522,24 @@ export function createHomeWindow(deps) {
async function show({ open = null, place = null } = {}) {
if (recovering) { if (!open && !place) return; recovering = null; }
const token = ++opens;
+ if (open || place) profileShown = null;
const current = await refresh();
if (!wanted(token)) return;
- // This computer's own copy is the server again before anything of the person's Cloud opens.
- if (!current.clean && clean?.active()) { await clean.leave(); if (!wanted(token)) return; }
+ if (current.kind !== "cloud") profileShown = null;
+ // This computer's own copy is the server again before anything of the person's Cloud opens; a profile they opened keeps
+ // running, so going back to it is one click.
+ if (!current.clean && clean?.active() && !clean.profile?.()) { await clean.leave(); if (!wanted(token)) return; }
+ if (profileShown) {
+ opening = null; asked = null; naming = null;
+ clearRenewal();
+ if (await clean.open(profileShown)) {
+ if (!wanted(token)) return;
+ ensureWindow(); clearRetry(); screen = null; status = null; shown = null; away = false;
+ return showLocal(onScreen() || !shows(localOrigin()));
+ }
+ profileShown = null;
+ if (!wanted(token)) return;
+ }
// Nobody signed in has nothing to open but the clean workspace; the place stays remembered for when they're back.
const target = current.clean && signedOut() ? { kind: "cloud" } : placeOf({ ask: place, remembered: remembered(), state: state() });
if (target.kind === "cloud" && target.left) { left(target.left); remember(null); }
@@ -634,6 +651,16 @@ export function createHomeWindow(deps) {
return {
show,
+ /** Profile `id` from the rail while My Cloud is home: the window shows it, and My Cloud is one click away. False when it
+ * can't open, and the window shows My Cloud as before. */
+ async openProfile(id) {
+ if (!clean?.open || (await refresh()).kind !== "cloud") return false;
+ profileShown = id;
+ await show();
+ return profileShown === id;
+ },
+ /** The profile on screen, opened from the rail, else null. */
+ profile: () => profileShown,
/** The person asked for My Cloud (the Server menu, the welcome, Settings, the ready notice). Before the move made it
* home it opens as a saved server, and while the Admin sets it up the setup screen shows until it opens by itself. */
async openCloud(open = null) {
@@ -703,6 +730,7 @@ export function createHomeWindow(deps) {
* the window off whatever it shows of that account. */
accountLeaving() {
opens++;
+ profileShown = null;
clearRetry(); clearRenewal();
asked = null; naming = null; shown = null; opening = null; screen = null; status = null;
away = away || !shows(localOrigin());
diff --git a/electron/lending-target.d.mts b/electron/lending-target.d.mts
index 11e8a4b069..878e89c60d 100644
--- a/electron/lending-target.d.mts
+++ b/electron/lending-target.d.mts
@@ -3,6 +3,8 @@ export function createLendingTarget<E extends { origin: string; cloud?: { id: st
environments: () => E[];
/** A server of the person's own their bots moved to, while home is there. */
ownHome?: () => { origin: string; environmentId: string } | null;
+ /** The clean workspace: nothing is lent while its workspace for nobody who can reach the bots runs. */
+ clean?: { stranded(): boolean } | null;
}): {
/** The sign-in as `env`'s lending checks it: another Cloud of the person's own at its own address, else My Cloud. */
cloud(env?: E | null): { status: string; accountId: string | null; origin: string | null } | null;
diff --git a/electron/lending-target.mjs b/electron/lending-target.mjs
index 514ea5defa..f49466b06b 100644
--- a/electron/lending-target.mjs
+++ b/electron/lending-target.mjs
@@ -4,11 +4,14 @@
* a brief disconnect of the same account, and `places()` the saved servers that are the person's own Clouds, My Cloud
* first. `ownHome()`: a server of the person's own their bots moved to (own-home-main.mjs), lent as their Clouds are, bound
* to that server's identity (`own:<environment id>` as its account), last. Security: never a Team Cloud, nor a server that
- * only signed in with their account (`isOwnCloud`), nor one connected by hand that the person did not make their home. */
-export function createLendingTarget({ account, environments, ownHome = () => null }) {
+ * only signed in with their account (`isOwnCloud`), nor one connected by hand that the person did not make their home; and
+ * nothing while the clean workspace for nobody who can reach the bots runs (`clean`, clean-workspace.mjs). A profile the
+ * person opened keeps this computer lent as before: the sign-in alone decides. */
+export function createLendingTarget({ account, environments, ownHome = () => null, clean = null }) {
let lastHome = null;
+ const signedIn = () => (clean?.stranded() ? null : account());
const mine = () => {
- const current = account();
+ const current = signedIn();
if (!current) return null;
const state = current.state();
const accountId = state.account?.id ?? null;
@@ -22,7 +25,7 @@ export function createLendingTarget({ account, environments, ownHome = () => nul
if (own && env?.origin === own.origin) return { status: "connected", accountId: `own:${own.environmentId}`, origin: own.origin };
const base = mine();
if (!base || !env?.cloud || base.origin === env.origin) return base;
- return account()?.isOwnCloud?.(env.origin) ? { ...base, origin: env.origin } : base;
+ return signedIn()?.isOwnCloud?.(env.origin) ? { ...base, origin: env.origin } : base;
};
const environment = () => {
const snapshot = mine();
@@ -34,7 +37,7 @@ export function createLendingTarget({ account, environments, ownHome = () => nul
environment,
places() {
const home = environment(), own = ownHome();
- const others = environments().filter((entry) => entry.cloud && entry !== home && account()?.isOwnCloud?.(entry.origin));
+ const others = environments().filter((entry) => entry.cloud && entry !== home && signedIn()?.isOwnCloud?.(entry.origin));
const theirs = own ? environments().filter((entry) => entry.origin === own.origin && !entry.cloud && !entry.team && !entry.home) : [];
return [...(home ? [home] : []), ...others, ...theirs];
},
diff --git a/electron/main.mjs b/electron/main.mjs
index 8bcc0a8b47..305bb96adc 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -104,7 +104,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClou
import { installCloudFiles } from "./cloud-sync-main.mjs";
import { createCloudEntry } from "./cloud-entry.mjs";
import { createLendingTarget } from "./lending-target.mjs"; import { createOpenAtLogin, installOpenAtLogin } from "./open-at-login.mjs";
-import { createCleanWorkspace } from "./clean-workspace.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { reopenSavedServer, serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";
+import { cleanWorkspaceDir, createCleanWorkspace, DEFAULT_PROFILE, profilesDir } from "./clean-workspace.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { reopenSavedServer, serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
@@ -1440,8 +1440,8 @@ async function requireSharedComputers() {
function sharingController() {
computerSharing ??= createComputerSharing({
file: path.join(app.getPath("userData"), "computer-sharing.json"),
- // Holds provider API keys and sessions.json: a broad share must never reach it.
- protectedPaths: [desktopDataDir()],
+ // Each holds provider API keys and sessions.json: a broad share must never reach them.
+ protectedPaths: [desktopDataDir(), cleanWorkspaceDir(desktopDataDir()), profilesDir(desktopDataDir())],
fetch: (...args) => session.defaultSession.fetch(...args),
environments: () => environmentsState.environments,
enabled: refreshSharedComputersAllowed, t: nativeT,
@@ -1455,7 +1455,7 @@ function sharingController() {
return computerSharing;
}
-const cleanWorkspace = createCleanWorkspace({ t: nativeT, dataDir: desktopDataDir, running: () => runningDataDir, swap: dir => switchLocalEnvironmentTo(dir, LOCAL_ID, true), allowed: () => app.isPackaged && !desktopRemoteAccess, changed: () => { computerSharing?.cloudChanged(); void oneHome.kick(); }, log: slog }); const lendingTarget = createLendingTarget({ account: () => (cleanWorkspace.active() ? null : cloudAccount), environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });
+const cleanWorkspace = createCleanWorkspace({ t: nativeT, dataDir: desktopDataDir, running: () => runningDataDir, swap: dir => switchLocalEnvironmentTo(dir, LOCAL_ID, true), allowed: () => app.isPackaged && !desktopRemoteAccess, changed: () => { computerSharing?.cloudChanged(); void oneHome.kick(); }, log: slog }); const lendingTarget = createLendingTarget({ account: () => cloudAccount, clean: cleanWorkspace, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });
const screenControl = createScreenControl({ connection: () => cuaReady, remote: () => Boolean(desktopRemoteAccess), request: requestComputerUse, log: slog });
let screenAskedAt = -Infinity;
/** Computer control starts again, as Settings' Retry does, which asks macOS for what it never asked; at most every 10 minutes. */
@@ -1675,7 +1675,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
}
async function switchEnvironment(id) {
- if ((id === environmentsState.activeId && !homeWindow.asking()) || (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id))) return;
+ if (id === LOCAL_ID && cleanWorkspace.profile() && homeWindow.cloudOrigin()) return void await homeWindow.openProfile(cleanWorkspace.profile()); if ((id === environmentsState.activeId && !homeWindow.asking()) || (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id))) return;
homeWindow.cancel();
const entry = environmentsState.environments.find((candidate) => candidate.id === id);
if (entry?.team || entry?.cloud) return void await showHome({ place: entry.team ? { team: entry.team.id, name: entry.name } : { cloud: entry.cloud.id, name: entry.name } });
@@ -1704,7 +1704,7 @@ function createLocalEnvironment(name, dataDir) {
? name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")
: "";
if (typeof name !== "string" || !name.trim()) return { ok: false, error: "name", state };
- candidateDir = path.join(os.homedir(), `.openmausbot-${slug && slug !== "clean" ? slug : randomUUID().slice(0, 8)}`);
+ candidateDir = path.join(os.homedir(), `.openmausbot-${slug && slug !== "clean" && slug !== "profiles" ? slug : randomUUID().slice(0, 8)}`);
} else {
candidateDir = typeof dataDir === "string" ? dataDir.trim() : "";
if (
@@ -2668,7 +2668,7 @@ function showHome(options) {
}
const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };
const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() });
-const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting() }); };
+const railProfiles = () => (app.isPackaged && !desktopRemoteAccess && homeWindow.cloudOrigin() ? [{ id: DEFAULT_PROFILE, active: homeWindow.profile() === DEFAULT_PROFILE && environmentsState.activeId === LOCAL_ID }] : []); const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: railProfiles() }); };
// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.
const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),
args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],
@@ -2681,7 +2681,7 @@ const rail = installCloudRail({ t: nativeT, ipcMain, clipboard, openCloud: openO
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)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true),
+ places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true), openProfile: id => workspaceMenuAction(async () => { const opened = await homeWindow.openProfile(id); railChanged(); if (!opened) throw new Error(nativeT("native.places.profileFailed")); }),
add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin(), account: !desktopRemoteAccess && Boolean(accounts.view().active) }),
run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });
const announceAddedCloud = createAddedCloudNotice({ t: nativeT, Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,
@@ -2765,8 +2765,8 @@ ipcMain.handle("environments:forget", localWorkspaceOnly("environments:forget",
// A cloud page may open the native chooser, never choose a destination or edit the saved list.
// Once My Cloud is home the switcher lists only whole places, and shows only when there is more than My Cloud.
const homeAlone = () => Boolean(homeWindow.cloudOrigin()) && !otherPlaces(environmentsState, homeWindow.cloudOrigin());
-ipcMain.handle("workspaces:state", workspaceOnly(event => ({ ...workspaceSummary(environmentsState), ...(homeAlone() && homeWindow.homePage(event) ? { home: true } : {}) })));
-ipcMain.handle("workspaces:line", workspaceOnly(event => (cleanWorkspace.active() && senderIsLocal(event) ? { kind: "clean", ...(accountRing.waiting().some(row => row.id === oneHome.journal()?.cloud?.account) ? { saved: true } : {}) } : homePlaces.line())));
+ipcMain.handle("workspaces:state", workspaceOnly(event => ({ ...workspaceSummary(environmentsState), ...(homeAlone() && homeWindow.homePage(event) ? { home: true } : {}), ...(cleanWorkspace.profile() && senderIsLocal(event) ? { profile: cleanWorkspace.profile() } : {}) })));
+ipcMain.handle("workspaces:line", workspaceOnly(event => (cleanWorkspace.active() && senderIsLocal(event) ? (cleanWorkspace.profile() ? { kind: "profile" } : { kind: "clean", ...(accountRing.waiting().some(row => row.id === oneHome.journal()?.cloud?.account) ? { saved: true } : {}) }) : homePlaces.line())));
let workspaceMenuOpen = false;
ipcMain.handle("workspaces:menu", workspaceOnly(async (_event, from) => {
if (workspaceMenuOpen || homeAlone()) return;
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 25cb4c0a13..5974c0ae06 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -57,6 +57,7 @@ export const VITEST_SUBSETS = {
"scripts/testing/bot-tools-ui.e2e.test.ts",
"scripts/testing/key-readback.e2e.test.ts",
"scripts/testing/one-workspace-ui.e2e.test.ts",
+ "scripts/testing/rail-profile-ui.e2e.test.ts",
"scripts/testing/secret-card-descriptions.test.ts",
"scripts/testing/team-own-chat.e2e.test.ts",
"server/body-thread-guards.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index a61508c6fe..ee68baefef 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -194,6 +194,7 @@ describe("CI outputs", () => {
"scripts/testing/bot-tools-ui.e2e.test.ts",
"scripts/testing/key-readback.e2e.test.ts",
"scripts/testing/one-workspace-ui.e2e.test.ts",
+ "scripts/testing/rail-profile-ui.e2e.test.ts",
"scripts/testing/secret-card-descriptions.test.ts",
"scripts/testing/team-own-chat.e2e.test.ts",
"server/body-thread-guards.e2e.test.ts",
diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.ts
index d4eb4da986..1501a2cbb5 100644
--- a/scripts/testing/cloud-send-fixture.ts
+++ b/scripts/testing/cloud-send-fixture.ts
@@ -83,8 +83,11 @@ export interface CloudSendFixture {
/** What main asked for besides: lending, the phone link, which home the window opened, and an app relaunch. */
spies: { lent: string[][]; phoneStops: number; phoneStarts: number; opened: string[]; relaunches: number };
/** The app quits or is killed: its main wiring stops, this computer's server is killed, and both start again on the
- * same data. With `cloud`, My Cloud's server is started again too, with more of its environment. */
- relaunch(options?: { kill?: boolean; cloud?: NodeJS.ProcessEnv }): Promise<void>;
+ * same data. With `cloud`, My Cloud's server is started again too, with more of its environment. With `dataDir`, this
+ * computer's server starts on that folder instead, at the same address, as main's swap to a profile does. */
+ relaunch(options?: { kill?: boolean; cloud?: NodeJS.ProcessEnv; dataDir?: string }): Promise<void>;
+ /** This computer's own data folder: the copy the move freezes. */
+ desktopDataDir: string;
/** The Team Cloud started with `team` (docs/team-cloud.md), paired the way the Admin pairs it: a signed body with
* the member claim, redeemed at /api/auth/pair. Null without `team`. */
team: CloudTeamFixture | null;
@@ -234,8 +237,8 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
const desktopPort = await freePortBlock([0, 1]);
const desktopBase = `http://127.0.0.1:${desktopPort}`;
const desktopInstallation = broker ? await broker.install() : null;
- const startDesktop = async () => {
- const child = await start("desktop", { OMB_DESKTOP_PARENT: "1",
+ const startDesktop = async (dataDir?: string) => {
+ const child = await start("desktop", { OMB_DESKTOP_PARENT: "1", ...(dataDir ? { OMB_DATA_DIR: dataDir } : {}),
...(broker && desktopInstallation ? { OMB_COMPOSIO_BROKER_URL: broker.url, OMB_COMPOSIO_BROKER_TOKEN: desktopInstallation.token } : {}) }, desktopPort, ["--import", parentPort], true, onePasswordToken, toolCalls, desktopEngine);
child.send({ type: "openmausbot:desktop-mutation-token", token: ownerCapability });
return child;
@@ -538,7 +541,8 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
get intercept() { return fixture.intercept; },
set intercept(hook) { fixture.intercept = hook; },
oneHome: { kick: () => main.kick(), view: () => main.view(), away: () => main.away() },
- async relaunch({ kill = true, cloud: cloudMore } = {}) {
+ desktopDataDir: join(root, "desktop", ".openmausbot"),
+ async relaunch({ kill = true, cloud: cloudMore, dataDir } = {}) {
main.close();
await waitForExit(desktop, { signal: kill ? "SIGKILL" : "SIGTERM" });
if (cloudMore) {
@@ -546,7 +550,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
cloud = await startCloud(cloudMore);
owner = await pairOwner();
}
- desktop = await startDesktop();
+ desktop = await startDesktop(dataDir);
for (let tries = 0; (await local("GET", "/api/bots")).status !== 200 && tries < 50; tries++) await new Promise((resolve) => setTimeout(resolve, 100));
main = wire();
listen();
diff --git a/scripts/testing/one-workspace-fixture.ts b/scripts/testing/one-workspace-fixture.ts
index bca33b3e19..e25e7168c7 100644
--- a/scripts/testing/one-workspace-fixture.ts
+++ b/scripts/testing/one-workspace-fixture.ts
@@ -8,7 +8,10 @@
// asking this computer's real, frozen server which page it serves. A team's Cloud is the same Cloud-mode server behind a
// third edge at its own origin (for opening, a Team Cloud is a My Cloud), paired through a fake Admin's team pairing
// route on this harness's own server, so main's team path (home-places.mjs, the session's teams as saved places) runs
-// as it does in the app.
+// as it does in the app. With `profiles`, This Mac is there too: main's real profile swap (clean-workspace.mjs) restarts
+// this computer's server on the profile's folder at the same address, the window's rail is its own page in a second tab
+// with main's rail handlers (cloud-rail.mjs), and this computer is really lent to My Cloud (computer-sharing.mjs over
+// lending-target.mjs) on the window's own session.
import { spawn, type ChildProcess } from "node:child_process";
import { EventEmitter } from "node:events";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
@@ -20,7 +23,11 @@ import { createServer as createViteServer, type ViteDevServer } from "vite";
import { appPermissionHandlers } from "../../electron/app-permissions.mjs";
import capabilities from "../../electron/capabilities.cjs";
import { chatLinkFrom } from "../../electron/chat-link.mjs";
+import { createCleanWorkspace, DEFAULT_PROFILE } from "../../electron/clean-workspace.mjs";
import { parsePairingGrant, withCloudHome } from "../../electron/cloud-home.mjs";
+import { installCloudRail, railPlaces } from "../../electron/cloud-rail.mjs";
+import { createComputerSharing } from "../../electron/computer-sharing.mjs";
+import { createLendingTarget } from "../../electron/lending-target.mjs";
import { createCloudPowerGate } from "../../electron/cloud-power.mjs";
import environments from "../../electron/environments.cjs";
import { createHomePlaces } from "../../electron/home-places.mjs";
@@ -177,7 +184,7 @@ function readBody(req: IncomingMessage): Promise<string> {
}
/** Electron's preload in a Chrome page: the real preload.cjs, its `require("electron")` and argv given by this harness. */
-function preloadStandIn(ipcBase: string, localOrigin: string): string {
+function preloadStandIn(ipcBase: string, localOrigin: string, tab = "window"): string {
return `(() => {
if (!/^https?:/.test(location.protocol)) return;
try { localStorage.setItem("omb-analytics-opt-out", "1"); localStorage.setItem("omb-email-gate", "skipped"); localStorage.setItem("omb-advanced-mode", "0");
@@ -185,7 +192,7 @@ function preloadStandIn(ipcBase: string, localOrigin: string): string {
const listeners = new Map();
window.__ogbEmit = (channel, ...args) => { for (const listener of [...(listeners.get(channel) ?? [])]) listener({}, ...args); };
const call = async (channel, args) => {
- const response = await fetch(${JSON.stringify(ipcBase)} + "/__ipc/" + channel, { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify({ args }) });
+ const response = await fetch(${JSON.stringify(ipcBase)} + "/__ipc/" + channel + "?tab=${tab}", { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify({ args }) });
const answer = await response.json();
if (!response.ok) throw new Error(answer.error);
return answer.value;
@@ -195,7 +202,7 @@ function preloadStandIn(ipcBase: string, localOrigin: string): string {
send: (channel, ...args) => { void call(channel, args).catch(() => {}); },
sendSync: (channel, ...args) => {
const request = new XMLHttpRequest();
- request.open("POST", ${JSON.stringify(ipcBase)} + "/__ipc-sync/" + channel, false);
+ request.open("POST", ${JSON.stringify(ipcBase)} + "/__ipc-sync/" + channel + "?tab=${tab}", false);
request.setRequestHeader("content-type", "text/plain");
request.send(JSON.stringify({ args }));
try { return JSON.parse(request.responseText).value; } catch { return undefined; }
@@ -244,6 +251,13 @@ export interface HomeWorld {
menu(): Array<{ label?: string; sublabel?: string; checked?: boolean }>;
/** The MausBot Cloud sign-in changed: main's own two steps (the places follow the session, then the window). */
sync(): Promise<void>;
+ /** With `profiles`: the window's rail as its own page, main's list for it, the profile swap and this computer's lending. */
+ rail: TabWindow | null;
+ railList(): ReturnType<typeof railPlaces>;
+ clean: ReturnType<typeof createCleanWorkspace> | null;
+ lending: ReturnType<typeof createComputerSharing> | null;
+ /** The folder this computer's server runs on now. */
+ running(): string;
/** Each request My Cloud's edge passed on, in order. */
cloudRequests: Array<{ path: string; at: number }>;
/** main.mjs's own chat-link delivery, as a link from the OS reaches it. */
@@ -273,8 +287,8 @@ async function vite(port: number, host: string, plugin: (server: ViteDevServer)
}
/** `chrome`: the pinned Chrome for Testing; `ports`: two free pairs (each Vite server takes its port and the next). */
-export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, versionEveryMs = 1_000, quietMs = 1_500 }: {
- chrome: string; ports: [number, number, number, number]; versionEveryMs?: number; quietMs?: number;
+export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, versionEveryMs = 1_000, quietMs = 1_500, profiles = false }: {
+ chrome: string; ports: [number, number, number, number]; versionEveryMs?: number; quietMs?: number; profiles?: boolean;
}): Promise<HomeWorld> {
const [cloudPort, localPort, ipcPort, teamPort] = ports;
const cloudOrigin = `http://localhost:${cloudPort}`;
@@ -296,6 +310,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
};
const cleanup: Array<() => Promise<unknown> | unknown> = [];
let windowRef: TabWindow | null = null, homeRef: ReturnType<typeof createHomeWindow> | null = null, responded: ((details: any) => void) | null = null;
+ let railRef: TabWindow | null = null, railHandlers: ReturnType<typeof installCloudRail> | null = null;
// My Cloud's edge: the renderer from source, and its API on the real Cloud-mode server with the edge's own headers.
const cloudEdge = await vite(cloudPort, "localhost", (server) => {
@@ -353,7 +368,8 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
const ipcMain = { handle: (channel: string, handler: (...args: any[]) => unknown) => { handlers.set(channel, handler); }, on: (channel: string, listener: (event: any) => void) => { syncHandlers.set(channel, listener); } };
const ipc: Server = createHttpServer(async (req: IncomingMessage, res: ServerResponse) => {
res.setHeader("access-control-allow-origin", "*");
- const sync = /^\/__ipc-sync\/([\w:.-]+)$/.exec(req.url ?? ""), asked = /^\/__ipc\/([\w:.-]+)$/.exec(req.url ?? "");
+ const [path = "", query = ""] = (req.url ?? "").split("?");
+ const sync = /^\/__ipc-sync\/([\w:.-]+)$/.exec(path), asked = /^\/__ipc\/([\w:.-]+)$/.exec(path);
const reply = (status: number, value: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(value)); };
// The fake Admin's team pairing: only for a team the session lists, answered as the Admin answers (docs/team-cloud.md).
const teamPairing = /^\/api\/cloud\/desktop\/teams\/([^/]+)\/pairing$/.exec(req.url ?? "");
@@ -367,7 +383,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
}
if (!sync && !asked) { res.writeHead(200, { "content-type": "text/html" }); res.end("<!doctype html><title>Another server</title><p>Another server</p>"); return; }
const { args = [] } = JSON.parse((await readBody(req)) || "{}") as { args?: unknown[] };
- const win = windowRef!;
+ const win = new URLSearchParams(query).get("tab") === "rail" && railRef ? railRef : windowRef!;
const event: Record<string, any> = { sender: win.webContents, senderFrame: win.webContents.mainFrame };
if (sync) {
const listener = syncHandlers.get(sync[1]!);
@@ -385,9 +401,13 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
// Channels of the page this harness does not drive, answered as main answers a page that has nothing to say.
const STAND_INS: Record<string, (...args: any[]) => unknown> = {
"desktop:capabilities": (event) => capabilities.desktopCapabilities({ remote: new URL(event.senderFrame.url).origin !== localOrigin, platform: "darwin", env: {}, packaged: true, localConnection: { mode: "unavailable", reason: "fixture" } }),
- "workspaces:state": (event) => ({ ...environments.workspaceSummary(envState), ...(homeAlone() && homeRef!.homePage(event) ? { home: true } : {}) }),
+ "workspaces:state": (event) => ({ ...environments.workspaceSummary(envState), ...(homeAlone() && homeRef!.homePage(event) ? { home: true } : {}),
+ ...(clean?.profile() && new URL(event.senderFrame.url).origin === localOrigin ? { profile: clean.profile() } : {}) }),
"workspaces:menu": () => null,
- "workspaces:line": () => homePlaces.line(),
+ "workspaces:line": (event) => (clean?.active() && new URL(event.senderFrame.url).origin === localOrigin ? (clean.profile() ? { kind: "profile" } : { kind: "clean" }) : homePlaces.line()),
+ "rail:offer": () => ({ available: true, hidden: false }),
+ "rail:expand": () => null,
+ "rail:draws-frame": () => null,
"desktop-notices:state": () => ({ seen: [...NOTICES], cloud: false }),
"desktop-notices:seen": () => null,
"cloud-plan:state": () => ({ status: "paid", tier: "pro", home: true }),
@@ -421,7 +441,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
let envState: { environments: any[]; activeId: string } = { environments: [], activeId: environments.LOCAL_ID };
let envIds = 0;
const makeId = () => `env-${++envIds}`;
- const persist = (next: typeof envState) => { envState = next; };
+ const persist = (next: typeof envState) => { envState = next; railHandlers?.changed(); };
let placeRecord: unknown = null;
const homePlaces = createHomePlaces({ store: { read: () => placeRecord, write: (value) => { placeRecord = value; } }, environments: () => envState, persist, makeId, homeOrigin: () => homeRef?.cloudOrigin() ?? null });
const homeAlone = () => Boolean(homeRef?.cloudOrigin()) && !environments.otherPlaces(envState, homeRef!.cloudOrigin());
@@ -495,9 +515,26 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
const world = {
splash: null as TabWindow | null,
};
+ // main.mjs's cleanWorkspace: its swap is switchLocalEnvironmentTo's, one server at a time at the same address, then the
+ // window onto this computer's page with LOCAL_ID active.
+ let running = fx.desktopDataDir;
+ const clean = profiles ? createCleanWorkspace({
+ dataDir: () => fx.desktopDataDir, running: () => running,
+ swap: async (dir: string) => {
+ await fx.relaunch({ kill: false, ...(dir === fx.desktopDataDir ? {} : { dataDir: dir }) });
+ running = dir;
+ persist(environments.withActive(envState, environments.LOCAL_ID));
+ homeRef?.cancel();
+ await win.loadURL(`${localOrigin}/`).catch(() => {});
+ return { ok: true };
+ },
+ changed: () => lending?.cloudChanged(),
+ }) : null;
+ const ownCopy = async (route: string, init?: RequestInit) => fetch(`${fx.desktopBase}${route}`, { ...init, headers: { "x-openmausbot-desktop-owner": fx.ownerCapability } });
const home = createHomeWindow({
+ ...(clean ? { clean } : {}),
journal: () => (moves.moved ? { v: 1, phase: "done", cloud: { origin: cloudOrigin, account: ACCOUNT_ID, machine: cloudOrigin }, doneAt: Date.now() } : null),
- frozen: async () => (moves.moved ? (await fetch(`${fx.desktopBase}/api/move/freeze`, { headers: { "x-openmausbot-desktop-owner": fx.ownerCapability } })).json() : { frozen: false }),
+ frozen: async () => (moves.moved ? (await (clean ? clean.realCopy(ownCopy) : ownCopy)("/api/move/freeze")).json() : { frozen: false }),
// The window's Electron session: its own resolver and host cache, for My Cloud's name.
hosts: () => ({
clearHostResolverCache: async () => { hostCache.cleared++; },
@@ -514,7 +551,11 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
power,
go: (url: string, origin: string | null, place: unknown) => { activate(origin, place); return win.loadURL(url).catch(() => {}); },
remembered: homePlaces.remembered, remember: homePlaces.remember, left: homePlaces.left, drop: homePlaces.drop,
- showLocal: (leaving: boolean) => (leaving || !/^https?:/.test(win.url) ? win.loadURL(`${localOrigin}/`).catch(() => {}) : undefined),
+ showLocal: (leaving: boolean) => {
+ if (!leaving && /^https?:/.test(win.url)) return undefined;
+ if (leaving && environments.activeEnvironment(envState)) persist(environments.withActive(envState, environments.LOCAL_ID));
+ return win.loadURL(`${localOrigin}/`).catch(() => {});
+ },
splash: () => (world.splash && !world.splash.destroyed ? { status: (text: string) => startup?.status(text) } : null),
publish: (view: unknown) => { if (new URL(win.url.startsWith("http") ? win.url : "about:blank").origin === localOrigin) win.webContents.send("home:state-changed", view); },
versionEveryMs, quietMs,
@@ -539,8 +580,50 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
vm.runInContext(`${MAIN.slice(start, end)}; this.queueChatLink = queueChatLink; this.deliverChatLink = deliverChatLink;`, linkContext);
win.webContents.on("did-stop-loading", () => linkContext.deliverChatLink(win));
+ // main.mjs's rail: its list (railList, with railProfiles) and handlers, for the rail's own page in a tab of its own, as
+ // wide as the window's rail view.
+ const railList = () => railPlaces({ saved: envState, home: home.cloudOrigin(), mine: cloudOrigin, state: account.state,
+ profiles: clean && home.cloudOrigin() ? [{ id: DEFAULT_PROFILE, active: home.profile() === DEFAULT_PROFILE && envState.activeId === environments.LOCAL_ID }] : [] });
+ let lending: ReturnType<typeof createComputerSharing> | null = null;
+ if (profiles) {
+ railRef = await TabWindow.open(cdp, preloadStandIn(ipcBase, localOrigin, "rail"));
+ await cdp.request("Emulation.setDeviceMetricsOverride", { width: 36, height: 800, deviceScaleFactor: 2, mobile: false }, railRef.sessionId);
+ railHandlers = installCloudRail({
+ ipcMain, guard: (handler: any) => handler, trusted: () => true, lists: (event: any) => event.sender === railRef!.webContents, beside: () => true,
+ places: railList, account: () => null, clipboard: { writeText: () => {} }, openCloud: async () => {},
+ add: { choices: () => ({ cloud: false, link: false, address: false }), run: () => {} },
+ targets: () => [win.webContents, railRef!.webContents],
+ // main.mjs's switchEnvironment for a saved place: My Cloud is shown again.
+ open: (id: string) => {
+ home.cancel();
+ const entry = envState.environments.find((candidate: any) => candidate.id === id);
+ if (entry?.origin === home.cloudOrigin()) return home.show({ place: "cloud" }).then(() => railHandlers?.changed());
+ throw new Error("This harness opens My Cloud and This Mac only");
+ },
+ openProfile: async (id: string) => {
+ const opened = await home.openProfile(id);
+ railHandlers?.changed();
+ if (!opened) throw new Error("This computer's own place didn't open.");
+ },
+ });
+ win.webContents.on("did-navigate", () => railHandlers?.changed());
+ await railRef.loadURL(`${localOrigin}/rail`);
+ // This computer, lent to My Cloud on the window's own session, as main's sharingController lends it.
+ const lentHome = mkdtempSync(join(tmpdir(), "omb-profile-lent-"));
+ cleanup.push(() => rmSync(lentHome, { recursive: true, force: true }));
+ const target = createLendingTarget({ account: () => client as never, clean, environments: () => envState.environments });
+ lending = createComputerSharing({
+ file: join(lentHome, "computer-sharing.json"), home: lentHome, fetch: cookieFetch as typeof fetch, environments: () => envState.environments,
+ cloud: target.cloud, myCloud: target.environment, ownClouds: target.places, screen: () => false, cuaConnection: async () => null,
+ linkHeaders: async (env: { origin: string }) => ({ cookie: ((await cdp.request("Network.getCookies", { urls: [env.origin] }, win.sessionId)).cookies as Array<{ name: string; value: string }>)
+ .map((entry) => `${entry.name}=${entry.value}`).join("; ") }),
+ });
+ cleanup.unshift(() => lending?.close());
+ }
+
let startup: ReturnType<typeof createStartupScreen> | null = null;
return {
+ rail: railRef, railList, clean, lending, running: () => running,
cloudOrigin, localOrigin, teamOrigin, otherOrigin, window: win, home, account, network, admin, cloudRequests, notifications, hostCache,
get moved() { return moves.moved; },
set moved(value: boolean) { moves.moved = value; },
diff --git a/scripts/testing/rail-profile-ui.e2e.test.ts b/scripts/testing/rail-profile-ui.e2e.test.ts
new file mode 100644
index 0000000000..1320831ea0
--- /dev/null
+++ b/scripts/testing/rail-profile-ui.e2e.test.ts
@@ -0,0 +1,161 @@
+// This Mac on the rail, for a person whose bots moved to My Cloud: main's own handlers in a real headless Chrome
+// (testing/one-workspace-fixture.ts with `profiles`), My Cloud a real Cloud-mode server, this computer its real, frozen server
+// until the rail's This Mac starts a fresh profile at the same address, and this computer really lent to My Cloud all along.
+// Each picture is the window as the person sees it: the rail's own page beside the page the window shows. Pictures go to
+// OMB_ONE_WORKSPACE_SHOTS, else the fixture's folder.
+import { randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { cleanWorkspaceConfig, profileDir } from "../../electron/clean-workspace.mjs";
+import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";
+import { hostTimeout } from "../../server/testing/host-timeout.ts";
+import { freePortBlock } from "../../server/testing/ports.ts";
+import { launchCloudSendFixture, type CloudSendFixture } from "./cloud-send-fixture.ts";
+import { ensureUiBrowser, UI_TOOLS_DIR } from "./control-omb-ui.ts";
+import { launchHomeWorld, shotsDir, welcomed, type HomeWorld } from "./one-workspace-fixture.ts";
+import { decodePng, encodePng } from "./png.ts";
+
+const enabled = process.env.OMB_UI_E2E === "1" || Boolean(resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }));
+if (!enabled) console.info("skipping the This Mac rail UI e2e: set OMB_UI_E2E=1 to install the pinned browser");
+
+const MAC = '[data-rail-place="profile:default"]';
+const WIDTH = 1280, HEIGHT = 800, SCALE = 2;
+
+(enabled ? describe : describe.skip)("This Mac on the rail, once My Cloud is home", () => {
+ let fx: CloudSendFixture;
+ let world: HomeWorld;
+ let shots = "";
+ let cloudEntry = "";
+ /** Every look at the lent link while the window switched, and whether it was up each time. */
+ const linkSeen: boolean[] = [];
+ let watching = false;
+ const until = async <T>(read: () => Promise<T>, ok: (value: T) => boolean, timeoutMs = 30_000, what = "the window"): Promise<T> => {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const value = await read().catch(() => undefined as T);
+ if (value !== undefined && ok(value)) return value;
+ if (Date.now() > deadline) {
+ await world.window.screenshot(join(shots, `failure-${Date.now()}.png`)).catch(() => {});
+ throw new Error(`timed out waiting for ${what}: ${JSON.stringify(value)} at ${world.window.url}`);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ };
+ const page = <T>(expression: string) => world.window.evaluate<T>(expression);
+ const rail = <T>(expression: string) => world.rail!.evaluate<T>(expression);
+ const myCloud = () => world.environments().environments.find((entry: { origin?: string }) => entry.origin === world.cloudOrigin);
+ const lent = () => Boolean(world.lending!.cloudState(myCloud()).connected);
+ const onCloud = () => until(() => page<string>("document.body.innerText"), (text) => new URL(world.window.url).origin === world.cloudOrigin && text.includes("Atlas"), 60_000, "My Cloud's page with its bots");
+ const railTiles = () => rail<Array<{ id: string; label: string; current: boolean }>>(
+ "[...document.querySelectorAll('[data-rail-place]')].map((tile) => ({ id: tile.dataset.railPlace, label: tile.getAttribute('aria-label'), current: tile.getAttribute('aria-current') === 'page' }))");
+ /** The window as the person sees it: the rail's page at its left edge, the place's page beside it. */
+ const picture = async (name: string) => {
+ await world.rail!.screenshot(join(shots, `${name}-rail.png`));
+ await world.window.screenshot(join(shots, `${name}-page.png`));
+ const left = decodePng(readFileSync(join(shots, `${name}-rail.png`))), right = decodePng(readFileSync(join(shots, `${name}-page.png`)));
+ writeFileSync(join(shots, `${name}.png`), encodePng(left.width + right.width, Math.max(left.height, right.height),
+ (x, y) => (x < left.width ? (y < left.height ? left.pixel(x, y) : [255, 255, 255]) : y < right.height ? right.pixel(x - left.width, y) : [255, 255, 255])));
+ };
+ const watchLink = async () => {
+ watching = true;
+ while (watching) { linkSeen.push(lent()); await new Promise((resolve) => setTimeout(resolve, 50)); }
+ };
+
+ beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-profile-${randomBytes(12).toString("hex")}` });
+ await welcomed(fx);
+ // What a move leaves: the bots on My Cloud, this computer's copy of them frozen.
+ for (const name of ["Atlas", "Juno"]) {
+ await fx.local("POST", "/api/bots", { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });
+ await fx.onCloud("POST", "/api/bots", { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });
+ }
+ const tools = await ensureUiBrowser(process.env);
+ if (!tools.chrome) throw new Error("This harness needs the pinned Chrome for Testing");
+ const ports = await Promise.all([freePortBlock([0, 1]), freePortBlock([0, 1]), freePortBlock([0]), freePortBlock([0, 1])]) as [number, number, number, number];
+ world = await launchHomeWorld(fx, { chrome: tools.chrome, ports, profiles: true });
+ shots = shotsDir(fx.root);
+ await world.window.cdp.request("Emulation.setDeviceMetricsOverride", { width: WIDTH, height: HEIGHT, deviceScaleFactor: SCALE, mobile: false }, world.window.sessionId);
+ await world.rail!.cdp.request("Emulation.setDeviceMetricsOverride", { width: 36, height: HEIGHT, deviceScaleFactor: SCALE, mobile: false }, world.rail!.sessionId);
+ // Each page's dev server bundles what it imports on the first visit, then reloads it once: done before anything counts.
+ for (const url of [`${world.localOrigin}/`, `${world.cloudOrigin}/`]) {
+ await world.window.loadURL(url).catch(() => {});
+ await new Promise((resolve) => setTimeout(resolve, 8_000));
+ }
+ expect((await fx.local("POST", "/api/move/freeze", { cloud: world.cloudOrigin })).body.frozen).toBe(true);
+ // The profile's first config as the app writes it, with the fixture's AIs only, so nothing on this machine's PATH is used.
+ const profile = profileDir(fx.desktopDataDir, "default");
+ mkdirSync(profile, { recursive: true });
+ const { instances } = JSON.parse(readFileSync(join(fx.desktopDataDir, "config.json"), "utf8"));
+ writeFileSync(join(profile, "config.json"), JSON.stringify({ ...cleanWorkspaceConfig("en"), instances }));
+ }, hostTimeout(300_000));
+ afterAll(async () => { watching = false; await world?.close(); await fx?.close(); }, hostTimeout(60_000));
+
+ it("My Cloud opens by default, the rail shows This Mac beside it, and this computer is lent to My Cloud", async () => {
+ await world.home.show();
+ await onCloud();
+ cloudEntry = myCloud()!.id;
+ world.lending!.start({ maintainer: false });
+ await until(async () => lent(), Boolean, 30_000, "this computer lent to My Cloud");
+ await until(async () => ((await fx.onCloud("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean }) => computer.online !== false).length,
+ (count) => count === 1, 30_000, "My Cloud to see this computer");
+ expect(world.railList().map((place) => place.id)).toEqual(["profile:default", cloudEntry]);
+ await world.rail!.loadURL(`${world.localOrigin}/rail`);
+ const tiles = await until(() => railTiles(), (found) => found.length === 2, 60_000, "the rail's two tiles");
+ expect(tiles).toEqual([
+ { id: "profile:default", label: "This Mac: a separate place on this computer, with its own bots. The bots on My Cloud stay there.", current: false },
+ { id: cloudEntry, label: expect.any(String), current: true },
+ ]);
+ expect(world.clean!.active()).toBe(false);
+ expect(await page<string | null>("document.querySelector('[data-home-line]')?.dataset.homeLine ?? null")).toBeNull();
+ await picture("1-my-cloud-with-this-mac-on-the-rail");
+ }, hostTimeout(180_000));
+
+ it("This Mac opens a fresh, empty place on this computer; the frozen copy stays frozen and the lent link stays up", async () => {
+ const watcher = watchLink();
+ await rail(`document.querySelector('${MAC}').click()`);
+ await until(() => page<string | null>("document.querySelector('[data-home-line]')?.textContent ?? null"), (text) => Boolean(text?.startsWith("This Mac starts fresh")), 90_000, "This Mac's page");
+ expect(new URL(world.window.url).origin).toBe(world.localOrigin);
+ expect(new URL(world.window.url).pathname).toBe("/");
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, "default"));
+ expect(world.clean!.profile()).toBe("default");
+ await until(() => page<string | null>("document.querySelector('[data-window-place]')?.textContent ?? null"), (name) => name === "This Mac", 15_000, "the top bar's name");
+ const bots = await page<string[]>("fetch('/api/bots').then((response) => response.json()).then((body) => body.bots.map((bot) => bot.name))");
+ expect(bots.filter((name) => ["Atlas", "Juno"].includes(name)), "none of the Cloud's bots, nor the frozen copy's").toEqual([]);
+ expect(await page<string>("document.body.innerText")).not.toContain("Atlas");
+ expect(await page<string>("document.querySelector('[data-home-line]').textContent"))
+ .toContain("The bots you had here are on My Cloud; to bring in an older copy, import its backup in Settings → Backups.");
+ // The frozen copy: its marker, and its bots, as the move left them.
+ expect(JSON.parse(readFileSync(join(fx.desktopDataDir, "moved.json"), "utf8")).cloud).toBe(world.cloudOrigin);
+ expect(existsSync(join(fx.desktopDataDir, "config.json"))).toBe(true);
+ await until(() => railTiles(), (found) => found.find((tile) => tile.id === "profile:default")?.current === true, 15_000, "This Mac marked on the rail");
+ await until(async () => lent(), Boolean, 15_000, "the lent link");
+ expect(((await fx.onCloud("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean }) => computer.online !== false)).toHaveLength(1);
+ watching = false; await watcher;
+ expect(linkSeen.length).toBeGreaterThan(10);
+ expect(linkSeen.every(Boolean), "the lent link never dropped while This Mac opened").toBe(true);
+ await picture("2-this-mac-fresh");
+ }, hostTimeout(180_000));
+
+ it("My Cloud on the rail goes back to the Cloud's bots; This Mac keeps running, so it is one click again, and the link never dropped", async () => {
+ linkSeen.length = 0;
+ const watcher = watchLink();
+ const made = await page<{ bot?: { id: string } }>("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Scout' }) }).then((response) => response.json())");
+ expect(made.bot?.id).toBeTruthy();
+ await rail(`document.querySelector('[data-rail-place="${cloudEntry}"]').click()`);
+ await onCloud();
+ expect(await page<string>("document.body.innerText")).not.toContain("Scout");
+ expect(await page<string | null>("document.querySelector('[data-home-line]')?.dataset.homeLine ?? null"), "My Cloud's page has no This Mac line").toBeNull();
+ expect(world.clean!.profile(), "This Mac's place still runs").toBe("default");
+ await until(() => railTiles(), (found) => found.find((tile) => tile.id === cloudEntry)?.current === true, 15_000, "My Cloud marked on the rail");
+ await picture("3-back-on-my-cloud");
+ await rail(`document.querySelector('${MAC}').click()`);
+ await until(() => page<string>("document.body.innerText"), (text) => new URL(world.window.url).origin === world.localOrigin && text.includes("Scout"), 60_000, "This Mac again, as it was left");
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, "default"));
+ watching = false; await watcher;
+ expect(linkSeen.every(Boolean), "the lent link never dropped either way").toBe(true);
+ expect(((await fx.onCloud("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean }) => computer.online !== false)).toHaveLength(1);
+ expect(JSON.parse(readFileSync(join(fx.desktopDataDir, "moved.json"), "utf8")).cloud, "never unfrozen").toBe(world.cloudOrigin);
+ await picture("4-this-mac-again");
+ }, hostTimeout(180_000));
+});
diff --git a/src/components/HomeLine.test.ts b/src/components/HomeLine.test.ts
index 04272c4e3e..25b6288941 100644
--- a/src/components/HomeLine.test.ts
+++ b/src/components/HomeLine.test.ts
@@ -84,3 +84,15 @@ it("a team's line never offers it", async () => {
await vi.waitFor(() => expect(host.querySelector("[data-home-line='left']")).not.toBeNull());
expect(host.querySelector("[data-home-line-ai]")).toBeNull();
});
+
+it("in This Mac's own place, the line says it is separate from My Cloud, where the bots from before are, and where an older copy comes in", async () => {
+ ais.instances = [{ ready: false, instanceId: "claude", driver: "claudeCode" }];
+ await mount(vi.fn().mockResolvedValue({ kind: "profile" }));
+ window.ogb = { ...window.ogb, platform: "darwin" } as unknown as typeof window.ogb;
+ await vi.waitFor(() => expect(host.querySelector("[data-home-line='profile']")).not.toBeNull());
+ expect(homeLineText({ kind: "profile" }, "darwin")).toBe("This Mac starts fresh, separate from My Cloud. The bots you had here are on My Cloud; to bring in an older copy, import its backup in Settings → Backups.");
+ expect(homeLineText({ kind: "profile" }, "win32")).toMatch(/^This PC starts fresh/);
+ expect(host.querySelector("[data-home-line-ai]")?.textContent, "a fresh place offers connecting an AI while none is ready").toBe("Connect an AI");
+ setLocale("pt-br");
+ expect(homeLineText({ kind: "profile" }, "darwin")).toMatch(/^Este Mac começa do zero/);
+});
diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsx
index dfd91ee056..850e33d628 100644
--- a/src/components/HomeLine.tsx
+++ b/src/components/HomeLine.tsx
@@ -1,22 +1,24 @@
import { useEffect, useState } from "react";
-import { Cloud, Users } from "lucide-react";
+import { Cloud, Laptop, Users } from "lucide-react";
import { freeFallback } from "../../shared/ai-ranking";
import { engineReady } from "@/components/EngineLibrary";
import { ConnectAiDialog } from "@/components/onboarding/ConnectAi";
import { t } from "@/lib/i18n";
+import { computerName } from "@/lib/places";
import { setNotificationPlace } from "@/lib/notify";
import { useStore } from "@/state/store";
-type Line = { kind: "left"; name: string } | { kind: "clean"; saved?: boolean };
+type Line = { kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile" };
-/** The words for main's one line: a team this person is no longer in, or that the clean workspace isn't where their bots went (`saved`: the account they moved with is signed in here too, one click away on the rail). */
-export function homeLineText(line: Line): string {
+/** The words for main's one line: a team this person is no longer in, that the clean workspace isn't where their bots went (`saved`: the account they moved with is signed in here too, one click away on the rail), or that a workspace of this computer's own opened from the rail is separate from My Cloud. */
+export function homeLineText(line: Line, platform?: string): string {
+ if (line.kind === "profile") return t("homeLine.profile", { name: computerName({ profile: "default" }, platform) });
if (line.kind === "clean") return t(line.saved ? "homeLine.cleanSaved" : "homeLine.clean");
return t("homeLine.left", { name: line.name });
}
-/** The clean workspace skips the new-user setup, so connecting an AI is offered here while none is ready. Nothing is sent to
- * test one: nothing starts by itself in this workspace. */
+/** The clean workspace and a profile skip the new-user setup, so connecting an AI is offered here while none is ready. Nothing
+ * is sent to test one: nothing starts by itself in this workspace. */
function ConnectAiLink() {
const { state } = useStore();
const [open, setOpen] = useState(false);
@@ -30,7 +32,8 @@ function ConnectAiLink() {
/** In the desktop app, never in a browser: one plain line main has for the next page, served once (home-places.mjs):
* after a team dropped this person, that they are no longer in it. Nothing to press; it goes with the page. (Who can
* see a team's private chats is said in the chat itself, by the team's own page.) Or, for as long as the clean workspace
- * runs (clean-workspace.mjs), that the person's bots are safe in their Cloud; Sign in stays in the You menu. */
+ * runs (clean-workspace.mjs), that the person's bots are safe in their Cloud; Sign in stays in the You menu. In a profile, that
+ * it is separate from My Cloud. */
export function HomeLine() {
const bridge = !window.ogb?.remoteClient?.active ? window.ogb?.workspaces : undefined;
const [line, setLine] = useState<Line | null>(null);
@@ -44,8 +47,8 @@ export function HomeLine() {
}, [bridge]);
if (!line) return null;
return <div role="status" data-home-line={line.kind} className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">
- {line.kind === "clean" ? <Cloud size={14} aria-hidden="true" /> : <Users size={14} aria-hidden="true" />}
- <span dir="auto">{homeLineText(line)}</span>
- {line.kind === "clean" && <ConnectAiLink />}
+ {line.kind === "clean" ? <Cloud size={14} aria-hidden="true" /> : line.kind === "profile" ? <Laptop size={14} aria-hidden="true" /> : <Users size={14} aria-hidden="true" />}
+ <span dir="auto">{homeLineText(line, window.ogb?.platform)}</span>
+ {line.kind !== "left" && <ConnectAiLink />}
</div>;
}
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
index edf923bff6..4749abcc68 100644
--- a/src/components/PlacesRail.test.ts
+++ b/src/components/PlacesRail.test.ts
@@ -535,3 +535,19 @@ it("+ stands for Add another account alone, when nothing else can be added", a
await act(async () => { await refreshPlaces(); });
expect(host.querySelector("[data-rail-add]")).toBeNull();
});
+
+it("once My Cloud is home, This Mac (This PC elsewhere) is a laptop circle that says what it is, and a click opens it through main by its profile id", async () => {
+ const mac = place("profile:default", "This computer", { kind: "computer", profile: "default" });
+ rail = { places: [mac, ...PLACES], add: { cloud: true, link: true, address: false } };
+ Object.assign(window, { ogb: { workspaces, cloudAdd, platform: "darwin" } });
+ await mount(createElement(PlacesRail));
+ const tile = host.querySelector('[data-rail-place="profile:default"]');
+ expect(tile?.getAttribute("aria-label")).toBe("This Mac: a separate place on this computer, with its own bots. The bots on My Cloud stay there.");
+ expect(tile?.getAttribute("data-rail-kind")).toBe("computer");
+ await click(tile);
+ expect(workspaces.open.mock.calls).toEqual([["profile:default"]]);
+ Object.assign(window, { ogb: { workspaces, cloudAdd, platform: "win32" } });
+ expect(placeLabel(mac)).toBe("This PC: a separate place on this computer, with its own bots. The bots on My Cloud stay there.");
+ expect(matchingPlaces([mac, ...PLACES], "pc").map((entry) => entry.id)).toEqual(["profile:default"]);
+ expect(placeLabel(place("local", "This computer", { kind: "computer" })), "before the move it is This computer, as ever").toBe("This computer");
+});
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index d630c3d596..8564640b6e 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -16,7 +16,7 @@ import { activeLocale, t } from "@/lib/i18n";
import { localizedRelativeTime } from "@/lib/relative-time";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useBesideFramed } from "@/lib/chrome-rail";
-import { makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
+import { computerName, makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
import { AccountsSheet, switchNote } from "./AccountMenu";
import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";
import { MENU_ROW, MENU_SHEET } from "./menu-recipe";
@@ -34,12 +34,13 @@ const tileRadius = (size: number) => Math.round(size * 0.3);
* own that signed in with their account says so, whether it is online, and why there is nothing to open when it is only
* reachable on its own network. */
export function placeLabel(place: RailPlace, now = Date.now()): string {
+ if (place.profile) return t("rail.profile", { name: computerName(place) });
const own = place.kind === "account" ? null : place.email ?? null;
return [placeStatus(place, now), own, place.signIn && t("accounts.needsSignIn")].filter(Boolean).join(" · ");
}
function placeStatus(place: RailPlace, now: number): string {
- const name = place.kind === "computer" ? t("rail.thisComputer") : place.server ? t("rail.ownServer", { name: place.name }) : place.name;
+ const name = place.kind === "computer" ? computerName(place) : place.server ? t("rail.ownServer", { name: place.name }) : place.name;
if (place.waiting) return t("rail.waiting", { name });
if (place.progress !== undefined) return t("rail.settingUp", { name });
if (place.attention) return t("rail.attention", { name });
@@ -65,7 +66,7 @@ export function shownPlaces(places: RailPlace[], limit = RAIL_SHOWN): RailPlace[
export function matchingPlaces(places: RailPlace[], query: string): RailPlace[] {
const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
return places.filter((place) => {
- const name = `${place.kind === "computer" ? t("rail.thisComputer") : place.name} ${place.email ?? ""}`.toLocaleLowerCase();
+ const name = `${place.kind === "computer" ? computerName(place) : place.name} ${place.email ?? ""}`.toLocaleLowerCase();
return words.every((word) => name.includes(word));
});
}
@@ -203,7 +204,7 @@ function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onC
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { (ref.current?.querySelector<HTMLElement>("[role='radio'][tabindex='0']") ?? ref.current?.querySelector<HTMLElement>("[data-rail-remove-ask], [data-rail-make-home-start]"))?.focus(); }, []);
if (!paint && !place.removable && !place.makeHome) return null;
- const name = place.kind === "computer" ? t("rail.thisComputer") : place.name;
+ const name = place.kind === "computer" ? computerName(place) : place.name;
const choose = (swatch: CloudSwatch) => {
if (!paint || paint.locked || pending || swatch === paint.swatch) return;
setPending(swatch); setOutcome(null);
diff --git a/src/components/WindowPlaceTitle.test.ts b/src/components/WindowPlaceTitle.test.ts
new file mode 100644
index 0000000000..fd221904c2
--- /dev/null
+++ b/src/components/WindowPlaceTitle.test.ts
@@ -0,0 +1,16 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import { windowPlaceName } from "./WindowPlaceTitle";
+
+beforeEach(() => setLocale("en"));
+afterEach(() => { delete window.ogb; });
+
+it("the top bar names the place as the rail does: This computer, This Mac (or This PC) in a profile, My Cloud while it is home", () => {
+ expect(windowPlaceName({ local: true, name: "This computer" }, undefined)).toBe("This computer");
+ window.ogb = { platform: "darwin" } as unknown as typeof window.ogb;
+ expect(windowPlaceName({ local: true, name: "This computer", profile: "default" }, undefined)).toBe("This Mac");
+ window.ogb = { platform: "win32" } as unknown as typeof window.ogb;
+ expect(windowPlaceName({ local: true, name: "This computer", profile: "default" }, undefined)).toBe("This PC");
+ expect(windowPlaceName({ local: false, name: "Studio", home: true }, undefined)).toBe("My Cloud");
+});
diff --git a/src/components/WindowPlaceTitle.tsx b/src/components/WindowPlaceTitle.tsx
index b9bbc51054..78d951cce6 100644
--- a/src/components/WindowPlaceTitle.tsx
+++ b/src/components/WindowPlaceTitle.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { t } from "@/lib/i18n";
import { usePlaceLook } from "@/lib/place-look";
+import { computerName } from "@/lib/places";
import { useStore } from "@/state/store";
import { PlaceMark } from "./PlacesRail";
@@ -21,10 +22,11 @@ export function useWindowPlace(): WorkspaceState | null {
return place;
}
-/** What the window's top bar calls the place: This computer, My Cloud while it is the window's only home (a team's name
- * on a team's Cloud), else the name it was saved under. */
+/** What the window's top bar calls the place: This computer (This Mac in a profile), My Cloud while it is the window's only
+ * home (a team's name on a team's Cloud), else the name it was saved under. */
export function windowPlaceName(place: WorkspaceState, team: string | undefined): string {
if (place.home) return team || t("cloudSetup.myCloud");
+ if (place.profile) return computerName({ profile: place.profile });
if (place.local && !place.localPath) return t("rail.thisComputer");
return place.name;
}
diff --git a/src/lib/places.ts b/src/lib/places.ts
index f963bd6a95..cdc853b6c1 100644
--- a/src/lib/places.ts
+++ b/src/lib/places.ts
@@ -86,6 +86,13 @@ export async function makeHome(id: string): Promise<true | string> {
* list main gave it (two places or more). */
export const railShown = (state: RailState): boolean => state.beside === true || state.places.length > 0;
+/** This computer's circle: This computer, or once My Cloud is home a workspace of its own (a profile), named as the app names
+ * this computer elsewhere: This Mac, or This PC. */
+export function computerName(place: Pick<RailPlace, "profile">, platform: string | undefined = typeof window === "undefined" ? undefined : window.ogb?.platform): string {
+ if (!place.profile) return t("rail.thisComputer");
+ return t(platform === "darwin" ? "rail.thisMac" : "rail.thisPc");
+}
+
/** A circle's letters: the first of up to two words, so "Client A" is CA and "Acme" is A. */
export function placeInitials(name: string): string {
const words = name.trim().split(/\s+/).filter(Boolean);
diff --git a/src/locales/de.json b/src/locales/de.json
index 7a974fe835..ba6df690b4 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2744,6 +2744,11 @@
"cloudBuy.extra.checkoutOpen": "Ein Bezahlvorgang für eine weitere Cloud ist bereits offen. Schließe ihn zuerst in deinem Browser ab.",
"rail.label": "Wo deine Bots leben",
"rail.thisComputer": "Dieser Computer",
+ "rail.thisMac": "Dieser Mac",
+ "rail.thisPc": "Dieser PC",
+ "rail.profile": "{name}: ein eigener Bereich auf diesem Computer, mit eigenen Bots. Die Bots deiner Cloud bleiben in My Cloud.",
+ "homeLine.profile": "{name} startet frisch, getrennt von My Cloud. Deine bisherigen Bots sind in My Cloud; eine ältere Kopie holst du zurück, indem du ihr Backup unter Einstellungen → Backups importierst.",
+ "native.places.profileFailed": "Der eigene Bereich dieses Computers wurde nicht geöffnet. Versuch es gleich noch einmal.",
"rail.settingUp": "{name}: wird eingerichtet",
"rail.waiting": "{name}: wartet auf Zahlung",
"rail.attention": "{name}: braucht dich",
diff --git a/src/locales/en.json b/src/locales/en.json
index 1185c582fa..50833a8844 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -628,6 +628,9 @@
"cloudBuy.extra.checkoutOpen": "A checkout for another Cloud is already open. Finish it in your browser first.",
"rail.label": "Where your bots live",
"rail.thisComputer": "This computer",
+ "rail.thisMac": "This Mac",
+ "rail.thisPc": "This PC",
+ "rail.profile": "{name}: a separate place on this computer, with its own bots. The bots on My Cloud stay there.",
"rail.settingUp": "{name}: setting up",
"rail.waiting": "{name}: waiting for payment",
"rail.attention": "{name}: needs you",
@@ -7277,6 +7280,7 @@
"homeLine.left": "You're no longer in {name}.",
"homeLine.clean": "Your bots are in the Cloud. Sign in to get them.",
"homeLine.cleanSaved": "Your bots are in your other account's Cloud. Click its icon on the left of the app to get them.",
+ "homeLine.profile": "{name} starts fresh, separate from My Cloud. The bots you had here are on My Cloud; to bring in an older copy, import its backup in Settings → Backups.",
"teamMove.menu": "Move to {team}",
"teamMove.title": "Move {bot} to {team}?",
"teamMove.everyone": "Everyone in {team} can use {bot}. Only {team}'s admins can change it.",
@@ -9197,6 +9201,7 @@
"native.cloud.ready.open": "Click to open it.",
"native.cloud.ready.quotedTitle": "“{name}” is ready",
"native.places.noLongerHere": "That place isn't here any more.",
+ "native.places.profileFailed": "This computer's own place didn't open. Try again in a moment.",
"native.places.cannotAdd": "That isn't something to add here.",
"native.cloud.addSignIn": "Sign in to MausBot Cloud first.",
"native.cloud.addPlanAndName": "Choose a plan and a name to continue.",
diff --git a/src/locales/es.json b/src/locales/es.json
index e39e91e737..4bedab17ad 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -512,6 +512,11 @@
"cloudBuy.extra.checkoutOpen": "Ya hay un pago abierto para otra Cloud. Termínalo primero en tu navegador.",
"rail.label": "Dónde viven tus bots",
"rail.thisComputer": "Este equipo",
+ "rail.thisMac": "Este Mac",
+ "rail.thisPc": "Este PC",
+ "rail.profile": "{name}: un espacio aparte en este equipo, con sus propios bots. Los bots de tu Cloud siguen en My Cloud.",
+ "homeLine.profile": "{name} empieza de cero, separado de My Cloud. Los bots que tenías aquí están en My Cloud; para traer una copia anterior, importa su copia de seguridad en Ajustes → Copias de seguridad.",
+ "native.places.profileFailed": "El espacio propio de este equipo no se abrió. Inténtalo de nuevo en un momento.",
"rail.settingUp": "{name}: configurándose",
"rail.waiting": "{name}: esperando el pago",
"rail.attention": "{name}: te necesita",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index a3db5ecaf9..97400faad6 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -2677,6 +2677,11 @@
"cloudBuy.extra.checkoutOpen": "Un paiement pour un autre Cloud est déjà ouvert. Terminez-le d'abord dans votre navigateur.",
"rail.label": "Où vivent vos bots",
"rail.thisComputer": "Cet ordinateur",
+ "rail.thisMac": "Ce Mac",
+ "rail.thisPc": "Ce PC",
+ "rail.profile": "{name} : un espace à part sur cet ordinateur, avec ses propres bots. Les bots de votre Cloud restent sur My Cloud.",
+ "homeLine.profile": "{name} repart de zéro, séparé de My Cloud. Les bots que vous aviez ici sont sur My Cloud ; pour récupérer une ancienne copie, importez sa sauvegarde dans Paramètres → Backups.",
+ "native.places.profileFailed": "L'espace propre à cet ordinateur ne s'est pas ouvert. Réessayez dans un instant.",
"rail.settingUp": "{name} : configuration en cours",
"rail.waiting": "{name} : en attente du paiement",
"rail.attention": "{name} : a besoin de vous",
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 2625967cfe..499b7c1383 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -2677,6 +2677,11 @@
"cloudBuy.extra.checkoutOpen": "दूसरे Cloud का एक चेकआउट पहले से खुला है। पहले उसे अपने ब्राउज़र में पूरा करें।",
"rail.label": "आपके बॉट कहाँ रहते हैं",
"rail.thisComputer": "यही कंप्यूटर",
+ "rail.thisMac": "यह Mac",
+ "rail.thisPc": "यह PC",
+ "rail.profile": "{name}: इस कंप्यूटर पर एक अलग जगह, अपने बॉट्स के साथ। आपके Cloud के बॉट्स My Cloud पर ही रहते हैं।",
+ "homeLine.profile": "{name} नए सिरे से शुरू होता है, My Cloud से अलग। आपके पहले के बॉट्स My Cloud पर हैं; पुरानी कॉपी लाने के लिए सेटिंग्स → Backups में उसका बैकअप इंपोर्ट करें।",
+ "native.places.profileFailed": "इस कंप्यूटर की अपनी जगह नहीं खुली। थोड़ी देर में फिर से कोशिश करें।",
"rail.settingUp": "{name}: सेट हो रहा है",
"rail.waiting": "{name}: भुगतान का इंतज़ार",
"rail.attention": "{name}: आपकी ज़रूरत है",
diff --git a/src/locales/it.json b/src/locales/it.json
index 583a78ed51..4afb44340f 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -516,6 +516,11 @@
"cloudBuy.extra.checkoutOpen": "C'è già un pagamento aperto per un altro Cloud. Prima completalo nel browser.",
"rail.label": "Dove vivono i tuoi bot",
"rail.thisComputer": "Questo computer",
+ "rail.thisMac": "Questo Mac",
+ "rail.thisPc": "Questo PC",
+ "rail.profile": "{name}: uno spazio a parte su questo computer, con i suoi bot. I bot del tuo Cloud restano su My Cloud.",
+ "homeLine.profile": "{name} riparte da zero, separato da My Cloud. I bot che avevi qui sono su My Cloud; per riportare una copia precedente, importa il suo backup in Impostazioni → Backup.",
+ "native.places.profileFailed": "Lo spazio di questo computer non si è aperto. Riprova tra un momento.",
"rail.settingUp": "{name}: in configurazione",
"rail.waiting": "{name}: in attesa del pagamento",
"rail.attention": "{name}: ha bisogno di te",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 889300aeaf..04a8401613 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -574,6 +574,11 @@
"cloudBuy.extra.checkoutOpen": "別の Cloud の支払い画面がすでに開いています。先にブラウザーで完了してください。",
"rail.label": "ボットの居場所",
"rail.thisComputer": "このコンピューター",
+ "rail.thisMac": "この Mac",
+ "rail.thisPc": "この PC",
+ "rail.profile": "{name}:このコンピューター上の別の場所で、専用のボットがあります。Cloud のボットは My Cloud にそのまま残ります。",
+ "homeLine.profile": "{name} は My Cloud とは別の、まっさらな場所です。以前ここにあったボットは My Cloud にあります。古いコピーを取り込むには、設定 → バックアップでそのバックアップをインポートしてください。",
+ "native.places.profileFailed": "このコンピューター専用の場所を開けませんでした。少し待ってからもう一度お試しください。",
"rail.settingUp": "{name}: 準備中",
"rail.waiting": "{name}: 支払い待ち",
"rail.attention": "{name}: 対応が必要です",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index ebbe2e0ada..2b86721297 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -564,6 +564,11 @@
"cloudBuy.extra.checkoutOpen": "다른 클라우드의 결제 페이지가 이미 열려 있어요. 브라우저에서 먼저 마무리하세요.",
"rail.label": "봇이 사는 곳",
"rail.thisComputer": "이 컴퓨터",
+ "rail.thisMac": "이 Mac",
+ "rail.thisPc": "이 PC",
+ "rail.profile": "{name}: 이 컴퓨터의 별도 공간으로, 자체 봇이 있습니다. Cloud의 봇은 My Cloud에 그대로 있습니다.",
+ "homeLine.profile": "{name}은(는) My Cloud와 분리된 새 공간입니다. 이전에 여기 있던 봇은 My Cloud에 있습니다. 예전 사본을 가져오려면 설정 → 백업에서 그 백업을 가져오세요.",
+ "native.places.profileFailed": "이 컴퓨터의 공간을 열지 못했습니다. 잠시 후 다시 시도하세요.",
"rail.settingUp": "{name}: 설정 중",
"rail.waiting": "{name}: 결제 대기 중",
"rail.attention": "{name}: 확인 필요",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 9a2a94657e..358399138d 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -521,6 +521,11 @@
"cloudBuy.extra.checkoutOpen": "Płatność za inną Chmurę jest już otwarta. Najpierw dokończ ją w przeglądarce.",
"rail.label": "Gdzie mieszkają twoje boty",
"rail.thisComputer": "Ten komputer",
+ "rail.thisMac": "Ten Mac",
+ "rail.thisPc": "Ten PC",
+ "rail.profile": "{name}: osobne miejsce na tym komputerze, z własnymi botami. Boty twojego Cloud zostają w My Cloud.",
+ "homeLine.profile": "{name} zaczyna od zera, osobno od My Cloud. Dotychczasowe boty z tego komputera są w My Cloud; aby przywrócić starszą kopię, zaimportuj jej kopię zapasową w Ustawienia → Kopie zapasowe.",
+ "native.places.profileFailed": "Nie udało się otworzyć miejsca tego komputera. Spróbuj ponownie za chwilę.",
"rail.settingUp": "{name}: konfigurowanie",
"rail.waiting": "{name}: czeka na płatność",
"rail.attention": "{name}: potrzebuje ciebie",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index b6bf9530a6..2be998a43d 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -611,6 +611,11 @@
"cloudBuy.extra.checkoutOpen": "Já há uma página de pagamento de outro Cloud aberta. Conclua o pagamento no navegador primeiro.",
"rail.label": "Onde seus bots ficam",
"rail.thisComputer": "Este computador",
+ "rail.thisMac": "Este Mac",
+ "rail.thisPc": "Este PC",
+ "rail.profile": "{name}: um lugar separado neste computador, com bots próprios. Os bots do seu Cloud continuam no My Cloud.",
+ "homeLine.profile": "{name} começa do zero, separado do My Cloud. Os bots que você tinha aqui estão no My Cloud; para trazer uma cópia antiga, importe o backup dela em Configurações → Backups.",
+ "native.places.profileFailed": "O lugar próprio deste computador não abriu. Tente de novo em instantes.",
"rail.settingUp": "{name}: em configuração",
"rail.waiting": "{name}: aguardando pagamento",
"rail.attention": "{name}: aguardando você",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index cd22216859..6e24df8ac6 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -521,6 +521,11 @@
"cloudBuy.extra.checkoutOpen": "Оплата другого Cloud уже открыта. Сначала завершите её в браузере.",
"rail.label": "Где живут ваши боты",
"rail.thisComputer": "Этот компьютер",
+ "rail.thisMac": "Этот Mac",
+ "rail.thisPc": "Этот ПК",
+ "rail.profile": "{name}: отдельное место на этом компьютере со своими ботами. Боты вашего Cloud остаются в My Cloud.",
+ "homeLine.profile": "{name} начинается с чистого листа, отдельно от My Cloud. Боты, которые были здесь, находятся в My Cloud; чтобы вернуть старую копию, импортируйте её резервную копию в Настройки → Резервные копии.",
+ "native.places.profileFailed": "Не удалось открыть место этого компьютера. Повторите попытку чуть позже.",
"rail.settingUp": "{name}: настраивается",
"rail.waiting": "{name}: ждёт оплаты",
"rail.attention": "{name}: нужно ваше внимание",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 50c64c7b70..96e7418271 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5112,6 +5112,11 @@
"cloudBuy.extra.checkoutOpen": "Başka bir Cloud için açık bir ödeme zaten var. Önce tarayıcınızda tamamlayın.",
"rail.label": "Botlarınızın yaşadığı yerler",
"rail.thisComputer": "Bu bilgisayar",
+ "rail.thisMac": "Bu Mac",
+ "rail.thisPc": "Bu PC",
+ "rail.profile": "{name}: bu bilgisayarda kendi botları olan ayrı bir alan. Cloud'unuzun botları My Cloud'da kalır.",
+ "homeLine.profile": "{name}, My Cloud'dan ayrı olarak sıfırdan başlar. Burada daha önce olan botlarınız My Cloud'da; eski bir kopyayı getirmek için yedeğini Ayarlar → Yedekler'de içe aktarın.",
+ "native.places.profileFailed": "Bu bilgisayarın kendi alanı açılmadı. Birazdan tekrar deneyin.",
"rail.settingUp": "{name}: kuruluyor",
"rail.waiting": "{name}: ödeme bekleniyor",
"rail.attention": "{name}: size ihtiyaç var",
diff --git a/src/locales/uk.json b/src/locales/uk.json
index 1d7d08bbe8..d6169c3d34 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -3118,6 +3118,11 @@
"cloudBuy.extra.checkoutOpen": "Оплата іншого Cloud уже відкрита. Спершу завершіть її в браузері.",
"rail.label": "Де живуть ваші боти",
"rail.thisComputer": "Цей комп'ютер",
+ "rail.thisMac": "Цей Mac",
+ "rail.thisPc": "Цей ПК",
+ "rail.profile": "{name}: окреме місце на цьому комп'ютері з власними ботами. Боти вашого Cloud залишаються в My Cloud.",
+ "homeLine.profile": "{name} починається з чистого аркуша, окремо від My Cloud. Боти, які були тут, тепер у My Cloud; щоб повернути старішу копію, імпортуйте її резервну копію в Налаштування → Резервні копії.",
+ "native.places.profileFailed": "Не вдалося відкрити місце цього комп'ютера. Спробуйте ще раз за мить.",
"rail.settingUp": "{name}: налаштовується",
"rail.waiting": "{name}: чекає на оплату",
"rail.attention": "{name}: потрібна ваша увага",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 263dae138e..31f89e5f07 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5112,6 +5112,11 @@
"cloudBuy.extra.checkoutOpen": "Đã có một trang thanh toán cho Cloud khác đang mở. Hãy hoàn tất nó trong trình duyệt trước.",
"rail.label": "Nơi các bot của bạn sống",
"rail.thisComputer": "Máy tính này",
+ "rail.thisMac": "Máy Mac này",
+ "rail.thisPc": "Máy tính này",
+ "rail.profile": "{name}: một nơi riêng trên máy tính này, có bot riêng. Các bot trong Cloud của bạn vẫn ở My Cloud.",
+ "homeLine.profile": "{name} bắt đầu mới hoàn toàn, tách biệt với My Cloud. Các bot bạn từng có ở đây hiện ở My Cloud; để đưa một bản cũ hơn về, hãy nhập bản sao lưu của nó trong Cài đặt → Sao lưu.",
+ "native.places.profileFailed": "Không mở được nơi riêng của máy tính này. Hãy thử lại sau giây lát.",
"rail.settingUp": "{name}: đang thiết lập",
"rail.waiting": "{name}: đang chờ thanh toán",
"rail.attention": "{name}: cần bạn",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 40df0e3f97..e0173dd695 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4503,6 +4503,11 @@
"cloudBuy.extra.checkoutOpen": "另一個 Cloud 的付款頁面已經開啟。請先在瀏覽器中完成付款。",
"rail.label": "你的機器人在哪裡",
"rail.thisComputer": "這台電腦",
+ "rail.thisMac": "這台 Mac",
+ "rail.thisPc": "這台 PC",
+ "rail.profile": "{name}:這台電腦上的獨立空間,有自己的機器人。你的 Cloud 裡的機器人仍在 My Cloud。",
+ "homeLine.profile": "{name} 是一個全新的、與 My Cloud 分開的空間。你之前在這裡的機器人都在 My Cloud;要找回舊的副本,請在 設定 → 備份 中匯入它的備份。",
+ "native.places.profileFailed": "這台電腦自己的空間沒能開啟。請稍後再試。",
"rail.settingUp": "{name}:設定中",
"rail.waiting": "{name}:等待付款",
"rail.attention": "{name}:需要你處理",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 9c1249cb3e..e629c88d68 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -572,6 +572,11 @@
"cloudBuy.extra.checkoutOpen": "另一个 Cloud 的付款页面已经打开。请先在浏览器中完成付款。",
"rail.label": "你的机器人在哪里",
"rail.thisComputer": "这台电脑",
+ "rail.thisMac": "这台 Mac",
+ "rail.thisPc": "这台 PC",
+ "rail.profile": "{name}:这台电脑上的独立空间,有自己的机器人。你的 Cloud 里的机器人仍在 My Cloud。",
+ "homeLine.profile": "{name} 是一个全新的、与 My Cloud 分开的空间。你之前在这里的机器人都在 My Cloud;要找回旧的副本,请在 设置 → 备份 中导入它的备份。",
+ "native.places.profileFailed": "这台电脑自己的空间没能打开。请稍后再试。",
"rail.settingUp": "{name}:设置中",
"rail.waiting": "{name}:等待付款",
"rail.attention": "{name}:需要你处理",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index c7843c9e4e..7a5aec20c1 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -162,12 +162,13 @@ const __APP_VERSION__: string;
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; `localPath`: a local workspace's folder, absent for This
- * computer's own. */
- state: () => Promise<{ local: boolean; name: string; origin?: string; color?: string; home?: boolean; role?: string; localPath?: string }>;
+ * computer's own; `profile`: this computer's page is a profile of its own (This Mac), by its id. */
+ state: () => Promise<{ local: boolean; name: string; origin?: string; color?: string; home?: boolean; role?: string; localPath?: string; profile?: string }>;
/** The native server menu; resolves when it closes. `from: "howto"`: the Show me how tip opened it. */
menu: (options?: { from?: "howto" }) => Promise<void>;
- /** One plain line for the next page, served once: a team this person is no longer in. */
- line?: () => Promise<{ kind: "left"; name: string } | null>;
+ /** One plain line for the next page: a team this person is no longer in (served once), or, while it runs, that the
+ * clean workspace or a profile (`profile`) of this computer's own isn't where the Cloud's bots are. */
+ line?: () => Promise<{ kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile" } | null>;
/** The rail's circles, for this app's page and a hosted Cloud's only (empty elsewhere, and with fewer than two
* places). Absent on an older app. */
places?: () => Promise<import("../../electron/cloud-rail.mjs").RailState>;