From 383fd35cf54b3fe5a69fd314b8b6802d27bd34de Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Mon, 2 Nov 2026 14:40:57 +0100 Subject: [PATCH] fix(hub): ask Windows about toasts on a thread of their own (#398) Before each notification, and for GET /hub/notify, the hub asked Windows' notification platform for devstack's setting, synchronously on a tokio worker (`deliver` evaluates `sink.status()` before it logs the notice). A call into that other process that does not return holds the worker, and with it the task in its LIFO slot: the accept loop can be that task, and the hub keeps its port and lock without answering, as in #398, whose last log line was a lane restart whose lane had notified before. The Windows sink now runs every WinRT call (the setting and each toast) on one thread of its own. `status()` answers the setting as asked last (again every minute and after each toast), or, while a call has waited 30 s, that Windows does not answer, told once to the hooks (`notify_failed`). At most 16 toasts wait; more are dropped meanwhile. Refs #398 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + crates/devstack-desktop/src/windows/notify.rs | 279 +++++++++++++++--- docs/dashboard-api.md | 2 +- 3 files changed, 254 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 712a38f7..ce3a519f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,19 @@ and listed with their assets on the the Windows build's symbols as an asset (`devstack-x86_64-pc-windows-msvc-pdb.zip`) to read such a dump. +### Fixed + +- **Asking Windows about notifications can no longer stop the hub** (#398). + Before each notification, and for `GET /hub/notify`, the hub asked + Windows' notification platform whether it takes devstack's toasts. The + call ran on a thread that also serves the dashboard's requests, and a + call that did not return would leave the hub holding its port and lock + without answering: the likeliest cause of the hang in #398. Toasts and that question now run on a thread of their own: + the hub answers with the setting as asked last. A call that has waited + 30 s makes notifications count as unavailable, logged once as + `notify_failed`, and toasts beyond 16 waiting are dropped until Windows + answers again. + ## [0.33.0] - 2026-10-31 A stack has a page of its own, above its lanes: its daemon, who serves the diff --git a/crates/devstack-desktop/src/windows/notify.rs b/crates/devstack-desktop/src/windows/notify.rs index a6de47c7..57b818b9 100644 --- a/crates/devstack-desktop/src/windows/notify.rs +++ b/crates/devstack-desktop/src/windows/notify.rs @@ -5,6 +5,10 @@ //! `devstack://open` link when it is registered, else the hub's address. use crate::notify::{Failure, Hooks, Note, Sink}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, SyncSender, sync_channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use windows::Data::Xml::Dom::XmlDocument; use windows::UI::Notifications::{ NotificationSetting, ToastNotification, ToastNotificationManager, @@ -80,52 +84,163 @@ fn link_registered() -> bool { rc == ERROR_SUCCESS } +/// How long a call into Windows' notification platform may take before the +/// sink says it does not answer. +const STUCK: Duration = Duration::from_secs(30); +/// How often the setting is asked again while nothing shows. +const REFRESH: Duration = Duration::from_secs(60); +/// Toasts waiting to be shown; more are dropped while Windows does not answer. +const QUEUE: usize = 16; + +/// What the sink asks of Windows: on its own thread, never on one of the +/// hub's runtime workers. Each is a call into the notification platform, +/// another process; one that does not return must not keep the hub from +/// answering (#398). +trait Calls: Send + 'static { + fn status(&self) -> Result<(), String>; + fn show(&self, xml: &str, tag: &str) -> Result<(), String>; +} + +struct WinRt; + +impl Calls for WinRt { + fn status(&self) -> Result<(), String> { + setting() + } + + fn show(&self, xml: &str, tag: &str) -> Result<(), String> { + show(xml, tag).map_err(|e| e.to_string()) + } +} + +/// What the toast thread and the hub share. +struct Shared { + /// The setting as the toast thread asked it last. + status: Mutex>, + /// Since when the call under way waits for Windows; `None`: no call. + busy: Mutex>, + /// The call under way was told as stuck. + told: AtomicBool, +} + +impl Shared { + fn call(&self, f: impl FnOnce() -> T) -> T { + *self.busy.lock().unwrap() = Some(Instant::now()); + let out = f(); + *self.busy.lock().unwrap() = None; + self.told.store(false, Ordering::SeqCst); + out + } +} + pub struct Toast { - port: u16, /// How the registration at hub start went (`register`). registered: Result<(), String>, hooks: Hooks, + shared: Arc, + jobs: SyncSender, + stuck: Duration, } impl Toast { pub fn new(port: u16, registered: Result<(), String>, hooks: Hooks) -> Self { + Self::with(port, registered, hooks, WinRt, STUCK) + } + + fn with( + port: u16, + registered: Result<(), String>, + hooks: Hooks, + calls: impl Calls, + stuck: Duration, + ) -> Self { + let shared = Arc::new(Shared { + status: Mutex::new(Ok(())), + busy: Mutex::new(None), + told: AtomicBool::new(false), + }); + let (jobs, queue) = sync_channel::(QUEUE); + let (s, failed) = (shared.clone(), hooks.failed.clone()); + let _ = std::thread::Builder::new() + .name("toasts".into()) + .spawn(move || { + loop { + let got = s.call(|| calls.status()); + *s.status.lock().unwrap() = got; + match queue.recv_timeout(REFRESH) { + Ok(n) => { + let launch = if link_registered() { + n.link.clone() + } else { + format!("http://127.0.0.1:{port}{}", n.route) + }; + let xml = toast_xml(&n, &launch); + if let Err(e) = s.call(|| calls.show(&xml, &n.tag)) { + failed(Failure::NotShown(e)); + } + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return, + } + } + }); Self { - port, registered, hooks, + shared, + jobs, + stuck, } } } +/// Whether Windows takes notifications from devstack: a call into the +/// notification platform, made on the toast thread only. +fn setting() -> Result<(), String> { + let setting = match ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID)) + .and_then(|n| n.Setting()) + { + Ok(s) => s, + // Windows knows a program's setting once it has shown a toast; + // before the first one there is none to ask (measured 2026-10-21). + Err(e) if e.code() == NOT_FOUND => return Ok(()), + Err(e) => { + return Err(format!( + "Windows does not take notifications from devstack: {e}" + )); + } + }; + match setting { + NotificationSetting::Enabled => Ok(()), + NotificationSetting::DisabledForApplication => { + Err("switched off for devstack in Windows' notification settings".into()) + } + NotificationSetting::DisabledForUser => { + Err("notifications are switched off in Windows' settings".into()) + } + NotificationSetting::DisabledByGroupPolicy => { + Err("notifications are switched off by group policy".into()) + } + _ => Err("Windows does not show notifications from devstack".into()), + } +} + impl Sink for Toast { + /// The setting as asked last, without asking Windows now; `Err` while + /// a call has waited longer than it may (told once to the hooks). fn status(&self) -> Result<(), String> { - let setting = - match ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID)) - .and_then(|n| n.Setting()) - { - Ok(s) => s, - // Windows knows a program's setting once it has shown a toast; - // before the first one there is none to ask (measured 2026-10-21). - Err(e) if e.code() == NOT_FOUND => return Ok(()), - Err(e) => { - return Err(format!( - "Windows does not take notifications from devstack: {e}" - )); - } - }; - match setting { - NotificationSetting::Enabled => Ok(()), - NotificationSetting::DisabledForApplication => { - Err("switched off for devstack in Windows' notification settings".into()) - } - NotificationSetting::DisabledForUser => { - Err("notifications are switched off in Windows' settings".into()) - } - NotificationSetting::DisabledByGroupPolicy => { - Err("notifications are switched off by group policy".into()) + let since = *self.shared.busy.lock().unwrap(); + if let Some(t) = since.filter(|t| t.elapsed() >= self.stuck) { + let e = format!( + "Windows' notification platform has not answered for {} s", + t.elapsed().as_secs() + ); + if !self.shared.told.swap(true, Ordering::SeqCst) { + (self.hooks.failed)(Failure::NotShown(e.clone())); } - _ => Err("Windows does not show notifications from devstack".into()), + return Err(e); } + self.shared.status.lock().unwrap().clone() } fn trouble(&self) -> Option { @@ -133,18 +248,9 @@ impl Sink for Toast { } fn show(&self, n: Note) { - let launch = if link_registered() { - n.link.clone() - } else { - format!("http://127.0.0.1:{}{}", self.port, n.route) - }; - let xml = toast_xml(&n, &launch); - let failed = self.hooks.failed.clone(); - tokio::task::spawn_blocking(move || { - if let Err(e) = show(&xml, &n.tag) { - failed(Failure::NotShown(e.to_string())); - } - }); + // Full: Windows has not answered for a while, and what waits + // already is enough. + let _ = self.jobs.try_send(n); } } @@ -199,4 +305,99 @@ mod tests { let doc = XmlDocument::new().unwrap(); doc.LoadXml(&HSTRING::from(xml)).unwrap(); } + + /// Windows as a test has it: a setting, and a `show` that waits until + /// the test lets it go. + struct Hanging { + setting: Result<(), String>, + release: Mutex>, + shown: std::sync::mpsc::Sender, + } + + impl Calls for Hanging { + fn status(&self) -> Result<(), String> { + self.setting.clone() + } + + fn show(&self, _: &str, tag: &str) -> Result<(), String> { + let _ = self.release.lock().unwrap().recv(); + let _ = self.shown.send(tag.to_string()); + Ok(()) + } + } + + fn note(tag: &str) -> Note { + Note { + title: "api: build failed".into(), + context: "shop".into(), + body: String::new(), + route: "/#/".into(), + link: "devstack://open".into(), + tag: tag.into(), + } + } + + fn until(what: impl Fn() -> bool) -> bool { + let t0 = Instant::now(); + while t0.elapsed() < Duration::from_secs(5) { + if what() { + return true; + } + std::thread::sleep(Duration::from_millis(10)); + } + false + } + + #[test] + fn a_toast_windows_does_not_answer_keeps_no_caller_waiting() { + let (release, wait) = std::sync::mpsc::channel(); + let (shown, seen) = std::sync::mpsc::channel(); + let failures = Arc::new(Mutex::new(Vec::new())); + let hooks = Hooks { + open: Arc::new(|_: &str| Ok(())), + failed: { + let f = failures.clone(); + Arc::new(move |e| f.lock().unwrap().push(e)) + }, + }; + let calls = Hanging { + setting: Ok(()), + release: Mutex::new(wait), + shown, + }; + let toast = Toast::with(4250, Ok(()), hooks, calls, Duration::from_millis(500)); + assert!(until(|| toast.status().is_ok())); + // Windows hangs on the first: `show` and `status` still return. + toast.show(note("a")); + toast.show(note("b")); + assert!(toast.status().is_ok(), "not stuck yet"); + assert!(until(|| toast.status().is_err()), "said once stuck"); + let e = toast.status().unwrap_err(); + assert!(e.contains("has not answered"), "{e}"); + assert_eq!(failures.lock().unwrap().len(), 1, "told once"); + // It answers again: what waited shows, and the setting counts. + release.send(()).unwrap(); + release.send(()).unwrap(); + let tags: Vec = (0..2) + .map(|_| seen.recv_timeout(Duration::from_secs(5)).unwrap()) + .collect(); + assert_eq!(tags, ["a", "b"]); + assert!(until(|| toast.status().is_ok())); + } + + #[test] + fn the_setting_is_the_one_asked_last() { + let (_release, wait) = std::sync::mpsc::channel(); + let hooks = Hooks { + open: Arc::new(|_: &str| Ok(())), + failed: Arc::new(|_| {}), + }; + let calls = Hanging { + setting: Err("switched off".into()), + release: Mutex::new(wait), + shown: std::sync::mpsc::channel().0, + }; + let toast = Toast::with(4250, Ok(()), hooks, calls, STUCK); + assert!(until(|| toast.status() == Err("switched off".into()))); + } } diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 6c5a8a4c..b3f5dbf0 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -46,7 +46,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /`, `/assets/*`, `/theme.js`, `/manifest.webmanifest`, `/sw.js`, the icons | none | the app shell (works offline once cached) | | `GET /auth?code=[&next=]` | none | sets the session cookie (one year, survives a hub restart), redirects to `/`, or to `next` when it is a dashboard route (`/#/…`, characters of a path and query only; a notification's, [ADR-0045](adr/0045-the-hub-notifies-the-desktop.md): a lane's views `/#/s//l/[/services/]`, `main` for the main working tree, or a stack's page `/#/s/`, [ADR-0081](adr/0081-a-stack-has-a-page-every-lane-the-same-view.md); the form before 0.33.0, `/#/s/[/services/]?lane=`, still lands on that lane). A browser that sends a valid session already keeps it: no second cookie | | `GET /hub/ping` | none | `{"devstack":true,"version":""}`; CORS for the landing page only (ADR-0021; `OPTIONS /hub/ping` answers its preflight). With `?nonce=<16 to 128 characters>` also `"proof"`: hex of blake3 `keyed_hash(derive_key("devstack hub ping proof v1", token), nonce)`. The CLI asks with a fresh nonce and sends the token only to a hub whose proof matches | -| `GET /hub/notify` | cookie | desktop notifications ([ADR-0045](adr/0045-the-hub-notifies-the-desktop.md)): `{"available": bool, "unavailable": string\|null, "trouble": string\|null, "kinds": [{"kind", "label", "on", "default"}], "muted": [scope]}`; `unavailable` says why nothing shows (no desktop session, switched off in the system's settings, `DEVSTACK_NO_NOTIFY`, "not on macOS yet"); `trouble` what does not work as it should while notifications show: on Windows devstack's name not registered at hub start (they may show without it, or not at all), on Linux the last click that could not open the dashboard (`xdg-open` did not start; gone with a click that does). Older hubs leave `trouble` out. Kinds: `build_failed`, `held`, `service_failed`, `lane_failed` (on by default), `main_ports`, `live` (off). A scope is a stack id or `/` | +| `GET /hub/notify` | cookie | desktop notifications ([ADR-0045](adr/0045-the-hub-notifies-the-desktop.md)): `{"available": bool, "unavailable": string\|null, "trouble": string\|null, "kinds": [{"kind", "label", "on", "default"}], "muted": [scope]}`; `unavailable` says why nothing shows (no desktop session, switched off in the system's settings, `DEVSTACK_NO_NOTIFY`, "not on macOS yet", on Windows a notification platform that has not answered for 30 s; there the setting is the one asked last, at most a minute ago or with the last notification); `trouble` what does not work as it should while notifications show: on Windows devstack's name not registered at hub start (they may show without it, or not at all), on Linux the last click that could not open the dashboard (`xdg-open` did not start; gone with a click that does). Older hubs leave `trouble` out. Kinds: `build_failed`, `held`, `service_failed`, `lane_failed` (on by default), `main_ports`, `live` (off). A scope is a stack id or `/` | | `PUT /hub/notify` | cookie + Origin | `{"kinds"?: {kind: bool}, "muted"?: [scope]}` (`muted` replaces the list): the new settings, as `GET`; `400` for an unknown kind or scope. Kept per machine in the hub's state (`notify.json`) | | `POST /hub/notify/test` | cookie + Origin | one notification whatever the settings say: `204`, or `503` with why nothing shows. A click opens the dashboard | | `GET /hub/session` | cookie | `200 {"version": "", "link_unavailable": string\|null}`, or `401` (not paired: show "run `devstack ui`"). `link_unavailable` says why this platform has no `devstack://` link (macOS: "not on macOS yet", ADR-0054): the page keeps it and offers `devstack hub start` instead of its "Start hub" link while the hub is down. Older hubs leave it out |