Skip to content

Commit b065571

Browse files
committed
refactor(notifications): simplify native state and request handling
Consolidate native connection state, permission reconciliation, and bridge replies. Prepare browser preferences once and remove unused notification wrappers. Use notification bridge URLs only to wake the current top-document queue; preserve socket, document, and presentation lifetime checks.
1 parent 3a510e3 commit b065571

14 files changed

Lines changed: 294 additions & 446 deletions

‎apps/linux/src-tauri/src/gateway_notifications.rs‎

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,10 @@ impl NotificationLease {
116116
}
117117
})
118118
.map_err(|error| format!("Could not listen for notification clicks: {error}"))?;
119-
let app = app.clone();
120119
let worker = lease.clone();
121120
tauri::async_runtime::spawn(async move {
122121
let _listener = listener;
123-
worker.run(app, receiver).await;
122+
worker.run(receiver).await;
124123
});
125124
Ok(lease)
126125
}
@@ -195,7 +194,7 @@ impl NotificationLease {
195194
let app = &self.0.app;
196195
let Some(revision) = app
197196
.state::<GatewayClient>()
198-
.record_notification_error(self, message)
197+
.record_notification_error(self, Some(message.to_string()))
199198
else {
200199
return;
201200
};
@@ -281,7 +280,8 @@ impl NotificationLease {
281280
}
282281
}
283282

284-
async fn run(&self, app: AppHandle, mut receiver: mpsc::Receiver<NotificationCommand>) {
283+
async fn run(&self, mut receiver: mpsc::Receiver<NotificationCommand>) {
284+
let app = &self.0.app;
285285
let mut owned = HashMap::<String, OwnedNotification>::new();
286286
while self.is_active() {
287287
tokio::select! {
@@ -297,13 +297,13 @@ impl NotificationLease {
297297
// Captured route, not OS payload data, owns the click destination.
298298
if webview.url().is_ok_and(|url| self.accepts_url(&url)) {
299299
let _ = webview.navigate(item.url.clone());
300-
tray::show_window(&app);
300+
tray::show_window(app);
301301
}
302302
}
303303
}
304304
}
305305
}
306-
NotificationCommand::Event(event, claim) => self.apply(&app, &mut owned, event, claim).await,
306+
NotificationCommand::Event(event, claim) => self.apply(&mut owned, event, claim).await,
307307
}
308308
}
309309
_ = tokio::time::sleep(Duration::from_secs(1)) => {}
@@ -314,7 +314,7 @@ impl NotificationLease {
314314
.map(|(id, _)| id.clone())
315315
.collect();
316316
for id in expired {
317-
self.remove_owned(&app, &mut owned, &id);
317+
self.remove_owned(&mut owned, &id);
318318
}
319319
}
320320
self.0
@@ -324,17 +324,17 @@ impl NotificationLease {
324324
.clear();
325325
// Serial with show(): late platform completions are removed before this lease exits.
326326
for item in owned.into_values() {
327-
remove_native(&app, item.native_id);
327+
remove_native(app, item.native_id);
328328
}
329329
}
330330

