fix(onboarding): streamline backup restore

This commit is contained in:
Thomas Camlong authored and ajnart committed 2026-08-14 11:32:13 +02:00
1 parent 30cb066b7f
commit 174e0a7606
7 files changed
+63 -17

No files matched your search

+3
View File
@@ -53,6 +53,9 @@ Before restoring, Homarr uses **sql.js WASM** to analyze the backup directly in
Type `I understand` to acknowledge that restoring will replace your current database. This cannot be undone. Type `I understand` to acknowledge that restoring will replace your current database. This cannot be undone.
During first-run onboarding, the database is still empty, so the restore preview goes directly to **Restore Database**
without the extra typed confirmation. After Homarr restarts, onboarding opens the restored default home board.
### 4. Restore ### 4. Restore
The backup ZIP is sent to the server, validated, and applied. After a successful restore: The backup ZIP is sent to the server, validated, and applied. After a successful restore:
@@ -172,6 +172,29 @@ const reEncryptSecrets = (tempDb: InstanceType<typeof Database>, importedKeyHex:
transaction(); transaction();
}; };
const getHomeBoardName = (tempDb: InstanceType<typeof Database>): string | null => {
const row = tempDb
.prepare(
`SELECT "name" FROM (
SELECT "board"."name" AS "name", 0 AS "priority"
FROM "group"
INNER JOIN "board" ON "board"."id" = "group"."home_board_id"
WHERE "group"."name" = 'everyone'
UNION ALL
SELECT "board"."name" AS "name", 1 AS "priority"
FROM "user"
INNER JOIN "board" ON "board"."id" = "user"."home_board_id"
UNION ALL
SELECT "board"."name" AS "name", 2 AS "priority"
FROM "board"
)
ORDER BY "priority", "name"
LIMIT 1`,
)
.get() as { name: string } | undefined;
return row?.name ?? null;
};
const isOnboardingActiveAsync = async (): Promise<boolean> => { const isOnboardingActiveAsync = async (): Promise<boolean> => {
const onboardingRow = await db.query.onboarding.findFirst(); const onboardingRow = await db.query.onboarding.findFirst();
if (!onboardingRow) return false; if (!onboardingRow) return false;
@@ -289,6 +312,8 @@ export async function POST(req: Request) {
reEncryptSecrets(tempDb, importedKey); reEncryptSecrets(tempDb, importedKey);
} }
const homeBoardName = getHomeBoardName(tempDb);
tempDb.close(); tempDb.close();
tempDb = null; tempDb = null;
@@ -313,6 +338,7 @@ export async function POST(req: Request) {
success: true, success: true,
message: "Database restored. Server is restarting...", message: "Database restored. Server is restarting...",
restartAfterMs: RESTART_DELAY_MS, restartAfterMs: RESTART_DELAY_MS,
homeBoardName,
}); });
} catch (error) { } catch (error) {
console.error("[backup/import] Restore failed:", error); console.error("[backup/import] Restore failed:", error);
@@ -128,7 +128,11 @@ describe("POST /api/backup/import", () => {
const response = await POST(createImportRequest(backup)); const response = await POST(createImportRequest(backup));
expect(response.status).toBe(200); expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ success: true, restartAfterMs: 500 }); await expect(response.json()).resolves.toMatchObject({
success: true,
restartAfterMs: 500,
homeBoardName: "Restored board",
});
expect(readBoardNames(activeDatabasePath)).toEqual(["Restored board"]); expect(readBoardNames(activeDatabasePath)).toEqual(["Restored board"]);
}); });
@@ -109,6 +109,7 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
const [importError, setImportError] = useState<string | null>(null); const [importError, setImportError] = useState<string | null>(null);
const [restoreStatus, setRestoreStatus] = useState<"restoring" | "restarting" | "timedOut">("restoring"); const [restoreStatus, setRestoreStatus] = useState<"restoring" | "restarting" | "timedOut">("restoring");
const restartControllerRef = useRef<AbortController | null>(null); const restartControllerRef = useRef<AbortController | null>(null);
const restoreDestinationRef = useRef<string | null>(null);
const { analysis, loading, error: analysisError, migrationProgress, analyzeFile, reset } = useBackupAnalysis(); const { analysis, loading, error: analysisError, migrationProgress, analyzeFile, reset } = useBackupAnalysis();
useEffect( useEffect(
@@ -141,8 +142,9 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
reset(); reset();
}, [reset]); }, [reset]);
const startReadinessCheck = useCallback((restartAfterMs: number) => { const startReadinessCheck = useCallback((restartAfterMs: number, destination = restoreDestinationRef.current) => {
restartControllerRef.current?.abort(); restartControllerRef.current?.abort();
restoreDestinationRef.current = destination;
const restartController = new AbortController(); const restartController = new AbortController();
restartControllerRef.current = restartController; restartControllerRef.current = restartController;
setRestoreStatus("restarting"); setRestoreStatus("restarting");
@@ -150,7 +152,8 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
void waitForServerReadinessAsync({ restartAfterMs, signal: restartController.signal }).then((result) => { void waitForServerReadinessAsync({ restartAfterMs, signal: restartController.signal }).then((result) => {
if (restartControllerRef.current !== restartController || result === "aborted") return; if (restartControllerRef.current !== restartController || result === "aborted") return;
if (result === "ready") { if (result === "ready") {
window.location.reload(); if (destination) window.location.assign(destination);
else window.location.reload();
return; return;
} }
restartControllerRef.current = null; restartControllerRef.current = null;
@@ -167,12 +170,14 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
restartControllerRef.current = null; restartControllerRef.current = null;
let restartAfterMs = DEFAULT_RESTART_DELAY_MS; let restartAfterMs = DEFAULT_RESTART_DELAY_MS;
let homeBoardName: string | null = null;
try { try {
const formData = new FormData(); const formData = new FormData();
formData.append("file", file); formData.append("file", file);
const response = await fetch("/api/backup/import", { method: "POST", body: formData }); const response = await fetch("/api/backup/import", { method: "POST", body: formData });
const data = (await response.json().catch(() => null)) as { const data = (await response.json().catch(() => null)) as {
error?: unknown; error?: unknown;
homeBoardName?: unknown;
restartAfterMs?: unknown; restartAfterMs?: unknown;
} | null; } | null;
@@ -190,6 +195,7 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
) { ) {
restartAfterMs = data.restartAfterMs; restartAfterMs = data.restartAfterMs;
} }
if (typeof data?.homeBoardName === "string") homeBoardName = data.homeBoardName;
} catch { } catch {
setImportError(t("failed.title")); setImportError(t("failed.title"));
setStep("error"); setStep("error");
@@ -197,8 +203,10 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
} }
onRestoreComplete?.(); onRestoreComplete?.();
startReadinessCheck(restartAfterMs); const destination =
}, [file, onRestoreComplete, startReadinessCheck, t]); variant === "standalone" && homeBoardName ? `/boards/${encodeURIComponent(homeBoardName)}` : null;
startReadinessCheck(restartAfterMs, destination);
}, [file, onRestoreComplete, startReadinessCheck, t, variant]);
if (step === "upload") { if (step === "upload") {
return ( return (
@@ -243,19 +251,19 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
if (step === "preview") { if (step === "preview") {
return ( return (
<Stack gap="md"> <Stack gap="md">
<Group justify="space-between"> <Group justify="space-between" wrap="nowrap">
<Group gap="sm"> <Group gap="sm" wrap="nowrap" miw={0}>
<IconFileZip size={20} /> <IconFileZip size={20} />
<div> <div style={{ minWidth: 0 }}>
<Text size="sm" fw={500}> <Text size="sm" fw={500} truncate>
{file?.name} {file?.name}
</Text> </Text>
<Text size="xs" c="dimmed"> <Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
{file ? `${(file.size / 1024 / 1024).toFixed(2)} MB` : ""} {file ? `${(file.size / 1024 / 1024).toFixed(2)} MB` : ""}
</Text> </Text>
</div> </div>
</Group> </Group>
<Button variant="subtle" size="xs" onClick={handleClear}> <Button variant="subtle" size="xs" onClick={handleClear} style={{ flexShrink: 0 }}>
{t("changeFile")} {t("changeFile")}
</Button> </Button>
</Group> </Group>
@@ -281,8 +289,11 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
<> <>
<BackupPreviewPanel analysis={analysis} /> <BackupPreviewPanel analysis={analysis} />
<Group justify="flex-end"> <Group justify="flex-end">
<Button rightSection={<IconArrowRight size={16} />} onClick={() => setStep("confirm")}> <Button
{t("continueToRestore")} rightSection={<IconArrowRight size={16} />}
onClick={() => (variant === "standalone" ? void handleConfirm() : setStep("confirm"))}
>
{variant === "standalone" ? t("confirm.submit") : t("continueToRestore")}
</Button> </Button>
</Group> </Group>
</> </>
@@ -9,6 +9,8 @@ import type { BackupAnalysis, MigrationFile, MigrationStatus } from "./types";
import { PREVIEW_TABLE_KEYS } from "./types"; import { PREVIEW_TABLE_KEYS } from "./types";
const DRIZZLE_MIGRATIONS_TABLE = "__drizzle_migrations"; const DRIZZLE_MIGRATIONS_TABLE = "__drizzle_migrations";
const MIGRATION_PREVIEW_DELAY_MS = 250;
const MIGRATION_COMPLETE_DELAY_MS = 100;
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -120,7 +122,7 @@ export const useBackupAnalysis = () => {
phase: "applying", phase: "applying",
}); });
await delay(100); await delay(MIGRATION_PREVIEW_DELAY_MS);
try { try {
const statements = migration.sql const statements = migration.sql
@@ -158,7 +160,7 @@ export const useBackupAnalysis = () => {
}); });
sounds.success(); sounds.success();
await delay(50); await delay(MIGRATION_COMPLETE_DELAY_MS);
} }
} }
@@ -106,7 +106,7 @@
.hero { .hero {
margin-inline: auto; margin-inline: auto;
max-width: 42rem; max-width: 58rem;
padding-block: 5rem 3rem; padding-block: 5rem 3rem;
text-align: center; text-align: center;
} }
+1 -1
View File
@@ -135,7 +135,7 @@ export const Welcome = ({ environment, sqliteRestore }: OnboardingStudioProps) =
</Group> </Group>
{showRestore && sqliteRestore ? ( {showRestore && sqliteRestore ? (
<Paper id="sqlite-restore-flow" withBorder p="lg" radius="lg" w="100%" maw="38rem"> <Paper id="sqlite-restore-flow" withBorder p="lg" radius="lg" w="100%" maw="56rem">
<Stack> <Stack>
<Group gap="xs"> <Group gap="xs">
<ThemeIcon variant="light" color="orange"> <ThemeIcon variant="light" color="orange">