An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(windows): the app shows a browser's finished monitor, task or reminder as a toast while the browser is behind, tells the Bridge whether Windows lets it notify, and a click, checked against the nonce it minted for that toast, brings the browser back to the tab
Shahriara0e7391dc361
diff --git a/docs/internals/windows-app.md b/docs/internals/windows-app.mdindex 24b6e44..499323e 100644--- a/docs/internals/windows-app.md+++ b/docs/internals/windows-app.md@@ -119,6 +119,14 @@ that start the app wait for the first pending list, at most eight. When no app iBridge starts it with `--pairing`, which re-subscribes a running copy without showing its window.The NSIS uninstall hook runs `browsentic unregister-host` before `stop`.+## Notices++On a Bridge at protocol 24 or later, each new control socket sends `notices {watch, allowed}`, and sends+it again when `allowed` changes (on the 2 s poll and on focus): whether the AUMID's `ToastNotifier`+reports `Enabled`, so a development build says false and the browser keeps its own card. On `notices-changed`+the app calls `takeNotices` and posts each as a toast (`notices.rs`, tagged by id), even while focused.+Its `browsentic://notice/open` link sends `openNotice` only with the nonce minted for it, used once, and never shows the window.+## Build and test```powershelldiff --git a/src/windows/src-tauri/src/main.rs b/src/windows/src-tauri/src/main.rsindex 8ef0fc3..ce1d244 100644--- a/src/windows/src-tauri/src/main.rs+++ b/src/windows/src-tauri/src/main.rs@@ -2,12 +2,14 @@mod control;mod node;+mod notices;mod pairing;mod path_env;mod paths;mod payload;mod process;mod system;+mod toast;mod tray;mod update;@@ -221,11 +223,33 @@ fn announce_paired(app: AppHandle, held: State<'_, pairing::Pairing>, session: SOk(())}+/// Whether a toast posted now would show, which is what the Bridge is told before it hands this app a notice.+#[tauri::command]+fn notices_allowed(app: AppHandle) -> Result<bool> {+ Ok(toast::enabled(&app.config().identifier))+}++/// Shown even while this window has the focus: the browser they came from is what is out of sight.+#[tauri::command]+fn post_notices(app: AppHandle, held: State<'_, notices::Notices>, queued: Vec<notices::Notice>) -> Result<()> {+ for notice in &queued {+ notices::post(&app.config().identifier, notice, &held.hold(¬ice.id)?);+ }+ Ok(())+}+fn focused(app: &AppHandle) -> bool {app.get_webview_window("main").and_then(|window| window.is_focused().ok()).unwrap_or(false)}+/// A notice's toast brings the browser's tab forward, never this window, and only with its own nonce.fn follow(app: &AppHandle, address: &str) {+ if let Some(link) = notices::parse(address) {+ if let Some(notice) = app.state::<notices::Notices>().judge(&link) {+ let _ = app.emit("notice-link", notice);+ }+ return;+ }match pairing::parse(address).and_then(|link| app.state::<pairing::Pairing>().judge(link)) {Some(act) => perform(app, act),None => tray::show(app),@@ -242,7 +266,7 @@ fn perform(app: &AppHandle, act: pairing::Act) {/// A second copy hands its arguments here: a link was already followed, and a start for pairing only/// makes sure the window is watching, without taking the keyboard from the browser that asked.fn second_launch(app: &AppHandle, args: Vec<String>) {- let scheme = format!("{}:", pairing::SCHEME);+ let scheme = format!("{}:", toast::SCHEME);if args.iter().any(|arg| arg == PAIRING_LAUNCH) {let _ = app.emit("pairing-launch", ());} else if !args.iter().any(|arg| arg.to_ascii_lowercase().starts_with(&scheme)) {@@ -287,6 +311,7 @@ fn main() {.plugin(tauri_plugin_updater::Builder::new().build()).manage(App { paths: paths::Paths::from_env(), control: control::Control::default(), node: Mutex::default() }).manage(pairing::Pairing::default())+ .manage(notices::Notices::default()).setup(|app| {let tray = tray::build(app.handle())?;app.manage(tray);@@ -320,9 +345,11 @@ fn main() {install_update,locate_node,log_tail,+ notices_allowed,npm_install,open_extensions_page,pair_requests,+ post_notices,read_lock,set_command_link,tray_status,diff --git a/src/windows/src-tauri/src/notices.rs b/src/windows/src-tauri/src/notices.rsnew file mode 100644index 0000000..0f6dffc--- /dev/null+++ b/src/windows/src-tauri/src/notices.rs@@ -0,0 +1,176 @@+use serde::Deserialize;+use sha2::{Digest, Sha256};+use std::sync::Mutex;+use url::Url;++use crate::toast::{self, escape, same_secret, SCHEME};++const GROUP: &str = "notice";+/// As many as the Bridge can still route a click for; older toasts only ignore their click.+const MOST_HELD: usize = 50;+/// Windows refuses a longer tag.+const TAG_MAX: usize = 64;++/// A monitor, a scheduled task or a timer that finished while the browser was out of sight, as much of+/// it as a toast shows.+#[derive(Deserialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Notice {+ pub id: String,+ pub title: String,+ #[serde(default)]+ pub body: String,+ #[serde(default)]+ pub tone: Option<String>,+ #[serde(default)]+ pub browser: Option<String>,+}++/// A click on a notice's toast: `browsentic://notice/open?id=…&n=…`.+#[derive(Debug, Clone, PartialEq)]+pub struct Link {+ pub notice: String,+ pub nonce: String,+}++pub fn parse(address: &str) -> Option<Link> {+ let url = Url::parse(address).ok()?;+ if url.scheme() != SCHEME || url.host_str() != Some("notice") || url.path().trim_end_matches('/') != "/open" {+ return None;+ }+ let take = |key: &str| url.query_pairs().find(|(name, _)| name == key).map(|(_, value)| value.into_owned()).filter(|value| !value.is_empty());+ Some(Link { notice: take("id")?, nonce: take("n").unwrap_or_default() })+}++/// The nonce minted for each notice this app posted, newest last.+#[derive(Default)]+pub struct Notices {+ held: Mutex<Vec<(String, String)>>,+}++impl Notices {+ /// A repeat of a notice replaces its toast, and its nonce with it.+ pub fn hold(&self, notice: &str) -> Result<String, String> {+ let nonce = toast::mint()?;+ let mut held = self.held.lock().unwrap();+ held.retain(|(id, _)| id != notice);+ held.push((notice.to_string(), nonce.clone()));+ let excess = held.len().saturating_sub(MOST_HELD);+ held.drain(..excess);+ Ok(nonce)+ }++ /// The notice whose tab to bring to the front, only for the nonce this app minted for it, and once.+ pub fn judge(&self, link: &Link) -> Option<String> {+ let mut held = self.held.lock().unwrap();+ let at = held.iter().position(|(id, nonce)| id == &link.notice && same_secret(Some(nonce), &link.nonce))?;+ Some(held.remove(at).0)+ }+}++pub fn tag_of(id: &str) -> String {+ if id.len() <= TAG_MAX {+ return id.to_string();+ }+ Sha256::digest(id.as_bytes()).iter().map(|byte| format!("{byte:02x}")).collect()+}++pub fn toast_xml(notice: &Notice, nonce: &str) -> String {+ let launch = toast::link("notice", "open", &[("id", ¬ice.id), ("n", nonce)]);+ let duration = if notice.tone.as_deref() == Some("warn") { "long" } else { "short" };+ let attribution = notice.browser.as_deref().filter(|browser| !browser.is_empty()).map(|browser| format!(r#"<text placement="attribution">{}</text>"#, escape(browser))).unwrap_or_default();+ format!(+ r#"<toast launch="{}" activationType="protocol" duration="{duration}"><visual><binding template="ToastGeneric"><text>{}</text><text>{}</text>{attribution}</binding></visual></toast>"#,+ escape(&launch),+ escape(¬ice.title),+ escape(¬ice.body),+ )+}++pub fn post(app_id: &str, notice: &Notice, nonce: &str) {+ toast::post(app_id, &toast_xml(notice, nonce), Some((GROUP, &tag_of(¬ice.id))));+}++#[cfg(test)]+mod tests {+ use super::*;++ fn notice(id: &str) -> Notice {+ Notice { id: id.into(), title: "Price dropped".into(), body: "The jacket is £84 now.".into(), tone: None, browser: Some("Google Chrome".into()) }+ }++ #[test]+ fn reads_a_notice_link_and_nothing_else() {+ assert_eq!(parse("browsentic://notice/open?id=monitor%3A42&n=abc"), Some(Link { notice: "monitor:42".into(), nonce: "abc".into() }));+ assert_eq!(parse("browsentic://notice/open/?id=t1"), Some(Link { notice: "t1".into(), nonce: String::new() }));+ assert_eq!(parse("browsentic://notice/open?n=abc"), None);+ assert_eq!(parse("browsentic://notice/close?id=t1&n=abc"), None);+ assert_eq!(parse("browsentic://pair/open?id=t1&n=abc"), None);+ assert_eq!(parse("https://notice/open?id=t1&n=abc"), None);+ }++ #[test]+ fn a_click_reaches_the_bridge_only_with_the_nonce_minted_for_that_notice_and_only_once() {+ let notices = Notices::default();+ let first = notices.hold("n1").unwrap();+ let second = notices.hold("n2").unwrap();+ let link = |notice: &str, nonce: &str| Link { notice: notice.into(), nonce: nonce.into() };++ assert_eq!(notices.judge(&link("n1", &second)), None);+ assert_eq!(notices.judge(&link("n1", "")), None);+ assert_eq!(notices.judge(&link("n3", &first)), None);+ assert_eq!(notices.judge(&link("n1", &first)), Some("n1".into()));+ assert_eq!(notices.judge(&link("n1", &first)), None);+ assert_eq!(notices.judge(&link("n2", &second)), Some("n2".into()));+ }++ #[test]+ fn a_repeat_replaces_the_nonce_and_only_the_newest_are_kept() {+ let notices = Notices::default();+ let stale = notices.hold("n1").unwrap();+ let fresh = notices.hold("n1").unwrap();+ assert_eq!(notices.judge(&Link { notice: "n1".into(), nonce: stale }), None);+ assert_eq!(notices.judge(&Link { notice: "n1".into(), nonce: fresh }), Some("n1".into()));++ let oldest = notices.hold("first").unwrap();+ for index in 0..MOST_HELD {+ notices.hold(&format!("later-{index}")).unwrap();+ }+ assert_eq!(notices.judge(&Link { notice: "first".into(), nonce: oldest }), None);+ }++ #[test]+ fn a_long_id_gets_a_tag_windows_accepts_and_the_same_one_each_time() {+ assert_eq!(tag_of("monitor:42"), "monitor:42");+ let long = "x".repeat(120);+ assert_eq!(tag_of(&long).len(), TAG_MAX);+ assert_eq!(tag_of(&long), tag_of(&long));+ assert_ne!(tag_of(&long), tag_of(&"y".repeat(120)));+ }++ #[test]+ fn the_toast_escapes_what_the_page_wrote_and_names_the_browser() {+ let xml = toast_xml(&Notice { title: "<b>Sold out</b> & gone".into(), body: "\"Size M\" isn't left".into(), ..notice("monitor:7") }, "n0nce");+ assert!(xml.contains(r#"launch="browsentic://notice/open?id=monitor%3A7&n=n0nce""#));+ assert!(xml.contains("<text><b>Sold out</b> & gone</text>"));+ assert!(xml.contains("<text>"Size M" isn't left</text>"));+ assert!(xml.contains(r#"<text placement="attribution">Google Chrome</text>"#));+ assert!(xml.contains(r#"duration="short""#));+ assert!(!xml.contains("<actions>"));++ let warning = toast_xml(&Notice { tone: Some("warn".into()), browser: None, ..notice("t1") }, "n");+ assert!(warning.contains(r#"duration="long""#));+ assert!(!warning.contains("attribution"));+ }++ #[test]+ fn decodes_a_queued_notice_and_ignores_what_a_toast_does_not_show() {+ let decoded: Vec<Notice> = serde_json::from_value(serde_json::json!([+ { "id": "t1", "kind": "timer", "title": "Timer done", "body": "Tea", "tone": "live", "at": 1, "browser": "Brave" },+ { "id": "m1", "title": "Changed" }+ ]))+ .unwrap();+ assert_eq!(decoded[0], Notice { id: "t1".into(), title: "Timer done".into(), body: "Tea".into(), tone: Some("live".into()), browser: Some("Brave".into()) });+ assert_eq!(decoded[1], Notice { id: "m1".into(), title: "Changed".into(), body: String::new(), tone: None, browser: None });+ }+}diff --git a/src/windows/src-tauri/src/pairing.rs b/src/windows/src-tauri/src/pairing.rsindex 8eb16f7..dbb6ff7 100644--- a/src/windows/src-tauri/src/pairing.rs+++ b/src/windows/src-tauri/src/pairing.rs@@ -3,8 +3,9 @@ use std::collections::{HashMap, VecDeque};use std::sync::Mutex;use url::Url;-/// Registered by the installer, so a toast's buttons reach this app whether it is running or not.-pub const SCHEME: &str = "browsentic";+use crate::toast::{self, escape, same_secret, SCHEME};++const GROUP: &str = "pair";/// What a `browsentic://pair/…` link asks for. Any web page can open one, so none of this is trusted/// until [`Held::act`] has matched its nonce.@@ -82,12 +83,6 @@ impl Held {}}-fn same_secret(held: Option<&String>, offered: &str) -> bool {- held.is_some_and(|held| {- !held.is_empty() && held.len() == offered.len() && held.bytes().zip(offered.bytes()).fold(0, |differs, (a, b)| differs | (a ^ b)) == 0- })-}-/// What changed since the last list: toasts to post and to take back, and links that were waiting for it.#[derive(Debug, Default, PartialEq)]pub struct Change {@@ -135,28 +130,14 @@ impl Pairing {}pub fn vouch_for(&self, session: &str) -> Result<String, String> {- let nonce = mint()?;+ let nonce = toast::mint()?;self.held.lock().unwrap().sessions.insert(session.to_string(), nonce.clone());Ok(nonce)}}-fn mint() -> Result<String, String> {- let mut bytes = [0u8; 16];- getrandom::fill(&mut bytes).map_err(|_| "Windows gave no random numbers to secure the notification with.".to_string())?;- Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())-}-fn link(path: &str, query: &[(&str, &str)]) -> String {- let mut address = Url::parse(&format!("{SCHEME}://pair/{path}")).expect("a pair link is a valid address");- if !query.is_empty() {- address.query_pairs_mut().extend_pairs(query);- }- address.into()-}--fn escape(text: &str) -> String {- text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")+ toast::link("pair", path, query)}fn toast(launch: &str, title: &str, body: &str, buttons: &[(&str, String)]) -> String {@@ -193,48 +174,15 @@ pub fn paired_toast(session: &str, name: &str, nonce: &str) -> String {)}-#[cfg(windows)]-mod toasts {- use windows::core::HSTRING;- use windows::Data::Xml::Dom::XmlDocument;- use windows::UI::Notifications::{ToastNotification, ToastNotificationManager};-- const GROUP: &str = "pair";-- pub fn post(app_id: &str, xml: &str, tag: Option<&str>) -> windows::core::Result<()> {- let content = XmlDocument::new()?;- content.LoadXml(&HSTRING::from(xml))?;- let toast = ToastNotification::CreateToastNotification(&content)?;- if let Some(tag) = tag {- toast.SetTag(&HSTRING::from(tag))?;- toast.SetGroup(&HSTRING::from(GROUP))?;- }- ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app_id))?.Show(&toast)- }-- pub fn withdraw(app_id: &str, tag: &str) -> windows::core::Result<()> {- ToastNotificationManager::History()?.RemoveGroupedTagWithId(&HSTRING::from(tag), &HSTRING::from(GROUP), &HSTRING::from(app_id))- }+/// A request's toast is tagged with its id, so the one for a decided request can be taken back.+pub fn post(app_id: &str, xml: &str, request: Option<&str>) {+ toast::post(app_id, xml, request.map(|request| (GROUP, request)));}-/// Toasts go to the identity the installer stamps on the Start menu shortcut; without that shortcut, as-/// in a development build, Windows drops them and the tray item and the window carry the request alone.-#[cfg(windows)]-pub fn post(app_id: &str, xml: &str, tag: Option<&str>) {- let _ = toasts::post(app_id, xml, tag);+pub fn withdraw(app_id: &str, request: &str) {+ toast::withdraw(app_id, GROUP, request);}-#[cfg(windows)]-pub fn withdraw(app_id: &str, tag: &str) {- let _ = toasts::withdraw(app_id, tag);-}--#[cfg(not(windows))]-pub fn post(_: &str, _: &str, _: Option<&str>) {}--#[cfg(not(windows))]-pub fn withdraw(_: &str, _: &str) {}-#[cfg(test)]mod tests {use super::*;diff --git a/src/windows/src-tauri/src/toast.rs b/src/windows/src-tauri/src/toast.rsnew file mode 100644index 0000000..690c8ce--- /dev/null+++ b/src/windows/src-tauri/src/toast.rs@@ -0,0 +1,127 @@+use url::Url;++/// Registered by the installer, so a toast's buttons reach this app whether it is running or not.+pub const SCHEME: &str = "browsentic";++/// `browsentic://<host>/<path>?…`. Any web page can open one, so whatever acts on it checks a nonce first.+pub fn link(host: &str, path: &str, query: &[(&str, &str)]) -> String {+ let mut address = Url::parse(&format!("{SCHEME}://{host}/{path}")).expect("a toast link is a valid address");+ if !query.is_empty() {+ address.query_pairs_mut().extend_pairs(query);+ }+ address.into()+}++/// 128 random bits, as hex.+pub fn mint() -> Result<String, String> {+ let mut bytes = [0u8; 16];+ getrandom::fill(&mut bytes).map_err(|_| "Windows gave no random numbers to secure the notification with.".to_string())?;+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())+}++pub fn same_secret(held: Option<&String>, offered: &str) -> bool {+ held.is_some_and(|held| {+ !held.is_empty() && held.len() == offered.len() && held.bytes().zip(offered.bytes()).fold(0, |differs, (a, b)| differs | (a ^ b)) == 0+ })+}++/// Text for toast XML, which also refuses the control characters XML 1.0 has no place for.+pub fn escape(text: &str) -> String {+ text.chars()+ .filter(|character| !character.is_control() || matches!(character, '\n' | '\r' | '\t'))+ .collect::<String>()+ .replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+ .replace('\'', "'")+}++#[cfg(windows)]+mod windows_toasts {+ use windows::core::HSTRING;+ use windows::Data::Xml::Dom::XmlDocument;+ use windows::UI::Notifications::{NotificationSetting, ToastNotification, ToastNotificationManager};++ pub fn post(app_id: &str, xml: &str, tag: Option<(&str, &str)>) -> windows::core::Result<()> {+ let content = XmlDocument::new()?;+ content.LoadXml(&HSTRING::from(xml))?;+ let toast = ToastNotification::CreateToastNotification(&content)?;+ if let Some((group, tag)) = tag {+ toast.SetGroup(&HSTRING::from(group))?;+ toast.SetTag(&HSTRING::from(tag))?;+ }+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app_id))?.Show(&toast)+ }++ pub fn withdraw(app_id: &str, group: &str, tag: &str) -> windows::core::Result<()> {+ ToastNotificationManager::History()?.RemoveGroupedTagWithId(&HSTRING::from(tag), &HSTRING::from(group), &HSTRING::from(app_id))+ }++ pub fn enabled(app_id: &str) -> windows::core::Result<bool> {+ Ok(ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app_id))?.Setting()? == NotificationSetting::Enabled)+ }+}++/// Toasts go to the identity the installer stamps on the Start menu shortcut; without that shortcut, as+/// in a development build, Windows drops them, which [`enabled`] reports.+#[cfg(windows)]+pub fn post(app_id: &str, xml: &str, tag: Option<(&str, &str)>) {+ let _ = windows_toasts::post(app_id, xml, tag);+}++#[cfg(windows)]+pub fn withdraw(app_id: &str, group: &str, tag: &str) {+ let _ = windows_toasts::withdraw(app_id, group, tag);+}++/// Whether a toast posted now would show: the app is installed under its identity and the person has not+/// turned its notifications off.+#[cfg(windows)]+pub fn enabled(app_id: &str) -> bool {+ windows_toasts::enabled(app_id).unwrap_or(false)+}++#[cfg(not(windows))]+pub fn post(_: &str, _: &str, _: Option<(&str, &str)>) {}++#[cfg(not(windows))]+pub fn withdraw(_: &str, _: &str, _: &str) {}++#[cfg(not(windows))]+pub fn enabled(_: &str) -> bool {+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn escapes_markup_and_drops_what_xml_cannot_carry() {+ assert_eq!(escape("Tom & \"Jerry\" <b>'s</b>"), "Tom & "Jerry" <b>'s</b>");+ assert_eq!(escape("price\u{0}dropped\u{1b}[0m\nto £3"), "pricedropped[0m\nto £3");+ }++ #[test]+ fn a_secret_matches_only_itself() {+ let held = "a1b2".to_string();+ assert!(same_secret(Some(&held), "a1b2"));+ assert!(!same_secret(Some(&held), "a1b3"));+ assert!(!same_secret(Some(&held), "a1b"));+ assert!(!same_secret(None, "a1b2"));+ assert!(!same_secret(Some(&String::new()), ""));+ }++ #[test]+ fn links_encode_what_they_carry() {+ assert_eq!(link("notice", "open", &[("id", "a b/c"), ("n", "x+y")]), "browsentic://notice/open?id=a+b%2Fc&n=x%2By");+ assert_eq!(link("pair", "open", &[]), "browsentic://pair/open");+ }++ #[cfg(not(windows))]+ #[test]+ fn a_build_for_another_system_never_claims_toasts_show() {+ assert!(!enabled("com.imshaikot.browsentic"));+ }+}diff --git a/src/windows/ui/backend.ts b/src/windows/ui/backend.tsindex 31a0270..63a60f0 100644--- a/src/windows/ui/backend.ts+++ b/src/windows/ui/backend.ts@@ -1,9 +1,13 @@import type { BridgeStatus, SessionSummary } from '@/daemon/control';import type { AgentDescriptor, AgentState } from '@/lib/agents/catalog';+import type { QueuedNotice } from '@/lib/notices';import type { BlockedBrowser, PairRequestSummary, PairedBy, PairingMode } from '@/lib/pairing';import type { Preferences } from '@/lib/settings/preferences';-export type { BlockedBrowser, BridgeStatus, PairRequestSummary, PairedBy, PairingMode, SessionSummary };+export type { BlockedBrowser, BridgeStatus, PairRequestSummary, PairedBy, PairingMode, QueuedNotice, SessionSummary };++/** As much of a notice as its toast shows. */+export type ShownNotice = Pick<QueuedNotice, 'id' | 'title' | 'body' | 'tone' | 'browser'>;export interface NodeInstall {path: string;@@ -163,6 +167,10 @@ export interface Backend {pairRequests(requests: PairRequestSummary[]): Promise<void>;/** A toast with an Unpair button, for a browser that paired by itself. */announcePaired(session: string, name: string): Promise<void>;+ /** Whether a toast posted now would show: false in a build Windows does not know by its identity, or with its notifications off. */+ noticesAllowed(): Promise<boolean>;+ /** One toast per notice; clicking it hands back the notice's id through `onNoticeLink`. */+ postNotices(notices: ShownNotice[]): Promise<void>;checkUpdate(): Promise<Release | null>;installUpdate(onProgress: (fraction: number) => void): Promise<void>;onControlEvent(listener: (event: string) => void): () => void;@@ -170,6 +178,9 @@ export interface Backend {onPairLink(listener: (act: PairLinkAct) => void): () => void;/** Browsentic Bridge started a second copy because a browser asked to pair and this window was not watching. */onPairingLaunch(listener: () => void): () => void;+ /** Someone clicked a notice's toast, and the Rust side matched the nonce it minted for it. */+ onNoticeLink(listener: (notice: string) => void): () => void;+ onWindowFocus(listener: () => void): () => void;openUrl(url: string): Promise<void>;reveal(path: string): Promise<void>;setWindowTheme(theme: 'light' | 'dark' | null): Promise<void>;@@ -211,6 +222,8 @@ export async function tauriBackend(): Promise<Backend> {trayStatus: (status) => invoke('tray_status', { status }),pairRequests: (requests) => invoke('pair_requests', { requests }),announcePaired: (session, name) => invoke('announce_paired', { session, name }),+ noticesAllowed: () => invoke('notices_allowed'),+ postNotices: (notices) => invoke('post_notices', { queued: notices }),checkUpdate: () => invoke('check_update'),installUpdate: async (onProgress) => {const stop = await listen<{ received: number; total: number | null }>('update-progress', ({ payload }) =>@@ -226,6 +239,8 @@ export async function tauriBackend(): Promise<Backend> {onTray: (listener) => unlisten(listen<string>('tray', (event) => listener(event.payload))),onPairLink: (listener) => unlisten(listen<PairLinkAct>('pair-link', (event) => listener(event.payload))),onPairingLaunch: (listener) => unlisten(listen('pairing-launch', () => listener())),+ onNoticeLink: (listener) => unlisten(listen<string>('notice-link', (event) => listener(event.payload))),+ onWindowFocus: (listener) => unlisten(getCurrentWindow().onFocusChanged(({ payload: focused }) => focused && listener())),openUrl: (url) => opener.openUrl(url),reveal: (path) => opener.revealItemInDir(path),setWindowTheme: (theme) => getCurrentWindow().setTheme(theme),diff --git a/src/windows/ui/mock-backend.ts b/src/windows/ui/mock-backend.tsindex 0a9ffd9..c649e95 100644--- a/src/windows/ui/mock-backend.ts+++ b/src/windows/ui/mock-backend.ts@@ -8,7 +8,7 @@ import type { GuardrailSettings } from '@/lib/settings/guardrails';import type { PreferenceChange } from '@/lib/settings/preferences';import { EMPTY_PROFILE } from '@/lib/settings/profile';import type { Source } from '@/lib/stores';-import type { AgentListing, Backend, BlockedBrowser, CliOutput, InstallStamp, Lockfile, NodeInstall, PairRequestSummary, PairedBy, PairingMode, Preferences } from './backend';+import type { AgentListing, Backend, BlockedBrowser, CliOutput, InstallStamp, Lockfile, NodeInstall, PairRequestSummary, PairedBy, PairingMode, Preferences, QueuedNotice } from './backend';/*** How the stand-in machine pairs, picked by the address's hash: #ask has two browsers waiting to be@@ -19,10 +19,12 @@ export type Scenario = 'ask' | 'kept' | 'arrives' | 'code' | 'auto';const SCENARIOS: Scenario[] = ['ask', 'kept', 'arrives', 'code', 'auto'];const scenarioOf = (hash: string): Scenario => SCENARIOS.find((scenario) => `#${scenario}` === hash) ?? 'auto';-/** The stand-in, with the hands a test needs: a browser asking, and one pairing by itself. */+/** The stand-in, with the hands a test needs: a browser asking, one pairing by itself, a notice arriving, and Windows turning toasts on or off. */export interface MockBackend extends Backend {ask(request: PairRequestSummary): void;arrive(): void;+ notify(notice: QueuedNotice): void;+ allowNotices(allowed: boolean): void;}/**@@ -51,6 +53,8 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshlet blocked: BlockedBrowser[] = scenario === 'kept' ? [...KEPT_OUT] : [];let sessions: PairedSession[] = SESSIONS.map(({ pairedAgo, ...session }) => ({ ...session, pairedAt: ago(pairedAgo) }));let sessionReads = 0;+ let noticesAllowed = true;+ let notices: QueuedNotice[] = [];const announce = (event: string) => listeners.forEach((listener) => listener(event));const arrive = () => void sessions.push({ ...ARRIVING, pairedAt: ago(0) });@@ -72,7 +76,7 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshstatus: {connected: true,daemonVersion: version,- protocolVersion: 22,+ protocolVersion: 24,port: 8765,manifestInSync: true,extensionVersion: version,@@ -116,6 +120,13 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshreturn { mode, approver: 'app' };},blocked: () => ({ blocked }),+ notices: () => ({ ok: true }),+ takeNotices: () => {+ const taken = notices;+ notices = [];+ return { notices: taken };+ },+ openNotice: () => ({ ok: true }),label: ({ session, label }) => {const named = sessions.find((held) => held.id === session);if (named) named.label = String(label).trim() || undefined;@@ -218,12 +229,16 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshtrayStatus: () => later(undefined, 0),pairRequests: () => later(undefined, 0),announcePaired: () => later(undefined, 0),+ noticesAllowed: () => later(noticesAllowed, 0),+ postNotices: () => later(undefined, 0),checkUpdate: () => later(null),installUpdate: () => later(undefined),onControlEvent: (listener) => (listeners.add(listener), () => listeners.delete(listener)),onTray: () => () => undefined,onPairLink: () => () => undefined,onPairingLaunch: () => () => undefined,+ onNoticeLink: () => () => undefined,+ onWindowFocus: () => () => undefined,openUrl: async (url) => void window.open(url, '_blank'),reveal: async () => undefined,setWindowTheme: async () => undefined,@@ -232,6 +247,11 @@ export function mockBackend({ instant = false, fresh = location.hash === '#freshannounce('pair-requests-changed');},arrive,+ notify: (notice) => {+ notices = [...notices.filter((queued) => queued.id !== notice.id), notice];+ announce('notices-changed');+ },+ allowNotices: (allowed) => void (noticesAllowed = allowed),};}diff --git a/src/windows/ui/model.test.ts b/src/windows/ui/model.test.tsindex ca94bc1..d0caeb4 100644--- a/src/windows/ui/model.test.ts+++ b/src/windows/ui/model.test.ts@@ -1,8 +1,8 @@import { afterEach, describe, expect, it } from 'vitest';-import type { Backend, PairLinkAct, PairRequestSummary, TrayStatus } from './backend';+import type { Backend, PairLinkAct, PairRequestSummary, ShownNotice, TrayStatus } from './backend';import { mockBackend, type MockBackend, type Scenario } from './mock-backend';-import { Model, TABS, outcome, parseJson, short, type State } from './model';+import { Model, TABS, outcome, parseJson, shownNotices, short, type State } from './model';import { splitLine } from './views/logs';const instantly = () => Promise.resolve();@@ -420,3 +420,105 @@ describe('pairing', () => {await until(model, (state) => !state.sessions.some((session) => session.id === 's2'));});});++describe('notices', () => {+ /** The mock, with a record of what reached the control socket and the toasts, and hands on a toast click and the window's focus. */+ function noticeBackend(protocolVersion = 24) {+ const backend = mockBackend({ instant: true });+ const frames: Record<string, unknown>[] = [];+ const posted: ShownNotice[][] = [];+ let click: (notice: string) => void = () => undefined;+ let focus: () => void = () => undefined;+ return {+ frames,+ posted,+ click: (notice: string) => click(notice),+ focus: () => focus(),+ backend: {+ ...backend,+ controlRequest: async (frame: Record<string, unknown>, timeoutMs?: number) => {+ frames.push(frame);+ const reply = await backend.controlRequest(frame, timeoutMs);+ return frame.op === 'status' ? { ...reply, status: { ...(reply.status as object), protocolVersion } } : reply;+ },+ postNotices: async (notices: ShownNotice[]) => void posted.push(notices),+ onNoticeLink: (listener: (notice: string) => void) => ((click = listener), () => undefined),+ onWindowFocus: (listener: () => void) => ((focus = listener), () => undefined),+ } satisfies MockBackend,+ };+ }++ const said = (frames: Record<string, unknown>[]) => frames.filter((frame) => frame.op === 'notices');++ async function opened(backend: Backend) {+ const model = start(backend);+ await model.runPreflight();+ await until(model, (state) => state.daemon === 'on');+ return model;+ }++ it('offers to show notices on a new socket, saying whether Windows will, and only once while nothing changes', async () => {+ const { backend, frames } = noticeBackend();+ const model = await opened(backend);+ await until(model, () => said(frames).length === 1);+ await model.refresh();+ await model.refresh();+ expect(said(frames)).toEqual([{ op: 'notices', watch: true, allowed: true }]);+ });++ it('says so again when Windows stops or starts showing them, on the poll and on focus', async () => {+ const { backend, frames, focus } = noticeBackend();+ const model = await opened(backend);+ await until(model, () => said(frames).length === 1);+ backend.allowNotices(false);+ await model.refresh();+ await until(model, () => said(frames).length === 2);+ backend.allowNotices(true);+ focus();+ await until(model, () => said(frames).length === 3);+ expect(said(frames).map((frame) => frame.allowed)).toEqual([true, false, true]);+ });++ it('takes the waiting notices when the Bridge says there are some, and posts each as a toast', async () => {+ const { backend, posted } = noticeBackend();+ const model = await opened(backend);+ backend.notify({ id: 'monitor:42', kind: 'monitor', title: 'Price dropped', body: 'The jacket is £84 now.', tone: 'live', browser: 'Google Chrome', at: Date.now() });+ await until(model, () => posted.length === 1);+ expect(posted[0]).toEqual([{ id: 'monitor:42', title: 'Price dropped', body: 'The jacket is £84 now.', tone: 'live', browser: 'Google Chrome' }]);+ });++ it('asks the browser to bring a notice’s tab forward when its toast is clicked, and leaves the window alone', async () => {+ const { backend, frames, click } = noticeBackend();+ const model = await opened(backend);+ const tab = model.snapshot().tab;+ click('monitor:42');+ await until(model, () => frames.some((frame) => frame.op === 'openNotice'));+ expect(frames.filter((frame) => frame.op === 'openNotice')).toEqual([{ op: 'openNotice', notice: 'monitor:42' }]);+ expect(model.snapshot().tab).toBe(tab);+ });++ it('never asks a Bridge from before notices', async () => {+ const { backend, frames, focus } = noticeBackend(23);+ const model = await opened(backend);+ await model.refresh();+ focus();+ await model.offerNotices();+ expect(frames.filter((frame) => ['notices', 'takeNotices', 'openNotice'].includes(String(frame.op)))).toEqual([]);+ });++ it('reads notices leniently, skipping only the ones a toast cannot show', () => {+ expect(+ shownNotices([+ { id: 't1', kind: 'timer', title: 'Timer done', body: 'Tea', tone: 'warn', browser: 'Brave', at: 1 },+ { id: 'm1', title: 'Changed', kind: 'something-new' },+ { id: '', title: 'No id' },+ { id: 'x' },+ null,+ ]),+ ).toEqual([+ { id: 't1', title: 'Timer done', body: 'Tea', tone: 'warn', browser: 'Brave' },+ { id: 'm1', title: 'Changed', body: '', tone: 'live' },+ ]);+ expect(shownNotices(undefined)).toEqual([]);+ });+});diff --git a/src/windows/ui/model.ts b/src/windows/ui/model.tsindex 564ba2d..8c883a1 100644--- a/src/windows/ui/model.ts+++ b/src/windows/ui/model.ts@@ -1,6 +1,7 @@import { useSyncExternalStore } from 'react';import { AGENT_LIST, type AgentDescriptor, type AgentKind } from '@/lib/agents/catalog';+import { NOTICE_PROTOCOL } from '@/lib/notices';import { isPairingMode } from '@/lib/pairing';import type { GuardrailValue } from '@/lib/settings/guardrails';import type { PreferenceChange } from '@/lib/settings/preferences';@@ -28,6 +29,7 @@ import type {Preferences,Release,SessionSummary,+ ShownNotice,SkillListing,} from './backend';@@ -209,6 +211,8 @@ export class Model {private started = false;/** Every session seen since the app opened, so one that is new can be told apart from the ones it found. */private seenSessions?: Set<string>;+ /** Whether this socket told the Bridge toasts show; unset on a new socket, which has said nothing yet. */+ private noticesSaid?: boolean;constructor(private readonly backend: Backend,@@ -222,6 +226,8 @@ export class Model {backend.onPairingLaunch(() => {if (this.state.phase === 'main') void this.refresh().then(() => this.watchPairRequests());});+ backend.onNoticeLink((notice) => void this.openNotice(notice));+ backend.onWindowFocus(() => void this.offerNotices());}subscribe = (listener: () => void) => {@@ -445,6 +451,7 @@ export class Model {void this.loadBlocked();return;}+ if (event === 'notices-changed') return void this.takeNotices();if (event !== 'settings-changed') return;void this.loadPreferences();void this.loadAgents();@@ -471,6 +478,7 @@ export class Model {if (!lock) return this.markOff();try {if (await this.backend.controlConnect()) {+ this.noticesSaid = undefined;void this.loadPreferences(true);void this.watchPairRequests();if (this.watchingAndroid) void this.watchAndroid(true);@@ -490,6 +498,7 @@ export class Model {}));this.announceArrivals(sessions);if (status.pairing) void this.loadPairRequests();+ void this.offerNotices();if (!this.state.agents) await this.loadAgents();if (changed) void this.loadBrowsers();} catch {@@ -631,6 +640,40 @@ export class Model {});}+ // Notices++ /**+ * Tells the Bridge on each new socket, and again whenever it changes, whether a toast would show, so a+ * browser hands this app its notices only when Windows will display them. A Bridge before notices is never asked.+ */+ async offerNotices() {+ if ((this.state.status?.protocolVersion ?? 0) < NOTICE_PROTOCOL) return;+ const allowed = await this.backend.noticesAllowed().catch(() => false);+ if (allowed === this.noticesSaid) return;+ const fresh = this.noticesSaid === undefined;+ this.noticesSaid = allowed;+ try {+ accepted(await this.control({ op: 'notices', watch: true, allowed }), 'Browsentic Bridge would not hand this app its notices.');+ if (fresh && allowed) await this.takeNotices();+ } catch {+ this.noticesSaid = undefined;+ }+ }++ async takeNotices() {+ try {+ const notices = shownNotices((await this.control({ op: 'takeNotices' })).notices);+ if (notices.length) await this.backend.postNotices(notices);+ } catch {+ /* What was not taken stays with the Bridge for the next notices-changed. */+ }+ }++ /** The browser brings the notice's tab to the front; this window stays where it is. */+ async openNotice(notice: string) {+ await this.control({ op: 'openNotice', notice }).catch(() => undefined);+ }+/** The sessions read first are the ones the app found; any after that are new, and one that paired by itself is announced once. */private announceArrivals(sessions: SessionSummary[]) {const keyOf = (session: SessionSummary) => `${session.id}@${session.pairedAt}`;@@ -1003,6 +1046,24 @@ export const browserName = (request: Pick<PairRequestSummary, 'browser'>) => reqexport const sessionName = (session: Pick<SessionSummary, 'label' | 'browser'>) => session.label ?? session.browser ?? 'A browser';+/** What `takeNotices` handed over, read leniently: one notice a toast cannot show is skipped, not the batch. */+export function shownNotices(value: unknown): ShownNotice[] {+ if (!Array.isArray(value)) return [];+ return value.flatMap((item: unknown) => {+ const notice = item as Partial<Record<keyof ShownNotice, unknown>> | null;+ if (typeof notice?.id !== 'string' || !notice.id || typeof notice.title !== 'string') return [];+ return [+ {+ id: notice.id,+ title: notice.title,+ body: typeof notice.body === 'string' ? notice.body : '',+ tone: notice.tone === 'warn' ? 'warn' : 'live',+ ...(typeof notice.browser === 'string' && notice.browser ? { browser: notice.browser } : {}),+ } satisfies ShownNotice,+ ];+ });+}+/** The pairing ops answer `{ok, error}` or `{mode, error}`, a refusal in words rather than an ActionResult. */function accepted(reply: Record<string, unknown>, fallback: string) {if (typeof reply.error === 'string' && reply.error) throw new Error(reply.error);