Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(desktop): move QA snapshot after native dispatch returns (#980)

Gener2e32db9c557f
diff --git a/scripts/ci/system-notifications-desktop.test.ts b/scripts/ci/system-notifications-desktop.test.ts
index 6e68bc067..2309bcc61 100644
--- a/scripts/ci/system-notifications-desktop.test.ts
+++ b/scripts/ci/system-notifications-desktop.test.ts
@@ -20,6 +20,12 @@ const desktopCommands = [
"desktop_system_notification_unlisten",
]
+function startupSnapshot(source: string) {
+ const snapshot = source.match(/#\[cfg\(all\(target_os = "macos", debug_assertions\)\)\]\npub\(crate\) fn diagnose_qa_main_snapshot\(window: &WebviewWindow\) \{[\s\S]*?\n\}/g) ?? []
+ expect(snapshot).toHaveLength(1)
+ return snapshot[0]!
+}
+
function quotedValues(source: string) {
return Array.from(source.matchAll(/"([a-z][a-z0-9_]*)"/g), (match) => match[1]!)
}
@@ -76,11 +82,71 @@ describe("desktop system notification contract", () => {
expect(linux).not.toContain("activate(&app")
})
+ it("limits startup snapshot reads to the exact QA handoff after its result and outer dispatch return", () => {
+ const runtime = read("src/system_notifications.rs")
+ const recovery = read("src/webview_recovery.rs")
+ const commands = read("src/commands.rs")
+ const snapshot = startupSnapshot(runtime)
+ const qualification = runtime.slice(
+ runtime.indexOf("pub(crate) fn notification_diagnostics_enabled"),
+ runtime.indexOf("macro_rules! notification_diagnostic"),
+ )
+ expect(qualification).toContain('cfg!(all(target_os = "macos", debug_assertions))')
+ expect(qualification).toContain('identifier == "ai.alook.desktop.qa.madox.notification208" && switch == Some("208")')
+ const rejection = snapshot.indexOf("if !notification_diagnostics_enabled(window.app_handle()) {\n return;\n }")
+ expect(rejection).toBeGreaterThan(-1)
+ expect(snapshot.match(/\.is_visible\(\)/g)).toHaveLength(1)
+ expect(snapshot.match(/\.url\(\)/g)).toHaveLength(1)
+ expect(rejection).toBeLessThan(snapshot.indexOf(".is_visible()"))
+ expect(snapshot.indexOf(".is_visible()")).toBeLessThan(snapshot.indexOf(".url()"))
+ const handoff = recovery.slice(recovery.indexOf("pub fn finish_native_creation"), recovery.indexOf("fn apple_class_method"))
+ const callbackStart = handoff.indexOf("let dispatched = window.with_webview(move |platform| {")
+ const callbackEnd = handoff.indexOf("\n });", callbackStart)
+ expect(callbackStart).toBeGreaterThan(-1)
+ expect(callbackEnd).toBeGreaterThan(callbackStart)
+ const callback = handoff.slice(callbackStart, callbackEnd)
+ const afterDispatch = handoff.slice(callbackEnd)
+ expect(handoff.indexOf('"handoff_return"')).toBeGreaterThan(handoff.indexOf("let completed ="))
+ expect(callback).not.toContain("diagnose_qa_main_snapshot")
+ expect(callback).not.toMatch(/\.(?:url|is_visible)\(/)
+ expect(callback).toContain("sender.send((completed, shown_main))")
+ expect(callback.indexOf("sender.send((completed, shown_main))")).toBeGreaterThan(callback.indexOf('"handoff_return"'))
+ expect(afterDispatch.indexOf("receiver.try_recv()")).toBeGreaterThan(afterDispatch.indexOf('"handoff_dispatch_return"'))
+ expect(afterDispatch.indexOf("diagnose_qa_main_snapshot(&main)")).toBeGreaterThan(afterDispatch.indexOf("receiver.try_recv()"))
+ expect(afterDispatch).toContain("qa_startup_snapshot_candidate(dispatched.is_ok(), receiver.try_recv())")
+ expect(afterDispatch).toContain("Ok((true, Some(main))) => Ok(main)")
+ expect(afterDispatch).toContain('return Err("dispatch_error")')
+ expect(afterDispatch).toContain('Err("handoff_not_eligible")')
+ const frontend = commands.slice(commands.indexOf("pub fn close_splashscreen"), commands.indexOf("// --- Daemon commands ---"))
+ expect(frontend).toContain("try_close_splashscreen(&handle, None)")
+ expect(frontend).not.toContain("diagnose_qa_main_snapshot")
+ })
+
+ it("keeps the one-shot handoff channel and actual thread record inside QA diagnostics", () => {
+ const recovery = read("src/webview_recovery.rs")
+ const handoff = recovery.slice(recovery.indexOf("pub fn finish_native_creation"), recovery.indexOf("fn apple_class_method"))
+ expect(handoff).toContain('#[cfg(all(target_os = "macos", debug_assertions))]\n let (diagnostic_sender, diagnostic_receiver) =')
+ expect(handoff).toContain("if crate::system_notifications::notification_diagnostics_enabled(window.app_handle()) {")
+ expect(handoff.match(/std::sync::mpsc::channel\(\)/g)).toHaveLength(1)
+ expect(handoff.match(/receiver\.try_recv\(\)/g)).toHaveLength(1)
+ expect(handoff).not.toMatch(/\.(?:recv|recv_timeout|recv_deadline)\(/)
+ expect(handoff).not.toMatch(/\b(?:loop|while|sleep|spawn|run_on_main_thread)\b(?!\(show_native_creation_error\))/)
+ expect(handoff).toContain('"dispatchMode": if *calling_thread == callback_thread { "inline" } else { "queued" }')
+ expect(handoff).toContain('"callingThread": format!("{calling_thread:?}")')
+ expect(handoff).toContain('"callbackThread": format!("{callback_thread:?}")')
+ expect(handoff).toContain('"handoff_result_send_return"')
+ expect(handoff).toContain('"main_snapshot_not_run"')
+ expect(handoff).toContain('"callbackCompletion": "not_inferred"')
+ expect(handoff).toContain('Err("handoff_result_pending")')
+ expect(handoff).toContain('Err("handoff_result_unavailable")')
+ })
+
it("does not gate delivery on main-window visibility and preserves real Quit", () => {
const runtime = read("src/system_notifications.rs")
const commands = read("src/commands.rs")
const app = read("src/lib.rs")
- expect(runtime).not.toContain("is_visible")
+ const snapshot = startupSnapshot(runtime)
+ expect(runtime.replace(snapshot, "")).not.toContain("is_visible")
expect(app).toContain("api.prevent_close();")
expect(app).toContain("let _ = window.hide();")
expect(commands).toContain("app.exit(0);")
diff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rs
index 79ea9e7f0..f805b6297 100644
--- a/src/desktop/src-tauri/src/commands.rs
+++ b/src/desktop/src-tauri/src/commands.rs
@@ -516,33 +516,97 @@ html,body{{width:100%;height:100%;overflow:hidden;background:transparent;display
)
}
+#[cfg(all(target_os = "macos", debug_assertions))]
+pub(crate) const QA_NOTIFICATION_STORE_ID: [u8; 16] = [
+ 158, 83, 199, 44, 135, 159, 85, 131, 171, 124, 5, 37, 18, 176, 5, 21,
+];
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+fn qa_main_window_config(
+ config: &tauri::utils::config::Config,
+) -> Result<Option<(tauri::utils::config::WindowConfig, [u8; 16])>, &'static str> {
+ if config.identifier != "ai.alook.desktop.qa.madox.notification208" {
+ return Ok(None);
+ }
+ let window = config
+ .app
+ .windows
+ .iter()
+ .find(|window| window.label == "main")
+ .cloned()
+ .ok_or("qa_main_unavailable")?;
+ if window.create {
+ return Err("qa_auto_main_enabled");
+ }
+ let store = window
+ .data_store_identifier
+ .filter(|store| *store == QA_NOTIFICATION_STORE_ID)
+ .ok_or("qa_store_unavailable")?;
+ Ok(Some((window, store)))
+}
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+pub fn create_qa_main_window(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
+ let Some((config, store)) = qa_main_window_config(app.config())? else {
+ return Ok(());
+ };
+ if app.get_webview_window("main").is_some() {
+ return Err("qa_auto_main_present".into());
+ }
+ let window = tauri::WebviewWindowBuilder::from_config(app, &config)?
+ .data_store_identifier(store)
+ .build()?;
+ crate::system_notifications::diagnose_qa_store(&window);
+ Ok(())
+}
+
#[cfg(desktop)]
pub fn create_splash_window(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
use tauri::{WebviewUrl, WebviewWindowBuilder};
- WebviewWindowBuilder::new(
+ let builder = WebviewWindowBuilder::new(
app,
"splash",
WebviewUrl::CustomProtocol("splash://index".parse()?),
- )
- .title("Alook")
- .inner_size(240.0, 240.0)
- .center()
- .decorations(false)
- .resizable(false)
- .transparent(true)
- .shadow(false)
- .always_on_top(true)
- .skip_taskbar(true)
- .build()?;
+ );
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ let builder = if app.config().identifier == "ai.alook.desktop.qa.madox.notification208" {
+ let store = app
+ .config()
+ .app
+ .windows
+ .iter()
+ .find(|window| window.label == "main")
+ .and_then(|window| window.data_store_identifier)
+ .ok_or("qa_store_unavailable")?;
+ builder.data_store_identifier(store)
+ } else {
+ builder
+ };
+ let _window = builder
+ .title("Alook")
+ .inner_size(240.0, 240.0)
+ .center()
+ .decorations(false)
+ .resizable(false)
+ .transparent(true)
+ .shadow(false)
+ .always_on_top(true)
+ .skip_taskbar(true)
+ .build()?;
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ crate::system_notifications::diagnose_qa_store(&_window);
Ok(())
}
#[cfg(desktop)]
-pub fn finish_native_startup(handle: &AppHandle) -> bool {
+pub fn finish_native_startup(
+ handle: &AppHandle,
+ diagnostic_main: Option<&mut Option<tauri::WebviewWindow>>,
+) -> bool {
SPLASH_NATIVE_READY.store(true, Ordering::SeqCst);
- try_close_splashscreen(handle)
+ try_close_splashscreen(handle, diagnostic_main)
}
#[cfg(target_os = "macos")]
@@ -563,26 +627,105 @@ pub fn show_startup_initialization_error<R: tauri::Runtime>(handle: &AppHandle<R
}
#[cfg(desktop)]
-fn try_close_splashscreen(handle: &AppHandle) -> bool {
+fn try_close_splashscreen(
+ handle: &AppHandle,
+ diagnostic_main: Option<&mut Option<tauri::WebviewWindow>>,
+) -> bool {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ let mut diagnostic_main = diagnostic_main
+ .filter(|_| crate::system_notifications::notification_diagnostics_enabled(handle));
+ #[cfg(not(all(target_os = "macos", debug_assertions)))]
+ let _ = diagnostic_main;
if SPLASH_CLOSED.load(Ordering::SeqCst) {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "already_closed_flag",
+ "main",
+ serde_json::json!({ "completed": true }),
+ );
+ }
return true;
}
if !should_close_splash(SPLASH_NATIVE_READY.load(Ordering::SeqCst), false) {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "native_not_ready",
+ "main",
+ serde_json::json!({ "completed": false }),
+ );
+ }
return false;
}
let Some(main) = handle.get_webview_window("main") else {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "main_absent",
+ "main",
+ serde_json::json!({ "completed": false }),
+ );
+ }
return false;
};
- if let Err(error) = main.show() {
+ let shown = main.show();
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "show_return",
+ main.label(),
+ serde_json::json!({ "status": if shown.is_ok() { "ok" } else { "error" }, "error": shown.as_ref().err().map(ToString::to_string) }),
+ );
+ }
+ if let Err(error) = shown {
eprintln!("startup main window unavailable: {error}");
return false;
}
- let _ = main.set_focus();
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if let Some(captured) = diagnostic_main.as_deref_mut() {
+ *captured = Some(main.clone());
+ }
+ let focused = main.set_focus();
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "focus_return",
+ main.label(),
+ serde_json::json!({ "status": if focused.is_ok() { "ok" } else { "error" }, "error": focused.as_ref().err().map(ToString::to_string) }),
+ );
+ }
+ let _ = focused;
if let Some(splash) = handle.get_webview_window("splash") {
- if let Err(error) = splash.close() {
+ let closed = splash.close();
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "close_request_return",
+ splash.label(),
+ serde_json::json!({ "status": if closed.is_ok() { "request_queued" } else { "error" }, "error": closed.as_ref().err().map(ToString::to_string) }),
+ );
+ }
+ if let Err(error) = closed {
eprintln!("startup splash close unavailable: {error}");
return false;
}
+ } else {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if diagnostic_main.is_some() {
+ crate::system_notifications::diagnose_qa_startup(
+ handle,
+ "close_request_return",
+ "splash",
+ serde_json::json!({ "status": "absent" }),
+ );
+ }
}
SPLASH_CLOSED.store(true, Ordering::SeqCst);
true
@@ -593,7 +736,7 @@ fn try_close_splashscreen(handle: &AppHandle) -> bool {
pub fn close_splashscreen(app: AppHandle) {
let handle = app.clone();
let _ = app.run_on_main_thread(move || {
- try_close_splashscreen(&handle);
+ try_close_splashscreen(&handle, None);
});
}
@@ -767,6 +910,68 @@ pub fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
mod tests {
use super::*;
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ fn qa_window_config_fixture() -> tauri::utils::config::Config {
+ let mut config = tauri::utils::config::Config::default();
+ config.identifier = "ai.alook.desktop.qa.madox.notification208".into();
+ config.app.windows = vec![serde_json::from_value(serde_json::json!({
+ "label": "main", "title": "QA original", "url": "alook-recovery://localhost/bootstrap",
+ "width": 1173, "height": 719, "visible": false, "create": false,
+ "dataStoreIdentifier": QA_NOTIFICATION_STORE_ID,
+ }))
+ .unwrap()];
+ config
+ }
+
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_main_preparation_keeps_the_complete_original_window_configuration() {
+ let config = qa_window_config_fixture();
+ let original = serde_json::to_value(&config.app.windows[0]).unwrap();
+ let (window, store) = qa_main_window_config(&config).unwrap().unwrap();
+ assert_eq!(serde_json::to_value(window).unwrap(), original);
+ assert_eq!(store, QA_NOTIFICATION_STORE_ID);
+ }
+
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_main_preparation_does_not_apply_to_another_bundle() {
+ let mut config = qa_window_config_fixture();
+ config.identifier = "ai.alook.desktop".into();
+ config.app.windows[0].create = true;
+ config.app.windows[0].data_store_identifier = None;
+ let original = serde_json::to_value(&config).unwrap();
+ assert!(qa_main_window_config(&config).unwrap().is_none());
+ assert_eq!(serde_json::to_value(config).unwrap(), original);
+ }
+
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_main_preparation_rejects_missing_store_and_automatic_creation() {
+ let mut config = qa_window_config_fixture();
+ config.app.windows[0].create = true;
+ assert_eq!(
+ qa_main_window_config(&config).err(),
+ Some("qa_auto_main_enabled")
+ );
+ config.app.windows[0].create = false;
+ config.app.windows[0].data_store_identifier = None;
+ assert_eq!(
+ qa_main_window_config(&config).err(),
+ Some("qa_store_unavailable")
+ );
+ config.app.windows[0].data_store_identifier = Some([0; 16]);
+ assert_eq!(
+ qa_main_window_config(&config).err(),
+ Some("qa_store_unavailable")
+ );
+ config.app.windows.clear();
+ assert_eq!(
+ qa_main_window_config(&config).err(),
+ Some("qa_main_unavailable")
+ );
+ }
+
#[test]
fn runtime_capability_requires_node_and_npm() {
let ok = || Ok("10.9.3".to_string());
diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rs
index 0604f22fc..78c9bf01a 100644
--- a/src/desktop/src-tauri/src/lib.rs
+++ b/src/desktop/src-tauri/src/lib.rs
@@ -180,6 +180,8 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
// System tray + window setup (desktop only)
builder = builder.setup(|app| {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ commands::create_qa_main_window(app)?;
commands::create_splash_window(app)?;
if file_save_runtime::setup(app.handle()).is_err() {
eprintln!("file save storage unavailable");
@@ -210,7 +212,15 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
macos_window::setup_inset_webview(&window);
}
}
- if let Some(window) = app.get_webview_window("main") {
+ let main = app.get_webview_window("main");
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ system_notifications::diagnose_qa_startup(
+ app.handle(),
+ "setup_tail",
+ "main",
+ serde_json::json!({ "window": if main.is_some() { "present" } else { "absent" } }),
+ );
+ if let Some(window) = main {
webview_recovery::finish_native_creation(&window);
}
@@ -257,6 +267,24 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
}
fn run_app(builder: tauri::Builder<tauri::Wry>) {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ let app = {
+ let mut context = tauri::generate_context!();
+ if context.config().identifier == "ai.alook.desktop.qa.madox.notification208" {
+ let main = context
+ .config_mut()
+ .app
+ .windows
+ .iter_mut()
+ .find(|window| window.label == "main")
+ .expect("qa_main_unavailable");
+ main.create = false;
+ main.data_store_identifier = Some(commands::QA_NOTIFICATION_STORE_ID);
+ }
+ builder.build(context)
+ }
+ .expect("error while building tauri application");
+ #[cfg(not(all(target_os = "macos", debug_assertions)))]
let app = builder
.build(tauri::generate_context!())
.expect("error while building tauri application");
diff --git a/src/desktop/src-tauri/src/system_notifications.rs b/src/desktop/src-tauri/src/system_notifications.rs
index b44f2543a..b22916c9b 100644
--- a/src/desktop/src-tauri/src/system_notifications.rs
+++ b/src/desktop/src-tauri/src/system_notifications.rs
@@ -11,6 +11,161 @@ const MAX_RECENT: usize = 256;
const ACTIVATION_SCHEME: &str = "ai.alook.desktop";
const ACTIVATION_HOST: &str = "notification";
const ACTIVATION_PATH: &str = "/open";
+
+pub(crate) fn notification_diagnostics_enabled(app: &AppHandle) -> bool {
+ cfg!(all(target_os = "macos", debug_assertions))
+ && notification_diagnostic_identity_allowed(
+ &app.config().identifier,
+ std::env::var("ALOOK_NOTIFICATION_DIAGNOSTICS")
+ .ok()
+ .as_deref(),
+ )
+}
+
+fn notification_diagnostic_identity_allowed(identifier: &str, switch: Option<&str>) -> bool {
+ identifier == "ai.alook.desktop.qa.madox.notification208" && switch == Some("208")
+}
+
+macro_rules! notification_diagnostic {
+ ($enabled:expr, $stage:expr, $data:expr) => {
+ if $enabled {
+ use std::io::Write;
+ let time = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .ok()
+ .map(|value| value.as_millis());
+ let _ = writeln!(std::io::stderr().lock(), "ALOOK208 {}",
+ serde_json::json!({ "stage": $stage, "timeMs": time, "data": $data }));
+ }
+ };
+}
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+pub(crate) fn diagnose_qa_startup(
+ app: &AppHandle,
+ phase: &str,
+ window: &str,
+ result: serde_json::Value,
+) {
+ notification_diagnostic!(
+ notification_diagnostics_enabled(app),
+ "native_startup",
+ serde_json::json!({
+ "phase": phase,
+ "window": window,
+ "pid": std::process::id(),
+ "result": result,
+ })
+ );
+}
+
+#[cfg(any(test, all(target_os = "macos", debug_assertions)))]
+fn sanitized_startup_url(mut url: url::Url) -> Result<String, &'static str> {
+ url.set_query(None);
+ url.set_fragment(None);
+ if url.password().is_some() {
+ url.set_password(None)
+ .map_err(|_| "password_sanitization_failed")?;
+ }
+ if !url.username().is_empty() {
+ url.set_username("")
+ .map_err(|_| "username_sanitization_failed")?;
+ }
+ Ok(url.to_string())
+}
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+pub(crate) fn diagnose_qa_main_snapshot(window: &WebviewWindow) {
+ if !notification_diagnostics_enabled(window.app_handle()) {
+ return;
+ }
+ let visible = window.is_visible();
+ diagnose_qa_startup(
+ window.app_handle(),
+ "main_visible_return",
+ window.label(),
+ match visible {
+ Ok(value) => serde_json::json!({ "status": "ok", "visible": value }),
+ Err(error) => serde_json::json!({ "status": "error", "error": error.to_string() }),
+ },
+ );
+ let url = window.url();
+ diagnose_qa_startup(
+ window.app_handle(),
+ "main_url_return",
+ window.label(),
+ match url {
+ Ok(value) => match sanitized_startup_url(value) {
+ Ok(value) => serde_json::json!({ "status": "ok", "url": value }),
+ Err(error) => serde_json::json!({ "status": "sanitization_error", "error": error }),
+ },
+ Err(error) => serde_json::json!({ "status": "error", "error": error.to_string() }),
+ },
+ );
+}
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+fn log_qa_store_identity(
+ window: &str,
+ identifier: Option<String>,
+ read_time_ms: Option<u128>,
+ error: Option<String>,
+) {
+ notification_diagnostic!(
+ true,
+ "native_store_identity",
+ serde_json::json!({
+ "window": window,
+ "pid": std::process::id(),
+ "identifier": identifier,
+ "readTimeMs": read_time_ms,
+ "error": error,
+ })
+ );
+}
+
+#[cfg(all(target_os = "macos", debug_assertions))]
+pub(crate) fn diagnose_qa_store(window: &WebviewWindow) {
+ use objc2::MainThreadMarker;
+ use objc2_web_kit::WKWebView;
+
+ if !notification_diagnostics_enabled(window.app_handle()) {
+ return;
+ }
+ let label = window.label().to_owned();
+ if !objc2::available!(macos = 14.0) {
+ log_qa_store_identity(&label, None, None, Some("macos_14_required".into()));
+ return;
+ }
+ let callback_label = label.clone();
+ if let Err(error) = window.with_webview(move |platform| {
+ if MainThreadMarker::new().is_none() {
+ log_qa_store_identity(&callback_label, None, None, Some("not_main_thread".into()));
+ return;
+ }
+ let Some(webview) = (unsafe { platform.inner().cast::<WKWebView>().as_ref() }) else {
+ log_qa_store_identity(
+ &callback_label,
+ None,
+ None,
+ Some("webview_unavailable".into()),
+ );
+ return;
+ };
+ let identifier = unsafe { webview.configuration().websiteDataStore().identifier() }
+ .map(|value| value.UUIDString().to_string());
+ let read_time_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .ok()
+ .map(|value| value.as_millis());
+ let error = read_time_ms
+ .is_none()
+ .then(|| "read_clock_unavailable".into());
+ log_qa_store_identity(&callback_label, identifier, read_time_ms, error);
+ }) {
+ log_qa_store_identity(&label, None, None, Some(error.to_string()));
+ }
+}
#[cfg(windows)]
const WINDOWS_APP_ID: &str = "ai.alook.desktop";
#[cfg(windows)]
@@ -503,26 +658,61 @@ pub async fn desktop_system_notification_show(
state: tauri::State<'_, DesktopSystemNotificationState>,
candidate: NotificationCandidate,
) -> Result<(), &'static str> {
- guard(&window)?;
- if !candidate.valid() {
+ let diagnostics = notification_diagnostics_enabled(window.app_handle());
+ let guarded = guard(&window);
+ notification_diagnostic!(
+ diagnostics,
+ "native.show.guard",
+ serde_json::json!({"result": guarded})
+ );
+ guarded?;
+ let valid = candidate.valid();
+ notification_diagnostic!(
+ diagnostics,
+ "native.show.payload",
+ serde_json::json!({"valid": valid})
+ );
+ if !valid {
return Err("notification_invalid");
}
- let Some(notification_id) = state.transact(|record| Ok(record.claim(&candidate)))? else {
+ let claimed = state.transact(|record| Ok(record.claim(&candidate)));
+ notification_diagnostic!(
+ diagnostics,
+ "native.show.claim",
+ serde_json::json!({
+ "viewerUserId": candidate.viewer_user_id, "target": candidate.target, "result": claimed
+ })
+ );
+ let Some(notification_id) = claimed? else {
return Ok(());
};
- if display_notification(
+ let displayed = display_notification(
window.app_handle(),
&notification_id,
&candidate.title,
&candidate.body,
)
- .await
- .is_err()
- {
- state.transact(|record| {
+ .await;
+ notification_diagnostic!(
+ diagnostics,
+ "native.show.return",
+ serde_json::json!({
+ "notificationId": notification_id, "result": displayed
+ })
+ );
+ if displayed.is_err() {
+ let rolled_back = state.transact(|record| {
record.rollback(&notification_id);
Ok(())
- })?;
+ });
+ notification_diagnostic!(
+ diagnostics,
+ "native.show.rollback",
+ serde_json::json!({
+ "notificationId": notification_id, "result": rolled_back
+ })
+ );
+ rolled_back?;
return Err("notification_unavailable");
}
#[cfg(any(windows, target_os = "linux"))]
@@ -601,17 +791,38 @@ pub async fn desktop_system_notification_dismiss(
state: tauri::State<'_, DesktopSystemNotificationState>,
notification_id: String,
) -> Result<(), &'static str> {
- guard(&window)?;
- if !valid_notification_id(&notification_id) {
+ let diagnostics = notification_diagnostics_enabled(window.app_handle());
+ let guarded = guard(&window);
+ notification_diagnostic!(
+ diagnostics,
+ "native.id.guard",
+ serde_json::json!({
+ "notificationId": notification_id, "result": guarded
+ })
+ );
+ guarded?;
+ let valid = valid_notification_id(&notification_id);
+ notification_diagnostic!(
+ diagnostics,
+ "native.id.payload",
+ serde_json::json!({"valid": valid})
+ );
+ if !valid {
return Err("notification_invalid");
}
- dismiss_notifications_confirmed(&[notification_id.clone()])
+ dismiss_notifications_confirmed(&[notification_id.clone()], diagnostics)
.await
.map_err(|_| "notification_unavailable")?;
- state.transact(|record| {
+ let completed = state.transact(|record| {
record.complete_dismissals(&[notification_id]);
Ok(())
- })
+ });
+ notification_diagnostic!(
+ diagnostics,
+ "native.id.transact",
+ serde_json::json!({"result": completed})
+ );
+ completed
}
#[tauri::command]
@@ -621,34 +832,132 @@ pub async fn desktop_system_notification_dismiss_conversation(
viewer_user_id: String,
target: NotificationConversation,
) -> Result<(), &'static str> {
- guard(&window)?;
- if !valid_id(&viewer_user_id) || !target.valid() {
+ let diagnostics = notification_diagnostics_enabled(window.app_handle());
+ let guarded = guard(&window);
+ notification_diagnostic!(
+ diagnostics,
+ "native.conversation.guard",
+ serde_json::json!({
+ "viewerUserId": viewer_user_id, "target": target, "result": guarded
+ })
+ );
+ guarded?;
+ let valid = valid_id(&viewer_user_id) && target.valid();
+ notification_diagnostic!(
+ diagnostics,
+ "native.conversation.payload",
+ serde_json::json!({"valid": valid})
+ );
+ if !valid {
return Err("notification_invalid");
}
- let notification_ids = state
- .record
- .lock()
- .map_err(|_| "store_unavailable")?
- .notification_ids(&viewer_user_id, &target);
+ let notification_ids = {
+ let record = state.record.lock().map_err(|_| "store_unavailable")?;
+ let ids = record.notification_ids(&viewer_user_id, &target);
+ notification_diagnostic!(
+ diagnostics,
+ "native.conversation.mapping",
+ serde_json::json!({
+ "matchingRecords": record.recent.iter().filter(|item| item.viewer_user_id == viewer_user_id
+ && target.matches(&item.target)).collect::<Vec<_>>()
+ })
+ );
+ ids
+ };
+ notification_diagnostic!(
+ diagnostics,
+ "native.conversation.select",
+ serde_json::json!({
+ "viewerUserId": viewer_user_id, "target": target, "notificationIds": notification_ids
+ })
+ );
if notification_ids.is_empty() {
return Ok(());
}
- dismiss_notifications_confirmed(&notification_ids)
+ dismiss_notifications_confirmed(&notification_ids, diagnostics)
.await
.map_err(|_| "notification_unavailable")?;
- state.transact(|record| {
+ let completed = state.transact(|record| {
record.complete_dismissals(&notification_ids);
Ok(())
- })
+ });
+ notification_diagnostic!(
+ diagnostics,
+ "native.conversation.transact",
+ serde_json::json!({
+ "notificationIds": notification_ids, "result": completed
+ })
+ );
+ completed
}
#[cfg(target_os = "macos")]
-async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<(), ()> {
+async fn notification_diagnostic_pending(stage: &'static str) {
+ use block2::RcBlock;
+ use objc2_foundation::NSArray;
+ use objc2_user_notifications::{UNNotificationRequest, UNUserNotificationCenter};
+ use std::ptr::NonNull;
+
+ let receiver = {
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let completion = RcBlock::new(move |requests: NonNull<NSArray<UNNotificationRequest>>| {
+ let ids = unsafe { requests.as_ref() }
+ .iter()
+ .map(|request| request.identifier().to_string())
+ .collect::<Vec<_>>();
+ notification_diagnostic!(true, stage, serde_json::json!({"pendingIds": ids}));
+ let _ = sender.send(Ok(()));
+ });
+ UNUserNotificationCenter::currentNotificationCenter()
+ .getPendingNotificationRequestsWithCompletionHandler(&completion);
+ receiver
+ };
+ let result = wait_for_macos_completion(receiver).await;
+ notification_diagnostic!(
+ true,
+ "os.pending.wait",
+ serde_json::json!({"stage": stage, "result": result})
+ );
+}
+
+#[cfg(target_os = "macos")]
+async fn dismiss_notifications_confirmed(
+ notification_ids: &[String],
+ diagnostics: bool,
+) -> Result<(), ()> {
use block2::RcBlock;
use objc2_foundation::{NSArray, NSString};
use objc2_user_notifications::{UNNotification, UNUserNotificationCenter};
use std::ptr::NonNull;
+ if diagnostics {
+ notification_diagnostic_pending("os.pending.before").await;
+ let receiver = {
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let completion =
+ RcBlock::new(move |notifications: NonNull<NSArray<UNNotification>>| {
+ let ids = unsafe { notifications.as_ref() }
+ .iter()
+ .map(|notification| notification.request().identifier().to_string())
+ .collect::<Vec<_>>();
+ notification_diagnostic!(
+ true,
+ "os.delivered.before",
+ serde_json::json!({"deliveredIds": ids})
+ );
+ let _ = sender.send(Ok(()));
+ });
+ UNUserNotificationCenter::currentNotificationCenter()
+ .getDeliveredNotificationsWithCompletionHandler(&completion);
+ receiver
+ };
+ let result = wait_for_macos_completion(receiver).await;
+ notification_diagnostic!(
+ true,
+ "os.delivered.before.wait",
+ serde_json::json!({"result": result})
+ );
+ }
let receiver = {
let identifiers = notification_ids
.iter()
@@ -656,6 +965,11 @@ async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<
.collect::<Vec<_>>();
let identifier_refs = identifiers.iter().map(|value| &**value).collect::<Vec<_>>();
let center = UNUserNotificationCenter::currentNotificationCenter();
+ notification_diagnostic!(
+ diagnostics,
+ "os.removeDelivered.call",
+ serde_json::json!({"notificationIds": notification_ids})
+ );
center.removeDeliveredNotificationsWithIdentifiers(&NSArray::from_slice(&identifier_refs));
let requested = notification_ids.to_vec();
let (sender, receiver) = std::sync::mpsc::channel();
@@ -664,16 +978,36 @@ async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<
let remains = notifications.iter().any(|notification| {
requested.contains(&notification.request().identifier().to_string())
});
+ notification_diagnostic!(
+ diagnostics,
+ "os.delivered.originalCallback",
+ serde_json::json!({
+ "requestedIds": requested, "remains": remains,
+ "deliveredIds": notifications.iter().map(|notification| notification.request().identifier().to_string()).collect::<Vec<_>>()
+ })
+ );
let _ = sender.send(if remains { Err(()) } else { Ok(()) });
});
center.getDeliveredNotificationsWithCompletionHandler(&completion);
receiver
};
- wait_for_macos_completion(receiver).await
+ let result = wait_for_macos_completion(receiver).await;
+ notification_diagnostic!(
+ diagnostics,
+ "native.dismiss.originalResult",
+ serde_json::json!({"notificationIds": notification_ids, "result": result})
+ );
+ if diagnostics {
+ notification_diagnostic_pending("os.pending.after").await;
+ }
+ result
}
#[cfg(windows)]
-async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<(), ()> {
+async fn dismiss_notifications_confirmed(
+ notification_ids: &[String],
+ _diagnostics: bool,
+) -> Result<(), ()> {
use windows::core::HSTRING;
use windows::UI::Notifications::ToastNotificationManager;
@@ -702,13 +1036,16 @@ async fn dismiss_notifications_confirmed(notification_ids: &[String]) -> Result<
}
#[cfg(target_os = "linux")]
-async fn dismiss_notifications_confirmed(_notification_ids: &[String]) -> Result<(), ()> {
+async fn dismiss_notifications_confirmed(
+ _notification_ids: &[String],
+ _diagnostics: bool,
+) -> Result<(), ()> {
Err(())
}
#[cfg(target_os = "macos")]
async fn display_notification(
- _app: &AppHandle,
+ app: &AppHandle,
notification_id: &str,
title: &str,
body: &str,
@@ -736,7 +1073,14 @@ async fn display_notification(
);
receiver
};
- wait_for_macos_completion(authorization).await?;
+ let authorized = wait_for_macos_completion(authorization).await;
+ let diagnostics = notification_diagnostics_enabled(app);
+ notification_diagnostic!(
+ diagnostics,
+ "os.add.authorization",
+ serde_json::json!({"notificationId": notification_id, "result": authorized})
+ );
+ authorized?;
let scheduled = {
let center = UNUserNotificationCenter::currentNotificationCenter();
@@ -750,7 +1094,13 @@ async fn display_notification(
None,
);
let (sender, receiver) = std::sync::mpsc::channel();
+ let id = notification_id.to_string();
let completion = RcBlock::new(move |error: *mut NSError| {
+ notification_diagnostic!(
+ diagnostics,
+ "os.add.originalCallback",
+ serde_json::json!({"notificationId": id, "hasError": !error.is_null()})
+ );
let _ = sender.send(macos_add_result(!error.is_null()));
});
center.addNotificationRequest_withCompletionHandler(&request, Some(&completion));
@@ -1088,6 +1438,63 @@ async fn display_notification(
mod tests {
use super::*;
+ #[test]
+ fn startup_url_removes_credentials_query_and_fragment() {
+ for input in [
+ "https://user:[email protected]:8443/c/invite?token=secret#private",
+ "https://[email protected]:8443/c/invite?token=secret#private",
+ "https://:[email protected]:8443/c/invite?token=secret#private",
+ ] {
+ assert_eq!(
+ sanitized_startup_url(url::Url::parse(input).unwrap()),
+ Ok("https://example.com:8443/c/invite".into())
+ );
+ }
+ }
+
+ #[test]
+ fn startup_url_preserves_actual_origin_port_and_path() {
+ for (input, expected) in [
+ (
+ "alook-recovery://localhost/bootstrap?private=value#fragment",
+ "alook-recovery://localhost/bootstrap",
+ ),
+ (
+ "http://localhost:5173/sign-in?redirect=%2Fc#fragment",
+ "http://localhost:5173/sign-in",
+ ),
+ ("about:blank?private=value#fragment", "about:blank"),
+ (
+ "file:///actual/bootstrap.html",
+ "file:///actual/bootstrap.html",
+ ),
+ ] {
+ assert_eq!(
+ sanitized_startup_url(url::Url::parse(input).unwrap()),
+ Ok(expected.into())
+ );
+ }
+ }
+
+ #[test]
+ fn notification_diagnostics_require_the_exact_qa_identity_and_switch() {
+ let qa = "ai.alook.desktop.qa.madox.notification208";
+ assert!(notification_diagnostic_identity_allowed(qa, Some("208")));
+ for switch in [Some("208 "), Some("0208"), Some("1"), Some(""), None] {
+ assert!(!notification_diagnostic_identity_allowed(qa, switch));
+ }
+ for identifier in [
+ "ai.alook.desktop",
+ "ai.alook.desktop.qa.madox.notification208.extra",
+ "",
+ ] {
+ assert!(!notification_diagnostic_identity_allowed(
+ identifier,
+ Some("208")
+ ));
+ }
+ }
+
fn target(message_id: &str) -> NotificationTarget {
NotificationTarget::Server {
server_id: "server_1".into(),
diff --git a/src/desktop/src-tauri/src/webview_recovery.rs b/src/desktop/src-tauri/src/webview_recovery.rs
index ea6ad0795..b0a171163 100644
--- a/src/desktop/src-tauri/src/webview_recovery.rs
+++ b/src/desktop/src-tauri/src/webview_recovery.rs
@@ -204,13 +204,70 @@ fn windows_recovers(error_code: i32) -> bool {
pub fn finish_native_creation(window: &tauri::WebviewWindow) {
let ready_window = window.clone();
let error_window = window.clone();
- if let Err(error) = window.with_webview(move |platform| {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ let (diagnostic_sender, diagnostic_receiver) =
+ if crate::system_notifications::notification_diagnostics_enabled(window.app_handle()) {
+ let (sender, receiver) = std::sync::mpsc::channel();
+ (Some((sender, std::thread::current().id())), Some(receiver))
+ } else {
+ (None, None)
+ };
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ crate::system_notifications::diagnose_qa_startup(
+ window.app_handle(),
+ "handoff_call",
+ window.label(),
+ serde_json::json!({ "status": "call" }),
+ );
+ let dispatched = window.with_webview(move |platform| {
#[cfg(desktop)]
{
let _ = platform;
- if !crate::commands::finish_native_startup(ready_window.app_handle()) {
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if let Some((_, calling_thread)) = &diagnostic_sender {
+ let callback_thread = std::thread::current().id();
+ crate::system_notifications::diagnose_qa_startup(
+ ready_window.app_handle(),
+ "callback_enter",
+ ready_window.label(),
+ serde_json::json!({
+ "status": "entered",
+ "callingThread": format!("{calling_thread:?}"),
+ "callbackThread": format!("{callback_thread:?}"),
+ "dispatchMode": if *calling_thread == callback_thread { "inline" } else { "queued" },
+ }),
+ );
+ }
+ let mut shown_main = None;
+ let capture = crate::system_notifications::notification_diagnostics_enabled(
+ ready_window.app_handle(),
+ )
+ .then_some(&mut shown_main);
+ let completed =
+ crate::commands::finish_native_startup(ready_window.app_handle(), capture);
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ crate::system_notifications::diagnose_qa_startup(
+ ready_window.app_handle(),
+ "handoff_return",
+ ready_window.label(),
+ serde_json::json!({ "completed": completed, "snapshot": if completed && shown_main.is_some() { "eligible" } else { "not_run" } }),
+ );
+ if !completed {
eprintln!("native WebView startup handoff unavailable");
}
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if let Some((sender, _)) = diagnostic_sender {
+ let sent = sender.send((completed, shown_main));
+ crate::system_notifications::diagnose_qa_startup(
+ ready_window.app_handle(),
+ "handoff_result_send_return",
+ ready_window.label(),
+ serde_json::json!({
+ "status": if sent.is_ok() { "sent" } else { "receiver_dropped" },
+ "callbackCompletion": "not_inferred",
+ }),
+ );
+ }
}
#[cfg(target_os = "ios")]
unsafe {
@@ -234,7 +291,36 @@ pub fn finish_native_creation(window: &tauri::WebviewWindow) {
show_native_creation_error();
}
}
- }) {
+ });
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ crate::system_notifications::diagnose_qa_startup(
+ window.app_handle(),
+ "handoff_dispatch_return",
+ window.label(),
+ serde_json::json!({ "status": if dispatched.is_ok() { "ok" } else { "error" }, "error": dispatched.as_ref().err().map(ToString::to_string), "callbackCompletion": "not_inferred" }),
+ );
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ if let Some(receiver) = diagnostic_receiver {
+ let snapshot = qa_startup_snapshot_candidate(dispatched.is_ok(), receiver.try_recv());
+ match snapshot {
+ Ok(main) => {
+ crate::system_notifications::diagnose_qa_startup(
+ window.app_handle(),
+ "main_snapshot_begin",
+ main.label(),
+ serde_json::json!({ "handoffResult": "completed_with_shown_main", "callbackCompletion": "not_inferred" }),
+ );
+ crate::system_notifications::diagnose_qa_main_snapshot(&main);
+ }
+ Err(reason) => crate::system_notifications::diagnose_qa_startup(
+ window.app_handle(),
+ "main_snapshot_not_run",
+ window.label(),
+ serde_json::json!({ "reason": reason, "callbackCompletion": "not_inferred" }),
+ ),
+ }
+ }
+ if let Err(error) = dispatched {
eprintln!("native WebView startup callback unavailable: {error}");
#[cfg(target_os = "macos")]
crate::commands::show_startup_initialization_error(error_window.app_handle());
@@ -247,6 +333,22 @@ pub fn finish_native_creation(window: &tauri::WebviewWindow) {
}
}
+#[cfg(all(target_os = "macos", debug_assertions))]
+fn qa_startup_snapshot_candidate<T>(
+ dispatched: bool,
+ received: Result<(bool, Option<T>), std::sync::mpsc::TryRecvError>,
+) -> Result<T, &'static str> {
+ if !dispatched {
+ return Err("dispatch_error");
+ }
+ match received {
+ Ok((true, Some(main))) => Ok(main),
+ Ok(_) => Err("handoff_not_eligible"),
+ Err(std::sync::mpsc::TryRecvError::Empty) => Err("handoff_result_pending"),
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("handoff_result_unavailable"),
+ }
+}
+
#[cfg(any(target_os = "ios", all(test, target_os = "macos")))]
fn apple_class_method(
name: &std::ffi::CStr,
@@ -907,6 +1009,58 @@ mod tests {
use super::*;
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_snapshot_requires_successful_dispatch_and_completed_shown_main() {
+ assert_eq!(
+ qa_startup_snapshot_candidate(true, Ok((true, Some(7)))),
+ Ok(7)
+ );
+ for result in [Ok((false, Some(7))), Ok((true, None)), Ok((false, None))] {
+ assert_eq!(
+ qa_startup_snapshot_candidate(true, result),
+ Err("handoff_not_eligible")
+ );
+ }
+ for result in [
+ Ok((true, Some(7))),
+ Err(std::sync::mpsc::TryRecvError::Empty),
+ Err(std::sync::mpsc::TryRecvError::Disconnected),
+ ] {
+ assert_eq!(
+ qa_startup_snapshot_candidate(false, result),
+ Err("dispatch_error")
+ );
+ }
+ }
+
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_snapshot_pending_and_disconnected_results_are_explicitly_not_run() {
+ let (sender, receiver) = std::sync::mpsc::channel::<(bool, Option<u8>)>();
+ assert_eq!(
+ qa_startup_snapshot_candidate(true, receiver.try_recv()),
+ Err("handoff_result_pending")
+ );
+ drop(sender);
+ assert_eq!(
+ qa_startup_snapshot_candidate(true, receiver.try_recv()),
+ Err("handoff_result_unavailable")
+ );
+ }
+
+ #[cfg(all(target_os = "macos", debug_assertions))]
+ #[test]
+ fn qa_snapshot_accepts_available_result_without_requiring_sender_completion() {
+ let (sender, receiver) = std::sync::mpsc::channel();
+ sender.send((true, Some(7))).unwrap();
+ assert_eq!(
+ qa_startup_snapshot_candidate(true, receiver.try_recv()),
+ Ok(7)
+ );
+ sender.send((false, None)).unwrap();
+ }
+
#[cfg(target_os = "macos")]
#[test]
fn apple_class_method_finds_registered_class_selector() {
@@ -1458,8 +1612,8 @@ mod tests {
assert_order(
commands,
&[
- "if let Err(error) = main.show()",
- "if let Err(error) = splash.close()",
+ "let shown = main.show()",
+ "let closed = splash.close()",
"SPLASH_CLOSED.store(true",
],
);
diff --git a/src/web/src/components/home/landing-shell-motion-lifetime.dom.test.ts b/src/web/src/components/home/landing-shell-motion-lifetime.dom.test.ts
new file mode 100644
index 000000000..a74cf3c40
--- /dev/null
+++ b/src/web/src/components/home/landing-shell-motion-lifetime.dom.test.ts
@@ -0,0 +1,111 @@
+import React, { createElement, type ReactNode } from "react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render, waitFor, type RenderResult } from "@/test/react-dom-harness"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+
+const observed = vi.hoisted(() => ({
+ owners: [] as Array<{ registry: CommunityDbRegistry; used: () => boolean }>,
+}))
+
+vi.mock("@/lib/community-db/collections", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/lib/community-db/collections")>()
+ return {
+ ...original,
+ createCommunityDbRegistry: (...args: Parameters<typeof original.createCommunityDbRegistry>) => {
+ const registry = original.createCommunityDbRegistry(...args)
+ if (!observed.owners.some((owner) => owner.registry === registry)) {
+ const collections = vi.spyOn(registry.dbClient, "collection")
+ observed.owners.push({ registry, used: () => collections.mock.calls.some(([options]) => options.id.startsWith("community-live:")) })
+ }
+ return registry
+ },
+ }
+})
+
+vi.mock("./landing-shell-motion.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
+
+import { LandingMobileChatMotion, LandingShellMotion } from "./landing-shell-motion"
+
+const mounted: RenderResult[] = []
+
+function mountPreview(kind: "desktop" | "mobile", beat: number) {
+ const view = render(preview(kind, beat))
+ mounted.push(view)
+ return view
+}
+
+class PreviewBoundary extends React.Component<{ children?: ReactNode }, { error: Error | null }> {
+ state = { error: null as Error | null }
+ static getDerivedStateFromError(error: Error) { return { error } }
+ render() {
+ return this.state.error
+ ? createElement("div", { "data-testid": "preview-error" }, this.state.error.message)
+ : this.props.children
+ }
+}
+
+function preview(kind: "desktop" | "mobile", beat: number) {
+ return createElement(React.StrictMode, null,
+ createElement(PreviewBoundary, null,
+ kind === "desktop"
+ ? createElement(LandingShellMotion, { scene: "server", beat })
+ : createElement(LandingMobileChatMotion, { beat })))
+}
+
+beforeEach(() => {
+ observed.owners.length = 0
+ mounted.length = 0
+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} })
+ vi.stubGlobal("IntersectionObserver", class { observe() {} unobserve() {} disconnect() {} })
+ vi.stubGlobal("matchMedia", () => ({
+ matches: false, media: "", onchange: null,
+ addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {}, dispatchEvent: () => true,
+ }))
+})
+
+afterEach(async () => {
+ for (const view of mounted) view.unmount()
+ for (const { registry } of observed.owners) {
+ await registry.cleanup()
+ registry.queryClient.clear()
+ }
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe("landing preview Collection lifetime", () => {
+ it.each(["desktop", "mobile"] as const)("keeps the actual %s consumers live through StrictMode effect replay and retires on unmount", async (kind) => {
+ const view = mountPreview(kind, 0)
+ await act(async () => { await Promise.resolve(); await new Promise((resolve) => setTimeout(resolve, 10)) })
+ view.rerender(preview(kind, 6))
+ await act(async () => { await Promise.resolve(); await new Promise((resolve) => setTimeout(resolve, 10)) })
+ expect(view.queryByTestId("preview-error")).toBeNull()
+ const used = observed.owners.filter((owner) => owner.used())
+ expect(used).toHaveLength(1)
+ expect(used[0]!.registry.runtime.lifecycle.get().active).toBe(true)
+ expect(view.container.textContent).toContain("Gus")
+ view.unmount()
+ await waitFor(() => expect(used[0]!.registry.runtime.lifecycle.get().active).toBe(false))
+ await waitFor(() => expect(used[0]!.registry.collections.profiles.status).toBe("cleaned-up"))
+ })
+
+ it("does not retire a separate surviving preview owner", async () => {
+ const first = mountPreview("desktop", 0)
+ const survivor = mountPreview("mobile", 0)
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)) })
+ first.unmount()
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)) })
+ survivor.rerender(preview("mobile", 6))
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)) })
+ expect(survivor.queryByTestId("preview-error")).toBeNull()
+ const used = observed.owners.filter((owner) => owner.used())
+ expect(used).toHaveLength(2)
+ expect(used[0]!.registry.runtime.lifecycle.get().active).toBe(false)
+ expect(used[1]!.registry.runtime.lifecycle.get().active).toBe(true)
+ expect(survivor.container.textContent).toContain("Gus")
+ survivor.unmount()
+ await waitFor(() => expect(used[1]!.registry.runtime.lifecycle.get().active).toBe(false))
+ })
+})
diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsx
index 59675358b..ebaeac055 100644
--- a/src/web/src/components/home/landing-shell-motion.tsx
+++ b/src/web/src/components/home/landing-shell-motion.tsx
@@ -11,7 +11,7 @@ import {
type RefObject,
} from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
-import { createCommunityDbRegistry } from "@/lib/community-db/collections"
+import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import {
Activity,
@@ -632,6 +632,22 @@ function useVisualFocus(scene: LandingScene, focus: string | null) {
return visualFocus
}
+function usePreviewDbLifetime(registry: CommunityDbRegistry, queryClient: QueryClient) {
+ const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ useEffect(() => {
+ if (disposeTimer.current !== null) {
+ clearTimeout(disposeTimer.current)
+ disposeTimer.current = null
+ }
+ return () => {
+ disposeTimer.current = setTimeout(() => {
+ disposeTimer.current = null
+ void registry.cleanup().finally(() => queryClient.clear())
+ }, 0)
+ }
+ }, [registry, queryClient])
+}
+
export function LandingShellMotion({
scene,
machineIntroDescription,
@@ -657,7 +673,7 @@ export function LandingShellMotion({
() => new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } }),
)
const [registry] = useState(() => createCommunityDbRegistry(queryClient, null))
- useEffect(() => () => { void registry.cleanup().finally(() => queryClient.clear()) }, [registry, queryClient])
+ usePreviewDbLifetime(registry, queryClient)
const maxBeat = SCENE_MAX_BEAT[scene]
const beat = controlledBeat ?? localBeat
@@ -769,7 +785,7 @@ export function LandingMobileChatMotion({ beat }: { beat: number }) {
() => new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } }),
)
const [registry] = useState(() => createCommunityDbRegistry(queryClient, null))
- useEffect(() => () => { void registry.cleanup().finally(() => queryClient.clear()) }, [registry, queryClient])
+ usePreviewDbLifetime(registry, queryClient)
useEffect(() => {
const stage = stageRef.current
diff --git a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts
index 5a8d6fda4..81b700202 100644
--- a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts
+++ b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { createElement, type PropsWithChildren } from "react"
+import { createElement, useLayoutEffect, type PropsWithChildren } from "react"
import { act, waitFor, renderHook as renderOwnedHook } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -115,7 +115,7 @@ beforeEach(()=>{
hookMocks.mobileDismissConversation.mockResolvedValue(undefined)
vi.spyOn(document,"visibilityState","get").mockReturnValue("visible")
})
-afterEach(()=>{window.localStorage.clear();window.sessionStorage.clear();vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals()})
+afterEach(()=>{window.localStorage.clear();window.sessionStorage.clear();vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();vi.unstubAllEnvs()})
describe("notification activation",()=>{
it("queues and navigates immediately without starting a HTTP precheck",async()=>{
const fetch=vi.fn(()=>new Promise<Response>(()=>undefined));vi.stubGlobal("fetch",fetch)
@@ -229,13 +229,24 @@ describe("current native conversation",()=>{
await waitFor(()=>expect(window.localStorage.length).toBe(0));rendered.unmount()
})
it("keeps a failed revision until a new wake and has no retry timer",async()=>{
+ vi.stubEnv("NODE_ENV", "development");vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ const log=vi.spyOn(console,"info").mockImplementation(()=>undefined)
let wake!:()=>void;hookMocks.listen.mockImplementation(async cb=>{wake=cb;return()=>undefined})
hookMocks.dismissConversation.mockRejectedValueOnce(new Error("native unavailable"))
const rendered=renderHook(()=>useCurrent(),{wrapper})
await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledOnce())
await act(async()=>{await Promise.resolve()});expect(window.localStorage.length).toBe(1)
+ const events=()=>log.mock.calls.map(([,raw])=>JSON.parse(raw as string))
+ const retained=events().find(event=>event.stage==="queue.retained")
+ expect(retained.data).toMatchObject({viewerUserId:"viewer",target,sourceRetired:false})
+ const pending=JSON.parse(window.localStorage.getItem("alook:native-system-notification:conversation-dismissals")!)
+ expect(retained.data.revision).toBe(pending[0].revision)
+ expect(events().find(event=>event.stage==="ready.matches").data).toMatchObject({matches:true,intentCurrent:true,navigationPending:false,visibility:"visible"})
act(()=>wake());await waitFor(()=>expect(hookMocks.dismissConversation).toHaveBeenCalledTimes(2))
- await waitFor(()=>expect(window.localStorage.length).toBe(0));rendered.unmount()
+ await waitFor(()=>expect(window.localStorage.length).toBe(0))
+ expect(events().filter(event=>event.stage==="queue.complete")).toHaveLength(1)
+ expect(events().find(event=>event.stage==="queue.complete").data.completed).toBe(true)
+ rendered.unmount()
})
it("authorizes presentation synchronously without queue or native side effects",async()=>{
const rendered=renderHook(()=>useCurrent(),{wrapper})
@@ -251,7 +262,52 @@ describe("current native conversation",()=>{
expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBe(false)
rendered.unmount();expect(presentation({viewerUserId:"viewer",targetId:"channel_1"})).toBeUndefined()
})
+ it("rejects presentation after readiness retires and before passive consumer cleanup", async () => {
+ vi.stubEnv("NODE_ENV", "development")
+ vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ const log = vi.spyOn(console, "info").mockImplementation(() => undefined)
+ const identity = { viewerUserId: "viewer", targetId: "channel_1" }
+ const probes: { consumerPresent: boolean; authorized: boolean | undefined }[] = []
+ const nativeCalls = () => ({
+ take: hookMocks.take.mock.calls.length,
+ dismiss: hookMocks.dismiss.mock.calls.length,
+ conversation: hookMocks.dismissConversation.mock.calls.length,
+ })
+ const rendered = renderHook(({ ready }) => {
+ useCurrent(ready)
+ useLayoutEffect(() => {
+ if (!ready) {
+ probes.push({
+ consumerPresent: consumer.current !== null,
+ authorized: presentation(identity),
+ })
+ }
+ }, [ready])
+ }, { wrapper, initialProps: { ready: true } })
+ await waitFor(() => expect(hookMocks.dismissConversation).toHaveBeenCalledOnce())
+ await waitFor(() => expect(window.localStorage.length).toBe(0))
+ expect(presentation(identity)).toBe(true)
+ const before = nativeCalls()
+
+ rendered.rerender({ ready: false })
+
+ expect(probes).toEqual([{ consumerPresent: true, authorized: false }])
+ const retired = log.mock.calls
+ .filter(([prefix]) => prefix === "ALOOK208")
+ .map(([, raw]) => JSON.parse(raw as string))
+ .filter((event) => event.stage === "ready.retired")
+ expect(retired).toHaveLength(1)
+ expect(retired[0].data).toEqual({ viewerUserId: "viewer", dismissalTarget: target })
+ expect(nativeCalls()).toEqual(before)
+ expect(window.localStorage.length).toBe(0)
+ expect(consumer.current).toBeNull()
+ expect(presentation(identity)).toBe(false)
+ rendered.unmount()
+ expect(presentation(identity)).toBeUndefined()
+ })
it.each(["not ready","hidden","pending elsewhere","parent split"])("does not consume %s",async state=>{
+ vi.stubEnv("NODE_ENV", "development");vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ vi.spyOn(console,"info").mockImplementation(()=>undefined)
if(state==="hidden") vi.spyOn(document,"visibilityState","get").mockReturnValue("hidden")
if(state==="pending elsewhere") setRoute("/c/channels/server_1/channel_1",true)
if(state==="parent split") setRoute("/c/channels/server_1/channel_2")
diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.ts
index 0009c3c3f..f2336f237 100644
--- a/src/web/src/hooks/community/use-native-system-notifications.ts
+++ b/src/web/src/hooks/community/use-native-system-notifications.ts
@@ -14,6 +14,7 @@ import {
dismissDesktopSystemNotificationConversation,
listenDesktopSystemNotificationActivations,
takeDesktopSystemNotificationActivation,
+ traceNotificationDiagnostic,
} from "@/lib/community/desktop-system-notification"
import {
systemNotificationHref,
@@ -99,12 +100,19 @@ function drainNativeSystemNotificationConversationDismissals(
) {
for (const { target, revision } of queue.pending(platform, viewerUserId)) {
const key = ["community", "native-conversation-dismiss", platform, viewerUserId, conversationKey(target)]
- if (client.getMutationCache().findAll({ mutationKey: key, status: "pending" }).length) continue
+ const pendingMutations = client.getMutationCache().findAll({ mutationKey: key, status: "pending" }).length
+ traceNotificationDiagnostic("queue.drain", { platform, viewerUserId, target, revision, pendingMutations })
+ if (pendingMutations) continue
void nativeCommand(client, key, original, async () => {
await dismissNativeSystemNotificationConversation(platform, viewerUserId, target)
original()
- queue.complete(platform, viewerUserId, target, revision)
- }).catch(() => undefined).finally(() => {
+ const completed = queue.complete(platform, viewerUserId, target, revision)
+ traceNotificationDiagnostic("queue.complete", { platform, viewerUserId, target, revision, completed })
+ }).catch((error: unknown) => {
+ traceNotificationDiagnostic("queue.retained", { platform, viewerUserId, target, revision,
+ sourceRetired: original.signal.aborted, errorType: typeof error,
+ nativeError: typeof error === "string" ? error : null })
+ }).finally(() => {
try { original() } catch { return }
if (queue.pending(platform, viewerUserId).some((entry) => conversationKey(entry.target) === conversationKey(target) && entry.revision !== revision)) {
drainNativeSystemNotificationConversationDismissals(platform, viewerUserId, queue, client, original)
@@ -128,6 +136,9 @@ export function useNativeSystemNotificationConversationDismissal(
const channelId = target.channelId
const serverId = target.kind === "server" ? target.serverId : undefined
useEffect(() => {
+ traceNotificationDiagnostic("ready.effect", { viewerUserId, kind, serverId, channelId, ready,
+ frame: current.current.frame, publishedHref: current.current.navigation.publishedHref,
+ navigationPending: current.current.navigation.navigationPending, visibility: document.visibilityState })
if (!ready || (!isDesktop() && !isMobile())) return
const platform = isDesktop() ? "desktop" : "mobile"
const dismissalTarget: NativeSystemNotificationConversation = kind === "server"
@@ -141,16 +152,26 @@ export function useNativeSystemNotificationConversationDismissal(
const intent = captureIntent()
const consumer: NativeNotificationConversationConsumer = {
matches: (viewer, targetId) => {
- try { original() } catch { return false }
+ try { original() } catch {
+ traceNotificationDiagnostic("ready.retired", { viewerUserId, dismissalTarget })
+ return false
+ }
const route = current.current
- return viewer === viewerUserId && targetId === channelId && intent()
+ let intentCurrent: boolean | undefined
+ const matches = viewer === viewerUserId && targetId === channelId && (intentCurrent = intent())
&& document.visibilityState === "visible" && !route.navigation.navigationPending
&& route.frame.pathname === systemNotificationHref(dismissalTarget)
&& normalizeCommunityHref(route.navigation.publishedHref).pathname === route.frame.pathname
+ traceNotificationDiagnostic("ready.matches", { viewerUserId, viewer, targetId, dismissalTarget,
+ sourceCurrent: true, intentCurrent: intentCurrent ?? null, matches,
+ frame: route.frame, publishedHref: route.navigation.publishedHref,
+ navigationPending: route.navigation.navigationPending, visibility: document.visibilityState })
+ return matches
},
requestDismiss: () => {
if (!consumer.matches(viewerUserId, channelId)) return
- queue.queue(platform, viewerUserId, dismissalTarget)
+ const queued = queue.queue(platform, viewerUserId, dismissalTarget)
+ traceNotificationDiagnostic("queue.write", { platform, viewerUserId, dismissalTarget, queued })
drainNativeSystemNotificationConversationDismissals(platform, viewerUserId, queue, client, original)
},
}
diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.ts
index 5c3fb13a8..3080e326b 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -11,6 +11,7 @@ import {
resolveDesktopSystemNotificationCandidate,
showDesktopSystemNotification,
takeDesktopSystemNotificationActivation,
+ traceNotificationDiagnostic,
} from "./desktop-system-notification"
const invoke = vi.hoisted(() => vi.fn())
@@ -112,9 +113,68 @@ afterEach(async () => {
for (const owner of owners.splice(0)) { await owner.cleanup(); owner.queryClient.clear() }
desktopMode.value = true
vi.unstubAllGlobals()
+ vi.unstubAllEnvs()
+ vi.restoreAllMocks()
vi.clearAllMocks()
})
+describe("isolated notification diagnostics", () => {
+ it.each([
+ ["test", undefined], ["development", undefined],
+ ["production", "208"], ["development", "other"],
+ ] as const)("does not emit with mode %s and switch %s", async (mode, enabled) => {
+ vi.stubEnv("NODE_ENV", mode)
+ vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", enabled)
+ const log = vi.spyOn(console, "info").mockImplementation(() => undefined)
+ invoke.mockResolvedValueOnce(undefined)
+ await dismissDesktopSystemNotificationConversation("viewer_1", { kind: "dm", channelId: "dm_1" })
+ expect(invoke).toHaveBeenCalledExactlyOnceWith("desktop_system_notification_dismiss_conversation",
+ { viewerUserId: "viewer_1", target: { kind: "dm", channelId: "dm_1" } })
+ expect(log).not.toHaveBeenCalled()
+ })
+
+ it("preserves one invocation and the original rejection object while omitting its contents", async () => {
+ vi.stubEnv("NODE_ENV", "development")
+ vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ const log = vi.spyOn(console, "info").mockImplementation(() => undefined)
+ const failure = new Error("private error payload")
+ invoke.mockRejectedValueOnce(failure)
+ await expect(dismissDesktopSystemNotification("notification_fixture")).rejects.toBe(failure)
+ expect(invoke).toHaveBeenCalledExactlyOnceWith("desktop_system_notification_dismiss",
+ { notificationId: "notification_fixture" })
+ const events = log.mock.calls.map(([, raw]) => JSON.parse(raw as string))
+ expect(events.map(event => event.stage)).toEqual(["invoke.id.start", "invoke.id.error"])
+ expect(events[1].data).toEqual({ notificationId: "notification_fixture", errorType: "object", nativeError: null })
+ expect(JSON.stringify(events)).not.toContain("private error payload")
+ })
+
+ it("records the native error string and keeps its original rejection", async () => {
+ vi.stubEnv("NODE_ENV", "development")
+ vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ const log = vi.spyOn(console, "info").mockImplementation(() => undefined)
+ invoke.mockRejectedValueOnce("notification_unavailable")
+ const target = { kind: "dm" as const, channelId: "dm_1" }
+ await expect(dismissDesktopSystemNotificationConversation("viewer_1", target)).rejects.toBe("notification_unavailable")
+ expect(invoke).toHaveBeenCalledExactlyOnceWith("desktop_system_notification_dismiss_conversation", { viewerUserId: "viewer_1", target })
+ expect(JSON.parse(log.mock.calls[1]![1] as string).data.nativeError).toBe("notification_unavailable")
+ })
+
+ it("keeps success and failure when local logging throws, and emits nothing for mobile", async () => {
+ vi.stubEnv("NODE_ENV", "development")
+ vi.stubEnv("NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS", "208")
+ const log = vi.spyOn(console, "info").mockImplementation(() => { throw new Error("closed logger") })
+ const target = { kind: "dm" as const, channelId: "dm_1" }
+ invoke.mockResolvedValueOnce(undefined).mockRejectedValueOnce("untrusted_caller")
+ await expect(dismissDesktopSystemNotificationConversation("viewer_1", target)).resolves.toBeUndefined()
+ await expect(dismissDesktopSystemNotificationConversation("viewer_1", target)).rejects.toBe("untrusted_caller")
+ expect(invoke).toHaveBeenCalledTimes(2)
+ log.mockClear()
+ desktopMode.value = false
+ traceNotificationDiagnostic("fixture", { viewerUserId: "viewer_1" })
+ expect(log).not.toHaveBeenCalled()
+ })
+})
+
describe("desktop system notification candidates", () => {
it("derives a hygienic server notification from one paired bundle", () => {
expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1", {
diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.ts
index bc21c49cb..2d0b2998f 100644
--- a/src/web/src/lib/community/desktop-system-notification.ts
+++ b/src/web/src/lib/community/desktop-system-notification.ts
@@ -18,6 +18,12 @@ import {
type CommunityUnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>
+export function traceNotificationDiagnostic(stage: string, data: Record<string, unknown>) {
+ if (process.env.NODE_ENV !== "development"
+ || process.env.NEXT_PUBLIC_ALOOK_NOTIFICATION_DIAGNOSTICS !== "208" || !isDesktop()) return
+ try { console.info("ALOOK208", JSON.stringify({ stage, timeMs: Date.now(), data })) } catch {}
+}
+
export type DesktopSystemNotificationCandidate = {
viewerUserId: string
title: string
@@ -166,12 +172,28 @@ export async function takeDesktopSystemNotificationActivation(): Promise<Desktop
}
export async function dismissDesktopSystemNotification(notificationId: string): Promise<void> {
- await tauriInvoke("desktop_system_notification_dismiss", { notificationId })
+ traceNotificationDiagnostic("invoke.id.start", { notificationId })
+ try {
+ await tauriInvoke("desktop_system_notification_dismiss", { notificationId })
+ traceNotificationDiagnostic("invoke.id.ok", { notificationId })
+ } catch (error) {
+ traceNotificationDiagnostic("invoke.id.error", { notificationId, errorType: typeof error,
+ nativeError: typeof error === "string" ? error : null })
+ throw error
+ }
}
export async function dismissDesktopSystemNotificationConversation(
viewerUserId: string,
target: { kind: "server"; serverId: string; channelId: string } | { kind: "dm"; channelId: string },
): Promise<void> {
- await tauriInvoke("desktop_system_notification_dismiss_conversation", { viewerUserId, target })
+ traceNotificationDiagnostic("invoke.conversation.start", { viewerUserId, target })
+ try {
+ await tauriInvoke("desktop_system_notification_dismiss_conversation", { viewerUserId, target })
+ traceNotificationDiagnostic("invoke.conversation.ok", { viewerUserId, target })
+ } catch (error) {
+ traceNotificationDiagnostic("invoke.conversation.error", { viewerUserId, target, errorType: typeof error,
+ nativeError: typeof error === "string" ? error : null })
+ throw error
+ }
}