From 4e88244a8b74a83e4766070be3b446b132373977 Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 3 Nov 2026 13:41:38 +0000 Subject: [PATCH] fix(desktop): apply UI updates automatically (app-first) (BIT-157) PhotoReport is a local app: when a new interface is downloaded, reload into it at once. Check on launch and every 2 minutes; Preferences can force a pull. No more "refresh like a browser" to see Enviar originais. --- apps/app/src/desktop/UpdateNotice.tsx | 52 ++++++++++++++++++-------- apps/app/src/desktop/desktop.test.tsx | 18 +++++++-- apps/app/src/i18n.ts | 6 +++ apps/app/src/pages/PreferencesPage.tsx | 27 ++++++++++++- apps/desktop/src-tauri/src/ui.rs | 15 +++++--- 5 files changed, 92 insertions(+), 26 deletions(-) diff --git a/apps/app/src/desktop/UpdateNotice.tsx b/apps/app/src/desktop/UpdateNotice.tsx index 81136e4..060906b 100644 --- a/apps/app/src/desktop/UpdateNotice.tsx +++ b/apps/app/src/desktop/UpdateNotice.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { t } from "../i18n.js"; import { API_URL } from "../api.js"; import { desktopInvoke, type Invoke, isDesktop, openExternal } from "../platform.js"; @@ -16,35 +16,55 @@ type Listen = (event: string, handler: () => void) => Promise<() => void>; const tauriListen: Listen = async (event, handler) => (await import("@tauri-apps/api/event")).listen(event, handler); /** - * Desktop only: a newer interface was downloaded in the background (apps/desktop/src-tauri/src/ui.rs). It is used - * from the next start; reloading now switches straight away (nothing is lost: edits wait in the local queue). + * Desktop only: a newer interface was downloaded onto this computer (`ui.rs`). This is a local app — switch into + * it at once (reload). Edits wait in the offline queue; nothing is lost. Also asks `ui_check` on open so a + * deploy that landed while the app was closed is applied without waiting for the background timer. */ -export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), reload = () => window.location.reload() }: { listen?: Listen; enabled?: boolean; reload?: () => void }) { - const [ready, setReady] = useState(false); - const [dismissed, setDismissed] = useState(false); +export function UiReadyNotice({ + listen = tauriListen, + invoke = desktopInvoke, + enabled = isDesktop(), + reload = () => window.location.reload(), +}: { + listen?: Listen; + invoke?: Invoke; + enabled?: boolean; + reload?: () => void; +}) { + const [applying, setApplying] = useState(false); + const applied = useRef(false); + useEffect(() => { if (!enabled) return; let stop: (() => void) | undefined; let alive = true; - listen("ui-ready", () => setReady(true)).then( + const apply = () => { + if (!alive || applied.current) return; + applied.current = true; + setApplying(true); + // Let the asset provider finish switching folders before the webview asks for index.html again. + window.setTimeout(() => reload(), 150); + }; + listen("ui-ready", apply).then( (unlisten) => (alive ? (stop = unlisten) : unlisten()), () => {}, ); + // Launch: pull the published interface now if this copy is behind (app-first, not "refresh the browser"). + invoke("ui_check") + .then((updated) => { + if (alive && updated) apply(); + }) + .catch(() => {}); return () => { alive = false; stop?.(); }; - }, [enabled, listen]); - if (!ready || dismissed) return null; + }, [enabled, listen, invoke, reload]); + + if (!applying) return null; return (
- {t.update.uiReady} - - + {t.update.uiApplying}
); } diff --git a/apps/app/src/desktop/desktop.test.tsx b/apps/app/src/desktop/desktop.test.tsx index d139d1f..ff5a4e1 100644 --- a/apps/app/src/desktop/desktop.test.tsx +++ b/apps/app/src/desktop/desktop.test.tsx @@ -38,18 +38,28 @@ describe("local catalogue", () => { }); describe("interface update notice", () => { - it("says when a newer interface is ready and reloads into it", async () => { + it("reloads into a newer interface as soon as it is ready (local app, not a browser tab)", async () => { let fire: () => void = () => {}; const listen = vi.fn(async (_event: string, handler: () => void) => { fire = handler; return () => {}; }); + const invoke = vi.fn(async () => false) as unknown as Invoke; const reload = vi.fn(); - render(); + render(); await waitFor(() => expect(listen).toHaveBeenCalledWith("ui-ready", expect.any(Function))); act(() => fire()); - fireEvent.click(await screen.findByText("Recarregar agora")); - expect(reload).toHaveBeenCalled(); + expect(await screen.findByText("A actualizar a interface da app…")).toBeTruthy(); + await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 }); + }); + + it("checks for a newer interface on launch and reloads when one was downloaded", async () => { + const listen = vi.fn(async () => () => {}); + const invoke = vi.fn(async (cmd: string) => (cmd === "ui_check" ? true : null)) as unknown as Invoke; + const reload = vi.fn(); + render(); + await waitFor(() => expect(invoke).toHaveBeenCalledWith("ui_check")); + await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 }); }); }); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 1707a23..79f7a67 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -852,6 +852,12 @@ export const t = { download: "Descarregar instalador", later: "Mais tarde", uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).", + uiApplying: "A actualizar a interface da app…", + uiSection: "Interface da app", + uiSectionHelp: "A PhotoReport é uma app neste computador. Novas funções descarregam-se sozinhas; podes forçar a verificação aqui.", + uiCheckNow: "Actualizar interface agora", + uiChecking: "A verificar…", + uiCurrent: "Já tens a interface mais recente.", reload: "Recarregar agora", }, editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.", diff --git a/apps/app/src/pages/PreferencesPage.tsx b/apps/app/src/pages/PreferencesPage.tsx index 3556f4d..d1b1363 100644 --- a/apps/app/src/pages/PreferencesPage.tsx +++ b/apps/app/src/pages/PreferencesPage.tsx @@ -4,7 +4,7 @@ import { useAuth } from "../auth.js"; import { Alert } from "../components/ui.js"; import { LocalCatalog } from "../desktop/LocalCatalog.js"; import { t } from "../i18n.js"; -import { isDesktop } from "../platform.js"; +import { desktopInvoke, isDesktop } from "../platform.js"; import { PageHeader } from "./Shell.js"; // "advanced" is an internal bucket for controls a future engine version adds before we name a panel. @@ -14,6 +14,7 @@ export function PreferencesPage() { const { api, me, reload } = useAuth(); const [selected, setSelected] = useState(me?.preferences.editorModules ?? [...DEFAULT_MODULES]); const [status, setStatus] = useState<"idle" | "saved" | "error">("idle"); + const [uiStatus, setUiStatus] = useState<"idle" | "checking" | "current" | "error">("idle"); const toggle = async (module: Module) => { const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module]; @@ -52,6 +53,30 @@ export function PreferencesPage() { ))} + {isDesktop() && ( +
+

{t.update.uiSection}

+

{t.update.uiSectionHelp}

+ + {uiStatus === "current" &&

{t.update.uiCurrent}

} + {uiStatus === "error" && {t.unexpectedError}} +
+ )} {isDesktop() && } ); diff --git a/apps/desktop/src-tauri/src/ui.rs b/apps/desktop/src-tauri/src/ui.rs index 39bb551..a0cab77 100644 --- a/apps/desktop/src-tauri/src/ui.rs +++ b/apps/desktop/src-tauri/src/ui.rs @@ -1,6 +1,6 @@ //! The interface lives on this computer. The window always opens the web app from disk (no download to start, works //! without a network); new versions of the interface are fetched in the background, only the files that changed, and -//! used from the next start (or when the photographer chooses to reload). +//! applied at once (the window reloads into them — this is a local app, not a browser tab waiting for a refresh). //! //! Every web deploy publishes `ui-manifest.json` next to the app (path, size and SHA-256 of each file, when it was //! built). In the background (`watch`, or now with `ui_check`) the app compares it with the version in use, copies @@ -194,8 +194,9 @@ pub async fn ui_check(app: tauri::AppHandle) -> Result { } /// How often the background check runs, and how long after start the first one waits (the window comes first). -const EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60); -const FIRST: std::time::Duration = std::time::Duration::from_secs(20); +/// Short on purpose: a web deploy during a shoot must land in the local app within minutes, not half an hour. +const EVERY: std::time::Duration = std::time::Duration::from_secs(2 * 60); +const FIRST: std::time::Duration = std::time::Duration::from_secs(3); /// Checks for new interface versions while the app runs; tells the window when one is ready (`ui-ready`). pub fn watch(app: tauri::AppHandle) { @@ -204,8 +205,12 @@ pub fn watch(app: tauri::AppHandle) { loop { match check(&app).await { Ok(true) => { - use tauri::Emitter; + use tauri::{Emitter, Manager}; let _ = app.emit("ui-ready", app.state::().status()); + // Local app: apply at once. Do not wait for a "refresh" click like a browser tab. + if let Some(window) = app.get_webview_window("main") { + let _ = window.eval("window.location.reload()"); + } } Ok(false) => {} // No network, server down: nothing to do, the interface on disk keeps working. @@ -327,7 +332,7 @@ fn write(target: &Path, bytes: &[u8]) -> Result<(), String> { } /// Switches to `manifest` once every file is in place and checks out; the version it replaces is kept as a fallback, -/// older ones removed. Served from the next start, or now if the window reloads. +/// older ones removed. The window reloads into it as soon as `ui-ready` fires. fn activate(ui: &UiShared, root: &Path, manifest: &Manifest) -> Result<(), String> { let stage = staging(root, &manifest.version)?; for f in &manifest.files { -- 2.47.3