Skip to content

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

The sidebar's rows and the link's records of the other place's bots carry one address and one word for where a bot lives (#6126)

Milind Sonid3fac44691ab
diff --git a/electron/bot-link-address.d.mts b/electron/bot-link-address.d.mts
new file mode 100644
index 0000000000..56e6d9ab1d
--- /dev/null
+++ b/electron/bot-link-address.d.mts
@@ -0,0 +1,4 @@
+/** The eight hex characters that stand for one place in every address of its bots (server/bot-link/protocol.ts `peerKey`). */
+export function placeKey(placeId: string): string;
+/** A bot's address in the other place (server/bot-link/protocol.ts `linkedId`). */
+export function linkedAddress(placeId: string, botId: string): string;
diff --git a/electron/bot-link-address.mjs b/electron/bot-link-address.mjs
new file mode 100644
index 0000000000..3a3e54180a
--- /dev/null
+++ b/electron/bot-link-address.mjs
@@ -0,0 +1,11 @@
+// The address a bot of the person's other place has over the link (server/bot-link/protocol.ts): `link-<place key>-<its
+// id there>`, the place key cut from that place's own identity. Main computes it for the rows the sidebar lists
+// (places-together.mjs), so a row and the link's record of the same bot (a stand-in) carry one id.
+// server/bot-link/address.test.ts holds this file and the server's own to the same answer.
+import { createHash } from "node:crypto";
+
+/** The eight hex characters that stand for one place in every address of its bots. */
+export const placeKey = (placeId) => createHash("sha256").update(String(placeId)).digest("hex").slice(0, 8);
+
+/** A bot's address in the other place: the place it lives in, and its id there. */
+export const linkedAddress = (placeId, botId) => `link-${placeKey(placeId)}-${botId}`;
diff --git a/electron/bot-link-main.mjs b/electron/bot-link-main.mjs
index 792b724777..295691f84e 100644
--- a/electron/bot-link-main.mjs
+++ b/electron/bot-link-main.mjs
@@ -12,6 +12,7 @@
//
// Security: only My Cloud is ever paired (the address the person's account names), never a server saved by hand or a
// team's Cloud. The link's sign-in goes from My Cloud to this computer's server and nowhere else; no page sees it.
+import { linkedAddress } from "./bot-link-address.mjs";
import { BACKGROUND_HEADERS } from "./cloud-power.mjs";
import { parseTogether } from "./places-together.mjs";
@@ -36,15 +37,17 @@ async function body(response) {
* fetch: typeof fetch,
* cloud(): { origin: string | null, account: string | null, asleep: boolean, signedOut?: boolean },
* cloudName(): string,
+ * changed?(): void,
* log?(line: string): void,
* watchMs?: number,
* now?(): number,
* }} deps `wanted()`: the switch is on and both places exist. `pref`: the switch's own file: turning it off ends a
* link (My Cloud not being seen for a moment leaves it alone, and so does a file that cannot be read). `cloud()`: My
* Cloud's address and the signed-in account while the person has them, whether the Admin says it sleeps now, and
- * whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language.
+ * whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language. `changed()`: the
+ * addresses `address` gives changed (the link came, went, or is another Cloud's now).
*/
-export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl, cloud, cloudName, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {
+export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl, cloud, cloudName, changed = () => {}, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {
const local = async (method, payload) => {
const response = await localRequest(STATE, { method, signal: AbortSignal.timeout(15_000),
...(payload === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }) });
@@ -83,19 +86,38 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl
}
}
+ /** What this computer's server last said of its link, and the Cloud and account it holds for: what `address` reads. */
+ let known = null, addressed = "";
+ const linkedTo = () => {
+ const mine = cloud();
+ if (!known?.on || known.role !== "dialer" || !known.peer?.id || !mine.origin || mine.signedOut || known.origin !== mine.origin) return null;
+ if (mine.account && known.account && mine.account !== known.account) return null;
+ return known.peer;
+ };
+ const note = (state) => {
+ known = state;
+ const next = JSON.stringify([linkedTo()?.id ?? null, computer?.id ?? null]);
+ if (next === addressed) return;
+ addressed = next;
+ try { changed(); } catch {}
+ };
+
const switchedOff = () => { try { return !parseTogether(pref.read()); } catch (error) { return error?.code === "ENOENT"; } };
- let retryAt = -Infinity, switchWasOn = null, looking = null;
+ let retryAt = -Infinity, switchWasOn = null, looking = null, idle = false;
async function tryPair(force) {
if (!force && now() < retryAt) return;
let paired;
try { paired = await pair(); } catch (error) { paired = { on: false, error: error?.message ?? String(error) }; }
- if (paired.on) { retryAt = -Infinity; return; }
+ if (paired.on) { retryAt = -Infinity; note(paired); return; }
retryAt = now() + (paired.error === "cloud-outdated" ? OUTDATED_RETRY_MS : RETRY_MS);
log(`bot link: not linked to My Cloud (${paired.error})`);
}
async function reconcile() {
+ idle = false;
const state = await local("GET").catch(() => null);
if (!state) return;
+ if (state.on) await thisComputer().catch(() => null);
+ note(state);
const mine = cloud(), off = switchedOff();
const justOn = switchWasOn === false && !off;
switchWasOn = !off;
@@ -103,13 +125,15 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl
// A link that ended while its Cloud slept or could not be reached: this computer's server tells that Cloud now.
if (mine.origin && !mine.asleep && Array.isArray(state.ended) && state.ended.includes(mine.origin)) await local("PUT", { cloud: "awake", origin: mine.origin }).catch(() => {});
if (wanted() && !mine.signedOut && (justOn || !mine.asleep)) await tryPair(justOn);
+ // Off, with nothing linked and nothing left to tell a Cloud: the timer has no more to do until something changes.
+ else idle = off && !(Array.isArray(state.ended) && state.ended.length);
return;
}
if (state.role !== "dialer") return;
const otherCloud = Boolean(mine.origin && state.origin && mine.origin !== state.origin), otherAccount = Boolean(mine.account && state.account && mine.account !== state.account);
if (off || mine.signedOut || otherCloud || otherAccount) {
retryAt = -Infinity;
- await local("PUT", { on: false });
+ note(await local("PUT", { on: false }));
const me = await thisComputer().catch(() => null);
// This computer's server told its Cloud if it could. Over the person's own sign-in main can make sure, for the same Cloud and account only.
if (me && mine.origin && mine.origin === state.origin && !mine.asleep && !mine.signedOut && !otherAccount) await forget(mine.origin, me.id);
@@ -127,8 +151,20 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl
return looking;
}
- const watch = setInterval(() => { void look(); }, watchMs);
+ const watch = setInterval(() => { if (!idle) void look(); }, watchMs);
watch.unref?.();
void look();
- return { look, close: () => clearInterval(watch) };
+ return {
+ look,
+ /** The address over the link of a bot the sidebar lists for `home`: where the other place's bots know it, and where
+ * this place's stand-in for it is found. Null while no link of this Cloud and account is on, so a row never carries
+ * an address that belongs to another Cloud's or another account's link. */
+ address(home, botId) {
+ const peer = linkedTo();
+ if (!peer || typeof botId !== "string" || !botId) return null;
+ if (home === "cloud") return linkedAddress(peer.id, botId);
+ return home === "computer" && computer ? linkedAddress(computer.id, botId) : null;
+ },
+ close: () => clearInterval(watch),
+ };
}
diff --git a/electron/bot-link-main.node-test.mjs b/electron/bot-link-main.node-test.mjs
index fcc24de209..315d35f80b 100644
--- a/electron/bot-link-main.node-test.mjs
+++ b/electron/bot-link-main.node-test.mjs
@@ -1,11 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { linkedAddress } from "./bot-link-address.mjs";
import { createBotLinkMain, OUTDATED_RETRY_MS, RETRY_MS } from "./bot-link-main.mjs";
const CLOUD = "https://omb-u-1.fly.dev";
-function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = false } = {}) {
+function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = false, watchMs = 3_600_000 } = {}) {
const cloudCalls = [], localCalls = [];
let server = { on: false };
const the = { switch: on, asleep: false, origin, account: "account-1", signedOut: false, clock: 1_000_000, unreadable: false, putFails };
@@ -31,7 +32,8 @@ function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = fals
},
cloud: () => ({ origin: the.origin, account: the.account, asleep: the.asleep, signedOut: the.signedOut }),
cloudName: () => "My Cloud",
- watchMs: 3_600_000,
+ watchMs,
+ changed: () => { the.changes = (the.changes ?? 0) + 1; },
now: () => the.clock,
});
const pairs = () => cloudCalls.filter((call) => call.method === "POST").length;
@@ -47,6 +49,57 @@ test("switch off: My Cloud is never asked and this computer's server is only rea
assert.equal(h.localCalls.every((call) => call.method === "GET"), true);
});
+test("switch off and nothing linked: after one look the timer asks this computer's server nothing more, until something changes", async (t) => {
+ const h = harness({ watchMs: 5 });
+ t.after(() => h.link.close());
+ await h.link.look();
+ const looked = h.localCalls.length;
+ await new Promise((done) => setTimeout(done, 60));
+ assert.equal(h.localCalls.length, looked, "the timer is idle");
+ assert.equal(h.link.address("cloud", "scout"), null);
+ h.the.switch = true;
+ await h.link.look();
+ assert.equal(h.server.on, true, "a change looks again, and pairs");
+});
+
+test("a link that ended while its Cloud could not be told keeps the timer looking", async (t) => {
+ const h = harness({ watchMs: 5 });
+ t.after(() => h.link.close());
+ await h.link.look();
+ h.server = { on: false, ended: [CLOUD] };
+ h.the.asleep = true;
+ await h.link.look();
+ const looked = h.localCalls.length;
+ await new Promise((done) => setTimeout(done, 60));
+ assert.equal(h.localCalls.length > looked, true);
+});
+
+test("the address of a bot of the other place is the link's own, only while the link is this Cloud's and this account's", async (t) => {
+ const h = harness({ on: true });
+ t.after(() => h.link.close());
+ assert.equal(h.link.address("cloud", "scout"), null, "not linked yet");
+ await h.link.look();
+ // sha256("cloud-1") and sha256 of this computer's id, cut to eight: server/bot-link/address.test.ts holds both sides to it.
+ assert.equal(h.link.address("cloud", "scout"), linkedAddress("cloud-1", "scout"));
+ assert.equal(h.link.address("computer", "scout"), linkedAddress("11111111-1111-4111-8111-111111111111", "scout"));
+ assert.match(h.link.address("cloud", "scout"), /^link-[0-9a-f]{8}-scout$/);
+ assert.equal(h.the.changes >= 1, true, "the sidebar is told the addresses came");
+ h.the.account = "account-2";
+ assert.equal(h.link.address("cloud", "scout"), null, "another account: none, before the next look");
+ h.the.account = "account-1";
+ h.the.origin = "https://omb-u-2.fly.dev";
+ assert.equal(h.link.address("cloud", "scout"), null, "another Cloud: none");
+ h.the.origin = CLOUD;
+ h.the.signedOut = true;
+ assert.equal(h.link.address("computer", "scout"), null, "signed out: none");
+ h.the.signedOut = false;
+ h.the.switch = false;
+ const before = h.the.changes;
+ await h.link.look();
+ assert.equal(h.link.address("cloud", "scout"), null, "turned off: none");
+ assert.equal(h.the.changes > before, true);
+});
+
test("switch on: pairs in the background over the person's own sign-in and hands the link's sign-in, bound to this Cloud and account, to this computer's server", async (t) => {
const h = harness({ on: true });
t.after(() => h.link.close());
diff --git a/electron/main.mjs b/electron/main.mjs
index 8403495a3b..0696e1b7af 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2604,7 +2604,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(
const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });
const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));
const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });
-const oneHome = installOneHome({ ipcMain, 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: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), 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, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, 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: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), 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(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, 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: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), 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, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, 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: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), 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(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, 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, synced: state => teamLinks.changed(state), log: slog });
const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,
@@ -2622,7 +2622,7 @@ function showHome(options) {
return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));
}
const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlaces, profiles: localProfiles, log: slog, server: id => { const entry = environmentsState.environments.find(candidate => candidate.id === id && handSaved(candidate)); return entry ? reopenSavedServer(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (found) => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); persistEnvironments(withActive(environmentsState, found.id)); return navigateMainWindow(activeOrigin()); } }) : Promise.resolve(false); } }).catch(error => slog(`start: ${error?.message ?? error}`)); const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };
-const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() }); const homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, together: createPlacesTogether({ pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: async () => { const account = cloudAccount; if (!account) return false; await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }, computer: () => !(homeWindow.cloudOrigin() ?? ownHome?.origin()), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { botLink?.look(); if (shownHome()) mainWindow.webContents.send("places-together:changed"); } }) });
+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 homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, together: createPlacesTogether({ pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: async () => { const account = cloudAccount; if (!account) return false; await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }, computer: () => !(homeWindow.cloudOrigin() ?? ownHome?.origin()), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), address: (home, botId) => botLink?.address(home, botId) ?? null, shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { botLink?.look(); if (shownHome()) mainWindow.webContents.send("places-together:changed"); } }) });
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 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 openPlace = (id, stale) => workspaceMenuAction(async () => { if (id === LOCAL_ID) await cleanWorkspace.settled(); if (!stale()) await switchEnvironment(id, stale); }); const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(), openComputer: (page) => openComputerSettings({ window: () => mainWindow, onLocal: (win) => senderIsLocal({ sender: win.webContents }), showLocal: () => placeSwitch.ask(LOCAL_ID, stale => { localProfiles.cancel(); return openPlace(LOCAL_ID, stale); }) }, page),
diff --git a/electron/places-together.d.mts b/electron/places-together.d.mts
index 2cbfd2cb11..dea83c7c27 100644
--- a/electron/places-together.d.mts
+++ b/electron/places-together.d.mts
@@ -5,6 +5,10 @@ export type BotHome = "computer" | "cloud";
export interface PlaceBotRow {
home: BotHome;
id: string;
+ /** Its address over the link between the two places (`link-<place key>-<id>`): the id of this place's stand-in record
+ * for it, and what a room, a Chief or an automation here names it by. Absent while no link of this Cloud and account
+ * is on; the row is listed all the same. */
+ address?: string;
threadId: string;
name: string;
title?: string;
diff --git a/electron/places-together.mjs b/electron/places-together.mjs
index d78284fbc6..32fd02fb9a 100644
--- a/electron/places-together.mjs
+++ b/electron/places-together.mjs
@@ -91,6 +91,7 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =
* local(route: string, init?: RequestInit): Promise<Response>,
* cloudFetch(url: string, init?: RequestInit): Promise<Response>,
* napped?(): void,
+ * address?(home: "computer" | "cloud", botId: string): string | null,
* shown(): "computer" | "cloud" | "waking" | "other" | null,
* focused(): boolean,
* openPlace(home: "computer" | "cloud"): unknown,
@@ -108,14 +109,15 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =
* wakes, "other" for any other place or screen, null while a page loads.
* `focused()`: the window is the one the person is using: in front, and the screen not locked. `openPlace(home)`: main's
* own switch to that place, waking My Cloud as opening it always does. `send`: to the page on screen. `changed()`: the
- * list or the switch changed, so a page that draws it asks again.
+ * list or the switch changed, so a page that draws it asks again. `address(home, botId)`: the address the link between
+ * the two places gives that bot (electron/bot-link-main.mjs), or null while no link of this Cloud and account is on.
*
* Security: My Cloud is never asked while it sleeps, since any request would wake it and run up its hours. It is asked
* only right after the Admin said it is awake, at most once a minute, and only while the person is using the window. What
* remains is a Cloud that fell asleep in the seconds since the Admin answered; one that only agreed to sleep answers so
* itself and is left alone. Rows are kept for the Cloud and account they came from, and dropped the moment either changes.
*/
-export function createPlacesTogether({ pref, cloud, powerChecked, computer, local, cloudFetch, napped = () => {}, shown, focused, openPlace, send, changed, now = Date.now,
+export function createPlacesTogether({ pref, cloud, powerChecked, computer, local, cloudFetch, napped = () => {}, address = () => null, shown, focused, openPlace, send, changed, now = Date.now,
setTimer = setInterval, clearTimer = clearInterval, later = setTimeout, cancelLater = clearTimeout }) {
/** What each place gave last: its rows, when, and how the last read went. */
const kept = new Map();
@@ -264,11 +266,19 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca
}, over);
}
+ /** The row with the address the link gives its bot, worked out as the row is handed over: the list is the sidebar's
+ * own read and stays whole with the link down; the address is there only while the link is this Cloud's and account's. */
+ function addressed(row) {
+ let linked = null;
+ try { linked = address(row.home, row.id); } catch {}
+ return typeof linked === "string" && linked ? { ...row, address: linked } : row;
+ }
+
function otherOf(asking) {
const home = otherHome(asking), known = kept.get(home);
const state = home === "cloud" && pending?.home === home && (cloud().asleep || known?.state !== "ready") ? "waking"
: home === "cloud" && cloud().asleep ? "asleep" : known?.state ?? "loading";
- return { home, state, bots: known?.bots ?? [], ...(typeof known?.newBot === "boolean" ? { newBot: known.newBot } : {}) };
+ return { home, state, bots: (known?.bots ?? []).map((row) => addressed(row)), ...(typeof known?.newBot === "boolean" ? { newBot: known.newBot } : {}) };
}
return {
@@ -294,6 +304,8 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca
refresh,
/** The signed-in account or My Cloud's address may have changed: lists that belong to another are dropped now. */
scopeChanged: sameScope,
+ /** The link between the two places came, went or changed hands: rows on screen get their addresses again. */
+ linkChanged() { if (active() && kept.size > 0) tell(); },
/** A row's click: the other place opens at that bot. Only a bot main listed itself, for this Cloud and account, opens. */
open(asking, botId) {
sameScope();
diff --git a/electron/places-together.node-test.mjs b/electron/places-together.node-test.mjs
index a935e477d3..e6b6cb092e 100644
--- a/electron/places-together.node-test.mjs
+++ b/electron/places-together.node-test.mjs
@@ -45,6 +45,7 @@ function setup(over = {}) {
test("the switch starts off, and off reads nothing, keeps nothing and starts no timer", async () => {
const f = setup({ saved: null });
+ f.together.linkChanged();
assert.equal(parseTogether(null), false);
assert.equal(parseTogether({ v: 1, on: "yes" }), false);
assert.deepEqual(f.together.state("computer"), { v: 1, available: true, on: false, here: "computer", other: null });
@@ -71,6 +72,28 @@ test("on: this computer's page lists My Cloud's bots, asked as background work w
assert.equal(f.changes, 1);
});
+test("a row carries the address the link gives its bot, worked out as it is handed over; with no link the list is as whole and has none", async () => {
+ let linked = true;
+ const f = setup({ deps: { address: (home, id) => (linked ? `link-0a1b2c3d-${home}-${id}` : null) } });
+ await f.together.refresh("cloud");
+ assert.deepEqual(f.together.state("computer").other.bots.map((row) => [row.home, row.id, row.address]), [["cloud", "scout", "link-0a1b2c3d-cloud-scout"], ["cloud", "nova", "link-0a1b2c3d-cloud-nova"]]);
+ const asked = f.asked.length;
+ linked = false;
+ const rows = f.together.state("computer").other.bots;
+ assert.deepEqual(rows.map((row) => [row.id, "address" in row]), [["scout", false], ["nova", false]], "the link went: the same rows, no address");
+ assert.equal(f.asked.length, asked, "an address asks no place anything");
+ assert.equal(f.together.open("computer", "nova"), true, "a row opens by its own id, linked or not");
+ const told = f.changes;
+ f.together.linkChanged();
+ assert.equal(f.changes, told + 1, "the page is told to ask again when the link changes");
+});
+
+test("an address that cannot be worked out leaves the row as it is", async () => {
+ const f = setup({ deps: { address: () => { throw new Error("no"); } } });
+ await f.together.refresh("cloud");
+ assert.deepEqual(f.together.state("computer").other.bots.map((row) => row.id), ["scout", "nova"]);
+});
+
test("My Cloud's page lists this computer's bots the same way", async () => {
const f = setup();
f.shown = "cloud";
diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.ts
index 4c4f5221e6..bc87132568 100644
--- a/server/bot-link.e2e.test.ts
+++ b/server/bot-link.e2e.test.ts
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from
import { join } from "node:path";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { linkedAddress } from "../electron/bot-link-address.mjs";
type Fixture = Awaited<ReturnType<typeof launchVerificationServer>>;
@@ -66,7 +67,9 @@ it("a bot on the computer and a bot on the person's own server hand each other w
// and it takes no turn on the computer.
const rows = (await computer.api("GET", "/api/bot-link/bots")).bots as any[];
const standIn = rows.find((row) => row.name === "Atlas");
- expect(standIn).toMatchObject({ botId: atlas.id, home: { name: "My server", online: true }, threadId: expect.any(String) });
+ expect(standIn).toMatchObject({ botId: atlas.id, home: { name: "My server", kind: "cloud", key: expect.stringMatching(/^[0-9a-f]{8}$/u), online: true }, threadId: expect.any(String) });
+ // The address is the one the app's main process works out for the sidebar's row of the same bot.
+ expect(standIn.id).toBe(linkedAddress(paired.place.id, atlas.id));
expect(standIn.id).toMatch(/^link-[0-9a-f]{8}-/);
expect(JSON.stringify(await computer.api("GET", `/api/bots/${standIn.id}`))).toContain("\"Atlas\"");
expect((await computer.api("GET", "/api/bots?messages=0")).bots.some((bot: any) => bot.id === standIn.id)).toBe(false);
diff --git a/server/bot-link/address.test.ts b/server/bot-link/address.test.ts
new file mode 100644
index 0000000000..6c2cc4e117
--- /dev/null
+++ b/server/bot-link/address.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+
+import { linkedAddress, placeKey } from "../../electron/bot-link-address.mjs";
+import { linkedId, parseLinked, peerKey } from "./protocol.ts";
+
+describe("a bot of the other place has one address", () => {
+ it("the app's main process and the server cut the same place key and build the same address", () => {
+ for (const place of ["11111111-1111-4111-8111-111111111111", "cloud-1", "ünïcode place", ""]) {
+ expect(placeKey(place)).toBe(peerKey(place));
+ for (const bot of ["scout", "bot-with-dashes-1", "a_b"]) {
+ expect(linkedAddress(place, bot)).toBe(linkedId(peerKey(place), bot));
+ expect(parseLinked(linkedAddress(place, bot))).toEqual({ peer: peerKey(place), botId: bot });
+ }
+ }
+ });
+});
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index 0e5b5b3689..c6afcd3885 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -698,6 +698,7 @@ describe("the link between a computer and its Cloud", () => {
const { computer, cloud } = await two();
expect(computer.link.linked().map((one) => [one.id, one.place.name, one.online, one.bot.name])).toEqual([[onCloud("shared"), "My Cloud", true, "Atlas"], [onCloud("cloud-analyst"), "My Cloud", true, "Analyst"]]);
expect(cloud.link.linked().map((one) => one.id)).toEqual([onComputer("shared"), onComputer("local-writer")]);
+ expect([...new Set(computer.link.linked().map((one) => one.kind)), ...new Set(cloud.link.linked().map((one) => one.kind))]).toEqual(["cloud", "computer"]);
const before = cloud.directoryChanges();
computer.bots.push({ id: "new", name: "Newcomer" });
computer.link.botsChanged();
diff --git a/server/bot-link/link.ts b/server/bot-link/link.ts
index 4749917f15..460bee2b58 100644
--- a/server/bot-link/link.ts
+++ b/server/bot-link/link.ts
@@ -738,8 +738,9 @@ export function createBotLink(deps: BotLinkDeps) {
peers: Object.entries(state.peers).map(([peer, known]) => ({ ...known.place, online: isOnline(peer), bots: known.bots.length })),
bots: Object.values(state.peers).reduce((sum, known) => sum + known.bots.length, 0), waiting: pending.size }
: (() => { const ended = [...new Set(readEnded().map((one) => one.origin))]; return { on: false as const, ...(ended.length ? { ended } : {}) }; })()),
- /** Every bot of every linked place, with its address here. */
- linked: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), peer, place: known.place, online: isOnline(peer), bot }))),
+ /** Every bot of every linked place, with its address here. `kind`: what that place is, in the words the sidebar's
+ * own rows use for where a bot lives: a computer links to its Cloud, a Cloud to computers. */
+ linked: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), peer, place: known.place, kind: state!.role === "dialer" ? "cloud" as const : "computer" as const, online: isOnline(peer), bot }))),
/** Other places' bots as list_bots names them. */
agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,
status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : `on ${known.place.name}, offline now: work for it waits until it is back`,
diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.ts
index 011888a841..48df15bdec 100644
--- a/server/host/bot-link-host.ts
+++ b/server/host/bot-link-host.ts
@@ -41,9 +41,9 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {
* It has no conversation, model or tools here, and takes no turn here. */
const syncStandIns = () => {
const next = new Map<string, BotRecord>();
- for (const { id, peer, place, bot } of link.linked()) {
+ for (const { id, peer, place, kind, bot } of link.linked()) {
next.set(id, { id, name: bot.name, color: bot.color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: bot.model ?? "" },
- home: { place: peer, placeName: place.name, botId: bot.id }, ...(bot.title ? { title: bot.title } : {}), ...(bot.description ? { description: bot.description } : {}),
+ home: { place: peer, placeName: place.name, botId: bot.id, kind }, ...(bot.title ? { title: bot.title } : {}), ...(bot.description ? { description: bot.description } : {}),
...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}) } as unknown as BotRecord);
}
store.standIns.clear();
diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.ts
index 06c9938ca5..82a3e8767c 100644
--- a/server/routes/bot-link.ts
+++ b/server/routes/bot-link.ts
@@ -101,7 +101,7 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
if (!deps.local(auth)) return json(res, 403, { error: "Only the app on this computer lists its other places' bots." });
if (method !== "GET") return json(res, 405, { error: "method not allowed" });
// Names and looks only, as each place told this one: no message, address or sign-in.
- return json(res, 200, { bots: link.linked().map(({ id, place, online, bot }) => ({ id, home: { id: place.id, name: place.name, online }, botId: bot.id, name: bot.name,
+ return json(res, 200, { bots: link.linked().map(({ id, peer, place, kind, online, bot }) => ({ id, home: { id: place.id, key: peer, kind, name: place.name, online }, botId: bot.id, name: bot.name,
...(bot.title ? { title: bot.title } : {}), ...(bot.color ? { color: bot.color } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}),
...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.chief ? { chiefOfStaff: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}) })) });
}
diff --git a/server/store.ts b/server/store.ts
index 1b4d9b6267..4bd4e474e6 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -156,7 +156,7 @@ export function titleFromLlm(raw: string): string | null {
export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {
tasks?: TaskRecord[];
avatarUrl?: string;
- resumeCursors: Record<string, unknown>; /** Set on a stand-in: the place this bot lives in, and its id there. */ home?: { place: string; placeName: string; botId: string }; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.
+ resumeCursors: Record<string, unknown>; /** Set on a stand-in: the place this bot lives in, and its id there. */ home?: { place: string; placeName: string; botId: string; /** What that place is, as the sidebar's rows say it. */ kind?: "computer" | "cloud" }; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.
/** Elevation journal: Full/Custom runs as Ask until Electron confirms the prepared reply; a marker surviving a restart is revoked on load. */
approvalGrant?: {
requestId: string;
diff --git a/src/components/OtherPlaceBots.tsx b/src/components/OtherPlaceBots.tsx
index 4bd1c66273..bcd0fb6ba2 100644
--- a/src/components/OtherPlaceBots.tsx
+++ b/src/components/OtherPlaceBots.tsx
@@ -48,7 +48,7 @@ function OtherPlaceBotRow({ row, dim, iconOnly, simple }: { row: PlaceBotRow; di
const line = row.waiting ? t("sidebar.preview.waiting") : row.working ? t("sidebar.preview.working") : row.title ?? "";
const label = [row.name, homeLabel(row.home), line, row.unread ? t("task.unread") : ""].filter(Boolean).join(" · ");
return (
- <button type="button" data-placed-bot={placedKey(row.home, row.id)} data-bot-home={row.home} title={iconOnly ? label : undefined} aria-label={label}
+ <button type="button" data-placed-bot={placedKey(row.home, row.id)} data-bot-home={row.home} data-bot-address={row.address} title={iconOnly ? label : undefined} aria-label={label}
onClick={() => openOtherPlaceBot(row.id)}
className={cn("flex w-full items-center rounded-xl text-left transition-colors duration-150 hover:bg-raised/50", SIMPLE_ROW_FOCUS,
iconOnly ? "justify-center px-1 py-1.5" : simple ? "gap-2 rounded-[8px] px-2 py-2" : "gap-3 py-2 pl-2.5 pr-3", dim && "opacity-60")}>