Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(notifications): clear native alert after route load (#829)

Generf29478da2dad
diff --git a/scripts/ci/mobile-system-notification.test.ts b/scripts/ci/mobile-system-notification.test.ts
index e1438d7c9..e1795d3bd 100644
--- a/scripts/ci/mobile-system-notification.test.ts
+++ b/scripts/ci/mobile-system-notification.test.ts
@@ -25,6 +25,7 @@ const commands = [
"mobile_system_notification_snapshot",
"mobile_system_notification_acknowledge_registration",
"mobile_system_notification_take_activation",
+ "mobile_system_notification_dismiss",
"mobile_system_notification_listen",
"mobile_system_notification_unlisten",
]
@@ -55,6 +56,9 @@ const androidService = readPlugin(
const androidPlugin = readPlugin(
"android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt",
)
+const androidRoute = readPlugin(
+ "android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt",
+)
const iosPlugin = readPlugin("ios/Sources/MobilePushPlugin.swift")
const iosProject = readTauri("gen/apple/project.yml")
const iosEntitlements = readTauri(
@@ -63,7 +67,7 @@ const iosEntitlements = readTauri(
const mobileRelease = readRoot(".github/workflows/mobile-release.yml")
describe("mobile system notification contract", () => {
- it("grants only the guarded seven-command API to trusted mobile WebViews", () => {
+ it("grants only the guarded eight-command API to trusted mobile WebViews", () => {
const expected = {
windows: ["main"],
platforms: ["android", "iOS"],
@@ -108,12 +112,14 @@ describe("mobile system notification contract", () => {
expect(readPlugin("build.rs")).toContain('"snapshot"')
expect(readPlugin("build.rs")).toContain('"acknowledgeRegistration"')
expect(readPlugin("build.rs")).toContain('"takeActivation"')
+ expect(readPlugin("build.rs")).toContain('"dismissNotification"')
const webAdapter = readRoot(
"src/web/src/lib/community/mobile-system-notification.ts",
)
expect(webAdapter).not.toMatch(/(?:localStorage|indexedDB|console\.)/)
expect(webAdapter).toContain('credentials: "same-origin"')
expect(webAdapter).toContain('"mobile_system_notification_acknowledge_registration"')
+ expect(webAdapter).toContain('"mobile_system_notification_dismiss"')
})
it("locks Android FCM delivery, durable state, and credential-free builds", () => {
@@ -140,6 +146,14 @@ describe("mobile system notification contract", () => {
expect(androidService).toContain("FLAG_ACTIVITY_SINGLE_TOP")
expect(androidService).toContain("setContentIntent")
expect(androidPlugin).toContain("override fun onNewIntent")
+ expect(androidRoute).toContain("mobilePushNotificationRequestCode")
+ expect(androidRoute).toContain("MOBILE_PUSH_NOTIFICATION_AUTO_CANCEL = false")
+ expect(androidService).toContain("setAutoCancel(MOBILE_PUSH_NOTIFICATION_AUTO_CANCEL)")
+ expect(androidService).not.toContain("setAutoCancel(true)")
+ expect(androidService).toContain("mobilePushNotificationRequestCode(route.notificationId)")
+ expect(androidService).toContain("mobilePushNotificationAction(packageName, route.notificationId)")
+ expect(androidPlugin).toContain("mobilePushNotificationRequestCode(args.notificationId)")
+ expect(androidPlugin).toContain("cancel(args.notificationId, requestCode)")
})
it("locks iOS APNs callbacks, foreground/tap handling, and production entitlement", () => {
@@ -150,6 +164,9 @@ describe("mobile system notification contract", () => {
expect(iosPlugin).toContain("didReceive response")
expect(iosPlugin).toContain("UIApplication.didBecomeActiveNotification")
expect(iosPlugin).toContain("MobilePushStore")
+ expect(iosPlugin).toContain("removeDeliveredNotifications")
+ expect(iosPlugin).toContain("response.notification.request.identifier")
+ expect(iosPlugin).toContain("takeDeliveredNotificationIdentifier")
expect(iosProject).toContain("aps-environment: $(APS_ENVIRONMENT)")
expect(iosProject).toContain("APS_ENVIRONMENT: development")
expect(iosProject).toContain("APS_ENVIRONMENT: production")
diff --git a/scripts/ci/system-notifications-desktop.test.ts b/scripts/ci/system-notifications-desktop.test.ts
index bc36872dc..b66e5a4f3 100644
--- a/scripts/ci/system-notifications-desktop.test.ts
+++ b/scripts/ci/system-notifications-desktop.test.ts
@@ -14,6 +14,8 @@ const desktopCommands = [
"desktop_system_notification_show",
"desktop_system_notification_listen",
"desktop_system_notification_take_activation",
+ "desktop_system_notification_retry_activation",
+ "desktop_system_notification_dismiss",
"desktop_system_notification_unlisten",
]
@@ -22,7 +24,7 @@ function quotedValues(source: string) {
}
describe("desktop system notification contract", () => {
- it("keeps the build manifest and desktop ACL at the exact old-five plus new-four set", () => {
+ it("keeps the build manifest and desktop ACL at the exact old-five plus notification command set", () => {
const manifestCommands = quotedValues(read("build.rs"))
.filter((command) => !command.startsWith("native_oauth_")
&& !command.startsWith("mobile_share_image_")
@@ -65,6 +67,9 @@ describe("desktop system notification contract", () => {
expect(source).toContain('#[cfg(target_os = "linux")]')
expect(source).toContain('<toast activationType=\\"protocol\\"')
expect(source).toContain("didReceiveNotificationResponse")
+ expect(source).toContain("removeDeliveredNotificationsWithIdentifiers")
+ expect(source).toContain("RemoveGroupedTagWithId")
+ expect(source).toContain("SetTag(&HSTRING::from(notification_id))")
const linux = source.slice(source.lastIndexOf('#[cfg(target_os = "linux")]'))
expect(linux).toContain("show_main_window")
expect(linux).not.toContain("activate(&app")
diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.toml
index 1021b3157..efc2aba6b 100644
--- a/src/desktop/src-tauri/Cargo.toml
+++ b/src/desktop/src-tauri/Cargo.toml
@@ -42,7 +42,7 @@ tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
[target."cfg(any(target_os = \"macos\", target_os = \"ios\"))".dependencies]
objc2 = "=0.6.4"
-objc2-foundation = { version = "=0.3.2", features = ["NSDictionary", "NSError", "NSGeometry", "NSObject", "NSString", "NSURL", "NSURLError", "NSURLRequest"] }
+objc2-foundation = { version = "=0.3.2", features = ["NSArray", "NSDictionary", "NSError", "NSGeometry", "NSObject", "NSString", "NSURL", "NSURLError", "NSURLRequest"] }
[target."cfg(target_os = \"macos\")".dependencies]
block2 = "=0.6.2"
diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rs
index 51ddd91f2..84e2e69cc 100644
--- a/src/desktop/src-tauri/build.rs
+++ b/src/desktop/src-tauri/build.rs
@@ -13,6 +13,8 @@ fn main() {
"desktop_system_notification_show",
"desktop_system_notification_listen",
"desktop_system_notification_take_activation",
+ "desktop_system_notification_retry_activation",
+ "desktop_system_notification_dismiss",
"desktop_system_notification_unlisten",
"mobile_share_image_copy",
"mobile_share_image_save",
@@ -21,6 +23,7 @@ fn main() {
"mobile_system_notification_snapshot",
"mobile_system_notification_acknowledge_registration",
"mobile_system_notification_take_activation",
+ "mobile_system_notification_dismiss",
"mobile_system_notification_listen",
"mobile_system_notification_unlisten",
"native_oauth_snapshot",
diff --git a/src/desktop/src-tauri/permissions/desktop-commands.toml b/src/desktop/src-tauri/permissions/desktop-commands.toml
index a76bb5270..a1d609ad3 100644
--- a/src/desktop/src-tauri/permissions/desktop-commands.toml
+++ b/src/desktop/src-tauri/permissions/desktop-commands.toml
@@ -1,4 +1,4 @@
[[permission]]
identifier = "desktop-commands"
description = "Existing main-window desktop commands"
-commands.allow = ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut", "desktop_system_notification_show", "desktop_system_notification_listen", "desktop_system_notification_take_activation", "desktop_system_notification_unlisten"]
+commands.allow = ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut", "desktop_system_notification_show", "desktop_system_notification_listen", "desktop_system_notification_take_activation", "desktop_system_notification_retry_activation", "desktop_system_notification_dismiss", "desktop_system_notification_unlisten"]
diff --git a/src/desktop/src-tauri/permissions/mobile-system-notification.toml b/src/desktop/src-tauri/permissions/mobile-system-notification.toml
index 4d014b411..a07d4c559 100644
--- a/src/desktop/src-tauri/permissions/mobile-system-notification.toml
+++ b/src/desktop/src-tauri/permissions/mobile-system-notification.toml
@@ -1,4 +1,4 @@
[[permission]]
identifier = "mobile-system-notification"
description = "Native mobile push registration and activation orchestration for the trusted main WebView"
-commands.allow = ["mobile_system_notification_check_permission", "mobile_system_notification_request_permission", "mobile_system_notification_snapshot", "mobile_system_notification_acknowledge_registration", "mobile_system_notification_take_activation", "mobile_system_notification_listen", "mobile_system_notification_unlisten"]
+commands.allow = ["mobile_system_notification_check_permission", "mobile_system_notification_request_permission", "mobile_system_notification_snapshot", "mobile_system_notification_acknowledge_registration", "mobile_system_notification_take_activation", "mobile_system_notification_dismiss", "mobile_system_notification_listen", "mobile_system_notification_unlisten"]
diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt
index 5960a678e..2736554a7 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt
+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt
@@ -24,10 +24,11 @@ class AlookFirebaseMessagingService : FirebaseMessagingService() {
MobilePushPlugin.createNotificationChannel(applicationContext)
val launchIntent = packageManager.getLaunchIntentForPackage(packageName) ?: return
launchIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
+ launchIntent.action = mobilePushNotificationAction(packageName, route.notificationId)
launchIntent.putExtra("notificationId", route.notificationId)
launchIntent.putExtra("messageId", route.messageId)
launchIntent.putExtra("targetId", route.targetId)
- val requestCode = route.notificationId.hashCode() and Int.MAX_VALUE
+ val requestCode = mobilePushNotificationRequestCode(route.notificationId)
val pendingIntent = PendingIntent.getActivity(
this,
requestCode,
@@ -38,7 +39,7 @@ class AlookFirebaseMessagingService : FirebaseMessagingService() {
.setSmallIcon(ai.alook.plugin.mobilepush.R.drawable.ic_alook_notification)
.setContentTitle(content.title ?: "Alook")
.setContentText(content.body ?: "New message")
- .setAutoCancel(true)
+ .setAutoCancel(MOBILE_PUSH_NOTIFICATION_AUTO_CANCEL)
.setContentIntent(pendingIntent)
.setGroup(route.targetId)
.build()
diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
index be9cdebba..94eb0bfee 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt
@@ -26,6 +26,11 @@ class AcknowledgeRegistrationArgs {
lateinit var providerToken: String
}
+@InvokeArg
+class DismissNotificationArgs {
+ lateinit var notificationId: String
+}
+
@InvokeArg
class MobilePushListenArgs {
lateinit var channel: Channel
@@ -151,6 +156,19 @@ class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {
}
}
+ @Command
+ fun dismissNotification(invoke: Invoke) {
+ val args = try {
+ invoke.parseArgs(DismissNotificationArgs::class.java)
+ } catch (_: Exception) {
+ invoke.reject("Notification dismissal is invalid", "invalid_request")
+ return
+ }
+ val requestCode = mobilePushNotificationRequestCode(args.notificationId)
+ NotificationManagerCompat.from(activity).cancel(args.notificationId, requestCode)
+ invoke.resolve()
+ }
+
@Command
fun listen(invoke: Invoke) {
val args = try {
diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt
index 2efa26136..f16577994 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt
+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt
@@ -2,6 +2,14 @@ package ai.alook.plugin.mobilepush
import java.util.UUID
+internal const val MOBILE_PUSH_NOTIFICATION_AUTO_CANCEL = false
+
+internal fun mobilePushNotificationRequestCode(notificationId: String): Int =
+ notificationId.hashCode() and Int.MAX_VALUE
+
+internal fun mobilePushNotificationAction(packageName: String, notificationId: String): String =
+ "$packageName.mobilepush.notification.$notificationId"
+
data class MobilePushRoute(
val notificationId: String,
val messageId: String,
diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt
index 0b0f18d3c..96cb07d21 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt
+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt
@@ -1,10 +1,41 @@
package ai.alook.plugin.mobilepush
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
import org.junit.Test
class MobilePushRouteTest {
+ @Test
+ fun keepsTappedNotificationUntilValidatedDestinationDismissal() {
+ assertFalse(MOBILE_PUSH_NOTIFICATION_AUTO_CANCEL)
+ }
+
+ @Test
+ fun derivesOneStableNonNegativeNotificationRequestCode() {
+ val notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"
+ assertEquals(
+ mobilePushNotificationRequestCode(notificationId),
+ mobilePushNotificationRequestCode(notificationId),
+ )
+ assertTrue(mobilePushNotificationRequestCode(notificationId) >= 0)
+ }
+
+ @Test
+ fun keepsPendingIntentIdentityExactAcrossRequestCodeCollisions() {
+ val first = "4f5dff4f-8ecf-4e12-8df0-09deeca44cad"
+ val second = "f0880472-8b15-4842-a905-c57cb4b94702"
+ assertEquals(
+ mobilePushNotificationRequestCode(first),
+ mobilePushNotificationRequestCode(second),
+ )
+ assertTrue(
+ mobilePushNotificationAction("ai.alook.android", first) !=
+ mobilePushNotificationAction("ai.alook.android", second),
+ )
+ }
+
@Test
fun acceptsOnlyCanonicalAllowlistedRouteValues() {
val route = MobilePushRoute.create(
diff --git a/src/desktop/src-tauri/plugins/mobile-push/build.rs b/src/desktop/src-tauri/plugins/mobile-push/build.rs
index dd3724d8a..3689a46ec 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/build.rs
+++ b/src/desktop/src-tauri/plugins/mobile-push/build.rs
@@ -3,6 +3,7 @@ fn main() {
"snapshot",
"acknowledgeRegistration",
"takeActivation",
+ "dismissNotification",
"listen",
"unlisten",
])
diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift
index d03ca6436..d054d0013 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift
+++ b/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift
@@ -121,12 +121,17 @@ final class MobilePushStore {
return true
}
- func saveActivation(_ route: MobilePushRoute) {
+ func saveActivation(
+ _ route: MobilePushRoute,
+ deliveredNotificationIdentifier: String? = nil
+ ) {
lock.lock()
defer { lock.unlock() }
defaults.set(route.notificationId, forKey: Keys.pendingNotificationId)
defaults.set(route.messageId, forKey: Keys.pendingMessageId)
defaults.set(route.targetId, forKey: Keys.pendingTargetId)
+ defaults.set(route.notificationId, forKey: Keys.dismissNotificationId)
+ defaults.set(deliveredNotificationIdentifier, forKey: Keys.deliveredNotificationIdentifier)
}
func takeActivation() -> MobilePushRoute? {
@@ -143,6 +148,18 @@ final class MobilePushStore {
return route
}
+ func takeDeliveredNotificationIdentifier(for notificationId: String) -> String? {
+ lock.lock()
+ defer { lock.unlock() }
+ guard defaults.string(forKey: Keys.dismissNotificationId) == notificationId else {
+ return nil
+ }
+ let deliveredIdentifier = defaults.string(forKey: Keys.deliveredNotificationIdentifier)
+ defaults.removeObject(forKey: Keys.dismissNotificationId)
+ defaults.removeObject(forKey: Keys.deliveredNotificationIdentifier)
+ return deliveredIdentifier
+ }
+
private func unlockedRegistration() -> MobilePushRegistrationState {
MobilePushRegistrationState(
currentToken: defaults.string(forKey: Keys.currentToken),
@@ -157,6 +174,8 @@ final class MobilePushStore {
static let pendingNotificationId = "alook.mobilePush.pendingNotificationId"
static let pendingMessageId = "alook.mobilePush.pendingMessageId"
static let pendingTargetId = "alook.mobilePush.pendingTargetId"
+ static let dismissNotificationId = "alook.mobilePush.dismissNotificationId"
+ static let deliveredNotificationIdentifier = "alook.mobilePush.deliveredNotificationIdentifier"
}
}
@@ -178,7 +197,10 @@ private final class MobilePushNotificationHandler: NSObject, UNUserNotificationC
guard let route = MobilePushRoute.from(response.notification.request.content.userInfo) else {
return
}
- MobilePushBridge.shared.acceptActivation(route)
+ MobilePushBridge.shared.acceptActivation(
+ route,
+ deliveredNotificationIdentifier: response.notification.request.identifier
+ )
}
}
@@ -198,8 +220,14 @@ private final class MobilePushBridge {
plugin?.signal()
}
- func acceptActivation(_ route: MobilePushRoute) {
- store.saveActivation(route)
+ func acceptActivation(
+ _ route: MobilePushRoute,
+ deliveredNotificationIdentifier: String
+ ) {
+ store.saveActivation(
+ route,
+ deliveredNotificationIdentifier: deliveredNotificationIdentifier
+ )
plugin?.signal()
}
}
@@ -304,6 +332,10 @@ private struct AcknowledgeRegistrationArgs: Decodable {
let providerToken: String
}
+private struct DismissNotificationArgs: Decodable {
+ let notificationId: String
+}
+
private struct ListenArgs: Decodable {
let channel: Channel
}
@@ -393,6 +425,21 @@ final class MobilePushPlugin: Plugin {
invoke.resolve(activation)
}
+ @objc public func dismissNotification(_ invoke: Invoke) {
+ do {
+ let args = try invoke.parseArgs(DismissNotificationArgs.self)
+ let identifier = bridge.store.takeDeliveredNotificationIdentifier(
+ for: args.notificationId
+ ) ?? args.notificationId
+ UNUserNotificationCenter.current().removeDeliveredNotifications(
+ withIdentifiers: [identifier]
+ )
+ invoke.resolve()
+ } catch {
+ invoke.reject("Notification dismissal is invalid", code: "invalid_request")
+ }
+ }
+
@objc public func listen(_ invoke: Invoke) {
do {
let args = try invoke.parseArgs(ListenArgs.self)
diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift
index 0e99e0a63..b11016d53 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift
+++ b/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift
@@ -70,8 +70,14 @@ final class MobilePushPluginTests: XCTestCase {
messageId: "message_1",
targetId: "channel_2"
)
- store.saveActivation(route)
+ store.saveActivation(route, deliveredNotificationIdentifier: "apns-delivered-1")
XCTAssertEqual(store.takeActivation(), route)
XCTAssertNil(store.takeActivation())
+ XCTAssertNil(store.takeDeliveredNotificationIdentifier(for: "another-notification"))
+ XCTAssertEqual(
+ store.takeDeliveredNotificationIdentifier(for: route.notificationId),
+ "apns-delivered-1"
+ )
+ XCTAssertNil(store.takeDeliveredNotificationIdentifier(for: route.notificationId))
}
}
diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissNotification.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissNotification.toml
new file mode 100644
index 000000000..d2d8a6376
--- /dev/null
+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/dismissNotification.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-dismissNotification"
+description = "Enables the dismissNotification command without any pre-configured scope."
+commands.allow = ["dismissNotification"]
+
+[[permission]]
+identifier = "deny-dismissNotification"
+description = "Denies the dismissNotification command without any pre-configured scope."
+commands.deny = ["dismissNotification"]
diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md
index 445f163e3..652597971 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md
+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md
@@ -36,6 +36,32 @@ Denies the acknowledgeRegistration command without any pre-configured scope.
<tr>
<td>
+`mobile-push:allow-dismissNotification`
+
+</td>
+<td>
+
+Enables the dismissNotification command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`mobile-push:deny-dismissNotification`
+
+</td>
+<td>
+
+Denies the dismissNotification command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`mobile-push:allow-listen`
</td>
diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json b/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json
index 81dba9093..787fcbc2e 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json
+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json
@@ -306,6 +306,18 @@
"const": "deny-acknowledgeRegistration",
"markdownDescription": "Denies the acknowledgeRegistration command without any pre-configured scope."
},
+ {
+ "description": "Enables the dismissNotification command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-dismissNotification",
+ "markdownDescription": "Enables the dismissNotification command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the dismissNotification command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-dismissNotification",
+ "markdownDescription": "Denies the dismissNotification command without any pre-configured scope."
+ },
{
"description": "Enables the listen command without any pre-configured scope.",
"type": "string",
diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs b/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs
index 9266bb89e..a8bbe8a58 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs
+++ b/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs
@@ -32,6 +32,10 @@ impl<R: Runtime> MobilePush<R> {
Err(Error::unavailable("Mobile push is unavailable"))
}
+ pub async fn dismiss_notification(&self, _notification_id: String) -> Result<(), Error> {
+ Err(Error::unavailable("Mobile push is unavailable"))
+ }
+
pub async fn listen(&self, _channel: Channel<()>) -> Result<u64, Error> {
Err(Error::unavailable("Mobile push is unavailable"))
}
diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs b/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs
index dae7bf097..d471a90b5 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs
+++ b/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs
@@ -16,8 +16,8 @@ pub use error::Error;
#[cfg(mobile)]
use mobile::MobilePush;
pub use models::{
- AcknowledgeRequest, Activation, ListenRequest, PermissionResponse, RegistrationSnapshot,
- UnlistenRequest,
+ AcknowledgeRequest, Activation, DismissRequest, ListenRequest, PermissionResponse,
+ RegistrationSnapshot, UnlistenRequest,
};
pub trait MobilePushExt<R: Runtime> {
diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs b/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs
index 915e7202c..3f8d26870 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs
+++ b/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs
@@ -1,6 +1,6 @@
use crate::{
- AcknowledgeRequest, Activation, Error, ListenRequest, PermissionResponse, RegistrationSnapshot,
- UnlistenRequest,
+ AcknowledgeRequest, Activation, DismissRequest, Error, ListenRequest, PermissionResponse,
+ RegistrationSnapshot, UnlistenRequest,
};
use serde::de::DeserializeOwned;
use tauri::{
@@ -67,6 +67,16 @@ impl<R: Runtime> MobilePush<R> {
.map_err(Into::into)
}
+ pub async fn dismiss_notification(&self, notification_id: String) -> Result<(), Error> {
+ self.0
+ .run_mobile_plugin_async(
+ "dismissNotification",
+ DismissRequest { notification_id },
+ )
+ .await
+ .map_err(Into::into)
+ }
+
pub async fn listen(&self, channel: Channel<()>) -> Result<u64, Error> {
self.0
.run_mobile_plugin_async("listen", ListenRequest { channel })
diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/models.rs b/src/desktop/src-tauri/plugins/mobile-push/src/models.rs
index 60d0a4ae5..b3f138659 100644
--- a/src/desktop/src-tauri/plugins/mobile-push/src/models.rs
+++ b/src/desktop/src-tauri/plugins/mobile-push/src/models.rs
@@ -32,6 +32,12 @@ pub struct AcknowledgeRequest {
pub provider_token: String,
}
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DismissRequest {
+ pub notification_id: String,
+}
+
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListenRequest {
diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rs
index 80d071ad9..992235c36 100644
--- a/src/desktop/src-tauri/src/lib.rs
+++ b/src/desktop/src-tauri/src/lib.rs
@@ -95,6 +95,7 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {
mobile_system_notification_runtime::mobile_system_notification_snapshot,
mobile_system_notification_runtime::mobile_system_notification_acknowledge_registration,
mobile_system_notification_runtime::mobile_system_notification_take_activation,
+ mobile_system_notification_runtime::mobile_system_notification_dismiss,
mobile_system_notification_runtime::mobile_system_notification_listen,
mobile_system_notification_runtime::mobile_system_notification_unlisten,
native_oauth_runtime::native_oauth_snapshot,
@@ -168,6 +169,8 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {
system_notifications::desktop_system_notification_show,
system_notifications::desktop_system_notification_listen,
system_notifications::desktop_system_notification_take_activation,
+ system_notifications::desktop_system_notification_retry_activation,
+ system_notifications::desktop_system_notification_dismiss,
system_notifications::desktop_system_notification_unlisten,
]);
diff --git a/src/desktop/src-tauri/src/mobile_system_notification.rs b/src/desktop/src-tauri/src/mobile_system_notification.rs
index d9da1fd00..46e7a52ed 100644
--- a/src/desktop/src-tauri/src/mobile_system_notification.rs
+++ b/src/desktop/src-tauri/src/mobile_system_notification.rs
@@ -124,6 +124,19 @@ pub fn validate_provider_token(token: &str) -> Result<(), MobileSystemNotificati
}
}
+pub fn validate_notification_id(
+ notification_id: &str,
+) -> Result<(), MobileSystemNotificationError> {
+ if uuid(notification_id) {
+ Ok(())
+ } else {
+ Err(MobileSystemNotificationError::new(
+ "invalid_request",
+ "Notification id is invalid",
+ ))
+ }
+}
+
pub fn validate_activation(
activation: Option<Activation>,
) -> Result<Option<Activation>, MobileSystemNotificationError> {
@@ -240,4 +253,10 @@ mod tests {
};
assert!(validate_activation(Some(invalid)).is_err());
}
+
+ #[test]
+ fn accepts_only_uuid_shaped_notification_ids() {
+ assert!(validate_notification_id("4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e").is_ok());
+ assert!(validate_notification_id("bad").is_err());
+ }
}
diff --git a/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs b/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs
index 9810ea249..3e932cd0e 100644
--- a/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs
+++ b/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs
@@ -1,6 +1,7 @@
use crate::mobile_system_notification::{
- validate_activation, validate_permission, validate_provider_token, validate_snapshot,
- Activation, MobileSystemNotificationError, PermissionResponse, RegistrationSnapshot,
+ validate_activation, validate_notification_id, validate_permission, validate_provider_token,
+ validate_snapshot, Activation, MobileSystemNotificationError, PermissionResponse,
+ RegistrationSnapshot,
};
use crate::native_command_guard::guard;
use tauri::{ipc::Channel, Manager, WebviewWindow};
@@ -94,6 +95,22 @@ pub async fn mobile_system_notification_take_activation(
}))
}
+#[tauri::command]
+pub async fn mobile_system_notification_dismiss(
+ window: WebviewWindow,
+ notification_id: String,
+) -> Result<(), MobileSystemNotificationError> {
+ guard(&window)
+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;
+ validate_notification_id(&notification_id)?;
+ window
+ .app_handle()
+ .mobile_push()
+ .dismiss_notification(notification_id)
+ .await?;
+ Ok(())
+}
+
#[tauri::command]
pub async fn mobile_system_notification_listen(
window: WebviewWindow,
diff --git a/src/desktop/src-tauri/src/system_notifications.rs b/src/desktop/src-tauri/src/system_notifications.rs
index 078fc8511..592a6da4f 100644
--- a/src/desktop/src-tauri/src/system_notifications.rs
+++ b/src/desktop/src-tauri/src/system_notifications.rs
@@ -11,6 +11,10 @@ const MAX_RECENT: usize = 256;
const ACTIVATION_SCHEME: &str = "ai.alook.desktop";
const ACTIVATION_HOST: &str = "notification";
const ACTIVATION_PATH: &str = "/open";
+#[cfg(windows)]
+const WINDOWS_APP_ID: &str = "ai.alook.desktop";
+#[cfg(windows)]
+const WINDOWS_NOTIFICATION_GROUP: &str = "messages";
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
@@ -168,6 +172,18 @@ impl NotificationRecord {
target: item.target.clone(),
})
}
+
+ fn retry_activation(&mut self, notification_id: &str) -> bool {
+ let Some(item) = self
+ .recent
+ .iter_mut()
+ .find(|item| item.notification_id == notification_id && item.activated)
+ else {
+ return false;
+ };
+ item.activated = false;
+ true
+ }
}
struct Notifications<T> {
@@ -460,6 +476,69 @@ pub fn desktop_system_notification_take_activation(
.take())
}
+#[tauri::command]
+pub fn desktop_system_notification_retry_activation(
+ window: WebviewWindow,
+ state: tauri::State<'_, DesktopSystemNotificationState>,
+ notification_id: String,
+) -> Result<(), &'static str> {
+ guard(&window)?;
+ if !valid_notification_id(&notification_id) {
+ return Err("notification_invalid");
+ }
+ state.transact(|record| {
+ if record.retry_activation(&notification_id) {
+ Ok(())
+ } else {
+ Err("activation_unavailable")
+ }
+ })
+}
+
+#[tauri::command]
+pub fn desktop_system_notification_dismiss(
+ window: WebviewWindow,
+ notification_id: String,
+) -> Result<(), &'static str> {
+ guard(&window)?;
+ if !valid_notification_id(&notification_id) {
+ return Err("notification_invalid");
+ }
+ dismiss_notification(&notification_id).map_err(|_| "notification_unavailable")
+}
+
+#[cfg(target_os = "macos")]
+fn dismiss_notification(notification_id: &str) -> Result<(), ()> {
+ use objc2_foundation::{NSArray, NSString};
+ use objc2_user_notifications::UNUserNotificationCenter;
+
+ let identifier = NSString::from_str(notification_id);
+ let identifiers = NSArray::from_slice(&[&*identifier]);
+ UNUserNotificationCenter::currentNotificationCenter()
+ .removeDeliveredNotificationsWithIdentifiers(&identifiers);
+ Ok(())
+}
+
+#[cfg(windows)]
+fn dismiss_notification(notification_id: &str) -> Result<(), ()> {
+ use windows::core::HSTRING;
+ use windows::UI::Notifications::ToastNotificationManager;
+
+ ToastNotificationManager::History()
+ .map_err(|_| ())?
+ .RemoveGroupedTagWithId(
+ &HSTRING::from(notification_id),
+ &HSTRING::from(WINDOWS_NOTIFICATION_GROUP),
+ &HSTRING::from(WINDOWS_APP_ID),
+ )
+ .map_err(|_| ())
+}
+
+#[cfg(target_os = "linux")]
+fn dismiss_notification(_notification_id: &str) -> Result<(), ()> {
+ Ok(())
+}
+
#[cfg(target_os = "macos")]
async fn display_notification(
_app: &AppHandle,
@@ -626,8 +705,14 @@ async fn display_notification(
let document = XmlDocument::new().map_err(|_| ())?;
document.LoadXml(&HSTRING::from(xml)).map_err(|_| ())?;
let toast = ToastNotification::CreateToastNotification(&document).map_err(|_| ())?;
+ toast
+ .SetTag(&HSTRING::from(notification_id))
+ .map_err(|_| ())?;
+ toast
+ .SetGroup(&HSTRING::from(WINDOWS_NOTIFICATION_GROUP))
+ .map_err(|_| ())?;
let notifier =
- ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from("ai.alook.desktop"))
+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(WINDOWS_APP_ID))
.map_err(|_| ())?;
notifier.Show(&toast).map_err(|_| ())
}
@@ -726,12 +811,18 @@ mod tests {
}
#[test]
- fn activation_is_one_shot_and_restorable() {
+ fn activation_is_one_shot_until_an_exact_retry_and_restorable() {
let mut record = NotificationRecord::new();
let id = record.claim(&candidate("viewer_1", "message_1")).unwrap();
assert_eq!(record.activate(&id).unwrap().target, target("message_1"));
assert!(record.activate(&id).is_none());
- let restored = NotificationRecord::restore(serde_json::to_value(record).unwrap()).unwrap();
+ assert!(!record.retry_activation("00000000-0000-0000-0000-000000000000"));
+ assert!(record.retry_activation(&id));
+ assert!(!record.retry_activation(&id));
+ let mut restored =
+ NotificationRecord::restore(serde_json::to_value(record).unwrap()).unwrap();
+ assert!(!restored.recent[0].activated);
+ assert_eq!(restored.activate(&id).unwrap().target, target("message_1"));
assert!(restored.recent[0].activated);
}
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 737304742..29d74c39e 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
@@ -7,12 +7,15 @@ import {
useNativeSystemNotifications,
} from "./use-native-system-notifications"
import type { DesktopSystemNotificationActivation } from "@/lib/community/system-notification-route"
+import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"
const hookMocks = vi.hoisted(() => ({
desktop: true,
mobile: false,
listen: vi.fn(),
take: vi.fn(),
+ retryActivation: vi.fn(async () => undefined),
+ dismiss: vi.fn(async () => undefined),
revalidate: vi.fn(),
mobileListen: vi.fn(),
mobileCheck: vi.fn(),
@@ -22,6 +25,7 @@ const hookMocks = vi.hoisted(() => ({
mobileAck: vi.fn(),
mobileDelete: vi.fn(),
mobileTake: vi.fn(),
+ mobileDismiss: vi.fn(async () => undefined),
mobileRevalidate: vi.fn(),
}))
vi.mock("@alook/shared", async () => {
@@ -40,6 +44,8 @@ vi.mock("@/lib/community/desktop-system-notification", async () => {
...actual,
listenDesktopSystemNotificationActivations: hookMocks.listen,
takeDesktopSystemNotificationActivation: hookMocks.take,
+ retryDesktopSystemNotificationActivation: hookMocks.retryActivation,
+ dismissDesktopSystemNotification: hookMocks.dismiss,
}
})
vi.mock("@/lib/community/system-notification-route", async () => {
@@ -62,6 +68,7 @@ vi.mock("@/lib/community/mobile-system-notification", async () => {
acknowledgeMobileSystemNotificationRegistration: hookMocks.mobileAck,
deleteMobileSystemNotificationRegistration: hookMocks.mobileDelete,
takeMobileSystemNotificationActivation: hookMocks.mobileTake,
+ dismissMobileSystemNotification: hookMocks.mobileDismiss,
revalidateMobileSystemNotificationActivation: hookMocks.mobileRevalidate,
}
})
@@ -93,12 +100,14 @@ describe("desktop notification activation controller", () => {
const controller = createDesktopSystemNotificationActivationController({
listen: vi.fn(async () => { calls.push("listen"); return () => calls.push("unlisten") }),
take: vi.fn(async () => { calls.push("take"); return activation }),
- revalidate: vi.fn(async () => { calls.push("revalidate"); return true }),
+ revalidate: vi.fn(async () => { calls.push("revalidate"); return "allowed" as const }),
+ retryActivation: vi.fn(),
+ queueDismiss: vi.fn(() => { calls.push("queueDismiss") }),
navigate: vi.fn(() => calls.push("navigate")),
openInbox: vi.fn(),
})
await controller.connect()
- expect(calls).toEqual(["listen", "take", "revalidate", "navigate"])
+ expect(calls).toEqual(["listen", "take", "revalidate", "queueDismiss", "navigate"])
controller.dispose()
expect(calls.at(-1)).toBe("unlisten")
})
@@ -106,16 +115,61 @@ describe("desktop notification activation controller", () => {
it("falls back to Inbox when the message is deleted or access is revoked", async () => {
const openInbox = vi.fn()
const navigate = vi.fn()
+ const retryActivation = vi.fn()
const controller = createDesktopSystemNotificationActivationController({
listen: vi.fn(async () => () => undefined),
take: vi.fn(async () => activation),
- revalidate: vi.fn(async () => false),
+ revalidate: vi.fn(async () => "invalid" as const),
+ retryActivation,
+ queueDismiss: vi.fn(),
navigate,
openInbox,
})
await controller.connect()
expect(openInbox).toHaveBeenCalledOnce()
expect(navigate).not.toHaveBeenCalled()
+ expect(retryActivation).not.toHaveBeenCalled()
+ })
+
+ it("re-arms only a retryable activation before falling back to Inbox", async () => {
+ const calls: string[] = []
+ const retryActivation = vi.fn(async (notificationId: string) => {
+ calls.push(`retry:${notificationId}`)
+ })
+ const controller = createDesktopSystemNotificationActivationController({
+ listen: vi.fn(async () => () => undefined),
+ take: vi.fn(async () => activation),
+ revalidate: vi.fn(async () => {
+ calls.push("revalidate")
+ return "retryable" as const
+ }),
+ retryActivation,
+ queueDismiss: vi.fn(),
+ navigate: vi.fn(),
+ openInbox: vi.fn(async () => { calls.push("inbox") }),
+ })
+
+ await controller.connect()
+ expect(calls).toEqual([
+ "revalidate",
+ `retry:${activation.notificationId}`,
+ "inbox",
+ ])
+ })
+
+ it("still navigates when dismissal persistence fails", async () => {
+ const navigate = vi.fn()
+ const controller = createDesktopSystemNotificationActivationController({
+ listen: vi.fn(async () => () => undefined),
+ take: vi.fn(async () => activation),
+ revalidate: vi.fn(async () => "allowed" as const),
+ retryActivation: vi.fn(),
+ queueDismiss: vi.fn(() => { throw new Error("storage unavailable") }),
+ navigate,
+ openInbox: vi.fn(),
+ })
+ await controller.connect()
+ expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/channels/server_1/channel_1")
})
it("handles hot activation signals and ignores work after disposal", async () => {
@@ -128,7 +182,9 @@ describe("desktop notification activation controller", () => {
const controller = createDesktopSystemNotificationActivationController({
listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),
take,
- revalidate: vi.fn(async () => true),
+ revalidate: vi.fn(async () => "allowed" as const),
+ retryActivation: vi.fn(),
+ queueDismiss: vi.fn(),
navigate,
openInbox: vi.fn(),
})
@@ -153,7 +209,9 @@ describe("desktop notification activation controller", () => {
const controller = createDesktopSystemNotificationActivationController({
listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),
take,
- revalidate: vi.fn(async () => true),
+ revalidate: vi.fn(async () => "allowed" as const),
+ retryActivation: vi.fn(),
+ queueDismiss: vi.fn(),
navigate: vi.fn(),
openInbox: vi.fn(),
})
@@ -174,6 +232,8 @@ describe("desktop notification activation controller", () => {
listen: vi.fn(() => listener),
take: vi.fn(),
revalidate: vi.fn(),
+ retryActivation: vi.fn(),
+ queueDismiss: vi.fn(),
navigate: vi.fn(),
openInbox: vi.fn(),
})
@@ -312,22 +372,73 @@ describe("native system notification hook", () => {
rendered.unmount()
})
- it("navigates an allowed activation and disposes the native listener", async () => {
+ it("dismisses on the loaded destination and retries a transient native failure", async () => {
const assign = vi.fn()
const stop = vi.fn()
vi.stubGlobal("location", { href: "https://alook.test/c", assign })
hookMocks.listen.mockResolvedValue(stop)
hookMocks.take.mockResolvedValueOnce(activation)
- hookMocks.revalidate.mockResolvedValue(true)
+ hookMocks.revalidate.mockResolvedValue("allowed")
const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))
await waitFor(() => expect(assign).toHaveBeenCalledWith(
"/c/channels/server_1/channel_1",
))
expect(hookMocks.revalidate).toHaveBeenCalledWith(activation.target)
+ expect(hookMocks.dismiss).not.toHaveBeenCalled()
rendered.unmount()
expect(stop).toHaveBeenCalledOnce()
+
+ hookMocks.take.mockResolvedValue(null)
+ hookMocks.dismiss
+ .mockRejectedValueOnce(new Error("native unavailable"))
+ .mockResolvedValueOnce(undefined)
+ vi.stubGlobal("location", {
+ href: "https://alook.test/c/channels/server_1/channel_1",
+ assign,
+ })
+ const destination = renderHook(() => useNativeSystemNotifications("viewer_1"))
+ await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledOnce())
+ expect(window.sessionStorage.length).toBe(1)
+ await act(async () => { await Promise.resolve() })
+ window.dispatchEvent(new Event("focus"))
+ await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledTimes(2))
+ expect(hookMocks.dismiss).toHaveBeenLastCalledWith(activation.notificationId)
+ await waitFor(() => expect(window.sessionStorage.length).toBe(0))
+ destination.unmount()
+ expect(stop).toHaveBeenCalledTimes(2)
+ })
+
+ it("deduplicates concurrent destination mounts before native dismissal settles", async () => {
+ const notificationId = activation.notificationId
+ const dismissal = createNativeSystemNotificationDismissalQueue({
+ getItem: (key) => window.sessionStorage.getItem(key),
+ setItem: (key, value) => window.sessionStorage.setItem(key, value),
+ removeItem: (key) => window.sessionStorage.removeItem(key),
+ now: () => Date.now(),
+ })
+ dismissal.queue("desktop", notificationId, "/c/channels/server_1/channel_1")
+ vi.stubGlobal("location", {
+ href: "https://alook.test/c/channels/server_1/channel_1",
+ assign: vi.fn(),
+ })
+ hookMocks.listen.mockResolvedValue(vi.fn())
+ hookMocks.take.mockResolvedValue(null)
+ let resolveDismiss = () => undefined
+ hookMocks.dismiss.mockImplementation(() => new Promise<void>((resolve) => {
+ resolveDismiss = resolve
+ }))
+
+ const first = renderHook(() => useNativeSystemNotifications("viewer_1"))
+ const second = renderHook(() => useNativeSystemNotifications("viewer_1"))
+ await waitFor(() => expect(hookMocks.dismiss).toHaveBeenCalledOnce())
+ expect(window.sessionStorage.length).toBe(1)
+ resolveDismiss()
+ await waitFor(() => expect(window.sessionStorage.length).toBe(0))
+
+ first.unmount()
+ second.unmount()
})
it("persists an Inbox fallback, resumes it, and clears it after a real click", async () => {
@@ -337,7 +448,7 @@ describe("native system notification hook", () => {
vi.stubGlobal("location", { href: "https://alook.test/c/channels/server_1/channel_1", assign })
hookMocks.listen.mockResolvedValue(stop)
hookMocks.take.mockResolvedValueOnce(activation).mockResolvedValue(null)
- hookMocks.revalidate.mockResolvedValue(false)
+ hookMocks.revalidate.mockResolvedValue("invalid")
const first = renderHook(() => useNativeSystemNotifications("viewer_1"))
await act(async () => {
@@ -345,6 +456,7 @@ describe("native system notification hook", () => {
await vi.advanceTimersByTimeAsync(2_000)
})
expect(assign).toHaveBeenCalledWith("https://alook.test/c")
+ expect(hookMocks.retryActivation).not.toHaveBeenCalled()
first.unmount()
const button = document.createElement("button")
@@ -358,6 +470,30 @@ describe("native system notification hook", () => {
second.unmount()
})
+ it("re-arms the exact desktop activation on retryable validation failure", async () => {
+ const assign = vi.fn()
+ const stop = vi.fn()
+ const button = document.createElement("button")
+ button.setAttribute("aria-label", "Inbox")
+ const click = vi.spyOn(button, "click")
+ document.body.append(button)
+ vi.stubGlobal("location", { href: "https://alook.test/c/me/friends", assign })
+ hookMocks.listen.mockResolvedValue(stop)
+ hookMocks.take.mockResolvedValueOnce(activation).mockResolvedValue(null)
+ hookMocks.revalidate.mockResolvedValue("retryable")
+
+ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))
+ await waitFor(() => expect(hookMocks.retryActivation).toHaveBeenCalledExactlyOnceWith(
+ activation.notificationId,
+ ))
+ expect(click).toHaveBeenCalledOnce()
+ expect(assign).not.toHaveBeenCalled()
+ expect(hookMocks.dismiss).not.toHaveBeenCalled()
+
+ rendered.unmount()
+ expect(stop).toHaveBeenCalledOnce()
+ })
+
it("disposes the controller when native listener setup rejects", async () => {
hookMocks.listen.mockRejectedValue(new Error("native unavailable"))
hookMocks.take.mockResolvedValue(null)
@@ -425,6 +561,7 @@ describe("native system notification hook", () => {
]))
expect(hookMocks.mobileListen).toHaveBeenCalledOnce()
expect(assign).toHaveBeenCalledWith("/c/me/channel_1")
+ expect(hookMocks.mobileDismiss).not.toHaveBeenCalled()
const button = document.createElement("button")
button.setAttribute("aria-label", "Inbox")
@@ -444,6 +581,41 @@ describe("native system notification hook", () => {
expect(stop).toHaveBeenCalledOnce()
})
+ it("retries a mobile destination dismissal while the handoff is current", async () => {
+ hookMocks.desktop = false
+ hookMocks.mobile = true
+ const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"
+ const dismissal = createNativeSystemNotificationDismissalQueue({
+ getItem: (key) => window.sessionStorage.getItem(key),
+ setItem: (key, value) => window.sessionStorage.setItem(key, value),
+ removeItem: (key) => window.sessionStorage.removeItem(key),
+ now: () => Date.now(),
+ })
+ dismissal.queue("mobile", notificationId, "/c/me/channel_1")
+ vi.stubGlobal("location", {
+ href: "https://alook.test/c/me/channel_1",
+ assign: vi.fn(),
+ })
+ hookMocks.mobileListen.mockResolvedValue(vi.fn())
+ hookMocks.mobileCheck.mockResolvedValue("denied")
+ hookMocks.mobileTake.mockResolvedValue(null)
+ hookMocks.mobileDismiss
+ .mockRejectedValueOnce(new Error("native unavailable"))
+ .mockResolvedValueOnce(undefined)
+ const visibilityState = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")
+
+ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))
+ await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledOnce())
+ expect(window.sessionStorage.length).toBe(1)
+ await act(async () => { await Promise.resolve() })
+ document.dispatchEvent(new Event("visibilitychange"))
+ await waitFor(() => expect(hookMocks.mobileDismiss).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(window.sessionStorage.length).toBe(0))
+
+ rendered.unmount()
+ visibilityState.mockRestore()
+ })
+
it.each(["unmounted", "open"])("preserves the page when a foreground activation read fails with Inbox %s", async (inboxState) => {
vi.useFakeTimers()
hookMocks.desktop = false
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 babd58204..0bdf9379f 100644
--- a/src/web/src/hooks/community/use-native-system-notifications.ts
+++ b/src/web/src/hooks/community/use-native-system-notifications.ts
@@ -3,13 +3,16 @@
import { useEffect } from "react"
import { isDesktop, isMobile } from "@alook/shared"
import {
+ dismissDesktopSystemNotification,
listenDesktopSystemNotificationActivations,
+ retryDesktopSystemNotificationActivation,
takeDesktopSystemNotificationActivation,
} from "@/lib/community/desktop-system-notification"
import {
revalidateDesktopSystemNotificationTarget,
systemNotificationHref,
type DesktopSystemNotificationActivation,
+ type DesktopSystemNotificationTargetValidation,
} from "@/lib/community/system-notification-route"
import {
acknowledgeMobileSystemNotificationRegistration,
@@ -17,6 +20,7 @@ import {
createMobileSystemNotificationActivationController,
createMobileSystemNotificationRegistrationController,
deleteMobileSystemNotificationRegistration,
+ dismissMobileSystemNotification,
listenMobileSystemNotificationSignals,
postMobileSystemNotificationRegistration,
requestMobileSystemNotificationPermission,
@@ -25,11 +29,35 @@ import {
snapshotMobileSystemNotificationRegistration,
takeMobileSystemNotificationActivation,
} from "@/lib/community/mobile-system-notification"
+import { createNativeSystemNotificationDismissalQueue } from "@/lib/community/native-system-notification-dismissal"
+
+const activeNativeDismissals = new Set<string>()
+
+function dismissPendingNativeSystemNotification(
+ platform: "desktop" | "mobile",
+ pathname: string,
+ dismissal: ReturnType<typeof createNativeSystemNotificationDismissalQueue>,
+ dismiss: (notificationId: string) => Promise<void>,
+) {
+ const notificationId = dismissal.peek(platform, pathname)
+ if (!notificationId) return
+ const key = `${platform}:${pathname}:${notificationId}`
+ if (activeNativeDismissals.has(key)) return
+ activeNativeDismissals.add(key)
+ void dismiss(notificationId)
+ .then(() => { dismissal.complete(platform, pathname, notificationId) })
+ .catch(() => undefined)
+ .finally(() => { activeNativeDismissals.delete(key) })
+}
export type DesktopSystemNotificationActivationDeps = {
listen: (ready: () => void) => Promise<() => void>
take: () => Promise<DesktopSystemNotificationActivation | null>
- revalidate: (activation: DesktopSystemNotificationActivation) => Promise<boolean>
+ revalidate: (
+ activation: DesktopSystemNotificationActivation,
+ ) => Promise<DesktopSystemNotificationTargetValidation>
+ retryActivation: (notificationId: string) => Promise<void>
+ queueDismiss: (notificationId: string, href: string) => void
navigate: (href: string) => void
openInbox: () => Promise<void> | void
}
@@ -177,10 +205,21 @@ export function createDesktopSystemNotificationActivationController(
rerun = false
const activation = await deps.take().catch(() => null)
if (!activation || disposed) continue
- const allowed = await deps.revalidate(activation).catch(() => false)
+ const validation = await deps.revalidate(activation).catch(() => "retryable" as const)
if (disposed) continue
- if (allowed) deps.navigate(systemNotificationHref(activation.target))
- else await deps.openInbox()
+ if (validation === "allowed") {
+ const href = systemNotificationHref(activation.target)
+ try {
+ deps.queueDismiss(activation.notificationId, href)
+ } catch {}
+ if (!disposed) deps.navigate(href)
+ } else {
+ if (validation === "retryable") {
+ await deps.retryActivation(activation.notificationId).catch(() => undefined)
+ if (disposed) continue
+ }
+ await deps.openInbox()
+ }
} while (rerun && !disposed)
} finally {
draining = false
@@ -208,6 +247,13 @@ export function createDesktopSystemNotificationActivationController(
export function useNativeSystemNotifications(viewerUserId: string) {
useEffect(() => {
+ const dismissal = createNativeSystemNotificationDismissalQueue({
+ getItem: (key) => window.sessionStorage.getItem(key),
+ setItem: (key, value) => window.sessionStorage.setItem(key, value),
+ removeItem: (key) => window.sessionStorage.removeItem(key),
+ now: () => Date.now(),
+ })
+ const pathname = new URL(window.location.href).pathname
const inbox = createDesktopSystemNotificationInboxOpener({
getItem: (key) => window.sessionStorage.getItem(key),
setItem: (key, value) => window.sessionStorage.setItem(key, value),
@@ -221,10 +267,22 @@ export function useNativeSystemNotifications(viewerUserId: string) {
})
if (isDesktop()) {
+ const dismissPending = () => dismissPendingNativeSystemNotification(
+ "desktop",
+ pathname,
+ dismissal,
+ dismissDesktopSystemNotification,
+ )
+ dismissPending()
+ window.addEventListener("focus", dismissPending)
const browserDeps: DesktopSystemNotificationActivationDeps = {
listen: listenDesktopSystemNotificationActivations,
take: takeDesktopSystemNotificationActivation,
revalidate: ({ target }) => revalidateDesktopSystemNotificationTarget(target),
+ retryActivation: retryDesktopSystemNotificationActivation,
+ queueDismiss: (notificationId, href) => {
+ dismissal.queue("desktop", notificationId, href)
+ },
navigate: (href) => window.location.assign(href),
openInbox: () => inbox.open(),
}
@@ -232,6 +290,7 @@ export function useNativeSystemNotifications(viewerUserId: string) {
void inbox.resume()
void controller.connect().catch(() => controller.dispose())
return () => {
+ window.removeEventListener("focus", dismissPending)
controller.dispose()
inbox.dispose()
}
@@ -243,6 +302,13 @@ export function useNativeSystemNotifications(viewerUserId: string) {
}
resumeMobileSystemNotificationRegistration()
+ const dismissPending = () => dismissPendingNativeSystemNotification(
+ "mobile",
+ pathname,
+ dismissal,
+ dismissMobileSystemNotification,
+ )
+ dismissPending()
const registration = createMobileSystemNotificationRegistrationController({
checkPermission: checkMobileSystemNotificationPermission,
@@ -257,6 +323,9 @@ export function useNativeSystemNotifications(viewerUserId: string) {
const activation = createMobileSystemNotificationActivationController({
take: takeMobileSystemNotificationActivation,
revalidate: revalidateMobileSystemNotificationActivation,
+ queueDismiss: (notificationId, href) => {
+ dismissal.queue("mobile", notificationId, href)
+ },
navigate: (href) => window.location.assign(href),
openInbox: () => inbox.open(),
})
@@ -264,6 +333,7 @@ export function useNativeSystemNotifications(viewerUserId: string) {
let unlisten: (() => void) | undefined
const synchronize = () => {
+ dismissPending()
void registration.sync()
void activation.drain()
}
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 3dbc7a144..734ca8607 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -4,8 +4,10 @@ import { QueryClient } from "@tanstack/react-query"
import type { StructuralSnapshotV1 } from "./structural-snapshot"
import {
buildDesktopSystemNotificationCandidate,
+ dismissDesktopSystemNotification,
listenDesktopSystemNotificationActivations,
resolveDesktopSystemNotificationCandidate,
+ retryDesktopSystemNotificationActivation,
showDesktopSystemNotification,
takeDesktopSystemNotificationActivation,
} from "./desktop-system-notification"
@@ -372,4 +374,24 @@ describe("desktop system notification activation bridge", () => {
invoke.mockResolvedValueOnce({ href: "https://evil.test" })
await expect(takeDesktopSystemNotificationActivation()).resolves.toBeNull()
})
+
+ it("dismisses exactly one native notification id", async () => {
+ invoke.mockResolvedValueOnce(undefined)
+ const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"
+ await expect(dismissDesktopSystemNotification(notificationId)).resolves.toBeUndefined()
+ expect(invoke).toHaveBeenCalledWith(
+ "desktop_system_notification_dismiss",
+ { notificationId },
+ )
+ })
+
+ it("re-arms exactly one native notification id", async () => {
+ invoke.mockResolvedValueOnce(undefined)
+ const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"
+ await expect(retryDesktopSystemNotificationActivation(notificationId)).resolves.toBeUndefined()
+ expect(invoke).toHaveBeenCalledWith(
+ "desktop_system_notification_retry_activation",
+ { notificationId },
+ )
+ })
})
diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.ts
index dc2fae2d7..75c1f1c44 100644
--- a/src/web/src/lib/community/desktop-system-notification.ts
+++ b/src/web/src/lib/community/desktop-system-notification.ts
@@ -166,3 +166,11 @@ export async function takeDesktopSystemNotificationActivation(): Promise<Desktop
const value = await tauriInvoke<unknown>("desktop_system_notification_take_activation")
return parseDesktopSystemNotificationActivation(value)
}
+
+export async function retryDesktopSystemNotificationActivation(notificationId: string): Promise<void> {
+ await tauriInvoke("desktop_system_notification_retry_activation", { notificationId })
+}
+
+export async function dismissDesktopSystemNotification(notificationId: string): Promise<void> {
+ await tauriInvoke("desktop_system_notification_dismiss", { notificationId })
+}
diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.ts
index 4bc9cebe5..1dae0b8d9 100644
--- a/src/web/src/lib/community/mobile-system-notification.test.ts
+++ b/src/web/src/lib/community/mobile-system-notification.test.ts
@@ -5,6 +5,7 @@ import {
createMobileSystemNotificationActivationController,
createMobileSystemNotificationRegistrationController,
deleteMobileSystemNotificationRegistration,
+ dismissMobileSystemNotification,
listenMobileSystemNotificationSignals,
parseMobileSystemNotificationActivation,
parseMobileSystemNotificationPermission,
@@ -167,6 +168,14 @@ describe("mobile notification native adapter", () => {
targetId: "channel_1",
})
await expect(takeMobileSystemNotificationActivation()).rejects.toThrow("invalid_native_response")
+
+ nativeMocks.invoke.mockResolvedValueOnce(undefined)
+ await expect(dismissMobileSystemNotification(notificationId)).resolves.toBeUndefined()
+ expect(nativeMocks.invoke).toHaveBeenLastCalledWith(
+ "mobile_system_notification_dismiss",
+ { notificationId },
+ )
+ await expect(dismissMobileSystemNotification("bad")).rejects.toThrow("invalid_notification_id")
})
it("bridges native signals and swallows unlisten failures", async () => {
@@ -528,9 +537,11 @@ describe("mobile notification activation", () => {
take.mockResolvedValueOnce(activation)
const navigate = vi.fn()
const openInbox = vi.fn()
+ const queueDismiss = vi.fn()
const controller = createMobileSystemNotificationActivationController({
take,
revalidate: (value) => revalidateMobileSystemNotificationActivation(value, fetchImpl),
+ queueDismiss,
navigate,
openInbox,
})
@@ -541,6 +552,7 @@ describe("mobile notification activation", () => {
await controller.drain()
const href = kind === "dm" ? "/c/me/channel_1" : "/c/channels/server_1/channel_1"
expect(navigate).toHaveBeenCalledExactlyOnceWith(href)
+ expect(queueDismiss).toHaveBeenCalledExactlyOnceWith(notificationId, href)
expect(new URL(href, "https://example.test").search).toBe("")
expect(openInbox).not.toHaveBeenCalled()
controller.dispose()
@@ -580,6 +592,7 @@ describe("mobile notification activation", () => {
.mockResolvedValueOnce(activation)
.mockRejectedValueOnce(new Error("invalid native response")),
revalidate: vi.fn().mockRejectedValueOnce(new Error("offline")),
+ queueDismiss: vi.fn(),
navigate,
openInbox,
})
@@ -590,6 +603,19 @@ describe("mobile notification activation", () => {
expect(navigate).not.toHaveBeenCalled()
})
+ it("still navigates when dismissal persistence fails", async () => {
+ const navigate = vi.fn()
+ const controller = createMobileSystemNotificationActivationController({
+ take: vi.fn(async () => activation),
+ revalidate: vi.fn(async () => ({ href: "/c/me/channel_1" })),
+ queueDismiss: vi.fn(() => { throw new Error("storage unavailable") }),
+ navigate,
+ openInbox: vi.fn(),
+ })
+ await controller.drain()
+ expect(navigate).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1")
+ })
+
it("coalesces a signal received while an activation drain is active", async () => {
let releaseTake = (_value: null) => undefined
const firstTake = new Promise<null>((resolve) => { releaseTake = resolve })
@@ -597,6 +623,7 @@ describe("mobile notification activation", () => {
const controller = createMobileSystemNotificationActivationController({
take,
revalidate: vi.fn(),
+ queueDismiss: vi.fn(),
navigate: vi.fn(),
openInbox: vi.fn(),
})
diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.ts
index edbebf840..357167b70 100644
--- a/src/web/src/lib/community/mobile-system-notification.ts
+++ b/src/web/src/lib/community/mobile-system-notification.ts
@@ -195,6 +195,11 @@ export async function takeMobileSystemNotificationActivation(): Promise<MobileSy
return activation
}
+export async function dismissMobileSystemNotification(notificationId: string): Promise<void> {
+ if (!UUID.test(notificationId)) throw new Error("invalid_notification_id")
+ await tauriInvoke("mobile_system_notification_dismiss", { notificationId })
+}
+
export async function postMobileSystemNotificationRegistration(
snapshot: MobileSystemNotificationRegistration,
fetchImpl: typeof fetch = fetch,
@@ -345,6 +350,7 @@ export type MobileSystemNotificationActivationDeps = {
revalidate: (
activation: MobileSystemNotificationActivation,
) => Promise<MobileSystemNotificationDestination | null>
+ queueDismiss: (notificationId: string, href: string) => void
navigate: (href: string) => void
openInbox: () => Promise<void> | void
}
@@ -375,8 +381,12 @@ export function createMobileSystemNotificationActivationController(
if (!activation || disposed) continue
const destination = await deps.revalidate(activation).catch(() => null)
if (disposed) continue
- if (destination) deps.navigate(destination.href)
- else await deps.openInbox()
+ if (destination) {
+ try {
+ deps.queueDismiss(activation.notificationId, destination.href)
+ } catch {}
+ if (!disposed) deps.navigate(destination.href)
+ } else await deps.openInbox()
} while (rerun && !disposed)
} finally {
draining = false
diff --git a/src/web/src/lib/community/native-system-notification-dismissal.test.ts b/src/web/src/lib/community/native-system-notification-dismissal.test.ts
new file mode 100644
index 000000000..e1403f71a
--- /dev/null
+++ b/src/web/src/lib/community/native-system-notification-dismissal.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it, vi } from "vitest"
+import {
+ createNativeSystemNotificationDismissalQueue,
+ type NativeSystemNotificationDismissalDeps,
+} from "./native-system-notification-dismissal"
+
+function deps(
+ values: Map<string, string>,
+ overrides: Partial<NativeSystemNotificationDismissalDeps> = {},
+): NativeSystemNotificationDismissalDeps {
+ return {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, value),
+ removeItem: (key) => { values.delete(key) },
+ now: () => 1_000,
+ ...overrides,
+ }
+}
+
+describe("native notification dismissal handoff", () => {
+ const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"
+
+ it("completes an exact platform and destination match once", () => {
+ const values = new Map<string, string>()
+ const queue = createNativeSystemNotificationDismissalQueue(deps(values))
+ expect(queue.queue("mobile", notificationId, "/c/me/channel_1")).toBe(true)
+ expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()
+ expect(queue.peek("mobile", "/c/me/channel_2")).toBeNull()
+ expect(queue.peek("mobile", "/c/me/channel_1")).toBe(notificationId)
+ expect(queue.complete("mobile", "/c/me/channel_2", notificationId)).toBe(false)
+ expect(queue.complete("mobile", "/c/me/channel_1", notificationId)).toBe(true)
+ expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()
+ })
+
+ it("rejects unsafe values and removes corrupt or expired handoffs", () => {
+ const values = new Map<string, string>()
+ const queue = createNativeSystemNotificationDismissalQueue(deps(values))
+ expect(queue.queue("desktop", "bad", "/c/me/channel_1")).toBe(false)
+ expect(queue.queue("desktop", notificationId, "https://evil.test/c/me/channel_1")).toBe(false)
+
+ values.set("alook:native-system-notification:pending-dismissal", "corrupt")
+ expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()
+ expect(values.size).toBe(0)
+
+ values.set("alook:native-system-notification:pending-dismissal", JSON.stringify({
+ version: 1,
+ platform: "desktop",
+ notificationId,
+ pathname: "/c/me/channel_1",
+ expiresAt: 1_000,
+ }))
+ expect(queue.peek("desktop", "/c/me/channel_1")).toBeNull()
+ expect(values.size).toBe(0)
+ })
+
+ it("keeps navigation best-effort when session storage is unavailable", () => {
+ const queue = createNativeSystemNotificationDismissalQueue(deps(new Map(), {
+ getItem: () => { throw new Error("blocked") },
+ setItem: () => { throw new Error("blocked") },
+ removeItem: vi.fn(),
+ }))
+ expect(queue.queue("mobile", notificationId, "/c/me/channel_1")).toBe(false)
+ expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()
+ })
+
+ it("drops an invalid handoff even when storage removal is blocked", () => {
+ const values = new Map([
+ ["alook:native-system-notification:pending-dismissal", "corrupt"],
+ ])
+ const removeItem = vi.fn(() => { throw new Error("blocked") })
+ const queue = createNativeSystemNotificationDismissalQueue(deps(values, { removeItem }))
+
+ expect(queue.peek("mobile", "/c/me/channel_1")).toBeNull()
+ expect(removeItem).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/lib/community/native-system-notification-dismissal.ts b/src/web/src/lib/community/native-system-notification-dismissal.ts
new file mode 100644
index 000000000..78f4f82b9
--- /dev/null
+++ b/src/web/src/lib/community/native-system-notification-dismissal.ts
@@ -0,0 +1,111 @@
+export type NativeSystemNotificationPlatform = "desktop" | "mobile"
+
+type PendingDismissal = {
+ version: 1
+ platform: NativeSystemNotificationPlatform
+ notificationId: string
+ pathname: string
+ expiresAt: number
+}
+
+export type NativeSystemNotificationDismissalDeps = {
+ getItem: (key: string) => string | null
+ setItem: (key: string, value: string) => void
+ removeItem: (key: string) => void
+ now: () => number
+}
+
+const KEY = "alook:native-system-notification:pending-dismissal"
+const VERSION = 1
+const TTL_MS = 2 * 60 * 1000
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+const SAFE_ID = "[A-Za-z0-9_-]{1,128}"
+const ROUTE = new RegExp(`^/c/(?:me/${SAFE_ID}|channels/${SAFE_ID}/${SAFE_ID})$`)
+const FIELDS = new Set(["version", "platform", "notificationId", "pathname", "expiresAt"])
+
+export function createNativeSystemNotificationDismissalQueue(
+ deps: NativeSystemNotificationDismissalDeps,
+) {
+ function remove() {
+ try {
+ deps.removeItem(KEY)
+ } catch {
+ return
+ }
+ }
+
+ function read(): PendingDismissal | null {
+ let raw: string | null
+ try {
+ raw = deps.getItem(KEY)
+ } catch {
+ return null
+ }
+ if (raw === null) return null
+ try {
+ const value = JSON.parse(raw) as Partial<PendingDismissal>
+ if (
+ value.version !== VERSION
+ || (value.platform !== "desktop" && value.platform !== "mobile")
+ || typeof value.notificationId !== "string"
+ || !UUID.test(value.notificationId)
+ || typeof value.pathname !== "string"
+ || !ROUTE.test(value.pathname)
+ || typeof value.expiresAt !== "number"
+ || !Number.isFinite(value.expiresAt)
+ || value.expiresAt <= deps.now()
+ || Object.keys(value).some((key) => !FIELDS.has(key))
+ ) {
+ remove()
+ return null
+ }
+ return value as PendingDismissal
+ } catch {
+ remove()
+ return null
+ }
+ }
+
+ return {
+ queue(
+ platform: NativeSystemNotificationPlatform,
+ notificationId: string,
+ pathname: string,
+ ) {
+ if (!UUID.test(notificationId) || !ROUTE.test(pathname)) return false
+ const value: PendingDismissal = {
+ version: VERSION,
+ platform,
+ notificationId,
+ pathname,
+ expiresAt: deps.now() + TTL_MS,
+ }
+ try {
+ deps.setItem(KEY, JSON.stringify(value))
+ return true
+ } catch {
+ return false
+ }
+ },
+ peek(platform: NativeSystemNotificationPlatform, pathname: string) {
+ const value = read()
+ if (!value || value.platform !== platform || value.pathname !== pathname) return null
+ return value.notificationId
+ },
+ complete(
+ platform: NativeSystemNotificationPlatform,
+ pathname: string,
+ notificationId: string,
+ ) {
+ const value = read()
+ if (
+ !value
+ || value.platform !== platform
+ || value.pathname !== pathname
+ || value.notificationId !== notificationId
+ ) return false
+ remove()
+ return true
+ },
+ }
+}
diff --git a/src/web/src/lib/community/system-notification-route.test.ts b/src/web/src/lib/community/system-notification-route.test.ts
index 4b260a742..b98345a7a 100644
--- a/src/web/src/lib/community/system-notification-route.test.ts
+++ b/src/web/src/lib/community/system-notification-route.test.ts
@@ -73,7 +73,10 @@ describe("desktop system notification routes", () => {
status: 200,
headers: { "content-type": "application/json" },
}))
- await expect(revalidateDesktopSystemNotificationTarget(activation.target, fetchImpl)).resolves.toBe(true)
+ await expect(revalidateDesktopSystemNotificationTarget(
+ activation.target,
+ fetchImpl,
+ )).resolves.toBe("allowed")
expect(fetchImpl).toHaveBeenCalledWith("/api/community/messages/message_3", {
method: "GET",
credentials: "same-origin",
@@ -88,21 +91,33 @@ describe("desktop system notification routes", () => {
}))
vi.stubGlobal("fetch", fetchImpl)
- await expect(revalidateDesktopSystemNotificationTarget(activation.target)).resolves.toBe(true)
+ await expect(revalidateDesktopSystemNotificationTarget(activation.target)).resolves.toBe("allowed")
expect(fetchImpl).toHaveBeenCalledOnce()
})
- it("rejects deleted, revoked, malformed, and mismatched responses", async () => {
+ it("classifies deleted and revoked targets as permanently invalid", async () => {
for (const response of [
new Response(null, { status: 404 }),
new Response(null, { status: 403 }),
- new Response("nope", { status: 200 }),
- new Response(JSON.stringify({ id: "other" }), { status: 200 }),
]) {
await expect(revalidateDesktopSystemNotificationTarget(
activation.target,
vi.fn(async () => response),
- )).resolves.toBe(false)
+ )).resolves.toBe("invalid")
+ }
+ })
+
+ it("classifies network, server, malformed, and mismatched responses as retryable", async () => {
+ for (const fetchImpl of [
+ vi.fn(async () => { throw new Error("offline") }),
+ vi.fn(async () => new Response(null, { status: 503 })),
+ vi.fn(async () => new Response("nope", { status: 200 })),
+ vi.fn(async () => new Response(JSON.stringify({ id: "other" }), { status: 200 })),
+ ]) {
+ await expect(revalidateDesktopSystemNotificationTarget(
+ activation.target,
+ fetchImpl,
+ )).resolves.toBe("retryable")
}
})
})
diff --git a/src/web/src/lib/community/system-notification-route.ts b/src/web/src/lib/community/system-notification-route.ts
index e996c5c2e..9a02524ad 100644
--- a/src/web/src/lib/community/system-notification-route.ts
+++ b/src/web/src/lib/community/system-notification-route.ts
@@ -18,6 +18,11 @@ export type DesktopSystemNotificationActivation = {
target: DesktopSystemNotificationTarget
}
+export type DesktopSystemNotificationTargetValidation =
+ | "allowed"
+ | "invalid"
+ | "retryable"
+
export type SystemNotificationRouteTarget =
| { kind: "server"; serverId: string; channelId: string }
| { kind: "dm"; channelId: string }
@@ -93,17 +98,18 @@ export function systemNotificationHref(target: SystemNotificationRouteTarget): s
export async function revalidateDesktopSystemNotificationTarget(
target: DesktopSystemNotificationTarget,
fetchImpl: typeof fetch = fetch,
-): Promise<boolean> {
+): Promise<DesktopSystemNotificationTargetValidation> {
try {
const response = await fetchImpl(`/api/community/messages/${encodeURIComponent(target.messageId)}`, {
method: "GET",
credentials: "same-origin",
cache: "no-store",
})
- if (!response.ok) return false
+ if (response.status === 403 || response.status === 404) return "invalid"
+ if (!response.ok) return "retryable"
const payload: unknown = await response.json()
- return isObject(payload) && payload.id === target.messageId
+ return isObject(payload) && payload.id === target.messageId ? "allowed" : "retryable"
} catch {
- return false
+ return "retryable"
}
}
diff --git a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts
index 26a71a4d5..3295dfabd 100644
--- a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts
+++ b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts
@@ -23,12 +23,25 @@ async function installDesktopNotificationBridge(
const usedKey = initialActivation
? `notification-activation:${initialActivation.notificationId}`
: ""
+ const dismissedKey = "qa-desktop-notification-dismissed"
+ const dismissed = JSON.parse(sessionStorage.getItem(dismissedKey) ?? "[]") as unknown[]
let pending = initialActivation && sessionStorage.getItem(usedKey) !== "used"
? initialActivation
: null
const state = {
shows: [] as unknown[],
+ dismissed,
+ retryActivations: [] as unknown[],
listener: null as null | { onmessage?: (value: unknown) => void },
+ click: () => undefined,
+ }
+ let activated = pending === null && initialActivation !== null
+ state.click = () => {
+ if (!initialActivation || activated) return
+ activated = true
+ pending = initialActivation
+ sessionStorage.setItem(usedKey, "used")
+ state.listener?.onmessage?.(undefined)
}
class Channel {
onmessage?: (value: unknown) => void
@@ -51,13 +64,30 @@ async function installDesktopNotificationBridge(
if (command === "desktop_system_notification_take_activation") {
const value = pending
pending = null
- if (value) sessionStorage.setItem(usedKey, "used")
+ if (value) {
+ activated = true
+ sessionStorage.setItem(usedKey, "used")
+ }
return value
}
+ if (command === "desktop_system_notification_retry_activation") {
+ const notificationId = args?.notificationId
+ if (notificationId !== initialActivation?.notificationId || !activated) {
+ throw new Error("activation_unavailable")
+ }
+ activated = false
+ state.retryActivations.push(notificationId)
+ return undefined
+ }
if (command === "desktop_system_notification_show") {
state.shows.push(args?.candidate)
return undefined
}
+ if (command === "desktop_system_notification_dismiss") {
+ state.dismissed.push(args?.notificationId)
+ sessionStorage.setItem(dismissedKey, JSON.stringify(state.dismissed))
+ return undefined
+ }
return undefined
},
},
@@ -72,6 +102,24 @@ async function shownNotifications(page: Page) {
).__desktopNotificationTest.shows)
}
+async function dismissedNotifications(page: Page) {
+ return page.evaluate(() => (
+ window as typeof window & { __desktopNotificationTest: { dismissed: unknown[] } }
+ ).__desktopNotificationTest.dismissed)
+}
+
+async function retriedNotifications(page: Page) {
+ return page.evaluate(() => (
+ window as typeof window & { __desktopNotificationTest: { retryActivations: unknown[] } }
+ ).__desktopNotificationTest.retryActivations)
+}
+
+async function clickDesktopNotification(page: Page) {
+ await page.evaluate(() => (
+ window as typeof window & { __desktopNotificationTest: { click: () => void } }
+ ).__desktopNotificationTest.click())
+}
+
test.describe.serial("desktop system notifications", () => {
test("a delivered message+bump bundle invokes the native command with the exact target", async ({ asUser }) => {
const stamp = Date.now()
@@ -117,6 +165,9 @@ test.describe.serial("desktop system notifications", () => {
await gotoAfterUserWsAuth(bob.page, "/c/me/friends")
await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${channelId}`))
+ await expect.poll(() => dismissedNotifications(bob.page)).toEqual([
+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",
+ ])
await expect(bob.page.getByTestId(tid.message(messageId))).toBeVisible({ timeout: 30_000 })
})
@@ -134,5 +185,40 @@ test.describe.serial("desktop system notifications", () => {
})
await gotoAfterUserWsAuth(bob.page, "/c/me/friends")
await expect(bob.page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")
+ expect(await dismissedNotifications(bob.page)).toEqual([])
+ })
+
+ test("a transient validation failure re-arms the exact notification for a later click", async ({ asUser }) => {
+ test.setTimeout(90_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `notification-retry-${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `notification-retry-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const messageId = await seedMessage("alice", channelId, `Retry activation ${stamp}`)
+ const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f720"
+ const bob = await asUser("bob")
+ let attempts = 0
+ await bob.page.route(`**/api/community/messages/${messageId}`, async (route) => {
+ attempts += 1
+ if (attempts === 1) {
+ await route.fulfill({ status: 503, body: "temporarily unavailable" })
+ return
+ }
+ await route.continue()
+ })
+ await installDesktopNotificationBridge(bob.page, {
+ notificationId,
+ target: { kind: "server", serverId, channelId, messageId, seq: 1 },
+ })
+
+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")
+ await expect(bob.page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")
+ await expect.poll(() => retriedNotifications(bob.page)).toEqual([notificationId])
+ expect(await dismissedNotifications(bob.page)).toEqual([])
+
+ await clickDesktopNotification(bob.page)
+ await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${channelId}`))
+ await expect.poll(() => dismissedNotifications(bob.page)).toEqual([notificationId])
+ expect(attempts).toBe(2)
})
})
diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
index b98413b0c..3ddfbbec8 100644
--- a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
+++ b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
@@ -6,15 +6,17 @@ import { tid } from "./_fixtures/testids"
import { WEB_URL } from "./_setup/paths"
type Activation = { notificationId: string; messageId: string; targetId: string }
-type Bridge = { pending: Activation | null; listener: unknown; takes: number; visibility: DocumentVisibilityState }
+type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState }
async function installMobileBridge(page: Page, activation: Activation | null) {
await page.addInitScript((initial) => {
const key = `qa-mobile-consumed:${initial?.notificationId}`
+ const dismissedKey = "qa-mobile-notification-dismissed"
const state: Bridge = {
pending: initial && !sessionStorage.getItem(key) ? initial : null,
listener: null,
takes: 0,
+ dismissed: JSON.parse(sessionStorage.getItem(dismissedKey) ?? "[]") as string[],
visibility: "visible",
}
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state.visibility })
@@ -32,6 +34,11 @@ async function installMobileBridge(page: Page, activation: Activation | null) {
return value
}
if (command === "mobile_system_notification_check_permission" || command === "mobile_system_notification_request_permission") return { permissionState: "prompt" }
+ if (command === "mobile_system_notification_dismiss") {
+ state.dismissed.push(args?.notificationId as string)
+ sessionStorage.setItem(dismissedKey, JSON.stringify(state.dismissed))
+ return undefined
+ }
return undefined
} } },
})
@@ -127,6 +134,9 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
expect(payload.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: messageId })]))
const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`
await expect(page).toHaveURL(`${WEB_URL}${path}`)
+ await expect.poll(() => page.evaluate(() => (
+ window as typeof window & { __mobileNotificationQa: Bridge }
+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])
await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })
await expect(page.getByTestId(tid.message(messageId))).toBeVisible()
await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)
@@ -154,6 +164,9 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
expect([403, 404]).toContain(status)
await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")
await expect(page).toHaveURL(`${WEB_URL}${route}`)
+ expect(await page.evaluate(() => (
+ window as typeof window & { __mobileNotificationQa: Bridge }
+ ).__mobileNotificationQa.dismissed)).toEqual([])
await testInfo.attach("fallback-evidence", { body: JSON.stringify({ kind, status, url: page.url() }), contentType: "application/json" })
})
}