Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Signed out or on the wrong account: a clean workspace, not a dead end
milind-sonibd3fbe44924c
diff --git a/electron/clean-workspace.d.mts b/electron/clean-workspace.d.mtsnew file mode 100644index 0000000000..88f141d15f--- /dev/null+++ b/electron/clean-workspace.d.mts@@ -0,0 +1,18 @@+export function cleanWorkspaceDir(dataDir: string): string;+export function cleanWorkspaceConfig(language?: string | null, now?: Date): { language?: string; onboarding: { completedAt: string; version: number; hintsSeen: string[] } };+export interface CleanWorkspace {+ active(): boolean;+ marker(): { frozen: boolean; cloud?: string; place?: string };+ enter(): Promise<boolean>;+ leave(): Promise<boolean>;+ holding<T>(work: () => Promise<T>): Promise<T>;+ realCopy(request: (route: string, init?: RequestInit) => Promise<Response>): (route: string, init?: RequestInit) => Promise<Response>;+}+export function createCleanWorkspace(deps: {+ dataDir(): string;+ running(): string | null;+ swap(dir: string): Promise<{ ok: boolean }>;+ allowed?(): boolean;+ changed?(): void;+ log?(line: string): void;+}): CleanWorkspace;diff --git a/electron/clean-workspace.mjs b/electron/clean-workspace.mjsnew file mode 100644index 0000000000..1294750997--- /dev/null+++ b/electron/clean-workspace.mjs@@ -0,0 +1,118 @@+// A computer whose bots moved to a Cloud nobody here can reach (nobody is signed in, or the account signed in has no way to+// that Cloud) isn't a dead end: its window opens a clean workspace, in a folder of its own beside this computer's data folder,+// and says the bots are safe in their Cloud. Signing in as the account they moved with goes to that Cloud as ever.+//+// The folder swap is the one named local environments use (environment-switch.mjs): one server at a time, on the same port.+// So this computer's frozen copy isn't running while the clean workspace is: nothing in it can run, its freeze isn't touched,+// and no page of it can show. It sits beside the data folder, not in it: a move carries that folder and forgetting the frozen+// copy empties it, and neither ever reaches this one. Nothing made here is merged anywhere.+//+// Security: the move's code knows one server, this computer's own copy. A top-up, a send or a lift pointed at the clean+// workspace would upload it over the person's Cloud or report a freeze lifted that wasn't, so while the clean workspace runs+// `realCopy` answers only what the copy's own files can say, and refuses the rest; `holding` brings the copy back first for+// the two things that must reach it (lifting the freeze, forgetting the copy).+import nodeFs from "node:fs";+import path from "node:path";++import { WELCOME_VERSION } from "./onboarding-record.mjs";++/** This first conversation stays quiet: no corner notices until a reply, no spotlights (src/lib/onboarding.ts MET_CHIEF_HINT). */+const QUIET_HINT = "met-chief-v1";+const CLEAN = "clean-workspace";++export const cleanWorkspaceDir = (dataDir) => `${dataDir}-clean`;++/** A clean workspace's first config: never the new-user setup, which would read as the person's bots being gone. Connecting+ * an AI isn't part of this: the page's line offers it while none works (HomeLine). */+export function cleanWorkspaceConfig(language = null, now = new Date()) {+ return { ...(typeof language === "string" && language ? { language } : {}), onboarding: { completedAt: now.toISOString(), version: WELCOME_VERSION, hintsSeen: [QUIET_HINT] } };+}++/**+ * @param {{+ * dataDir(): string,+ * running(): string | null,+ * swap(dir: string): Promise<{ ok: boolean }>,+ * allowed?(): boolean,+ * changed?(): void,+ * log?(line: string): void,+ * fs?: typeof nodeFs,+ * }} deps `dataDir`: this computer's own data folder, the frozen copy's. `running`: the folder its server runs on now.+ * `swap`: starts the server on that folder instead, and moves the window to its page. `changed`: the clean workspace started or+ * ended, so whatever depends on it (lending) looks again.+ */+export function createCleanWorkspace({ dataDir, running, swap, allowed = () => true, changed = () => {}, log = () => {}, fs = nodeFs }) {+ const folder = () => cleanWorkspaceDir(dataDir());+ const active = () => running() === folder();+ let held = 0;+ let queue = Promise.resolve();+ /** One swap at a time: a second would stop the server the first just started. */+ const inTurn = (work) => {+ const turn = queue.then(work, work);+ queue = turn.catch(() => {});+ return turn;+ };+ const readOwn = (name) => { try { return fs.readFileSync(path.join(dataDir(), name), "utf8"); } catch { return null; } };++ function seed(dir) {+ fs.mkdirSync(dir, { recursive: true });+ let language = null;+ try { language = JSON.parse(readOwn("config.json") ?? "{}")?.language ?? null; } catch {}+ try { fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify(cleanWorkspaceConfig(language)), { mode: 0o600, flag: "wx" }); }+ catch (error) { if (error?.code !== "EEXIST") throw error; }+ }+ async function swapTo(dir) {+ const done = await swap(dir).catch((error) => ({ ok: false, error }));+ if (done?.ok !== true) { log(`clean workspace: could not start on ${dir} (${done?.error?.message ?? done?.error ?? "no answer"})`); return false; }+ changed();+ return true;+ }+ /** The frozen copy's server again; true once it is the one running. */+ const leave = () => inTurn(() => (active() ? swapTo(dataDir()) : true));+ /** This computer's freeze marker, as the frozen copy's own server would say it. */+ function marker() {+ const text = readOwn("moved.json");+ if (text === null) return { frozen: false };+ let saved = null;+ try { saved = JSON.parse(text); } catch {}+ return { frozen: true, ...(typeof saved?.cloud === "string" ? { cloud: saved.cloud } : {}), ...(typeof saved?.place === "string" ? { place: saved.place } : {}) };+ }++ return {+ active,+ marker,+ /** Opens the clean workspace; true once it runs. False when it can't, and the window says why as before. A named local+ * environment the person chose is no frozen copy, so it stays. */+ enter: () => inTurn(async () => {+ if (active()) return true;+ if (!allowed() || held > 0) return false;+ if (running() !== dataDir()) return true;+ try { seed(folder()); } catch (error) { log(`clean workspace: could not set it up (${error?.message ?? error})`); return false; }+ return swapTo(folder());+ }),+ leave,+ /** Runs `work` on this computer's own copy, its server back first, and nothing opens the clean workspace meanwhile. */+ async holding(work) {+ held++;+ try {+ if (!(await leave())) throw new Error("OpenMausBot on this computer could not go back to its own copy yet.");+ return await work();+ } finally { held--; }+ },+ /** `request` (this computer's server) as the move may use it: while the clean workspace runs, what the frozen copy's own+ * files say, and everything else refused. */+ realCopy(request) {+ return async (route, init) => {+ if (!active()) return request(route, init);+ if ((init?.method ?? "GET").toUpperCase() === "GET") {+ if (route === "/api/move/freeze") return Response.json(marker());+ if (route === "/.well-known/openmausbot/environment") {+ const id = readOwn("environment-id")?.trim();+ return Response.json(id ? { environmentId: id } : {});+ }+ }+ throw Object.assign(new Error("This computer's own copy isn't running."), { code: CLEAN });+ };+ },+ };+}diff --git a/electron/clean-workspace.node-test.mjs b/electron/clean-workspace.node-test.mjsnew file mode 100644index 0000000000..7c69e0016c--- /dev/null+++ b/electron/clean-workspace.node-test.mjs@@ -0,0 +1,264 @@+import assert from "node:assert/strict";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import { cleanWorkspaceConfig, cleanWorkspaceDir, createCleanWorkspace } from "./clean-workspace.mjs";+import { cloudLendingVerdict } from "./computer-sharing.mjs";+import { createLendingTarget } from "./lending-target.mjs";+import { installOneHome } from "./one-home-main.mjs";+import { WELCOME_VERSION } from "./onboarding-record.mjs";++const CLOUD = "https://omb-t-1.fly.dev";+const json = (value, status = 200) => new Response(JSON.stringify(value), { status });++/** A computer's data folder on disk, frozen for My Cloud, with the one server the app runs at a time: `running`, and each+ * request as [the folder it reached, method, route]. */+function computer(t, { frozen = { v: 1, at: 1, cloud: CLOUD } } = {}) {+ const parent = mkdtempSync(join(tmpdir(), "omb-clean-"));+ t.after(() => rmSync(parent, { recursive: true, force: true }));+ const dataDir = join(parent, ".openmausbot");+ const w = { dataDir, cleanDir: cleanWorkspaceDir(dataDir), running: dataDir, swaps: [], requests: [], swapFails: false, changes: 0 };+ mkdirSync(dataDir, { recursive: true });+ w.write = (name, text) => { writeFileSync(join(dataDir, name), text); };+ w.clean = createCleanWorkspace({+ dataDir: () => dataDir, running: () => w.running,+ swap: async (dir) => { w.swaps.push(dir); if (w.swapFails) return { ok: false, error: "switch-failed" }; await new Promise((resolve) => setImmediate(resolve)); w.running = dir; return { ok: true }; },+ changed: () => { w.changes++; },+ });+ w.request = async (route, init) => { w.requests.push([w.running, (init?.method ?? "GET").toUpperCase(), route]); return json({ frozen: w.running === dataDir && Boolean(frozen) }); };+ if (frozen) w.write("moved.json", JSON.stringify(frozen));+ w.write("environment-id", "own-copy-id\n");+ return w;+}++test("a clean workspace sits beside the data folder, never in it: a move carries that folder and forgetting the copy empties it", () => {+ assert.equal(cleanWorkspaceDir("/Users/a/.openmausbot"), "/Users/a/.openmausbot-clean");+});++test("opening it starts the server on its own folder, once, set up so the new-user setup never shows", async (t) => {+ const w = computer(t);+ w.write("config.json", JSON.stringify({ language: "de", providers: { key: "secret-of-the-frozen-copy" } }));+ assert.equal(w.clean.active(), false);+ assert.equal(await w.clean.enter(), true);+ assert.deepEqual(w.swaps, [w.cleanDir]);+ assert.equal(w.clean.active(), true);+ assert.equal(w.changes, 1, "what depends on it (lending) looks again");+ const config = JSON.parse(readFileSync(join(w.cleanDir, "config.json"), "utf8"));+ assert.equal(config.language, "de");+ assert.equal(config.onboarding.version, WELCOME_VERSION);+ assert.ok(config.onboarding.completedAt);+ assert.equal(JSON.stringify(config).includes("secret"), false, "nothing but the language comes from the frozen copy's config");+ assert.equal(await w.clean.enter(), true);+ assert.deepEqual(w.swaps, [w.cleanDir], "open already: no second start");+});++test("whatever someone did there stays: opening it again never writes over its config, and leaving deletes nothing", async (t) => {+ const w = computer(t);+ await w.clean.enter();+ writeFileSync(join(w.cleanDir, "config.json"), JSON.stringify({ language: "fr", theirs: true }));+ assert.equal(await w.clean.leave(), true);+ assert.equal(w.running, w.dataDir);+ assert.equal(w.clean.active(), false);+ await w.clean.enter();+ assert.deepEqual(JSON.parse(readFileSync(join(w.cleanDir, "config.json"), "utf8")), { language: "fr", theirs: true });+ assert.equal(existsSync(join(w.dataDir, "moved.json")), true, "the frozen copy's marker is never touched");+});++test("leaving only ever swaps from the clean workspace, and a swap that fails says so", async (t) => {+ const w = computer(t);+ assert.equal(await w.clean.leave(), true);+ assert.deepEqual(w.swaps, [], "this computer's own copy already runs");+ w.swapFails = true;+ assert.equal(await w.clean.enter(), false, "the window then says why, as before");+ assert.equal(w.clean.active(), false);+ assert.equal(w.changes, 0);+});++test("a local environment the person chose is no frozen copy: it stays, and nothing is set up", async (t) => {+ const w = computer(t);+ w.running = `${w.dataDir}-work`;+ assert.equal(await w.clean.enter(), true);+ assert.deepEqual(w.swaps, []);+ assert.equal(existsSync(w.cleanDir), false);+});++test("it isn't for an app that can't sign in here", async (t) => {+ const w = computer(t);+ const off = createCleanWorkspace({ dataDir: () => w.dataDir, running: () => w.running, swap: async (dir) => { w.swaps.push(dir); return { ok: true }; }, allowed: () => false });+ assert.equal(await off.enter(), false);+ assert.deepEqual(w.swaps, []);+});++test("one swap at a time: open, leave and open again at once end where the last asked, each after the one before", async (t) => {+ const w = computer(t);+ const seen = await Promise.all([w.clean.enter(), w.clean.leave(), w.clean.enter()]);+ assert.deepEqual(seen, [true, true, true]);+ assert.deepEqual(w.swaps, [w.cleanDir, w.dataDir, w.cleanDir]);+ assert.equal(w.clean.active(), true);+});++test("the marker is the frozen copy's own, read from its folder whichever server runs", async (t) => {+ const w = computer(t, { frozen: { v: 1, at: 1, cloud: CLOUD, place: "Garage" } });+ await w.clean.enter();+ assert.deepEqual(w.clean.marker(), { frozen: true, cloud: CLOUD, place: "Garage" });+ w.write("moved.json", "not json");+ assert.deepEqual(w.clean.marker(), { frozen: true }, "as the server reads it: a marker it can't read is still frozen");+ rmSync(join(w.dataDir, "moved.json"));+ assert.deepEqual(w.clean.marker(), { frozen: false });+});++test("the move's server, while the clean workspace runs: the copy's own marker and identity from its files, everything else refused", async (t) => {+ const w = computer(t);+ const request = w.clean.realCopy(w.request);+ await request("/api/bots?messages=0");+ assert.deepEqual(w.requests, [[w.dataDir, "GET", "/api/bots?messages=0"]], "its own copy running: passed on");+ w.requests.length = 0;+ await w.clean.enter();+ assert.deepEqual(await (await request("/api/move/freeze")).json(), { frozen: true, cloud: CLOUD });+ assert.deepEqual(await (await request("/.well-known/openmausbot/environment")).json(), { environmentId: "own-copy-id" }, "the Admin never hears the clean folder's identity as this computer's");+ for (const [route, init] of [["/api/bots?messages=0"], ["/api/cloud-send?move=1"], ["/api/config"], ["/api/move/freeze", { method: "POST" }], ["/api/move/freeze", { method: "DELETE" }], ["/api/move/forget", { method: "POST" }], ["/api/workspace-backup/upload", { method: "POST" }]]) {+ await assert.rejects(request(route, init), { code: "clean-workspace" }, `${init?.method ?? "GET"} ${route}`);+ }+ assert.deepEqual(w.requests, [], "nothing reached the clean workspace's server");+});++test("what must reach the frozen copy brings its server back first, and nothing opens the clean workspace until it's done", async (t) => {+ const w = computer(t);+ await w.clean.enter();+ let release;+ const held = new Promise((resolve) => { release = resolve; });+ const lift = w.clean.holding(async () => {+ assert.equal(w.running, w.dataDir, "its own server, before the work");+ assert.equal(await w.clean.enter(), false, "the window asking meanwhile gets no clean workspace");+ assert.equal(w.running, w.dataDir);+ await held;+ return "lifted";+ });+ release();+ assert.equal(await lift, "lifted");+ assert.equal(await w.clean.enter(), true, "afterwards it opens again if it's still wanted");+ w.swapFails = true;+ await assert.rejects(w.clean.holding(async () => assert.fail("never on the clean workspace")), /could not go back/u);+});++/** One home on the real journal and the real clean workspace: every request that reaches this computer's server is recorded,+ * with the folder it reached. `state`: the sign-in. */+function moved(t, { state, journal = null, marker, gone = null, version = "0.1.141" } = {}) {+ const w = computer(t, marker === undefined ? {} : { frozen: marker });+ w.journal = journal;+ w.state = state;+ w.lent = [];+ w.fetches = [];+ w.main = installOneHome({+ ipcMain: { handle: () => {} }, cloudPage: () => "local", server: () => null, clean: w.clean,+ home: () => ({ origin: CLOUD, grant: async () => ({ origin: CLOUD, code: "AAAA", expiresAt: Date.now() + 60_000 }) }),+ cookieFetch: async (url) => { w.fetches.push(String(url)); return json({ v: 1, items: [], bots: [] }); },+ reconnect: async () => false, power: { asleep: () => false }, file: () => join(w.dataDir, "..", "cloud-send.json"), window: () => null, localOrigin: () => "http://127.0.0.1:4100",+ fetch: async (url) => { w.fetches.push(String(url)); return json({ error: "no" }, 500); }, localRequest: w.request,+ account: () => ({ state: () => w.state, pairHome: async () => ({ origin: CLOUD, code: "AAAA" }), movedTo: async () => gone }),+ journalFile: () => join(w.dataDir, "..", "one-home.json"), tempRoot: () => join(w.dataDir, "..", "temp"), journal: { read: () => w.journal, write: (value) => { w.journal = value; } },+ keep: { read: () => null, write: () => {} }, lend: async (projects) => { w.lent.push(projects); }, phone: { paired: () => false, stop: async () => {}, start: async () => {} },+ version, log: () => {},+ });+ t.after(() => w.main.close());+ return w;+}+const owner = { id: "acct-1", email: "[email protected]" };+const ready = (extra = {}) => ({ status: "connected", account: owner, deviceId: "d1", entitlement: { plan: "pro", status: "active" }, machine: { status: "ready", origin: CLOUD, moves: true }, ...extra });+const done = (extra = {}) => ({ v: 1, phase: "done", cloud: { origin: CLOUD, account: owner.id, machine: CLOUD }, startedAt: 1, doneAt: 2, frozenAt: 2, version: "0.1.140", reported: "d1", lent: true, phoneStopped: true, ...extra });+const onClean = (w) => w.requests.filter(([folder]) => folder === w.cleanDir);++test("a top-up can't read the clean workspace: it waits, and nothing of it reaches the person's Cloud", async (t) => {+ const w = moved(t, { state: ready(), journal: done() });+ await w.clean.enter();+ await w.main.kick();+ assert.deepEqual(onClean(w), []);+ assert.equal(w.journal.version, "0.1.140", "the top-up didn't count as made");+ assert.ok(w.journal.retryAt, "and goes again later");+ await w.clean.leave();+ w.requests.length = 0;+ w.journal = done();+ await w.main.kick();+ assert.deepEqual(w.requests[0], [w.dataDir, "GET", "/api/cloud-send?move=1"], "its own copy running, the same top-up does read this computer's server");+});++test("settling can't record this computer as lent from the clean workspace's empty bot list", async (t) => {+ const w = moved(t, { state: { status: "signed-out" }, journal: done({ lent: undefined }) });+ await w.clean.enter();+ await w.main.kick();+ assert.deepEqual(onClean(w), []);+ assert.deepEqual(w.lent, []);+ assert.equal(w.journal.lent, undefined);+ await w.clean.leave();+ await w.main.kick();+ assert.deepEqual(w.lent, [[]], "its own copy running, it lends what's there");+ assert.equal(w.journal.lent, true);+});++test("a send can't read the clean workspace", async (t) => {+ const w = moved(t, { state: ready(), journal: done() });+ await w.clean.enter();+ await assert.rejects(w.main.move({ final: true }));+ assert.deepEqual(onClean(w), []);+});++test("no first move and no freeze from the clean workspace: the frozen copy's own marker still says frozen", async (t) => {+ const w = moved(t, { state: ready(), journal: null });+ await w.clean.enter();+ await w.main.kick();+ assert.equal(w.journal, null, "no move started");+ assert.deepEqual(onClean(w), []);+ assert.deepEqual(w.main.oneHome.facts().noted, "frozen_without_move");+});++test("another account leaves the journal alone, and nothing reaches the clean workspace", async (t) => {+ const w = moved(t, { state: ready({ account: { id: "acct-2", email: "[email protected]" } }), journal: done() });+ await w.clean.enter();+ const before = structuredClone(w.journal);+ await w.main.kick();+ assert.deepEqual(w.journal, before);+ assert.deepEqual(onClean(w), []);+});++test("a Cloud that's gone still brings this computer home from the clean workspace: the lift reaches the frozen copy, not the clean one", async (t) => {+ const elsewhere = "https://omb-other-2.fly.dev";+ const w = moved(t, { state: ready({ machine: { status: "ready", origin: elsewhere, moves: true } }), journal: null, gone: "deleted" });+ await w.clean.enter();+ await w.main.kick();+ assert.deepEqual(onClean(w), []);+ assert.deepEqual(w.requests.filter(([, method]) => method === "DELETE"), [[w.dataDir, "DELETE", "/api/move/freeze"]]);+ assert.equal(w.running, w.dataDir);+ assert.equal(w.journal.phase, "back");+});++test("forgetting the copy reaches the frozen copy only, and never empties the clean workspace", async (t) => {+ const w = moved(t, { state: ready(), journal: done({ doneAt: 2, version: "0.1.141" }) });+ await w.clean.enter();+ writeFileSync(join(w.cleanDir, "made-here.txt"), "mine");+ await w.main.kick();+ assert.deepEqual(w.requests.filter(([, , route]) => route === "/api/move/forget"), [[w.dataDir, "POST", "/api/move/forget"]]);+ assert.deepEqual(onClean(w), []);+ assert.equal(readFileSync(join(w.cleanDir, "made-here.txt"), "utf8"), "mine");+});++test("a clean workspace's first config carries the language and that the setup was seen, nothing else", () => {+ assert.deepEqual(Object.keys(cleanWorkspaceConfig("en")).sort(), ["language", "onboarding"]);+ assert.equal(cleanWorkspaceConfig().language, undefined);+});++test("no lending from the clean workspace: nothing is lent or asked while it runs, and a grant only pauses, so it goes on after", async (t) => {+ const w = computer(t);+ const env = { id: "c", origin: CLOUD, cloud: { id: "c" } };+ const state = { status: "connected", account: owner, machine: { status: "ready", origin: CLOUD } };+ const target = createLendingTarget({ account: () => (w.clean.active() ? null : { state: () => state, isOwnCloud: () => true, ownClouds: () => [] }), environments: () => [env] });+ const grant = { accountId: owner.id, origin: CLOUD };+ assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true });+ await w.clean.enter();+ assert.equal(target.environment(), null);+ assert.deepEqual(target.places(), []);+ assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { pause: "unverified" });+ await w.clean.leave();+ assert.deepEqual(cloudLendingVerdict(grant, target.cloud(env), env), { allow: true });+});diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjsindex 982e5b95ac..26fd30a4ac 100644--- a/electron/fixtures/home-window-world.mjs+++ b/electron/fixtures/home-window-world.mjs@@ -18,7 +18,7 @@ export const json = (body, status = 200, headers = {}) => new Response(JSON.stri* sign-in (its power word, wake, pairing code), My Cloud's answers (`cloud`), the window (where it went), the startup* screen and a manual clock.*/-export function world({ journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null, ownMove = null } = {}) {+export function world({ clean = null, journal = done(), marker = null, state = connected(), power = null, cloud = {}, team = {}, client = {}, splash = true, url = "", remembered = null, ownMove = null } = {}) {const w = {journal, marker, state, power, ownMove, clock: 1_000_000, typed: 0, now: () => w.clock,cloud: { down: false, signedIn: true, version: "0.1.130", health: 200, wakes: true, ...cloud },@@ -76,6 +76,7 @@ export function world({ journal = done(), marker = null, state = connected(), po},};w.home = createHomeWindow({+ clean,journal: () => w.journal,frozen: async () => w.marker,ownMove: () => w.ownMove,diff --git a/electron/home-window-clean.node-test.mjs b/electron/home-window-clean.node-test.mjsnew file mode 100644index 0000000000..1fa2c21102--- /dev/null+++ b/electron/home-window-clean.node-test.mjs@@ -0,0 +1,181 @@+import assert from "node:assert/strict";+import test from "node:test";++import { homeOf, noWayHome } from "./home-window.mjs";+import { ACCOUNT, ACME, CLIENT, CLIENT_A, CLOUD, connected, done, LOCAL, world } from "./fixtures/home-window-world.mjs";++// The window of a computer whose bots moved, when nobody here can reach them (clean-workspace.mjs): the clean workspace opens+// in place of the sign-in screen, and a person who can reach them never gets it, whatever is wrong with the connection.+function cleanSide() {+ const side = { on: false, enters: 0, leaves: 0, fails: false, order: [],+ active: () => side.on,+ enter: async () => { side.enters++; side.order.push("enter"); if (side.fails) return false; side.on = true; return true; },+ leave: async () => { side.leaves++; side.order.push("leave"); side.on = false; return true; } };+ return side;+}+const signedOut = { status: "signed-out" };+const other = () => ({ ...connected(), account: { id: "acct-2", email: "[email protected]" } });++test("the clean workspace is for nobody signed in, or an account with no way to the Cloud; nothing else", () => {+ const cases = [+ ["signed out", { journal: done(), state: signedOut }, true],+ ["no sign-in at all", { journal: done(), state: null }, true],+ ["a sign-in on its way", { journal: done(), state: { status: "connecting" } }, true],+ ["another account", { journal: done(), state: other() }, true],+ ["another account, with the Admin not answering", { journal: done(), state: { status: "unavailable", account: { id: "acct-2" } } }, true],+ ["a freeze for another Cloud", { frozenCloud: "https://omb-t-2.fly.dev", state: connected() }, true],+ ["signed in, with no Cloud a freeze can name", { frozenCloud: true, state: { status: "connected", account: ACCOUNT, machine: null } }, true],+ ["a sign-in still being read", { journal: done(), state: { status: "signed-out", message: "restoring" } }, false],+ ["the owner", { journal: done(), state: connected() }, false],+ ["the owner's sign-in ended", { journal: done(), state: { status: "reauth-required", account: ACCOUNT } }, false],+ ["the Admin not answering", { journal: done(), state: { status: "unavailable", account: ACCOUNT } }, false],+ ["the Admin not answering, and no Cloud a freeze can name", { frozenCloud: true, state: { status: "unavailable", account: ACCOUNT } }, false],+ ["never moved", { state: signedOut }, false],+ ];+ for (const [name, input, expected] of cases) assert.equal(noWayHome(homeOf(input), input.state), expected, name);+});++test("signed out: the clean workspace opens on this computer, never the sign-in screen, and nothing asks the Cloud or the Admin", async () => {+ const clean = cleanSide(), w = world({ clean, state: signedOut, url: "" });+ await w.home.show();+ assert.equal(clean.enters, 1);+ assert.deepEqual(w.local, [true], "this computer's page, with no window page to leave");+ assert.deepEqual([w.went, w.fetched, w.pairs], [[], [], 0]);+ assert.equal(w.home.cloudOrigin(), null);+ assert.equal(w.home.current().clean, true);+ assert.equal(w.home.current().kind, "computer");+});++test("another account with no way to that Cloud gets the same, and the journal's Cloud is never asked", async () => {+ const clean = cleanSide(), w = world({ clean, state: other() });+ await w.home.show();+ assert.equal(clean.enters, 1);+ assert.deepEqual([w.went, w.fetched, w.pairs], [[], [], 0]);+ assert.equal(w.home.current().other, true);+});++test("it survives a restart: a new launch with the same journal, or only the freeze marker, opens it again", async () => {+ for (const setup of [{ state: signedOut }, { state: signedOut, journal: null, marker: { frozen: true, cloud: CLOUD } }, { state: signedOut, journal: null, marker: { frozen: true } }]) {+ const clean = cleanSide(), w = world({ clean, ...setup });+ await w.home.show();+ assert.equal(clean.enters, 1, JSON.stringify(setup));+ assert.deepEqual(w.went, []);+ }+});++test("signing back in as the owner goes to that Cloud as ever, with this computer's own copy running first", async () => {+ const clean = cleanSide(), w = world({ clean, state: signedOut });+ await w.home.show();+ w.state = connected();+ await w.home.changed();+ assert.deepEqual(clean.order, ["enter", "leave"]);+ assert.equal(clean.on, false);+ assert.deepEqual(w.went, [[CLOUD, CLOUD]]);+ assert.equal(w.home.cloudOrigin(), CLOUD);+ assert.equal(w.home.current().clean, undefined);+});++test("signed in and the Cloud doesn't answer: the normal can't-be-reached screen, never the clean workspace, so nobody thinks their bots are gone", async () => {+ const clean = cleanSide(), w = world({ clean, state: signedOut });+ await w.home.show();+ w.state = connected();+ w.cloud.down = true;+ await w.home.changed();+ assert.equal(clean.on, false);+ assert.equal(w.home.view().screen, "offline");+ assert.equal(clean.enters, 1, "it isn't opened again");+ w.state = { status: "unavailable", account: ACCOUNT };+ await w.home.show();+ assert.equal(clean.enters, 1, "nor when the Admin doesn't answer either");+ assert.equal(w.home.view().screen, "offline");+});++test("a launch while the sign-in is still being read never opens it", async () => {+ const clean = cleanSide(), w = world({ clean, state: { status: "signed-out", message: "restoring" } });+ await w.home.show();+ assert.equal(clean.enters, 0);+ assert.equal(w.home.view().screen, "signin");+});++test("a sign-in that ended keeps today's Sign in screen: that person didn't choose to leave, and their bots are one sign-in away", async () => {+ const clean = cleanSide(), w = world({ clean, state: { status: "reauth-required", account: ACCOUNT } });+ w.cloud.signedIn = false;+ await w.home.show();+ assert.equal(clean.enters, 0);+ assert.equal(w.home.view().screen, "signin");+});++test("the clean workspace that can't start is the sign-in screen, as before", async () => {+ const clean = cleanSide(), w = world({ clean, state: other() });+ clean.fails = true;+ await w.home.show();+ assert.deepEqual(w.home.view(), { screen: "signin", other: true });+ assert.deepEqual(w.local, []);+});++test("without a clean workspace (an app that can't sign in here), nothing changes", async () => {+ const w = world({ state: signedOut });+ await w.home.show();+ assert.equal(w.home.current().kind, "signin");+ assert.equal(w.home.view().screen, "signin");+});++test("signed out with a place remembered: the clean workspace opens, and the place is still there once they're back", async () => {+ const remembered = { team: ACME.id, name: ACME.name, origin: "https://omb-u-acme.fly.dev" };+ const clean = cleanSide(), w = world({ clean, state: signedOut, remembered });+ await w.home.show();+ assert.equal(clean.enters, 1);+ assert.deepEqual(w.remembers, []);+ assert.deepEqual(w.teamPairs, []);+ assert.deepEqual(w.went, []);+});++test("from the clean workspace, this account's own Clouds open as they do for anyone: My Cloud, and another of its own", async () => {+ const mine = { ...other(), machine: { status: "ready", origin: CLIENT }, clouds: [{ ...CLIENT_A, id: "own", primary: true }, { ...CLIENT_A, id: "c-b", origin: "https://omb-c-b.fly.dev", name: "Client B" }] };+ const clean = cleanSide(), w = world({ clean, state: mine });+ await w.home.show();+ assert.equal(clean.enters, 1);+ await w.home.openCloud();+ assert.equal(w.went.at(-1)?.[1], CLIENT, "its My Cloud");+ assert.equal(clean.on, true, "the frozen copy stays stopped");+ assert.equal(clean.leaves, 0);+ await w.home.show({ place: { cloud: "c-b" } });+ assert.equal(w.went.at(-1)?.[1], "https://omb-c-b.fly.dev");+ assert.equal(clean.on, true);+});++test("the Sign in that switches account ends this sign-in first, as the screen's did", async () => {+ const clean = cleanSide(), w = world({ clean, state: other() });+ await w.home.show();+ await w.home.signIn();+ assert.deepEqual(w.signIns, ["out", "begin"]);+ w.signIns.length = 0;+ const owner = world({ clean: cleanSide(), state: connected() });+ await owner.home.signIn();+ assert.deepEqual(owner.signIns, [], "still good: it only looks again");+});++test("signing out of a moved computer's Cloud leaves it for the clean workspace at once", async () => {+ const clean = cleanSide(), w = world({ clean, state: connected(), url: `${CLOUD}/` });+ await w.home.show();+ assert.equal(clean.enters, 0);+ w.state = signedOut;+ await w.home.changed();+ assert.equal(clean.enters, 1);+ assert.deepEqual(w.local.at(-1), true, "the window leaves the Cloud's page");+ assert.equal(w.url, `${LOCAL}/`);+});++test("the move's word changing while nobody's signed in moves the window too, both ways", async () => {+ const clean = cleanSide(), w = world({ clean, journal: null, state: signedOut });+ await w.home.show();+ assert.equal(clean.enters, 0, "never moved: this computer as ever");+ w.journal = done();+ await w.home.changed();+ assert.equal(clean.enters, 1);+ assert.equal(clean.on, true);+ w.journal = { ...done(), phase: "back" };+ await w.home.changed();+ assert.equal(clean.on, false, "home again: this computer's own copy, not the clean workspace");+ assert.equal(w.home.current().clean, undefined);+});diff --git a/electron/home-window.d.mts b/electron/home-window.d.mtsindex 5e48934992..c9cb248a3e 100644--- a/electron/home-window.d.mts+++ b/electron/home-window.d.mts@@ -61,6 +61,7 @@ export function splashText(status: "opening" | "waking", name?: string | null):export function placeOf(input: { ask?: HomeAsk; remembered?: RememberedPlace; state?: any }): { kind: "cloud"; left?: string | null } | { kind: "team" | "own"; id: string; name: string; role: string | null; origin: string | null; machine: any };export function homeOf(input: { journal?: any; frozenCloud?: string | true | null; state?: any }): Home;+export function noWayHome(worked: Home, state?: any): boolean;export function routeOf(url: string, origin: string): string | null;interface WindowLike { isDestroyed(): boolean; webContents: { id: number; getURL(): string; reload(): void; mainFrame?: unknown } }@@ -109,6 +110,7 @@ export function createHomeWindow(deps: {power: { asleep(): boolean; hold(): void; woke(): void };go(url: string, origin: string | null, place: HomePlace | null): unknown;showLocal(leaving: boolean): unknown;+ clean?: import("./clean-workspace.mjs").CleanWorkspace | null;remembered?(): RememberedPlace;remember?(place: { team: string } | { cloud: string } | null): void;left?(name: string): void;diff --git a/electron/home-window.mjs b/electron/home-window.mjsindex 64d3d3b3c5..7705af4cee 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -84,6 +84,14 @@ export function homeOf({ journal = null, frozenCloud = null, state = null }) {return { kind: "cloud", origin };}+/** Nobody here can reach the bots: nobody is signed in, or the account signed in has no way to their Cloud, so the clean+ * workspace opens (clean-workspace.mjs). An account the Admin can't be asked about isn't that, nor a sign-in still being read:+ * those are a Cloud that can't be reached yet, never an empty workspace that reads as their bots being gone. */+export function noWayHome(worked, state) {+ if (worked.kind !== "signin" || state?.message === "restoring") return false;+ return worked.other === true || !state?.account?.id || ["signed-out", "connecting", "connected"].includes(state.status);+}+/** A place besides My Cloud: a team's Cloud, or another Cloud of the person's own (`own`), each the session's. */export const otherPlace = (place) => place?.kind === "team" || place?.kind === "own";@@ -206,7 +214,7 @@ export function routeOf(url, origin) {* out changed.*/export function createHomeWindow(deps) {- const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal,+ const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal, clean = null,remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },splash = () => null, lastInput = () => 0, publish = () => {}, rehomed = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {} } = deps;@@ -244,8 +252,10 @@ export function createHomeWindow(deps) {}if (frozenCloud || awayIn(kept)) await restored();const before = home;- home = homeOf({ journal: kept, frozenCloud, state: state() });- if (home.kind !== before.kind || home.origin !== before.origin) {+ const worked = homeOf({ journal: kept, frozenCloud, state: state() });+ // Home is this computer then, in its clean workspace, so a Cloud of this account's own opens from it as for anyone.+ home = clean && noWayHome(worked, state()) ? { kind: "computer", clean: true, ...(worked.other ? { other: true } : {}) } : worked;+ if (home.kind !== before.kind || home.origin !== before.origin || home.clean !== before.clean) {try { rehomed(home); } catch {}}return home;@@ -485,7 +495,10 @@ export function createHomeWindow(deps) {const token = ++opens;const current = await refresh();if (!wanted(token)) return;- const target = placeOf({ ask: place, remembered: remembered(), state: state() });+ // This computer's own copy is the server again before anything of the person's Cloud opens.+ if (!current.clean && clean?.active()) { await clean.leave(); if (!wanted(token)) return; }+ // Nobody signed in has nothing to open but the clean workspace; the place stays remembered for when they're back.+ const target = current.clean && signedOut() ? { kind: "cloud" } : placeOf({ ask: place, remembered: remembered(), state: state() });if (target.kind === "cloud" && target.left) { left(target.left); remember(null); }if (otherPlace(target)) {ensureWindow();@@ -514,6 +527,8 @@ export function createHomeWindow(deps) {asked = null; naming = null;}if (current.kind === "computer") {+ if (current.clean && !(await clean.enter())) { if (wanted(token)) { ensureWindow(); clearRetry(); toScreen({ screen: "signin", ...(current.other ? { other: true } : {}) }); } return; }+ if (!wanted(token)) return;clearRetry(); screen = null; status = null; shown = null;const win = window();const leaving = away || Boolean(win && !win.isDestroyed() && !originOf(win.webContents.getURL()));@@ -625,7 +640,7 @@ export function createHomeWindow(deps) {if (status === "connecting") return void await client.reopen?.();if (status !== "signed-out") {const current = await refresh();- if (!(current.kind === "signin" && current.other)) return void await show();+ if (!current.other) return void await show();await client.signOut?.();}await client.begin();@@ -638,7 +653,7 @@ export function createHomeWindow(deps) {const after = await refresh();const next = shown && shows(shown.origin) ? placeOf({ remembered: remembered(), state: state() }) : null;const moved = Boolean(next && (next.kind !== shown.kind || (next.origin ?? null) !== (shown.origin ?? null) || (next.id ?? null) !== (shown.id ?? null)));- if (moved || after.kind !== before.kind || after.origin !== before.origin || screen || status) await show();+ if (moved || after.kind !== before.kind || after.origin !== before.origin || after.clean !== before.clean || screen || status) await show();},/** The signed-in account is about to change: nothing under way for the one leaving goes on, and the next show() takes* the window off whatever it shows of that account. */diff --git a/electron/main.mjs b/electron/main.mjsindex 5864348509..a3369f3856 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -104,7 +104,7 @@ import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createClouimport { installCloudFiles } from "./cloud-sync-main.mjs";import { createCloudEntry } from "./cloud-entry.mjs";import { createLendingTarget } from "./lending-target.mjs"; import { createOpenAtLogin, installOpenAtLogin } from "./open-at-login.mjs";-import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";+import { createCleanWorkspace } from "./clean-workspace.mjs"; import { installOneHome } from "./one-home-main.mjs"; import { handSaved, installOwnHome } from "./own-home-main.mjs"; import { serverOpens } from "./saved-server.mjs"; import { installTwoPlacesMain } from "./two-places-main.mjs";import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";@@ -1468,7 +1468,7 @@ function sharingController() {return computerSharing;}-const lendingTarget = createLendingTarget({ account: () => cloudAccount, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });+const cleanWorkspace = createCleanWorkspace({ dataDir: desktopDataDir, running: () => runningDataDir, swap: dir => switchLocalEnvironmentTo(dir, LOCAL_ID, true), allowed: () => app.isPackaged && !desktopRemoteAccess, changed: () => computerSharing?.cloudChanged(), log: slog }); const lendingTarget = createLendingTarget({ account: () => (cleanWorkspace.active() ? null : cloudAccount), environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });const screenControl = createScreenControl({ connection: () => cuaReady, remote: () => Boolean(desktopRemoteAccess), request: requestComputerUse, log: slog });let screenAskedAt = -Infinity;/** Computer control starts again, as Settings' Retry does, which asks macOS for what it never asked; at most every 10 minutes. */@@ -1590,7 +1590,7 @@ function acquireDataDirLeaseFor(dir) {}/** Pause the supervisor first, or its recovery forks on the wrong data dir; resume() stays in the finally. */-async function switchLocalEnvironmentTo(targetDir, targetId) {+async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {if (!app.isPackaged) return { ok: false, error: "dev" };// A second switch would be un-paused by the first's finally mid-handoff.if (localSwitchInFlight) return { ok: false, error: "busy" };@@ -1598,7 +1598,7 @@ async function switchLocalEnvironmentTo(targetDir, targetId) {let startedProc = null;let switchSucceeded = false;const failedSwitch = () => {- dialog.showErrorBox(+ if (!quiet) dialog.showErrorBox("Could not switch environments","OpenMausBot could not switch to that environment. The app log has the details.",);@@ -1691,7 +1691,7 @@ async function switchEnvironment(id) {if (entry?.team || entry?.cloud) return void await showHome({ place: entry.team ? { team: entry.team.id, name: entry.name } : { cloud: entry.cloud.id, name: entry.name } });homePlaces.remember(null);if (entry?.kind === "local") return await switchLocalEnvironmentTo(entry.dataDir, entry.id);- if (id === LOCAL_ID && (runningDataDir ?? desktopDataDir()) !== desktopDataDir()) {+ if (id === LOCAL_ID && (runningDataDir ?? desktopDataDir()) !== desktopDataDir() && !cleanWorkspace.active()) {return await switchLocalEnvironmentTo(desktopDataDir(), LOCAL_ID);}if (entry && entry.origin === homeWindow.cloudOrigin()) return void await showHome({ place: "cloud" });@@ -1714,7 +1714,7 @@ function createLocalEnvironment(name, dataDir) {? name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""): "";if (typeof name !== "string" || !name.trim()) return { ok: false, error: "name", state };- candidateDir = path.join(os.homedir(), `.openmausbot-${slug || randomUUID().slice(0, 8)}`);+ candidateDir = path.join(os.homedir(), `.openmausbot-${slug && slug !== "clean" ? slug : randomUUID().slice(0, 8)}`);} else {candidateDir = typeof dataDir === "string" ? dataDir.trim() : "";if (@@ -2657,10 +2657,10 @@ 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, cloudPage: cloudPageAsking, 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 }); ownHome = installOwnHome({ 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({ 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, 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 }); ownHome = installOwnHome({ 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({ 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({ journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,+const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), ensureWindow: () => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); },localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog,hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")), ownMove: () => ownHome?.underWay() ?? null,@@ -2778,7 +2778,7 @@ ipcMain.handle("environments:forget", localWorkspaceOnly("environments:forget",// Once My Cloud is home the switcher lists only whole places, and shows only when there is more than My Cloud.const homeAlone = () => Boolean(homeWindow.cloudOrigin()) && !otherPlaces(environmentsState, homeWindow.cloudOrigin());ipcMain.handle("workspaces:state", workspaceOnly(event => ({ ...workspaceSummary(environmentsState), ...(homeAlone() && homeWindow.homePage(event) ? { home: true } : {}) })));-ipcMain.handle("workspaces:line", workspaceOnly(() => homePlaces.line()));+ipcMain.handle("workspaces:line", workspaceOnly(event => (cleanWorkspace.active() && senderIsLocal(event) ? { kind: "clean" } : homePlaces.line())));let workspaceMenuOpen = false;ipcMain.handle("workspaces:menu", workspaceOnly(async (_event, from) => {if (workspaceMenuOpen || homeAlone()) return;@@ -3106,7 +3106,7 @@ app.whenReady().then(async () => {cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).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()) {+ if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away() && !cleanWorkspace.marker().frozen) {// Retries stop once the person turns the phone off, starts it by hand or quits.const wanted = () => !desktopShutdownStarted && companionEnabledAtRest() && !companionRunning() && !oneHome.away() && !ownHome?.away();void autoStartCompanion({ restored: managedDesktop?.whenRestored(), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }), wanted, log: slog });diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjsindex 039fa50c0f..9222c6c93f 100644--- a/electron/one-home-main.mjs+++ b/electron/one-home-main.mjs@@ -117,7 +117,9 @@ async function answer(response) {* keep?: { read(): unknown, write(value: unknown): void },* reportTimers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void },* other?(): null | { view(): unknown, seen(): unknown, retry(): Promise<unknown>, active(): boolean },- * }} deps `localRequest`: this computer's server, as its owner (main adds the owner's header). `account`: the MausBot+ * clean?: import("./clean-workspace.mjs").CleanWorkspace | null,+ * }} deps `localRequest`: this computer's server, as its owner (main adds the owner's header), and only its own copy while `clean`+ * (the clean workspace) runs. `account`: the MausBot* Cloud sign-in (cloud-account.mjs). `journal`: where the move's journal is kept, journalFile by default; `keep`: the* person's choice to keep this computer's bots here, one-home-keep.json beside it by default. `openTeam`:* shows a team's page, where a bot moved into it from My Cloud now lives (team-move-main.mjs, whose journal is@@ -126,9 +128,11 @@ async function answer(response) {* while it is chosen no move to My Cloud starts, and its line is the one this computer's page shows. The rest are* installCloudSend's.*/-export function installOneHome({ localRequest, account, journalFile, tempRoot, lend, phone, openHome, openLocal, restart, version, log = () => {}, journal: kept, keep: keptChoice, openTeam, teamJournal,+export function installOneHome({ localRequest: anyServer, clean = null, account, journalFile, tempRoot, lend, phone, openHome, openLocal, restart, version, log = () => {}, journal: kept, keep: keptChoice, openTeam, teamJournal,reportTimers, other = () => null, ...sendDeps }) {const fetchImpl = sendDeps.fetch ?? globalThis.fetch;+ const localRequest = clean ? clean.realCopy(anyServer) : anyServer;+ const onOwnCopy = (work) => (clean ? clean.holding(work) : work());let home = null;let lastInput = 0;const watched = new WeakSet();@@ -225,13 +229,13 @@ export function installOneHome({ localRequest, account, journalFile, tempRoot, l...local,freeze: async (origin) => freezeAnswer(await local.call("POST", "/api/move/freeze", { cloud: origin })),async unfreeze(options) {- const got = await local.call("DELETE", "/api/move/freeze", options?.automations === "off" ? { automations: "off" } : undefined);+ const got = await onOwnCopy(() => local.call("DELETE", "/api/move/freeze", options?.automations === "off" ? { automations: "off" } : undefined));if (!got.ok) throw Object.assign(new Error("OpenMausBot on this computer could not go on again."), { status: got.status });},frozen: async () => (await local.json("/api/move/freeze"))?.frozen === true,marker: () => local.json("/api/move/freeze"),async forget() {- const got = await local.call("POST", "/api/move/forget");+ const got = await onOwnCopy(() => local.call("POST", "/api/move/forget"));if (!got.ok) throw Object.assign(new Error("This computer's copy could not be deleted."), { status: got.status });},},diff --git a/src/components/HomeLine.test.ts b/src/components/HomeLine.test.tsindex 0fb2e1f63e..72c4a1d795 100644--- a/src/components/HomeLine.test.ts+++ b/src/components/HomeLine.test.ts@@ -9,7 +9,11 @@ import { HomeLine, homeLineText } from "./HomeLine";let host: HTMLDivElement;let root: Root;const place = vi.hoisted(() => ({ set: [] as Array<string | null> }));+const ais = vi.hoisted(() => ({ instances: [] as unknown[] }));vi.mock("@/lib/notify", () => ({ setNotificationPlace: (name: string | null) => place.set.push(name) }));+vi.mock("@/state/store", () => ({ useStore: () => ({ state: { instances: ais.instances } }) }));+vi.mock("@/components/onboarding/ConnectAi", () => ({ ConnectAiDialog: () => createElement("div", { "data-connect-ai": "" }) }));+vi.mock("@/components/EngineLibrary", () => ({ engineReady: (instance: { ready?: boolean }) => instance.ready === true }));const mount = async (line: ReturnType<typeof vi.fn>, remote = false, state: Record<string, unknown> = { local: false, name: "My Cloud" }) => {window.ogb = { workspaces: { state: vi.fn().mockResolvedValue(state), menu: vi.fn(), line }, ...(remote ? { remoteClient: { active: true } } : {}) } as unknown as typeof window.ogb;flushSync(() => root.render(createElement(HomeLine)));@@ -54,3 +58,28 @@ it("a team's page names its notifications after the team; My Cloud's names none"await mount(vi.fn().mockResolvedValue(null));await vi.waitFor(() => expect(place.set).toEqual(["Acme", null]));});++it("the clean workspace's line says the bots are safe in their Cloud, on every load, with no Sign in button: that stays in the You menu", async () => {+ ais.instances = [{ ready: true, instanceId: "claude", driver: "claudeCode" }];+ const line = vi.fn().mockResolvedValue({ kind: "clean" });+ await mount(line);+ await vi.waitFor(() => expect(host.querySelector("[data-home-line='clean']")?.textContent).toBe("Your bots are in your Cloud. Sign in to get them."));+ expect(host.querySelector("button")).toBeNull();+ expect(homeLineText({ kind: "clean" })).toBe("Your bots are in your Cloud. Sign in to get them.");+});++it("with the new-user setup skipped, the clean workspace still offers connecting an AI while none is ready", async () => {+ ais.instances = [{ ready: false, instanceId: "claude", driver: "claudeCode" }];+ await mount(vi.fn().mockResolvedValue({ kind: "clean" }));+ await vi.waitFor(() => expect(host.querySelector("[data-home-line-ai]")?.textContent).toBe("Connect an AI"));+ expect(host.querySelector("[data-connect-ai]")).toBeNull();+ flushSync(() => (host.querySelector("[data-home-line-ai]") as HTMLButtonElement).click());+ expect(host.querySelector("[data-connect-ai]")).not.toBeNull();+});++it("a team's line never offers it", async () => {+ ais.instances = [];+ await mount(vi.fn().mockResolvedValue({ kind: "left", name: "Acme" }));+ await vi.waitFor(() => expect(host.querySelector("[data-home-line='left']")).not.toBeNull());+ expect(host.querySelector("[data-home-line-ai]")).toBeNull();+});diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsxindex ad2e4e6d54..f0d4feedac 100644--- a/src/components/HomeLine.tsx+++ b/src/components/HomeLine.tsx@@ -1,18 +1,35 @@import { useEffect, useState } from "react";-import { Users } from "lucide-react";+import { Cloud, Users } from "lucide-react";+import { freeFallback } from "../../shared/ai-ranking";+import { engineReady } from "@/components/EngineLibrary";+import { ConnectAiDialog } from "@/components/onboarding/ConnectAi";import { t } from "@/lib/i18n";import { setNotificationPlace } from "@/lib/notify";+import { useStore } from "@/state/store";-type Line = { kind: "left"; name: string };+type Line = { kind: "left"; name: string } | { kind: "clean" };-/** The words for main's one line: a team this person is no longer in. */+/** The words for main's one line: a team this person is no longer in, or that the clean workspace isn't where their bots went. */export function homeLineText(line: Line): string {- return t("homeLine.left", { name: line.name });+ return line.kind === "clean" ? t("homeLine.clean") : t("homeLine.left", { name: line.name });+}++/** The clean workspace skips the new-user setup, so connecting an AI is offered here while none is ready. Nothing is sent to+ * test one: nothing starts by itself in this workspace. */+function ConnectAiLink() {+ const { state } = useStore();+ const [open, setOpen] = useState(false);+ if (state.instances.some((instance) => engineReady(instance) && !freeFallback(instance))) return null;+ return <>+ <button type="button" data-home-line-ai className="underline underline-offset-2 hover:text-ink" onClick={() => setOpen(true)}>{t("onboarding.meet.connectAi")}</button>+ {open && <ConnectAiDialog tested={null} onClose={() => setOpen(false)} />}+ </>;}/** In the desktop app, never in a browser: one plain line main has for the next page, served once (home-places.mjs):* after a team dropped this person, that they are no longer in it. Nothing to press; it goes with the page. (Who can- * see a team's private chats is said in the chat itself, by the team's own page.) */+ * see a team's private chats is said in the chat itself, by the team's own page.) Or, for as long as the clean workspace+ * runs (clean-workspace.mjs), that the person's bots are safe in their Cloud; Sign in stays in the You menu. */export function HomeLine() {const bridge = !window.ogb?.remoteClient?.active ? window.ogb?.workspaces : undefined;const [line, setLine] = useState<Line | null>(null);@@ -26,7 +43,8 @@ export function HomeLine() {}, [bridge]);if (!line) return null;return <div role="status" data-home-line={line.kind} className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">- <Users size={14} aria-hidden="true" />+ {line.kind === "clean" ? <Cloud size={14} aria-hidden="true" /> : <Users size={14} aria-hidden="true" />}<span dir="auto">{homeLineText(line)}</span>+ {line.kind === "clean" && <ConnectAiLink />}</div>;}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 22f8bd6d47..d1cd03ba70 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7092,6 +7092,7 @@"homeScreen.planNamed": "{name} isn't running","homeScreen.setupNamed": "Setting up {name}…","homeLine.left": "You're no longer in {name}.",+ "homeLine.clean": "Your bots are in your Cloud. Sign in to get them.","teamMove.menu": "Move to {team}","teamMove.title": "Move {bot} to {team}?","teamMove.everyone": "Everyone in {team} can use {bot}. Only {team}'s admins can change it.",