Skip to content

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

fix(desktop): the app's own window no longer gets stuck on its pairing screen

aivsomkar0fc5d3173bed
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 083108e718..f85b95c2f2 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -898,8 +898,9 @@ export function createHomeWindow(deps) {
}
/** The window's IPC: this computer's screen reads why the place isn't open and asks again; the place's own page, while
- * it is shown, asks for a new session; either asks this device's sign-in again (from the person's click on My Cloud). */
-export function installHomeWindowIpc({ ipcMain, homeWindow, cloudPage }) {
+ * it is shown, asks for a new session; either asks this device's sign-in again (from the person's click on My Cloud).
+ * `repairLocal`: this computer's own page, read as signed out, asks the app to sign it in again (local-sign-in-repair.mjs). */
+export function installHomeWindowIpc({ ipcMain, homeWindow, cloudPage, repairLocal = null }) {
const from = (channel, allowed, handler) => (event, ...args) => {
if (!allowed(event)) throw new Error(`${channel} is only available in this app's window`);
return handler(...args);
@@ -909,7 +910,11 @@ export function installHomeWindowIpc({ ipcMain, homeWindow, cloudPage }) {
ipcMain.handle("home:retry", from("home:retry", screenPage, (pressed) => homeWindow.retry({ pressed: pressed === true }).then(() => homeWindow.view())));
ipcMain.handle("home:remove", from("home:remove", screenPage, () => homeWindow.remove()));
ipcMain.handle("home:sign-in", from("home:sign-in", (event) => screenPage(event) || cloudPage(event) === "cloud" || (homeWindow.homePage(event) && homeWindow.shown()?.kind === "own"), () => homeWindow.signIn()));
- ipcMain.handle("home:repair", from("home:repair", (event) => homeWindow.homePage(event), () => homeWindow.repair()));
+ ipcMain.handle("home:repair", (event) => {
+ if (homeWindow.homePage(event)) return homeWindow.repair();
+ if (repairLocal && screenPage(event)) return repairLocal();
+ throw new Error("home:repair is only available in this app's window");
+ });
ipcMain.handle("home:operation", from("home:operation", (event) => homeWindow.homePage(event), () => homeWindow.operation()));
ipcMain.on("home:page", (event) => { try { event.returnValue = homeWindow.homePage(event); } catch { event.returnValue = false; } });
ipcMain.on("home:updating", (event) => { try { event.returnValue = homeWindow.updating(event); } catch { event.returnValue = false; } });
diff --git a/electron/local-sign-in-repair.mjs b/electron/local-sign-in-repair.mjs
new file mode 100644
index 0000000000..c1801e01a4
--- /dev/null
+++ b/electron/local-sign-in-repair.mjs
@@ -0,0 +1,25 @@
+// The app's own window signs in to the app's own server with the owner header (server-session.mjs), never a session.
+// When that window still reads "signed out", either it loaded before the server held the header's token, or it carries a
+// session cookie the server has ended (a code once typed into it, since expired or revoked), and the server reads a
+// presented cookie before the header, refusing it on every launch. The server's rule stays; the app drops its own ended
+// cookie for its own server and loads the page again.
+
+/** At most one repair a minute, so a page that still can't sign in shows the pairing page instead of reloading forever. */
+export const LOCAL_REPAIR_EVERY_MS = 60_000;
+
+/** `cookies`: the window's session cookies (read when asked: Electron's session exists only once the app is ready).
+ * `now` is a monotonic clock (performance.now): the wall clock can step back and hold the page in a loop. */
+export function createLocalSignInRepair({ ready, origin, port, cookies, window, log = () => {}, now = () => performance.now() }) {
+ let lastAt = null;
+ return async function repairLocalSignIn() {
+ if (!ready()) throw new Error("this computer's server is not ready");
+ if (lastAt !== null && now() - lastAt < LOCAL_REPAIR_EVERY_MS) throw new Error("already tried signing this window in again");
+ lastAt = now();
+ const url = origin(), prefix = `omb_session_${port()}_`, jar = cookies(); // request-auth.ts sessionCookieName
+ const ended = (await jar.get({ url })).filter(({ name }) => name.startsWith(prefix));
+ for (const { name } of ended) await jar.remove(url, name);
+ log(`own window read signed out: ${ended.length} session cookie(s) dropped, loading it again`);
+ const win = window();
+ if (win && !win.isDestroyed()) win.webContents.reload();
+ };
+}
diff --git a/electron/local-sign-in-repair.node-test.mjs b/electron/local-sign-in-repair.node-test.mjs
new file mode 100644
index 0000000000..490807d948
--- /dev/null
+++ b/electron/local-sign-in-repair.node-test.mjs
@@ -0,0 +1,97 @@
+// The app's own window on its own server, read as signed out (local-sign-in-repair.mjs): its ended session cookie goes and
+// the page loads again, at most once a minute, and only while the server is the app's and ready.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { installHomeWindowIpc } from "./home-window.mjs";
+import { createLocalSignInRepair, LOCAL_REPAIR_EVERY_MS } from "./local-sign-in-repair.mjs";
+import { CLOUD, LOCAL, world as homeWorld } from "./fixtures/home-window-world.mjs";
+
+const ORIGIN = "http://127.0.0.1:8799";
+
+function world({ ready = true, jar = ["omb_session_8799_3f2aabcdef01", "omb_session_8800_3f2aabcdef01", "theme"], open = true } = {}) {
+ const w = { ready, clock: 1_000, jar: [...jar], removed: [], reloads: 0, open };
+ const win = { isDestroyed: () => !w.open, webContents: { reload: () => { w.reloads++; } } };
+ w.repair = createLocalSignInRepair({
+ ready: () => w.ready,
+ origin: () => ORIGIN,
+ port: () => 8799,
+ cookies: () => ({
+ get: async ({ url }) => { assert.equal(url, ORIGIN); return w.jar.map((name) => ({ name })); },
+ remove: async (url, name) => { assert.equal(url, ORIGIN); w.removed.push(name); w.jar = w.jar.filter((other) => other !== name); },
+ }),
+ window: () => win,
+ now: () => w.clock,
+ });
+ return w;
+}
+
+test("drops this server's ended session cookie, keeps another port's and other cookies, and loads the page again", async () => {
+ const w = world();
+ await w.repair();
+ assert.deepEqual(w.removed, ["omb_session_8799_3f2aabcdef01"]);
+ assert.deepEqual(w.jar, ["omb_session_8800_3f2aabcdef01", "theme"]);
+ assert.equal(w.reloads, 1);
+});
+
+test("with no cookie (the page loaded before the server had the window's token), it only loads the page again", async () => {
+ const w = world({ jar: [] });
+ await w.repair();
+ assert.deepEqual(w.removed, []);
+ assert.equal(w.reloads, 1);
+});
+
+test("never loops: a second ask within the minute is refused, so the pairing page shows", async () => {
+ const w = world();
+ await w.repair();
+ w.clock += LOCAL_REPAIR_EVERY_MS - 1;
+ await assert.rejects(w.repair(), /already tried/);
+ assert.equal(w.reloads, 1);
+ w.clock += 1;
+ await w.repair();
+ assert.equal(w.reloads, 2);
+});
+
+test("refused, touching nothing, while the server is not the app's own or not ready", async () => {
+ const w = world({ ready: false });
+ await assert.rejects(w.repair(), /not ready/);
+ assert.deepEqual(w.removed, []);
+ assert.equal(w.reloads, 0);
+ w.ready = true;
+ await w.repair();
+ assert.equal(w.reloads, 1, "a refusal does not use up the minute");
+});
+
+test("a closed window is not reloaded", async () => {
+ const w = world({ open: false });
+ await w.repair();
+ assert.equal(w.reloads, 0);
+});
+
+test("the window's IPC: this computer's own page, read as signed out, asks the app to sign it in again", async () => {
+ const w = homeWorld();
+ await w.home.show();
+ const handlers = new Map(), repaired = [];
+ const install = (repairLocal) => installHomeWindowIpc({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler), on: () => {} },
+ homeWindow: w.home, cloudPage: () => null, repairLocal });
+ install(async () => { repaired.push("local"); });
+ const frame = w.contents.mainFrame, page = { sender: w.contents, senderFrame: frame };
+ w.url = `${LOCAL}/`;
+ await handlers.get("home:repair")(page);
+ assert.deepEqual(repaired, ["local"]);
+ assert.throws(() => handlers.get("home:repair")({ sender: {}, senderFrame: frame }), /only available/, "another window");
+ w.url = "https://other.example.test/";
+ assert.throws(() => handlers.get("home:repair")(page), /only available/, "a page from elsewhere");
+ w.url = `${CLOUD}/`;
+ await handlers.get("home:repair")(page);
+ assert.deepEqual(repaired, ["local"], "My Cloud's page still renews its own session");
+ install(undefined);
+ w.url = `${LOCAL}/`;
+ assert.throws(() => handlers.get("home:repair")(page), /only available/, "without a local repair, as before");
+});
+
+test("main.mjs hands the window's IPC this repair, only for the app's own packaged server once it is ready", () => {
+ const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");
+ assert.match(main, /installHomeWindowIpc\(\{[^\n]*?repairLocal: createLocalSignInRepair\(\{ ready: \(\) => app\.isPackaged && !desktopRemoteAccess && serverReady, origin: rendererOrigin, port: \(\) => SERVER_PORT, cookies: \(\) => session\.defaultSession\.cookies, window: \(\) => mainWindow,/);
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index ff8a405191..fe61038e20 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -108,7 +108,7 @@ import { createCloudEntry } from "./cloud-entry.mjs"; import { installTeamJoin }
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 { 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, HOME_SCREEN_PATH } from "./home-window.mjs";
+import { createHomeWindow, installHomeWindowIpc, HOME_SCREEN_PATH } from "./home-window.mjs"; import { createLocalSignInRepair } from "./local-sign-in-repair.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE, START_QUIET_MS, togetherComputer, togetherPrefFile } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs"; import { createPlaceChatMain } from "./place-chat-main.mjs"; import { createTogetherBackground } from "./together-background.mjs";
import { createWindowStateFile } from "./window-state-file.mjs"; import { createSystemProxyCache } from "./system-proxy.mjs"; import { createBootHeadStart } from "./boot-head-start.mjs";
@@ -2583,7 +2583,7 @@ const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.jo
go: (url, origin, place) => { if (place?.kind === "team" || place?.kind === "own") { activatePlace(place); if (place.kind === "team") { teamProfileSeeds.opened(place.origin); teamLinks.opened(place.id); } } 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()); } });
-installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking });
+installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking, repairLocal: createLocalSignInRepair({ ready: () => app.isPackaged && !desktopRemoteAccess && serverReady, origin: rendererOrigin, port: () => SERVER_PORT, cookies: () => session.defaultSession.cookies, window: () => mainWindow, log: slog }) });
/** Every path that shows the window: My Cloud once it is the person's home, else as before. */
function showHome(options) {
return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));
diff --git a/src/locales/en.json b/src/locales/en.json
index 044c99d0d8..8a0cb550a0 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -9802,6 +9802,8 @@
"pair.onPhone": "On your phone?",
"pair.openInApp": "Open in the {app} app",
"pair.noCode": "No code? On the server, run",
+ "pair.noCode.app": "No code? Open {app} on that computer and make one in Settings → Devices.",
+ "pair.noCode.reopen": "Still asking for a code? Quit {app} and open it again.",
"pair.invitedByEmail": "Invited by email?",
"pair.notEncrypted": "This connection isn't encrypted.",
"pairing.worksOnceUntil": "Works once, until {time}",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 29d6d06e27..47d4339f33 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11098,6 +11098,8 @@
"pair.onPhone": "No celular?",
"pair.openInApp": "Abrir no app {app}",
"pair.noCode": "Sem código? No servidor, rode",
+ "pair.noCode.app": "Sem código? Abra o {app} nesse computador e crie um em Configurações → Dispositivos.",
+ "pair.noCode.reopen": "Ainda pedindo um código? Feche o {app} e abra de novo.",
"pair.invitedByEmail": "Convidado por e-mail?",
"pair.notEncrypted": "Esta conexão não é criptografada.",
"pairing.worksOnceUntil": "Funciona uma vez, até {time}",
diff --git a/src/pair/PairPage.test.ts b/src/pair/PairPage.test.ts
index c04f8de0d4..8104cb8cc6 100644
--- a/src/pair/PairPage.test.ts
+++ b/src/pair/PairPage.test.ts
@@ -6,7 +6,7 @@ const f = vi.hoisted(() => ({ effects: [] as EffectCallback[], pair: vi.fn() }))
vi.mock("react", async original => ({ ...await original<typeof import("react")>(), useEffect: (effect: EffectCallback) => { f.effects.push(effect); } }));
vi.mock("../lib/session", async original => ({ ...await original<typeof import("../lib/session")>(), pairWithCode: f.pair, readSessionState: vi.fn().mockResolvedValue({ kind: "unauthenticated", error: "" }) }));
vi.mock("../components/DesktopWorkspaceSwitcher", () => ({ DesktopWorkspaceSwitcher: () => null }));
-import { codeProblem, codeReady, openInAppLink, PairPage, pairIntro, pairsAutomatically, pairTitle, phoneBrowser, TeamLeftPage, teamPage, unencryptedPublic } from "./PairPage";
+import { codeProblem, codeReady, noCodeHint, openInAppLink, PairPage, pairIntro, pairsAutomatically, pairTitle, phoneBrowser, TeamLeftPage, teamPage, unencryptedPublic } from "./PairPage";
import en from "../locales/en.json";
import type { EnvironmentDescriptor } from "../lib/session";
@@ -72,6 +72,21 @@ it("a team's Cloud is called by the team's name, a person's own Cloud My Cloud",
expect(pairTitle(null, "code")).toBe("Connect to this MausBot");
});
+it("without a code: the command where it works, the app's Settings where the app runs the server, never a command it refuses", () => {
+ const descriptor = (selfUpdate: "operator" | "desktop-managed", capabilities: Record<string, unknown> = {}) =>
+ ({ environmentId: "e", label: "MacBook", platform: "darwin", version: "1", capabilities: { remoteSessions: true as const, selfUpdate, ...capabilities } }) as EnvironmentDescriptor;
+ expect(noCodeHint(null, false), "before the server describes itself, as before").toBe("command");
+ expect(noCodeHint(descriptor("operator"), false)).toBe("command");
+ // `openmausbot pair` is refused on a server the desktop app runs (cli-pairing.ts desktopOwnedRefusal).
+ expect(noCodeHint(descriptor("desktop-managed"), false)).toBe("app");
+ expect(noCodeHint(descriptor("desktop-managed"), true), "the app's own window: its Settings is the page that won't open").toBe("reopen");
+ expect(noCodeHint(descriptor("operator", { cloudHome: true }), false)).toBeNull();
+ expect(noCodeHint(descriptor("operator", { cloudHome: true, cloudTeam: true }), false)).toBeNull();
+ expect(en["pair.noCode.app"]).toContain("Settings → Devices");
+ expect(en["pair.noCode.app"]).not.toContain("openmausbot pair");
+ expect(en["pair.noCode.reopen"]).toContain("{app}");
+});
+
it("names a wrong kind of code instead of letting it be sent as a wrong one", () => {
expect(codeProblem("1234 5678")).toBe(en["serverError.pair.emailCode"]);
expect(codeProblem("123456")).toBe(en["serverError.pair.oldCodeDevices"]);
diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsx
index c570dc6fc4..ded5d9e968 100644
--- a/src/pair/PairPage.tsx
+++ b/src/pair/PairPage.tsx
@@ -54,6 +54,15 @@ export function openInAppLink(origin: string, code: string): string {
return `openmausbot://pair?address=${encodeURIComponent(origin)}${filled}`;
}
+/** What to do without a code: the command on a server the CLI runs; on one the desktop app runs, which refuses that command
+ * (cli-pairing.ts desktopOwnedRefusal), a code from the app's Settings, or in the app's own window, whose Settings is the
+ * page that won't open, quitting and reopening the app. Nothing on a Cloud, whose intro says where its codes come from. */
+export function noCodeHint(environment: EnvironmentDescriptor | null, ownPage = typeof window !== "undefined" && window.ogb?.app?.ownPage === true): "command" | "app" | "reopen" | null {
+ if (environment?.capabilities.cloudHome === true || environment?.capabilities.cloudTeam === true) return null;
+ if (environment?.capabilities.selfUpdate !== "desktop-managed") return "command";
+ return ownPage ? "reopen" : "app";
+}
+
/** The link opens the phone app, so only a phone or tablet is offered it. A tablet asking for desktop sites says
* Macintosh (iPad) or Linux (Android) and is told apart by its touch screen. */
export function phoneBrowser(userAgent = typeof navigator === "undefined" ? "" : navigator.userAgent, touchPoints = typeof navigator === "undefined" ? 0 : navigator.maxTouchPoints ?? 0): boolean {
@@ -131,7 +140,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
const connected = isConnected(session);
const emailOffered = environment?.capabilities.emailSignIn === true;
const cloudHome = environment?.capabilities.cloudHome === true;
- const ownServer = !cloudHome && environment?.capabilities.cloudTeam !== true;
+ const hint = noCodeHint(environment);
const problem = codeProblem(code);
const where = typeof location !== "undefined" && typeof location.protocol === "string" ? location : null;
@@ -284,10 +293,12 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
<a href={openInAppLink(where.origin, code)} className="text-accent underline">{t("pair.openInApp", { app: productName() })}</a>
</p>
) : null}
- {ownServer ? (
+ {hint === "command" ? (
<p className="mt-3 text-[13px] text-ink-secondary">
{t("pair.noCode")} <code className="select-all rounded bg-inset px-1.5 py-0.5 text-[12px] text-ink">npx openmausbot pair</code>
</p>
+ ) : hint ? (
+ <p className="mt-3 text-[13px] text-ink-secondary">{t(hint === "app" ? "pair.noCode.app" : "pair.noCode.reopen", { app: productName() })}</p>
) : null}
{emailOffered ? (
<p className="mt-5 border-t border-hairline/40 pt-4 text-[13px] text-ink-secondary">