Skip to content

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

fix(backup): recover interrupted restore preparation

Sebastian B0669bf07261c
diff --git a/server/workspace-backup-workflow.test.ts b/server/workspace-backup-workflow.test.ts
index c0464a36f3..a9395f0063 100644
--- a/server/workspace-backup-workflow.test.ts
+++ b/server/workspace-backup-workflow.test.ts
@@ -1,5 +1,52 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { expect, it } from "vitest";
+import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment } from "../scripts/control-omb.ts";
import { verifyWorkspaceBackup } from "../scripts/verify-workspace-backup.ts";
+import { waitForExit } from "./testing/cleanup.ts";
+import { commitPendingWorkspaceRestore, createWorkspaceBackup, stageWorkspaceBackup } from "./workspace-backup.ts";
+
+it("starts the server with the original workspace after an interrupted restore preparation", async () => {
+ const fixture = await launchVerificationServer({});
+ const source = mkdtempSync(join(tmpdir(), "omb-restore-prepare-"));
+ let restarted: ChildProcess | undefined;
+ try {
+ await waitForExit(fixture.child, { signal: "SIGTERM" });
+ writeFileSync(join(source, "note.txt"), "new workspace");
+ const target = fixture.info.dataDir;
+ writeFileSync(join(target, "note.txt"), "original workspace");
+ const password = "fixture-backup-password-only";
+ const exported = await createWorkspaceBackup(source, { password });
+ const staged = await stageWorkspaceBackup(target, exported.path, { password });
+ commitPendingWorkspaceRestore(target, staged.id);
+ mkdirSync(join(target, ".backups", `safety-${staged.id}`, "data"), { recursive: true });
+ const env = verificationServerEnvironment({}, join(source, "home"), Number(new URL(fixture.info.url).port));
+ env.OMB_DATA_DIR = target;
+ mkdirSync(env.TMPDIR!, { recursive: true });
+ const log = openSync(fixture.info.logPath, "a", 0o600);
+ try {
+ restarted = spawn(process.execPath, verificationServerArgs(env), { env, stdio: ["ignore", log, log] });
+ } finally { closeSync(log); }
+ await expect.poll(async () => {
+ try {
+ const response = await fetch(`${fixture.info.url}/api/health`, { signal: AbortSignal.timeout(1_000) });
+ const health = await response.json() as { pid?: number };
+ return response.ok && health.pid === restarted!.pid;
+ } catch { return false; }
+ }, { timeout: 20_000 }).toBe(true);
+ const response = await fetch(`${fixture.info.url}/api/health`);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ app: "openmausbot", pid: restarted.pid });
+ expect(readFileSync(join(target, "note.txt"), "utf8")).toBe("original workspace");
+ expect(existsSync(join(target, ".backups", "pending-restore.json"))).toBe(false);
+ } finally {
+ if (restarted) await waitForExit(restarted, { signal: "SIGTERM" });
+ await fixture.close();
+ rmSync(source, { recursive: true, force: true });
+ }
+}, 60_000);
it("restores an encrypted workspace through the real server and continues its original chat", async () => {
const result = await verifyWorkspaceBackup();
diff --git a/server/workspace-backup.test.ts b/server/workspace-backup.test.ts
index 56b828635a..51a8d9e44e 100644
--- a/server/workspace-backup.test.ts
+++ b/server/workspace-backup.test.ts
@@ -750,7 +750,87 @@ describe("encrypted full workspace backups", () => {
expect(readFileSync(join(data, "imported-skills", "pdf", "scripts", "run.sh"), "utf8")).toBe("echo run\n");
});
- it("recovers an interrupted top-level swap before any application state is loaded", async () => {
+ it.each([
+ "safety directory", "data directory", "partial manifest", "manifest",
+ "partial previous receipt", "previous receipt", "partial journal", "journal",
+ ])("cancels an interrupted restore preparation after %s without changing original data", async (step) => {
+ const source = directory();
+ writeFileSync(join(source, "note.txt"), "new workspace");
+ const exported = await createWorkspaceBackup(source, { password: PASSWORD });
+ const target = directory();
+ const original = join(target, "note.txt");
+ writeFileSync(original, "original workspace");
+ const before = statSync(original);
+ const staged = await stageWorkspaceBackup(target, exported.path, { password: PASSWORD });
+ commitPendingWorkspaceRestore(target, staged.id);
+ const root = join(target, ".backups");
+ const safety = join(root, `safety-${staged.id}`);
+ const receipt = { restored: true, id: "00000000-0000-4000-8000-000000000000", clientState: {} };
+ json(join(root, "last-restore.json"), receipt);
+ const journal = { id: staged.id, phase: "applying", existing: ["note.txt"], incoming: ["note.txt"] };
+ const steps = ["safety directory", "data directory", "partial manifest", "manifest", "partial previous receipt", "previous receipt", "partial journal", "journal"];
+ const reached = (name: string) => steps.indexOf(step) >= steps.indexOf(name);
+ mkdirSync(safety);
+ if (reached("data directory")) mkdirSync(join(safety, "data"));
+ if (step === "partial manifest") writeFileSync(join(safety, "manifest.json.123.crash.tmp"), '{"id":');
+ if (reached("manifest")) json(join(safety, "manifest.json"), { id: staged.id, originalEntries: ["note.txt"] });
+ if (step === "partial previous receipt") writeFileSync(join(safety, "previous-restore.json.123.crash.tmp"), '{"restored":');
+ if (reached("previous receipt")) json(join(safety, "previous-restore.json"), receipt);
+ if (step === "partial journal") writeFileSync(join(root, "restore-journal.json.123.crash.tmp"), '{"id":');
+ if (step === "journal") json(join(root, "restore-journal.json"), journal);
+
+ expect(applyPendingWorkspaceRestore(target)).toMatchObject({ restored: false, rolledBack: true, id: staged.id });
+ expect(readFileSync(original, "utf8")).toBe("original workspace");
+ expect(statSync(original).ino).toBe(before.ino);
+ expect(statSync(original).mtimeMs).toBe(before.mtimeMs);
+ expect(readFileSync(join(root, staged.id, "apply", "data", "note.txt"), "utf8")).toBe("new workspace");
+ expect(readJson(join(root, "last-restore.json"))).toEqual(receipt);
+ expect(readPendingWorkspaceRestoreMetadata(target)).toBeNull();
+ expect(applyPendingWorkspaceRestore(target)).toEqual({ restored: false });
+ });
+
+ it("preserves moved originals and prepared files when the recovery journal is missing", async () => {
+ const source = directory();
+ writeFileSync(join(source, "note.txt"), "new workspace");
+ const exported = await createWorkspaceBackup(source, { password: PASSWORD });
+ const target = directory();
+ writeFileSync(join(target, "note.txt"), "original workspace");
+ const staged = await stageWorkspaceBackup(target, exported.path, { password: PASSWORD });
+ commitPendingWorkspaceRestore(target, staged.id);
+ const root = join(target, ".backups");
+ const saved = join(root, `safety-${staged.id}`, "data");
+ mkdirSync(saved, { recursive: true });
+ renameSync(join(target, "note.txt"), join(saved, "note.txt"));
+ const prepared = join(root, staged.id, "apply", "data", "note.txt");
+ writeFileSync(prepared, "prepared recovery copy");
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect(() => applyPendingWorkspaceRestore(target)).toThrow(/safety copy already exists/i);
+ expect(readFileSync(join(saved, "note.txt"), "utf8")).toBe("original workspace");
+ expect(readFileSync(prepared, "utf8")).toBe("prepared recovery copy");
+ expect(existsSync(join(target, "note.txt"))).toBe(false);
+ expect(readPendingWorkspaceRestoreMetadata(target)?.id).toBe(staged.id);
+ }
+ });
+
+ it.each(["safety", "data"])("refuses an unjournaled restore with a linked %s directory", async (linked) => {
+ const source = directory();
+ writeFileSync(join(source, "note.txt"), "new workspace");
+ const exported = await createWorkspaceBackup(source, { password: PASSWORD });
+ const target = directory();
+ writeFileSync(join(target, "note.txt"), "original workspace");
+ const staged = await stageWorkspaceBackup(target, exported.path, { password: PASSWORD });
+ commitPendingWorkspaceRestore(target, staged.id);
+ const safety = join(target, ".backups", `safety-${staged.id}`);
+ const outside = directory();
+ if (linked === "data") mkdirSync(safety);
+ symlinkSync(outside, linked === "safety" ? safety : join(safety, "data"), process.platform === "win32" ? "junction" : "dir");
+ expect(() => applyPendingWorkspaceRestore(target)).toThrow(/safety copy already exists/i);
+ expect(readFileSync(join(target, "note.txt"), "utf8")).toBe("original workspace");
+ expect(readPendingWorkspaceRestoreMetadata(target)?.id).toBe(staged.id);
+ expect(readdirSync(outside)).toEqual([]);
+ });
+
+ it.each([false, true])("recovers an interrupted top-level swap with incoming moved=%s before any application state is loaded", async (incomingMoved) => {
const source = directory();
json(join(source, "bots.json"), []);
const exported = await createWorkspaceBackup(source, { password: PASSWORD });
@@ -765,7 +845,7 @@ describe("encrypted full workspace backups", () => {
mkdirSync(saved, { recursive: true });
json(join(root, "restore-journal.json"), { id: staged.id, phase: "applying", existing: ["bots.json"], incoming: ["bots.json"] });
renameSync(join(target, "bots.json"), join(saved, "bots.json"));
- renameSync(join(apply, "bots.json"), join(target, "bots.json"));
+ if (incomingMoved) renameSync(join(apply, "bots.json"), join(target, "bots.json"));
expect(applyPendingWorkspaceRestore(target)).toMatchObject({ restored: false, rolledBack: true, id: staged.id });
expect(readJson(join(target, "bots.json"))).toEqual([{ id: "original" }]);
expect(applyPendingWorkspaceRestore(target)).toEqual({ restored: false });
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index 3b8350f5fa..876fcae301 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -892,11 +892,20 @@ export function applyPendingWorkspaceRestore(dataDir: string): WorkspaceRestoreR
}
const pending = readPendingWorkspaceRestoreMetadata(dataDir);
if (!pending) return { restored: false };
+ const safetyCopyPath = join(root, `safety-${pending.id}`);
+ if (entryExists(safetyCopyPath)) {
+ const saved = join(safetyCopyPath, "data");
+ // Moves start only after the journal is durable; an empty safety tree is an interrupted preparation.
+ if (!lstatSync(safetyCopyPath).isDirectory() || (entryExists(saved) &&
+ (!lstatSync(saved).isDirectory() || readdirSync(saved).length !== 0))) {
+ throw new Error("A safety copy already exists for this restore. Original files have not been changed.");
+ }
+ rmSync(pendingFile, { force: true });
+ return { restored: false, rolledBack: true, id: pending.id, safetyCopyPath };
+ }
const staged = join(jobPath(dataDir, pending.id), "staged");
const manifest = validateStaged(staged);
const prepared = prepareRestore(dataDir, pending.id, manifest);
- const safetyCopyPath = join(root, `safety-${pending.id}`);
- if (existsSync(safetyCopyPath)) throw new Error("A safety copy already exists for this restore. Original files have not been changed.");
folder(join(safetyCopyPath, "data"));
const journal: RestoreJournal = {
id: pending.id, phase: "applying",