Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge remote-tracking branch 'origin/main' into feat/account-switcher
milind-soni6a2f87926a01
diff --cc electron/cloud-rail.mjsindex 06b88eb4b3,6d98704a57..8766c97966--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@@ -60,11 -59,11 +60,12 @@@ const unlisted = (entry, { clouds, home* checkout or its setup), never an address. My Cloud's saved place leaves once the session's list doesn't have it (removed* from the list). Fewer than RAIL_MIN_PLACES places in all, This computer counted while it is one: no rail at all, the window* as it was, unless the person has a Cloud of their own: then its one circle is the rail, for the + that buys another.- * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs). `waiting`: the other accounts- * signed in on this device, each with its places as they were kept: grouped by account after these (withAccounts).- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: any[] }} input+ * `offers(entry)`: a server connected by hand whose menu offers Make … my home (own-home-main.mjs). `waiting(id)`: inbox lines- * wait in that place, and the window shows another (place-inbox-watch.mjs).- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean }} input++ * wait in that place, and the window shows another (place-inbox-watch.mjs). `accounts`: the other accounts signed in on this++ * device, each with its places as they were kept: grouped by account after these (withAccounts).++ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean, accounts?: any[] }} input*/- export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = [] }) {-export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false }) {++export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [] }) {const connected = state?.status === "connected" ? state : null;const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };@@@ -83,8 -82,7 +84,8 @@@const places = [...remote, ...servers, ...making];const computer = environments.savedPlace(saved, environments.LOCAL_ID), color = computer.color ?? null;const all = home ? places : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),- ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}) }, ...places];- if (waiting.length) return withAccounts(all, { saved, waiting, email: state?.account?.email ?? null });+ ...(saved.activeId === environments.LOCAL_ID ? { active: true } : {}), ...(waiting(computer.id) ? { attention: true } : {}) }, ...places];++ if (accounts.length) return withAccounts(all, { saved, accounts, email: state?.account?.email ?? null });return all.length < (clouds.some(ownCloud) ? 1 : RAIL_MIN_PLACES) ? [] : all;}diff --cc electron/main.mjsindex 9997fb24c6,42c4e47d81..3b694e643d--- a/electron/main.mjs+++ b/electron/main.mjs@@@ -108,7 -108,7 +108,7 @@@ import { createCleanWorkspace } from ".import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";- import { createHomePlaces } from "./home-places.mjs"; import { 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 { createHomePlaces } from "./home-places.mjs"; import { createAccountLeave, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.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 { createPlaceInboxWatch } from "./place-inbox-watch.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";@@@ -2657,7 -2657,7 +2657,7 @@@ const cloudLook = createCloudLook({ stoconst cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });- const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1 }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });++const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1 }); ownHome = installOwnHome({ localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,@@@ -2679,8 -2679,8 +2679,8 @@@ function showHome(options)return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));}const openOwnCloud = id => showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } });- // The rail and its + (cloud-rail.mjs): its list for this app's page and hosted Clouds' pages only, opened through switchEnvironment.- const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, waiting: accountRing.waiting() }); };+ const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() });-const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true }); };++const railList = () => { ownHome?.refresh(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting() }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],@@@ -2694,10 -2694,10 +2694,10 @@@ const rail = installCloudRail({ ipcMainlists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true),- add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),+ add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin(), account: !desktopRemoteAccess && Boolean(accounts.view().active) }),run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,- open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });+ open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() }); const desktopNotifications = installDesktopNotifications({ ipcMain, Notification, nativeImage, fetch: (...args) => session.defaultSession.fetch(...args), window: () => mainWindow, mayNotify: (contents, url) => appPermissions?.check(contents, "notifications", url, { isMainFrame: true }) === true, reveal: revealForLink, openPlace: origin => (origin === homeWindow.cloudOrigin() ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(origin === rendererOrigin() ? LOCAL_ID : environmentsState.environments.find(entry => entry.origin === origin)?.id))) });// A place's colour (place-look.mjs): the Admin's for a Cloud, this app's for This computer and a server connected by// hand; changed on the place's own page or from the window's rail, whatever that server runs.installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),diff --cc electron/rail-accounts.mjsindex 08e2b36f9e,0000000000..2b3ddc5412mode 100644,000000..100644--- a/electron/rail-accounts.mjs+++ b/electron/rail-accounts.mjs@@@ -1,48 -1,0 +1,48 @@@+// The rail with several accounts signed in on this device: it lists places, each place knows its account, and a click on a+// place of another account switches first (cloud-rail.mjs `workspaces:open`). An account that waits makes no request and has no+// timer, so its places show as they looked when it was last the one in use, with no counts or live state.+//+// Security: these rows go only to the rail's own page (cloud-rail.mjs), the one page allowed to know other accounts' addresses.+// With one account nothing here changes the rail at all.++/** A place of no Cloud: an account with nothing on the rail still has one way to reach it. */+export const ACCOUNT_PLACE = "account:";+const ACTIVE = "active", HAND = "hand";++/** The account's places as the rail shows them now, to keep while it waits: what they are and how they look, nothing that would+ * need asking again and nothing to act on but opening. This computer and a server saved by hand aren't any account's. */+export function accountRows(rows) {+ return rows.filter((row) => row.opens && row.kind !== "computer" && !row.forget && !row.account)+ .map(({ id, name, color, kind, ended }) => ({ id, name, color, kind, opens: true, ...(ended ? { ended: true } : {}) }));+}++/**+ * The rail's rows, grouped: This computer, each account by its address, then servers saved by hand. A Cloud two accounts can reach+ * (a team's) is one row: the account in use's when it can, else the first that waits. An account that waits, left with no row, gets+ * one of its own.+ * @param {any[]} all the account in use's rows, from railPlaces.- * @param {{ saved: { environments: any[] }, email?: string | null, waiting?: Array<{ id: string, email: string, signIn?: true, places: any[], rows: any[] }> }} input++ * @param {{ saved: { environments: any[] }, email?: string | null, accounts?: Array<{ id: string, email: string, signIn?: true, places: any[], rows: any[] }> }} input+ */- export function withAccounts(all, { saved, email = null, waiting = [] }) {- if (!waiting.length) return all;++export function withAccounts(all, { saved, email = null, accounts = [] }) {++ if (!accounts.length) return all;+ const taken = new Set(saved.environments.map((entry) => entry.origin).filter(Boolean));+ const first = (account, row) => {+ const origin = account.places.find((entry) => entry.id === row.id)?.origin;+ if (!origin) return true;+ if (taken.has(origin)) return false;+ taken.add(origin);+ return true;+ };+ const rowsOf = (account) => {+ const mark = { account: account.id, group: account.id, email: account.email, ...(account.signIn ? { signIn: true } : {}) };+ const rows = account.rows.filter((row) => first(account, row)).map((row) => ({ ...row, ...mark }));+ return rows.length ? rows : [{ id: `${ACCOUNT_PLACE}${account.id}`, name: account.email, color: null, kind: "account", opens: true, ...mark }];+ };+ const isComputer = (row) => row.kind === "computer";+ // The first claim to a Cloud two accounts share is the account in use's, whatever the order they show in.- const waited = waiting.map((account) => ({ email: account.email, rows: rowsOf(account) }));++ const waited = accounts.map((account) => ({ email: account.email, rows: rowsOf(account) }));+ const own = all.filter((row) => !isComputer(row) && !row.forget).map((row) => ({ ...row, group: ACTIVE, ...(email ? { email } : {}) }));+ // In a fixed order, so a click that makes another account the one in use doesn't move the row under the pointer.+ const groups = [...(own.length ? [{ email: email ?? "", rows: own }] : []), ...waited].sort((a, b) => a.email.localeCompare(b.email));+ return [...all.filter(isComputer), ...groups.flatMap((group) => group.rows), ...all.filter((row) => row.forget).map((row) => ({ ...row, group: HAND }))];+}diff --cc electron/rail-accounts.node-test.mjsindex dc9bf93c1d,0000000000..0f104d1541mode 100644,000000..100644--- a/electron/rail-accounts.node-test.mjs+++ b/electron/rail-accounts.node-test.mjs@@@ -1,175 -1,0 +1,175 @@@+import assert from "node:assert/strict";+import test from "node:test";++import environments from "./environments.cjs";+import { installCloudRail, railPlaces } from "./cloud-rail.mjs";+import { accountRows, ACCOUNT_PLACE, withAccounts } from "./rail-accounts.mjs";++const { LOCAL_ID } = environments;+// The owner's list of cases for the rail with several accounts: each is a test here, by its number.+const myCloud = (origin, id = origin) => ({ id, kind: "remote", origin, name: "My Cloud", home: true });+const ownCloud = (origin, name, id = origin) => ({ id, kind: "remote", origin, name, cloud: { id: `c-${id}`, role: "owner" } });+const teamCloud = (origin, name, id = origin) => ({ id, kind: "remote", origin, name, team: { id: `t-${origin}`, role: "member" } });+const byHand = (origin, name) => ({ id: origin, kind: "remote", origin, name });+const signedIn = (email, extra = {}) => ({ status: "connected", account: { id: email, email }, ...extra });+const list = (environmentsList, activeId = LOCAL_ID) => ({ environments: environmentsList, activeId });+const waits = (email, places, rows = places.map((entry) => ({ id: entry.id, name: entry.name, color: null, kind: entry.team ? "team" : "cloud", opens: true }))) => ({ id: email, email, places, rows });+const ids = (rows) => rows.map((row) => row.id);+const dividers = (rows) => rows.slice(1).filter((row, at) => row.group !== rows[at].group).length;++test("1. no account: This computer and hand-connected servers only, as ever, with no grouping", () => {+ assert.deepEqual(railPlaces({ saved: list([]) }), [], "only This computer: no rail");+ const rows = railPlaces({ saved: list([byHand("https://hand.test", "Hand")]) });+ assert.deepEqual(ids(rows), [LOCAL_ID, "https://hand.test"]);+ assert.equal(dividers(rows), 0);+ assert.equal(rows.some((row) => row.email || row.group), false);+});++test("2, 3, 4, 5. one account: exactly today's rail, with no grouping, divider or address", () => {+ const shapes = [+ [myCloud("https://a.test")],+ [myCloud("https://a.test"), ownCloud("https://a2.test", "Two"), ownCloud("https://a3.test", "Three"), ownCloud("https://a4.test", "Four"), ownCloud("https://a5.test", "Five")],+ [myCloud("https://a.test"), teamCloud("https://t.test", "Team")],+ [teamCloud("https://t.test", "Team")],+ ];+ for (const places of shapes) {+ const state = signedIn(A);+ const none = railPlaces({ saved: list(places), mine: "https://a.test", state });- assert.deepEqual(railPlaces({ saved: list(places), mine: "https://a.test", state, waiting: [] }), none);++ assert.deepEqual(railPlaces({ saved: list(places), mine: "https://a.test", state, accounts: [] }), none);+ assert.equal(dividers(none), 0);+ assert.equal(JSON.stringify(none).includes("@"), false, "no address");+ assert.equal(none.some((row) => row.group !== undefined), false);+ }+});++test("6. two accounts, one Cloud each, both called My Cloud: told apart by group, divider and address; This computer on top", () => {- const rows = railPlaces({ saved: list([myCloud("https://a.test", "a-home")]), mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b-home")])] });++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a-home")]), mine: "https://a.test", state: signedIn(A), accounts: [waits(B, [myCloud("https://b.test", "b-home")])] });+ assert.deepEqual(ids(rows), [LOCAL_ID, "a-home", "b-home"]);+ assert.deepEqual(rows.map((row) => row.name), ["This computer", "My Cloud", "My Cloud"]);+ assert.deepEqual(rows.map((row) => row.email ?? null), [null, A, B]);+ assert.equal(rows[0].group, undefined, "This computer is no account's");+ assert.equal(dividers(rows), 2);+ assert.equal(rows[1].account, undefined, "a click on the account in use's own place doesn't switch");+ assert.equal(rows[2].account, B);+});++test("7. two accounts with several Clouds and teams: groups in a fixed order by address, each in its order, colours per Cloud", () => {+ const b = [myCloud("https://b.test", "b1"), ownCloud("https://b2.test", "B Two", "b2"), teamCloud("https://bt.test", "B Team", "b3")];+ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1"), ownCloud("https://a2.test", "A Two", "a2"), teamCloud("https://at.test", "A Team", "a3")]), mine: "https://a.test", state: signedIn(A),- waiting: [waits(B, b, [{ id: "b1", name: "My Cloud", color: "red", kind: "cloud", opens: true }, { id: "b2", name: "B Two", color: "blue", kind: "cloud", opens: true }, { id: "b3", name: "B Team", color: null, kind: "team", opens: true }])] });++ accounts: [waits(B, b, [{ id: "b1", name: "My Cloud", color: "red", kind: "cloud", opens: true }, { id: "b2", name: "B Two", color: "blue", kind: "cloud", opens: true }, { id: "b3", name: "B Team", color: null, kind: "team", opens: true }])] });+ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", "a2", "a3", "b1", "b2", "b3"]);+ assert.deepEqual(rows.slice(4).map((row) => row.color), ["red", "blue", null], "as they looked");+ assert.equal(new Set(rows.slice(1, 4).map((row) => row.group)).size, 1);+ assert.equal(new Set(rows.slice(4).map((row) => row.group)).size, 1);+});++test("8. an account with no Clouds has one row of its own while it waits; while it's the one in use, it has none", () => {- const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), mine: "https://a.test", state: signedIn(A), waiting: [{ id: C, email: C, places: [], rows: [] }] });++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), mine: "https://a.test", state: signedIn(A), accounts: [{ id: C, email: C, places: [], rows: [] }] });+ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", `${ACCOUNT_PLACE}${C}`]);+ assert.deepEqual({ kind: rows[2].kind, name: rows[2].name, opens: rows[2].opens, account: rows[2].account }, { kind: "account", name: C, opens: true, account: C });- const active = railPlaces({ saved: list([]), state: signedIn(C), waiting: [waits(A, [myCloud("https://a.test", "a1")])] });++ const active = railPlaces({ saved: list([]), state: signedIn(C), accounts: [waits(A, [myCloud("https://a.test", "a1")])] });+ assert.deepEqual(ids(active), [LOCAL_ID, "a1"], "the rail stands though the one in use has nothing on it");+});++test("9. the same team under both accounts is one row: the account in use's when it's a member, else the first that waits", () => {+ const mine = teamCloud("https://t.test", "Team", "t-as-a"), theirs = teamCloud("https://t.test", "Team", "t-as-b");- const both = railPlaces({ saved: list([mine]), state: signedIn(A), waiting: [waits(B, [theirs])] });++ const both = railPlaces({ saved: list([mine]), state: signedIn(A), accounts: [waits(B, [theirs])] });+ assert.deepEqual(ids(both).sort(), [LOCAL_ID, "t-as-a", `${ACCOUNT_PLACE}${B}`].sort(), "one row, opened as the account in use, and B can still be reached");+ assert.equal(both[1].account, undefined);- const notMine = railPlaces({ saved: list([]), state: signedIn(A), waiting: [waits(B, [theirs]), waits(C, [teamCloud("https://t.test", "Team", "t-as-c")])] });++ const notMine = railPlaces({ saved: list([]), state: signedIn(A), accounts: [waits(B, [theirs]), waits(C, [teamCloud("https://t.test", "Team", "t-as-c")])] });+ assert.deepEqual(ids(notMine), [LOCAL_ID, "t-as-b", `${ACCOUNT_PLACE}${C}`]);+ assert.equal(notMine[1].account, B, "a click switches to the one that is a member");+});++test("10. a Cloud that ended keeps looking so while it waits; once its account is in use, today's rows say the rest", () => {+ const rows = accountRows([{ id: "x", name: "Old", color: "red", kind: "cloud", opens: true, ended: true, removable: true, cloudId: "c1", attention: true, progress: 0.2, paint: {} }]);+ assert.deepEqual(rows, [{ id: "x", name: "Old", color: "red", kind: "cloud", opens: true, ended: true }], "no Remove here: it needs the account in use, which a click makes it");+});++test("11. hand-connected servers stay outside any account's group, after them, and aren't kept with an account", () => {- const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1"), byHand("https://hand.test", "Hand")]), mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")])] });++ const rows = railPlaces({ saved: list([myCloud("https://a.test", "a1"), byHand("https://hand.test", "Hand")]), mine: "https://a.test", state: signedIn(A), accounts: [waits(B, [myCloud("https://b.test", "b1")])] });+ assert.deepEqual(ids(rows), [LOCAL_ID, "a1", "b1", "https://hand.test"]);+ assert.equal(rows[3].group, "hand");+ assert.equal(rows[3].email, undefined);+ assert.equal(rows[3].account, undefined);+ assert.deepEqual(accountRows(rows), [{ id: "a1", name: "My Cloud", color: null, kind: "cloud", opens: true }], "this computer, a hand-saved server and another account's rows aren't this account's");+});++test("12. a place that waits carries no live state: nothing on the rail can say it is lent or busy", () => {- const rows = railPlaces({ saved: list([]), state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")], accountRows([{ id: "b1", name: "My Cloud", color: null, kind: "cloud", opens: true, active: true, progress: 0.4, attention: true, update: {}, offline: true, server: true }]))] });++ const rows = railPlaces({ saved: list([]), state: signedIn(A), accounts: [waits(B, [myCloud("https://b.test", "b1")], accountRows([{ id: "b1", name: "My Cloud", color: null, kind: "cloud", opens: true, active: true, progress: 0.4, attention: true, update: {}, offline: true, server: true }]))] });+ assert.deepEqual(Object.keys(rows[1]).sort(), ["account", "color", "email", "group", "id", "kind", "name", "opens"]);+});++test("14. a moved computer whose home is a Cloud of the account that waits: its row is there, and This computer is the clean workspace's", () => {- const rows = railPlaces({ saved: list([]), home: null, state: signedIn(B), waiting: [waits(A, [myCloud("https://a.test", "a1")])] });++ const rows = railPlaces({ saved: list([]), home: null, state: signedIn(B), accounts: [waits(A, [myCloud("https://a.test", "a1")])] });+ assert.deepEqual(ids(rows), [LOCAL_ID, "a1"]);+ assert.equal(rows[1].account, A);- const home = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), home: "https://a.test", mine: "https://a.test", state: signedIn(A), waiting: [waits(B, [myCloud("https://b.test", "b1")])] });++ const home = railPlaces({ saved: list([myCloud("https://a.test", "a1")]), home: "https://a.test", mine: "https://a.test", state: signedIn(A), accounts: [waits(B, [myCloud("https://b.test", "b1")])] });+ assert.deepEqual(ids(home), ["a1", "b1"], "home on the account in use: as today, no This computer, and the other account's Clouds beside it");+});++test("an account whose sign-in ended keeps its rows, and says so", () => {- const rows = withAccounts([], { saved: list([]), waiting: [{ ...waits(B, [myCloud("https://b.test", "b1")]), signIn: true }] });++ const rows = withAccounts([], { saved: list([]), accounts: [{ ...waits(B, [myCloud("https://b.test", "b1")]), signIn: true }] });+ assert.equal(rows[0].signIn, true);+ assert.equal(rows[0].opens, true);+});++function railWith({ rows, switched = async () => ({ outcome: "switched" }), after = rows }) {+ const handlers = new Map(), opened = [], asked = [];+ let current = rows;+ installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (handler) => handler, trusted: () => true, lists: (event) => event.rail === true, places: () => current, open: async (id) => opened.push(id),+ add: { choices: () => ({ cloud: false, link: false, address: false }), run() {} }, account: () => null, clipboard: {}, openCloud: async (id) => opened.push(`cloud:${id}`), targets: () => [],+ switchAccount: async (id) => { asked.push(id); const said = await switched(id); if (said.outcome === "switched") current = after; return said; } });+ return { call: (channel, ...args) => handlers.get(channel)({ rail: true }, ...args), page: (channel, ...args) => handlers.get(channel)({ rail: false }, ...args), opened, asked };+}+const mineRow = { id: "a1", name: "My Cloud", kind: "cloud", opens: true, group: "active", email: A };+const theirRow = { id: "b1", name: "My Cloud", kind: "cloud", opens: true, group: B, email: B, account: B };+const theirsActive = { id: "b1", name: "My Cloud", kind: "cloud", opens: true, group: "active", email: B };++test("a click on the account in use's place opens it, with no switch", async () => {+ const f = railWith({ rows: [mineRow, theirRow] });+ await f.call("workspaces:open", "a1");+ assert.deepEqual([f.asked, f.opened], [[], ["a1"]]);+});++test("a click on another account's place switches first, then opens it as that account's own", async () => {+ const f = railWith({ rows: [mineRow, theirRow], after: [theirsActive, { ...mineRow, account: A }] });+ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "switched" });+ assert.deepEqual([f.asked, f.opened], [[B], ["b1"]]);+});++test("a click during a move is refused with the plain outcome, and nothing moves", async () => {+ const f = railWith({ rows: [mineRow, theirRow], switched: async () => ({ outcome: "moving" }) });+ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "moving" });+ assert.deepEqual(f.opened, []);+});++test("a saved sign-in past its time: the click asks for the code for that address, and nothing moves", async () => {+ const f = railWith({ rows: [mineRow, { ...theirRow, signIn: true }], switched: async () => ({ outcome: "sign-in", email: B }) });+ assert.deepEqual(await f.call("workspaces:open", "b1"), { outcome: "sign-in", email: B });+ assert.deepEqual(f.opened, []);+});++test("a click on an account with no place of its own switches, and the window goes where that account belongs", async () => {+ const id = `${ACCOUNT_PLACE}${C}`;+ const f = railWith({ rows: [mineRow, { id, name: C, kind: "account", opens: true, group: C, email: C, account: C }], after: [{ ...mineRow, account: A }] });+ assert.deepEqual(await f.call("workspaces:open", id), { outcome: "switched" });+ assert.deepEqual([f.asked, f.opened], [[C], []]);+});++test("no page but the rail's reads the rows, and the rail's never hears which account main switches to", async () => {+ const f = railWith({ rows: [mineRow, theirRow] });+ const seen = await f.call("workspaces:places");+ assert.equal(JSON.stringify(seen.places).includes('"account"'), false);+ assert.deepEqual((await f.page("workspaces:places")).places, []);+ assert.throws(() => f.page("workspaces:open", "b1"), /only available/);+});++test("the groups keep their order whichever account is in use, so a click doesn't move the row under the pointer", () => {+ const a = [myCloud("https://a.test", "a1")], b = [myCloud("https://b.test", "b1")];- const asAlice = railPlaces({ saved: list(a), mine: "https://a.test", state: signedIn(A), waiting: [waits(B, b)] });- const asBob = railPlaces({ saved: list(b), mine: "https://b.test", state: signedIn(B), waiting: [waits(A, a)] });++ const asAlice = railPlaces({ saved: list(a), mine: "https://a.test", state: signedIn(A), accounts: [waits(B, b)] });++ const asBob = railPlaces({ saved: list(b), mine: "https://b.test", state: signedIn(B), accounts: [waits(A, a)] });+ assert.deepEqual(ids(asAlice), ids(asBob));+ assert.deepEqual(ids(asAlice), [LOCAL_ID, "a1", "b1"], "alice before bob");+});