Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A phone paired with a computer whose bots moved hears where they went, and reaches This Mac (#4724)
Milind Soni7b9659aac357
diff --git a/electron/main.mjs b/electron/main.mjsindex f9e1f53e69..d313cad892 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -2648,7 +2648,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), stop: () => stopDesktopCompanion({ remember: false }).then(() => {}), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });+const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionEnabledAtRest(), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionEnabledAtRest(), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,@@ -3093,9 +3093,9 @@ app.whenReady().then(async () => {cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).then(() => accountRing()?.start()).finally(() => { cloudAccountRestoring = false; });}void cloudAccountStarted.then(() => { cloudSignInRestored = true; void oneHome.kick(); void homeWindow.refresh(); }); void ownHome?.kick();- if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away() && !cleanWorkspace.marker().frozen) {+ if (!desktopRemoteAccess && serverReady && companionEnabledAtRest()) {// Retries stop once the person turns the phone off, starts it by hand or quits.- const wanted = () => !desktopShutdownStarted && companionEnabledAtRest() && !companionRunning() && !oneHome.away() && !ownHome?.away();+ const wanted = () => !desktopShutdownStarted && companionEnabledAtRest() && !companionRunning();void autoStartCompanion({ restored: managedDesktop?.whenRestored(), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }), wanted, log: slog });}setLocalOrigin(rendererOrigin());diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjsindex aea3bbf13f..7f8760bee7 100644--- a/electron/one-home-main.mjs+++ b/electron/one-home-main.mjs@@ -106,7 +106,7 @@ async function answer(response) {* journalFile(): string,* tempRoot(): string,* lend?(projects: string[]): Promise<unknown>,- * phone?: { paired(): boolean, stop(): Promise<void>, start(): Promise<void> },+ * phone?: { paired(): boolean, start(): Promise<void> },* openHome?(): void,* openLocal?(): void,* restart?(): void,@@ -294,7 +294,7 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,holding: () => { const bot = teamMove.view()?.phase; return home.moving() || (bot && !["done", "failed"].includes(bot)) ? "moving" : null; },/** Goes on with the move, and with any bot moving into a team: at launch, and whenever the MausBot Cloud sign-in changes. */kick: () => { void teamMove.kick(); return home.kick(); },- /** Home is My Cloud: this computer's own server is frozen for good, and its phone link stays off. */+ /** Home is My Cloud: this computer's own server is frozen for good. */away: () => home.away(),view: () => home.view(),close: () => { teamMove.close(); home.close(); report.close(); void moveSession.end(); },diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex eb9e2c9ad9..7a8a5325c3 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -7,7 +7,7 @@// final the same pass again, for what changed since, with the sign-ins that refresh themselves// check what arrived, against what is here; anything missing goes again, three passes at most// switch My Cloud switches on what was on here, and keeps which computer its bots came from-// done home is My Cloud: this computer lends itself, stops its phone link, and says once what arrived+// done home is My Cloud: this computer lends itself and says once what arrived//// Before the switch a failure lifts the freeze and tries again later; from the switch on the move only goes forward, so// nothing ever runs in two places. If My Cloud ends, this computer is home again at once (`home-again`), then brings@@ -57,7 +57,7 @@ const NAMED_MAX = 5;export const KEPT_MS = 30 * DAY;const PHASES = new Set(["copy", "wait", "freeze", "final", "check", "switch", "done", "keeping", "home-again", "back"]);const FROZEN = new Set(["freeze", "final", "check"]);-/** The phases in which home is My Cloud: the window shows it, and this computer's phone link stays off. */+/** The phases in which home is My Cloud: the window shows it. */const AWAY = new Set(["switch", "done", "keeping"]);/** The phases that use My Cloud's owner session, a pass that failed and waits to go again included. */const MOVING = new Set(["copy", "wait", "freeze", "final", "check", "switch"]);@@ -166,7 +166,7 @@ export function arrivedCounts(here, there) {* session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>, close(): Promise<void> }>,* release?(): Promise<void>,* lend?(projects: string[]): Promise<unknown>,- * phone?: { paired(): boolean, stop(): Promise<void>, start(): Promise<void> },+ * phone?: { paired(): boolean, start(): Promise<void> },* openHome?(): void,* openLocal?(): void,* lastInput?(): number,@@ -395,8 +395,9 @@ export function createOneHome(deps) {return null;}- /** Once home is My Cloud: the bots' project folders are lent to it with this computer, its own phone link stops, and- * the Admin is told it moved, once per sign-in (tried again at most hourly while the Admin can't take it). */+ /** Once home is My Cloud: the bots' project folders are lent to it with this computer, and the Admin is told it moved,+ * once per sign-in (tried again at most hourly while the Admin can't take it). The phone link stays on: a phone paired+ * here hears from the frozen copy where its bots went, and reaches a workspace of this computer's own while one runs. */async function settle(journal, cloud = deps.cloud()) {let next = journal;if (deps.reportMove && cloud?.signIn && next.reported !== cloud.signIn && now() - reportFailedAt >= HOUR) {@@ -413,12 +414,6 @@ export function createOneHome(deps) {next = write({ ...next, lent: true });} catch (error) { log(`one home: this computer is lent later (${error?.message ?? error})`); }}- if (!next.phoneStopped) {- try {- if (next.phone) await deps.phone?.stop();- next = write({ ...next, phoneStopped: true });- } catch (error) { log(`one home: the phone link stops later (${error?.message ?? error})`); }- }return next;}diff --git a/electron/one-home.node-test.mjs b/electron/one-home.node-test.mjsindex 47fa937059..169df9e57c 100644--- a/electron/one-home.node-test.mjs+++ b/electron/one-home.node-test.mjs@@ -98,7 +98,7 @@ function world({ cloud = {}, switches = { "routine:r1": true, "routine:r2": falsreturn w;}-test("a new buyer's move runs every phase and ends with home on My Cloud, this computer lent and its phone link off", async () => {+test("a new buyer's move runs every phase and ends with home on My Cloud, this computer lent and its phone link left on", async () => {const w = world();await w.home.kick();assert.equal(w.journal.phase, "done");@@ -108,7 +108,7 @@ test("a new buyer's move runs every phase and ends with home on My Cloud, this cassert.deepEqual(w.switchedOn().sort(), ["/api/calendar-calls/c1", "/api/routines/r1", "/api/webhooks/w1"], "only what was on here, and nothing off");assert.deepEqual(w.cloudCalls.find(([, route]) => route === "/api/cloud-send/arrived")?.[2], { v: 1, computer: "MacBook Air", webhooks: ["w1"] });assert.deepEqual(w.lent, [["/Users/p/code/shop"]], "lent once, with each bot's own project folder");- assert.equal(w.phone.stopped, 1);+ assert.equal(w.phone.stopped, 0, "a phone paired here hears from the frozen copy where its bots went, and reaches a workspace of this computer's own once one is open");assert.deepEqual(w.opened, ["cloud"]);assert.equal(w.home.away(), true);assert.deepEqual(w.home.view(), { phase: "done", at: w.journal.doneAt, counts: { bots: 2, skills: 0, logins: 1, onePassword: false, chats: 1, routines: 1 }, phone: true, held: ["OpenRouter"] });@@ -116,7 +116,7 @@ test("a new buyer's move runs every phase and ends with home on My Cloud, this cawait w.relaunch().kick();assert.equal(w.lent.length, 1, "a relaunch lends nothing again");- assert.equal(w.phone.stopped, 1);+ assert.equal(w.phone.stopped, 0);assert.equal(w.server.unfreezes, 0);});diff --git a/electron/own-home-main.mjs b/electron/own-home-main.mjsindex a432ada8ba..25281f3ede 100644--- a/electron/own-home-main.mjs+++ b/electron/own-home-main.mjs@@ -92,7 +92,7 @@ function jsonStore(store) {* sendState: { read(): unknown, write(value: unknown): void },* cloudJournal(): unknown,* lend?(projects: string[], place: any): Promise<unknown>,- * phone?: { paired(): boolean, stop(): Promise<void>, start(): Promise<void> },+ * phone?: { paired(): boolean, start(): Promise<void> },* openHome?(place: any): void,* lastInput?(): number,* version?: string,diff --git a/server/move-freeze.test.ts b/server/move-freeze.test.tsindex 423f30f4ff..1063cc913d 100644--- a/server/move-freeze.test.ts+++ b/server/move-freeze.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL, movedRefusal, RAIL_PAGE, switchAutomationsOff, type MoveAutomations } from "./move-freeze.ts";+import { createMoveFreeze, ENDED_REFUSAL, HOME_SCREEN, MOVED_REFUSAL, movedRefusal, phoneMovedRefusal, RAIL_PAGE, switchAutomationsOff, type MoveAutomations } from "./move-freeze.ts";import type { MoveWait } from "./move-waits.ts";import { createMoveFreezeRoutes } from "./routes/move-freeze.ts";import { PASS } from "./routes/table.ts";@@ -128,9 +128,9 @@ describe("switching this computer's automations off for a move", () => {});describe("/api/move/freeze", () => {- const ask = async (route: ReturnType<typeof createMoveFreezeRoutes>, method: string, path = "/api/move/freeze", body: unknown = {}, kind = "loopback") => {+ const ask = async (route: ReturnType<typeof createMoveFreezeRoutes>, method: string, path = "/api/move/freeze", body: unknown = {}, kind = "loopback", companionDevice?: string) => {let answered: { status: number; body: any } | undefined;- const out = await route({ path, method, url: new URL(`http://127.0.0.1${path}`), req: {} as never, res: {} as never, auth: { kind, scopes: ["admin"] } as never,+ const out = await route({ path, method, url: new URL(`http://127.0.0.1${path}`), req: {} as never, res: {} as never, auth: { kind, scopes: ["admin"], ...(companionDevice ? { companionDevice } : {}) } as never,json: (_res: unknown, status: number, value: unknown) => { answered = { status, body: value }; }, readBody: async () => body } as never);return out === PASS ? "pass" : answered!;};@@ -168,6 +168,24 @@ describe("/api/move/freeze", () => {expect(await ask(route, "POST", undefined, { cloud: "https://garage.example.test", place: "x".repeat(121) }), "a name past 120 characters").toMatchObject({ status: 400 });});+ it("a phone still paired with this computer hears where its bots went, on every route, reads and its event stream too", async () => {+ const dir = dataDir();+ const freeze = createMoveFreeze({ dataDir: dir });+ const route = createMoveFreezeRoutes({ freeze, busy: () => null, restart() {}, platform: "darwin" });+ expect(await ask(route, "GET", "/api/bots", {}, "loopback", "phone-1"), "not frozen: the phone uses this computer as ever").toBe("pass");+ freeze.freeze("https://omb-t-1.fly.dev");+ const moved = { status: 410, body: { error: "This computer's bots moved to My Cloud. Open This Mac in the app on this computer to use it from your phone, or open My Cloud.", code: "home_moved" } };+ for (const [method, path] of [["GET", "/api/bots"], ["GET", "/api/events"], ["POST", "/api/bots/b1/messages"], ["GET", "/api/move/freeze"]]) {+ expect(await ask(route, method!, path, {}, "loopback", "phone-1"), `${method} ${path}`).toEqual(moved);+ }+ expect(await ask(route, "GET", "/api/health", {}, "loopback", "phone-1"), "this computer is up, so the phone reads the reason instead of trying again").toBe("pass");+ expect(await ask(route, "GET", "/api/bots"), "this computer's own app still reads its frozen copy").toBe("pass");+ expect(phoneMovedRefusal(null, "win32")).toMatch(/Open This PC in the app/);+ const garage = createMoveFreezeRoutes({ freeze: createMoveFreeze({ dataDir: dataDir() }), busy: () => null, restart() {}, platform: "darwin" });+ await ask(garage, "POST", undefined, { cloud: "https://garage.example.test", place: "Garage server" });+ expect(await ask(garage, "GET", "/api/bots", {}, "loopback", "phone-1")).toEqual({ status: 410, body: { error: "This computer's bots moved to Garage server. Open Garage server from your phone instead.", code: "home_moved", place: "Garage server" } });+ });+it("is only for OpenMausBot on this computer, never a paired device", async () => {const freeze = createMoveFreeze({ dataDir: dataDir() });const route = createMoveFreezeRoutes({ freeze, busy: () => null, restart() {} });diff --git a/server/move-freeze.ts b/server/move-freeze.tsindex 32fae338e0..5f722194fb 100644--- a/server/move-freeze.ts+++ b/server/move-freeze.ts@@ -16,6 +16,11 @@ import type { WebhookManager } from "./webhooks.ts";export const MOVED_REFUSAL = "This bot lives on My Cloud now.";/** Why a frozen copy refuses, naming the server of the person's own its bots moved to (`place`), else My Cloud. */export const movedRefusal = (place: string | null): string => (place ? `This bot lives on ${place} now.` : MOVED_REFUSAL);+/** What a frozen copy answers a phone still paired with this computer: where its bots went, and, after a move to My+ * Cloud, the workspace of this computer's own (This Mac or This PC) that the same pairing reaches once it is open. */+export const phoneMovedRefusal = (place: string | null, platform: NodeJS.Platform = process.platform): string => place+ ? `This computer's bots moved to ${place}. Open ${place} from your phone instead.`+ : `This computer's bots moved to My Cloud. Open ${platform === "darwin" ? "This Mac" : "This PC"} in the app on this computer to use it from your phone, or open My Cloud.`;/** The one page a frozen copy serves: the desktop app's screen while My Cloud can't be opened (electron/home-window.mjs). */export const HOME_SCREEN = "/home";/** The desktop window's own rail of places (electron/chrome-rail.mjs): this app's page, beside whichever place is open. */diff --git a/server/one-home.e2e.test.ts b/server/one-home.e2e.test.tsindex 9797e1d65b..dfccbedb8a 100644--- a/server/one-home.e2e.test.ts+++ b/server/one-home.e2e.test.ts@@ -150,9 +150,10 @@ it("a new buyer: every phase, the app killed at each one, ends with home on My Cexpect(cloudBots.find((bot) => bot.id === cloudy.id)?.name).toBe("Cloudy");expect(cloudBots.some((bot) => bot.id === old.id)).toBe(false);- // This computer is lent with Scout's project folder, its phone link stops, and the window opens My Cloud: once each.+ // This computer is lent with Scout's project folder and the window opens My Cloud, once each; its phone link stays on,+ // so a paired phone hears where the bots went.expect(fx.spies.lent).toEqual([[project]]);- expect(fx.spies.phoneStops).toBe(1);+ expect(fx.spies.phoneStops).toBe(0);expect(fx.spies.opened).toEqual(["cloud"]);// The schedules on both servers: the one that runs at every start ran here only before the freeze, never on My Cloud,diff --git a/server/own-home.e2e.test.ts b/server/own-home.e2e.test.tsindex 691f2e53c6..0faa4847e5 100644--- a/server/own-home.e2e.test.ts+++ b/server/own-home.e2e.test.ts@@ -120,9 +120,10 @@ it("Make Garage server my home: bots, chats, memory and routines arrive, this coexpect(webhook.webhook.id).toBeTruthy();expect((await local("GET", "/api/move/freeze")).body).toMatchObject({ frozen: true, cloud: garage.base, place: "Garage server" });- // This computer is lent with Scout's project folder to Garage server, its phone link stops, and the window opens Garage server.+ // This computer is lent with Scout's project folder to Garage server and the window opens Garage server; its phone link+ // stays on, so a paired phone hears where the bots went.expect(fx.spies.lent).toEqual([{ projects: [project], place: garage.base }]);- expect(fx.spies.phoneStops).toBe(1);+ expect(fx.spies.phoneStops).toBe(0);expect(fx.spies.opened).toEqual([garage.base]);expect(fx.main.offers(garage.place), "home is there: nothing more to offer").toBe(false);diff --git a/server/routes/move-freeze.ts b/server/routes/move-freeze.tsindex b93292d72b..1672479ffd 100644--- a/server/routes/move-freeze.ts+++ b/server/routes/move-freeze.ts@@ -1,10 +1,10 @@// /api/move/freeze: the desktop app freezes this computer's copy at the move's quiet moment (POST), lifts it when the// move can't finish or My Cloud ended (DELETE; `{ automations: "off" }` when another computer is home now), and asks who// is still busy (GET); POST /api/move/forget deletes the frozen copy once the move is long done. Every other change a-// frozen server refuses here, before any other route.+// frozen server refuses here, before any other route, and a phone still paired with it hears where the bots went on every route.import { z } from "zod";-import type { MoveFreeze } from "../move-freeze.ts";+import { type MoveFreeze, phoneMovedRefusal } from "../move-freeze.ts";import type { MoveWait } from "../move-waits.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -17,13 +17,20 @@ export interface MoveFreezeRouteDeps {restart(): void;/** Switches off every automation here (move-freeze.ts `switchAutomationsOff`). */automationsOff?(): Promise<unknown>;+ platform?: NodeJS.Platform;}const freezeBody = z.object({ cloud: z.string().url().max(300).optional(), place: z.string().trim().min(1).max(120).optional() });const thawBody = z.object({ automations: z.literal("off").optional() });-export function createMoveFreezeRoutes({ freeze, busy, restart, automationsOff }: MoveFreezeRouteDeps): RouteHandler {+export function createMoveFreezeRoutes({ freeze, busy, restart, automationsOff, platform = process.platform }: MoveFreezeRouteDeps): RouteHandler {return async ({ req, res, path, method, auth, json, readBody }) => {+ // Health still answers: without it the companion tells the phone OpenMausBot isn't ready here, and the phone keeps+ // trying instead of reading the reason.+ if (auth.kind === "loopback" && auth.companionDevice && freeze.frozen() && freeze.lifts() && !(method === "GET" && path === "/api/health")) {+ const place = freeze.place();+ return json(res, 410, { error: phoneMovedRefusal(place, platform), code: "home_moved", ...(place ? { place } : {}) });+ }if (path === "/api/move/forget") {if (auth.kind !== "loopback") return json(res, 403, { error: "Only OpenMausBot on this computer can do this." });if (method !== "POST") return json(res, 405, { error: "method not allowed" });