Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(desktop): a saved server that needs pairing no longer takes over the app at launch
milind-soni267b6ec24ecc
diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex 70b9cb6bae..2b7e484194 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -201,6 +201,12 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, besif (!place) throw new Error(t("native.places.noLongerHere"));return ask(place.id, stale => (place.account ? switchingTo(place, stale) : opening(place, stale)));});+ // Back to this computer, from a saved server's sign-in page in this window (`guard`: the window's own page, whichever+ // place it shows): one fixed place the page can't name, This computer as the rail lists it, else the Server menu's.+ ipcMain.handle("workspaces:this-computer", guard(() => {+ const computer = places().find(entry => entry.kind === "computer" && entry.opens && !entry.account && !entry.named) ?? null;+ return ask(computer?.id ?? environments.LOCAL_ID, stale => (computer ? opening(computer, stale) : open(environments.LOCAL_ID, 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.listed("workspaces:remove", async (_event, id) => {diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex a3afa2d511..b4069becbd 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -365,7 +365,7 @@ function preload(origin, { activation = false } = {}) {test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {const page = preload(HOME);- assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "probe", "look", "color", "recolor", "remove", "rename", "makeHome", "homeOffers", "together", "onChanged", "local", "onNewLocal"]);+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "probe", "thisComputer", "look", "color", "recolor", "remove", "rename", "makeHome", "homeOffers", "together", "onChanged", "local", "onNewLocal"]);assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);await page.bridge.workspaces.places();await page.bridge.cloudAdd.state();@@ -382,6 +382,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await assert.rejects(page.bridge.workspaces.remove("old"), /Choose Remove from list/, "Remove from list only from the person's click");await assert.rejects(page.bridge.workspaces.rename("vps", "Office"), /Choose Rename/, "Rename only from the person's click");await assert.rejects(page.bridge.workspaces.makeHome("vps"), /Choose Make my home/, "a move starts only from the person's click");+ await assert.rejects(page.bridge.workspaces.thisComputer(), /Choose This computer/, "back to This computer only from the person's click");await assert.rejects(page.bridge.workspaces.local.create("Work", "rose"), /Choose a name/, "a workspace of this computer's own only from the person's click");await assert.rejects(page.bridge.workspaces.local.edit("profile:work", { name: "Office" }), /Choose a change/);await assert.rejects(page.bridge.workspaces.local.remove("profile:work"), /Choose Remove/);@@ -394,8 +395,9 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await clicked.bridge.workspaces.color("rose");await clicked.bridge.workspaces.color(null);await clicked.bridge.cloudAdd.organization({ toString: () => "Client C" }, null);+ await clicked.bridge.workspaces.thisComputer("vps");assert.deepEqual(clicked.invoked, [["workspaces:open", "a"], ["workspaces:add", "link"], ["cloud-add:start", "pro", "Client B", null], ["workspaces:color", "rose"], ["workspaces:color", null],- ["cloud-add:organization", "Client C", null]]);+ ["cloud-add:organization", "Client C", null], ["workspaces:this-computer"]], "no place travels with it");await clicked.bridge.cloudAdd.start("team", "Studio", "blue", { toString: () => "app_whats_new_team" });assert.deepEqual(clicked.invoked.at(-1), ["cloud-add:start", "team", "Studio", "blue", "app_whats_new_team"], "a source travels as plain text");assert.equal(page.bridge.cloudAccount, undefined, "never the account bridge");@@ -535,3 +537,19 @@ test("Show bots together: in the menu of This computer and My Cloud while this c[["profile:default", false], ["home", false]], "My Cloud as home: This Mac, which runs, and My Cloud; never Client A, a team's Cloud or a server");assert.deepEqual(marked(railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }], together: null })), [], "not offered (the frozen copy runs): no row");});++test("Back to This computer, from a saved server's sign-in page: always this computer, never a place the page names", async () => {+ const asked = [];+ const ask = (id, run) => { asked.push(id); return run(() => false); };+ const before = rail({ ask, places: () => railPlaces({ saved: saved("vps"), home: null, mine: HOME, state: session() }) });+ before.w.trusted = false; before.w.lists = false;+ await before.handlers.get("workspaces:this-computer")({ sender: {} }, "vps");+ assert.deepEqual([asked, before.opened], [["local"], ["local"]], "the Server menu's This computer, on a page main doesn't list for");+ const profiles = [];+ const home = rail({ ask, openProfile: id => { profiles.push(id); }, places: () => railPlaces({ saved: saved("vps"), home: HOME, mine: HOME, state: session(), profiles: [{ id: "work", name: "Work" }, { id: "default" }] }) });+ await home.call("workspaces:this-computer");+ assert.deepEqual(profiles, ["default"], "once My Cloud is home, This Mac's own workspace, not a named one");+ const none = rail({ ask, places: () => [] });+ await none.call("workspaces:this-computer");+ assert.deepEqual(none.opened, ["local"], "no rail: still This computer");+});diff --git a/electron/main.mjs b/electron/main.mjsindex ff8a405191..19ad30fe04 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -106,7 +106,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClouimport { installCloudFiles } from "./cloud-sync-main.mjs";import { createCloudEntry } from "./cloud-entry.mjs"; import { installTeamJoin } from "./team-join-main.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 { 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 { 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, reopenSavedServerAtLaunch, 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 { createTeamProfileSeeds } from "./team-profile-seed.mjs";@@ -1788,8 +1788,8 @@ async function addServerFromClipboard() {}}-const serverConnect = createServerConnect({ fetch: (...args) => session.defaultSession.fetch(...args), t: nativeT, tailnet: () => onTailnet(os.networkInterfaces()),- ownEnvironmentId: async () => (await (await localServerRequest("/.well-known/openmausbot/environment")).json())?.environmentId ?? null,+const ownEnvironmentId = async () => (await (await localServerRequest("/.well-known/openmausbot/environment")).json())?.environmentId ?? null; const serverConnect = createServerConnect({ fetch: (...args) => session.defaultSession.fetch(...args), t: nativeT, tailnet: () => onTailnet(os.networkInterfaces()),+ ownEnvironmentId,ask: async (found) => (await dialog.showMessageBox({ type: "question", buttons: [nativeT("native.dialog.connect.button"), nativeT("native.common.cancel")], defaultId: 0, cancelId: 1,message: nativeT("native.dialog.connect.title", { host: found.label }), detail: nativeT(found.code || found.credential ? "native.dialog.connect.withCode" : "native.dialog.connect.noCode") })).response === 0,open: (found, name) => {@@ -2588,7 +2588,7 @@ installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking });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 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 ? reopenSavedServerAtLaunch(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), ownEnvironmentId, declined: () => { if (environmentsState.activeId === entry.id) persistEnvironments(withActive(environmentsState, LOCAL_ID)); }, 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 togetherCommands = () => { try { void sharingController().lendTerminal(true)?.catch?.(error => slog(`together: commands not lent (${error?.message ?? error})`)); } catch (error) { slog(`together: commands not lent (${error?.message ?? error})`); } }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, rail: event => chromeRail.owns(event), together: createPlacesTogether({ turnedOn: togetherCommands, inPlace: createPlaceChatMain({ cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), grant: () => ensureCloudAccount().pairHome(), wake: () => cloudAccount?.wakeHome(), server: () => serverProc, fetch: (...args) => session.defaultSession.fetch(...args), log: slog }), commands: { on: () => sharingController().terminalOn(), set: on => (on ? lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)) : sharingController().lendTerminal(false)) }, pref: togetherPrefFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: cloudAwakeNow, computer: () => togetherComputer({ cloudHome: Boolean(homeWindow.cloudOrigin()), ownHome: Boolean(ownHome?.origin()), frozen: cleanWorkspace.marker().frozen, profile: cleanWorkspace.profile(), running: runningDataDir }), 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"); try { togetherBackground.changed(); } catch {} const offered = JSON.stringify(placesTogether?.offered() ?? null); if (offered !== togetherOnRail) { togetherOnRail = offered; railChanged(); } } }) }); let togetherOnRail = "null"; const togetherBackground = createTogetherBackground({ cloudHome: () => Boolean(homeWindow.cloudOrigin()), togetherOn: () => placesTogether.switchOn(), shown: placeShown, ownCopyRuns: () => cleanWorkspace.ownCopy(), running: () => cleanWorkspace.profile(), dataDir: desktopDataDir, open: id => cleanWorkspace.open(id, { background: true }), leave: () => cleanWorkspace.leave({ background: true }), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string"; }, linkOff: async () => { await botLink?.look(); await botLink?.look(); }, log: slog });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, together: placesTogether.offered() && { on: placesTogether.offered().on, profile: cleanWorkspace.profile() } }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.diff --git a/electron/preload.cjs b/electron/preload.cjsindex 13e00d07bf..a49eb51a78 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -177,6 +177,9 @@ const bridge = {add: (choice, link, code) => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("workspaces:add", String(choice), ...(typeof link === "string" ? [link, ...(typeof code === "string" ? [code] : [])] : [])) : Promise.reject(new Error("Choose what to add.")),probe: (address, code) => ipcRenderer.invoke("workspaces:probe", String(address ?? ""), String(code ?? "")),+ // Back to This computer, from a saved server's sign-in page: one fixed place, only from the person's click.+ thisComputer: () => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("workspaces:this-computer") : Promise.reject(new Error("Choose This computer.")),// The colour of the place this page is (never another's): read, and changed only from the person's click.look: () => ipcRenderer.invoke("workspaces:look"),color: (swatch) => isLocalPage || navigator.userActivation?.isActive === truediff --git a/electron/saved-server.d.mts b/electron/saved-server.d.mtsindex a20a2552c1..44660de3f3 100644--- a/electron/saved-server.d.mts+++ b/electron/saved-server.d.mts@@ -1,5 +1,13 @@export declare const SERVER_LOOK_MS: number;export declare function serverAnswers(origin: string, fetchImpl: typeof fetch, timeoutMs?: number): Promise<boolean>;+export declare function savedServerLook(+ origin: string,+ deps: { fetch: typeof fetch; ownEnvironmentId(): Promise<string | null>; timeoutMs?: number },+): Promise<"in" | "own" | "sign-in" | "gone">;+export declare function reopenSavedServerAtLaunch(+ entry: { id: string; origin: string },+ deps: { saved(): Array<{ id: string }>; fetch: typeof fetch; ownEnvironmentId(): Promise<string | null>; opened(entry: object): unknown; declined?(): unknown; timeoutMs?: number },+): Promise<boolean | "own" | "sign-in">;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; t?: (key: string, params?: Record<string, string | number>) => string },diff --git a/electron/saved-server.mjs b/electron/saved-server.mjsindex 1ed2b05652..b017b973c2 100644--- a/electron/saved-server.mjs+++ b/electron/saved-server.mjs@@ -37,6 +37,48 @@ export async function serverOpens(entry, { fetch: fetchImpl, dialog, forget, tim}}+/**+ * What a server saved by hand is to this app at launch, before the window goes there unasked: "in" when this app has a+ * session there (its page opens signed in), "own" when it is this computer's own server under another address,+ * "sign-in" when it answers but its page would ask this window to pair, "gone" when nothing answers. Only a session+ * counts as in: this process isn't a browser, so a server on this machine lets it in where the window's page would not.+ * @param {string} origin+ * @param {{ fetch: typeof fetch, ownEnvironmentId(): Promise<string | null>, timeoutMs?: number }} deps+ * @returns {Promise<"in" | "own" | "sign-in" | "gone">}+ */+export async function savedServerLook(origin, { fetch: fetchImpl, ownEnvironmentId, timeoutMs = SERVER_LOOK_MS }) {+ const read = async (route, credentials) => {+ try {+ const response = await fetchImpl(`${origin}${route}`, {+ cache: "no-store", redirect: "manual", credentials, signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json" },+ });+ return { status: response.status, body: await response.json().catch(() => null) };+ } catch {+ return null;+ }+ };+ const [described, session] = await Promise.all([read("/.well-known/openmausbot/environment", "omit"), read("/api/auth/session", "include")]);+ if (!described || described.status >= 500) return "gone";+ const own = await ownEnvironmentId().catch(() => null);+ if (typeof own === "string" && own && [described.body?.environmentId, session?.body?.environmentId].includes(own)) return "own";+ return session?.status === 200 && session.body?.kind === "session" ? "in" : "sign-in";+}++/**+ * The launch's way back to the server saved by hand that was on screen when the app closed: the window goes there only+ * when this app is signed in there (savedServerLook). True when it went; false when the server isn't saved any more or+ * doesn't answer; "own" or "sign-in" when it answers but isn't a place to open unasked (`declined()` is told first).+ * @param {{ id: string, origin: string }} entry+ * @param {{ saved(): Array<{ id: string }>, fetch: typeof fetch, ownEnvironmentId(): Promise<string | null>, opened(entry: object): unknown, declined?(): unknown, timeoutMs?: number }} deps+ * @returns {Promise<boolean | "own" | "sign-in">}+ */+export async function reopenSavedServerAtLaunch(entry, { saved, fetch: fetchImpl, ownEnvironmentId, opened, declined = () => {}, timeoutMs }) {+ const look = await savedServerLook(entry.origin, { fetch: fetchImpl, ownEnvironmentId, timeoutMs });+ if (look === "gone" || !saved().some((candidate) => candidate.id === entry.id)) return false;+ if (look !== "in") { await declined(); return look; }+ return Boolean(await opened(entry));+}+/*** The window's way back to a server this computer's bots moved to: opens it again as the Server menu does, without that* menu's dialog, because this is the app putting itself right and the screen it lands on has Try again. False when thediff --git a/electron/saved-server.node-test.mjs b/electron/saved-server.node-test.mjsindex 3502ede56a..9b967e411b 100644--- a/electron/saved-server.node-test.mjs+++ b/electron/saved-server.node-test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { reopenSavedServer, serverAnswers, serverOpens } from "./saved-server.mjs";+import { reopenSavedServer, reopenSavedServerAtLaunch, savedServerLook, 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 });@@ -60,3 +60,48 @@ test("the way back opens a saved server that answers, and gives up on one that lassert.equal(await reopenSavedServer({ origin: office.origin }, { saved: left, fetch: answering(200), opened: (found) => { opened = found; return true; } }), false, "forgotten while it was asked");assert.equal(opened, null, "never opened the environment that is now active");});++/** A server at `office.origin`: its descriptor's id, and what its session check says to this app's request. */+function server({ id = "env-office", session = { status: 401, body: { error: "unauthorized: this browser is not signed in" } }, down = false } = {}) {+ const asked = [];+ const fetch = async (url, init) => {+ asked.push([new URL(url).pathname, init.credentials]);+ if (down) throw new TypeError("fetch failed");+ if (url.endsWith("/.well-known/openmausbot/environment")) return Response.json({ environmentId: id, label: "DESKTOP-1" });+ return Response.json(session.body, { status: session.status });+ };+ return { asked, fetch };+}+const own = (id) => async () => id;++test("at launch a saved server is in only with this app's session there; this computer's own and a pairing page are not", async () => {+ const signedIn = server({ session: { status: 200, body: { kind: "session", id: "s-1", environmentId: "env-office" } } });+ assert.equal(await savedServerLook(office.origin, { fetch: signedIn.fetch, ownEnvironmentId: own("env-mine") }), "in");+ assert.deepEqual(signedIn.asked.sort(), [["/.well-known/openmausbot/environment", "omit"], ["/api/auth/session", "include"]], "the session check carries this app's cookie");+ assert.equal(await savedServerLook(office.origin, { fetch: server().fetch, ownEnvironmentId: own("env-mine") }), "sign-in", "the sign-in gate");+ assert.equal(await savedServerLook(office.origin, { fetch: server({ session: { status: 403, body: { error: "forbidden: loopback host required" } } }).fetch, ownEnvironmentId: own("env-mine") }), "sign-in");+ const loopback = server({ session: { status: 200, body: { kind: "loopback", environmentId: "env-other" } } });+ assert.equal(await savedServerLook(office.origin, { fetch: loopback.fetch, ownEnvironmentId: own("env-mine") }), "sign-in",+ "another server on this machine lets this process in as loopback, but the window's page would still have to pair");+ assert.equal(await savedServerLook(office.origin, { fetch: server({ id: "env-mine" }).fetch, ownEnvironmentId: own("env-mine") }), "own", "this computer's own, by its descriptor");+ const mineSignedIn = server({ id: "env-mine", session: { status: 200, body: { kind: "session", id: "s-2", environmentId: "env-mine" } } });+ assert.equal(await savedServerLook(office.origin, { fetch: mineSignedIn.fetch, ownEnvironmentId: own("env-mine") }), "own", "even with a session there, it is never a place of its own");+ assert.equal(await savedServerLook(office.origin, { fetch: server({ id: "env-mine" }).fetch, ownEnvironmentId: async () => { throw new Error("not ready"); } }), "sign-in",+ "this computer's server not ready: not known as its own, still not opened unasked");+ assert.equal(await savedServerLook(office.origin, { fetch: server({ down: true }).fetch, ownEnvironmentId: own("env-mine") }), "gone");+ assert.equal(await savedServerLook(office.origin, { fetch: answering(503), ownEnvironmentId: own("env-mine") }), "gone");+});++test("the launch opens a saved server only where it is in; otherwise it says why, after main puts the window back on This computer", async () => {+ const saved = () => [office];+ const run = async (fetch, list = saved) => {+ const said = [];+ const result = await reopenSavedServerAtLaunch(office, { saved: list, fetch, ownEnvironmentId: own("env-mine"), opened: async (entry) => { said.push(`opened:${entry.id}`); return true; }, declined: () => said.push("declined") });+ return { result, said };+ };+ assert.deepEqual(await run(server({ session: { status: 200, body: { kind: "session", id: "s-1" } } }).fetch), { result: true, said: ["opened:vps"] });+ assert.deepEqual(await run(server().fetch), { result: "sign-in", said: ["declined"] });+ assert.deepEqual(await run(server({ id: "env-mine" }).fetch), { result: "own", said: ["declined"] });+ assert.deepEqual(await run(server({ down: true }).fetch), { result: false, said: [] }, "nothing answers: the old fallback");+ assert.deepEqual(await run(server().fetch, () => []), { result: false, said: [] }, "forgotten meanwhile");+});diff --git a/electron/start-place.mjs b/electron/start-place.mjsindex 242f8bd3eb..9a5608ad4a 100644--- a/electron/start-place.mjs+++ b/electron/start-place.mjs@@ -1,6 +1,8 @@// The place a launch opens: the one on screen when the app last closed. One that can't open now falls back without a// dialog: to My Cloud, and when My Cloud doesn't run either, to This Mac. A workspace of this computer's own opens only-// through `profiles`, so one runs at a time and the frozen copy is never one of them.+// through `profiles`, so one runs at a time and the frozen copy is never one of them. A server saved by hand opens only+// where this app is signed in: one whose page would ask the window to pair, or this computer's own server under another+// address, is never what the app opens to unasked.import { DEFAULT_PROFILE } from "./clean-workspace.mjs";/**@@ -8,11 +10,12 @@ import { DEFAULT_PROFILE } from "./clean-workspace.mjs";* home: { refresh(): Promise<{ kind: string }>, show(options?: object): Promise<unknown>, opensNow(ask: unknown): boolean | null },* places: { remembered(): any, remember(place: null): void },* profiles: { open(id: string): Promise<boolean | null> } | null,- * server(id: string): Promise<boolean>,+ * server(id: string): Promise<boolean | "own" | "sign-in">,* log?(line: string): void,* }} deps `home`: the home window. `profiles`: the workspaces of this computer's own, null where there are* none. `server(id)`: opens the server saved by hand under that id without a dialog, false when it isn't saved or doesn't- * answer in a short wait.+ * answer in a short wait, "sign-in" when it answers but this app isn't signed in there, "own" when it is this computer's+ * own server (saved-server.mjs reopenSavedServerAtLaunch).* @returns {Promise<"remembered" | "cloud" | "this-mac" | "home">} where the window went: the remembered place, My Cloud* instead of it, This Mac instead of both, or home as worked out with nothing remembered (or nobody signed in).*/@@ -21,7 +24,16 @@ export async function openStartPlace({ home, places, profiles, server, log = ()const last = places.remembered();if (!last) { await home.show(); return "home"; }// A server saved by hand belongs to this computer, not to an account: it reopens even when nobody is signed in.- if (typeof last.server === "string" && (await server(last.server).catch(() => false)) === true) return "remembered";+ const saved = typeof last.server === "string" ? await server(last.server).catch(() => false) : false;+ if (saved === true) return "remembered";+ // It answers, but its page would only ask this window to pair: home as worked out, and the place waits until this app+ // is signed in there. This computer's own server under another address is never a place of its own: it is forgotten.+ if (saved === "sign-in" || saved === "own") {+ log(`start: the server open last time ${saved === "own" ? "is this computer's own" : "needs this app to sign in"}; home instead`);+ if (saved === "own") places.remember(null);+ await home.show();+ return "home";+ }// Signed out, nothing else of the account's opens: home shows as ever, and the place waits for the person to be back.if (home.opensNow("cloud") === null) { await home.show(); return "home"; }if (typeof last.server !== "string" && (await reopens(last))) return "remembered";diff --git a/electron/start-place.node-test.mjs b/electron/start-place.node-test.mjsindex 65a7b7566a..1e1886e839 100644--- a/electron/start-place.node-test.mjs+++ b/electron/start-place.node-test.mjs@@ -4,7 +4,7 @@ import test from "node:test";import { openStartPlace } from "./start-place.mjs";/** A launch: the home window's word on each place (`opens`), the workspaces that open (`workspaces`), the servers that answer. */-function launch({ remembered = null, kind = "cloud", opens = {}, workspaces = ["default", "work"], servers = [], profiles = true } = {}) {+function launch({ remembered = null, kind = "cloud", opens = {}, workspaces = ["default", "work"], servers = [], declined = {}, profiles = true } = {}) {const w = { remembered, steps: [], forgot: 0 };const args = {home: {@@ -14,7 +14,7 @@ function launch({ remembered = null, kind = "cloud", opens = {}, workspaces = ["},places: { remembered: () => w.remembered, remember: (place) => { w.remembered = place; w.forgot++; } },profiles: profiles ? { open: async (id) => { w.steps.push(`profile:${id}`); return workspaces.includes(id); } } : null,- server: async (id) => { w.steps.push(`server:${id}`); if (id === "throws") throw new Error("boom"); return servers.includes(id); },+ server: async (id) => { w.steps.push(`server:${id}`); if (id === "throws") throw new Error("boom"); return declined[id] ?? servers.includes(id); },};w.run = () => openStartPlace(args);return w;@@ -46,7 +46,7 @@ test("one that can't open now falls back to My Cloud and is forgotten: a removed}});-test("a server saved by hand reopens whether or not Cloud is home or anyone is signed in", async () => {+test("a server saved by hand that this app is signed in to reopens whether or not Cloud is home or anyone is signed in", async () => {for (const extra of [{}, { kind: "computer" }, { opens: { cloud: null } }]) {const w = launch({ remembered: { server: "env-1" }, servers: ["env-1"], ...extra });assert.equal(await w.run(), "remembered", JSON.stringify(extra));@@ -82,3 +82,21 @@ test("nobody signed in: home as ever, and the place stays remembered for when thassert.deepEqual(w.steps, ["refresh", "show"]);assert.deepEqual(w.remembered, { profile: "work" });});++test("a saved server that answers but would only ask the window to pair: home as worked out, and it stays remembered", async () => {+ for (const extra of [{}, { kind: "computer" }, { opens: { cloud: null } }, { opens: { cloud: false } }]) {+ const w = launch({ remembered: { server: "lan" }, declined: { lan: "sign-in" }, ...extra });+ assert.equal(await w.run(), "home", JSON.stringify(extra));+ assert.deepEqual(w.steps, ["refresh", "server:lan", "show"], "This computer (or My Cloud) as before, not the pairing page");+ assert.deepEqual(w.remembered, { server: "lan" }, "it opens again once this app is signed in there");+ }+});++test("a saved server that is this computer's own under another address: home as worked out, and it is forgotten", async () => {+ for (const extra of [{}, { kind: "computer" }, { opens: { cloud: null } }]) {+ const w = launch({ remembered: { server: "me" }, declined: { me: "own" }, ...extra });+ assert.equal(await w.run(), "home", JSON.stringify(extra));+ assert.deepEqual(w.steps, ["refresh", "server:me", "show"]);+ assert.equal(w.remembered, null, "never a place of its own");+ }+});diff --git a/src/locales/de.json b/src/locales/de.jsonindex be95775b2e..8e96affe39 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4631,5 +4631,6 @@"automations.pauseAll": "Alle pausieren","automations.resumeAll": "Alle fortsetzen","automations.pausedAll.one": "1 Automatisierung pausiert.",- "automations.pausedAll.other": "{count} Automatisierungen pausiert."+ "automations.pausedAll.other": "{count} Automatisierungen pausiert.",+ "pair.backTo": "Zurück zu {place}"}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 5a6056a081..baf2533c89 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10507,6 +10507,7 @@"pair.team.openHint": "You sign in there with your email, then come straight back here.","pair.signInTo": "Sign in to {name}","pair.connectTo": "Connect to {name}",+ "pair.backTo": "Back to {place}","shortcuts.toggle-sidebar": "Collapse or expand the sidebar","readyBots.bot.social.title": "Social media manager","readyBots.bot.social.description": "Plans your posts and adds them to Postiz as drafts or scheduled posts, ready for you to review.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 30b7f34939..a9ad6b35c1 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6813,5 +6813,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Las imágenes necesitan una clave de API de imágenes. Las suscripciones de IA como Antigravity o Gemini no pueden crearlas aquí.","botIdentity.ai.getGeminiKey": "Obtener una clave de API de Gemini",- "publishedApps.access.owner": "Solo tú"+ "publishedApps.access.owner": "Solo tú",+ "pair.backTo": "Volver a {place}"}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 601e261327..909082c0c0 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -4225,5 +4225,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Les images demandent une clé API d'images. Les abonnements IA comme Antigravity ou Gemini ne peuvent pas en créer ici.","botIdentity.ai.getGeminiKey": "Obtenir une clé API Gemini",- "publishedApps.access.owner": "Vous seul"+ "publishedApps.access.owner": "Vous seul",+ "pair.backTo": "Retour à {place}"}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 1869610830..d292abbbcb 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -4077,5 +4077,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "तस्वीरें बनाने के लिए इमेज API कुंजी चाहिए। Antigravity या Gemini जैसी AI सदस्यताएँ यहाँ तस्वीरें नहीं बना सकतीं।","botIdentity.ai.getGeminiKey": "Gemini API कुंजी पाएँ",- "publishedApps.access.owner": "केवल आप"+ "publishedApps.access.owner": "केवल आप",+ "pair.backTo": "{place} पर वापस जाएँ"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex 88bb11fe13..3ce363b9bf 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -10393,6 +10393,7 @@"pair.team.openHint": "Se firmi con la tua email, torna subito qui.","pair.signInTo": "Iscriviti a {name}","pair.connectTo": "Collegare {name}",+ "pair.backTo": "Torna a {place}","shortcuts.toggle-sidebar": "Collapse o espandere la barra laterale","readyBots.bot.social.title": "Gestore social media","readyBots.bot.social.description": "Pianifica i tuoi messaggi e li aggiunge a Postiz come bozze o post programmati, pronti per voi a rivedere.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex a83ba06c77..0e627cb092 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -8348,5 +8348,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "画像の作成には画像用の API キーが必要です。Antigravity や Gemini などの AI サブスクリプションでは、ここで画像を作成できません。","botIdentity.ai.getGeminiKey": "Gemini の API キーを取得",- "publishedApps.access.owner": "自分のみ"+ "publishedApps.access.owner": "自分のみ",+ "pair.backTo": "{place}に戻る"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 12fe1a5a39..15bb7befe2 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -8040,5 +8040,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "그림을 만들려면 이미지 API 키가 필요합니다. Antigravity나 Gemini 같은 AI 구독으로는 여기서 그림을 만들 수 없습니다.","botIdentity.ai.getGeminiKey": "Gemini API 키 받기",- "publishedApps.access.owner": "나만"+ "publishedApps.access.owner": "나만",+ "pair.backTo": "{place}(으)로 돌아가기"}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex b8310aad6d..0e362dc6a9 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7509,5 +7509,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Do tworzenia obrazów potrzebny jest klucz API do obrazów. Subskrypcje AI, takie jak Antigravity czy Gemini, nie mogą ich tu tworzyć.","botIdentity.ai.getGeminiKey": "Uzyskaj klucz API Gemini",- "publishedApps.access.owner": "Tylko ty"+ "publishedApps.access.owner": "Tylko ty",+ "pair.backTo": "Wróć do: {place}"}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex ea9aaf9f7e..5727412ffa 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10426,6 +10426,7 @@"pair.myCloud": "My Cloud","pair.signInTo": "Entrar em {name}","pair.connectTo": "Conectar a {name}",+ "pair.backTo": "Voltar para {place}","shortcuts.toggle-sidebar": "Recolher ou expandir a barra lateral","readyBots.bot.social.title": "Gerente de redes sociais","readyBots.bot.social.description": "Planeja seus posts e os adiciona ao Postiz como rascunhos ou posts agendados para você revisar.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex e701dc97bb..6ac4eb952f 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7563,5 +7563,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Для картинок нужен API-ключ для изображений. Подписки на ИИ, например Antigravity или Gemini, здесь их не создают.","botIdentity.ai.getGeminiKey": "Получить API-ключ Gemini",- "publishedApps.access.owner": "Только вы"+ "publishedApps.access.owner": "Только вы",+ "pair.backTo": "Вернуться: {place}"}diff --git a/src/locales/th.json b/src/locales/th.jsonindex 880fc8bcd4..754457d337 100644--- a/src/locales/th.json+++ b/src/locales/th.json@@ -10369,6 +10369,7 @@"pair.team.openHint": "ลงชื่อเข้าใช้ที่นั่นด้วยอีเมล แล้วกลับมาที่นี่โดยตรง","pair.signInTo": "ลงชื่อเข้าใช้ {name}","pair.connectTo": "เชื่อมต่อกับ {name}",+ "pair.backTo": "กลับไปที่ {place}","shortcuts.toggle-sidebar": "ย่อหรือขยายแถบด้านข้าง","readyBots.bot.social.title": "ผู้จัดการโซเชียลมีเดีย","readyBots.bot.social.description": "วางแผนโพสต์แล้วเพิ่มลง Postiz เป็นฉบับร่างหรือโพสต์ตามกำหนดเวลา เพื่อให้คุณตรวจสอบ",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex eb1b973a62..e5c7c34779 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -6308,5 +6308,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Görsel oluşturmak için bir görsel API anahtarı gerekir. Antigravity veya Gemini gibi yapay zekâ abonelikleri burada görsel oluşturamaz.","botIdentity.ai.getGeminiKey": "Gemini API anahtarı al",- "publishedApps.access.owner": "Yalnızca sen"+ "publishedApps.access.owner": "Yalnızca sen",+ "pair.backTo": "Geri dön: {place}"}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 9469f8431c..6908c305ce 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -4493,5 +4493,6 @@"githubSignIn.tokenPlaceholder": "github_pat_…","botIdentity.ai.keyNeeded": "Для зображень потрібен API-ключ для зображень. Підписки на ШІ, як-от Antigravity чи Gemini, тут їх не створюють.","botIdentity.ai.getGeminiKey": "Отримати API-ключ Gemini",- "publishedApps.access.owner": "Лише ви"+ "publishedApps.access.owner": "Лише ви",+ "pair.backTo": "Повернутися: {place}"}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 25909466f7..1855e4e078 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -6489,5 +6489,6 @@"shortcuts.start-fresh": "Bắt đầu lại cuộc trò chuyện này (giữ nguyên tin nhắn)","botIdentity.ai.keyNeeded": "Cần khóa API hình ảnh để tạo ảnh. Các gói đăng ký AI như Antigravity hoặc Gemini không tạo được ảnh ở đây.","botIdentity.ai.getGeminiKey": "Lấy khóa API Gemini",- "publishedApps.access.owner": "Chỉ bạn"+ "publishedApps.access.owner": "Chỉ bạn",+ "pair.backTo": "Quay lại {place}"}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex cb2dab403a..472cd2aff9 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -9202,6 +9202,7 @@"pair.myCloud": "我的 Cloud","pair.signInTo": "登入 {name}","pair.connectTo": "連線至 {name}",+ "pair.backTo": "返回{place}","shortcuts.toggle-sidebar": "收合或展開側邊欄","readyBots.bot.social.title": "社群媒體經理","readyBots.bot.social.description": "規劃你的貼文,並以草稿或排程貼文加入 Postiz,等你檢閱。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 8c792bd53d..a6b90c6bbe 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -10321,6 +10321,7 @@"pair.team.openHint": "你在那里用邮箱登录,然后直接回到这里。","pair.signInTo": "登录 {name}","pair.connectTo": "连接到 {name}",+ "pair.backTo": "返回{place}","shortcuts.toggle-sidebar": "折叠或展开侧边栏","readyBots.bot.social.title": "社交媒体管理","readyBots.bot.social.description": "规划你的帖子,并以草稿或定时帖的形式加入 Postiz,等你审阅。",diff --git a/src/pair/PairPage.dom.test.ts b/src/pair/PairPage.dom.test.tsnew file mode 100644index 0000000000..5631739ce4--- /dev/null+++ b/src/pair/PairPage.dom.test.ts@@ -0,0 +1,38 @@+// @vitest-environment happy-dom+// A saved server's sign-in page in the app: its way back to This computer goes there on the person's click.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { setLocale } from "@/lib/i18n";++vi.mock("../lib/session", async original => ({ ...await original<typeof import("../lib/session")>(), readSessionState: vi.fn().mockResolvedValue({ kind: "unauthenticated", error: "" }) }));+vi.mock("../components/DesktopWorkspaceSwitcher", () => ({ DesktopWorkspaceSwitcher: () => null }));+const { PairPage } = await import("./PairPage");++let host: HTMLDivElement;+let root: Root;+beforeEach(() => {+ setLocale("en");+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+ delete (window as { ogb?: unknown }).ogb;+ vi.unstubAllGlobals();+});++it("the pairing page of a saved server, in the app, goes back to This computer on click", () => {+ const thisComputer = vi.fn().mockResolvedValue(undefined);+ (window as { ogb?: unknown }).ogb = { app: { version: "1", ownPage: false }, workspaces: { thisComputer } };+ flushSync(() => root.render(createElement(PairPage, { initialCode: null })));+ const back = host.querySelector<HTMLButtonElement>("[data-pair-this-computer]");+ expect(back?.textContent).toBe("Back to This computer");+ back!.click();+ expect(thisComputer).toHaveBeenCalledOnce();+});diff --git a/src/pair/PairPage.test.ts b/src/pair/PairPage.test.tsindex c04f8de0d4..672e1f0d6d 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 { backToComputer, codeProblem, codeReady, openInAppLink, PairPage, pairIntro, pairsAutomatically, pairTitle, phoneBrowser, TeamLeftPage, teamPage, unencryptedPublic } from "./PairPage";import en from "../locales/en.json";import type { EnvironmentDescriptor } from "../lib/session";@@ -140,3 +140,19 @@ it("Chrome on Windows sees the pairing form without the phone app's line", () =>expect(html).not.toContain(en["pair.onPhone"]);expect(html).not.toContain("openmausbot://pair");});++it("in the app, a saved server's sign-in page has a way back to This computer that goes there on click; this computer's own page and a browser don't", async () => {+ const thisComputer = vi.fn().mockResolvedValue(undefined);+ expect(backToComputer({ app: { version: "1", ownPage: false }, workspaces: { thisComputer } } as unknown as Window["ogb"])).toBe(thisComputer);+ expect(backToComputer({ app: { version: "1", ownPage: true }, workspaces: { thisComputer } } as unknown as Window["ogb"])).toBeNull();+ expect(backToComputer({ app: { version: "1", ownPage: false }, workspaces: {} } as unknown as Window["ogb"]), "an older app").toBeNull();+ expect(backToComputer(undefined), "a browser").toBeNull();+ vi.stubGlobal("window", { ogb: { app: { version: "1", ownPage: false }, workspaces: { thisComputer } } });+ const html = render(null);+ expect(html).toContain(">Back to This computer</button>");+ expect(html).toContain("data-pair-this-computer");+ vi.stubGlobal("window", { ogb: { app: { version: "1", ownPage: true }, workspaces: { thisComputer } } });+ expect(render(null)).not.toContain("Back to This computer");+ vi.stubGlobal("window", {});+ expect(render(null)).not.toContain("Back to This computer");+});diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsxindex c570dc6fc4..bdae3a8f52 100644--- a/src/pair/PairPage.tsx+++ b/src/pair/PairPage.tsx@@ -82,6 +82,12 @@ export function pairTitle(environment: EnvironmentDescriptor | null, mode: "emaireturn t(mode === "email" ? "pair.signInTo" : "pair.connectTo", { name: environment?.label ?? t("pair.thisOpenMausBot", { app: productName() }) });}+/** In the app, on a saved server's page (never this computer's own): the way back to This computer, else null. */+export function backToComputer(ogb: Window["ogb"] = typeof window === "undefined" ? undefined : window.ogb): (() => Promise<unknown>) | null {+ const back = ogb?.workspaces?.thisComputer;+ return ogb?.app?.ownPage === false && typeof back === "function" ? back : null;+}+/** A team's page whose session ended because its person is no longer in the team: one sentence, nothing that can't work. */export function TeamLeftPage({ team }: { team: string | null }) {return <main data-team-left className="flex min-h-screen items-center justify-center bg-app px-6 text-ink">@@ -134,6 +140,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initialconst ownServer = !cloudHome && environment?.capabilities.cloudTeam !== true;const problem = codeProblem(code);const where = typeof location !== "undefined" && typeof location.protocol === "string" ? location : null;+ const back = backToComputer();async function submitCode(e: React.FormEvent) {e.preventDefault();@@ -299,6 +306,11 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial) : null}</form>)}+ {back && !opening ? (+ <button type="button" data-pair-this-computer onClick={() => void back().catch(() => {})} className="ui-button ui-button-md mt-5 w-full">+ {t("pair.backTo", { place: t("place.local") })}+ </button>+ ) : null}</div></main>);diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 7631ea8043..737ff8fe22 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -198,6 +198,8 @@ const __APP_VERSION__: string;state: () => Promise<{ local: boolean; name: string; origin?: string; color?: string; home?: boolean; role?: string; localPath?: string; profile?: string; profileName?: string }>;/** The native server menu; resolves when it closes. `from: "howto"`: the Show me how tip opened it. */menu: (options?: { from?: "howto" }) => Promise<void>;+ /** Back to This computer, from a saved server's sign-in page: only from the person's click. Absent on an older app. */+ thisComputer?: () => Promise<unknown>;/** One plain line for the next page: a team this person is no longer in (served once), or, while it runs, that the* clean workspace or a profile (`profile`) of this computer's own isn't where the Cloud's bots are. */line?: () => Promise<{ kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile"; name?: string } | null>;