Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
desktop: check for updates periodically (#9505)
Maheswar Kumarffeb2b6dfaf4
diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.tsindex 23050c71985..74855f8a0eb 100644--- a/studio/frontend/src/hooks/use-tauri-update.ts+++ b/studio/frontend/src/hooks/use-tauri-update.ts@@ -97,6 +97,8 @@ const DEFAULT_UPDATE_POLICY: DesktopUpdatePolicy = {releasePageBaseUrl: "https://github.com/unslothai/unsloth/releases/tag/",releaseTagPrefix: "v",};+const STARTUP_UPDATE_CHECK_DELAY_MS = 5000;+const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;const PREPARATION_STATUSES: ReadonlySet<UpdateStatus> = new Set(["available",@@ -165,7 +167,7 @@ export function useTauriUpdate(isExternalServer = false) {const preparingVersionRef = useRef<string | null>(null);const updateRef = useRef<DesktopUpdateMetadata | null>(null);const checkedRef = useRef(false);- const startupScheduledRef = useRef(false);+ const lastCheckAtRef = useRef<number | null>(null);const checkingRef = useRef(false);const updatingRef = useRef(false);// Windows kill-on-close: false once a re-arm has failed, and every path that@@ -198,7 +200,16 @@ export function useTauriUpdate(isExternalServer = false) {setInfo(nextInfo);}- function offerUpdate(nextInfo: UpdateInfo) {+ function restoredPreparationStatus(previousStatus: UpdateStatus): UpdateStatus {+ if (previousStatus === "available") return previousStatus;+ const nextStatus = preparationStatus(preparationRef.current);+ if (nextStatus === "ready" && previousStatus !== "ready") {+ setDismissed(false);+ }+ return nextStatus;+ }++ function offerUpdate(nextInfo: UpdateInfo, previousStatus?: UpdateStatus) {const isNewOffer = infoRef.current?.version !== nextInfo.version;replaceInfo(nextInfo);if (isNewOffer) {@@ -207,7 +218,11 @@ export function useTauriUpdate(isExternalServer = false) {setError(null);setDismissed(false);}- updateStatus("available");+ updateStatus(+ !isNewOffer && previousStatus && PREPARATION_STATUSES.has(previousStatus)+ ? restoredPreparationStatus(previousStatus)+ : "available",+ );}function replaceLogs(nextLogs: string[]) {@@ -287,7 +302,10 @@ export function useTauriUpdate(isExternalServer = false) {}}- async function checkManualUpdate(policy: DesktopUpdatePolicy) {+ async function checkManualUpdate(+ policy: DesktopUpdatePolicy,+ previousStatus: UpdateStatus,+ ) {if (policy.mode !== "manual_linux_package") return false;const { invoke } = await import("@tauri-apps/api/core");const manualUpdate = await invoke<ManualUpdateInfo | null>(@@ -295,13 +313,16 @@ export function useTauriUpdate(isExternalServer = false) {);if (!manualUpdate) return false;updateRef.current = null;- offerUpdate({- version: manualUpdate.version,- currentVersion: manualUpdate.currentVersion,- pypiVersion: manualUpdate.pypiVersion ?? undefined,- body: manualUpdate.body,- date: manualUpdate.date,- });+ offerUpdate(+ {+ version: manualUpdate.version,+ currentVersion: manualUpdate.currentVersion,+ pypiVersion: manualUpdate.pypiVersion ?? undefined,+ body: manualUpdate.body,+ date: manualUpdate.date,+ },+ previousStatus,+ );return true;}@@ -316,8 +337,10 @@ export function useTauriUpdate(isExternalServer = false) {async function checkForUpdate() {if (checkingRef.current || updatingRef.current) return;+ const previousStatus = statusRef.current;// A manual check covers startup, so the delayed timer must not repeat it.checkedRef.current = true;+ lastCheckAtRef.current = Date.now();checkingRef.current = true;setCheckError(null);updateStatus("checking");@@ -327,13 +350,13 @@ export function useTauriUpdate(isExternalServer = false) {if (policy.mode === "manual_linux_package") {// Self-gates on the real target_os, so it is authoritative even if policy is a guess.- if (await checkManualUpdate(policy)) return;+ if (await checkManualUpdate(policy, previousStatus)) return;if (resolved) {// latest.json has no deb/rpm key, so the in-app updater would offer an// AppImage this install cannot apply. Stop instead.updateRef.current = null;- await clearPreparedBackendUpdate();replaceInfo(null);+ await clearPreparedBackendUpdate();updateStatus("idle");return;}@@ -344,24 +367,33 @@ export function useTauriUpdate(isExternalServer = false) {const update = await checkDesktopUpdate();if (update) {updateRef.current = update;- offerUpdate({- version: update.version,- currentVersion: update.currentVersion,- pypiVersion: rawPypiVersion(update.rawJson),- body: update.body,- date: update.date,- });+ offerUpdate(+ {+ version: update.version,+ currentVersion: update.currentVersion,+ pypiVersion: rawPypiVersion(update.rawJson),+ body: update.body,+ date: update.date,+ },+ previousStatus,+ );} else {updateRef.current = null;- await clearPreparedBackendUpdate();replaceInfo(null);resetPreparation();+ await clearPreparedBackendUpdate();updateStatus("idle");}} catch (e) {console.error("Update check failed:", e);setCheckError(String(e));- updateStatus(infoRef.current ? preparationStatus(preparationRef.current) : "idle");+ updateStatus(+ infoRef.current+ ? PREPARATION_STATUSES.has(previousStatus)+ ? restoredPreparationStatus(previousStatus)+ : previousStatus+ : "idle",+ );} finally {checkingRef.current = false;setHasChecked(true);@@ -373,19 +405,48 @@ export function useTauriUpdate(isExternalServer = false) {if (staged.staging) await cancelStagedUpdate();await discardStagedUpdate();}- // Startup owns one delayed check; this ref keeps a per-render function out of- // the empty dep list. The closure reads only refs/setState, so it cannot stale.- const initialCheckRef = useRef(checkForUpdate);++ function checkForUpdateWhenSafe() {+ // preparation and recovery own version-specific state until they settle.+ if (statusRef.current === "preparing" || statusRef.current === "error") return;+ void checkForUpdate();+ }++ // scheduled checks use the mount's stable closure, which only reads refs and state setters.+ const scheduledCheckRef = useRef(checkForUpdateWhenSafe);useEffect(() => {- if (!isTauri || startupScheduledRef.current) return;- startupScheduledRef.current = true;+ if (!isTauri) return;- const timer = setTimeout(() => {+ const startupTimer = setTimeout(() => {if (checkedRef.current) return;- void initialCheckRef.current();- }, 5000);- return () => clearTimeout(timer);+ scheduledCheckRef.current();+ }, STARTUP_UPDATE_CHECK_DELAY_MS);+ const periodicTimer = setInterval(() => {+ scheduledCheckRef.current();+ }, PERIODIC_UPDATE_CHECK_INTERVAL_MS);+ const checkWhenVisibleAndDue = () => {+ if (document.hidden) return;+ const lastCheckAt = lastCheckAtRef.current;+ if (lastCheckAt === null) return;+ const elapsed = Date.now() - lastCheckAt;+ if (+ elapsed >= 0 &&+ elapsed < PERIODIC_UPDATE_CHECK_INTERVAL_MS+ ) {+ return;+ }+ scheduledCheckRef.current();+ };+ window.addEventListener("focus", checkWhenVisibleAndDue);+ document.addEventListener("visibilitychange", checkWhenVisibleAndDue);++ return () => {+ clearTimeout(startupTimer);+ clearInterval(periodicTimer);+ window.removeEventListener("focus", checkWhenVisibleAndDue);+ document.removeEventListener("visibilitychange", checkWhenVisibleAndDue);+ };}, []);async function prepareUpdate(version: string, policy: DesktopUpdatePolicy) {diff --git a/studio/frontend/tests/tauri-update-schedule.test.ts b/studio/frontend/tests/tauri-update-schedule.test.tsnew file mode 100644index 00000000000..8612c914ef1--- /dev/null+++ b/studio/frontend/tests/tauri-update-schedule.test.ts@@ -0,0 +1,477 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test, { type TestContext } from "node:test";++import { loadWithStubs } from "./helpers/module-stubs.ts";++const STARTUP_DELAY_MS = 5_000;+const PERIODIC_INTERVAL_MS = 60 * 60 * 1_000;++type UpdateController = {+ checkForUpdate: () => Promise<void>;+ installUpdate: () => Promise<void>;+};++type Listener = EventListenerOrEventListenerObject;++interface HookHarnessOptions {+ failCheckAt?: number;+ holdPreparation?: boolean;+ noUpdateAt?: number;+ rejectDiscard?: boolean;+ tauri?: boolean;+}++function createEventTarget() {+ const listeners = new Map<string, Set<Listener>>();+ return {+ addEventListener(type: string, listener: Listener): void {+ const registered = listeners.get(type) ?? new Set<Listener>();+ registered.add(listener);+ listeners.set(type, registered);+ },+ removeEventListener(type: string, listener: Listener): void {+ listeners.get(type)?.delete(listener);+ },+ fire(type: string): void {+ const event = new Event(type);+ for (const listener of listeners.get(type) ?? []) {+ if (typeof listener === "function") listener(event);+ else listener.handleEvent(event);+ }+ },+ listenerCount(): number {+ let count = 0;+ for (const registered of listeners.values()) count += registered.size;+ return count;+ },+ };+}++function restoreProperty(+ target: object,+ key: PropertyKey,+ descriptor: PropertyDescriptor | undefined,+): void {+ if (descriptor) Object.defineProperty(target, key, descriptor);+ else Reflect.deleteProperty(target, key);+}++function installBrowserClock() {+ const windowTarget = createEventTarget();+ const documentTarget = createEventTarget();+ const timeouts = new Map<number, { callback: () => void; delay: number }>();+ const intervals = new Map<number, { callback: () => void; delay: number }>();+ const originalDescriptors = {+ window: Object.getOwnPropertyDescriptor(globalThis, "window"),+ document: Object.getOwnPropertyDescriptor(globalThis, "document"),+ setTimeout: Object.getOwnPropertyDescriptor(globalThis, "setTimeout"),+ clearTimeout: Object.getOwnPropertyDescriptor(globalThis, "clearTimeout"),+ setInterval: Object.getOwnPropertyDescriptor(globalThis, "setInterval"),+ clearInterval: Object.getOwnPropertyDescriptor(globalThis, "clearInterval"),+ dateNow: Object.getOwnPropertyDescriptor(Date, "now"),+ };+ let hidden = false;+ let now = 1_000;+ let nextTimerId = 1;++ const windowStub = {+ addEventListener: windowTarget.addEventListener,+ removeEventListener: windowTarget.removeEventListener,+ };+ const documentStub = {+ addEventListener: documentTarget.addEventListener,+ removeEventListener: documentTarget.removeEventListener,+ };+ Object.defineProperty(documentStub, "hidden", {+ configurable: true,+ get: () => hidden,+ });++ Object.defineProperties(globalThis, {+ window: { configurable: true, writable: true, value: windowStub },+ document: { configurable: true, writable: true, value: documentStub },+ setTimeout: {+ configurable: true,+ writable: true,+ value: ((callback: () => void, delay = 0) => {+ const id = nextTimerId++;+ timeouts.set(id, { callback, delay });+ return id;+ }) as unknown as typeof setTimeout,+ },+ clearTimeout: {+ configurable: true,+ writable: true,+ value: ((id: number) =>+ timeouts.delete(id)) as unknown as typeof clearTimeout,+ },+ setInterval: {+ configurable: true,+ writable: true,+ value: ((callback: () => void, delay = 0) => {+ const id = nextTimerId++;+ intervals.set(id, { callback, delay });+ return id;+ }) as unknown as typeof setInterval,+ },+ clearInterval: {+ configurable: true,+ writable: true,+ value: ((id: number) =>+ intervals.delete(id)) as unknown as typeof clearInterval,+ },+ });+ Object.defineProperty(Date, "now", {+ configurable: true,+ writable: true,+ value: () => now,+ });++ return {+ activeTimers: () => timeouts.size + intervals.size,+ advance: (elapsed: number) => {+ now += elapsed;+ },+ delays: () => [+ ...[...timeouts.values()].map(({ delay }) => delay),+ ...[...intervals.values()].map(({ delay }) => delay),+ ],+ fireDocument: (type: string) => documentTarget.fire(type),+ fireIntervals: (delay: number) => {+ for (const timer of intervals.values()) {+ if (timer.delay === delay) timer.callback();+ }+ },+ fireTimeouts: (delay: number) => {+ for (const [id, timer] of [...timeouts]) {+ if (timer.delay !== delay) continue;+ timeouts.delete(id);+ timer.callback();+ }+ },+ fireWindow: (type: string) => windowTarget.fire(type),+ listenerCount: () =>+ windowTarget.listenerCount() + documentTarget.listenerCount(),+ setHidden: (nextHidden: boolean) => {+ hidden = nextHidden;+ },+ restore(): void {+ restoreProperty(globalThis, "window", originalDescriptors.window);+ restoreProperty(globalThis, "document", originalDescriptors.document);+ restoreProperty(globalThis, "setTimeout", originalDescriptors.setTimeout);+ restoreProperty(+ globalThis,+ "clearTimeout",+ originalDescriptors.clearTimeout,+ );+ restoreProperty(+ globalThis,+ "setInterval",+ originalDescriptors.setInterval,+ );+ restoreProperty(+ globalThis,+ "clearInterval",+ originalDescriptors.clearInterval,+ );+ restoreProperty(Date, "now", originalDescriptors.dateNow);+ },+ };+}++function createHookReact() {+ const effects: Array<() => unknown> = [];+ const cleanups: Array<() => void> = [];+ const statusUpdates: string[] = [];+ let stateIndex = 0;+ return {+ react: {+ useState<T>(initial: T): [T, (next: unknown) => void] {+ const index = stateIndex++;+ return [+ initial,+ (next: unknown) => {+ if (index === 0 && typeof next === "string")+ statusUpdates.push(next);+ },+ ];+ },+ useRef<T>(initial: T): { current: T } {+ return { current: initial };+ },+ useEffect(effect: () => unknown): void {+ effects.push(effect);+ },+ },+ mount(): void {+ for (const effect of effects) {+ const cleanup = effect();+ if (typeof cleanup === "function") cleanups.push(cleanup as () => void);+ }+ },+ unmount(): void {+ for (const cleanup of cleanups.splice(0)) cleanup();+ },+ statusUpdates,+ };+}++function hookHarness(+ t: TestContext,+ {+ failCheckAt,+ holdPreparation = false,+ noUpdateAt,+ rejectDiscard = false,+ tauri = true,+ }: HookHarnessOptions = {},+) {+ const browser = installBrowserClock();+ const host = createHookReact();+ t.after(() => {+ host.unmount();+ browser.restore();+ });+ let checks = 0;+ const initialPreparation = {+ shell: "pending",+ backend: "pending",+ shellProgress: 0,+ };+ const hook = loadWithStubs<{+ useTauriUpdate: () => UpdateController;+ }>(new URL("../src/hooks/use-tauri-update.ts", import.meta.url), {+ react: host.react,+ "@/features/training": {+ isTrainingStartPending: () => false,+ useTrainingRuntimeStore: { getState: () => ({}) },+ },+ "@/lib/api-base": { apiUrl: (path: string) => path, isTauri: tauri },+ "@/lib/tauri-diagnostics": {+ copySupportDiagnostics: async () => ({ copied: true }),+ },+ "@/lib/tauri-updater": {+ adoptStagedUpdate: () => Promise.resolve({}),+ cancelStagedUpdate: () => Promise.resolve(),+ checkDesktopUpdate: () => {+ checks += 1;+ if (checks === failCheckAt) throw new Error("update check failed");+ if (checks === noUpdateAt) return Promise.resolve(null);+ return Promise.resolve({+ version: "2.0.0",+ currentVersion: "1.0.0",+ rawJson: {},+ });+ },+ desktopUpdateBundleStatus: () =>+ holdPreparation+ ? new Promise(() => {})+ : Promise.resolve({ downloaded: false }),+ discardStagedUpdate: () =>+ rejectDiscard+ ? Promise.reject(new Error("discard failed"))+ : Promise.resolve(),+ downloadDesktopUpdate: () => Promise.resolve(),+ installDesktopUpdate: () => Promise.resolve(),+ stagedUpdateStatus: () => Promise.resolve({ staging: false }),+ startStagedUpdate: () => Promise.resolve(),+ waitForDesktopUpdateDownload: () => Promise.resolve(),+ },+ "@/lib/toast": { toast: { error: () => undefined } },+ "@/lib/update-preparation": {+ INITIAL_PREPARATION: initialPreparation,+ backendIdle: () => true,+ desktopDownloadDecision: () => "ready",+ preparationStatus: (preparation: typeof initialPreparation) =>+ preparation.shell === "done" && preparation.backend === "skipped"+ ? "ready"+ : "preparing",+ restartPlan: () => "classic",+ sameUpdateVersion: () => true,+ settleWithin: async () => null,+ stagingDecision: () => "skip",+ waitForBackendIdle: async () => "cancelled",+ },+ "@tauri-apps/api/core": {+ invoke: async (command: string) => {+ if (command === "desktop_update_policy") {+ return {+ mode: "in_app",+ releasePageBaseUrl: "https://example.com/",+ releaseTagPrefix: "v",+ };+ }+ if (command === "desktop_update_cleanup_armed") return true;+ throw new Error(`unexpected invoke: ${command}`);+ },+ },+ "@tauri-apps/api/event": {+ listen: async () => {+ throw new Error("backend update failed");+ },+ },+ });+ const controller = hook.useTauriUpdate();+ host.mount();+ return {+ browser,+ checks: () => checks,+ controller,+ host,+ statusUpdates: host.statusUpdates,+ };+}++function settle(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve));+}++test("the desktop hook checks at startup and every hour", async (t) => {+ const hook = hookHarness(t);+ assert.deepEqual(hook.browser.delays(), [+ STARTUP_DELAY_MS,+ PERIODIC_INTERVAL_MS,+ ]);++ hook.browser.fireWindow("focus");+ await settle();+ assert.equal(hook.checks(), 0);++ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ assert.equal(hook.checks(), 1);++ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ await settle();+ assert.equal(hook.checks(), 2);+});++test("a manual check suppresses only the startup check", async (t) => {+ const hook = hookHarness(t);+ await hook.controller.checkForUpdate();++ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ assert.equal(hook.checks(), 1);++ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ await settle();+ assert.equal(hook.checks(), 2);+});++test("a periodic recheck preserves a prepared update", async (t) => {+ const hook = hookHarness(t);+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ await hook.controller.installUpdate();+ await settle();+ assert.equal(hook.statusUpdates.at(-1), "ready");++ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ await settle();+ assert.equal(hook.statusUpdates.at(-1), "ready");+});++test("a failed periodic recheck preserves an untouched offer", async (t) => {+ const hook = hookHarness(t, { failCheckAt: 2 });+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ assert.equal(hook.statusUpdates.at(-1), "available");++ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ await settle();+ assert.equal(hook.checks(), 2);+ assert.equal(hook.statusUpdates.at(-1), "available");+});++test("a cleanup failure does not restore a withdrawn offer", async (t) => {+ const hook = hookHarness(t, { noUpdateAt: 2, rejectDiscard: true });+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ assert.equal(hook.statusUpdates.at(-1), "available");++ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ await settle();+ assert.equal(hook.checks(), 2);+ assert.equal(hook.statusUpdates.at(-1), "idle");+});++test("scheduled checks wait for update preparation", async (t) => {+ const hook = hookHarness(t, { holdPreparation: true });+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ await hook.controller.installUpdate();+ assert.equal(hook.statusUpdates.at(-1), "preparing");++ hook.browser.advance(PERIODIC_INTERVAL_MS + 1);+ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ hook.browser.fireWindow("focus");+ await settle();+ assert.equal(hook.checks(), 1);+ assert.equal(hook.statusUpdates.at(-1), "preparing");+});++test("scheduled checks preserve update recovery", async (t) => {+ const hook = hookHarness(t);+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ await hook.controller.installUpdate();+ await settle();+ assert.equal(hook.statusUpdates.at(-1), "ready");++ await hook.controller.installUpdate();+ assert.equal(hook.statusUpdates.at(-1), "error");++ hook.browser.advance(PERIODIC_INTERVAL_MS + 1);+ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ hook.browser.fireWindow("focus");+ await settle();+ assert.equal(hook.checks(), 1);+ assert.equal(hook.statusUpdates.at(-1), "error");+});++test("restoring an overdue hidden window checks immediately", async (t) => {+ const hook = hookHarness(t);+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ await settle();+ assert.equal(hook.checks(), 1);++ hook.browser.setHidden(true);+ hook.browser.advance(PERIODIC_INTERVAL_MS + 1);+ hook.browser.fireDocument("visibilitychange");+ await settle();+ assert.equal(hook.checks(), 1);++ hook.browser.setHidden(false);+ hook.browser.fireDocument("visibilitychange");+ hook.browser.fireWindow("focus");+ await settle();+ assert.equal(hook.checks(), 2);+});++test("unmount removes update timers and wake listeners", async (t) => {+ const hook = hookHarness(t);+ assert.equal(hook.browser.activeTimers(), 2);+ assert.equal(hook.browser.listenerCount(), 2);++ hook.host.unmount();+ assert.equal(hook.browser.activeTimers(), 0);+ assert.equal(hook.browser.listenerCount(), 0);++ hook.browser.advance(PERIODIC_INTERVAL_MS + 1);+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);+ hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);+ hook.browser.fireDocument("visibilitychange");+ hook.browser.fireWindow("focus");+ await settle();+ assert.equal(hook.checks(), 0);+});++test("web sessions do not schedule desktop update checks", (t) => {+ const hook = hookHarness(t, { tauri: false });+ assert.equal(hook.browser.activeTimers(), 0);+ assert.equal(hook.browser.listenerCount(), 0);+});