The personal finance app for everyone (by everyone)
Ruby
fix(desktop): save attachment downloads and confirm them in the app (#3571)
Anthony618a9931b366
diff --git a/app/views/layouts/shared/_notification_tray.html.erb b/app/views/layouts/shared/_notification_tray.html.erbindex 6ea5c3cc89..c19e58a2dd 100644--- a/app/views/layouts/shared/_notification_tray.html.erb+++ b/app/views/layouts/shared/_notification_tray.html.erb@@ -15,3 +15,14 @@up. Empty and visually hidden, so it costs nothing when unused. %><div id="aria-announcer" class="sr-only" role="status" aria-live="polite" aria-atomic="true"></div></div>++<%# The desktop app has no download list of its own: when a download ends it+ clones one of these into the tray, so the confirmation is an ordinary Sure+ toast, and reads the data attributes for its native notification. A+ template stays inert in a browser. %>+<template id="desktop-download-complete" data-message="<%= t(".download_complete") %>" data-description="<%= t(".download_location") %>">+ <%= render "shared/notifications/notice", message: t(".download_complete"), description: t(".download_location") %>+</template>+<template id="desktop-download-failed" data-message="<%= t(".download_failed") %>">+ <%= render "shared/notifications/alert", message: t(".download_failed") %>+</template>diff --git a/config/locales/views/layout/en.yml b/config/locales/views/layout/en.ymlindex b708be65d7..4cada73e4b 100644--- a/config/locales/views/layout/en.yml+++ b/config/locales/views/layout/en.yml@@ -32,6 +32,10 @@ en:are_you_sure: Are you sure?cannot_be_undone: This action cannot be undone.confirm: Confirm+ notification_tray:+ download_complete: Download complete+ download_failed: Download failed. Please try again.+ download_location: The file is in your Downloads folder.trial:open_demo: Open demodata_deleted_in_days: Data deleted in %{days} daysdiff --git a/config/locales/views/layout/fr.yml b/config/locales/views/layout/fr.ymlindex 5b76b401af..065a0377dd 100644--- a/config/locales/views/layout/fr.yml+++ b/config/locales/views/layout/fr.yml@@ -29,6 +29,10 @@ fr:footer:privacy_policy: Politique de confidentialitéterms_of_service: Conditions d'utilisation+ notification_tray:+ download_complete: Téléchargement terminé+ download_failed: Le téléchargement a échoué. Veuillez réessayer.+ download_location: Le fichier se trouve dans votre dossier Téléchargements.trial:contribute: Contribuerdata_deleted_in_days: Les données seront supprimées dans %{days} joursdiff --git a/desktop/README.md b/desktop/README.mdindex 03f5f35f5f..d60deadf96 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -59,9 +59,16 @@ cargo test## Reports and downloads-CSV exports are saved in the macOS Downloads folder. Sure sends a native-notification when a download finishes or fails; allow Sure notifications in-System Settings to see them. Repeated downloads get a numbered filename.+Files your Sure server sends as downloads (CSV exports, statements, transaction+attachments, the import sample CSV) are saved in the macOS Downloads folder,+even when the app could display them. When a download finishes or fails, Sure+shows its usual message in the window, or in the main window when the download+came from a window that closed itself. A native notification is also sent when+that window is not in front, and replaces the message when the window is hidden+or the server is too old to provide it (allow Sure notifications in System+Settings to see them). The notification uses the message's text in Sure's+language, and is in English only with a server too old to provide the message.+Repeated downloads get a numbered filename.Print Report opens a separate Sure window using the current signed-in session,then the native print dialog once the report has loaded. Print it, or choose@@ -70,12 +77,16 @@ PDF → Save as PDF. Close the report window to return to the app.Other links that open a new window follow the same rule: pages of your Sureserver open in a separate Sure window with your session, and other websitesopen in your default browser. Only the main window has the desktop-integrations: notifications, SSO in your browser and report CSV exports.-Downloads are only accepted from pages of your saved servers.--To verify changes to this flow, run `npm test` and `npm run build` in `desktop`,-then `cargo test --locked` in `desktop/src-tauri`. In the desktop app, export a-CSV twice, check both files in Downloads, and open Print Report to save a PDF.+integrations: notifications and SSO in your browser. Downloads are only+accepted from pages of your saved servers.++To verify changes to this flow, run `npm run build` in `desktop`, then+`cargo test --locked` in `desktop/src-tauri`. In the desktop app, export a+report CSV twice and check both files in Downloads. Download a statement PDF+and a transaction attachment, check that the app page stays in place, and open+Print Report to save a PDF. Open a CSV statement with its view link (the eye+icon on an account's statements): the file is saved in Downloads, no empty Sure+window stays open, and the message appears in the main window.Open an external link (for example the Discord help icon) and check that itopens in your browser. Repeat against a server mounted under a URL prefix, ifapplicable.diff --git a/desktop/package.json b/desktop/package.jsonindex f76d571f2b..237b6ec8ee 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -6,7 +6,6 @@"scripts": {"dev": "vite","build": "tsc --noEmit && vite build",- "test": "node --test tests/*.test.mjs","tauri": "tauri"},"devDependencies": {diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lockindex 235f21660f..584a927574 100644--- a/desktop/src-tauri/Cargo.lock+++ b/desktop/src-tauri/Cargo.lock@@ -3634,8 +3634,12 @@ name = "sure-desktop"version = "0.1.0"dependencies = ["base64 0.22.1",+ "block2","getrandom 0.2.17","keyring",+ "objc2",+ "objc2-foundation",+ "objc2-web-kit","open","serde","serde_json",diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 2310bb5d03..c841cd8790 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -26,4 +26,11 @@ sha2 = "0.10"base64 = "0.22"getrandom = "0.2"+# Already in the tree through wry; used directly to save attachment responses.+[target.'cfg(target_os = "macos")'.dependencies]+block2 = "0.6"+objc2 = "0.6"+objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSObject", "NSString", "NSURLResponse"] }+objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-app-kit", "WKDownload", "WKNavigation", "WKNavigationAction", "WKNavigationDelegate", "WKNavigationResponse", "WKWebView"] }+[dev-dependencies]diff --git a/desktop/src-tauri/src/attachments.rs b/desktop/src-tauri/src/attachments.rsnew file mode 100644index 0000000000..ba90c8c1d4--- /dev/null+++ b/desktop/src-tauri/src/attachments.rs@@ -0,0 +1,220 @@+//! Save the files a server sends as downloads.+//!+//! wry only turns a response into a download when WebKit cannot display it, so+//! a PDF or CSV sent with `Content-Disposition: attachment` replaced the page+//! instead of being saved. A browser saves it. [`save_attachments`] puts a+//! navigation delegate in front of wry's that makes the same choice, and passes+//! every other delegate call on to wry's delegate.++/// Whether a `Content-Disposition` header value asks for the body to be saved.+pub fn is_attachment(content_disposition: &str) -> bool {+ content_disposition+ .split(';')+ .next()+ .is_some_and(|kind| kind.trim().eq_ignore_ascii_case("attachment"))+}++#[cfg(target_os = "macos")]+pub use macos::save_attachments;++/// The delegate is specific to WKWebView, so other platforms keep wry's own+/// download handling.+#[cfg(not(target_os = "macos"))]+pub fn save_attachments(_window: &tauri::WebviewWindow) {}++#[cfg(target_os = "macos")]+mod macos {+ use std::ffi::c_void;++ use objc2::rc::{Retained, Weak};+ use objc2::runtime::{AnyObject, NSObject, ProtocolObject};+ use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};+ use objc2_foundation::{NSHTTPURLResponse, NSObjectProtocol, NSString};+ use objc2_web_kit::{+ WKDownload, WKNavigation, WKNavigationAction, WKNavigationActionPolicy,+ WKNavigationDelegate, WKNavigationResponse, WKNavigationResponsePolicy, WKWebView,+ };++ /// Associates the delegate with its webview, which retains it: the+ /// `navigationDelegate` property itself is weak.+ static DELEGATE_KEY: u8 = 0;++ struct Ivars {+ /// wry's delegate, which wry keeps alive as long as its webview. Held+ /// weakly: the webview retains this object, and wry's delegate retains+ /// the webview.+ wry: Weak<ProtocolObject<dyn WKNavigationDelegate>>,+ }++ define_class!(+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "SureAttachmentNavigationDelegate"]+ #[ivars = Ivars]+ struct AttachmentNavigationDelegate;++ unsafe impl NSObjectProtocol for AttachmentNavigationDelegate {}++ // The delegate methods wry 0.55 implements, each passed on to wry's+ // delegate while it exists. They are explicit rather than forwarded, so+ // a call arriving once wry's delegate is gone is dropped instead of+ // raising an unrecognized selector exception; policy calls still get a+ // decision.+ unsafe impl WKNavigationDelegate for AttachmentNavigationDelegate {+ #[unsafe(method(webView:decidePolicyForNavigationAction:decisionHandler:))]+ fn decide_policy_for_navigation_action(+ &self,+ web_view: &WKWebView,+ navigation_action: &WKNavigationAction,+ decision_handler: &block2::DynBlock<dyn Fn(WKNavigationActionPolicy)>,+ ) {+ match self.ivars().wry.load() {+ Some(wry) => unsafe {+ wry.webView_decidePolicyForNavigationAction_decisionHandler(+ web_view,+ navigation_action,+ decision_handler,+ );+ },+ None => decision_handler.call((WKNavigationActionPolicy::Cancel,)),+ }+ }++ #[unsafe(method(webView:decidePolicyForNavigationResponse:decisionHandler:))]+ fn decide_policy_for_navigation_response(+ &self,+ web_view: &WKWebView,+ navigation_response: &WKNavigationResponse,+ decision_handler: &block2::DynBlock<dyn Fn(WKNavigationResponsePolicy)>,+ ) {+ match self.ivars().wry.load() {+ Some(_) if response_is_attachment(navigation_response) => {+ decision_handler.call((WKNavigationResponsePolicy::Download,));+ }+ Some(wry) => unsafe {+ wry.webView_decidePolicyForNavigationResponse_decisionHandler(+ web_view,+ navigation_response,+ decision_handler,+ );+ },+ None => decision_handler.call((WKNavigationResponsePolicy::Cancel,)),+ }+ }++ #[unsafe(method(webView:didCommitNavigation:))]+ fn did_commit_navigation(+ &self,+ web_view: &WKWebView,+ navigation: Option<&WKNavigation>,+ ) {+ if let Some(wry) = self.ivars().wry.load() {+ unsafe { wry.webView_didCommitNavigation(web_view, navigation) };+ }+ }++ #[unsafe(method(webView:didFinishNavigation:))]+ fn did_finish_navigation(+ &self,+ web_view: &WKWebView,+ navigation: Option<&WKNavigation>,+ ) {+ if let Some(wry) = self.ivars().wry.load() {+ unsafe { wry.webView_didFinishNavigation(web_view, navigation) };+ }+ }++ #[unsafe(method(webView:navigationAction:didBecomeDownload:))]+ fn navigation_action_did_become_download(+ &self,+ web_view: &WKWebView,+ navigation_action: &WKNavigationAction,+ download: &WKDownload,+ ) {+ if let Some(wry) = self.ivars().wry.load() {+ unsafe {+ wry.webView_navigationAction_didBecomeDownload(+ web_view,+ navigation_action,+ download,+ );+ }+ }+ }++ #[unsafe(method(webView:navigationResponse:didBecomeDownload:))]+ fn navigation_response_did_become_download(+ &self,+ web_view: &WKWebView,+ navigation_response: &WKNavigationResponse,+ download: &WKDownload,+ ) {+ if let Some(wry) = self.ivars().wry.load() {+ unsafe {+ wry.webView_navigationResponse_didBecomeDownload(+ web_view,+ navigation_response,+ download,+ );+ }+ }+ }++ #[unsafe(method(webViewWebContentProcessDidTerminate:))]+ fn web_content_process_did_terminate(&self, web_view: &WKWebView) {+ if let Some(wry) = self.ivars().wry.load() {+ unsafe { wry.webViewWebContentProcessDidTerminate(web_view) };+ }+ }+ }+ );++ fn response_is_attachment(navigation_response: &WKNavigationResponse) -> bool {+ let response = unsafe { navigation_response.response() };+ let Some(http) = response.downcast_ref::<NSHTTPURLResponse>() else {+ return false;+ };+ let header = NSString::from_str("Content-Disposition");+ http.valueForHTTPHeaderField(&header)+ .is_some_and(|value| super::is_attachment(&value.to_string()))+ }++ /// Save attachment responses of this window's webview into Downloads,+ /// through wry's download handling and so the window's `on_download`.+ pub fn save_attachments(window: &tauri::WebviewWindow) {+ let result = window.with_webview(|platform| {+ // SAFETY: on macOS tauri passes a WKWebView, its content controller+ // and its NSWindow, each retained for this call and never released.+ // Taking the references back releases them when this closure ends.+ let web_view = unsafe { Retained::<WKWebView>::from_raw(platform.inner().cast()) };+ drop(unsafe { Retained::<AnyObject>::from_raw(platform.controller().cast()) });+ drop(unsafe { Retained::<AnyObject>::from_raw(platform.ns_window().cast()) });+ // The closure runs on the main thread.+ let (Some(web_view), Some(mtm)) = (web_view, MainThreadMarker::new()) else {+ return;+ };+ let Some(wry) = (unsafe { web_view.navigationDelegate() }) else {+ return;+ };+ let delegate = mtm+ .alloc::<AttachmentNavigationDelegate>()+ .set_ivars(Ivars {+ wry: Weak::from_retained(&wry),+ });+ let delegate: Retained<AttachmentNavigationDelegate> =+ unsafe { msg_send![super(delegate), init] };+ unsafe {+ objc2::ffi::objc_setAssociatedObject(+ Retained::as_ptr(&web_view).cast_mut().cast(),+ (&DELEGATE_KEY as *const u8).cast::<c_void>(),+ Retained::as_ptr(&delegate).cast_mut().cast(),+ objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,+ );+ web_view.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate)));+ }+ });+ if let Err(error) = result {+ eprintln!("[sure] failed to enable attachment downloads: {error}");+ }+ }+}diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 18853b1c98..7d451235aa 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -1,3 +1,4 @@+pub mod attachments;pub mod badge;pub mod commands;pub mod deep_link;diff --git a/desktop/src-tauri/src/window.rs b/desktop/src-tauri/src/window.rsindex 8a5c37de41..11fbd23002 100644--- a/desktop/src-tauri/src/window.rs+++ b/desktop/src-tauri/src/window.rs@@ -1,4 +1,4 @@-use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use tauri::webview::{DownloadEvent, NewWindowResponse, PageLoadEvent, PageLoadPayload};@@ -13,6 +13,11 @@ static POPUP_WINDOW_ID: AtomicUsize = AtomicUsize::new(0);/// matches the delay in Sure's print layout, which lets styles settle.const PRINT_DELAY: Duration = Duration::from_millis(500);+/// Ids of the toast templates Sure renders next to its notification tray, one+/// per download outcome.+const DOWNLOAD_COMPLETE_TOAST: &str = "desktop-download-complete";+const DOWNLOAD_FAILED_TOAST: &str = "desktop-download-failed";+pub fn setup(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {// Build the configured window here so native download and popup handlers// are attached before the webview loads the server.@@ -37,6 +42,7 @@ pub fn setup(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {}).on_new_window(move |url, _| on_new_window(&handle, &page, url)).build()?;+ crate::attachments::save_attachments(&window);// The window is opaque (the app paints its own solid backgrounds), so we// skip the transparent-window vibrancy blur — it never showed through and@@ -143,13 +149,20 @@ fn open_server_window(handle: &AppHandle, url: Url) {// Until a page commits, the window stands for the saved-server address it// was opened with, so a file served directly at that address can download.let page = ShownPage(Arc::new(Mutex::new(Some(url.clone()))));+ // Stays false when the address answers with a file, as a CSV statement+ // opened for viewing does: the window then never shows a page.+ let showed_page = Arc::new(AtomicBool::new(false));let popup_handle = handle.clone();let result = WebviewWindowBuilder::new(handle, label, WebviewUrl::External(url)).title("Sure").inner_size(1000.0, 800.0).on_page_load({let page = page.clone();+ let showed_page = showed_page.clone();move |window, payload| {+ if payload.event() == PageLoadEvent::Started {+ showed_page.store(true, Ordering::Relaxed);+ }page.record(&payload);print_loaded_report(window, payload);}@@ -157,15 +170,38 @@ fn open_server_window(handle: &AppHandle, url: Url) {.on_download({let page = page.clone();let refused = RefusedDownloads::default();- move |webview, event| on_download(&page, &refused, webview, event)+ move |webview, event| {+ let finished = matches!(event, DownloadEvent::Finished { .. });+ let window = webview.window();+ let allowed = on_download(&page, &refused, webview, event);+ if !showed_page.load(Ordering::Relaxed) {+ dismiss_empty_popup(window, finished);+ }+ allowed+ }}).on_new_window(move |url, _| on_new_window(&popup_handle, &page, url)).on_document_title_changed(|window, title| {let _ = window.set_title(&title);}).build();- if let Err(error) = result {- eprintln!("[sure] failed to open window: {error}");+ match result {+ Ok(window) => crate::attachments::save_attachments(&window),+ Err(error) => eprintln!("[sure] failed to open window: {error}"),+ }+}++/// Hide a popup whose address answered with a file instead of a page, then+/// close it once the download ends. `close` is queued on the event loop, so the+/// webview, whose download delegate runs this callback, is destroyed only after+/// the callback returns.+fn dismiss_empty_popup(window: tauri::Window, download_finished: bool) {+ if download_finished {+ if let Err(error) = window.close() {+ eprintln!("[sure] failed to close an empty window: {error}");+ }+ } else if let Err(error) = window.hide() {+ eprintln!("[sure] failed to hide an empty window: {error}");}}@@ -233,29 +269,115 @@ fn on_download(refused.remember(&url, allowed)}DownloadEvent::Finished { url, success, .. } => {- if !refused.should_report(&url, success) {- return true;- }- // macOS does not return a path in Finished. Wry saves downloads to the- // Downloads directory and adds a suffix when a filename already exists.- let body = if success {- "Download complete. The file is in your Downloads folder."- } else {- eprintln!("[sure] download failed");- "Download failed. Please try again."- };- if let Err(error) = webview- .app_handle()- .notification()- .builder()- .title("Sure")- .body(body)- .show()- {- eprintln!("[sure] failed to show download notification: {error}");+ if refused.should_report(&url, success) {+ if !success {+ eprintln!("[sure] download failed");+ }+ report_download(&webview, success);}true}_ => true,}}++/// What the toast script reports: whether it showed Sure's toast, and the+/// toast's text in the page's language, for the native notification.+#[derive(Debug, Default, PartialEq, serde::Deserialize)]+pub struct DownloadToast {+ #[serde(default)]+ pub shown: bool,+ pub message: Option<String>,+ pub description: Option<String>,+}++impl DownloadToast {+ /// Read the script's result. `null`, from a page without the template (an+ /// older server), or any other unexpected value means no toast and no text.+ pub fn from_script_result(result: &str) -> Self {+ serde_json::from_str::<Option<Self>>(result)+ .ok()+ .flatten()+ .unwrap_or_default()+ }+}++/// Title and body of the native notification for a finished download: the+/// toast's own text when the page provides it, English otherwise.+pub fn download_notification(success: bool, toast: &DownloadToast) -> (String, String) {+ let message = toast.message.clone().filter(|text| !text.is_empty());+ let description = toast.description.clone().filter(|text| !text.is_empty());+ match (message, description) {+ (Some(message), Some(description)) => (message, description),+ (Some(message), None) => ("Sure".to_string(), message),+ // macOS does not return a path in Finished. Wry saves downloads to the+ // Downloads directory and adds a suffix when a filename already exists.+ (None, _) if success => (+ "Sure".to_string(),+ "Download complete. The file is in your Downloads folder.".to_string(),+ ),+ (None, _) => (+ "Sure".to_string(),+ "Download failed. Please try again.".to_string(),+ ),+ }+}++/// Confirm a finished download with Sure's own toast, cloned from a template the+/// page renders. A native notification replaces it when no visible window can+/// show it or the page has no such template, as with an older server, and is+/// sent as well when the window is not in front. It reuses the toast's text, so+/// it is in the page's language whenever the page provides the template.+fn report_download(webview: &tauri::Webview, success: bool) {+ let app = webview.app_handle().clone();+ // A popup hidden because its address was the file shows nothing.+ let target = if webview.window().is_visible().unwrap_or(false) {+ Some(webview.clone())+ } else {+ app.get_webview_window("main")+ .map(|main| main.as_ref().clone())+ };+ let Some(target) = target else {+ return notify_download(&app, success, &DownloadToast::default());+ };+ // A toast added to a hidden window would only show up, stale, on reopening,+ // so there the script only reads the text.+ let visible = target.window().is_visible().unwrap_or(false);+ let in_front = visible && target.window().is_focused().unwrap_or(false);+ let template = if success {+ DOWNLOAD_COMPLETE_TOAST+ } else {+ DOWNLOAD_FAILED_TOAST+ };+ let script = format!(+ "(() => {{+ const template = document.getElementById({template:?});+ if (!(template instanceof HTMLTemplateElement)) return null;+ const tray = document.getElementById(\"notification-tray\");+ const shown = {visible} && tray !== null;+ if (shown) tray.append(template.content.cloneNode(true));+ return {{+ shown,+ message: template.dataset.message ?? null,+ description: template.dataset.description ?? null,+ }};+ }})()"+ );+ let notify_app = app.clone();+ let evaluated = target.eval_with_callback(script, move |result| {+ let toast = DownloadToast::from_script_result(&result);+ if !toast.shown || !in_front {+ notify_download(¬ify_app, success, &toast);+ }+ });+ if evaluated.is_err() {+ notify_download(&app, success, &DownloadToast::default());+ }+}++fn notify_download(app: &AppHandle, success: bool, toast: &DownloadToast) {+ let (title, body) = download_notification(success, toast);+ if let Err(error) = app.notification().builder().title(title).body(body).show() {+ eprintln!("[sure] failed to show download notification: {error}");+ }+}diff --git a/desktop/src-tauri/tests/attachments_test.rs b/desktop/src-tauri/tests/attachments_test.rsnew file mode 100644index 0000000000..1d179d54b9--- /dev/null+++ b/desktop/src-tauri/tests/attachments_test.rs@@ -0,0 +1,26 @@+use sure_desktop_lib::attachments::is_attachment;++#[test]+fn saves_responses_marked_as_attachments() {+ for header in [+ "attachment",+ "attachment; filename=\"statement.pdf\"; filename*=UTF-8''statement.pdf",+ "Attachment; filename=transactions_breakdown.csv",+ " attachment ;filename=sample.csv",+ ] {+ assert!(is_attachment(header), "{header}");+ }+}++#[test]+fn displays_every_other_response() {+ for header in [+ "",+ "inline",+ "inline; filename=\"attachment.pdf\"",+ "attachments",+ "form-data; name=\"attachment\"",+ ] {+ assert!(!is_attachment(header), "{header}");+ }+}diff --git a/desktop/src-tauri/tests/window_test.rs b/desktop/src-tauri/tests/window_test.rsindex 5219ae3301..4c783f88a3 100644--- a/desktop/src-tauri/tests/window_test.rs+++ b/desktop/src-tauri/tests/window_test.rs@@ -1,5 +1,8 @@use sure_desktop_lib::servers::{base_covers, normalize_server_url};-use sure_desktop_lib::window::{popup_action, print_report_server, PopupAction, RefusedDownloads};+use sure_desktop_lib::window::{+ download_notification, popup_action, print_report_server, DownloadToast, PopupAction,+ RefusedDownloads,+};use url::Url;#[test]@@ -136,3 +139,94 @@ fn reports_every_download_outcome_except_refused_downloads() {"each refusal silences only its own failure");}++#[test]+fn reads_what_the_toast_script_reports() {+ assert_eq!(+ DownloadToast::from_script_result(+ r#"{"shown":true,"message":"Téléchargement terminé","description":"Le fichier se trouve dans votre dossier Téléchargements."}"#+ ),+ DownloadToast {+ shown: true,+ message: Some("Téléchargement terminé".to_string()),+ description: Some(+ "Le fichier se trouve dans votre dossier Téléchargements.".to_string()+ ),+ }+ );+ assert_eq!(+ DownloadToast::from_script_result(+ r#"{"shown":false,"message":"Download failed. Please try again.","description":null}"#+ ),+ DownloadToast {+ shown: false,+ message: Some("Download failed. Please try again.".to_string()),+ description: None,+ }+ );+ // A page without the template, a failed script, or anything unexpected.+ for result in ["null", "", "true", "{\"shown\":\"yes\"}"] {+ assert_eq!(+ DownloadToast::from_script_result(result),+ DownloadToast::default(),+ "{result}"+ );+ }+}++#[test]+fn notifies_in_the_page_language_when_the_page_provides_the_text() {+ let complete = DownloadToast {+ shown: true,+ message: Some("Téléchargement terminé".to_string()),+ description: Some("Le fichier se trouve dans votre dossier Téléchargements.".to_string()),+ };+ assert_eq!(+ download_notification(true, &complete),+ (+ "Téléchargement terminé".to_string(),+ "Le fichier se trouve dans votre dossier Téléchargements.".to_string()+ )+ );++ let failed = DownloadToast {+ shown: false,+ message: Some("Le téléchargement a échoué. Veuillez réessayer.".to_string()),+ description: None,+ };+ assert_eq!(+ download_notification(false, &failed),+ (+ "Sure".to_string(),+ "Le téléchargement a échoué. Veuillez réessayer.".to_string()+ )+ );+}++#[test]+fn notifies_in_english_when_the_page_has_no_toast_text() {+ let none = DownloadToast::default();+ assert_eq!(+ download_notification(true, &none),+ (+ "Sure".to_string(),+ "Download complete. The file is in your Downloads folder.".to_string()+ )+ );+ assert_eq!(+ download_notification(false, &none),+ (+ "Sure".to_string(),+ "Download failed. Please try again.".to_string()+ )+ );+ let empty = DownloadToast {+ shown: false,+ message: Some(String::new()),+ description: Some(String::new()),+ };+ assert_eq!(+ download_notification(true, &empty),+ download_notification(true, &none)+ );+}diff --git a/desktop/src/bridge.ts b/desktop/src/bridge.tsindex dd2d9d9431..8778bb116a 100644--- a/desktop/src/bridge.ts+++ b/desktop/src/bridge.ts@@ -1,7 +1,7 @@// Injected into every page loaded in the main window (local onboarding + the// remote Sure site). Adds native-titlebar chrome, drags the window, forwards-// notifications/badge to Rust, enables report downloads, intercepts SSO into the-// system browser, and navigates on server switches.+// notifications/badge to Rust, intercepts SSO into the system browser, and+// navigates on server switches.(() => {const tauri = (window as any).__TAURI__;@@ -16,36 +16,6 @@hasWindow: !!tauri?.window,});- // WKWebView needs the download attribute for renderable types such as CSV.- // Keep the request in this webview so its authenticated session is retained.- // Capture runs before Turbo, while leaving the native click action intact.- if (!(window as any).__sureReportDownloadHook) {- (window as any).__sureReportDownloadHook = true;- document.addEventListener(- "click",- (ev) => {- const link = (ev.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;- if (!link) return;- let url: URL;- try {- url = new URL(link.href, location.href);- } catch {- return;- }- if (- url.origin !== location.origin ||- !url.pathname.endsWith("/reports/export_transactions.csv")- ) {- return;- }- if (!link.hasAttribute("download")) link.setAttribute("download", "");- link.setAttribute("data-turbo", "false");- link.setAttribute("target", "_self");- },- true- );- }-// Native titlebar chrome — offset the left icon rail so its logo clears the// traffic lights, and make the top ~34px band drag the window. Using a// document-level mousedown (rather than a fixed overlay strip) means draggingdiff --git a/desktop/tests/bridge.test.mjs b/desktop/tests/bridge.test.mjsdeleted file mode 100644index a957a56772..0000000000--- a/desktop/tests/bridge.test.mjs+++ /dev/null@@ -1,147 +0,0 @@-import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import vm from "node:vm";-import ts from "typescript";--const source = readFileSync(new URL("../src/bridge.ts", import.meta.url), "utf8");-const script = new vm.Script(- ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2021 } }).outputText-);--function loadBridge(pageUrl = "https://sure.example/reports") {- const listeners = new Map();- const context = vm.createContext({- URL,- window: {},- location: new URL(pageUrl),- console: { log() {}, warn() {} },- document: {- head: { appendChild() {} },- createElement: () => ({}),- addEventListener(type, listener, capture) {- const entries = listeners.get(type) || [];- entries.push({ listener, capture });- listeners.set(type, entries);- },- },- });- script.runInContext(context);-- return {- reinject: () => script.runInContext(context),- listeners,- click(target) {- const event = {- target,- defaultPrevented: false,- propagationStopped: false,- preventDefault() { this.defaultPrevented = true; },- stopImmediatePropagation() { this.propagationStopped = true; },- };- for (const { listener, capture } of listeners.get("click") || []) {- assert.equal(capture, true, "the export link must be prepared before Turbo handles the click");- listener(event);- }- return event;- },- };-}--function anchor(href, attributes = {}) {- const values = { href, ...attributes };- const link = {- href,- attributes: values,- hasAttribute: (name) => Object.hasOwn(values, name),- setAttribute: (name, value) => { values[name] = value; },- closest: (selector) => {- assert.equal(selector, "a[href]");- return link;- },- };- return link;-}--function nestedTarget(link) {- return {- closest(selector) {- assert.equal(selector, "a[href]");- return link;- },- };-}--test("CSV clicks select native download without cancelling the authenticated request", () => {- const bridge = loadBridge();- const href = "/reports/export_transactions.csv?period_type=custom&start_date=2026-09-01&end_date=2026-09-09";- const link = anchor(href, { target: "_blank" });-- const event = bridge.click(nestedTarget(link));-- assert.deepEqual(link.attributes, {- href,- target: "_self",- download: "",- "data-turbo": "false",- });- assert.equal(link.href, href, "the export URL and date filters must stay unchanged");- assert.equal(event.defaultPrevented, false);- assert.equal(event.propagationStopped, false);-});--test("CSV downloads support a server mounted beneath a path prefix", () => {- const bridge = loadBridge("https://sure.example/finance/sure/reports");- const link = anchor("https://sure.example/finance/sure/reports/export_transactions.csv?period_type=ytd");-- bridge.click(link);-- assert.equal(link.attributes.download, "");- assert.equal(link.attributes.target, "_self");-});--test("an explicit filename is retained when marking a report download", () => {- const bridge = loadBridge();- const link = anchor("/reports/export_transactions.csv", { download: "report.csv" });-- bridge.click(nestedTarget(link));-- assert.equal(link.attributes.download, "report.csv");-});--test("other origins, routes and formats are left unchanged", () => {- const bridge = loadBridge();- for (const href of [- "https://other.example/reports/export_transactions.csv",- "http://sure.example/reports/export_transactions.csv",- "https://sure.example:8443/reports/export_transactions.csv",- "/reports/print",- "/reports/export_transactions.pdf",- "/reports/export_transactions.csv/preview",- "/other.csv",- "http://[invalid",- ]) {- const link = anchor(href, { target: "_blank" });-- bridge.click(nestedTarget(link));-- assert.deepEqual(link.attributes, { href, target: "_blank" }, href);- }-});--test("clicks outside links remain unaffected", () => {- const bridge = loadBridge();- assert.doesNotThrow(() => bridge.click(nestedTarget(null)));- assert.doesNotThrow(() => bridge.click({}));- assert.doesNotThrow(() => bridge.click(null));-});--test("reinjection installs only one report download listener, even without Tauri IPC", () => {- const bridge = loadBridge();- bridge.reinject();-- assert.equal(bridge.listeners.get("click").length, 1);- const link = anchor("/reports/export_transactions.csv");- bridge.click(nestedTarget(link));- assert.equal(link.attributes.download, "");-});diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex ddd3ae2ea6..0356aa62ba 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -96,6 +96,24 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_response :okend+ # The desktop app clones these into the tray when a download such as the CSV+ # export ends, since it has no download list of its own, and reads their data+ # attributes for its native notification.+ test "index provides the download toasts the desktop app shows" do+ get reports_path++ assert_response :ok+ scope = "layouts.shared.notification_tray"+ assert_select "template#desktop-download-complete", 1+ assert_select "template#desktop-download-failed", 1+ assert_select "template#desktop-download-complete[data-message=?][data-description=?]",+ I18n.t("#{scope}.download_complete"), I18n.t("#{scope}.download_location")+ assert_select "template#desktop-download-failed[data-message=?]", I18n.t("#{scope}.download_failed")+ assert_includes response.body, I18n.t("#{scope}.download_complete")+ assert_includes response.body, I18n.t("#{scope}.download_location")+ assert_includes response.body, I18n.t("#{scope}.download_failed")+ end+test "index with monthly period" doget reports_path(period_type: :monthly)assert_response :ok