Skip to content

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

Rail: a click is taken at once, and the last click wins

milind-sonia7737866ca85
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index 094965cf74..c9db3889f0 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -47,6 +47,12 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
computer's or a Cloud's; a page learns only that the rail stands beside it. A
circle opens only a place main listed, by its id, through main's own switch,
and only from the person's click.
+- A click on a circle is taken at once: the place clicked is marked from that
+ click, pending, with its name on a shell over the page while main opens it
+ (Waking My Cloud… while it wakes), and any other click replaces it on the
+ spot, even one back to the place on screen. Main ends what the earlier click
+ had under way; a server restart that can't stop leaves the window on the place
+ the person chose last, and the rail stays up through it.
- Buying another Cloud sends the plan, a name and a swatch to the Admin, which
answers with a checkout this app opens in the browser; the sheet then follows
the payment and the setup. An Admin that sells one Cloud per account (no
diff --git a/electron/clean-workspace.d.mts b/electron/clean-workspace.d.mts
index 194fc2c1d1..1beb0ea354 100644
--- a/electron/clean-workspace.d.mts
+++ b/electron/clean-workspace.d.mts
@@ -14,6 +14,7 @@ export interface CleanWorkspace {
enter(): Promise<boolean>;
open(id?: string): Promise<boolean>;
leave(): Promise<boolean>;
+ settled(): Promise<unknown>;
holding<T>(work: () => Promise<T>): Promise<T>;
realCopy(request: (route: string, init?: RequestInit) => Promise<Response>): (route: string, init?: RequestInit) => Promise<Response>;
}
diff --git a/electron/clean-workspace.mjs b/electron/clean-workspace.mjs
index ac0dabc66b..bc7e5abf75 100644
--- a/electron/clean-workspace.mjs
+++ b/electron/clean-workspace.mjs
@@ -132,6 +132,8 @@ export function createCleanWorkspace({ dataDir, running, swap, allowed = () => t
return swapTo(dir);
}),
leave,
+ /** Settles once the swaps asked for so far are done. */
+ settled: () => queue,
/** Runs `work` on this computer's own copy, its server back first, and nothing opens the clean workspace meanwhile. */
async holding(work) {
held++;
diff --git a/electron/clean-workspace.node-test.mjs b/electron/clean-workspace.node-test.mjs
index 8d9765e37d..d096f939cd 100644
--- a/electron/clean-workspace.node-test.mjs
+++ b/electron/clean-workspace.node-test.mjs
@@ -99,6 +99,16 @@ test("one swap at a time: open, leave and open again at once end where the last
assert.equal(w.clean.active(), true);
});
+test("settled() waits for the swaps asked for so far, and is already done with none", async (t) => {
+ const w = computer(t);
+ await w.clean.settled();
+ assert.deepEqual(w.swaps, []);
+ const entering = w.clean.enter();
+ await w.clean.settled();
+ assert.deepEqual(w.swaps, [w.cleanDir], "after the swap under way");
+ await entering;
+});
+
test("the marker is the frozen copy's own, read from its folder whichever server runs", async (t) => {
const w = computer(t, { frozen: { v: 1, at: 1, cloud: CLOUD, place: "Garage" } });
await w.clean.enter();
diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mts
index 9c1363df44..db54a6737f 100644
--- a/electron/cloud-rail.d.mts
+++ b/electron/cloud-rail.d.mts
@@ -60,7 +60,13 @@ export interface RailPlace {
/** `local`: a new workspace of this computer's own. */
export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean; organization?: boolean; account?: boolean; local?: boolean }
/** `beside`: a place's page, which never reads the list, learns that the window's rail stands beside it. */
-export interface RailState { places: RailPlace[]; add: RailAddChoices; beside?: true }
+export interface RailState {
+ places: RailPlace[];
+ add: RailAddChoices;
+ beside?: true;
+ /** The place a click on this rail is opening, until its page has loaded; `waking` while My Cloud is being woken for it. */
+ switching?: { id: string; waking?: true };
+}
/** Buying another Cloud as a page sees it: what the sheet says, never the account, an address or the checkout page. */
export type AddCloudView =
| { signedIn: false }
diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjs
index 43a59d9644..6f1fbd1757 100644
--- a/electron/cloud-rail.mjs
+++ b/electron/cloud-rail.mjs
@@ -157,8 +157,9 @@ const CHOICES = Object.freeze(["cloud", "link", "address"]);
* of the person's own (own-home-main.mjs `start`). `switchAccount(id)`: that account becomes the one in use (cloud-accounts.mjs).
* `openProfile(id)`: the window shows that workspace of this computer's own (local-profiles.mjs `open`). `local`: those
* workspaces' +, names, colours and removal (local-profiles.mjs), and the end of a switch still waiting when another place opens.
+ * `ask(id, run)`: a circle's click, listed at once, `run` told when a newer one came (place-switch.mjs); `switching()`: the place it opens, or null.
*/
-export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null, switchAccount = null, openProfile = null, local = null, t = nativeText.englishText.t }) {
+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null, switchAccount = null, openProfile = null, local = null, ask = (_id, run) => run(() => false), switching = () => null, t = nativeText.englishText.t }) {
let sheetOpen = false, sent = "";
const allowed = (channel, handler) => guard((event, ...args) => {
if (!trusted(event)) throw new Error(`${channel} is only available in this app's window`);
@@ -173,28 +174,28 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
// +'s choices: main's, and a new organization while this account runs a Team plan's organizations (unless the Admin has
// turned adding them off).
const choices = () => { const organizations = account()?.state().organizations; return { ...add.choices(), organization: Boolean(organizations) && organizations.blocked !== "off", local: local?.creatable() === true }; };
- ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places().map(seen), add: choices() }
+ ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places().map(seen), add: choices(), ...(switching() ? { switching: switching() } : {}) }
: { places: [], add: { cloud: false, link: false, address: false, organization: false }, ...(beside() ? { beside: true } : {}) })));
// A Cloud the Admin is still making has no saved place: its own screen opens, by main's word for which Cloud it is.
- const opening = place => {
+ const opening = (place, stale) => {
if (place.id.startsWith(PENDING)) { local?.cancel(); return openCloud(place.cloudId); }
- if (!place.profile) { local?.cancel(); return open(place.id); }
+ if (!place.profile) { local?.cancel(); return open(place.id, stale); }
if (!openProfile) throw new Error(t("native.places.noLongerHere"));
- return openProfile(place.profile);
+ return openProfile(place.profile, stale);
};
// A place of another account: that account becomes the one in use first, and nothing moves if it can't. By then the place is
// listed as that account's own; an account with no place of its own is simply where the window goes.
- const switchingTo = async place => {
+ const switchingTo = async (place, stale) => {
const said = await switchAccount(place.account);
if (said.outcome !== "switched") return { outcome: said.outcome, ...(said.email ? { email: said.email } : {}) };
const arrived = places().find(entry => entry.id === place.id && entry.opens && !entry.account);
- if (arrived) await opening(arrived);
+ if (arrived) await opening(arrived, stale);
return { outcome: "switched" };
};
listed("workspaces:open", (_event, id) => {
const place = places().find(entry => entry.id === plain(id) && entry.opens);
if (!place) throw new Error(t("native.places.noLongerHere"));
- return place.account ? switchingTo(place) : opening(place);
+ return ask(place.id, stale => (place.account ? switchingTo(place, stale) : opening(place, stale)));
});
// Remove from list, from a circle's menu (the page asked the person first): only a Cloud or a server saved by hand that
// main listed as removable. A server is forgotten here; a Cloud is taken off the person's list at the Admin.
@@ -284,7 +285,7 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes
/** The places, the sign-in or the rail beside the page changed: the rail's page and the page beside it read them
* again (a signal only, never the list). */
changed() {
- const key = JSON.stringify([places(), choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null, beside()]);
+ const key = JSON.stringify([places(), choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null, beside(), switching()]);
if (key === sent) return;
sent = key;
for (const target of targets()) if (target && !target.isDestroyed()) target.send("workspaces:changed");
diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjs
index bcc20e4051..79d3b60523 100644
--- a/electron/cloud-rail.node-test.mjs
+++ b/electron/cloud-rail.node-test.mjs
@@ -154,6 +154,27 @@ test("the rail's channels: the list only for the rail's own page, a circle only
assert.deepEqual(r.sent.slice(2), ["page:workspaces:changed", "rail:workspaces:changed"], "the rail came beside the page (or went): the page reads it again");
});
+test("a circle's click goes through main's list of what is being opened, the rail's page reads it, and it hears when it changes", async () => {
+ const asked = [], w = { trusted: true }, sent = [];
+ let target = null;
+ const handlers = new Map();
+ const installed = installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler, trusted: () => w.trusted,
+ places: () => [{ id: "a", name: "Client A", color: null, kind: "cloud", opens: true }], open: async id => { asked.push(["open", id]); return "opened"; }, add: { choices: () => ({ cloud: false, link: false, address: false }), run: () => {} }, account: () => null, clipboard: {}, openCloud: () => {},
+ targets: () => [{ send: channel => sent.push(channel), isDestroyed: () => false }], ask: async (id, run) => { asked.push(["ask", id]); return run(); }, switching: () => target });
+ const call = (channel, ...args) => handlers.get(channel)({}, ...args);
+ assert.equal(await call("workspaces:open", "a"), "opened");
+ assert.deepEqual(asked, [["ask", "a"], ["open", "a"]], "the click is listed before main switches");
+ assert.equal(call("workspaces:places").switching, undefined, "nothing being opened: nothing said");
+ installed.changed();
+ target = { id: "a", waking: true };
+ assert.deepEqual(call("workspaces:places").switching, { id: "a", waking: true });
+ sent.length = 0;
+ installed.changed();
+ assert.deepEqual(sent, ["workspaces:changed"], "the rail's page reads the list again");
+ installed.changed();
+ assert.deepEqual(sent, ["workspaces:changed"], "and only when it changed");
+});
+
test("Settings → Servers on this computer's own page looks a server up and connects to it; a page main doesn't vouch for can't", () => {
const r = rail();
r.w.lists = false;
diff --git a/electron/home-window.d.mts b/electron/home-window.d.mts
index 22fb0dfc2e..7dbbdfa5a7 100644
--- a/electron/home-window.d.mts
+++ b/electron/home-window.d.mts
@@ -80,6 +80,8 @@ export interface HomeWindow {
profile(): string | null;
opensNow(ask: "cloud" | { team: string } | { cloud: string }): boolean | null;
cancel(): void;
+ stopOpening(): void;
+ stay(): void;
openCloud(open?: "phone" | null): Promise<unknown>;
/** Remove from list from this computer's screen: the Cloud it shows leaves the person's list. */
remove(): Promise<import("./cloud-account.mjs").CloudRemoveOutcome>;
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 87e05f6eec..1407cb8f14 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -330,6 +330,8 @@ export function createHomeWindow(deps) {
try { const at = new URL(win.webContents.getURL()); return at.origin === localOrigin() && at.pathname === HOME_SCREEN_PATH; } catch { return false; }
};
const clearRetry = () => { if (retry) timers.clear(retry); retry = null; };
+ /** Whatever was being opened for an earlier click stops; the window still shows what it showed. */
+ function stopOpening() { opens++; recovering = null; clearRetry(); screen = null; status = null; }
function goScreen() {
tell();
@@ -487,7 +489,7 @@ export function createHomeWindow(deps) {
const look = await answers(origin);
if (look === "no") return unreachable(place, token);
if (look === "asleep" && otherPlace(place)) return offline(token);
- if (look === "asleep") { power.hold(); asleep = true; say("waking"); }
+ if (look === "asleep") { power.hold(); asleep = true; if (wanted(token)) say("waking"); }
}
let session = null;
const signedIn = asleep
@@ -817,7 +819,10 @@ export function createHomeWindow(deps) {
},
/** Signs the team on screen in again now, without moving the page (the timer's own step; also for tests). */
renew: () => renew(),
- cancel() { opens++; recovering = null; clearRetry(); screen = null; status = null; shown = null; away = false; },
+ cancel() { stopOpening(); shown = null; away = false; },
+ stopOpening,
+ /** The person chose the place on screen again before the one they'd asked for opened: it stays as it is. */
+ stay() { stopOpening(); profileShown = null; },
close() { opens++; clearRetry(); clearRenewal(); timers.clear(watcher); },
};
}
diff --git a/electron/main.mjs b/electron/main.mjs
index 3430f8c505..bfb1eb90d9 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -105,7 +105,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClou
import { installCloudFiles } from "./cloud-sync-main.mjs";
import { createCloudEntry } from "./cloud-entry.mjs";
import { createLendingTarget } from "./lending-target.mjs"; import { createOpenAtLogin, installOpenAtLogin } from "./open-at-login.mjs";
-import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-workspace.mjs"; import { createLocalProfiles, createProfileRegistry } from "./local-profiles.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { reopenSavedServer, serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";
+import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-workspace.mjs"; import { createLocalProfiles, createProfileRegistry } from "./local-profiles.mjs"; import { createPlaceSwitch } from "./place-switch.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { reopenSavedServer, serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
@@ -1562,7 +1562,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
if (!app.isPackaged) return { ok: false, error: "dev" };
// A second switch would be un-paused by the first's finally mid-handoff.
if (localSwitchInFlight) return { ok: false, error: "busy" };
- const previousDir = runningDataDir ?? startupEnvironmentDir(environmentsState, desktopDataDir());
+ const previousDir = runningDataDir ?? startupEnvironmentDir(environmentsState, desktopDataDir()), asked = placeSwitch.turn(), windowFollows = () => placeSwitch.turn() === asked || (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents }));
let startedProc = null;
let switchSucceeded = false;
const failedSwitch = () => {
@@ -1620,7 +1620,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
throw error;
}
},
- persistActive: (id) => persistEnvironments(withActive(environmentsState, id)),
+ persistActive: (id) => { if (windowFollows()) persistEnvironments(withActive(environmentsState, id)); },
log: slog,
},
});
@@ -1629,7 +1629,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
return failedSwitch();
}
switchSucceeded = true;
- navigateMainWindow(rendererOrigin());
+ if (windowFollows()) navigateMainWindow(rendererOrigin());
return { ok: true };
} catch (error) {
slog(`environment switch to ${targetDir} failed (${error?.message ?? error})`);
@@ -1649,25 +1649,25 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {
}
}
-async function switchEnvironment(id) {
- if (id === LOCAL_ID && cleanWorkspace.profile()) return void await (homeWindow.cloudOrigin() ? localProfiles.open(cleanWorkspace.profile()) : localProfiles.computer()); if ((id === environmentsState.activeId && !homeWindow.asking()) || (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id))) return;
- homeWindow.cancel();
+async function switchEnvironment(id, stale = () => false) {
+ if (id === LOCAL_ID && cleanWorkspace.profile()) return void await (homeWindow.cloudOrigin() ? localProfiles.open(cleanWorkspace.profile()) : localProfiles.computer()); if (id !== LOCAL_ID && !environmentsState.environments.some((entry) => entry.id === id)) return; if (id === environmentsState.activeId && !homeWindow.asking()) { if (placeSwitch.replacing()) { homeWindow.stay(); homePlaces.remember(placeSwitch.before()); } return; }
const entry = environmentsState.environments.find((candidate) => candidate.id === id);
if (entry?.team || entry?.cloud) return void await showHome({ place: entry.team ? { team: entry.team.id, name: entry.name } : { cloud: entry.cloud.id, name: entry.name } });
homePlaces.remember(null);
+ if (entry && entry.origin === homeWindow.cloudOrigin()) return void await showHome({ place: "cloud" });
+ homeWindow.cancel();
if (entry?.kind === "local") return await switchLocalEnvironmentTo(entry.dataDir, entry.id);
if (id === LOCAL_ID && (runningDataDir ?? desktopDataDir()) !== desktopDataDir() && !cleanWorkspace.active()) {
return await switchLocalEnvironmentTo(desktopDataDir(), LOCAL_ID);
}
- if (entry && entry.origin === homeWindow.cloudOrigin()) return void await showHome({ place: "cloud" });
if (entry && cloudAccount && isCloudHomeEntry(entry, { homeOrigin: cloudAccount.homeTarget()?.origin ?? cloudAccount.state().machine?.origin, remembered: rememberedHome })) {
try { await connectCloudHome(); return; } catch (error) {
slog(`cloud home: could not connect from the Server menu (${error?.message ?? error})`);
if (!(await cloudHomeSignedIn(entry.origin))) { await openCloudSettings(); return; }
}
}
- if (entry && handSaved(entry) && !(await serverOpens(entry, { t: nativeT, fetch: (...args) => session.defaultSession.fetch(...args), dialog, forget: (gone) => forgetEnvironment(gone, false, true) }))) return;
- persistEnvironments(withActive(environmentsState, id)); navigateMainWindow(activeOrigin()); if (entry && handSaved(entry) && homeWindow.cloudOrigin()) homePlaces.remember({ server: id });
+ if ((entry && handSaved(entry) && !(await serverOpens(entry, { t: nativeT, fetch: (...args) => session.defaultSession.fetch(...args), dialog, forget: (gone) => forgetEnvironment(gone, false, true) }))) || stale()) return;
+ persistEnvironments(withActive(environmentsState, id)); await navigateMainWindow(activeOrigin()); if (entry && handSaved(entry) && homeWindow.cloudOrigin()) homePlaces.remember({ server: id });
}
function createLocalEnvironment(name, dataDir) {
@@ -2621,7 +2621,7 @@ const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.jo
localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog, t: nativeT,
hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")), ownMove: () => ownHome?.underWay() ?? null,
remembered: homePlaces.remembered, remember: homePlaces.remember, left: homePlaces.left, drop: homePlaces.drop,
- publish: view => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("home:state-changed", view); },
+ publish: view => { placeSwitch.waking(view?.screen === "waking"); if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("home:state-changed", view); },
go: (url, origin, place) => { if (place?.kind === "team" || place?.kind === "own") { activatePlace(place); if (place.kind === "team") teamProfileSeeds.opened(place.origin); } else if (origin) activateCloud(origin); else if (activeEnvironment(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(url, true); },
reopen: (place, still) => reopenSavedServer(place, { still, saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (entry) => { homePlaces.remember(null); persistEnvironments(withActive(environmentsState, entry.id)); return navigateMainWindow(activeOrigin(), true); } }),
showLocal: leaving => { if (!mainWindow || mainWindow.isDestroyed()) return createWindow(); if (!leaving) return; persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); } });
@@ -2634,9 +2634,9 @@ const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlac
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 localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };
// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.
-const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),
+const placeSwitch = createPlaceSwitch({ changed: () => railChanged(), stop: () => homeWindow.stopOpening(), kept: () => homePlaces.remembered(), pageSettled: () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; if (page?.isLoadingMainFrame()) return new Promise(done => { page.once("did-stop-loading", done); page.once("destroyed", done); }); } }); 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()}`],
- url: () => `${rendererOrigin()}${CHROME_RAIL_PATH}`, wanted: () => !desktopRemoteAccess && serverReady && railList().length > 0 });
+ url: () => `${rendererOrigin()}${CHROME_RAIL_PATH}`, wanted: () => !desktopRemoteAccess && (serverReady || placeSwitch.target() !== null) && railList().length > 0 });
chromeRail.install(ipcMain);
function railChanged() { chromeRail.refresh(); rail.changed(); }
const accountPages = [() => (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents }) ? mainWindow.webContents : null), () => ({ send: channel => chromeRail.send(channel) })];
@@ -2645,7 +2645,7 @@ const rail = installCloudRail({ t: nativeT, ipcMain, clipboard, openCloud: openO
guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),
lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),
targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],
- places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true), openProfile: id => workspaceMenuAction(async () => { const opened = await localProfiles.open(id); railChanged(); if (opened === false) throw new Error(nativeT("native.places.profileFailed")); }), local: localProfiles,
+ places: railList, ask: placeSwitch.ask, switching: placeSwitch.target, open: (id, stale) => workspaceMenuAction(async () => { if (id === LOCAL_ID) await cleanWorkspace.settled(); if (!stale()) await switchEnvironment(id, stale); }), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true), openProfile: (id, stale = () => false) => workspaceMenuAction(async () => { await cleanWorkspace.settled(); if (stale()) return; const opened = await localProfiles.open(id); railChanged(); if (opened === false) throw new Error(nativeT("native.places.profileFailed")); }), local: localProfiles,
add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin(), account: !desktopRemoteAccess && Boolean(accounts.view().active) }),
probe: serverConnect.probe, run: (choice, link, code) => (choice === "link" ? (link ? (code === null ? connectHostedWorkspace(link) : serverConnect.connect(link, code)) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });
const announceAddedCloud = createAddedCloudNotice({ t: nativeT, Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,
diff --git a/electron/place-switch.mjs b/electron/place-switch.mjs
new file mode 100644
index 0000000000..04b721cc4b
--- /dev/null
+++ b/electron/place-switch.mjs
@@ -0,0 +1,64 @@
+// A click on the window's rail is taken at once and the place asked for last is the one that opens. A click while a
+// switch is under way replaces it straight away, whether it goes to another place or back to the one on screen:
+// main stops what can be stopped (`stop`) and a server restart that can't be stopped leaves the window alone when it
+// ends (`turn`). The rail's page marks the place from its own click; this list says what only main knows (`waking`).
+
+/** The longest a switch stays listed once its work is done, waiting for the new page to finish loading. */
+export const PAGE_SETTLE_MS = 30_000;
+
+/**
+ * @param {{
+ * changed?(): void,
+ * stop?(): void,
+ * kept?(): unknown,
+ * pageSettled?(): Promise<unknown> | undefined,
+ * setTimer?: typeof setTimeout,
+ * clearTimer?: typeof clearTimeout,
+ * }} deps `stop()`: ends what the last click had under way, before the new one runs. `kept()`: what the next launch would
+ * open, read before a switch starts so going back to the place on screen can put it back. `pageSettled()`: settles once
+ * the window's page has finished loading (undefined while it isn't loading).
+ */
+export function createPlaceSwitch({ changed = () => {}, stop = () => {}, kept = () => null, pageSettled = () => undefined, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
+ let turn = 0, target = null, replacing = false, before = null;
+ const tell = () => { try { changed(); } catch {} };
+ async function settled() {
+ const loading = pageSettled();
+ if (!loading) return;
+ let timer = null;
+ await Promise.race([loading, new Promise((done) => { timer = setTimer(done, PAGE_SETTLE_MS); timer?.unref?.(); })]);
+ clearTimer(timer);
+ }
+ return {
+ /** The place the rail's last click asked for, while it opens: `{ id, waking? }`, else null. */
+ target: () => target,
+ /** Moves with every click. Work that was under way when it moved was replaced. */
+ turn: () => turn,
+ /** The running click replaced one still under way, so going back to the place on screen has something to undo. */
+ replacing: () => replacing,
+ /** What the next launch would open from before the switch under way. */
+ before: () => before,
+ /** My Cloud is being woken for the place asked for, or no longer. */
+ waking(on) {
+ if (!target || Boolean(target.waking) === on) return;
+ target = on ? { ...target, waking: true } : { id: target.id };
+ tell();
+ },
+ /** The rail's click: listed at once, whatever `open` still has to do (it gets `stale()`, true once a newer click came); finished once its page has loaded. */
+ async ask(id, open) {
+ const mine = ++turn;
+ replacing = target !== null;
+ if (!target) before = kept();
+ target = { id };
+ try { stop(); } catch {}
+ tell();
+ try {
+ return await open(() => mine !== turn);
+ } finally {
+ if (mine === turn) {
+ await settled();
+ if (mine === turn) { target = null; replacing = false; before = null; tell(); }
+ }
+ }
+ },
+ };
+}
diff --git a/electron/place-switch.node-test.mjs b/electron/place-switch.node-test.mjs
new file mode 100644
index 0000000000..9fcf4d4611
--- /dev/null
+++ b/electron/place-switch.node-test.mjs
@@ -0,0 +1,125 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ACME, CLOUD, connected, world } from "./fixtures/home-window-world.mjs";
+import { createPlaceSwitch, PAGE_SETTLE_MS } from "./place-switch.mjs";
+
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+const gate = () => { let open; const shut = new Promise((resolve) => { open = resolve; }); return { shut, open }; };
+function rail(over = {}) {
+ const told = [], switches = { told };
+ switches.of = createPlaceSwitch({ changed: () => told.push(switches.of.target()), ...over });
+ return switches;
+}
+
+test("a click is listed before anything else happens, and the place stays listed until its work is done", async () => {
+ const r = rail(), calls = [];
+ const work = gate();
+ const opening = r.of.ask("cloud", async () => { calls.push(r.of.target()); await work.shut; return "opened"; });
+ assert.deepEqual(r.of.target(), { id: "cloud" }, "at once, from the click");
+ assert.deepEqual(r.told, [{ id: "cloud" }], "the rail hears before the switch has done anything");
+ await tick();
+ assert.deepEqual(calls, [{ id: "cloud" }]);
+ assert.deepEqual(r.of.target(), { id: "cloud" });
+ work.open();
+ assert.equal(await opening, "opened");
+ assert.equal(r.of.target(), null, "done");
+ assert.deepEqual(r.told, [{ id: "cloud" }, null]);
+});
+
+test("a click during a switch is not lost: it runs at once, and the last click is the one left listed when the others finish", async () => {
+ const r = rail(), started = [], first = gate(), second = gate(), third = gate();
+ const one = r.of.ask("a", () => { started.push("a"); return first.shut; });
+ const two = r.of.ask("b", () => { started.push("b"); return second.shut; });
+ await tick();
+ assert.deepEqual(started, ["a", "b"], "the second does not wait for the first");
+ assert.equal(r.of.replacing(), true, "it replaced one still under way");
+ first.open();
+ await one;
+ assert.deepEqual(r.of.target(), { id: "b" }, "the older one finishing leaves the newer one listed");
+ const three = r.of.ask("c", () => { started.push("c"); return third.shut; });
+ second.open();
+ await two;
+ assert.deepEqual(r.of.target(), { id: "c" }, "the last click wins, however the earlier ones finish");
+ third.open();
+ await three;
+ assert.equal(r.of.target(), null);
+ assert.equal(r.of.replacing(), false);
+});
+
+test("the first click replaces nothing; what the next launch would open is read once, before the first of a run of clicks", async () => {
+ const seen = { remembered: { team: "t1" } }, r = rail({ kept: () => seen.remembered });
+ const done = r.of.ask("a", async () => { assert.equal(r.of.replacing(), false); });
+ assert.deepEqual(r.of.before(), { team: "t1" });
+ await done;
+ assert.equal(r.of.before(), null, "a finished switch keeps nothing");
+ const held = gate();
+ const one = r.of.ask("b", () => held.shut);
+ seen.remembered = { team: "t2" };
+ const two = r.of.ask("c", async () => { assert.equal(r.of.replacing(), true); assert.deepEqual(r.of.before(), { team: "t1" }, "still from before the run of clicks"); });
+ await two;
+ held.open();
+ await one;
+});
+
+test("the switch stays listed while its page loads, for as long as PAGE_SETTLE_MS at most", async () => {
+ const timers = [];
+ let loading;
+ const r = rail({ pageSettled: () => loading, setTimer: (work, ms) => { const timer = { work, ms }; timers.push(timer); return timer; }, clearTimer: () => {} });
+ await r.of.ask("idle", async () => {});
+ assert.equal(r.of.target(), null, "no load under way: done with the work");
+ const page = gate();
+ loading = page.shut;
+ const opening = r.of.ask("cloud", async () => {});
+ await tick();
+ assert.deepEqual(r.of.target(), { id: "cloud" }, "its page is still loading");
+ page.open();
+ await opening;
+ assert.equal(r.of.target(), null);
+ loading = new Promise(() => {});
+ const stuck = r.of.ask("cloud", async () => {});
+ await tick();
+ assert.deepEqual(r.of.target(), { id: "cloud" });
+ assert.equal(timers.at(-1).ms, PAGE_SETTLE_MS);
+ timers.at(-1).work();
+ await stuck;
+ assert.equal(r.of.target(), null, "a page that never finishes doesn't hold the rail forever");
+});
+
+test("waking is said for the place asked for, and only once it changes", () => {
+ const r = rail();
+ r.of.waking(true);
+ assert.equal(r.of.target(), null, "nothing asked for: nothing to say");
+ void r.of.ask("home", () => new Promise(() => {}));
+ r.told.length = 0;
+ r.of.waking(true); r.of.waking(true);
+ assert.deepEqual(r.of.target(), { id: "home", waking: true });
+ r.of.waking(false);
+ assert.deepEqual(r.told, [{ id: "home", waking: true }, { id: "home" }]);
+});
+
+test("a click ends what the last one had under way in the window: a Cloud being woken never opens once another place was chosen", async () => {
+ const wake = gate();
+ const w = world({ state: connected(), power: { state: "asleep", since: 1, sleeps: true }, cloud: { wakeGate: wake.shut }, url: "http://127.0.0.1:8799/" });
+ const r = rail({ stop: () => w.home.stopOpening() });
+ const opening = r.of.ask("home", () => w.home.show({ place: "cloud" }));
+ await tick();
+ assert.deepEqual(w.home.view(), { screen: "waking" }, "the switch is under way");
+ await r.of.ask("elsewhere", async () => {});
+ assert.deepEqual(w.home.view(), { screen: "opening" }, "the waking is over for this window");
+ wake.open();
+ await opening;
+ assert.deepEqual(w.went, [], "the Cloud it asked for never opens");
+});
+
+test("going back to the place on screen before the other one opened: it stops there, and that place is still the one shown", async () => {
+ const w = world({ state: { ...connected(), teams: [ACME] } });
+ await w.home.show({ place: "cloud" });
+ w.went.length = 0;
+ const r = rail({ stop: () => w.home.stopOpening() });
+ const opening = r.of.ask("team", () => w.home.show({ place: { team: ACME.id, name: ACME.name } }));
+ await r.of.ask("home", async () => { w.home.stay(); });
+ await opening;
+ assert.deepEqual(w.went, [], "the team's Cloud never opens");
+ assert.equal(w.home.placeOrigin(), CLOUD, "My Cloud is still the place on screen");
+});
diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.ts
index 1456daa96d..bfbb72ef0c 100644
--- a/src/components/PlacesRail.test.ts
+++ b/src/components/PlacesRail.test.ts
@@ -84,6 +84,79 @@ it("a click opens the place through main by its id; the one on screen and one no
expect(workspaces.open.mock.calls).toEqual([["a"]]);
});
+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>((done) => { resolve = done; }); return { promise, resolve }; }
+const tile = (id: string) => host.querySelector(`[data-rail-place="${id}"]`);
+const pending = () => [...host.querySelectorAll("[data-rail-pending]")].map((element) => element.getAttribute("data-rail-place"));
+const openWaits = () => { const answer = deferred<undefined>(); workspaces.open.mockImplementationOnce(() => answer.promise); return answer; };
+
+it("the place clicked shows as the one on screen from the click itself, before main has answered, with a pending ring, and the old one stops looking chosen", async () => {
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const main = openWaits();
+ await click(tile("a"));
+ expect(workspaces.open.mock.calls).toEqual([["a"]]);
+ expect(pending()).toEqual(["a"]);
+ expect(tile("a")?.querySelector("[data-rail-ring]")?.getAttribute("data-rail-ring")).toBe("waiting");
+ expect(tile("a")?.querySelector("[data-rail-pill]")?.getAttribute("data-rail-pill")).toBe("page");
+ expect(tile("home")?.querySelector("[data-rail-pill]")?.getAttribute("data-rail-pill")).toBe("hover");
+ await act(async () => { main.resolve(undefined); await main.promise; });
+ expect(pending()).toEqual([]);
+});
+
+it("a click during a switch replaces it at once, and is not lost: the last click is the one left pending", async () => {
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const first = openWaits(), second = openWaits(), third = openWaits();
+ await click(tile("a"));
+ await click(tile("vps"));
+ expect(pending()).toEqual(["vps"]);
+ await click(tile("c"));
+ expect(pending()).toEqual(["c"]);
+ expect(workspaces.open.mock.calls).toEqual([["a"], ["vps"], ["c"]]);
+ await act(async () => { first.resolve(undefined); await first.promise; });
+ await act(async () => { second.resolve(undefined); await second.promise; });
+ expect(pending(), "the older switches finishing leave the last one pending").toEqual(["c"]);
+ await act(async () => { third.resolve(undefined); await third.promise; });
+ expect(pending()).toEqual([]);
+});
+
+it("the same place clicked twice while it is pending is one click; the place on screen clicked meanwhile is the last click, and it is not lost", async () => {
+ await mount(createElement(PlacesRail, { chrome: true }));
+ const first = openWaits(), back = openWaits();
+ await click(tile("a"));
+ await click(tile("a"));
+ expect(workspaces.open.mock.calls).toEqual([["a"]]);
+ await click(tile("home"));
+ expect(workspaces.open.mock.calls, "main hears the person's change of mind").toEqual([["a"], ["home"]]);
+ expect(pending(), "nothing is going anywhere: the place on screen is simply marked again").toEqual([]);
+ expect(tile("home")?.querySelector("[data-rail-pill]")?.getAttribute("data-rail-pill")).toBe("page");
+ await act(async () => { back.resolve(undefined); await back.promise; });
+ await act(async () => { first.resolve(undefined); await first.promise; });
+});
+
+it("on the window's own rail the new place's shell covers the page at once and says waking when main does; a place waiting on a bot keeps its ring only", async () => {
+ await mount(createElement(PlacesRail, { chrome: true }));
+ Object.assign(window, { ogb: { workspaces, cloudAdd, rail: { expand: vi.fn(async () => {}) } } });
+ const main = openWaits();
+ await click(tile("a"));
+ const veil = () => host.querySelector("[data-rail-veil]");
+ expect(veil()?.textContent).toContain("Opening Client A…");
+ expect((window.ogb!.rail!.expand as ReturnType<typeof vi.fn>).mock.calls.at(-1), "it asks for the whole window while it covers the page").toEqual([true]);
+ await act(async () => { rail = { ...rail, switching: { id: "a", waking: true } }; await refreshPlaces(); });
+ expect(veil()?.textContent).toContain("Waking My Cloud…");
+ await act(async () => { rail = { ...rail, places: rail.places.map((entry) => (entry.id === "a" ? { ...entry, settling: "Sam" } : entry)) }; await refreshPlaces(); });
+ expect(veil(), "the work there may take a minute: the page stays to watch").toBeNull();
+ expect(pending()).toEqual(["a"]);
+ await act(async () => { main.resolve(undefined); await main.promise; });
+});
+
+it("a rail drawn on a page draws no shell of its own: its page is the one going away", async () => {
+ await mount(createElement(PlacesRail));
+ const main = openWaits();
+ await click(tile("a"));
+ expect(pending()).toEqual(["a"]);
+ expect(host.querySelector("[data-rail-veil]")).toBeNull();
+ await act(async () => { main.resolve(undefined); await main.promise; });
+});
+
it("one place or none, an older app, or a browser: no rail, and the switcher stays", async () => {
rail = { places: [], add: { cloud: true, link: true, address: true } };
await mount(createElement("div", null, createElement(PlacesRail), createElement(DesktopWorkspaceSwitcher, { inline: true })));
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index 159beea6d6..c504f9cd5b 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -149,17 +149,17 @@ export function topWithin(element: HTMLElement, rail: HTMLElement): number {
/** A place's tile: its mark, with a pill on the rail's edge for the place on screen (a short one on hover), and its dots,
* badge and progress round it, all inside the rail. */
-function PlaceTile({ place, canPair, onOpen, onMenu }: { place: RailPlace; canPair: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void }) {
+function PlaceTile({ place, canPair, pending, onOpen, onMenu }: { place: RailPlace; canPair: boolean; pending: boolean; onOpen: (place: RailPlace) => void; onMenu: (at: MenuAt) => void }) {
const label = placeLabel(place), acts = placeActs(place, canPair);
- return <button type="button" aria-label={tileLabel(place)} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true}
- data-rail-place={place.id} data-rail-kind={place.kind} onClick={() => { if (acts) onOpen(place); }} onContextMenu={menuOpener(place, onMenu)}
+ return <button type="button" aria-label={tileLabel(place)} title={label} aria-current={place.active ? "page" : undefined} aria-disabled={acts ? undefined : true} aria-busy={pending || undefined}
+ data-rail-place={place.id} data-rail-kind={place.kind} data-rail-pending={pending ? "" : undefined} onClick={() => { if (acts) onOpen(place); }} onContextMenu={menuOpener(place, onMenu)}
className={cn("group/tile relative shrink-0 rounded-[8px] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",
!acts && cn("cursor-default", !place.offline && "opacity-75"))}>
<span aria-hidden="true" data-rail-pill={place.active ? "page" : acts ? "hover" : undefined}
className={cn("pointer-events-none absolute -left-1.5 top-1/2 w-[3px] -translate-y-1/2 rounded-r-full bg-ink transition-[height,opacity] duration-150 motion-reduce:transition-none",
place.active ? "h-4" : acts ? "h-2 opacity-0 group-hover/tile:opacity-100" : "hidden")} />
<PlaceMark place={place} />
- {(place.progress !== undefined || place.settling !== undefined) && <ProgressRing value={place.progress} waiting={place.waiting === true || place.settling !== undefined} />}
+ {(place.progress !== undefined || place.settling !== undefined || pending) && <ProgressRing value={place.progress} waiting={place.waiting === true || place.settling !== undefined || pending} />}
{place.attention && <span aria-hidden="true" data-rail-dot className="absolute -right-1 -top-1 size-2.5 rounded-full border-2 border-(--rail-surface) bg-danger" />}
{place.update && !place.attention && <span aria-hidden="true" data-rail-update className="absolute -right-1 -top-1 size-2.5 rounded-full border-2 border-(--rail-surface) bg-accent" />}
<KindBadge place={place} />
@@ -382,6 +382,10 @@ function MorePlaces({ places, canPair, onOpen, onMenu, onClose }: { places: Rail
</div>;
}
+/** The place on screen as the rail should mark it: the one just clicked, from that very click, if there is one. */
+export const markingClicked = (places: RailPlace[], clicked: string | null): RailPlace[] => (clicked === null ? places
+ : places.map(({ active: _active, ...place }) => (place.id === clicked ? { ...place, active: true as const } : place)));
+
/** `chrome`: the window's own rail (ChromeRail), drawn whatever the window's width, whose sheets ask main for the whole
* window while open. Without it, a rail drawn on a page from a list main gave that page: wide windows only. */
export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
@@ -396,7 +400,13 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
const [accounts, setAccounts] = useState<{ adding: string | null; note: string | null } | null>(null);
const moreRef = useRef<HTMLDivElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
- // The place last clicked, until main lists it on screen: the one still marked meanwhile can be clicked to stay.
+ // The place last clicked and the one on screen when it was, from the click until main is done with it: another click
+ // replaces it at once, whether it goes elsewhere or back to the place on screen.
+ const [clicked, setClicked] = useState<{ id: string; from: string | null } | null>(null);
+ const lastClick = useRef<{ id: string; from: string | null } | null>(null);
+ const clicks = useRef(0);
+ const click = (next: { id: string; from: string | null } | null) => { lastClick.current = next; setClicked(next); };
+ // The place last asked for, until main lists it on screen: the one still marked meanwhile can be clicked to stay.
const asked = useRef<string | null>(null);
useEffect(() => { if (asked.current && state.places.find((place) => place.id === asked.current)?.active) asked.current = null; }, [state.places]);
const navRef = useRef<HTMLElement>(null);
@@ -409,20 +419,27 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
window.addEventListener("mousedown", away);
return () => window.removeEventListener("mousedown", away);
}, [more, menu]);
- const covering = more || adding || connecting !== null || menu !== null || accounts !== null;
+ const going = clicked && clicked.id !== clicked.from ? state.places.find((place) => place.id === clicked.id) ?? null : null;
+ const veil = chrome && going?.settling === undefined ? going : null;
+ const covering = more || adding || connecting !== null || menu !== null || accounts !== null || veil !== null;
useEffect(() => { if (chrome) void window.ogb?.rail?.expand?.(covering)?.catch(() => {}); }, [chrome, covering]);
if (!state.places.length) return null;
const bridge = window.ogb?.workspaces;
const open = (place: RailPlace) => {
if (!place.opens) { if (place.pairs) setConnecting(place.name); return; }
- if (place.active && (asked.current === null || asked.current === place.id)) return;
+ const onScreen = state.places.find((entry) => entry.active)?.id ?? null;
+ if (place.id === lastClick.current?.id || (place.id === onScreen && (asked.current === null || asked.current === place.id))) return;
asked.current = place.id;
+ const mine = ++clicks.current;
+ click({ id: place.id, from: onScreen });
+ const done = () => { if (mine === clicks.current) click(null); };
track("rail_place_opened", { kind: place.kind });
- void bridge?.open?.(place.id).then((said) => {
+ void Promise.resolve(bridge?.open?.(place.id)).then((said) => {
+ done();
if (!said) return;
if (said.outcome === "sign-in") setAccounts({ adding: said.email ?? place.email ?? "", note: null });
else { const note = switchNote(said); if (note) setAccounts({ adding: null, note }); }
- }, () => {});
+ }, done);
};
const framed = windowFramed(capabilities), draggable = capabilities.windowChrome !== "native";
// In a framed window the rail is part of the frame: the window's own rail runs the full height, its top in the frame's
@@ -433,7 +450,8 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
// SAFETY: Electron's -webkit-app-region is not in React's CSSProperties type; the renderer accepts it as an inline style.
const drag = draggable ? ({ WebkitAppRegion: "drag" } as CSSProperties) : undefined;
const noDrag = draggable ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;
- const shown = shownPlaces(state.places);
+ const places = markingClicked(state.places, clicked?.id ?? null);
+ const shown = shownPlaces(places);
const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair || state.add.organization === true || state.add.account === true || state.add.local === true;
const addLabel = t(state.add.local ? "rail.addAny" : "rail.add");
// The menu opens next to the tile or row it was asked from (measured now, while that row is there), within the rail.
@@ -449,7 +467,7 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
<ul className="flex min-h-0 w-full flex-col items-center gap-2 overflow-y-auto py-1" style={noDrag}>
{shown.map((place, at) => <li key={place.id} className="flex flex-col items-center gap-2">
{startsGroup(shown, at) && <span role="separator" data-rail-divider className="h-px w-4 bg-hairline" />}
- <PlaceTile place={place} canPair={canPair} onOpen={open} onMenu={openMenu} />
+ <PlaceTile place={place} canPair={canPair} pending={place.id === going?.id} onOpen={open} onMenu={openMenu} />
</li>)}
</ul>
<div className="relative mt-2 flex flex-col items-center gap-2 pb-3" style={noDrag} ref={moreRef}>
@@ -458,7 +476,7 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
className="grid size-6 place-items-center rounded-[8px] text-ink-secondary hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus aria-expanded:bg-ink/[0.06]">
<MoreHorizontal size={13} aria-hidden="true" />
</button>}
- {more && <MorePlaces places={state.places} canPair={canPair} onOpen={open} onMenu={openMenu} onClose={() => setMore(false)} />}
+ {more && <MorePlaces places={places} canPair={canPair} onOpen={open} onMenu={openMenu} onClose={() => setMore(false)} />}
{canAdd && <button type="button" aria-label={addLabel} title={addLabel} aria-haspopup="dialog" data-rail-add onClick={() => { track("rail_add", { step: "opened" }); setAdding(true); }}
className="grid size-6 place-items-center rounded-[8px] border border-dashed border-ink/25 text-ink-secondary hover:border-ink/40 hover:bg-ink/[0.04] hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
<Plus size={13} aria-hidden="true" />
@@ -471,5 +489,9 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {
{adding && <PlaceAddSheet choices={state.add} places={state.places} onClose={() => setAdding(false)} onAccount={() => { setAdding(false); setAccounts({ adding: "", note: null }); }} />}
{accounts && <AccountsSheet adding={accounts.adding} note={accounts.note} onClose={() => setAccounts(null)} />}
{connecting !== null && <PlaceAddSheet choices={state.add} connect={{ name: connecting }} onClose={() => setConnecting(null)} />}
+ {veil && <div role="status" data-rail-veil style={drag} className="absolute inset-y-0 left-full z-40 flex w-[calc(100vw-2.25rem)] flex-col items-center justify-center gap-3 bg-panel text-[13px] text-ink-secondary">
+ <PlaceMark place={veil} size={40} />
+ <span>{state.switching?.id === veil.id && state.switching.waking ? t("homeScreen.waking") : t("homeScreen.openingNamed", { name: veil.kind === "computer" ? computerName(veil) : veil.name })}</span>
+ </div>}
</nav>;
}