Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge main into the account switcher, and the rail becomes the switcher
milind-sonia1fcfce954ff
diff --cc electron/account-places.mjsindex 5453e6cf5c,b42d167727..f106caeb15--- a/electron/account-places.mjs+++ b/electron/account-places.mjs@@@ -25,25 -34,3 +34,26 @@@ export async function clearPlaceStorageawait Promise.all(places.filter((entry) => entry.origin).map((entry) => session.clearStorageData({ origin: entry.origin, storages: [...(entry.team ? SHARED_STORAGE : OWN_STORAGE)] }).catch((error) => log(`accounts: could not clear what the window kept for a place (${error?.message ?? error})`))));}+- /** Each account's places while it waits, kept as they were (the same ids, so what was lent to them and their colours come- * back with them). `store`: a JSON file of names and addresses, no secret. */++/** Each account's places while it waits: as they were saved (`places`, the same ids, so what was lent to them and their colours++ * come back with them), and as the rail showed them (`rows`). `store`: a JSON file of names and addresses, no secret. */+export function createPlaceStash(store) {+ const all = () => { try { const value = store.read(); return value && typeof value === "object" && !Array.isArray(value) ? value : {}; } catch { return {}; } };++ const one = (kept) => ({ places: Array.isArray(kept?.places) ? kept.places : [], rows: Array.isArray(kept?.rows) ? kept.rows : [] });+ return {- put(accountId, places) { if (accountId) store.write({ ...all(), [accountId]: places }); },++ put(accountId, places, rows = []) { if (accountId) store.write({ ...all(), [accountId]: { places, rows } }); },+ take(accountId) {- const kept = all(), places = Array.isArray(kept[accountId]) ? kept[accountId] : [];++ const kept = all();+ if (accountId in kept) { const { [accountId]: _, ...rest } = kept; store.write(rest); }- return places;++ return one(kept[accountId]);+ },- peek: (accountId) => { const places = all()[accountId]; return Array.isArray(places) ? places : []; },++ peek: (accountId) => one(all()[accountId]),+ };+}++/** The saved places with an account's kept ones back; one saved here meanwhile under the same address stays as it is. */+export function withPlacesBack(saved, places) {+ const origins = new Set(saved.environments.map((entry) => entry.origin).filter(Boolean)), ids = new Set(saved.environments.map((entry) => entry.id));+ const back = places.filter((entry) => !origins.has(entry.origin) && !ids.has(entry.id));+ return back.length ? { ...saved, environments: [...saved.environments, ...back] } : saved;+}diff --cc electron/accounts-main.mjsindex 409628474d,a3816fb1db..f28aa2e8c7--- a/electron/accounts-main.mjs+++ b/electron/accounts-main.mjs@@@ -1,54 -1,32 +1,68 @@@--// Who is signed in on this device, for the You menu. The list goes only to this app's own pages: this computer's and the--// rail's. A Cloud's or a server's page never reads it, because it would learn the addresses of the person's other accounts;--// it may only ask main, from the person's click, to open the sheet on the rail's page.- import { clearPlaceStorage, createPlaceStash, withoutAccountPlaces, withPlacesBack } from "./account-places.mjs";-import { accountPlaces, clearPlaceStorage, withoutPlaces } from "./account-places.mjs";++// Who is signed in on this device, for the You menu: the account in use, by its address, and only on this app's own pages. The++// accounts that wait show on the rail (rail-accounts.mjs), whose page is the only one that learns their addresses. A Cloud's or a++// server's page never reads any of it; it may only ask main, from the person's click, to open the sheet on the rail's page.++import { accountPlaces, clearPlaceStorage, createPlaceStash, withoutPlaces, withPlacesBack } from "./account-places.mjs";+import { createCloudAccounts } from "./cloud-accounts.mjs";++import { accountRows } from "./rail-accounts.mjs";- /** The accounts as the You menu shows them: never a token, and no active account while none is signed in. */- export function accountsView(state, others = []) {+ /** The sign-in as the You menu shows it: never a token, and no account while none is signed in. */+ export function accountsView(state) {const account = state?.account;- const active = account?.id && state.status !== "signed-out" && state.status !== "connecting"- ? { id: account.id, email: account.email, ...(state.status === "reauth-required" ? { signIn: true } : {}) } : null;- return { active, others: others.filter((row) => row.id !== active?.id) };- if (!account?.id || state.status === "signed-out" || state.status === "connecting") return { active: null, others: [] };- return { active: { id: account.id, email: account.email, ...(state.status === "reauth-required" ? { signIn: true } : {}) }, others: [] };++ if (!account?.id || state.status === "signed-out" || state.status === "connecting") return { active: null };++ return { active: { id: account.id, email: account.email, ...(state.status === "reauth-required" ? { signIn: true } : {}) } };}- /** Everything of the account this window held: its places leave the list and wait in `keep` (or go, signing out), the window- * leaves them, and their sessions go. */- export function createAccountLeave({ saved, persist, session, mine, leaveWindow, keep = () => {}, log = () => {} }) {- return async (accountId = null) => {- const { saved: next, left } = withoutAccountPlaces(saved(), mine());- if (left.length) { keep(accountId, left); persist(next); }- await leaveWindow();- await clearPlaceStorage(session(), left, log);- return left;+ /** Everything of the account this window held. `places()` names them while the sign-in still says which Cloud is My Cloud:+ * a My Cloud saved by hand carries no other mark, and the sign-in names none once it has ended. `finish(left)`, once it has:+ * they leave the list, the window leaves them, and once nothing is still waiting on them (`settled`) their sessions go. */+ export function createAccountLeave({ saved, persist, session, mine, leaveWindow, settled = async () => {}, log = () => {} }) {+ return {+ places: () => accountPlaces(saved(), mine()),+ async finish(left) {+ const next = withoutPlaces(saved(), left);+ if (next !== saved()) persist(next);+ await leaveWindow();+ await settled();+ await clearPlaceStorage(session(), left, log);+ return left;+ },};}+/**+ * The accounts as main keeps them, made on first use, and what a change of account does to the rest of this app.+ * @param {{+ * allowed(): boolean, active(): any, savedStore(): any, stash(): { read(): unknown, write(value: unknown): void }, client(): any, origin: string,+ * makeClient(options: { store: any, onState(state: any): void }): any,- * saved(): any, persist(next: unknown): void, session(): any, mine(): string | null, leaveWindow(): unknown,- * holding(): string | null, letGo(accountId: string | null): void, settled(): Promise<unknown>, forgetLending(place: any): void, tell(): void, log?(line: string): void,- * }} deps `letGo(id)`: what runs for that account in the window and for lending stops; `forgetLending(place)`: that place is off- * this device with its account.++ * saved(): any, persist(next: unknown): void, session(): any, mine(): string | null, leaveWindow(): unknown, rows(): any[],++ * holding(): string | null, letGo(accountId: string | null): void, lendingDone(): Promise<unknown>, settled(): Promise<unknown>, forgetLending(place: any): void, tell(): void, log?(line: string): void,++ * }} deps `letGo(id)`: what runs for that account in the window and for lending stops; `lendingDone`: lending's last requests have++ * been answered; `rows`: the rail as it is now, kept for while the account waits; `forgetLending(place)`: that place is off this++ * device with its account.+ */+export function createDesktopRing(deps) {- let made = null, stash = null;++ let made = null, stash = null, leavingNow = null;+ const places = () => (stash ??= createPlaceStash(deps.stash()));- const leave = createAccountLeave({ saved: deps.saved, persist: deps.persist, session: deps.session, mine: deps.mine, leaveWindow: deps.leaveWindow, keep: (id, left) => places().put(id, left), log: deps.log });++ const leave = createAccountLeave({ saved: deps.saved, persist: deps.persist, session: deps.session, mine: deps.mine, leaveWindow: deps.leaveWindow, settled: deps.lendingDone, log: deps.log });+ const ring = () => {+ if (!deps.allowed()) return null;+ return made ??= createCloudAccounts({ active: deps.active(), saved: deps.savedStore(), client: deps.client, makeClient: deps.makeClient, origin: deps.origin, holding: deps.holding, settled: deps.settled, changed: deps.tell, log: deps.log,- leaving: async (id) => { deps.letGo(id); await leave(id); },- arriving: async (id) => { deps.persist(withPlacesBack(deps.saved(), places().take(id))); },- removed: async (id) => { for (const place of places().take(id)) deps.forgetLending(place); } });++ leaving: async (id) => { deps.letGo(id); leavingNow = { left: leave.places(), rows: accountRows(deps.rows()) }; },++ left: async (id) => {++ const { left, rows } = leavingNow ?? { left: [], rows: [] };++ leavingNow = null;++ places().put(id, left, rows);++ await leave.finish(left);++ },++ arriving: async (id) => { deps.persist(withPlacesBack(deps.saved(), places().take(id).places)); },++ removed: async (id) => { for (const place of places().take(id).places) deps.forgetLending(place); } });+ };++ /** The accounts that wait, with their places as they were kept: for the rail's own page only. */++ ring.waiting = () => (ring()?.others() ?? []).map((row) => ({ ...row, ...places().peek(row.id) }));+ ring.close = () => made?.close();+ return ring;+}+/*** @param {{* ipcMain: { handle(channel: string, handler: (event: unknown, ...args: any[]) => unknown): void },@@@ -56,37 -34,40 +70,35 @@@* placePage(event: unknown): boolean,* account(): { state(): any } | null,* client(): { state(): any, signOut(): Promise<any> },+ * ring(): ReturnType<typeof import("./cloud-accounts.mjs").createCloudAccounts> | null,* holdSheet(open: boolean): void,* tellSheet(): void,- * leaving(): void,- * leave: ReturnType<typeof createAccountLeave>,- * show(): Promise<unknown>,* tell(): void,* }} deps `ownPage`: this app's own page in the window, or the rail's. `placePage`: the page of a place of the person's own- * or their team's, which may offer the sheet. `holdSheet`: the rail's page stays up for the sheet, even for someone who hid- * the rail. `leaving`: the home window lets go of what it was doing for this account; `leave`: createAccountLeave's;- * `show`: the window goes where it belongs now; `tell`: this app's pages read the list again.+ * or their team's, which may offer the sheet. `ring`: the accounts kept on this device. `holdSheet`: the rail's page stays up+ * for the sheet, even for someone who hid the rail. `tell`: this app's pages read the list again.*/-export function installAccounts({ ipcMain, ownPage, placePage, account, client, holdSheet, tellSheet, leaving, leave, show, tell }) {- let sheetPending = false, queue = Promise.resolve();+export function installAccounts({ ipcMain, ownPage, placePage, account, client, ring, holdSheet, tellSheet, tell }) {+ let sheetPending = false;- const view = () => accountsView(account()?.state(), ring()?.others() ?? []);- const answered = async (work) => {- try { return { ...await work(), view: view() }; }- catch { return { outcome: "failed", view: view() }; }- };+ const view = () => accountsView(account()?.state());- const serial = (work) => { const run = queue.then(work, work); queue = run.catch(() => {}); return run; };const own = (channel, handler) => ipcMain.handle(channel, (event, ...args) => {if (!ownPage(event)) throw new Error(`${channel} is only available on this app's own page`);return handler(...args);});- const signOutActive = () => serial(async () => {- leaving();- const left = leave.places();- const after = await client().signOut();- await leave.finish(left);- await show();- tell();- return after;- });+ const text = (value, max) => (typeof value === "string" ? value.slice(0, max) : "");own("accounts:list", view);- own("accounts:switch", (id) => answered(() => ring().switchTo(text(id, 128))));- own("accounts:sign-out", (id) => answered(() => ring().signOut(text(id, 128))));+ own("accounts:sign-out", async (id) => {- if (view().active?.id !== id) throw new Error("That account isn't signed in here any more.");- await signOutActive();- return view();++ try { return { ...await ring().signOut(text(id, 128)), view: view() }; }++ catch { return { outcome: "failed", view: view() }; }++ });+ own("accounts:add-start", (email) => ring().addStart(text(email, 254)));+ own("accounts:add-verify", async (code) => {+ const result = await ring().addVerify(text(code, 16));+ return "email" in result || ["switched", "added", "already"].includes(result.outcome) ? { ...result, view: view() } : result;});+ own("accounts:add-browser", () => ring().addBrowser());+ own("accounts:add-reopen", () => ring().addReopen());+ own("accounts:add-cancel", () => ring().addCancel());own("accounts:sheet-pending", () => { const pending = sheetPending; sheetPending = false; return pending; });own("accounts:sheet-closed", () => { sheetPending = false; holdSheet(false); });ipcMain.handle("accounts:offered", (event) => placePage(event) === true);diff --cc electron/accounts-main.node-test.mjsindex d154e357fb,1270b13c19..549bf99697--- a/electron/accounts-main.node-test.mjs+++ b/electron/accounts-main.node-test.mjs@@@ -1,7 -1,8 +1,8 @@@import assert from "node:assert/strict";+ import { readFileSync } from "node:fs";import test from "node:test";- import { accountPlace, clearPlaceStorage, createPlaceStash, withoutAccountPlaces, withPlacesBack } from "./account-places.mjs";-import { accountPlace, accountPlaces, clearPlaceStorage, withoutAccountPlaces, withoutPlaces } from "./account-places.mjs";--import { accountsView, createAccountLeave, installAccounts } from "./accounts-main.mjs";++import { accountPlace, accountPlaces, clearPlaceStorage, createPlaceStash, withoutAccountPlaces, withoutPlaces, withPlacesBack } from "./account-places.mjs";++import { accountsView, createAccountLeave, createDesktopRing, installAccounts } from "./accounts-main.mjs";const signedIn = { status: "connected", account: { id: "a", email: "[email protected]" }, deviceId: "d" };@@@ -15,23 -17,19 +16,20 @@@ function harness({ state = signedIn, otreturn { handlers, calls, accounts, call: (channel, ...args) => handlers.get(channel)({}, ...args) };}- test("the view names each account by id and address, never a token, and the active one once", () => {-test("the view names the account and its address, never a token, and nothing while signed out", () => {-- assert.deepEqual(accountsView({ ...signedIn, token: "omc_secret", machine: { origin: "https://a.test" } }), { active: { id: "a", email: "[email protected]" }, others: [] });-- assert.deepEqual(accountsView({ status: "reauth-required", account: signedIn.account }).active.signIn, true);-- assert.deepEqual(accountsView({ status: "signed-out" }), { active: null, others: [] });-- assert.deepEqual(accountsView({ status: "connecting" }), { active: null, others: [] });-- assert.deepEqual(accountsView(null), { active: null, others: [] });- const b = { id: "b", email: "[email protected]" };- assert.deepEqual(accountsView(signedIn, [{ id: "a", email: "[email protected]" }, b]).others, [b]);++test("the view names the account in use and its address, never a token, and nothing while signed out; no page reads the others through it", () => {++ assert.deepEqual(accountsView(signedIn), { active: { id: "a", email: "[email protected]" } });++ assert.deepEqual(accountsView({ status: "reauth-required", account: { id: "a", email: "[email protected]" } }), { active: { id: "a", email: "[email protected]", signIn: true } });++ for (const state of [null, { status: "signed-out" }, { status: "connecting", account: { id: "a", email: "[email protected]" } }]) assert.deepEqual(accountsView(state), { active: null });++ assert.equal(JSON.stringify(accountsView({ ...signedIn, token: "omc_secret" })).includes("omc_"), false);});- test("only this app's own pages read the list, switch, add or sign out; another page only opens the sheet, from main", async () => {-test("only this app's own pages read the list or sign out; another page only opens the sheet, from main", async () => {- const f = harness({ ownPage: () => false });- for (const channel of ["accounts:list", "accounts:sign-out", "accounts:sheet-pending", "accounts:sheet-closed"]) await assert.rejects(async () => f.call(channel, "a"), /only available/);++test("only this app's own pages read who is signed in, add or sign out; another page only opens the sheet, from main", async () => {+ const f = harness({ ownPage: () => false, others: [{ id: "b", email: "[email protected]" }] });- for (const channel of ["accounts:list", "accounts:switch", "accounts:sign-out", "accounts:add-start", "accounts:add-verify", "accounts:add-browser", "accounts:add-reopen", "accounts:add-cancel", "accounts:sheet-pending", "accounts:sheet-closed"]) {++ for (const channel of ["accounts:list", "accounts:sign-out", "accounts:add-start", "accounts:add-verify", "accounts:add-browser", "accounts:add-reopen", "accounts:add-cancel", "accounts:sheet-pending", "accounts:sheet-closed"]) {+ await assert.rejects(async () => f.call(channel, "a"), /only available/, channel);+ }assert.equal(await f.call("accounts:offered"), true);- assert.equal(await f.call("accounts:open"), undefined);+ assert.equal(await f.call("accounts:open"), undefined, "the page gets nothing back");assert.deepEqual(f.calls, ["hold:true", "tell-sheet"]);const refused = harness({ ownPage: () => false, placePage: () => false });assert.equal(await refused.call("accounts:offered"), false);@@@ -48,23 -46,30 +46,29 @@@ test("the sheet asked for before the raassert.deepEqual(f.calls, ["hold:true", "tell-sheet", "hold:false"]);});- test("a switch and a sign-out answer with the list as it is now; a failure says failed, with no detail", async () => {-test("sign out: the window lets go, the account's places are named while the sign-in still names My Cloud, the sign-in ends, they leave, then the window goes where it belongs", async () => {- const f = harness();- assert.deepEqual(await f.call("accounts:sign-out", "a"), { active: null, others: [] });- assert.deepEqual(f.calls, ["leaving", "places", "sign-out", "leave", "show", "tell"]);++test("no page can switch or read another account's address: switching is a click on the rail, which main acts on", async () => {++ const f = harness({ others: [{ id: "b", email: "[email protected]" }] });++ assert.equal(f.handlers.has("accounts:switch"), false);++ assert.deepEqual(await f.call("accounts:list"), { active: { id: "a", email: "[email protected]" } });++ assert.equal(JSON.stringify(await f.call("accounts:list")).includes("[email protected]"), false);+ });+-test("a My Cloud saved by hand, which carries no mark of its own, leaves with the account although the sign-in no longer names it by the time its session goes", async () => {- const HOME = "https://byhand.example.test";- let state = signedIn, saved = { activeId: "h", environments: [{ id: "h", kind: "remote", origin: HOME, name: "My server" }, { id: "s", kind: "remote", origin: "https://other.example", name: "Other" }] };- const cleared = [];- const client = { state: () => state, signOut: async () => { state = { status: "signed-out" }; return state; } };- const leave = createAccountLeave({ saved: () => saved, persist: (next) => { saved = next; }, mine: () => (state.status === "connected" ? HOME : null), leaveWindow: async () => {},- session: () => ({ clearStorageData: async ({ origin }) => { cleared.push(origin); } }) });- const accounts = installAccounts({ ipcMain: { handle() {} }, ownPage: () => true, placePage: () => true, account: () => client, client: () => client, leave, holdSheet() {}, tellSheet() {}, leaving() {}, show: async () => {}, tell() {} });- await accounts.signOutActive();- assert.deepEqual(saved.environments.map((entry) => entry.id), ["s"], "the hand-saved My Cloud left the list; the other server stays");- assert.equal(saved.activeId, "local");- assert.deepEqual(cleared, [HOME]);++test("a sign-out answers with who is signed in now; a failure says failed, with no detail", async () => {+ const f = harness();- assert.deepEqual(await f.call("accounts:switch", "b"), { outcome: "switched", view: { active: { id: "a", email: "[email protected]" }, others: [] } });+ assert.deepEqual((await f.call("accounts:sign-out", "a")).outcome, "signed-out");+ const handlers = new Map();+ installAccounts({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, ownPage: () => true, placePage: () => true, account: () => null, client: () => null,- ring: () => ({ others: () => [], switchTo: async () => { throw new Error("omc_secret token in a message"); } }), holdSheet() {}, tellSheet() {}, tell() {} });- assert.deepEqual(await handlers.get("accounts:switch")({}, "b"), { outcome: "failed", view: { active: null, others: [] } });++ ring: () => ({ signOut: async () => { throw new Error("omc_secret token in a message"); } }), holdSheet() {}, tellSheet() {}, tell() {} });++ assert.deepEqual(await handlers.get("accounts:sign-out")({}, "b"), { outcome: "failed", view: { active: null } });});-test("signing out an account that isn't the one here changes nothing", async () => {+test("Settings' Sign out is the same sign-out, refused while the move holds it, and works with no account to name", async () => {const f = harness();- await assert.rejects(f.call("accounts:sign-out", "other"), /isn't signed in here/);- assert.deepEqual(f.calls, []);+ assert.equal((await f.accounts.signOutActive()).account.id, "a");+ assert.deepEqual(f.calls, ["sign-out:a"]);+ const none = harness({ state: { status: "signed-out" } });+ await none.accounts.signOutActive();+ assert.deepEqual(none.calls, ["client-sign-out"]);});const places = {@@@ -106,32 -111,35 +110,119 @@@ test("leaving: the list changes, then tassert.deepEqual(order, ["persist", "window", "clear", "clear", "clear"]);});- /** The window's cookies, by address, as Electron's session keeps them. */+ test("sessions go only after what was still waiting on those places has been answered, since a Cloud's answer re-issues its cookie", async () => {+ const order = [];+ let answer;+ const waiting = new Promise((resolve) => { answer = resolve; });+ const jar = new Map(places.environments.filter((entry) => entry.origin).map((entry) => [entry.origin, "session"]));+ const leave = createAccountLeave({ saved: () => places, persist: () => order.push("persist"), mine: () => null, leaveWindow: async () => order.push("window"),+ settled: () => waiting.then(() => { jar.set("https://home-a.test", "re-issued in the disconnect's answer"); order.push("answered"); }),+ session: () => ({ clearStorageData: async ({ origin }) => { order.push("clear"); jar.delete(origin); } }) });+ const left = leave.finish(leave.places());+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(order, ["persist", "window"], "nothing is cleared while an answer is on its way");+ answer();+ await left;+ assert.deepEqual(order, ["persist", "window", "answered", "clear", "clear", "clear"]);+ assert.equal(jar.has("https://home-a.test"), false, "the re-issued cookie went with the rest");+ });+-test("the app waits for lending's last answers before it clears a signed-out account's sessions", () => {+function cookieJar() {+ const jar = new Map();+ return { jar, session: { clearStorageData: async ({ origin }) => { jar.delete(origin); } } };+}++test("cookies never cross accounts: leaving takes every session of that account's places, a team's Cloud the two share included, and leaves a server saved by hand", async () => {+ const { jar, session } = cookieJar();+ for (const entry of places.environments) if (entry.origin) jar.set(entry.origin, `session-of-a-at-${entry.id}`);- const stash = createPlaceStash(memoryFile());- const leave = createAccountLeave({ saved: () => places, persist() {}, mine: () => null, leaveWindow: async () => {}, keep: (id, left) => stash.put(id, left), session: () => session });- await leave("a");++ const leave = createAccountLeave({ saved: () => places, persist() {}, mine: () => null, leaveWindow: async () => {}, session: () => session });++ await leave.finish(leave.places());+ assert.deepEqual([...jar.keys()], ["https://mine.example"], "account B opening the shared team's Cloud finds no cookie of A's, so it signs in with its own code");+});++function memoryFile(start = null) { let held = start; return { read: () => held, write: (value) => { held = value; } }; }++test("an account's places wait with it and come back as they were: same ids, so what was lent to them comes back too", () => {+ const stash = createPlaceStash(memoryFile());+ const { saved: without, left } = withoutAccountPlaces(places);- stash.put("a", left);- assert.deepEqual(stash.peek("b"), []);- const backAgain = withPlacesBack(without, stash.take("a"));++ const rows = [{ id: "home-a", name: "My Cloud", color: "green", kind: "cloud", opens: true }];++ stash.put("a", left, rows);++ assert.deepEqual(stash.peek("b"), { places: [], rows: [] });++ assert.deepEqual(stash.peek("a").rows, rows, "what the rail shows while it waits");++ const backAgain = withPlacesBack(without, stash.take("a").places);+ assert.deepEqual(backAgain.environments.map((entry) => entry.id).sort(), ["by-hand", "cloud-a", "home-a", "local-2", "team-a"]);- assert.deepEqual(stash.take("a"), [], "taken once");++ assert.deepEqual(stash.take("a"), { places: [], rows: [] }, "taken once");+ const keptOne = withPlacesBack({ ...without, environments: [...without.environments, { id: "new", origin: "https://shared-team.test", team: { id: "t1" } }] }, left);+ assert.equal(keptOne.environments.filter((entry) => entry.origin === "https://shared-team.test").length, 1, "a place at that address saved meanwhile stays the one");- assert.deepEqual(createPlaceStash({ read: () => { throw new Error("unreadable"); }, write() {} }).take("a"), [], "an unreadable file is nothing kept");++ assert.deepEqual(createPlaceStash({ read: () => { throw new Error("unreadable"); }, write() {} }).take("a"), { places: [], rows: [] }, "an unreadable file is nothing kept");++});++++/** The ring on real stash and leave code, with a sign-in that says who is in use. */++function desktopRing({ environments = places.environments, order = [], activeId = "a", mine = "https://home-a.test" } = {}) {++ let saved = { activeId: "cloud-a", environments }, state = { status: "connected", account: { id: activeId, email: `${activeId}@example.test` } };++ const stash = memoryFile(), lent = [];++ const tokens = (id) => ({ origin: "https://admin.test", token: `omc_${id.repeat(43)}`, account: { id, email: `${id}@example.test` }, device: { id: `d-${id}` }, expiresAt: Date.now() + 86_400_000 });++ const files = { active: tokens(activeId), saved: { v: 1, accounts: [tokens("b")] } };++ const store = (key) => ({ read: async () => files[key], write: async (value) => { files[key] = value; } });++ const client = { state: () => state, quiesce() {}, async reload() { const id = files.active.account.id; state = { status: "connected", account: { id, email: `${id}@example.test` } }; order.push(`reload:${id}`); }, async refresh() {}, async revokeSaved() { order.push("revoke"); },++ async signOut() { order.push("client-sign-out"); files.active = null; state = { status: "signed-out" }; return state; } };++ const ring = createDesktopRing({ allowed: () => true, active: () => store("active"), savedStore: () => store("saved"), stash: () => stash, client: () => client, origin: "https://admin.test", makeClient: () => { throw new Error("not here"); },++ saved: () => saved, persist: (next) => { saved = next; order.push("persist"); }, session: () => ({ clearStorageData: async ({ origin }) => { order.push(`clear:${origin}`); } }), mine: () => mine, leaveWindow: async () => order.push("window"),++ rows: () => [{ id: "home-a", name: "My Cloud", color: "green", kind: "cloud", opens: true, active: true, progress: 0.5, attention: true, paint: { swatch: "green" } }, { id: "by-hand", name: "By hand", kind: "server", opens: true, forget: true }, { id: "local", name: "This computer", kind: "computer", opens: true }],++ holding: () => null, letGo: (id) => order.push(`let-go:${id}`), lendingDone: async () => { order.push("lending-done"); }, settled: async () => order.push("settled"), forgetLending: (place) => lent.push(place.id), tell: () => order.push("tell"), log: () => {} });++ return { ring, order, lent, saved: () => saved, files };++}++++test("a switch keeps the rail's rows for the account leaving, without their live state, and brings the other's places back", async () => {++ const f = desktopRing({ order: [] });++ await f.ring().start();++ assert.deepEqual(f.ring.waiting().map((row) => row.id), ["b"], "the other account waits, with nothing kept for it yet");++ assert.deepEqual(f.ring.waiting()[0].rows, []);++ assert.equal((await f.ring().switchTo("b")).outcome, "switched");++ const [a] = f.ring.waiting();++ assert.equal(a.id, "a");++ assert.deepEqual(a.rows, [{ id: "home-a", name: "My Cloud", color: "green", kind: "cloud", opens: true }], "no live state, no menu; this computer and a hand-saved server aren't the account's");++ assert.deepEqual(a.places.map((entry) => entry.id), ["home-a", "cloud-a", "team-a"]);++ assert.deepEqual(f.saved().environments.map((entry) => entry.id), ["by-hand", "local-2"], "they leave the list while they wait");++ assert.equal((await f.ring().switchTo("a")).outcome, "switched");++ assert.deepEqual(f.saved().environments.map((entry) => entry.id).sort(), ["by-hand", "cloud-a", "home-a", "local-2", "team-a"], "same ids back");++ assert.deepEqual(f.ring.waiting()[0].id, "b");++});++++test("signing out the last account: the sign-in ends before its sessions go, since lending's last answers can re-issue a cookie", async () => {++ const order = [];++ const f = desktopRing({ order });++ await f.ring().start();++ f.files.saved = null;++ await f.ring().start();++ assert.equal((await f.ring().signOut("a")).outcome, "signed-out");++ const steps = order.filter((step) => !step.startsWith("clear:") || step === "clear:https://home-a.test");++ assert.deepEqual(steps.slice(steps.indexOf("let-go:a")), ["let-go:a", "client-sign-out", "persist", "window", "lending-done", "clear:https://home-a.test", "settled", "tell"]);++ assert.deepEqual(f.lent.sort(), ["cloud-a", "home-a", "team-a"], "what was lent to its places is forgotten with it");++ assert.deepEqual(f.ring.waiting(), []);++});++++test("signing out one of two: only its group goes, and the other account takes over", async () => {++ const f = desktopRing({ order: [] });++ await f.ring().start();++ assert.equal((await f.ring().signOut("a")).outcome, "signed-out");++ assert.deepEqual(f.ring.waiting(), [], "nothing of it kept");++ assert.equal(f.files.active.account.id, "b");++ assert.deepEqual(f.saved().environments.map((entry) => entry.id), ["by-hand", "local-2"], "servers saved by hand stay");++});++++test("the app waits for lending's last answers before it clears an account's sessions", () => {+ const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");- assert.match(main, /createAccountLeave\(\{[^\n]*settled: \(\) => computerSharing\?\.goodbyesDone\(\)/);++ assert.match(main, /createDesktopRing\(\{[^\n]*lendingDone: \(\) => computerSharing\?\.goodbyesDone\(\)/);+ });++ test("a My Cloud saved by hand is the account's only while the sign-in names it; what left is removed by id, so a list that changed meanwhile loses nothing else", () => {+ const byHand = { id: "h", kind: "remote", origin: "https://byhand.example.test", name: "My server" };+ const saved = { activeId: "h", environments: [byHand, places.environments[3]] };+ assert.deepEqual(accountPlaces(saved, "https://byhand.example.test").map((entry) => entry.id), ["h"]);+ assert.deepEqual(accountPlaces(saved, null), [], "once the sign-in has ended, nothing says which server was My Cloud");+ const changed = { activeId: "h", environments: [...saved.environments, { id: "new", kind: "remote", origin: "https://new.example", name: "New" }] };+ assert.deepEqual(withoutPlaces(changed, [byHand]).environments.map((entry) => entry.id), ["by-hand", "new"]);+ assert.equal(withoutPlaces(changed, [byHand]).activeId, "local");+ assert.equal(withoutPlaces(changed, []), changed, "nothing to remove: the same list");});diff --cc electron/cloud-account.d.mtsindex 09deb765f8,ffcfe742b0..9619e92aa9--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@@ -174,26 -174,12 +174,26 @@@ export interface CloudAccountBridge}/** Who is signed in on this device, as the You menu shows it. `signIn`: this account's sign-in has ended here. */export interface AccountRow { id: string; email: string; signIn?: true }--export interface AccountsView { active: AccountRow | null; others: AccountRow[] }++export interface AccountsView { active: AccountRow | null }+export interface AccountSwitchResult { outcome: "switched" | "signed-out" | "moving" | "sign-in" | "gone" | "failed"; email?: string; view: AccountsView }++/** What a click on a place of another account answers when it didn't switch: nothing moved. `sign-in`: that sign-in has ended. */++export interface RailOpenResult { outcome: "switched" | "moving" | "sign-in" | "gone" | "failed"; email?: string }+/** `added`: kept signed in, not switched to, while this computer's move finishes; `already`: that account is the one signed in. */+export type AccountAddResult =+ | { outcome: "switched" | "added" | "already"; email?: string; view: AccountsView }+ | { outcome: "wrong-code"; triesLeft: number }+ | { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> };/** This app's own pages only: main refuses any other page. Absent on an older app. */export interface AccountsBridge {list(): Promise<AccountsView>;- /** One tap, no code: `moving` while this computer's move is finishing, `sign-in` once that sign-in has ended, `gone` when it isn't here any more. */- switchTo(id: string): Promise<AccountSwitchResult>;- /** Removes that account from this device; the active one's place goes to another signed in here, else the app is signed out. */- /** Removes that account from this device. */- signOut(id: string): Promise<AccountsView>;++ /** Removes that account from this device; the window goes to another signed in here, else the app is signed out. */+ signOut(id: string): Promise<AccountSwitchResult>;+ /** Add another account: the active account goes on until this succeeds. The attempt and the token stay in main. */+ addStart(email: string): Promise<CloudSignInStart>;+ addVerify(code: string): Promise<AccountAddResult>;+ addBrowser(): Promise<{ outcome: "browser" | "failed"; code?: string }>;+ addReopen(): Promise<void>;+ addCancel(): Promise<void>;sheetPending(): Promise<boolean>;sheetClosed(): Promise<void>;onChanged(callback: () => void): () => void;diff --cc electron/cloud-accounts.mjsindex 81a71e29ae,0000000000..d7289fbfa5mode 100644,000000..100644--- a/electron/cloud-accounts.mjs+++ b/electron/cloud-accounts.mjs@@@ -1,203 -1,0 +1,208 @@@+// The accounts kept signed in on this device. One is active: its sign-in stays in the file an older app reads, in the same+// format, so nothing happens on an upgrade and a downgrade finds the active account as it was. The others wait in a file of+// their own (`saved`), which an older app never opens, and do nothing until one becomes active: no request, no timer.+//+// A switch writes in the order that loses nothing: at every step each token is in at least one file. An account found in+// both files after a crash is the active one.+//+// Security: tokens are read and written here and in cloud-account.mjs only, both files encrypted by the OS. What leaves this+// module for a page is an id and an address.+import { unreadableRecord } from "./managed-desktop.mjs";++const TOKEN = /^omc_[A-Za-z0-9_-]{43}$/;+const VERSION = 1;++const usable = (record, origin) => record?.origin === origin && TOKEN.test(record.token ?? "") && typeof record.account?.id === "string" && Boolean(record.account.id)+ && typeof record.account.email === "string" && typeof record.device?.id === "string" && Number.isSafeInteger(record.expiresAt);+const memoryStore = () => { let held = null; return { read: async () => held, write: async (value) => { held = value; }, held: () => held }; };++/**+ * @param {{+ * active: { read(): Promise<any>, write(value: unknown): Promise<void> },+ * saved: { read(): Promise<any>, write(value: unknown): Promise<void> },+ * client(): { state(): any, quiesce(): void, reload(): Promise<any>, signOut(): Promise<any>, refresh(): Promise<any>, revokeSaved(record: unknown): Promise<void> },+ * makeClient(options: { store: any, onState(state: any): void }): any,+ * origin: string,+ * holding?(): string | null,+ * leaving?(accountId: string | null): Promise<unknown>,++ * left?(accountId: string | null): Promise<unknown>,+ * arriving?(accountId: string): Promise<unknown>,+ * settled?(): Promise<unknown>,+ * removed?(accountId: string): Promise<unknown>,+ * changed?(): void,+ * now?(): number,+ * log?(line: string): void,+ * }} deps `holding()`: why the active account can't be left now ("moving"), else null. `leaving(id)`: everything that was- * running for that account stops, while the sign-in is already out of the way. `arriving(id)`: what this device kept for that++ * running for that account stops, and its places are named while its sign-in can still say which they are. `left(id)`: those++ * places leave the list and the window, and their sessions go; a sign-out's comes after its sign-in ended, whose last answers can++ * re-issue a session. `arriving(id)`: what this device kept for that+ * account comes back, before its sign-in is read. `settled()`: the window goes where it belongs. `removed(id)`: that account+ * is off this device: what was kept for it goes. `makeClient`: a sign-in of its own for Add another account, which leaves the+ * active account running until it succeeds.+ */- export function createCloudAccounts({ active, saved, client, makeClient, origin, holding = () => null, leaving = async () => {}, arriving = async () => {}, settled = async () => {}, removed = async () => {}, changed = () => {}, now = Date.now, log = () => {} }) {++export function createCloudAccounts({ active, saved, client, makeClient, origin, holding = () => null, leaving = async () => {}, left = async () => {}, arriving = async () => {}, settled = async () => {}, removed = async () => {}, changed = () => {}, now = Date.now, log = () => {} }) {+ let rows = [], known = false, queue = Promise.resolve(), adder = null;+ const serial = (work) => { const run = queue.then(work, work); queue = run.catch(() => {}); return run; };++ /** An unreadable file stays when the keychain is only locked (it throws here), and is replaced once it can never be read. */+ async function readSaved() {+ let raw;+ try { raw = await saved.read(); } catch (error) {+ if (!unreadableRecord(error)) throw error;+ log("accounts: the saved sign-ins could not be read and were dropped");+ known = true;+ return [];+ }+ known = true;+ if (raw === null || raw === undefined) return [];+ if (raw.v !== VERSION || !Array.isArray(raw.accounts)) throw new Error("These saved sign-ins are from a newer version.");+ return raw.accounts.filter((record) => usable(record, origin));+ }+ const activeId = () => { const state = client().state(); return ["signed-out", "connecting"].includes(state?.status) ? null : state?.account?.id ?? null; };+ const remember = (list, without = activeId()) => {+ rows = list.filter((record) => record.account.id !== without).map((record) => ({ id: record.account.id, email: record.account.email, ...(record.expiresAt <= now() ? { signIn: true } : {}) }));+ };+ const writeSaved = async (list, without) => {+ const seen = new Set(), kept = list.filter((record) => record.account.id !== without && !seen.has(record.account.id) && seen.add(record.account.id));+ await saved.write(kept.length ? { v: VERSION, accounts: kept } : null);+ remember(kept, without);+ };++ /** The account `next` becomes active; `keep`: the one active now stays signed in, waiting. */+ async function become(next, { list, keep = true }) {+ const leavingId = activeId();+ const current = await active.read().catch(() => null);+ const waiting = keep && usable(current, origin) ? current : null;+ await saved.write({ v: VERSION, accounts: [...list.filter((record) => record.account.id !== waiting?.account.id), ...(waiting ? [waiting] : [])] });+ client().quiesce();+ try { await active.write(next); }+ catch (error) { void client().refresh().catch(() => {}); throw error; }+ await writeSaved([...list, ...(waiting ? [waiting] : [])], next.account.id);+ await leaving(leavingId);++ await left(leavingId);+ await arriving(next.account.id);+ await client().reload();+ await settled();+ changed();+ }++ async function switchTo(id) {+ if (activeId() === id) return { outcome: "switched" };+ const hold = holding();+ if (hold) return { outcome: hold };+ const list = await readSaved(), next = list.find((record) => record.account.id === id);+ if (!next) { remember(list); changed(); return { outcome: "gone" }; }+ if (next.expiresAt <= now()) return { outcome: "sign-in", email: next.account.email };+ await become(next, { list });+ return { outcome: "switched" };+ }++ /** Off this device: the token ends at the Admin (kept off this device even when it can't be told). The active account's+ * place goes to another that is still good; with none left, the app is signed out. */+ async function signOut(id) {+ const list = await readSaved();+ if (activeId() !== id) {+ const gone = list.find((record) => record.account.id === id);+ if (gone) {+ await writeSaved(list.filter((record) => record !== gone), activeId());+ await client().revokeSaved(gone).catch((error) => log(`accounts: signed out here only (${error?.message ?? error})`));+ await removed(id);+ }+ changed();+ return { outcome: "signed-out" };+ }+ const hold = holding();+ if (hold) return { outcome: hold };+ const next = list.find((record) => record.account.id !== id && record.expiresAt > now());+ const current = await active.read().catch(() => null);+ if (next) {+ await become(next, { list: list.filter((record) => record.account.id !== id), keep: false });+ if (usable(current, origin)) await client().revokeSaved(current).catch((error) => log(`accounts: signed out here only (${error?.message ?? error})`));+ } else {+ await leaving(id);+ await client().signOut();++ await left(id);+ await settled();+ }+ await removed(id);+ changed();+ return { outcome: "signed-out" };+ }++ /** The sign-in Add another account just finished: this account joins, active unless the move holds the switch. */+ async function joined(record, signIn) {+ const list = await readSaved(), id = record.account.id, email = record.account.email;+ const inUse = activeId() === id, kept = list.find((entry) => entry.account.id === id);+ // A sign-in that has ended here gives way to this one; one still good stays, and this one ends at once.+ const ended = inUse ? client().state().status === "reauth-required" : kept ? kept.expiresAt <= now() : true;+ if (!ended) {+ await signIn.signOut().catch(() => {});+ if (!inUse) await switchTo(id);+ return { outcome: inUse ? "already" : "switched", email };+ }+ const others = list.filter((entry) => entry !== kept);+ if (holding() && !inUse) {+ await writeSaved([...others, record], activeId());+ changed();+ return { outcome: "added", email };+ }+ await become(record, { list: others, keep: !inUse });+ return { outcome: "switched", email };+ }++ function endAdding() { adder?.client.close(); adder = null; }+ function startAdding() {+ endAdding();+ const store = memoryStore();+ const entry = { store, finished: null, client: null };+ entry.client = makeClient({ store, onState: (state) => { if (state?.status === "connected" && store.held() && adder === entry) void finish(entry); } });+ adder = entry;+ return entry;+ }+ /** Runs once per sign-in: the browser's way and the code's way both end here. */+ const finish = (entry) => (entry.finished ??= serial(async () => {+ try { return await joined(entry.store.held(), entry.client); }+ finally { if (adder === entry) endAdding(); }+ }));++ return {+ /** An account found in both files is the active one; with none active, the first still good takes its place. */+ start: () => serial(async () => {+ const list = await readSaved();+ remember(list);+ if (activeId() || !list.length) return;+ const current = await active.read().catch(() => undefined);+ if (current !== null) return;+ const next = list.find((record) => record.expiresAt > now());+ if (next) await become(next, { list, keep: false });+ }).catch((error) => log(`accounts: ${error?.message ?? error}`)),+ /** The others, as a page may see them: an id and an address. */+ others: () => rows.filter((row) => row.id !== activeId()),+ /** How many accounts are signed in on this device; more than one until that is known, so nothing that needs there to be+ * only one starts on a guess. */+ count: () => (known ? (activeId() ? 1 : 0) + rows.filter((row) => row.id !== activeId()).length : 2),+ email: (id) => (activeId() === id ? client().state()?.account?.email ?? null : rows.find((row) => row.id === id)?.email ?? null),+ switchTo: (id) => serial(() => switchTo(id)),+ signOut: (id) => serial(() => signOut(id)),+ addStart(email) {+ const entry = adder && !adder.finished ? adder : startAdding();+ return entry.client.emailStart(email);+ },+ async addVerify(code) {+ const entry = adder;+ if (!entry) return { outcome: "expired" };+ const result = await entry.client.emailVerify(code);+ if (result.outcome !== "signed-in") return result;+ return finish(entry);+ },+ /** Single sign-on, two-step, or the person asked: the browser approves it. The browser may be signed in to another+ * account: its own page says which, and lets them change it. */+ addBrowser() {+ const entry = startAdding();+ return entry.client.begin().then((state) => ({ outcome: state.status === "connecting" ? "browser" : "failed", ...(state.enrollment ? { code: state.enrollment.userCode } : {}) }));+ },+ addReopen: () => adder?.client.reopen().then(() => {}) ?? Promise.resolve(),+ addCancel() { if (adder && !adder.finished) { const entry = adder; adder = null; void entry.client.cancel().catch(() => {}).finally(() => entry.client.close()); } },+ close() { endAdding(); },+ };+}diff --cc electron/cloud-rail.d.mtsindex c186fe385f,c186fe385f..fd4c5a9619--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@@ -4,8 -4,8 +4,15 @@@ export interface RailPlaceid: string;name: string;color: import("./cloud-buy.mjs").CloudColor | null;-- /** This computer, a Cloud of the person's own (My Cloud included), a team's Cloud, or a server they connected by hand. */-- kind: "computer" | "cloud" | "team" | "server";++ /** 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";++ /** 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. */++ email?: string;++ /** Its account's sign-in has ended: a click asks for the emailed code. */++ signIn?: true;/** False while there is nothing to open yet (a Cloud being made, with no address). */opens: boolean;active?: true;@@@ -42,7 -42,7 +49,8 @@@}/** +'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). */--export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean; organization?: boolean }++/** `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 }/** `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. */diff --cc electron/cloud-rail.mjsindex 8ebcb6a8d8,8ebcb6a8d8..c5b1fc66bd--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@@ -12,6 -12,6 +12,7 @@@ import { CHECKOUT_SOURCES } from "./cloimport { cleanCloudListName, CLOUD_SWATCHES, cloudSetupProgress, cloudState, olderRelease, otherOwnClouds, ownCloud, signedInServers, stepProgress, swatchColor } from "./cloud-list.mjs";import { machineSetup } from "./cloud-home.mjs";import { listedLook, placeLook, railPaint, SIGNED_IN } from "./place-look.mjs";++import { withAccounts } from "./rail-accounts.mjs";export const RAIL_MIN_PLACES = 2;const PENDING = "pending:";@@@ -59,10 -59,10 +60,11 @@@ const unlisted = (entry, { clouds, home* checkout or its setup), never an address. My Cloud's saved place leaves once the session's list doesn't have it (removed* from the list). Fewer than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window* as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.-- * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs).-- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean }} input++ * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs). `waiting`: the other accounts++ * signed in on this device, each with its places as they were kept: grouped by account after these (withAccounts).++ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: any[] }} input*/--export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false }) {++export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = [] }) {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; };@@@ -82,6 -82,6 +84,7 @@@const computer = environments.savedPlace(saved, environments.LOCAL_ID), color = computer.color ?? null;const all = home ? places : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];++ if (waiting.length) return withAccounts(all, { saved, waiting, email: state?.account?.email ?? null });return all.length < (clouds.some(ownCloud) ? 1 : RAIL_MIN_PLACES) ? [] : all;}@@@ -129,8 -129,8 +132,8 @@@ export function createAddedCloudNotice(}const plain = value => (typeof value === "string" ? value : "");--/** A circle as the rail's page sees it: never the Cloud's id, which only main acts on. */--const seen = ({ cloudId: _cloudId, ...place }) => place;++/** A circle as the rail's page sees it: never the Cloud's id or which account main switches to, which only main acts on. */++const seen = ({ cloudId: _cloudId, account: _account, ...place }) => place;const CHOICES = Object.freeze(["cloud", "link", "address"]);/**@@@ -139,9 -139,9 +142,9 @@@* (the rail's, or this computer's own). Any other page learns only whether the rail stands beside it (`beside`).* `places()` is railPlaces' list now; `open(id)` main's own switch; `add` the + sheet's fixed actions; `account()` the* MausBot Cloud sign-in; `targets()` the pages told when something changed; `makeHome(id)` starts the move to a server-- * of the person's own (own-home-main.mjs `start`).++ * of the person's own (own-home-main.mjs `start`). `switchAccount(id)`: that account becomes the one in use (cloud-accounts.mjs).*/--export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null }) {++export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null, switchAccount = null }) {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`);@@@ -159,10 -159,10 +162,18 @@@ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places().map(seen), add: choices() }: { places: [], add: { cloud: false, link: false, address: false, organization: false }, ...(beside() ? { beside: true } : {}) })));// A Cloud the Admin is still making has no saved place: its own screen opens, by main's word for which Cloud it is.-- listed("workspaces:open", (_event, id) => {++ const opening = place => (place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id));++ // A place of another account: that account becomes the one in use first, and nothing moves if it can't. By then the place is++ // listed as that account's own; an account with no place of its own is simply where the window goes.++ listed("workspaces:open", async (_event, id) => {const place = places().find(entry => entry.id === plain(id) && entry.opens);if (!place) throw new Error("That place isn't here any more.");-- return place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id);++ if (!place.account) return opening(place);++ const said = await switchAccount(place.account);++ if (said.outcome !== "switched") return { outcome: said.outcome, ...(said.email ? { email: said.email } : {}) };++ const arrived = places().find(entry => entry.id === place.id && entry.opens && !entry.account);++ if (arrived) await opening(arrived);++ return { outcome: "switched" };});// Remove from list, from a circle's menu (the page asked the person first): only a Cloud or a server saved by hand that// main listed as removable. A server is forgotten here; a Cloud is taken off the person's list at the Admin.diff --cc electron/computer-sharing.d.mtsindex 2f83c041a0,b766e985c9..428c11f1cf--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@@ -144,8 -144,8 +144,10 @@@ export function createComputerSharing(ocloudState(env: Workspace | null | undefined): CloudLendingState;/** The folders lent to My Cloud, for Files' copies of them (electron/lent-folders.mjs). */lentToCloud(env: Workspace | null | undefined): { lendingId: string; folders: Array<{ id: string; path: string; name: string; write: boolean }>; protectedPaths: string[]; paused?: true } | { off: true };+ /** Another account takes over: lending to this account's Clouds stops, and goes on if it comes back. */+ leaveAccount(accountId: string | null): void;+ /** Lending's last requests have been answered or have timed out; a Cloud's answer can re-issue its session cookie. */+ goodbyesDone(): Promise<unknown>;lendingToCloud(): boolean;/** A server is using this computer now: a job running on it, or its browsing going through this computer. */busy(): boolean;diff --cc electron/home-window.node-test.mjsindex 21a3595282,93084e6929..029777b5cb--- a/electron/home-window.node-test.mjs+++ b/electron/home-window.node-test.mjs@@@ -858,32 -858,3 +858,14 @@@ test("an account leaving: nothing undeawait here.home.show();assert.deepEqual(here.local, [false], "already on this computer's page: nothing moves");});++const B_CLOUD = "https://omb-b.fly.dev";+const accountB = (machine) => ({ status: "connected", account: { id: "acct-2", email: "[email protected]" }, ...(machine ? { machine } : {}) });++test("moved to A's Cloud, B signed in with a Cloud of its own: B's Cloud opens, and A's frozen copy is never shown", () => {+ assert.deepEqual(homeOf({ journal: done(), state: accountB({ status: "ready", origin: B_CLOUD }) }), { kind: "cloud", origin: B_CLOUD, otherAccount: true });+ assert.deepEqual(homeOf({ journal: done(), state: accountB(null) }), { kind: "signin", other: true }, "B has no Cloud: the screen says where the bots are");+ assert.deepEqual(homeOf({ journal: done(), state: accountB({ status: "stopped", hold: { until: 9 } }) }), { kind: "signin", other: true }, "B's Cloud ended: never this computer's frozen copy");+ assert.deepEqual(homeOf({ journal: done(), state: { status: "unavailable", account: { id: "acct-2" } } }), { kind: "signin", other: true }, "before the Admin answers");+ assert.deepEqual(homeOf({ journal: done(), state: { status: "reauth-required", account: { id: "acct-2" } } }), { kind: "signin", other: true });+});-- test("moved to A's Cloud, B signed in with none: the screen names where the bots are, and Sign in adds that account beside B", async () => {- const added = [], asked = [];- const w = world({ state: accountB(null), deps: { signInOther: async () => added.push("add"), movedAccount: (id) => { asked.push(id); return { id, email: "[email protected]" }; } } });- await w.home.show();- assert.deepEqual(w.home.view(), { screen: "signin", other: true, movedTo: { id: "acct-1", email: "[email protected]" } });- assert.deepEqual(asked, ["acct-1"]);- assert.deepEqual([w.fetched, w.pairs], [[], 0], "A's Cloud is never asked for with B's sign-in");- await w.home.signIn();- assert.deepEqual(added, ["add"]);- assert.deepEqual(w.signIns, [], "B stays signed in: nothing signs out or starts over");- });-- test("moved to A's Cloud, B signed in and A not saved here: the plain words, with no address to switch to", async () => {- const w = world({ state: accountB(null), deps: { movedAccount: () => null } });- await w.home.show();- assert.deepEqual(w.home.view(), { screen: "signin", other: true });- });diff --cc electron/main.mjsindex 8336dcaaf6,5864348509..e7714045b3--- a/electron/main.mjs+++ b/electron/main.mjs@@@ -2657,10 -2657,10 +2657,10 @@@ const cloudLook = createCloudLook({ stoconst cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });- const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1 }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });-const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });++const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1 }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });- const homeWindow = createHomeWindow({ signInOther: () => accountRing().addBrowser(), movedAccount: id => { const email = id ? accountRing()?.email(id) : null; return email ? { id, email } : null; }, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,+ const homeWindow = createHomeWindow({ journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), ensureWindow: () => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); },localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog,hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")), ownMove: () => ownHome?.underWay() ?? null,@@@ -2680,7 -2680,7 +2680,7 @@@ function showHome(options)}const openOwnCloud = id => showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } });// The rail and its + (cloud-rail.mjs): its list for this app's page and hosted Clouds' pages only, opened through switchEnvironment.--const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true }); };++const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, waiting: accountRing.waiting() }); };// 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()}`],@@@ -2688,14 -2688,13 +2688,13 @@@chromeRail.install(ipcMain);function railChanged() { chromeRail.refresh(); rail.changed(); }const accountPages = [() => (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents }) ? mainWindow.webContents : null), () => ({ send: channel => chromeRail.send(channel) })];- const accountRing = createDesktopRing({ allowed: () => app.isPackaged && !desktopRemoteAccess, active: cloudAccountStore, savedStore: () => createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).saved), encryption: cloudEncryption }), stash: () => jsonFile(path.join(app.getPath("userData"), cloudTarget(process.env).places)), client: ensureCloudAccount, origin: cloudTarget(process.env).origin, makeClient: ({ store, onState }) => createCloudAccountClient({ store, onState, platform: process.platform, deviceName: os.hostname().slice(0, 100) || "My computer", appVersion: app.getVersion(), origin: cloudTarget(process.env).origin, openBrowser: url => shell.openExternal(url) }), saved: () => environmentsState, persist: persistEnvironments, session: () => session.defaultSession, mine: () => myCloud(), leaveWindow: () => (mainWindow && !mainWindow.isDestroyed() && !senderIsLocal({ sender: mainWindow.webContents }) ? navigateMainWindow(rendererOrigin()) : null), holding: () => oneHome.holding(), letGo: id => { homeWindow.accountLeaving(); homePlaces.remember(null); computerSharing?.leaveAccount(id); }, settled: () => showHome(), forgetLending: env => sharingController().forget(env), tell: () => accounts.tell(), log: slog });- const accounts = installAccounts({ ipcMain, ownPage: event => chromeRail.owns(event) || cloudPageAsking(event) === "local", placePage: event => cloudPageAsking(event) !== null || ownCloudPage(event) !== null || homeWindow.homePage(event) || (Boolean(ownHome?.home()) && activeEnvironment(environmentsState)?.origin === ownHome.home().origin && workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin())), account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), client: ensureCloudAccount, ring: accountRing, holdSheet: open => chromeRail.holdOpen(open), tellSheet: () => chromeRail.send("accounts:open-sheet"), tell: () => { for (const page of accountPages) page()?.send("accounts:changed"); } });-const accounts = installAccounts({ ipcMain, ownPage: event => chromeRail.owns(event) || cloudPageAsking(event) === "local", placePage: event => cloudPageAsking(event) !== null || ownCloudPage(event) !== null || homeWindow.homePage(event) || (Boolean(ownHome?.home()) && activeEnvironment(environmentsState)?.origin === ownHome.home().origin && workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin())), account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), client: ensureCloudAccount, holdSheet: open => chromeRail.holdOpen(open), tellSheet: () => chromeRail.send("accounts:open-sheet"), leaving: () => homeWindow.accountLeaving(), leave: createAccountLeave({ saved: () => environmentsState, persist: persistEnvironments, session: () => session.defaultSession, mine: () => myCloud(), leaveWindow: () => (mainWindow && !mainWindow.isDestroyed() && !senderIsLocal({ sender: mainWindow.webContents }) ? navigateMainWindow(rendererOrigin()) : null), settled: () => computerSharing?.goodbyesDone(), log: slog }), show: () => showHome(), tell: () => { for (const page of accountPages) page()?.send("accounts:changed"); } });--const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),++const accountRing = createDesktopRing({ allowed: () => app.isPackaged && !desktopRemoteAccess, active: cloudAccountStore, savedStore: () => createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).saved), encryption: cloudEncryption }), stash: () => jsonFile(path.join(app.getPath("userData"), cloudTarget(process.env).places)), client: ensureCloudAccount, origin: cloudTarget(process.env).origin, makeClient: ({ store, onState }) => createCloudAccountClient({ store, onState, platform: process.platform, deviceName: os.hostname().slice(0, 100) || "My computer", appVersion: app.getVersion(), origin: cloudTarget(process.env).origin, openBrowser: url => shell.openExternal(url) }), saved: () => environmentsState, persist: persistEnvironments, session: () => session.defaultSession, mine: () => myCloud(), leaveWindow: () => (mainWindow && !mainWindow.isDestroyed() && !senderIsLocal({ sender: mainWindow.webContents }) ? navigateMainWindow(rendererOrigin()) : null), rows: () => railList(), holding: () => oneHome.holding(), letGo: id => { homeWindow.accountLeaving(); homePlaces.remember(null); computerSharing?.leaveAccount(id); }, lendingDone: () => computerSharing?.goodbyesDone(), settled: () => showHome(), forgetLending: env => sharingController().forget(env), tell: () => { accounts.tell(); railChanged(); }, log: slog }); const accounts = installAccounts({ ipcMain, ownPage: event => chromeRail.owns(event) || cloudPageAsking(event) === "local", placePage: event => cloudPageAsking(event) !== null || ownCloudPage(event) !== null || homeWindow.homePage(event) || (Boolean(ownHome?.home()) && activeEnvironment(environmentsState)?.origin === ownHome.home().origin && workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin())), account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), client: ensureCloudAccount, ring: accountRing, holdSheet: open => chromeRail.holdOpen(open), tellSheet: () => chromeRail.send("accounts:open-sheet"), tell: () => { for (const page of accountPages) page()?.send("accounts:changed"); } });++const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, switchAccount: id => accountRing().switchTo(id), account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true),-- add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),++ 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({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });diff --cc electron/preload.cjsindex 2d42946b4f,c32ec6b923..af002a394b--- a/electron/preload.cjs+++ b/electron/preload.cjs@@@ -500,13 -500,7 +500,12 @@@ const bridge =// Who is signed in on this device: this app's own pages only (main checks the sender). No token ever comes through here.accounts: process.argv.includes("--omb-company-desktop=1") ? {list: () => ipcRenderer.invoke("accounts:list"),- switchTo: id => ipcRenderer.invoke("accounts:switch", String(id)),signOut: id => ipcRenderer.invoke("accounts:sign-out", String(id)),+ addStart: email => ipcRenderer.invoke("accounts:add-start", String(email)),+ addVerify: code => ipcRenderer.invoke("accounts:add-verify", String(code)),+ addBrowser: () => ipcRenderer.invoke("accounts:add-browser"),+ addReopen: () => ipcRenderer.invoke("accounts:add-reopen"),+ addCancel: () => ipcRenderer.invoke("accounts:add-cancel"),sheetPending: () => ipcRenderer.invoke("accounts:sheet-pending"),sheetClosed: () => ipcRenderer.invoke("accounts:sheet-closed"),onChanged: cb => {diff --cc electron/rail-accounts.mjsindex 0000000000,0000000000..13bb3e34d7new file mode 100644--- /dev/null+++ b/electron/rail-accounts.mjs@@@ -1,0 -1,0 +1,48 @@@++// The rail with several accounts signed in on this device: it lists places, each place knows its account, and a click on a++// place of another account switches first (cloud-rail.mjs `workspaces:open`). An account that waits makes no request and has no++// timer, so its places show as they looked when it was last the one in use, with no counts or live state.++//++// Security: these rows go only to the rail's own page (cloud-rail.mjs), the one page allowed to know other accounts' addresses.++// With one account nothing here changes the rail at all.++++/** A place of no Cloud: an account with nothing on the rail still has one way to reach it. */++export const ACCOUNT_PLACE = "account:";++const ACTIVE = "active", HAND = "hand";++++/** The account's places as the rail shows them now, to keep while it waits: what they are and how they look, nothing that would++ * need asking again and nothing to act on but opening. This computer and a server saved by hand aren't any account's. */++export function accountRows(rows) {++ return rows.filter((row) => row.opens && row.kind !== "computer" && !row.forget && !row.account)++ .map(({ id, name, color, kind, ended }) => ({ id, name, color, kind, opens: true, ...(ended ? { ended: true } : {}) }));++}++++/**++ * The rail's rows, grouped: This computer, the account in use, each account that waits, then servers saved by hand. A Cloud two++ * accounts can reach (a team's) is one row: the account in use's when it can, else the first that waits. An account left with++ * no row gets one of its own.++ * @param {any[]} all the account in use's rows, from railPlaces.++ * @param {{ saved: { environments: any[] }, email?: string | null, waiting?: Array<{ id: string, email: string, signIn?: true, places: any[], rows: any[] }> }} input++ */++export function withAccounts(all, { saved, email = null, waiting = [] }) {++ if (!waiting.length) return all;++ const taken = new Set(saved.environments.map((entry) => entry.origin).filter(Boolean));++ const first = (account, row) => {++ const origin = account.places.find((entry) => entry.id === row.id)?.origin;++ if (!origin) return true;++ if (taken.has(origin)) return false;++ taken.add(origin);++ return true;++ };++ const others = waiting.flatMap((account) => {++ const mark = { account: account.id, group: account.id, email: account.email, ...(account.signIn ? { signIn: true } : {}) };++ const rows = account.rows.filter((row) => first(account, row)).map((row) => ({ ...row, ...mark }));++ return rows.length ? rows : [{ id: `${ACCOUNT_PLACE}${account.id}`, name: account.email, color: null, kind: "account", opens: true, ...mark }];++ });++ const isComputer = (row) => row.kind === "computer";++ return [++ ...all.filter(isComputer),++ ...all.filter((row) => !isComputer(row) && !row.forget).map((row) => ({ ...row, group: ACTIVE, ...(email ? { email } : {}) })),++ ...others,++ ...all.filter((row) => row.forget).map((row) => ({ ...row, group: HAND })),++ ];++}diff --cc electron/rail-accounts.node-test.mjsindex 0000000000,0000000000..8b9a8b3fd3new file mode 100644--- /dev/null+++ b/electron/rail-accounts.node-test.mjs@@@ -1,0 -1,0 +1,167 @@@++import assert from "node:assert/strict";++import test from "node:test";++++import environments from "./environments.cjs";++import { installCloudRail, railPlaces } from "./cloud-rail.mjs";++import { accountRows, ACCOUNT_PLACE, withAccounts } from "./rail-accounts.mjs";++++const { LOCAL_ID } = environments;++// The owner's list of cases for the rail with several accounts: each is a test here, by its number.++const myCloud = (origin, id = origin) => ({ id, kind: "remote", origin, name: "My Cloud", home: true });++const ownCloud = (origin, name, id = origin) => ({ id, kind: "remote", origin, name, cloud: { id: `c-${id}`, role: "owner" } });++const teamCloud = (origin, name, id = origin) => ({ id, kind: "remote", origin, name, team: { id: `t-${origin}`, role: "member" } });++const byHand = (origin, name) => ({ id: origin, kind: "remote", origin, name });++const signedIn = (email, extra = {}) => ({ status: "connected", account: { id: email, email }, clouds: [], ...extra });++const list = (environmentsList, activeId = LOCAL_ID) => ({ environments: environmentsList, activeId });++const waits = (email, places, rows = places.map((entry) => ({ id: entry.id, name: entry.name, color: null, kind: entry.team ? "team" : "cloud", opens: true }))) => ({ id: email, email, places, rows });++const ids = (rows) => rows.map((row) => row.id);++const dividers = (rows) => rows.slice(1).filter((row, at) => row.group !== rows[at].group).length;++++test("1. no account: This computer and hand-connected servers only, as ever, with no grouping", () => {++ assert.deepEqual(railPlaces({ saved: list([]) }), [], "only This computer: no rail");++ const rows = railPlaces({ saved: list([byHand("https://hand.test", "Hand")]) });++ assert.deepEqual(ids(rows), [LOCAL_ID, "https://hand.test"]);++ assert.equal(dividers(rows), 0);++ assert.equal(rows.some((row) => row.email || row.group), false);++});++++test("2, 3, 4, 5. one account: exactly today's rail, with no grouping, divider or address", () => {++ const shapes = [++ [myCloud("https://a.test")],++ [myCloud("https://a.test"), ownCloud("https://a2.test", "Two"), ownCloud("https://a3.test", "Three"), ownCloud("https://a4.test", "Four"), ownCloud("https://a5.test", "Five")],++ [myCloud("https://a.test"), teamCloud("https://t.test", "Team")],++ [teamCloud("https://t.test", "Team")],++ ];++ for (const places of shapes) {++ const state = signedIn(A);++ const none = railPlaces({ saved: list(places), mine: "https://a.test", state });++ assert.deepEqual(railPlaces({ saved: list(places), mine: "https://a.test", state, waiting: [] }), none);++ assert.equal(dividers(none), 0);++ assert.equal(JSON.stringify(none).includes("@"), false, "no address");++ assert.equal(none.some((row) => row.group !== undefined), false);++ }++});++++test("6. two accounts, one Cloud each, both called My Cloud: told apart by group, divider and address; This computer on top", () => {++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a-home")]), mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b-home")])] });++ assert.deepEqual(ids(rows), [LOCAL_ID, "a-home", "b-home"]);++ assert.deepEqual(rows.map((row) => row.name), ["This computer", "My Cloud", "My Cloud"]);++ assert.deepEqual(rows.map((row) => row.email ?? null), [null, A, B]);++ assert.equal(rows[0].group, undefined, "This computer is no account's");++ assert.equal(dividers(rows), 2);++ assert.equal(rows[1].account, undefined, "a click on the account in use's own place doesn't switch");++ assert.equal(rows[2].account, B);++});++++test("7. two accounts with several Clouds and teams: the account in use first, each group in its order, colours per Cloud", () => {++ const b = [myCloud("https://b.test", "b1"), ownCloud("https://b2.test", "B Two", "b2"), teamCloud("https://bt.test", "B Team", "b3")];++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1"), ownCloud("https://a2.test", "A Two", "a2"), teamCloud("https://at.test", "A Team", "a3")]), mine: "https://a.test", state: signedIn(A),++ waiting: [waits(B, b, [{ id: "b1", name: "My Cloud", color: "red", kind: "cloud", opens: true }, { id: "b2", name: "B Two", color: "blue", kind: "cloud", opens: true }, { id: "b3", name: "B Team", color: null, kind: "team", opens: true }])] });++ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", "a2", "a3", "b1", "b2", "b3"]);++ assert.deepEqual(rows.slice(4).map((row) => row.color), ["red", "blue", null], "as they looked");++ assert.equal(new Set(rows.slice(1, 4).map((row) => row.group)).size, 1);++ assert.equal(new Set(rows.slice(4).map((row) => row.group)).size, 1);++});++++test("8. an account with no Clouds has one row of its own while it waits; while it's the one in use, it has none", () => {++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), mine: "https://a.test", state: signedIn(A), waiting: [{ id: C, email: C, places: [], rows: [] }] });++ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", `${ACCOUNT_PLACE}${C}`]);++ assert.deepEqual({ kind: rows[2].kind, name: rows[2].name, opens: rows[2].opens, account: rows[2].account }, { kind: "account", name: C, opens: true, account: C });++ const active = railPlaces({ saved: list([]), state: signedIn(C), waiting: [waits(A, [myCloud("https://a.test", "a1")])] });++ assert.deepEqual(ids(active), [LOCAL_ID, "a1"], "the rail stands though the one in use has nothing on it");++});++++test("9. the same team under both accounts is one row: the account in use's when it's a member, else the first that waits", () => {++ const mine = teamCloud("https://t.test", "Team", "t-as-a"), theirs = teamCloud("https://t.test", "Team", "t-as-b");++ const both = railPlaces({ saved: list([mine]), state: signedIn(A), waiting: [waits(B, [theirs])] });++ assert.deepEqual(ids(both), [LOCAL_ID, "t-as-a", `${ACCOUNT_PLACE}${B}`], "one row, opened as the account in use, and B can still be reached");++ assert.equal(both[1].account, undefined);++ const notMine = railPlaces({ saved: list([]), state: signedIn(A), waiting: [waits(B, [theirs]), waits(C, [teamCloud("https://t.test", "Team", "t-as-c")])] });++ assert.deepEqual(ids(notMine), [LOCAL_ID, "t-as-b", `${ACCOUNT_PLACE}${C}`]);++ assert.equal(notMine[1].account, B, "a click switches to the one that is a member");++});++++test("10. a Cloud that ended keeps looking so while it waits; once its account is in use, today's rows say the rest", () => {++ const rows = accountRows([{ id: "x", name: "Old", color: "red", kind: "cloud", opens: true, ended: true, removable: true, cloudId: "c1", attention: true, progress: 0.2, paint: {} }]);++ assert.deepEqual(rows, [{ id: "x", name: "Old", color: "red", kind: "cloud", opens: true, ended: true }], "no Remove here: it needs the account in use, which a click makes it");++});++++test("11. hand-connected servers stay outside any account's group, after them, and aren't kept with an account", () => {++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1"), byHand("https://hand.test", "Hand")]), mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")])] });++ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", "b1", "https://hand.test"]);++ assert.equal(rows[3].group, "hand");++ assert.equal(rows[3].email, undefined);++ assert.equal(rows[3].account, undefined);++ assert.deepEqual(accountRows(rows), [{ id: "a1", name: "My Cloud", color: null, kind: "cloud", opens: true }], "this computer, a hand-saved server and another account's rows aren't this account's");++});++++test("12. a place that waits carries no live state: nothing on the rail can say it is lent or busy", () => {++ const rows = railPlaces({ saved: list([]), state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")], accountRows([{ id: "b1", name: "My Cloud", color: null, kind: "cloud", opens: true, active: true, progress: 0.4, attention: true, update: {}, offline: true, server: true }]))] });++ assert.deepEqual(Object.keys(rows[1]).sort(), ["account", "color", "email", "group", "id", "kind", "name", "opens"]);++});++++test("14. a moved computer whose home is a Cloud of the account that waits: its row is there, and This computer is the clean workspace's", () => {++ const rows = railPlaces({ saved: list([]), home: null, state: signedIn(B), waiting: [waits(A, [myCloud("https://a.test", "a1")])] });++ assert.deepEqual(ids(rows), [LOCAL_ID, "a1"]);++ assert.equal(rows[1].account, A);++ const home = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), home: "https://a.test", mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")])] });++ assert.deepEqual(ids(home), ["a1", "b1"], "home on the account in use: as today, no This computer, and the other account's Clouds beside it");++});++++test("an account whose sign-in ended keeps its rows, and says so", () => {++ const rows = withAccounts([], { saved: list([]), waiting: [{ ...waits(B, [myCloud("https://b.test", "b1")]), signIn: true }] });++ assert.equal(rows[0].signIn, true);++ assert.equal(rows[0].opens, true);++});++++function railWith({ rows, switched = async () => ({ outcome: "switched" }), after = rows }) {++ const handlers = new Map(), opened = [], asked = [];++ let current = rows;++ installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (handler) => handler, trusted: () => true, lists: (event) => event.rail === true, places: () => current, open: async (id) => opened.push(id),++ add: { choices: () => ({ cloud: false, link: false, address: false }), run() {} }, account: () => null, clipboard: {}, openCloud: async (id) => opened.push(`cloud:${id}`), targets: () => [],++ switchAccount: async (id) => { asked.push(id); const said = await switched(id); if (said.outcome === "switched") current = after; return said; } });++ return { call: (channel, ...args) => handlers.get(channel)({ rail: true }, ...args), page: (channel, ...args) => handlers.get(channel)({ rail: false }, ...args), opened, asked };++}++const mineRow = { id: "a1", name: "My Cloud", kind: "cloud", opens: true, group: "active", email: A };++const theirRow = { id: "b1", name: "My Cloud", kind: "cloud", opens: true, group: B, email: B, account: B };++const theirsActive = { id: "b1", name: "My Cloud", kind: "cloud", opens: true, group: "active", email: B };++++test("a click on the account in use's place opens it, with no switch", async () => {++ const f = railWith({ rows: [mineRow, theirRow] });++ await f.call("workspaces:open", "a1");++ assert.deepEqual([f.asked, f.opened], [[], ["a1"]]);++});++++test("a click on another account's place switches first, then opens it as that account's own", async () => {++ const f = railWith({ rows: [mineRow, theirRow], after: [theirsActive, { ...mineRow, account: A }] });++ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "switched" });++ assert.deepEqual([f.asked, f.opened], [[B], ["b1"]]);++});++++test("a click during a move is refused with the plain outcome, and nothing moves", async () => {++ const f = railWith({ rows: [mineRow, theirRow], switched: async () => ({ outcome: "moving" }) });++ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "moving" });++ assert.deepEqual(f.opened, []);++});++++test("a saved sign-in past its time: the click asks for the code for that address, and nothing moves", async () => {++ const f = railWith({ rows: [mineRow, { ...theirRow, signIn: true }], switched: async () => ({ outcome: "sign-in", email: B }) });++ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "sign-in", email: B });++ assert.deepEqual(f.opened, []);++});++++test("a click on an account with no place of its own switches, and the window goes where that account belongs", async () => {++ const id = `${ACCOUNT_PLACE}${C}`;++ const f = railWith({ rows: [mineRow, { id, name: C, kind: "account", opens: true, group: C, email: C, account: C }], after: [{ ...mineRow, account: A }] });++ assert.deepEqual(await f.call("workspaces:open", id), { outcome: "switched" });++ assert.deepEqual([f.asked, f.opened], [[C], []]);++});++++test("no page but the rail's reads the rows, and the rail's never hears which account main switches to", async () => {++ const f = railWith({ rows: [mineRow, theirRow] });++ const seen = await f.call("workspaces:places");++ assert.equal(JSON.stringify(seen.places).includes('"account"'), false);++ assert.deepEqual((await f.page("workspaces:places")).places, []);++ assert.throws(() => f.page("workspaces:open", "b1"), /only available/);++});diff --cc src/components/AccountMenu.test.tsindex 518145fc74,073b6b1bb4..9e344007c5--- a/src/components/AccountMenu.test.ts+++ b/src/components/AccountMenu.test.ts@@@ -1,55 -1,26 +1,51 @@@import { afterEach, expect, it, vi } from "vitest";-import { accountMenuItems } from "./AccountMenu";+import { accountMenuItems, switchNote } from "./AccountMenu";-afterEach(() => vi.unstubAllGlobals());-const signOut = vi.fn();+afterEach(() => vi.clearAllMocks());- const actions = { switchTo: vi.fn(), signOut: vi.fn(), add: vi.fn() };- const a = { id: "a", email: "[email protected]" }, b = { id: "b", email: "[email protected]" }, c = { id: "c", email: "[email protected]" };++const actions = { signOut: vi.fn(), add: vi.fn() };++const a = { id: "a", email: "[email protected]" };- it("one account: just its address, Add another account and Sign out", () => {- const items = accountMenuItems({ view: { active: a, others: [] }, openSheet: null, ...actions });- expect(items.map((item) => item.label)).toEqual(["[email protected]", "Add another account", "Sign out"]);- items[2].onSelect();- expect(actions.signOut).toHaveBeenCalledWith("a");-it("one account: its address, then Sign out", () => {- const items = accountMenuItems({ view: { active: { id: "a", email: "[email protected]" }, others: [] }, openSheet: null, signOut });++it("the You menu: just the address and Sign out, with no list of accounts", () => {++ const items = accountMenuItems({ view: { active: a }, openSheet: null, noRail: false, ...actions });+ expect(items.map((item) => item.label)).toEqual(["[email protected]", "Sign out"]);++ expect(items[0].disabled).toBe(true);items[1].onSelect();- expect(actions.add).toHaveBeenCalledWith();- expect(signOut).toHaveBeenCalledWith("a");++ expect(actions.signOut).toHaveBeenCalledWith("a");});- it("three accounts: each other one is a tap away", () => {- const items = accountMenuItems({ view: { active: a, others: [b, c] }, openSheet: null, ...actions });- expect(items.map((item) => item.label)).toEqual(["[email protected]", "[email protected]", "[email protected]", "Add another account", "Sign out"]);- expect(items[0].disabled).toBe(true);- items[2].onSelect();- expect(actions.switchTo).toHaveBeenCalledWith(c);-it("signed out, or a page that isn't offered the sheet: no rows", () => {- expect(accountMenuItems({ view: { active: null, others: [] }, openSheet: null, signOut })).toEqual([]);- expect(accountMenuItems({ view: null, openSheet: null, signOut })).toEqual([]);++it("with no rail beside the page, its + can't be reached, so Add another account stays here", () => {++ const items = accountMenuItems({ view: { active: a }, openSheet: null, noRail: true, ...actions });++ expect(items.map((item) => item.label)).toEqual(["[email protected]", "Add another account", "Sign out"]);++ items[1].onSelect();++ expect(actions.add).toHaveBeenCalledWith();+});++it("an account whose sign-in ended says so, and its tap goes to the sign-in", () => {- const ended = { ...a, signIn: true as const };- const items = accountMenuItems({ view: { active: ended, others: [{ ...b, signIn: true }] }, openSheet: null, ...actions });++ const items = accountMenuItems({ view: { active: { ...a, signIn: true as const } }, openSheet: null, noRail: false, ...actions });+ expect(items[0].subtitle).toBe("Sign in again");+ expect(items[0].disabled).toBe(false);+ items[0].onSelect();+ expect(actions.add).toHaveBeenCalledWith("[email protected]");- expect(items[1].subtitle).toBe("Sign in again");+});++it("no rows on a page that isn't offered the sheet, or while nobody is signed in here", () => {- expect(accountMenuItems({ view: { active: null, others: [] }, openSheet: null, ...actions })).toEqual([]);- expect(accountMenuItems({ view: null, openSheet: null, ...actions })).toEqual([]);++ expect(accountMenuItems({ view: { active: null }, openSheet: null, noRail: true, ...actions })).toEqual([]);++ expect(accountMenuItems({ view: null, openSheet: null, noRail: true, ...actions })).toEqual([]);});it("another place's page shows no address, only the row that asks main for the sheet", () => {const openSheet = vi.fn();- const items = accountMenuItems({ view: null, openSheet, ...actions });- const items = accountMenuItems({ view: null, openSheet, signOut });++ const items = accountMenuItems({ view: null, openSheet, noRail: false, ...actions });expect(items.map((item) => item.label)).toEqual(["Account and sign out"]);- expect(JSON.stringify(items)).not.toContain("@");+ expect(JSON.stringify(items.map(({ label, subtitle, title }) => ({ label, subtitle, title })))).not.toContain("@");items[0].onSelect();expect(openSheet).toHaveBeenCalled();});+- it("what a switch that didn't go through says, in plain words", () => {++it("what a click or sign-out that didn't go through says, in plain words", () => {+ expect(switchNote({ outcome: "moving" })).toContain("moving to the Cloud");+ expect(switchNote({ outcome: "gone" })).toContain("isn't signed in here");+ expect(switchNote({ outcome: "failed" })).toContain("Try again");+ expect(switchNote({ outcome: "switched" })).toBeNull();+ expect(switchNote({ outcome: "signed-out" })).toBeNull();+});diff --cc src/components/AccountMenu.tsxindex 01c80ad6eb,b126a82dfd..9b0d9f9cb6--- a/src/components/AccountMenu.tsx+++ b/src/components/AccountMenu.tsx@@@ -1,41 -1,26 +1,44 @@@import { useEffect, useState } from "react";-import { Check, LogOut, UserRound, X } from "lucide-react";-import type { AccountsView } from "../../electron/cloud-account.mjs";+import { Check, LogOut, Plus, UserRound, X } from "lucide-react";- import type { AccountRow, AccountsView, AccountSwitchResult } from "../../electron/cloud-account.mjs";++import type { AccountsView, AccountSwitchResult, RailOpenResult } from "../../electron/cloud-account.mjs";import { cn } from "@/lib/cn";+import type { CloudSignInPhase } from "@/lib/cloud-plan";import { t } from "@/lib/i18n";- import { CLOSE, Heading, QUIET, SCREEN, SHEET } from "./cloud-buy/parts";-import { CLOSE, Heading, PRIMARY, SCREEN, SHEET } from "./cloud-buy/parts";++import { usePlaces } from "@/lib/places";++import { CLOSE, Heading, PRIMARY, QUIET, SCREEN, SHEET } from "./cloud-buy/parts";+import { codeDigits, SignInScreen } from "./cloud-buy/SignInScreen";import type { SidebarMenuItem } from "./SidebarPopoverMenu";export interface AccountsAccess {-- /** This app's own page: the list itself. Any other page has none. */++ /** This app's own page: who is signed in. Any other page has none. */view: AccountsView | null;/** Another page: main opens the sheet on the rail's page for it. */openSheet: (() => void) | null;- switchTo(row: AccountRow): void;++ /** No rail stands beside this page, so its + can't be where another account is added. */++ noRail: boolean;signOut(id: string): void;+ add(email?: string): void;+}+- /** What a switch or sign-out that didn't go through says; null when it went through. */- export function switchNote(result: Pick<AccountSwitchResult, "outcome">): string | null {++/** What a click or sign-out that didn't go through says; null when it went through. */++export function switchNote(result: Pick<RailOpenResult | AccountSwitchResult, "outcome">): string | null {+ switch (result.outcome) {+ case "moving": return t("accounts.moving");+ case "gone": return t("accounts.gone");+ case "failed": return t("accounts.failed");+ default: return null;+ }}/** Who is signed in on this device, on this app's own page; on any other page, only whether main offers the sheet. */-export function useAccounts(): AccountsAccess {+export function useAccounts(): AccountsAccess & { sheet: { email: string | null; note: string | null } | null; closeSheet(): void } {const bridge = window.ogb?.remoteClient?.active ? undefined : window.ogb?.accounts;- const sheet = window.ogb?.accountSheet;+ const remote = window.ogb?.accountSheet;const own = window.ogb?.app?.ownPage === true && Boolean(bridge);++ const places = usePlaces();const [view, setView] = useState<AccountsView | null>(null);const [offered, setOffered] = useState(false);+ const [sheet, setSheet] = useState<{ email: string | null; note: string | null } | null>(null);useEffect(() => {if (!own) return;const read = () => { void bridge!.list().then(setView).catch(() => {}); };@@@ -43,143 -28,54 +46,123 @@@return bridge!.onChanged(read);}, [own, bridge]);useEffect(() => {- if (own || !sheet) return;+ if (own || !remote) return;let alive = true;- void sheet.offered().then((yes) => { if (alive) setOffered(yes === true); }).catch(() => {});+ void remote.offered().then((yes) => { if (alive) setOffered(yes === true); }).catch(() => {});return () => { alive = false; };- }, [own, sheet]);+ }, [own, remote]);- const said = (result: AccountSwitchResult, row?: AccountRow) => {- setView(result.view);- if (result.outcome === "sign-in") setSheet({ email: row?.email ?? null, note: null });- else { const note = switchNote(result); if (note) setSheet({ email: null, note }); }- };return {view: own ? view : null,- openSheet: !own && offered && sheet ? () => { void sheet.open().catch(() => {}); } : null,- signOut: (id) => { void bridge?.signOut(id).then(setView).catch(() => {}); },+ openSheet: !own && offered && remote ? () => { void remote.open().catch(() => {}); } : null,- switchTo: (row) => {- if (row.signIn) { setSheet({ email: row.email, note: null }); return; }- void bridge?.switchTo(row.id).then((result) => said(result, row)).catch(() => setSheet({ email: null, note: t("accounts.failed") }));- },- signOut: (id) => { void bridge?.signOut(id).then((result) => said(result)).catch(() => setSheet({ email: null, note: t("accounts.failed") })); },++ noRail: !places.beside && !places.places.length,++ signOut: (id) => { void bridge?.signOut(id).then((result) => { setView(result.view); const note = switchNote(result); if (note) setSheet({ email: null, note }); }).catch(() => setSheet({ email: null, note: t("accounts.failed") })); },+ add: (email) => setSheet({ email: email ?? "", note: null }),+ sheet,+ closeSheet: () => setSheet(null),};}- /** The You menu's last rows. One account: its address, Add another account, Sign out. On another page, one row that opens- * the sheet. Signed out here: Sign in, as anyone with no account yet has. */- export function accountMenuItems({ view, openSheet, switchTo, signOut, add }: AccountsAccess): SidebarMenuItem[] {-/** The You menu's last rows. On another page, one row that opens the sheet. Signed out: nothing, as Settings has the sign-in. */-export function accountMenuItems({ view, openSheet, signOut }: AccountsAccess): SidebarMenuItem[] {++/** The You menu's last rows: who is signed in here and Sign out. The other accounts are on the rail, and so is Add another account,++ * in its +; with no rail beside this page (nothing to list but This computer, or the person hid it) it is here. On another page,++ * one row that opens the sheet, with no address. Signed out: nothing, as Settings has the sign-in. */++export function accountMenuItems({ view, openSheet, noRail, signOut, add }: AccountsAccess): SidebarMenuItem[] {if (openSheet) return [{ key: "accounts-sheet", label: t("accounts.manage"), icon: <UserRound size={18} />, onSelect: openSheet }];- if (!view) return [];- const active = view.active;- if (!active && !view.others.length) return [];+ const active = view?.active;+ if (!active) return [];return [- ...(active ? [{ key: "accounts-active", heading: t("accounts.heading"), label: active.email, title: active.email, checked: true, icon: <Check size={18} />, disabled: !active.signIn, ...(active.signIn ? { subtitle: t("accounts.needsSignIn") } : {}), onSelect: () => { if (active.signIn) add(active.email); } }] : []),- ...view.others.map((row) => ({ key: `accounts-${row.id}`, label: row.email, title: row.email, checked: false, icon: <UserRound size={18} />, ...(row.signIn ? { subtitle: t("accounts.needsSignIn") } : {}), onSelect: () => switchTo(row) })),- { key: "accounts-add", label: t("accounts.add"), icon: <Plus size={18} />, onSelect: () => add() },- ...(active ? [{ key: "accounts-sign-out", label: t("accounts.signOut"), icon: <LogOut size={18} />, onSelect: () => signOut(active.id) }] : []),- { key: "accounts-active", heading: t("accounts.heading"), label: active.email, title: active.email, icon: <Check size={18} />, disabled: true, onSelect: () => {} },++ { key: "accounts-active", heading: t("accounts.heading"), label: active.email, title: active.email, checked: true, icon: <Check size={18} />, disabled: !active.signIn, ...(active.signIn ? { subtitle: t("accounts.needsSignIn") } : {}), onSelect: () => { if (active.signIn) add(active.email); } },++ ...(noRail ? [{ key: "accounts-add", label: t("accounts.add"), icon: <Plus size={18} />, onSelect: () => add() }] : []),+ { key: "accounts-sign-out", label: t("accounts.signOut"), icon: <LogOut size={18} />, onSelect: () => signOut(active.id) },];}-/** Over any place's page, on the rail's own page: who is signed in here and Sign out. */-export function AccountsSheet({ onClose }: { onClose: () => void }) {+const EMAIL_STEP: CloudSignInPhase = { step: "email", intent: false, problem: null };++/** Add another account in place: the emailed code, or the browser for single sign-on and two-step. The account in use goes+ * on until this succeeds; the code's attempt and the token stay in main. */- function AddAccount({ start, onDone, onBack }: { start: string; onDone: (note: string | null, view?: AccountsView) => void; onBack: () => void }) {++function AddAccount({ start, onDone, onBack }: { start: string; onDone: (note: string | null) => void; onBack: () => void }) {+ const bridge = window.ogb?.accounts;+ const [phase, setPhase] = useState<CloudSignInPhase>(EMAIL_STEP);+ const [email, setEmail] = useState(start);+ const [code, setCode] = useState("");+ const [busy, setBusy] = useState(false);+ const [browser, setBrowser] = useState(false);+ const [now, setNow] = useState(Date.now());+ useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(timer); }, []);+ useEffect(() => () => { void bridge?.addCancel().catch(() => {}); }, [bridge]);+ const send = () => {+ if (busy || !bridge) return;+ setBusy(true);+ void bridge.addStart(email).then((result) => {- if (result.outcome === "sent") { setPhase({ step: "code", intent: false, email: result.email, resendAt: result.resendAt, problem: null, triesLeft: null, ...(result.signupOpen === false ? { signupOpen: false } : {}) }); setEmail(result.email); setCode(""); }++ if (result.outcome === "sent") { setPhase({ step: "code", intent: false, email: result.email, resendAt: result.resendAt, problem: null, triesLeft: null, ...(result.signupOpen === false ? { signupOpen: false } : {}) }); setCode(""); }+ else setPhase({ step: "email", intent: false, problem: result.outcome });+ }, () => setPhase({ step: "email", intent: false, problem: "failed" })).finally(() => setBusy(false));+ };+ const verify = (digits: string) => {+ if (!bridge || phase.step !== "code") return;+ const at = phase;+ setBusy(true);+ void bridge.addVerify(digits).then((result) => {- if (result.outcome === "switched") onDone(null, result.view);- else if (result.outcome === "added") onDone(t("accounts.added", { email: result.email ?? email }), result.view);- else if (result.outcome === "already") onDone(t("accounts.already", { email: result.email ?? email }), result.view);++ if (result.outcome === "switched") onDone(null);++ else if (result.outcome === "added") onDone(t("accounts.added", { email: result.email ?? email }));++ else if (result.outcome === "already") onDone(t("accounts.already", { email: result.email ?? email }));+ else { setCode(""); setPhase({ ...at, problem: result.outcome, triesLeft: result.outcome === "wrong-code" ? result.triesLeft : null }); }+ }, () => setPhase({ ...at, problem: "failed", triesLeft: null })).finally(() => setBusy(false));+ };+ // The browser's way ends in main; the sheet closes once the account it brought is the one in use.+ useEffect(() => {+ if (!browser || !bridge) return;- let before: AccountRow | null | undefined;++ let before: AccountsView["active"] | undefined;+ const look = () => { void bridge.list().then((view) => {+ if (before === undefined) { before = view.active; return; }- if (view.active && !view.active.signIn && (view.active.id !== before?.id || before?.signIn)) onDone(null, view);++ if (view.active && !view.active.signIn && (view.active.id !== before?.id || before?.signIn)) onDone(null);+ }).catch(() => {}); };+ look();+ return bridge.onChanged(look);+ }, [browser, bridge, onDone]);+ if (browser) return <div data-accounts-browser className={SCREEN}>+ <Heading title={t("accounts.browserTitle")} sub={t("accounts.browserBody")} />+ <button type="button" className={QUIET} onClick={() => { void bridge?.addReopen().catch(() => {}); }}>{t("accounts.browserOpen")}</button>+ </div>;+ return <SignInScreen phase={phase} email={email} code={code} profileEmail={null} busy={busy} now={now} onBack={onBack} onEmail={setEmail} onSend={send}+ onChangeEmail={() => { setPhase(EMAIL_STEP); void bridge?.addCancel().catch(() => {}); }}+ onCode={(value) => { const digits = codeDigits(value); setCode(digits); if (digits.length === 8 && !busy) verify(digits); }}+ onResend={send} onBrowser={() => { setBusy(true); void bridge?.addBrowser().then((result) => { if (result.outcome === "browser") setBrowser(true); else setPhase({ step: "email", intent: false, problem: "failed" }); }, () => setPhase({ step: "email", intent: false, problem: "failed" })).finally(() => setBusy(false)); }} />;+}+- /** Over any place's page, on the rail's own page, or over this computer's: who is signed in here, the others, Add another- * account and Sign out. `adding`: straight to the sign-in, for this address when it has one. */++/** Over any place's page, on the rail's own page, or over this computer's: who is signed in here and Sign out, or a plain line++ * (`note`). `adding`: the sign-in, for this address when it has one: Add another account, or a saved account whose sign-in ended. */+export function AccountsSheet({ onClose, adding = null, note: given = null }: { onClose: () => void; adding?: string | null; note?: string | null }) {const bridge = window.ogb?.accounts;const [view, setView] = useState<AccountsView | null>(null);- const [failed, setFailed] = useState(false);+ const [note, setNote] = useState<string | null>(given);+ const [add, setAdd] = useState<string | null>(adding);useEffect(() => {if (!bridge) return;- const read = () => { void bridge.list().then(setView).catch(() => setFailed(true)); };+ const read = () => { void bridge.list().then(setView).catch(() => setNote(t("accounts.failed"))); };read();return bridge.onChanged(read);}, [bridge]);- const act = (work: Promise<AccountSwitchResult> | undefined, row?: AccountRow) => {- const active = view?.active ?? null;+ const signOut = (id: string) => {- setFailed(false);- void bridge?.signOut(id).then((next) => { setView(next); if (!next.active) onClose(); }, () => setFailed(true));+ setNote(null);- void work?.then((result) => {++ void bridge?.signOut(id).then((result) => {+ setView(result.view);- if (result.outcome === "sign-in") setAdd(row?.email ?? "");- else { const said = switchNote(result); if (said) setNote(said); else onClose(); }++ const said = switchNote(result);++ if (said) setNote(said); else onClose();+ }, () => setNote(t("accounts.failed")));};+ const active = view?.active ?? null;return <div className="ui-scrim fixed inset-0 z-[60] flex items-center justify-center p-4" onMouseDown={(event) => event.target === event.currentTarget && onClose()}><div role="dialog" aria-modal="true" aria-labelledby="cloud-add-title" data-accounts-sheet className={cn(SHEET, "relative w-full max-w-[420px]")}><button type="button" onClick={onClose} aria-label={t("accounts.close")} className={cn(CLOSE, "absolute end-4 top-4 z-10")}><X size={16} /></button>- <div className={SCREEN}>- <Heading title={t("accounts.title")} />- {active && <p data-accounts-active className="truncate text-[14px] text-ink" title={active.email}>{t("accounts.heading")} {active.email}</p>}- {active && <button type="button" data-accounts-sign-out className={PRIMARY} onClick={() => signOut(active.id)}>{t("accounts.signOut")}</button>}- {failed && <p role="alert" className="text-[13px] text-danger">{t("accounts.failed")}</p>}- </div>+ {add !== null- ? <AddAccount start={add} onBack={() => setAdd(null)} onDone={(said, next) => { if (next) setView(next); setAdd(null); if (said) setNote(said); else onClose(); }} />++ ? <AddAccount start={add} onBack={() => (adding !== null ? onClose() : setAdd(null))} onDone={(said) => { setAdd(null); if (said) setNote(said); else onClose(); }} />+ : <div className={SCREEN}>+ <Heading title={t("accounts.title")} />- <ul className="flex flex-col gap-1">- {active && <li data-accounts-active className="flex min-h-[36px] items-center gap-2 text-[14px] text-ink"><Check size={16} aria-label={t("accounts.heading")} /><span className="truncate" title={active.email}>{active.email}</span></li>}- {(view?.others ?? []).map((row) => <li key={row.id}>- <button type="button" data-accounts-other={row.id} className="flex min-h-[36px] w-full items-center gap-2 rounded-lg px-1 text-start text-[14px] text-ink hover:bg-ink/[0.05]" onClick={() => (row.signIn ? setAdd(row.email) : act(bridge?.switchTo(row.id), row))}>- <UserRound size={16} aria-hidden="true" /><span className="min-w-0 flex-1 truncate" title={row.email}>{row.email}</span>- {row.signIn && <span className="shrink-0 text-[12px] text-ink-secondary">{t("accounts.needsSignIn")}</span>}- </button>- </li>)}- </ul>- {note && <p role="status" className="text-[13px] leading-5 text-ink-secondary">{note}</p>}- <div className="flex flex-wrap gap-2">- <button type="button" data-accounts-add className={QUIET} onClick={() => setAdd("")}>{t("accounts.add")}</button>- {active && <button type="button" data-accounts-sign-out className={QUIET} onClick={() => act(bridge?.signOut(active.id))}>{t("accounts.signOut")}</button>}- </div>++ {active && !given && <p data-accounts-active className="truncate text-[14px] text-ink" title={active.email}>{t("accounts.heading")} {active.email}</p>}++ {note && <p role="status" data-accounts-note className="text-[13px] leading-5 text-ink-secondary">{note}</p>}++ {active && !given && <button type="button" data-accounts-sign-out className={PRIMARY} onClick={() => signOut(active.id)}>{t("accounts.signOut")}</button>}+ </div>}</div></div>;}diff --cc src/components/PlaceAddSheet.tsxindex bd943d29cc,bd943d29cc..3f4fcea4a4--- a/src/components/PlaceAddSheet.tsx+++ b/src/components/PlaceAddSheet.tsx@@@ -2,7 -2,7 +2,7 @@@// 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, X } from "lucide-react";++import { Building2, Cloud, Loader2, Server, UserRound, X } from "lucide-react";import type { RailAddChoices } from "../../electron/cloud-rail.mjs";import { track } from "@/lib/analytics";import { cn } from "@/lib/cn";@@@ -89,9 -89,9 +89,9 @@@ export function RailSheet({ wide = fals</div>;}--export function PlaceAddSheet({ choices, connect = null, onClose }: { choices: RailAddChoices; connect?: { name: string } | null; onClose: () => void }) {-- const server = choices.link, organization = choices.organization === true;-- const several = [organization, choices.cloud, server].filter(Boolean).length > 1;++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");const [wide, setWide] = useState(false);const workspaces = window.ogb?.workspaces;@@@ -107,6 -107,6 +107,7 @@@{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")} />}{server && <Choice kind="server" icon={<Server size={19} />} title={t("rail.own")} sub={t("rail.ownSub")} onClick={() => setView("server")} />}++ {account && <Choice kind="account" icon={<UserRound size={19} />} title={t("accounts.add")} sub={t("rail.accountSub")} onClick={() => onAccount!()} />}</div></div>}{view === "server" && <OwnServerLink onBack={several && !connect ? () => setView("choose") : null} onConnected={onClose} connect={connect} />}diff --cc src/components/PlacesRail.tsxindex 682695bebc,682695bebc..0769878e69--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@@ -3,9 -3,9 +3,10 @@@// never names an address. A right-click on a tile (or its row past eight) opens that place's menu: 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).++// 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 } from "lucide-react";++import { 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,6 -16,6 +17,7 @@@ import { localizedRelativeTime } from "import { useAdvancedMode } from "@/lib/interface-mode";import { useBesideFramed } from "@/lib/chrome-rail";import { makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";++import { AccountsSheet, switchNote } from "./AccountMenu";import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";import { MENU_ROW, MENU_SHEET } from "./menu-recipe";import { PlaceAddSheet } from "./PlaceAddSheet";@@@ -32,6 -32,6 +34,11 @@@ const tileRadius = (size: number) => Ma* own that signed in with their account says so, whether it is online, and why there is nothing to open when it is only* reachable on its own network. */export function placeLabel(place: RailPlace, now = Date.now()): string {++ const own = place.kind === "account" ? null : place.email ?? null;++ return [placeStatus(place, now), own, place.signIn && t("accounts.needsSignIn")].filter(Boolean).join(" · ");++}++++function placeStatus(place: RailPlace, now: number): string {const name = place.kind === "computer" ? t("rail.thisComputer") : place.server ? t("rail.ownServer", { name: place.name }) : place.name;if (place.waiting) return t("rail.waiting", { name });if (place.progress !== undefined) return t("rail.settingUp", { name });@@@ -54,15 -54,15 +61,18 @@@ export function shownPlaces(places: Raireturn [...first, active && !first.includes(active) ? active : places[limit - 1]!];}--/** Places whose name has every word typed, in the rail's order. */++/** Places whose name, or account's address, has every word typed, in the rail's order. */export function matchingPlaces(places: RailPlace[], query: string): RailPlace[] {const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);return places.filter((place) => {-- const name = (place.kind === "computer" ? t("rail.thisComputer") : place.name).toLocaleLowerCase();++ const name = `${place.kind === "computer" ? t("rail.thisComputer") : place.name} ${place.email ?? ""}`.toLocaleLowerCase();return words.every((word) => name.includes(word));});}++/** A divider goes between two places of different groups; with one account no place has a group, so none does. */++export const startsGroup = (places: RailPlace[], at: number): boolean => at > 0 && places[at]!.group !== places[at - 1]!.group;++/** The tile's progress, drawn round its edge: a 2px line 1px off the tile, its corners in step with the tile's, on whole* pixels at any scale. The line starts at the top edge's middle and runs clockwise. */function ProgressRing({ value = 0, waiting = false }: { value?: number; waiting?: boolean }) {@@@ -88,7 -88,7 +98,7 @@@ export function PlaceMark({ place, sizreturn <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} /> : placeInitials(place.name)}++ {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)}</span>;}@@@ -233,7 -233,7 +243,8 @@@ function MorePlaces({ places, canPair,className="w-full bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-tertiary" /></label><ul className="max-h-72 overflow-y-auto">-- {found.map((place) => <li key={place.id}>++ {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(); }}onContextMenu={menuOpener(place, (menu) => { onClose(); onMenu(menu); })} className={cn(MENU_ROW, "h-9")}><PlaceMark place={place} size={22} />@@@ -256,6 -256,6 +267,7 @@@ export function PlacesRail({ chrome = fconst [adding, setAdding] = useState(false);const [connecting, setConnecting] = useState<string | null>(null);const [menu, setMenu] = useState<{ place: RailPlace; top: number } | null>(null);++ const [accounts, setAccounts] = useState<{ adding: string | null; note: string | null } | null>(null);const moreRef = useRef<HTMLDivElement>(null);const menuRef = useRef<HTMLDivElement>(null);const navRef = useRef<HTMLElement>(null);@@@ -268,14 -268,14 +280,18 @@@window.addEventListener("mousedown", away);return () => window.removeEventListener("mousedown", away);}, [more, menu]);-- const covering = more || adding || connecting !== null || menu !== null;++ const covering = more || adding || connecting !== null || menu !== null || accounts !== null;useEffect(() => { if (chrome) void window.ogb?.rail?.expand?.(covering)?.catch(() => {}); }, [chrome, covering]);if (!state.places.length) return null;const bridge = window.ogb?.workspaces;const open = (place: RailPlace) => {if (!place.opens) { if (place.pairs) setConnecting(place.name); return; }track("rail_place_opened", { kind: place.kind });-- void bridge?.open?.(place.id).catch(() => {});++ void bridge?.open?.(place.id).then((said) => {++ if (!said) return;++ if (said.outcome === "sign-in") setAccounts({ adding: said.email ?? place.email ?? "", note: null });++ else { const note = switchNote(said); if (note) setAccounts({ adding: null, note }); }++ }, () => {});};const framed = windowFramed(capabilities), draggable = capabilities.windowChrome !== "native";// In a framed window the rail is part of the frame: the window's own rail runs the full height, its top in the frame's@@@ -287,7 -287,7 +303,7 @@@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;++ const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair || state.add.organization === true || state.add.account === true;// 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;@@@ -299,7 -299,7 +315,8 @@@<div aria-hidden="true" className={cn(above, "shrink-0")} />{/* As wide as the rail, so nothing round a tile is cut off at the sides: a list that scrolls clips its overflow. */}<ul className="flex min-h-0 w-full flex-col items-center gap-2 overflow-y-auto py-1" style={noDrag}>-- {shown.map((place) => <li key={place.id} className="flex">++ {shown.map((place, at) => <li key={place.id} className="flex flex-col items-center gap-2">++ {startsGroup(shown, at) && <span role="separator" data-rail-divider className="h-px w-4 bg-hairline" />}<PlaceTile place={place} canPair={canPair} onOpen={open} onMenu={openMenu} /></li>)}</ul>@@@ -319,7 -319,7 +336,8 @@@{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)} />}++ {adding && <PlaceAddSheet choices={state.add} 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 --cc src/locales/en.jsonindex f25aebce68,22f8bd6d47..b03800dbc7--- a/src/locales/en.json+++ b/src/locales/en.json@@@ -2177,19 -2177,8 +2177,18 @@@"phoneApp.androidAction": "Download the APK","phoneApp.next": "Installed? Connect your phone next, and scan the pairing code with the app.","accounts.heading": "Signed in as",+ "accounts.add": "Add another account",- "accounts.moving": "This computer's bots are moving to the Cloud. You can switch once that's done.",- "accounts.added": "{email} is signed in too. You can switch to it once this computer's bots have finished moving.",++ "rail.accountSub": "Stay signed in to more than one, and move between them from here.",++ "accounts.moving": "This computer's bots are moving to the Cloud. You can open this once that's done.",++ "accounts.added": "{email} is signed in too. You can open its Clouds once this computer's bots have finished moving.",+ "accounts.already": "You're already signed in as {email}.",+ "accounts.gone": "That account isn't signed in here any more.",+ "accounts.needsSignIn": "Sign in again",+ "accounts.browserTitle": "Finish signing in in your browser",+ "accounts.browserBody": "Check that the browser shows the account you want to add. If it shows another one, change it there.",+ "accounts.browserOpen": "Open the browser again",- "homeScreen.otherAccountTitle": "Your bots are on another account's Cloud",- "homeScreen.otherAccountBody": "This computer's bots moved to {email}'s Cloud. They're safe there and keep running. Switch to that account to open them.",- "homeScreen.otherAccountSwitch": "Switch to {email}","accounts.signOut": "Sign out",+ "accounts.signInAgain": "Sign in again","accounts.manage": "Account and sign out","accounts.title": "Your account","accounts.close": "Close",