Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Switch between MausBot accounts without signing in again
milind-soni64c305854fa3
diff --git a/electron/account-places.mjs b/electron/account-places.mjsindex 3d5a0e863d..5453e6cf5c 100644--- a/electron/account-places.mjs+++ b/electron/account-places.mjs@@ -25,3 +25,25 @@ export async function clearPlaceStorage(session, places, log = () => {}) {await 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. */+export function createPlaceStash(store) {+ const all = () => { try { const value = store.read(); return value && typeof value === "object" && !Array.isArray(value) ? value : {}; } catch { return {}; } };+ return {+ put(accountId, places) { if (accountId) store.write({ ...all(), [accountId]: places }); },+ take(accountId) {+ const kept = all(), places = Array.isArray(kept[accountId]) ? kept[accountId] : [];+ if (accountId in kept) { const { [accountId]: _, ...rest } = kept; store.write(rest); }+ return places;+ },+ peek: (accountId) => { const places = all()[accountId]; return Array.isArray(places) ? places : []; },+ };+}++/** 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 --git a/electron/accounts-main.mjs b/electron/accounts-main.mjsindex 59b0f5313d..409628474d 100644--- a/electron/accounts-main.mjs+++ b/electron/accounts-main.mjs@@ -1,26 +1,54 @@// 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 { withoutAccountPlaces, clearPlaceStorage } from "./account-places.mjs";+import { clearPlaceStorage, createPlaceStash, withoutAccountPlaces, withPlacesBack } from "./account-places.mjs";+import { createCloudAccounts } from "./cloud-accounts.mjs";-/** The sign-in as the You menu shows it: never a token, and no account while none is signed in. */-export function accountsView(state) {+/** 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 = []) {const account = state?.account;- 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: [] };+ 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) };}-/** Everything of the account this window held: its places leave the list, the window leaves them, and their sessions go. */-export function createAccountLeave({ saved, persist, session, mine, leaveWindow, log = () => {} }) {- return async () => {+/** 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) persist(next);+ if (left.length) { keep(accountId, left); persist(next); }await leaveWindow();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.+ */+export function createDesktopRing(deps) {+ let made = null, stash = 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 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); } });+ };+ ring.close = () => made?.close();+ return ring;+}+/*** @param {{* ipcMain: { handle(channel: string, handler: (event: unknown, ...args: any[]) => unknown): void },@@ -28,39 +56,37 @@ export function createAccountLeave({ saved, persist, session, mine, leaveWindow,* 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(): Promise<unknown>,- * 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();- const view = () => accountsView(account()?.state());- const serial = (work) => { const run = queue.then(work, work); queue = run.catch(() => {}); return run; };+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 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 after = await client().signOut();- await leave();- await show();- tell();- return after;- });+ const text = (value, max) => (typeof value === "string" ? value.slice(0, max) : "");own("accounts:list", view);- 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();+ own("accounts:switch", (id) => answered(() => ring().switchTo(text(id, 128))));+ own("accounts:sign-out", (id) => answered(() => ring().signOut(text(id, 128))));+ 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);@@ -70,5 +96,16 @@ export function installAccounts({ ipcMain, ownPage, placePage, account, client,holdSheet(true);tellSheet();});- return { view, signOutActive, tell };+ return {+ view,+ tell,+ /** Settings' Sign out, which is the You menu's: answers the sign-in's state. */+ async signOutActive() {+ const id = view().active?.id;+ if (!id) return client().signOut();+ const { outcome } = await ring().signOut(id);+ if (outcome === "moving") throw new Error("This computer's bots are moving to the Cloud. Try again once that's done.");+ return client().state();+ },+ };}diff --git a/electron/accounts-main.node-test.mjs b/electron/accounts-main.node-test.mjsindex 9c299918d0..d154e357fb 100644--- a/electron/accounts-main.node-test.mjs+++ b/electron/accounts-main.node-test.mjs@@ -1,34 +1,37 @@import assert from "node:assert/strict";import test from "node:test";-import { accountPlace, clearPlaceStorage, withoutAccountPlaces } from "./account-places.mjs";+import { accountPlace, clearPlaceStorage, createPlaceStash, withoutAccountPlaces, withPlacesBack } from "./account-places.mjs";import { accountsView, createAccountLeave, installAccounts } from "./accounts-main.mjs";const signedIn = { status: "connected", account: { id: "a", email: "[email protected]" }, deviceId: "d" };-function harness({ state = signedIn, placePage = () => true, ownPage = () => true } = {}) {+function harness({ state = signedIn, others = [], placePage = () => true, ownPage = () => true } = {}) {const handlers = new Map(), calls = [];- let current = state;- const client = { state: () => current, signOut: async () => { calls.push("sign-out"); current = { status: "signed-out" }; return current; } };- const accounts = installAccounts({- ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, ownPage, placePage, account: () => client, client: () => client,- holdSheet: (open) => calls.push(`hold:${open}`), tellSheet: () => calls.push("tell-sheet"), leaving: () => calls.push("leaving"), leave: async () => calls.push("leave"), show: async () => calls.push("show"), tell: () => calls.push("tell"),- });+ const client = { state: () => state, signOut: async () => { calls.push("client-sign-out"); return { status: "signed-out" }; } };+ const ring = { others: () => others, switchTo: async (id) => { calls.push(`switch:${id}`); return { outcome: "switched" }; }, signOut: async (id) => { calls.push(`sign-out:${id}`); return { outcome: "signed-out" }; },+ addStart: async (email) => { calls.push(`add:${email}`); return { outcome: "sent", email }; }, addVerify: async () => ({ outcome: "switched", email: "[email protected]" }) };+ const accounts = installAccounts({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, ownPage, placePage, account: () => client, client: () => client, ring: () => ring,+ holdSheet: (open) => calls.push(`hold:${open}`), tellSheet: () => calls.push("tell-sheet"), tell: () => calls.push("tell") });return { handlers, calls, accounts, call: (channel, ...args) => handlers.get(channel)({}, ...args) };}-test("the view names the account and its address, never a token, and nothing while signed out", () => {+test("the view names each account by id and address, never a token, and the active one once", () => {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("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 the list, switch, 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"]) {+ 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);@@ -45,16 +48,23 @@ test("the sheet asked for before the rail's page was up opens once when that pagassert.deepEqual(f.calls, ["hold:true", "tell-sheet", "hold:false"]);});-test("sign out: the window lets go first, the sign-in ends, the account's places leave, then the window goes where it belongs", async () => {+test("a switch and a sign-out answer with the list as it is now; a failure says failed, with no detail", async () => {const f = harness();- assert.deepEqual(await f.call("accounts:sign-out", "a"), { active: null, others: [] });- assert.deepEqual(f.calls, ["leaving", "sign-out", "leave", "show", "tell"]);+ 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: [] } });});-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 = {@@ -95,3 +105,33 @@ test("leaving: the list changes, then the window leaves, and only then the sessiassert.equal(left.length, 3);assert.deepEqual(order, ["persist", "window", "clear", "clear", "clear"]);});++/** The window's cookies, by address, as Electron's session keeps them. */+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");+ 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"));+ 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");+ 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");+});diff --git a/electron/chrome-rail.d.mts b/electron/chrome-rail.d.mtsindex 8ac37269b4..99a0124131 100644--- a/electron/chrome-rail.d.mts+++ b/electron/chrome-rail.d.mts@@ -23,6 +23,7 @@ export interface ChromeRailBridge {export interface ChromeRail {attach(window: unknown): void;refresh(): void;+ holdOpen(on: boolean): void;expand(on: boolean): void;owns(event: unknown): boolean;shown(): boolean;diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex ffcfe742b0..09deb765f8 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -175,11 +175,25 @@ 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 AccountSwitchResult { outcome: "switched" | "signed-out" | "moving" | "sign-in" | "gone" | "failed"; email?: string; view: AccountsView }+/** `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>;- /** Removes that account from this device. */- signOut(id: string): 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. */+ 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;@@ -232,7 +246,7 @@ export declare const STAGING_CLOUD_ORIGIN: string;export declare function cloudTarget(env?: Record<string, string | undefined>): {origin: string; staging: boolean;/** Under userData: the sign-in, saved servers, Files' folder, the Cloud's chosen name. */- file: string; environments: string; sync: string; look: string;+ file: string; saved: string; places: string; environments: string; sync: string; look: string;};export declare const CHECKOUT_SOURCES: readonly string[];export declare const UPGRADE_SOURCES: readonly string[];@@ -343,6 +357,12 @@ export interface CloudAccountClient {/** No sign-in needed: returns the Admin's receipt for this email-only answer. */updatesConsentByEmail(input: { email: string; installId: string; textVersion: string }): Promise<string>;withdrawUpdatesConsent(input: { status: "declined" | "withdrawn"; receipt: string }): Promise<void>;+ /** Another account takes over: nothing more is asked or written for this sign-in. */+ quiesce(): void;+ /** Reads the sign-in saved in `store` afresh, keeping nothing of the one before. */+ reload(): Promise<CloudAccountState>;+ /** Ends a sign-in that waits on this device, at the Admin. */+ revokeSaved(record: unknown): Promise<void>;close(): void;}export declare function createCloudAccountClient(options: {diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex a13bbbd84f..cce535664e 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -11,8 +11,8 @@ export const STAGING_CLOUD_ORIGIN = "https://omb-cloud-staging.fly.dev";* entry, Files' state, the Cloud's chosen name): staging never reads or writes production's. */export function cloudTarget(env = process.env) {return env?.OMB_CLOUD_STAGING === "1"- ? { origin: STAGING_CLOUD_ORIGIN, staging: true, file: "cloud-account-staging.bin", environments: "environments-staging.json", sync: "cloud-sync-staging", look: "cloud-home-look-staging.json" }- : { origin: CLOUD_ORIGIN, staging: false, file: "cloud-account.bin", environments: "environments.json", sync: "cloud-sync", look: "cloud-home-look.json" };+ ? { origin: STAGING_CLOUD_ORIGIN, staging: true, file: "cloud-account-staging.bin", saved: "cloud-accounts-staging.bin", places: "account-places-staging.json", environments: "environments-staging.json", sync: "cloud-sync-staging", look: "cloud-home-look-staging.json" }+ : { origin: CLOUD_ORIGIN, staging: false, file: "cloud-account.bin", saved: "cloud-accounts.bin", places: "account-places.json", environments: "environments.json", sync: "cloud-sync", look: "cloud-home-look.json" };}const TOKEN = /^omc_[A-Za-z0-9_-]{43}$/;const CODE = /^[A-HJ-NP-Z2-9]{5}-[A-HJ-NP-Z2-9]{5}$/;@@ -924,6 +924,18 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst result = await request(null, { method: "POST", path: "/api/updates-consent", body: { status, receipt }, signal: AbortSignal.timeout(10_000) });if (result?.ok !== true) throw new Error("Invalid Cloud consent response.");},+ /** Another account takes over: nothing more is asked or written for this sign-in. */+ quiesce() { reset(); },+ /** Reads the sign-in saved in `store` afresh: nothing of the one before stays. Told once, when the Admin has answered. */+ reload() {+ reset();+ grant = null; issued = null; cleanup = null; cleanupNeeded = false; plan = null; savedHint = null; opened = null; adding = null; renewalCloud = null; offerCache = null; waking = false;+ confirmations.clear();+ value = { status: "signed-out", message: "restoring" };+ return start();+ },+ /** Ends a sign-in that waits on this device, at the Admin. */+ revokeSaved: revoke,close() { closed = true; reset(); },};}diff --git a/electron/cloud-accounts.mjs b/electron/cloud-accounts.mjsnew file mode 100644index 0000000000..81a71e29ae--- /dev/null+++ b/electron/cloud-accounts.mjs@@ -0,0 +1,203 @@+// 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>,+ * 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+ * 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 = () => {} }) {+ 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 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 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 --git a/electron/cloud-accounts.node-test.mjs b/electron/cloud-accounts.node-test.mjsnew file mode 100644index 0000000000..be9a24173d--- /dev/null+++ b/electron/cloud-accounts.node-test.mjs@@ -0,0 +1,338 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import test from "node:test";+import { createCloudAccountClient } from "./cloud-account.mjs";+import { createCloudAccounts } from "./cloud-accounts.mjs";++const tokenOf = (letter) => `omc_${letter.repeat(43)}`;+const ATTEMPT = "a".repeat(43), CODE = "48201937", DAY = 86400_000;+const person = (letter) => ({ id: `acct-${letter}`, email: `${letter}@example.test` });++/** A fixture Admin: each account has a token per sign-in, and its session answers only for that token. */+async function world(t, { active = null, saved = null } = {}) {+ const w = { now: 1_800_000_000_000, requests: [], revoked: [], writes: [], calls: [], holding: null, nextLetter: "b", activeFile: active, savedFile: saved, failActive: false, readSaved: null };+ const accounts = new Map();+ const account = (letter, token = tokenOf(letter)) => { accounts.set(token, { letter, ...person(letter) }); return token; };+ for (const letter of "abc") account(letter);+ const server = createServer(async (req, res) => {+ let body = ""; for await (const chunk of req) body += chunk;+ const token = req.headers.authorization?.replace("Bearer ", "");+ w.requests.push({ route: req.url, method: req.method, token });+ const send = (status, data) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(data)); };+ if (req.url === "/api/cloud/app/sign-in/start") { w.emailed = JSON.parse(body).email; return send(200, { cloudContractVersion: 1, attempt: ATTEMPT, expiresIn: 600, resendAfter: 30, signupOpen: true }); }+ if (req.url === "/api/cloud/app/sign-in/verify") {+ if (JSON.parse(body).code !== CODE) return send(400, { error: "invalid_code" });+ const letter = w.emailed[0], fresh = w.freshToken ?? tokenOf(letter);+ account(letter, fresh);+ return send(200, { cloudContractVersion: 1, accessToken: fresh, expiresAt: w.now + 30 * DAY, device: { id: `device-${letter}` }, account: person(letter) });+ }+ const who = accounts.get(token);+ if (req.url === "/api/cloud/desktop/session") {+ if (!who || w.revoked.includes(token)) return send(401, { error: "invalid_token" });+ if (req.method === "DELETE") { w.revoked.push(token); return send(200, { ok: true }); }+ return send(200, { cloudContractVersion: 1, expiresAt: w.now + 30 * DAY, device: { id: `device-${who.letter}` }, account: { id: who.id, email: who.email }, entitlement: { plan: "free", status: "inactive", expiresAt: null, version: 0 }, cloud: null });+ }+ send(404, { error: "not_found" });+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const origin = `http://127.0.0.1:${server.address().port}`;+ w.origin = origin;+ w.grant = (letter, extra = {}) => ({ origin, token: tokenOf(letter), expiresAt: w.now + 30 * DAY, device: { id: `device-${letter}` }, account: person(letter), ...extra });+ const options = { origin, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.140", now: () => w.now, openBrowser: async () => {}, setTimer: () => 1, clearTimer: () => {} };+ const activeStore = { read: async () => (typeof w.activeFile === "function" ? w.activeFile() : w.activeFile), write: async (value) => { if (w.failActive) throw new Error("no keychain"); w.writes.push(["active", value?.account?.id ?? null]); w.activeFile = structuredClone(value); } };+ w.make = () => {+ w.client = createCloudAccountClient({ ...options, store: activeStore, onState: () => w.calls.push("state") });+ w.ring = createCloudAccounts({ active: activeStore, client: () => w.client, origin, now: () => w.now,+ saved: { read: async () => { if (w.readSaved) throw w.readSaved; return w.savedFile; }, write: async (value) => { w.writes.push(["saved", (value?.accounts ?? []).map((entry) => entry.account.id)]); w.savedFile = structuredClone(value); } },+ makeClient: ({ store, onState }) => createCloudAccountClient({ ...options, store, onState }),+ holding: () => w.holding, leaving: async (id) => { w.calls.push(`leaving:${id}`); }, arriving: async (id) => { w.calls.push(`arriving:${id}`); }, settled: async () => { w.calls.push("settled"); }, removed: async (id) => { w.calls.push(`removed:${id}`); }, changed: () => w.calls.push("changed") });+ return w;+ };+ w.boot = async () => { w.make(); await w.client.start(); await w.ring.start(); return w; };+ w.addByCode = async (letter) => { await w.ring.addStart(`${letter}@example.test`); return w.ring.addVerify(CODE); };+ w.signedInAs = () => w.client.state().account?.id ?? null;+ t.after(async () => { w.ring?.close(); w.client?.close(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); });+ return w;+}+const ids = (w) => w.ring.others().map((row) => row.id);++test("an old saved sign-in upgrades as it is: no prompt, no sign-out, nothing written", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ const before = structuredClone(w.activeFile);+ await w.boot();+ assert.equal(w.client.state().status, "connected");+ assert.equal(w.signedInAs(), "acct-a");+ assert.deepEqual(w.activeFile, before, "the file an older app reads is untouched");+ assert.deepEqual(w.writes.filter(([file]) => file === "saved"), [], "no file of accounts until there is another");+ assert.deepEqual(w.ring.others(), []);+ assert.equal(w.ring.count(), 1);+ assert.deepEqual(w.revoked, []);+});++test("a downgrade: the active account stays in the old format for the old file, and the others are in a file an older app never opens", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ assert.deepEqual(Object.keys(w.activeFile).sort(), ["account", "device", "expiresAt", "origin", "token"], "exactly what an older app validates");+ assert.equal(w.activeFile.account.id, "acct-b");+ assert.equal(w.savedFile.v, 1);+ w.client.close();+ const older = createCloudAccountClient({ origin: w.origin, fixture: true, deviceName: "Old", platform: "darwin", now: () => w.now, openBrowser: async () => {}, setTimer: () => 1, clearTimer: () => {}, store: { read: async () => w.activeFile, write: async () => { throw new Error("nothing to write"); } } });+ await older.start();+ assert.equal(older.state().status, "connected", "an older app starts signed in, without a crash");+ assert.equal(older.state().account.id, "acct-b");+ older.close();+});++test("add: signs in beside the account in use, which goes on until it succeeds, then the new one is active and the old one waits", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ assert.equal((await w.ring.addStart("[email protected]")).outcome, "sent");+ assert.equal(w.signedInAs(), "acct-a", "still A while the code is on its way");+ assert.equal((await w.ring.addVerify("00000000")).outcome, "wrong-code");+ assert.equal(w.signedInAs(), "acct-a");+ const added = await w.ring.addVerify(CODE);+ assert.deepEqual([added.outcome, added.email], ["switched", "[email protected]"]);+ assert.equal(w.client.state().status, "connected");+ assert.equal(w.signedInAs(), "acct-b");+ assert.deepEqual(w.ring.others(), [{ id: "acct-a", email: "[email protected]" }]);+ assert.equal(w.ring.count(), 2);+ assert.deepEqual(w.revoked, [], "A stays signed in");+ assert.ok(!JSON.stringify([w.ring.others(), added]).includes("omc_"), "no token leaves this module");+});++test("a cancelled add changes nothing and asks nothing of the account in use", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.ring.addStart("[email protected]");+ w.ring.addCancel();+ assert.equal((await w.ring.addVerify(CODE)).outcome, "expired");+ assert.equal(w.signedInAs(), "acct-a");+ assert.deepEqual(w.savedFile, null);+});++test("switch: one tap, no code, each account's own token; a saved account asks nothing while it waits", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.requests.length = 0; w.calls.length = 0;+ assert.deepEqual(await w.ring.switchTo("acct-a"), { outcome: "switched" });+ assert.equal(w.signedInAs(), "acct-a");+ assert.deepEqual(w.requests.map((request) => request.route), ["/api/cloud/desktop/session"], "no sign-in route");+ assert.equal(w.requests[0].token, tokenOf("a"));+ assert.deepEqual(w.calls.filter((call) => !["state"].includes(call)), ["leaving:acct-b", "arriving:acct-a", "settled", "changed"]);+ w.requests.length = 0;+ await w.client.refresh();+ assert.deepEqual(w.requests.map((request) => request.token), [tokenOf("a")], "only the active account's token is ever used");+ assert.deepEqual(ids(w), ["acct-b"]);+ assert.deepEqual(await w.ring.switchTo("acct-a"), { outcome: "switched" }, "already that one");+});++test("three accounts: each is one tap from any other", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b"); await w.addByCode("c");+ assert.deepEqual(ids(w).sort(), ["acct-a", "acct-b"]);+ await w.ring.switchTo("acct-b");+ assert.deepEqual(ids(w).sort(), ["acct-a", "acct-c"]);+ await w.ring.switchTo("acct-a");+ assert.deepEqual(ids(w).sort(), ["acct-b", "acct-c"]);+ assert.equal(w.ring.count(), 3);+ assert.deepEqual(w.revoked, []);+});++test("a switch writes in the order that loses nothing: at every write each token is in a file", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.writes.length = 0;+ await w.ring.switchTo("acct-a");+ assert.deepEqual(w.writes, [["saved", ["acct-a", "acct-b"]], ["active", "acct-a"], ["saved", ["acct-b"]]]);+});++test("a crash mid-switch: an account found in both files is the active one, shown once", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ w.savedFile = { v: 1, accounts: [w.grant("a"), w.grant("b")] };+ await w.boot();+ assert.equal(w.signedInAs(), "acct-a");+ assert.deepEqual(ids(w), ["acct-b"]);+ assert.equal(w.ring.count(), 2);+});++test("the active file can't be written: nothing changes, the account in use goes on, and both tokens are kept", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.failActive = true; w.calls.length = 0;+ await assert.rejects(w.ring.switchTo("acct-a"), /no keychain/);+ assert.equal(w.signedInAs(), "acct-b");+ assert.ok(!w.calls.some((call) => call.startsWith("leaving")), "nothing of B's was stopped");+ assert.equal(w.savedFile.accounts.some((entry) => entry.account.id === "acct-a"), true);+ assert.equal(w.activeFile.account.id, "acct-b");+});++test("sign out of the active account: gone from this device and ended at the Admin, and the app moves to another signed in here", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.calls.length = 0;+ assert.deepEqual(await w.ring.signOut("acct-b"), { outcome: "signed-out" });+ assert.equal(w.signedInAs(), "acct-a");+ assert.deepEqual(w.ring.others(), []);+ assert.deepEqual(w.revoked, [tokenOf("b")]);+ assert.equal(w.savedFile, null);+ assert.ok(w.calls.includes("removed:acct-b"));+ assert.ok(!JSON.stringify(w.activeFile).includes(tokenOf("b")));+});++test("sign out of the last account: signed out, with nothing left on this device", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ w.calls.length = 0;+ assert.deepEqual(await w.ring.signOut("acct-a"), { outcome: "signed-out" });+ assert.equal(w.client.state().status, "signed-out");+ assert.equal(w.activeFile, null);+ assert.deepEqual(w.revoked, [tokenOf("a")]);+ assert.equal(w.ring.count(), 0);+ assert.deepEqual(w.calls.filter((call) => call !== "state"), ["leaving:acct-a", "settled", "removed:acct-a", "changed"]);+});++test("sign out of an account that is waiting: its token ends, and the one in use isn't touched", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.calls.length = 0;+ await w.ring.signOut("acct-a");+ assert.equal(w.signedInAs(), "acct-b");+ assert.deepEqual(w.revoked, [tokenOf("a")]);+ assert.deepEqual(w.ring.others(), []);+ assert.ok(!w.calls.some((call) => call.startsWith("leaving")));+});++test("while the move holds the account: no switch and no sign-out, nothing written; an added account waits", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ await w.addByCode("b");+ w.holding = "moving"; w.writes.length = 0; w.calls.length = 0;+ assert.deepEqual(await w.ring.switchTo("acct-a"), { outcome: "moving" });+ assert.deepEqual(await w.ring.signOut("acct-b"), { outcome: "moving" });+ assert.deepEqual(w.writes, []);+ assert.equal(w.signedInAs(), "acct-b");+ assert.ok(!w.calls.some((call) => call.startsWith("leaving")));+ const added = await w.addByCode("c");+ assert.equal(added.outcome, "added");+ assert.equal(w.signedInAs(), "acct-b", "stays with the move");+ assert.deepEqual(ids(w).sort(), ["acct-a", "acct-c"]);+});++test("adding the account that's already here: its new token ends at once, and the address is said", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ w.freshToken = tokenOf("d");+ const added = await w.addByCode("a");+ assert.equal(added.outcome, "already");+ assert.deepEqual(w.revoked, [tokenOf("d")]);+ assert.equal(w.activeFile.token, tokenOf("a"), "the sign-in in use is still that one");+});++test("a waiting sign-in that ended by its date asks for the code again, and changes nothing", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ w.savedFile = { v: 1, accounts: [w.grant("b", { expiresAt: w.now - 1 })] };+ await w.boot();+ assert.deepEqual(w.ring.others(), [{ id: "acct-b", email: "[email protected]", signIn: true }]);+ assert.deepEqual(await w.ring.switchTo("acct-b"), { outcome: "sign-in", email: "[email protected]" });+ assert.equal(w.signedInAs(), "acct-a");+});++test("a switch to an account no longer here says so", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ await w.boot();+ assert.deepEqual(await w.ring.switchTo("acct-z"), { outcome: "gone" });+});++test("a locked keychain never loses the saved accounts: the switch fails and the file stays; one that can never be read is dropped", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ w.savedFile = { v: 1, accounts: [w.grant("b")] };+ await w.boot();+ w.readSaved = new Error("Unlock your keychain");+ w.writes.length = 0;+ await assert.rejects(w.ring.switchTo("acct-b"), /Unlock/);+ assert.deepEqual(w.writes, []);+ assert.equal(w.savedFile.accounts.length, 1);+ w.readSaved = Object.assign(new Error("corrupt"), { code: "unreadable_record" });+ assert.deepEqual(await w.ring.switchTo("acct-b"), { outcome: "gone" });+});++test("a saved file from a newer version is left alone; a record for another Admin or with a bad token is never used", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ const newer = { v: 2, accounts: [] };+ w.savedFile = newer;+ await w.boot();+ await assert.rejects(w.ring.switchTo("acct-b"), /newer version/);+ assert.deepEqual(w.savedFile, newer);+ w.savedFile = { v: 1, accounts: [{ ...w.grant("b"), origin: "https://elsewhere.test" }, { ...w.grant("c"), token: "stolen" }] };+ assert.deepEqual(await w.ring.switchTo("acct-b"), { outcome: "gone" });+ assert.deepEqual(await w.ring.switchTo("acct-c"), { outcome: "gone" });+ assert.equal(w.signedInAs(), "acct-a");+});++test("a launch with no one active but others waiting: the first still good takes its place; a locked active file is left alone", async (t) => {+ const w = await world(t);+ w.savedFile = { v: 1, accounts: [w.grant("b", { expiresAt: w.now - 1 }), w.grant("c")] };+ await w.boot();+ assert.equal(w.signedInAs(), "acct-c");+ assert.deepEqual(ids(w), ["acct-b"]);+});++test("a sign-in that ended gives way: the code brings that account back with the new token, for the active one and for one waiting", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ w.savedFile = { v: 1, accounts: [w.grant("b", { expiresAt: w.now - 1 })] };+ await w.boot();+ w.freshToken = tokenOf("e");+ assert.equal((await w.addByCode("b")).outcome, "switched");+ assert.equal(w.signedInAs(), "acct-b");+ assert.equal(w.activeFile.token, tokenOf("e"));+ assert.deepEqual(ids(w), ["acct-a"], "A waits, B is there once");+ assert.deepEqual(w.revoked, []);+ w.revoked.push(tokenOf("e"));+ await w.client.refresh();+ assert.equal(w.client.state().status, "reauth-required");+ w.freshToken = tokenOf("f");+ assert.equal((await w.addByCode("b")).outcome, "switched");+ assert.equal(w.activeFile.token, tokenOf("f"));+ assert.equal(w.client.state().status, "connected");+ assert.deepEqual(ids(w), ["acct-a"]);+});++test("until the saved accounts have been read, there may be more than one: nothing that needs one account starts on a guess", async (t) => {+ const w = await world(t);+ w.activeFile = w.grant("a");+ w.make();+ await w.client.start();+ assert.equal(w.ring.count(), 2);+ w.readSaved = new Error("Unlock your keychain");+ await w.ring.start();+ assert.equal(w.ring.count(), 2, "still unknown");+ w.readSaved = null;+ await w.ring.start();+ assert.equal(w.ring.count(), 1);+});diff --git a/electron/cloud-files-accounts.node-test.mjs b/electron/cloud-files-accounts.node-test.mjsnew file mode 100644index 0000000000..40f084fb97--- /dev/null+++ b/electron/cloud-files-accounts.node-test.mjs@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { filesFolderOf, installCloudFiles } from "./cloud-sync-main.mjs";++const scratch = (t) => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-files-accounts-")); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); return dir; };++test("the first account keeps Files' folder as it was; another gets one of its own", (t) => {+ const root = scratch(t);+ assert.equal(filesFolderOf(root, "acct-a"), root, "an upgrade changes nothing for the account that set Files up");+ assert.equal(filesFolderOf(root, "acct-a"), root);+ const b = filesFolderOf(root, "acct-b");+ assert.notEqual(b, root);+ assert.ok(b.startsWith(path.join(root, "accounts")));+ assert.ok(!b.includes("acct-b"), "no account id in a path");+ assert.notEqual(filesFolderOf(root, "acct-c"), b);+});++test("a folder one account shares is never registered on another's Cloud: each account's Files have their own settings, and the one before is closed", (t) => {+ const root = scratch(t), opened = [];+ const makeService = (options) => {+ const service = { settingsFile: options.settingsFile, closed: false, started: 0, start() { this.started++; }, close() { this.closed = true; }, running: () => false, state: () => ({}), wake() {} };+ opened.push(service);+ return service;+ };+ const files = installCloudFiles({ app: { getPath: () => root }, ipcMain: { handle() {} }, dialog: {}, shell: {}, powerMonitor: { on() {} }, fetch: async () => new Response("{}"), localWorkspaceOnly: (_channel, handler) => handler,+ send() {}, cloudOrigin: () => null, cloudAccount: () => ({ state: () => null }), localDataDir: root, makeService, stateDir: "cloud-sync" });+ files.start();+ files.accountChanged("acct-a");+ assert.equal(opened.length, 1, "the first account stays in the folder that was open");+ files.accountChanged("acct-a");+ assert.equal(opened.length, 1, "nothing changed");+ files.accountChanged(null);+ assert.equal(opened.length, 1, "signed out: its Files wait");+ files.accountChanged("acct-b");+ assert.equal(opened.length, 2);+ assert.equal(opened[0].closed, true);+ assert.notEqual(opened[1].settingsFile, opened[0].settingsFile, "B starts from its own settings, with none of A's shared folders");+ assert.equal(opened[1].started, 1);+ files.accountChanged("acct-a");+ assert.equal(opened[2].settingsFile, opened[0].settingsFile, "A's come back as they were");+ files.close();+});diff --git a/electron/cloud-staging.node-test.mjs b/electron/cloud-staging.node-test.mjsindex f6c4e5a556..943e1e96dc 100644--- a/electron/cloud-staging.node-test.mjs+++ b/electron/cloud-staging.node-test.mjs@@ -6,8 +6,8 @@ import { CLOUD_ORIGIN, STAGING_CLOUD_ORIGIN, checkoutDestination, cloudOrigin, cconst accessToken = `omc_${"S".repeat(43)}`;test("OMB_CLOUD_STAGING=1, and only that, points the app at the fixed staging Admin with its own token file", () => {- assert.deepEqual(cloudTarget({}), { origin: CLOUD_ORIGIN, staging: false, file: "cloud-account.bin", environments: "environments.json", sync: "cloud-sync", look: "cloud-home-look.json" });- assert.deepEqual(cloudTarget({ OMB_CLOUD_STAGING: "1" }), { origin: "https://omb-cloud-staging.fly.dev", staging: true, file: "cloud-account-staging.bin",+ assert.deepEqual(cloudTarget({}), { origin: CLOUD_ORIGIN, staging: false, file: "cloud-account.bin", saved: "cloud-accounts.bin", places: "account-places.json", environments: "environments.json", sync: "cloud-sync", look: "cloud-home-look.json" });+ assert.deepEqual(cloudTarget({ OMB_CLOUD_STAGING: "1" }), { origin: "https://omb-cloud-staging.fly.dev", staging: true, file: "cloud-account-staging.bin", saved: "cloud-accounts-staging.bin", places: "account-places-staging.json",environments: "environments-staging.json", sync: "cloud-sync-staging", look: "cloud-home-look-staging.json" });const production = Object.values(cloudTarget({})), staging = Object.values(cloudTarget({ OMB_CLOUD_STAGING: "1" }));assert.ok(staging.filter(value => typeof value === "string").every(name => !production.includes(name)), "no file or address shared with production");@@ -74,7 +74,9 @@ test("main keeps each Admin's sign-in, saved servers, Files state and Cloud nameassert.match(main, /lookFile\(\(\) => path\.join\(app\.getPath\("userData"\), cloudTarget\(process\.env\)\.look\), fs\)/);for (const name of ['"environments.json"', '"cloud-home-look.json"']) assert.equal(main.includes(name), false, `no fixed ${name}`);const ensure = main.slice(main.indexOf("function ensureCloudAccount() {"), main.indexOf("\n}\n", main.indexOf("function ensureCloudAccount() {")));- assert.match(ensure, /createCloudAccountStore\(\{ file: path\.join\(app\.getPath\("userData"\), cloudTarget\(process\.env\)\.file\)/);+ assert.match(ensure, /store: cloudAccountStore\(\),/);+ assert.match(main, /const cloudAccountStore = \(\) => \(activeSignIn \?\?= createCloudAccountStore\(\{ file: path\.join\(app\.getPath\("userData"\), cloudTarget\(process\.env\)\.file\)/);+ assert.match(main, /createCloudAccountStore\(\{ file: path\.join\(app\.getPath\("userData"\), cloudTarget\(process\.env\)\.saved\)/);assert.match(ensure, /origin: cloudTarget\(process\.env\)\.origin,/);assert.equal(main.includes('"cloud-account.bin"'), false, "no second, fixed token file");});diff --git a/electron/cloud-sync-main.mjs b/electron/cloud-sync-main.mjsindex 88a81740fd..b079374469 100644--- a/electron/cloud-sync-main.mjs+++ b/electron/cloud-sync-main.mjs@@ -1,6 +1,7 @@// Wires Files into the desktop app: the service with Electron's pieces, and its channels for this computer's own window// only. A folder reaches `share` only as a token for one the person picked (or the app suggested and checked) here.-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";+import fs from "node:fs";import path from "node:path";import { createCloudFilesService } from "./cloud-sync.mjs";import { createDownloadMarker } from "./cloud-sync-mark.mjs";@@ -9,19 +10,29 @@ import { lendingForFiles } from "./lent-folders.mjs";const TOKEN_MS = 30 * 60_000;+/** Whose Files this folder keeps: the first account to use it, as it was before there could be several. Another account's+ * are in a folder of their own, so a folder one account shares is never registered on another's Cloud. */+export function filesFolderOf(root, accountId, read = (file) => { try { return JSON.parse(fs.readFileSync(file, "utf8")).accountId ?? null; } catch { return null; } },+ write = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value), { mode: 0o600 }); }) {+ const owner = path.join(root, "account.json"), first = read(owner);+ if (!first) write(owner, { accountId });+ return !first || first === accountId ? root : path.join(root, "accounts", createHash("sha256").update(accountId).digest("hex").slice(0, 32));+}+/** `stateDir`: Files' own folder under userData; the staging Admin keeps its own (cloud-account.mjs cloudTarget).* `lending`: main's pieces for lending to My Cloud ({ environment, sharing, validate }): each lent folder gets a copy,* and a folder added here is lent, read only (lent-folders.mjs). */-export function installCloudFiles({ app, ipcMain, dialog, shell, powerMonitor, fetch, localWorkspaceOnly, send, cloudOrigin, cloudAccount, localDataDir, power, lending: lendingParts = null, now = Date.now, stateDir = "cloud-sync" }) {+export function installCloudFiles({ app, ipcMain, dialog, shell, powerMonitor, fetch, localWorkspaceOnly, send, cloudOrigin, cloudAccount, localDataDir, power, lending: lendingParts = null, now = Date.now, stateDir = "cloud-sync", makeService = createCloudFilesService }) {const lending = lendingParts ? lendingForFiles(lendingParts) : null;- const dir = path.join(app.getPath("userData"), stateDir);- const service = createCloudFilesService({+ const root = path.join(app.getPath("userData"), stateDir);+ const open = (dir) => makeService({settingsFile: path.join(dir, "settings.json"), stateFile: path.join(dir, "state.db"),documentsDir: app.getPath("documents"), homeDir: app.getPath("home"), localDataDir, cloudOrigin, fetch, ...(power ? { power } : {}),trashItem: (file) => shell.trashItem(file), markDownloaded: createDownloadMarker(),onChange: (state) => send("files:state-changed", state),lending, planDisk: () => { try { return cloudPlanDisk(cloudAccount().state()); } catch { return null; } },});+ let dir = root, service = open(dir), started = false;const tokens = new Map();const issue = (checked) => {for (const [token, entry] of tokens) if (entry.at + TOKEN_MS < now()) tokens.delete(token);@@ -77,10 +88,22 @@ export function installCloudFiles({ app, ipcMain, dialog, shell, powerMonitor, flet lentSeen = null, follow = null;const lentNow = () => { try { return JSON.stringify(lending?.now() ?? null); } catch { return null; } };const start = () => {+ started = true;service.start();lentSeen = lentNow();follow ??= setInterval(() => { const next = lentNow(); if (next !== lentSeen) { lentSeen = next; service.wake(); } }, 15_000);follow.unref?.();};- return { start, running: () => service.running(), close: () => { clearInterval(follow); service.close(); } };+ /** The signed-in account changed: its own Files go on, and nothing recorded for the one before applies. */+ const accountChanged = (accountId) => {+ if (!accountId) return;+ const next = filesFolderOf(root, accountId);+ if (next === dir) return;+ service.close();+ dir = next;+ service = open(dir);+ tokens.clear();+ if (started) service.start();+ };+ return { start, accountChanged, running: () => service.running(), close: () => { clearInterval(follow); service.close(); } };}diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mtsindex 99717b1e4c..2f83c041a0 100644--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@ -144,6 +144,8 @@ export function createComputerSharing(options: {cloudState(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;lendingToCloud(): boolean;/** A server is using this computer now: a job running on it, or its browsing going through this computer. */busy(): boolean;diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex 8131136eee..468ad6752c 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -822,6 +822,18 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cuchanged();void lendAutomatically();},+ /** Another account takes over: this computer stops being lent to this one's Clouds, as when this app quits. Nothing is+ * told to them (one asleep stays asleep) and what was lent is kept, so lending goes on if it comes back. */+ leaveAccount(accountId) {+ if (!accountId) return;+ for (const [id, grant] of Object.entries(records)) {+ if (grant?.cloud?.accountId !== accountId) continue;+ stop(id);+ const entry = asking.get(id);+ if (entry) { entry.stop.abort(); asking.delete(id); }+ }+ changed();+ },cloudChanged() {if (closed) return;// The Admin's word on each other Cloud may have changed: a lending loop waiting for one to wake goes on.diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjsindex 982e5b95ac..b20496d1d3 100644--- a/electron/fixtures/home-window-world.mjs+++ b/electron/fixtures/home-window-world.mjs@@ -18,7 +18,7 @@ export const json = (body, status = 200, headers = {}) => new Response(JSON.stri* sign-in (its power word, wake, pairing code), My Cloud's answers (`cloud`), the window (where it went), the startup* screen and a manual clock.*/-export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null, ownMove = null } = {}) {+export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null, ownMove = null, deps = {} } = {}) {const w = {journal, marker, state, power, ownMove, clock: 1_000_000, typed: 0, now: () => w.clock,cloud: { down: false, signedIn: true, version: "0.1.130", health: 200, wakes: true, ...cloud },@@ -79,6 +79,7 @@ export function world({ journal = done(), marker = null, state = connected(), pojournal: () => w.journal,frozen: async () => w.marker,ownMove: () => w.ownMove,+ ...deps,account: () => account,window: () => w.window,ensureWindow: () => { w.calls.push("ensure"); },diff --git a/electron/home-window.d.mts b/electron/home-window.d.mtsindex 5e48934992..18c718da6e 100644--- a/electron/home-window.d.mts+++ b/electron/home-window.d.mts@@ -6,7 +6,8 @@ export type HomeView = { name?: string } & (/** The Admin is setting it up (or a brand-new one's name isn't found yet, at `checking`): the step it reports. */| { screen: "setup"; step?: import("./cloud-home.mjs").CloudSetupStep; slow?: true }| { screen: "offline"; reason?: string }- | { screen: "signin"; other?: true }+ /** `movedTo`: this computer's bots moved to that account's Cloud, and it is signed in on this device too. */+ | { screen: "signin"; other?: true; movedTo?: { id: string; email: string } }| { screen: "plan"; machine: "stopped" | "payment-problem" | "failed" }/** A Cloud the session's list says isn't running, so nothing looks up its address: it has ended (`deleteAt`: when its kept* files are deleted), its checkout wasn't finished, or its payment has a problem; `removable` while its owner may take itdiff --git a/electron/home-window.mjs b/electron/home-window.mjsindex 64d3d3b3c5..50e74aa241 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -72,6 +72,12 @@ export function homeOf({ journal = null, frozenCloud = null, state = null }) {: frozenCloud ? { origin: typeof frozenCloud === "string" ? frozenCloud : null, account: null } : null;if (!moved) return { kind: "computer" };const connected = state?.status === "connected";+ const signedInNow = state?.account?.id ?? null;+ // This computer moved to another account's Cloud: its frozen copy stays frozen, and this account's own Cloud is what opens.+ if (moved.account && signedInNow && moved.account !== signedInNow && state.status !== "signed-out" && state.status !== "connecting") {+ const own = connected && !state.machine?.hold ? state.machine?.origin ?? null : null;+ return own && own !== moved.origin ? { kind: "cloud", origin: own, otherAccount: true } : { kind: "signin", other: true };+ }if (connected && state.machine?.hold && (!moved.origin || !state.machine.origin || state.machine.origin === moved.origin)) return { kind: "computer" };const signedIn = state?.account?.id ?? null;if (!signedIn || state.status === "signed-out" || state.status === "connecting") return { kind: "signin" };@@ -178,6 +184,8 @@ export function routeOf(url, origin) {* power: { asleep(): boolean, hold(): void, woke(): void },* go(url: string, origin: string | null, place: { kind: "cloud", origin: string } | { kind: "team" | "own", id: string, name: string, role: string | null, origin: string } | null): Promise<unknown>,* showLocal(leaving: boolean): unknown,+ * signInOther?(): Promise<unknown>,+ * movedAccount?(accountId: string | undefined): { id: string, email: string } | null,* remembered?(): ({ team: string } | { cloud: string }) & { name?: string, origin?: string } | null,* remember?(place: { team: string } | { cloud: string } | null): void,* left?(name: string): void,@@ -199,6 +207,8 @@ export function routeOf(url, origin) {* became ready (createReadyClock). `go(url, origin, place)`: main's one way to move the window, to My Cloud or a team's Cloud (`origin`, with the* `place` it is) or this computer's screen (null). `showLocal(leaving)`: the window as it was before the move (this computer's page, or a saved server it* shows); `leaving`: it showed a place or this computer's screen until now, so it goes back to this computer's page.+ * `signInOther()`: the account this computer moved to signs in beside the one signed in now, which stays;+ * `movedAccount(id)`: that account, while it is signed in on this device too.* `frozen()`: this computer's server's freeze marker. `splash()`: the startup screen while it is up. `remembered()`: the* team or other Cloud shown last time, with its name and origin as saved; `remember(place)`: what to open next time;* `left(name)`: the team shown is no longer this person's, so the window says so once; `drop(place)`: the Admin said so@@ -207,7 +217,7 @@ export function routeOf(url, origin) {*/export function createHomeWindow(deps) {const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal,- remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },+ signInOther = null, movedAccount = () => null, remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },splash = () => null, lastInput = () => 0, publish = () => {}, rehomed = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {} } = deps;let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;@@ -521,7 +531,11 @@ export function createHomeWindow(deps) {return showLocal(leaving);}ensureWindow();- if (current.kind === "signin") { clearRetry(); return toScreen({ screen: "signin", ...(current.other ? { other: true } : {}) }); }+ if (current.kind === "signin") {+ clearRetry();+ const movedTo = current.other ? movedAccount(parseJournal(journal())?.cloud?.account) : null;+ return toScreen({ screen: "signin", ...(current.other ? { other: true } : {}), ...(movedTo ? { movedTo } : {}) });+ }return connect({ kind: "cloud", origin: current.origin }, token, open);}@@ -626,6 +640,7 @@ export function createHomeWindow(deps) {if (status !== "signed-out") {const current = await refresh();if (!(current.kind === "signin" && current.other)) return void await show();+ if (signInOther) return void await signInOther();await client.signOut?.();}await client.begin();diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjsindex 93084e6929..21a3595282 100644--- a/electron/home-window.node-test.mjs+++ b/electron/home-window.node-test.mjs@@ -858,3 +858,32 @@ test("an account leaving: nothing under way for it goes on, and the next show taawait 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 --git a/electron/lending-accounts.node-test.mjs b/electron/lending-accounts.node-test.mjsnew file mode 100644index 0000000000..c87d6f5b63--- /dev/null+++ b/electron/lending-accounts.node-test.mjs@@ -0,0 +1,70 @@+import assert from "node:assert/strict";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { randomUUID } from "node:crypto";+import { test } from "node:test";+import { createComputerSharing } from "./computer-sharing.mjs";++const until = async (check, what) => { for (let i = 0; i < 400; i++) { if (check()) return; await new Promise((resolve) => setTimeout(resolve, 5)); } assert.fail(`never: ${what}`); };++async function fixture(t) {+ const dir = await mkdtemp(path.join(tmpdir(), "omb-lending-accounts-"));+ const env = { id: "cloud-a", origin: "https://a.fixture.test", name: "A's Cloud", cloud: { id: "c" } };+ const f = { env, account: "acct-a", status: "connected", origin: env.origin, places: [env], polls: [], asks: [], routes: [], live: () => [...f.polls, ...f.asks].filter((signal) => !signal.aborted).length };+ const identity = { sessionId: randomUUID(), environmentId: randomUUID() };+ const hold = (signal, list) => new Promise((resolve, reject) => { list.push(signal); signal.throwIfAborted(); signal.addEventListener("abort", () => reject(signal.reason), { once: true }); });+ f.sharing = createComputerSharing({+ file: path.join(dir, "sharing.json"), environments: () => f.places, enabled: async () => false, home: path.join(dir, "home"),+ cloud: () => ({ status: f.status, accountId: f.account, origin: f.origin }), myCloud: () => f.places[0] ?? null, ownClouds: () => f.places,+ hostControl: async () => ({ renew: async () => {}, release: async () => {} }), screen: () => false,+ async fetch(url, { signal }) {+ const route = new URL(url).pathname;+ f.routes.push(route);+ if (route === "/api/auth/session") return Response.json({ kind: "session", id: identity.sessionId, cloudHome: true, scopes: ["admin"] });+ if (route === "/.well-known/openmausbot/environment") return Response.json({ environmentId: identity.environmentId, capabilities: { sharedComputers: true, computerAsks: true, asks: true } });+ if (route.endsWith("/poll")) await hold(signal, f.polls);+ if (route === "/api/shared-computers/asks") await hold(signal, f.asks);+ return Response.json({ ok: true });+ },+ });+ t.after(async () => { f.sharing.close(); await rm(dir, { recursive: true, force: true }); });+ return f;+}++test("switching: this computer stops working for the account left, its Cloud is told nothing and can go to sleep, and it comes back with that account", async (t) => {+ const f = await fixture(t);+ await f.sharing.saveCloud(f.env, { folders: [], internet: true });+ f.sharing.cloudChanged();+ await until(() => f.polls.length > 0, "the lent connection");+ assert.equal(f.sharing.lendingToCloud(), true);+ f.routes.length = 0;++ f.sharing.leaveAccount("acct-a");+ assert.equal(f.live(), 0, "the lent connection and the asks' long poll both ended");+ assert.equal(f.sharing.lendingToCloud(), false, "nothing wants that Cloud awake");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(f.routes.filter((route) => route.endsWith("/disconnect")), [], "no request that could wake a sleeping Cloud");+ assert.equal(f.sharing.cloudState(f.env).enabled, true, "what was lent is kept");++ f.account = "acct-b"; f.origin = null; f.places = [];+ f.sharing.cloudChanged();+ const dialled = f.polls.length;+ await new Promise((resolve) => setTimeout(resolve, 30));+ assert.equal(f.polls.length, dialled, "nothing dials the account left");++ f.account = "acct-a"; f.origin = f.env.origin; f.places = [f.env];+ f.sharing.cloudChanged();+ await until(() => f.sharing.lendingToCloud(), "lending again");+ await until(() => f.live() > 0, "its connection again");+});++test("leaving another account, or none, stops nothing", async (t) => {+ const f = await fixture(t);+ await f.sharing.saveCloud(f.env, { folders: [], internet: true });+ f.sharing.cloudChanged();+ await until(() => f.polls.length > 0, "the lent connection");+ f.sharing.leaveAccount("acct-z");+ f.sharing.leaveAccount(null);+ assert.equal(f.sharing.lendingToCloud(), true);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 7c47b920ca..8336dcaaf6 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -108,7 +108,7 @@ import { installOneHome } from "./one-home-main.mjs"; import { handSaved, instalimport { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";-import { createHomePlaces } from "./home-places.mjs"; import { createAccountLeave, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";+import { createHomePlaces } from "./home-places.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";import { createWindowStateFile } from "./window-state-file.mjs";import { createEnvironmentsFile } from "./environments-file.mjs";import { createOrgLibrary } from "./org-library.mjs";@@ -820,16 +820,16 @@ function syncPhoneSecretKey(proc) {}}-const cloudEncryption = { available: async () => (await safeStorage.isAsyncEncryptionAvailable()) && (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"), encrypt: value => safeStorage.encryptStringAsync(value), decrypt: value => safeStorage.decryptStringAsync(value) };+const cloudEncryption = { available: async () => (await safeStorage.isAsyncEncryptionAvailable()) && (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"), encrypt: value => safeStorage.encryptStringAsync(value), decrypt: value => safeStorage.decryptStringAsync(value) }; let activeSignIn = null; const cloudAccountStore = () => (activeSignIn ??= createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).file), encryption: cloudEncryption }));function ensureCloudAccount() {if (cloudAccount) return cloudAccount;if (!app.isPackaged || desktopRemoteAccess) throw new Error("MausBot Cloud sign-in requires the local desktop app.");cloudAccount = createCloudAccountClient({- store: createCloudAccountStore({ file: path.join(app.getPath("userData"), cloudTarget(process.env).file), encryption: cloudEncryption }),+ store: cloudAccountStore(),platform: process.platform, deviceName: os.hostname().slice(0, 100) || "My computer", appVersion: app.getVersion(), origin: cloudTarget(process.env).origin,openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(),onState: state => {- rememberCloudHome(state);+ cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);rememberedHome = rememberedCloudHome(rememberedHome, state);sendUpdaterState();cloudPower.changed(); computerSharing?.cloudChanged(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); } catch {}@@ -2657,10 +2657,10 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(const 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 }); 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, 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"); } });// 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({ journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,+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,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,@@ -2688,7 +2688,8 @@ const chromeRail = createChromeRail({ createView: options => new WebContentsViewchromeRail.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 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), log: slog }), show: () => showHome(), tell: () => { for (const page of accountPages) page()?.send("accounts:changed"); } });+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 rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),@@ -3103,7 +3104,7 @@ app.whenReady().then(async () => {// Fresh local use never makes a Cloud request; start only restores an existing grant.if (app.isPackaged && !desktopRemoteAccess) {cloudAccountRestoring = true;- cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).finally(() => { cloudAccountRestoring = false; });+ cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).then(() => accountRing()?.start()).finally(() => { cloudAccountRestoring = false; });}void cloudAccountStarted.then(() => { cloudSignInRestored = true; void oneHome.kick(); void homeWindow.refresh(); }); void ownHome?.kick();if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away()) {@@ -3194,7 +3195,7 @@ app.on("before-quit", (e) => {companyBackupSchedule?.close();orgLibrary?.close();managedDesktop?.close();- cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close();+ accountRing.close(); cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close();companyBackupController?.abort();computerSharing?.close();cloudSync.close();diff --git a/electron/one-home-accounts.node-test.mjs b/electron/one-home-accounts.node-test.mjsnew file mode 100644index 0000000000..974dfdd932--- /dev/null+++ b/electron/one-home-accounts.node-test.mjs@@ -0,0 +1,140 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createOneHome } from "./one-home.mjs";+import { installOneHome } from "./one-home-main.mjs";++const CLOUD_A = "https://omb-a.fly.dev", CLOUD_B = "https://omb-b.fly.dev";+const cloudOf = (account, origin) => ({ origin, account, machine: origin, ready: true, moves: true, ended: false, paid: true, verified: true, signIn: `device-${account}` });+const movedToA = (phase = "done") => ({ v: 1, phase, cloud: { origin: CLOUD_A, account: "a", machine: CLOUD_A }, doneAt: 1, version: "1", lent: true, phoneStopped: true, reported: "device-a", told: false });++/** One home with fakes: the journal, this computer's server, each pass and every call to a Cloud or the Admin. */+function world({ journal = null, cloud = cloudOf("b", CLOUD_B), marker = { frozen: false }, gone = async () => null, onPass = () => {} } = {}) {+ const w = { journal, cloud, marker, passes: [], unfreezes: [], freezes: 0, sessions: 0, reports: 0, gone: [], running: null };+ w.home = createOneHome({+ journal: { read: () => structuredClone(w.journal), write: (value) => { w.journal = structuredClone(value); } },+ cloud: () => (w.cloud ? { ...w.cloud } : null),+ send: { async move(options) { w.passes.push(options?.final ? "final" : "copy"); await onPass(w); }, check: async () => ({ ok: true }), switches: () => ({}), snapshot: () => ({ running: w.running }) },+ local: {+ freeze: async () => { w.freezes++; w.marker = { frozen: true }; return { frozen: true }; },+ unfreeze: async (options) => { w.unfreezes.push(options ?? null); w.marker = { frozen: false }; },+ frozen: async () => w.marker.frozen, marker: async () => w.marker, json: async () => ({}), call: async () => ({ ok: true, status: 200, body: {} }), forget: async () => {},+ },+ gone: async (origin) => { w.gone.push(origin); return gone(origin); },+ session: async () => { w.sessions++; return { call: async () => ({ ok: true, status: 200, body: {} }), close: async () => {} }; },+ reportMove: async () => { w.reports++; return true; }, lastInput: () => 0, version: "1", now: () => 1_000_000, timers: { set: () => 1, clear() {} },+ });+ return w;+}++for (const phase of ["done", "switch", "keeping", "home-again", "back", "copy", "wait"]) {+ test(`this computer's move to A's Cloud (${phase}), and B is signed in: the journal stays, no freeze lifts, nothing moves, nothing is told`, async () => {+ const w = world({ journal: movedToA(phase), marker: { frozen: true, cloud: CLOUD_A } });+ const before = structuredClone(w.journal);+ await w.home.kick();+ assert.deepEqual(w.journal, before, "the journal is exactly as it was");+ assert.deepEqual([w.passes, w.unfreezes, w.sessions, w.reports, w.freezes], [[], [], 0, 0, 0]);+ assert.deepEqual(w.gone, [], "B's Admin is asked nothing about A's Cloud");+ assert.equal(w.home.view(), null, "no line about A's move on B's pages");+ assert.equal(w.home.moving(), false, "nothing holds B: B can switch away again");+ });+}++test("back to A: the same move goes on from where it was, and its line returns", async () => {+ const w = world({ journal: { ...movedToA("copy"), doneAt: undefined } });+ await w.home.kick();+ assert.deepEqual(w.passes, []);+ w.cloud = cloudOf("a", CLOUD_A);+ await w.home.kick();+ assert.equal(w.passes[0], "copy");+ assert.equal(w.journal.cloud.account, "a");+ assert.notEqual(w.home.view(), null);+});++test("no first move for the wrong account: a journal of A's never becomes a move to B, whichever phase it is in", async () => {+ const w = world({ journal: movedToA("back") });+ await w.home.kick();+ assert.equal(w.journal.cloud.origin, CLOUD_A);+ assert.deepEqual(w.passes, []);+});++test("the account changes during a pass: no next step runs, no freeze starts, for either account", async () => {+ const w = world({ cloud: cloudOf("a", CLOUD_A), onPass: (at) => { at.cloud = cloudOf("b", CLOUD_B); } });+ await w.home.kick();+ assert.deepEqual(w.passes, ["copy"], "the pass under way ended; the next read My Cloud from the new sign-in and never ran");+ assert.equal(w.freezes, 0);+ assert.equal(w.journal.cloud.account, "a");+ assert.equal(w.sessions, 0);+});++test("the account changes while frozen for a pass: the freeze this move took lifts, and the move goes back to its copy, still A's", async () => {+ const w = world({ journal: { ...movedToA("final"), frozenAt: 1, doneAt: undefined }, cloud: cloudOf("b", CLOUD_B), marker: { frozen: true, cloud: CLOUD_A } });+ await w.home.kick();+ assert.equal(w.journal.phase, "copy");+ assert.equal(w.journal.cloud.account, "a");+ assert.equal(w.journal.failure?.code ?? "other_account", "other_account");+ assert.deepEqual(w.passes, []);+});++for (const phase of ["wait", "freeze", "final", "check", "switch"]) {+ test(`the move past where it can stop (${phase}) holds the account signed in: the switcher refuses, so no freeze is ever lifted by a switch`, () => {+ const w = world({ journal: movedToA(phase), cloud: cloudOf("a", CLOUD_A) });+ assert.equal(w.home.moving(), true);+ });+}++test("a pass copying now holds its account too; a journal at rest doesn't", () => {+ const copying = world({ journal: movedToA("copy"), cloud: cloudOf("a", CLOUD_A) });+ assert.equal(copying.home.moving(), false);+ copying.running = { phase: "chats" };+ assert.equal(copying.home.moving(), true);+ assert.equal(world({ journal: movedToA("done"), cloud: cloudOf("a", CLOUD_A) }).home.moving(), false);+});++test("a freeze with no journal, naming A's Cloud: B's Admin doesn't know that Cloud, so it stays frozen and no move starts", async () => {+ const w = world({ marker: { frozen: true, cloud: CLOUD_A } });+ await w.home.kick();+ assert.deepEqual(w.gone, [CLOUD_A], "asked of B's Admin, which answers only for B's own Clouds");+ assert.deepEqual([w.unfreezes, w.passes, w.freezes], [[], [], 0]);+ assert.equal(w.journal, null);+});++function main({ state, accounts = 1, journal = null, marker = { frozen: false } }) {+ let kept = journal, passes = 0;+ const handlers = new Map();+ const reply = (value) => new Response(JSON.stringify(value), { status: 200 });+ const installed = installOneHome({+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, cloudPage: () => "local", server: () => null, home: () => null, cookieFetch: async () => reply({}), reconnect: async () => false,+ power: { asleep: () => false }, file: () => "/nonexistent/cloud-send.json", window: () => null, localOrigin: () => "http://127.0.0.1:4100", fetch: async () => reply({}),+ localRequest: async (route) => { if (route.startsWith("/api/cloud-send")) passes++; return route === "/api/move/freeze" ? reply(marker) : reply({}); },+ account: () => ({ state: () => state, reportMoveStatus: async () => { throw new Error("nothing is reported"); } }), journalFile: () => "/nonexistent/one-home.json", tempRoot: () => "/nonexistent",+ journal: { read: () => kept, write: (value) => { kept = value; } }, keep: { read: () => null, write() {} }, accountsHere: () => accounts,+ });+ return { installed, handlers, journal: () => kept, passes: () => passes };+}+const withCloud = (id, origin) => ({ status: "connected", deviceId: `device-${id}`, account: { id, email: `${id}@example.test` }, entitlement: { plan: "pro", status: "active", expiresAt: 9e15, version: 1 }, machine: { status: "ready", origin, moves: true } });++test("one account with a Cloud: its first move starts as ever; with a second account signed in here, none starts by itself", async () => {+ const one = main({ state: withCloud("b", CLOUD_B), accounts: 1 });+ await one.installed.oneHome.kick();+ assert.equal(one.journal()?.cloud?.account, "b");+ one.installed.close();+ const two = main({ state: withCloud("b", CLOUD_B), accounts: 2 });+ await two.installed.oneHome.kick();+ assert.equal(two.journal(), null, "this computer's own workspace stays as it is");+ two.installed.close();+});++test("a move under way stays with its account when a second one signs in here", async () => {+ const running = main({ state: withCloud("a", CLOUD_A), accounts: 2, journal: { ...movedToA("copy"), doneAt: undefined } });+ await running.installed.oneHome.kick();+ assert.notEqual(running.journal().paused, true);+ running.installed.close();+});++test("Keep this computer's bots here isn't offered to B for A's move, and a move's status isn't reported through B's sign-in", async () => {+ const f = main({ state: withCloud("b", CLOUD_B), accounts: 2, journal: movedToA("done"), marker: { frozen: true, cloud: CLOUD_A } });+ const keep = await f.handlers.get("one-home:keep")({});+ assert.equal(keep.shown, false);+ assert.equal(f.installed.holding(), null);+ f.installed.close();+});diff --git a/electron/one-home-main.d.mts b/electron/one-home-main.d.mtsindex c33911d509..30793a236c 100644--- a/electron/one-home-main.d.mts+++ b/electron/one-home-main.d.mts@@ -44,6 +44,8 @@ export function installOneHome(deps: Omit<SendDeps, "local" | "move" | "moveSessother?(): null | { view(): unknown; seen(): unknown; retry(): Promise<unknown>; active(): boolean };}): ReturnType<typeof installCloudSend> & {keep: { state(): KeepHereState; set(on: boolean): Promise<void> };+ /** Why the account signed in can't be left now, else null. */+ holding(): "moving" | null;kick(): Promise<void>;away(): boolean;view(): OneHomeView | null;diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjsindex 039fa50c0f..7fde8f58f0 100644--- a/electron/one-home-main.mjs+++ b/electron/one-home-main.mjs@@ -117,7 +117,9 @@ async function answer(response) {* keep?: { read(): unknown, write(value: unknown): void },* reportTimers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void },* other?(): null | { view(): unknown, seen(): unknown, retry(): Promise<unknown>, active(): boolean },- * }} deps `localRequest`: this computer's server, as its owner (main adds the owner's header). `account`: the MausBot+ * accountsHere?(): number,+ * }} deps `accountsHere`: how many accounts are signed in on this device: with more than one, which Cloud this computer's bots+ * belong in is the person's to say, so no first move starts by itself. `localRequest`: this computer's server, as its owner (main adds the owner's header). `account`: the MausBot* Cloud sign-in (cloud-account.mjs). `journal`: where the move's journal is kept, journalFile by default; `keep`: the* person's choice to keep this computer's bots here, one-home-keep.json beside it by default. `openTeam`:* shows a team's page, where a bot moved into it from My Cloud now lives (team-move-main.mjs, whose journal is@@ -127,7 +129,7 @@ async function answer(response) {* installCloudSend's.*/export function installOneHome({ localRequest, account, journalFile, tempRoot, lend, phone, openHome, openLocal, restart, version, log = () => {}, journal: kept, keep: keptChoice, openTeam, teamJournal,- reportTimers, other = () => null, ...sendDeps }) {+ reportTimers, other = () => null, accountsHere = () => 1, ...sendDeps }) {const fetchImpl = sendDeps.fetch ?? globalThis.fetch;let home = null;let lastInput = 0;@@ -146,7 +148,10 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, lconst report = createMoveStatusReport({status,// A sign-in the Admin has ended (or that expired) only gets 401s until the person signs in again.- signIn: () => { const state = account()?.state(); return state?.status === "reauth-required" ? null : state?.deviceId ?? null; },+ signIn: () => {+ const state = account()?.state(), moved = parseJournal(journal.read());+ return state?.status === "reauth-required" || (moved && state?.account?.id !== moved.cloud.account) ? null : state?.deviceId ?? null;+ },send: async (body) => (await account()?.reportMoveStatus?.(body)) === true,log,...(reportTimers ? { timers: reportTimers } : {}),@@ -219,7 +224,11 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, lhome = createOneHome({journal,// Every run starts here: the key watch is set up before any wait asks, so a key pressed since then counts.- cloud: () => { typed(); const cloud = oneHomeCloud(account()?.state()); return cloud && other()?.active() ? { ...cloud, moves: false } : cloud; },+ cloud: () => {+ typed();+ const cloud = oneHomeCloud(account()?.state()), moved = parseJournal(journal.read());+ return cloud && (other()?.active() || (accountsHere() > 1 && (!moved || moved.phase === "back"))) ? { ...cloud, moves: false } : cloud;+ },send,local: {...local,@@ -259,7 +268,7 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, l* applies to; `moved`, turning it on brings this computer's bots home; `coming`, they are on their way past turning back. */const keepState = () => {const cloud = oneHomeCloud(account()?.state()), moving = parseJournal(journal.read());- return { shown: Boolean(cloud?.origin) && (cloud.moves || Boolean(moving) || home.keeps()), on: home.keeps(), moved: awayIn(moving) && moving.phase !== "keeping",+ return { shown: Boolean(cloud?.origin) && (!moving || moving.cloud.account === cloud.account) && (cloud.moves || Boolean(moving) || home.keeps()), on: home.keeps(), moved: awayIn(moving) && moving.phase !== "keeping",coming: underWay(moving) };};const onPage = (channel, handler) => (event, ...args) => {@@ -277,6 +286,8 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, l...send,/** The switch "Keep this computer's bots on this computer", as Settings shows it, and the person turning it. */keep: { state: keepState, set: (on) => home.keep(on === true) },+ /** Why the account signed in can't be left now: its move, or a bot of its own moving into a team, is under way. */+ holding: () => { const bot = teamMove.view()?.phase; return home.moving() || (bot && !["done", "failed"].includes(bot)) ? "moving" : null; },/** Goes on with the move, and with any bot moving into a team: at launch, and whenever the MausBot Cloud sign-in changes. */kick: () => { void teamMove.kick(); return home.kick(); },/** Home is My Cloud: this computer's own server is frozen for good, and its phone link stays off. */diff --git a/electron/one-home.d.mts b/electron/one-home.d.mtsindex d004fa3a7d..b937d61f00 100644--- a/electron/one-home.d.mts+++ b/electron/one-home.d.mts@@ -104,6 +104,8 @@ export function createOneHome(deps: {away(): boolean;/** A move or a send under way that restarting this app would cut into. */busy(): boolean;+ /** The move of the account signed in is past where it can stop by itself: that account can't be left for a moment. */+ moving(): boolean;keeps(): boolean;/** Throws once this computer's bots are on their way home past turning back and `on` is false. */keep(on: boolean): Promise<void>;diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex 4a5159fc39..166305602e 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -194,6 +194,8 @@ export function createOneHome(deps) {publish();return next;};+ /** Someone else is signed in than the account this journal's move belongs to. */+ const anotherAccount = (journal) => { const cloud = deps.cloud(); return Boolean(journal && cloud && cloud.account !== journal.cloud.account); };const later = (ms) => {if (closed) return;if (timer) timers.clear(timer);@@ -204,6 +206,7 @@ export function createOneHome(deps) {* until it is closed, and coming home; `place`, a server of the person's own the move goes to, by its name. Null when* there is nothing to say. */function view() {+ if (anotherAccount(read())) return null;const seen = phaseView(), place = read()?.cloud?.name;return seen && typeof place === "string" ? { ...seen, place } : seen;}@@ -641,6 +644,8 @@ export function createOneHome(deps) {if (journal.phase === "copy" && waiting()) { later(journal.retryAt - now()); return; }}for (let step = 0; journal && step < 12 && !closed && !kept(); step++) {+ // Each step reads My Cloud from the sign-in: none of them ever runs for an account that signed in since the last.+ if (anotherAccount(journal)) { if (FROZEN.has(journal.phase)) await failed(journal, tagged("Another MausBot Cloud account signed in.", "other_account"), true); break; }if (journal.phase === "copy") journal = await copy(journal);else if (journal.phase === "wait") journal = await wait(journal);else if (journal.phase === "freeze") journal = await freeze(journal);@@ -675,6 +680,9 @@ export function createOneHome(deps) {away: () => awayIn(read()),/** A move or a send under way that restarting this app would cut into. */busy: () => Boolean(running) || Boolean(deps.send.snapshot?.()?.running) || CUT_SHORT.has(read()?.phase ?? ""),+ /** The move belonging to the account signed in is under way, past where it can stop by itself: that account can't be+ * left for a moment, or this computer's freeze would have to lift for the other. */+ moving: () => { const journal = read(); return !anotherAccount(journal) && (Boolean(deps.send.snapshot?.()?.running) || CUT_SHORT.has(journal?.phase ?? "")); },/** This computer keeps its bots here: the person's own choice. */keeps: kept,/** Keeps this computer's bots here (`on`), or lets them move with everything else again, at the next quiet moment asdiff --git a/electron/preload.cjs b/electron/preload.cjsindex c32ec6b923..2d42946b4f 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -500,7 +500,13 @@ 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 --git a/src/components/AccountMenu.test.ts b/src/components/AccountMenu.test.tsindex 073b6b1bb4..518145fc74 100644--- a/src/components/AccountMenu.test.ts+++ b/src/components/AccountMenu.test.ts@@ -1,26 +1,55 @@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]" };-it("one account: its address, then Sign out", () => {- const items = accountMenuItems({ view: { active: { id: "a", email: "[email protected]" }, others: [] }, openSheet: null, signOut });- expect(items.map((item) => item.label)).toEqual(["[email protected]", "Sign out"]);+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");items[1].onSelect();- expect(signOut).toHaveBeenCalledWith("a");+ expect(actions.add).toHaveBeenCalledWith();});-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("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("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 });+ 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([]);});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, signOut });+ const items = accountMenuItems({ view: null, openSheet, ...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", () => {+ 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 --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsxindex b126a82dfd..01c80ad6eb 100644--- a/src/components/AccountMenu.tsx+++ b/src/components/AccountMenu.tsx@@ -1,9 +1,11 @@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 { cn } from "@/lib/cn";+import type { CloudSignInPhase } from "@/lib/cloud-plan";import { t } from "@/lib/i18n";-import { CLOSE, Heading, PRIMARY, SCREEN, SHEET } from "./cloud-buy/parts";+import { CLOSE, Heading, QUIET, SCREEN, SHEET } from "./cloud-buy/parts";+import { codeDigits, SignInScreen } from "./cloud-buy/SignInScreen";import type { SidebarMenuItem } from "./SidebarPopoverMenu";export interface AccountsAccess {@@ -11,16 +13,29 @@ export interface AccountsAccess {view: AccountsView | null;/** Another page: main opens the sheet on the rail's page for it. */openSheet: (() => void) | null;+ switchTo(row: AccountRow): void;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 {+ 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 [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(() => {}); };@@ -28,54 +43,143 @@ export function useAccounts(): AccountsAccess {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") })); },+ add: (email) => setSheet({ email: email ?? "", note: null }),+ sheet,+ closeSheet: () => setSheet(null),};}-/** 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. 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[] {if (openSheet) return [{ key: "accounts-sheet", label: t("accounts.manage"), icon: <UserRound size={18} />, onSelect: openSheet }];- const active = view?.active;- if (!active) return [];+ if (!view) return [];+ const active = view.active;+ if (!active && !view.others.length) return [];return [- { key: "accounts-active", heading: t("accounts.heading"), label: active.email, title: active.email, icon: <Check size={18} />, disabled: true, onSelect: () => {} },- { key: "accounts-sign-out", label: t("accounts.signOut"), icon: <LogOut size={18} />, onSelect: () => signOut(active.id) },+ ...(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) }] : []),];}-/** 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 }) {+ 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(""); }+ 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);+ 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;+ 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);+ }).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. */+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 active = view?.active ?? null;- const signOut = (id: string) => {- setFailed(false);- void bridge?.signOut(id).then((next) => { setView(next); if (!next.active) onClose(); }, () => setFailed(true));+ const act = (work: Promise<AccountSwitchResult> | undefined, row?: AccountRow) => {+ setNote(null);+ void work?.then((result) => {+ setView(result.view);+ if (result.outcome === "sign-in") setAdd(row?.email ?? "");+ else { 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(); }} />+ : <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>+ </div>}</div></div>;}diff --git a/src/components/HomeScreen.test.ts b/src/components/HomeScreen.test.tsindex 2817cf852d..0081bda4eb 100644--- a/src/components/HomeScreen.test.ts+++ b/src/components/HomeScreen.test.ts@@ -49,3 +49,11 @@ it("a Cloud that isn't running says what it is in plain words with its one actiofor (const words of Object.values(homeScreenText({ screen, name: "Client B", deleteAt: day }, now))) expect(String(words)).not.toMatch(/—|\bVM\b|engine|ctx|server/i);}});++it("moved to another account's Cloud, that account signed in here too: where the bots are, and one button, never a sign-in", () => {+ const text = homeScreenText({ screen: "signin", other: true, movedTo: { id: "a", email: "[email protected]" } });+ expect(text.title).toBe("Your bots are on another account's Cloud");+ expect(text.body).toContain("[email protected]");+ expect(text.action).toBeNull();+ expect(homeScreenText({ screen: "signin", other: true }).action).toBe("sign-in");+});diff --git a/src/components/HomeScreen.tsx b/src/components/HomeScreen.tsxindex a45422e752..2f0724d9bc 100644--- a/src/components/HomeScreen.tsx+++ b/src/components/HomeScreen.tsx@@ -28,6 +28,7 @@ export function homeScreenText(view: HomeView | null, now = Date.now()): { titleif (view?.screen === "setup") return { title: named("homeScreen.setup", "homeScreen.setupNamed"), body: t(view.slow ? "cloudHome.slow" : "homeScreen.setupBody"), reason: null, action: null, busy: true };// It didn't answer: said once, with Try again, never a spinner that goes on for ever (it still looks again by itself).if (view?.screen === "offline") return { title: named("homeScreen.offline", "homeScreen.offlineNamed"), body: t("homeScreen.offlineBack"), reason: view.reason ?? null, action: "retry", busy: false };+ if (view?.screen === "signin" && view.movedTo) return { title: t("homeScreen.otherAccountTitle"), body: t("homeScreen.otherAccountBody", { email: view.movedTo.email }), reason: null, action: null, busy: false };if (view?.screen === "signin") return { title: named("homeScreen.signIn", "homeScreen.signInNamed"), body: t(view.other ? "homeScreen.signInOther" : "homeScreen.signInEnded"), reason: null, action: "sign-in", busy: false };if (view?.screen === "plan") return { title: named("homeScreen.plan", "homeScreen.planNamed"), body: t(MACHINE[view.machine] ?? "cloudHome.failed"), reason: null, action: view.machine === "failed" ? null : "manage", busy: false };// A Cloud the Admin's list says isn't running: what it is in plain words, with its one fitting action.@@ -108,6 +109,7 @@ export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: (){text.body && <p className="text-[14px] leading-relaxed text-ink-secondary">{text.body}</p>}{view?.screen === "setup" && <CloudSetupSteps step={view.step ?? "reserving"} />}{text.reason && <p data-home-reason className="text-[13px] leading-relaxed text-ink-secondary">{text.reason}</p>}+ {view?.screen === "signin" && view.movedTo && <button type="button" data-home-switch className="ui-button ui-button-primary mt-2" onClick={() => act(() => window.ogb!.accounts!.switchTo(view.movedTo!.id))}>{t("homeScreen.otherAccountSwitch", { email: view.movedTo.email })}</button>}{text.action === "sign-in" && <button type="button" className="ui-button ui-button-primary mt-2" onClick={() => act(() => bridge.signIn())}>{t("homeScreen.signInButton")}</button>}{text.action === "manage" && manage && <button type="button" className="ui-button mt-2" onClick={() => act(manage)}>{t("cloudAccount.manageInBrowser")}</button>}{button && run[button] && <button type="button" data-home-action={button} className={button === "retry" ? "ui-button mt-2" : "ui-button ui-button-primary mt-2"}diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsxindex 9b6622abc3..19c0a80a84 100644--- a/src/components/SidebarProfileMenu.tsx+++ b/src/components/SidebarProfileMenu.tsx@@ -23,7 +23,7 @@ import {Zap,} from "lucide-react";-import { accountMenuItems, useAccounts } from "./AccountMenu";+import { accountMenuItems, AccountsSheet, useAccounts } from "./AccountMenu";import { AccountMoveStatus, useAccountMove, type AccountMoveKind } from "./AccountMove";import { InitialsAvatar } from "./Avatar";import { DiscordIcon } from "./DiscordIcon";@@ -700,6 +700,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa)}/><AboutDialog open={aboutOpen} onClose={() => setAboutOpen(false)} />+ {accounts.sheet && <AccountsSheet adding={accounts.sheet.email} note={accounts.sheet.note} onClose={accounts.closeSheet} />}{phoneAppOpen && <PhoneAppDialogopenonClose={() => setPhoneAppOpen(false)}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 82b4bb89bf..5590cbdf14 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2180,8 +2180,19 @@"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.",+ "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",