All files / src/hooks useUpdateChecker.ts

98.16% Statements 107/109
85.71% Branches 24/28
100% Functions 1/1
98.16% Lines 107/109

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 1471x 1x 1x 1x 1x                             1x 59x 59x 59x 59x 59x 59x     59x       59x   59x 20x   19x 19x 19x 19x   19x 16x 16x   19x 19x   19x 19x   19x 19x 1x 1x 1x 19x 19x 19x 19x 19x   19x 19x 59x     59x 16x 59x     59x 16x 16x     16x 16x 16x 59x   59x 1x 1x 59x   59x 8x   7x 7x 7x   7x 8x   1x 1x 1x 1x 1x 1x 1x 1x 1x 8x   6x 6x 6x 3x 1x 3x 2x 2x 2x 2x 2x 2x 2x 6x 3x 4x 8x 3x 3x 3x 3x 3x 3x 59x   59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x  
import { useEffect, useState, useCallback, useRef } from "react";
import { check, type Update } from "@tauri-apps/plugin-updater";
import { relaunch } from "@tauri-apps/plugin-process";
import { listen } from "@tauri-apps/api/event";
import { getInstallInfo, packageUpdate } from "@/lib/tauri";
 
export interface UpdateState {
	update: Update | null;
	checking: boolean;
	installing: boolean;
	progress: number | null;
	error: string | null;
	/** true when using package manager update (deb/rpm) instead of Tauri updater */
	packageInstall: boolean;
	dismiss: () => void;
	install: () => Promise<void>;
	checkForUpdates: () => Promise<Update | null>;
}
 
export const useUpdateChecker = (): UpdateState => {
	const [update, setUpdate] = useState<Update | null>(null);
	const [checking, setChecking] = useState(false);
	const [installing, setInstalling] = useState(false);
	const [progress, setProgress] = useState<number | null>(null);
	const [error, setError] = useState<string | null>(null);
	const [packageInstall, setPackageInstall] = useState(false);
 
	// Cache install info so we only call it once
	const installInfoRef = useRef<{ installType: string; releaseUrl: string } | null>(null);
 
	// Share a single in-flight promise so concurrent callers (mount + splash)
	// all wait for the same check() call instead of one getting null.
	const inflightRef = useRef<Promise<Update | null> | null>(null);
 
	const checkForUpdates = useCallback((): Promise<Update | null> => {
		if (inflightRef.current) return inflightRef.current;
 
		const promise = (async () => {
			setChecking(true);
			setError(null);
			try {
				// Fetch install info once
				if (!installInfoRef.current) {
					installInfoRef.current = await getInstallInfo();
				}
 
				const result = (await check({ timeout: 5_000 })) ?? null;
				setUpdate(result);
 
				const type = installInfoRef.current.installType;
				setPackageInstall(type === "deb" || type === "rpm");
 
				return result;
			} catch (err) {
				const msg = err instanceof Error ? err.message : String(err);
				console.warn("[updater] check error:", msg);
				return null;
			} finally {
				setChecking(false);
				inflightRef.current = null;
			}
		})();
 
		inflightRef.current = promise;
		return promise;
	}, []);
 
	// Check on mount
	useEffect(() => {
		checkForUpdates();
	}, [checkForUpdates]);
 
	// Re-check every 2 hours
	useEffect(() => {
		const id = setInterval(
			() => {
				checkForUpdates();
			},
			2 * 60 * 60 * 1000
		);
		return () => clearInterval(id);
	}, [checkForUpdates]);
 
	const dismiss = useCallback(() => {
		setUpdate(null);
		setPackageInstall(false);
	}, []);
 
	const install = useCallback(async () => {
		if (!update) return;
 
		setInstalling(true);
		setProgress(0);
		setError(null);
 
		try {
			if (packageInstall) {
				// deb/rpm: use our custom package update command
				const unlisten = await listen<{ percent: number }>(
					"package-update://progress",
					(event) => setProgress(event.payload.percent)
				);
				try {
					await packageUpdate();
				} finally {
					unlisten();
				}
			} else {
				// AppImage/macOS/Windows: use Tauri's built-in updater
				let downloaded = 0;
				let total: number | undefined;
				await update.downloadAndInstall((event) => {
					if (event.event === "Started") {
						total = event.data.contentLength ?? undefined;
					} else if (event.event === "Progress") {
						downloaded += event.data.chunkLength;
						if (total) {
							setProgress(
								Math.min(100, Math.round((downloaded / total) * 100))
							);
						}
					}
				});
			}
			await relaunch();
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			console.error("[updater] install failed:", msg);
			setError(`Update failed: ${msg}`);
			setInstalling(false);
			setProgress(null);
		}
	}, [update, packageInstall]);
 
	return {
		update,
		checking,
		installing,
		progress,
		error,
		packageInstall,
		dismiss,
		install,
		checkForUpdates,
	};
};