Skip to content

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

fix: 清理中断的备份并校准过期检查

Zhehui Bi05088509d9db
diff --git a/scripts/testing/workspace-backup-ui.e2e.test.ts b/scripts/testing/workspace-backup-ui.e2e.test.ts
index bc5fcc7a53..6d95eb578d 100644
--- a/scripts/testing/workspace-backup-ui.e2e.test.ts
+++ b/scripts/testing/workspace-backup-ui.e2e.test.ts
@@ -69,7 +69,7 @@ describe("full backup Settings in the real renderer", () => {
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: 'ready', id: 'download-stage', filename: 'fixture.ombbackup', expiresInMs: 60 * 60_000 }
: { state: 'running' });
}
if (path.endsWith('/upload')) return reply({ id: 'uploaded-file' });
diff --git a/server/workspace-backup-http.test.ts b/server/workspace-backup-http.test.ts
index f3b568eb44..949940f8a4 100644
--- a/server/workspace-backup-http.test.ts
+++ b/server/workspace-backup-http.test.ts
@@ -1,6 +1,6 @@
// Archive work is mocked so revocation can be held at a deterministic boundary.
import { randomUUID } from "node:crypto";
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { createServer, request, type IncomingMessage, type Server } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -181,7 +181,7 @@ it("reports a failed job when polled and accepts a new explicit export", async (
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) });
+ await expect.poll(async () => (await get(retry)).json()).toMatchObject({ state: "ready", expiresInMs: expect.any(Number) });
expect(archive.create).toHaveBeenCalledTimes(2);
});
@@ -191,12 +191,12 @@ it("retains each successful async archive for one hour from completion", async (
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);
+ const { expiresInMs } = await (await get(first)).json() as { expiresInMs: number };
+ expect(expiresInMs).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);
+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + expiresInMs);
try {
expect((await get(first)).status).toBe(404);
expect((await get(download)).status).toBe(404);
@@ -204,6 +204,24 @@ it("retains each successful async archive for one hour from completion", async (
} finally { clock.mockRestore(); }
});
+it("schedules cleanup for an interrupted export that left a snapshot but no archive", async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ const id = randomUUID();
+ const directory = join(dataDir, ".backups", id);
+ mkdirSync(join(directory, "snapshot"), { recursive: true });
+ const createdAt = new Date(Date.now() - 60 * 60_000 + 5_000);
+ utimesSync(directory, createdAt, createdAt);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ await listen();
+ expect(existsSync(directory)).toBe(true);
+ await vi.advanceTimersByTimeAsync(5_001);
+ expect(archive.remove).toHaveBeenCalledWith(dataDir, id);
+ expect(existsSync(directory)).toBe(false);
+ } finally { vi.useRealTimers(); }
+});
+
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));
diff --git a/server/workspace-backup-http.ts b/server/workspace-backup-http.ts
index 62142120e2..77f6a22695 100644
--- a/server/workspace-backup-http.ts
+++ b/server/workspace-backup-http.ts
@@ -25,6 +25,9 @@ const exportSchema = z.object({ password: passwordSchema, clientState: z.record(
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; keepUntilExpiry?: boolean };
type RestoreResult = { id?: string; restored?: boolean; safetyCopyPath?: string; clientState?: Record<string, string> };
+type ExportJob =
+ | Exclude<WorkspaceBackupExportStatus, { state: "ready" }>
+ | { state: "ready"; id: string; filename: string; expiresAt: number };
function backupError(error: unknown) {
return {
@@ -53,7 +56,7 @@ export function createWorkspaceBackupRoutes(options: {
restart?: () => void;
}) {
const artifacts = new Map<string, Artifact>();
- const exportJobs = new Map<string, WorkspaceBackupExportStatus>();
+ const exportJobs = new Map<string, ExportJob>();
let operating = false;
const json = (res: ServerResponse, status: number, body: unknown) => {
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
@@ -78,7 +81,7 @@ export function createWorkspaceBackupRoutes(options: {
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();
+ else setTimeout(reclaim, Math.min(delay, EXPIRES_MS)).unref();
}
const uploads = join(root, "uploads");
if (!existsSync(uploads) || lstatSync(uploads).isSymbolicLink()) return;
@@ -140,7 +143,7 @@ export function createWorkspaceBackupRoutes(options: {
}
});
}
- function finishExport(key: string, status: Exclude<WorkspaceBackupExportStatus, { state: "running" }>) {
+ function finishExport(key: string, status: Exclude<ExportJob, { state: "running" }>) {
exportJobs.set(key, status);
setTimeout(() => {
exportJobs.delete(key);
@@ -184,9 +187,12 @@ export function createWorkspaceBackupRoutes(options: {
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);
+ const status: WorkspaceBackupExportStatus = existing.state === "ready"
+ ? { state: "ready", id: existing.id, filename: existing.filename, expiresInMs: existing.expiresAt - Date.now() }
+ : existing;
+ if (status.state === "ready" && status.expiresInMs <= 0) throw failure("This backup has expired. Start another export.", 404);
+ json(res, input ? 202 : 200, status);
return true;
}
if (!input) throw failure("This backup export is no longer available. Start another export.", 404);
diff --git a/shared/workspace-backup.ts b/shared/workspace-backup.ts
index 6443ba0750..e889688b13 100644
--- a/shared/workspace-backup.ts
+++ b/shared/workspace-backup.ts
@@ -29,7 +29,7 @@ export type WorkspaceBackupClientState = Record<string, string>;
export type WorkspaceBackupExportStatus =
| { state: "running" }
- | { state: "ready"; id: string; filename: string; expiresAt: number }
+ | { state: "ready"; id: string; filename: string; expiresInMs: number }
| { state: "failed"; error: string; errorKey?: string; errorParams?: Record<string, string | number> };
export interface WorkspaceBackupPrivateMetadata {
diff --git a/src/components/WorkspaceBackupSettings.test.ts b/src/components/WorkspaceBackupSettings.test.ts
index 622b2106d1..3a5fb4308d 100644
--- a/src/components/WorkspaceBackupSettings.test.ts
+++ b/src/components/WorkspaceBackupSettings.test.ts
@@ -95,7 +95,7 @@ describe("Settings full backups", () => {
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 })
+ fixture.api.mockResolvedValueOnce({ state: "ready", id: "download-id", filename: "fixture.ombbackup", expiresInMs: 60_000 })
.mockResolvedValueOnce({ busy: false });
const stopPolling = fixture.effects[1]();
try {
@@ -111,15 +111,21 @@ describe("Settings full backups", () => {
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 })
+ fixture.api.mockResolvedValueOnce({ state: "ready", id: "recovered-id", filename: "recovered.ombbackup", expiresInMs: 2_000 })
.mockResolvedValueOnce({ busy: false });
+ vi.useFakeTimers();
+ vi.setSystemTime(Date.now() - 10 * 60_000);
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?.(); }
+ fixture.api.mockRejectedValueOnce(Object.assign(new Error("Expired"), { status: 404 })).mockResolvedValueOnce({ busy: false });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(render().html).not.toContain("recovered.ombbackup");
+ expect(render().html).toContain("Start another export and enter your backup password");
+ } finally { stopPolling?.(); vi.useRealTimers(); }
});
it("asks for a fresh export when the saved job is gone", async () => {
diff --git a/src/components/WorkspaceBackupSettings.tsx b/src/components/WorkspaceBackupSettings.tsx
index c2ac1788d9..9e7346133b 100644
--- a/src/components/WorkspaceBackupSettings.tsx
+++ b/src/components/WorkspaceBackupSettings.tsx
@@ -121,10 +121,7 @@ export function WorkspaceBackupSettings({ layout = BOTH_ROWS }: { layout?: (rows
link.remove();
}
}
- if (job.state === "ready") {
- const remaining = job.expiresAt - Date.now();
- timer = setTimeout(() => void poll(), remaining > 0 ? remaining : 30_000);
- }
+ if (job.state === "ready") timer = setTimeout(() => void poll(), Math.max(1_000, job.expiresInMs));
void refresh();
} catch (cause) {
if (signal.aborted || currentExport.current !== exportRequest) return;