Skip to content

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

More workspaces on this computer from the rail's +, and a cloud on every Cloud's tile (#4718)

Milind Soni50df92437ef8
diff --git a/docs/pr-screenshots/rail-workspaces/01-badge-zoom.png b/docs/pr-screenshots/rail-workspaces/01-badge-zoom.png
new file mode 100644
index 0000000000..a920c1ea75
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/01-badge-zoom.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-dark.png b/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-dark.png
new file mode 100644
index 0000000000..7a7753aacb
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-dark.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-light.png b/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-light.png
new file mode 100644
index 0000000000..ab313b0c13
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/01-rail-cloud-badge-light.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/03-plus-choices-dark.png b/docs/pr-screenshots/rail-workspaces/03-plus-choices-dark.png
new file mode 100644
index 0000000000..5d8e9f2b3e
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/03-plus-choices-dark.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/03-plus-choices-light.png b/docs/pr-screenshots/rail-workspaces/03-plus-choices-light.png
new file mode 100644
index 0000000000..731ce36650
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/03-plus-choices-light.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/04-plus-name-work.png b/docs/pr-screenshots/rail-workspaces/04-plus-name-work.png
new file mode 100644
index 0000000000..e54afb5319
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/04-plus-name-work.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/05-work-fresh.png b/docs/pr-screenshots/rail-workspaces/05-work-fresh.png
new file mode 100644
index 0000000000..43c2b31023
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/05-work-fresh.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/06-switch-waits-for-turn.png b/docs/pr-screenshots/rail-workspaces/06-switch-waits-for-turn.png
new file mode 100644
index 0000000000..30691284a8
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/06-switch-waits-for-turn.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/07-menu.png b/docs/pr-screenshots/rail-workspaces/07-menu.png
new file mode 100644
index 0000000000..951fb8f1be
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/07-menu.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/08-remove-asks.png b/docs/pr-screenshots/rail-workspaces/08-remove-asks.png
new file mode 100644
index 0000000000..84563928ac
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/08-remove-asks.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/10-after-restart.png b/docs/pr-screenshots/rail-workspaces/10-after-restart.png
new file mode 100644
index 0000000000..a32cdd32b1
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/10-after-restart.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/11-past-eight.png b/docs/pr-screenshots/rail-workspaces/11-past-eight.png
new file mode 100644
index 0000000000..28f90a80c7
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/11-past-eight.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/L1-server-menu-name-step.png b/docs/pr-screenshots/rail-workspaces/L1-server-menu-name-step.png
new file mode 100644
index 0000000000..99c0b39869
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/L1-server-menu-name-step.png differ
diff --git a/docs/pr-screenshots/rail-workspaces/L2-rail-appears.png b/docs/pr-screenshots/rail-workspaces/L2-rail-appears.png
new file mode 100644
index 0000000000..336ca80a6b
Binary files /dev/null and b/docs/pr-screenshots/rail-workspaces/L2-rail-appears.png differ
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index 433adb7365..e6f7b22e70 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -119,6 +119,41 @@ 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.
+## More workspaces on this computer, and the cloud badge
+
++ offers New workspace on this computer first, to everyone with the rail (and
+in the Server menu where there is no rail yet). It asks a name (Work, then
+Personal, then Workspace 2 and on) and a colour, then opens it fresh: another
+profile under `~/.openmausbot-profiles/<id>`, listed with its name, colour and
+creation time in `~/.openmausbot-profiles/profiles.json` (This Mac, `default`,
+is its first entry, kept as it was). One runs at a time: opening another waits
+for the work under way in the one that runs (as the move waits for it, at most
+a minute, the circle saying so), then stops it as a quit does and starts the
+next. Once My Cloud is home every workspace is on the rail; with no home the
+named ones sit after This computer, which stays the data folder. A workspace's
+menu renames it, changes its colour and removes it, asked first; removing the
+open one moves the window to My Cloud (or This computer) and stops its server
+before its folder goes to the Trash. Every Cloud's tile has a small cloud at its
+corner, and a screen reader hears "…, Cloud"; a named workspace's has a laptop
+and a server of the person's own its server mark.
+
+```sh
+node --test electron/local-profiles.node-test.mjs electron/cloud-rail.node-test.mjs electron/environments.node-test.mjs
+pnpm exec vitest run src/components/PlacesRail.test.ts src/components/PlaceAddSheet.test.ts src/components/HomeLine.test.ts src/components/WindowPlaceTitle.test.ts
+OMB_UI_E2E=1 pnpm exec vitest run scripts/testing/rail-profile-ui.e2e.test.ts
+```
+
+The UI test walks every path through the real pages: + with Escape, Close and
+Back at each step, an empty and a taken name, a new workspace opening fresh,
+This Mac, Work and My Cloud in every order, a switch while a turn runs (the
+circle waits, the turn finishes there and its reply is there on return), two
+quick clicks, Rename, Colour, Remove with Cancel, removing the open one and the
+last one, an app restart while a workspace is open, the rail past eight, the
+badge in the light and dark looks, and, in a second world with no Cloud, the
+Server menu's New workspace and the rail appearing with a second place. It
+watches the lent link every 50 ms throughout and checks that the frozen copy's
+server never starts.
+
## Automated fixtures
```sh
diff --git a/electron/clean-workspace.d.mts b/electron/clean-workspace.d.mts
index d06c276d85..194fc2c1d1 100644
--- a/electron/clean-workspace.d.mts
+++ b/electron/clean-workspace.d.mts
@@ -3,6 +3,7 @@ export function cleanWorkspaceDir(dataDir: string): string;
export function profilesDir(dataDir: string): string;
export function profileDir(dataDir: string, id: string): string;
export declare const DEFAULT_PROFILE: "default";
+export declare const PROFILE_ID: RegExp;
export function cleanWorkspaceConfig(language?: string | null, now?: Date): { language?: string; onboarding: { completedAt: string; version: number; hintsSeen: string[] } };
export interface CleanWorkspace {
active(): boolean;
diff --git a/electron/clean-workspace.mjs b/electron/clean-workspace.mjs
index 182112b854..1694e3b159 100644
--- a/electron/clean-workspace.mjs
+++ b/electron/clean-workspace.mjs
@@ -31,7 +31,8 @@ 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}$/;
+/** A profile id: its folder's name, and nothing that could reach outside the profiles' folder. */
+export 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
diff --git a/electron/cloud-home.node-test.mjs b/electron/cloud-home.node-test.mjs
index 683a93a083..01ab99a5eb 100644
--- a/electron/cloud-home.node-test.mjs
+++ b/electron/cloud-home.node-test.mjs
@@ -441,7 +441,7 @@ test("the Server menu opens My Cloud through the Cloud's own connection, never a
openCloudSettings: async () => { calls.push("settings"); },
persistEnvironments: next => { calls.push(`active:${next.activeId}`); context.environmentsState = next; }, withActive: environments.withActive,
navigateMainWindow: url => calls.push(`navigate:${url}`), activeOrigin: () => context.environmentsState.environments.find(e => e.id === context.environmentsState.activeId)?.origin,
- homeWindow: { cloudOrigin: () => null, asking: () => false, cancel: () => {} }, showHome: async (options) => { calls.push(options ? `home:${JSON.stringify(options)}` : "home"); },
+ homeWindow: { cloudOrigin: () => null, asking: () => false, cancel: () => {} }, cleanWorkspace: { profile: () => null }, showHome: async (options) => { calls.push(options ? `home:${JSON.stringify(options)}` : "home"); },
homePlaces: { remember: (place) => calls.push(`remember:${JSON.stringify(place)}`) },
runningDataDir: "/data", desktopDataDir: () => "/data",
handSaved, serverOpens: async (place) => { calls.push(`look:${place.id}`); return answers; }, session: { defaultSession: { fetch: async () => null } }, dialog: {},
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
index f50ff6652f..9c1363df44 100644
--- a/electron/cloud-rail.d.mts
+++ b/electron/cloud-rail.d.mts
@@ -7,8 +7,13 @@ 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). */
+ /** A workspace of this computer's own, by its profile id: the default one is This Mac (or This PC), offered once My Cloud
+ * is home. Its circle's menu renames it, changes its colour and removes it. */
profile?: string;
+ /** A workspace of this computer's own with a name of its own (`name`), not This Mac's. */
+ named?: true;
+ /** It opens once this bot, in the workspace that runs now, finishes what it is doing (empty: the bot isn't named). */
+ settling?: 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. */
@@ -52,7 +57,8 @@ export interface RailPlace {
/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings, and
* a new organization on the Team plan this account pays for (absent from an older app's main). */
/** `account`: Add another account (the rail's own page runs that sign-in). */
-export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean; organization?: boolean; account?: boolean }
+/** `local`: a new workspace of this computer's own. */
+export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean; organization?: boolean; account?: boolean; local?: boolean }
/** `beside`: a place's page, which never reads the list, learns that the window's rail stands beside it. */
export interface RailState { places: RailPlace[]; add: RailAddChoices; beside?: true }
/** Buying another Cloud as a page sees it: what the sheet says, never the account, an address or the checkout page. */
@@ -81,5 +87,5 @@ 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; accounts?: any[]; profiles?: Array<{ id: string; active?: 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; name?: string | null; color?: string | null; swatch?: string | null; active?: boolean; settling?: string }>; computerSettling?: string | null }): 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 99b8a6a5a9..cd7433453f 100644
--- a/electron/cloud-rail.mjs
+++ b/electron/cloud-rail.mjs
@@ -65,11 +65,13 @@ 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). `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
+ * device, each with its places as they were kept: grouped by account after these (withAccounts). `profiles`: the workspaces
+ * of this computer's own it may open (local-profiles.mjs; `active`: the one on screen, `settling`: it opens once that bot
+ * finishes): first once My Cloud is home, as This computer was, else right after This computer. `computerSettling`: This
+ * computer opens once that bot finishes.
+ * @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, name?: string | null, color?: string | null, swatch?: string | null, active?: boolean, settling?: string }>, computerSettling?: string | null }} input
*/
-export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [], profiles = [] }) {
+export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [], profiles = [], computerSettling = null }) {
const connected = state?.status === "connected" ? state : null;
const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];
const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };
@@ -87,10 +89,13 @@ 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 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 own = profiles.map(profile => ({ id: `${PROFILE_PLACE}${profile.id}`, name: profile.name || computer.name, color: profile.color ?? null, kind: "computer", profile: profile.id,
+ ...(profile.name ? { named: true } : {}), opens: true, paint: { swatch: profile.swatch ?? null }, ...(profile.active ? { active: true } : {}),
+ ...(typeof profile.settling === "string" ? { settling: profile.settling } : {}) }));
+ const profileShown = own.some(place => place.active);
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];
+ ...(saved.activeId === environments.LOCAL_ID && !profileShown ? { active: true } : {}), ...(waiting(computer.id) ? { attention: true } : {}),
+ ...(typeof computerSettling === "string" ? { settling: computerSettling } : {}) }, ...own, ...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;
}
@@ -150,9 +155,10 @@ 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`).
+ * `openProfile(id)`: the window shows that workspace of this computer's own (local-profiles.mjs `open`). `local`: those
+ * workspaces' +, names, colours and removal (local-profiles.mjs), and the end of a switch still waiting when another place opens.
*/
-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 }) {
+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, local = 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`);
@@ -166,13 +172,13 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
const view = async () => addCloudView(account()?.state() ?? null, account() ? await account().offer().catch(() => null) : null);
// +'s choices: main's, and a new organization while this account runs a Team plan's organizations (unless the Admin has
// turned adding them off).
- const choices = () => { const organizations = account()?.state().organizations; return { ...add.choices(), organization: Boolean(organizations) && organizations.blocked !== "off" }; };
+ const choices = () => { const organizations = account()?.state().organizations; return { ...add.choices(), organization: Boolean(organizations) && organizations.blocked !== "off", local: local?.creatable() === true }; };
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 => {
- if (place.id.startsWith(PENDING)) return openCloud(place.cloudId);
- if (!place.profile) return open(place.id);
+ if (place.id.startsWith(PENDING)) { local?.cancel(); return openCloud(place.cloudId); }
+ if (!place.profile) { local?.cancel(); return open(place.id); }
if (!openProfile) throw new Error(t("native.places.noLongerHere"));
return openProfile(place.profile);
};
@@ -205,6 +211,26 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
if (!place || !makeHome) throw new Error(t("native.home.notAvailable"));
return makeHome(place.id);
});
+ // A workspace of this computer's own: a new one from + (on the rail's page, or this computer's own from the Server menu),
+ // and a name, a colour or its removal from its circle's menu, only for one main listed.
+ handle("workspaces:local-new", (_event, name, color) => {
+ if (!local?.creatable()) throw new Error(t("native.places.cannotAdd"));
+ const made = local.create({ name: plain(name), color: plain(color) || null });
+ if (made.outcome === "made" && openProfile) void Promise.resolve().then(() => openProfile(made.id)).catch(() => {});
+ return made;
+ });
+ const profileListed = id => {
+ const place = places().find(entry => entry.id === plain(id) && entry.profile && !entry.account);
+ if (!place || !local) throw new Error(t("native.places.noLongerHere"));
+ return place.profile;
+ };
+ listed("workspaces:local-edit", (_event, id, changes) => {
+ const profile = profileListed(id);
+ if (changes && typeof changes.name === "string") return local.rename(profile, changes.name);
+ if (changes && Object.hasOwn(changes, "color")) return local.recolor(profile, changes.color === null ? null : plain(changes.color));
+ throw new Error(t("native.places.noLongerHere"));
+ });
+ listed("workspaces:local-remove", (_event, id) => local.remove(profileListed(id)));
// A link pasted on +'s sheet goes to main's own Connect dialog, which checks it and names its host before connecting.
listed("workspaces:add", (_event, choice, link) => {
if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error(t("native.places.cannotAdd"));
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
index e546b97b55..6f0fc1d037 100644
--- a/electron/cloud-rail.node-test.mjs
+++ b/electron/cloud-rail.node-test.mjs
@@ -180,7 +180,7 @@ test("New organization on +: only while this account runs a Team plan's organi
const r = rail(), plan = { planCloudId: "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", canAdd: true, count: 2, max: 10 };
assert.equal((await r.call("workspaces:places")).add.organization, false, "no Team plan's organizations: no such choice");
r.w.state = session({ organizations: plan });
- assert.deepEqual((await r.call("workspaces:places")).add, { cloud: true, link: true, address: false, organization: true });
+ assert.deepEqual((await r.call("workspaces:places")).add, { cloud: true, link: true, address: false, organization: true, local: false });
r.w.state = session({ organizations: { ...plan, canAdd: false, blocked: "limit" } });
assert.equal((await r.call("workspaces:places")).add.organization, true, "at the plan's limit it is still there, to say so");
r.w.state = session({ organizations: { ...plan, canAdd: false, blocked: "off" } });
@@ -322,7 +322,7 @@ function preload(origin, { activation = false } = {}) {
test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {
const page = preload(HOME);
- assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "remove", "makeHome", "onChanged"]);
+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "remove", "makeHome", "onChanged", "local", "onNewLocal"]);
assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);
await page.bridge.workspaces.places();
await page.bridge.cloudAdd.state();
@@ -337,6 +337,9 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,
await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);
await assert.rejects(page.bridge.workspaces.remove("old"), /Choose Remove from list/, "Remove from list only from the person's click");
await assert.rejects(page.bridge.workspaces.makeHome("vps"), /Choose Make my home/, "a move starts only from the person's click");
+ await assert.rejects(page.bridge.workspaces.local.create("Work", "rose"), /Choose a name/, "a workspace of this computer's own only from the person's click");
+ await assert.rejects(page.bridge.workspaces.local.edit("profile:work", { name: "Office" }), /Choose a change/);
+ await assert.rejects(page.bridge.workspaces.local.remove("profile:work"), /Choose Remove/);
await page.bridge.workspaces.look();
assert.deepEqual(page.invoked.at(-1), ["workspaces:look"]);
const clicked = preload(HOME, { activation: true });
@@ -353,7 +356,12 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,
assert.equal(page.bridge.cloudAccount, undefined, "never the account bridge");
const local = preload(LOCAL);
await local.bridge.workspaces.open("a");
- assert.deepEqual(local.invoked, [["workspaces:open", "a"]], "this app's own page needs no click check");
+ await local.bridge.workspaces.local.create({ toString: () => "Work" }, "rose");
+ await local.bridge.workspaces.local.edit("profile:work", { name: "Office", color: "blue" });
+ await local.bridge.workspaces.local.edit("profile:work", { color: null });
+ await local.bridge.workspaces.local.remove("profile:work");
+ assert.deepEqual(JSON.parse(JSON.stringify(local.invoked)), [["workspaces:open", "a"], ["workspaces:local-new", "Work", "rose"], ["workspaces:local-edit", "profile:work", { name: "Office" }],
+ ["workspaces:local-edit", "profile:work", { color: null }], ["workspaces:local-remove", "profile:work"]], "this app's own page needs no click check, and only a name or a colour goes");
});
test("Remove from list on a server saved by hand: main forgets it here, by its own word for which one", async () => {
@@ -380,7 +388,7 @@ test("a place with inbox lines waiting says so on its circle, this computer's to
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.deepEqual(places[0], { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true, paint: { swatch: null } });
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 }] });
@@ -404,3 +412,56 @@ test("a profile's circle opens it by main's own word for it: only one main liste
assert.throws(() => older.call("workspaces:open", "profile:default"), /isn't here/, "a main with no profiles opens none");
assert.deepEqual(older.opened, []);
});
+
+test("workspaces of this computer's own with names: first after My Cloud is home, else right after This computer; each with its name and colour; the one on screen marked", () => {
+ const rows = [{ id: "default", name: null, color: null, swatch: null }, { id: "work", name: "Work", color: "teal", swatch: "green", active: true }, { id: "lab", name: "Lab", color: null, swatch: null, settling: "Scout" }];
+ const home = railPlaces({ saved: saved("local"), home: HOME, mine: HOME, state: session(), profiles: rows });
+ assert.deepEqual(home.slice(0, 3), [
+ { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true, paint: { swatch: null } },
+ { id: "profile:work", name: "Work", color: "teal", kind: "computer", profile: "work", named: true, opens: true, paint: { swatch: "green" }, active: true },
+ { id: "profile:lab", name: "Lab", color: null, kind: "computer", profile: "lab", named: true, opens: true, paint: { swatch: null }, settling: "Scout" },
+ ]);
+ const local = { activeId: "local", environments: [] };
+ assert.deepEqual(railPlaces({ saved: local, home: null, state: null, profiles: [] }), [], "This computer alone: no rail, as ever");
+ const two = railPlaces({ saved: local, home: null, state: null, profiles: [{ id: "work", name: "Work", color: null, swatch: null }] });
+ assert.deepEqual(two.map(place => [place.id, place.active ?? false]), [["local", true], ["profile:work", false]], "This computer and Work: a rail of two, This computer on screen");
+ const inWork = railPlaces({ saved: local, home: null, state: null, profiles: [{ id: "work", name: "Work", color: null, swatch: null, active: true }], computerSettling: "Juno" });
+ assert.deepEqual(inWork.map(place => [place.id, place.active ?? false]), [["local", false], ["profile:work", true]], "Work on screen: This computer isn't marked too");
+ assert.equal(inWork[0].settling, "Juno", "This computer opens once Juno, in Work, finishes");
+});
+
+test("+'s new workspace and a workspace's menu: only while main offers it, only for a workspace main listed, never a Cloud or another account's", async () => {
+ const made = [], opened = [], cancels = [], edits = [], removed = [];
+ let creatable = true;
+ const rows = () => [{ id: "default", name: null, color: null, swatch: null }, { id: "work", name: "Work", color: null, swatch: null }];
+ const local = { creatable: () => creatable, cancel: () => cancels.push(true),
+ create: (input) => { made.push(input); return input.name === "Work" ? { outcome: "taken" } : { outcome: "made", id: "lab" }; },
+ rename: (id, name) => { edits.push(["rename", id, name]); return { outcome: "saved" }; }, recolor: (id, color) => { edits.push(["recolor", id, color]); return { outcome: "saved" }; },
+ remove: async (id) => { removed.push(id); return { outcome: "removed" }; } };
+ const r = rail({ local, openProfile: async (id) => { opened.push(id); }, places: () => railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: rows() }) });
+ assert.equal((await r.call("workspaces:places")).add.local, true);
+ assert.deepEqual(await r.call("workspaces:local-new", "Work", "rose"), { outcome: "taken" });
+ assert.deepEqual(await r.call("workspaces:local-new", { toString: () => "Lab" }, 7), { outcome: "made", id: "lab" });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(made, [{ name: "Work", color: "rose" }, { name: "", color: null }], "only plain text reaches main");
+ assert.deepEqual(opened, ["lab"], "a new workspace opens next, by main's own switch");
+ assert.deepEqual(await r.call("workspaces:local-edit", "profile:work", { name: "Office" }), { outcome: "saved" });
+ assert.deepEqual(await r.call("workspaces:local-edit", "profile:default", { color: "violet" }), { outcome: "saved" });
+ assert.deepEqual(await r.call("workspaces:local-edit", "profile:default", { color: null }), { outcome: "saved" });
+ assert.deepEqual(edits, [["rename", "work", "Office"], ["recolor", "default", "violet"], ["recolor", "default", null]]);
+ assert.deepEqual(await r.call("workspaces:local-remove", "profile:work"), { outcome: "removed" });
+ assert.deepEqual(removed, ["work"]);
+ for (const id of ["home", "a", "local", "profile:../x", "profile:gone"]) {
+ assert.throws(() => r.call("workspaces:local-edit", id, { name: "X" }), /isn't here/, id);
+ assert.throws(() => r.call("workspaces:local-remove", id), /isn't here/, id);
+ }
+ await r.call("workspaces:open", "a");
+ assert.equal(cancels.length, 1, "another place clicked: a switch still waiting ends");
+ r.w.lists = false;
+ assert.throws(() => r.call("workspaces:local-edit", "profile:work", { name: "X" }), /only available/, "a place's page never renames one");
+ assert.deepEqual(await r.call("workspaces:local-new", "Notes", null), { outcome: "made", id: "lab" }, "this computer's own page names one from the Server menu");
+ r.w.trusted = false;
+ assert.throws(() => r.call("workspaces:local-new", "Notes", null), /only available/, "a Cloud's page never makes one");
+ creatable = false; r.w.trusted = true;
+ assert.throws(() => r.call("workspaces:local-new", "Notes", null), /isn't something to add/);
+});
diff --git a/electron/environments.cjs b/electron/environments.cjs
index 2c84399212..595d1424c2 100644
--- a/electron/environments.cjs
+++ b/electron/environments.cjs
@@ -113,13 +113,17 @@ function workspaceSenderAllowed(event, contents, state, localOrigin) {
/** Native menu choices, never renderer-supplied destinations or callbacks. `iconFor`: a saved colour's small dot, when main can draw one.
* `places`: the one line saying which side has which bots, shown first; `copyToCloud`: the send line under the list. `foldSublabels`: where menus show no sublabels (Windows, Linux), My Cloud's status line
- * joins its name instead of vanishing. */
-function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddCloud, sublabels = {}, iconFor = null, places = null, copyToCloud = null, foldSublabels = false, homeOrigin = null, text = englishText }) {
+ * joins its name instead of vanishing. `locals`: the workspaces of this computer's own (local-profiles.mjs), each opened by
+ * `onLocal(id)` (`shown`: the one on screen); `onNewLocal`: a new one, named on this computer's own page. */
+function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddCloud, sublabels = {}, iconFor = null, places = null, copyToCloud = null, foldSublabels = false, homeOrigin = null, locals = [], onLocal = null, onNewLocal = null, text = englishText }) {
const active = activeEnvironment(state), { t } = text;
- if (homeOrigin) return homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldSublabels, homeOrigin, t });
+ const own = onLocal ? locals.map((local) => ({ id: `workspace-local-${local.id}`, label: local.label, type: "radio", checked: local.shown === true, click: () => onLocal(local.id) })) : [];
+ const fresh = onNewLocal ? [{ id: "workspace-new-local", label: t("native.menu.newLocal"), click: onNewLocal }] : [];
+ if (homeOrigin) return homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldSublabels, homeOrigin, own, fresh, t });
return [
...(places ? [{ id: "workspace-places", label: places, enabled: false }, { type: "separator" }] : []),
- { id: "workspace-local", label: t("place.local"), type: "radio", checked: !active, ...(iconFor && cleanColor(state.localColor) ? { icon: iconFor(state.localColor) } : {}), click: () => onSwitch(LOCAL_ID) },
+ { id: "workspace-local", label: t("place.local"), type: "radio", checked: !active && !own.some((item) => item.checked), ...(iconFor && cleanColor(state.localColor) ? { icon: iconFor(state.localColor) } : {}), click: () => onSwitch(LOCAL_ID) },
+ ...own,
...[...state.environments].sort((a, b) => listedPlace(b) - listedPlace(a)).map((entry) => {
const icon = iconFor && cleanColor(entry.color) ? iconFor(entry.color) : null;
const status = Object.hasOwn(sublabels, entry.id) ? sublabels[entry.id] : entry.team ? teamRoleLabel(entry.team.role, t) : null;
@@ -132,6 +136,7 @@ function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddClou
...(copyToCloud ? [{ id: "workspace-copy-to-cloud", label: copyToCloud.label, click: copyToCloud.click }] : []),
...(onAddCloud ? [{ id: "workspace-add-cloud", label: t("native.menu.addCloud"), sublabel: t("native.switcher.addCloudSub"), click: onAddCloud }] : []),
{ type: "separator" },
+ ...fresh,
{ id: "workspace-connect", label: t("native.menu.connect"), click: onConnect },
...(active && !listedPlace(active) ? [{ id: "workspace-forget", label: t("native.switcher.forgetNamed", { name: active.name }), click: () => onForget(active.id) }] : []),
];
@@ -140,18 +145,21 @@ function workspaceMenuTemplate(state, { onSwitch, onConnect, onForget, onAddClou
/** Once My Cloud is the person's home: My Cloud, each Cloud of theirs and each team's Cloud (with this person's role),
* then the other saved servers, each a whole place of its own; this computer is not one of them, and nothing here sends
* or copies. A Cloud or a team is the Admin's to list and remove, so it has no Forget. */
-function homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldSublabels, homeOrigin, t }) {
+function homeMenuTemplate(state, { onSwitch, onForget, sublabels, iconFor, foldSublabels, homeOrigin, own = [], fresh = [], t }) {
const active = activeEnvironment(state);
const places = state.environments.filter((entry) => entry.kind !== "local").sort((a, b) => placeRank(a, homeOrigin) - placeRank(b, homeOrigin));
+ const shown = own.some((item) => item.checked);
return [
+ ...own,
...places.map((entry) => {
const icon = iconFor && cleanColor(entry.color) ? iconFor(entry.color) : null;
const status = Object.hasOwn(sublabels, entry.id) ? sublabels[entry.id] : entry.team ? teamRoleLabel(entry.team.role, t) : null;
return {
id: `workspace-${entry.id}`, label: foldSublabels && status ? `${entry.name} · ${status}` : entry.name, sublabel: status ?? new URL(entry.origin).host,
- ...(icon ? { icon } : {}), type: "radio", checked: entry.id === state.activeId, click: () => onSwitch(entry.id),
+ ...(icon ? { icon } : {}), type: "radio", checked: entry.id === state.activeId && !shown, click: () => onSwitch(entry.id),
};
}),
+ ...(fresh.length ? [{ type: "separator" }, ...fresh] : []),
...(active && active.origin !== homeOrigin && !listedPlace(active) ? [{ type: "separator" }, { id: "workspace-forget", label: t("native.switcher.forgetNamed", { name: active.name }), click: () => onForget(active.id) }] : []),
];
}
diff --git a/electron/environments.node-test.mjs b/electron/environments.node-test.mjs
index 49a72b3c23..b9e5962620 100644
--- a/electron/environments.node-test.mjs
+++ b/electron/environments.node-test.mjs
@@ -487,3 +487,21 @@ test("a Cloud or team joining the list leaves this computer's page the active pl
const gone = env.reconcileTeams({ environments: [{ id: "t", kind: "remote", name: "Acme", origin: "https://acme.example.test", team: { id: "team-a", role: "member" } }, saved.environments[0]], activeId: "t" }, [], () => "x", HOME);
assert.equal(gone.state.activeId, "h", "a place on screen that's gone still falls back to My Cloud");
});
+
+test("the Server menu lists the workspaces of this computer's own and offers a new one, so they are reached with the rail hidden too", () => {
+ const calls = [];
+ const options = { onSwitch: (id) => calls.push(["switch", id]), onConnect() {}, onForget() {}, onLocal: (id) => calls.push(["local", id]), onNewLocal: () => calls.push(["new"]) };
+ const state = { environments: [{ id: "office", name: "Office", origin: "https://office.example" }], activeId: "local" };
+ const items = env.workspaceMenuTemplate(state, { ...options, locals: [{ id: "work", label: "Work", shown: true }] });
+ assert.deepEqual(items.filter((item) => item.type === "radio").map((item) => [item.id, item.label, item.checked]),
+ [["workspace-local", "This computer", false], ["workspace-local-work", "Work", true], ["workspace-office", "Office", false]], "Work on screen: This computer isn't checked");
+ items.find((item) => item.id === "workspace-local-work").click();
+ items.find((item) => item.id === "workspace-new-local").click();
+ assert.equal(items.find((item) => item.id === "workspace-new-local").label, "New workspace on this computer…");
+ const home = { environments: [{ id: "home", name: "My Cloud", origin: "https://omb-u-1.fly.dev", home: true }], activeId: "local" };
+ const homeItems = env.workspaceMenuTemplate(home, { ...options, homeOrigin: "https://omb-u-1.fly.dev", locals: [{ id: "default", label: "This Mac" }, { id: "work", label: "Work" }] });
+ assert.deepEqual(homeItems.filter((item) => item.type === "radio").map((item) => item.label), ["This Mac", "Work", "My Cloud"]);
+ homeItems.find((item) => item.id === "workspace-local-default").click();
+ assert.deepEqual(calls, [["local", "work"], ["new"], ["local", "default"]]);
+ assert.equal(env.workspaceMenuTemplate(state, { onSwitch() {}, onConnect() {}, onForget() {} }).some((item) => String(item.id).startsWith("workspace-new-local")), false, "only where main offers it");
+});
diff --git a/electron/home-window-profile.node-test.mjs b/electron/home-window-profile.node-test.mjs
index 2388df2415..62013b6fa7 100644
--- a/electron/home-window-profile.node-test.mjs
+++ b/electron/home-window-profile.node-test.mjs
@@ -90,3 +90,18 @@ test("signing out from the profile ends it as the place on screen: the next sign
assert.deepEqual(w.went.at(-1), [CLOUD, CLOUD]);
assert.equal(new URL(w.url).origin === LOCAL, false);
});
+
+test("My Cloud clicked, then a workspace before My Cloud's page arrived: the workspace's page loads over it, so the last click wins", async () => {
+ const clean = profiles(), w = world({ clean });
+ await w.home.show();
+ await w.home.openProfile("default");
+ w.url = `${LOCAL}/`;
+ w.stall = () => true;
+ void w.home.show({ place: "cloud" });
+ await new Promise((resolve) => setImmediate(resolve));
+ w.url = `${LOCAL}/`;
+ w.local.length = 0;
+ assert.equal(await w.home.openProfile("default"), true);
+ assert.deepEqual(w.local, [true], "a load of its own, never left to the Cloud's page on its way");
+ assert.equal(w.home.profile(), "default");
+});
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 2df2c74225..a63561019e 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -534,8 +534,10 @@ export function createHomeWindow(deps) {
clearRenewal();
if (await clean.open(profileShown)) {
if (!wanted(token)) return;
+ // `away`: a Cloud's page may still be on its way (a click just before this one); this page's load replaces it.
+ const leaving = away || onScreen() || !shows(localOrigin());
ensureWindow(); clearRetry(); screen = null; status = null; shown = null; away = false;
- return showLocal(onScreen() || !shows(localOrigin()));
+ return showLocal(leaving);
}
profileShown = null;
if (!wanted(token)) return;
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index c0a528629b..09cd15d21c 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -572,13 +572,18 @@ test("main shows the switcher at home only with somewhere else to go: My Cloud a
const start = MAIN.indexOf("const homeAlone = "), end = MAIN.indexOf("\n", start);
assert.ok(start > 0 && end > start);
const cloud = { id: "c", kind: "remote", name: "My Cloud", origin: CLOUD }, office = { id: "o", kind: "remote", name: "Office", origin: "https://office.example.test" };
- const context = vm.createContext({ homeWindow: { cloudOrigin: () => CLOUD }, otherPlaces: environments.otherPlaces, environmentsState: { environments: [cloud], activeId: "c" } });
+ const workspaces = [];
+ const context = vm.createContext({ homeWindow: { cloudOrigin: () => CLOUD }, otherPlaces: environments.otherPlaces, environmentsState: { environments: [cloud], activeId: "c" },
+ localProfiles: { places: () => workspaces } });
vm.runInContext(`${MAIN.slice(start, end)}; this.homeAlone = homeAlone;`, context);
assert.equal(context.homeAlone(), true, "My Cloud alone: no switcher");
context.environmentsState = { environments: [cloud, office], activeId: "c" };
assert.equal(context.homeAlone(), false, "a saved server besides: the switcher lists both");
context.environmentsState = { environments: [cloud, { id: "l", kind: "local", name: "Lab", dataDir: "/lab" }], activeId: "c" };
assert.equal(context.homeAlone(), true, "a named folder of this computer is not a place once home is My Cloud");
+ workspaces.push({ id: "default" });
+ assert.equal(context.homeAlone(), false, "a workspace of this computer's own is: the Server menu lists it, for when the rail is hidden");
+ workspaces.length = 0;
context.homeWindow = { cloudOrigin: () => null };
assert.equal(context.homeAlone(), false, "no home: the switcher as before");
});
diff --git a/electron/local-profiles.d.mts b/electron/local-profiles.d.mts
new file mode 100644
index 0000000000..3de49b9eed
--- /dev/null
+++ b/electron/local-profiles.d.mts
@@ -0,0 +1,60 @@
+import type { CloudSwatch } from "./cloud-list.mjs";
+import type { CleanWorkspace } from "./clean-workspace.mjs";
+
+export declare const PROFILES_FILE: "profiles.json";
+export declare const PROFILE_NAME_LIMIT: number;
+export declare const MAX_PROFILES: number;
+export declare const SETTLE_MS: number;
+export declare const SETTLE_POLL_MS: number;
+
+/** One workspace of this computer's own, as the registry keeps it: `name` null is This Mac's own (This Mac or This PC). */
+export interface ProfileEntry { id: string; name: string | null; color: CloudSwatch | null; createdAt: number }
+export type ProfileRefusal = "name" | "taken" | "full" | "gone";
+
+export function profileName(value: unknown): string | null;
+
+export interface ProfileRegistry {
+ list(): ProfileEntry[];
+ get(id: string): ProfileEntry | null;
+ create(input: { name: unknown; color?: unknown; reserved?: string | null }): { ok: true; profile: ProfileEntry } | { ok: false; error: ProfileRefusal };
+ rename(id: string, name: unknown, reserved?: string | null): { ok: true } | { ok: false; error: ProfileRefusal };
+ recolor(id: string, color: unknown): { ok: true } | { ok: false; error: ProfileRefusal };
+ remove(id: string): boolean;
+}
+export function createProfileRegistry(deps: { dataDir(): string; fs?: typeof import("node:fs"); now?(): number; random?(): string }): ProfileRegistry;
+
+/** A workspace as the rail lists it (cloud-rail.mjs railPlaces `profiles`). */
+export interface ProfileRow { id: string; name: string | null; color: string | null; swatch: CloudSwatch | null; active?: true; settling?: string }
+
+export interface LocalProfiles {
+ places(input: { activeLocal: boolean }): ProfileRow[];
+ settling(): { id: string | null; name: string } | null;
+ creatable(): boolean;
+ open(id: string): Promise<boolean | null>;
+ computer(): Promise<boolean | null>;
+ cancel(): void;
+ create(input: { name: unknown; color?: unknown }): { outcome: "made"; id: string } | { outcome: "name" | "taken" | "failed" };
+ rename(id: string, name: unknown): { outcome: "saved" | ProfileRefusal };
+ recolor(id: string, color: unknown): { outcome: "saved" | ProfileRefusal };
+ remove(id: string): Promise<{ outcome: "removed" | "gone" | "failed" }>;
+ name(id: string): string | null;
+}
+export function createLocalProfiles(deps: {
+ registry: ProfileRegistry;
+ clean: CleanWorkspace;
+ dataDir(): string;
+ home(): "cloud" | "local" | null;
+ window: { openProfile(id: string): Promise<boolean>; profile(): string | null; showCloud(): Promise<unknown> };
+ showLocal(): unknown;
+ onLocal(): boolean;
+ busy(): Promise<{ name: string; what?: string } | null>;
+ trash(dir: string): Promise<void>;
+ reserved?(): string | null;
+ allowed?(): boolean;
+ changed?(): void;
+ log?(line: string): void;
+ fs?: typeof import("node:fs");
+ sleep?(ms: number): Promise<void>;
+ now?(): number;
+ settleMs?: number;
+}): LocalProfiles;
diff --git a/electron/local-profiles.mjs b/electron/local-profiles.mjs
new file mode 100644
index 0000000000..ebc3e55ec7
--- /dev/null
+++ b/electron/local-profiles.mjs
@@ -0,0 +1,248 @@
+// The workspaces of this computer's own on the rail (each a profile, clean-workspace.mjs): their names and colours, a new
+// one from the rail's +, and switching between them. One runs at a time, on this computer's one server: opening another
+// stops the one that runs once the work under way in it has finished (as the move waits for it, server/move-waits.ts),
+// or after SETTLE_MS, when its server notes each turn cut short as a quit does.
+//
+// Who sees them: once My Cloud is home, every one, This Mac (`default`) first; before any home, This computer is the data
+// folder as ever and the named ones sit beside it, so This Mac's profile is never offered there. A server of the person's
+// own as home offers none yet.
+//
+// Removing one moves its folder to the computer's Trash (the same keep-it-recoverable step the app takes before it replaces
+// a file it downloaded), never deleting it outright, and never while its server runs: the window goes to another place
+// and the server back to this computer's own copy first.
+import { randomBytes } from "node:crypto";
+import nodeFs from "node:fs";
+import path from "node:path";
+
+import { CLOUD_SWATCHES, swatchColor } from "./cloud-list.mjs";
+import { DEFAULT_PROFILE, PROFILE_ID, profileDir, profilesDir } from "./clean-workspace.mjs";
+
+export const PROFILES_FILE = "profiles.json";
+export const PROFILE_NAME_LIMIT = 40;
+export const MAX_PROFILES = 20;
+/** The longest a switch waits for the work under way in the workspace it leaves. */
+export const SETTLE_MS = 60_000;
+export const SETTLE_POLL_MS = 1_000;
+
+/** A name as a person typed it: one line, no control characters, at most PROFILE_NAME_LIMIT characters; null when empty. */
+export function profileName(value) {
+ if (typeof value !== "string") return null;
+ const printable = Array.from(value, (char) => { const code = char.codePointAt(0) ?? 0; return code < 32 || (code >= 127 && code < 160) ? " " : char; }).join("");
+ const name = Array.from(printable.replace(/\s+/gu, " ").trim()).slice(0, PROFILE_NAME_LIMIT).join("").trim();
+ return name || null;
+}
+
+const swatch = (value) => (CLOUD_SWATCHES.includes(value) ? value : null);
+const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.toLocaleLowerCase() === b.toLocaleLowerCase();
+
+/**
+ * The registry beside the profiles' folders: `{ v: 1, profiles: [{ id, name, color, createdAt }] }`, in the rail's order.
+ * Without the file, This Mac (`default`) is its only entry, unnamed (the app calls it This Mac or This PC) and plain: so a
+ * computer from before keeps its This Mac with its folder as it was, and the first change writes it down.
+ * @param {{ dataDir(): string, fs?: typeof nodeFs, now?(): number, random?(): string }} deps
+ */
+export function createProfileRegistry({ dataDir, fs = nodeFs, now = Date.now, random = () => randomBytes(3).toString("hex") }) {
+ const file = () => path.join(profilesDir(dataDir()), PROFILES_FILE);
+ const born = (id) => { try { return Math.round(fs.statSync(profileDir(dataDir(), id)).birthtimeMs) || now(); } catch { return now(); } };
+ function list() {
+ let saved = null;
+ try { saved = JSON.parse(fs.readFileSync(file(), "utf8")); } catch {}
+ if (!Array.isArray(saved?.profiles)) return [{ id: DEFAULT_PROFILE, name: null, color: null, createdAt: born(DEFAULT_PROFILE) }];
+ const seen = new Set();
+ return saved.profiles.filter((entry) => typeof entry?.id === "string" && PROFILE_ID.test(entry.id) && !seen.has(entry.id) && seen.add(entry.id))
+ .map((entry) => ({ id: entry.id, name: profileName(entry.name), color: swatch(entry.color), createdAt: Number.isSafeInteger(entry.createdAt) ? entry.createdAt : now() }));
+ }
+ function write(profiles) {
+ const target = file(), temporary = `${target}.${process.pid}.tmp`;
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ try {
+ fs.writeFileSync(temporary, JSON.stringify({ v: 1, profiles }), { mode: 0o600 });
+ fs.renameSync(temporary, target);
+ } catch (error) {
+ try { fs.rmSync(temporary, { force: true }); } catch {}
+ throw error;
+ }
+ return profiles;
+ }
+ /** The name is free: no other workspace here has it, This Mac's own word for itself (`reserved`) included. */
+ const free = (profiles, name, except, reserved) => !profiles.some((entry) => entry.id !== except && sameName(entry.name ?? (entry.id === DEFAULT_PROFILE ? reserved : null), name));
+ function idFor(name, profiles) {
+ const used = (id) => id === DEFAULT_PROFILE || profiles.some((entry) => entry.id === id) || fs.existsSync(profileDir(dataDir(), id));
+ const slug = name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
+ if (slug && PROFILE_ID.test(slug) && !used(slug)) return slug;
+ for (;;) {
+ const id = `${slug && PROFILE_ID.test(slug) ? `${slug}-` : "w-"}${random()}`;
+ if (!used(id)) return id;
+ }
+ }
+ const find = (id) => list().find((entry) => entry.id === id) ?? null;
+ return {
+ list,
+ get: find,
+ /** A new workspace's entry, last; its folder is made when it first opens. `reserved`: what This Mac is called here. */
+ create({ name, color = null, reserved = null }) {
+ const clean = profileName(name), profiles = list();
+ if (!clean) return { ok: false, error: "name" };
+ if (!free(profiles, clean, null, reserved)) return { ok: false, error: "taken" };
+ if (profiles.length >= MAX_PROFILES) return { ok: false, error: "full" };
+ const profile = { id: idFor(clean, profiles), name: clean, color: swatch(color), createdAt: now() };
+ write([...profiles, profile]);
+ return { ok: true, profile };
+ },
+ rename(id, name, reserved = null) {
+ const clean = profileName(name), profiles = list();
+ if (!profiles.some((entry) => entry.id === id)) return { ok: false, error: "gone" };
+ if (!clean) return { ok: false, error: "name" };
+ if (!free(profiles, clean, id, reserved)) return { ok: false, error: "taken" };
+ write(profiles.map((entry) => (entry.id === id ? { ...entry, name: clean } : entry)));
+ return { ok: true };
+ },
+ recolor(id, color) {
+ const profiles = list();
+ if (!profiles.some((entry) => entry.id === id)) return { ok: false, error: "gone" };
+ write(profiles.map((entry) => (entry.id === id ? { ...entry, color: swatch(color) } : entry)));
+ return { ok: true };
+ },
+ remove(id) {
+ const profiles = list();
+ if (!profiles.some((entry) => entry.id === id)) return false;
+ write(profiles.filter((entry) => entry.id !== id));
+ return true;
+ },
+ };
+}
+
+/**
+ * @param {{
+ * registry: ReturnType<typeof createProfileRegistry>,
+ * clean: import("./clean-workspace.mjs").CleanWorkspace,
+ * dataDir(): string,
+ * home(): "cloud" | "local" | null,
+ * window: { openProfile(id: string): Promise<boolean>, profile(): string | null, showCloud(): Promise<unknown> },
+ * showLocal(): unknown,
+ * onLocal(): boolean,
+ * busy(): Promise<{ name: string, what?: string } | null>,
+ * trash(dir: string): Promise<void>,
+ * reserved?(): string | null,
+ * allowed?(): boolean,
+ * changed?(): void,
+ * log?(line: string): void,
+ * fs?: typeof nodeFs,
+ * sleep?(ms: number): Promise<void>,
+ * now?(): number,
+ * settleMs?: number,
+ * }} deps `home()`: My Cloud is home ("cloud"), no home but this computer ("local"), or another home (null). `window`: the
+ * home window's profile on screen (home-window.mjs), and My Cloud shown again. `showLocal()`: the window onto this
+ * computer's page, LOCAL_ID active. `onLocal()`: this computer's page is on screen. `busy()`: what the server that runs now
+ * still does (GET /api/move/freeze), null when nothing. `trash(dir)`: moves a folder to the computer's Trash. `reserved()`:
+ * what This Mac is called here (This Mac or This PC).
+ */
+export function createLocalProfiles({ registry, clean, dataDir, home, window: shown, showLocal, onLocal, busy, trash, reserved = () => null, allowed = () => true,
+ changed = () => {}, log = () => {}, fs = nodeFs, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now, settleMs = SETTLE_MS }) {
+ /** Each switch asked for; a newer one (another tile, My Cloud) ends the wait of the one before. */
+ let turn = 0;
+ /** The workspace a switch waits to open (null: This computer's own copy), and for whom. */
+ let settling = null;
+ const listed = (id) => registry.list().find((entry) => entry.id === id && offered(entry.id)) ?? null;
+ const offered = (id) => (home() === "cloud" ? true : home() === "local" ? id !== DEFAULT_PROFILE : false);
+ const running = () => clean.profile();
+ const tell = () => { try { changed(); } catch {} };
+
+ /** Waits while the server that runs now still works and will stop for this switch, at most `settleMs`. False when a newer
+ * switch took over. */
+ async function settle(mine, target, stops) {
+ if (!stops) return true;
+ const until = now() + settleMs;
+ for (;;) {
+ if (mine !== turn) return false;
+ let who = null;
+ try { who = await busy(); } catch {}
+ if (mine !== turn) return false;
+ if (!who) break;
+ if (now() >= until) { log(`local profiles: ${target} opens though ${who.name || who.what || "a turn"} still works`); break; }
+ if (settling?.id !== target || settling.name !== who.name) { settling = { id: target, name: who.name || "" }; tell(); }
+ await sleep(SETTLE_POLL_MS);
+ }
+ if (settling && mine === turn) { settling = null; tell(); }
+ return mine === turn;
+ }
+
+ /** True once workspace `id` is on screen, false when it can't open, null when a newer switch took over. */
+ async function open(id) {
+ const mine = ++turn;
+ if (!allowed() || !listed(id)) return false;
+ const stops = running() !== id && (home() === "local" || running() !== null);
+ if (!(await settle(mine, id, stops))) return null;
+ const opened = home() === "cloud" ? await shown.openProfile(id) : running() === id ? (await showLocal(), true) : await clean.open(id);
+ return opened || mine === turn ? opened : null;
+ }
+
+ return {
+ /** The rail's rows (cloud-rail.mjs railPlaces `profiles`); `activeLocal`: this computer's page is the window's place. */
+ places({ activeLocal }) {
+ const mode = home();
+ if (!allowed() || !mode) return [];
+ const onScreen = activeLocal ? (mode === "cloud" ? shown.profile() : running()) : null;
+ return registry.list().filter((entry) => offered(entry.id)).map((entry) => ({ id: entry.id, name: entry.name, color: swatchColor(entry.color), swatch: entry.color,
+ ...(entry.id === onScreen ? { active: true } : {}), ...(settling?.id === entry.id ? { settling: settling.name } : {}) }));
+ },
+ /** The workspace a switch waits to open (`id` null: This computer), and the name of what it waits for. */
+ settling: () => settling,
+ /** A new workspace may be added from + here. */
+ creatable: () => allowed() && home() !== null,
+ open,
+ /** Back to This computer's own copy from a workspace (no home but this computer). */
+ async computer() {
+ const mine = ++turn;
+ if (running() === null) { await showLocal(); return true; }
+ if (!(await settle(mine, null, true))) return null;
+ return clean.leave();
+ },
+ /** Another place was chosen: a switch still waiting ends. */
+ cancel() { turn++; if (settling) { settling = null; tell(); } },
+ /** A new workspace's entry; the rail opens it next (cloud-rail.mjs), so a switch that waits shows on its circle. */
+ create({ name, color }) {
+ if (!allowed() || home() === null) return { outcome: "failed" };
+ const made = registry.create({ name, color, reserved: reserved() });
+ if (!made.ok) return { outcome: made.error === "full" ? "failed" : made.error };
+ tell();
+ return { outcome: "made", id: made.profile.id };
+ },
+ rename(id, name) {
+ if (!listed(id)) return { outcome: "gone" };
+ const done = registry.rename(id, name, reserved());
+ if (done.ok) tell();
+ return { outcome: done.ok ? "saved" : done.error };
+ },
+ recolor(id, color) {
+ if (!listed(id)) return { outcome: "gone" };
+ const done = registry.recolor(id, color);
+ if (done.ok) tell();
+ return { outcome: done.ok ? "saved" : done.error };
+ },
+ /** Removes workspace `id` from this computer: its server stopped first (the window on another place), then its folder
+ * to the Trash, then its entry. */
+ async remove(id) {
+ if (!listed(id)) return { outcome: "gone" };
+ turn++;
+ if (running() === id) {
+ if (!(await clean.leave()) || running() === id) return { outcome: "failed" };
+ if (home() === "cloud") await shown.showCloud();
+ }
+ const dir = profileDir(dataDir(), id);
+ try {
+ if (fs.existsSync(dir)) await trash(dir);
+ } catch (error) {
+ log(`local profiles: ${id} could not go to the Trash (${error?.message ?? error})`);
+ try { fs.renameSync(dir, path.join(profilesDir(dataDir()), `.removed-${id}-${now()}`)); }
+ catch { return { outcome: "failed" }; }
+ }
+ registry.remove(id);
+ tell();
+ if (home() === "local" && running() === null && !onLocal()) await showLocal();
+ return { outcome: "removed" };
+ },
+ /** What the window's top bar and line call the workspace that runs: its own name, or null for This Mac's. */
+ name: (id) => registry.get(id)?.name ?? null,
+ };
+}
diff --git a/electron/local-profiles.node-test.mjs b/electron/local-profiles.node-test.mjs
new file mode 100644
index 0000000000..a5efe1d30c
--- /dev/null
+++ b/electron/local-profiles.node-test.mjs
@@ -0,0 +1,259 @@
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { createCleanWorkspace, DEFAULT_PROFILE, profileDir, profilesDir } from "./clean-workspace.mjs";
+import { createLocalProfiles, createProfileRegistry, MAX_PROFILES, PROFILES_FILE, profileName, SETTLE_MS } from "./local-profiles.mjs";
+
+/** This computer's data folder on disk, with the one server the app runs at a time (`running`), the real profile swap
+ * (clean-workspace.mjs) over it, the registry beside it and the home window's side of a profile on screen. */
+function computer(t, { home = "cloud", frozen = home === "cloud" } = {}) {
+ const parent = mkdtempSync(join(tmpdir(), "omb-profiles-"));
+ t.after(() => rmSync(parent, { recursive: true, force: true }));
+ const dataDir = join(parent, ".openmausbot");
+ mkdirSync(dataDir, { recursive: true });
+ if (frozen) writeFileSync(join(dataDir, "moved.json"), JSON.stringify({ v: 1, at: 1, cloud: "https://omb-t-1.fly.dev" }));
+ let clock = 1_000;
+ const w = { dataDir, running: dataDir, swaps: [], home, shown: null, onScreen: "cloud", busy: [], trashed: [], trashFails: false, changes: 0, logs: [], waits: 0 };
+ w.now = () => clock;
+ w.clean = createCleanWorkspace({ dataDir: () => dataDir, running: () => w.running,
+ swap: async (dir) => { w.swaps.push(dir); await new Promise((resolve) => setImmediate(resolve)); w.running = dir; w.onScreen = "local"; return { ok: true }; } });
+ w.registry = createProfileRegistry({ dataDir: () => dataDir, now: w.now, random: () => "abc123" });
+ w.profiles = createLocalProfiles({ registry: w.registry, clean: w.clean, dataDir: () => dataDir, home: () => w.home,
+ window: {
+ openProfile: async (id) => { if (w.beforeOpen) return w.beforeOpen(); const opened = await w.clean.open(id); if (opened) { w.shown = id; w.onScreen = "local"; } return opened; },
+ profile: () => w.shown,
+ showCloud: async () => { w.shown = null; w.onScreen = "cloud"; },
+ },
+ showLocal: () => { w.onScreen = "local"; }, onLocal: () => w.onScreen === "local",
+ busy: async () => w.busy[0] ?? null,
+ trash: async (dir) => { if (w.trashFails) throw new Error("no Trash here"); w.trashed.push(dir); rmSync(dir, { recursive: true, force: true }); },
+ reserved: () => "This Mac", changed: () => { w.changes++; }, log: (line) => w.logs.push(line), now: w.now,
+ sleep: async (ms) => { clock += ms; w.waits++; w.onWait?.(); } });
+ w.file = () => join(profilesDir(dataDir), PROFILES_FILE);
+ w.saved = () => JSON.parse(readFileSync(w.file(), "utf8"));
+ return w;
+}
+
+test("a name is one line a person typed: trimmed, no control characters, at most 40 characters", () => {
+ assert.equal(profileName(" Work \n stuff "), "Work stuff");
+ assert.equal(profileName("\u0007Bell"), "Bell");
+ assert.equal(profileName(" "), null);
+ assert.equal(profileName(42), null);
+ assert.equal([...profileName("😀".repeat(60))].length, 40, "by characters, never splitting one");
+});
+
+test("This Mac is the registry's first entry before anything is written: a computer from before keeps its folder and its data", (t) => {
+ const w = computer(t);
+ mkdirSync(profileDir(w.dataDir, DEFAULT_PROFILE), { recursive: true });
+ writeFileSync(join(profileDir(w.dataDir, DEFAULT_PROFILE), "bots.json"), "[\"made-there\"]");
+ assert.deepEqual(w.registry.list().map(({ id, name, color }) => ({ id, name, color })), [{ id: "default", name: null, color: null }]);
+ assert.equal(existsSync(w.file()), false, "reading writes nothing");
+ const made = w.registry.create({ name: "Work", color: "green" });
+ assert.equal(made.ok, true);
+ assert.deepEqual(w.saved().profiles.map(({ id, name, color }) => ({ id, name, color })), [{ id: "default", name: null, color: null }, { id: "work", name: "Work", color: "green" }],
+ "the first change writes This Mac down first, as it was");
+ assert.equal(readFileSync(join(profileDir(w.dataDir, DEFAULT_PROFILE), "bots.json"), "utf8"), "[\"made-there\"]");
+});
+
+test("create, rename, colour and remove: names stay unique (This Mac's own name included), ids are folder names that never change", (t) => {
+ const w = computer(t);
+ const work = w.registry.create({ name: " Work ", color: "rose" });
+ assert.deepEqual(work, { ok: true, profile: { id: "work", name: "Work", color: "rose", createdAt: 1_000 } });
+ assert.deepEqual(w.registry.create({ name: "work" }), { ok: false, error: "taken" });
+ assert.deepEqual(w.registry.create({ name: "this mac", reserved: "This Mac" }), { ok: false, error: "taken" }, "This Mac's name is This Mac's");
+ assert.deepEqual(w.registry.create({ name: " " }), { ok: false, error: "name" });
+ assert.equal(w.registry.create({ name: "Café ☕", color: "not-a-swatch" }).profile.id, "cafe", "a folder name from the name");
+ assert.equal(w.registry.create({ name: "工作" }).profile.id, "w-abc123", "a name with no letters a folder can take");
+ mkdirSync(profileDir(w.dataDir, "personal"), { recursive: true });
+ assert.equal(w.registry.create({ name: "Personal" }).profile.id, "personal-abc123", "a folder already there is never reused");
+ assert.equal(w.registry.get("cafe").color, null, "an unknown colour is none");
+ assert.deepEqual(w.registry.rename("work", "Office"), { ok: true });
+ assert.deepEqual(w.registry.rename("work", "café ☕"), { ok: false, error: "taken" });
+ assert.deepEqual(w.registry.rename("work", ""), { ok: false, error: "name" });
+ assert.deepEqual(w.registry.rename("gone", "X"), { ok: false, error: "gone" });
+ assert.deepEqual(w.registry.rename(DEFAULT_PROFILE, "Home"), { ok: true }, "This Mac may take a name of its own");
+ assert.deepEqual(w.registry.recolor("work", "violet"), { ok: true });
+ assert.deepEqual(w.registry.recolor("work", null), { ok: true });
+ assert.deepEqual(w.registry.get("work"), { id: "work", name: "Office", color: null, createdAt: 1_000 });
+ assert.equal(w.registry.remove("work"), true);
+ assert.equal(w.registry.remove("work"), false);
+ assert.deepEqual(w.registry.list().map((entry) => entry.id), ["default", "cafe", "w-abc123", "personal-abc123"]);
+ assert.equal(w.registry.remove(DEFAULT_PROFILE), true);
+ assert.deepEqual(w.registry.list().map((entry) => entry.id), ["cafe", "w-abc123", "personal-abc123"], "This Mac removed stays removed");
+});
+
+test("a registry someone edited by hand: anything not a folder name is dropped, nothing reaches outside the profiles' folder", (t) => {
+ const w = computer(t);
+ mkdirSync(profilesDir(w.dataDir), { recursive: true });
+ writeFileSync(w.file(), JSON.stringify({ v: 1, profiles: [{ id: "../.openmausbot", name: "Evil" }, { id: "work", name: "Work" }, { id: "work", name: "Again" }, { id: "Work2" }, null] }));
+ assert.deepEqual(w.registry.list().map((entry) => entry.id), ["work"]);
+ writeFileSync(w.file(), "not json");
+ assert.deepEqual(w.registry.list().map((entry) => entry.id), ["default"]);
+});
+
+test(`at most ${MAX_PROFILES} workspaces`, (t) => {
+ const w = computer(t);
+ for (let at = 1; at < MAX_PROFILES; at++) assert.equal(w.registry.create({ name: `W${at}` }).ok, true);
+ assert.deepEqual(w.registry.create({ name: "One more" }), { ok: false, error: "full" });
+});
+
+test("who sees which: once My Cloud is home every workspace, This Mac first; with no home the named ones only; another home none", (t) => {
+ const w = computer(t);
+ w.registry.create({ name: "Work", color: "green" });
+ assert.deepEqual(w.profiles.places({ activeLocal: false }), [
+ { id: "default", name: null, color: null, swatch: null },
+ { id: "work", name: "Work", color: "teal", swatch: "green" },
+ ]);
+ w.home = "local";
+ assert.deepEqual(w.profiles.places({ activeLocal: true }).map((row) => row.id), ["work"]);
+ assert.equal(w.profiles.creatable(), true);
+ w.home = null;
+ assert.deepEqual(w.profiles.places({ activeLocal: true }), []);
+ assert.equal(w.profiles.creatable(), false);
+ assert.deepEqual(w.profiles.create({ name: "Lab" }), { outcome: "failed" });
+});
+
+test("switching once My Cloud is home: one runs at a time, the next one starts on its own folder, My Cloud never stops it", async (t) => {
+ const w = computer(t);
+ const work = w.profiles.create({ name: "Work" });
+ assert.deepEqual(work, { outcome: "made", id: "work" });
+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), true);
+ assert.deepEqual([w.running, w.shown], [profileDir(w.dataDir, DEFAULT_PROFILE), DEFAULT_PROFILE]);
+ assert.deepEqual(w.profiles.places({ activeLocal: true }).filter((row) => row.active).map((row) => row.id), [DEFAULT_PROFILE]);
+ writeFileSync(join(profileDir(w.dataDir, DEFAULT_PROFILE), "bots.json"), "[\"Scout\"]");
+ assert.equal(await w.profiles.open("work"), true);
+ assert.deepEqual(w.swaps, [profileDir(w.dataDir, DEFAULT_PROFILE), profileDir(w.dataDir, "work")], "This Mac's server stopped, Work's started");
+ assert.equal(readFileSync(join(profileDir(w.dataDir, DEFAULT_PROFILE), "bots.json"), "utf8"), "[\"Scout\"]", "what was made in This Mac stays");
+ assert.equal(existsSync(join(profileDir(w.dataDir, "work"), "bots.json")), false, "Work starts fresh");
+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), true);
+ assert.equal(readFileSync(join(profileDir(w.dataDir, DEFAULT_PROFILE), "bots.json"), "utf8"), "[\"Scout\"]");
+ assert.equal(JSON.parse(readFileSync(join(w.dataDir, "moved.json"), "utf8")).cloud, "https://omb-t-1.fly.dev", "the frozen copy stays frozen and never runs");
+ assert.equal(w.swaps.includes(w.dataDir), false);
+ assert.equal(await w.profiles.open("nope"), false, "only a workspace the registry has");
+});
+
+test("a switch waits for the work under way in the workspace it leaves, says so on the circle it opens, then goes", async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ await w.profiles.open(DEFAULT_PROFILE);
+ w.busy = [{ name: "Scout", what: "bot" }];
+ let seen = null;
+ w.onWait = () => { seen ??= w.profiles.places({ activeLocal: true }).find((row) => row.id === "work"); if (w.waits === 3) w.busy = []; };
+ assert.equal(await w.profiles.open("work"), true);
+ assert.equal(w.waits, 3, "it waited while Scout answered");
+ assert.deepEqual(seen, { id: "work", name: "Work", color: null, swatch: null, settling: "Scout" });
+ assert.equal(w.profiles.places({ activeLocal: true }).find((row) => row.id === "work").settling, undefined, "and the circle says nothing once it went");
+ assert.equal(w.running, profileDir(w.dataDir, "work"));
+});
+
+test(`a switch waits at most ${SETTLE_MS / 1000} s: then the server stops as a quit stops it, and each cut turn says so there`, async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ await w.profiles.open(DEFAULT_PROFILE);
+ w.busy = [{ name: "Scout", what: "bot" }];
+ assert.equal(await w.profiles.open("work"), true);
+ assert.equal(w.waits, SETTLE_MS / 1000);
+ assert.match(w.logs.at(-1), /work opens though Scout still works/);
+});
+
+test("nothing to wait for when the frozen copy runs: My Cloud's first This Mac opens at once", async (t) => {
+ const w = computer(t);
+ w.busy = [{ name: "never asked", what: "bot" }];
+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), true);
+ assert.equal(w.waits, 0);
+});
+
+test("a second click takes over: the first switch's wait ends, and only the last place clicked opens", async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ w.profiles.create({ name: "Personal" });
+ await w.profiles.open(DEFAULT_PROFILE);
+ w.busy = [{ name: "Scout", what: "bot" }];
+ let second = null;
+ w.onWait = () => { if (w.waits === 2) { w.busy = []; second = w.profiles.open("personal"); } };
+ assert.equal(await w.profiles.open("work"), null, "taken over");
+ assert.equal(await second, true);
+ assert.deepEqual(w.swaps.slice(1), [profileDir(w.dataDir, "personal")], "Work never started");
+ w.busy = [{ name: "Scout", what: "bot" }];
+ w.waits = 0; w.onWait = () => { if (w.waits === 1) w.profiles.cancel(); };
+ assert.equal(await w.profiles.open("work"), null, "My Cloud clicked meanwhile: nothing opens");
+ assert.equal(w.running, profileDir(w.dataDir, "personal"));
+ assert.equal(w.profiles.settling(), null);
+});
+
+test("with no home but this computer: This computer is the data folder as ever, and a workspace's switch stops it, and back", async (t) => {
+ const w = computer(t, { home: "local" });
+ w.onScreen = "local";
+ w.profiles.create({ name: "Work" });
+ assert.equal(await w.profiles.open("work"), true);
+ assert.equal(w.running, profileDir(w.dataDir, "work"));
+ assert.deepEqual(w.profiles.places({ activeLocal: true }), [{ id: "work", name: "Work", color: null, swatch: null, active: true }]);
+ w.busy = [{ name: "Juno", what: "bot" }];
+ w.onWait = () => { assert.deepEqual(w.profiles.settling(), { id: null, name: "Juno" }); w.busy = []; };
+ assert.equal(await w.profiles.computer(), true);
+ assert.equal(w.running, w.dataDir, "This computer's own server again");
+ w.onScreen = "elsewhere";
+ assert.equal(await w.profiles.open("work"), true);
+ w.onScreen = "a server";
+ assert.equal(await w.profiles.open("work"), true, "already running: the window comes back to it");
+ assert.equal(w.onScreen, "local");
+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), false, "This Mac's profile isn't one here");
+});
+
+test("removing the workspace on screen: the window goes to My Cloud and its server stops first, then its folder goes to the Trash", async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ await w.profiles.open("work");
+ writeFileSync(join(profileDir(w.dataDir, "work"), "bots.json"), "[]");
+ assert.deepEqual(await w.profiles.remove("work"), { outcome: "removed" });
+ assert.equal(w.running, w.dataDir, "stopped before anything was removed");
+ assert.equal(w.onScreen, "cloud");
+ assert.deepEqual(w.trashed, [profileDir(w.dataDir, "work")]);
+ assert.deepEqual(w.registry.list().map((entry) => entry.id), ["default"]);
+ assert.deepEqual(await w.profiles.remove("work"), { outcome: "gone" });
+});
+
+test("removing the last one leaves My Cloud; one that never opened has no folder to keep; a missing Trash keeps the folder aside", async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ assert.deepEqual(await w.profiles.remove("work"), { outcome: "removed" });
+ assert.deepEqual(w.trashed, [], "never opened, nothing on disk");
+ await w.profiles.open(DEFAULT_PROFILE);
+ w.trashFails = true;
+ assert.deepEqual(await w.profiles.remove(DEFAULT_PROFILE), { outcome: "removed" });
+ assert.deepEqual([w.onScreen, w.profiles.places({ activeLocal: true })], ["cloud", []], "no workspace of this computer's own left: My Cloud");
+ assert.equal(existsSync(profileDir(w.dataDir, DEFAULT_PROFILE)), false);
+ assert.ok(readdirSync(profilesDir(w.dataDir)).some((name) => name.startsWith(".removed-default-")), "kept aside, never deleted outright");
+});
+
+test("removing the workspace on screen with no home: back on This computer, and the rail's rows go with it", async (t) => {
+ const w = computer(t, { home: "local" });
+ w.profiles.create({ name: "Work" });
+ await w.profiles.open("work");
+ assert.deepEqual(await w.profiles.remove("work"), { outcome: "removed" });
+ assert.deepEqual([w.running, w.onScreen], [w.dataDir, "local"]);
+ assert.deepEqual(w.profiles.places({ activeLocal: true }), []);
+});
+
+test("renaming and recolouring a workspace the rail lists, and refusing one it doesn't", (t) => {
+ const w = computer(t, { home: "local" });
+ w.profiles.create({ name: "Work" });
+ assert.deepEqual(w.profiles.rename("work", "Office"), { outcome: "saved" });
+ assert.deepEqual(w.profiles.recolor("work", "amber"), { outcome: "saved" });
+ assert.deepEqual(w.profiles.rename(DEFAULT_PROFILE, "Home"), { outcome: "gone" }, "This Mac isn't on this rail");
+ assert.deepEqual(w.profiles.places({ activeLocal: false }), [{ id: "work", name: "Office", color: "yellow", swatch: "amber" }]);
+ assert.equal(w.profiles.name("work"), "Office");
+ assert.equal(w.profiles.name(DEFAULT_PROFILE), null);
+});
+
+test("a switch a newer click took over while its workspace started says so (null), never that it failed: no error over the place the person chose", async (t) => {
+ const w = computer(t);
+ w.profiles.create({ name: "Work" });
+ w.beforeOpen = () => { w.profiles.cancel(); return false; };
+ assert.equal(await w.profiles.open("work"), null, "the home window gave way to the newer click");
+ w.beforeOpen = () => false;
+ assert.equal(await w.profiles.open("work"), false, "with no newer click it didn't open: main says so");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 4f9edba8a8..f9e1f53e69 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 { 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 { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-workspace.mjs"; import { createLocalProfiles, createProfileRegistry } from "./local-profiles.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";
@@ -1674,7 +1674,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
}
async function switchEnvironment(id) {
- if (id === LOCAL_ID && homeWindow.cloudOrigin() && cleanWorkspace.profile()) return void await homeWindow.openProfile(cleanWorkspace.profile()); if ((id === environmentsState.activeId && !homeWindow.asking()) || (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id))) return;
+ if (id === LOCAL_ID && cleanWorkspace.profile()) return void await (homeWindow.cloudOrigin() ? localProfiles.open(cleanWorkspace.profile()) : localProfiles.computer()); 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 } });
@@ -2667,7 +2667,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 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() }); };
+const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); 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: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };
// 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()}`],
@@ -2680,7 +2680,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), openProfile: id => workspaceMenuAction(async () => { const opened = await homeWindow.openProfile(id); railChanged(); if (!opened) throw new Error(nativeT("native.places.profileFailed")); }),
+ 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 localProfiles.open(id); railChanged(); if (opened === false) throw new Error(nativeT("native.places.profileFailed")); }), local: localProfiles,
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,
@@ -2763,11 +2763,11 @@ 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 } : {}), ...(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())));
+const homeAlone = () => Boolean(homeWindow.cloudOrigin()) && !otherPlaces(environmentsState, homeWindow.cloudOrigin()) && !localProfiles.places({ activeLocal: false }).length;
+ipcMain.handle("workspaces:state", workspaceOnly(event => ({ ...workspaceSummary(environmentsState), ...(homeAlone() && homeWindow.homePage(event) ? { home: true } : {}), ...(cleanWorkspace.profile() && senderIsLocal(event) ? { profile: cleanWorkspace.profile(), ...(localProfiles.name(cleanWorkspace.profile()) ? { profileName: localProfiles.name(cleanWorkspace.profile()) } : {}) } : {}) })));
+ipcMain.handle("workspaces:line", workspaceOnly(event => (cleanWorkspace.active() && senderIsLocal(event) ? (cleanWorkspace.profile() ? { kind: "profile", ...(localProfiles.name(cleanWorkspace.profile()) ? { name: localProfiles.name(cleanWorkspace.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) => {
+ipcMain.handle("workspaces:menu", workspaceOnly(async (event, from) => {
if (workspaceMenuOpen || homeAlone()) return;
workspaceMenuOpen = true;
try {
@@ -2777,7 +2777,7 @@ ipcMain.handle("workspaces:menu", workspaceOnly(async (_event, from) => {
onConnect: () => void workspaceMenuAction(openWorkspaceSettings),
onForget: (id) => void workspaceMenuAction(() => forgetEnvironment(id)),
...cloudMenuOptions(from === "howto" ? "app_howto" : "app_menu"),
- ...(await placesMenuOptions({ homeOrigin: homeWindow.cloudOrigin(), cloud: cloudHomeEntry(), home: oneHome.away() || ownHome?.away() === true, platform: process.platform, port: SERVER_PORT, text: nativeText })), text: nativeText,
+ ...(await placesMenuOptions({ homeOrigin: homeWindow.cloudOrigin(), cloud: cloudHomeEntry(), home: oneHome.away() || ownHome?.away() === true, platform: process.platform, port: SERVER_PORT, text: nativeText })), text: nativeText, locals: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }).map(local => ({ id: local.id, label: local.name ?? nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), shown: local.active === true })), onLocal: id => void workspaceMenuAction(async () => { if ((await localProfiles.open(id)) === false) throw new Error(nativeT("native.places.profileFailed")); }), ...(localProfiles.creatable() && senderIsLocal(event) ? { onNewLocal: () => event.sender.send("workspaces:new-local") } : {}),
}));
await new Promise((resolve) => menu.popup({ window: mainWindow, callback: resolve }));
} finally {
diff --git a/electron/native-text.cjs b/electron/native-text.cjs
index 22ffdb80c5..a4f5fc742d 100644
--- a/electron/native-text.cjs
+++ b/electron/native-text.cjs
@@ -6,7 +6,7 @@ const LOCALE_FILE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*\.json$/;
const SOURCE_HASHES = "source-hashes.json";
const ENGLISH = "en";
const LOCALE_ALIASES = Object.freeze({ pt: "pt-br", "zh-hant": "zh-tw", "zh-hk": "zh-tw", "zh-mo": "zh-tw" });
-const SHARED_KEYS = new Set(["place.local", "rail.thisComputer", "rail.remove", "cloudHome.tryAgain", "computer.windows.start", "mcp.turnOn", "cloudSetup.myCloud", "computer.badge.local", "room.aBot"]);
+const SHARED_KEYS = new Set(["place.local", "rail.thisComputer", "rail.thisMac", "rail.thisPc", "rail.remove", "cloudHome.tryAgain", "computer.windows.start", "mcp.turnOn", "cloudSetup.myCloud", "computer.badge.local", "room.aBot"]);
const kept = (key) => key.startsWith("native.") || key.startsWith("teamMove.") || SHARED_KEYS.has(key);
/** Security: a language is only ever a pack file listed here; a code from a page never reaches a path unchecked. */
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 637fbbb0de..b48cc52ea9 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -174,6 +174,23 @@ const bridge = {
ipcRenderer.on("workspaces:changed", handler);
return () => ipcRenderer.removeListener("workspaces:changed", handler);
},
+ // A workspace of this computer's own, from a click on the rail's page or this computer's own page (main refuses any
+ // other): a new one by its name and colour, and a name, colour or removal for one the rail lists.
+ local: {
+ create: (name, color) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:local-new", String(name), color === null || color === undefined ? null : String(color)) : Promise.reject(new Error("Choose a name.")),
+ edit: (id, changes) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:local-edit", String(id), typeof changes?.name === "string" ? { name: changes.name } : { color: changes?.color === null || changes?.color === undefined ? null : String(changes.color) })
+ : Promise.reject(new Error("Choose a change.")),
+ remove: (id) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("workspaces:local-remove", String(id)) : Promise.reject(new Error("Choose Remove.")),
+ },
+ // The Server menu's New workspace on this computer, for this computer's own page to ask its name.
+ onNewLocal: (cb) => {
+ const handler = () => cb();
+ ipcRenderer.on("workspaces:new-local", handler);
+ return () => ipcRenderer.removeListener("workspaces:new-local", handler);
+ },
},
// The window's own rail (this app's page at /rail, beside every place's page): while a sheet of its own is open it
// covers the window; the skin of the page beside it comes from main, and whether that page draws the window's frame.
diff --git a/scripts/testing/one-workspace-fixture.ts b/scripts/testing/one-workspace-fixture.ts
index e25e7168c7..6c8526221b 100644
--- a/scripts/testing/one-workspace-fixture.ts
+++ b/scripts/testing/one-workspace-fixture.ts
@@ -14,7 +14,7 @@
// 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";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { createServer as createHttpServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -23,7 +23,8 @@ 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 { createCleanWorkspace } from "../../electron/clean-workspace.mjs";
+import { createLocalProfiles, createProfileRegistry } from "../../electron/local-profiles.mjs";
import { parsePairingGrant, withCloudHome } from "../../electron/cloud-home.mjs";
import { installCloudRail, railPlaces } from "../../electron/cloud-rail.mjs";
import { createComputerSharing } from "../../electron/computer-sharing.mjs";
@@ -191,8 +192,9 @@ function preloadStandIn(ipcBase: string, localOrigin: string, tab = "window"): s
for (const notice of ${JSON.stringify(NOTICES)}) localStorage.setItem(notice, "1"); } catch {}
const listeners = new Map();
window.__ogbEmit = (channel, ...args) => { for (const listener of [...(listeners.get(channel) ?? [])]) listener({}, ...args); };
+ let sent = 0;
const call = async (channel, args) => {
- const response = await fetch(${JSON.stringify(ipcBase)} + "/__ipc/" + channel + "?tab=${tab}", { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify({ args }) });
+ const response = await fetch(${JSON.stringify(ipcBase)} + "/__ipc/" + channel + "?tab=${tab}&seq=" + (++sent), { 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;
@@ -258,6 +260,19 @@ export interface HomeWorld {
lending: ReturnType<typeof createComputerSharing> | null;
/** The folder this computer's server runs on now. */
running(): string;
+ /** With `profiles`: the workspaces of this computer's own as main keeps them (local-profiles.mjs), and the Trash a
+ * removed one goes to. */
+ registry: ReturnType<typeof createProfileRegistry> | null;
+ readonly profiles: ReturnType<typeof createLocalProfiles> | null;
+ trashDir: string;
+ /** A sheet of the rail's is open: its view covers the window. */
+ railCovers(): boolean;
+ setSize(width: number, height: number): Promise<void>;
+ /** The OS's light or dark look, which both pages follow. */
+ theme(dark: boolean): Promise<void>;
+ /** The app quits and opens again: this computer's server stopped as a quit stops it and started on the data folder, and a
+ * new home window that knows nothing of the last run shows home. */
+ restartApp(): Promise<void>;
/** 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. */
@@ -311,6 +326,8 @@ 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;
+ let railCovers = false;
+ const size = { width: 1280, height: 800 };
// 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) => {
@@ -364,6 +381,8 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
// Main's ipcMain, reached by the preload's ipcRenderer.
const handlers = new Map<string, (...args: any[]) => unknown>();
+ /** The last invoke each tab's page sent that main has started on. */
+ const started = new Map<string, number>();
const syncHandlers = new Map<string, (event: any) => void>();
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) => {
@@ -383,7 +402,11 @@ 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 = new URLSearchParams(query).get("tab") === "rail" && railRef ? railRef : windowRef!;
+ const params = new URLSearchParams(query), tab = params.get("tab") ?? "window", seq = Number(params.get("seq") ?? 0);
+ // Electron hands a page's invokes to main in the order the page sent them; separate HTTP requests may arrive in any.
+ for (let waits = 0; asked && seq > 1 && (started.get(tab) ?? 0) < seq - 1 && waits < 40; waits++) await new Promise((resolve) => setTimeout(resolve, 50));
+ if (asked) started.set(tab, seq);
+ const win = 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]!);
@@ -402,11 +425,15 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
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 } : {}),
- ...(clean?.profile() && new URL(event.senderFrame.url).origin === localOrigin ? { profile: clean.profile() } : {}) }),
+ ...(clean?.profile() && new URL(event.senderFrame.url).origin === localOrigin ? { profile: clean.profile(), ...(localProfiles?.name(clean.profile()!) ? { profileName: localProfiles.name(clean.profile()!) } : {}) } : {}) }),
"workspaces:menu": () => null,
- "workspaces:line": (event) => (clean?.active() && new URL(event.senderFrame.url).origin === localOrigin ? (clean.profile() ? { kind: "profile" } : { kind: "clean" }) : homePlaces.line()),
+ "workspaces:line": (event) => (clean?.active() && new URL(event.senderFrame.url).origin === localOrigin ? (clean.profile() ? { kind: "profile", ...(localProfiles?.name(clean.profile()!) ? { name: localProfiles.name(clean.profile()!) } : {}) } : { kind: "clean" }) : homePlaces.line()),
"rail:offer": () => ({ available: true, hidden: false }),
- "rail:expand": () => null,
+ // chrome-rail.mjs: while a sheet of the rail's is open, its view covers the window, see-through but for the sheet.
+ "rail:expand": async (_event, covering) => {
+ railCovers = covering === true;
+ if (railRef) await cdp.request("Emulation.setDeviceMetricsOverride", { width: railCovers ? size.width : 36, height: size.height, deviceScaleFactor: 2, mobile: false }, railRef.sessionId);
+ },
"rail:draws-frame": () => null,
"desktop-notices:state": () => ({ seen: [...NOTICES], cloud: false }),
"desktop-notices:seen": () => null,
@@ -521,6 +548,12 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
const clean = profiles ? createCleanWorkspace({
dataDir: () => fx.desktopDataDir, running: () => running,
swap: async (dir: string) => {
+ // A workspace's first config as the app writes it, with the fixture's AIs only, so nothing on this machine's PATH is used.
+ const config = join(dir, "config.json");
+ if (dir !== fx.desktopDataDir && existsSync(config)) {
+ const seeded = JSON.parse(readFileSync(config, "utf8"));
+ if (!seeded.instances) writeFileSync(config, JSON.stringify({ ...seeded, instances: JSON.parse(readFileSync(join(fx.desktopDataDir, "config.json"), "utf8")).instances }));
+ }
await fx.relaunch({ kill: false, ...(dir === fx.desktopDataDir ? {} : { dataDir: dir }) });
running = dir;
persist(environments.withActive(envState, environments.LOCAL_ID));
@@ -531,7 +564,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
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({
+ const makeHome = () => 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 (clean ? clean.realCopy(ownCopy) : ownCopy)("/api/move/freeze")).json() : { frozen: false }),
@@ -561,19 +594,25 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
versionEveryMs, quietMs,
log: () => {},
});
- homeRef = home;
- installHomeWindowIpc({ ipcMain, homeWindow: home, cloudPage: (event: any) => (home.homePage(event) ? "cloud" : null) });
- responded = (details) => home.responded(details);
- win.webContents.on("did-navigate", (_event: unknown, url: string) => home.navigated(url));
- win.webContents.on("did-fail-load", (_event: unknown, _code: number, _description: string, url: string) => home.failed(url));
- cleanup.unshift(() => home.close());
+ // A launch of the app: its home window as main makes it, knowing nothing of the last run.
+ const launchHome = () => {
+ const made = makeHome();
+ homeRef = made;
+ installHomeWindowIpc({ ipcMain, homeWindow: made, cloudPage: (event: any) => (made.homePage(event) ? "cloud" : null) });
+ return made;
+ };
+ let home = launchHome();
+ responded = (details) => homeRef!.responded(details);
+ win.webContents.on("did-navigate", (_event: unknown, url: string) => homeRef!.navigated(url));
+ win.webContents.on("did-fail-load", (_event: unknown, _code: number, _description: string, url: string) => homeRef!.failed(url));
+ cleanup.unshift(() => homeRef!.close());
// main.mjs's own delivery of a link the OS opened: queued, then sent to the page that is home.
const start = MAIN.indexOf("/** To this computer's page, or to My Cloud's once it is home");
const end = MAIN.indexOf('app.on("open-url"', start);
const linkContext = vm.createContext({
homeWindow: home, rendererOrigin: () => localOrigin, activeRemote: () => null, environmentsState: { environments: [], activeId: "local" },
- showHome: () => home.show(), workspaceMenuAction: (action: () => unknown) => action(), switchEnvironment: () => {}, LOCAL_ID: "local",
+ showHome: () => homeRef!.show(), workspaceMenuAction: (action: () => unknown) => action(), switchEnvironment: () => {}, LOCAL_ID: "local",
mainWindow: win, desktopTray: null, startupScreen: null, BrowserWindow: { getAllWindows: () => [win] }, activateExistingWindow: () => true,
chatLinkFrom, packageUrlFromDeepLink, pendingChatLink: null, pendingPackageInstallUrl: null, URL,
});
@@ -582,29 +621,50 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
// 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 }] : [] });
+ // main.mjs's localProfiles: the registry beside the profiles' folders, the Trash a folder of the fixture's own, and what
+ // the server that runs still does asked as main asks it.
+ const trashDir = join(fx.root, "Trash");
+ const registry = profiles ? createProfileRegistry({ dataDir: () => fx.desktopDataDir }) : null;
+ const makeLocal = () => (clean && registry ? createLocalProfiles({ registry, clean, dataDir: () => fx.desktopDataDir,
+ home: () => (homeRef!.cloudOrigin() ? "cloud" : clean.marker().frozen ? null : "local"),
+ window: { openProfile: (id: string) => homeRef!.openProfile(id), profile: () => homeRef!.profile(), showCloud: () => homeRef!.show({ place: "cloud" }) },
+ showLocal: () => { homeRef!.cancel(); persist(environments.withActive(envState, environments.LOCAL_ID)); return win.loadURL(`${localOrigin}/`).catch(() => {}); },
+ onLocal: () => /^https?:/.test(win.url) && new URL(win.url).origin === localOrigin,
+ busy: async () => { const said = await (await ownCopy("/api/move/freeze")).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; },
+ trash: async (dir: string) => { mkdirSync(trashDir, { recursive: true }); renameSync(dir, join(trashDir, `${Date.now()}-${dir.split(/[\\/]/).pop()}`)); },
+ reserved: () => "This Mac", changed: () => railHandlers?.changed() }) : null);
+ let localProfiles = makeLocal();
+ const railList = () => {
+ const settling = localProfiles?.settling() ?? null;
+ return railPlaces({ saved: envState, home: homeRef!.cloudOrigin(), mine: cloudOrigin, state: account.state,
+ profiles: localProfiles?.places({ activeLocal: envState.activeId === environments.LOCAL_ID }) ?? [], computerSettling: settling && settling.id === null ? settling.name : null });
+ };
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);
+ await cdp.request("Emulation.setDefaultBackgroundColorOverride", { color: { r: 0, g: 0, b: 0, a: 0 } }, 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: () => {} },
+ add: { choices: () => ({ cloud: false, link: true, 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();
+ // main.mjs's switchEnvironment: This computer (its own copy, or back from a workspace), or My Cloud shown again.
+ open: async (id: string) => {
+ if (id === environments.LOCAL_ID && clean!.profile()) { await (homeRef!.cloudOrigin() ? localProfiles!.open(clean!.profile()!) : localProfiles!.computer()); railHandlers?.changed(); return; }
+ homeRef!.cancel();
+ if (id === environments.LOCAL_ID) { persist(environments.withActive(envState, environments.LOCAL_ID)); await win.loadURL(`${localOrigin}/`).catch(() => {}); return; }
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");
+ if (entry?.origin === homeRef!.cloudOrigin()) return homeRef!.show({ place: "cloud" }).then(() => railHandlers?.changed());
+ throw new Error("This harness opens My Cloud and this computer's own places only");
},
openProfile: async (id: string) => {
- const opened = await home.openProfile(id);
+ const opened = await localProfiles!.open(id);
railHandlers?.changed();
- if (!opened) throw new Error("This computer's own place didn't open.");
+ if (opened === false) throw new Error("This computer's own place didn't open.");
},
+ local: { creatable: () => localProfiles!.creatable(), create: (input: any) => localProfiles!.create(input), rename: (id: string, name: string) => localProfiles!.rename(id, name),
+ recolor: (id: string, color: string | null) => localProfiles!.recolor(id, color), remove: (id: string) => localProfiles!.remove(id), cancel: () => localProfiles!.cancel() } as never,
});
win.webContents.on("did-navigate", () => railHandlers?.changed());
await railRef.loadURL(`${localOrigin}/rail`);
@@ -623,13 +683,40 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
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,
+ rail: railRef, railList, clean, lending, running: () => running, registry, trashDir,
+ get profiles() { return localProfiles; },
+ railCovers: () => railCovers,
+ async setSize(width: number, height: number) {
+ Object.assign(size, { width, height });
+ await cdp.request("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 2, mobile: false }, win.sessionId);
+ if (railRef) await cdp.request("Emulation.setDeviceMetricsOverride", { width: railCovers ? width : 36, height, deviceScaleFactor: 2, mobile: false }, railRef.sessionId);
+ },
+ async theme(dark: boolean) {
+ for (const tab of [win, railRef].filter(Boolean) as TabWindow[]) {
+ await cdp.request("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: dark ? "dark" : "light" }] }, tab.sessionId);
+ // The app follows the OS's look once its skin is System; a page reads that choice as it loads.
+ if (await tab.evaluate("localStorage.getItem('omb-skin') === 'system'").catch(() => true)) continue;
+ await tab.evaluate("localStorage.setItem('omb-skin', 'system')").catch(() => {});
+ await cdp.request("Page.reload", {}, tab.sessionId).catch(() => {});
+ }
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ },
+ async restartApp() {
+ homeRef!.close();
+ // A quit stops this computer's server as main's before-quit does, and the next launch starts it on the data folder.
+ await fx.relaunch({ kill: false });
+ running = fx.desktopDataDir;
+ home = launchHome();
+ localProfiles = makeLocal();
+ await home.show();
+ if (railRef) await railRef.loadURL(`${localOrigin}/rail`);
+ },
+ cloudOrigin, localOrigin, teamOrigin, otherOrigin, window: win, get home() { return homeRef!; }, account, network, admin, cloudRequests, notifications, hostCache,
get moved() { return moves.moved; },
set moved(value: boolean) { moves.moved = value; },
places: homePlaces, environments: () => envState,
- menu: () => environments.workspaceMenuTemplate(envState, { onSwitch() {}, onConnect() {}, onForget() {}, homeOrigin: home.cloudOrigin() }),
- async sync() { homePlaces.sync(account.state); await home.changed(); },
+ menu: () => environments.workspaceMenuTemplate(envState, { onSwitch() {}, onConnect() {}, onForget() {}, homeOrigin: homeRef!.cloudOrigin() }),
+ async sync() { homePlaces.sync(account.state); await homeRef!.changed(); },
get splash() { return world.splash; },
async launch() {
const splashTab = await TabWindow.open(cdp);
@@ -640,7 +727,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
startup = createStartupScreen({ BrowserWindow: SplashWindow as never, iconPath: SPLASH_ICON, platform: "darwin", isQuitting: () => false, onQuit: () => {}, onFinished: () => { startup = null; } });
await startup.ready;
startup.attach(win as never, { maximized: false });
- await home.show();
+ await homeRef!.show();
},
openLink: (link) => linkContext.queueChatLink(link),
async cloudCookies() { return (await cdp.request("Network.getCookies", { urls: [cloudOrigin] }, win.sessionId)).cookies; },
diff --git a/scripts/testing/png.ts b/scripts/testing/png.ts
index 2cae62495d..80d5698e56 100644
--- a/scripts/testing/png.ts
+++ b/scripts/testing/png.ts
@@ -8,6 +8,8 @@ export interface DecodedPng {
height: number;
/** RGB at (x, y); alpha is dropped. */
pixel: (x: number, y: number) => [number, number, number];
+ /** How opaque (x, y) is, 0 to 255: 255 for a picture without alpha. */
+ alpha: (x: number, y: number) => number;
}
export function decodePng(file: Buffer): DecodedPng {
@@ -59,6 +61,7 @@ export function decodePng(file: Buffer): DecodedPng {
const at = y * stride + x * channels;
return [pixels[at], pixels[at + 1], pixels[at + 2]];
},
+ alpha: (x, y) => (channels === 4 ? pixels[y * stride + x * channels + 3]! : 255),
};
}
diff --git a/scripts/testing/rail-profile-ui.e2e.test.ts b/scripts/testing/rail-profile-ui.e2e.test.ts
index 1320831ea0..3b2ca02501 100644
--- a/scripts/testing/rail-profile-ui.e2e.test.ts
+++ b/scripts/testing/rail-profile-ui.e2e.test.ts
@@ -1,13 +1,18 @@
-// 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.
+// This computer's own workspaces on the rail: main's own handlers in a real headless Chrome (testing/one-workspace-fixture.ts
+// with `profiles`), this computer's real server swapped between their folders at one address, the rail's own page in a tab of
+// its own, and, once My Cloud is home, this computer really lent to My Cloud all along. Every path a person can take is walked
+// through the real pages: + and its naming step (Back, Close, Escape, an empty or taken name), switching in every order (a
+// turn under way, two quick clicks), a workspace's menu (Rename, Colour, Remove asked first, the open one, the last one), an
+// app restart, the rail past eight, the cloud badge in both looks, and a person with no Cloud, whose rail appears with a second
+// place. Each picture is the window as the person sees it: the rail's own page over or 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 { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
-import { cleanWorkspaceConfig, profileDir } from "../../electron/clean-workspace.mjs";
+import { cleanWorkspaceConfig, profileDir, profilesDir } from "../../electron/clean-workspace.mjs";
+import { parseCloudList } from "../../electron/cloud-list.mjs";
import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";
import { hostTimeout } from "../../server/testing/host-timeout.ts";
import { freePortBlock } from "../../server/testing/ports.ts";
@@ -17,53 +22,90 @@ import { launchHomeWorld, shotsDir, welcomed, type HomeWorld } from "./one-works
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");
+if (!enabled) console.info("skipping the rail workspaces 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;
+const WIDTH = 1280, HEIGHT = 800;
-(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;
+/** One world's helpers: waiting, both pages, the rail's tiles and the window's picture. */
+function harness(get: () => { world: HomeWorld; shots: string }) {
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 get().world.window.screenshot(join(get().shots, `failure-${Date.now()}.png`)).catch(() => {});
+ throw new Error(`timed out waiting for ${what}: ${JSON.stringify(value)} at ${get().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 page = <T>(expression: string) => get().world.window.evaluate<T>(expression);
+ const rail = <T>(expression: string) => get().world.rail!.evaluate<T>(expression);
+ const tiles = () => rail<Array<{ id: string; label: string; current: boolean; cloud: boolean; local: boolean }>>(
+ "[...document.querySelectorAll('[data-rail-place]')].map((tile) => ({ id: tile.dataset.railPlace, label: tile.getAttribute('aria-label'), current: tile.getAttribute('aria-current') === 'page', cloud: Boolean(tile.querySelector('[data-rail-cloud]')), local: Boolean(tile.querySelector('[data-rail-local]')) }))");
+ const onLocal = () => /^https?:/.test(get().world.window.url) && new URL(get().world.window.url).origin === get().world.localOrigin;
+ /** The window as the person sees it: the rail at its left edge beside the page, or, while a sheet of the rail's is open,
+ * the rail's see-through view over the whole window. */
const picture = async (name: string) => {
+ const { world, shots } = get();
+ await new Promise((resolve) => setTimeout(resolve, 400));
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 over = decodePng(readFileSync(join(shots, `${name}-rail.png`))), under = decodePng(readFileSync(join(shots, `${name}-page.png`)));
+ const covers = world.railCovers(), width = covers ? under.width : over.width + under.width, height = Math.max(over.height, under.height);
+ writeFileSync(join(shots, `${name}.png`), encodePng(width, height, (x, y) => {
+ const base = covers ? (y < under.height ? under.pixel(x, y) : [255, 255, 255] as [number, number, number])
+ : x < over.width ? [255, 255, 255] as [number, number, number] : y < under.height ? under.pixel(x - over.width, y) : [255, 255, 255] as [number, number, number];
+ if (x >= over.width || y >= over.height) return base;
+ const top = over.pixel(x, y), alpha = over.alpha(x, y) / 255;
+ return [0, 1, 2].map((at) => Math.round(top[at]! * alpha + base[at]! * (1 - alpha))) as [number, number, number];
+ }));
+ for (const part of ["rail", "page"]) rmSync(join(shots, `${name}-${part}.png`), { force: true });
};
- const watchLink = async () => {
- watching = true;
- while (watching) { linkSeen.push(lent()); await new Promise((resolve) => setTimeout(resolve, 50)); }
+ /** A click on the rail's page, once React has drawn what is clicked. */
+ const click = (selector: string) => until(() => rail<boolean>(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return false; el.click(); return true; })()`),
+ Boolean, 10_000, selector);
+ /** A right-click on a tile, then its menu as React drew it. */
+ const menu = async (id: string) => {
+ await rail(`document.querySelector('[data-rail-place="${id}"]').dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }))`);
+ await until(() => rail<boolean>(`Boolean(document.querySelector('[data-rail-menu="${id}"]'))`), Boolean, 10_000, `${id}'s menu`);
};
+ /** Typing as a person does into a field of the rail's page (React's own value setter, then its input event). */
+ const fill = (selector: string, value: string) => rail(`(() => { const input = document.querySelector(${JSON.stringify(selector)});
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(input, ${JSON.stringify(value)}); input.dispatchEvent(new Event("input", { bubbles: true })); return true; })()`);
+ const key = (target: "rail" | "page", name: string) => (target === "rail" ? rail : page)(`(document.activeElement ?? document.body).dispatchEvent(new KeyboardEvent("keydown", { key: ${JSON.stringify(name)}, bubbles: true })), window.dispatchEvent(new KeyboardEvent("keydown", { key: ${JSON.stringify(name)}, bubbles: true }))`);
+ const bots = () => page<string[]>("fetch('/api/bots?messages=0').then((response) => response.json()).then((body) => body.bots.map((bot) => bot.name))");
+ return { until, page, rail, tiles, onLocal, picture, click, menu, fill, key, bots };
+}
+
+(enabled ? describe : describe.skip)("workspaces of this computer's own on the rail, once My Cloud is home", () => {
+ let fx: CloudSendFixture;
+ let world: HomeWorld;
+ let shots = "";
+ let cloudEntry = "";
+ const gate = join(mkdtempSync(join(tmpdir(), "omb-rail-gate-")), "finish");
+ writeFileSync(gate, "");
+ const h = harness(() => ({ world, shots }));
+ const { until, page, rail, tiles, onLocal, picture, click, menu, fill, key, bots } = h;
+ /** Every look at the lent link and at the server's folder while the window switched. */
+ const linkSeen: boolean[] = [];
+ const foldersSeen = new Set<string>();
+ let watching = false, watcher: Promise<void> = Promise.resolve();
+ 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 lentCount = async () => ((await fx.onCloud("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean }) => computer.online !== false).length;
+ const current = async () => (await tiles()).find((tile) => tile.current)?.id ?? null;
+ const shown = (id: string, text?: string) => until(async () => ({ current: await current(), local: onLocal(), body: await page<string>("document.body.innerText") }),
+ (seen) => seen.current === id && (id === cloudEntry ? !seen.local : seen.local) && (!text || seen.body.includes(text)), 90_000, `${id} on screen${text ? ` with ${text}` : ""}`);
+ const lineOf = () => page<string | null>("document.querySelector('[data-home-line]')?.textContent ?? null");
+ const workId = () => world.registry!.list().find((entry) => entry.name === "Work")?.id ?? "work";
beforeAll(async () => {
- fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-profile-${randomBytes(12).toString("hex")}` });
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-profile-${randomBytes(12).toString("hex")}`,
+ desktopEngine: `process.env.FAKE_CLAUDE_MODE = "slow"; process.env.FAKE_CLAUDE_SLOW_FINISH_GATE = ${JSON.stringify(gate)};` });
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"]) {
@@ -75,87 +117,331 @@ const WIDTH = 1280, HEIGHT = 800, SCALE = 2;
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);
+ await world.setSize(WIDTH, HEIGHT);
+ // The session lists My Cloud as the person's own, as the Admin does: so its circle is a rail even alone, for +.
+ // The Admin lists https addresses only; this one's is the fixture's own edge.
+ world.account.state = { ...world.account.state, clouds: parseCloudList([{ id: "c-home", name: "My Cloud", color: null, role: "owner", tier: "pro", runsOn: "cloud",
+ status: "ready", origin: "https://omb-u-fixture.fly.dev", teamId: null, primary: true }])!.map((cloud) => ({ ...cloud, origin: world.cloudOrigin })) };
// 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));
+ afterAll(async () => { watching = false; await watcher; 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 () => {
+ it("My Cloud opens by default: This Mac beside it, a small cloud on My Cloud's tile only, in the light look and the dark; this computer 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");
+ await until(lentCount, (count) => count === 1, 30_000, "My Cloud to see this computer");
+ watching = true;
+ watcher = (async () => { while (watching) { linkSeen.push(lent()); foldersSeen.add(world.running()); await new Promise((resolve) => setTimeout(resolve, 50)); } })();
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 },
+ const found = await until(() => tiles(), (seen) => seen.length === 2, 60_000, "the rail's two tiles");
+ expect(found).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, cloud: false, local: false },
+ { id: cloudEntry, label: expect.stringMatching(/, Cloud$/), current: true, cloud: true, local: false },
]);
- 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");
+ const ring = await rail<{ badge: number; ring: string; tile: number }>(`(() => { const badge = document.querySelector('[data-rail-cloud]'); const tile = badge.parentElement;
+ return { badge: badge.getBoundingClientRect().width, ring: getComputedStyle(badge).borderTopColor, tile: tile.getBoundingClientRect().width }; })()`);
+ expect(ring.badge, "a small circle at the tile's corner").toBeGreaterThanOrEqual(13);
+ expect(ring.badge).toBeLessThan(ring.tile);
+ await world.theme(false);
+ await onCloud();
+ const lightRing = await until(() => rail<string>("getComputedStyle(document.querySelector('[data-rail-cloud]')).borderTopColor"), Boolean, 15_000, "the badge in the light look");
+ await picture("01-rail-cloud-badge-light");
+ await world.theme(true);
+ await until(() => rail<string>("getComputedStyle(document.querySelector('[data-rail-cloud]')).borderTopColor"), (color) => color !== lightRing, 15_000, "the badge's ring in the dark look");
+ await picture("01-rail-cloud-badge-dark");
+ await world.theme(false);
}, 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("/");
+ it("This Mac opens fresh; the frozen copy stays frozen; My Cloud and back keeps This Mac running and as it was left", async () => {
+ await click(MAC);
+ await until(lineOf, (text) => Boolean(text?.startsWith("This Mac starts fresh")), 90_000, "This Mac's page");
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");
+ expect((await bots()).filter((name) => ["Atlas", "Juno"].includes(name)), "none of the Cloud's bots, nor the frozen copy's").toEqual([]);
+ expect(await page<string>("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Scout' }) }).then((response) => response.status)")).toBe(201);
+ await picture("02-this-mac-fresh");
+ await click(`[data-rail-place="${cloudEntry}"]`);
+ await onCloud();
+ expect(world.clean!.profile(), "This Mac's place still runs").toBe("default");
+ await click(MAC);
+ await shown("profile:default", "Scout");
+ }, hostTimeout(240_000));
+
+ it("+: the choices with New workspace first; Escape, Close and Back each leave cleanly; an empty name can't be made and a taken one says so", async () => {
+ const choose = () => until(async () => world.railCovers() && await rail<boolean>("Boolean(document.querySelector('[data-place-add=\"choose\"]'))"), Boolean, 15_000, "+'s choices over the window");
+ await click("[data-rail-add]");
+ await choose();
+ expect(await rail<string[]>("[...document.querySelectorAll('[data-place-add-choice]')].map((choice) => choice.dataset.placeAddChoice)")).toEqual(["local", "server"]);
+ expect(await rail<string>("document.querySelector('[data-place-add-choice=\"local\"]').textContent")).toContain("New workspace on this computer");
+ await picture("03-plus-choices-light");
+ await world.theme(true);
+ await picture("03-plus-choices-dark");
+ await world.theme(false);
+ await key("rail", "Escape");
+ await until(async () => !world.railCovers() && !(await rail("Boolean(document.querySelector('[data-place-add-sheet]'))")), Boolean, 10_000, "Escape closing the sheet");
+ await click("[data-rail-add]");
+ await choose();
+ await click('[data-place-add-choice="local"]');
+ await until(() => rail("Boolean(document.querySelector('[data-place-add=\"local\"]'))"), Boolean, 10_000, "the naming step");
+ await rail("[...document.querySelectorAll('[data-place-add=\"local\"] button')].find((button) => button.textContent === 'Back').click()");
+ await choose();
+ await click('[data-place-add-sheet] [aria-label="Close"]');
+ await until(async () => !world.railCovers(), Boolean, 10_000, "Close closing the sheet");
+ expect(world.registry!.list().map((entry) => entry.id), "nothing made").toEqual(["default"]);
+ }, hostTimeout(120_000));
+
+ it("+ → New workspace → Work, in a colour: it opens fresh, This Mac keeps its data, and the window and the line call it Work", async () => {
+ await click("[data-rail-add]");
+ await until(() => rail("Boolean(document.querySelector('[data-place-add-choice=\"local\"]'))"), Boolean, 15_000, "+'s choices");
+ await click('[data-place-add-choice="local"]');
+ await until(() => rail("Boolean(document.querySelector('[data-place-add=\"local\"]'))"), Boolean, 15_000, "the naming step");
+ expect(await rail<string>("document.querySelector('[data-local-name]').value"), "the first name no place here has").toBe("Work");
+ await fill("[data-local-name]", " ");
+ expect(await rail<boolean>("document.querySelector('[data-local-create]').disabled"), "no name: nothing to make").toBe(true);
+ await fill("[data-local-name]", "this mac");
+ await click("[data-local-create]");
+ await until(() => rail<string | null>("document.querySelector('[data-local-problem]')?.textContent ?? null"), (text) => text === "Another place here has that name. Choose another.", 10_000, "the taken name said");
+ await picture("04-plus-name-taken");
+ await fill("[data-local-name]", "Work");
+ await click('[data-place-add="local"] [data-swatch="rose"]');
+ await picture("04-plus-name-work");
+ await click("[data-local-create]");
+ await until(async () => !world.railCovers(), Boolean, 15_000, "the sheet closing once made");
+ await shown(`profile:${workId()}`);
+ await until(lineOf, (text) => text === "Work starts fresh: a separate place on this computer, with its own bots, chats and files.", 30_000, "Work's line");
+ await until(() => page<string | null>("document.querySelector('[data-window-place]')?.textContent ?? null"), (name) => name === "Work", 15_000, "the top bar naming Work");
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, workId()));
+ expect(await bots(), "fresh: no Scout").not.toContain("Scout");
+ const work = (await tiles()).find((tile) => tile.id === `profile:${workId()}`)!;
+ expect([work.local, work.cloud, work.label]).toEqual([true, false, "Work: a separate place on this computer, with its own bots"]);
+ expect(world.registry!.get(workId())?.color).toBe("rose");
+ await picture("05-work-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()`);
+ it("This Mac ↔ Work ↔ My Cloud in every order: each shows what was left there, the frozen copy never runs, the link never drops", async () => {
+ const work = `profile:${workId()}`;
+ foldersSeen.clear();
+ const steps: Array<[string, string]> = [["profile:default", "Scout"], [cloudEntry, "Atlas"], [work, ""], [cloudEntry, "Atlas"], ["profile:default", "Scout"], [work, ""], ["profile:default", "Scout"]];
+ for (const [id, text] of steps) {
+ await click(`[data-rail-place="${id}"]`);
+ await shown(id, text || undefined);
+ if (id === work) expect(await bots()).not.toContain("Scout");
+ }
+ expect(foldersSeen.has(fx.desktopDataDir), "switching between workspaces never starts the frozen copy's server").toBe(false);
+ expect(JSON.parse(readFileSync(join(fx.desktopDataDir, "moved.json"), "utf8")).cloud).toBe(world.cloudOrigin);
+ expect(linkSeen.every(Boolean), "this computer stayed lent to My Cloud throughout").toBe(true);
+ expect(await lentCount(), "one lent computer, whichever workspace is open").toBe(1);
+ }, hostTimeout(400_000));
+
+ it("a switch while a turn runs: the circle says it opens once the bot finishes, the turn finishes there, and its reply is there on return", async () => {
+ await click(`[data-rail-place="profile:${workId()}"]`);
+ await shown(`profile:${workId()}`);
+ if (!(await bots()).length) await page("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Chief', modelSelection: { instanceId: 'claude', model: 'claude-sonnet-5' } }) })");
+ await world.window.loadURL(`${world.localOrigin}/`);
+ const composer = "textarea[aria-label^=\"Message\"]";
+ await until(() => page<boolean>(`Boolean(document.querySelector('${composer}'))`), Boolean, 60_000, "Work's composer");
+ rmSync(gate, { force: true });
+ await page(`document.querySelector('${composer}').focus()`);
+ await world.window.cdp.request("Input.insertText", { text: "Sort the quarterly notes" }, world.window.sessionId);
+ for (const type of ["keyDown", "keyUp"]) await world.window.cdp.request("Input.dispatchKeyEvent", { type, key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }, world.window.sessionId);
+ const busy = await until(async () => (await fetch(`${fx.desktopBase}/api/move/freeze`, { headers: { "x-openmausbot-desktop-owner": fx.ownerCapability } }).then((response) => response.json())).busy as string | undefined,
+ (name) => typeof name === "string" && name.length > 0, 30_000, "the turn under way");
+ await click(MAC);
+ await until(() => tiles(), (seen) => seen.find((tile) => tile.id === "profile:default")?.label === `This Mac opens once ${busy} finishes`, 15_000, "This Mac's circle saying it waits");
+ expect(world.running(), "Work still runs while its bot answers").toBe(profileDir(fx.desktopDataDir, workId()));
+ await picture("06-switch-waits-for-turn");
+ writeFileSync(gate, "");
+ await shown("profile:default", "Scout");
+ await click(`[data-rail-place="profile:${workId()}"]`);
+ await shown(`profile:${workId()}`);
+ await until(() => page<string>("document.body.innerText"), (text) => text.includes("reply to:") && text.includes("Sort the quarterly notes"), 30_000, "the reply, there on return");
+ expect(await page<string>("document.body.innerText"), "it finished: never cut short").not.toContain("turn interrupted");
+ }, hostTimeout(240_000));
+
+ it("two quick clicks on two tiles: only the last opens, and the rail and the window agree", async () => {
+ await rail(`document.querySelector('${MAC}').click(); document.querySelector('[data-rail-place="${cloudEntry}"]').click(); document.querySelector('[data-rail-place="profile:${workId()}"]').click();`);
+ await shown(`profile:${workId()}`);
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ expect(await current(), JSON.stringify({ list: world.railList(), profile: world.home.profile(), active: world.environments().activeId, url: world.window.url, running: world.running() })).toBe(`profile:${workId()}`);
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, workId()));
+ await rail(`document.querySelector('[data-rail-place="profile:${workId()}"]').click(); document.querySelector('${MAC}').click();`);
+ await shown("profile:default", "Scout");
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ expect([await current(), world.running()]).toEqual(["profile:default", profileDir(fx.desktopDataDir, "default")]);
+ }, hostTimeout(240_000));
+
+ it("a workspace's menu: Rename, its colour, and Remove asked first; Cancel changes nothing; removing the open one goes to My Cloud first", async () => {
+ const id = workId(), tile = `profile:${id}`;
+ await menu(tile);
+ await until(() => rail("Boolean(document.querySelector('[data-rail-menu]'))"), Boolean, 10_000, "Work's menu");
+ await picture("07-menu");
+ await click("[data-rail-rename]");
+ await fill("[data-rail-rename-form] input", "Office");
+ await rail("document.querySelector('[data-rail-rename-form]').requestSubmit()");
+ await until(() => tiles(), (seen) => seen.find((entry) => entry.id === tile)?.label === "Office: a separate place on this computer, with its own bots", 10_000, "the tile renamed");
+ await menu(tile);
+ await click('[data-rail-local-color] [data-swatch="violet"]');
+ await until(async () => world.registry!.get(id)?.color, (color) => color === "violet", 10_000, "the colour saved");
+ await menu(tile);
+ await click("[data-rail-remove-ask]");
+ await until(() => rail<boolean>("Boolean(document.querySelector('[data-rail-menu] [role=\"alertdialog\"]'))"), Boolean, 10_000, "Remove asking");
+ expect(await rail<string>("document.querySelector('[data-rail-menu] [role=\"alertdialog\"] p').textContent"))
+ .toBe("Remove “Office”? Its bots, chats and files on this computer are deleted. Its folder goes to the Trash first.");
+ await picture("08-remove-asks");
+ await click("[data-rail-remove-cancel]");
+ await key("rail", "Escape");
+ expect(world.registry!.get(id), "Cancel: nothing removed").not.toBeNull();
+ await click(`[data-rail-place="${tile}"]`);
+ await shown(tile);
+ await page("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Ledger' }) })");
+ await menu(tile);
+ await click("[data-rail-remove-ask]");
+ await click("[data-rail-remove-confirm]");
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"));
+ await until(() => tiles(), (seen) => !seen.some((entry) => entry.id === tile), 30_000, "Office gone from the rail");
+ expect(world.running(), "its server stopped before its folder went").not.toBe(profileDir(fx.desktopDataDir, id));
+ expect(existsSync(profileDir(fx.desktopDataDir, id))).toBe(false);
+ const trashed = readdirSync(world.trashDir).find((name) => name.endsWith(`-${id}`))!;
+ expect(readFileSync(join(world.trashDir, trashed, "bots.json"), "utf8"), "its bots are in the Trash, not gone").toContain("Ledger");
+ await picture("09-removed-open-one");
+ }, hostTimeout(240_000));
+
+ it("an app restart while a workspace is open: My Cloud opens, the frozen copy's server is back without a workspace stranded, and the workspace opens again as it was", async () => {
+ await click("[data-rail-add]");
+ await until(() => rail("Boolean(document.querySelector('[data-place-add-choice=\"local\"]'))"), Boolean, 15_000, "+'s choices");
+ await click('[data-place-add-choice="local"]');
+ await until(() => rail("Boolean(document.querySelector('[data-local-name]'))"), Boolean, 15_000);
+ await fill("[data-local-name]", "Personal");
+ await click("[data-local-create]");
+ const personal = world.registry!.list().find((entry) => entry.name === "Personal")!.id;
+ await shown(`profile:${personal}`);
+ await page("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Diary' }) })");
+ await world.restartApp();
+ await onCloud();
+ expect(world.running(), "a launch starts the data folder's server, as ever").toBe(fx.desktopDataDir);
+ expect(world.clean!.active()).toBe(false);
+ const after = await until(() => tiles(), (seen) => seen.length === 3, 30_000, "the rail after the restart");
+ expect(after.map((tile) => [tile.id, tile.current])).toEqual([["profile:default", false], [`profile:${personal}`, false], [cloudEntry, true]]);
+ await picture("10-after-restart");
+ await click(`[data-rail-place="profile:${personal}"]`);
+ await shown(`profile:${personal}`, "Diary");
+ await until(async () => lent(), Boolean, 30_000, "this computer lent again after the restart");
+ }, hostTimeout(240_000));
+
+ it("past eight tiles: ⋯ lists every place, a row opens its place and its right-click opens its menu", async () => {
+ for (const name of ["Lab", "Studio", "Garden", "Kitchen", "Travel", "Music"]) expect(world.profiles!.create({ name }).outcome).toBe("made");
+ await until(() => tiles(), (seen) => seen.length === 8, 30_000, "eight tiles");
+ expect(await rail<boolean>("Boolean(document.querySelector('[data-rail-more-button]'))")).toBe(true);
+ await click("[data-rail-more-button]");
+ await until(() => rail<number>("document.querySelectorAll('[data-rail-more] li').length"), (count) => count === world.railList().length && count > 8, 10_000, "every place in the list");
+ await picture("11-past-eight");
+ await rail("[...document.querySelectorAll('[data-rail-more] li button')].find((row) => row.textContent.includes('Music')).dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))");
+ await until(() => rail("Boolean(document.querySelector('[data-rail-menu] [data-rail-rename]'))"), Boolean, 10_000, "Music's menu from its row");
+ await key("rail", "Escape");
+ await click("[data-rail-more-button]");
+ await rail("[...document.querySelectorAll('[data-rail-more] li button')].find((row) => row.textContent.includes('Music')).click()");
+ const music = world.registry!.list().find((entry) => entry.name === "Music")!.id;
+ await shown(`profile:${music}`);
+ expect((await tiles()).some((tile) => tile.id === `profile:${music}`), "the place on screen is always among the tiles").toBe(true);
+ }, hostTimeout(240_000));
+
+ it("removing the last workspace of this computer's own lands on My Cloud, whose + still offers a new one", async () => {
+ for (const entry of world.registry!.list()) {
+ const on = await current();
+ if (on === `profile:${entry.id}`) {
+ await menu(`profile:${entry.id}`);
+ await click("[data-rail-remove-ask]");
+ await click("[data-rail-remove-confirm]");
+ await onCloud();
+ } else expect(await world.profiles!.remove(entry.id)).toEqual({ outcome: "removed" });
+ }
+ await until(() => tiles(), (seen) => seen.length === 1 && seen[0]!.id === cloudEntry, 30_000, "My Cloud alone on the rail");
+ expect(world.running()).toBe(fx.desktopDataDir);
+ expect(readdirSync(profilesDir(fx.desktopDataDir)).filter((name) => !name.startsWith(".") && name !== "profiles.json")).toEqual([]);
+ await click("[data-rail-add]");
+ await until(() => rail("Boolean(document.querySelector('[data-place-add-choice=\"local\"]'))"), Boolean, 15_000, "+'s choices");
+ await click('[data-place-add-choice="local"]');
+ await until(() => rail("Boolean(document.querySelector('[data-local-name]'))"), Boolean, 15_000, "+ still offering a new workspace");
+ expect(await rail<string>("document.querySelector('[data-local-name]').value"), "This Mac's name is free again").toBe("Work");
+ await key("rail", "Escape");
+ await picture("12-last-removed");
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");
+ expect(linkSeen.length).toBeGreaterThan(100);
+ expect(linkSeen.every(Boolean), "the lent link never dropped, from the first switch to the last removal").toBe(true);
+ expect(JSON.parse(readFileSync(join(fx.desktopDataDir, "moved.json"), "utf8")).cloud, "never unfrozen: its routines never ran beside a workspace's").toBe(world.cloudOrigin);
}, hostTimeout(180_000));
});
+
+(enabled ? describe : describe.skip)("a person with no Cloud: a new workspace from the Server menu, and the rail once there are two places", () => {
+ let fx: CloudSendFixture;
+ let world: HomeWorld;
+ let shots = "";
+ const { until, page, tiles, onLocal, picture, click, menu, key, bots } = harness(() => ({ world, shots }));
+
+ beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-local-${randomBytes(12).toString("hex")}` });
+ await welcomed(fx);
+ await fx.local("POST", "/api/bots", { name: "Atlas", 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.setSize(WIDTH, HEIGHT);
+ world.moved = false;
+ world.account.state = { status: "signed-out" } as never;
+ await world.window.loadURL(`${world.localOrigin}/`).catch(() => {});
+ await new Promise((resolve) => setTimeout(resolve, 8_000));
+ }, hostTimeout(300_000));
+ afterAll(async () => { await world?.close(); await fx?.close(); }, hostTimeout(60_000));
+
+ it("one place, no rail; the Server menu's New workspace asks a name on this computer's page, Escape leaves, Create makes it and the rail appears", async () => {
+ await world.home.show();
+ await until(async () => onLocal() && (await bots()).includes("Atlas"), Boolean, 60_000, "This computer's page");
+ expect(world.railList()).toEqual([]);
+ await world.rail!.loadURL(`${world.localOrigin}/rail`);
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ expect(await tiles()).toEqual([]);
+ world.window.webContents.send("workspaces:new-local");
+ await until(() => page("Boolean(document.querySelector('[data-place-add=\"local\"]'))"), Boolean, 15_000, "the naming step on this computer's page");
+ await picture("L1-server-menu-name-step");
+ await key("page", "Escape");
+ await until(() => page("!document.querySelector('[data-place-add-sheet]')"), Boolean, 10_000, "Escape closing it");
+ expect(world.registry!.list().filter((entry) => entry.name)).toEqual([]);
+ world.window.webContents.send("workspaces:new-local");
+ await until(() => page("Boolean(document.querySelector('[data-local-create]'))"), Boolean, 15_000);
+ await page("document.querySelector('[data-local-create]').click()");
+ await until(() => tiles(), (seen) => seen.map((tile) => [tile.id, tile.current]).join() === "local,false,profile:work,true", 90_000, "This computer and Work on the rail, Work on screen");
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, "work"));
+ expect(await bots()).not.toContain("Atlas");
+ await until(() => page<string | null>("document.querySelector('[data-home-line]')?.textContent ?? null"), (text) => Boolean(text?.startsWith("Work starts fresh")), 30_000, "Work's line");
+ await picture("L2-rail-appears");
+ }, hostTimeout(240_000));
+
+ it("This computer and Work both ways, each as it was; removing the open one goes back to This computer and the rail goes with it", async () => {
+ await click('[data-rail-place="local"]');
+ await until(async () => (await bots()).includes("Atlas") && world.running() === fx.desktopDataDir, Boolean, 90_000, "This computer again");
+ expect((await tiles()).find((tile) => tile.current)?.id).toBe("local");
+ await click('[data-rail-place="profile:work"]');
+ await until(async () => world.running() === profileDir(fx.desktopDataDir, "work") && !(await bots()).includes("Atlas"), Boolean, 90_000, "Work again");
+ await menu("profile:work");
+ await click("[data-rail-remove-ask]");
+ await click("[data-rail-remove-confirm]");
+ await until(async () => onLocal() && world.running() === fx.desktopDataDir && (await bots()).includes("Atlas"), Boolean, 90_000, "This computer after the removal");
+ await until(() => tiles(), (seen) => seen.length === 0, 30_000, "one place again: no rail");
+ expect(world.railList()).toEqual([]);
+ await picture("L3-back-to-one-place");
+ }, hostTimeout(240_000));
+});
diff --git a/src/App.tsx b/src/App.tsx
index 4c1fef2d46..1ea27e47b1 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -39,6 +39,7 @@ import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";
import { inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";
import { InboxPanel } from "@/components/inbox/InboxPanel";
import { PlacesRail } from "@/components/PlacesRail";
+import { NewLocalFromMenu } from "@/components/PlaceAddSheet";
import { CloudHowTo } from "@/components/CloudHowTo";
import { DesktopCapabilitiesProvider, useCaptionChrome, useDesktopCapabilities, WindowDragStrip, windowFramed } from "@/components/DesktopCapabilities";
import { WindowCaptionButtons } from "@/components/WindowCaptionButtons";
@@ -339,6 +340,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
/>
)}
{!calendarFocus && <PlacesRail />}
+ <NewLocalFromMenu />
{/* A framed window shows the app, its sidebar and the chat or page, as one square pane under the top bar and beside
the window's rail, running to the window's right and bottom edges. */}
<div data-window-card={framed ? "" : undefined}
diff --git a/src/components/DesktopWorkspaceSwitcher.tsx b/src/components/DesktopWorkspaceSwitcher.tsx
index 136e93f0b8..49cb1ba86f 100644
--- a/src/components/DesktopWorkspaceSwitcher.tsx
+++ b/src/components/DesktopWorkspaceSwitcher.tsx
@@ -55,7 +55,7 @@ export type WorkspacePlace = ReturnType<typeof useWorkspacePlace>;
*/
export function useWorkspacePlace({ cloudHome = false, howTo = false, onMenuClosed }: { cloudHome?: boolean; howTo?: boolean; onMenuClosed?: () => void }) {
const bridge = window.ogb?.workspaces;
- const [current, setCurrent] = useState<{ local: boolean; name: string; localPath?: string; origin?: string; color?: string; home?: boolean } | null>(null);
+ const [current, setCurrent] = useState<{ local: boolean; name: string; localPath?: string; origin?: string; color?: string; home?: boolean; profileName?: string } | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
@@ -117,7 +117,7 @@ function Switcher({ compact = false, inline = false, pill = false, rail = false,
</div>
</div>;
}
- const name = (current?.local && !current.localPath ? t("place.local") : current?.name) ?? (cloudHome ? cloudName : t("sidebar.servers"));
+ const name = current?.profileName ?? (current?.local && !current.localPath ? t("place.local") : current?.name) ?? (cloudHome ? cloudName : t("sidebar.servers"));
const Icon = current?.local === false || (cloudHome && !current) ? Cloud : Laptop;
const shown = cloudHome ? withPower(name) : name;
const title = current?.origin ? `${shown} · ${current.origin}` : shown;
diff --git a/src/components/HomeLine.test.ts b/src/components/HomeLine.test.ts
index 25b6288941..594a397383 100644
--- a/src/components/HomeLine.test.ts
+++ b/src/components/HomeLine.test.ts
@@ -96,3 +96,7 @@ it("in This Mac's own place, the line says it is separate from My Cloud, where t
setLocale("pt-br");
expect(homeLineText({ kind: "profile" }, "darwin")).toMatch(/^Este Mac começa do zero/);
});
+
+it("in a workspace added from +, the line names it and says it is separate, with its own bots, chats and files", () => {
+ expect(homeLineText({ kind: "profile", name: "Work" }, "darwin")).toBe("Work starts fresh: a separate place on this computer, with its own bots, chats and files.");
+});
diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsx
index 850e33d628..c99a1f281b 100644
--- a/src/components/HomeLine.tsx
+++ b/src/components/HomeLine.tsx
@@ -8,11 +8,11 @@ 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 } | { kind: "profile" };
+type Line = { kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile"; name?: 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. */
+/** 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 (`name`: one added from +, separate from the rest). */
export function homeLineText(line: Line, platform?: string): string {
- if (line.kind === "profile") return t("homeLine.profile", { name: computerName({ profile: "default" }, platform) });
+ if (line.kind === "profile") return line.name ? t("homeLine.local", { name: line.name }) : 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 });
}
diff --git a/src/components/PlaceAddSheet.test.ts b/src/components/PlaceAddSheet.test.ts
new file mode 100644
index 0000000000..2184cb8c2a
--- /dev/null
+++ b/src/components/PlaceAddSheet.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import { suggestedLocalName } from "@/lib/places";
+
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("./cloud-buy/CloudMascotScene", () => ({ CloudMascotScene: () => null }));
+const { NewLocalFromMenu } = await import("./PlaceAddSheet");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root | null = null, ask: (() => void) | null = null;
+const create = vi.fn(async (_name: string, _color: unknown) => ({ outcome: "made" as const, id: "work" }));
+beforeEach(() => {
+ setLocale("en");
+ vi.clearAllMocks();
+ Object.assign(window, { ogb: { workspaces: { places: vi.fn(async () => ({ places: [], add: { cloud: false, link: false, address: false } })), onChanged: () => () => {},
+ local: { create, edit: vi.fn(), remove: vi.fn() }, onNewLocal: (callback: () => void) => { ask = callback; return () => { ask = null; }; } } } });
+ host = document.createElement("div"); document.body.append(host);
+});
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); document.body.innerHTML = ""; });
+
+it("a new workspace's first names: Work, Personal, then Workspace 2, 3 and on, whichever no place has", () => {
+ expect(suggestedLocalName([])).toBe("Work");
+ expect(suggestedLocalName(["work"])).toBe("Personal");
+ expect(suggestedLocalName(["Work", "Personal", "Workspace 2"])).toBe("Workspace 3");
+});
+
+it("the Server menu's New workspace on this computer opens the same step on this computer's own page, where no rail stands yet", async () => {
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement(NewLocalFromMenu)); });
+ expect(document.querySelector("[data-place-add-sheet]")).toBeNull();
+ await act(async () => { ask!(); });
+ const form = document.querySelector('[data-place-add="local"]')!;
+ expect(form.querySelector<HTMLInputElement>("[data-local-name]")!.value).toBe("Work");
+ await act(async () => { (form as HTMLFormElement).requestSubmit(); for (let i = 0; i < 4; i++) await Promise.resolve(); });
+ expect(create.mock.calls).toEqual([["Work", "blue"]]);
+ expect(document.querySelector("[data-place-add-sheet]"), "made: main opens it, and the rail appears with two places").toBeNull();
+ await act(async () => { ask!(); });
+ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(document.querySelector("[data-place-add-sheet]"), "Escape: no dead end").toBeNull();
+});
diff --git a/src/components/PlaceAddSheet.tsx b/src/components/PlaceAddSheet.tsx
index 3f4fcea4a4..8ba0c534c9 100644
--- a/src/components/PlaceAddSheet.tsx
+++ b/src/components/PlaceAddSheet.tsx
@@ -1,15 +1,19 @@
-// + at the end of the rail: one sheet of choices. A new organization on the Team plan the person pays for (when they run
-// one), buy a Cloud (the buying sheet: another Cloud right here, or the first one on this computer's own sheet), or add a
-// server of the person's own by pasting its pairing link.
+// + at the end of the rail: one sheet of choices. A new workspace on this computer (named here, then main opens it), a new
+// organization on the Team plan the person pays for (when they run one), buy a Cloud (the buying sheet: another Cloud right
+// here, or the first one on this computer's own sheet), or add a server of the person's own by pasting its pairing link.
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
-import { Building2, Cloud, Loader2, Server, UserRound, X } from "lucide-react";
-import type { RailAddChoices } from "../../electron/cloud-rail.mjs";
+import { Building2, Cloud, Laptop, Loader2, Server, UserRound, X } from "lucide-react";
+import type { CloudSwatch } from "../../electron/cloud-list.mjs";
+import type { RailAddChoices, RailPlace } from "../../electron/cloud-rail.mjs";
import { track } from "@/lib/analytics";
import { cn } from "@/lib/cn";
+import { CLOUD_LIST_NAME_LIMIT, CLOUD_SWATCH_ORDER, SWATCH_COLOR, swatchFill } from "@/lib/cloud-extra";
import { t } from "@/lib/i18n";
+import { computerName, createLocal, placeInitials, suggestedLocalName } from "@/lib/places";
import { AddCloudFlow } from "./cloud-buy/AddCloudFlow";
import { NewOrganization } from "./cloud-buy/NewOrganization";
-import { BackLink, Heading } from "./cloud-buy/parts";
+import { BackLink, FIELD, Heading, PRIMARY_WIDE } from "./cloud-buy/parts";
+import { SwatchRadios } from "./SwatchRadios";
/** A server's pairing link, pasted here: main checks it and asks "Connect to <host>?" itself, then opens it. The sheet
* stays open when the person cancels, and says so when the link isn't one. `connect`: a server of theirs that signed in
@@ -89,10 +93,73 @@ export function RailSheet({ wide = false, focusKey, onClose, children }: { wide?
</div>;
}
-export function PlaceAddSheet({ choices, connect = null, onClose, onAccount }: { choices: RailAddChoices; connect?: { name: string } | null; onClose: () => void; onAccount?: () => void }) {
- const server = choices.link, organization = choices.organization === true, account = choices.account === true && Boolean(onAccount);
- const several = [organization, choices.cloud, server, account].filter(Boolean).length > 1;
- const [view, setView] = useState<"choose" | "cloud" | "server" | "organization">(connect ? "server" : several ? "choose" : organization ? "organization" : choices.cloud ? "cloud" : "server");
+/** The names and colours already on the rail: a new workspace's first name and colour are ones no place has yet. */
+function placesTaken(places: readonly RailPlace[]): { names: string[]; swatches: Set<CloudSwatch> } {
+ const names = places.map((place) => (place.kind === "computer" ? computerName(place) : place.name));
+ return { names, swatches: new Set(places.map((place) => place.paint?.swatch ?? CLOUD_SWATCH_ORDER.find((swatch) => place.color !== null && SWATCH_COLOR[swatch] === place.color)).filter((swatch): swatch is CloudSwatch => Boolean(swatch))) };
+}
+
+/** A new workspace on this computer: its name (Work, Personal or Workspace 2 to start) and its colour, then main makes it
+ * and opens it. A name another place here has is said at once; main says it too, for one the rail doesn't list. */
+export function NewLocalWorkspace({ places, onBack, onDone }: { places: readonly RailPlace[]; onBack: (() => void) | null; onDone: () => void }) {
+ const [taken] = useState(() => placesTaken(places));
+ const [name, setName] = useState(() => suggestedLocalName(taken.names));
+ const [color, setColor] = useState<CloudSwatch>(() => CLOUD_SWATCH_ORDER.find((swatch) => swatch !== "slate" && !taken.swatches.has(swatch)) ?? "slate");
+ const [busy, setBusy] = useState(false), [problem, setProblem] = useState<"taken" | "failed" | null>(null);
+ const shown = name.trim().replace(/\s+/g, " ");
+ const clash = taken.names.some((other) => other.toLocaleLowerCase() === shown.toLocaleLowerCase());
+ const create = async () => {
+ if (!shown || busy) return;
+ if (clash) { setProblem("taken"); return; }
+ setBusy(true); setProblem(null);
+ const outcome = await createLocal(shown, color === "slate" ? null : color);
+ setBusy(false);
+ if (outcome === "made") { track("rail_add", { step: "local" }); onDone(); return; }
+ setProblem(outcome === "taken" ? "taken" : "failed");
+ };
+ return <form data-place-add="local" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7" onSubmit={(event) => { event.preventDefault(); void create(); }}>
+ {onBack && <div><BackLink label={t("rail.back")} onClick={onBack} /></div>}
+ <Heading title={t("rail.local")} sub={t("rail.localSub")} />
+ <label className="flex flex-col gap-1.5 text-[13px] font-medium text-ink">{t("rail.orgName")}
+ <input data-autofocus data-local-name value={name} maxLength={CLOUD_LIST_NAME_LIMIT} disabled={busy} aria-invalid={problem === "taken" || undefined}
+ onChange={(event) => { setName(event.target.value); setProblem(null); }} onFocus={(event) => event.currentTarget.select()} className={FIELD} />
+ </label>
+ <div className="flex flex-col gap-1.5">
+ <span aria-hidden="true" className="text-[13px] font-medium text-ink">{t("rail.orgColor")}</span>
+ <SwatchRadios value={color} onChange={setColor} label={t("rail.orgColor")} disabled={busy} none />
+ </div>
+ <div className="flex items-center gap-3 rounded-xl border border-hairline/70 bg-card/70 px-4 py-3">
+ <span aria-hidden="true" className={cn("relative grid size-10 shrink-0 place-items-center rounded-[12px] text-[14px] font-semibold", color === "slate" ? "bg-raised text-ink" : "text-white")}
+ style={color === "slate" ? undefined : { background: swatchFill(color) }}>{placeInitials(shown || t("rail.localWork"))}
+ <span className="absolute -bottom-1 -right-1 grid size-4 place-items-center rounded-full border border-hairline bg-panel text-ink-secondary"><Laptop size={9} strokeWidth={2.25} /></span>
+ </span>
+ <span className="min-w-0">
+ <span data-local-preview className="block truncate text-[14px] font-semibold text-ink">{shown || t("rail.localWork")}</span>
+ <span className="block text-[13px] text-ink-secondary">{t("rail.localPreview")}</span>
+ </span>
+ </div>
+ {problem && <p role="alert" data-local-problem className="text-[13px] leading-relaxed text-danger">{t(problem === "taken" ? "rail.localTaken" : "rail.localFailed")}</p>}
+ <button type="submit" data-local-create className={PRIMARY_WIDE} disabled={busy || !shown}>
+ {busy && <Loader2 size={15} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}{t("rail.localCreate")}
+ </button>
+ </form>;
+}
+
+/** The Server menu's New workspace on this computer, where no rail stands beside this computer's own page: the same step
+ * on a sheet of its own. */
+export function NewLocalFromMenu() {
+ const [open, setOpen] = useState(false);
+ useEffect(() => (window.ogb?.remoteClient?.active ? undefined : window.ogb?.workspaces?.onNewLocal?.(() => setOpen(true))), []);
+ if (!open) return null;
+ return <RailSheet focusKey="local" onClose={() => setOpen(false)}>
+ <NewLocalWorkspace places={[]} onBack={null} onDone={() => setOpen(false)} />
+ </RailSheet>;
+}
+
+export function PlaceAddSheet({ choices, places = [], connect = null, onClose, onAccount }: { choices: RailAddChoices; places?: readonly RailPlace[]; connect?: { name: string } | null; onClose: () => void; onAccount?: () => void }) {
+ const server = choices.link, organization = choices.organization === true, account = choices.account === true && Boolean(onAccount), local = choices.local === true;
+ const several = [local, organization, choices.cloud, server, account].filter(Boolean).length > 1;
+ const [view, setView] = useState<"choose" | "local" | "cloud" | "server" | "organization">(connect ? "server" : several ? "choose" : local ? "local" : organization ? "organization" : choices.cloud ? "cloud" : "server");
const [wide, setWide] = useState(false);
const workspaces = window.ogb?.workspaces;
const firstCloud = () => {
@@ -102,7 +169,8 @@ export function PlaceAddSheet({ choices, connect = null, onClose, onAccount }: {
};
return <RailSheet wide={view === "cloud" && wide} focusKey={view} onClose={onClose}>
{view === "choose" && <div data-place-add="choose" className="flex flex-col gap-5 px-[30px] pb-[26px] pt-7">
- <Heading title={t("rail.add")} />
+ <Heading title={t(local ? "rail.addAny" : "rail.add")} />
+ {local && <Choice kind="local" icon={<Laptop size={19} />} title={t("rail.local")} sub={t("rail.localSub")} onClick={() => setView("local")} />}
<div className="flex flex-col gap-3 sm:flex-row">
{organization && <Choice kind="organization" icon={<Building2 size={19} />} title={t("rail.org")} sub={t("rail.orgSub")} onClick={() => setView("organization")} />}
{choices.cloud && <Choice kind="cloud" icon={<Cloud size={19} />} title={t("rail.buy")} sub={t("rail.buySub")} onClick={() => setView("cloud")} />}
@@ -110,6 +178,7 @@ export function PlaceAddSheet({ choices, connect = null, onClose, onAccount }: {
{account && <Choice kind="account" icon={<UserRound size={19} />} title={t("accounts.add")} sub={t("rail.accountSub")} onClick={() => onAccount!()} />}
</div>
</div>}
+ {view === "local" && <NewLocalWorkspace places={places} onBack={several ? () => setView("choose") : null} onDone={onClose} />}
{view === "server" && <OwnServerLink onBack={several && !connect ? () => setView("choose") : null} onConnected={onClose} connect={connect} />}
{view === "cloud" && <AddCloudFlow onClose={onClose} onFirstCloud={firstCloud} onWide={setWide} onBack={several ? () => setView("choose") : null} />}
{view === "organization" && <NewOrganization onClose={onClose} onBack={several ? () => setView("choose") : null} />}
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
index 4749abcc68..cbc5a76944 100644
--- a/src/components/PlacesRail.test.ts
+++ b/src/components/PlacesRail.test.ts
@@ -56,8 +56,8 @@ it("a circle per place, with its initials on its colour; the place on screen is
expect(host.querySelector('[data-rail-place="acme"] [data-rail-dot]')).toBeTruthy();
expect(host.querySelector('[data-rail-place="pending:c-b"] [data-rail-ring]')?.getAttribute("data-rail-ring")).toBe("waiting");
expect(host.querySelector('[data-rail-place="c"] [data-rail-ring]')?.getAttribute("data-rail-ring")).toBe("40");
- expect(host.querySelector('[data-rail-place="c"]')?.getAttribute("aria-label")).toBe("Client C: setting up");
- expect(host.querySelector('[data-rail-place="pending:c-b"]')?.getAttribute("aria-label")).toBe("Client B: waiting for payment");
+ expect(host.querySelector('[data-rail-place="c"]')?.getAttribute("aria-label")).toBe("Client C: setting up, Cloud");
+ expect(host.querySelector('[data-rail-place="pending:c-b"]')?.getAttribute("aria-label")).toBe("Client B: waiting for payment, Cloud");
expect(host.querySelector("[data-rail-more-button]")).toBeNull();
expect(host.querySelector("[data-rail-add]")?.getAttribute("aria-label")).toBe("Add a Cloud or your own server");
});
@@ -78,8 +78,8 @@ it("marks the place on screen with a pill on the rail's edge, a short one on hov
it("a click opens the place through main by its id; the one on screen and one not ready yet open nothing", async () => {
await mount(createElement(PlacesRail));
- await click(host.querySelector('[data-rail-place="a"]'));
await click(host.querySelector('[data-rail-place="home"]'));
+ await click(host.querySelector('[data-rail-place="a"]'));
await click(host.querySelector('[data-rail-place="pending:c-b"]'));
expect(workspaces.open.mock.calls).toEqual([["a"]]);
});
@@ -395,7 +395,7 @@ it("a Cloud of the person's own that ended says so on its circle, and its menu o
await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });
return host.querySelector(`[data-rail-menu="${id}"]`);
};
- expect(host.querySelector('[data-rail-place="old"]')?.getAttribute("aria-label")).toBe("Old Cloud: ended");
+ expect(host.querySelector('[data-rail-place="old"]')?.getAttribute("aria-label")).toBe("Old Cloud: ended, Cloud");
expect(host.querySelector('[data-rail-place="old"] [data-rail-ended]'), "dimmed, as a Cloud that isn't running").toBeTruthy();
expect((await menuOf("a"))?.querySelector("[data-rail-remove]"), "a running Cloud: no such choice").toBeNull();
await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
@@ -551,3 +551,167 @@ it("once My Cloud is home, This Mac (This PC elsewhere) is a laptop circle that
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");
});
+
+it("a small cloud sits at the corner of every Cloud's tile, its own, a team's and another account's, and a screen reader hears Cloud; never on this computer, a workspace or a server", async () => {
+ const mac = place("profile:default", "This computer", { kind: "computer", profile: "default", paint: { swatch: null } });
+ const work = place("profile:work", "Work", { kind: "computer", profile: "work", named: true, color: "teal", paint: { swatch: "green" } });
+ rail = { places: [mac, work, PLACES[0]!, PLACES[2]!, PLACES[3]!, place("vps2", "Mini", { kind: "cloud", server: true }), place("acct:b", "[email protected]", { kind: "account" }),
+ place("other", "Their Cloud", { group: "b", email: "[email protected]" })], add: { cloud: true, link: true, address: false } };
+ Object.assign(window, { ogb: { workspaces, cloudAdd, platform: "darwin" } });
+ await mount(createElement(PlacesRail));
+ const badged = [...host.querySelectorAll("[data-rail-place]")].filter((tile) => tile.querySelector("[data-rail-cloud]")).map((tile) => tile.getAttribute("data-rail-place"));
+ expect(badged.sort()).toEqual(["acme", "home", "other", "pending:c-b"].sort());
+ expect(host.querySelector('[data-rail-place="home"]')?.getAttribute("aria-label")).toBe("My Cloud, Cloud");
+ expect(host.querySelector('[data-rail-place="other"]')?.getAttribute("aria-label")).toBe("Their Cloud · [email protected], Cloud");
+ expect(host.querySelector('[data-rail-place="home"]')?.getAttribute("title"), "the tooltip stays the place's own words").toBe("My Cloud");
+ expect(host.querySelector('[data-rail-place="profile:default"]')?.getAttribute("aria-label")).not.toContain("Cloud,");
+ expect(host.querySelector('[data-rail-place="profile:work"] [data-rail-local]'), "a named workspace: a laptop at its corner").toBeTruthy();
+ expect(host.querySelector('[data-rail-place="profile:work"]')?.textContent, "its initials, as a place with a name").toBe("W");
+ expect(host.querySelector('[data-rail-place="profile:work"]')?.getAttribute("aria-label")).toBe("Work: a separate place on this computer, with its own bots");
+ expect(host.querySelector('[data-rail-place="profile:default"] [data-rail-local]'), "This Mac is the laptop itself").toBeNull();
+ expect(host.querySelector('[data-rail-place="vps2"] [data-rail-server]'), "a server of the person's own keeps its server mark").toBeTruthy();
+ const badge = host.querySelector('[data-rail-place="home"] [data-rail-cloud]')!;
+ expect(badge.getAttribute("class")).toContain("border-(--rail-surface)");
+ expect(badge.getAttribute("aria-hidden")).toBe("true");
+});
+
+it("a workspace that opens once a bot in the one running finishes: a waiting ring, and its tooltip says so", async () => {
+ rail = { places: [place("local", "This computer", { kind: "computer", settling: "" }), place("profile:work", "Work", { kind: "computer", profile: "work", named: true, active: true, settling: "Scout" })],
+ add: { cloud: false, link: false, address: false, local: true } };
+ await mount(createElement(PlacesRail));
+ expect(host.querySelector('[data-rail-place="profile:work"]')?.getAttribute("aria-label")).toBe("Work opens once Scout finishes");
+ expect(host.querySelector('[data-rail-place="profile:work"] [data-rail-ring]')?.getAttribute("data-rail-ring")).toBe("waiting");
+ expect(host.querySelector('[data-rail-place="local"]')?.getAttribute("aria-label")).toBe("This computer opens once the work there finishes");
+});
+
+it("+ offers a new workspace on this computer first, to Cloud owners too: a name (Work, then Personal, then Workspace 2) and a colour no place has, then main makes and opens it", async () => {
+ const create = vi.fn(async (_name: string, _color: unknown) => ({ outcome: "made" as const, id: "personal" }) as { outcome: "made"; id: string } | { outcome: "name" | "taken" | "failed" });
+ const mac = place("profile:default", "This computer", { kind: "computer", profile: "default", paint: { swatch: null } });
+ rail = { places: [mac, place("profile:work", "Work", { kind: "computer", profile: "work", named: true, paint: { swatch: "blue" } }), ...PLACES], add: { cloud: true, link: true, address: false, local: true } };
+ Object.assign(window, { ogb: { workspaces: { ...workspaces, local: { create, edit: vi.fn(), remove: vi.fn() } }, cloudAdd, platform: "darwin" } });
+ await mount(createElement(PlacesRail));
+ expect(host.querySelector("[data-rail-add]")?.getAttribute("aria-label")).toBe("Add a place for your bots");
+ await click(host.querySelector("[data-rail-add]"));
+ const sheet = document.querySelector("[data-place-add-sheet]")!;
+ expect([...sheet.querySelectorAll("[data-place-add-choice]")].map((choice) => choice.getAttribute("data-place-add-choice"))).toEqual(["local", "cloud", "server"]);
+ expect(sheet.querySelector('[data-place-add-choice="local"]')?.textContent).toContain("New workspace on this computer");
+ await click(sheet.querySelector('[data-place-add-choice="local"]'));
+ let form = document.querySelector('[data-place-add="local"]')!;
+ const name = form.querySelector<HTMLInputElement>("[data-local-name]")!;
+ expect(name.value, "Work is taken here: the next first name").toBe("Personal");
+ expect(document.activeElement).toBe(name);
+ expect(form.querySelector('[role="radio"][aria-checked="true"]')?.getAttribute("data-swatch"), "a colour no place here has: My Cloud is violet, Client A green, Work blue").toBe("amber");
+ await click([...form.querySelectorAll("button")].find((button) => button.textContent === "Back") ?? null);
+ expect(document.querySelector('[data-place-add="choose"]'), "Back: the choices again").toBeTruthy();
+ await click(document.querySelector('[data-place-add-choice="local"]'));
+ form = document.querySelector('[data-place-add="local"]')!;
+ await type(form.querySelector("[data-local-name]"), " ");
+ expect(form.querySelector<HTMLButtonElement>("[data-local-create]")!.disabled, "no name: nothing to create").toBe(true);
+ await type(form.querySelector("[data-local-name]"), " this mac ");
+ await submit(form);
+ expect(form.querySelector("[data-local-problem]")?.textContent, "a name a place here has, said at once").toBe("Another place here has that name. Choose another.");
+ expect(create).not.toHaveBeenCalled();
+ await type(form.querySelector("[data-local-name]"), " Side project ");
+ await click(form.querySelector('[data-swatch="rose"]'));
+ await submit(form);
+ await act(async () => { for (let i = 0; i < 4; i++) await Promise.resolve(); });
+ expect(create.mock.calls).toEqual([["Side project", "rose"]]);
+ expect(document.querySelector("[data-place-add-sheet]"), "made: the sheet closes, and the rail shows it opening").toBeNull();
+ await click(host.querySelector("[data-rail-add]"));
+ await click(document.querySelector('[data-place-add-choice="local"]'));
+ create.mockResolvedValueOnce({ outcome: "taken" });
+ await submit(document.querySelector('[data-place-add="local"]'));
+ await act(async () => { for (let i = 0; i < 4; i++) await Promise.resolve(); });
+ expect(document.querySelector("[data-local-problem]")?.textContent, "main's own no").toBe("Another place here has that name. Choose another.");
+ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(document.querySelector("[data-place-add-sheet]"), "Escape closes it, nothing made").toBeNull();
+ expect(create).toHaveBeenCalledTimes(2);
+});
+
+it("with only the new workspace to add, + goes straight to its name, and Close leaves nothing behind", async () => {
+ const create = vi.fn();
+ rail = { places: [place("local", "This computer", { kind: "computer", active: true }), place("vps", "Office", { kind: "server" })], add: { cloud: false, link: false, address: false, local: true } };
+ Object.assign(window, { ogb: { workspaces: { ...workspaces, local: { create, edit: vi.fn(), remove: vi.fn() } }, cloudAdd } });
+ await mount(createElement(PlacesRail));
+ await click(host.querySelector("[data-rail-add]"));
+ const form = document.querySelector('[data-place-add="local"]')!;
+ expect(form.querySelector<HTMLInputElement>("[data-local-name]")!.value).toBe("Work");
+ expect([...form.querySelectorAll("button")].some((button) => button.textContent === "Back"), "nothing to go back to").toBe(false);
+ await click(document.querySelector('[data-place-add-sheet] [aria-label="Close"]'));
+ expect(document.querySelector("[data-place-add-sheet]")).toBeNull();
+ expect(create).not.toHaveBeenCalled();
+});
+
+it("a workspace's menu: Rename (Enter saves, Escape leaves it), its colour, and Remove asked first in plain words; Cancel changes nothing", async () => {
+ const edit = vi.fn(async (_id: string, _changes: unknown) => ({ outcome: "saved" as const }) as { outcome: "saved" | "taken" | "name" | "full" | "gone" });
+ const remove = vi.fn(async (_id: string) => ({ outcome: "removed" as const }) as { outcome: "removed" | "gone" | "failed" });
+ rail = { places: [place("profile:default", "This computer", { kind: "computer", profile: "default", paint: { swatch: null } }),
+ place("profile:work", "Work", { kind: "computer", profile: "work", named: true, active: true, paint: { swatch: "green" } }), ...PLACES], add: { cloud: true, link: true, address: false, local: true } };
+ Object.assign(window, { ogb: { workspaces: { ...workspaces, local: { create: vi.fn(), edit, remove } }, cloudAdd, platform: "darwin", rail: { expand: vi.fn(async () => {}), onSkin: () => () => {} } } });
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const settle = () => act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });
+ const menuOf = async (id: string) => {
+ await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });
+ return host.querySelector(`[data-rail-menu="${id}"]`)!;
+ };
+ let menu = await menuOf("profile:work");
+ expect(menu.getAttribute("aria-label")).toBe("Work");
+ expect(document.activeElement, "the first row takes the focus").toBe(menu.querySelector("[data-rail-rename]"));
+ await click(menu.querySelector("[data-rail-rename]"));
+ const field = menu.querySelector<HTMLInputElement>("[data-rail-rename-form] input")!;
+ expect(field.value).toBe("Work");
+ await type(field, "Office");
+ await act(async () => { field.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(menu.querySelector("[data-rail-rename-form]"), "Escape leaves the name as it was").toBeNull();
+ expect(host.querySelector("[data-rail-menu]"), "and the menu stays").toBeTruthy();
+ expect(edit).not.toHaveBeenCalled();
+ await click(menu.querySelector("[data-rail-rename]"));
+ await type(menu.querySelector("[data-rail-rename-form] input"), " Office ");
+ edit.mockResolvedValueOnce({ outcome: "taken" });
+ await submit(menu.querySelector("[data-rail-rename-form]"));
+ await settle();
+ expect(menu.querySelector("[data-rail-rename-form] [role='alert']")?.textContent).toBe("Another place here has that name. Choose another.");
+ await submit(menu.querySelector("[data-rail-rename-form]"));
+ await settle();
+ expect(edit.mock.calls, "by the circle's own id, which main listed").toEqual([["profile:work", { name: "Office" }], ["profile:work", { name: "Office" }]]);
+ expect(host.querySelector("[data-rail-menu]"), "saved: the menu closes").toBeNull();
+ menu = await menuOf("profile:work");
+ await click(menu.querySelector('[data-rail-local-color] [data-swatch="violet"]'));
+ await settle();
+ expect(edit.mock.calls.at(-1)).toEqual(["profile:work", { color: "violet" }]);
+ menu = await menuOf("profile:default");
+ await click(menu.querySelector('[data-rail-local-color] [data-swatch="slate"]'));
+ expect(edit.mock.calls.length, "None is This Mac's colour already: nothing to save").toBe(3);
+ await click(menu.querySelector("[data-rail-remove-ask]"));
+ expect(menu.querySelector("[role='alertdialog'] p")?.textContent).toBe("Remove “This Mac”? Its bots, chats and files on this computer are deleted. Its folder goes to the Trash first.");
+ await click(menu.querySelector("[data-rail-remove-cancel]"));
+ expect(remove, "Cancel: nothing removed").not.toHaveBeenCalled();
+ expect(menu.querySelector("[data-rail-remove-ask]"), "and the menu as it was").toBeTruthy();
+ await act(async () => { menu.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ menu = await menuOf("profile:work");
+ await click(menu.querySelector("[data-rail-remove-ask]"));
+ remove.mockResolvedValueOnce({ outcome: "failed" });
+ await click(menu.querySelector("[data-rail-remove-confirm]"));
+ await settle();
+ expect(host.querySelector("[data-rail-menu] [role='alert']")?.textContent).toBe("It wasn't removed. Try again in a moment.");
+ await click(host.querySelector("[data-rail-menu] [data-rail-remove-ask]"));
+ await click(host.querySelector("[data-rail-menu] [data-rail-remove-confirm]"));
+ await settle();
+ expect(remove.mock.calls).toEqual([["profile:work"], ["profile:work"]]);
+ expect(host.querySelector("[data-rail-menu]"), "removed: the menu closes, and the tile goes with main's next list").toBeNull();
+ Object.assign(window, { ogb: { ...window.ogb, platform: "win32" } });
+ menu = await menuOf("profile:work");
+ await click(menu.querySelector("[data-rail-remove-ask]"));
+ expect(menu.querySelector("[role='alertdialog'] p")?.textContent).toContain("Recycle Bin");
+});
+
+it("two quick clicks: the place still marked can be clicked to stay, so the last click wins; on its own it opens nothing", async () => {
+ rail = { places: [place("profile:default", "This computer", { kind: "computer", profile: "default" }), place("profile:work", "Work", { kind: "computer", profile: "work", named: true, active: true }), ...PLACES.slice(1)],
+ add: { cloud: false, link: false, address: false } };
+ await mount(createElement(PlacesRail));
+ await click(host.querySelector('[data-rail-place="profile:work"]'));
+ expect(workspaces.open, "the place on screen: nothing to open").not.toHaveBeenCalled();
+ await click(host.querySelector('[data-rail-place="profile:default"]'));
+ await click(host.querySelector('[data-rail-place="profile:work"]'));
+ expect(workspaces.open.mock.calls).toEqual([["profile:default"], ["profile:work"]]);
+});
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index 8564640b6e..6874ab737d 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -1,12 +1,15 @@
// The rail at the window's left edge once a person has two places or more: one tile per Cloud, team's Cloud or server,
-// the place on screen marked, ⋯ for the rest past eight, + last. Main lists the places and opens one by its id; the rail
-// never names an address. A right-click on a tile (or its row past eight) opens that place's menu: its colour, changed
+// the place on screen marked, ⋯ for the rest past eight, + last. A Cloud's tile has a small cloud at its corner, a server of
+// the person's own a server and a workspace of this computer's own with a name of its own a laptop, so each reads at a
+// glance. Main lists the places and opens one by its id; the rail never names an address. A right-click on a tile (or its
+// row past eight) opens that place's menu: a workspace of this computer's own is renamed, recoloured or removed there (asked
+// first); for the rest, its colour, changed
// here for every place whatever its server runs, Remove from list for a Cloud of the person's own that ended or was
// never paid for (asked first; main takes it off their list on the Admin), and Make … my home for a server of theirs that
// main says this computer's bots may move to (one tap: main starts the move). With several accounts signed in here, the tiles
// are grouped by account with a thin divider, and a click on another account's tile switches to it first (main does that).
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";
-import { House, Laptop, Loader2, MoreHorizontal, Plus, Search, Server, UserRound } from "lucide-react";
+import { Cloud, House, Laptop, Loader2, MoreHorizontal, Plus, Search, Server, UserRound } from "lucide-react";
import type { CloudSwatch } from "../../electron/cloud-list.mjs";
import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
import { track } from "@/lib/analytics";
@@ -16,7 +19,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 { computerName, makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
+import { computerName, editLocal, makeHome, placeInitials, recolorPlace, removeLocal, 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,7 +37,8 @@ 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) });
+ if (place.settling !== undefined) return place.settling ? t("rail.settling", { name: computerName(place), bot: place.settling }) : t("rail.settlingAny", { name: computerName(place) });
+ if (place.profile) return place.named ? t("rail.localPlace", { name: computerName(place) }) : 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(" · ");
}
@@ -51,6 +55,12 @@ function placeStatus(place: RailPlace, now: number): string {
return [status, place.update && t("rail.update", place.update), place.ownNetwork && t("rail.ownNetwork")].filter(Boolean).join(" · ");
}
+/** A Cloud of the person's own, a team's Cloud or another account's: not a server they run, this computer or an account. */
+export const cloudTile = (place: RailPlace): boolean => (place.kind === "cloud" || place.kind === "team") && !place.server;
+
+/** What a screen reader hears for a tile: its words, and that it is a Cloud when it is one. */
+export const tileLabel = (place: RailPlace, now = Date.now()): string => (cloudTile(place) ? t("rail.cloudLabel", { label: placeLabel(place, now) }) : placeLabel(place, now));
+
/** Whether a tile does anything: opens its place, or, for a server of the person's own not connected yet, shows how
* to connect it (only where a pairing link can be pasted). */
export const placeActs = (place: RailPlace, canPair: boolean): boolean => place.opens || (place.pairs === true && canPair);
@@ -92,14 +102,30 @@ function ProgressRing({ value = 0, waiting = false }: { value?: number; waiting?
}
/** What a place's mark draws: its kind, its name's letters and its colour, faded while it is offline or has ended. */
-type MarkedPlace = Pick<RailPlace, "kind" | "name" | "offline" | "ended"> & { color: unknown };
+type MarkedPlace = Pick<RailPlace, "kind" | "name" | "offline" | "ended"> & Partial<Pick<RailPlace, "named">> & { color: unknown };
export function PlaceMark({ place, size = TILE }: { place: MarkedPlace; size?: number }) {
const color = cloudColor(place.color);
return <span aria-hidden="true" data-rail-offline={place.offline ? "" : undefined} data-rail-ended={place.ended ? "" : undefined}
className={cn("grid shrink-0 place-items-center font-semibold leading-none", color ? "text-white" : "bg-card text-ink", (place.offline || place.ended) && "opacity-55 grayscale")}
style={{ width: size, height: size, borderRadius: tileRadius(size), fontSize: Math.round(size * 0.4), ...(color ? { background: cloudColorFill(color) } : {}) }}>
- {place.kind === "computer" ? <Laptop size={Math.round(size * 0.46)} strokeWidth={1.75} /> : place.kind === "account" ? <UserRound size={Math.round(size * 0.5)} strokeWidth={1.75} /> : placeInitials(place.name)}
+ {place.kind === "computer" && !place.named ? <Laptop size={Math.round(size * 0.46)} strokeWidth={1.75} /> : place.kind === "account" ? <UserRound size={Math.round(size * 0.5)} strokeWidth={1.75} /> : placeInitials(place.name)}
+ </span>;
+}
+
+/** What kind of place a mark is, at its bottom-right corner: a cloud for a Cloud, a server for a server of the person's
+ * own, a laptop for a workspace of this computer's own with a name of its own. The ring is the rail's own surface, so it
+ * reads on any tile colour in either theme. */
+function KindBadge({ place }: { place: RailPlace }) {
+ if (cloudTile(place)) return <span aria-hidden="true" data-rail-cloud
+ className="pointer-events-none absolute -bottom-1 -right-1 grid size-3.5 place-items-center rounded-full border-2 border-(--rail-surface) bg-ink text-(--rail-surface)">
+ <Cloud size={9} strokeWidth={3} />
+ </span>;
+ const Icon = place.server ? Server : place.named ? Laptop : null;
+ if (!Icon) return null;
+ return <span aria-hidden="true" data-rail-server={place.server ? "" : undefined} data-rail-local={place.server ? undefined : ""}
+ className="pointer-events-none absolute -bottom-1 -right-1 grid size-3 place-items-center rounded-full border border-hairline bg-(--rail-surface) text-ink-secondary">
+ <Icon size={7} strokeWidth={2.25} />
</span>;
}
@@ -125,20 +151,18 @@ export function topWithin(element: HTMLElement, rail: HTMLElement): number {
* badge and progress round it, all inside the rail. */
function PlaceTile({ place, canPair, onOpen, onMenu }: { place: RailPlace; canPair: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void }) {
const label = placeLabel(place), acts = placeActs(place, canPair);
- return <button type="button" aria-label={label} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true}
- data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts && !place.active) onOpen(place); }} onContextMenu={menuOpener(place, onMenu)}
+ return <button type="button" aria-label={tileLabel(place)} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true}
+ data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts) onOpen(place); }} onContextMenu={menuOpener(place, onMenu)}
className={cn("group/tile relative shrink-0 rounded-[7px] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",
!acts && cn("cursor-default", !place.offline && "opacity-75"))}>
<span aria-hidden="true" data-rail-pill={place.active ? "page" : acts ? "hover" : undefined}
className={cn("pointer-events-none absolute -left-1.5 top-1/2 w-[3px] -translate-y-1/2 rounded-r-full bg-ink transition-[height,opacity] duration-150 motion-reduce:transition-none",
place.active ? "h-4" : acts ? "h-2 opacity-0 group-hover/tile:opacity-100" : "hidden")} />
<PlaceMark place={place} />
- {place.progress !== undefined && <ProgressRing value={place.progress} waiting={place.waiting === true} />}
+ {(place.progress !== undefined || place.settling !== undefined) && <ProgressRing value={place.progress} waiting={place.waiting === true || place.settling !== undefined} />}
{place.attention && <span aria-hidden="true" data-rail-dot className="absolute -right-1 -top-1 size-2.5 rounded-full border-2 border-(--rail-surface) bg-danger" />}
{place.update && !place.attention && <span aria-hidden="true" data-rail-update className="absolute -right-1 -top-1 size-2.5 rounded-full border-2 border-(--rail-surface) bg-accent" />}
- {place.server && <span aria-hidden="true" data-rail-server className="absolute -bottom-1 -right-1 grid size-3 place-items-center rounded-full border border-hairline bg-(--rail-surface) text-ink-secondary">
- <Server size={7} strokeWidth={2.25} />
- </span>}
+ <KindBadge place={place} />
</button>;
}
@@ -198,6 +222,11 @@ function MakeHomeRow({ place, onStarted }: { place: RailPlace; onStarted: () =>
* whatever its server runs (on the Admin for a Cloud), and Remove from list for a Cloud its owner may take off their list.
* A team member sees who may change its colour. */
function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onClose: () => void }) {
+ if (place.profile) return <LocalMenu place={place} top={top} onClose={onClose} />;
+ return <ListedMenu place={place} top={top} onClose={onClose} />;
+}
+
+function ListedMenu({ place, top, onClose }: { place: RailPlace; top: number; onClose: () => void }) {
const paint = place.paint;
const [pending, setPending] = useState<CloudSwatch | null>(null);
const [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);
@@ -231,15 +260,110 @@ function PlaceMenu({ place, top, onClose }: { place: RailPlace; top: number; onC
</div>;
}
+const rowText = (place: RailPlace) => [placeStatus(place, Date.now()), place.signIn && t("accounts.needsSignIn")].filter(Boolean).join(" · ");
+
+/** Rename in a workspace's menu: its name in a field, saved on Enter or Save; Escape or Cancel leaves it as it was. */
+function RenameRow({ place, onSaved }: { place: RailPlace; onSaved: () => void }) {
+ const [editing, setEditing] = useState(false);
+ const [name, setName] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<"taken" | "failed" | null>(null);
+ const start = () => { setName(computerName(place)); setSaid(null); setEditing(true); };
+ const save = () => {
+ const next = name.trim();
+ if (!next || busy) return;
+ if (next === computerName(place)) { setEditing(false); return; }
+ setBusy(true); setSaid(null);
+ void editLocal(place.id, { name: next }).then((outcome) => {
+ setBusy(false);
+ if (outcome === "saved") { setEditing(false); onSaved(); return; }
+ setSaid(outcome === "taken" ? "taken" : "failed");
+ });
+ };
+ if (!editing) return <button type="button" data-rail-rename className={MENU_ROW} onClick={start}>{t("rail.rename")}</button>;
+ return <form data-rail-rename-form className="flex flex-col gap-1.5 px-1.5 pb-1" onSubmit={(event) => { event.preventDefault(); save(); }}>
+ <input autoFocus value={name} maxLength={80} disabled={busy} aria-label={t("rail.rename")} aria-invalid={said ? true : undefined}
+ onChange={(event) => { setName(event.target.value); setSaid(null); }}
+ onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setEditing(false); } }}
+ className="h-8 w-full rounded-md border border-hairline/60 bg-inset px-2 text-[13px] text-ink outline-none focus:border-accent/50" />
+ {said && <p role="alert" className="text-[12px] text-danger">{t(said === "taken" ? "rail.localTaken" : "rail.localFailed")}</p>}
+ <div className="flex gap-2">
+ <button type="submit" data-rail-rename-save className="ui-button ui-button-primary" disabled={busy || !name.trim()}>{t("rail.renameSave")}</button>
+ <button type="button" className="ui-button" disabled={busy} onClick={() => setEditing(false)}>{t("rail.removeNo")}</button>
+ </div>
+ </form>;
+}
+
+/** Remove in a workspace's menu: asked first, in plain words; main stops it first if it runs, and its folder goes to the
+ * Trash. */
+function RemoveLocalRow({ place, onRemoved }: { place: RailPlace; onRemoved: () => void }) {
+ const [asking, setAsking] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const confirm = () => {
+ setBusy(true); setFailed(false);
+ void removeLocal(place.id).then((outcome) => {
+ setBusy(false);
+ if (outcome === "removed") { onRemoved(); return; }
+ setAsking(false); setFailed(true);
+ });
+ };
+ const ask = t(window.ogb?.platform === "win32" ? "rail.localRemoveAskWin" : "rail.localRemoveAsk", { name: computerName(place) });
+ return <div data-rail-remove className="flex flex-col gap-1.5 border-t border-hairline/50 px-0.5 pt-1.5">
+ {asking
+ ? <div role="alertdialog" aria-label={t("rail.localRemove")} className="flex flex-col gap-2 px-1.5 pb-1">
+ <p className="text-[12px] leading-snug text-ink">{ask}</p>
+ <div className="flex gap-2">
+ <button type="button" data-rail-remove-confirm className="ui-button ui-button-primary inline-flex items-center gap-1.5" disabled={busy} onClick={confirm}>
+ {busy && <Loader2 size={13} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />}{t("rail.removeYes")}
+ </button>
+ <button type="button" data-rail-remove-cancel className="ui-button" disabled={busy} onClick={() => setAsking(false)}>{t("rail.removeNo")}</button>
+ </div>
+ </div>
+ : <button type="button" data-rail-remove-ask className={MENU_ROW} onClick={() => { setFailed(false); setAsking(true); }}>{t("rail.localRemove")}</button>}
+ {failed && <p role="alert" className="px-1.5 pb-1 text-[12px] text-danger">{t("rail.localRemoveFailed")}</p>}
+ </div>;
+}
+
+/** A workspace of this computer's own: its name (Rename), its colour in the six swatches, and Remove. */
+function LocalMenu({ place, top, onClose }: { place: RailPlace; top: number; onClose: () => void }) {
+ const [pending, setPending] = useState<CloudSwatch | null | undefined>(undefined);
+ const [failed, setFailed] = useState(false);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => { ref.current?.querySelector<HTMLElement>("[data-rail-rename]")?.focus(); }, []);
+ const name = computerName(place), swatch = place.paint?.swatch ?? null;
+ const choose = (next: CloudSwatch) => {
+ const value = next === "slate" ? null : next;
+ if (pending !== undefined || value === swatch) return;
+ setPending(value); setFailed(false);
+ void editLocal(place.id, { color: value }).then((outcome) => { setPending(undefined); if (outcome === "saved") onClose(); else setFailed(true); });
+ };
+ return <div ref={ref} role="dialog" aria-label={name} data-rail-menu={place.id} className={cn("absolute left-full z-50 ml-2 w-72", MENU_SHEET)} style={{ top }}
+ onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }}>
+ <div className="flex items-center gap-2 px-2 pt-1">
+ <PlaceMark place={place} size={22} />
+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink">{name}</span>
+ </div>
+ <div className="px-0.5 pt-1"><RenameRow place={place} onSaved={onClose} /></div>
+ <p className="px-2 pt-1 text-[12px] text-ink-secondary">{t("placeLook.title")}</p>
+ <div className="px-2 pb-1.5 pt-0.5" data-rail-local-color>
+ <SwatchRadios value={(pending === undefined ? swatch : pending) ?? "slate"} onChange={choose} label={t("placeLook.aria", { name })} offset="menu" none />
+ </div>
+ {failed && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}
+ <RemoveLocalRow place={place} onRemoved={onClose} />
+ </div>;
+}
+
/** Every place, searchable: ⋯ once there are more than RAIL_SHOWN. */
function MorePlaces({ places, canPair, onOpen, onMenu, onClose }: { places: RailPlace[]; canPair: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void; onClose: () => void }) {
const [query, setQuery] = useState("");
const found = matchingPlaces(places, query);
- return <div role="dialog" aria-label={t("rail.search")} data-rail-more className={cn("absolute bottom-0 left-full z-50 ml-2 w-64", MENU_SHEET)}
+ const search = t(places.some((place) => place.profile) ? "rail.searchAny" : "rail.search");
+ return <div role="dialog" aria-label={search} data-rail-more className={cn("absolute bottom-0 left-full z-50 ml-2 w-64", MENU_SHEET)}
onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }}>
<label className="flex h-8 items-center gap-2 rounded-md bg-ink/[0.05] px-2">
<Search size={14} aria-hidden="true" className="shrink-0 text-ink-secondary" />
- <input autoFocus value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("rail.search")} aria-label={t("rail.search")}
+ <input autoFocus value={query} onChange={(event) => setQuery(event.target.value)} placeholder={search} aria-label={search}
onKeyDown={(event) => { if (event.key === "Enter" && found[0] && placeActs(found[0], canPair)) { onOpen(found[0]); onClose(); } }}
className="w-full bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-tertiary" />
</label>
@@ -247,9 +371,10 @@ function MorePlaces({ places, canPair, onOpen, onMenu, onClose }: { places: Rail
{found.map((place, at) => <li key={place.id}>
{startsGroup(found, at) && <div data-rail-group className="mt-1 truncate border-t border-hairline/50 px-2 pt-1.5 text-[12px] text-ink-tertiary">{place.kind === "account" ? "" : place.email ?? ""}</div>}
<button type="button" disabled={!placeActs(place, canPair)} aria-current={place.active ? "page" : undefined} onClick={() => { onOpen(place); onClose(); }}
+ aria-label={cloudTile(place) ? t("rail.cloudLabel", { label: rowText(place) }) : undefined}
onContextMenu={menuOpener(place, (menu) => { onClose(); onMenu(menu); })} className={cn(MENU_ROW, "h-9")}>
- <PlaceMark place={place} size={22} />
- <span className="min-w-0 flex-1 truncate">{[placeStatus(place, Date.now()), place.signIn && t("accounts.needsSignIn")].filter(Boolean).join(" · ")}</span>
+ <span className="relative shrink-0"><PlaceMark place={place} size={22} /><KindBadge place={place} /></span>
+ <span className="min-w-0 flex-1 truncate">{rowText(place)}</span>
</button>
</li>)}
</ul>
@@ -271,6 +396,9 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
const [accounts, setAccounts] = useState<{ adding: string | null; note: string | null } | null>(null);
const moreRef = useRef<HTMLDivElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
+ // The place last clicked, until main lists it on screen: the one still marked meanwhile can be clicked to stay.
+ const asked = useRef<string | null>(null);
+ useEffect(() => { if (asked.current && state.places.find((place) => place.id === asked.current)?.active) asked.current = null; }, [state.places]);
const navRef = useRef<HTMLElement>(null);
useEffect(() => {
if (!more && !menu) return;
@@ -287,6 +415,8 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
const bridge = window.ogb?.workspaces;
const open = (place: RailPlace) => {
if (!place.opens) { if (place.pairs) setConnecting(place.name); return; }
+ if (place.active && (asked.current === null || asked.current === place.id)) return;
+ asked.current = place.id;
track("rail_place_opened", { kind: place.kind });
void bridge?.open?.(place.id).then((said) => {
if (!said) return;
@@ -304,7 +434,8 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
const drag = draggable ? ({ WebkitAppRegion: "drag" } as CSSProperties) : undefined;
const noDrag = draggable ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;
const shown = shownPlaces(state.places);
- const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair || state.add.organization === true || state.add.account === true;
+ const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair || state.add.organization === true || state.add.account === true || state.add.local === true;
+ const addLabel = t(state.add.local ? "rail.addAny" : "rail.add");
// The menu opens next to the tile or row it was asked from (measured now, while that row is there), within the rail.
const openMenu = ({ place, from }: MenuAt) => {
const nav = navRef.current;
@@ -328,7 +459,7 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
<MoreHorizontal size={13} aria-hidden="true" />
</button>}
{more && <MorePlaces places={state.places} canPair={canPair} onOpen={open} onMenu={openMenu} onClose={() => setMore(false)} />}
- {canAdd && <button type="button" aria-label={t("rail.add")} title={t("rail.add")} aria-haspopup="dialog" data-rail-add onClick={() => { track("rail_add", { step: "opened" }); setAdding(true); }}
+ {canAdd && <button type="button" aria-label={addLabel} title={addLabel} aria-haspopup="dialog" data-rail-add onClick={() => { track("rail_add", { step: "opened" }); setAdding(true); }}
className="grid size-6 place-items-center rounded-[7px] border border-dashed border-ink/25 text-ink-secondary hover:border-ink/40 hover:bg-ink/[0.04] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
<Plus size={13} aria-hidden="true" />
</button>}
@@ -337,7 +468,7 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
{menu && <div ref={menuRef} style={noDrag}>
<PlaceMenu key={menu.place.id} place={state.places.find((entry) => entry.id === menu.place.id) ?? menu.place} top={menu.top} onClose={() => setMenu(null)} />
</div>}
- {adding && <PlaceAddSheet choices={state.add} onClose={() => setAdding(false)} onAccount={() => { setAdding(false); setAccounts({ adding: "", note: null }); }} />}
+ {adding && <PlaceAddSheet choices={state.add} places={state.places} onClose={() => setAdding(false)} onAccount={() => { setAdding(false); setAccounts({ adding: "", note: null }); }} />}
{accounts && <AccountsSheet adding={accounts.adding} note={accounts.note} onClose={() => setAccounts(null)} />}
{connecting !== null && <PlaceAddSheet choices={state.add} connect={{ name: connecting }} onClose={() => setConnecting(null)} />}
</nav>;
diff --git a/src/components/WindowPlaceTitle.test.ts b/src/components/WindowPlaceTitle.test.ts
index fd221904c2..f06de54b00 100644
--- a/src/components/WindowPlaceTitle.test.ts
+++ b/src/components/WindowPlaceTitle.test.ts
@@ -14,3 +14,8 @@ it("the top bar names the place as the rail does: This computer, This Mac (or Th
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");
});
+
+it("a workspace added from + is called by its own name in the top bar", () => {
+ window.ogb = { platform: "darwin" } as unknown as typeof window.ogb;
+ expect(windowPlaceName({ local: true, name: "This computer", profile: "work", profileName: "Work" }, undefined)).toBe("Work");
+});
diff --git a/src/components/WindowPlaceTitle.tsx b/src/components/WindowPlaceTitle.tsx
index 78d951cce6..bd65d5badc 100644
--- a/src/components/WindowPlaceTitle.tsx
+++ b/src/components/WindowPlaceTitle.tsx
@@ -26,7 +26,7 @@ export function useWindowPlace(): WorkspaceState | null {
* 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.profile) return place.profileName || 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 cdc853b6c1..a03ef3c9cd 100644
--- a/src/lib/places.ts
+++ b/src/lib/places.ts
@@ -86,13 +86,45 @@ 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 {
+/** This computer's circle: This computer, or a workspace of its own (a profile): its own name, else as the app names this
+ * computer elsewhere, This Mac or This PC. */
+export function computerName(place: Pick<RailPlace, "profile"> & Partial<Pick<RailPlace, "named" | "name">>, platform: string | undefined = typeof window === "undefined" ? undefined : window.ogb?.platform): string {
if (!place.profile) return t("rail.thisComputer");
+ if (place.named && place.name) return place.name;
return t(platform === "darwin" ? "rail.thisMac" : "rail.thisPc");
}
+/** A new workspace's first name: Work, then Personal, then Workspace 2, 3 and on, whichever no place here has yet. */
+export function suggestedLocalName(taken: readonly string[]): string {
+ const used = new Set(taken.map((name) => name.toLocaleLowerCase()));
+ const free = (name: string) => !used.has(name.toLocaleLowerCase());
+ for (const name of [t("rail.localWork"), t("rail.localPersonal")]) if (free(name)) return name;
+ for (let count = 2; ; count++) { const name = t("rail.localNumbered", { count }); if (free(name)) return name; }
+}
+
+/** A new workspace of this computer's own, from +: main makes it and opens it next. */
+export async function createLocal(name: string, color: CloudSwatch | null): Promise<"made" | "name" | "taken" | "failed"> {
+ const answer = await bridge()?.local?.create(name, color).catch(() => null);
+ if (!answer) return "failed";
+ if (answer.outcome === "made") void refreshPlaces();
+ return answer.outcome;
+}
+
+/** A workspace's new name or colour, from its circle's menu. */
+export async function editLocal(id: string, changes: { name: string } | { color: CloudSwatch | null }): Promise<"saved" | "name" | "taken" | "failed"> {
+ const answer = await bridge()?.local?.edit(id, changes).catch(() => null);
+ if (!answer) return "failed";
+ if (answer.outcome === "saved") void refreshPlaces();
+ return answer.outcome === "saved" || answer.outcome === "name" || answer.outcome === "taken" ? answer.outcome : "failed";
+}
+
+/** Removes a workspace from this computer, once the person said yes in its circle's menu. */
+export async function removeLocal(id: string): Promise<"removed" | "failed"> {
+ const answer = await bridge()?.local?.remove(id).catch(() => null);
+ if (answer?.outcome === "removed" || answer?.outcome === "gone") { void refreshPlaces(); return "removed"; }
+ return "failed";
+}
+
/** 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 ea52ac4425..c06bf1f589 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2750,6 +2750,7 @@
"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.",
+ "homeLine.local": "{name} startet frisch: ein eigener Bereich auf diesem Computer, mit eigenen Bots, Chats und Dateien.",
"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",
@@ -3240,5 +3241,27 @@
"email.needsGoogle": "Gmail braucht hier ein App-Passwort (mit aktivierter Bestätigung in zwei Schritten), oder melde dich mit Google an.",
"email.needsMicrosoft": "Outlook nimmt hier kein Mail-Passwort an: Melde dich mit Microsoft an.",
"email.needsAppPassword": "{provider} braucht hier ein App-Passwort, nicht dein normales Passwort.",
- "serverError.mailbox.outgoingFields": "Prüfe den Postausgangsserver: ein Name wie mail.example.com, ein Port von 1 bis 65535 und SSL/TLS oder STARTTLS."
+ "serverError.mailbox.outgoingFields": "Prüfe den Postausgangsserver: ein Name wie mail.example.com, ein Port von 1 bis 65535 und SSL/TLS oder STARTTLS.",
+ "rail.addAny": "Einen Ort für deine Bots hinzufügen",
+ "rail.searchAny": "Einen Ort finden",
+ "rail.local": "Neuer Arbeitsbereich auf diesem Computer",
+ "rail.localSub": "Ein eigener Bereich auf diesem Computer, mit eigenen Bots, Chats und Dateien.",
+ "rail.localPreview": "Auf diesem Computer",
+ "rail.localCreate": "Erstellen",
+ "rail.localTaken": "Ein anderer Bereich hier hat schon diesen Namen. Wähle einen anderen.",
+ "rail.localFailed": "Das hat nicht geklappt. Versuch es gleich noch einmal.",
+ "rail.localWork": "Arbeit",
+ "rail.localPersonal": "Privat",
+ "rail.localNumbered": "Arbeitsbereich {count}",
+ "rail.localPlace": "{name}: ein eigener Bereich auf diesem Computer, mit eigenen Bots",
+ "rail.settling": "{name} öffnet sich, sobald {bot} fertig ist",
+ "rail.settlingAny": "{name} öffnet sich, sobald die Arbeit dort fertig ist",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Umbenennen",
+ "rail.renameSave": "Speichern",
+ "rail.localRemove": "Von diesem Computer entfernen",
+ "rail.localRemoveAsk": "„{name}“ entfernen? Seine Bots, Chats und Dateien auf diesem Computer werden gelöscht. Sein Ordner kommt vorher in den Papierkorb.",
+ "rail.localRemoveAskWin": "„{name}“ entfernen? Seine Bots, Chats und Dateien auf diesem Computer werden gelöscht. Sein Ordner kommt vorher in den Papierkorb.",
+ "rail.localRemoveFailed": "Es wurde nicht entfernt. Versuch es gleich noch einmal.",
+ "native.menu.newLocal": "Neuer Arbeitsbereich auf diesem Computer…"
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 54422481e9..b80ab193ee 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -716,6 +716,27 @@
"rail.removeNo": "Cancel",
"rail.removeRefused": "It can't be removed right now: it is running again, or still has a plan.",
"rail.removeFailed": "It wasn't removed. Check your connection and try again.",
+ "rail.addAny": "Add a place for your bots",
+ "rail.searchAny": "Find a place",
+ "rail.local": "New workspace on this computer",
+ "rail.localSub": "A separate place on this computer, with its own bots, chats and files.",
+ "rail.localPreview": "On this computer",
+ "rail.localCreate": "Create",
+ "rail.localTaken": "Another place here has that name. Choose another.",
+ "rail.localFailed": "That didn't work. Try again in a moment.",
+ "rail.localWork": "Work",
+ "rail.localPersonal": "Personal",
+ "rail.localNumbered": "Workspace {count}",
+ "rail.localPlace": "{name}: a separate place on this computer, with its own bots",
+ "rail.settling": "{name} opens once {bot} finishes",
+ "rail.settlingAny": "{name} opens once the work there finishes",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Rename",
+ "rail.renameSave": "Save",
+ "rail.localRemove": "Remove from this computer",
+ "rail.localRemoveAsk": "Remove “{name}”? Its bots, chats and files on this computer are deleted. Its folder goes to the Trash first.",
+ "rail.localRemoveAskWin": "Remove “{name}”? Its bots, chats and files on this computer are deleted. Its folder goes to the Recycle Bin first.",
+ "rail.localRemoveFailed": "It wasn't removed. Try again in a moment.",
"placeLook.title": "Color",
"placeLook.sub": "{name} shows in this color at the top of the sidebar and on its icon on the left of the app.",
"placeLook.aria": "Color of {name}",
@@ -7299,6 +7320,7 @@
"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.",
+ "homeLine.local": "{name} starts fresh: a separate place on this computer, with its own bots, chats and files.",
"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.",
@@ -8884,6 +8906,7 @@
"native.menu.addCloud": "Add a Cloud…",
"native.menu.orgSignIn": "Sign in with your organization…",
"native.menu.connect": "Connect to a server…",
+ "native.menu.newLocal": "New workspace on this computer…",
"native.menu.preferences": "Preferences…",
"native.role.about": "About {app}",
"native.role.hide": "Hide {app}",
diff --git a/src/locales/es.json b/src/locales/es.json
index ca73af7091..abd01bd188 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -517,6 +517,7 @@
"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.",
+ "homeLine.local": "{name} empieza de cero: un espacio aparte en este equipo, con sus propios bots, chats y archivos.",
"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",
@@ -5906,5 +5907,27 @@
"email.needsGoogle": "Gmail necesita aquí una contraseña de aplicación (con la verificación en dos pasos activada), o inicia sesión con Google.",
"email.needsMicrosoft": "Outlook no acepta aquí una contraseña de correo: inicia sesión con Microsoft.",
"email.needsAppPassword": "{provider} necesita aquí una contraseña de aplicación, no tu contraseña normal.",
- "serverError.mailbox.outgoingFields": "Revisa el servidor de salida: un nombre como mail.example.com, un puerto de 1 a 65535 y SSL/TLS o STARTTLS."
+ "serverError.mailbox.outgoingFields": "Revisa el servidor de salida: un nombre como mail.example.com, un puerto de 1 a 65535 y SSL/TLS o STARTTLS.",
+ "rail.addAny": "Añadir un lugar para tus bots",
+ "rail.searchAny": "Buscar un lugar",
+ "rail.local": "Nuevo espacio de trabajo en este equipo",
+ "rail.localSub": "Un espacio aparte en este equipo, con sus propios bots, chats y archivos.",
+ "rail.localPreview": "En este equipo",
+ "rail.localCreate": "Crear",
+ "rail.localTaken": "Otro espacio de aquí ya tiene ese nombre. Elige otro.",
+ "rail.localFailed": "No funcionó. Inténtalo de nuevo en un momento.",
+ "rail.localWork": "Trabajo",
+ "rail.localPersonal": "Personal",
+ "rail.localNumbered": "Espacio de trabajo {count}",
+ "rail.localPlace": "{name}: un espacio aparte en este equipo, con sus propios bots",
+ "rail.settling": "{name} se abre cuando {bot} termine",
+ "rail.settlingAny": "{name} se abre cuando termine el trabajo de allí",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Cambiar nombre",
+ "rail.renameSave": "Guardar",
+ "rail.localRemove": "Quitar de este equipo",
+ "rail.localRemoveAsk": "¿Quitar “{name}”? Sus bots, chats y archivos en este equipo se borran. Antes, su carpeta va a la Papelera.",
+ "rail.localRemoveAskWin": "¿Quitar “{name}”? Sus bots, chats y archivos en este equipo se borran. Antes, su carpeta va a la Papelera de reciclaje.",
+ "rail.localRemoveFailed": "No se quitó. Inténtalo de nuevo en un momento.",
+ "native.menu.newLocal": "Nuevo espacio de trabajo en este equipo…"
}
diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.ts
index 49eabf6383..a1f4fe929b 100644
--- a/src/locales/everyday-words.test.ts
+++ b/src/locales/everyday-words.test.ts
@@ -90,6 +90,8 @@ const ALLOWED: Record<string, string> = {
"cloudPhone.step1": "points at the app menu's Server menu, entry by entry",
"botAccess.tools.syntax": "the tool names people type, such as mcp:SERVER:NAME",
"chat.notice.modelServerStoppedAnswering": "the person's model server at a named host, not the app's internal server",
+ "rail.local": "the owner's own name for the + choice that adds a workspace of this computer's own",
+ "rail.localNumbered": "a new workspace's first name, which the person may change, in the owner's word for it",
};
const prefixes = Object.values(EVERYDAY_PREFIXES).flat();
diff --git a/src/locales/fr.json b/src/locales/fr.json
index f7e693641b..5282c36ab3 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -2683,6 +2683,7 @@
"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.",
+ "homeLine.local": "{name} repart de zéro : un espace à part sur cet ordinateur, avec ses propres bots, discussions et fichiers.",
"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",
@@ -3106,5 +3107,27 @@
"email.needsGoogle": "Gmail demande ici un mot de passe d’application (avec la validation en deux étapes activée), ou connectez-vous avec Google.",
"email.needsMicrosoft": "Outlook n’accepte pas de mot de passe de messagerie ici : connectez-vous avec Microsoft.",
"email.needsAppPassword": "{provider} demande ici un mot de passe d’application, pas votre mot de passe habituel.",
- "serverError.mailbox.outgoingFields": "Vérifiez le serveur sortant : un nom comme mail.example.com, un port de 1 à 65535, et SSL/TLS ou STARTTLS."
+ "serverError.mailbox.outgoingFields": "Vérifiez le serveur sortant : un nom comme mail.example.com, un port de 1 à 65535, et SSL/TLS ou STARTTLS.",
+ "rail.addAny": "Ajouter un lieu pour vos bots",
+ "rail.searchAny": "Trouver un lieu",
+ "rail.local": "Nouvel espace de travail sur cet ordinateur",
+ "rail.localSub": "Un espace à part sur cet ordinateur, avec ses propres bots, discussions et fichiers.",
+ "rail.localPreview": "Sur cet ordinateur",
+ "rail.localCreate": "Créer",
+ "rail.localTaken": "Un autre espace ici porte déjà ce nom. Choisissez-en un autre.",
+ "rail.localFailed": "Ça n'a pas marché. Réessayez dans un instant.",
+ "rail.localWork": "Travail",
+ "rail.localPersonal": "Perso",
+ "rail.localNumbered": "Espace de travail {count}",
+ "rail.localPlace": "{name} : un espace à part sur cet ordinateur, avec ses propres bots",
+ "rail.settling": "{name} s'ouvre dès que {bot} a fini",
+ "rail.settlingAny": "{name} s'ouvre dès que le travail en cours là-bas est fini",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Renommer",
+ "rail.renameSave": "Enregistrer",
+ "rail.localRemove": "Retirer de cet ordinateur",
+ "rail.localRemoveAsk": "Retirer « {name} » ? Ses bots, discussions et fichiers sur cet ordinateur sont supprimés. Son dossier va d'abord à la Corbeille.",
+ "rail.localRemoveAskWin": "Retirer « {name} » ? Ses bots, discussions et fichiers sur cet ordinateur sont supprimés. Son dossier va d'abord à la Corbeille.",
+ "rail.localRemoveFailed": "Il n'a pas été retiré. Réessayez dans un instant.",
+ "native.menu.newLocal": "Nouvel espace de travail sur cet ordinateur…"
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 680aefe221..fd3c5241c2 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -2683,6 +2683,7 @@
"rail.thisPc": "यह PC",
"rail.profile": "{name}: इस कंप्यूटर पर एक अलग जगह, अपने बॉट्स के साथ। आपके Cloud के बॉट्स My Cloud पर ही रहते हैं।",
"homeLine.profile": "{name} नए सिरे से शुरू होता है, My Cloud से अलग। आपके पहले के बॉट्स My Cloud पर हैं; पुरानी कॉपी लाने के लिए सेटिंग्स → Backups में उसका बैकअप इंपोर्ट करें।",
+ "homeLine.local": "{name} नए सिरे से शुरू होता है: इस कंप्यूटर पर एक अलग जगह, अपने बॉट्स, चैट और फ़ाइलों के साथ।",
"native.places.profileFailed": "इस कंप्यूटर की अपनी जगह नहीं खुली। थोड़ी देर में फिर से कोशिश करें।",
"rail.settingUp": "{name}: सेट हो रहा है",
"rail.waiting": "{name}: भुगतान का इंतज़ार",
@@ -2958,5 +2959,27 @@
"email.needsGoogle": "Gmail को यहाँ ऐप पासवर्ड चाहिए (2-स्टेप वेरिफ़िकेशन चालू होने पर), या Google से साइन इन करें।",
"email.needsMicrosoft": "Outlook यहाँ मेल पासवर्ड नहीं लेता: Microsoft से साइन इन करें।",
"email.needsAppPassword": "{provider} को यहाँ ऐप पासवर्ड चाहिए, आपका सामान्य पासवर्ड नहीं।",
- "serverError.mailbox.outgoingFields": "आउटगोइंग सर्वर जाँचें: mail.example.com जैसा नाम, 1 से 65535 तक का पोर्ट, और SSL/TLS या STARTTLS।"
+ "serverError.mailbox.outgoingFields": "आउटगोइंग सर्वर जाँचें: mail.example.com जैसा नाम, 1 से 65535 तक का पोर्ट, और SSL/TLS या STARTTLS।",
+ "rail.addAny": "अपने बॉट्स के लिए एक जगह जोड़ें",
+ "rail.searchAny": "कोई जगह खोजें",
+ "rail.local": "इस कंप्यूटर पर नया वर्कस्पेस",
+ "rail.localSub": "इस कंप्यूटर पर एक अलग जगह, अपने बॉट्स, चैट और फ़ाइलों के साथ।",
+ "rail.localPreview": "इस कंप्यूटर पर",
+ "rail.localCreate": "बनाएँ",
+ "rail.localTaken": "यहाँ किसी और जगह का यही नाम है। कोई दूसरा नाम चुनें।",
+ "rail.localFailed": "यह नहीं हो पाया। थोड़ी देर में फिर कोशिश करें।",
+ "rail.localWork": "काम",
+ "rail.localPersonal": "निजी",
+ "rail.localNumbered": "वर्कस्पेस {count}",
+ "rail.localPlace": "{name}: इस कंप्यूटर पर एक अलग जगह, अपने बॉट्स के साथ",
+ "rail.settling": "{bot} का काम पूरा होते ही {name} खुलेगा",
+ "rail.settlingAny": "वहाँ का काम पूरा होते ही {name} खुलेगा",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "नाम बदलें",
+ "rail.renameSave": "सहेजें",
+ "rail.localRemove": "इस कंप्यूटर से हटाएँ",
+ "rail.localRemoveAsk": "“{name}” हटाएँ? इस कंप्यूटर पर इसके बॉट्स, चैट और फ़ाइलें मिट जाएँगी। पहले इसका फ़ोल्डर ट्रैश में जाएगा।",
+ "rail.localRemoveAskWin": "“{name}” हटाएँ? इस कंप्यूटर पर इसके बॉट्स, चैट और फ़ाइलें मिट जाएँगी। पहले इसका फ़ोल्डर रीसायकल बिन में जाएगा।",
+ "rail.localRemoveFailed": "यह हटाया नहीं गया। थोड़ी देर में फिर कोशिश करें।",
+ "native.menu.newLocal": "इस कंप्यूटर पर नया वर्कस्पेस…"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index 2e8c1e6de0..5a7f2b327a 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -521,6 +521,7 @@
"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.",
+ "homeLine.local": "{name} riparte da zero: uno spazio a parte su questo computer, con i suoi bot, chat e file.",
"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",
@@ -6528,5 +6529,27 @@
"email.needsGoogle": "Gmail richiede qui una password per le app (con la verifica in due passaggi attiva), oppure accedi con Google.",
"email.needsMicrosoft": "Outlook non accetta qui una password di posta: accedi con Microsoft.",
"email.needsAppPassword": "{provider} richiede qui una password per le app, non la tua password normale.",
- "serverError.mailbox.outgoingFields": "Controlla il server in uscita: un nome come mail.example.com, una porta da 1 a 65535 e SSL/TLS o STARTTLS."
+ "serverError.mailbox.outgoingFields": "Controlla il server in uscita: un nome come mail.example.com, una porta da 1 a 65535 e SSL/TLS o STARTTLS.",
+ "rail.addAny": "Aggiungi un posto per i tuoi bot",
+ "rail.searchAny": "Trova un posto",
+ "rail.local": "Nuovo spazio di lavoro su questo computer",
+ "rail.localSub": "Uno spazio a parte su questo computer, con i suoi bot, chat e file.",
+ "rail.localPreview": "Su questo computer",
+ "rail.localCreate": "Crea",
+ "rail.localTaken": "Un altro spazio qui ha già quel nome. Scegline un altro.",
+ "rail.localFailed": "Non ha funzionato. Riprova tra un momento.",
+ "rail.localWork": "Lavoro",
+ "rail.localPersonal": "Personale",
+ "rail.localNumbered": "Spazio di lavoro {count}",
+ "rail.localPlace": "{name}: uno spazio a parte su questo computer, con i suoi bot",
+ "rail.settling": "{name} si apre appena {bot} ha finito",
+ "rail.settlingAny": "{name} si apre appena finisce il lavoro in corso lì",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Rinomina",
+ "rail.renameSave": "Salva",
+ "rail.localRemove": "Rimuovi da questo computer",
+ "rail.localRemoveAsk": "Rimuovere “{name}”? I suoi bot, chat e file su questo computer vengono eliminati. Prima la sua cartella va nel Cestino.",
+ "rail.localRemoveAskWin": "Rimuovere “{name}”? I suoi bot, chat e file su questo computer vengono eliminati. Prima la sua cartella va nel Cestino.",
+ "rail.localRemoveFailed": "Non è stato rimosso. Riprova tra un momento.",
+ "native.menu.newLocal": "Nuovo spazio di lavoro su questo computer…"
}
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 4b0c04330c..51177fff7f 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -579,6 +579,7 @@
"rail.thisPc": "この PC",
"rail.profile": "{name}:このコンピューター上の別の場所で、専用のボットがあります。Cloud のボットは My Cloud にそのまま残ります。",
"homeLine.profile": "{name} は My Cloud とは別の、まっさらな場所です。以前ここにあったボットは My Cloud にあります。古いコピーを取り込むには、設定 → バックアップでそのバックアップをインポートしてください。",
+ "homeLine.local": "{name} はまっさらな状態から始まります。このコンピューター上の別の場所で、専用のボット、チャット、ファイルがあります。",
"native.places.profileFailed": "このコンピューター専用の場所を開けませんでした。少し待ってからもう一度お試しください。",
"rail.settingUp": "{name}: 準備中",
"rail.waiting": "{name}: 支払い待ち",
@@ -644,6 +645,27 @@
"rail.removeNo": "キャンセル",
"rail.removeRefused": "今は削除できません。再び稼働しているか、まだプランが残っています。",
"rail.removeFailed": "削除できませんでした。接続を確認して、もう一度お試しください。",
+ "rail.addAny": "ボットの場所を追加",
+ "rail.searchAny": "場所を検索",
+ "rail.local": "このコンピューターに新しいワークスペース",
+ "rail.localSub": "このコンピューター上の別の場所で、専用のボット、チャット、ファイルがあります。",
+ "rail.localPreview": "このコンピューター",
+ "rail.localCreate": "作成",
+ "rail.localTaken": "ここにある別の場所がその名前を使っています。別の名前にしてください。",
+ "rail.localFailed": "うまくいきませんでした。少ししてからもう一度お試しください。",
+ "rail.localWork": "仕事",
+ "rail.localPersonal": "個人",
+ "rail.localNumbered": "ワークスペース {count}",
+ "rail.localPlace": "{name}:このコンピューター上の別の場所で、専用のボットがあります",
+ "rail.settling": "{bot} の作業が終わると {name} が開きます",
+ "rail.settlingAny": "そちらの作業が終わると {name} が開きます",
+ "rail.cloudLabel": "{label}、Cloud",
+ "rail.rename": "名前を変更",
+ "rail.renameSave": "保存",
+ "rail.localRemove": "このコンピューターから削除",
+ "rail.localRemoveAsk": "「{name}」を削除しますか?このコンピューター上のボット、チャット、ファイルが削除されます。フォルダはまずゴミ箱に移動します。",
+ "rail.localRemoveAskWin": "「{name}」を削除しますか?このコンピューター上のボット、チャット、ファイルが削除されます。フォルダはまずごみ箱に移動します。",
+ "rail.localRemoveFailed": "削除できませんでした。少ししてからもう一度お試しください。",
"placeLook.title": "色",
"placeLook.sub": "{name} は、サイドバーの上部とアプリ左側のアイコンにこの色で表示されます。",
"placeLook.aria": "{name} の色",
@@ -7587,5 +7609,6 @@
"email.needsGoogle": "Gmail ではここでアプリ パスワード(2 段階認証プロセスを有効にしたもの)が必要です。または Google でサインインしてください。",
"email.needsMicrosoft": "Outlook はここでメールのパスワードを受け付けません。Microsoft でサインインしてください。",
"email.needsAppPassword": "{provider} ではここでアプリ パスワードが必要です。通常のパスワードは使えません。",
- "serverError.mailbox.outgoingFields": "送信サーバーを確認してください: mail.example.com のような名前、1〜65535 のポート、SSL/TLS または STARTTLS。"
+ "serverError.mailbox.outgoingFields": "送信サーバーを確認してください: mail.example.com のような名前、1〜65535 のポート、SSL/TLS または STARTTLS。",
+ "native.menu.newLocal": "このコンピューターに新しいワークスペース…"
}
diff --git a/src/locales/ko.json b/src/locales/ko.json
index 6dd62afd20..41307ad4d8 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -569,6 +569,7 @@
"rail.thisPc": "이 PC",
"rail.profile": "{name}: 이 컴퓨터의 별도 공간으로, 자체 봇이 있습니다. Cloud의 봇은 My Cloud에 그대로 있습니다.",
"homeLine.profile": "{name}은(는) My Cloud와 분리된 새 공간입니다. 이전에 여기 있던 봇은 My Cloud에 있습니다. 예전 사본을 가져오려면 설정 → 백업에서 그 백업을 가져오세요.",
+ "homeLine.local": "{name}은(는) 새로 시작합니다: 이 컴퓨터의 별도 공간으로, 자체 봇, 채팅, 파일이 있습니다.",
"native.places.profileFailed": "이 컴퓨터의 공간을 열지 못했습니다. 잠시 후 다시 시도하세요.",
"rail.settingUp": "{name}: 설정 중",
"rail.waiting": "{name}: 결제 대기 중",
@@ -7253,5 +7254,27 @@
"email.needsGoogle": "Gmail은 여기서 앱 비밀번호(2단계 인증 사용 시)가 필요합니다. 또는 Google로 로그인하세요.",
"email.needsMicrosoft": "Outlook은 여기서 메일 비밀번호를 받지 않습니다. Microsoft로 로그인하세요.",
"email.needsAppPassword": "{provider}은(는) 여기서 일반 비밀번호가 아닌 앱 비밀번호가 필요합니다.",
- "serverError.mailbox.outgoingFields": "보내는 서버를 확인하세요: mail.example.com 같은 이름, 1~65535 사이의 포트, SSL/TLS 또는 STARTTLS."
+ "serverError.mailbox.outgoingFields": "보내는 서버를 확인하세요: mail.example.com 같은 이름, 1~65535 사이의 포트, SSL/TLS 또는 STARTTLS.",
+ "rail.addAny": "봇을 위한 공간 추가",
+ "rail.searchAny": "공간 찾기",
+ "rail.local": "이 컴퓨터에 새 작업 공간",
+ "rail.localSub": "이 컴퓨터의 별도 공간으로, 자체 봇, 채팅, 파일이 있습니다.",
+ "rail.localPreview": "이 컴퓨터",
+ "rail.localCreate": "만들기",
+ "rail.localTaken": "여기 다른 공간이 이미 그 이름을 쓰고 있습니다. 다른 이름을 고르세요.",
+ "rail.localFailed": "잘 되지 않았습니다. 잠시 후 다시 시도하세요.",
+ "rail.localWork": "업무",
+ "rail.localPersonal": "개인",
+ "rail.localNumbered": "작업 공간 {count}",
+ "rail.localPlace": "{name}: 이 컴퓨터의 별도 공간으로, 자체 봇이 있습니다",
+ "rail.settling": "{bot}의 작업이 끝나면 {name}이(가) 열립니다",
+ "rail.settlingAny": "그곳의 작업이 끝나면 {name}이(가) 열립니다",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "이름 바꾸기",
+ "rail.renameSave": "저장",
+ "rail.localRemove": "이 컴퓨터에서 제거",
+ "rail.localRemoveAsk": "“{name}”을(를) 제거할까요? 이 컴퓨터에 있는 봇, 채팅, 파일이 삭제됩니다. 폴더는 먼저 휴지통으로 옮겨집니다.",
+ "rail.localRemoveAskWin": "“{name}”을(를) 제거할까요? 이 컴퓨터에 있는 봇, 채팅, 파일이 삭제됩니다. 폴더는 먼저 휴지통으로 옮겨집니다.",
+ "rail.localRemoveFailed": "제거되지 않았습니다. 잠시 후 다시 시도하세요.",
+ "native.menu.newLocal": "이 컴퓨터에 새 작업 공간…"
}
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 59917d3637..0bf1e13cfd 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -526,6 +526,7 @@
"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.",
+ "homeLine.local": "{name} zaczyna od zera: osobne miejsce na tym komputerze, z własnymi botami, czatami i plikami.",
"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ść",
@@ -6668,5 +6669,27 @@
"email.needsGoogle": "Gmail wymaga tu hasła do aplikacji (przy włączonej weryfikacji dwuetapowej) albo zaloguj się przez Google.",
"email.needsMicrosoft": "Outlook nie przyjmuje tu hasła do poczty: zaloguj się przez Microsoft.",
"email.needsAppPassword": "{provider} wymaga tu hasła do aplikacji, a nie zwykłego hasła.",
- "serverError.mailbox.outgoingFields": "Sprawdź serwer wychodzący: nazwa w rodzaju mail.example.com, port od 1 do 65535 oraz SSL/TLS lub STARTTLS."
+ "serverError.mailbox.outgoingFields": "Sprawdź serwer wychodzący: nazwa w rodzaju mail.example.com, port od 1 do 65535 oraz SSL/TLS lub STARTTLS.",
+ "rail.addAny": "Dodaj miejsce dla swoich botów",
+ "rail.searchAny": "Znajdź miejsce",
+ "rail.local": "Nowy obszar roboczy na tym komputerze",
+ "rail.localSub": "Osobne miejsce na tym komputerze, z własnymi botami, czatami i plikami.",
+ "rail.localPreview": "Na tym komputerze",
+ "rail.localCreate": "Utwórz",
+ "rail.localTaken": "Inne miejsce tutaj ma już tę nazwę. Wybierz inną.",
+ "rail.localFailed": "Nie udało się. Spróbuj ponownie za chwilę.",
+ "rail.localWork": "Praca",
+ "rail.localPersonal": "Prywatne",
+ "rail.localNumbered": "Obszar roboczy {count}",
+ "rail.localPlace": "{name}: osobne miejsce na tym komputerze, z własnymi botami",
+ "rail.settling": "{name} otworzy się, gdy {bot} skończy",
+ "rail.settlingAny": "{name} otworzy się, gdy skończy się tamtejsza praca",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Zmień nazwę",
+ "rail.renameSave": "Zapisz",
+ "rail.localRemove": "Usuń z tego komputera",
+ "rail.localRemoveAsk": "Usunąć „{name}”? Jego boty, czaty i pliki na tym komputerze zostaną usunięte. Najpierw jego folder trafi do Kosza.",
+ "rail.localRemoveAskWin": "Usunąć „{name}”? Jego boty, czaty i pliki na tym komputerze zostaną usunięte. Najpierw jego folder trafi do Kosza.",
+ "rail.localRemoveFailed": "Nie usunięto. Spróbuj ponownie za chwilę.",
+ "native.menu.newLocal": "Nowy obszar roboczy na tym komputerze…"
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 7dbe456ddf..26d21b0f06 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -636,6 +636,7 @@
"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.",
+ "homeLine.local": "{name} começa do zero: um lugar separado neste computador, com bots, conversas e arquivos próprios.",
"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",
@@ -701,6 +702,27 @@
"rail.removeNo": "Cancelar",
"rail.removeRefused": "Não é possível remover agora: ele voltou a funcionar ou ainda tem um plano.",
"rail.removeFailed": "Não foi removido. Confira a conexão e tente novamente.",
+ "rail.addAny": "Adicionar um lugar para seus bots",
+ "rail.searchAny": "Encontrar um lugar",
+ "rail.local": "Novo espaço de trabalho neste computador",
+ "rail.localSub": "Um lugar separado neste computador, com bots, conversas e arquivos próprios.",
+ "rail.localPreview": "Neste computador",
+ "rail.localCreate": "Criar",
+ "rail.localTaken": "Outro lugar aqui já tem esse nome. Escolha outro.",
+ "rail.localFailed": "Não deu certo. Tente de novo em instantes.",
+ "rail.localWork": "Trabalho",
+ "rail.localPersonal": "Pessoal",
+ "rail.localNumbered": "Espaço de trabalho {count}",
+ "rail.localPlace": "{name}: um lugar separado neste computador, com bots próprios",
+ "rail.settling": "{name} abre assim que {bot} terminar",
+ "rail.settlingAny": "{name} abre assim que o trabalho de lá terminar",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Renomear",
+ "rail.renameSave": "Salvar",
+ "rail.localRemove": "Remover deste computador",
+ "rail.localRemoveAsk": "Remover “{name}”? Os bots, conversas e arquivos dele neste computador são apagados. Antes, a pasta dele vai para o Lixo.",
+ "rail.localRemoveAskWin": "Remover “{name}”? Os bots, conversas e arquivos dele neste computador são apagados. Antes, a pasta dele vai para a Lixeira.",
+ "rail.localRemoveFailed": "Não foi removido. Tente de novo em instantes.",
"placeLook.title": "Cor",
"placeLook.sub": "{name} aparece nesta cor no topo da barra lateral e no ícone à esquerda do app.",
"placeLook.aria": "Cor de {name}",
@@ -8867,6 +8889,7 @@
"native.menu.addCloud": "Adicionar um Cloud…",
"native.menu.orgSignIn": "Entrar com a conta da sua organização…",
"native.menu.connect": "Conectar a um servidor…",
+ "native.menu.newLocal": "Novo espaço de trabalho neste computador…",
"native.menu.preferences": "Configurações…",
"native.role.about": "Sobre {app}",
"native.role.hide": "Ocultar {app}",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 8e5359193a..6b7e9ed93a 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -526,6 +526,7 @@
"rail.thisPc": "Этот ПК",
"rail.profile": "{name}: отдельное место на этом компьютере со своими ботами. Боты вашего Cloud остаются в My Cloud.",
"homeLine.profile": "{name} начинается с чистого листа, отдельно от My Cloud. Боты, которые были здесь, находятся в My Cloud; чтобы вернуть старую копию, импортируйте её резервную копию в Настройки → Резервные копии.",
+ "homeLine.local": "{name} начинается с чистого листа: отдельное место на этом компьютере со своими ботами, чатами и файлами.",
"native.places.profileFailed": "Не удалось открыть место этого компьютера. Повторите попытку чуть позже.",
"rail.settingUp": "{name}: настраивается",
"rail.waiting": "{name}: ждёт оплаты",
@@ -6730,5 +6731,27 @@
"email.needsGoogle": "Gmail требует здесь пароль приложения (при включённой двухэтапной аутентификации) — или войдите через Google.",
"email.needsMicrosoft": "Outlook не принимает здесь пароль от почты: войдите через Microsoft.",
"email.needsAppPassword": "{provider} требует здесь пароль приложения, а не обычный пароль.",
- "serverError.mailbox.outgoingFields": "Проверьте сервер исходящей почты: имя вроде mail.example.com, порт от 1 до 65535 и SSL/TLS или STARTTLS."
+ "serverError.mailbox.outgoingFields": "Проверьте сервер исходящей почты: имя вроде mail.example.com, порт от 1 до 65535 и SSL/TLS или STARTTLS.",
+ "rail.addAny": "Добавить место для ботов",
+ "rail.searchAny": "Найти место",
+ "rail.local": "Новое рабочее пространство на этом компьютере",
+ "rail.localSub": "Отдельное место на этом компьютере со своими ботами, чатами и файлами.",
+ "rail.localPreview": "На этом компьютере",
+ "rail.localCreate": "Создать",
+ "rail.localTaken": "Другое место здесь уже так называется. Выберите другое название.",
+ "rail.localFailed": "Не получилось. Попробуйте ещё раз чуть позже.",
+ "rail.localWork": "Работа",
+ "rail.localPersonal": "Личное",
+ "rail.localNumbered": "Рабочее пространство {count}",
+ "rail.localPlace": "{name}: отдельное место на этом компьютере со своими ботами",
+ "rail.settling": "{name} откроется, когда {bot} закончит",
+ "rail.settlingAny": "{name} откроется, когда там закончится работа",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Переименовать",
+ "rail.renameSave": "Сохранить",
+ "rail.localRemove": "Удалить с этого компьютера",
+ "rail.localRemoveAsk": "Удалить «{name}»? Его боты, чаты и файлы на этом компьютере будут удалены. Сначала его папка попадёт в Корзину.",
+ "rail.localRemoveAskWin": "Удалить «{name}»? Его боты, чаты и файлы на этом компьютере будут удалены. Сначала его папка попадёт в Корзину.",
+ "rail.localRemoveFailed": "Не удалось удалить. Попробуйте ещё раз чуть позже.",
+ "native.menu.newLocal": "Новое рабочее пространство на этом компьютере…"
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index df187120f4..ca5b1df5c0 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5118,6 +5118,7 @@
"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.",
+ "homeLine.local": "{name} sıfırdan başlar: bu bilgisayarda kendi botları, sohbetleri ve dosyaları olan ayrı bir alan.",
"native.places.profileFailed": "Bu bilgisayarın kendi alanı açılmadı. Birazdan tekrar deneyin.",
"rail.settingUp": "{name}: kuruluyor",
"rail.waiting": "{name}: ödeme bekleniyor",
@@ -5389,5 +5390,27 @@
"email.needsGoogle": "Gmail burada bir uygulama şifresi ister (2 Adımlı Doğrulama açıkken) ya da Google ile oturum açın.",
"email.needsMicrosoft": "Outlook burada e-posta şifresi kabul etmiyor: Microsoft ile oturum açın.",
"email.needsAppPassword": "{provider} burada normal şifrenizi değil, bir uygulama şifresi ister.",
- "serverError.mailbox.outgoingFields": "Giden sunucuyu kontrol edin: mail.example.com gibi bir ad, 1 ile 65535 arasında bir bağlantı noktası ve SSL/TLS veya STARTTLS."
+ "serverError.mailbox.outgoingFields": "Giden sunucuyu kontrol edin: mail.example.com gibi bir ad, 1 ile 65535 arasında bir bağlantı noktası ve SSL/TLS veya STARTTLS.",
+ "rail.addAny": "Botların için bir yer ekle",
+ "rail.searchAny": "Bir yer bul",
+ "rail.local": "Bu bilgisayarda yeni çalışma alanı",
+ "rail.localSub": "Bu bilgisayarda kendi botları, sohbetleri ve dosyaları olan ayrı bir alan.",
+ "rail.localPreview": "Bu bilgisayarda",
+ "rail.localCreate": "Oluştur",
+ "rail.localTaken": "Buradaki başka bir alan bu adı kullanıyor. Başka bir ad seçin.",
+ "rail.localFailed": "Olmadı. Birazdan tekrar deneyin.",
+ "rail.localWork": "İş",
+ "rail.localPersonal": "Kişisel",
+ "rail.localNumbered": "Çalışma alanı {count}",
+ "rail.localPlace": "{name}: bu bilgisayarda kendi botları olan ayrı bir alan",
+ "rail.settling": "{bot} bitirince {name} açılır",
+ "rail.settlingAny": "Oradaki iş bitince {name} açılır",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Yeniden adlandır",
+ "rail.renameSave": "Kaydet",
+ "rail.localRemove": "Bu bilgisayardan kaldır",
+ "rail.localRemoveAsk": "“{name}” kaldırılsın mı? Bu bilgisayardaki botları, sohbetleri ve dosyaları silinir. Klasörü önce Çöp Sepeti'ne gider.",
+ "rail.localRemoveAskWin": "“{name}” kaldırılsın mı? Bu bilgisayardaki botları, sohbetleri ve dosyaları silinir. Klasörü önce Geri Dönüşüm Kutusu'na gider.",
+ "rail.localRemoveFailed": "Kaldırılamadı. Birazdan tekrar deneyin.",
+ "native.menu.newLocal": "Bu bilgisayarda yeni çalışma alanı…"
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index 08468dd759..2e5f6da244 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -3124,6 +3124,7 @@
"rail.thisPc": "Цей ПК",
"rail.profile": "{name}: окреме місце на цьому комп'ютері з власними ботами. Боти вашого Cloud залишаються в My Cloud.",
"homeLine.profile": "{name} починається з чистого аркуша, окремо від My Cloud. Боти, які були тут, тепер у My Cloud; щоб повернути старішу копію, імпортуйте її резервну копію в Налаштування → Резервні копії.",
+ "homeLine.local": "{name} починається з чистого аркуша: окреме місце на цьому комп'ютері з власними ботами, чатами й файлами.",
"native.places.profileFailed": "Не вдалося відкрити місце цього комп'ютера. Спробуйте ще раз за мить.",
"rail.settingUp": "{name}: налаштовується",
"rail.waiting": "{name}: чекає на оплату",
@@ -3399,5 +3400,27 @@
"email.needsGoogle": "Gmail потребує тут пароль застосунку (з увімкненою двоетапною перевіркою) — або увійдіть через Google.",
"email.needsMicrosoft": "Outlook не приймає тут пароль від пошти: увійдіть через Microsoft.",
"email.needsAppPassword": "{provider} потребує тут пароль застосунку, а не звичайний пароль.",
- "serverError.mailbox.outgoingFields": "Перевірте сервер вихідної пошти: назва на кшталт mail.example.com, порт від 1 до 65535 і SSL/TLS або STARTTLS."
+ "serverError.mailbox.outgoingFields": "Перевірте сервер вихідної пошти: назва на кшталт mail.example.com, порт від 1 до 65535 і SSL/TLS або STARTTLS.",
+ "rail.addAny": "Додати місце для ботів",
+ "rail.searchAny": "Знайти місце",
+ "rail.local": "Новий робочий простір на цьому комп'ютері",
+ "rail.localSub": "Окреме місце на цьому комп'ютері з власними ботами, чатами й файлами.",
+ "rail.localPreview": "На цьому комп'ютері",
+ "rail.localCreate": "Створити",
+ "rail.localTaken": "Інше місце тут уже має таку назву. Виберіть іншу.",
+ "rail.localFailed": "Не вдалося. Спробуйте ще раз за мить.",
+ "rail.localWork": "Робота",
+ "rail.localPersonal": "Особисте",
+ "rail.localNumbered": "Робочий простір {count}",
+ "rail.localPlace": "{name}: окреме місце на цьому комп'ютері з власними ботами",
+ "rail.settling": "{name} відкриється, щойно {bot} завершить",
+ "rail.settlingAny": "{name} відкриється, щойно там завершиться робота",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Перейменувати",
+ "rail.renameSave": "Зберегти",
+ "rail.localRemove": "Видалити з цього комп'ютера",
+ "rail.localRemoveAsk": "Видалити «{name}»? Його боти, чати й файли на цьому комп'ютері буде видалено. Спершу його папка потрапить у Кошик.",
+ "rail.localRemoveAskWin": "Видалити «{name}»? Його боти, чати й файли на цьому комп'ютері буде видалено. Спершу його папка потрапить у Кошик.",
+ "rail.localRemoveFailed": "Не вдалося видалити. Спробуйте ще раз за мить.",
+ "native.menu.newLocal": "Новий робочий простір на цьому комп'ютері…"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 1b1b57cdd5..ee22f1bdfe 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5118,6 +5118,7 @@
"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.",
+ "homeLine.local": "{name} bắt đầu mới hoàn toàn: một nơi riêng trên máy tính này, có bot, cuộc trò chuyện và tệp riêng.",
"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",
@@ -5389,5 +5390,27 @@
"email.needsGoogle": "Gmail cần mật khẩu ứng dụng ở đây (khi đã bật xác minh 2 bước), hoặc đăng nhập bằng Google.",
"email.needsMicrosoft": "Outlook không nhận mật khẩu thư ở đây: hãy đăng nhập bằng Microsoft.",
"email.needsAppPassword": "{provider} cần mật khẩu ứng dụng ở đây, không phải mật khẩu thường của bạn.",
- "serverError.mailbox.outgoingFields": "Hãy kiểm tra máy chủ thư đi: một tên như mail.example.com, cổng từ 1 đến 65535, và SSL/TLS hoặc STARTTLS."
+ "serverError.mailbox.outgoingFields": "Hãy kiểm tra máy chủ thư đi: một tên như mail.example.com, cổng từ 1 đến 65535, và SSL/TLS hoặc STARTTLS.",
+ "rail.addAny": "Thêm một nơi cho bot của bạn",
+ "rail.searchAny": "Tìm một nơi",
+ "rail.local": "Không gian làm việc mới trên máy tính này",
+ "rail.localSub": "Một nơi riêng trên máy tính này, có bot, cuộc trò chuyện và tệp riêng.",
+ "rail.localPreview": "Trên máy tính này",
+ "rail.localCreate": "Tạo",
+ "rail.localTaken": "Một nơi khác ở đây đã dùng tên này. Hãy chọn tên khác.",
+ "rail.localFailed": "Không được. Hãy thử lại sau giây lát.",
+ "rail.localWork": "Công việc",
+ "rail.localPersonal": "Cá nhân",
+ "rail.localNumbered": "Không gian làm việc {count}",
+ "rail.localPlace": "{name}: một nơi riêng trên máy tính này, có bot riêng",
+ "rail.settling": "{name} sẽ mở khi {bot} xong việc",
+ "rail.settlingAny": "{name} sẽ mở khi việc ở đó xong",
+ "rail.cloudLabel": "{label}, Cloud",
+ "rail.rename": "Đổi tên",
+ "rail.renameSave": "Lưu",
+ "rail.localRemove": "Xóa khỏi máy tính này",
+ "rail.localRemoveAsk": "Xóa “{name}”? Bot, cuộc trò chuyện và tệp của nó trên máy tính này sẽ bị xóa. Thư mục của nó sẽ được chuyển vào Thùng rác trước.",
+ "rail.localRemoveAskWin": "Xóa “{name}”? Bot, cuộc trò chuyện và tệp của nó trên máy tính này sẽ bị xóa. Thư mục của nó sẽ được chuyển vào Thùng rác trước.",
+ "rail.localRemoveFailed": "Chưa xóa được. Hãy thử lại sau giây lát.",
+ "native.menu.newLocal": "Không gian làm việc mới trên máy tính này…"
}
diff --git a/src/locales/words.test.ts b/src/locales/words.test.ts
index 9b585d9814..395a62bcc9 100644
--- a/src/locales/words.test.ts
+++ b/src/locales/words.test.ts
@@ -4,9 +4,13 @@ import { expect, it } from "vitest";
import en from "./en.json";
+/** A workspace of this computer's own is the owner's own word for what + adds to the rail: the choice, its first names and
+ * the Server menu's entry. */
+const OWNER_WORKSPACE = new Set(["rail.local", "rail.localNumbered", "native.menu.newLocal"]);
+
it("English copy says Organization and installation, not Organisation or workspace", () => {
const offending = Object.entries(en)
- .filter(([, value]) => /organis/i.test(value) || /(?<!Slack )\bworkspaces?\b/i.test(value))
+ .filter(([key, value]) => /organis/i.test(value) || (!OWNER_WORKSPACE.has(key) && /(?<!Slack )\bworkspaces?\b/i.test(value)))
.map(([key]) => key);
expect(offending).toEqual([]);
});
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 6c177a3391..ceb4832654 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4509,6 +4509,7 @@
"rail.thisPc": "這台 PC",
"rail.profile": "{name}:這台電腦上的獨立空間,有自己的機器人。你的 Cloud 裡的機器人仍在 My Cloud。",
"homeLine.profile": "{name} 是一個全新的、與 My Cloud 分開的空間。你之前在這裡的機器人都在 My Cloud;要找回舊的副本,請在 設定 → 備份 中匯入它的備份。",
+ "homeLine.local": "{name} 從頭開始:這台電腦上的獨立空間,有自己的機器人、對話和檔案。",
"native.places.profileFailed": "這台電腦自己的空間沒能開啟。請稍後再試。",
"rail.settingUp": "{name}:設定中",
"rail.waiting": "{name}:等待付款",
@@ -4781,5 +4782,27 @@
"email.needsGoogle": "Gmail 在這裡需要應用程式密碼(需開啟兩步驟驗證),或使用 Google 登入。",
"email.needsMicrosoft": "Outlook 在這裡不接受郵件密碼:請使用 Microsoft 登入。",
"email.needsAppPassword": "{provider} 在這裡需要應用程式密碼,而不是你平常的密碼。",
- "serverError.mailbox.outgoingFields": "請檢查外寄伺服器:名稱如 mail.example.com、1 到 65535 之間的連接埠,以及 SSL/TLS 或 STARTTLS。"
+ "serverError.mailbox.outgoingFields": "請檢查外寄伺服器:名稱如 mail.example.com、1 到 65535 之間的連接埠,以及 SSL/TLS 或 STARTTLS。",
+ "rail.addAny": "為你的機器人新增一個地方",
+ "rail.searchAny": "尋找地方",
+ "rail.local": "在這台電腦上新增工作區",
+ "rail.localSub": "這台電腦上的獨立空間,有自己的機器人、對話和檔案。",
+ "rail.localPreview": "在這台電腦上",
+ "rail.localCreate": "建立",
+ "rail.localTaken": "這裡已有其他地方使用這個名稱,請換一個。",
+ "rail.localFailed": "沒有成功,請稍後再試。",
+ "rail.localWork": "工作",
+ "rail.localPersonal": "個人",
+ "rail.localNumbered": "工作區 {count}",
+ "rail.localPlace": "{name}:這台電腦上的獨立空間,有自己的機器人",
+ "rail.settling": "{bot} 完成後就會開啟 {name}",
+ "rail.settlingAny": "那邊的工作完成後就會開啟 {name}",
+ "rail.cloudLabel": "{label},Cloud",
+ "rail.rename": "重新命名",
+ "rail.renameSave": "儲存",
+ "rail.localRemove": "從這台電腦移除",
+ "rail.localRemoveAsk": "要移除「{name}」嗎?它在這台電腦上的機器人、對話和檔案都會被刪除。它的資料夾會先移到垃圾桶。",
+ "rail.localRemoveAskWin": "要移除「{name}」嗎?它在這台電腦上的機器人、對話和檔案都會被刪除。它的資料夾會先移到資源回收筒。",
+ "rail.localRemoveFailed": "沒有移除,請稍後再試。",
+ "native.menu.newLocal": "在這台電腦上新增工作區…"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 6cc9873d1e..0590af504d 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -577,6 +577,7 @@
"rail.thisPc": "这台 PC",
"rail.profile": "{name}:这台电脑上的独立空间,有自己的机器人。你的 Cloud 里的机器人仍在 My Cloud。",
"homeLine.profile": "{name} 是一个全新的、与 My Cloud 分开的空间。你之前在这里的机器人都在 My Cloud;要找回旧的副本,请在 设置 → 备份 中导入它的备份。",
+ "homeLine.local": "{name} 从头开始:这台电脑上的独立空间,有自己的机器人、对话和文件。",
"native.places.profileFailed": "这台电脑自己的空间没能打开。请稍后再试。",
"rail.settingUp": "{name}:设置中",
"rail.waiting": "{name}:等待付款",
@@ -638,6 +639,27 @@
"rail.removeNo": "取消",
"rail.removeRefused": "现在无法移除:它又在运行了,或者还有未结束的方案。",
"rail.removeFailed": "未能移除。请检查网络连接后重试。",
+ "rail.addAny": "为你的机器人添加一个地方",
+ "rail.searchAny": "查找地方",
+ "rail.local": "在这台电脑上新建工作区",
+ "rail.localSub": "这台电脑上的独立空间,有自己的机器人、对话和文件。",
+ "rail.localPreview": "在这台电脑上",
+ "rail.localCreate": "创建",
+ "rail.localTaken": "这里已有其他地方使用这个名称,请换一个。",
+ "rail.localFailed": "没有成功,请稍后再试。",
+ "rail.localWork": "工作",
+ "rail.localPersonal": "个人",
+ "rail.localNumbered": "工作区 {count}",
+ "rail.localPlace": "{name}:这台电脑上的独立空间,有自己的机器人",
+ "rail.settling": "{bot} 完成后就会打开 {name}",
+ "rail.settlingAny": "那边的工作完成后就会打开 {name}",
+ "rail.cloudLabel": "{label},Cloud",
+ "rail.rename": "重命名",
+ "rail.renameSave": "保存",
+ "rail.localRemove": "从这台电脑移除",
+ "rail.localRemoveAsk": "要移除「{name}」吗?它在这台电脑上的机器人、对话和文件都会被删除。它的文件夹会先移到废纸篓。",
+ "rail.localRemoveAskWin": "要移除「{name}」吗?它在这台电脑上的机器人、对话和文件都会被删除。它的文件夹会先移到回收站。",
+ "rail.localRemoveFailed": "没有移除,请稍后再试。",
"placeLook.title": "颜色",
"placeLook.sub": "{name} 会以这个颜色显示在侧栏顶部,以及应用左侧它的图标上。",
"placeLook.aria": "{name} 的颜色",
@@ -7473,5 +7495,6 @@
"email.needsGoogle": "Gmail 在这里需要应用专用密码(需开启两步验证),或使用 Google 登录。",
"email.needsMicrosoft": "Outlook 在这里不接受邮箱密码:请使用 Microsoft 登录。",
"email.needsAppPassword": "{provider} 在这里需要应用专用密码,而不是你的常用密码。",
- "serverError.mailbox.outgoingFields": "请检查发件服务器:名称如 mail.example.com,端口在 1 到 65535 之间,以及 SSL/TLS 或 STARTTLS。"
+ "serverError.mailbox.outgoingFields": "请检查发件服务器:名称如 mail.example.com,端口在 1 到 65535 之间,以及 SSL/TLS 或 STARTTLS。",
+ "native.menu.newLocal": "在这台电脑上新建工作区…"
}
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 7a5aec20c1..e47c418d05 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -162,13 +162,14 @@ 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; `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 }>;
+ * computer's own; `profile`: this computer's page is a profile of its own (This Mac), by its id, and
+ * `profileName` its own name when it has one (a workspace added from +). */
+ state: () => Promise<{ local: boolean; name: string; origin?: string; color?: string; home?: boolean; role?: string; localPath?: string; profile?: string; profileName?: 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: 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>;
+ line?: () => Promise<{ kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile"; name?: string } | null>;
/** The rail's circles, for this app's page and a hosted Cloud's only (empty elsewhere, and with fewer than two
* places). Absent on an older app. */
places?: () => Promise<import("../../electron/cloud-rail.mjs").RailState>;
@@ -193,6 +194,16 @@ const __APP_VERSION__: string;
makeHome?: (id: string) => Promise<{ started: true }>;
/** Main's word that the places or the sign-in changed: read them again. */
onChanged?: (callback: () => void) => () => void;
+ /** A workspace of this computer's own (main refuses any page but the rail's and this computer's own): a new one,
+ * which main opens next; a name or colour for one the rail lists; its removal, once the person said yes. Absent on
+ * an older app. */
+ local?: {
+ create(name: string, color: import("../../electron/cloud-list.mjs").CloudSwatch | null): Promise<{ outcome: "made"; id: string } | { outcome: "name" | "taken" | "failed" }>;
+ edit(id: string, changes: { name: string } | { color: import("../../electron/cloud-list.mjs").CloudSwatch | null }): Promise<{ outcome: "saved" | "name" | "taken" | "full" | "gone" }>;
+ remove(id: string): Promise<{ outcome: "removed" | "gone" | "failed" }>;
+ };
+ /** The Server menu's New workspace on this computer: this computer's own page asks its name. */
+ onNewLocal?: (callback: () => void) => () => void;
};
/** Buying another Cloud from the rail's +, on this app's page or a hosted Cloud's; absent on an older app. */
cloudAdd?: {