Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(rail): remove a server saved by hand from the rail, and never send the window to one that doesn't answer (#4081)
Milind Sonicdbf1495d3f1
diff --git a/electron/cloud-home.node-test.mjs b/electron/cloud-home.node-test.mjsindex 76ed07a88e..04ac8757f2 100644--- a/electron/cloud-home.node-test.mjs+++ b/electron/cloud-home.node-test.mjs@@ -6,6 +6,7 @@ import vm from "node:vm";import { createCloudAccountClient } from "./cloud-account.mjs";import { CLOUD_HOME_NAME, cloudHomeConnectUrl, cloudPlanDisk, cloudUnreachableText, isCloudHomeEntry, parseCloudCredit, parseCloudOffer, parseCloudPower, parseCloudPurchase, parseCloudSummary, parseCloudTeams, teamRoleLabel, CLOUD_TEAM_ROLES, parseCloudTrial, parsePairingGrant, parsePublicOffer, rememberedCloudHome, savedCloudHomeOrigin, withCloudHome, withoutTrial } from "./cloud-home.mjs";import environments from "./environments.cjs";+import { handSaved } from "./own-home-main.mjs";import { homeLook, withoutOldCloudHome } from "./cloud-list.mjs";const NOW = 1_800_000_000_000;@@ -429,7 +430,7 @@ test("the Server menu opens My Cloud through the Cloud's own connection, never aassert.ok(start > 0 && end > start);const calls = [];let connect = async () => { calls.push("connect"); }, signedIn = false;- const entry = { id: "cloud", name: CLOUD_HOME_NAME, origin }, other = { id: "vps", name: "VPS", origin: "https://vps.example.test" };+ const entry = { id: "cloud", name: CLOUD_HOME_NAME, origin }, other = { id: "vps", kind: "remote", name: "VPS", origin: "https://vps.example.test" };const context = vm.createContext({environmentsState: { environments: [entry, other], activeId: environments.LOCAL_ID }, LOCAL_ID: environments.LOCAL_ID,cloudAccount: { homeTarget: () => ({ origin }), state: () => ({}) }, isCloudHomeEntry, slog: () => {},@@ -440,12 +441,18 @@ test("the Server menu opens My Cloud through the Cloud's own connection, never ahomeWindow: { cloudOrigin: () => null, asking: () => false }, showHome: async (options) => { calls.push(options ? `home:${JSON.stringify(options)}` : "home"); },homePlaces: { remember: (place) => calls.push(`remember:${JSON.stringify(place)}`) },runningDataDir: "/data", desktopDataDir: () => "/data",+ handSaved, serverOpens: async (place) => { calls.push(`look:${place.id}`); return answers; }, session: { defaultSession: { fetch: async () => null } }, dialog: {},});+ let answers = true;vm.runInContext(`${source.slice(start, end)}; this.switchEnvironment = switchEnvironment; this.remember = value => { rememberedHome = value; };`, context);await context.switchEnvironment("cloud");assert.deepEqual(calls, ["remember:null", "connect"]);calls.length = 0; await context.switchEnvironment("vps");- assert.deepEqual(calls, ["remember:null", "active:vps", `navigate:${other.origin}`], "another server: the remembered team is let go");+ assert.deepEqual(calls, ["remember:null", "look:vps", "active:vps", `navigate:${other.origin}`], "another server: the remembered team is let go");+ calls.length = 0; context.environmentsState = { ...context.environmentsState, activeId: environments.LOCAL_ID }; answers = false;+ await context.switchEnvironment("vps");+ assert.deepEqual(calls, ["remember:null", "look:vps"], "a server that doesn't answer: the window stays where it is");+ answers = true;const acme = { id: "acme", name: "Acme", origin: "https://omb-u-acme.fly.dev", team: { id: "team-acme", role: "member" } };context.environmentsState = { environments: [entry, other, acme], activeId: environments.LOCAL_ID };calls.length = 0; await context.switchEnvironment("acme");diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mtsindex e61e1627b2..c186fe385f 100644--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@ -34,6 +34,8 @@ export interface RailPlace {ended?: true;/** Its owner may take this Cloud off their list (it ended, or was never paid for): its menu offers Remove from list. */removable?: true;+ /** A server connected by hand: Remove from list forgets it on this computer (this app signs out of it there). */+ forget?: true;/** A server of the person's own, theirs alone by its own word, that this computer's bots may move to: its menu offers* Make … my home. */makeHome?: true;diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex e33e25a7d1..8ebcb6a8d8 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -41,7 +41,7 @@ function circle(entry, { activeId, mine, state, offers }) {const paint = railPaint(placeLook(entry, { clouds: connected?.clouds ?? null, homeOrigin: mine }), color);return { id: entry.id, name: entry.name, color, kind, opens: true, ...(paint ? { paint } : {}), ...(entry.id === activeId ? { active: true } : {}),...(progress !== null ? { progress } : {}), ...(problem ? { attention: true } : {}), ...(listed?.managed === false ? serverState(listed, connected?.latestVersion ?? null) : {}),- ...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}),+ ...(kind === "cloud" && cloudState(listed) === "ended" ? { ended: true } : {}), ...(listed?.removable && kind === "cloud" ? { removable: true, cloudId: listed.id } : {}), ...(kind === "server" ? { removable: true, forget: true } : {}),...(kind === "server" && offers(entry) ? { makeHome: true } : {}) };}@@ -141,7 +141,7 @@ const CHOICES = Object.freeze(["cloud", "link", "address"]);* MausBot Cloud sign-in; `targets()` the pages told when something changed; `makeHome(id)` starts the move to a server* of the person's own (own-home-main.mjs `start`).*/-export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null }) {+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, makeHome = null, forget = null }) {let sheetOpen = false, sent = "";const allowed = (channel, handler) => guard((event, ...args) => {if (!trusted(event)) throw new Error(`${channel} is only available in this app's window`);@@ -164,10 +164,12 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, besif (!place) throw new Error("That place isn't here any more.");return place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id);});- // Remove from list, from a circle's menu (the page asked the person first): only a Cloud main listed as removable.+ // 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.listed("workspaces:remove", async (_event, id) => {- const place = places().find(entry => entry.id === plain(id) && entry.removable && entry.cloudId);+ const place = places().find(entry => entry.id === plain(id) && entry.removable && (entry.cloudId || entry.forget));if (!place) throw new Error("That place isn't here any more.");+ if (place.forget) return { outcome: forget ? ((await forget(place.id)) === false ? "failed" : "removed") : "unsupported" };const client = account();return { outcome: client?.hideCloud ? (await client.hideCloud(place.cloudId)).outcome : "unsupported" };});diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex a9f29516d1..832b7cef2d 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -30,7 +30,7 @@ test("the rail: My Cloud, the person's Clouds and teams' Clouds in the session's{ id: "home", name: "Studio", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, active: true },{ id: "a", name: "Client A", color: "teal", kind: "cloud", opens: true, paint: { swatch: "green" } },{ id: "acme", name: "Acme", color: "yellow", kind: "team", opens: true, paint: { swatch: "amber", locked: "member" } },- { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null } },+ { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null }, removable: true, forget: true },], "each colour changed from the rail, but a team's by its admins alone");for (const origin of [HOME, CLIENT_A, TEAM, VPS, "/Users/person/lab"]) assert.equal(JSON.stringify(places).includes(origin), false, origin);const before = railPlaces({ saved: saved("local"), home: null, mine: HOME, state: session() });@@ -84,7 +84,7 @@ test("a server of the person's own that signed in with their account: one savedentry({ id: "s-render", name: "Render VPS", color: "rose", tier: null, runsOn: "server", managed: false, status: "offline", origin: RENDER, lastSeenAt: 1_761_000_100_000 })]);const state = session({ clouds });const places = railPlaces({ saved: saved(), home: HOME, mine: HOME, state });- assert.deepEqual(places.find(place => place.id === "vps"), { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null }, server: true },+ assert.deepEqual(places.find(place => place.id === "vps"), { id: "vps", name: "Office", color: null, kind: "server", opens: true, paint: { swatch: null }, removable: true, forget: true, server: true },"saved by hand at its address: the same circle, marked as theirs, online, opening as it always did");assert.deepEqual(places.slice(-2), [{ id: "signed-in:s-mini", name: "Mac mini", color: null, kind: "server", opens: false, paint: { swatch: null }, ownNetwork: true, server: true, offline: true, lastSeenAt: 1_761_000_000_000 },@@ -355,3 +355,16 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await local.bridge.workspaces.open("a");assert.deepEqual(local.invoked, [["workspaces:open", "a"]], "this app's own page needs no click check");});++test("Remove from list on a server saved by hand: main forgets it here, by its own word for which one", async () => {+ const forgotten = [];+ const installed = rail({ forget: async (id) => { forgotten.push(id); } });+ const vps = (await installed.call("workspaces:places")).places.find(place => place.id === "vps");+ assert.deepEqual([vps.removable, vps.forget], [true, true]);+ assert.deepEqual(await installed.call("workspaces:remove", "vps"), { outcome: "removed" });+ assert.deepEqual(forgotten, ["vps"]);+ for (const id of ["home", "a", "acme", "lab"]) await assert.rejects(installed.call("workspaces:remove", id), /isn't here/, id);+ assert.deepEqual(forgotten, ["vps"], "never a Cloud, a team's Cloud or this computer's own");+ assert.deepEqual(await rail({ forget: async () => false }).call("workspaces:remove", "vps"), { outcome: "failed" });+ assert.deepEqual(await rail().call("workspaces:remove", "vps"), { outcome: "unsupported" }, "a main without forget says so");+});diff --git a/electron/main.mjs b/electron/main.mjsindex 2527a4aa6a..962dc89b85 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -104,7 +104,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClouimport { 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 { installOneHome } from "./one-home-main.mjs"; import { installOwnHome } from "./own-home-main.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";+import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { 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";@@ -1704,8 +1704,8 @@ async function switchEnvironment(id) {if (!(await cloudHomeSignedIn(entry.origin))) { await openCloudSettings(); return; }}}- persistEnvironments(withActive(environmentsState, id));- navigateMainWindow(activeOrigin());+ if (entry && handSaved(entry) && !(await serverOpens(entry, { fetch: (...args) => session.defaultSession.fetch(...args), dialog, forget: (gone) => forgetEnvironment(gone, false, true) }))) return;+ persistEnvironments(withActive(environmentsState, id)); navigateMainWindow(activeOrigin());}function createLocalEnvironment(name, dataDir) {@@ -1923,11 +1923,11 @@ function askRemoteMicrophone(origin) {return remoteMicrophoneAsks.get(origin);}-async function forgetEnvironment(id, purge = false) {+async function forgetEnvironment(id, purge = false, confirmed = false) {const env = environmentsState.environments.find((e) => e.id === id);if (!env) return;if (env.kind === "local" && environmentsState.activeId === id) return { ok: false, error: "active" };- if (env.kind !== "local") {+ if (env.kind !== "local" && !confirmed) {const { response } = await dialog.showMessageBox({type: "warning",buttons: ["Forget", "Cancel"],@@ -2694,7 +2694,7 @@ const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, accguard: 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),+ places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)), makeHome: id => ownHome.start(id), forget: id => forgetEnvironment(id, false, true),add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,diff --git a/electron/saved-server.d.mts b/electron/saved-server.d.mtsnew file mode 100644index 0000000000..ab87a3994e--- /dev/null+++ b/electron/saved-server.d.mts@@ -0,0 +1,6 @@+export declare const SERVER_LOOK_MS: number;+export declare function serverAnswers(origin: string, fetchImpl: typeof fetch, timeoutMs?: number): Promise<boolean>;+export declare function serverOpens(+ entry: { id: string; name: string; origin: string },+ deps: { fetch: typeof fetch; dialog: { showMessageBox(options: object): Promise<{ response: number }> }; forget: (id: string) => unknown; timeoutMs?: number },+): Promise<boolean>;diff --git a/electron/saved-server.mjs b/electron/saved-server.mjsnew file mode 100644index 0000000000..a267297cec--- /dev/null+++ b/electron/saved-server.mjs@@ -0,0 +1,36 @@+// A server connected by hand, before the window goes there: the window goes only to a server that answers; one that+// doesn't (its name no longer resolves, nothing listens) is the person's choice: try again, remove it, or stay.++/** How long a server has to answer before it counts as not answering. */+export const SERVER_LOOK_MS = 3_000;++/** Whether anything answers at `origin` (any HTTP status but a 5xx from a proxy in front of a stopped app). */+export async function serverAnswers(origin, fetchImpl, timeoutMs = SERVER_LOOK_MS) {+ try {+ const response = await fetchImpl(`${origin}/.well-known/openmausbot/environment`, {+ cache: "no-store", redirect: "manual", credentials: "omit", signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json" },+ });+ return response.status < 500;+ } catch {+ return false;+ }+}++/**+ * True when the window may go to `entry` now. A server that doesn't answer asks the person, in one dialog: Try again+ * (looks once more), Remove from list (`forget(entry.id)`, then false), or Cancel (false: the window stays where it is).+ * @param {{ id: string, name: string, origin: string }} entry+ * @param {{ fetch: typeof fetch, dialog: { showMessageBox(options: object): Promise<{ response: number }> }, forget: (id: string) => unknown, timeoutMs?: number }} deps+ */+export async function serverOpens(entry, { fetch: fetchImpl, dialog, forget, timeoutMs = SERVER_LOOK_MS }) {+ for (;;) {+ if (await serverAnswers(entry.origin, fetchImpl, timeoutMs)) return true;+ const { response } = await dialog.showMessageBox({+ type: "warning", buttons: ["Try again", "Remove from list", "Cancel"], defaultId: 0, cancelId: 2,+ message: `${entry.name} isn't answering`,+ detail: `Nothing answers at ${new URL(entry.origin).host}. If that server is gone for good, remove it from your list. Your bots elsewhere aren't affected.`,+ });+ if (response === 1) { await forget(entry.id); return false; }+ if (response !== 0) return false;+ }+}diff --git a/electron/saved-server.node-test.mjs b/electron/saved-server.node-test.mjsnew file mode 100644index 0000000000..d4a2c3777d--- /dev/null+++ b/electron/saved-server.node-test.mjs@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import test from "node:test";++import { serverAnswers, serverOpens } from "./saved-server.mjs";++const office = { id: "vps", name: "pro cloud", origin: "https://omb-u-gone.fly.dev" };+const answering = (status) => async () => new Response("{}", { status });+const gone = async () => { throw new TypeError("fetch failed"); };+const asked = (responses) => {+ const shown = [];+ return { shown, dialog: { showMessageBox: async (options) => { shown.push(options); return { response: responses.shift() ?? 2 }; } } };+};++test("a server answers with any status but a proxy's 5xx; a name that doesn't resolve, a refused or a slow one doesn't", async () => {+ for (const status of [200, 401, 404]) assert.equal(await serverAnswers(office.origin, answering(status)), true, String(status));+ for (const status of [502, 503]) assert.equal(await serverAnswers(office.origin, answering(status)), false, String(status));+ assert.equal(await serverAnswers(office.origin, gone), false);+ const slow = (_url, init) => new Promise((_, fail) => init.signal.addEventListener("abort", () => fail(init.signal.reason)));+ assert.equal(await serverAnswers(office.origin, slow, 20), false, "no answer within the look");+});++test("the window goes to a server that answers without asking anything", async () => {+ const { shown, dialog } = asked([]);+ assert.equal(await serverOpens(office, { fetch: answering(200), dialog, forget: () => assert.fail("nothing to forget") }), true);+ assert.deepEqual(shown, []);+});++test("one that doesn't answer is the person's choice: Cancel stays put, Remove forgets it, Try again looks once more", async () => {+ const cancel = asked([2]);+ assert.equal(await serverOpens(office, { fetch: gone, dialog: cancel.dialog, forget: () => assert.fail("not asked to") }), false);+ assert.equal(cancel.shown[0].message, "pro cloud isn't answering");+ assert.match(cancel.shown[0].detail, /omb-u-gone\.fly\.dev/);+ assert.deepEqual(cancel.shown[0].buttons, ["Try again", "Remove from list", "Cancel"]);++ const forgotten = [];+ const remove = asked([1]);+ assert.equal(await serverOpens(office, { fetch: gone, dialog: remove.dialog, forget: (id) => forgotten.push(id) }), false);+ assert.deepEqual(forgotten, ["vps"]);++ let tries = 0;+ const back = async () => (++tries < 2 ? gone() : new Response("{}", { status: 200 }));+ const retry = asked([0]);+ assert.equal(await serverOpens(office, { fetch: back, dialog: retry.dialog, forget: () => assert.fail("not asked to") }), true, "it answered the second time");+ assert.equal(retry.shown.length, 1);+});diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsxindex 36e3e52831..483a97de99 100644--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@ -148,7 +148,7 @@ function RemoveRow({ place, onRemoved }: { place: RailPlace; onRemoved: () => voreturn <div data-rail-remove className="flex flex-col gap-1.5 border-t border-hairline/50 px-0.5 pt-1.5">{asking? <div role="alertdialog" aria-label={t("rail.remove")} className="flex flex-col gap-2 px-1.5 pb-1">- <p className="text-[12px] leading-snug text-ink">{t("rail.removeAsk", { name: place.name })}</p>+ <p className="text-[12px] leading-snug text-ink">{t(place.forget ? "rail.removeServerAsk" : "rail.removeAsk", { name: place.name })}</p><div className="flex gap-2"><button type="button" data-rail-remove-confirm className="ui-button ui-button-primary" disabled={busy} onClick={confirm}>{t("rail.removeYes")}</button><button type="button" className="ui-button" disabled={busy} onClick={() => setAsking(false)}>{t("rail.removeNo")}</button>diff --git a/src/locales/en.json b/src/locales/en.jsonindex 2a1462a5f3..ea55e72505 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -553,6 +553,7 @@"twoPlaces.bring": "Bring them together","twoPlaces.failed": "Your bots didn't start moving. Try again in a moment.","rail.removeAsk": "Remove “{name}” from your list? You can buy a new Cloud any time.",+ "rail.removeServerAsk": "Remove “{name}” from your list? This app signs out of it; nothing on that server changes.","rail.removeYes": "Remove","rail.removeNo": "Cancel","rail.removeRefused": "It can't be removed right now: it is running again, or still has a plan.",