Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: 支持断线后恢复备份导出
Zhehui Bi89d33f8bcc64
diff --git a/docs/verification/workspace-backups.md b/docs/verification/workspace-backups.mdindex 367bb3cb80..132637b25a 100644--- a/docs/verification/workspace-backups.md+++ b/docs/verification/workspace-backups.md@@ -11,6 +11,13 @@ A hosted server must restart before its browser's **Retry** can finish recovery.No restore writes into a running Store. The native-button workflow is exercisedby the [company-backup fixture](company-backups.md).+During an export, the settings row shows that the backup is being created.+After a connection drop or page refresh, the same signed-in browser tab can+recover the job while the server is still running. A recovered export shows+a download link. The encrypted file expires one hour after it is ready. If+the server restarts or the backup expires, export again using the backup+password.+The previous workspace is retained under `.backups/safety-<restore-id>/data`.Keep this copy until the restored workspace is checked. Do not publish it.The downloaded archive is encrypted; private staging and safety directoriesdiff --git a/scripts/testing/workspace-backup-ui.e2e.test.ts b/scripts/testing/workspace-backup-ui.e2e.test.tsindex 914a2b8e23..bc5fcc7a53 100644--- a/scripts/testing/workspace-backup-ui.e2e.test.ts+++ b/scripts/testing/workspace-backup-ui.e2e.test.ts@@ -66,7 +66,12 @@ describe("full backup Settings in the real renderer", () => {fixture.calls.push({ path, body, rawFile: init.body instanceof File, type: init.headers?.['content-type'] });const reply = (value, status = 200) => Promise.resolve(new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }));if (path.endsWith('/status')) return reply({ busy: false, pendingRestore: fixture.pending });- if (path.endsWith('/export')) return reply({ id: 'download-stage', filename: 'fixture.ombbackup' });+ if (path.includes('/export-jobs/')) {+ if (init.method === 'POST') { fixture.exportPath = path; return reply({ error: 'Fixture proxy timed out' }, 524); }+ if (path === fixture.exportPath) return reply(fixture.exportReady+ ? { state: 'ready', id: 'download-stage', filename: 'fixture.ombbackup', expiresAt: Date.now() + 60 * 60_000 }+ : { state: 'running' });+ }if (path.endsWith('/upload')) return reply({ id: 'uploaded-file' });if (path.endsWith('/preview')) {if (body.password !== 'fixture password 123') return reply({ error: 'Fixture password rejected' }, 400);@@ -107,10 +112,13 @@ describe("full backup Settings in the real renderer", () => {await type("Backup password", "fixture password 123");await type("Confirm backup password", "fixture password 123");await ui("press", "--keys", "Enter");+ await expect.poll(snapshot).toContain("Creating encrypted backup");+ await ui("screenshot", "--out", join(ROOT, ".omb-scratch", "verify-evidence", "workspace-backup-exporting.png"));+ await evaluate("window.backupFixture.exportReady = true");await expect.poll(() => evaluate("window.backupFixture.download"), { timeout: 10_000 }).toEqual({ href: "/api/workspace-backup/download/download-stage", filename: "fixture.ombbackup" });- expect(await evaluate("window.backupFixture.calls.find(call => call.path.endsWith('/export')).body.clientState['fixture-auth-token'] ?? null")).toBeNull();- expect(await evaluate("window.backupFixture.calls.find(call => call.path.endsWith('/export')).body.clientState['omb-webhook-credentials'] ?? null")).toBeNull();- expect(await evaluate("Object.values(localStorage).some(value => value.includes('fixture password 123'))")).toBe(false);+ expect(await evaluate("window.backupFixture.calls.find(call => call.path === window.backupFixture.exportPath && call.body).body.clientState['fixture-auth-token'] ?? null")).toBeNull();+ expect(await evaluate("window.backupFixture.calls.find(call => call.path === window.backupFixture.exportPath && call.body).body.clientState['omb-webhook-credentials'] ?? null")).toBeNull();+ expect(await evaluate("[...Object.values(localStorage), ...Object.values(sessionStorage)].some(value => value.includes('fixture password 123'))")).toBe(false);await expect.poll(() => evaluate("document.querySelector('[data-backup-import]')?.disabled")).toBe(false);await click("Choose file…");diff --git a/scripts/verify-workspace-backup.ts b/scripts/verify-workspace-backup.tsindex 8f6243e957..342d68cfcc 100644--- a/scripts/verify-workspace-backup.ts+++ b/scripts/verify-workspace-backup.ts@@ -1,13 +1,14 @@// Owns two disposable fake-engine workspaces; accepts no live URL or home.import assert from "node:assert/strict";import { spawn, type ChildProcess } from "node:child_process";-import { createHash } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";import { basename, dirname, join, relative, resolve } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { launchVerificationServer, runControlOmb, type VerificationServer } from "./control-omb.ts";import { waitForExit } from "../server/testing/cleanup.ts";import { escapeAttribute } from "../src/lib/composer-attachments.ts";+import type { WorkspaceBackupExportStatus } from "../shared/workspace-backup.ts";const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");const PASSWORD = "fixture-backup-password-only";@@ -150,16 +151,33 @@ export async function verifyWorkspaceBackup(report: (event: unknown) => void = (assert.ok(original.messages.some((message: { text?: string }) => message.text?.includes("hello from fake claude")));const oldBytes = readFileSync(join(destination.info.dataDir, "bots.json"));const clientState = { "omb-skin": "default", "omb-drafts": JSON.stringify({ [bot.threadId]: "Keep draft" }), "omb-webhook-credentials": "private-source-webhook-url", "unrelated-auth-token": "must-not-transfer" };- const exported = await api(source, "POST", "/api/workspace-backup/export", { password: PASSWORD, clientState });- assert.equal(exported.status, 200, JSON.stringify(exported.body));- assert.equal(exported.body.summary.bots, before.bots.length);- assert.equal(Object.hasOwn(exported.body.summary, "includesCredentials"), false);- const download = await fetch(`${source.info.url}/api/workspace-backup/download/${exported.body.id}`);+ const legacy = await api(source, "POST", "/api/workspace-backup/export", { password: PASSWORD, clientState });+ assert.equal(legacy.status, 200, JSON.stringify(legacy.body));+ assert.equal(legacy.body.summary.bots, before.bots.length);+ assert.equal(Object.hasOwn(legacy.body.summary, "includesCredentials"), false);+ const exportPath = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ const submitted = await fetch(`${source.info.url}${exportPath}`, {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ password: PASSWORD, clientState }), signal: AbortSignal.timeout(10_000),+ });+ assert.equal(submitted.status, 202);+ await submitted.body?.cancel();+ const deadline = Date.now() + 60_000;+ let job: WorkspaceBackupExportStatus;+ do {+ const response = await api(source, "GET", exportPath);+ assert.equal(response.status, 200);+ job = response.body as WorkspaceBackupExportStatus;+ if (job.state === "running") await new Promise((done) => setTimeout(done, 100));+ } while (job.state === "running" && Date.now() < deadline);+ assert.equal(job.state, "ready", JSON.stringify(job));+ const download = await fetch(`${source.info.url}/api/workspace-backup/download/${job.id}`);assert.equal(download.status, 200);const encrypted = Buffer.from(await download.arrayBuffer());- assert.equal(encrypted.byteLength, exported.body.bytes);+ assert.ok(encrypted.byteLength > 0);+ assert.equal(encrypted.byteLength, Number(download.headers.get("content-length")));for (const privateText of [soul, "fixture-voice-key", "WORKSPACE_SKILL_MARKER", "Keep draft"]) assert.equal(encrypted.includes(Buffer.from(privateText)), false);- record({ command: "download encrypted workspace", bytes: encrypted.length, summary: exported.body.summary });+ record({ command: "recover and download encrypted workspace", bytes: encrypted.length });const pairing = await api(destination, "POST", "/api/auth/pairing", { scopes: ["client"] });const paired = await api(destination, "POST", "/api/auth/pair", { code: pairing.body.code, label: "Fixture client" });diff --git a/server/workspace-backup-http.test.ts b/server/workspace-backup-http.test.tsindex d3ca3fa46f..f3b568eb44 100644--- a/server/workspace-backup-http.test.ts+++ b/server/workspace-backup-http.test.ts@@ -110,6 +110,100 @@ function post(path: string, body: unknown, token = admin.token) {return fetch(`${url}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });}+function get(path: string, token = admin.token) {+ return fetch(`${url}${path}`, { headers: { authorization: `Bearer ${token}` } });+}++it("finds the original export after a lost response and allows only its own session to download it", async () => {+ const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ let release!: () => void;+ let started!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ const starting = new Promise<void>((resolve) => { started = resolve; });+ const artifact = fakeArchive();+ archive.create.mockImplementationOnce(async () => {+ started();+ await held;+ return artifact;+ });+ const body = JSON.stringify({ password: PASSWORD });+ const connection = request(`${url}${path}`, { method: "POST", headers: {+ authorization: `Bearer ${admin.token}`, "content-type": "application/json", "content-length": Buffer.byteLength(body),+ } });+ const closed = new Promise<void>((resolve) => connection.once("close", resolve));+ connection.on("error", () => {});+ connection.end(body);+ const other = sessions.issue({ label: "Another admin session", scopes: ["admin", "client"] });+ try {+ await starting;+ connection.destroy();+ await closed;+ const retry = await post(path, { password: PASSWORD });+ expect(retry.status).toBe(202);+ expect(await retry.json()).toEqual({ state: "running" });+ expect(await (await get(path)).json()).toEqual({ state: "running" });+ expect((await get(path, other.token)).status).toBe(404);+ expect((await post(`/api/workspace-backup/export-jobs/${randomUUID()}`, { password: PASSWORD })).status).toBe(409);+ expect((await post("/api/workspace-backup/export", { password: PASSWORD })).status).toBe(409);+ expect(maintenance.active).toBe(true);+ } finally { release(); }+ const ready = { state: "ready", id: artifact.id, filename: "OpenMausBot-2026-09-11.ombbackup" };+ await expect.poll(async () => (await get(path)).json()).toMatchObject(ready);+ expect(await (await post(path, { password: PASSWORD })).json()).toMatchObject(ready);+ expect(archive.create).toHaveBeenCalledOnce();+ const download = `/api/workspace-backup/download/${artifact.id}`;+ expect(await (await get(download)).text()).toBe("fixture encrypted bytes");+ expect((await get(download, other.token)).status).toBe(404);+});++it("cleans up a completed asynchronous export if the initiating session was revoked", async () => {+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ const artifact = fakeArchive();+ archive.create.mockImplementationOnce(async () => { await held; return artifact; });+ const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ try {+ expect((await post(path, { password: PASSWORD })).status).toBe(202);+ expect((await post("/api/auth/logout", {})).status).toBe(200);+ } finally { release(); }+ await vi.waitFor(() => expect(archive.remove).toHaveBeenCalledWith(dataDir, artifact.id));+ expect(existsSync(artifact.path)).toBe(false);+ expect((await get(path)).status).toBe(401);+ expect((await get(`/api/workspace-backup/download/${artifact.id}`)).status).toBe(401);+});++it("reports a failed job when polled and accepts a new explicit export", async () => {+ const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ archive.create.mockRejectedValueOnce(new Error("Fixture archive failed"));+ expect((await post(path, { password: PASSWORD })).status).toBe(202);+ await expect.poll(async () => (await get(path)).json()).toEqual({ state: "failed", error: "Fixture archive failed" });+ expect(await (await post(path, { password: PASSWORD })).json()).toEqual({ state: "failed", error: "Fixture archive failed" });+ expect(archive.create).toHaveBeenCalledOnce();+ const retry = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ expect((await post(retry, { password: PASSWORD })).status).toBe(202);+ await expect.poll(async () => (await get(retry)).json()).toMatchObject({ state: "ready", expiresAt: expect.any(Number) });+ expect(archive.create).toHaveBeenCalledTimes(2);+});++it("retains each successful async archive for one hour from completion", async () => {+ const first = `/api/workspace-backup/export-jobs/${randomUUID()}`;+ const artifact = fakeArchive();+ archive.create.mockResolvedValueOnce(artifact);+ expect((await post(first, { password: PASSWORD })).status).toBe(202);+ await expect.poll(async () => (await get(first)).json()).toMatchObject({ state: "ready" });+ const { expiresAt } = await (await get(first)).json() as { expiresAt: number };+ expect(expiresAt - Date.now()).toBeGreaterThan(59 * 60_000);+ expect((await post("/api/workspace-backup/export", { password: PASSWORD })).status).toBe(200);+ const download = `/api/workspace-backup/download/${artifact.id}`;+ expect((await get(download)).status).toBe(200);+ const clock = vi.spyOn(Date, "now").mockReturnValue(expiresAt);+ try {+ expect((await get(first)).status).toBe(404);+ expect((await get(download)).status).toBe(404);+ expect(existsSync(artifact.path)).toBe(false);+ } finally { clock.mockRestore(); }+});+it("carries a fixed backup refusal and its redacted string path to the client", async () => {const params = { path: "workspaces/ws/project/loop" };archive.create.mockRejectedValueOnce(userErrorThrown("serverError.backup.recursiveLink", params));@@ -209,4 +303,6 @@ it("leaves the restart to the person where no launcher restarts the server", asyexpect(restored.status).toBe(200);expect(await restored.json()).not.toHaveProperty("restarting");expect(await status()).toMatchObject({ pendingRestore: true });+ expect((await post(`/api/workspace-backup/export-jobs/${randomUUID()}`, { password: PASSWORD })).status).toBe(409);+ expect(archive.create).not.toHaveBeenCalled();});diff --git a/server/workspace-backup-http.ts b/server/workspace-backup-http.tsindex 08e902e252..62142120e2 100644--- a/server/workspace-backup-http.ts+++ b/server/workspace-backup-http.ts@@ -5,6 +5,7 @@ import { join } from "node:path";import { Transform } from "node:stream";import { pipeline } from "node:stream/promises";import { z } from "zod";+import type { WorkspaceBackupExportStatus } from "../shared/workspace-backup.ts";import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";import {createWorkspaceBackup, stageWorkspaceBackup, commitPendingWorkspaceRestore,@@ -20,10 +21,18 @@ const MAX_UPLOAD_BYTES = MAX_WORKSPACE_BACKUP_UPLOAD_BYTES;const MAX_CLIENT_STATE_BYTES = 2 * 1024 ** 2;const EXPIRES_MS = 60 * 60_000;const passwordSchema = z.string().min(12, "Use a password of at least 12 characters.").max(1024);+const exportSchema = z.object({ password: passwordSchema, clientState: z.record(z.string(), z.string()).default({}) });const failure = (message: string, status = 400) => Object.assign(new Error(message), { status });-type Artifact = { owner: string; kind: "download" | "upload" | "staged"; path?: string; expires: number; summary?: WorkspaceBackupSummary };+type Artifact = { owner: string; kind: "download" | "upload" | "staged"; path?: string; expires: number; summary?: WorkspaceBackupSummary; keepUntilExpiry?: boolean };type RestoreResult = { id?: string; restored?: boolean; safetyCopyPath?: string; clientState?: Record<string, string> };+function backupError(error: unknown) {+ return {+ error: error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid backup request." : error instanceof Error ? error.message : "Backup failed.",+ ...userErrorFields(error),+ };+}+export function isWorkspaceBackupSessionControl(method: string, path: string): boolean {return (method === "GET" && path === "/api/auth/sessions") ||(method === "POST" && path === "/api/auth/logout") ||@@ -44,6 +53,7 @@ export function createWorkspaceBackupRoutes(options: {restart?: () => void;}) {const artifacts = new Map<string, Artifact>();+ const exportJobs = new Map<string, WorkspaceBackupExportStatus>();let operating = false;const json = (res: ServerResponse, status: number, body: unknown) => {res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });@@ -64,8 +74,11 @@ export function createWorkspaceBackupRoutes(options: {if (!existsSync(root) || lstatSync(root).isSymbolicLink()) return;for (const entry of readdirSync(root, { withFileTypes: true })) {if (!entry.isDirectory() || !/^[a-f0-9-]{36}$/.test(entry.name)) continue;- if (statSync(join(root, entry.name)).mtimeMs + EXPIRES_MS > Date.now()) continue;- try { removeWorkspaceBackupJob(options.dataDir, entry.name); } catch {}+ const directory = join(root, entry.name);+ const delay = statSync(directory).mtimeMs + EXPIRES_MS - Date.now();+ const reclaim = () => { try { removeWorkspaceBackupJob(options.dataDir, entry.name); } catch {} };+ if (delay <= 0) reclaim();+ else if (existsSync(join(directory, "workspace.ombbackup"))) setTimeout(reclaim, Math.min(delay, EXPIRES_MS)).unref();}const uploads = join(root, "uploads");if (!existsSync(uploads) || lstatSync(uploads).isSymbolicLink()) return;@@ -84,7 +97,9 @@ export function createWorkspaceBackupRoutes(options: {}function replacePrevious(auth: RequestAuth, kinds: Artifact["kind"][]) {expire();- for (const [id, artifact] of artifacts) if (artifact.owner === owner(auth) && kinds.includes(artifact.kind)) remove(id, artifact);+ for (const [id, artifact] of artifacts) {+ if (artifact.owner === owner(auth) && kinds.includes(artifact.kind) && !artifact.keepUntilExpiry) remove(id, artifact);+ }}const get = (id: unknown, auth: RequestAuth, kind: Artifact["kind"]) => {expire();@@ -99,6 +114,42 @@ export function createWorkspaceBackupRoutes(options: {operating = true;try { return await work(); } finally { operating = false; }}+ async function readExport(req: IncomingMessage) {+ const body = exportSchema.parse(await options.readBody(req, MAX_CLIENT_STATE_BYTES + 8 * 1024));+ if (Buffer.byteLength(JSON.stringify(body.clientState)) > MAX_CLIENT_STATE_BYTES) throw failure("Saved drafts exceed the 2 MB backup preference limit.", 413);+ const clientState = Object.fromEntries(Object.entries(body.clientState).filter(([key]) => WORKSPACE_BACKUP_CLIENT_KEYS.includes(key as typeof WORKSPACE_BACKUP_CLIENT_KEYS[number])));+ return { password: body.password, clientState };+ }+ function runExport(req: IncomingMessage, auth: RequestAuth, input: z.infer<typeof exportSchema>, keepUntilExpiry = false) {+ return operate(async () => {+ const result = await options.exclusive(async () => {+ check(req, auth);+ if (keepUntilExpiry) expire();+ else replacePrevious(auth, ["download"]);+ if (artifacts.size >= 4) throw failure("There are already four backup files in progress. Restart or wait an hour before creating another.", 409);+ return createWorkspaceBackup(options.dataDir, { ...input, appVersion: options.appVersion });+ });+ try {+ check(req, auth);+ const bytes = statSync(result.path).size, expiresAt = Date.now() + EXPIRES_MS;+ artifacts.set(result.id, { owner: owner(auth), kind: "download", path: result.path, summary: result.summary, expires: expiresAt, keepUntilExpiry });+ return { id: result.id, filename: `OpenMausBot-${result.summary.createdAt.slice(0, 10)}.ombbackup`, bytes, summary: result.summary, expiresAt };+ } catch (error) {+ removeWorkspaceBackupJob(options.dataDir, result.id);+ throw error;+ }+ });+ }+ function finishExport(key: string, status: Exclude<WorkspaceBackupExportStatus, { state: "running" }>) {+ exportJobs.set(key, status);+ setTimeout(() => {+ exportJobs.delete(key);+ if (status.state === "ready") {+ const artifact = artifacts.get(status.id);+ if (artifact) remove(status.id, artifact);+ }+ }, EXPIRES_MS).unref();+ }return async (req: IncomingMessage, res: ServerResponse, path: string, auth: RequestAuth): Promise<boolean> => {if (!path.startsWith(`${PREFIX}/`)) return false;res.setHeader("cache-control", "no-store");@@ -122,18 +173,34 @@ export function createWorkspaceBackupRoutes(options: {return true;}if (method === "POST" && path === `${PREFIX}/export`) {- const body = z.object({ password: passwordSchema, clientState: z.record(z.string(), z.string()).default({}) }).parse(await options.readBody(req, MAX_CLIENT_STATE_BYTES + 8 * 1024));- if (Buffer.byteLength(JSON.stringify(body.clientState)) > MAX_CLIENT_STATE_BYTES) throw failure("Saved drafts exceed the 2 MB backup preference limit.", 413);- const clientState = Object.fromEntries(Object.entries(body.clientState).filter(([key]) => WORKSPACE_BACKUP_CLIENT_KEYS.includes(key as typeof WORKSPACE_BACKUP_CLIENT_KEYS[number])));- const result = await operate(() => options.exclusive(async () => {- check(req, auth);- replacePrevious(auth, ["download"]);- if (artifacts.size >= 4) throw failure("There are already four backup files in progress. Restart or wait an hour before creating another.", 409);- return createWorkspaceBackup(options.dataDir, { password: body.password, clientState, appVersion: options.appVersion });- }));- try { check(req, auth); } catch (error) { removeWorkspaceBackupJob(options.dataDir, result.id); throw error; }- artifacts.set(result.id, { owner: owner(auth), kind: "download", path: result.path, summary: result.summary, expires: Date.now() + EXPIRES_MS });- json(res, 200, { id: result.id, filename: `OpenMausBot-${result.summary.createdAt.slice(0, 10)}.ombbackup`, bytes: statSync(result.path).size, summary: result.summary });+ const { id, filename, bytes, summary } = await runExport(req, auth, await readExport(req));+ json(res, 200, { id, filename, bytes, summary });+ return true;+ }+ const exportJob = /^\/api\/workspace-backup\/export-jobs\/([\w-]+)$/.exec(path);+ if (exportJob && (method === "GET" || method === "POST")) {+ const id = z.string().uuid().parse(exportJob[1]).toLowerCase();+ const input = method === "POST" ? await readExport(req) : null;+ check(req, auth);+ const key = `${owner(auth)}/${id}`;+ const existing = exportJobs.get(key);+ if (existing?.state === "ready" && existing.expiresAt <= Date.now()) throw failure("This backup has expired. Start another export.", 404);+ if (existing) {+ json(res, input ? 202 : 200, existing);+ return true;+ }+ if (!input) throw failure("This backup export is no longer available. Start another export.", 404);+ const { busy, pendingRestore } = options.status();+ if (operating || busy || pendingRestore) {+ throw failure("Another backup operation is in progress. Wait for it to finish.", 409);+ }+ const running = { state: "running" } as const;+ exportJobs.set(key, running);+ void runExport(req, auth, input, true).then(+ ({ id, filename, expiresAt }) => finishExport(key, { state: "ready", id, filename, expiresAt }),+ (error: unknown) => finishExport(key, { state: "failed", ...backupError(error) }),+ );+ json(res, 202, running);return true;}const download = /^\/api\/workspace-backup\/download\/([\w-]+)$/.exec(path);@@ -206,10 +273,7 @@ export function createWorkspaceBackupRoutes(options: {json(res, 404, { error: "Unknown backup operation." });} catch (error) {if (res.headersSent) { res.destroy(); return true; }- json(res, error instanceof z.ZodError ? 400 : (error as { status?: number }).status ?? 400, {- error: error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid backup request." : error instanceof Error ? error.message : "Backup failed.",- ...userErrorFields(error),- });+ json(res, error instanceof z.ZodError ? 400 : (error as { status?: number }).status ?? 400, backupError(error));}return true;};diff --git a/shared/workspace-backup.ts b/shared/workspace-backup.tsindex 88ea11aaea..6443ba0750 100644--- a/shared/workspace-backup.ts+++ b/shared/workspace-backup.ts@@ -27,6 +27,11 @@ export interface WorkspaceLeftBehind {export type WorkspaceBackupClientState = Record<string, string>;+export type WorkspaceBackupExportStatus =+ | { state: "running" }+ | { state: "ready"; id: string; filename: string; expiresAt: number }+ | { state: "failed"; error: string; errorKey?: string; errorParams?: Record<string, string | number> };+export interface WorkspaceBackupPrivateMetadata {summary: WorkspaceBackupSummary;clientState: WorkspaceBackupClientState;diff --git a/src/components/WorkspaceBackupSettings.test.ts b/src/components/WorkspaceBackupSettings.test.tsindex 3676e6af41..622b2106d1 100644--- a/src/components/WorkspaceBackupSettings.test.ts+++ b/src/components/WorkspaceBackupSettings.test.ts@@ -3,13 +3,14 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { WorkspaceBackupSummary } from "../../shared/workspace-backup";-const fixture = vi.hoisted(() => ({ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], api: vi.fn() }));+const fixture = vi.hoisted(() => ({ values: [] as unknown[], refs: [] as Array<{ current: unknown }>, index: 0, refIndex: 0, effects: [] as EffectCallback[], api: vi.fn() }));vi.mock("react", async (original) => ({ ...await original<typeof import("react")>(),useState: (initial: unknown) => {const index = fixture.index++;if (!(index in fixture.values)) fixture.values[index] = typeof initial === "function" ? initial() : initial;return [fixture.values[index], (next: unknown) => { fixture.values[index] = typeof next === "function" ? next(fixture.values[index]) : next; }];},+ useRef: (initial: unknown) => fixture.refs[fixture.refIndex++] ??= { current: initial },useEffect: (effect: EffectCallback) => { fixture.effects.push(effect); },}));vi.mock("@/state/store", () => ({ api: fixture.api }));@@ -24,7 +25,7 @@ function nodes(value: ReactNode): Node[] {return [node, ...Children.toArray(node.props.children).flatMap(nodes), ...Children.toArray(extra.subtitle).flatMap(nodes), ...Children.toArray(extra.message).flatMap(nodes)];}function render(recovery: boolean | "restart" | "cloud" = false) {- fixture.index = 0; fixture.effects = [];+ fixture.index = 0; fixture.refIndex = 0; fixture.effects = [];let tree: ReactNode;function Capture() { tree = recovery === "restart" ? WorkspaceBackupRestartNotice() : recovery === "cloud" ? WorkspaceBackupRestartNotice({ serverRestarts: true }) : recovery ? WorkspaceBackupRecovery({ children: createElement("p", null, "Normal app") }) : WorkspaceBackupSettings(); return tree; }const html = renderToStaticMarkup(createElement(Capture));@@ -35,10 +36,13 @@ const submit = (form: Node) => form.props.onSubmit!({ preventDefault: vi.fn() })const change = (input: Node, value: string) => input.props.onChange!({ target: { value } });const summary: WorkspaceBackupSummary = { format: "openmaus.workspace-backup", version: 1, id: "archive-id", createdAt: "2026-09-11T00:00:00Z", appVersion: "0.1.71", files: 9, directories: 3, bytes: 1234, bots: 2, groups: 1, threads: 4, messages: 8, warnings: ["Fixture warning"], exclusions: ["Saved account credentials and connections", "External CLI sign-ins"] };let storage: Map<string, string>;+let session: Map<string, string>;beforeEach(() => {- fixture.values = []; fixture.index = 0; fixture.effects = []; fixture.api.mockReset();+ fixture.values = []; fixture.refs = []; fixture.index = 0; fixture.effects = []; fixture.api.mockReset();storage = new Map();+ session = new Map();vi.stubGlobal("localStorage", { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value), removeItem: (key: string) => storage.delete(key) });+ vi.stubGlobal("sessionStorage", { getItem: (key: string) => session.get(key) ?? null, setItem: (key: string, value: string) => session.set(key, value), removeItem: (key: string) => session.delete(key) });vi.stubGlobal("window", { location: { reload: vi.fn() } });});afterEach(() => vi.unstubAllGlobals());@@ -78,30 +82,74 @@ describe("Settings full backups", () => {view = render();const link = { href: "", download: "", click: vi.fn(), remove: vi.fn() };vi.stubGlobal("document", { createElement: () => link, body: { append: vi.fn() } });- fixture.api.mockResolvedValueOnce({ id: "download-id", filename: "fixture.ombbackup" });+ fixture.api.mockRejectedValueOnce(Object.assign(new Error("524"), { status: 524 }));const form = formOf("backup-export");submit(form); submit(form); await flush();expect(fixture.api).toHaveBeenCalledTimes(2); // one status, one exportconst [path, init] = fixture.api.mock.calls[1];- expect(path).toBe("/api/workspace-backup/export");+ const requestId = session.get("omb-backup-export-request");+ expect(requestId).toMatch(/^[a-f0-9-]{36}$/);+ expect(path).toBe(`/api/workspace-backup/export-jobs/${requestId}`);expect(JSON.parse(init.body)).toEqual({ password: "correct horse battery", clientState: { "omb-drafts": "private draft" } });- expect(link.href).toBe("/api/workspace-backup/download/download-id");- expect(link.click).toHaveBeenCalledOnce();expect([...storage.values()]).not.toContain("correct horse battery");+ expect([...session.values()]).toEqual([requestId]);expect(render().html).not.toContain('value="correct horse battery"');expect(render().html).not.toContain('id="backup-export"');+ fixture.api.mockResolvedValueOnce({ state: "ready", id: "download-id", filename: "fixture.ombbackup", expiresAt: Date.now() + 60_000 })+ .mockResolvedValueOnce({ busy: false });+ const stopPolling = fixture.effects[1]();+ try {+ await flush();+ expect(fixture.api.mock.calls[2][0]).toBe(path);+ expect(link.href).toBe("/api/workspace-backup/download/download-id");+ expect(link.click).toHaveBeenCalledOnce();+ } finally { stopPolling?.(); }+ });++ it("recovers a saved export after reopening settings and offers a manual download", async () => {+ session.set("omb-backup-export-request", "e4238912-594a-44bf-a952-929eb79ac4cb");+ const link = { click: vi.fn() };+ vi.stubGlobal("document", { createElement: () => link });+ await ready();+ fixture.api.mockResolvedValueOnce({ state: "ready", id: "recovered-id", filename: "recovered.ombbackup", expiresAt: Date.now() + 60_000 })+ .mockResolvedValueOnce({ busy: false });+ const stopPolling = fixture.effects[1]();+ try {+ await flush();+ expect(fixture.api.mock.calls[1][0]).toBe("/api/workspace-backup/export-jobs/e4238912-594a-44bf-a952-929eb79ac4cb");+ expect(render().html).toContain('href="/api/workspace-backup/download/recovered-id"');+ expect(link.click).not.toHaveBeenCalled();+ } finally { stopPolling?.(); }+ });++ it("asks for a fresh export when the saved job is gone", async () => {+ session.set("omb-backup-export-request", "e4238912-594a-44bf-a952-929eb79ac4cb");+ await ready();+ const missing = Object.assign(new Error("Not found"), { status: 404 });+ fixture.api.mockRejectedValueOnce(missing).mockRejectedValueOnce(missing).mockResolvedValueOnce({ busy: false });+ vi.useFakeTimers();+ const stopPolling = fixture.effects[1]();+ try {+ await flush();+ expect(render().html).toContain("Reconnecting to check your backup");+ await vi.advanceTimersByTimeAsync(3_000);+ expect(render().html).toContain("Start another export and enter your backup password");+ expect(session.size).toBe(0);+ expect(fixture.api.mock.calls.some(([, init]) => init?.method === "POST")).toBe(false);+ } finally { stopPolling?.(); vi.useRealTimers(); }});- it("keeps the export dialog open with its reason when the export fails, so it can be tried again", async () => {+ it("keeps the export dialog open with its reason when the server refuses a new export", async () => {await ready();open("export");const passwords = render().nodes.filter((node) => node.type === "input" && node.props.type === "password");change(passwords[0], "correct horse battery"); change(passwords[1], "correct horse battery");- fixture.api.mockRejectedValueOnce(new Error("Disk full"));+ fixture.api.mockRejectedValueOnce(Object.assign(new Error("Another backup is running"), { status: 409 }));submit(formOf("backup-export")); await flush();const html = render().html;expect(html).toContain('id="backup-export"');- expect(html).toMatch(/role="alert"[^>]*>Disk full</);+ expect(html).toMatch(/role="alert"[^>]*>Another backup is running</);+ expect(session.size).toBe(0);});it("uploads a raw file, validates it, and requires exact REPLACE with the staged ID", async () => {diff --git a/src/components/WorkspaceBackupSettings.tsx b/src/components/WorkspaceBackupSettings.tsxindex b662bce69e..c2ac1788d9 100644--- a/src/components/WorkspaceBackupSettings.tsx+++ b/src/components/WorkspaceBackupSettings.tsx@@ -1,8 +1,10 @@-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";import { Loader2 } from "lucide-react";-import type { WorkspaceBackupSummary } from "../../shared/workspace-backup";+import type { WorkspaceBackupExportStatus, WorkspaceBackupSummary } from "../../shared/workspace-backup";import { api } from "@/state/store";import { intlLocale, t } from "@/lib/i18n";+import { randomUuid } from "@/lib/random-uuid";+import { serverErrorText } from "@/lib/server-error";import { collectWorkspaceClientState, WORKSPACE_RESTORE_MARKER } from "@/lib/workspace-backup-client";import { LearnMore, SETTINGS_INPUT, SettingRow, SettingsField, SettingsRows } from "./SettingsPrimitives";import { SettingsDialog } from "./settings/SettingsDialog";@@ -11,6 +13,25 @@ import { WorkspaceBackupRestartNotice, type BackupStatus } from "./WorkspaceBackexport { WorkspaceBackupRecovery, WorkspaceBackupRestartNotice } from "./WorkspaceBackupRecovery";const validPassword = (value: string) => value.length >= 12 && value.length <= 1024;+const EXPORT_REQUEST = "omb-backup-export-request";+const exportJobPath = (id: string) => `/api/workspace-backup/export-jobs/${encodeURIComponent(id)}`;+const downloadPath = (id: string) => `/api/workspace-backup/download/${encodeURIComponent(id)}`;++function savedExportRequest(): string | null {+ try { return sessionStorage.getItem(EXPORT_REQUEST); } catch { return null; }+}++function rememberExportRequest(id: string | null): void {+ try {+ if (id === null) sessionStorage.removeItem(EXPORT_REQUEST);+ else sessionStorage.setItem(EXPORT_REQUEST, id);+ } catch {}+}++function retryableExportRequest(error: unknown): boolean {+ const status = (error as { status?: number } | null)?.status;+ return status === undefined || status === 408 || status === 429 || status >= 500;+}export function WorkspaceBackupSummaryView({ summary }: { summary: WorkspaceBackupSummary }) {return <div className="rounded-[12px] border-[0.5px] border-(--settings-edge) bg-menu p-3">@@ -47,28 +68,91 @@ export function WorkspaceBackupSettings({ layout = BOTH_ROWS }: { layout?: (rowsconst [uploadedId, setUploadedId] = useState<string | null>(null);const [preview, setPreview] = useState<{ id: string; summary: WorkspaceBackupSummary } | null>(null);const [confirmation, setConfirmation] = useState("");- const [download, setDownload] = useState<{ url: string; filename: string } | null>(null);+ const [exportRequest, setExportRequest] = useState(savedExportRequest);+ const [exportJob, setExportJob] = useState<WorkspaceBackupExportStatus | null>(null);+ const [exportReconnecting, setExportReconnecting] = useState(false);+ const currentExport = useRef(exportRequest);+ const autoDownload = useRef<string | null>(null);const [exporting, setExporting] = useState(false);const [importing, setImporting] = useState(false);const [more, setMore] = useState(false);const fileInput = useRef<HTMLInputElement>(null);- const refresh = async () => {+ const refresh = useCallback(async () => {try {const result: BackupStatus = await api("/api/workspace-backup/status");if (alive.current) { setStatus(result); setError(null); }} catch (cause) {if (alive.current) { setStatus(null); setError(cause instanceof Error ? cause.message : String(cause)); }}- };+ }, []);useEffect(() => {alive.current = true;void refresh();return () => { alive.current = false; };- }, []);+ }, [refresh]);+ useEffect(() => {+ if (!exportRequest) return;+ const controller = new AbortController();+ const { signal } = controller;+ let timer: ReturnType<typeof setTimeout>;+ let retryMissing = true;+ const poll = async () => {+ try {+ const job = await api<WorkspaceBackupExportStatus>(exportJobPath(exportRequest), { background: true, timeoutMs: 10_000, signal });+ if (signal.aborted || currentExport.current !== exportRequest) return;+ if (job.state !== "running" && job.state !== "ready" && job.state !== "failed") throw new Error("Invalid backup export status.");+ retryMissing = false;+ setExportJob(job);+ setExportReconnecting(false);+ if (job.state === "running") {+ timer = setTimeout(() => void poll(), 2_000);+ return;+ }+ if (autoDownload.current === exportRequest) {+ autoDownload.current = null;+ if (job.state === "ready") {+ const link = document.createElement("a");+ link.href = downloadPath(job.id);+ link.download = job.filename;+ document.body.append(link);+ link.click();+ link.remove();+ }+ }+ if (job.state === "ready") {+ const remaining = job.expiresAt - Date.now();+ timer = setTimeout(() => void poll(), remaining > 0 ? remaining : 30_000);+ }+ void refresh();+ } catch (cause) {+ if (signal.aborted || currentExport.current !== exportRequest) return;+ const missing = (cause as { status?: number } | null)?.status === 404;+ if (retryableExportRequest(cause) || (missing && retryMissing)) {+ if (missing) retryMissing = false;+ setExportReconnecting(true);+ timer = setTimeout(() => void poll(), 3_000);+ return;+ }+ if (savedExportRequest() === exportRequest) rememberExportRequest(null);+ currentExport.current = null;+ setExportRequest(null);+ setExportReconnecting(false);+ if (autoDownload.current === exportRequest) autoDownload.current = null;+ setExportJob({ state: "failed", error: missing+ ? t("backup.exportUnavailable")+ : cause instanceof Error ? cause.message : t("backup.exportUnavailable") });+ void refresh();+ }+ };+ void poll();+ return () => { controller.abort(); clearTimeout(timer); };+ }, [exportRequest, refresh]);++ const exportPending = Boolean(exportRequest) && (exportJob === null || exportJob.state === "running");const perform = async (operation: NonNullable<typeof busy>, work: () => Promise<void>) => {- if (lock.current || !status || status.busy || status.pendingRestore) return;+ if (lock.current || exportPending || !status || status.busy || status.pendingRestore) return;lock.current = true;setBusy(operation);setError(null);@@ -79,20 +163,26 @@ export function WorkspaceBackupSettings({ layout = BOTH_ROWS }: { layout?: (rowsconst exportBackup = () => perform("export", async () => {if (!validPassword(exportPassword) || exportPassword !== confirmPassword) return;- const result: { id: string; filename: string } = await api("/api/workspace-backup/export", {- method: "POST", body: JSON.stringify({ password: exportPassword, clientState: collectWorkspaceClientState() }),- });- if (alive.current) { setExportPassword(""); setConfirmPassword(""); }+ const id = randomUuid();+ rememberExportRequest(id);+ try {+ await api(exportJobPath(id), {+ method: "POST", timeoutMs: 10_000,+ body: JSON.stringify({ password: exportPassword, clientState: collectWorkspaceClientState() }),+ });+ } catch (cause) {+ if (!retryableExportRequest(cause)) {+ if (savedExportRequest() === id) rememberExportRequest(exportRequest);+ throw cause;+ }+ }if (!alive.current) return;- const url = `/api/workspace-backup/download/${encodeURIComponent(result.id)}`;- setDownload({ url, filename: result.filename });- const link = document.createElement("a");- link.href = url;- link.download = result.filename;- document.body.append(link);- link.click();- link.remove();- setExporting(false);+ autoDownload.current = id;+ currentExport.current = id;+ setExportJob(null);+ setExportReconnecting(false);+ setExportRequest(id);+ closeExport();});const previewBackup = () => perform("preview", async () => {@@ -135,7 +225,7 @@ export function WorkspaceBackupSettings({ layout = BOTH_ROWS }: { layout?: (rowsif (alive.current) { setStatus({ busy: false, pendingRestore: true, restarts: restarting }); setPreview(null); setConfirmation(""); }});- const disabled = busy !== null || !status || status.busy || Boolean(status.pendingRestore);+ const disabled = busy !== null || exportPending || !status || status.busy || Boolean(status.pendingRestore);const closeExport = () => { setExporting(false); setExportPassword(""); setConfirmPassword(""); };const closeImport = () => { setImporting(false); setFile(null); setUploadedId(null); setPreview(null); setConfirmation(""); setImportPassword(""); };if (status?.pendingRestore) {@@ -146,8 +236,11 @@ export function WorkspaceBackupSettings({ layout = BOTH_ROWS }: { layout?: (rowsexportRow: <SettingRow title={t("backup.export")} subtitle={<>{t("backup.exportShort")}{" "}<LearnMore onClick={() => setMore((open) => !open)} /></>}message={<>{more && <span data-backup-more="" className="flex flex-col gap-1"><span>{t("backup.scope")}</span><span>{t("backup.excluded")}</span><span>{t("backup.privacy")}</span></span>}- {download && <a href={download.url} download={download.filename} className="break-all text-accent-text hover:underline">{t("backup.downloadAgain", { filename: download.filename })}</a>}- {(!status || status.busy) && <span role="status">{status?.busy ? t("backup.serverBusy") : t("backup.checkStatus")}{" "}<button type="button" onClick={() => void refresh()} className="cursor-pointer text-accent-text hover:underline">{t("connectors.action.retry")}</button></span>}+ {exportJob?.state === "ready" && <a href={downloadPath(exportJob.id)} download={exportJob.filename} className="break-all text-accent-text hover:underline">{t("backup.downloadAgain", { filename: exportJob.filename })}</a>}+ {exportReconnecting && <span role="status">{t("backup.exportReconnecting")}</span>}+ {exportPending && !exportReconnecting && <span role="status">{t("backup.exporting")}</span>}+ {exportJob?.state === "failed" && <span role="alert" className="block break-words text-danger">{serverErrorText(exportJob, exportJob.error)}</span>}+ {!exportPending && (!status || status.busy) && <span role="status">{status?.busy ? t("backup.serverBusy") : t("backup.checkStatus")}{" "}<button type="button" onClick={() => void refresh()} className="cursor-pointer text-accent-text hover:underline">{t("connectors.action.retry")}</button></span>}{error && <span role="alert" className="block break-words text-danger">{error}</span>}</>}><button type="button" className="ui-button" disabled={disabled} data-backup-export="" onClick={() => setExporting(true)}>{t("backup.exportAction")}</button>diff --git a/src/locales/en.json b/src/locales/en.jsonindex a172bf1117..1c3eac6ba9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6449,6 +6449,8 @@"backup.exportPassword": "Backup password","backup.confirmPassword": "Confirm backup password","backup.exporting": "Creating encrypted backup…",+ "backup.exportReconnecting": "Reconnecting to check your backup…",+ "backup.exportUnavailable": "This backup is no longer available. Start another export and enter your backup password.","backup.downloadAgain": "Download {filename}","backup.import": "Import backup","backup.importHint": "Choose an encrypted .ombbackup file and validate it before changing anything. Backups support up to 10 GB of installation data. Older team backups and shareable templates can still be imported from Templates.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 20958d5738..b3cff3c38a 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6112,6 +6112,8 @@"backup.exportPassword": "Senha do backup","backup.confirmPassword": "Confirmar a senha do backup","backup.exporting": "Criando backup criptografado…",+ "backup.exportReconnecting": "Reconectando para verificar seu backup…",+ "backup.exportUnavailable": "Este backup não está mais disponível. Exporte novamente e informe a senha do backup.","backup.downloadAgain": "Baixar {filename}","backup.import": "Importar backup","backup.importHint": "Antes de alterar qualquer coisa, escolha e valide um arquivo .ombbackup criptografado. Os backups aceitam até 10 GB de dados da instalação. Você ainda pode importar backups de equipe mais antigos e modelos compartilháveis em Modelos.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 6a12df3ad1..ea9691f4f3 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -5843,6 +5843,8 @@"backup.exportPassword": "備份密碼","backup.confirmPassword": "確認備份密碼","backup.exporting": "正在建立加密備份…",+ "backup.exportReconnecting": "正在重新連線以檢查備份…",+ "backup.exportUnavailable": "此備份已無法使用。請重新匯出並輸入備份密碼。","backup.downloadAgain": "下載 {filename}","backup.import": "匯入備份","backup.importHint": "選取加密的 .ombbackup 檔案,並在變更任何內容前先驗證。備份最多支援 10 GB 安裝實例資料。較舊的團隊備份與可分享範本仍可從「範本」匯入。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 25897f0f4e..e33610a9fa 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -5842,6 +5842,8 @@"backup.exportPassword": "备份密码","backup.confirmPassword": "确认备份密码","backup.exporting": "正在创建加密备份…",+ "backup.exportReconnecting": "正在重新连接以检查备份…",+ "backup.exportUnavailable": "此备份已不可用。请重新导出并输入备份密码。","backup.downloadAgain": "下载 {filename}","backup.import": "导入备份","backup.importHint": "选择加密的 .ombbackup 文件,并在变更任何内容前先验证。备份最多支持 10 GB 安装数据。较旧的团队备份与可分享模板仍可从「模板」导入。",