331331
async fn apply(
332332
&self,
333-
app: &AppHandle,
334333
owned: &mut HashMap<String, OwnedNotification>,
335334
event: NotificationEvent,
336335
claim: Arc<NotificationClaim>,
337336
) {
337+
let app = &self.0.app;
338338
let NotificationEvent::Show {
339339
id,
340340
category: _category,
@@ -346,23 +346,19 @@ impl NotificationLease {
346346
} = event
347347
else {
348348
if let NotificationEvent::Remove { id } = event {
349-
self.remove_owned(app, owned, &id);
349+
self.remove_owned(owned, &id);
350350
}
351351
return;
352352
};
353353
let Some(url) = notification_url(&self.0.target, &path) else {
354354
self.fail("The Gateway sent an unsafe notification destination.");
355355
return;
356356
};
357-
if id.is_empty()
358-
|| id.len() > 200
359-
|| title.chars().count() > 160
360-
|| body.chars().count() > 320
361-
{
357+
if title.chars().count() > 160 || body.chars().count() > 320 {
362358
self.fail("The Gateway sent an oversized notification.");
363359
return;
364360
}
365-
self.remove_owned(app, owned, &id);
361+
self.remove_owned(owned, &id);
366362
if !self.is_active() || !claim.is_current(now_ms()) {
367363
self.finish_claim(&id, &claim);
368364
return;
@@ -379,7 +375,7 @@ impl NotificationLease {
379375
.min_by_key(|(_, item)| item.claim.expires_at_ms)
380376
.map(|(id, _)| id.clone())
381377
{
382-
self.remove_owned(app, owned, &oldest);
378+
self.remove_owned(owned, &oldest);
383379
}
384380
}
385381
match app.notifications().permission_state().await {
@@ -438,15 +434,10 @@ impl NotificationLease {
438434
}
439435
}
440436

441-
fn remove_owned(
442-
&self,
443-
app: &AppHandle,
444-
owned: &mut HashMap<String, OwnedNotification>,
445-
id: &str,
446-
) {
437+
fn remove_owned(&self, owned: &mut HashMap<String, OwnedNotification>, id: &str) {
447438
if let Some(item) = owned.remove(id) {
448439
self.finish_claim(id, &item.claim);
449-
remove_native(app, item.native_id);
440+
remove_native(&self.0.app, item.native_id);
450441
}
451442
}
452443
}

‎apps/linux/src-tauri/src/gateway_notifications_bridge.rs‎

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use crate::gateway_ws::GatewayClient;
44
use crate::notify;
55
use serde::Deserialize;
66
use serde_json::{json, Value};
7-
use std::collections::HashMap;
87
use std::sync::Arc;
98
use tauri::{AppHandle, Manager, Url};
109
use tauri_plugin_notifications::{NotificationsExt, PermissionState};
@@ -28,18 +27,18 @@ pub(crate) const BRIDGE_SCRIPT: &str = r#"(() => {
2827
window.dispatchEvent(new CustomEvent('openclaw:native-notifications-status', { detail:snapshot }));
2928
};
3029
Object.defineProperty(window, '__OPENCLAW_NATIVE_NOTIFICATIONS_DOCUMENT__', { value: documentId });
31-
Object.defineProperty(window, '__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__', { value: (document, request, payload, acknowledge = false) => {
30+
Object.defineProperty(window, '__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__', { value: (request, acknowledgeDocument = null) => {
3231
const entry = pending.get(request);
33-
if (document !== documentId || entry?.payload !== payload) return false;
34-
if (acknowledge) {
35-
if (!entry.claimed) return false;
32+
if (!entry) return null;
33+
if (acknowledgeDocument !== null) {
34+
if (acknowledgeDocument !== documentId || !entry.claimed) return false;
3635
clearTimeout(entry.timer);
3736
pending.delete(request);
38-
} else {
39-
if (entry.claimed) return false;
40-
entry.claimed = true;
37+
return true;
4138
}
42-
return true;
39+
if (entry.claimed) return null;
40+
entry.claimed = true;
41+
return [documentId, entry.payload];
4342
}});
4443
Object.defineProperty(window, '__OPENCLAW_NATIVE_NOTIFICATIONS_BRIDGE__', { value: {
4544
postMessage(message) {
@@ -58,8 +57,7 @@ pub(crate) const BRIDGE_SCRIPT: &str = r#"(() => {
5857
reject(message, 'Could not authorize notification settings. Reload the Dashboard and try again.');
5958
}, 10000);
6059
pending.set(message.requestId, {payload, timer, claimed:false});
61-
location.href = 'openclaw-notifications://request?document=' + encodeURIComponent(documentId)
62-
+ '&request=' + encodeURIComponent(message.requestId) + '&message=' + encodeURIComponent(payload);
60+
location.href = 'openclaw-notifications://request?request=' + encodeURIComponent(message.requestId);
6361
}
6462
}});
6563
})();"#;
@@ -117,31 +115,22 @@ pub(crate) fn intercept_navigation(app: &AppHandle, view: &Arc<BridgeView>, targ
117115
{
118116
return true;
119117
}
120-
let parameters: HashMap<_, _> = target.query_pairs().into_owned().collect();
121-
let (Some(document), Some(request_id), Some(message)) = (
122-
parameters.get("document"),
123-
parameters.get("request"),
124-
parameters.get("message"),
125-
) else {
118+
let Some((_, request_id)) = target.query_pairs().find(|(key, _)| key == "request") else {
126119
return true;
127120
};
128-
if target.host_str() != Some("request")
129-
|| document.is_empty()
130-
|| document.len() > 64
131-
|| request_id.is_empty()
132-
|| request_id.len() > 64
133-
{
121+
if target.host_str() != Some("request") || request_id.is_empty() || request_id.len() > 64 {
134122
return true;
135123
}
136-
let document = view.document(document.clone());
137124
let lease = gateway.notification_lease();
138-
let request_id = request_id.clone();
139-
let message = message.clone();
125+
let request_id = request_id.into_owned();
126+
// The URL only wakes the bridge. Its payload and document come from the
127+
// current top frame's private queue, never from a navigating child frame.
128+
let admission = view.admit(webview, request_id.clone());
140129
let app = app.clone();
141130
tauri::async_runtime::spawn(async move {
142-
if !document.admit(&webview, &request_id, &message).await {
131+
let Some((document, message)) = admission.await else {
143132
return;
144-
}
133+
};
145134
gateway.register_notification_document(generation, document.clone());
146135
respond_to_bridge(
147136
&app,
@@ -266,7 +255,7 @@ async fn handle_bridge(
266255
let send_test = matches!(action, BridgeAction::SendTest {});
267256
if send_test || matches!(action, BridgeAction::RequestPermission {}) {
268257
if let Some(lease) = lease.as_ref() {
269-
gateway.clear_notification_error(lease);
258+
gateway.record_notification_error(lease, None);
270259
}
271260
}
272261
let permission = if gateway.notifications_supported()

‎apps/linux/src-tauri/src/gateway_notifications_document.rs‎

Lines changed: 48 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
22
use std::sync::{Arc, Mutex};
33
use std::time::Duration;
44
use tauri::{AppHandle, Manager, Webview};
5-
use tokio::sync::oneshot;
5+
use tokio::sync::mpsc;
66

77
#[derive(Default)]
88
pub(crate) struct BridgeViews(Mutex<Option<Arc<BridgeView>>>);
@@ -62,6 +62,53 @@ impl BridgeView {
6262
id,
6363
}
6464
}
65+
66+
pub(crate) fn admit(
67+
self: &Arc<Self>,
68+
webview: Webview,
69+
request_id: String,
70+
) -> impl std::future::Future<Output = Option<(BridgeDocument, String)>> + Send + 'static {
71+
// Capture before returning the future: spawning it must not adopt a
72+
// navigation or same-label replacement that happened while it was queued.
73+
let navigation = self.navigation.load(Ordering::SeqCst);
74+
let view = self.clone();
75+
async move {
76+
if !view.active.load(Ordering::SeqCst)
77+
|| view.navigation.load(Ordering::SeqCst) != navigation
78+
{
79+
return None;
80+
}
81+
let request =
82+
serde_json::to_string(&request_id).expect("request identifier serialization");
83+
let script =
84+
format!("window.__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__?.({request}) ?? null");
85+
let (sender, mut receiver) = mpsc::channel(1);
86+
webview
87+
.eval_with_callback(script, move |result| {
88+
let _ = sender.try_send(result);
89+
})
90+
.ok()?;
91+
// Wry can drop callbacks while initial scripts are queued. Only a
92+
// returned top-frame request, still bound to this epoch, is admitted.
93+
let result = tokio::time::timeout(Duration::from_secs(5), receiver.recv())
94+
.await
95+
.ok()??;
96+
let (document_id, payload): (String, String) = serde_json::from_str(&result).ok()?;
97+
let document = view.document(document_id);
98+
if document.navigation != navigation || !document.is_current() {
99+
return None;
100+
}
101+
// Acknowledge receipt before OS permission can outlive the transport
102+
// timeout; a lost callback leaves that timeout available to the UI.
103+
let args = serde_json::json!([request_id, document.id]);
104+
webview
105+
.eval(format!(
106+
"window.__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__?.(...{args})"
107+
))
108+
.ok()?;
109+
document.is_current().then_some((document, payload))
110+
}
111+
}
65112
}
66113

67114
impl BridgeDocument {
@@ -72,49 +119,6 @@ impl BridgeDocument {
72119
pub(crate) fn is_current(&self) -> bool {
73120
self.is_attached() && self.view.navigation.load(Ordering::SeqCst) == self.navigation
74121
}
75-
76-
pub(crate) async fn admit(&self, webview: &Webview, request_id: &str, payload: &str) -> bool {
77-
if !self.is_current() {
78-
return false;
79-
}
80-
let args = serde_json::json!([self.id, request_id, payload]);
81-
let script =
82-
format!("window.__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__?.(...{args}) === true");
83-
let (sender, receiver) = oneshot::channel();
84-
let sender = Mutex::new(Some(sender));
85-
if webview
86-
.eval_with_callback(script, move |result| {
87-
if let Some(sender) = sender
88-
.lock()
89-
.expect("notification admission mutex poisoned")
90-
.take()
91-
{
92-
let _ = sender.send(result == "true");
93-
}
94-
})
95-
.is_err()
96-
{
97-
return false;
98-
}
99-
// Wry may drop callbacks while initial scripts are queued. Dispatch success
100-
// is not document proof, and a callback from a replaced page grants nothing.
101-
if !matches!(
102-
tokio::time::timeout(Duration::from_secs(5), receiver).await,
103-
Ok(Ok(true))
104-
) || !self.is_current()
105-
{
106-
return false;
107-
}
108-
// Clear only this admitted request's transport timeout. The permission prompt
109-
// may legitimately outlive it; a dropped eval callback never reaches this ack.
110-
let args = serde_json::json!([self.id, request_id, payload, true]);
111-
webview
112-
.eval(format!(
113-
"window.__OPENCLAW_NATIVE_NOTIFICATIONS_ADMIT__?.(...{args})"
114-
))
115-
.is_ok()
116-
&& self.is_current()
117-
}
118122
}
119123

120124
pub(crate) fn replace_view(app: &AppHandle) -> Arc<BridgeView> {

0 commit comments

Comments
 (0)