Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(desktop): Windows approval dialogs that refuse by default

Marcelito76485b962d18
diff --git a/apps/desktop/src-tauri/src/alert.rs b/apps/desktop/src-tauri/src/alert.rs
index f80d700..9d0dbcf 100644
--- a/apps/desktop/src-tauri/src/alert.rs
+++ b/apps/desktop/src-tauri/src/alert.rs
@@ -10,6 +10,15 @@
//! rfd shows a `CFUserNotification` and reports cancels and failures as `Cancel`, which the plugin
//! turns into the second label of `OkCancelCustom` (T23c B1).
//!
+//! Windows: a task dialog whose default button is the refusing one, so Return refuses; Escape and
+//! closing answer `IDCANCEL`, and only the allowing button's own id allows. The dialog plugin is
+//! not used there: rfd's task dialog makes its first button (the OK slot, the allowing label) the
+//! default, so Return would allow. It asks to be raised above the app being controlled when it
+//! opens. Another thread can ask an `OpenDialog` to refuse its dialog (an approval that timed out,
+//! as `abortModal` does on macOS): the dialog's own timer presses its refusing button, on its own
+//! thread, so no other thread ever touches its window. A dialog given a deadline refuses itself
+//! the same way once it passes, even when it opened after the timeout.
+//!
//! Elsewhere (Linux): the dialog plugin with the allowing label in the OK slot and the refusing one
//! in the cancel slot, so every outcome rfd reports as `Cancel` (the refusing button, Escape,
//! closing, a dialog that failed) arrives as the refusing label. rfd's GTK dialog sets no default
@@ -23,6 +32,31 @@ pub const REFUSE_RESPONSE: isize = 1000;
/// The `NSAlert` response of the allowing button, added second (`NSAlertSecondButtonReturn`).
pub const ALLOW_RESPONSE: isize = 1001;
+/// The Windows task dialog's button ids: the refusing one is the default.
+pub const TASK_REFUSE_ID: i32 = 2000;
+pub const TASK_ALLOW_ID: i32 = 2001;
+
+/// A request to refuse the dialog on screen (Windows), set from another thread and acted on by
+/// the dialog's own timer. Elsewhere it holds nothing: no other platform refuses a dialog this way.
+#[derive(Default)]
+pub struct OpenDialog(#[cfg(windows)] std::sync::atomic::AtomicBool);
+
+impl OpenDialog {
+ /// Asks the dialog on screen, if one is, to refuse (Windows; elsewhere nothing). Its next
+ /// timer tick, within about 200 ms, presses its refusing button, and the dialog answers as
+ /// refused.
+ pub fn refuse(&self) {
+ #[cfg(windows)]
+ self.0.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+}
+
+/// Whether a dialog's timer should press its refusing button now: a refusal was asked for, or
+/// its deadline has passed.
+pub fn refuse_due(requested: bool, deadline: Option<std::time::Instant>, now: std::time::Instant) -> bool {
+ requested || deadline.is_some_and(|deadline| now >= deadline)
+}
+
/// The two buttons of a yes/no alert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Choice {
@@ -41,7 +75,12 @@ impl Choice {
self.allow != self.refuse && response == Some(ALLOW_RESPONSE)
}
- /// The plugin's buttons (off macOS): the refusing label takes the cancel slot, where rfd puts
+ /// True only for the allowing button's id (Windows); `None` is a dialog that never ran.
+ pub fn allows_task_button(&self, button: Option<i32>) -> bool {
+ self.allow != self.refuse && button == Some(TASK_ALLOW_ID)
+ }
+
+ /// The plugin's buttons (Linux): the refusing label takes the cancel slot, where rfd puts
/// Escape, closing, and failures.
pub fn buttons(&self) -> MessageDialogButtons {
MessageDialogButtons::OkCancelCustom(self.allow.into(), self.refuse.into())
@@ -56,10 +95,32 @@ impl Choice {
/// Shows the alert and waits for the answer. Blocks, so it never runs on the main thread (there it
/// refuses at once).
pub fn ask(app: &AppHandle, title: &str, message: &str, choice: Choice) -> bool {
+ ask_tracked(app, title, message, choice, None, None)
+}
+
+/// `ask`, letting `open` refuse the dialog from another thread (`OpenDialog::refuse`), and refusing
+/// it by itself once `deadline` passes (Windows).
+pub fn ask_tracked(
+ app: &AppHandle,
+ title: &str,
+ message: &str,
+ choice: Choice,
+ open: Option<&OpenDialog>,
+ deadline: Option<std::time::Instant>,
+) -> bool {
#[cfg(target_os = "macos")]
- return macos::ask(app, title, message, choice);
- #[cfg(not(target_os = "macos"))]
{
+ let _ = (open, deadline);
+ return macos::ask(app, title, message, choice);
+ }
+ #[cfg(windows)]
+ {
+ let _ = app;
+ windows::ask(title, message, choice, open, deadline)
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
+ {
+ let _ = (open, deadline);
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
let result = app
.dialog()
@@ -112,12 +173,121 @@ mod macos {
}
}
+#[cfg(windows)]
+mod windows {
+ use super::{refuse_due, Choice, OpenDialog, TASK_ALLOW_ID, TASK_REFUSE_ID};
+ use std::sync::atomic::Ordering;
+ use std::mem::{size_of, zeroed};
+ use std::ptr::null_mut;
+ use windows_sys::core::HRESULT;
+ use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
+ use windows_sys::Win32::UI::Controls::{
+ TaskDialogIndirect, TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TDF_ALLOW_DIALOG_CANCELLATION,
+ TDF_CALLBACK_TIMER, TDF_SIZE_TO_CONTENT, TDM_CLICK_BUTTON, TDN_CREATED, TDN_TIMER,
+ TD_WARNING_ICON,
+ };
+ use windows_sys::Win32::UI::WindowsAndMessaging::{
+ PostMessageW, SetForegroundWindow, SetWindowDisplayAffinity, SetWindowPos, HWND_TOPMOST, SWP_NOMOVE, SWP_NOSIZE, WDA_EXCLUDEFROMCAPTURE,
+ };
+
+ fn wide(text: &str) -> Vec<u16> {
+ text.encode_utf16().chain(Some(0)).collect()
+ }
+
+ /// What the callback is given: where a refusal is asked for, and when to refuse by itself.
+ struct Watch<'a> {
+ open: Option<&'a OpenDialog>,
+ deadline: Option<std::time::Instant>,
+ }
+
+ /// Called only from the dialog's own callback, where `hwnd` is its live window.
+ fn press_refuse(hwnd: HWND) {
+ // SAFETY: a plain message to the dialog's live window.
+ if unsafe { PostMessageW(hwnd, TDM_CLICK_BUTTON as u32, TASK_REFUSE_ID as WPARAM, 0) } == 0 {
+ eprintln!("gentle-dot: a dialog could not be refused: {}", std::io::Error::last_os_error());
+ }
+ }
+
+ /// Asks for the dialog to be raised above the app being controlled, which holds the
+ /// foreground, and presses its refusing button when a refusal was asked for or its deadline
+ /// passed (the timer ticks about every 200 ms). Everything here runs on the dialog's thread,
+ /// during a notification, while its window is alive.
+ unsafe extern "system" fn on_event(hwnd: HWND, notification: u32, _: WPARAM, _: LPARAM, data: isize) -> HRESULT {
+ // SAFETY: `data` is the `Watch` borrowed by `ask`, alive for the whole dialog.
+ let watch = unsafe { &*(data as *const Watch) };
+ if notification == TDN_TIMER as u32 {
+ let requested = watch.open.is_some_and(|open| open.0.load(Ordering::SeqCst));
+ if refuse_due(requested, watch.deadline, std::time::Instant::now()) {
+ press_refuse(hwnd);
+ }
+ }
+ if notification == TDN_CREATED as u32 {
+ // SAFETY: `hwnd` is the dialog's live window during the notification.
+ unsafe {
+ SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ SetForegroundWindow(hwnd);
+ // Like Gentle Dot's other windows, kept out of computer-control screenshots.
+ if SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) == 0 {
+ eprintln!("gentle-dot: a dialog may show in computer-control screenshots");
+ }
+ }
+ }
+ 0
+ }
+
+ pub fn ask(
+ title: &str,
+ message: &str,
+ choice: Choice,
+ open: Option<&OpenDialog>,
+ deadline: Option<std::time::Instant>,
+ ) -> bool {
+ // A refusal asked for an earlier dialog is not this one's. One asked for while this dialog
+ // was still opening is only lost when the approval already timed out, and then its
+ // deadline has passed, so the first tick refuses.
+ if let Some(open) = open {
+ open.0.store(false, Ordering::SeqCst);
+ }
+ let watch = Watch { open, deadline };
+ let (title, message) = (wide(title), wide(message));
+ let (allow, refuse) = (wide(choice.allow), wide(choice.refuse));
+ let buttons = [
+ TASKDIALOG_BUTTON { nButtonID: TASK_ALLOW_ID, pszButtonText: allow.as_ptr() },
+ TASKDIALOG_BUTTON { nButtonID: TASK_REFUSE_ID, pszButtonText: refuse.as_ptr() },
+ ];
+ // SAFETY: every pointer in the config outlives the modal call that reads it.
+ unsafe {
+ let mut config: TASKDIALOGCONFIG = zeroed();
+ config.cbSize = size_of::<TASKDIALOGCONFIG>() as u32;
+ config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_SIZE_TO_CONTENT;
+ if deadline.is_some() || open.is_some() {
+ config.dwFlags |= TDF_CALLBACK_TIMER;
+ }
+ config.pszWindowTitle = title.as_ptr();
+ config.pszContent = message.as_ptr();
+ config.Anonymous1.pszMainIcon = TD_WARNING_ICON;
+ config.cButtons = buttons.len() as u32;
+ config.pButtons = buttons.as_ptr();
+ config.nDefaultButton = TASK_REFUSE_ID;
+ config.pfCallback = Some(on_event);
+ config.lpCallbackData = &watch as *const Watch as isize;
+ let mut pressed = 0i32;
+ let shown = TaskDialogIndirect(&config, &mut pressed, null_mut(), null_mut());
+ choice.allows_task_button((shown >= 0).then_some(pressed))
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
const CHOICE: Choice = Choice { allow: "Allow", refuse: "Cancel" };
+ // A task dialog needs the common controls v6 that the app's manifest declares; the test
+ // executable has none (it would not even start), so refusing a dialog on screen is checked
+ // in the app itself.
+
#[test]
fn only_the_allowing_buttons_response_allows_an_alert() {
assert!(CHOICE.allows_response(Some(ALLOW_RESPONSE)));
@@ -131,6 +301,31 @@ mod tests {
assert!(!same.allows_response(Some(ALLOW_RESPONSE)));
}
+ #[test]
+ fn a_dialogs_timer_refuses_when_asked_or_once_its_deadline_passes() {
+ let now = std::time::Instant::now();
+ let second = std::time::Duration::from_secs(1);
+ assert!(!refuse_due(false, None, now));
+ assert!(!refuse_due(false, Some(now + second), now));
+ assert!(refuse_due(false, Some(now), now));
+ assert!(refuse_due(false, Some(now - second), now));
+ assert!(refuse_due(true, None, now));
+ assert!(refuse_due(true, Some(now + second), now));
+ }
+
+ #[test]
+ fn on_windows_only_the_allowing_task_buttons_id_allows() {
+ assert!(CHOICE.allows_task_button(Some(TASK_ALLOW_ID)));
+ // The refusing (default) button, Escape or closing (IDCANCEL), OK and the other common
+ // buttons nobody can press, an unknown id, and a dialog that failed to show all refuse.
+ for button in [Some(TASK_REFUSE_ID), Some(2), Some(1), Some(6), Some(7), Some(0), Some(-1), Some(2002), None] {
+ assert!(!CHOICE.allows_task_button(button), "{button:?}");
+ }
+ let same = Choice { allow: "OK", refuse: "OK" };
+ assert!(!same.allows_task_button(Some(TASK_ALLOW_ID)));
+ assert_ne!(TASK_ALLOW_ID, TASK_REFUSE_ID);
+ }
+
#[test]
fn the_refusing_button_is_added_first_so_it_is_the_default() {
assert_eq!(CHOICE.alert_buttons(), ["Cancel", "Allow"]);
diff --git a/apps/desktop/src-tauri/src/approvals/mod.rs b/apps/desktop/src-tauri/src/approvals/mod.rs
index 329b8fa..adef67e 100644
--- a/apps/desktop/src-tauri/src/approvals/mod.rs
+++ b/apps/desktop/src-tauri/src/approvals/mod.rs
@@ -71,6 +71,8 @@ pub struct ApprovalDialog {
pub title: String,
/// The sentence, every field with its (possibly cut) value, and the timeout note.
pub message: String,
+ /// When the approval is declined: a dialog still up then refuses itself (Windows).
+ pub deadline: Option<Instant>,
}
impl ApprovalDialog {
@@ -103,6 +105,7 @@ impl ApprovalDialog {
If you do not answer within {}, it is declined.",
spell(timeout)
),
+ deadline: None,
}
}
}
@@ -197,7 +200,7 @@ impl Approvals {
/// Asks the user. Blocks until the answer or the timeout, so call it off the main thread.
pub fn confirm(&self, request: &ApprovalRequest) -> Decision {
let deadline = Instant::now() + self.timeout;
- let dialog = ApprovalDialog::new(request, self.timeout);
+ let dialog = ApprovalDialog { deadline: Some(deadline), ..ApprovalDialog::new(request, self.timeout) };
let Some(ticket) = self.gate.acquire(deadline) else {
return Decision::Declined;
};
diff --git a/apps/desktop/src-tauri/src/approvals/native.rs b/apps/desktop/src-tauri/src/approvals/native.rs
index b12e5a2..0bd291f 100644
--- a/apps/desktop/src-tauri/src/approvals/native.rs
+++ b/apps/desktop/src-tauri/src/approvals/native.rs
@@ -2,30 +2,36 @@
//! does, S24.3), "Decline" as the default button.
use super::{ApprovalDialog, Prompt, APPROVAL_CHOICE};
+use crate::alert::OpenDialog;
use tauri::AppHandle;
pub struct NativePrompt {
app: AppHandle,
+ /// The approval dialog on screen (Windows), so a timed-out one can be refused.
+ open: OpenDialog,
}
impl NativePrompt {
pub fn new(app: AppHandle) -> Self {
- NativePrompt { app }
+ NativePrompt { app, open: OpenDialog::default() }
}
}
impl Prompt for NativePrompt {
fn ask(&self, dialog: &ApprovalDialog) -> bool {
- crate::alert::ask(&self.app, &dialog.title, &dialog.message, APPROVAL_CHOICE)
+ crate::alert::ask_tracked(&self.app, &dialog.title, &dialog.message, APPROVAL_CHOICE, Some(&self.open), dialog.deadline)
}
/// macOS: aborts the modal alert on screen. `-[NSApplication abortModal]` is the one modal
/// call meant for other threads; the aborted alert answers `NSModalResponseAbort`, which
/// `alert` reads as Decline. The approvals gate
/// guarantees no other approval dialog is up, but a computer-control dialog stacked on top
- /// would be aborted instead, which also refuses (fail closed). Elsewhere the stale dialog
- /// stays until the user answers, and that answer is ignored.
+ /// would be aborted instead, which also refuses (fail closed). Windows: presses the approval
+ /// dialog's own refusing button; a dialog not yet up then refuses itself at its deadline
+ /// (`ApprovalDialog::deadline`). Elsewhere the stale dialog stays until the user answers, and
+ /// that answer is ignored.
fn dismiss(&self) {
+ self.open.refuse();
#[cfg(target_os = "macos")]
{
use objc2::runtime::AnyObject;
diff --git a/apps/desktop/src-tauri/src/approvals/tests.rs b/apps/desktop/src-tauri/src/approvals/tests.rs
index 26ceb25..9aca16b 100644
--- a/apps/desktop/src-tauri/src/approvals/tests.rs
+++ b/apps/desktop/src-tauri/src/approvals/tests.rs
@@ -105,6 +105,18 @@ fn the_approval_buttons_default_to_decline() {
assert_eq!(APPROVAL_CHOICE.alert_buttons()[0], "Decline");
}
+#[test]
+fn the_dialog_carries_the_approvals_deadline_so_a_late_one_refuses_itself() {
+ let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::ZERO, true)]));
+ let before = Instant::now();
+ approvals(&prompt, LONG).confirm(&request(vec![]));
+ let after = Instant::now();
+ let deadline = prompt.shown.lock().unwrap()[0].deadline.expect("a deadline");
+ assert!(deadline >= before + LONG && deadline <= after + LONG, "the confirmation's own deadline");
+ // A dialog built for a preview carries none.
+ assert_eq!(ApprovalDialog::new(&request(vec![]), LONG).deadline, None);
+}
+
#[test]
fn allow_approves_and_decline_declines() {
let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::ZERO, true), Answer::After(Duration::ZERO, false)]));