Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(backup): restart My Cloud's server to finish a restore
Bugfixer 20097ce586480
diff --git a/server/index.ts b/server/index.tsindex 33ca6c1391..c7bbdc6a64 100644--- a/server/index.ts+++ b/server/index.ts@@ -12109,7 +12109,7 @@ const workspaceBackupAccess = {}, keepLocked),status: () => ({ busy: workspaceMaintenance.active, pendingRestore: workspaceMaintenance.pendingRestore }),};-const workspaceCopyAccess = { dataDir: DATA_DIR, appVersion: serverVersion(), readBody, restored: workspaceRestore, ...workspaceBackupAccess };+const workspaceCopyAccess = { dataDir: DATA_DIR, appVersion: serverVersion(), readBody, restored: workspaceRestore, ...workspaceBackupAccess, ...(CLOUD_HOME ? { restart: () => { restartRequested = true; gracefulShutdown(); } } : {}) };const workspaceBackupRoutes = createWorkspaceBackupRoutes(workspaceCopyAccess);let restartRequested = false;const cloudMoveRoutes = createCloudMoveRoutes();diff --git a/server/workspace-backup-http.test.ts b/server/workspace-backup-http.test.tsindex 931327e71a..d3ca3fa46f 100644--- a/server/workspace-backup-http.test.ts+++ b/server/workspace-backup-http.test.ts@@ -47,6 +47,11 @@ beforeEach(async () => {archive.stage.mockImplementation(async () => fakeArchive());archive.commit.mockImplementation((_dataDir: string, id: string) => ({ id, restartRequired: true }));archive.remove.mockImplementation((_dataDir: string, id: string) => rmSync(join(dataDir, ".backups", id), { recursive: true, force: true }));+ await listen();+});++/** Serves the backup routes; `extra` adds options such as a launcher restart. */+async function listen(extra: Partial<Parameters<typeof createWorkspaceBackupRoutes>[0]> = {}) {const authenticate = (req: IncomingMessage) => resolveRequestAuth(req, { sessions, cookieName: "fixture", streamPath: "/api/events", url: new URL(req.url!, url) });const routes = createWorkspaceBackupRoutes({dataDir, appVersion: "0.1.71", restored: {},@@ -67,6 +72,7 @@ beforeEach(async () => {},status: () => ({ busy: maintenance.active, pendingRestore: maintenance.pendingRestore }),exclusive: (work, keepLocked) => maintenance.run(work, { idle: () => true, pause: () => {}, resume: () => {}, flush: async () => {} }, keepLocked),+ ...extra,});server = createServer(async (req, res) => {const path = new URL(req.url!, url).pathname;@@ -92,7 +98,7 @@ beforeEach(async () => {const address = server.address();if (!address || typeof address === "string") throw new Error("Fixture did not listen");url = `http://127.0.0.1:${address.port}`;-});+}afterEach(async () => {server?.closeAllConnections();@@ -171,3 +177,36 @@ it("accepts drafts between 1 and 2 MiB and enforces the preference cap in UTF-8expect(archive.create).toHaveBeenCalledOnce();expect(readdirSync(join(dataDir, ".backups"))).toHaveLength(1);});++async function stagedRestore() {+ const uploaded = await fetch(`${url}/api/workspace-backup/upload`, { method: "POST", headers: { authorization: `Bearer ${admin.token}` }, body: "fixture bytes" }).then((response) => response.json()) as { id: string };+ return await post("/api/workspace-backup/preview", { id: uploaded.id, password: PASSWORD }).then((response) => response.json()) as { id: string };+}++function status() {+ return fetch(`${url}/api/workspace-backup/status`, { headers: { authorization: `Bearer ${admin.token}` } }).then((response) => response.json()) as Promise<Record<string, unknown>>;+}++it("restarts a server its launcher starts again (My Cloud) once a restore commits, after answering", async () => {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ const restart = vi.fn();+ await listen({ restart });+ expect(await status()).toMatchObject({ restarts: true, pendingRestore: false });+ const preview = await stagedRestore();+ expect(restart).not.toHaveBeenCalled();+ const restored = await post("/api/workspace-backup/restore", { id: preview.id, confirmation: "REPLACE" });+ expect(restored.status).toBe(200);+ expect(await restored.json()).toMatchObject({ restarting: true, restoreId: preview.id });+ await vi.waitFor(() => expect(restart).toHaveBeenCalledTimes(1));+ expect(await status()).toMatchObject({ restarts: true, pendingRestore: true });+});++it("leaves the restart to the person where no launcher restarts the server", async () => {+ expect(await status()).not.toHaveProperty("restarts");+ const preview = await stagedRestore();+ const restored = await post("/api/workspace-backup/restore", { id: preview.id, confirmation: "REPLACE" });+ expect(restored.status).toBe(200);+ expect(await restored.json()).not.toHaveProperty("restarting");+ expect(await status()).toMatchObject({ pendingRestore: true });+});diff --git a/server/workspace-backup-http.ts b/server/workspace-backup-http.tsindex 2a59fc7d8b..08e902e252 100644--- a/server/workspace-backup-http.ts+++ b/server/workspace-backup-http.ts@@ -39,6 +39,9 @@ export function createWorkspaceBackupRoutes(options: {authorized: (req: IncomingMessage, auth: RequestAuth) => boolean;status: () => { busy: boolean; pendingRestore: boolean };restored: RestoreResult;+ /** Starts this server again so startup installs a committed restore. Given only where a launcher always starts it+ * again (My Cloud), since the person there has no app to quit or process to restart. */+ restart?: () => void;}) {const artifacts = new Map<string, Artifact>();let operating = false;@@ -105,6 +108,7 @@ export function createWorkspaceBackupRoutes(options: {if (method === "GET" && path === `${PREFIX}/status`) {json(res, 200, {...options.status(),+ ...(options.restart ? { restarts: true } : {}),lastRestoreId: options.restored.restored ? options.restored.id : null,safetyCopyPath: options.restored.safetyCopyPath ?? null,});@@ -193,7 +197,10 @@ export function createWorkspaceBackupRoutes(options: {return commitPendingWorkspaceRestore(options.dataDir, body.id);}, true));artifacts.delete(body.id);- json(res, 200, { ...result, restoreId: body.id });+ const restart = options.restart;+ json(res, 200, { ...result, restoreId: body.id, ...(restart ? { restarting: true } : {}) });+ // Answer first, so the browser knows to wait for the server to come back; restart even if it hung up.+ if (restart) { if (res.closed) restart(); else res.once("close", restart); }return true;}json(res, 404, { error: "Unknown backup operation." });diff --git a/src/components/WorkspaceBackupSettings.test.ts b/src/components/WorkspaceBackupSettings.test.tsindex 0d62aaf4f0..6ad7bcabdf 100644--- a/src/components/WorkspaceBackupSettings.test.ts+++ b/src/components/WorkspaceBackupSettings.test.ts@@ -21,10 +21,10 @@ function nodes(value: ReactNode): Node[] {const node = value as Node;return [node, ...Children.toArray(node.props.children).flatMap(nodes)];}-function render(recovery: boolean | "restart" = false) {+function render(recovery: boolean | "restart" | "cloud" = false) {fixture.index = 0; fixture.effects = [];let tree: ReactNode;- function Capture() { tree = recovery === "restart" ? WorkspaceBackupRestartNotice() : recovery ? WorkspaceBackupRecovery({ children: createElement("p", null, "Normal app") }) : WorkspaceBackupSettings(); return tree; }+ 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));return { html, nodes: nodes(tree) };}@@ -146,6 +146,47 @@ describe("Settings full backups", () => {expect(storage.has("omb-pending-workspace-restore")).toBe(false); expect(window.location.reload).toHaveBeenCalledOnce();});+ it("on a server that restarts itself, waits instead of asking to quit, then carries on once the restore is installed", async () => {+ storage.set("omb-pending-workspace-restore", "stage-id");+ fixture.api.mockResolvedValueOnce({ busy: true, pendingRestore: true, restarts: true });+ render(true); fixture.effects[0](); await flush();+ expect(render(true).html).toContain("is restarting to finish it");+ expect(render(true).html).not.toContain("Fully quit");+ vi.useFakeTimers();+ try {+ fixture.values = [];+ const view = render("cloud");+ expect(view.html).toContain("is restarting to finish it");+ expect(view.nodes.some(node => node.type === "button")).toBe(false);+ const stop = fixture.effects[0]() as () => void;+ fixture.api.mockResolvedValueOnce({ busy: true, pendingRestore: true });+ await vi.advanceTimersByTimeAsync(3_000);+ expect(window.location.reload).not.toHaveBeenCalled();+ fixture.api.mockResolvedValueOnce({});+ await vi.advanceTimersByTimeAsync(3_000);+ expect(window.location.reload).not.toHaveBeenCalled();+ fixture.api.mockResolvedValueOnce({ busy: false, pendingRestore: false, lastRestoreId: "stage-id" });+ await vi.advanceTimersByTimeAsync(3_000);+ expect(window.location.reload).toHaveBeenCalledOnce();+ await vi.advanceTimersByTimeAsync(9_000);+ expect(window.location.reload).toHaveBeenCalledOnce();+ stop();+ } finally { vi.useRealTimers(); }+ expect(storage.get("omb-pending-workspace-restore")).toBe("stage-id");+ });++ it("on a server that restarts itself, reloads to sign-in when the restored workspace does not know this browser", async () => {+ vi.useFakeTimers();+ try {+ render("cloud");+ const stop = fixture.effects[0]() as () => void;+ fixture.api.mockRejectedValueOnce(Object.assign(new Error("Sign in"), { status: 401 }));+ await vi.advanceTimersByTimeAsync(3_000);+ expect(window.location.reload).toHaveBeenCalledOnce();+ stop();+ } finally { vi.useRealTimers(); }+ });+it("offers a real desktop restart without clearing the restore marker or drafts, once only", async () => {const relaunch = vi.fn().mockResolvedValue(true);vi.stubGlobal("window", { ...window, ogb: { relaunch } });diff --git a/src/components/WorkspaceBackupSettings.tsx b/src/components/WorkspaceBackupSettings.tsxindex f7ad68f198..b61b9f38cc 100644--- a/src/components/WorkspaceBackupSettings.tsx+++ b/src/components/WorkspaceBackupSettings.tsx@@ -6,16 +6,38 @@ import { intlLocale, t } from "@/lib/i18n";import { applyWorkspaceClientState, collectWorkspaceClientState, WORKSPACE_RESTORE_MARKER } from "@/lib/workspace-backup-client";import { Card } from "./SettingsPrimitives";-type BackupStatus = { busy: boolean; pendingRestore?: boolean; lastRestoreId?: string };+type BackupStatus = { busy: boolean; pendingRestore?: boolean; restarts?: boolean; lastRestoreId?: string };const inputClass = "w-full rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[14px] text-ink disabled:opacity-50";const buttonClass = "cursor-pointer inline-flex items-center justify-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-accent-ink disabled:opacity-40";const validPassword = (value: string) => value.length >= 12 && value.length <= 1024;-/** A renderer reload cannot apply a restore; the owning server must restart. */-export function WorkspaceBackupRestartNotice({ onRetry }: { onRetry?: () => void } = {}) {+/** A renderer reload cannot apply a restore; the owning server must restart. A server that restarts itself (My Cloud)+ * is waited for, then the page carries on as after a reload. */+export function WorkspaceBackupRestartNotice({ onRetry, serverRestarts = false }: { onRetry?: () => void; serverRestarts?: boolean } = {}) {const [restarting, setRestarting] = useState(false);const [error, setError] = useState(false);const lock = useRef(false);+ const retry = useRef(onRetry);+ retry.current = onRetry;+ useEffect(() => {+ if (!serverRestarts) return;+ let alive = true;+ let timer: ReturnType<typeof setTimeout>;+ // One check at a time, so requests do not pile up while the server is down.+ // A restored workspace may not know this browser's session: a reload shows sign-in.+ const check = () => api("/api/workspace-backup/status").then((status: BackupStatus) => status.pendingRestore === false ? "installed" : "wait",+ (cause: unknown) => cause instanceof Error && "status" in cause && cause.status === 401 ? "signedOut" : "wait").then((state) => {+ if (!alive) return;+ if (state === "wait") timer = setTimeout(check, 3_000);+ else if (state === "installed" && retry.current) retry.current();+ else window.location.reload();+ });+ timer = setTimeout(check, 3_000);+ return () => { alive = false; clearTimeout(timer); };+ }, [serverRestarts]);+ if (serverRestarts) return <div role="status" className="flex max-w-lg items-center gap-3 text-[14px]">+ <Loader2 aria-hidden="true" size={15} className="animate-spin" /><p>{t("backup.serverRestarting")}</p>+ </div>;const relaunch = typeof window !== "undefined" && !window.ogb?.remoteClient?.active ? window.ogb?.relaunch : undefined;const restart = async () => {if (!relaunch || lock.current || restarting) return;@@ -134,17 +156,18 @@ export function WorkspaceBackupSettings() {// The stage ID is the restore ID: persist it before the request so a lost response still lets this browser recover// its drafts at boot.localStorage.setItem(WORKSPACE_RESTORE_MARKER, preview.id);+ let restarting = false;try {- await api("/api/workspace-backup/restore", {+ ({ restarting = false } = await api("/api/workspace-backup/restore", {method: "POST", body: JSON.stringify({ id: preview.id, confirmation: "REPLACE" }),- });+ }) as { restarting?: boolean });} catch (cause) {if (cause instanceof Error && "status" in cause && cause.status === 404 && alive.current) {setPreview(null); setUploadedId(null); setConfirmation("");}throw cause;}- if (alive.current) { setStatus({ busy: false, pendingRestore: true }); setPreview(null); setConfirmation(""); }+ if (alive.current) { setStatus({ busy: false, pendingRestore: true, restarts: restarting }); setPreview(null); setConfirmation(""); }});const disabled = busy !== null || !status || status.busy || Boolean(status.pendingRestore);@@ -156,7 +179,7 @@ export function WorkspaceBackupSettings() {</section><div className="flex flex-col gap-4">{error && <p role="alert" className="break-words px-4 text-[13px] text-danger">{error}</p>}- {status?.pendingRestore ? <div className="rounded-xl border border-warning/40 bg-warning/10 p-4 text-ink"><WorkspaceBackupRestartNotice /></div> : <>+ {status?.pendingRestore ? <div className="rounded-xl border border-warning/40 bg-warning/10 p-4 text-ink"><WorkspaceBackupRestartNotice serverRestarts={status.restarts === true} /></div> : <>{(!status || status.busy) && <div role="status" className="flex items-center gap-3 px-4 text-[13px] text-ink-secondary"><span>{status?.busy ? t("backup.serverBusy") : t("backup.checkStatus")}</span><button type="button" onClick={() => void refresh()} className="cursor-pointer underline">{t("connectors.action.retry")}</button></div>}<Card title={t("backup.export")} subtitle={t("backup.passwordHint")}><form className="flex flex-col gap-3" onSubmit={(event) => { event.preventDefault(); void exportBackup(); }}>@@ -196,6 +219,7 @@ export function WorkspaceBackupRecovery({ children }: { children: ReactNode }) {const [ready, setReady] = useState(!restoreId);const [error, setError] = useState<string | null>(null);const [restartRequired, setRestartRequired] = useState(false);+ const [serverRestarts, setServerRestarts] = useState(false);const [attempt, setAttempt] = useState(0);useEffect(() => {if (!restoreId) return;@@ -204,7 +228,7 @@ export function WorkspaceBackupRecovery({ children }: { children: ReactNode }) {void (async () => {const status: BackupStatus = await api("/api/workspace-backup/status");if (!alive) return;- if (status.pendingRestore) { setRestartRequired(true); return; }+ if (status.pendingRestore) { setServerRestarts(status.restarts === true); setRestartRequired(true); return; }if (status.lastRestoreId !== restoreId) {localStorage.removeItem(WORKSPACE_RESTORE_MARKER);setReady(true);@@ -226,7 +250,7 @@ export function WorkspaceBackupRecovery({ children }: { children: ReactNode }) {} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }};return <main className="flex h-dvh flex-col items-center justify-center gap-4 bg-app p-6 text-ink">- {restartRequired ? <WorkspaceBackupRestartNotice onRetry={() => { setRestartRequired(false); setAttempt((value) => value + 1); }} /> : <p className="max-w-lg text-[14px]">{t("backup.recovering")}</p>}+ {restartRequired ? <WorkspaceBackupRestartNotice serverRestarts={serverRestarts} onRetry={() => { setRestartRequired(false); setAttempt((value) => value + 1); }} /> : <p className="max-w-lg text-[14px]">{t("backup.recovering")}</p>}{error && <p role="alert" className="max-w-lg break-words text-[13px] text-danger">{error}</p>}{error && <button type="button" className={buttonClass} onClick={() => { setRestartRequired(false); setAttempt((value) => value + 1); }}>{t("connectors.action.retry")}</button>}{error && <>diff --git a/src/locales/en.json b/src/locales/en.jsonindex 9731a7eb9f..216e56acb1 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6002,6 +6002,7 @@"backup.confirmReplace": "Type REPLACE to confirm","backup.replace": "Replace installation","backup.restoring": "Preparing replacement…",+ "backup.serverRestarting": "The backup is ready to restore. {app} is restarting to finish it. This page carries on by itself in a minute or two.","backup.restart": "The backup is ready to restore. Fully quit {app} and reopen it to finish. For a self-hosted server, restart the server process, then reload this browser. Do not just close this window.","backup.restartDesktop": "Your backup is ready. Restart {app} to finish restoring it. Closing this window will not restart the server.","backup.restartAction": "Restart and restore",