Skip to content

Commit 91c3809

Browse files
fix(desktop): complete reliable native notifications
Signed-off-by: Bernhard Kaindl <[email protected]>
1 parent 0f89114 commit 91c3809

13 files changed

Lines changed: 587 additions & 22 deletions

‎AGENTS.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,14 @@ lane subprocesses resolve the pinned flutter/dart/lefthook even when an
142142
unactivated shell has Homebrew first. Activating Hermit remains recommended for
143143
non-hook commands.
144144

145+
**Windows tool resolution:** the committed files under `bin\` (for example
146+
`bin\cargo`, `bin\rustc`, `bin\pnpm`, and `bin\node`) are Hermit package
147+
entries, not native Windows executables. Do not invoke those paths directly,
148+
and do not assume a bare command is valid when `Get-Command` resolves it into
149+
the repository's `bin\` directory. For Windows validation, run the actual
150+
installed `.exe`/`.cmd` tools, or use their full paths, and verify the resolved
151+
`Source` is not under this repository before running a build or test.
152+
145153
**Commit with `git commit -s`.** The required **DCO Check** fails any PR with a commit missing a `Signed-off-by` trailer, and `just hooks` installs a `commit-msg` hook that adds it to commits you create locally (`git rebase` and `git cherry-pick` still need `--signoff`) — if you build commit commands programmatically, include `-s` every time. To repair a branch that already has unsigned commits: `git rebase --signoff main`, then force-push.
146154

147155
Additional rules:

‎desktop/src-tauri/Cargo.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,13 @@ user-idle = { version = "0.6", default-features = false }
6363
plist = "1"
6464

6565
[target.'cfg(windows)'.dependencies]
66-
windows-sys = { version = "0.61", features = ["Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_Threading", "Win32_Foundation"] }
66+
windows-sys = { version = "0.61", features = ["Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_Threading", "Win32_Foundation", "Win32_UI_Shell"] }
6767
keyring = { version = "3.6.3", default-features = false, features = ["windows-native", "vendored"], optional = true }
6868
user-idle = { version = "0.6", default-features = false }
6969
# Native Windows toast notifications so the app registers with Windows Settings
7070
# > System > Notifications and click actions work through WinRT.
7171
tauri-winrt-notification = "0.7"
72-
windows = { version = "0.61", features = ["UI_Notifications"] }
72+
windows = { version = "0.61", features = ["UI_Notifications", "Win32_Foundation", "Win32_Storage_EnhancedStorage", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem"] }
7373

7474
[dependencies]
7575
atomic-write-file = "0.3"

‎desktop/src-tauri/src/commands/notifications.rs‎

Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@ pub async fn show_native_notification(
5151
}
5252
}
5353

54+
#[cfg(target_os = "windows")]
55+
pub(crate) fn ensure_startup_registration(app: &tauri::AppHandle) {
56+
windows::ensure_startup_registration(app);
57+
}
58+
59+
#[cfg(not(target_os = "windows"))]
60+
pub(crate) fn ensure_startup_registration(_app: &tauri::AppHandle) {}
61+
5462
#[cfg(target_os = "windows")]
5563
#[tauri::command]
5664
pub async fn windows_notification_permission_state(
@@ -59,6 +67,12 @@ pub async fn windows_notification_permission_state(
5967
windows::permission_state(app).await.map(str::to_string)
6068
}
6169

70+
#[cfg(target_os = "windows")]
71+
#[tauri::command]
72+
pub fn take_pending_windows_activations() -> Result<Vec<serde_json::Value>, String> {
73+
windows::take_pending_windows_activations()
74+
}
75+
6276
#[cfg(target_os = "linux")]
6377
mod linux {
6478
use super::NATIVE_NOTIFICATION_ACTIVATED_EVENT;
@@ -131,13 +145,305 @@ mod linux {
131145
#[cfg(target_os = "windows")]
132146
mod windows {
133147
use super::NATIVE_NOTIFICATION_ACTIVATED_EVENT;
148+
use std::collections::VecDeque;
149+
use std::sync::{Mutex, Once, OnceLock};
134150
use tauri::Emitter;
135151
use tauri_winrt_notification::{Duration, Toast};
136152
use windows::{
137153
core::HSTRING,
138154
UI::Notifications::{NotificationSetting, ToastNotificationManager},
139155
};
140156

157+
const MAX_PENDING_ACTIVATIONS: usize = 64;
158+
static STARTUP_REGISTRATION: Once = Once::new();
159+
static PENDING_ACTIVATIONS: OnceLock<Mutex<VecDeque<serde_json::Value>>> = OnceLock::new();
160+
161+
pub fn ensure_startup_registration(app: &tauri::AppHandle) {
162+
STARTUP_REGISTRATION.call_once(|| {
163+
let app = app.clone();
164+
let (ready_sender, ready_receiver) = std::sync::mpsc::sync_channel(1);
165+
std::thread::spawn(move || {
166+
let app_id = app.config().identifier.clone();
167+
set_process_aumid(&app_id);
168+
if let Err(error) = write_aumid_registry_entry(&app, &app_id) {
169+
eprintln!("buzz-desktop: failed to register Windows AUMID: {error}");
170+
}
171+
if let Err(error) = write_notification_settings_entry(&app_id) {
172+
eprintln!(
173+
"buzz-desktop: failed to register Windows notification settings: {error}"
174+
);
175+
}
176+
if let Err(error) = ensure_start_menu_shortcut(&app, &app_id) {
177+
eprintln!("buzz-desktop: failed to repair Windows shortcut AUMID: {error}");
178+
}
179+
let _ = ready_sender.send(());
180+
});
181+
let _ = ready_receiver.recv();
182+
});
183+
}
184+
185+
fn to_wide(value: &str) -> Vec<u16> {
186+
value.encode_utf16().chain(std::iter::once(0)).collect()
187+
}
188+
189+
fn set_process_aumid(app_id: &str) {
190+
use windows_sys::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID;
191+
192+
let app_id = to_wide(app_id);
193+
let result = unsafe { SetCurrentProcessExplicitAppUserModelID(app_id.as_ptr()) };
194+
if result < 0 {
195+
eprintln!("buzz-desktop: failed to set Windows process AUMID: 0x{result:08X}");
196+
}
197+
}
198+
199+
fn write_notification_settings_entry(app_id: &str) -> Result<(), String> {
200+
use windows_sys::Win32::System::Registry::{
201+
RegCloseKey, RegCreateKeyExW, RegOpenKeyExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,
202+
KEY_READ, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE,
203+
};
204+
205+
let subkey = to_wide(&format!(
206+
"Software\\Microsoft\\Windows\\CurrentVersion\\Notifications\\Settings\\{app_id}"
207+
));
208+
unsafe {
209+
let mut existing: HKEY = std::ptr::null_mut();
210+
if RegOpenKeyExW(
211+
HKEY_CURRENT_USER,
212+
subkey.as_ptr(),
213+
0,
214+
KEY_READ,
215+
&mut existing,
216+
) == 0
217+
{
218+
RegCloseKey(existing);
219+
return Ok(());
220+
}
221+
222+
let mut key: HKEY = std::ptr::null_mut();
223+
let status = RegCreateKeyExW(
224+
HKEY_CURRENT_USER,
225+
subkey.as_ptr(),
226+
0,
227+
std::ptr::null(),
228+
REG_OPTION_NON_VOLATILE,
229+
KEY_WRITE,
230+
std::ptr::null(),
231+
&mut key,
232+
std::ptr::null_mut(),
233+
);
234+
if status != 0 {
235+
return Err(format!("RegCreateKeyExW failed with status {status}"));
236+
}
237+
238+
let show_name = to_wide("ShowInActionCenter");
239+
let enabled_name = to_wide("Enabled");
240+
let value: u32 = 1;
241+
let show_status = RegSetValueExW(
242+
key,
243+
show_name.as_ptr(),
244+
0,
245+
REG_DWORD,
246+
(&value as *const u32).cast(),
247+
std::mem::size_of::<u32>() as u32,
248+
);
249+
let enabled_status = RegSetValueExW(
250+
key,
251+
enabled_name.as_ptr(),
252+
0,
253+
REG_DWORD,
254+
(&value as *const u32).cast(),
255+
std::mem::size_of::<u32>() as u32,
256+
);
257+
RegCloseKey(key);
258+
if show_status != 0 {
259+
return Err(format!(
260+
"RegSetValueExW(ShowInActionCenter) failed: {show_status}"
261+
));
262+
}
263+
if enabled_status != 0 {
264+
return Err(format!("RegSetValueExW(Enabled) failed: {enabled_status}"));
265+
}
266+
}
267+
Ok(())
268+
}
269+
270+
fn write_aumid_registry_entry(app: &tauri::AppHandle, app_id: &str) -> Result<(), String> {
271+
use windows_sys::Win32::System::Registry::{
272+
RegCloseKey, RegCreateKeyExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, KEY_WRITE,
273+
REG_OPTION_NON_VOLATILE, REG_SZ,
274+
};
275+
276+
let display_name = app
277+
.config()
278+
.product_name
279+
.clone()
280+
.unwrap_or_else(|| "Buzz".to_string());
281+
let icon_path = std::env::current_exe()
282+
.map_err(|error| format!("could not resolve current executable: {error}"))?
283+
.to_string_lossy()
284+
.into_owned();
285+
let subkey = to_wide(&format!("Software\\Classes\\AppUserModelId\\{app_id}"));
286+
let display_name_key = to_wide("DisplayName");
287+
let display_name_value = to_wide(&display_name);
288+
let icon_key = to_wide("IconUri");
289+
let icon_value = to_wide(&icon_path);
290+
291+
unsafe {
292+
let mut key: HKEY = std::ptr::null_mut();
293+
let status = RegCreateKeyExW(
294+
HKEY_CURRENT_USER,
295+
subkey.as_ptr(),
296+
0,
297+
std::ptr::null(),
298+
REG_OPTION_NON_VOLATILE,
299+
KEY_WRITE,
300+
std::ptr::null(),
301+
&mut key,
302+
std::ptr::null_mut(),
303+
);
304+
if status != 0 {
305+
return Err(format!("RegCreateKeyExW failed with status {status}"));
306+
}
307+
let display_status = RegSetValueExW(
308+
key,
309+
display_name_key.as_ptr(),
310+
0,
311+
REG_SZ,
312+
display_name_value.as_ptr().cast(),
313+
(display_name_value.len() * 2) as u32,
314+
);
315+
let icon_status = RegSetValueExW(
316+
key,
317+
icon_key.as_ptr(),
318+
0,
319+
REG_SZ,
320+
icon_value.as_ptr().cast(),
321+
(icon_value.len() * 2) as u32,
322+
);
323+
RegCloseKey(key);
324+
if display_status != 0 {
325+
return Err(format!(
326+
"RegSetValueExW(DisplayName) failed: {display_status}"
327+
));
328+
}
329+
if icon_status != 0 {
330+
return Err(format!("RegSetValueExW(IconUri) failed: {icon_status}"));
331+
}
332+
}
333+
Ok(())
334+
}
335+
336+
fn ensure_start_menu_shortcut(app: &tauri::AppHandle, app_id: &str) -> Result<(), String> {
337+
use windows::core::{Interface, PCWSTR};
338+
use windows::Win32::Storage::EnhancedStorage::PKEY_AppUserModel_ID;
339+
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
340+
use windows::Win32::System::Com::{
341+
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, IPersistFile,
342+
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, STGM_READWRITE,
343+
};
344+
use windows::Win32::UI::Shell::{
345+
FOLDERID_Programs, IShellLinkW, PropertiesSystem::IPropertyStore, SHGetKnownFolderPath,
346+
ShellLink, KF_FLAG_CREATE,
347+
};
348+
349+
let product_name = app
350+
.config()
351+
.product_name
352+
.clone()
353+
.unwrap_or_else(|| "Buzz".to_string());
354+
let executable = std::env::current_exe()
355+
.map_err(|error| format!("could not resolve current executable: {error}"))?;
356+
let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
357+
if initialized.is_err() {
358+
return Err(format!("CoInitializeEx failed: {initialized:?}"));
359+
}
360+
361+
let result = (|| -> Result<(), String> {
362+
let programs_path_ptr = unsafe {
363+
SHGetKnownFolderPath(&FOLDERID_Programs, KF_FLAG_CREATE, None)
364+
.map_err(|error| format!("SHGetKnownFolderPath failed: {error}"))?
365+
};
366+
let programs_path_result = unsafe { programs_path_ptr.to_string() };
367+
unsafe {
368+
CoTaskMemFree(Some(programs_path_ptr.0.cast()));
369+
}
370+
let programs_path = programs_path_result
371+
.map_err(|error| format!("invalid Start Menu path: {error}"))?;
372+
373+
let subfolder = format!("{programs_path}\\{product_name}");
374+
let nested_path = format!("{subfolder}\\{product_name}.lnk");
375+
let flat_path = format!("{programs_path}\\{product_name}.lnk");
376+
let shortcut_path = if std::path::Path::new(&nested_path).exists() {
377+
nested_path
378+
} else if std::path::Path::new(&flat_path).exists() {
379+
flat_path
380+
} else {
381+
std::fs::create_dir_all(&subfolder)
382+
.map_err(|error| format!("could not create Start Menu folder: {error}"))?;
383+
nested_path
384+
};
385+
let shortcut_path = to_wide(&shortcut_path);
386+
let executable = to_wide(&executable.to_string_lossy());
387+
let link: IShellLinkW = unsafe {
388+
CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)
389+
.map_err(|error| format!("CoCreateInstance(ShellLink) failed: {error}"))?
390+
};
391+
let persist: IPersistFile = link
392+
.cast()
393+
.map_err(|error| format!("IShellLinkW -> IPersistFile failed: {error}"))?;
394+
if unsafe { persist.Load(PCWSTR(shortcut_path.as_ptr()), STGM_READWRITE) }.is_err() {
395+
unsafe {
396+
link.SetPath(PCWSTR(executable.as_ptr()))
397+
.map_err(|error| format!("IShellLinkW::SetPath failed: {error}"))?;
398+
link.SetIconLocation(PCWSTR(executable.as_ptr()), 0)
399+
.map_err(|error| format!("IShellLinkW::SetIconLocation failed: {error}"))?;
400+
}
401+
}
402+
let properties: IPropertyStore = link
403+
.cast()
404+
.map_err(|error| format!("IShellLinkW -> IPropertyStore failed: {error}"))?;
405+
let value = PROPVARIANT::from(app_id);
406+
unsafe {
407+
properties
408+
.SetValue(&PKEY_AppUserModel_ID, &value)
409+
.map_err(|error| format!("IPropertyStore::SetValue failed: {error}"))?;
410+
properties
411+
.Commit()
412+
.map_err(|error| format!("IPropertyStore::Commit failed: {error}"))?;
413+
persist
414+
.Save(PCWSTR(shortcut_path.as_ptr()), true)
415+
.map_err(|error| format!("IPersistFile::Save failed: {error}"))?;
416+
}
417+
Ok(())
418+
})();
419+
420+
unsafe { CoUninitialize() };
421+
result
422+
}
423+
424+
fn queue_activation(target: Option<serde_json::Value>) {
425+
let Some(target) = target else {
426+
return;
427+
};
428+
let queue = PENDING_ACTIVATIONS.get_or_init(Default::default);
429+
let Ok(mut queue) = queue.lock() else {
430+
eprintln!("buzz-desktop: Windows activation queue is unavailable");
431+
return;
432+
};
433+
if queue.len() == MAX_PENDING_ACTIVATIONS {
434+
queue.pop_front();
435+
}
436+
queue.push_back(target);
437+
}
438+
439+
pub fn take_pending_windows_activations() -> Result<Vec<serde_json::Value>, String> {
440+
let queue = PENDING_ACTIVATIONS.get_or_init(Default::default);
441+
let mut queue = queue
442+
.lock()
443+
.map_err(|_| "Windows activation queue is unavailable".to_string())?;
444+
Ok(queue.drain(..).collect())
445+
}
446+
141447
fn permission_state_label(setting: NotificationSetting) -> &'static str {
142448
if setting == NotificationSetting::Enabled {
143449
"granted"
@@ -193,6 +499,7 @@ mod windows {
193499
// _action is None for the default (body) click and
194500
// Some(arg) for button clicks. We only use the default
195501
// click, matching the Linux behaviour.
502+
queue_activation(target.clone());
196503
let _ = activation_app.emit(NATIVE_NOTIFICATION_ACTIVATED_EVENT, &target);
197504
Ok(())
198505
})
@@ -226,5 +533,17 @@ mod windows {
226533
assert_eq!(permission_state_label(setting), "denied");
227534
}
228535
}
536+
537+
#[test]
538+
fn activation_queue_is_bounded() {
539+
let _ = take_pending_windows_activations();
540+
for index in 0..=MAX_PENDING_ACTIVATIONS {
541+
queue_activation(Some(serde_json::json!({ "index": index })));
542+
}
543+
544+
let activations = take_pending_windows_activations().expect("activation queue");
545+
assert_eq!(activations.len(), MAX_PENDING_ACTIVATIONS);
546+
assert_eq!(activations[0]["index"], 1);
547+
}
229548
}
230549
}

0 commit comments

Comments
 (0)