Skip to content

Commit c466ebf

Browse files
committed
Merge branch 'feature/up' into develop
2 parents 4dcb1f2 + 37a673c commit c466ebf

18 files changed

Lines changed: 127 additions & 39 deletions

File tree

‎e2e/preferences.spec.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ test.describe('preferences', () => {
302302
await expect(preferences.getByText('General')).toBeVisible()
303303
await expect(
304304
preferences.getByText(
305-
'When enabled, SwitchHosts checks for official release updates at launch and only shows a reminder. Updates are never downloaded automatically.',
305+
'When enabled, SwitchHosts will remind you when a new version is available and will not download or install updates automatically.',
306306
),
307307
).toBeVisible()
308308

@@ -328,28 +328,34 @@ test.describe('preferences', () => {
328328

329329
test('manual no-update check reports latest version without downloading', async ({ page }) => {
330330
await clearMockCalls(page)
331+
await page.evaluate(() => {
332+
window.__SWITCHHOSTS_E2E__.delayNextCheckUpdate(300)
333+
})
331334

332335
await page.getByLabel('Settings').click()
333336
await page.getByText('Check for Updates').click()
334337

338+
await expect(page.getByText('Loading...')).toBeVisible()
335339
await expect(page.getByText('Current version is up to date.')).toBeVisible()
336340
const calls = await getMockCalls(page)
337341
expect(calls.some((call) => call.cmd === 'check_update')).toBe(true)
338342
expect(calls.some((call) => call.cmd === 'download_update')).toBe(false)
339343
})
340344

341-
test('startup update check only prompts until the user downloads', async ({ browser }) => {
345+
test('background update event only prompts until the user downloads', async ({ browser }) => {
342346
const page = await browser.newPage()
343347

344348
try {
345349
await openApp(page, '/?e2eUpdateAvailable=true')
350+
await page.evaluate(() => {
351+
window.__SWITCHHOSTS_E2E__.emitNextUpdateAvailable()
352+
})
346353

347354
const updateDialog = page.getByRole('dialog').filter({ hasText: 'New Version Found' })
348355
await expect(updateDialog).toBeVisible()
349356
await expect(updateDialog.getByText('Mock release notes')).toBeVisible()
350357

351358
let calls = await getMockCalls(page)
352-
expect(calls.some((call) => call.cmd === 'check_update')).toBe(true)
353359
expect(calls.some((call) => call.cmd === 'download_update')).toBe(false)
354360

355361
await updateDialog.getByRole('button', { name: /Download/ }).click()

‎e2e/support/tauri-mock.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@
166166
nextApplyResult: null,
167167
nextRefreshResult: null,
168168
nextCheckUpdateResult: { has_update: false },
169+
nextCheckUpdateDelayMs: 0,
169170
}
170171

171172
const searchParams = new URLSearchParams(window.location.search)
@@ -284,9 +285,17 @@
284285
failNextImportFromUrl: (result = 'mock_import_url_error') => {
285286
state.nextImportFromUrlResult = result
286287
},
288+
delayNextCheckUpdate: (ms = 300) => {
289+
state.nextCheckUpdateDelayMs = ms
290+
},
287291
setNextCheckUpdateResult: (result = { has_update: false }) => {
288292
state.nextCheckUpdateResult = result
289293
},
294+
emitNextUpdateAvailable: () => {
295+
if (state.nextCheckUpdateResult?.has_update) {
296+
dispatchEvent('new_version', { _args: [clone(state.nextCheckUpdateResult)] })
297+
}
298+
},
290299
}
291300

292301
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = {
@@ -516,6 +525,11 @@
516525
case 'popup_menu':
517526
return true
518527
case 'check_update':
528+
if (state.nextCheckUpdateDelayMs) {
529+
const ms = state.nextCheckUpdateDelayMs
530+
state.nextCheckUpdateDelayMs = 0
531+
await delay(ms)
532+
}
519533
if (state.nextCheckUpdateResult instanceof Error) {
520534
const error = state.nextCheckUpdateResult
521535
state.nextCheckUpdateResult = { has_update: false }

‎e2e/support/test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ declare global {
6161
failNextImport: (result?: string | false | null) => void
6262
delayNextImportFromUrl: (ms?: number) => void
6363
failNextImportFromUrl: (result?: string | false | null) => void
64+
delayNextCheckUpdate: (ms?: number) => void
6465
setNextCheckUpdateResult: (result?: unknown) => void
66+
emitNextUpdateAvailable: () => void
6567
}
6668
}
6769
}

‎src-tauri/src/commands.rs‎

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
//! storage access.
1212
1313
use std::sync::atomic::{AtomicU64, Ordering};
14+
use std::time::Duration;
1415

1516
use serde_json::{json, Value};
1617
use tauri::menu::{MenuBuilder, MenuItemBuilder};
@@ -289,6 +290,7 @@ fn apply_side_effects(
289290
.any(|k| *k == "http_api_on" || *k == "http_api_only_local");
290291
let touches_locale = touched_keys.iter().any(|k| *k == "locale");
291292
let touches_tray_title = touched_keys.iter().any(|k| *k == "show_title_on_tray");
293+
let touches_auto_update = touched_keys.iter().any(|k| *k == "auto_check_update");
292294

293295
if touches_locale {
294296
if let Err(e) = app_menu::refresh(app) {
@@ -350,6 +352,19 @@ fn apply_side_effects(
350352
http_api::stop();
351353
}
352354
}
355+
356+
if touches_auto_update {
357+
let enabled = {
358+
let cfg = state.config.lock().expect("config mutex poisoned");
359+
cfg.auto_check_update
360+
};
361+
if enabled {
362+
let app = app.clone();
363+
tauri::async_runtime::spawn(async move {
364+
run_auto_update_check(&app).await;
365+
});
366+
}
367+
}
353368
}
354369

355370
// ---- list / tree -----------------------------------------------------------
@@ -1256,13 +1271,42 @@ async fn fetch_url(client: &reqwest::Client, url: &str) -> Result<String, String
12561271

12571272
// ---- updater ---------------------------------------------------------------
12581273

1259-
#[tauri::command]
1260-
pub async fn check_update<R: Runtime>(
1261-
app: AppHandle<R>,
1262-
state: State<'_, AppState>,
1263-
_args: Args,
1274+
const AUTO_UPDATE_CHECK_INTERVAL: Duration = Duration::from_secs(12 * 60 * 60);
1275+
1276+
pub fn start_auto_update_checker<R: Runtime + 'static>(app: AppHandle<R>) {
1277+
tauri::async_runtime::spawn(async move {
1278+
run_auto_update_check(&app).await;
1279+
1280+
loop {
1281+
tokio::time::sleep(AUTO_UPDATE_CHECK_INTERVAL).await;
1282+
run_auto_update_check(&app).await;
1283+
}
1284+
});
1285+
}
1286+
1287+
async fn run_auto_update_check<R: Runtime>(app: &AppHandle<R>) {
1288+
let state = app.state::<AppState>();
1289+
let auto_check_update = state
1290+
.config
1291+
.lock()
1292+
.map(|cfg| cfg.auto_check_update)
1293+
.unwrap_or(false);
1294+
1295+
if !auto_check_update {
1296+
return;
1297+
}
1298+
1299+
if let Err(e) = check_update_inner(app, state.inner()).await {
1300+
log::info!("automatic update check failed: {e}");
1301+
}
1302+
}
1303+
1304+
async fn check_update_inner<R: Runtime>(
1305+
app: &AppHandle<R>,
1306+
state: &AppState,
12641307
) -> Result<Value, String> {
1265-
let updater = updater_builder_with_proxy(&app, state.inner())?
1308+
let _guard = state.update_check_lock.lock().await;
1309+
let updater = updater_builder_with_proxy(app, state)?
12661310
.build()
12671311
.map_err(|e| e.to_string())?;
12681312
let update = updater.check().await.map_err(|e| e.to_string())?;
@@ -1281,12 +1325,22 @@ pub async fn check_update<R: Runtime>(
12811325
}
12821326
}
12831327

1328+
#[tauri::command]
1329+
pub async fn check_update<R: Runtime>(
1330+
app: AppHandle<R>,
1331+
state: State<'_, AppState>,
1332+
_args: Args,
1333+
) -> Result<Value, String> {
1334+
check_update_inner(&app, state.inner()).await
1335+
}
1336+
12841337
#[tauri::command]
12851338
pub async fn download_update<R: Runtime>(
12861339
app: AppHandle<R>,
12871340
state: State<'_, AppState>,
12881341
_args: Args,
12891342
) -> Result<Value, String> {
1343+
let _guard = state.update_check_lock.lock().await;
12901344
let updater = updater_builder_with_proxy(&app, state.inner())?
12911345
.build()
12921346
.map_err(|e| e.to_string())?;

‎src-tauri/src/find.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,7 @@ mod tests {
831831
config: Mutex::new(AppConfig::default()),
832832
store_lock: Mutex::new(()),
833833
config_write_lock: Mutex::new(()),
834+
update_check_lock: tokio::sync::Mutex::new(()),
834835
is_will_quit: AtomicBool::new(false),
835836
last_geometry_persist_ms: AtomicU64::new(0),
836837
}

‎src-tauri/src/lib.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,19 @@ pub fn run() {
154154
// user interaction, so no Moved/Resized events are lost.
155155
lifecycle::install_main_window_handlers(&main);
156156

157+
// Run automatic update checks from the backend so they keep
158+
// working while the main window is hidden to the tray. The
159+
// renderer's ready event gives UpdateDialog a chance to attach
160+
// its listeners before the first check can emit `new_version`.
161+
let update_checker_started = Arc::new(AtomicBool::new(false));
162+
let update_checker_ready_app = app_handle.clone();
163+
let update_checker_ready_flag = update_checker_started.clone();
164+
app.listen("main_window_ready", move |_event| {
165+
if !update_checker_ready_flag.swap(true, Ordering::SeqCst) {
166+
commands::start_auto_update_checker(update_checker_ready_app.clone());
167+
}
168+
});
169+
157170
let hide_at_launch = app_state
158171
.config
159172
.lock()

‎src-tauri/src/storage/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ pub struct AppState {
4444
/// `save()` — losing one of the writes. Held only by `commit_config_patch`;
4545
/// callers that just *read* config still go through `config` directly.
4646
pub config_write_lock: Mutex<()>,
47+
/// Serializes update checks so the background scheduler and manual
48+
/// "Check for Updates" action do not run two updater requests at once.
49+
pub update_check_lock: tokio::sync::Mutex<()>,
4750
pub is_will_quit: AtomicBool,
4851
/// Epoch milliseconds of the last window-geometry persist. Used by
4952
/// the Moved/Resized handlers in `lifecycle` to coalesce writes
@@ -74,6 +77,7 @@ impl AppState {
7477
config: Mutex::new(config),
7578
store_lock: Mutex::new(()),
7679
config_write_lock: Mutex::new(()),
80+
update_check_lock: tokio::sync::Mutex::new(()),
7781
is_will_quit: AtomicBool::new(false),
7882
last_geometry_persist_ms: AtomicU64::new(0),
7983
})

‎src/common/i18n/languages/de.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const lang: LanguageDict = {
1616
append: 'Anhängen',
1717
auto_check_update: 'Automatisch nach Updates suchen',
1818
auto_check_update_desc:
19-
'Wenn aktiviert, sucht SwitchHosts beim Start nach offiziellen Release-Updates und zeigt nur einen Hinweis an. Updates werden nie automatisch heruntergeladen.',
19+
'Wenn aktiviert, zeigt SwitchHosts einen Hinweis an, sobald eine neue Version verfügbar ist. Updates werden nicht automatisch heruntergeladen oder installiert.',
2020
auto_refresh: 'Automatisch aktualisieren',
2121
btn_cancel: 'Abbrechen',
2222
btn_ok: 'OK',

‎src/common/i18n/languages/en.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export default {
1414
append: 'Append',
1515
auto_check_update: 'Automatically Check for Updates',
1616
auto_check_update_desc:
17-
'When enabled, SwitchHosts checks for official release updates at launch and only shows a reminder. Updates are never downloaded automatically.',
17+
'When enabled, SwitchHosts will remind you when a new version is available and will not download or install updates automatically.',
1818
auto_refresh: 'Auto Refresh',
1919
btn_cancel: 'Cancel',
2020
btn_ok: 'OK',

‎src/common/i18n/languages/fr.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const lang: LanguageDict = {
1616
append: 'Ajouter',
1717
auto_check_update: 'Vérifier automatiquement les mises à jour',
1818
auto_check_update_desc:
19-
'Si activé, SwitchHosts vérifie au lancement les mises à jour des versions officielles et affiche seulement un rappel. Les mises à jour ne sont jamais téléchargées automatiquement.',
19+
'Si activé, SwitchHosts vous avertit lorsqu’une nouvelle version est disponible, sans télécharger ni installer les mises à jour automatiquement.',
2020
auto_refresh: 'Rafraîchissement automatique',
2121
btn_cancel: 'Annuler',
2222
btn_ok: 'OK',

0 commit comments

Comments
 (0)