Skip to content

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

fix(sharing): keep failed pauses stopped across restarts

Sebastian B405c29604251
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 893ccc6e16..0bb1e66fa8 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -648,6 +648,12 @@ to resume, a menu-bar item (the notification area on Windows) shows it
**Resume**, which lends every Cloud again. Files keeps copying lent folders
while paused, but bots' changes made on My Cloud wait there until Resume, as
they do while this computer is away.
+- If saving Pause fails, sharing stops immediately. The item reports that the pause is not saved.
+ Choose **Retry saving pause** to save it without resuming. A failed Resume save also keeps sharing paused.
+ Before lending, the desktop reserves `computer-sharing.json.lending-session`, an empty recovery directory beside its settings.
+ A normal exit removes it. A failed pause save or unclean exit retains it.
+ On the next start, lending stays paused with a recovery message. Choose **Retry saving pause** or **Resume**.
+ This guard exists before a disk-full error can prevent saving Pause. It also pauses lending after a crash.
- **See activity** opens this computer's own record of what its Clouds did here
(`electron/lending-activity-window.mjs`): every request, refused ones
included, and each website opened through its internet connection (**Opened a
diff --git a/electron/cloud-lending.node-test.mjs b/electron/cloud-lending.node-test.mjs
index 13ea8d8bb9..cd4a6bd9b3 100644
--- a/electron/cloud-lending.node-test.mjs
+++ b/electron/cloud-lending.node-test.mjs
@@ -365,11 +365,12 @@ test("quitting the app pauses lending; it never switches it off, even mid-reconn
if (new URL(url).pathname === "/api/auth/session") { identityStarted(); await delay(200); }
return answer(url, init);
};
+ sharing.close();
const restarted = createComputerSharing({
file: path.join(dir, "profile", "computer-sharing.json"), fetch: (...args) => home.fetch(...args), environments: () => [env], enabled: async () => false,
cloud: () => ({ status: "connected", accountId: "acct_1", origin: ORIGIN }), home: path.join(dir, "home"), cuaConnection: async () => null,
});
- sharing.close();
+ t.after(() => restarted.close());
restarted.start({ maintainer: false });
await started;
restarted.close();
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index 2f16416f61..487554c838 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -47,6 +47,8 @@ export interface LendingSummary {
clouds: string[];
using: string[];
paused: boolean;
+ /** A pause needs a save retry or review after an unclean exit; sharing stays stopped. */
+ pauseError?: string;
busy: { env: string; action: string } | null;
}
export interface AutomaticGrant { folders: SharedFolder[]; screen: boolean; internet: true; chrome: true; terminal: false }
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index a4ab18e26b..d1f8ad338f 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -198,6 +198,22 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
if (parsed?.version === 1 && parsed.records && typeof parsed.records === "object") records = parsed.records;
paused = parsed?.automatic ? parsed.automatic.paused === true : Object.values(records).some(saidNo);
} catch {}
+ const sessionMarker = `${file}.lending-session`;
+ let sessionGuarded = false, pauseError;
+ // Reserve recovery state before lending: a failed Pause write must survive an app exit, even on a full disk.
+ const guardSession = () => {
+ if (sessionGuarded) return;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.mkdirSync(sessionMarker);
+ sessionGuarded = true;
+ };
+ try { guardSession(); } catch (error) {
+ if (error.code === "EEXIST") {
+ sessionGuarded = true;
+ if (!paused) pauseError = "Lending stays paused because the previous session did not finish saving its state. Retry saving pause or choose Resume.";
+ } else pauseError = "Lending stays paused because restart protection could not be saved. Retry saving pause or choose Resume.";
+ paused = true;
+ }
const running = new Map();
const grantVersions = new Map();
const changeGrant = id => { const version = (grantVersions.get(id) ?? 0) + 1; grantVersions.set(id, version); return version; };
@@ -212,13 +228,15 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
const changed = () => { if (!closed) try { onChange(summary()); } catch {} };
const summary = () => {
const browsing = [...inUse.keys()].find(id => linked.has(id));
- const lent = paused ? [] : environments().filter(env => records[env.id]?.cloud && records[env.id]?.enabled === true);
- const using = lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));
+ const lent = environments().filter(env => records[env.id]?.cloud && records[env.id]?.enabled === true);
+ const clouds = paused ? new Map([...ownClouds(), ...lent].map(env => [env.id, env])).values() : lent;
+ const using = paused ? [] : lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));
return {
- lending: lent.map(env => env.id),
- clouds: (paused ? ownClouds() : lent).map(env => env.name),
+ lending: paused ? [] : lent.map(env => env.id),
+ clouds: [...clouds].map(env => env.name),
using: using.map(env => env.name),
paused,
+ ...(pauseError ? { pauseError } : {}),
busy: executing ?? (browsing ? { env: browsing, action: "internet" } : null),
};
};
@@ -651,20 +669,30 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
paused: () => paused,
/** Every Cloud of the person's own stops using this computer, across restarts too, until resume(). */
pause() {
- if (paused || closed) return;
+ if (closed) return;
paused = true;
- try { store(records); } catch {}
for (const env of environments()) {
if (!records[env.id]?.cloud) continue;
if (running.has(env.id)) disconnect(env, records[env.id]);
status.set(env.id, { connected: false, problem: "paused" });
}
+ try { store(records); pauseError = undefined; }
+ catch { pauseError = "Pause is not saved. Sharing is stopped now. Retry saving pause before quitting; the next start will stay paused for review."; }
changed();
},
resume() {
if (!paused || closed) return;
- paused = false;
- try { store(records); } catch {}
+ try {
+ guardSession();
+ paused = false;
+ store(records);
+ pauseError = undefined;
+ } catch {
+ paused = true;
+ pauseError = "Resume could not be saved. Sharing stays paused. Retry Resume.";
+ changed();
+ return;
+ }
const automatic = lentAutomatically();
for (const env of environments()) {
const grant = records[env.id];
@@ -707,6 +735,11 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
}
void lendAutomatically();
},
- close() { closed = true; for (const id of running.keys()) stop(id); },
+ close() {
+ if (closed) return;
+ closed = true;
+ for (const id of running.keys()) stop(id);
+ if (sessionGuarded && !pauseError) try { fs.rmdirSync(sessionMarker); } catch {}
+ },
};
}
diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjs
index c8046d5995..87c9abd3b3 100644
--- a/electron/lending-indicator.mjs
+++ b/electron/lending-indicator.mjs
@@ -5,8 +5,9 @@ const listed = names => names.length < 3 ? names.join(" and ") : `${names.slice(
/** Beside the icon there is room for two names at most. */
const short = names => names.length < 3 ? listed(names) : `${names.length} Clouds`;
-export function indicatorText({ clouds, using, paused }, device) {
+export function indicatorText({ clouds, using, paused, pauseError }, device) {
const it = `this ${device}`;
+ if (pauseError) return { line: pauseError, title: "Paused: save needs attention" };
if (paused) return { line: `Paused: ${listed(clouds)} can't use ${it}`, title: "Paused" };
if (using.length) return { line: `${listed(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, title: `${short(using)} ${using.length > 1 ? "are" : "is"} using ${it}` };
return { line: `${listed(clouds)} can use ${it}`, title: "" };
@@ -23,13 +24,14 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa
tray.setContextMenu(Menu.buildFromTemplate([
{ label: line, enabled: false },
{ type: "separator" },
+ ...(view.pauseError ? [{ label: "Retry saving pause", click: () => onPause() }] : []),
view.paused ? { label: "Resume", click: () => onResume() } : { label: "Pause", click: () => onPause() },
{ label: "See activity", click: () => onActivity() },
]));
};
return {
- update({ clouds = [], using = [], paused = false }) {
- const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true };
+ update({ clouds = [], using = [], paused = false, pauseError }) {
+ const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, ...(pauseError ? { pauseError } : {}) };
if (shown && JSON.stringify(next) === JSON.stringify(shown)) return;
shown = next;
if (!next.clouds.length) { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; return; }
diff --git a/electron/sharing-persistence.node-test.mjs b/electron/sharing-persistence.node-test.mjs
new file mode 100644
index 0000000000..141503da10
--- /dev/null
+++ b/electron/sharing-persistence.node-test.mjs
@@ -0,0 +1,186 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import fs from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { setImmediate } from "node:timers/promises";
+import { createComputerSharing } from "./computer-sharing.mjs";
+import { createLendingIndicator } from "./lending-indicator.mjs";
+
+function fixture(t) {
+ const dir = fs.mkdtempSync(path.join(tmpdir(), "omb-sharing-persistence-"));
+ const file = path.join(dir, "computer-sharing.json");
+ const env = { id: "fixture-cloud", origin: "https://cloud.fixture.test", name: "Fixture" };
+ const grant = { id: randomUUID(), secret: "a".repeat(64), sessionId: randomUUID(), environmentId: randomUUID(), enabled: true,
+ folders: [], terminal: false, computer: false, internet: true, chrome: true, cloud: { accountId: "fixture-account", origin: env.origin } };
+ fs.writeFileSync(file, JSON.stringify({ version: 1, records: { [env.id]: grant }, automatic: { paused: false } }));
+ const summaries = [], connects = [], polls = [];
+ const polled = Promise.withResolvers();
+ const controllers = [];
+ const options = {
+ file, home: dir, environments: () => [env],
+ cloud: () => ({ status: "connected", accountId: "fixture-account", origin: env.origin }),
+ onChange: summary => summaries.push(summary),
+ async fetch(url, { signal }) {
+ const route = new URL(url).pathname;
+ if (route === "/api/auth/session") return Response.json({ kind: "session", id: grant.sessionId, cloudHome: true, scopes: ["admin"] });
+ if (route === "/.well-known/openmausbot/environment") return Response.json({ environmentId: grant.environmentId, capabilities: { sharedComputers: true } });
+ if (route === "/api/shared-computers/connect") connects.push(url);
+ if (route.endsWith("/poll")) await new Promise((resolve, reject) => {
+ polls.push(signal);
+ polled.resolve();
+ signal.throwIfAborted();
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
+ });
+ return Response.json({ ok: true });
+ },
+ };
+ t.after(() => { for (const controller of controllers) controller.close(); fs.rmSync(dir, { recursive: true, force: true }); });
+ return { file, summaries, connects, polls, polled: polled.promise,
+ make() { const controller = createComputerSharing(options); controllers.push(controller); return controller; },
+ saved: () => JSON.parse(fs.readFileSync(file, "utf8")),
+ block: () => fs.mkdirSync(`${file}.tmp`),
+ unblock: () => fs.rmdirSync(`${file}.tmp`),
+ };
+}
+
+test("a failed Pause save stops active sharing and reports that the pause is not saved", async t => {
+ const f = fixture(t), sharing = f.make();
+ sharing.start();
+ await f.polled;
+ f.block();
+ const write = fs.writeFileSync;
+ let stoppedBeforeSave;
+ t.mock.method(fs, "writeFileSync", (...args) => {
+ if (args[0] === `${f.file}.tmp`) stoppedBeforeSave = f.polls[0].aborted;
+ return write(...args);
+ });
+ sharing.pause();
+ assert.equal(stoppedBeforeSave, true, "work stops before the save is attempted");
+ assert.equal(sharing.paused(), true);
+ assert.equal(f.polls[0].aborted, true);
+ assert.equal(sharing.lendingToCloud(), false);
+ assert.equal(f.saved().automatic.paused, false);
+ assert.match(f.summaries.at(-1).pauseError, /not saved/i);
+ assert.deepEqual(f.summaries.at(-1).clouds, ["Fixture"]);
+});
+
+test("Pause retries a failed save while sharing stays paused", async t => {
+ const f = fixture(t), sharing = f.make();
+ f.block();
+ sharing.pause();
+ f.unblock();
+ sharing.pause();
+ assert.equal(f.saved().automatic.paused, true);
+ assert.equal(f.summaries.at(-1).pauseError, undefined);
+ sharing.close();
+ assert.equal(f.make().paused(), true);
+});
+
+test("a failed Pause save cannot silently reconnect after restart", async t => {
+ const f = fixture(t), sharing = f.make();
+ sharing.start();
+ await f.polled;
+ f.block();
+ sharing.pause();
+ sharing.close();
+ f.unblock();
+ const restarted = f.make();
+ restarted.start();
+ restarted.cloudChanged();
+ assert.equal(restarted.paused(), true);
+ assert.match(f.summaries.at(-1).pauseError, /previous session/i);
+ await setImmediate();
+ assert.equal(f.connects.length, 1);
+ restarted.pause();
+ assert.equal(f.saved().automatic.paused, true);
+ assert.equal(f.summaries.at(-1).pauseError, undefined);
+ await restarted.resume();
+ assert.equal(restarted.paused(), false);
+ assert.equal(f.saved().automatic.paused, false);
+});
+
+test("an unclean exit leaves lending paused with a recovery message on the next start", t => {
+ const f = fixture(t);
+ const child = spawnSync(process.execPath, ["--input-type=module", "--eval", `
+ import { createComputerSharing } from ${JSON.stringify(new URL("./computer-sharing.mjs", import.meta.url).href)};
+ createComputerSharing({ file: ${JSON.stringify(f.file)}, environments: () => [] });
+ process.exit(0);
+ `], { encoding: "utf8" });
+ assert.equal(child.status, 0, child.stderr);
+ const restarted = f.make();
+ restarted.start();
+ assert.equal(restarted.paused(), true);
+ assert.match(f.summaries.at(-1).pauseError, /previous session/i);
+});
+
+test("a clean exit keeps saved active lending available on the next start", t => {
+ const f = fixture(t), sharing = f.make();
+ sharing.close();
+ assert.equal(f.make().paused(), false);
+});
+
+test("lending stays paused when restart protection cannot be reserved, until Resume can save it", async t => {
+ const f = fixture(t);
+ const mkdir = fs.mkdirSync;
+ const blocked = t.mock.method(fs, "mkdirSync", (...args) => {
+ if (args[0] === `${f.file}.lending-session`) throw Object.assign(new Error("disk full"), { code: "ENOSPC" });
+ return mkdir(...args);
+ });
+ const sharing = f.make();
+ sharing.start();
+ assert.equal(sharing.paused(), true);
+ assert.match(f.summaries.at(-1).pauseError, /restart protection/);
+ await sharing.resume();
+ assert.equal(sharing.paused(), true);
+ await setImmediate();
+ assert.equal(f.connects.length, 0);
+ blocked.mock.restore();
+ await sharing.resume();
+ assert.equal(sharing.paused(), false);
+ assert.equal(f.summaries.at(-1).pauseError, undefined);
+});
+
+test("Resume stays paused if its save fails and can be retried", async t => {
+ const f = fixture(t), sharing = f.make();
+ sharing.pause();
+ f.block();
+ await sharing.resume();
+ assert.equal(sharing.paused(), true);
+ assert.equal(sharing.lendingToCloud(), false);
+ assert.equal(f.saved().automatic.paused, true);
+ assert.match(f.summaries.at(-1).pauseError, /resume/i);
+ f.unblock();
+ await sharing.resume();
+ assert.equal(sharing.paused(), false);
+ assert.equal(f.saved().automatic.paused, false);
+ assert.equal(f.summaries.at(-1).pauseError, undefined);
+});
+
+test("the tray reports an unsaved pause and offers a save retry alongside Resume", () => {
+ let tray, retries = 0;
+ class Tray {
+ constructor() { tray = this; }
+ setToolTip(value) { this.tooltip = value; }
+ setTitle(value) { this.title = value; }
+ setContextMenu(value) { this.menu = value; }
+ isDestroyed() { return false; }
+ on() {}
+ destroy() {}
+ }
+ const indicator = createLendingIndicator({ Tray, Menu: { buildFromTemplate: items => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }) },
+ iconPath: "fixture.png", onPause: () => retries++, onResume() {}, onActivity() {} });
+ try {
+ indicator.update({ clouds: ["Fixture"], using: [], paused: true });
+ indicator.update({ clouds: ["Fixture"], using: [], paused: true, pauseError: "Pause is not saved. Retry saving pause." });
+ assert.match(tray.tooltip, /not saved/);
+ assert.match(tray.title, /save/i);
+ const retry = tray.menu.find(item => item.label === "Retry saving pause");
+ assert.ok(retry);
+ retry.click();
+ assert.equal(retries, 1);
+ assert.ok(tray.menu.some(item => item.label === "Resume"));
+ } finally { indicator.destroy(); }
+});